@kivacore/api-client 0.0.0 → 0.3.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +792 -1
- package/REVIEW.md +292 -0
- package/dist/index.d.ts +597 -0
- package/dist/index.js +1486 -0
- package/dist/index.js.map +1 -0
- package/dist/react-native/index.d.ts +75 -0
- package/dist/react-native/index.js +1534 -0
- package/dist/react-native/index.js.map +1 -0
- package/docyrus-api-query-guide.md +2057 -0
- package/package.json +40 -3
- package/src/clients/base-client.ts +570 -0
- package/src/clients/cf-client.ts +82 -0
- package/src/clients/edge-client.ts +34 -0
- package/src/clients/rest-client.ts +58 -0
- package/src/core/crypto.ts +63 -0
- package/src/core/errors.ts +183 -0
- package/src/core/token-manager.ts +59 -0
- package/src/core/types.ts +96 -0
- package/src/core/utils.ts +138 -0
- package/src/index.ts +112 -0
- package/src/oauth2/index.ts +37 -0
- package/src/oauth2/oauth2-client.ts +668 -0
- package/src/oauth2/oauth2-token-manager.ts +128 -0
- package/src/oauth2/oauth2-types.ts +234 -0
- package/src/oauth2/pkce.ts +121 -0
- package/src/react-native/index.ts +112 -0
- package/src/react-native/rn-crypto.ts +115 -0
- package/src/react-native/rn-helpers.ts +89 -0
- package/tsconfig.json +9 -0
- package/tsup.config.ts +13 -0
- package/vitest.config.mts +13 -0
|
@@ -0,0 +1,668 @@
|
|
|
1
|
+
import { type CryptoProvider } from '../core/crypto';
|
|
2
|
+
|
|
3
|
+
import {
|
|
4
|
+
type OAuth2ClientConfig,
|
|
5
|
+
type AuthorizationParams,
|
|
6
|
+
type AuthorizationCodeTokenRequest,
|
|
7
|
+
type RefreshTokenRequest,
|
|
8
|
+
type ClientCredentialsRequest,
|
|
9
|
+
type DeviceCodeTokenRequest,
|
|
10
|
+
type TokenRequest,
|
|
11
|
+
type TokenResponse,
|
|
12
|
+
type RevokeTokenRequest,
|
|
13
|
+
type IntrospectTokenRequest,
|
|
14
|
+
type IntrospectTokenResponse,
|
|
15
|
+
type DeviceAuthorizationRequest,
|
|
16
|
+
type DeviceAuthorizationResponse,
|
|
17
|
+
type DeviceVerifyRequest,
|
|
18
|
+
type DeviceVerifyResponse,
|
|
19
|
+
type RateLimitInfo,
|
|
20
|
+
type AuthorizationCallbackResult,
|
|
21
|
+
type DevicePollingOptions,
|
|
22
|
+
type OAuth2Tokens,
|
|
23
|
+
type OAuth2TokenStorage,
|
|
24
|
+
type PKCEState,
|
|
25
|
+
type TokenTypeHint
|
|
26
|
+
} from './oauth2-types';
|
|
27
|
+
|
|
28
|
+
import {
|
|
29
|
+
generatePKCEChallenge,
|
|
30
|
+
generateState,
|
|
31
|
+
generateNonce
|
|
32
|
+
} from './pkce';
|
|
33
|
+
import { MemoryOAuth2TokenStorage } from './oauth2-token-manager';
|
|
34
|
+
import {
|
|
35
|
+
OAuth2Error,
|
|
36
|
+
InvalidGrantError,
|
|
37
|
+
InvalidClientError,
|
|
38
|
+
AuthorizationPendingError,
|
|
39
|
+
SlowDownError,
|
|
40
|
+
ExpiredTokenError,
|
|
41
|
+
AccessDeniedError
|
|
42
|
+
} from '../core/errors';
|
|
43
|
+
import { buildUrl } from '../core/utils';
|
|
44
|
+
|
|
45
|
+
/** Tokens another tab refreshed are reused only if they stay valid at least this long. */
|
|
46
|
+
const REFRESHED_ELSEWHERE_MIN_VALIDITY_SECONDS = 30;
|
|
47
|
+
|
|
48
|
+
interface WebLockManager {
|
|
49
|
+
request<T>(name: string, callback: () => Promise<T>): Promise<T>;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** Run `fn` under a Web Lock shared by every tab and window of the origin; directly where there are none. */
|
|
53
|
+
async function withRefreshLock<T>(name: string, fn: () => Promise<T>): Promise<T> {
|
|
54
|
+
const locks = (globalThis as { navigator?: { locks?: WebLockManager } }).navigator?.locks;
|
|
55
|
+
|
|
56
|
+
return locks ? await locks.request(name, fn) : await fn();
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
export class OAuth2Client {
|
|
60
|
+
private readonly config: Required<Pick<OAuth2ClientConfig, 'baseURL' | 'clientId'>> & OAuth2ClientConfig;
|
|
61
|
+
private readonly fetchImpl: typeof fetch;
|
|
62
|
+
private readonly storage: OAuth2TokenStorage;
|
|
63
|
+
private readonly cryptoProvider: CryptoProvider | undefined;
|
|
64
|
+
/** Shared in-flight refresh, so concurrent callers don't each spend the refresh token. */
|
|
65
|
+
private refreshInFlight: Promise<OAuth2Tokens> | null = null;
|
|
66
|
+
constructor(config: OAuth2ClientConfig) {
|
|
67
|
+
if (!config.baseURL) {
|
|
68
|
+
throw new Error('OAuth2Client requires a baseURL');
|
|
69
|
+
}
|
|
70
|
+
if (!config.clientId) {
|
|
71
|
+
throw new Error('OAuth2Client requires a clientId');
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
this.config = {
|
|
75
|
+
...config,
|
|
76
|
+
baseURL: config.baseURL,
|
|
77
|
+
clientId: config.clientId,
|
|
78
|
+
usePKCE: config.usePKCE ?? true,
|
|
79
|
+
defaultScopes: config.defaultScopes ?? []
|
|
80
|
+
};
|
|
81
|
+
|
|
82
|
+
// Bind fetch to global to avoid "Illegal invocation"
|
|
83
|
+
const rawFetch = (config.fetch || globalThis.fetch) as typeof fetch | undefined;
|
|
84
|
+
|
|
85
|
+
if (!rawFetch) {
|
|
86
|
+
throw new Error('Fetch API not available');
|
|
87
|
+
}
|
|
88
|
+
this.fetchImpl = rawFetch.bind(globalThis);
|
|
89
|
+
|
|
90
|
+
this.storage = config.tokenStorage || new MemoryOAuth2TokenStorage();
|
|
91
|
+
this.cryptoProvider = config.cryptoProvider;
|
|
92
|
+
}
|
|
93
|
+
// ===== Authorization Code Flow =====
|
|
94
|
+
/**
|
|
95
|
+
* Generate authorization URL for the authorization code flow
|
|
96
|
+
* Handles PKCE automatically if enabled
|
|
97
|
+
*/
|
|
98
|
+
async getAuthorizationUrl(options: {
|
|
99
|
+
scope?: string;
|
|
100
|
+
state?: string;
|
|
101
|
+
nonce?: string;
|
|
102
|
+
redirectUri?: string;
|
|
103
|
+
} = {}): Promise<{ url: string; state: string; codeVerifier?: string }> {
|
|
104
|
+
const state = options.state || generateState(32, this.cryptoProvider);
|
|
105
|
+
const scope = options.scope || this.config.defaultScopes?.join(' ') || 'openid';
|
|
106
|
+
const redirectUri = options.redirectUri || this.config.redirectUri;
|
|
107
|
+
|
|
108
|
+
if (!redirectUri) {
|
|
109
|
+
throw new Error('redirectUri is required for authorization code flow');
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
const params: AuthorizationParams = {
|
|
113
|
+
client_id: this.config.clientId,
|
|
114
|
+
redirect_uri: redirectUri,
|
|
115
|
+
response_type: 'code',
|
|
116
|
+
state,
|
|
117
|
+
scope
|
|
118
|
+
};
|
|
119
|
+
|
|
120
|
+
// Add nonce for OpenID Connect
|
|
121
|
+
if (scope.includes('openid')) {
|
|
122
|
+
params.nonce = options.nonce || generateNonce(32, this.cryptoProvider);
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
let codeVerifier: string | undefined;
|
|
126
|
+
|
|
127
|
+
// Generate PKCE challenge
|
|
128
|
+
if (this.config.usePKCE) {
|
|
129
|
+
const pkce = await generatePKCEChallenge(this.cryptoProvider);
|
|
130
|
+
|
|
131
|
+
params.code_challenge = pkce.codeChallenge;
|
|
132
|
+
params.code_challenge_method = pkce.codeChallengeMethod;
|
|
133
|
+
({ codeVerifier } = pkce);
|
|
134
|
+
|
|
135
|
+
// Store PKCE state for later use
|
|
136
|
+
if (this.storage.setPKCEState) {
|
|
137
|
+
await Promise.resolve(this.storage.setPKCEState({
|
|
138
|
+
codeVerifier,
|
|
139
|
+
state,
|
|
140
|
+
nonce: params.nonce
|
|
141
|
+
}));
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
const url = buildUrl(this.config.baseURL, '/v1/oauth2/authorize', params as unknown as Record<string, string>);
|
|
146
|
+
|
|
147
|
+
return { url, state, codeVerifier };
|
|
148
|
+
}
|
|
149
|
+
/**
|
|
150
|
+
* Handle the authorization callback and exchange code for tokens
|
|
151
|
+
*/
|
|
152
|
+
async handleCallback(
|
|
153
|
+
callbackUrl: string | AuthorizationCallbackResult,
|
|
154
|
+
options: {
|
|
155
|
+
codeVerifier?: string;
|
|
156
|
+
expectedState?: string;
|
|
157
|
+
} = {}
|
|
158
|
+
): Promise<OAuth2Tokens> {
|
|
159
|
+
let code: string;
|
|
160
|
+
let state: string;
|
|
161
|
+
|
|
162
|
+
if (typeof callbackUrl === 'string') {
|
|
163
|
+
const url = new URL(callbackUrl);
|
|
164
|
+
|
|
165
|
+
code = url.searchParams.get('code') || '';
|
|
166
|
+
state = url.searchParams.get('state') || '';
|
|
167
|
+
|
|
168
|
+
// Check for error response
|
|
169
|
+
const error = url.searchParams.get('error');
|
|
170
|
+
|
|
171
|
+
if (error) {
|
|
172
|
+
const errorDescription = url.searchParams.get('error_description') || undefined;
|
|
173
|
+
|
|
174
|
+
throw this.createOAuth2Error(error, errorDescription);
|
|
175
|
+
}
|
|
176
|
+
} else {
|
|
177
|
+
({ code, state } = callbackUrl);
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
// Validate state
|
|
181
|
+
let storedPKCE: PKCEState | null = null;
|
|
182
|
+
|
|
183
|
+
if (this.storage.getPKCEState) {
|
|
184
|
+
storedPKCE = await Promise.resolve(this.storage.getPKCEState());
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
const expectedState = options.expectedState || storedPKCE?.state;
|
|
188
|
+
|
|
189
|
+
if (expectedState && state !== expectedState) {
|
|
190
|
+
throw new OAuth2Error('invalid_state', 'State mismatch - possible CSRF attack');
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
// Get code verifier
|
|
194
|
+
const codeVerifier = options.codeVerifier || storedPKCE?.codeVerifier;
|
|
195
|
+
|
|
196
|
+
// Exchange code for tokens
|
|
197
|
+
const tokens = await this.exchangeCode(code, codeVerifier);
|
|
198
|
+
|
|
199
|
+
// Clear PKCE state
|
|
200
|
+
if (this.storage.clearPKCEState) {
|
|
201
|
+
await Promise.resolve(this.storage.clearPKCEState());
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
return tokens;
|
|
205
|
+
}
|
|
206
|
+
/**
|
|
207
|
+
* Exchange authorization code for tokens
|
|
208
|
+
*/
|
|
209
|
+
async exchangeCode(
|
|
210
|
+
code: string,
|
|
211
|
+
codeVerifier?: string,
|
|
212
|
+
redirectUri?: string
|
|
213
|
+
): Promise<OAuth2Tokens> {
|
|
214
|
+
const body: AuthorizationCodeTokenRequest = {
|
|
215
|
+
grant_type: 'authorization_code',
|
|
216
|
+
client_id: this.config.clientId,
|
|
217
|
+
code,
|
|
218
|
+
redirect_uri: redirectUri || this.config.redirectUri
|
|
219
|
+
};
|
|
220
|
+
|
|
221
|
+
if (codeVerifier) {
|
|
222
|
+
body.code_verifier = codeVerifier;
|
|
223
|
+
} else if (this.config.clientSecret) {
|
|
224
|
+
body.client_secret = this.config.clientSecret;
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
return this.requestToken(body);
|
|
228
|
+
}
|
|
229
|
+
// ===== Refresh Token Flow =====
|
|
230
|
+
/**
|
|
231
|
+
* Refresh the access token using a refresh token.
|
|
232
|
+
*
|
|
233
|
+
* Concurrent calls share a single in-flight request. Without this, several
|
|
234
|
+
* requests crossing the expiry buffer at once each fire their own refresh;
|
|
235
|
+
* with refresh-token rotation only the first succeeds and the losers can
|
|
236
|
+
* leave the client holding an already-expired token (surfacing as backend
|
|
237
|
+
* "JWTExpired" errors on subsequent calls).
|
|
238
|
+
*/
|
|
239
|
+
async refreshAccessToken(refreshToken?: string): Promise<OAuth2Tokens> {
|
|
240
|
+
if (this.refreshInFlight) return this.refreshInFlight;
|
|
241
|
+
|
|
242
|
+
this.refreshInFlight = this.performRefresh(refreshToken).finally(() => {
|
|
243
|
+
this.refreshInFlight = null;
|
|
244
|
+
});
|
|
245
|
+
|
|
246
|
+
return this.refreshInFlight;
|
|
247
|
+
}
|
|
248
|
+
/**
|
|
249
|
+
* Refresh tokens rotate, and the Docyrus API refuses a rotated refresh token presented again (and can end
|
|
250
|
+
* the whole sign-in for it). Tabs and windows sharing one token storage therefore refresh one at a time,
|
|
251
|
+
* under a Web Lock, and with the token as stored *now*: if another tab refreshed while this one waited, its
|
|
252
|
+
* tokens are used instead of refreshing again. Outside browsers (no Web Locks) only the per-instance
|
|
253
|
+
* single-flight above applies.
|
|
254
|
+
*/
|
|
255
|
+
private async performRefresh(refreshToken?: string): Promise<OAuth2Tokens> {
|
|
256
|
+
const seenRefreshToken = refreshToken || (await Promise.resolve(this.storage.getTokens()))?.refreshToken;
|
|
257
|
+
|
|
258
|
+
return await withRefreshLock(`docyrus-oauth2-refresh:${this.config.baseURL}:${this.config.clientId}`, async () => {
|
|
259
|
+
const stored = await Promise.resolve(this.storage.getTokens());
|
|
260
|
+
|
|
261
|
+
if (
|
|
262
|
+
stored?.refreshToken
|
|
263
|
+
&& seenRefreshToken
|
|
264
|
+
&& stored.refreshToken !== seenRefreshToken
|
|
265
|
+
&& !(await this.isTokenExpired(REFRESHED_ELSEWHERE_MIN_VALIDITY_SECONDS))
|
|
266
|
+
) {
|
|
267
|
+
return stored;
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
// the stored token is the newest one; an argument can only be an older copy of it
|
|
271
|
+
return await this.requestRefresh(stored?.refreshToken || refreshToken);
|
|
272
|
+
});
|
|
273
|
+
}
|
|
274
|
+
private async requestRefresh(token: string | undefined): Promise<OAuth2Tokens> {
|
|
275
|
+
if (!token) {
|
|
276
|
+
throw new InvalidGrantError('No refresh token available');
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
const body: RefreshTokenRequest = {
|
|
280
|
+
grant_type: 'refresh_token',
|
|
281
|
+
client_id: this.config.clientId,
|
|
282
|
+
refresh_token: token
|
|
283
|
+
};
|
|
284
|
+
|
|
285
|
+
if (this.config.clientSecret) {
|
|
286
|
+
body.client_secret = this.config.clientSecret;
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
return this.requestToken(body);
|
|
290
|
+
}
|
|
291
|
+
// ===== Client Credentials Flow =====
|
|
292
|
+
/**
|
|
293
|
+
* Get access token using client credentials
|
|
294
|
+
*/
|
|
295
|
+
async getClientCredentialsToken(options: {
|
|
296
|
+
scope: string;
|
|
297
|
+
delegatedUserId: string;
|
|
298
|
+
clientAssertion?: string;
|
|
299
|
+
}): Promise<OAuth2Tokens> {
|
|
300
|
+
const body: ClientCredentialsRequest = {
|
|
301
|
+
grant_type: 'client_credentials',
|
|
302
|
+
client_id: this.config.clientId,
|
|
303
|
+
scope: options.scope,
|
|
304
|
+
delegated_user_id: options.delegatedUserId
|
|
305
|
+
};
|
|
306
|
+
|
|
307
|
+
if (options.clientAssertion) {
|
|
308
|
+
body.client_assertion_type = 'urn:ietf:params:oauth:client-assertion-type:jwt-bearer';
|
|
309
|
+
body.client_assertion = options.clientAssertion;
|
|
310
|
+
} else if (this.config.clientSecret) {
|
|
311
|
+
body.client_secret = this.config.clientSecret;
|
|
312
|
+
} else {
|
|
313
|
+
throw new InvalidClientError('Client credentials flow requires client_secret or client_assertion');
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
return this.requestToken(body);
|
|
317
|
+
}
|
|
318
|
+
// ===== Device Authorization Flow (RFC 8628) =====
|
|
319
|
+
/**
|
|
320
|
+
* Start device authorization flow
|
|
321
|
+
*/
|
|
322
|
+
async startDeviceAuthorization(scope?: string): Promise<DeviceAuthorizationResponse> {
|
|
323
|
+
const body: DeviceAuthorizationRequest = {
|
|
324
|
+
client_id: this.config.clientId,
|
|
325
|
+
scope: scope || this.config.defaultScopes?.join(' ')
|
|
326
|
+
};
|
|
327
|
+
|
|
328
|
+
const response = await this.fetchImpl(
|
|
329
|
+
buildUrl(this.config.baseURL, '/v1/oauth2/device/authorize', {}),
|
|
330
|
+
{
|
|
331
|
+
method: 'POST',
|
|
332
|
+
headers: { 'Content-Type': 'application/json' },
|
|
333
|
+
body: JSON.stringify(body)
|
|
334
|
+
}
|
|
335
|
+
);
|
|
336
|
+
|
|
337
|
+
if (!response.ok) {
|
|
338
|
+
await this.handleErrorResponse(response);
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
return response.json();
|
|
342
|
+
}
|
|
343
|
+
/**
|
|
344
|
+
* Poll for device authorization completion
|
|
345
|
+
* Returns tokens when user completes authorization
|
|
346
|
+
*/
|
|
347
|
+
async pollDeviceAuthorization(
|
|
348
|
+
deviceCode: string,
|
|
349
|
+
interval: number = 5,
|
|
350
|
+
expiresIn: number = 1800,
|
|
351
|
+
options: DevicePollingOptions = {}
|
|
352
|
+
): Promise<OAuth2Tokens> {
|
|
353
|
+
const startTime = Date.now();
|
|
354
|
+
const expiresAt = startTime + expiresIn * 1000;
|
|
355
|
+
let currentInterval = interval * 1000;
|
|
356
|
+
|
|
357
|
+
while (Date.now() < expiresAt) {
|
|
358
|
+
// Check for abort signal
|
|
359
|
+
if (options.signal?.aborted) {
|
|
360
|
+
throw new Error('Device authorization polling was aborted');
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
await this.sleep(currentInterval);
|
|
364
|
+
|
|
365
|
+
try {
|
|
366
|
+
const body: DeviceCodeTokenRequest = {
|
|
367
|
+
grant_type: 'urn:ietf:params:oauth:grant-type:device_code',
|
|
368
|
+
client_id: this.config.clientId,
|
|
369
|
+
device_code: deviceCode
|
|
370
|
+
};
|
|
371
|
+
|
|
372
|
+
return await this.requestToken(body);
|
|
373
|
+
} catch (error) {
|
|
374
|
+
if (error instanceof AuthorizationPendingError) {
|
|
375
|
+
// User hasn't completed auth yet, continue polling
|
|
376
|
+
continue;
|
|
377
|
+
}
|
|
378
|
+
if (error instanceof SlowDownError) {
|
|
379
|
+
// Increase polling interval
|
|
380
|
+
currentInterval += 5000;
|
|
381
|
+
continue;
|
|
382
|
+
}
|
|
383
|
+
if (error instanceof ExpiredTokenError) {
|
|
384
|
+
options.onExpired?.();
|
|
385
|
+
throw error;
|
|
386
|
+
}
|
|
387
|
+
throw error;
|
|
388
|
+
}
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
options.onExpired?.();
|
|
392
|
+
throw new ExpiredTokenError();
|
|
393
|
+
}
|
|
394
|
+
/**
|
|
395
|
+
* Verify a device user code
|
|
396
|
+
*/
|
|
397
|
+
async verifyDeviceCode(userCode: string): Promise<DeviceVerifyResponse> {
|
|
398
|
+
const body: DeviceVerifyRequest = { user_code: userCode };
|
|
399
|
+
|
|
400
|
+
const response = await this.fetchImpl(
|
|
401
|
+
buildUrl(this.config.baseURL, '/v1/oauth2/device/verify', {}),
|
|
402
|
+
{
|
|
403
|
+
method: 'POST',
|
|
404
|
+
headers: { 'Content-Type': 'application/json' },
|
|
405
|
+
body: JSON.stringify(body)
|
|
406
|
+
}
|
|
407
|
+
);
|
|
408
|
+
|
|
409
|
+
if (!response.ok) {
|
|
410
|
+
await this.handleErrorResponse(response);
|
|
411
|
+
}
|
|
412
|
+
|
|
413
|
+
return response.json();
|
|
414
|
+
}
|
|
415
|
+
// ===== Token Revocation =====
|
|
416
|
+
/**
|
|
417
|
+
* Revoke a refresh token
|
|
418
|
+
*/
|
|
419
|
+
async revokeToken(
|
|
420
|
+
refreshToken: string,
|
|
421
|
+
clientAssertion?: string
|
|
422
|
+
): Promise<void> {
|
|
423
|
+
const body: RevokeTokenRequest = {
|
|
424
|
+
client_id: this.config.clientId,
|
|
425
|
+
refresh_token: refreshToken
|
|
426
|
+
};
|
|
427
|
+
|
|
428
|
+
if (clientAssertion) {
|
|
429
|
+
body.client_assertion_type = 'urn:ietf:params:oauth:client-assertion-type:jwt-bearer';
|
|
430
|
+
body.client_assertion = clientAssertion;
|
|
431
|
+
} else if (this.config.clientSecret) {
|
|
432
|
+
body.client_secret = this.config.clientSecret;
|
|
433
|
+
}
|
|
434
|
+
|
|
435
|
+
const response = await this.fetchImpl(
|
|
436
|
+
buildUrl(this.config.baseURL, '/v1/oauth2/revoke', {}),
|
|
437
|
+
{
|
|
438
|
+
method: 'POST',
|
|
439
|
+
headers: { 'Content-Type': 'application/json' },
|
|
440
|
+
body: JSON.stringify(body)
|
|
441
|
+
}
|
|
442
|
+
);
|
|
443
|
+
|
|
444
|
+
if (!response.ok && response.status !== 204) {
|
|
445
|
+
await this.handleErrorResponse(response);
|
|
446
|
+
}
|
|
447
|
+
}
|
|
448
|
+
// ===== Token Introspection =====
|
|
449
|
+
/**
|
|
450
|
+
* Introspect a token to check its validity and metadata
|
|
451
|
+
*/
|
|
452
|
+
async introspectToken(
|
|
453
|
+
token: string,
|
|
454
|
+
tokenTypeHint?: TokenTypeHint,
|
|
455
|
+
clientAssertion?: string
|
|
456
|
+
): Promise<IntrospectTokenResponse> {
|
|
457
|
+
const body: IntrospectTokenRequest = {
|
|
458
|
+
token,
|
|
459
|
+
client_id: this.config.clientId,
|
|
460
|
+
token_type_hint: tokenTypeHint
|
|
461
|
+
};
|
|
462
|
+
|
|
463
|
+
if (clientAssertion) {
|
|
464
|
+
body.client_assertion_type = 'urn:ietf:params:oauth:client-assertion-type:jwt-bearer';
|
|
465
|
+
body.client_assertion = clientAssertion;
|
|
466
|
+
} else if (this.config.clientSecret) {
|
|
467
|
+
body.client_secret = this.config.clientSecret;
|
|
468
|
+
}
|
|
469
|
+
|
|
470
|
+
const response = await this.fetchImpl(
|
|
471
|
+
buildUrl(this.config.baseURL, '/v1/oauth2/introspect', {}),
|
|
472
|
+
{
|
|
473
|
+
method: 'POST',
|
|
474
|
+
headers: { 'Content-Type': 'application/json' },
|
|
475
|
+
body: JSON.stringify(body)
|
|
476
|
+
}
|
|
477
|
+
);
|
|
478
|
+
|
|
479
|
+
if (!response.ok) {
|
|
480
|
+
await this.handleErrorResponse(response);
|
|
481
|
+
}
|
|
482
|
+
|
|
483
|
+
return response.json();
|
|
484
|
+
}
|
|
485
|
+
// ===== Rate Limit Check =====
|
|
486
|
+
/**
|
|
487
|
+
* Check rate limit status without consuming units
|
|
488
|
+
*/
|
|
489
|
+
async checkRateLimit(): Promise<RateLimitInfo> {
|
|
490
|
+
const currentTokens = await Promise.resolve(this.storage.getTokens());
|
|
491
|
+
|
|
492
|
+
const headers: HeadersInit = {};
|
|
493
|
+
|
|
494
|
+
if (currentTokens?.accessToken) {
|
|
495
|
+
headers['Authorization'] = `Bearer ${currentTokens.accessToken}`;
|
|
496
|
+
}
|
|
497
|
+
|
|
498
|
+
const response = await this.fetchImpl(
|
|
499
|
+
buildUrl(this.config.baseURL, '/v1/oauth2', {}),
|
|
500
|
+
{
|
|
501
|
+
method: 'HEAD',
|
|
502
|
+
headers
|
|
503
|
+
}
|
|
504
|
+
);
|
|
505
|
+
|
|
506
|
+
return {
|
|
507
|
+
policy: response.headers.get('RateLimit-Policy') || '',
|
|
508
|
+
reset: parseInt(response.headers.get('RateLimit-Reset') || '0', 10),
|
|
509
|
+
remaining: parseInt(response.headers.get('RateLimit-Remaining') || '0', 10),
|
|
510
|
+
limit: parseInt(response.headers.get('RateLimit-Limit') || '0', 10)
|
|
511
|
+
};
|
|
512
|
+
}
|
|
513
|
+
// ===== Token Management =====
|
|
514
|
+
/**
|
|
515
|
+
* Get current stored tokens
|
|
516
|
+
*/
|
|
517
|
+
async getTokens(): Promise<OAuth2Tokens | null> {
|
|
518
|
+
return Promise.resolve(this.storage.getTokens());
|
|
519
|
+
}
|
|
520
|
+
/**
|
|
521
|
+
* Check if the current access token is expired
|
|
522
|
+
*/
|
|
523
|
+
async isTokenExpired(bufferSeconds: number = 60): Promise<boolean> {
|
|
524
|
+
const tokens = await this.getTokens();
|
|
525
|
+
|
|
526
|
+
if (!tokens) return true;
|
|
527
|
+
|
|
528
|
+
const expiresAt = (tokens.expiresAt || 0) > 0 ? tokens.expiresAt : this.parseJwtExp(tokens.accessToken);
|
|
529
|
+
|
|
530
|
+
if (!expiresAt || !Number.isFinite(expiresAt)) return false;
|
|
531
|
+
|
|
532
|
+
return Date.now() >= (expiresAt - bufferSeconds) * 1000;
|
|
533
|
+
}
|
|
534
|
+
/**
|
|
535
|
+
* Get a valid access token, refreshing if necessary
|
|
536
|
+
*/
|
|
537
|
+
async getValidAccessToken(): Promise<string> {
|
|
538
|
+
const tokens = await this.getTokens();
|
|
539
|
+
|
|
540
|
+
if (!tokens) {
|
|
541
|
+
throw new InvalidGrantError('No tokens available');
|
|
542
|
+
}
|
|
543
|
+
|
|
544
|
+
if (await this.isTokenExpired()) {
|
|
545
|
+
if (!tokens.refreshToken) {
|
|
546
|
+
throw new InvalidGrantError('Access token expired and no refresh token available');
|
|
547
|
+
}
|
|
548
|
+
|
|
549
|
+
const newTokens = await this.refreshAccessToken(tokens.refreshToken);
|
|
550
|
+
|
|
551
|
+
return newTokens.accessToken;
|
|
552
|
+
}
|
|
553
|
+
|
|
554
|
+
return tokens.accessToken;
|
|
555
|
+
}
|
|
556
|
+
/**
|
|
557
|
+
* Clear all stored tokens (logout)
|
|
558
|
+
*/
|
|
559
|
+
async logout(): Promise<void> {
|
|
560
|
+
const tokens = await this.getTokens();
|
|
561
|
+
|
|
562
|
+
// Revoke refresh token if present
|
|
563
|
+
if (tokens?.refreshToken) {
|
|
564
|
+
try {
|
|
565
|
+
await this.revokeToken(tokens.refreshToken);
|
|
566
|
+
} catch {
|
|
567
|
+
// Ignore revocation errors during logout
|
|
568
|
+
}
|
|
569
|
+
}
|
|
570
|
+
|
|
571
|
+
await Promise.resolve(this.storage.clearTokens());
|
|
572
|
+
}
|
|
573
|
+
// ===== Private Methods =====
|
|
574
|
+
private async requestToken(body: TokenRequest): Promise<OAuth2Tokens> {
|
|
575
|
+
const response = await this.fetchImpl(
|
|
576
|
+
buildUrl(this.config.baseURL, '/v1/oauth2/token', {}),
|
|
577
|
+
{
|
|
578
|
+
method: 'POST',
|
|
579
|
+
headers: { 'Content-Type': 'application/json' },
|
|
580
|
+
body: JSON.stringify(body)
|
|
581
|
+
}
|
|
582
|
+
);
|
|
583
|
+
|
|
584
|
+
if (!response.ok) {
|
|
585
|
+
await this.handleErrorResponse(response);
|
|
586
|
+
}
|
|
587
|
+
|
|
588
|
+
const tokenResponse: TokenResponse = await response.json();
|
|
589
|
+
|
|
590
|
+
const expiresIn = tokenResponse.expires_in;
|
|
591
|
+
const expiresAt = (Number.isFinite(expiresIn) && expiresIn > 0) ? Math.floor(Date.now() / 1000) + expiresIn : (this.parseJwtExp(tokenResponse.access_token) ?? 0);
|
|
592
|
+
|
|
593
|
+
const tokens: OAuth2Tokens = {
|
|
594
|
+
accessToken: tokenResponse.access_token,
|
|
595
|
+
refreshToken: tokenResponse.refresh_token,
|
|
596
|
+
idToken: tokenResponse.id_token,
|
|
597
|
+
expiresAt,
|
|
598
|
+
scope: tokenResponse.scope
|
|
599
|
+
};
|
|
600
|
+
|
|
601
|
+
// Store tokens
|
|
602
|
+
await Promise.resolve(this.storage.setTokens(tokens));
|
|
603
|
+
|
|
604
|
+
return tokens;
|
|
605
|
+
}
|
|
606
|
+
private async handleErrorResponse(response: Response): Promise<never> {
|
|
607
|
+
let errorData: { error?: string; error_description?: string; error_uri?: string };
|
|
608
|
+
|
|
609
|
+
try {
|
|
610
|
+
errorData = await response.json();
|
|
611
|
+
} catch {
|
|
612
|
+
throw new OAuth2Error('unknown_error', response.statusText);
|
|
613
|
+
}
|
|
614
|
+
|
|
615
|
+
throw this.createOAuth2Error(
|
|
616
|
+
errorData.error || 'unknown_error',
|
|
617
|
+
errorData.error_description,
|
|
618
|
+
errorData.error_uri
|
|
619
|
+
);
|
|
620
|
+
}
|
|
621
|
+
private createOAuth2Error(
|
|
622
|
+
error: string,
|
|
623
|
+
description?: string,
|
|
624
|
+
uri?: string
|
|
625
|
+
): OAuth2Error {
|
|
626
|
+
switch (error) {
|
|
627
|
+
case 'invalid_grant':
|
|
628
|
+
return new InvalidGrantError(description);
|
|
629
|
+
|
|
630
|
+
case 'invalid_client':
|
|
631
|
+
return new InvalidClientError(description);
|
|
632
|
+
|
|
633
|
+
case 'authorization_pending':
|
|
634
|
+
return new AuthorizationPendingError();
|
|
635
|
+
|
|
636
|
+
case 'slow_down':
|
|
637
|
+
return new SlowDownError();
|
|
638
|
+
|
|
639
|
+
case 'expired_token':
|
|
640
|
+
return new ExpiredTokenError();
|
|
641
|
+
|
|
642
|
+
case 'access_denied':
|
|
643
|
+
return new AccessDeniedError(description);
|
|
644
|
+
|
|
645
|
+
default:
|
|
646
|
+
return new OAuth2Error(error, description, uri);
|
|
647
|
+
}
|
|
648
|
+
}
|
|
649
|
+
private sleep(ms: number): Promise<void> {
|
|
650
|
+
return new Promise(resolve => setTimeout(resolve, ms));
|
|
651
|
+
}
|
|
652
|
+
/** Extract exp claim from a JWT access token as a fallback for expires_in. */
|
|
653
|
+
private parseJwtExp(accessToken: string): number | undefined {
|
|
654
|
+
const parts = accessToken.split('.');
|
|
655
|
+
|
|
656
|
+
if (parts.length < 2) return undefined;
|
|
657
|
+
|
|
658
|
+
try {
|
|
659
|
+
const payload = JSON.parse(
|
|
660
|
+
atob(parts[1].replace(/-/g, '+').replace(/_/g, '/'))
|
|
661
|
+
) as Record<string, unknown>;
|
|
662
|
+
|
|
663
|
+
return typeof payload['exp'] === 'number' ? payload['exp'] : undefined;
|
|
664
|
+
} catch {
|
|
665
|
+
return undefined;
|
|
666
|
+
}
|
|
667
|
+
}
|
|
668
|
+
}
|