All files / src/internal token.ts

98.46% Statements 64/65
92.5% Branches 37/40
100% Functions 17/17
98.46% Lines 64/65

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175    15x 15x 15x                           7x       9x         77x   77x 77x     77x       20x       82x 82x 74x     8x 8x 8x 6x     8x 8x 8x 8x         8x         77x 77x   77x                           53x 53x 53x     53x 77x 77x 77x   77x 77x   23x           18x     5x 5x       54x 54x 54x 54x   54x       53x 100x 1x     99x 12x     87x 17x     70x 65x   70x                 8x 8x 8x 8x   8x     8x     8x 8x             32x 32x           28x          
import type { AbortSignalLike, AccessToken } from '../types'
 
const refreshSkewMs = 300_000
const failedRefreshCooldownMs = 30_000
const aborted = Symbol('aborted')
 
export interface CachedTokenRequest<Challenge> {
  abortSignal?: AbortSignalLike
  /** A claims challenge always sends its own request and never falls back to the cached token. */
  challenge?: Challenge
}
 
export type LoadToken<Challenge> = (
  signal: AbortSignal,
  challenge?: Challenge,
) => Promise<AccessToken>
 
export function formatAuthorizationHeader(token: AccessToken): string {
  return `${token.tokenType ?? 'Bearer'} ${token.token}`
}
 
export function abortReason(signal: AbortSignalLike): unknown {
  return signal.reason ?? new DOMException('This operation was aborted', 'AbortError')
}
 
/** One token request that callers join; it is cancelled once every waiting caller has aborted. */
class Acquisition {
  readonly #controller = new AbortController()
  readonly #promise: Promise<AccessToken>
  #settled = false
  #waiters = 0
 
  public constructor(load: (signal: AbortSignal) => Promise<AccessToken>) {
    this.#promise = this.#run(load)
  }
 
  public isJoinable(): boolean {
    return !this.#settled && !this.#controller.signal.aborted
  }
 
  public async join(signal: AbortSignalLike | undefined): Promise<AccessToken> {
    this.#waiters += 1
    if (signal === undefined) {
      return await this.#promise
    }
 
    const abort = listenForAbort(signal, () => {
      this.#waiters -= 1
      if (this.#waiters === 0) {
        this.#controller.abort()
      }
    })
    try {
      const result = await Promise.race([this.#promise, abort.promise])
      Eif (result === aborted) {
        throw abortReason(signal)
      }
 
      return result
    } finally {
      abort.remove()
    }
  }
 
  async #run(load: (signal: AbortSignal) => Promise<AccessToken>): Promise<AccessToken> {
    try {
      return await load(this.#controller.signal)
    } finally {
      this.#settled = true
    }
  }
}
 
/**
 * Reuses a token until it is due for refresh and shares one request between concurrent callers.
 * A failed refresh keeps an unexpired token and waits 30 s before trying again. Cancellation only
 * rejects the aborting caller.
 */
export function cacheToken<Challenge>(
  loadToken: LoadToken<Challenge>,
): (request?: CachedTokenRequest<Challenge>) => Promise<AccessToken> {
  let cached: AccessToken | undefined
  let cachedOrder = 0
  let started = 0
  let retryAfterTimestamp = 0
  let pending: Acquisition | undefined
 
  const acquire = (challenge: Challenge | undefined): Acquisition => {
    started += 1
    const order = started
    return new Acquisition(async (signal) => {
      let token: AccessToken
      try {
        token = await loadToken(signal, challenge)
      } catch (error) {
        if (
          challenge !== undefined ||
          signal.aborted ||
          cached === undefined ||
          Date.now() >= cached.expiresOnTimestamp
        ) {
          throw error
        }
 
        retryAfterTimestamp = Date.now() + failedRefreshCooldownMs
        return cached
      }
 
      // A refresh that started before the cached token, such as a claims result, must not replace it.
      Eif (order > cachedOrder) {
        cached = token
        cachedOrder = order
        retryAfterTimestamp = 0
      }
      return token
    })
  }
 
  return async ({ abortSignal, challenge } = {}) => {
    if (abortSignal?.aborted === true) {
      throw abortReason(abortSignal)
    }
 
    if (challenge !== undefined) {
      return await acquire(challenge).join(abortSignal)
    }
 
    if (cached !== undefined && isUsable(cached, retryAfterTimestamp)) {
      return cached
    }
 
    if (pending?.isJoinable() !== true) {
      pending = acquire(undefined)
    }
    return await pending.join(abortSignal)
  }
}
 
function listenForAbort(
  signal: AbortSignalLike,
  onAbort: () => void,
): { promise: Promise<typeof aborted>; remove: () => void } {
  let listener: (() => void) | undefined
  const promise = new Promise<typeof aborted>((resolve) => {
    listener = () => {
      onAbort()
      resolve(aborted)
    }
    signal.addEventListener('abort', listener)
  })
 
  return {
    promise,
    remove: () => {
      Eif (listener !== undefined) {
        signal.removeEventListener('abort', listener)
      }
    },
  }
}
 
function isUsable(token: AccessToken, retryAfterTimestamp: number): boolean {
  const now = Date.now()
  return (
    now < token.expiresOnTimestamp && (now < retryAfterTimestamp || !isDueForRefresh(token, now))
  )
}
 
function isDueForRefresh(token: AccessToken, now: number): boolean {
  return (
    now >= (token.refreshAfterTimestamp ?? Number.POSITIVE_INFINITY) ||
    now >= token.expiresOnTimestamp - refreshSkewMs
  )
}