@authfn/client 0.4.1 → 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,257 @@
1
+ import type { AuthFnClientOptions, AuthFnRegionalClient, AuthFnSocialHandoffClient } from './types.js';
2
+ /**
3
+ * Single-use browser handoff for social sign-in (AUTH-38).
4
+ *
5
+ * `begin()` keeps a random verifier in `store`, binds the flow to a random
6
+ * handoff id carried in the `returnTo` fragment, and returns the
7
+ * `/social/start` input. When the callback lands, `complete()` checks the
8
+ * origin and the flow, claims the stored record by replacing it with a
9
+ * tombstone that no longer holds the verifier, and only then exchanges the
10
+ * one-time code with the verifier through the existing
11
+ * `/social/handoff/exchange` route. The claim must be atomic across every
12
+ * window that shares the store: the server consumes each code once, but a
13
+ * retried `/social/start` can mint a second code for the same handoff, so
14
+ * only the claim keeps a begun handoff to one completion. A store that
15
+ * cannot claim atomically (`atomic: false`) is refused. In a browser the
16
+ * store is `createIndexedDbHandoffStore()`: its compare-and-set runs in one
17
+ * IndexedDB readwrite transaction, which the browser serializes across every
18
+ * window, tab and process of the origin.
19
+ *
20
+ * Navigation (sending the browser to `redirectTo`, removing the callback
21
+ * parameters from the address bar with `cleanUrl`) stays with the host.
22
+ */
23
+ type Awaitable<T> = T | Promise<T>;
24
+ /** Key-value storage the handoff keeps its single-use records in. */
25
+ export interface AuthFnBrowserHandoffStore {
26
+ get(key: string): Awaitable<string | null | undefined>;
27
+ set(key: string, value: string): Awaitable<void>;
28
+ delete(key: string): Awaitable<void>;
29
+ /** Keys currently stored, used by `prune()` to retire expired records. */
30
+ keys(): Awaitable<Iterable<string>>;
31
+ /**
32
+ * Replaces the value of `key` with `next` (or removes it when `next` is
33
+ * `null`) only if it still equals `expected`, and reports whether it did.
34
+ * It must be atomic across every participant that shares the store
35
+ * (every window, tab and renderer process of the origin).
36
+ */
37
+ compareAndSet(key: string, expected: string, next: string | null): Awaitable<boolean>;
38
+ /**
39
+ * `true` only when `compareAndSet` is atomic across participants. Any
40
+ * other value, including a missing one, makes the handoff refuse to begin
41
+ * or complete.
42
+ */
43
+ readonly atomic: boolean;
44
+ /**
45
+ * `true` when the store holds records for one origin only, as the bundled
46
+ * IndexedDB and memory stores do. `begin()` then refuses a `returnTo` on
47
+ * another origin than the page's, whose return could never find the
48
+ * record.
49
+ */
50
+ readonly originScoped?: boolean;
51
+ }
52
+ /** The part of `IDBFactory` (`globalThis.indexedDB`) the store uses. */
53
+ export interface AuthFnIndexedDbFactoryLike {
54
+ open(name: string, version?: number): unknown;
55
+ }
56
+ export interface AuthFnBrowserHandoffClock {
57
+ /** Milliseconds since the epoch. */
58
+ now(): number;
59
+ }
60
+ export type AuthFnBrowserHandoffExchange = (input: {
61
+ code: string;
62
+ verifier: string;
63
+ },
64
+ /**
65
+ * `regionId` is the region passed to `begin()`, read back from the store,
66
+ * never from the callback URL.
67
+ */
68
+ context: {
69
+ handoffId: string;
70
+ regionId?: string;
71
+ }) => ReturnType<AuthFnSocialHandoffClient['exchangeSocialHandoff']>;
72
+ export type AuthFnBrowserHandoffEvent = {
73
+ type: 'begun';
74
+ handoffId: string;
75
+ expiresAt: string;
76
+ } | {
77
+ type: 'completed';
78
+ handoffId: string;
79
+ } | {
80
+ type: 'two-factor-required';
81
+ handoffId: string;
82
+ } | {
83
+ type: 'failed';
84
+ handoffId?: string;
85
+ reason: AuthFnBrowserHandoffFailureReason;
86
+ } | {
87
+ type: 'pruned';
88
+ count: number;
89
+ };
90
+ export interface AuthFnBrowserHandoffOptions {
91
+ store: AuthFnBrowserHandoffStore;
92
+ /** Absolute http(s) origins on which a handoff may begin and complete. */
93
+ allowedOrigins: readonly string[];
94
+ /**
95
+ * Usually `client.exchangeSocialHandoff`; with the region-aware client,
96
+ * `createRegionalHandoffExchange({ regionalClient, resolveBaseUrl })`.
97
+ */
98
+ exchange: AuthFnBrowserHandoffExchange;
99
+ clock?: AuthFnBrowserHandoffClock;
100
+ /** How long a begun handoff may wait for its callback. Default 10 minutes, at most 1 hour. */
101
+ ttlMs?: number;
102
+ /** Store key prefix. Default `authfn.handoff.`. */
103
+ keyPrefix?: string;
104
+ /** Observability hook. Events never carry the verifier or the code. */
105
+ onEvent?(event: AuthFnBrowserHandoffEvent): void;
106
+ }
107
+ export interface AuthFnBrowserHandoffBeginInput {
108
+ /** Absolute http(s) URL on an allowed origin, without a fragment. */
109
+ returnTo: string;
110
+ /**
111
+ * The region the sign-in starts in (`regionalClient.getCurrentRegionId()`).
112
+ * It is stored with the handoff and given to `exchange`, so the exchange
113
+ * after a reload reaches the region that issued the code.
114
+ */
115
+ regionId?: string;
116
+ }
117
+ export interface AuthFnBrowserHandoffBeginResult {
118
+ handoffId: string;
119
+ expiresAt: string;
120
+ /** Spread into `client.startSocialSignIn({ provider, ...start })`. */
121
+ start: {
122
+ returnTo: string;
123
+ callbackMode: 'redirect';
124
+ handoffMode: 'session-token';
125
+ handoffChallenge: string;
126
+ };
127
+ }
128
+ export type AuthFnBrowserHandoffFailureReason =
129
+ /**
130
+ * The callback is not an http(s) URL on an allowed origin without
131
+ * credentials, or not on the origin the handoff began on.
132
+ */
133
+ 'origin-mismatch'
134
+ /** The callback is not the code-and-verifier return of the handoff it names. */
135
+ | 'flow-mismatch'
136
+ /** No handoff with this id is stored (never begun here, abandoned, or long expired). */
137
+ | 'unknown-handoff' | 'expired'
138
+ /** The handoff was already claimed: a duplicate return, a reload, or another window. */
139
+ | 'already-used'
140
+ /** The stored record could not be read; it is removed. */
141
+ | 'malformed-state' | 'malformed-callback'
142
+ /** The callback reports that sign-in failed before a code was issued. */
143
+ | 'provider-error'
144
+ /** The server refused the code. Start the sign-in again. */
145
+ | 'exchange-rejected'
146
+ /** The exchange did not complete (network failure or abort). Start the sign-in again. */
147
+ | 'exchange-canceled'
148
+ /** The store cannot claim atomically across windows (`atomic: false`); nothing was exchanged. */
149
+ | 'store-not-atomic';
150
+ export type AuthFnBrowserHandoffResult = {
151
+ status: 'completed';
152
+ handoffId: string;
153
+ session: SocialHandoffData['session'];
154
+ handoff: SocialHandoffData['handoff'];
155
+ requestId: string;
156
+ /** The callback URL without the handoff parameters, for `history.replaceState`. */
157
+ cleanUrl: string;
158
+ } | {
159
+ /**
160
+ * The server needs a second factor before it issues a session. The
161
+ * handoff is retired; continue with
162
+ * `client.completeTwoFactorChallenge({ challengeId, code })` in the
163
+ * region that issued the challenge (`regionId`).
164
+ */
165
+ status: 'two-factor-required';
166
+ handoffId: string;
167
+ challengeId: string;
168
+ primaryMethod: string;
169
+ /**
170
+ * The region passed to `begin()`, read back from the store, never from
171
+ * the callback URL. The challenge exists only there.
172
+ */
173
+ regionId?: string;
174
+ cleanUrl: string;
175
+ } | {
176
+ status: 'failed';
177
+ reason: AuthFnBrowserHandoffFailureReason;
178
+ handoffId?: string;
179
+ /** A fixed message; it never repeats free-form text from the exchange. */
180
+ error?: {
181
+ code: string;
182
+ message: string;
183
+ };
184
+ requestId?: string;
185
+ /** Present whenever the callback is an http(s) URL; it never carries credentials. */
186
+ cleanUrl?: string;
187
+ }
188
+ /** The URL carries no handoff callback; there is nothing to do. */
189
+ | {
190
+ status: 'not-callback';
191
+ };
192
+ export interface AuthFnBrowserHandoff {
193
+ /** A store failure throws `AuthFnBrowserHandoffStorageError`, never the store's own error. */
194
+ begin(input: AuthFnBrowserHandoffBeginInput): Promise<AuthFnBrowserHandoffBeginResult>;
195
+ /** Completes the handoff named by a callback URL (usually `location.href`). Never throws for callback or store content. */
196
+ complete(callbackUrl: string | URL): Promise<AuthFnBrowserHandoffResult>;
197
+ /**
198
+ * Retires a pending handoff, for example when the user closes the sign-in.
199
+ * Throws `AuthFnBrowserHandoffStorageError` only if the store could neither
200
+ * retire nor delete it.
201
+ */
202
+ abandon(handoffId: string): Promise<void>;
203
+ /**
204
+ * Retires expired or malformed records and removes expired tombstones.
205
+ * `begin()` also does this. Returns how many it confirmed retired or
206
+ * removed; a record the store fails on is left and not counted.
207
+ */
208
+ prune(): Promise<number>;
209
+ }
210
+ type SocialHandoffData = Extract<Awaited<ReturnType<AuthFnSocialHandoffClient['exchangeSocialHandoff']>>, {
211
+ ok: true;
212
+ }>['data'];
213
+ export declare function createBrowserHandoff(options: AuthFnBrowserHandoffOptions): AuthFnBrowserHandoff;
214
+ /** A store over `Map`, atomic within one JavaScript realm. */
215
+ export declare function createMemoryHandoffStore(): AuthFnBrowserHandoffStore;
216
+ export interface AuthFnRegionalHandoffExchangeOptions {
217
+ /** The region-aware client of the page; it is moved to the handoff's region once a session is issued. */
218
+ regionalClient: Pick<AuthFnRegionalClient, 'setCurrentRegionId'> & AuthFnSocialHandoffClient;
219
+ /** The same trusted region-to-URL mapping the regional client was created with. */
220
+ resolveBaseUrl(regionId: string): string;
221
+ /** The same client options the regional client was created with. */
222
+ clientOptions?: Omit<AuthFnClientOptions, 'baseUrl'>;
223
+ }
224
+ /**
225
+ * The exchange for the region-aware client. It sends the code to the region
226
+ * passed to `begin()` through a client of that region alone, so it never
227
+ * changes which region other calls use while it runs, even when the page
228
+ * after the redirect starts in the default region. Only once the session is
229
+ * issued does it move `regionalClient` to that region, where the session
230
+ * lives. Without a stored region it uses `regionalClient` as it is.
231
+ */
232
+ export declare function createRegionalHandoffExchange(options: AuthFnRegionalHandoffExchangeOptions): AuthFnBrowserHandoffExchange;
233
+ export interface AuthFnIndexedDbHandoffStoreOptions {
234
+ /** Defaults to `globalThis.indexedDB`. Without one the store is `atomic: false`. */
235
+ indexedDB?: AuthFnIndexedDbFactoryLike | null;
236
+ /** Database name. Default `authfn-handoff`. */
237
+ databaseName?: string;
238
+ }
239
+ /**
240
+ * The browser store: records live in an IndexedDB database of the origin,
241
+ * which every window, tab and popup of the origin shares, and
242
+ * `compareAndSet` reads and writes in one readwrite transaction. The browser
243
+ * runs readwrite transactions over the same object store one at a time
244
+ * across all connections, so a claim is atomic across renderer processes
245
+ * (unlike Web Storage, whose `sessionStorage` is copied into popups and whose
246
+ * `localStorage` reaches other processes asynchronously).
247
+ */
248
+ export declare function createIndexedDbHandoffStore(options?: AuthFnIndexedDbHandoffStoreOptions): AuthFnBrowserHandoffStore;
249
+ /**
250
+ * The only error the handoff throws for a store failure. It never carries
251
+ * the store's own message or cause, which may repeat the stored record.
252
+ */
253
+ export declare class AuthFnBrowserHandoffStorageError extends Error {
254
+ constructor();
255
+ }
256
+ export {};
257
+ //# sourceMappingURL=browser-handoff.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"browser-handoff.d.ts","sourceRoot":"","sources":["../src/browser-handoff.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EACV,mBAAmB,EAEnB,oBAAoB,EACpB,yBAAyB,EAC1B,MAAM,YAAY,CAAC;AAEpB;;;;;;;;;;;;;;;;;;;;GAoBG;AAEH,KAAK,SAAS,CAAC,CAAC,IAAI,CAAC,GAAG,OAAO,CAAC,CAAC,CAAC,CAAC;AAEnC,qEAAqE;AACrE,MAAM,WAAW,yBAAyB;IACxC,GAAG,CAAC,GAAG,EAAE,MAAM,GAAG,SAAS,CAAC,MAAM,GAAG,IAAI,GAAG,SAAS,CAAC,CAAC;IACvD,GAAG,CAAC,GAAG,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,GAAG,SAAS,CAAC,IAAI,CAAC,CAAC;IACjD,MAAM,CAAC,GAAG,EAAE,MAAM,GAAG,SAAS,CAAC,IAAI,CAAC,CAAC;IACrC,0EAA0E;IAC1E,IAAI,IAAI,SAAS,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC,CAAC;IACpC;;;;;OAKG;IACH,aAAa,CAAC,GAAG,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,CAAC,OAAO,CAAC,CAAC;IACtF;;;;OAIG;IACH,QAAQ,CAAC,MAAM,EAAE,OAAO,CAAC;IACzB;;;;;OAKG;IACH,QAAQ,CAAC,YAAY,CAAC,EAAE,OAAO,CAAC;CACjC;AAED,wEAAwE;AACxE,MAAM,WAA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