|
| 1 | +import { HeadersInit } from 'node-fetch'; |
| 2 | + |
| 3 | +/** |
| 4 | + * Safety buffer in seconds to consider a token expired before its actual expiration time. |
| 5 | + * This prevents using tokens that are about to expire during in-flight requests. |
| 6 | + */ |
| 7 | +const EXPIRATION_BUFFER_SECONDS = 30; |
| 8 | + |
| 9 | +/** |
| 10 | + * Options for creating a Token instance. |
| 11 | + */ |
| 12 | +export interface TokenOptions { |
| 13 | + /** The token type (e.g., "Bearer"). Defaults to "Bearer". */ |
| 14 | + tokenType?: string; |
| 15 | + /** The expiration time of the token. */ |
| 16 | + expiresAt?: Date; |
| 17 | + /** The refresh token, if available. */ |
| 18 | + refreshToken?: string; |
| 19 | + /** The scopes associated with this token. */ |
| 20 | + scopes?: string[]; |
| 21 | +} |
| 22 | + |
| 23 | +/** |
| 24 | + * Options for creating a Token from a JWT string. |
| 25 | + * Does not include expiresAt since it is extracted from the JWT payload. |
| 26 | + */ |
| 27 | +export type TokenFromJWTOptions = Omit<TokenOptions, 'expiresAt'>; |
| 28 | + |
| 29 | +/** |
| 30 | + * Represents an access token with optional metadata and lifecycle management. |
| 31 | + */ |
| 32 | +export default class Token { |
| 33 | + private readonly _accessToken: string; |
| 34 | + |
| 35 | + private readonly _tokenType: string; |
| 36 | + |
| 37 | + private readonly _expiresAt?: Date; |
| 38 | + |
| 39 | + private readonly _refreshToken?: string; |
| 40 | + |
| 41 | + private readonly _scopes?: string[]; |
| 42 | + |
| 43 | + constructor(accessToken: string, options?: TokenOptions) { |
| 44 | + this._accessToken = accessToken; |
| 45 | + this._tokenType = options?.tokenType ?? 'Bearer'; |
| 46 | + this._expiresAt = options?.expiresAt; |
| 47 | + this._refreshToken = options?.refreshToken; |
| 48 | + this._scopes = options?.scopes; |
| 49 | + } |
| 50 | + |
| 51 | + /** |
| 52 | + * The access token string. |
| 53 | + */ |
| 54 | + get accessToken(): string { |
| 55 | + return this._accessToken; |
| 56 | + } |
| 57 | + |
| 58 | + /** |
| 59 | + * The token type (e.g., "Bearer"). |
| 60 | + */ |
| 61 | + get tokenType(): string { |
| 62 | + return this._tokenType; |
| 63 | + } |
| 64 | + |
| 65 | + /** |
| 66 | + * The expiration time of the token, if known. |
| 67 | + */ |
| 68 | + get expiresAt(): Date | undefined { |
| 69 | + return this._expiresAt; |
| 70 | + } |
| 71 | + |
| 72 | + /** |
| 73 | + * The refresh token, if available. |
| 74 | + */ |
| 75 | + get refreshToken(): string | undefined { |
| 76 | + return this._refreshToken; |
| 77 | + } |
| 78 | + |
| 79 | + /** |
| 80 | + * The scopes associated with this token. |
| 81 | + */ |
| 82 | + get scopes(): string[] | undefined { |
| 83 | + return this._scopes; |
| 84 | + } |
| 85 | + |
| 86 | + /** |
| 87 | + * Checks if the token has expired, including a safety buffer. |
| 88 | + * Returns false if expiration time is unknown. |
| 89 | + */ |
| 90 | + isExpired(): boolean { |
| 91 | + if (!this._expiresAt) { |
| 92 | + return false; |
| 93 | + } |
| 94 | + const now = new Date(); |
| 95 | + const bufferMs = EXPIRATION_BUFFER_SECONDS * 1000; |
| 96 | + return this._expiresAt.getTime() - bufferMs <= now.getTime(); |
| 97 | + } |
| 98 | + |
| 99 | + /** |
| 100 | + * Sets the Authorization header on the provided headers object. |
| 101 | + * @param headers - The headers object to modify |
| 102 | + * @returns The modified headers object with Authorization set |
| 103 | + */ |
| 104 | + setAuthHeader(headers: HeadersInit): HeadersInit { |
| 105 | + return { |
| 106 | + ...headers, |
| 107 | + Authorization: `${this._tokenType} ${this._accessToken}`, |
| 108 | + }; |
| 109 | + } |
| 110 | + |
| 111 | + /** |
| 112 | + * Creates a Token from a JWT string, extracting the expiration time from the payload. |
| 113 | + * If the JWT cannot be decoded, the token is created without expiration info. |
| 114 | + * The server will validate the token anyway, so decoding failures are handled gracefully. |
| 115 | + * @param jwt - The JWT token string |
| 116 | + * @param options - Additional token options (tokenType, refreshToken, scopes). |
| 117 | + * Note: expiresAt is not accepted here as it is extracted from the JWT payload. |
| 118 | + * @returns A new Token instance with expiration extracted from the JWT (if available) |
| 119 | + */ |
| 120 | + static fromJWT(jwt: string, options?: TokenFromJWTOptions): Token { |
| 121 | + let expiresAt: Date | undefined; |
| 122 | + |
| 123 | + try { |
| 124 | + const parts = jwt.split('.'); |
| 125 | + if (parts.length >= 2) { |
| 126 | + const payload = Buffer.from(parts[1], 'base64').toString('utf8'); |
| 127 | + const decoded = JSON.parse(payload); |
| 128 | + if (typeof decoded.exp === 'number') { |
| 129 | + expiresAt = new Date(decoded.exp * 1000); |
| 130 | + } |
| 131 | + } |
| 132 | + } catch { |
| 133 | + // If we can't decode the JWT, we'll proceed without expiration info |
| 134 | + // The server will validate the token anyway |
| 135 | + } |
| 136 | + |
| 137 | + return new Token(jwt, { |
| 138 | + tokenType: options?.tokenType, |
| 139 | + expiresAt, |
| 140 | + refreshToken: options?.refreshToken, |
| 141 | + scopes: options?.scopes, |
| 142 | + }); |
| 143 | + } |
| 144 | + |
| 145 | + /** |
| 146 | + * Converts the token to a plain object for serialization. |
| 147 | + */ |
| 148 | + toJSON(): Record<string, unknown> { |
| 149 | + return { |
| 150 | + accessToken: this._accessToken, |
| 151 | + tokenType: this._tokenType, |
| 152 | + expiresAt: this._expiresAt?.toISOString(), |
| 153 | + refreshToken: this._refreshToken, |
| 154 | + scopes: this._scopes, |
| 155 | + }; |
| 156 | + } |
| 157 | +} |
0 commit comments