@useauthio/react 0.2.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.
package/dist/index.cjs ADDED
@@ -0,0 +1,824 @@
1
+ 'use strict';
2
+
3
+ var react = require('react');
4
+ var node = require('@useauthio/node');
5
+ var jsxRuntime = require('react/jsx-runtime');
6
+
7
+ // src/provider.tsx
8
+ function wrapFetchError(err, fallbackCode = "network_error") {
9
+ if (err instanceof node.AuthioError) return err;
10
+ if (err instanceof Error && err.name === "AbortError") {
11
+ return new node.AuthioError({
12
+ code: "aborted",
13
+ message: err.message || "Request aborted",
14
+ status: 0
15
+ });
16
+ }
17
+ if (err instanceof Error && /timeout/i.test(err.message)) {
18
+ return new node.AuthioError({
19
+ code: "timeout",
20
+ message: err.message,
21
+ status: 0
22
+ });
23
+ }
24
+ const message = err instanceof Error ? err.message : "Unknown network error";
25
+ return new node.AuthioError({
26
+ code: fallbackCode,
27
+ message,
28
+ status: 0
29
+ });
30
+ }
31
+
32
+ // src/version.ts
33
+ var SDK_VERSION = "0.2.0";
34
+ var SDK_USER_AGENT = `react/${SDK_VERSION}`;
35
+
36
+ // src/fetch.ts
37
+ var DEFAULT_TIMEOUT_MS = 1e4;
38
+ async function authioFetch(opts) {
39
+ const fetchImpl = opts.fetchImpl ?? globalThis.fetch.bind(globalThis);
40
+ const url = opts.apiUrl.replace(/\/$/, "") + opts.path;
41
+ const timeoutMs = opts.timeoutMs ?? DEFAULT_TIMEOUT_MS;
42
+ const controller = new AbortController();
43
+ const timer = setTimeout(() => {
44
+ controller.abort(new DOMException("Request timed out", "AbortError"));
45
+ }, timeoutMs);
46
+ const onCallerAbort = () => {
47
+ controller.abort(opts.signal?.reason);
48
+ };
49
+ if (opts.signal) {
50
+ if (opts.signal.aborted) {
51
+ clearTimeout(timer);
52
+ throw wrapFetchError(opts.signal.reason ?? new Error("Aborted"));
53
+ }
54
+ opts.signal.addEventListener("abort", onCallerAbort);
55
+ }
56
+ let res;
57
+ try {
58
+ res = await fetchImpl(url, {
59
+ method: opts.method ?? "GET",
60
+ headers: {
61
+ Accept: "application/json",
62
+ "Content-Type": "application/json",
63
+ "X-Authio-Project": opts.projectId,
64
+ "X-Authio-SDK": SDK_USER_AGENT,
65
+ ...opts.extraHeaders ?? {}
66
+ },
67
+ body: opts.body !== void 0 ? JSON.stringify(opts.body) : void 0,
68
+ credentials: opts.credentials,
69
+ signal: controller.signal
70
+ });
71
+ } catch (err) {
72
+ throw wrapFetchError(err);
73
+ } finally {
74
+ clearTimeout(timer);
75
+ if (opts.signal) opts.signal.removeEventListener("abort", onCallerAbort);
76
+ }
77
+ if (!res.ok) {
78
+ const body = await res.json().catch(() => ({}));
79
+ throw new node.AuthioError({
80
+ code: body.code ?? body.error ?? "request_failed",
81
+ message: body.message ?? `Request to ${opts.path} failed with status ${res.status}`,
82
+ status: res.status,
83
+ requestId: body.request_id
84
+ });
85
+ }
86
+ if (res.status === 204) return void 0;
87
+ const text = await res.text();
88
+ if (!text) return void 0;
89
+ try {
90
+ return JSON.parse(text);
91
+ } catch {
92
+ throw new node.AuthioError({
93
+ code: "invalid_response",
94
+ message: `Response from ${opts.path} was not valid JSON`,
95
+ status: res.status
96
+ });
97
+ }
98
+ }
99
+ function createDefaultVerifier(apiUrl, issuer, audience) {
100
+ const verifier = new node.JwtVerifier(apiUrl, issuer, audience);
101
+ return async (token) => {
102
+ try {
103
+ const claims = await verifier.verify(token);
104
+ if (!claims.sub) return null;
105
+ return {
106
+ subject: claims.sub,
107
+ expiresAt: typeof claims.exp === "number" ? claims.exp : void 0
108
+ };
109
+ } catch {
110
+ return null;
111
+ }
112
+ };
113
+ }
114
+ function readJwtExp(token) {
115
+ const parts = token.split(".");
116
+ const body = parts[1];
117
+ if (!body) return null;
118
+ try {
119
+ const padded = body.replace(/-/g, "+").replace(/_/g, "/").padEnd(body.length + (4 - body.length % 4) % 4, "=");
120
+ const json = decodeBase64(padded);
121
+ const obj = JSON.parse(json);
122
+ return typeof obj.exp === "number" ? obj.exp : null;
123
+ } catch {
124
+ return null;
125
+ }
126
+ }
127
+ function decodeBase64(b64) {
128
+ if (typeof atob === "function") return atob(b64);
129
+ const g = globalThis;
130
+ if (g.Buffer) return g.Buffer.from(b64, "base64").toString("utf-8");
131
+ throw new Error("No base64 decoder available");
132
+ }
133
+
134
+ // src/ssr.ts
135
+ function isBrowser() {
136
+ return typeof window !== "undefined" && typeof document !== "undefined";
137
+ }
138
+ function isTabHidden() {
139
+ if (!isBrowser()) return false;
140
+ return document.visibilityState === "hidden";
141
+ }
142
+
143
+ // src/refresh.ts
144
+ var BACKOFF_DELAYS_MS = [1e3, 2e3, 4e3, 8e3, 16e3, 3e4];
145
+ var MAX_ATTEMPTS = 5;
146
+ var RefreshScheduler = class {
147
+ constructor(opts) {
148
+ this.opts = opts;
149
+ if (isBrowser()) {
150
+ this.visibilityHandler = () => {
151
+ if (this.destroyed) return;
152
+ if (!isTabHidden() && this.timer === null && this.lastExp !== null) {
153
+ this.scheduleAt(this.lastExp);
154
+ }
155
+ };
156
+ document.addEventListener("visibilitychange", this.visibilityHandler);
157
+ }
158
+ }
159
+ opts;
160
+ timer = null;
161
+ attempts = 0;
162
+ lastExp = null;
163
+ destroyed = false;
164
+ visibilityHandler = null;
165
+ scheduleAt(exp) {
166
+ if (this.destroyed) return;
167
+ this.lastExp = exp;
168
+ this.attempts = 0;
169
+ this.clear();
170
+ const now = Math.floor(Date.now() / 1e3);
171
+ const delayMs = Math.max(0, (exp - now - this.opts.leadSeconds) * 1e3);
172
+ this.opts.onScheduled?.(Date.now() + delayMs);
173
+ this.timer = setTimeout(() => void this.tick(), delayMs);
174
+ }
175
+ async tick() {
176
+ this.timer = null;
177
+ if (this.destroyed) return;
178
+ if (isTabHidden()) {
179
+ return;
180
+ }
181
+ let ok = false;
182
+ try {
183
+ ok = await this.opts.run();
184
+ } catch {
185
+ ok = false;
186
+ }
187
+ if (this.destroyed) return;
188
+ if (ok) {
189
+ return;
190
+ }
191
+ this.scheduleBackoff();
192
+ }
193
+ scheduleBackoff() {
194
+ if (this.destroyed) return;
195
+ if (this.attempts >= MAX_ATTEMPTS) {
196
+ this.opts.onGiveUp();
197
+ this.lastExp = null;
198
+ return;
199
+ }
200
+ const delay = BACKOFF_DELAYS_MS[Math.min(this.attempts, BACKOFF_DELAYS_MS.length - 1)] ?? 3e4;
201
+ this.attempts++;
202
+ this.opts.onScheduled?.(Date.now() + delay);
203
+ this.timer = setTimeout(() => void this.tick(), delay);
204
+ }
205
+ /** Cancel any pending timer but keep the scheduler alive for re-scheduling. */
206
+ clear() {
207
+ if (this.timer !== null) {
208
+ clearTimeout(this.timer);
209
+ this.timer = null;
210
+ }
211
+ }
212
+ /** Permanently stop and unhook listeners. */
213
+ destroy() {
214
+ this.destroyed = true;
215
+ this.clear();
216
+ if (this.visibilityHandler && isBrowser()) {
217
+ document.removeEventListener("visibilitychange", this.visibilityHandler);
218
+ }
219
+ this.visibilityHandler = null;
220
+ }
221
+ };
222
+
223
+ // src/storage.ts
224
+ var MemoryStorage = class {
225
+ value = null;
226
+ get() {
227
+ return this.value;
228
+ }
229
+ set(value) {
230
+ this.value = value;
231
+ }
232
+ clear() {
233
+ this.value = null;
234
+ }
235
+ };
236
+ var NoneStorage = class {
237
+ get() {
238
+ return null;
239
+ }
240
+ set() {
241
+ }
242
+ clear() {
243
+ }
244
+ };
245
+ var WebStorageBacking = class {
246
+ constructor(storage, key) {
247
+ this.storage = storage;
248
+ this.key = key;
249
+ }
250
+ storage;
251
+ key;
252
+ get() {
253
+ try {
254
+ return this.storage.getItem(this.key);
255
+ } catch {
256
+ return null;
257
+ }
258
+ }
259
+ set(value) {
260
+ try {
261
+ if (value === null) this.storage.removeItem(this.key);
262
+ else this.storage.setItem(this.key, value);
263
+ } catch {
264
+ }
265
+ }
266
+ clear() {
267
+ try {
268
+ this.storage.removeItem(this.key);
269
+ } catch {
270
+ }
271
+ }
272
+ };
273
+ var ACCESS_TOKEN_STORAGE_KEY = "authio.access_token";
274
+ function createTokenStorage(mode = "memory") {
275
+ if (mode === "none") return new NoneStorage();
276
+ if (mode === "memory") return new MemoryStorage();
277
+ if (!isBrowser()) return new MemoryStorage();
278
+ if (mode === "localStorage") {
279
+ return new WebStorageBacking(window.localStorage, ACCESS_TOKEN_STORAGE_KEY);
280
+ }
281
+ if (mode === "sessionStorage") {
282
+ return new WebStorageBacking(
283
+ window.sessionStorage,
284
+ ACCESS_TOKEN_STORAGE_KEY
285
+ );
286
+ }
287
+ return new MemoryStorage();
288
+ }
289
+
290
+ // src/telemetry.ts
291
+ var noopEmitter = () => {
292
+ };
293
+ var AuthioContext = react.createContext(null);
294
+ AuthioContext.displayName = "AuthioContext";
295
+ var DEFAULT_REFRESH_LEAD = 60;
296
+ var DEFAULT_AUDIENCE = "authio";
297
+ var DEFAULT_SIGN_IN_URL = "https://lobby.authio.com/";
298
+ function AuthioProvider(props) {
299
+ const {
300
+ apiUrl,
301
+ projectId,
302
+ storage: storageMode = "memory",
303
+ refreshLeadSeconds = DEFAULT_REFRESH_LEAD,
304
+ onTelemetryEvent,
305
+ fetch: fetchImpl,
306
+ signInUrl,
307
+ jwtIssuer,
308
+ jwtAudience = DEFAULT_AUDIENCE,
309
+ verifyToken,
310
+ skipInitialRefresh,
311
+ children
312
+ } = props;
313
+ const emit = onTelemetryEvent ?? noopEmitter;
314
+ const storageRef = react.useRef(null);
315
+ if (storageRef.current === null) {
316
+ storageRef.current = createTokenStorage(storageMode);
317
+ }
318
+ const verifierRef = react.useRef(null);
319
+ if (verifierRef.current === null) {
320
+ verifierRef.current = verifyToken ?? createDefaultVerifier(
321
+ apiUrl,
322
+ jwtIssuer ?? apiUrl.replace(/\/$/, ""),
323
+ jwtAudience
324
+ );
325
+ }
326
+ const propsRef = react.useRef({
327
+ apiUrl,
328
+ projectId,
329
+ fetchImpl,
330
+ signInUrl,
331
+ emit
332
+ });
333
+ propsRef.current = { apiUrl, projectId, fetchImpl, signInUrl, emit };
334
+ react.useEffect(() => {
335
+ if (!projectId) {
336
+ console.warn(
337
+ '[@useauthio/react] AuthioProvider projectId is missing \u2014 auth-core calls and Lobby sign-in will fail. Set projectId="proj_\u2026" on <AuthioProvider>.'
338
+ );
339
+ }
340
+ }, [projectId]);
341
+ const schedulerRef = react.useRef(null);
342
+ const [user, setUser] = react.useState(null);
343
+ const [status, setStatus] = react.useState(
344
+ skipInitialRefresh ? "unauthenticated" : "loading"
345
+ );
346
+ const [accessToken, setAccessToken] = react.useState(null);
347
+ const performRefresh = react.useCallback(async () => {
348
+ const p = propsRef.current;
349
+ try {
350
+ const env = await authioFetch({
351
+ apiUrl: p.apiUrl,
352
+ projectId: p.projectId,
353
+ path: "/v1/auth/refresh",
354
+ method: "POST",
355
+ body: {},
356
+ credentials: "include",
357
+ fetchImpl: p.fetchImpl
358
+ });
359
+ const token = env.access_token;
360
+ if (!token) {
361
+ p.emit({
362
+ kind: "refresh_failed",
363
+ timestamp: Date.now(),
364
+ reason: "missing_access_token",
365
+ attempt: 0
366
+ });
367
+ return false;
368
+ }
369
+ const verification = await verifierRef.current(token).catch(() => null);
370
+ if (!verification) {
371
+ p.emit({
372
+ kind: "token_rejected",
373
+ timestamp: Date.now(),
374
+ reason: "verification_failed"
375
+ });
376
+ p.emit({
377
+ kind: "refresh_failed",
378
+ timestamp: Date.now(),
379
+ reason: "verification_failed",
380
+ attempt: 0
381
+ });
382
+ return false;
383
+ }
384
+ p.emit({
385
+ kind: "token_verified",
386
+ timestamp: Date.now(),
387
+ subject: verification.subject
388
+ });
389
+ storageRef.current.set(token);
390
+ setAccessToken(token);
391
+ if (env.user) setUser(coerceUser(env.user));
392
+ setStatus("authenticated");
393
+ p.emit({
394
+ kind: "refresh_succeeded",
395
+ timestamp: Date.now(),
396
+ expiresAt: verification.expiresAt
397
+ });
398
+ const exp = verification.expiresAt ?? readJwtExp(token);
399
+ if (exp !== null && exp !== void 0) {
400
+ schedulerRef.current?.scheduleAt(exp);
401
+ }
402
+ return true;
403
+ } catch (err) {
404
+ const httpStatus = err instanceof node.AuthioError ? err.status : void 0;
405
+ const reason = err instanceof Error ? err.message : "refresh_failed_unknown";
406
+ p.emit({
407
+ kind: "refresh_failed",
408
+ timestamp: Date.now(),
409
+ reason,
410
+ status: httpStatus,
411
+ attempt: 0
412
+ });
413
+ return false;
414
+ }
415
+ }, []);
416
+ react.useEffect(() => {
417
+ schedulerRef.current = new RefreshScheduler({
418
+ leadSeconds: refreshLeadSeconds,
419
+ run: performRefresh,
420
+ onGiveUp: () => {
421
+ storageRef.current.clear();
422
+ setAccessToken(null);
423
+ setUser(null);
424
+ setStatus("unauthenticated");
425
+ },
426
+ onScheduled: (runAt) => propsRef.current.emit({
427
+ kind: "refresh_scheduled",
428
+ timestamp: Date.now(),
429
+ runAt
430
+ })
431
+ });
432
+ return () => {
433
+ schedulerRef.current?.destroy();
434
+ schedulerRef.current = null;
435
+ };
436
+ }, [refreshLeadSeconds, performRefresh]);
437
+ react.useEffect(() => {
438
+ if (skipInitialRefresh) {
439
+ const stored2 = storageRef.current.get();
440
+ if (!stored2) return;
441
+ let mounted2 = true;
442
+ (async () => {
443
+ const verification = await verifierRef.current(stored2).catch(
444
+ () => null
445
+ );
446
+ if (!mounted2) return;
447
+ if (!verification) {
448
+ storageRef.current.clear();
449
+ setStatus("unauthenticated");
450
+ return;
451
+ }
452
+ propsRef.current.emit({
453
+ kind: "token_verified",
454
+ timestamp: Date.now(),
455
+ subject: verification.subject
456
+ });
457
+ setAccessToken(stored2);
458
+ setStatus("authenticated");
459
+ const exp = verification.expiresAt ?? readJwtExp(stored2);
460
+ if (exp !== null && exp !== void 0) {
461
+ schedulerRef.current?.scheduleAt(exp);
462
+ }
463
+ })();
464
+ return () => {
465
+ mounted2 = false;
466
+ };
467
+ }
468
+ if (!isBrowser()) {
469
+ setStatus("unauthenticated");
470
+ return;
471
+ }
472
+ let mounted = true;
473
+ const stored = storageRef.current.get();
474
+ if (stored) {
475
+ (async () => {
476
+ const verification = await verifierRef.current(stored).catch(
477
+ () => null
478
+ );
479
+ if (!mounted) return;
480
+ if (verification) {
481
+ propsRef.current.emit({
482
+ kind: "token_verified",
483
+ timestamp: Date.now(),
484
+ subject: verification.subject
485
+ });
486
+ setAccessToken(stored);
487
+ setStatus("authenticated");
488
+ const exp = verification.expiresAt ?? readJwtExp(stored);
489
+ if (exp !== null && exp !== void 0) {
490
+ schedulerRef.current?.scheduleAt(exp);
491
+ }
492
+ return;
493
+ }
494
+ propsRef.current.emit({
495
+ kind: "token_rejected",
496
+ timestamp: Date.now(),
497
+ reason: "stored_token_invalid"
498
+ });
499
+ storageRef.current.clear();
500
+ const ok = await performRefresh();
501
+ if (!ok && mounted) setStatus("unauthenticated");
502
+ })();
503
+ return () => {
504
+ mounted = false;
505
+ };
506
+ }
507
+ (async () => {
508
+ const ok = await performRefresh();
509
+ if (!ok && mounted) setStatus("unauthenticated");
510
+ })();
511
+ return () => {
512
+ mounted = false;
513
+ };
514
+ }, [skipInitialRefresh, performRefresh]);
515
+ const getAccessToken = react.useCallback(async () => {
516
+ if (accessToken) {
517
+ const exp = readJwtExp(accessToken);
518
+ const now = Math.floor(Date.now() / 1e3);
519
+ if (exp !== null && exp - now > 10) return accessToken;
520
+ }
521
+ const ok = await performRefresh();
522
+ return ok ? storageRef.current.get() : null;
523
+ }, [accessToken, performRefresh]);
524
+ const signIn = react.useCallback(
525
+ (opts = {}) => {
526
+ const p = propsRef.current;
527
+ p.emit({
528
+ kind: "sign_in_started",
529
+ timestamp: Date.now(),
530
+ method: "redirect"
531
+ });
532
+ if (!isBrowser()) return;
533
+ if (!p.projectId) {
534
+ console.warn(
535
+ '[@useauthio/react] AuthioProvider projectId is missing \u2014 Lobby cannot resolve your project. Set projectId="proj_\u2026" on <AuthioProvider>.'
536
+ );
537
+ }
538
+ const base = p.signInUrl ?? DEFAULT_SIGN_IN_URL;
539
+ const url = new URL(base);
540
+ if (p.projectId) {
541
+ url.searchParams.set("project_id", p.projectId);
542
+ }
543
+ url.searchParams.set(
544
+ "redirect_uri",
545
+ opts.returnTo ?? window.location.href
546
+ );
547
+ window.location.assign(url.toString());
548
+ },
549
+ []
550
+ );
551
+ const signOut = react.useCallback(async () => {
552
+ const p = propsRef.current;
553
+ const token = storageRef.current.get();
554
+ try {
555
+ await authioFetch({
556
+ apiUrl: p.apiUrl,
557
+ projectId: p.projectId,
558
+ path: "/v1/auth/sign-out",
559
+ method: "POST",
560
+ body: {},
561
+ credentials: "include",
562
+ extraHeaders: token ? { Authorization: `Bearer ${token}` } : {},
563
+ fetchImpl: p.fetchImpl
564
+ });
565
+ } catch {
566
+ } finally {
567
+ storageRef.current.clear();
568
+ schedulerRef.current?.clear();
569
+ setAccessToken(null);
570
+ setUser(null);
571
+ setStatus("unauthenticated");
572
+ p.emit({ kind: "sign_out", timestamp: Date.now() });
573
+ }
574
+ }, []);
575
+ const refresh = react.useCallback(
576
+ () => performRefresh(),
577
+ [performRefresh]
578
+ );
579
+ const value = react.useMemo(
580
+ () => ({
581
+ user,
582
+ status,
583
+ accessToken,
584
+ getAccessToken,
585
+ signIn,
586
+ signOut,
587
+ refresh
588
+ }),
589
+ [user, status, accessToken, getAccessToken, signIn, signOut, refresh]
590
+ );
591
+ return /* @__PURE__ */ jsxRuntime.jsx(AuthioContext.Provider, { value, children });
592
+ }
593
+ function coerceUser(raw) {
594
+ return {
595
+ id: String(raw.id ?? raw.user_id ?? ""),
596
+ email: String(raw.email ?? ""),
597
+ emailVerified: Boolean(raw.emailVerified ?? raw.email_verified ?? false),
598
+ name: raw.name ?? void 0,
599
+ avatarUrl: raw.avatarUrl ?? raw.avatar_url ?? void 0
600
+ };
601
+ }
602
+ function useAuthio() {
603
+ const ctx = react.useContext(AuthioContext);
604
+ if (!ctx) {
605
+ throw new Error(
606
+ "useAuthio() must be used inside an <AuthioProvider>. Wrap your app root with `<AuthioProvider apiUrl=\u2026 projectId=\u2026>` once."
607
+ );
608
+ }
609
+ return ctx;
610
+ }
611
+ function useAuthioRequired(opts = {}) {
612
+ const { fallback = null, redirectTo } = opts;
613
+ const ctx = useAuthio();
614
+ react.useEffect(() => {
615
+ if (ctx.status !== "unauthenticated") return;
616
+ if (!isBrowser()) return;
617
+ if (redirectTo) {
618
+ window.location.assign(redirectTo);
619
+ return;
620
+ }
621
+ ctx.signIn();
622
+ }, [ctx, redirectTo]);
623
+ let gate = null;
624
+ if (ctx.status === "loading") gate = fallback;
625
+ else if (ctx.status === "unauthenticated") gate = fallback;
626
+ return {
627
+ user: ctx.user,
628
+ status: ctx.status,
629
+ accessToken: ctx.accessToken,
630
+ gate
631
+ };
632
+ }
633
+ function SignedIn({ children }) {
634
+ const { status } = useAuthio();
635
+ if (status !== "authenticated") return null;
636
+ return /* @__PURE__ */ jsxRuntime.jsx(jsxRuntime.Fragment, { children });
637
+ }
638
+ function SignedOut({ children }) {
639
+ const { status } = useAuthio();
640
+ if (status !== "unauthenticated") return null;
641
+ return /* @__PURE__ */ jsxRuntime.jsx(jsxRuntime.Fragment, { children });
642
+ }
643
+ function RedirectToSignIn({
644
+ returnTo
645
+ }) {
646
+ const { signIn } = useAuthio();
647
+ react.useEffect(() => {
648
+ if (!isBrowser()) return;
649
+ signIn(returnTo ? { returnTo } : {});
650
+ }, [signIn, returnTo]);
651
+ return null;
652
+ }
653
+ async function signInWithMagicLink(opts) {
654
+ await authioFetch({
655
+ apiUrl: opts.apiUrl,
656
+ projectId: opts.projectId,
657
+ path: "/v1/auth/magic-link/send",
658
+ method: "POST",
659
+ body: {
660
+ email: opts.email,
661
+ redirect_uri: opts.redirectUri
662
+ },
663
+ signal: opts.signal,
664
+ fetchImpl: opts.fetch
665
+ });
666
+ }
667
+ async function signInWithPasskey(opts) {
668
+ if (!isBrowser() || typeof navigator === "undefined") {
669
+ throw new node.AuthioError({
670
+ code: "not_in_browser",
671
+ message: "signInWithPasskey can only be invoked in a browser environment.",
672
+ status: 0
673
+ });
674
+ }
675
+ if (!navigator.credentials || !navigator.credentials.get) {
676
+ throw new node.AuthioError({
677
+ code: "webauthn_unsupported",
678
+ message: "This browser does not support WebAuthn (passkeys).",
679
+ status: 0
680
+ });
681
+ }
682
+ const options = await authioFetch({
683
+ apiUrl: opts.apiUrl,
684
+ projectId: opts.projectId,
685
+ path: "/v1/auth/passkey/login/options",
686
+ method: "POST",
687
+ body: opts.email ? { email: opts.email } : {},
688
+ signal: opts.signal,
689
+ fetchImpl: opts.fetch
690
+ });
691
+ const publicKey = {
692
+ challenge: base64UrlToBuffer(options.challenge),
693
+ rpId: options.rpId,
694
+ timeout: options.timeout,
695
+ userVerification: options.userVerification,
696
+ allowCredentials: options.allowCredentials?.map((c) => ({
697
+ id: base64UrlToBuffer(c.id),
698
+ type: c.type,
699
+ transports: c.transports
700
+ }))
701
+ };
702
+ let credential;
703
+ try {
704
+ credential = await navigator.credentials.get({
705
+ publicKey,
706
+ signal: opts.signal
707
+ });
708
+ } catch (err) {
709
+ throw new node.AuthioError({
710
+ code: "webauthn_cancelled",
711
+ message: err instanceof Error ? err.message : "Passkey ceremony cancelled by user.",
712
+ status: 0
713
+ });
714
+ }
715
+ if (!credential) {
716
+ throw new node.AuthioError({
717
+ code: "webauthn_cancelled",
718
+ message: "Passkey ceremony returned no credential.",
719
+ status: 0
720
+ });
721
+ }
722
+ const assertion = credential;
723
+ const verifyBody = {
724
+ id: assertion.id,
725
+ raw_id: bufferToBase64Url(assertion.rawId),
726
+ type: assertion.type,
727
+ response: {
728
+ client_data_json: bufferToBase64Url(assertion.response.clientDataJSON),
729
+ authenticator_data: bufferToBase64Url(
730
+ assertion.response.authenticatorData
731
+ ),
732
+ signature: bufferToBase64Url(assertion.response.signature),
733
+ user_handle: assertion.response.userHandle ? bufferToBase64Url(assertion.response.userHandle) : null
734
+ }
735
+ };
736
+ const verifyRes = await authioFetch({
737
+ apiUrl: opts.apiUrl,
738
+ projectId: opts.projectId,
739
+ path: "/v1/auth/passkey/login/verify",
740
+ method: "POST",
741
+ body: verifyBody,
742
+ credentials: "include",
743
+ signal: opts.signal,
744
+ fetchImpl: opts.fetch
745
+ });
746
+ return {
747
+ accessToken: verifyRes.access_token,
748
+ refreshToken: verifyRes.refresh_token,
749
+ user: {
750
+ id: verifyRes.user.id,
751
+ email: verifyRes.user.email,
752
+ emailVerified: Boolean(
753
+ verifyRes.user.emailVerified ?? verifyRes.user.email_verified
754
+ ),
755
+ name: verifyRes.user.name,
756
+ avatarUrl: verifyRes.user.avatarUrl ?? verifyRes.user.avatar_url
757
+ }
758
+ };
759
+ }
760
+ function base64UrlToBuffer(b64u) {
761
+ const padded = b64u.replace(/-/g, "+").replace(/_/g, "/").padEnd(b64u.length + (4 - b64u.length % 4) % 4, "=");
762
+ const bin = atob(padded);
763
+ const out = new Uint8Array(bin.length);
764
+ for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);
765
+ return out.buffer;
766
+ }
767
+ function bufferToBase64Url(buf) {
768
+ const bytes = new Uint8Array(buf);
769
+ let bin = "";
770
+ for (let i = 0; i < bytes.length; i++) {
771
+ bin += String.fromCharCode(bytes[i]);
772
+ }
773
+ return btoa(bin).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
774
+ }
775
+
776
+ // src/locate.ts
777
+ function captureClientLocation(opts = {}) {
778
+ if (typeof navigator === "undefined" || !navigator.geolocation) {
779
+ return Promise.reject(new Error("geolocation_unavailable"));
780
+ }
781
+ const timeoutMs = opts.timeoutMs ?? 1e4;
782
+ return new Promise((resolve, reject) => {
783
+ const timer = setTimeout(() => reject(new Error("geolocation_timeout")), timeoutMs);
784
+ navigator.geolocation.getCurrentPosition(
785
+ (pos) => {
786
+ clearTimeout(timer);
787
+ resolve({
788
+ latitude: pos.coords.latitude,
789
+ longitude: pos.coords.longitude,
790
+ accuracy_m: Math.round(pos.coords.accuracy),
791
+ captured_at: new Date(pos.timestamp).toISOString(),
792
+ source: "browser_geolocation"
793
+ });
794
+ },
795
+ (err) => {
796
+ clearTimeout(timer);
797
+ reject(err);
798
+ },
799
+ {
800
+ enableHighAccuracy: opts.enableHighAccuracy ?? false,
801
+ maximumAge: opts.maximumAgeMs ?? 6e4,
802
+ timeout: timeoutMs
803
+ }
804
+ );
805
+ });
806
+ }
807
+
808
+ Object.defineProperty(exports, "AuthioError", {
809
+ enumerable: true,
810
+ get: function () { return node.AuthioError; }
811
+ });
812
+ exports.AuthioContext = AuthioContext;
813
+ exports.AuthioProvider = AuthioProvider;
814
+ exports.RedirectToSignIn = RedirectToSignIn;
815
+ exports.SignedIn = SignedIn;
816
+ exports.SignedOut = SignedOut;
817
+ exports.captureClientLocation = captureClientLocation;
818
+ exports.signInWithMagicLink = signInWithMagicLink;
819
+ exports.signInWithPasskey = signInWithPasskey;
820
+ exports.useAuthio = useAuthio;
821
+ exports.useAuthioRequired = useAuthioRequired;
822
+ exports.wrapFetchError = wrapFetchError;
823
+ //# sourceMappingURL=index.cjs.map
824
+ //# sourceMappingURL=index.cjs.map