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