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