@useauthio/react 0.2.3 → 0.3.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,164 @@
1
+ import React, { useState } from "react";
2
+ import { usePasskeys } from "./usePasskeys";
3
+
4
+ export interface PasskeyManagerProps {
5
+ className?: string;
6
+ /** Passed to {@link enrollPasskey} as `returnUrl`. */
7
+ enrollReturnUrl?: string;
8
+ enrollNext?: string;
9
+ }
10
+
11
+ /**
12
+ * Drop-in passkey device list for customer apps. Lists, renames, and
13
+ * revokes via `/v1/me/passkeys`; "Add passkey" redirects to the hosted
14
+ * sign-in UI (`mode=add_credential`) so the WebAuthn ceremony runs on
15
+ * the sign-in origin.
16
+ */
17
+ export function PasskeyManager({
18
+ className,
19
+ enrollReturnUrl,
20
+ enrollNext,
21
+ }: PasskeyManagerProps): React.ReactElement {
22
+ const { passkeys, loading, error, rename, revoke, enroll } = usePasskeys();
23
+ const [busyId, setBusyId] = useState<string | null>(null);
24
+ const [actionError, setActionError] = useState<string | null>(null);
25
+ const [enrolling, setEnrolling] = useState(false);
26
+
27
+ async function onRename(id: string, nickname: string) {
28
+ setBusyId(id);
29
+ setActionError(null);
30
+ try {
31
+ await rename(id, nickname);
32
+ } catch (err) {
33
+ setActionError(err instanceof Error ? err.message : "Rename failed");
34
+ } finally {
35
+ setBusyId(null);
36
+ }
37
+ }
38
+
39
+ async function onRevoke(id: string) {
40
+ setBusyId(id);
41
+ setActionError(null);
42
+ try {
43
+ await revoke(id);
44
+ } catch (err) {
45
+ setActionError(err instanceof Error ? err.message : "Revoke failed");
46
+ } finally {
47
+ setBusyId(null);
48
+ }
49
+ }
50
+
51
+ async function onEnroll() {
52
+ setEnrolling(true);
53
+ setActionError(null);
54
+ try {
55
+ await enroll({ returnUrl: enrollReturnUrl, next: enrollNext });
56
+ } catch (err) {
57
+ setEnrolling(false);
58
+ setActionError(err instanceof Error ? err.message : "Could not start enrollment");
59
+ }
60
+ }
61
+
62
+ return (
63
+ <section className={className} aria-labelledby="authio-passkey-manager-title">
64
+ <div className="authio-passkey-manager__header">
65
+ <h2 id="authio-passkey-manager-title">Passkeys</h2>
66
+ <button
67
+ type="button"
68
+ onClick={() => void onEnroll()}
69
+ disabled={enrolling || loading}
70
+ >
71
+ {enrolling ? "Redirecting…" : "Add passkey"}
72
+ </button>
73
+ </div>
74
+
75
+ {(error || actionError) && (
76
+ <p role="alert" className="authio-passkey-manager__error">
77
+ {error ?? actionError}
78
+ </p>
79
+ )}
80
+
81
+ {loading ? (
82
+ <p className="authio-passkey-manager__loading">Loading passkeys…</p>
83
+ ) : passkeys.length === 0 ? (
84
+ <p className="authio-passkey-manager__empty">
85
+ No passkeys yet. Add one to sign in faster on this account.
86
+ </p>
87
+ ) : (
88
+ <ul className="authio-passkey-manager__list">
89
+ {passkeys.map((p) => (
90
+ <li key={p.id} className="authio-passkey-manager__item">
91
+ <PasskeyRow
92
+ passkey={p}
93
+ busy={busyId === p.id}
94
+ onRename={onRename}
95
+ onRevoke={onRevoke}
96
+ />
97
+ </li>
98
+ ))}
99
+ </ul>
100
+ )}
101
+ </section>
102
+ );
103
+ }
104
+
105
+ function PasskeyRow({
106
+ passkey,
107
+ busy,
108
+ onRename,
109
+ onRevoke,
110
+ }: {
111
+ passkey: {
112
+ id: string;
113
+ nickname: string | null;
114
+ authenticator_name: string;
115
+ created_at: string;
116
+ last_used_at: string | null;
117
+ };
118
+ busy: boolean;
119
+ onRename: (id: string, nickname: string) => Promise<void>;
120
+ onRevoke: (id: string) => Promise<void>;
121
+ }) {
122
+ const [nickname, setNickname] = useState(passkey.nickname ?? "");
123
+
124
+ return (
125
+ <div className="authio-passkey-manager__row">
126
+ <div>
127
+ <strong>{passkey.authenticator_name}</strong>
128
+ <div className="authio-passkey-manager__meta">
129
+ Added {new Date(passkey.created_at).toLocaleDateString()}
130
+ {passkey.last_used_at
131
+ ? ` · Last used ${new Date(passkey.last_used_at).toLocaleDateString()}`
132
+ : ""}
133
+ </div>
134
+ </div>
135
+ <form
136
+ className="authio-passkey-manager__rename"
137
+ onSubmit={(e) => {
138
+ e.preventDefault();
139
+ void onRename(passkey.id, nickname.trim());
140
+ }}
141
+ >
142
+ <input
143
+ type="text"
144
+ value={nickname}
145
+ onChange={(e) => setNickname(e.target.value)}
146
+ placeholder="Nickname"
147
+ maxLength={64}
148
+ disabled={busy}
149
+ />
150
+ <button type="submit" disabled={busy}>
151
+ Save
152
+ </button>
153
+ </form>
154
+ <button
155
+ type="button"
156
+ disabled={busy}
157
+ onClick={() => void onRevoke(passkey.id)}
158
+ className="authio-passkey-manager__revoke"
159
+ >
160
+ Revoke
161
+ </button>
162
+ </div>
163
+ );
164
+ }
@@ -0,0 +1,95 @@
1
+ import { isBrowser, isTabHidden } from "./ssr";
2
+
3
+ /**
4
+ * DOM events that count as "the user is here". All are registered
5
+ * passive + capture so we never delay the page's own handlers, and
6
+ * `scroll` is the only high-frequency one — the throttle below keeps
7
+ * it from churning.
8
+ */
9
+ const ACTIVITY_EVENTS = [
10
+ "pointerdown",
11
+ "keydown",
12
+ "touchstart",
13
+ "scroll",
14
+ "focus",
15
+ ] as const;
16
+
17
+ /** Minimum gap between two recorded activity timestamps. */
18
+ const THROTTLE_MS = 1000;
19
+
20
+ export type ActivityListener = (at: number) => void;
21
+
22
+ /**
23
+ * Tracks the last moment the user interacted with the page. Used by the
24
+ * provider to decide whether a scheduled silent refresh should run or
25
+ * be deferred: when the project/org has an inactivity (idle) timeout,
26
+ * refreshing on a timer while nobody is at the keyboard would bump the
27
+ * server's `last_active_at` and defeat that policy. See `RefreshScheduler`.
28
+ *
29
+ * SSR-safe — under SSR `lastActivityAt()` is `0` and listeners are never
30
+ * attached.
31
+ */
32
+ export class ActivityTracker {
33
+ private last = 0;
34
+ private listeners = new Set<ActivityListener>();
35
+ private handler: (() => void) | null = null;
36
+ private visibilityHandler: (() => void) | null = null;
37
+ private destroyed = false;
38
+
39
+ constructor(now: () => number = Date.now) {
40
+ this.now = now;
41
+ if (!isBrowser()) return;
42
+ this.handler = () => this.mark();
43
+ for (const ev of ACTIVITY_EVENTS) {
44
+ window.addEventListener(ev, this.handler, { passive: true, capture: true });
45
+ }
46
+ this.visibilityHandler = () => {
47
+ if (!isTabHidden()) this.mark();
48
+ };
49
+ document.addEventListener("visibilitychange", this.visibilityHandler);
50
+ }
51
+
52
+ private readonly now: () => number;
53
+
54
+ /** Unix ms of the most recent recorded interaction, `0` if none yet. */
55
+ lastActivityAt(): number {
56
+ return this.last;
57
+ }
58
+
59
+ /**
60
+ * Record activity now. Throttled to one write per second; listeners
61
+ * fire only when a write actually happens. Exposed so tests (and
62
+ * embedders with their own activity signal) can poke it directly.
63
+ */
64
+ mark(): void {
65
+ if (this.destroyed) return;
66
+ const t = this.now();
67
+ if (t - this.last < THROTTLE_MS) return;
68
+ this.last = t;
69
+ for (const l of this.listeners) l(t);
70
+ }
71
+
72
+ /** Subscribe to recorded activity. Returns an unsubscribe function. */
73
+ onActivity(listener: ActivityListener): () => void {
74
+ this.listeners.add(listener);
75
+ return () => {
76
+ this.listeners.delete(listener);
77
+ };
78
+ }
79
+
80
+ destroy(): void {
81
+ this.destroyed = true;
82
+ this.listeners.clear();
83
+ if (!isBrowser()) return;
84
+ if (this.handler) {
85
+ for (const ev of ACTIVITY_EVENTS) {
86
+ window.removeEventListener(ev, this.handler, { capture: true });
87
+ }
88
+ }
89
+ if (this.visibilityHandler) {
90
+ document.removeEventListener("visibilitychange", this.visibilityHandler);
91
+ }
92
+ this.handler = null;
93
+ this.visibilityHandler = null;
94
+ }
95
+ }
@@ -0,0 +1,86 @@
1
+ /**
2
+ * Optional browser device signals for Authio risk / device fingerprinting.
3
+ *
4
+ * Web browsers do not expose a hardware ID (IMEI, serial, MAC). These
5
+ * coarse, non-PII signals improve device recognition alongside the
6
+ * server-parsed user agent. auth-core hashes them server-side — never
7
+ * send a precomputed fingerprint from the client.
8
+ */
9
+
10
+ export interface DeviceSignalsCapture {
11
+ timezone?: string;
12
+ screen_resolution?: string;
13
+ language?: string;
14
+ platform?: string;
15
+ }
16
+
17
+ /** Collect coarse device signals available in a browser context. */
18
+ export function collectDeviceSignals(): DeviceSignalsCapture {
19
+ if (typeof window === "undefined") {
20
+ return {};
21
+ }
22
+ const out: DeviceSignalsCapture = {};
23
+ try {
24
+ out.timezone = Intl.DateTimeFormat().resolvedOptions().timeZone;
25
+ } catch {
26
+ /* ignore */
27
+ }
28
+ if (typeof screen !== "undefined") {
29
+ out.screen_resolution = `${screen.width}x${screen.height}`;
30
+ }
31
+ if (typeof navigator !== "undefined") {
32
+ if (navigator.language) {
33
+ out.language = navigator.language;
34
+ }
35
+ if (navigator.platform) {
36
+ out.platform = navigator.platform;
37
+ }
38
+ }
39
+ return out;
40
+ }
41
+
42
+ /** Encode signals for the `X-Authio-Device-Signals` request header. */
43
+ export function encodeDeviceSignalsHeader(
44
+ signals: DeviceSignalsCapture,
45
+ ): string {
46
+ const json = JSON.stringify(signals);
47
+ if (typeof btoa === "function") {
48
+ return btoa(json).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
49
+ }
50
+ // Node / test fallback. Typed structurally off globalThis so the browser
51
+ // SDK doesn't need @types/node just for this branch.
52
+ const nodeBuffer = (
53
+ globalThis as {
54
+ Buffer?: {
55
+ from(input: string, encoding: string): { toString(encoding: string): string };
56
+ };
57
+ }
58
+ ).Buffer;
59
+ if (!nodeBuffer) {
60
+ throw new Error("No base64 encoder available in this environment.");
61
+ }
62
+ return nodeBuffer
63
+ .from(json, "utf8")
64
+ .toString("base64")
65
+ .replace(/\+/g, "-")
66
+ .replace(/\//g, "_")
67
+ .replace(/=+$/, "");
68
+ }
69
+
70
+ /** Header name auth-core reads for optional client device signals. */
71
+ export const DEVICE_SIGNALS_HEADER = "X-Authio-Device-Signals";
72
+
73
+ export function deviceSignalsExtraHeaders(
74
+ signals?: DeviceSignalsCapture,
75
+ ): Record<string, string> {
76
+ const s = signals ?? collectDeviceSignals();
77
+ if (
78
+ !s.timezone &&
79
+ !s.screen_resolution &&
80
+ !s.language &&
81
+ !s.platform
82
+ ) {
83
+ return {};
84
+ }
85
+ return { [DEVICE_SIGNALS_HEADER]: encodeDeviceSignalsHeader(s) };
86
+ }
package/src/index.ts CHANGED
@@ -17,25 +17,71 @@ export type {
17
17
  RedirectToSignInProps,
18
18
  } from "./gates";
19
19
 
20
- export { signInWithMagicLink, signInWithPasskey } from "./sign-in";
20
+ export {
21
+ signInWithMagicLink,
22
+ signInWithPasskey,
23
+ sendEmailOtp,
24
+ verifyEmailOtp,
25
+ } from "./sign-in";
26
+
27
+ export {
28
+ addPasskey,
29
+ listPasskeys,
30
+ renamePasskey,
31
+ revokePasskey,
32
+ mintPasskeyRegisterIntent,
33
+ buildEnrollPasskeyUrl,
34
+ enrollPasskey,
35
+ signInOrigin,
36
+ canEnrollPasskeyEmbedded,
37
+ } from "./passkeys";
38
+ export type {
39
+ AuthioPasskey,
40
+ PasskeyApiOptions,
41
+ AddPasskeyOptions,
42
+ EnrollPasskeyOptions,
43
+ } from "./passkeys";
44
+
45
+ export { usePasskeys } from "./usePasskeys";
46
+ export type { UsePasskeysResult } from "./usePasskeys";
47
+
48
+ export { PasskeyManager } from "./PasskeyManager";
49
+ export type { PasskeyManagerProps } from "./PasskeyManager";
21
50
  export type {
22
51
  SignInWithMagicLinkOptions,
23
52
  SignInWithPasskeyOptions,
24
53
  SignInWithPasskeyResult,
54
+ SendEmailOtpOptions,
55
+ VerifyEmailOtpOptions,
56
+ VerifyEmailOtpResult,
25
57
  } from "./sign-in";
26
58
 
27
- export { captureClientLocation } from "./locate";
59
+ export { captureClientLocation, verifyLocate } from "./locate";
28
60
  export type {
29
61
  ClientLocationCapture,
30
62
  CaptureClientLocationOptions,
63
+ LocateAction,
64
+ VerifyLocateOptions,
65
+ LocateVerifyResult,
31
66
  } from "./locate";
32
67
 
68
+ export {
69
+ collectDeviceSignals,
70
+ encodeDeviceSignalsHeader,
71
+ deviceSignalsExtraHeaders,
72
+ DEVICE_SIGNALS_HEADER,
73
+ } from "./device-signals";
74
+ export type { DeviceSignalsCapture } from "./device-signals";
75
+
33
76
  export { AuthioError, wrapFetchError } from "./errors";
34
77
 
35
78
  export type {
36
79
  AuthioUser,
37
80
  AuthioStatus,
38
81
  AuthioStorageMode,
82
+ AuthioIdleRefreshMode,
83
+ SessionPolicy,
84
+ RawSessionPolicy,
39
85
  AuthioContextValue,
40
86
  AuthioProviderProps,
41
87
  AuthioTokenVerification,
@@ -43,3 +89,8 @@ export type {
43
89
  } from "./types";
44
90
 
45
91
  export type { AuthioTelemetryEvent } from "./telemetry";
92
+
93
+ export { coerceSessionPolicy } from "./types";
94
+ export { ActivityTracker } from "./activity";
95
+ export type { ActivityListener } from "./activity";
96
+ export type { RefreshDeferReason } from "./refresh";
@@ -7,6 +7,8 @@ export interface MintLobbySignInUrlOptions {
7
7
  redirectUri: string;
8
8
  /** Post-login path threaded separately from redirect_uri (BFF ?next=). */
9
9
  next?: string;
10
+ /** Org scope for org_policies.disabled_methods on the Lobby surface. */
11
+ organizationId?: string;
10
12
  fetchImpl?: typeof fetch;
11
13
  }
12
14
 
@@ -37,6 +39,9 @@ export async function mintLobbySignInUrl(
37
39
  project_id: opts.projectId,
38
40
  redirect_uri: opts.redirectUri,
39
41
  ...(opts.next ? { next: opts.next } : {}),
42
+ ...(opts.organizationId
43
+ ? { organization_id: opts.organizationId }
44
+ : {}),
40
45
  }),
41
46
  },
42
47
  );
@@ -59,5 +64,8 @@ export async function mintLobbySignInUrl(
59
64
  if (opts.next) {
60
65
  target.searchParams.set("next", opts.next);
61
66
  }
67
+ if (opts.organizationId) {
68
+ target.searchParams.set("organization_id", opts.organizationId);
69
+ }
62
70
  return target.toString();
63
71
  }
package/src/locate.ts CHANGED
@@ -55,3 +55,45 @@ export function captureClientLocation(
55
55
  );
56
56
  });
57
57
  }
58
+
59
+ export type LocateAction = "sign_in" | "wager_placed" | "contest_entry" | string;
60
+
61
+ export interface VerifyLocateOptions {
62
+ apiUrl: string;
63
+ projectId: string;
64
+ accessToken: string;
65
+ action: LocateAction;
66
+ clientLocation?: ClientLocationCapture;
67
+ idempotencyKey?: string;
68
+ fetchImpl?: typeof fetch;
69
+ signal?: AbortSignal;
70
+ }
71
+
72
+ export interface LocateVerifyResult {
73
+ verification_id: string;
74
+ decision: "allow" | "block";
75
+ confidence: number;
76
+ method: string;
77
+ location: { country: string; region: string; source: string };
78
+ network_signals: {
79
+ vpn: boolean;
80
+ datacenter: boolean;
81
+ tor: boolean;
82
+ anonymous_proxy: boolean;
83
+ satellite: boolean;
84
+ };
85
+ evasion_signals: string[];
86
+ }
87
+
88
+ const VERIFY_LOCATE_BACKEND_ONLY =
89
+ "verifyLocate() is not supported in @useauthio/react: POST /v1/locate/verify requires a project secret key (sk_live_/sk_test_), not a user JWT. " +
90
+ "Capture GPS with captureClientLocation(), POST to your backend, and call authio.locate.verify() via @useauthio/node. " +
91
+ "See authio_locate/docs/JB_MIGRATION_GUIDE.md.";
92
+
93
+ /**
94
+ * @deprecated Use backend proxy with `@useauthio/node` `authio.locate.verify()` — see JB migration guide.
95
+ * This helper always throws; it must not send a user JWT to the sk_-only verify route.
96
+ */
97
+ export async function verifyLocate(_opts: VerifyLocateOptions): Promise<LocateVerifyResult> {
98
+ throw new Error(VERIFY_LOCATE_BACKEND_ONLY);
99
+ }