@authfn/client 0.4.0 → 0.5.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.
@@ -0,0 +1,923 @@
1
+ import { createAuthFnClient } from './client.js';
2
+ import { isRegionId } from './region-id.js';
3
+ import { repeatsSecret, safeLabel, safeText } from './secret-text.js';
4
+ const HANDOFF_ID_PARAM = 'authfn_handoff';
5
+ const CODE_PARAM = 'token';
6
+ const MODE_PARAM = 'handoff';
7
+ const REGION_PARAM = 'regionId';
8
+ const FRAGMENT_PARAMS = [HANDOFF_ID_PARAM, CODE_PARAM, MODE_PARAM, REGION_PARAM];
9
+ const ERROR_QUERY_PARAMS = ['auth_error', 'auth_error_code', 'auth_provider', 'auth_request_id'];
10
+ const TWO_FACTOR_CODE_PARAM = 'authfnCode';
11
+ const TWO_FACTOR_QUERY_PARAMS = [TWO_FACTOR_CODE_PARAM, 'challengeId', 'primaryMethod'];
12
+ const READ_FAILED = Symbol('read-failed');
13
+ /** Query parameters the social callback adds to the return target. */
14
+ const SERVER_QUERY_PARAMS = [...ERROR_QUERY_PARAMS, ...TWO_FACTOR_QUERY_PARAMS];
15
+ const TWO_FACTOR_REQUIRED_CODE = 'AUTHFN_2FA_REQUIRED';
16
+ const HANDOFF_ID_PATTERN = /^[A-Za-z0-9_-]{22}$/;
17
+ const VERIFIER_PATTERN = /^[A-Za-z0-9_-]{43}$/;
18
+ const CODE_PATTERN = /^[A-Za-z0-9_-]{1,256}$/;
19
+ /** The server's canonical challenge id spelling (`CANONICAL_CHALLENGE_ID`). */
20
+ const CHALLENGE_ID_PATTERN = /^[a-z0-9_-]{1,255}$/;
21
+ /** The social sign-in methods the social callback names (`SOCIAL_PROVIDER_METHODS`). */
22
+ const SOCIAL_METHODS = new Set(['oauth-google', 'oauth-apple', 'oauth-github']);
23
+ const ERROR_CODE_PATTERN = /^[A-Z][A-Z0-9_]{0,63}$/;
24
+ const REQUEST_ID_PATTERN = /^[A-Za-z0-9_.:-]{1,128}$/;
25
+ const USED_RECORD_KEYS = new Set(['expiresAt', 'id', 'issuedAt', 'state', 'v']);
26
+ const DEFAULT_TTL_MS = 10 * 60 * 1000;
27
+ const MAX_TTL_MS = 60 * 60 * 1000;
28
+ const DEFAULT_KEY_PREFIX = 'authfn.handoff.';
29
+ const REPLAYED_CODE = 'AUTHFN_OAUTH_STATE_REPLAYED';
30
+ const NETWORK_ERROR_CODE = 'AUTHFN_NETWORK_ERROR';
31
+ const INTERNAL_ERROR_CODE = 'AUTHFN_INTERNAL_ERROR';
32
+ const NOT_ATOMIC_MESSAGE = 'createBrowserHandoff needs a store that claims atomically across windows; '
33
+ + 'this store is not atomic: true (for example createIndexedDbHandoffStore without IndexedDB)';
34
+ const NO_WEB_CRYPTO_MESSAGE = 'createBrowserHandoff needs Web Crypto (crypto.getRandomValues and crypto.subtle), '
35
+ + 'which browsers provide only in secure contexts (https, or http on localhost)';
36
+ const EXCHANGE_FAILURE_MESSAGES = {
37
+ 'already-used': 'This social sign-in was already completed',
38
+ 'exchange-canceled': 'The social sign-in exchange did not complete',
39
+ 'exchange-rejected': 'The server refused the social sign-in code'
40
+ };
41
+ export function createBrowserHandoff(options) {
42
+ const store = options.store;
43
+ if (!store || typeof store.compareAndSet !== 'function' || typeof store.get !== 'function') {
44
+ throw new TypeError('createBrowserHandoff needs a store with get, set, delete, keys and compareAndSet');
45
+ }
46
+ if (typeof options.exchange !== 'function') {
47
+ throw new TypeError('createBrowserHandoff needs an exchange function, such as client.exchangeSocialHandoff');
48
+ }
49
+ const guarded = guardStore(store);
50
+ const allowedOrigins = normalizeAllowedOrigins(options.allowedOrigins);
51
+ const ttlMs = options.ttlMs ?? DEFAULT_TTL_MS;
52
+ if (!Number.isInteger(ttlMs) || ttlMs <= 0 || ttlMs > MAX_TTL_MS) {
53
+ throw new TypeError(`createBrowserHandoff ttlMs must be a whole number of milliseconds from 1 to ${MAX_TTL_MS}`);
54
+ }
55
+ const keyPrefix = options.keyPrefix ?? DEFAULT_KEY_PREFIX;
56
+ if (typeof keyPrefix !== 'string' || keyPrefix.length === 0) {
57
+ throw new TypeError('createBrowserHandoff keyPrefix must be a non-empty string');
58
+ }
59
+ const now = () => options.clock?.now() ?? Date.now();
60
+ const keyFor = (handoffId) => `${keyPrefix}${handoffId}`;
61
+ const emit = (event) => {
62
+ try {
63
+ options.onEvent?.(event);
64
+ }
65
+ catch {
66
+ // Observability must not change the outcome.
67
+ }
68
+ };
69
+ const fail = (reason, extra = {}) => {
70
+ emit({ type: 'failed', handoffId: extra.handoffId, reason });
71
+ return { status: 'failed', reason, ...extra };
72
+ };
73
+ /**
74
+ * Retires the record under `key`, which was last seen holding `observed`
75
+ * (anything but a string when it could not be read or is not a string),
76
+ * by replacing it with a used tombstone that holds no verifier. A
77
+ * committed tombstone is final: retirement never writes over it, and only
78
+ * `prune()` removes it once it has expired. The ladder, in the order of
79
+ * what matters most (at most one exchange, then no verifier left behind,
80
+ * then a later return still reading `already-used`):
81
+ * 1. compare-and-set `observed` -> tombstone; `changed` when another
82
+ * participant moved the record first;
83
+ * 2. if that throws (or nothing could be compared), read the record again:
84
+ * a tombstone is left byte for byte (`changed`), nothing stored is
85
+ * `absent`, and any other string is compared-and-set to a tombstone;
86
+ * 3. only if the re-read fails, is not a string, or its compare-and-set
87
+ * throws, a plain write of the tombstone;
88
+ * 4. if that throws too, delete: the verifier is gone, and a later return
89
+ * reads `unknown-handoff` instead of `already-used`.
90
+ * With `expectedOrigin` (only `complete()` passes it), a pending record
91
+ * bound to another origin, as observed or as read again, is `foreign`:
92
+ * nothing is written, so that origin's own return still works.
93
+ */
94
+ const retire = async (key, observed, expiresAt, expectedOrigin) => {
95
+ const handoffId = key.slice(keyPrefix.length);
96
+ const swap = async (expected, expiry) => await guarded.compareAndSet(key, expected, tombstoneFor(handoffId, expiry, now())) ? 'tombstoned' : 'changed';
97
+ const foreign = (record) => expectedOrigin !== undefined && record?.state === 'pending' && record.origin !== expectedOrigin;
98
+ if (typeof observed === 'string' && foreign(parseRecord(observed, handoffId))) {
99
+ return 'foreign';
100
+ }
101
+ if (typeof observed === 'string') {
102
+ try {
103
+ return await swap(observed, expiresAt);
104
+ }
105
+ catch {
106
+ // The re-read below.
107
+ }
108
+ }
109
+ const current = await read(key);
110
+ if (current === null || current === undefined) {
111
+ return 'absent';
112
+ }
113
+ if (typeof current === 'string') {
114
+ const record = parseRecord(current, handoffId);
115
+ if (record?.state === 'used') {
116
+ return 'changed';
117
+ }
118
+ if (foreign(record)) {
119
+ return 'foreign';
120
+ }
121
+ try {
122
+ return await swap(current, record ? tombstoneExpiry(record) : expiresAt);
123
+ }
124
+ catch {
125
+ // The plain write below.
126
+ }
127
+ }
128
+ try {
129
+ await guarded.set(key, tombstoneFor(handoffId, expiresAt, now()));
130
+ return 'tombstoned';
131
+ }
132
+ catch {
133
+ // The delete below.
134
+ }
135
+ try {
136
+ await guarded.delete(key);
137
+ return 'deleted';
138
+ }
139
+ catch {
140
+ return 'failed';
141
+ }
142
+ };
143
+ /** When a retired record's tombstone expires: its own deadline, never earlier than now. */
144
+ const tombstoneExpiry = (record) => record ? Math.max(record.expiresAt, now()) : now() + ttlMs;
145
+ /** The stored value, or `READ_FAILED` when the store could not read it. */
146
+ const read = async (key) => {
147
+ try {
148
+ return await guarded.get(key);
149
+ }
150
+ catch {
151
+ return READ_FAILED;
152
+ }
153
+ };
154
+ /** The failure for a retire() outcome in complete(): another participant's tombstone, another origin's record, or `otherwise`. */
155
+ const retiredReason = (outcome, otherwise) => outcome === 'changed' ? 'already-used' : outcome === 'foreign' ? 'origin-mismatch' : otherwise;
156
+ const prune = async () => {
157
+ let removed = 0;
158
+ for (const key of await guarded.keys()) {
159
+ // Only this instance's records: a key whose suffix is not a handoff id
160
+ // belongs to another instance (a nested prefix) or to the host.
161
+ if (typeof key !== 'string' || !key.startsWith(keyPrefix) || !HANDOFF_ID_PATTERN.test(key.slice(keyPrefix.length))) {
162
+ continue;
163
+ }
164
+ const raw = await read(key);
165
+ if (raw === READ_FAILED || raw === null || raw === undefined) {
166
+ // An unreadable record is left for complete(), which retires it.
167
+ continue;
168
+ }
169
+ // The clock is read after the record, so a record another window
170
+ // began while this prune was enumerating is judged by a time no
171
+ // earlier than its own begin.
172
+ const current = now();
173
+ const record = typeof raw === 'string' ? parseRecord(raw, key.slice(keyPrefix.length)) : null;
174
+ if (record?.state === 'used') {
175
+ // An expired tombstone holds no secret: it is removed only if it is
176
+ // still the same tombstone, and left when the store fails.
177
+ if (record.expiresAt <= current) {
178
+ try {
179
+ if (await guarded.compareAndSet(key, raw, null)) {
180
+ removed += 1;
181
+ }
182
+ }
183
+ catch {
184
+ // Left for a later prune.
185
+ }
186
+ }
187
+ continue;
188
+ }
189
+ // Expired or malformed pending state and values this helper never
190
+ // writes (it stores strings) may hold a verifier: retire them.
191
+ if (!record || record.expiresAt <= current) {
192
+ const outcome = await retire(key, raw, tombstoneExpiry(record));
193
+ if (outcome === 'tombstoned' || outcome === 'deleted') {
194
+ removed += 1;
195
+ }
196
+ }
197
+ }
198
+ if (removed > 0) {
199
+ emit({ type: 'pruned', count: removed });
200
+ }
201
+ return removed;
202
+ };
203
+ return {
204
+ async begin(input) {
205
+ const target = parseBeginTarget(input?.returnTo, allowedOrigins);
206
+ const regionId = input?.regionId;
207
+ if (regionId !== undefined && !isRegionId(regionId)) {
208
+ throw new TypeError('begin regionId must be a region id: 1 to 255 characters, '
209
+ + 'no control characters and no leading or trailing whitespace');
210
+ }
211
+ if (store.atomic !== true) {
212
+ throw new Error(NOT_ATOMIC_MESSAGE);
213
+ }
214
+ const pageOrigin = globalThis.location?.origin;
215
+ if (store.originScoped === true && typeof pageOrigin === 'string' && target.origin !== pageOrigin) {
216
+ throw new TypeError('begin returnTo must be on the page\'s own origin: this store keeps records for one origin');
217
+ }
218
+ // Checked before anything is stored: on a page that is not a secure
219
+ // context `crypto.subtle` is missing.
220
+ const webCrypto = globalThis.crypto;
221
+ if (typeof webCrypto?.getRandomValues !== 'function' || typeof webCrypto.subtle?.digest !== 'function') {
222
+ throw new Error(NO_WEB_CRYPTO_MESSAGE);
223
+ }
224
+ await prune();
225
+ const handoffId = randomBase64Url(16);
226
+ const verifier = randomBase64Url(32);
227
+ const handoffChallenge = await sha256Base64Url(verifier);
228
+ const issuedAt = now();
229
+ const expiresAt = issuedAt + ttlMs;
230
+ const record = {
231
+ v: 1,
232
+ id: handoffId,
233
+ state: 'pending',
234
+ origin: target.origin,
235
+ // Serialized as the callback's query is compared, so a target whose
236
+ // query the server re-encodes (auth_error, authfnCode) still matches.
237
+ path: target.pathname + stripServerParams(target.search),
238
+ verifier,
239
+ issuedAt,
240
+ expiresAt,
241
+ ...(regionId ? { regionId } : {})
242
+ };
243
+ const key = keyFor(handoffId);
244
+ const serialized = JSON.stringify(record);
245
+ try {
246
+ await guarded.set(key, serialized);
247
+ }
248
+ catch (error) {
249
+ // The write may have committed before the store failed: retire it.
250
+ await retire(key, serialized, expiresAt);
251
+ throw error;
252
+ }
253
+ const returnTo = new URL(target.href);
254
+ returnTo.hash = new URLSearchParams({ [HANDOFF_ID_PARAM]: handoffId }).toString();
255
+ const expiresAtIso = new Date(expiresAt).toISOString();
256
+ emit({ type: 'begun', handoffId, expiresAt: expiresAtIso });
257
+ return {
258
+ handoffId,
259
+ expiresAt: expiresAtIso,
260
+ start: {
261
+ returnTo: returnTo.href,
262
+ callbackMode: 'redirect',
263
+ handoffMode: 'session-token',
264
+ handoffChallenge
265
+ }
266
+ };
267
+ },
268
+ async complete(callbackUrl) {
269
+ let url;
270
+ try {
271
+ url = new URL(String(callbackUrl));
272
+ }
273
+ catch {
274
+ return fail('malformed-callback');
275
+ }
276
+ const fragment = new URLSearchParams(url.hash.startsWith('#') ? url.hash.slice(1) : url.hash);
277
+ const handoffIdValues = fragment.getAll(HANDOFF_ID_PARAM);
278
+ const looksLikeHandoff = fragment.has(CODE_PARAM)
279
+ || fragment.has(MODE_PARAM)
280
+ || url.searchParams.has('auth_error')
281
+ || url.searchParams.has(TWO_FACTOR_CODE_PARAM);
282
+ if (handoffIdValues.length === 0 && !looksLikeHandoff) {
283
+ return { status: 'not-callback' };
284
+ }
285
+ // Only an http(s) URL like the one begin() bound: a blob: URL shares
286
+ // the origin but is not that return target, and its cleanUrl could
287
+ // carry credentials in its path, so it gets none.
288
+ if (url.protocol !== 'https:' && url.protocol !== 'http:') {
289
+ return fail('origin-mismatch');
290
+ }
291
+ const cleanUrl = stripCallbackParams(url);
292
+ if (url.username || url.password || !allowedOrigins.has(url.origin)) {
293
+ return fail('origin-mismatch', { cleanUrl });
294
+ }
295
+ // Only a page on the callback's origin may read, burn or exchange it.
296
+ const pageOrigin = globalThis.location?.origin;
297
+ if (typeof pageOrigin === 'string' && pageOrigin !== url.origin) {
298
+ return fail('origin-mismatch', { cleanUrl });
299
+ }
300
+ if (handoffIdValues.length === 0) {
301
+ // A callback that no handoff of this helper is bound to.
302
+ return fail('flow-mismatch', { cleanUrl });
303
+ }
304
+ const handoffId = handoffIdValues[0];
305
+ if (handoffIdValues.length !== 1 || !HANDOFF_ID_PATTERN.test(handoffId)) {
306
+ return fail('malformed-callback', { cleanUrl });
307
+ }
308
+ const key = keyFor(handoffId);
309
+ const raw = await read(key);
310
+ if (raw === null || raw === undefined) {
311
+ return fail(store.atomic === true ? 'unknown-handoff' : 'store-not-atomic', { handoffId, cleanUrl });
312
+ }
313
+ const record = typeof raw === 'string' ? parseRecord(raw, handoffId) : null;
314
+ // A return on another origin than the handoff's changes nothing, live
315
+ // or expired, so the return on the right origin still works. retire()
316
+ // applies the same rule to what it reads again.
317
+ if (record?.state === 'pending' && record.origin !== url.origin) {
318
+ return fail('origin-mismatch', { handoffId, cleanUrl });
319
+ }
320
+ if (store.atomic !== true) {
321
+ // Without an atomic claim two windows could both exchange; retire
322
+ // the verifier instead.
323
+ const outcome = record?.state === 'used' ? 'changed' : await retire(key, raw, tombstoneExpiry(record), url.origin);
324
+ return fail(outcome === 'foreign' ? 'origin-mismatch' : 'store-not-atomic', { handoffId, cleanUrl });
325
+ }
326
+ if (!record) {
327
+ // Unreadable, not a string, or not a record this helper wrote: it
328
+ // cannot be trusted to be claimed later, so it is retired.
329
+ const outcome = await retire(key, raw, tombstoneExpiry(null), url.origin);
330
+ return fail(retiredReason(outcome, 'malformed-state'), { handoffId, cleanUrl });
331
+ }
332
+ if (record.state === 'used') {
333
+ return fail('already-used', { handoffId, cleanUrl });
334
+ }
335
+ if (record.expiresAt <= now()) {
336
+ const outcome = await retire(key, raw, tombstoneExpiry(record), url.origin);
337
+ return fail(retiredReason(outcome, 'expired'), { handoffId, cleanUrl });
338
+ }
339
+ // From here on the callback names a live handoff, so any outcome
340
+ // retires it: a misdirected or corrupted return must not leave the
341
+ // verifier for a second attempt.
342
+ let claimed;
343
+ try {
344
+ claimed = await guarded.compareAndSet(key, raw, tombstoneFor(handoffId, record.expiresAt, now()));
345
+ }
346
+ catch {
347
+ // Whether the claim committed is unknown, so this window never
348
+ // exchanges. It reads the record again: another participant's
349
+ // tombstone is left as it is; anything else is retired (and retire()
350
+ // reads once more before any plain write).
351
+ const current = await read(key);
352
+ if (typeof current === 'string' && parseRecord(current, handoffId)?.state === 'used') {
353
+ return fail('already-used', { handoffId, cleanUrl });
354
+ }
355
+ const outcome = current === null || current === undefined
356
+ ? 'absent'
357
+ : await retire(key, current, record.expiresAt, url.origin);
358
+ return fail(retiredReason(outcome, 'malformed-state'), { handoffId, cleanUrl });
359
+ }
360
+ if (!claimed) {
361
+ return fail('already-used', { handoffId, cleanUrl });
362
+ }
363
+ // The claim can wait on another window's lock: the deadline is checked
364
+ // again before anything is exchanged. The tombstone stays.
365
+ if (record.expiresAt <= now()) {
366
+ return fail('expired', { handoffId, cleanUrl });
367
+ }
368
+ if (url.pathname + stripServerParams(url.search) !== record.path) {
369
+ return fail('flow-mismatch', { handoffId, cleanUrl });
370
+ }
371
+ const twoFactor = readTwoFactorChallenge(url, fragment);
372
+ if (twoFactor === 'malformed') {
373
+ return fail('malformed-callback', { handoffId, cleanUrl });
374
+ }
375
+ if (twoFactor) {
376
+ emit({ type: 'two-factor-required', handoffId });
377
+ return {
378
+ status: 'two-factor-required',
379
+ handoffId,
380
+ ...twoFactor,
381
+ ...(record.regionId ? { regionId: record.regionId } : {}),
382
+ cleanUrl
383
+ };
384
+ }
385
+ if (url.searchParams.has('auth_error')) {
386
+ if (fragment.has(CODE_PARAM)) {
387
+ return fail('malformed-callback', { handoffId, cleanUrl });
388
+ }
389
+ // The callback query is not trusted: an error code or request id that
390
+ // repeats the verifier is dropped like any other text that does.
391
+ const requestId = safeText(url.searchParams.get('auth_request_id'), REQUEST_ID_PATTERN, [record.verifier]);
392
+ const code = safeText(url.searchParams.get('auth_error_code'), ERROR_CODE_PATTERN, [record.verifier]);
393
+ return fail('provider-error', {
394
+ handoffId,
395
+ cleanUrl,
396
+ error: {
397
+ code: code ?? 'AUTHFN_OAUTH_CALLBACK_FAILED',
398
+ message: 'Social sign-in did not complete'
399
+ },
400
+ ...(requestId ? { requestId } : {})
401
+ });
402
+ }
403
+ const codes = fragment.getAll(CODE_PARAM);
404
+ const modes = fragment.getAll(MODE_PARAM);
405
+ if (modes.length !== 1 || modes[0] !== 'code') {
406
+ return fail(modes.length === 0 && codes.length === 0 ? 'malformed-callback' : 'flow-mismatch', {
407
+ handoffId,
408
+ cleanUrl
409
+ });
410
+ }
411
+ const code = codes[0];
412
+ if (codes.length !== 1 || !code || !CODE_PATTERN.test(code)) {
413
+ return fail('malformed-callback', { handoffId, cleanUrl });
414
+ }
415
+ // Text from the exchange is passed on only in a fixed shape that cannot
416
+ // carry the verifier or the code back out.
417
+ const verifier = record.verifier;
418
+ const secrets = [code, verifier];
419
+ let envelope;
420
+ try {
421
+ envelope = await options.exchange({ code, verifier }, { handoffId, ...(record.regionId ? { regionId: record.regionId } : {}) });
422
+ }
423
+ catch {
424
+ return fail('exchange-canceled', {
425
+ handoffId,
426
+ cleanUrl,
427
+ error: { code: NETWORK_ERROR_CODE, message: EXCHANGE_FAILURE_MESSAGES['exchange-canceled'] }
428
+ });
429
+ }
430
+ if (!envelope || typeof envelope !== 'object') {
431
+ return fail('exchange-rejected', { handoffId, cleanUrl });
432
+ }
433
+ const requestId = safeText(envelope.requestId, REQUEST_ID_PATTERN, secrets);
434
+ if (envelope.ok !== true) {
435
+ const errorCode = safeLabel(envelope.error?.code, ERROR_CODE_PATTERN, secrets)
436
+ ?? INTERNAL_ERROR_CODE;
437
+ const reason = errorCode === REPLAYED_CODE
438
+ ? 'already-used'
439
+ : errorCode === NETWORK_ERROR_CODE
440
+ ? 'exchange-canceled'
441
+ : 'exchange-rejected';
442
+ return fail(reason, {
443
+ handoffId,
444
+ cleanUrl,
445
+ error: { code: errorCode, message: EXCHANGE_FAILURE_MESSAGES[reason] },
446
+ ...(requestId ? { requestId } : {})
447
+ });
448
+ }
449
+ const data = acceptedHandoffSession(envelope, secrets);
450
+ if (!data) {
451
+ return fail('exchange-rejected', { handoffId, cleanUrl });
452
+ }
453
+ emit({ type: 'completed', handoffId });
454
+ return {
455
+ status: 'completed',
456
+ handoffId,
457
+ session: data.session,
458
+ handoff: data.handoff,
459
+ requestId: requestId ?? 'authfn-browser-handoff',
460
+ cleanUrl
461
+ };
462
+ },
463
+ async abandon(handoffId) {
464
+ if (typeof handoffId !== 'string' || !HANDOFF_ID_PATTERN.test(handoffId)) {
465
+ return;
466
+ }
467
+ const key = keyFor(handoffId);
468
+ const raw = await read(key);
469
+ if (raw === null || raw === undefined) {
470
+ return;
471
+ }
472
+ const record = typeof raw === 'string' ? parseRecord(raw, handoffId) : null;
473
+ if (record?.state !== 'used' && await retire(key, raw, tombstoneExpiry(record)) === 'failed') {
474
+ throw new AuthFnBrowserHandoffStorageError();
475
+ }
476
+ },
477
+ prune
478
+ };
479
+ }
480
+ /** A store over `Map`, atomic within one JavaScript realm. */
481
+ export function createMemoryHandoffStore() {
482
+ const values = new Map();
483
+ return {
484
+ get: (key) => values.get(key) ?? null,
485
+ set: (key, value) => {
486
+ values.set(key, value);
487
+ },
488
+ delete: (key) => {
489
+ values.delete(key);
490
+ },
491
+ keys: () => Array.from(values.keys()),
492
+ compareAndSet: (key, expected, next) => compareAndSetSync(values, key, expected, next),
493
+ atomic: true,
494
+ originScoped: true
495
+ };
496
+ }
497
+ /**
498
+ * The exchange for the region-aware client. It sends the code to the region
499
+ * passed to `begin()` through a client of that region alone, so it never
500
+ * changes which region other calls use while it runs, even when the page
501
+ * after the redirect starts in the default region. Only once the session is
502
+ * issued does it move `regionalClient` to that region, where the session
503
+ * lives. Without a stored region it uses `regionalClient` as it is.
504
+ */
505
+ export function createRegionalHandoffExchange(options) {
506
+ const { regionalClient, resolveBaseUrl, clientOptions } = options ?? {};
507
+ if (!regionalClient || typeof resolveBaseUrl !== 'function') {
508
+ throw new TypeError('createRegionalHandoffExchange needs regionalClient and resolveBaseUrl');
509
+ }
510
+ const clients = new Map();
511
+ const clientFor = (regionId) => {
512
+ let client = clients.get(regionId);
513
+ if (!client) {
514
+ client = createAuthFnClient({ ...(clientOptions ?? {}), baseUrl: resolveBaseUrl(regionId) });
515
+ clients.set(regionId, client);
516
+ }
517
+ return client;
518
+ };
519
+ return async (input, context) => {
520
+ if (!context.regionId) {
521
+ return regionalClient.exchangeSocialHandoff(input);
522
+ }
523
+ const response = await clientFor(context.regionId).exchangeSocialHandoff(input);
524
+ // Moves the page only for a response complete() accepts as a session.
525
+ if (acceptedHandoffSession(response, [input.code, input.verifier])) {
526
+ regionalClient.setCurrentRegionId(context.regionId);
527
+ }
528
+ return response;
529
+ };
530
+ }
531
+ const IDB_OBJECT_STORE = 'records';
532
+ /**
533
+ * The browser store: records live in an IndexedDB database of the origin,
534
+ * which every window, tab and popup of the origin shares, and
535
+ * `compareAndSet` reads and writes in one readwrite transaction. The browser
536
+ * runs readwrite transactions over the same object store one at a time
537
+ * across all connections, so a claim is atomic across renderer processes
538
+ * (unlike Web Storage, whose `sessionStorage` is copied into popups and whose
539
+ * `localStorage` reaches other processes asynchronously).
540
+ */
541
+ export function createIndexedDbHandoffStore(options = {}) {
542
+ const factory = (options.indexedDB === undefined
543
+ ? globalThis.indexedDB ?? null
544
+ : options.indexedDB);
545
+ const databaseName = options.databaseName ?? 'authfn-handoff';
546
+ if (typeof databaseName !== 'string' || databaseName.length === 0) {
547
+ throw new TypeError('createIndexedDbHandoffStore databaseName must be a non-empty string');
548
+ }
549
+ let opening = null;
550
+ const database = () => {
551
+ if (!factory) {
552
+ return Promise.reject(new Error('IndexedDB is not available'));
553
+ }
554
+ opening ??= new Promise((resolve, reject) => {
555
+ const request = factory.open(databaseName, 1);
556
+ request.onupgradeneeded = () => {
557
+ if (!request.result.objectStoreNames.contains(IDB_OBJECT_STORE)) {
558
+ request.result.createObjectStore(IDB_OBJECT_STORE);
559
+ }
560
+ };
561
+ request.onsuccess = () => {
562
+ const db = request.result;
563
+ const forget = () => {
564
+ opening = null;
565
+ };
566
+ db.onversionchange = () => {
567
+ db.close();
568
+ forget();
569
+ };
570
+ db.onclose = forget;
571
+ resolve(db);
572
+ };
573
+ request.onerror = () => reject(request.error ?? new Error('IndexedDB open failed'));
574
+ request.onblocked = () => reject(new Error('IndexedDB open is blocked'));
575
+ }).catch((error) => {
576
+ opening = null;
577
+ throw error;
578
+ });
579
+ return opening;
580
+ };
581
+ /**
582
+ * Runs `body` in one transaction and settles once the transaction has
583
+ * committed, with the value `body` decided, or rejects if it aborts.
584
+ */
585
+ const run = async (mode, body) => {
586
+ const db = await database();
587
+ return new Promise((resolve, reject) => {
588
+ const transaction = db.transaction(IDB_OBJECT_STORE, mode);
589
+ let decided;
590
+ transaction.oncomplete = () => resolve(decided);
591
+ transaction.onerror = () => reject(transaction.error ?? new Error('IndexedDB transaction failed'));
592
+ transaction.onabort = () => reject(transaction.error ?? new Error('IndexedDB transaction aborted'));
593
+ body(transaction.objectStore(IDB_OBJECT_STORE), (value) => {
594
+ decided = value;
595
+ });
596
+ });
597
+ };
598
+ return {
599
+ // A value that is not a string is passed on as it is, so the handoff
600
+ // removes it as malformed state.
601
+ get: (key) => run('readonly', (records, decide) => {
602
+ const request = records.get(key);
603
+ request.onsuccess = () => decide((request.result ?? null));
604
+ }),
605
+ set: (key, value) => run('readwrite', (records) => {
606
+ records.put(value, key);
607
+ }),
608
+ delete: (key) => run('readwrite', (records) => {
609
+ records.delete(key);
610
+ }),
611
+ keys: () => run('readonly', (records, decide) => {
612
+ const request = records.getAllKeys();
613
+ request.onsuccess = () => decide(request.result.filter((key) => typeof key === 'string'));
614
+ }),
615
+ compareAndSet: (key, expected, next) => run('readwrite', (records, decide) => {
616
+ decide(false);
617
+ const request = records.get(key);
618
+ request.onsuccess = () => {
619
+ if (request.result !== expected) {
620
+ return;
621
+ }
622
+ if (next === null) {
623
+ records.delete(key);
624
+ }
625
+ else {
626
+ records.put(next, key);
627
+ }
628
+ decide(true);
629
+ };
630
+ }),
631
+ atomic: factory !== null,
632
+ originScoped: true
633
+ };
634
+ }
635
+ function compareAndSetSync(map, key, expected, next) {
636
+ if (map.get(key) !== expected) {
637
+ return false;
638
+ }
639
+ if (next === null) {
640
+ map.delete(key);
641
+ }
642
+ else {
643
+ map.set(key, next);
644
+ }
645
+ return true;
646
+ }
647
+ /**
648
+ * The session and handoff of an exchange response that issued a session in
649
+ * the shape the server sends, or `undefined`. The handoff is a session-token
650
+ * handoff for this session (`sessionId` is `session.id`) with a non-blank
651
+ * token; the session is a user session whose subject is its actor. No string
652
+ * in the envelope but its request id (checked on its own) may repeat the code
653
+ * or the verifier. `complete()` and the regional
654
+ * exchange both accept only this.
655
+ */
656
+ function acceptedHandoffSession(envelope, secrets) {
657
+ if (!isRecord(envelope) || envelope.ok !== true || !isRecord(envelope.data)) {
658
+ return undefined;
659
+ }
660
+ const { session, handoff } = envelope.data;
661
+ if (!isRecord(session)
662
+ || !isRecord(handoff)
663
+ || !isNonBlank(session.id)
664
+ || session.type !== 'session'
665
+ || !isNonBlank(session.actorId)
666
+ // The social exchange issues only user sessions.
667
+ || session.actorType !== 'user'
668
+ || !isRecord(session.subject)
669
+ || session.subject.actorId !== session.actorId
670
+ || session.subject.actorType !== 'user'
671
+ || !isStringArray(session.resourceIds)
672
+ || !isStringArray(session.methods)
673
+ // Servers that predate scopes omit them.
674
+ || (session.scopes !== undefined && !isStringArray(session.scopes))
675
+ || handoff.type !== 'session-token'
676
+ // The bearer resolver trims the token, so whitespace alone is no token.
677
+ || !isNonBlank(handoff.token)
678
+ || handoff.sessionId !== session.id
679
+ || (handoff.regionId !== null && typeof handoff.regionId !== 'string')
680
+ || (handoff.expiresAt !== null && typeof handoff.expiresAt !== 'string')
681
+ || repeatsSecret(withoutRequestId(envelope), secrets)) {
682
+ return undefined;
683
+ }
684
+ return { session, handoff };
685
+ }
686
+ /** The envelope without its request id, which callers check on its own. */
687
+ function withoutRequestId(envelope) {
688
+ const { requestId: _requestId, ...rest } = envelope;
689
+ return rest;
690
+ }
691
+ function isRecord(value) {
692
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
693
+ }
694
+ /** Whether `record`'s own keys are exactly `keys`, compared as a set (no locale-dependent sort). */
695
+ function hasExactlyKeys(record, keys) {
696
+ const own = Object.keys(record);
697
+ return own.length === keys.size && own.every((key) => keys.has(key));
698
+ }
699
+ function isStringArray(value) {
700
+ return Array.isArray(value) && value.every((entry) => typeof entry === 'string');
701
+ }
702
+ function isNonBlank(value) {
703
+ return typeof value === 'string' && value.trim().length > 0;
704
+ }
705
+ /**
706
+ * The only error the handoff throws for a store failure. It never carries
707
+ * the store's own message or cause, which may repeat the stored record.
708
+ */
709
+ export class AuthFnBrowserHandoffStorageError extends Error {
710
+ constructor() {
711
+ super('The browser handoff store failed');
712
+ this.name = 'AuthFnBrowserHandoffStorageError';
713
+ }
714
+ }
715
+ /**
716
+ * Wraps every store call so that a rejection or synchronous throw becomes
717
+ * the fixed `AuthFnBrowserHandoffStorageError`.
718
+ */
719
+ function guardStore(store) {
720
+ const guard = async (action) => {
721
+ try {
722
+ return await action();
723
+ }
724
+ catch {
725
+ throw new AuthFnBrowserHandoffStorageError();
726
+ }
727
+ };
728
+ return {
729
+ get: (key) => guard(() => store.get(key)),
730
+ set: (key, value) => guard(() => store.set(key, value)),
731
+ delete: (key) => guard(() => store.delete(key)),
732
+ keys: () => guard(async () => Array.from(await store.keys())),
733
+ compareAndSet: (key, expected, next) => guard(() => store.compareAndSet(key, expected, next))
734
+ };
735
+ }
736
+ /** A used record issued at `now`, or no earlier than `MAX_TTL_MS` before `expiresAt` after the clock stepped back. */
737
+ function tombstoneFor(handoffId, expiresAt, now) {
738
+ const issuedAt = Math.max(Math.min(now, expiresAt), expiresAt - MAX_TTL_MS);
739
+ return JSON.stringify({ v: 1, id: handoffId, state: 'used', issuedAt, expiresAt });
740
+ }
741
+ function normalizeAllowedOrigins(input) {
742
+ if (!Array.isArray(input) || input.length === 0) {
743
+ throw new TypeError('createBrowserHandoff needs at least one allowed origin');
744
+ }
745
+ const origins = new Set();
746
+ for (const entry of input) {
747
+ let url;
748
+ try {
749
+ url = typeof entry === 'string' ? new URL(entry) : undefined;
750
+ }
751
+ catch {
752
+ url = undefined;
753
+ }
754
+ if (!url
755
+ || (url.protocol !== 'https:' && url.protocol !== 'http:')
756
+ || url.username
757
+ || url.password
758
+ || (url.pathname !== '/' && url.pathname !== '')
759
+ || url.search
760
+ || url.hash
761
+ || (entry !== url.origin && entry !== `${url.origin}/`)) {
762
+ throw new TypeError(`createBrowserHandoff allowedOrigins entries must be http(s) origins: ${String(entry)}`);
763
+ }
764
+ origins.add(url.origin);
765
+ }
766
+ return origins;
767
+ }
768
+ function parseBeginTarget(returnTo, allowedOrigins) {
769
+ let target;
770
+ try {
771
+ target = new URL(String(returnTo));
772
+ }
773
+ catch {
774
+ throw new TypeError('begin returnTo must be an absolute URL');
775
+ }
776
+ if (target.protocol !== 'https:' && target.protocol !== 'http:') {
777
+ throw new TypeError('begin returnTo must be an http(s) URL');
778
+ }
779
+ if (typeof returnTo !== 'string' || !allowedOrigins.has(target.origin)) {
780
+ throw new TypeError('begin returnTo must be on an allowed origin');
781
+ }
782
+ if (target.username || target.password) {
783
+ throw new TypeError('begin returnTo must not carry credentials');
784
+ }
785
+ if (target.hash || returnTo.includes('#')) {
786
+ throw new TypeError('begin returnTo must not have a fragment; the handoff uses it');
787
+ }
788
+ if (SERVER_QUERY_PARAMS.some((name) => target.searchParams.has(name))) {
789
+ throw new TypeError(`begin returnTo must not carry the callback parameters ${SERVER_QUERY_PARAMS.join(', ')}`);
790
+ }
791
+ return target;
792
+ }
793
+ /** Whether `value` is a canonical http(s) origin, as `begin()` stores it. */
794
+ function isPageOrigin(value) {
795
+ if (typeof value !== 'string') {
796
+ return false;
797
+ }
798
+ try {
799
+ const url = new URL(value);
800
+ return (url.protocol === 'https:' || url.protocol === 'http:') && url.origin === value;
801
+ }
802
+ catch {
803
+ return false;
804
+ }
805
+ }
806
+ function parseRecord(raw, handoffId) {
807
+ let value;
808
+ try {
809
+ value = JSON.parse(raw);
810
+ }
811
+ catch {
812
+ return null;
813
+ }
814
+ if (!value || typeof value !== 'object' || Array.isArray(value)) {
815
+ return null;
816
+ }
817
+ const record = value;
818
+ if (record.v !== 1
819
+ || record.id !== handoffId
820
+ || typeof record.expiresAt !== 'number'
821
+ || !Number.isFinite(record.expiresAt)
822
+ || typeof record.issuedAt !== 'number'
823
+ || !Number.isFinite(record.issuedAt)
824
+ // Judged from the record's own issue time, never the reading clock.
825
+ || record.expiresAt - record.issuedAt < 0
826
+ || record.expiresAt - record.issuedAt > MAX_TTL_MS) {
827
+ return null;
828
+ }
829
+ if (record.state === 'used') {
830
+ // A tombstone holds nothing else; one that still carries the verifier
831
+ // (or anything more) is not one this helper wrote.
832
+ return hasExactlyKeys(record, USED_RECORD_KEYS)
833
+ ? { v: 1, id: handoffId, state: 'used', issuedAt: record.issuedAt, expiresAt: record.expiresAt }
834
+ : null;
835
+ }
836
+ if (record.state !== 'pending'
837
+ // begin() needs ttlMs >= 1, so a pending record it wrote has a lifetime.
838
+ || record.expiresAt - record.issuedAt < 1
839
+ || !isPageOrigin(record.origin)
840
+ || typeof record.path !== 'string'
841
+ || !record.path.startsWith('/')
842
+ || typeof record.verifier !== 'string'
843
+ || !VERIFIER_PATTERN.test(record.verifier)
844
+ || (record.regionId !== undefined && !isRegionId(record.regionId))) {
845
+ return null;
846
+ }
847
+ return {
848
+ v: 1,
849
+ id: handoffId,
850
+ state: 'pending',
851
+ origin: record.origin,
852
+ path: record.path,
853
+ verifier: record.verifier,
854
+ issuedAt: record.issuedAt,
855
+ expiresAt: record.expiresAt,
856
+ ...(typeof record.regionId === 'string' ? { regionId: record.regionId } : {})
857
+ };
858
+ }
859
+ /**
860
+ * Reads the social callback's two-factor return
861
+ * (`?authfnCode=AUTHFN_2FA_REQUIRED&challengeId=…&primaryMethod=…`, no code).
862
+ */
863
+ function readTwoFactorChallenge(url, fragment) {
864
+ const present = TWO_FACTOR_QUERY_PARAMS.some((name) => url.searchParams.has(name));
865
+ if (!present) {
866
+ return null;
867
+ }
868
+ const single = (name, pattern) => {
869
+ const values = url.searchParams.getAll(name);
870
+ return values.length === 1 && pattern.test(values[0]) ? values[0] : undefined;
871
+ };
872
+ const authfnCode = single(TWO_FACTOR_CODE_PARAM, ERROR_CODE_PATTERN);
873
+ const challengeId = single('challengeId', CHALLENGE_ID_PATTERN);
874
+ const methods = url.searchParams.getAll('primaryMethod');
875
+ const primaryMethod = methods.length === 1 && SOCIAL_METHODS.has(methods[0]) ? methods[0] : undefined;
876
+ if (authfnCode !== TWO_FACTOR_REQUIRED_CODE
877
+ || !challengeId
878
+ || !primaryMethod
879
+ || fragment.has(CODE_PARAM)
880
+ || fragment.has(MODE_PARAM)
881
+ || url.searchParams.has('auth_error')) {
882
+ return 'malformed';
883
+ }
884
+ return { challengeId, primaryMethod };
885
+ }
886
+ function stripServerParams(search) {
887
+ const params = new URLSearchParams(search);
888
+ for (const name of SERVER_QUERY_PARAMS) {
889
+ params.delete(name);
890
+ }
891
+ const value = params.toString();
892
+ return value ? `?${value}` : '';
893
+ }
894
+ function stripCallbackParams(url) {
895
+ const clean = new URL(url.href);
896
+ clean.username = '';
897
+ clean.password = '';
898
+ clean.search = stripServerParams(url.search);
899
+ const fragment = new URLSearchParams(url.hash.startsWith('#') ? url.hash.slice(1) : url.hash);
900
+ for (const name of FRAGMENT_PARAMS) {
901
+ fragment.delete(name);
902
+ }
903
+ const hash = fragment.toString();
904
+ clean.hash = hash;
905
+ return clean.href;
906
+ }
907
+ function randomBase64Url(byteLength) {
908
+ const bytes = new Uint8Array(byteLength);
909
+ globalThis.crypto.getRandomValues(bytes);
910
+ return toBase64Url(bytes);
911
+ }
912
+ async function sha256Base64Url(value) {
913
+ const digest = await globalThis.crypto.subtle.digest('SHA-256', new TextEncoder().encode(value));
914
+ return toBase64Url(new Uint8Array(digest));
915
+ }
916
+ function toBase64Url(bytes) {
917
+ let binary = '';
918
+ for (const byte of bytes) {
919
+ binary += String.fromCharCode(byte);
920
+ }
921
+ return btoa(binary).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
922
+ }
923
+ //# sourceMappingURL=browser-handoff.js.map