@absolutejs/auth 0.68.2 → 0.69.1

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.
@@ -37,10 +37,36 @@ export type AuthClientRoutes = {
37
37
  export type AuthClientConfig = {
38
38
  baseUrl?: string;
39
39
  credentials?: RequestCredentials;
40
- fetch?: typeof fetch;
40
+ fetch?: AuthClientFetch;
41
41
  routes?: AuthClientRoutes;
42
+ transport?: AuthClientTransport;
42
43
  };
43
- export declare const createAuthClient: ({ baseUrl, credentials, fetch: fetchImpl, routes }?: AuthClientConfig) => {
44
+ export type AuthClientFetch = (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>;
45
+ export type AuthClientTransport = {
46
+ fetch?: AuthClientFetch;
47
+ signInEmail?: (body: {
48
+ email: string;
49
+ password: string;
50
+ }) => Promise<{
51
+ passwordCompromised?: boolean;
52
+ status: 'authenticated' | 'mfa_required';
53
+ }>;
54
+ signOut?: () => Promise<null>;
55
+ signUpEmail?: (body: {
56
+ email: string;
57
+ password: string;
58
+ [extra: string]: unknown;
59
+ }) => Promise<{
60
+ status: 'authenticated';
61
+ } | {
62
+ status: 'verification_required';
63
+ }>;
64
+ status?: () => Promise<{
65
+ impersonator?: unknown;
66
+ user: unknown | null;
67
+ }>;
68
+ };
69
+ export declare const createAuthClient: ({ baseUrl, credentials, fetch: fetchImpl, routes, transport }?: AuthClientConfig) => {
44
70
  emailVerification: {
45
71
  request: (body: {
46
72
  email: string;
@@ -1,4 +1,5 @@
1
1
  export * from './createAuthClient';
2
2
  export * from './sessionExpiry';
3
+ export * from './mobile';
3
4
  export * from '../redirect';
4
5
  export { runConditionalAuthentication, runPasskeyRegistration } from './passkeyHelpers';
@@ -46,6 +46,523 @@ var __export = (target, all) => {
46
46
  var __esm = (fn, res) => () => (fn && (res = fn(fn = 0)), res);
47
47
  var __require = import.meta.require;
48
48
 
49
+ // src/client/mobile.ts
50
+ class MobileAuthError extends Error {
51
+ code;
52
+ cause;
53
+ constructor(code, message, options) {
54
+ super(message);
55
+ this.name = "MobileAuthError";
56
+ this.code = code;
57
+ this.cause = options?.cause;
58
+ }
59
+ }
60
+ var PENDING_KEY = "oidc.pending";
61
+ var REFRESH_KEY = "oidc.refresh";
62
+ var DEFAULT_CLOCK_SKEW_MS = 30000;
63
+ var PENDING_TTL_MS = 10 * 60000;
64
+ var RANDOM_BYTES = 32;
65
+ var isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
66
+ var base64Url = (value) => {
67
+ let binary = "";
68
+ for (const byte of value)
69
+ binary += String.fromCharCode(byte);
70
+ return btoa(binary).replaceAll("+", "-").replaceAll("/", "_").replace(/=+$/u, "");
71
+ };
72
+ var decodeBase64Url = (value) => {
73
+ const normalized = value.replaceAll("-", "+").replaceAll("_", "/");
74
+ const padded = normalized.padEnd(normalized.length + (4 - normalized.length % 4) % 4, "=");
75
+ const binary = atob(padded);
76
+ return Uint8Array.from(binary, (character) => character.charCodeAt(0));
77
+ };
78
+ var randomValue = () => {
79
+ const value = new Uint8Array(RANDOM_BYTES);
80
+ crypto.getRandomValues(value);
81
+ return base64Url(value);
82
+ };
83
+ var pkceChallenge = async (verifier) => base64Url(new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(verifier))));
84
+ var normalizeIssuer = (value) => {
85
+ const issuer = new URL(value);
86
+ const loopback = issuer.protocol === "http:" && ["127.0.0.1", "[::1]", "localhost"].includes(issuer.hostname);
87
+ if (issuer.protocol !== "https:" && !loopback)
88
+ throw new TypeError("Mobile auth issuer must use HTTPS.");
89
+ if (issuer.username || issuer.password || issuer.search || issuer.hash)
90
+ throw new TypeError("Mobile auth issuer cannot contain credentials, query, or fragment.");
91
+ issuer.pathname = issuer.pathname.replace(/\/$/u, "");
92
+ return issuer.href.replace(/\/$/u, "");
93
+ };
94
+ var exactRedirect = (actualValue, expectedValue) => {
95
+ const actual = new URL(actualValue);
96
+ const expected = new URL(expectedValue);
97
+ return actual.protocol === expected.protocol && actual.host === expected.host && actual.pathname === expected.pathname && actual.username === "" && actual.password === "";
98
+ };
99
+ var parsePending = (value) => {
100
+ if (value === null)
101
+ return;
102
+ try {
103
+ const parsed = JSON.parse(value);
104
+ if (!isRecord(parsed) || typeof parsed.createdAt !== "number" || typeof parsed.nonce !== "string" || typeof parsed.state !== "string" || typeof parsed.verifier !== "string")
105
+ return;
106
+ return {
107
+ createdAt: parsed.createdAt,
108
+ nonce: parsed.nonce,
109
+ state: parsed.state,
110
+ verifier: parsed.verifier
111
+ };
112
+ } catch {
113
+ return;
114
+ }
115
+ };
116
+ var parseTokenResponse = (value) => {
117
+ if (!isRecord(value) || typeof value.access_token !== "string" || typeof value.expires_in !== "number" || !Number.isFinite(value.expires_in) || value.expires_in <= 0 || typeof value.id_token !== "string" || typeof value.refresh_token !== "string" || typeof value.token_type !== "string")
118
+ throw new MobileAuthError("token", "The token response is malformed.");
119
+ if (value.token_type.toLowerCase() !== "bearer")
120
+ throw new MobileAuthError("token", `Unsupported mobile token type ${value.token_type}; DPoP is not enabled for this client.`);
121
+ return {
122
+ access_token: value.access_token,
123
+ expires_in: value.expires_in,
124
+ id_token: value.id_token,
125
+ refresh_token: value.refresh_token,
126
+ scope: typeof value.scope === "string" ? value.scope : undefined,
127
+ token_type: value.token_type
128
+ };
129
+ };
130
+ var responseBody = async (response) => {
131
+ const text = await response.text();
132
+ try {
133
+ return JSON.parse(text);
134
+ } catch {
135
+ return text;
136
+ }
137
+ };
138
+ var requireEndpoint = (value, name, issuer) => {
139
+ if (typeof value !== "string")
140
+ throw new MobileAuthError("discovery", `OIDC discovery is missing ${name}.`);
141
+ const endpoint = new URL(value);
142
+ if (endpoint.protocol !== "https:" && new URL(issuer).protocol === "https:")
143
+ throw new MobileAuthError("discovery", `OIDC discovery ${name} must use HTTPS.`);
144
+ return endpoint.href;
145
+ };
146
+ var parseDiscovery = (value, issuer) => {
147
+ if (!isRecord(value) || value.issuer !== issuer)
148
+ throw new MobileAuthError("discovery", "OIDC discovery issuer does not match the configured issuer.");
149
+ const methods = Array.isArray(value.code_challenge_methods_supported) ? value.code_challenge_methods_supported.filter((method) => typeof method === "string") : undefined;
150
+ if (!methods?.includes("S256"))
151
+ throw new MobileAuthError("discovery", "OIDC provider does not advertise S256 PKCE.");
152
+ const authMethods = Array.isArray(value.token_endpoint_auth_methods_supported) ? value.token_endpoint_auth_methods_supported.filter((method) => typeof method === "string") : undefined;
153
+ if (!authMethods?.includes("none"))
154
+ throw new MobileAuthError("discovery", "OIDC provider does not accept public clients at the token endpoint.");
155
+ return {
156
+ authorization_endpoint: requireEndpoint(value.authorization_endpoint, "authorization_endpoint", issuer),
157
+ code_challenge_methods_supported: methods,
158
+ issuer,
159
+ jwks_uri: requireEndpoint(value.jwks_uri, "jwks_uri", issuer),
160
+ revocation_endpoint: typeof value.revocation_endpoint === "string" ? requireEndpoint(value.revocation_endpoint, "revocation_endpoint", issuer) : undefined,
161
+ socket_ticket_endpoint: typeof value.socket_ticket_endpoint === "string" ? requireEndpoint(value.socket_ticket_endpoint, "socket_ticket_endpoint", issuer) : undefined,
162
+ token_endpoint: requireEndpoint(value.token_endpoint, "token_endpoint", issuer),
163
+ token_endpoint_auth_methods_supported: authMethods,
164
+ userinfo_endpoint: requireEndpoint(value.userinfo_endpoint, "userinfo_endpoint", issuer)
165
+ };
166
+ };
167
+ var verifyIdToken = async ({
168
+ clientId,
169
+ fetchImpl,
170
+ idToken,
171
+ issuer,
172
+ jwksUri,
173
+ nonce,
174
+ now
175
+ }) => {
176
+ const [encodedHeader, encodedPayload, encodedSignature, ...extra] = idToken.split(".");
177
+ if (!encodedHeader || !encodedPayload || !encodedSignature || extra.length)
178
+ throw new MobileAuthError("id-token", "The ID token is malformed.");
179
+ let header;
180
+ let payload;
181
+ try {
182
+ header = JSON.parse(new TextDecoder().decode(decodeBase64Url(encodedHeader)));
183
+ payload = JSON.parse(new TextDecoder().decode(decodeBase64Url(encodedPayload)));
184
+ } catch (cause) {
185
+ throw new MobileAuthError("id-token", "The ID token is malformed.", {
186
+ cause
187
+ });
188
+ }
189
+ if (!isRecord(header) || header.alg !== "ES256" || typeof header.kid !== "string" || !isRecord(payload))
190
+ throw new MobileAuthError("id-token", "The ID token header or claims are invalid.");
191
+ const response = await fetchImpl(jwksUri, { cache: "no-store" });
192
+ if (!response.ok)
193
+ throw new MobileAuthError("network", "Unable to fetch OIDC signing keys.");
194
+ const body = await response.json();
195
+ const keys = isRecord(body) && Array.isArray(body.keys) ? body.keys : [];
196
+ const jwk = keys.find((candidate) => isRecord(candidate) && candidate.kid === header.kid);
197
+ if (!jwk)
198
+ throw new MobileAuthError("id-token", "The ID token signing key is unknown.");
199
+ const key = await crypto.subtle.importKey("jwk", jwk, { hash: "SHA-256", name: "ECDSA", namedCurve: "P-256" }, false, ["verify"]);
200
+ const valid = await crypto.subtle.verify({ hash: "SHA-256", name: "ECDSA" }, key, decodeBase64Url(encodedSignature), new TextEncoder().encode(`${encodedHeader}.${encodedPayload}`));
201
+ const audience = payload.aud;
202
+ if (!valid || payload.iss !== issuer || !(audience === clientId || Array.isArray(audience) && audience.includes(clientId)) || payload.nonce !== nonce || typeof payload.exp !== "number" || payload.exp * 1000 <= now)
203
+ throw new MobileAuthError("id-token", "The ID token signature or claims are invalid.");
204
+ };
205
+ var createMobileAuthClient = (config) => {
206
+ const issuer = normalizeIssuer(config.issuer);
207
+ const redirectUri = new URL(config.redirectUri).href;
208
+ const fetchImpl = config.fetch ?? globalThis.fetch;
209
+ const now = config.now ?? Date.now;
210
+ const clockSkewMs = config.clockSkewMs ?? DEFAULT_CLOCK_SKEW_MS;
211
+ const scopes = [...new Set(config.scopes ?? ["openid", "profile"])];
212
+ const resource = config.resource ?? issuer;
213
+ if (!scopes.includes("openid"))
214
+ scopes.unshift("openid");
215
+ const allowedOrigins = new Set((config.allowedOrigins ?? [new URL(issuer).origin]).map((value) => new URL(value).origin));
216
+ let discoveryPromise;
217
+ let access;
218
+ let refreshPromise;
219
+ let stopLinks;
220
+ let stopResume;
221
+ let startPromise;
222
+ const pendingSignIns = new Map;
223
+ const fetchDiscovery = async () => {
224
+ const url = new URL("/.well-known/openid-configuration", `${issuer}/`);
225
+ const response = await fetchImpl(url, {
226
+ cache: "no-store",
227
+ headers: { accept: "application/json" }
228
+ });
229
+ if (!response.ok)
230
+ throw new MobileAuthError("discovery", `OIDC discovery failed with HTTP ${response.status}.`);
231
+ return parseDiscovery(await response.json(), issuer);
232
+ };
233
+ const discovery = () => {
234
+ discoveryPromise ??= fetchDiscovery();
235
+ return discoveryPromise;
236
+ };
237
+ const assertSecureStorage = async () => {
238
+ const capability = await config.storage.capability?.();
239
+ if (capability && !capability.available)
240
+ throw new MobileAuthError("secure-storage", capability.message ?? "Native secure credential storage is unavailable.");
241
+ };
242
+ const tokenRequest = async (metadata, body, nonce) => {
243
+ let response;
244
+ try {
245
+ response = await fetchImpl(metadata.token_endpoint, {
246
+ body,
247
+ credentials: "omit",
248
+ headers: {
249
+ accept: "application/json",
250
+ "content-type": "application/x-www-form-urlencoded"
251
+ },
252
+ method: "POST"
253
+ });
254
+ } catch (cause) {
255
+ throw new MobileAuthError("network", "The token request failed.", {
256
+ cause
257
+ });
258
+ }
259
+ const value = await responseBody(response);
260
+ if (!response.ok) {
261
+ const oauthCode = isRecord(value) && typeof value.error === "string" ? value.error : `HTTP ${response.status}`;
262
+ throw new MobileAuthError("oauth", `The authorization server rejected the token request (${oauthCode}).`);
263
+ }
264
+ const tokens = parseTokenResponse(value);
265
+ if (nonce)
266
+ await verifyIdToken({
267
+ clientId: config.clientId,
268
+ fetchImpl,
269
+ idToken: tokens.id_token,
270
+ issuer,
271
+ jwksUri: metadata.jwks_uri,
272
+ nonce,
273
+ now: now()
274
+ });
275
+ return tokens;
276
+ };
277
+ const acceptTokens = async (tokens) => {
278
+ try {
279
+ await config.storage.set(REFRESH_KEY, tokens.refresh_token);
280
+ } catch (cause) {
281
+ access = undefined;
282
+ await config.storage.remove(REFRESH_KEY).catch(() => {
283
+ return;
284
+ });
285
+ throw new MobileAuthError("secure-storage", "The rotated refresh credential could not be saved securely.", { cause });
286
+ }
287
+ access = {
288
+ accessToken: tokens.access_token,
289
+ expiresAt: now() + tokens.expires_in * 1000,
290
+ idToken: tokens.id_token,
291
+ scope: tokens.scope?.split(" ").filter(Boolean) ?? scopes,
292
+ tokenType: "Bearer"
293
+ };
294
+ return { ...access, refreshToken: tokens.refresh_token };
295
+ };
296
+ const rotateAccessToken = async () => {
297
+ await assertSecureStorage();
298
+ const refreshToken = await config.storage.get(REFRESH_KEY);
299
+ if (!refreshToken)
300
+ throw new MobileAuthError("token", "This app has no renewable mobile session.");
301
+ const metadata = await discovery();
302
+ const body = new URLSearchParams({
303
+ client_id: config.clientId,
304
+ grant_type: "refresh_token",
305
+ refresh_token: refreshToken
306
+ });
307
+ body.set("resource", resource);
308
+ const tokens = await tokenRequest(metadata, body);
309
+ return (await acceptTokens(tokens)).accessToken;
310
+ };
311
+ const refreshAccessToken = async () => {
312
+ if (access && access.expiresAt - clockSkewMs > now())
313
+ return access.accessToken;
314
+ if (refreshPromise)
315
+ return refreshPromise;
316
+ refreshPromise = rotateAccessToken().finally(() => {
317
+ refreshPromise = undefined;
318
+ });
319
+ return refreshPromise;
320
+ };
321
+ const handleCallback = async (value) => {
322
+ if (!exactRedirect(value, redirectUri))
323
+ throw new MobileAuthError("callback", "The authorization callback does not match this app registration.");
324
+ const url = new URL(value);
325
+ const pending = parsePending(await config.storage.get(PENDING_KEY));
326
+ if (!pending || now() - pending.createdAt > PENDING_TTL_MS) {
327
+ await config.storage.remove(PENDING_KEY).catch(() => {
328
+ return;
329
+ });
330
+ throw new MobileAuthError("callback", "The authorization transaction is missing or expired.");
331
+ }
332
+ const deferred = pendingSignIns.get(pending.state);
333
+ const reject = (error) => {
334
+ pendingSignIns.delete(pending.state);
335
+ config.storage.remove(PENDING_KEY);
336
+ deferred?.reject(error);
337
+ throw error;
338
+ };
339
+ if (url.searchParams.get("state") !== pending.state)
340
+ return reject(new MobileAuthError("callback", "The authorization callback state does not match."));
341
+ if (url.searchParams.get("iss") !== issuer)
342
+ return reject(new MobileAuthError("callback", "The authorization callback issuer does not match."));
343
+ const oauthError = url.searchParams.get("error");
344
+ if (oauthError) {
345
+ await config.storage.remove(PENDING_KEY);
346
+ return reject(new MobileAuthError("oauth", `Authorization failed (${oauthError}).`));
347
+ }
348
+ const code = url.searchParams.get("code");
349
+ if (!code)
350
+ return reject(new MobileAuthError("callback", "The authorization callback contains no code."));
351
+ await config.storage.remove(PENDING_KEY);
352
+ try {
353
+ const metadata = await discovery();
354
+ const body = new URLSearchParams({
355
+ client_id: config.clientId,
356
+ code,
357
+ code_verifier: pending.verifier,
358
+ grant_type: "authorization_code",
359
+ redirect_uri: redirectUri
360
+ });
361
+ body.set("resource", resource);
362
+ const tokens = await acceptTokens(await tokenRequest(metadata, body, pending.nonce));
363
+ pendingSignIns.delete(pending.state);
364
+ deferred?.resolve(tokens);
365
+ return tokens;
366
+ } catch (error) {
367
+ return reject(error);
368
+ }
369
+ };
370
+ const initialize = async () => {
371
+ await assertSecureStorage();
372
+ stopLinks = await config.links.onOpen((url) => {
373
+ if (exactRedirect(url, redirectUri))
374
+ handleCallback(url).catch(() => {
375
+ return;
376
+ });
377
+ });
378
+ if (config.lifecycle?.onResume)
379
+ stopResume = await config.lifecycle.onResume(() => {
380
+ refreshAccessToken().catch(() => {
381
+ return;
382
+ });
383
+ });
384
+ const launchUrl = await config.links.getLaunchUrl();
385
+ if (launchUrl && exactRedirect(launchUrl, redirectUri))
386
+ await handleCallback(launchUrl);
387
+ };
388
+ const start = () => {
389
+ startPromise ??= initialize();
390
+ return startPromise;
391
+ };
392
+ const signIn = async (options = {}) => {
393
+ await start();
394
+ if (options.signal?.aborted)
395
+ throw new MobileAuthError("aborted", "Authorization was cancelled.");
396
+ const metadata = await discovery();
397
+ const pending = {
398
+ createdAt: now(),
399
+ nonce: randomValue(),
400
+ state: randomValue(),
401
+ verifier: randomValue()
402
+ };
403
+ await config.storage.set(PENDING_KEY, JSON.stringify(pending));
404
+ const url = new URL(metadata.authorization_endpoint);
405
+ url.search = new URLSearchParams({
406
+ client_id: config.clientId,
407
+ code_challenge: await pkceChallenge(pending.verifier),
408
+ code_challenge_method: "S256",
409
+ nonce: pending.nonce,
410
+ redirect_uri: redirectUri,
411
+ response_type: "code",
412
+ scope: scopes.join(" "),
413
+ state: pending.state,
414
+ ...options.authorizationParameters
415
+ }).toString();
416
+ url.searchParams.set("resource", resource);
417
+ const result = new Promise((resolve, reject) => {
418
+ pendingSignIns.set(pending.state, { reject, resolve });
419
+ options.signal?.addEventListener("abort", () => {
420
+ pendingSignIns.delete(pending.state);
421
+ config.storage.remove(PENDING_KEY);
422
+ reject(new MobileAuthError("aborted", "Authorization was cancelled."));
423
+ }, { once: true });
424
+ });
425
+ try {
426
+ await config.links.openExternal(url.href);
427
+ } catch (error) {
428
+ pendingSignIns.delete(pending.state);
429
+ await config.storage.remove(PENDING_KEY);
430
+ throw error;
431
+ }
432
+ return result;
433
+ };
434
+ const authenticatedFetch = async (input, init) => {
435
+ const original = new Request(input, init);
436
+ if (!allowedOrigins.has(new URL(original.url).origin))
437
+ throw new MobileAuthError("origin", "Mobile auth refused to send a credential to an unregistered origin.");
438
+ const send = async (forceRefresh) => {
439
+ if (forceRefresh)
440
+ access = undefined;
441
+ const token = await refreshAccessToken();
442
+ const request = original.clone();
443
+ const headers = new Headers(request.headers);
444
+ headers.set("authorization", `Bearer ${token}`);
445
+ return fetchImpl(new Request(request, { credentials: "omit", headers }));
446
+ };
447
+ const response = await send(false);
448
+ return response.status === 401 ? send(true) : response;
449
+ };
450
+ const optionalAuthenticatedFetch = async (input, init) => {
451
+ const request = new Request(input, init);
452
+ if (!allowedOrigins.has(new URL(request.url).origin))
453
+ throw new MobileAuthError("origin", "Mobile auth refused to send a request outside an allowed origin.");
454
+ const refreshToken = await config.storage.get(REFRESH_KEY);
455
+ if (access || refreshToken)
456
+ return authenticatedFetch(request);
457
+ return fetchImpl(new Request(request, { credentials: "omit" }));
458
+ };
459
+ const status = async () => {
460
+ try {
461
+ const metadata = await discovery();
462
+ const response = await authenticatedFetch(metadata.userinfo_endpoint);
463
+ if (response.status === 401)
464
+ return null;
465
+ if (!response.ok)
466
+ throw new MobileAuthError("network", `User info failed with HTTP ${response.status}.`);
467
+ const user = await response.json();
468
+ if (!isRecord(user) || typeof user.sub !== "string")
469
+ throw new MobileAuthError("token", "The user-info response is malformed.");
470
+ return { ...user, sub: user.sub };
471
+ } catch (error) {
472
+ if (error instanceof MobileAuthError && (error.code === "oauth" || error.code === "token"))
473
+ return null;
474
+ throw error;
475
+ }
476
+ };
477
+ const socketTicket = async (audience = resource) => {
478
+ const metadata = await discovery();
479
+ if (!metadata.socket_ticket_endpoint)
480
+ throw new MobileAuthError("discovery", "The authorization server does not advertise WebSocket tickets.");
481
+ const response = await authenticatedFetch(metadata.socket_ticket_endpoint, {
482
+ body: JSON.stringify({ audience }),
483
+ headers: { "content-type": "application/json" },
484
+ method: "POST"
485
+ });
486
+ const body = await responseBody(response);
487
+ if (!response.ok || !isRecord(body) || typeof body.ticket !== "string")
488
+ throw new MobileAuthError(response.ok ? "token" : "oauth", `WebSocket ticket request failed with HTTP ${response.status}.`);
489
+ return body.ticket;
490
+ };
491
+ const revokeRefreshToken = async (refreshToken) => {
492
+ const metadata = await discovery();
493
+ if (metadata.revocation_endpoint)
494
+ await fetchImpl(metadata.revocation_endpoint, {
495
+ body: new URLSearchParams({
496
+ client_id: config.clientId,
497
+ token: refreshToken,
498
+ token_type_hint: "refresh_token"
499
+ }),
500
+ credentials: "omit",
501
+ headers: {
502
+ "content-type": "application/x-www-form-urlencoded"
503
+ },
504
+ method: "POST"
505
+ });
506
+ };
507
+ const signOut = async () => {
508
+ const refreshToken = await config.storage.get(REFRESH_KEY);
509
+ try {
510
+ if (refreshToken)
511
+ await revokeRefreshToken(refreshToken);
512
+ } finally {
513
+ access = undefined;
514
+ await Promise.all([
515
+ config.storage.remove(PENDING_KEY),
516
+ config.storage.remove(REFRESH_KEY)
517
+ ]);
518
+ }
519
+ };
520
+ const stop = async () => {
521
+ await Promise.all([stopLinks?.(), stopResume?.()]);
522
+ stopLinks = undefined;
523
+ stopResume = undefined;
524
+ startPromise = undefined;
525
+ };
526
+ return {
527
+ fetch: authenticatedFetch,
528
+ fetchOptional: optionalAuthenticatedFetch,
529
+ handleCallback,
530
+ refresh: refreshAccessToken,
531
+ signIn,
532
+ signOut,
533
+ socketTicket,
534
+ start,
535
+ status,
536
+ stop
537
+ };
538
+ };
539
+ var createMobileAuthTransport = (client) => ({
540
+ fetch: client.fetch,
541
+ signInEmail: async ({ email }) => {
542
+ await client.signIn({
543
+ authorizationParameters: { login_hint: email }
544
+ });
545
+ return { status: "authenticated" };
546
+ },
547
+ signOut: async () => {
548
+ await client.signOut();
549
+ return null;
550
+ },
551
+ signUpEmail: async ({ email }) => {
552
+ await client.signIn({
553
+ authorizationParameters: {
554
+ login_hint: email,
555
+ screen_hint: "signup"
556
+ }
557
+ });
558
+ return { status: "authenticated" };
559
+ },
560
+ status: async () => {
561
+ const user = await client.status();
562
+ return { user };
563
+ }
564
+ });
565
+
49
566
  // src/client/createAuthClient.ts
50
567
  var DEFAULT_ROUTES = {
51
568
  emailVerify: "/auth/verify-email",
@@ -87,15 +604,21 @@ var createAuthClient = ({
87
604
  baseUrl = "",
88
605
  credentials = "same-origin",
89
606
  fetch: fetchImpl = fetch,
90
- routes
607
+ routes,
608
+ transport
91
609
  } = {}) => {
610
+ const resolvedFetch = transport?.fetch ?? fetchImpl;
611
+ const signInEmail = transport?.signInEmail;
612
+ const signOut = transport?.signOut;
613
+ const signUpEmail = transport?.signUpEmail;
614
+ const transportStatus = transport?.status;
92
615
  const resolvedRoutes = {
93
616
  ...DEFAULT_ROUTES,
94
617
  ...routes
95
618
  };
96
619
  const request = async (path, init) => {
97
620
  try {
98
- const response = await fetchImpl(`${baseUrl}${path}`, {
621
+ const response = await resolvedFetch(`${baseUrl}${path}`, {
99
622
  credentials,
100
623
  ...init
101
624
  });
@@ -109,6 +632,14 @@ var createAuthClient = ({
109
632
  return fail({ body: null, message, status: 0 });
110
633
  }
111
634
  };
635
+ const runTransport = async (operation) => {
636
+ try {
637
+ return succeed(await operation());
638
+ } catch (caught) {
639
+ const message = caught instanceof Error ? caught.message : "authentication";
640
+ return fail({ body: null, message, status: 0 });
641
+ }
642
+ };
112
643
  const post = (path, body, method = "POST") => request(path, {
113
644
  body: body === undefined ? undefined : JSON.stringify(body),
114
645
  headers: body === undefined ? undefined : { "content-type": "application/json" },
@@ -149,13 +680,13 @@ var createAuthClient = ({
149
680
  revoke: (sessionId) => del(`${resolvedRoutes.sessions}/${encodeURIComponent(sessionId)}`)
150
681
  },
151
682
  signIn: {
152
- email: (body) => post(resolvedRoutes.login, body)
683
+ email: (body) => signInEmail ? runTransport(() => signInEmail(body)) : post(resolvedRoutes.login, body)
153
684
  },
154
685
  signUp: {
155
- email: (body) => post(resolvedRoutes.register, body)
686
+ email: (body) => signUpEmail ? runTransport(() => signUpEmail(body)) : post(resolvedRoutes.register, body)
156
687
  },
157
- signOut: () => del(resolvedRoutes.signout),
158
- status: () => get(resolvedRoutes.status)
688
+ signOut: () => signOut ? runTransport(() => signOut()) : del(resolvedRoutes.signout),
689
+ status: () => transportStatus ? runTransport(() => transportStatus()) : get(resolvedRoutes.status)
159
690
  };
160
691
  };
161
692
  var safeJson = (text) => {
@@ -384,9 +915,12 @@ export {
384
915
  isSafeLocalPath,
385
916
  isProtectedSessionRequest,
386
917
  installSessionExpiryGuard,
918
+ createMobileAuthTransport,
919
+ createMobileAuthClient,
387
920
  createAuthClient,
388
- buildSessionExpiredSignInUrl
921
+ buildSessionExpiredSignInUrl,
922
+ MobileAuthError
389
923
  };
390
924
 
391
- //# debugId=E8018F05FE86589464756E2164756E21
925
+ //# debugId=E661DCC8D887DF4364756E2164756E21
392
926
  //# sourceMappingURL=index.js.map