@idp.global/sdk 19.3.0 → 19.4.0

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.
Files changed (38) hide show
  1. package/changelog.md +40 -0
  2. package/dist_ts/00_commitinfo_data.js +1 -1
  3. package/dist_ts_browser/classes.idpclient.js +1 -1
  4. package/dist_ts_browser/classes.idprequests.js +1 -1
  5. package/dist_ts_browser/classes.relyingpartybearerclient.d.ts +276 -0
  6. package/dist_ts_browser/classes.relyingpartybearerclient.js +591 -0
  7. package/dist_ts_browser/index.d.ts +1 -0
  8. package/dist_ts_browser/index.js +2 -1
  9. package/dist_ts_browser/plugins.js +1 -1
  10. package/dist_ts_browser/secret-delivery.js +1 -1
  11. package/dist_ts_relyingparty/classes.authorityobserver.d.ts +23 -0
  12. package/dist_ts_relyingparty/classes.authorityobserver.js +68 -13
  13. package/dist_ts_relyingparty/classes.errors.d.ts +3 -1
  14. package/dist_ts_relyingparty/classes.errors.js +2 -1
  15. package/dist_ts_relyingparty/classes.relyingpartyroutes.d.ts +12 -0
  16. package/dist_ts_relyingparty/classes.relyingpartyroutes.js +33 -6
  17. package/dist_ts_relyingparty/classes.relyingpartysessions.d.ts +102 -7
  18. package/dist_ts_relyingparty/classes.relyingpartysessions.js +228 -29
  19. package/dist_ts_relyingparty/classes.rpmodels.d.ts +6 -4
  20. package/dist_ts_relyingparty/classes.rpmodels.js +8 -6
  21. package/dist_ts_relyingparty/contract.bearer.d.ts +82 -0
  22. package/dist_ts_relyingparty/contract.bearer.js +9 -0
  23. package/dist_ts_relyingparty/helpers.bearer.d.ts +3 -3
  24. package/dist_ts_relyingparty/helpers.bearer.js +3 -3
  25. package/dist_ts_relyingparty/interfaces.d.ts +34 -24
  26. package/package.json +2 -1
  27. package/readme.md +215 -19
  28. package/ts/00_commitinfo_data.ts +1 -1
  29. package/ts_browser/classes.relyingpartybearerclient.ts +821 -0
  30. package/ts_browser/index.ts +1 -0
  31. package/ts_relyingparty/classes.authorityobserver.ts +80 -12
  32. package/ts_relyingparty/classes.errors.ts +4 -1
  33. package/ts_relyingparty/classes.relyingpartyroutes.ts +38 -7
  34. package/ts_relyingparty/classes.relyingpartysessions.ts +298 -34
  35. package/ts_relyingparty/classes.rpmodels.ts +7 -4
  36. package/ts_relyingparty/contract.bearer.ts +99 -0
  37. package/ts_relyingparty/helpers.bearer.ts +8 -9
  38. package/ts_relyingparty/interfaces.ts +49 -26
@@ -0,0 +1,821 @@
1
+ import {
2
+ RELYING_PARTY_BEARER_MESSAGE_TYPE,
3
+ type IRelyingPartyBearerLogoutAnswer,
4
+ type IRelyingPartyBearerTokenAnswer,
5
+ } from '../ts_relyingparty/contract.bearer.js';
6
+
7
+ export type {
8
+ IRelyingPartyBearerErrorAnswer,
9
+ IRelyingPartyBearerLogoutAnswer,
10
+ IRelyingPartyBearerMessage,
11
+ IRelyingPartyBearerSessionAnswer,
12
+ IRelyingPartyBearerSessionInfo,
13
+ IRelyingPartyBearerTokenAnswer,
14
+ TRelyingPartyBearerDeliveryError,
15
+ TRelyingPartyBearerErrorCode,
16
+ } from '../ts_relyingparty/contract.bearer.js';
17
+ export { RELYING_PARTY_BEARER_MESSAGE_TYPE };
18
+
19
+ /** The client kinds a browser signs in as; native clients use `loopback` and `custom_scheme` themselves. */
20
+ export type TRelyingPartyBearerBrowserClientKind = 'web' | 'popup';
21
+
22
+ /** The pair a bearer client keeps: the relying party's answer and when it arrived. */
23
+ export interface IRelyingPartyBearerStoredTokens extends IRelyingPartyBearerTokenAnswer {
24
+ /** epoch milliseconds on this device's clock when the answer arrived; with `expiresIn` it dates the access token's end here */
25
+ receivedAt: number;
26
+ }
27
+
28
+ /**
29
+ * Where the application keeps the token pair — IndexedDB, say — for every
30
+ * tab of its origin. The client keeps no pair in memory: it reads this store
31
+ * on every use and again inside the refresh lock, so a pair another tab
32
+ * rotated is seen at once. `set` and `clear` resolve once the change is
33
+ * durable; the client hands out a rotated pair only after `set` resolved.
34
+ *
35
+ * Each `set` and `clear` is given the signal of its operation's deadline
36
+ * (`requestTimeoutMs`). An adapter either honours it, so a write the signal
37
+ * aborted is not made and the call rejects, or completes synchronously, as
38
+ * one over `localStorage` does, so it is never late. The lock is never held
39
+ * past the deadline, whatever a write still does: an adapter that ignores the
40
+ * signal can finish one after another tab took the lock. A late `set`
41
+ * overwrites what that tab stored or cleared, and the pair it leaves can be
42
+ * spent or of an ended session; its refresh then ends the session
43
+ * (`refresh_token_reused`) or is refused. A late `clear` removes the pair that
44
+ * tab stored. Either way the user signs in again.
45
+ */
46
+ export interface IRelyingPartyBearerTokenStorage {
47
+ get(): Promise<IRelyingPartyBearerStoredTokens | null>;
48
+ set(tokensArg: IRelyingPartyBearerStoredTokens, optionsArg: { signal: AbortSignal }): Promise<void>;
49
+ clear(optionsArg: { signal: AbortSignal }): Promise<void>;
50
+ }
51
+
52
+ /**
53
+ * A login on its way: what `createLogin` made and the receiver needs back.
54
+ * A `web` login leaves the page, so the application keeps it until the
55
+ * return target page hands it to `completeRedirectLogin` — in
56
+ * `sessionStorage` or IndexedDB, never in a URL or a log: `codeVerifier` is
57
+ * the secret that makes the code worth anything.
58
+ */
59
+ export interface IRelyingPartyBearerClientLogin {
60
+ clientKind: TRelyingPartyBearerBrowserClientKind;
61
+ returnTarget: string;
62
+ state: string;
63
+ codeVerifier: string;
64
+ /** the bearer login start: navigate to it (`web`) or open it (`popup`) */
65
+ url: string;
66
+ }
67
+
68
+ /** What the client reads of a `message` event. */
69
+ export interface IRelyingPartyBearerMessageEvent {
70
+ readonly origin: string;
71
+ readonly source: unknown;
72
+ readonly data: unknown;
73
+ }
74
+
75
+ /** What the client reads of a popup it opened. */
76
+ export interface IRelyingPartyBearerPopup {
77
+ readonly closed: boolean;
78
+ }
79
+
80
+ /** The parts of `window` the login receivers use; `window` itself is one. */
81
+ export interface IRelyingPartyBearerClientWindow {
82
+ readonly location: { readonly href: string };
83
+ readonly history: {
84
+ readonly state: unknown;
85
+ replaceState(dataArg: unknown, unusedArg: string, urlArg?: string): void;
86
+ };
87
+ open(urlArg: string, targetArg?: string, featuresArg?: string): IRelyingPartyBearerPopup | null;
88
+ addEventListener(typeArg: 'message', listenerArg: (eventArg: IRelyingPartyBearerMessageEvent) => void): void;
89
+ removeEventListener(typeArg: 'message', listenerArg: (eventArg: IRelyingPartyBearerMessageEvent) => void): void;
90
+ }
91
+
92
+ export interface IRelyingPartyBearerClientOptions {
93
+ /** the relying party's public origin, exactly: where its bearer routes and its popup page are served */
94
+ origin: string;
95
+ /** the prefix of the relying party's login routes; `/auth/` unless it mounts them elsewhere */
96
+ loginPathPrefix?: string;
97
+ storage: IRelyingPartyBearerTokenStorage;
98
+ /** the Web Lock every refresh, logout and store of a claimed pair holds; one name per pair in `storage` */
99
+ lockName?: string;
100
+ /** how long before its end on this device's clock an access token is rotated; at most half its lifetime */
101
+ refreshSkewMs?: number;
102
+ /**
103
+ * The deadline of each operation of the client: the claim of a login's
104
+ * code, a refresh with the write of its pair, the store of a claimed pair
105
+ * with the end of the session it replaced, and a logout. 30 seconds unless
106
+ * given, at most two minutes, since every tab of the origin waits on the
107
+ * lock meanwhile. When it fires the request and the storage write are
108
+ * aborted, a late answer is never stored and the lock is released.
109
+ */
110
+ requestTimeoutMs?: number;
111
+ /** `navigator.locks` unless given */
112
+ locks?: LockManager;
113
+ /** `globalThis.fetch` unless given */
114
+ fetch?: typeof globalThis.fetch;
115
+ /** `window` unless given; only the login receivers need one */
116
+ window?: IRelyingPartyBearerClientWindow;
117
+ now?: () => number;
118
+ }
119
+
120
+ export interface IRelyingPartyBearerPopupOptions {
121
+ /** how long the popup may take; ten minutes, the life of a login attempt, unless given */
122
+ timeoutMs?: number;
123
+ signal?: AbortSignal;
124
+ /** the `features` of `window.open`; never `noopener`, the popup posts to its opener */
125
+ windowFeatures?: string;
126
+ }
127
+
128
+ /** What a login did to the pair stored before it. */
129
+ export type TRelyingPartyBearerPreviousSessionOutcome =
130
+ /** no pair was stored */
131
+ | 'no_previous_session'
132
+ /** the stored pair was of the session this login opened; there was nothing to end */
133
+ | 'same_session'
134
+ /** the logout route ended the previous session, or answered that it was over already */
135
+ | 'previous_session_ended'
136
+ /** the previous session could not be ended and lives on at the relying party until it expires; `previousSessionError` says why */
137
+ | 'previous_session_not_revoked';
138
+
139
+ /** A received login: the pair now stored, and what became of the session of the pair it replaced. */
140
+ export interface IRelyingPartyBearerLoginResult {
141
+ tokens: IRelyingPartyBearerStoredTokens;
142
+ previousSession: TRelyingPartyBearerPreviousSessionOutcome;
143
+ /** with `previous_session_not_revoked`: why the logout route did not end it */
144
+ previousSessionError?: RelyingPartyBearerClientError;
145
+ }
146
+
147
+ export type TRelyingPartyBearerClientErrorCode =
148
+ /** the delivery's state is not the one of the login it came back to; nothing was claimed */
149
+ | 'state_mismatch'
150
+ /** the delivery carries no code; `deliveryError` says why */
151
+ | 'login_failed'
152
+ /** this login was received once already; a code is claimed once, never again */
153
+ | 'already_received'
154
+ /** the browser opened no popup */
155
+ | 'popup_blocked'
156
+ /** the popup was closed before it delivered */
157
+ | 'popup_closed'
158
+ /** the popup delivered nothing in time */
159
+ | 'popup_timeout'
160
+ /** the request got no answer (network, CORS, a redirect) or none before `requestTimeoutMs`; a claim or refresh may have been spent anyway */
161
+ | 'request_failed'
162
+ /** the relying party refused the request; `status` and `answerError` say how */
163
+ | 'request_refused'
164
+ /** an answer outside the bearer contract */
165
+ | 'unexpected_answer'
166
+ /** `logout()` cleared the pair, so this device is signed out, but the relying party did not confirm the session's end; `cause` says why */
167
+ | 'session_not_revoked';
168
+
169
+ export class RelyingPartyBearerClientError extends Error {
170
+ public readonly status?: number;
171
+ /** the `error` the relying party answered (`TRelyingPartyBearerErrorCode`) */
172
+ public readonly answerError?: string;
173
+ /** the `error` a delivery carried (`TRelyingPartyBearerDeliveryError`) */
174
+ public readonly deliveryError?: string;
175
+
176
+ constructor(
177
+ public readonly code: TRelyingPartyBearerClientErrorCode,
178
+ detailsArg: { status?: number; answerError?: string; deliveryError?: string; cause?: unknown } = {},
179
+ ) {
180
+ super(code, detailsArg.cause !== undefined ? { cause: detailsArg.cause } : undefined);
181
+ this.name = 'RelyingPartyBearerClientError';
182
+ if (detailsArg.status !== undefined) this.status = detailsArg.status;
183
+ if (detailsArg.answerError !== undefined) this.answerError = detailsArg.answerError;
184
+ if (detailsArg.deliveryError !== undefined) this.deliveryError = detailsArg.deliveryError;
185
+ }
186
+ }
187
+
188
+ const DEFAULT_LOGIN_PATH_PREFIX = '/auth/';
189
+ const DEFAULT_REFRESH_SKEW_MS = 60_000;
190
+ const DEFAULT_REQUEST_TIMEOUT_MS = 30_000;
191
+ /** Every tab of the origin waits on the lock while a section runs: two minutes at most. */
192
+ const MAX_REQUEST_TIMEOUT_MS = 120_000;
193
+ /** The life of a login attempt at the relying party (`LOGIN_ATTEMPT_MAX_AGE_SECONDS`). */
194
+ const DEFAULT_POPUP_TIMEOUT_MS = 10 * 60 * 1_000;
195
+ const DEFAULT_POPUP_FEATURES = 'popup,width=480,height=720';
196
+ const POPUP_CLOSED_POLL_MS = 500;
197
+ /** A popup posts and closes at once; its message can arrive after the opener sees it closed. */
198
+ const POPUP_CLOSED_GRACE_MS = 1_000;
199
+ /** 32 random bytes: a 43-character verifier and state (RFC 7636 §4.1). */
200
+ const RANDOM_BYTES = 32;
201
+ const DELIVERY_PARAMS = ['code', 'error', 'state'] as const;
202
+
203
+ const base64Url = (bytesArg: Uint8Array): string => {
204
+ let binary = '';
205
+ for (const byte of bytesArg) binary += String.fromCharCode(byte);
206
+ return globalThis.btoa(binary).replace(/\+/gu, '-').replace(/\//gu, '_').replace(/=+$/u, '');
207
+ };
208
+
209
+ const randomBase64Url = (): string => base64Url(globalThis.crypto.getRandomValues(new Uint8Array(RANDOM_BYTES)));
210
+
211
+ /** The S256 challenge of a verifier: BASE64URL(SHA-256(ASCII(verifier))). */
212
+ const pkceChallengeOf = async (verifierArg: string): Promise<string> =>
213
+ base64Url(new Uint8Array(await globalThis.crypto.subtle.digest('SHA-256', new TextEncoder().encode(verifierArg))));
214
+
215
+ const isRecord = (valueArg: unknown): valueArg is Record<string, unknown> =>
216
+ typeof valueArg === 'object' && valueArg !== null && !Array.isArray(valueArg);
217
+
218
+ const isText = (valueArg: unknown): valueArg is string => typeof valueArg === 'string' && valueArg.length > 0;
219
+
220
+ const isTime = (valueArg: unknown): valueArg is number => typeof valueArg === 'number' && Number.isFinite(valueArg);
221
+
222
+ /** Throws `request_failed` once a section's deadline has fired: nothing is sent or written past it. */
223
+ const inTime = (signalArg: AbortSignal): void => {
224
+ if (signalArg.aborted) {
225
+ throw new RelyingPartyBearerClientError('request_failed');
226
+ }
227
+ };
228
+
229
+ /** The one value of a parameter, or `undefined` when it is absent or repeated. */
230
+ const singleParam = (paramsArg: URLSearchParams, nameArg: string): string | undefined => {
231
+ const values = paramsArg.getAll(nameArg);
232
+ return values.length === 1 ? values[0] : undefined;
233
+ };
234
+
235
+ /** A token answer exactly as the bearer contract says, or `null`. */
236
+ const tokenAnswerOf = (answerArg: unknown): IRelyingPartyBearerTokenAnswer | null => {
237
+ if (
238
+ !isRecord(answerArg)
239
+ || answerArg.tokenType !== 'Bearer'
240
+ || !isText(answerArg.accessToken)
241
+ || !isText(answerArg.refreshToken)
242
+ || !isTime(answerArg.accessTokenExpiresAt)
243
+ || !isTime(answerArg.expiresIn)
244
+ || answerArg.expiresIn <= 0
245
+ || !isTime(answerArg.refreshTokenExpiresAt)
246
+ || !isRecord(answerArg.session)
247
+ || !isText(answerArg.session.sessionId)
248
+ || !isText(answerArg.session.principalId)
249
+ || !isTime(answerArg.session.expiresAt)
250
+ ) {
251
+ return null;
252
+ }
253
+ return {
254
+ tokenType: 'Bearer',
255
+ accessToken: answerArg.accessToken,
256
+ accessTokenExpiresAt: answerArg.accessTokenExpiresAt,
257
+ expiresIn: answerArg.expiresIn,
258
+ refreshToken: answerArg.refreshToken,
259
+ refreshTokenExpiresAt: answerArg.refreshTokenExpiresAt,
260
+ session: {
261
+ sessionId: answerArg.session.sessionId,
262
+ principalId: answerArg.session.principalId,
263
+ expiresAt: answerArg.session.expiresAt,
264
+ },
265
+ };
266
+ };
267
+
268
+ /**
269
+ * The browser side of bearer hand-off (`@idp.global/sdk/relyingparty`
270
+ * `bearer`): it starts a `web` or `popup` login with PKCE and a state,
271
+ * receives the delivery, claims the code once and keeps the token pair in
272
+ * the application's storage. Every refresh, logout and store of a claimed
273
+ * pair holds one Web Lock, so the tabs of an origin rotate the pair one at a
274
+ * time: inside the lock the pair is read from storage again, a pair another
275
+ * tab rotated is used as it is, and a rotated pair is stored before the lock
276
+ * is released and before its access token is handed out. Each claim and
277
+ * each section that holds the lock ends by `requestTimeoutMs`, so a hanging
278
+ * request or write never holds the other tabs. A login replaces the stored
279
+ * pair and ends that pair's session. Rotation is strict at the relying
280
+ * party: a refresh token spent once ends the session when it comes back, so
281
+ * nothing here retries a claim or a refresh.
282
+ *
283
+ * It needs the Web Locks API and Web Crypto, both of them only in a secure
284
+ * context, and has no fallback for either.
285
+ */
286
+ export class RelyingPartyBearerClient {
287
+ public readonly origin: string;
288
+ readonly #paths: { claim: string; refresh: string; logout: string; login: string };
289
+ readonly #storage: IRelyingPartyBearerTokenStorage;
290
+ readonly #lockName: string;
291
+ readonly #refreshSkewMs: number;
292
+ readonly #requestTimeoutMs: number;
293
+ readonly #locks: LockManager;
294
+ readonly #fetch: typeof globalThis.fetch;
295
+ readonly #window: IRelyingPartyBearerClientWindow | undefined;
296
+ readonly #now: () => number;
297
+ /** the states of the logins received here; a login is received once */
298
+ readonly #receivedStates = new Set<string>();
299
+
300
+ constructor(optionsArg: IRelyingPartyBearerClientOptions) {
301
+ const origin = optionsArg?.origin;
302
+ let parsedOrigin: URL | null = null;
303
+ try {
304
+ parsedOrigin = typeof origin === 'string' ? new URL(origin) : null;
305
+ } catch {
306
+ parsedOrigin = null;
307
+ }
308
+ if (!parsedOrigin || parsedOrigin.origin !== origin || !['https:', 'http:'].includes(parsedOrigin.protocol)) {
309
+ throw new Error('origin must be the relying party\'s exact origin, such as https://app.example');
310
+ }
311
+ const prefix = optionsArg.loginPathPrefix ?? DEFAULT_LOGIN_PATH_PREFIX;
312
+ if (typeof prefix !== 'string' || !/^\/(?:[A-Za-z0-9._~-]+\/)*$/u.test(prefix)) {
313
+ throw new Error('loginPathPrefix must be a path that starts and ends with /');
314
+ }
315
+ const storage = optionsArg.storage;
316
+ if (!storage || typeof storage.get !== 'function' || typeof storage.set !== 'function' || typeof storage.clear !== 'function') {
317
+ throw new Error('storage must have get, set and clear');
318
+ }
319
+ const locks = optionsArg.locks ?? globalThis.navigator?.locks;
320
+ if (!locks || typeof locks.request !== 'function') {
321
+ throw new Error('RelyingPartyBearerClient needs the Web Locks API (navigator.locks)');
322
+ }
323
+ if (typeof globalThis.crypto?.subtle?.digest !== 'function' || typeof globalThis.crypto.getRandomValues !== 'function') {
324
+ throw new Error('RelyingPartyBearerClient needs Web Crypto (crypto.subtle), which a browser offers only in a secure context');
325
+ }
326
+ const fetchFunction = optionsArg.fetch ?? globalThis.fetch?.bind(globalThis);
327
+ if (typeof fetchFunction !== 'function') {
328
+ throw new Error('RelyingPartyBearerClient needs fetch');
329
+ }
330
+ const refreshSkewMs = optionsArg.refreshSkewMs ?? DEFAULT_REFRESH_SKEW_MS;
331
+ if (!Number.isInteger(refreshSkewMs) || refreshSkewMs < 0) {
332
+ throw new Error('refreshSkewMs must be a whole number of milliseconds');
333
+ }
334
+ // only an absent deadline takes the default: any other value that is not one throws
335
+ const requestTimeoutMs = optionsArg.requestTimeoutMs === undefined ? DEFAULT_REQUEST_TIMEOUT_MS : optionsArg.requestTimeoutMs;
336
+ if (
337
+ typeof requestTimeoutMs !== 'number'
338
+ || !Number.isFinite(requestTimeoutMs)
339
+ || requestTimeoutMs <= 0
340
+ || requestTimeoutMs > MAX_REQUEST_TIMEOUT_MS
341
+ ) {
342
+ throw new Error(`requestTimeoutMs must be more than 0 and at most ${MAX_REQUEST_TIMEOUT_MS} milliseconds`);
343
+ }
344
+ this.origin = origin;
345
+ this.#paths = {
346
+ login: `${origin}${prefix}bearer/login`,
347
+ claim: `${origin}${prefix}bearer/claim`,
348
+ refresh: `${origin}${prefix}bearer/refresh`,
349
+ logout: `${origin}${prefix}bearer/logout`,
350
+ };
351
+ this.#storage = storage;
352
+ this.#lockName = optionsArg.lockName ?? `idp.global/relyingparty:bearer-tokens ${origin}`;
353
+ this.#refreshSkewMs = refreshSkewMs;
354
+ this.#requestTimeoutMs = requestTimeoutMs;
355
+ this.#locks = locks;
356
+ this.#fetch = fetchFunction;
357
+ this.#window = optionsArg.window ?? (globalThis as { window?: IRelyingPartyBearerClientWindow }).window;
358
+ this.#now = optionsArg.now ?? Date.now;
359
+ }
360
+
361
+ /**
362
+ * A new login: a fresh verifier, its S256 challenge and a state, each from
363
+ * 32 random bytes, and the URL that starts it. Make a popup login before
364
+ * the click that opens it: this is async, and a browser opens a popup only
365
+ * within the user's gesture.
366
+ */
367
+ public async createLogin(optionsArg: {
368
+ clientKind: TRelyingPartyBearerBrowserClientKind;
369
+ returnTarget: string;
370
+ }): Promise<IRelyingPartyBearerClientLogin> {
371
+ const { clientKind, returnTarget } = optionsArg ?? ({} as typeof optionsArg);
372
+ if (clientKind !== 'web' && clientKind !== 'popup') {
373
+ throw new Error('a browser signs in as a web or popup client');
374
+ }
375
+ if (!isText(returnTarget)) {
376
+ throw new Error('returnTarget must name the configured return target');
377
+ }
378
+ const codeVerifier = randomBase64Url();
379
+ const state = randomBase64Url();
380
+ const url = new URL(this.#paths.login);
381
+ url.searchParams.set('client_kind', clientKind);
382
+ url.searchParams.set('return_target', returnTarget);
383
+ url.searchParams.set('code_challenge', await pkceChallengeOf(codeVerifier));
384
+ url.searchParams.set('code_challenge_method', 'S256');
385
+ url.searchParams.set('state', state);
386
+ return { clientKind, returnTarget, state, codeVerifier, url: url.href };
387
+ }
388
+
389
+ /**
390
+ * Receives a `web` login on its return target page. The delivery leaves
391
+ * the address first, before anything is checked, so neither a reload nor
392
+ * the history holds the code. A delivery whose state is not the login's is
393
+ * refused unclaimed; a code is claimed once, and a failed claim is not
394
+ * retried. The claimed pair replaces the stored one, whose session is
395
+ * ended then (`IRelyingPartyBearerLoginResult`). Answers `null` on a page
396
+ * that holds no delivery.
397
+ */
398
+ public async completeRedirectLogin(
399
+ loginArg: IRelyingPartyBearerClientLogin | null | undefined,
400
+ ): Promise<IRelyingPartyBearerLoginResult | null> {
401
+ const window = this.requireWindow();
402
+ const url = new URL(window.location.href);
403
+ if (!DELIVERY_PARAMS.some((nameArg) => url.searchParams.has(nameArg))) {
404
+ return null;
405
+ }
406
+ const delivered = url.searchParams;
407
+ const code = singleParam(delivered, 'code');
408
+ const error = singleParam(delivered, 'error');
409
+ const state = singleParam(delivered, 'state');
410
+ const kept = new URL(url.href);
411
+ for (const name of DELIVERY_PARAMS) {
412
+ kept.searchParams.delete(name);
413
+ }
414
+ window.history.replaceState(window.history.state, '', kept.pathname + kept.search + kept.hash);
415
+ if (!loginArg || loginArg.clientKind !== 'web' || state === undefined || state !== loginArg.state) {
416
+ throw new RelyingPartyBearerClientError('state_mismatch');
417
+ }
418
+ return this.receive(loginArg, code, error);
419
+ }
420
+
421
+ /**
422
+ * Opens a `popup` login and receives what its page posts: a message is
423
+ * taken only from the relying party's origin, from this very popup, of the
424
+ * bearer message type and with the login's state; any other is ignored.
425
+ * The popup opens before this returns, so call it in the click handler
426
+ * itself, with a login made beforehand. The claimed pair replaces the
427
+ * stored one like `completeRedirectLogin`'s.
428
+ */
429
+ public openPopupLogin(
430
+ loginArg: IRelyingPartyBearerClientLogin,
431
+ optionsArg: IRelyingPartyBearerPopupOptions = {},
432
+ ): Promise<IRelyingPartyBearerLoginResult> {
433
+ let window: IRelyingPartyBearerClientWindow;
434
+ try {
435
+ window = this.requireWindow();
436
+ if (!loginArg || loginArg.clientKind !== 'popup') {
437
+ throw new Error('openPopupLogin needs a popup login');
438
+ }
439
+ if (this.#receivedStates.has(loginArg.state)) {
440
+ throw new RelyingPartyBearerClientError('already_received');
441
+ }
442
+ } catch (error) {
443
+ return Promise.reject(error);
444
+ }
445
+ let popup: IRelyingPartyBearerPopup | null;
446
+ try {
447
+ popup = window.open(loginArg.url, '_blank', optionsArg.windowFeatures ?? DEFAULT_POPUP_FEATURES);
448
+ } catch (error) {
449
+ return Promise.reject(error);
450
+ }
451
+ if (!popup) {
452
+ return Promise.reject(new RelyingPartyBearerClientError('popup_blocked'));
453
+ }
454
+ return this.receivePopup(window, popup, loginArg, optionsArg);
455
+ }
456
+
457
+ /**
458
+ * An access token to send right now, or `null` when there is no session.
459
+ * One that is about to end is rotated first, by one tab for all of them.
460
+ */
461
+ public async accessToken(): Promise<string | null> {
462
+ const stored = await this.#storage.get();
463
+ if (!stored) {
464
+ return null;
465
+ }
466
+ if (this.isFresh(stored)) {
467
+ return stored.accessToken;
468
+ }
469
+ return (await this.rotate(stored.refreshToken, null))?.accessToken ?? null;
470
+ }
471
+
472
+ /**
473
+ * Rotates the pair now — after the relying party refused
474
+ * `rejectedAccessTokenArg`, say — unless another tab already did, and
475
+ * answers the pair to use: `null` once the session is over, which clears
476
+ * the storage. A relying party that cannot refresh right now
477
+ * (`authority_unavailable`) keeps the pair as it is; try again later.
478
+ */
479
+ public async refresh(rejectedAccessTokenArg?: string): Promise<IRelyingPartyBearerStoredTokens | null> {
480
+ const stored = await this.#storage.get();
481
+ if (!stored) {
482
+ return null;
483
+ }
484
+ return this.rotate(stored.refreshToken, rejectedAccessTokenArg ?? null);
485
+ }
486
+
487
+ /**
488
+ * Clears the storage and then ends the session at the relying party with
489
+ * the pair it held, and answers whether that ended a live session. When the
490
+ * relying party cannot be reached, refuses or gives no answer by
491
+ * `requestTimeoutMs`, the call throws `session_not_revoked` with that
492
+ * failure as its `cause`: this device is signed out, and the session may
493
+ * live on at the relying party until it expires, so tell the user they are
494
+ * signed out on this device only. A deadline that fires before the storage
495
+ * is cleared throws `request_failed`, and the pair stays.
496
+ */
497
+ public async logout(): Promise<boolean> {
498
+ let cleared = false;
499
+ const notRevoked = (errorArg: unknown) => new RelyingPartyBearerClientError('session_not_revoked', { cause: errorArg });
500
+ return this.#locks.request(this.#lockName, () => this.withDeadline(async (signalArg) => {
501
+ const current = await this.#storage.get();
502
+ if (!current) {
503
+ return false;
504
+ }
505
+ inTime(signalArg);
506
+ await this.#storage.clear({ signal: signalArg });
507
+ cleared = true;
508
+ try {
509
+ return await this.endSessionOf(current, signalArg);
510
+ } catch (error) {
511
+ throw notRevoked(error);
512
+ }
513
+ }, () => {
514
+ // once the pair is cleared this device is signed out, whatever the request still does
515
+ const failure = new RelyingPartyBearerClientError('request_failed');
516
+ throw cleared ? notRevoked(failure) : failure;
517
+ }));
518
+ }
519
+
520
+ private requireWindow(): IRelyingPartyBearerClientWindow {
521
+ if (!this.#window) {
522
+ throw new Error('the login receivers of RelyingPartyBearerClient need a window');
523
+ }
524
+ return this.#window;
525
+ }
526
+
527
+ private isFresh(storedArg: IRelyingPartyBearerStoredTokens): boolean {
528
+ const lifetimeMs = storedArg.expiresIn * 1_000;
529
+ const skewMs = Math.min(this.#refreshSkewMs, lifetimeMs / 2);
530
+ return this.#now() < storedArg.receivedAt + lifetimeMs - skewMs;
531
+ }
532
+
533
+ /** Takes a delivery for its login, once, claims its code and stores the pair in place of the one before. */
534
+ private async receive(
535
+ loginArg: IRelyingPartyBearerClientLogin,
536
+ codeArg: unknown,
537
+ errorArg: unknown,
538
+ ): Promise<IRelyingPartyBearerLoginResult> {
539
+ if (this.#receivedStates.has(loginArg.state)) {
540
+ throw new RelyingPartyBearerClientError('already_received');
541
+ }
542
+ this.#receivedStates.add(loginArg.state);
543
+ if (errorArg !== undefined) {
544
+ throw new RelyingPartyBearerClientError(isText(errorArg) && codeArg === undefined ? 'login_failed' : 'unexpected_answer', {
545
+ ...(isText(errorArg) ? { deliveryError: errorArg } : {}),
546
+ });
547
+ }
548
+ if (!isText(codeArg)) {
549
+ throw new RelyingPartyBearerClientError('unexpected_answer');
550
+ }
551
+ // the claim touches no stored pair, so it holds no lock, only its own deadline; a failed one leaves the stored pair as it was
552
+ const answer = tokenAnswerOf(await this.withDeadline((signalArg) =>
553
+ this.post(this.#paths.claim, { code: codeArg, codeVerifier: loginArg.codeVerifier }, {}, signalArg)));
554
+ if (!answer) {
555
+ throw new RelyingPartyBearerClientError('unexpected_answer', { status: 200 });
556
+ }
557
+ return this.replacePair({ ...answer, receivedAt: this.#now() });
558
+ }
559
+
560
+ /**
561
+ * Stores a claimed pair in place of the stored one and then ends the
562
+ * session of that one with its tokens, held here, through the logout
563
+ * route. Both run under the lock a refresh holds, so no tab rotates the
564
+ * replaced pair meanwhile. A session that cannot be ended is the result's
565
+ * `previous_session_not_revoked`, neither thrown nor dropped: the new pair
566
+ * is stored by then.
567
+ */
568
+ private replacePair(tokensArg: IRelyingPartyBearerStoredTokens): Promise<IRelyingPartyBearerLoginResult> {
569
+ /** what the login answers if the deadline fires now: nothing before the pair is stored */
570
+ let atDeadline: IRelyingPartyBearerLoginResult | null = null;
571
+ const notRevoked = (errorArg: unknown): IRelyingPartyBearerLoginResult => ({
572
+ tokens: tokensArg,
573
+ previousSession: 'previous_session_not_revoked',
574
+ previousSessionError: errorArg instanceof RelyingPartyBearerClientError
575
+ ? errorArg
576
+ : new RelyingPartyBearerClientError('unexpected_answer', { cause: errorArg }),
577
+ });
578
+ return this.#locks.request(this.#lockName, () => this.withDeadline<IRelyingPartyBearerLoginResult>(async (signalArg) => {
579
+ const previous = await this.#storage.get();
580
+ inTime(signalArg);
581
+ await this.#storage.set(tokensArg, { signal: signalArg });
582
+ if (!previous) {
583
+ return { tokens: tokensArg, previousSession: 'no_previous_session' };
584
+ }
585
+ if (previous.session.sessionId === tokensArg.session.sessionId) {
586
+ return { tokens: tokensArg, previousSession: 'same_session' };
587
+ }
588
+ atDeadline = notRevoked(new RelyingPartyBearerClientError('request_failed'));
589
+ try {
590
+ await this.endSessionOf(previous, signalArg);
591
+ return { tokens: tokensArg, previousSession: 'previous_session_ended' };
592
+ } catch (error) {
593
+ return notRevoked(error);
594
+ }
595
+ }, () => {
596
+ // past its write the login stands; only the end of the previous session is cut short
597
+ if (!atDeadline) {
598
+ throw new RelyingPartyBearerClientError('request_failed');
599
+ }
600
+ return atDeadline;
601
+ }));
602
+ }
603
+
604
+ private receivePopup(
605
+ windowArg: IRelyingPartyBearerClientWindow,
606
+ popupArg: IRelyingPartyBearerPopup,
607
+ loginArg: IRelyingPartyBearerClientLogin,
608
+ optionsArg: IRelyingPartyBearerPopupOptions,
609
+ ): Promise<IRelyingPartyBearerLoginResult> {
610
+ return new Promise<IRelyingPartyBearerLoginResult>((resolve, reject) => {
611
+ const cleanups: Array<() => void> = [];
612
+ let settled = false;
613
+ const settle = (actionArg: () => void) => {
614
+ if (settled) {
615
+ return;
616
+ }
617
+ settled = true;
618
+ for (const cleanup of cleanups) {
619
+ cleanup();
620
+ }
621
+ actionArg();
622
+ };
623
+ const fail = (errorArg: unknown) => settle(() => reject(errorArg));
624
+
625
+ const onMessage = (eventArg: IRelyingPartyBearerMessageEvent) => {
626
+ const data: unknown = eventArg?.data;
627
+ if (
628
+ eventArg?.origin !== this.origin
629
+ || eventArg.source !== popupArg
630
+ || !isRecord(data)
631
+ || data.type !== RELYING_PARTY_BEARER_MESSAGE_TYPE
632
+ || data.state !== loginArg.state
633
+ ) {
634
+ return;
635
+ }
636
+ settle(() => {
637
+ this.receive(loginArg, data.code, data.error).then(resolve, reject);
638
+ });
639
+ };
640
+ windowArg.addEventListener('message', onMessage);
641
+ cleanups.push(() => windowArg.removeEventListener('message', onMessage));
642
+
643
+ const timeout = setTimeout(
644
+ () => fail(new RelyingPartyBearerClientError('popup_timeout')),
645
+ optionsArg.timeoutMs ?? DEFAULT_POPUP_TIMEOUT_MS,
646
+ );
647
+ cleanups.push(() => clearTimeout(timeout));
648
+ let closedGrace: ReturnType<typeof setTimeout> | undefined;
649
+ const closedPoll = setInterval(() => {
650
+ if (popupArg.closed && closedGrace === undefined) {
651
+ closedGrace = setTimeout(() => fail(new RelyingPartyBearerClientError('popup_closed')), POPUP_CLOSED_GRACE_MS);
652
+ }
653
+ }, POPUP_CLOSED_POLL_MS);
654
+ cleanups.push(() => {
655
+ clearInterval(closedPoll);
656
+ if (closedGrace !== undefined) {
657
+ clearTimeout(closedGrace);
658
+ }
659
+ });
660
+
661
+ const signal = optionsArg.signal;
662
+ if (signal) {
663
+ if (signal.aborted) {
664
+ fail(signal.reason);
665
+ return;
666
+ }
667
+ const onAbort = () => fail(signal.reason);
668
+ signal.addEventListener('abort', onAbort, { once: true });
669
+ cleanups.push(() => signal.removeEventListener('abort', onAbort));
670
+ }
671
+ });
672
+ }
673
+
674
+ /**
675
+ * One rotation under the lock. The pair is read again inside it: one
676
+ * whose refresh token is no longer `seenRefreshTokenArg`, or whose access
677
+ * token is no longer `rejectedAccessTokenArg`, was rotated already and is
678
+ * used as it is. A rotated pair is stored before the lock is released. The
679
+ * whole section has one deadline: past it, the lock is released with
680
+ * `request_failed` and an answer that still arrives is dropped unstored.
681
+ */
682
+ private rotate(
683
+ seenRefreshTokenArg: string,
684
+ rejectedAccessTokenArg: string | null,
685
+ ): Promise<IRelyingPartyBearerStoredTokens | null> {
686
+ return this.#locks.request(this.#lockName, () => this.withDeadline(async (signalArg) => {
687
+ const current = await this.#storage.get();
688
+ if (!current) {
689
+ return null;
690
+ }
691
+ if (
692
+ current.refreshToken !== seenRefreshTokenArg
693
+ || (rejectedAccessTokenArg !== null && current.accessToken !== rejectedAccessTokenArg)
694
+ ) {
695
+ return current;
696
+ }
697
+ let answer: IRelyingPartyBearerTokenAnswer | null;
698
+ try {
699
+ answer = tokenAnswerOf(await this.post(this.#paths.refresh, { refreshToken: current.refreshToken }, {}, signalArg));
700
+ } catch (error) {
701
+ if (error instanceof RelyingPartyBearerClientError && error.answerError === 'invalid_bearer_grant') {
702
+ // the session is over: this pair opens nothing any more
703
+ inTime(signalArg);
704
+ await this.#storage.clear({ signal: signalArg });
705
+ return null;
706
+ }
707
+ throw error;
708
+ }
709
+ if (!answer) {
710
+ throw new RelyingPartyBearerClientError('unexpected_answer', { status: 200 });
711
+ }
712
+ const stored: IRelyingPartyBearerStoredTokens = { ...answer, receivedAt: this.#now() };
713
+ inTime(signalArg);
714
+ await this.#storage.set(stored, { signal: signalArg });
715
+ return stored;
716
+ }));
717
+ }
718
+
719
+ /** Ends the session of a pair through the logout route and answers whether that ended a live one. */
720
+ private async endSessionOf(pairArg: IRelyingPartyBearerStoredTokens, signalArg: AbortSignal): Promise<boolean> {
721
+ const answer = await this.post(
722
+ this.#paths.logout,
723
+ { refreshToken: pairArg.refreshToken },
724
+ { authorization: `Bearer ${pairArg.accessToken}` },
725
+ signalArg,
726
+ );
727
+ if (!isRecord(answer) || typeof answer.endedLiveSession !== 'boolean') {
728
+ throw new RelyingPartyBearerClientError('unexpected_answer', { status: 200 });
729
+ }
730
+ return (answer as unknown as IRelyingPartyBearerLogoutAnswer).endedLiveSession;
731
+ }
732
+
733
+ /**
734
+ * Runs one operation, a claim or a section that holds the lock, under
735
+ * `requestTimeoutMs`. When the deadline fires, the section's signal aborts
736
+ * its request and its storage write and keeps it from writing anything
737
+ * more (`inTime`), and the call answers `onDeadlineArg()` at once, so the
738
+ * lock is released whatever the request or the storage still does.
739
+ */
740
+ private async withDeadline<T>(
741
+ sectionArg: (signalArg: AbortSignal) => Promise<T>,
742
+ onDeadlineArg: () => T = () => {
743
+ throw new RelyingPartyBearerClientError('request_failed');
744
+ },
745
+ ): Promise<T> {
746
+ const controller = new AbortController();
747
+ let timer: ReturnType<typeof setTimeout> | undefined;
748
+ const deadline = new Promise<T>((resolve, reject) => {
749
+ timer = setTimeout(() => {
750
+ controller.abort(new RelyingPartyBearerClientError('request_failed'));
751
+ try {
752
+ resolve(onDeadlineArg());
753
+ } catch (error) {
754
+ reject(error);
755
+ }
756
+ }, this.#requestTimeoutMs);
757
+ });
758
+ const section = sectionArg(controller.signal);
759
+ // past the deadline the section's own end, its aborted request among them, has nobody left to answer
760
+ section.catch(() => undefined);
761
+ try {
762
+ return await Promise.race([section, deadline]);
763
+ } finally {
764
+ clearTimeout(timer);
765
+ }
766
+ }
767
+
768
+ /**
769
+ * A bearer API call: JSON in, JSON out, no cookie, no cache, no redirect.
770
+ * With `signalArg` none is sent past the deadline and an answer that
771
+ * arrives after it counts as none.
772
+ */
773
+ private async post(
774
+ urlArg: string,
775
+ bodyArg: Record<string, string>,
776
+ headersArg: Record<string, string> = {},
777
+ signalArg?: AbortSignal,
778
+ ): Promise<unknown> {
779
+ if (signalArg) {
780
+ inTime(signalArg);
781
+ }
782
+ let response: Response;
783
+ try {
784
+ response = await this.#fetch(urlArg, {
785
+ method: 'POST',
786
+ headers: { 'content-type': 'application/json', ...headersArg },
787
+ body: JSON.stringify(bodyArg),
788
+ credentials: 'omit',
789
+ cache: 'no-store',
790
+ redirect: 'error',
791
+ referrerPolicy: 'no-referrer',
792
+ ...(signalArg ? { signal: signalArg } : {}),
793
+ });
794
+ } catch (error) {
795
+ throw new RelyingPartyBearerClientError('request_failed', { cause: error });
796
+ }
797
+ let answer: unknown;
798
+ try {
799
+ answer = await response.json();
800
+ } catch {
801
+ // the parse error is not kept: its message quotes the body
802
+ answer = undefined;
803
+ if (signalArg) {
804
+ inTime(signalArg);
805
+ }
806
+ if (response.status === 200) {
807
+ throw new RelyingPartyBearerClientError('unexpected_answer', { status: 200 });
808
+ }
809
+ }
810
+ if (signalArg) {
811
+ inTime(signalArg);
812
+ }
813
+ if (response.status !== 200) {
814
+ throw new RelyingPartyBearerClientError('request_refused', {
815
+ status: response.status,
816
+ ...(isRecord(answer) && isText(answer.error) ? { answerError: answer.error } : {}),
817
+ });
818
+ }
819
+ return answer;
820
+ }
821
+ }