@mentra/cloud-client 3.2.1 → 3.3.0-beta.942
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/node/index.ts +2 -0
- package/package.json +2 -2
- package/src/client.ts +9 -1
- package/src/errors.ts +27 -2
- package/src/http.ts +123 -15
- package/src/index.ts +13 -6
- package/src/modules/auth/auth.ts +266 -61
- package/src/modules/core/core.ts +49 -129
- package/src/modules/core/fleet.ts +175 -0
- package/src/modules/core/reports.ts +145 -9
- package/src/modules/runtime/audio-udp.ts +56 -4
- package/src/modules/runtime/runtime.ts +25 -3
package/src/modules/auth/auth.ts
CHANGED
|
@@ -14,10 +14,23 @@
|
|
|
14
14
|
* - Exchange, refresh, and each per-miniapp mint are single-flighted, so a
|
|
15
15
|
* reconnect storm cannot fire a burst of competing requests (and a rotated
|
|
16
16
|
* refresh token cannot be invalidated out from under a concurrent caller).
|
|
17
|
-
* - If
|
|
18
|
-
*
|
|
19
|
-
*
|
|
20
|
-
*
|
|
17
|
+
* - If Core definitively rejects the refresh token (see
|
|
18
|
+
* `DEAD_REFRESH_TOKEN_ERRORS`) and the host can fetch a fresh subject token
|
|
19
|
+
* on demand, we clear the dead refresh token and exchange once. If no fresh
|
|
20
|
+
* subject is available (or exchange also fails), `onExpired` fires once and
|
|
21
|
+
* the host re-authenticates. We do not retry forever against a dead refresh
|
|
22
|
+
* token.
|
|
23
|
+
* - Any other refresh failure (network error, timeout, 408, 429, 5xx, an answer
|
|
24
|
+
* that is not Core's) says nothing about the token. It is kept, `onExpired`
|
|
25
|
+
* does not fire, no exchange is attempted, and `AuthUnavailableError` is
|
|
26
|
+
* thrown so the caller retries later with the same refresh token.
|
|
27
|
+
* - Exchange failures are classified the same way: only Core's own refusal of
|
|
28
|
+
* the subject token (`EXCHANGE_REFUSAL_ERRORS`) is an `AuthExpiredError`, and
|
|
29
|
+
* `onExpired` fires only when that refusal answers the fresh exchange that
|
|
30
|
+
* follows a rejected refresh token. Anything else, including the host's
|
|
31
|
+
* `getSubjectToken` throwing, is an `AuthUnavailableError` and notifies no one.
|
|
32
|
+
* - A rejection or exchange answer that arrives after `clearSession()` is about
|
|
33
|
+
* a session that is gone: it notifies no one and restores nothing.
|
|
21
34
|
*
|
|
22
35
|
* Security: the access token is never written to storage, never given to a
|
|
23
36
|
* miniapp, and no token is ever logged.
|
|
@@ -29,7 +42,7 @@ import type {AuthConfig, CoreAuthConfig, RuntimeAuthConfig, SubjectTokenType} fr
|
|
|
29
42
|
import type {HttpClient} from "../../http"
|
|
30
43
|
import type {Logger} from "../../logger"
|
|
31
44
|
import type {HttpTransport} from "../../transports"
|
|
32
|
-
import {AuthExpiredError, HttpError, SessionRevocationError} from "../../errors"
|
|
45
|
+
import {AuthExpiredError, AuthUnavailableError, HttpError, SessionRevocationError} from "../../errors"
|
|
33
46
|
import {systemTimers, type CloudClientTimers} from "../../timers"
|
|
34
47
|
import {decodeClaims} from "./jwt"
|
|
35
48
|
import {TokenStore} from "./token-store"
|
|
@@ -53,7 +66,7 @@ export interface AuthModule {
|
|
|
53
66
|
// a miniapp-scoped token, cached per packageName and re-minted before expiry
|
|
54
67
|
getMiniappToken(
|
|
55
68
|
packageName: string,
|
|
56
|
-
opts?: {minTtlMs?: number
|
|
69
|
+
opts?: {minTtlMs?: number},
|
|
57
70
|
): Promise<{token: string; expiresAt: number}>
|
|
58
71
|
// Core-owned user/oem identity, read from the Core access token.
|
|
59
72
|
// Runtime-only deployments do not expose this surface.
|
|
@@ -62,7 +75,7 @@ export interface AuthModule {
|
|
|
62
75
|
// credentials are always cleared; rejects with `SessionRevocationError` when
|
|
63
76
|
// Core did not confirm revocation of the server-side session.
|
|
64
77
|
clearSession(): Promise<void>
|
|
65
|
-
// refresh
|
|
78
|
+
// Core rejected the refresh token; the host must send the user back through login
|
|
66
79
|
onExpired(handler: () => void): () => void
|
|
67
80
|
}
|
|
68
81
|
|
|
@@ -93,6 +106,8 @@ const EXPIRY_MARGIN_SECONDS = 60
|
|
|
93
106
|
const REVOKE_ATTEMPTS = 3
|
|
94
107
|
/** Base backoff between revoke attempts in milliseconds; doubles per attempt. */
|
|
95
108
|
const REVOKE_RETRY_BASE_MS = 250
|
|
109
|
+
/** Whole remote logout operation, including refresh and retries. */
|
|
110
|
+
const REVOKE_TIMEOUT_MS = 10_000
|
|
96
111
|
|
|
97
112
|
/** The cloud's token endpoints, relative to the core base URL. */
|
|
98
113
|
const EXCHANGE_PATH = "/api/client/auth/exchange"
|
|
@@ -140,6 +155,88 @@ function isRetryableRevokeError(err: unknown): boolean {
|
|
|
140
155
|
return err instanceof HttpError && (err.status === 0 || err.status >= 500)
|
|
141
156
|
}
|
|
142
157
|
|
|
158
|
+
/**
|
|
159
|
+
* What counts as Core itself refusing a token request, as opposed to a request
|
|
160
|
+
* that merely failed. Core renders every refusal as `{error, error_description}`
|
|
161
|
+
* through its global error translator (`api/app.ts`) with the status its
|
|
162
|
+
* `OauthError` carries (`types/oauth.types.ts`). Only a 400 or 401 whose body has
|
|
163
|
+
* one of the codes below counts; RFC 6749 lets a server pick between the two
|
|
164
|
+
* statuses, so both are accepted for every code. A 5xx, 408 or 429, a body that
|
|
165
|
+
* is not JSON, or any other 4xx is not Core talking about the credentials at all
|
|
166
|
+
* (a proxy, a captive portal, an outage), so it is never a refusal.
|
|
167
|
+
*/
|
|
168
|
+
const CORE_REFUSAL_STATUSES: ReadonlySet<number> = new Set([400, 401])
|
|
169
|
+
|
|
170
|
+
/**
|
|
171
|
+
* The only answers to `POST /api/client/auth/refresh` that say the refresh token
|
|
172
|
+
* (or the session it belongs to) is gone for good. `refreshSession`
|
|
173
|
+
* (`services/session.service.ts`) refuses a token for exactly two reasons:
|
|
174
|
+
*
|
|
175
|
+
* - `invalid_grant`, HTTP 400: the token is unknown, expired or already used,
|
|
176
|
+
* its session identity is incomplete, or its account is deleted.
|
|
177
|
+
* - `unauthorized_client`, HTTP 401: the session's tenant (OEM or enterprise
|
|
178
|
+
* org) is unknown or disabled.
|
|
179
|
+
*
|
|
180
|
+
* `invalid_request` and `unsupported_grant_type` describe the shape of the
|
|
181
|
+
* request (a missing `refresh_token` or `grant_type`), which a proxy that drops
|
|
182
|
+
* or rewrites the form body produces just as well, so they are no verdict on the
|
|
183
|
+
* token.
|
|
184
|
+
*/
|
|
185
|
+
const DEAD_REFRESH_TOKEN_ERRORS: ReadonlySet<string> = new Set(["invalid_grant", "unauthorized_client"])
|
|
186
|
+
|
|
187
|
+
/**
|
|
188
|
+
* The answers to `POST /api/client/auth/exchange` that say the subject token is
|
|
189
|
+
* unusable (`oem.service.ts`, `session.service.ts`): `invalid_grant` (it failed
|
|
190
|
+
* verification or lacks required claims), `unauthorized_client` (its OEM is
|
|
191
|
+
* unknown or disabled), and `invalid_request` (it is not a parseable JWT).
|
|
192
|
+
* `unsupported_grant_type` is left out for the same reason as on refresh.
|
|
193
|
+
*/
|
|
194
|
+
const EXCHANGE_REFUSAL_ERRORS: ReadonlySet<string> = new Set([
|
|
195
|
+
"invalid_grant",
|
|
196
|
+
"unauthorized_client",
|
|
197
|
+
"invalid_request",
|
|
198
|
+
])
|
|
199
|
+
|
|
200
|
+
/** OAuth error codes are short snake_case words; anything else is not safe to keep or log. */
|
|
201
|
+
const OAUTH_ERROR_CODE_PATTERN = /^[a-z][a-z0-9_]{0,63}$/
|
|
202
|
+
|
|
203
|
+
/**
|
|
204
|
+
* A token endpoint answered with a non-2xx status. `status` is the HTTP status and
|
|
205
|
+
* `code` is the OAuth `error` from a JSON body, when there was a well-formed one.
|
|
206
|
+
*
|
|
207
|
+
* It is an `AuthExpiredError` so the logout refresh, which has always thrown that
|
|
208
|
+
* for any non-2xx, is unchanged. `requestTokens` lets it out only when it is
|
|
209
|
+
* Core's refusal (`isCoreRefusal`); every other non-2xx becomes an
|
|
210
|
+
* `AuthUnavailableError` there.
|
|
211
|
+
*/
|
|
212
|
+
class TokenEndpointError extends AuthExpiredError {
|
|
213
|
+
constructor(
|
|
214
|
+
message: string,
|
|
215
|
+
readonly status: number,
|
|
216
|
+
readonly code?: string,
|
|
217
|
+
) {
|
|
218
|
+
super(message)
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
/** Core definitively rejected the refresh token: it is cleared, and the host must re-authenticate. */
|
|
223
|
+
class RefreshTokenRejectedError extends AuthExpiredError {}
|
|
224
|
+
|
|
225
|
+
/** `err` is Core itself refusing the request: a 400 or 401 carrying one of `codes`. */
|
|
226
|
+
function isCoreRefusal(err: unknown, codes: ReadonlySet<string>): err is TokenEndpointError {
|
|
227
|
+
return (
|
|
228
|
+
err instanceof TokenEndpointError &&
|
|
229
|
+
CORE_REFUSAL_STATUSES.has(err.status) &&
|
|
230
|
+
err.code !== undefined &&
|
|
231
|
+
codes.has(err.code)
|
|
232
|
+
)
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
/** The caller or the transport cancelled the request. */
|
|
236
|
+
function isAbortError(error: unknown): boolean {
|
|
237
|
+
return typeof error === "object" && error !== null && "name" in error && error.name === "AbortError"
|
|
238
|
+
}
|
|
239
|
+
|
|
143
240
|
export class Auth implements AuthModule {
|
|
144
241
|
private readonly http?: HttpClient
|
|
145
242
|
private readonly store: TokenStore
|
|
@@ -257,7 +354,7 @@ export class Auth implements AuthModule {
|
|
|
257
354
|
*/
|
|
258
355
|
async getMiniappToken(
|
|
259
356
|
packageName: string,
|
|
260
|
-
opts?: {minTtlMs?: number
|
|
357
|
+
opts?: {minTtlMs?: number},
|
|
261
358
|
): Promise<{token: string; expiresAt: number}> {
|
|
262
359
|
this.assertSessionActive()
|
|
263
360
|
const generation = this.sessionGeneration
|
|
@@ -277,14 +374,9 @@ export class Auth implements AuthModule {
|
|
|
277
374
|
|
|
278
375
|
const accessToken = await this.getCoreToken()
|
|
279
376
|
const http = this.requireCoreHttp()
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
packageName,
|
|
284
|
-
...(opts?.devAttestation ? {devAttestation: opts.devAttestation} : {}),
|
|
285
|
-
},
|
|
286
|
-
{bearer: accessToken},
|
|
287
|
-
)
|
|
377
|
+
// A dev build of a package is that package: the request names it and
|
|
378
|
+
// nothing else. The phone has already applied the installed signer rule.
|
|
379
|
+
const res = await http.post<MiniappTokenEntry>(MINIAPP_TOKEN_PATH, {packageName}, {bearer: accessToken})
|
|
288
380
|
|
|
289
381
|
this.assertSessionActive(generation)
|
|
290
382
|
const entry: MiniappTokenEntry = {token: res.token, expiresAt: res.expiresAt}
|
|
@@ -317,31 +409,43 @@ export class Auth implements AuthModule {
|
|
|
317
409
|
}
|
|
318
410
|
|
|
319
411
|
async clearSession(): Promise<void> {
|
|
412
|
+
const current = this.store.current()
|
|
413
|
+
// Capture the saved refresh token before deleting it, but never reacquire
|
|
414
|
+
// credentials through the upstream provider during logout.
|
|
415
|
+
const refreshSnapshot = this.store.refreshToken()
|
|
320
416
|
this.sessionGeneration += 1
|
|
321
417
|
this.sessionCleared = true
|
|
322
|
-
|
|
418
|
+
this.runtimeToken = null
|
|
419
|
+
this.miniappCache.clear()
|
|
420
|
+
this.expiredFired = false
|
|
421
|
+
// Start local deletion in the same synchronous prefix as invalidation;
|
|
422
|
+
// only local storage work may precede it, never a network operation.
|
|
423
|
+
const localClear = this.store.clear()
|
|
424
|
+
const [refreshToken] = await Promise.all([refreshSnapshot, localClear])
|
|
425
|
+
const controller = new AbortController()
|
|
426
|
+
let timeout: unknown
|
|
323
427
|
try {
|
|
324
|
-
await
|
|
325
|
-
|
|
326
|
-
|
|
428
|
+
await Promise.race([
|
|
429
|
+
this.revokeCoreSession(current, refreshToken, controller.signal),
|
|
430
|
+
new Promise<never>((_, reject) => {
|
|
431
|
+
timeout = this.timers.setTimeout(() => {
|
|
432
|
+
controller.abort()
|
|
433
|
+
reject(new Error("Core session revocation timed out"))
|
|
434
|
+
}, REVOKE_TIMEOUT_MS)
|
|
435
|
+
}),
|
|
436
|
+
])
|
|
437
|
+
} catch (error) {
|
|
327
438
|
this.logger.warn("Core session revocation failed during local logout", {
|
|
328
|
-
error: (
|
|
439
|
+
error: (error as Error)?.message,
|
|
329
440
|
})
|
|
441
|
+
throw new SessionRevocationError("Core session revocation failed; local credentials were cleared", {cause: error})
|
|
330
442
|
} finally {
|
|
331
|
-
|
|
332
|
-
this.runtimeToken = null
|
|
333
|
-
this.miniappCache.clear()
|
|
334
|
-
this.expiredFired = false
|
|
335
|
-
}
|
|
336
|
-
if (revokeError) {
|
|
337
|
-
throw new SessionRevocationError("Core session revocation failed; local credentials were cleared", {
|
|
338
|
-
cause: revokeError,
|
|
339
|
-
})
|
|
443
|
+
this.timers.clearTimeout(timeout)
|
|
340
444
|
}
|
|
341
445
|
}
|
|
342
446
|
|
|
343
447
|
/**
|
|
344
|
-
* Revoke the Core session
|
|
448
|
+
* Revoke the captured Core session after local credentials are dropped.
|
|
345
449
|
*
|
|
346
450
|
* Core verifies the presented access token with no clock tolerance, so a
|
|
347
451
|
* cached token inside the usual expiry margin is refreshed first rather than
|
|
@@ -350,23 +454,26 @@ export class Auth implements AuthModule {
|
|
|
350
454
|
* not. Any failure propagates so the caller can tell revocation did not
|
|
351
455
|
* complete.
|
|
352
456
|
*/
|
|
353
|
-
private async revokeCoreSession(
|
|
457
|
+
private async revokeCoreSession(
|
|
458
|
+
current: ReturnType<TokenStore["current"]>,
|
|
459
|
+
refreshToken: string | null,
|
|
460
|
+
signal: AbortSignal,
|
|
461
|
+
): Promise<void> {
|
|
354
462
|
if (!this.coreConfig || !this.http) return
|
|
355
|
-
const current = this.store.current()
|
|
356
|
-
const refreshToken = await this.store.refreshToken()
|
|
357
463
|
let accessToken: string | null = null
|
|
358
464
|
if (current && !this.isExpiring(current.exp)) {
|
|
359
465
|
accessToken = current.accessToken
|
|
360
466
|
} else if (refreshToken) {
|
|
361
467
|
const body = new URLSearchParams({grant_type: "refresh_token", refresh_token: refreshToken})
|
|
362
|
-
const tokens = await this.postForm(REFRESH_PATH, body, "logout refresh")
|
|
468
|
+
const tokens = await this.postForm(REFRESH_PATH, body, "logout refresh", signal)
|
|
363
469
|
accessToken = tokens.access_token
|
|
364
470
|
}
|
|
365
471
|
if (!accessToken) return
|
|
366
472
|
|
|
367
473
|
for (let attempt = 0; ; attempt++) {
|
|
474
|
+
if (signal.aborted) throw new Error("Core session revocation timed out")
|
|
368
475
|
try {
|
|
369
|
-
await this.http.post(REVOKE_PATH, {}, {bearer: accessToken})
|
|
476
|
+
await this.http.post(REVOKE_PATH, {}, {bearer: accessToken, signal})
|
|
370
477
|
return
|
|
371
478
|
} catch (err) {
|
|
372
479
|
if (attempt + 1 >= REVOKE_ATTEMPTS || !isRetryableRevokeError(err)) throw err
|
|
@@ -422,13 +529,12 @@ export class Auth implements AuthModule {
|
|
|
422
529
|
try {
|
|
423
530
|
return await this.refresh(refreshToken, {deferExpired: this.canExchangeFreshSubject(), generation})
|
|
424
531
|
} catch (err) {
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
}
|
|
532
|
+
// Only a definitive rejection of the refresh token earns a fresh subject
|
|
533
|
+
// exchange. A transient failure would meet the same network, an abort
|
|
534
|
+
// was the caller's answer, and a cleared session must not reacquire
|
|
535
|
+
// credentials from the upstream provider.
|
|
536
|
+
if (err instanceof RefreshTokenRejectedError && this.canExchangeFreshSubject()) {
|
|
537
|
+
return this.exchangeAfterRejection(generation, err)
|
|
432
538
|
}
|
|
433
539
|
throw err
|
|
434
540
|
}
|
|
@@ -436,6 +542,36 @@ export class Auth implements AuthModule {
|
|
|
436
542
|
return this.exchange(generation)
|
|
437
543
|
}
|
|
438
544
|
|
|
545
|
+
/**
|
|
546
|
+
* One fresh subject exchange after Core rejected the refresh token (the host
|
|
547
|
+
* can supply a subject token on demand). The dead refresh token is already
|
|
548
|
+
* cleared, so a failure here leaves the next `getCoreToken` on the first-use
|
|
549
|
+
* exchange; `onExpired` fires only if Core itself refuses the fresh subject
|
|
550
|
+
* token, which is when the host really must re-authenticate.
|
|
551
|
+
*/
|
|
552
|
+
private async exchangeAfterRejection(generation: number, rejection: RefreshTokenRejectedError): Promise<string> {
|
|
553
|
+
this.assertSessionActive(generation)
|
|
554
|
+
this.logger.info("refresh token rejected; exchanging fresh subject token")
|
|
555
|
+
try {
|
|
556
|
+
return await this.exchange(generation)
|
|
557
|
+
} catch (err) {
|
|
558
|
+
if (isAbortError(err)) throw err
|
|
559
|
+
// A logout that raced the exchange wins over whatever the exchange came to.
|
|
560
|
+
this.assertSessionActive(generation)
|
|
561
|
+
if (isCoreRefusal(err, EXCHANGE_REFUSAL_ERRORS)) {
|
|
562
|
+
this.fireExpired()
|
|
563
|
+
throw rejection
|
|
564
|
+
}
|
|
565
|
+
// Already classified: a retryable failure, or a local problem that is not about the credentials.
|
|
566
|
+
if (err instanceof AuthUnavailableError || err instanceof AuthExpiredError) throw err
|
|
567
|
+
// The host's getSubjectToken threw (or the like): nothing was refused.
|
|
568
|
+
this.logger.warn("fresh subject token could not be exchanged; keeping the session retryable", {
|
|
569
|
+
error: err instanceof Error ? err.name : typeof err,
|
|
570
|
+
})
|
|
571
|
+
throw new AuthUnavailableError("fresh subject token could not be exchanged; try again later", {cause: err})
|
|
572
|
+
}
|
|
573
|
+
}
|
|
574
|
+
|
|
439
575
|
/**
|
|
440
576
|
* First-use exchange: trade the configured subject token for an access +
|
|
441
577
|
* refresh pair and save them.
|
|
@@ -469,7 +605,7 @@ export class Auth implements AuthModule {
|
|
|
469
605
|
subject_token_type: SUBJECT_TOKEN_TYPE_URN[subject.type],
|
|
470
606
|
})
|
|
471
607
|
|
|
472
|
-
const tokens = await this.
|
|
608
|
+
const tokens = await this.requestTokens(EXCHANGE_PATH, body, "exchange", EXCHANGE_REFUSAL_ERRORS)
|
|
473
609
|
await this.saveTokenPair(
|
|
474
610
|
{
|
|
475
611
|
accessToken: tokens.access_token,
|
|
@@ -488,13 +624,20 @@ export class Auth implements AuthModule {
|
|
|
488
624
|
* Refresh near expiry: trade the stored refresh token for a new access token
|
|
489
625
|
* and a rotated refresh token, saving both.
|
|
490
626
|
*
|
|
491
|
-
*
|
|
492
|
-
*
|
|
493
|
-
*
|
|
494
|
-
*
|
|
495
|
-
*
|
|
627
|
+
* Only Core's definitive rejection of the refresh token
|
|
628
|
+
* (`DEAD_REFRESH_TOKEN_ERRORS`) clears the stored state. The caller either
|
|
629
|
+
* falls back to one fresh subject-token exchange (for on-demand subject-token
|
|
630
|
+
* configs) or fires `onExpired` once; both surface a
|
|
631
|
+
* `RefreshTokenRejectedError`. We do not retry refresh forever: a dead
|
|
632
|
+
* refresh token will not heal on its own, and retrying would loop.
|
|
633
|
+
*
|
|
634
|
+
* Every other failure leaves the refresh token in place for the next call: it
|
|
635
|
+
* says nothing about the token, and Core accepts a retry with the same token
|
|
636
|
+
* even when it rotated the token and the response never arrived. Those throw
|
|
637
|
+
* `AuthUnavailableError`, except an abort, which propagates unchanged.
|
|
496
638
|
*/
|
|
497
639
|
private async refresh(refreshToken: string, opts?: {deferExpired?: boolean; generation?: number}): Promise<string> {
|
|
640
|
+
const generation = opts?.generation ?? this.sessionGeneration
|
|
498
641
|
const body = new URLSearchParams({
|
|
499
642
|
grant_type: "refresh_token",
|
|
500
643
|
refresh_token: refreshToken,
|
|
@@ -502,15 +645,20 @@ export class Auth implements AuthModule {
|
|
|
502
645
|
|
|
503
646
|
let tokens: TokenResponse
|
|
504
647
|
try {
|
|
505
|
-
tokens = await this.
|
|
506
|
-
} catch {
|
|
507
|
-
//
|
|
508
|
-
|
|
648
|
+
tokens = await this.requestTokens(REFRESH_PATH, body, "refresh", DEAD_REFRESH_TOKEN_ERRORS)
|
|
649
|
+
} catch (err) {
|
|
650
|
+
// An abort, a retryable failure and a local problem are not a rejection of the token.
|
|
651
|
+
if (!isCoreRefusal(err, DEAD_REFRESH_TOKEN_ERRORS)) throw err
|
|
652
|
+
// A rejection that arrives after logout is about a session that is already gone: it must
|
|
653
|
+
// not notify the host, clear what a newer session saved, or send the caller to exchange.
|
|
654
|
+
this.assertSessionActive(generation)
|
|
655
|
+
// Core rejected the refresh token for good: drop it so we do not keep
|
|
656
|
+
// presenting a known-bad token.
|
|
509
657
|
await this.store.clear()
|
|
510
658
|
if (!opts?.deferExpired) {
|
|
511
659
|
this.fireExpired()
|
|
512
660
|
}
|
|
513
|
-
throw new
|
|
661
|
+
throw new RefreshTokenRejectedError("token refresh failed; re-auth required")
|
|
514
662
|
}
|
|
515
663
|
|
|
516
664
|
await this.saveTokenPair(
|
|
@@ -518,7 +666,7 @@ export class Auth implements AuthModule {
|
|
|
518
666
|
accessToken: tokens.access_token,
|
|
519
667
|
refreshToken: tokens.refresh_token,
|
|
520
668
|
},
|
|
521
|
-
|
|
669
|
+
generation,
|
|
522
670
|
)
|
|
523
671
|
this.expiredFired = false
|
|
524
672
|
this.logger.debug("refreshed access token")
|
|
@@ -593,6 +741,42 @@ export class Auth implements AuthModule {
|
|
|
593
741
|
}
|
|
594
742
|
}
|
|
595
743
|
|
|
744
|
+
/**
|
|
745
|
+
* `postForm` for the calls whose failure says something about the credentials
|
|
746
|
+
* (`/exchange` and `/refresh`). Settles as exactly one of:
|
|
747
|
+
* - the tokens;
|
|
748
|
+
* - the caller's abort, unchanged;
|
|
749
|
+
* - a `TokenEndpointError` that is Core's own refusal (`isCoreRefusal` with
|
|
750
|
+
* `refusals`), for the caller to act on;
|
|
751
|
+
* - an `AuthExpiredError` that is not a failed request (no Core endpoint
|
|
752
|
+
* configured), unchanged;
|
|
753
|
+
* - `AuthUnavailableError` for everything else: a network error, a timeout, a
|
|
754
|
+
* 408, 429 or 5xx, a body that is not Core's JSON, any other 4xx. None of
|
|
755
|
+
* those says the credentials are bad, so the caller keeps them and retries.
|
|
756
|
+
*/
|
|
757
|
+
private async requestTokens(
|
|
758
|
+
path: string,
|
|
759
|
+
body: URLSearchParams,
|
|
760
|
+
label: string,
|
|
761
|
+
refusals: ReadonlySet<string>,
|
|
762
|
+
): Promise<TokenResponse> {
|
|
763
|
+
try {
|
|
764
|
+
return await this.postForm(path, body, label)
|
|
765
|
+
} catch (err) {
|
|
766
|
+
if (isAbortError(err) || isCoreRefusal(err, refusals)) throw err
|
|
767
|
+
if (err instanceof AuthExpiredError && !(err instanceof TokenEndpointError)) throw err
|
|
768
|
+
// Core answering with an error we do not recognize still carries its status;
|
|
769
|
+
// a transport or parse failure does not.
|
|
770
|
+
const status = err instanceof TokenEndpointError ? err.status : undefined
|
|
771
|
+
this.logger.warn("token request failed; keeping the credentials", {
|
|
772
|
+
label,
|
|
773
|
+
...(status !== undefined ? {status} : {}),
|
|
774
|
+
error: err instanceof Error ? err.name : typeof err,
|
|
775
|
+
})
|
|
776
|
+
throw new AuthUnavailableError(`${label} could not be completed; try again later`, {status, cause: err})
|
|
777
|
+
}
|
|
778
|
+
}
|
|
779
|
+
|
|
596
780
|
/**
|
|
597
781
|
* POST a form-encoded body to a token endpoint and parse the RFC token
|
|
598
782
|
* response.
|
|
@@ -602,25 +786,46 @@ export class Auth implements AuthModule {
|
|
|
602
786
|
* subject/refresh token in the body, not as a Bearer header. We never log the
|
|
603
787
|
* body: it carries a token.
|
|
604
788
|
*/
|
|
605
|
-
private async postForm(
|
|
789
|
+
private async postForm(
|
|
790
|
+
path: string,
|
|
791
|
+
body: URLSearchParams,
|
|
792
|
+
label: string,
|
|
793
|
+
signal?: AbortSignal,
|
|
794
|
+
): Promise<TokenResponse> {
|
|
606
795
|
const url = this.joinUrl(path)
|
|
607
796
|
const res = await this.httpTransport(url, {
|
|
608
797
|
method: "POST",
|
|
609
798
|
headers: {"Content-Type": "application/x-www-form-urlencoded"},
|
|
610
799
|
body: body.toString(),
|
|
800
|
+
...(signal ? {signal} : {}),
|
|
611
801
|
})
|
|
802
|
+
if (signal?.aborted) throw new Error("Core session revocation timed out")
|
|
612
803
|
|
|
613
804
|
if (!res.ok) {
|
|
614
|
-
// The body may carry an RFC `{ error, error_description }
|
|
615
|
-
//
|
|
616
|
-
//
|
|
617
|
-
|
|
618
|
-
|
|
805
|
+
// The body may carry an RFC `{ error, error_description }`. We keep only
|
|
806
|
+
// the short `error` code (the caller decides what it means) and never the
|
|
807
|
+
// description, so no token field can leak into a message a host might
|
|
808
|
+
// surface.
|
|
809
|
+
// Only a 400 or 401 body is ever consulted, so no other body is read.
|
|
810
|
+
const code = CORE_REFUSAL_STATUSES.has(res.status) ? await this.readOauthErrorCode(res) : undefined
|
|
811
|
+
this.logger.warn("auth token request failed", {label, status: res.status, ...(code ? {code} : {})})
|
|
812
|
+
throw new TokenEndpointError(`${label} request failed with status ${res.status}`, res.status, code)
|
|
619
813
|
}
|
|
620
814
|
|
|
621
815
|
return (await res.json()) as TokenResponse
|
|
622
816
|
}
|
|
623
817
|
|
|
818
|
+
/** The OAuth `error` code of a refusal, or undefined when the body is not Core's `{error}` JSON. */
|
|
819
|
+
private async readOauthErrorCode(res: Response): Promise<string | undefined> {
|
|
820
|
+
try {
|
|
821
|
+
const data: unknown = await res.json()
|
|
822
|
+
const code = typeof data === "object" && data !== null ? (data as {error?: unknown}).error : undefined
|
|
823
|
+
return typeof code === "string" && OAUTH_ERROR_CODE_PATTERN.test(code) ? code : undefined
|
|
824
|
+
} catch {
|
|
825
|
+
return undefined
|
|
826
|
+
}
|
|
827
|
+
}
|
|
828
|
+
|
|
624
829
|
/**
|
|
625
830
|
* Join the core base URL and a path without a double or missing slash.
|
|
626
831
|
*
|