@useauthio/react 0.2.4 → 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.
package/src/sign-in.ts CHANGED
@@ -1,7 +1,17 @@
1
1
  import { AuthioError } from "@useauthio/node";
2
2
  import { authioFetch } from "./fetch";
3
+ import {
4
+ deviceSignalsExtraHeaders,
5
+ type DeviceSignalsCapture,
6
+ } from "./device-signals";
3
7
  import { isBrowser } from "./ssr";
4
- import type { AuthioUser } from "./types";
8
+ import type { ClientLocationCapture } from "./locate";
9
+ import {
10
+ coerceSessionPolicy,
11
+ type AuthioUser,
12
+ type RawSessionPolicy,
13
+ type SessionPolicy,
14
+ } from "./types";
5
15
 
6
16
  export interface SignInWithMagicLinkOptions {
7
17
  /** Authio auth-core base URL. */
@@ -73,6 +83,14 @@ export interface SignInWithPasskeyOptions {
73
83
  * the user picks their key from the browser's native chooser.
74
84
  */
75
85
  email?: string;
86
+ /**
87
+ * Post-sign-in path on the app (`next`) forwarded to auth-core on
88
+ * the verify call. Older auth-core deployments ignore it; token
89
+ * handling on the client is unchanged either way.
90
+ */
91
+ next?: string;
92
+ /** Organization scope (`org_…`) for org-policy enforcement. */
93
+ organizationId?: string;
76
94
  signal?: AbortSignal;
77
95
  fetch?: typeof fetch;
78
96
  }
@@ -80,6 +98,8 @@ export interface SignInWithPasskeyOptions {
80
98
  export interface SignInWithPasskeyResult {
81
99
  accessToken: string;
82
100
  refreshToken?: string;
101
+ /** Effective session policy from the envelope, `null` on older auth-core. */
102
+ sessionPolicy: SessionPolicy | null;
83
103
  user: AuthioUser;
84
104
  }
85
105
 
@@ -98,6 +118,7 @@ interface PasskeyLoginOptionsResponse {
98
118
  interface PasskeyLoginVerifyResponse {
99
119
  access_token: string;
100
120
  refresh_token?: string;
121
+ session_policy?: RawSessionPolicy;
101
122
  user: {
102
123
  id: string;
103
124
  email: string;
@@ -228,15 +249,181 @@ export async function signInWithPasskey(
228
249
  projectId: opts.projectId,
229
250
  path: "/v1/auth/passkey/login/verify",
230
251
  method: "POST",
231
- body: { credential: webauthnCredential },
252
+ body: {
253
+ credential: webauthnCredential,
254
+ ...(opts.next ? { next: opts.next } : {}),
255
+ ...(opts.organizationId ? { organization_id: opts.organizationId } : {}),
256
+ },
257
+ extraHeaders: deviceSignalsExtraHeaders(),
258
+ credentials: "include",
259
+ signal: opts.signal,
260
+ fetchImpl: opts.fetch,
261
+ });
262
+
263
+ return {
264
+ accessToken: verifyRes.access_token,
265
+ refreshToken: verifyRes.refresh_token,
266
+ sessionPolicy: coerceSessionPolicy(verifyRes.session_policy),
267
+ user: {
268
+ id: verifyRes.user.id,
269
+ email: verifyRes.user.email,
270
+ emailVerified: Boolean(
271
+ verifyRes.user.emailVerified ?? verifyRes.user.email_verified,
272
+ ),
273
+ name: verifyRes.user.name,
274
+ avatarUrl: verifyRes.user.avatarUrl ?? verifyRes.user.avatar_url,
275
+ },
276
+ };
277
+ }
278
+
279
+ // ============================================================
280
+ // Email OTP (6-digit code) sign-in — M6
281
+ // ============================================================
282
+
283
+ export interface SendEmailOtpOptions {
284
+ /** Authio auth-core base URL. */
285
+ apiUrl: string;
286
+ /** Project ID (`proj_…`). */
287
+ projectId: string;
288
+ /** Email address to send the 6-digit code to. */
289
+ email: string;
290
+ /**
291
+ * Where auth-core should consider the sign-in to be headed. Optional —
292
+ * when omitted, auth-core derives it from the request Origin.
293
+ */
294
+ redirectUri?: string;
295
+ /** Post-sign-in path on the app, carried through to the session redirect. */
296
+ next?: string;
297
+ /** Organization scope (`org_…`) for org-policy enforcement. */
298
+ organizationId?: string;
299
+ signal?: AbortSignal;
300
+ fetch?: typeof fetch;
301
+ }
302
+
303
+ /**
304
+ * POSTs `/v1/auth/email-otp/send` — the same endpoint/body shape the
305
+ * hosted Lobby's "Email me a code" button uses. Returns `void` on
306
+ * success; the code is now in the user's inbox. Throws `AuthioError`
307
+ * on any failure (rate-limit, invalid email, org policy, network).
308
+ *
309
+ * Note: unlike `verifyEmailOtp`, the send endpoint does not accept
310
+ * `client_location` — capture location once and pass it to verify.
311
+ */
312
+ export async function sendEmailOtp(opts: SendEmailOtpOptions): Promise<void> {
313
+ await authioFetch<{ expires_in?: number }>({
314
+ apiUrl: opts.apiUrl,
315
+ projectId: opts.projectId,
316
+ path: "/v1/auth/email-otp/send",
317
+ method: "POST",
318
+ body: {
319
+ email: opts.email,
320
+ ...(opts.redirectUri ? { redirect_uri: opts.redirectUri } : {}),
321
+ ...(opts.next ? { next: opts.next } : {}),
322
+ ...(opts.organizationId ? { organization_id: opts.organizationId } : {}),
323
+ },
324
+ signal: opts.signal,
325
+ fetchImpl: opts.fetch,
326
+ });
327
+ }
328
+
329
+ export interface VerifyEmailOtpOptions {
330
+ apiUrl: string;
331
+ projectId: string;
332
+ /** Email address the code was sent to. */
333
+ email: string;
334
+ /** The 6-digit code from the user's inbox. */
335
+ code: string;
336
+ /** Fallback redirect target when the send call didn't record one. */
337
+ redirectUri?: string;
338
+ /** Post-sign-in path on the app. */
339
+ next?: string;
340
+ /** Organization scope (`org_…`) for org-policy enforcement. */
341
+ organizationId?: string;
342
+ /** Optional browser geolocation for Authio Locate attestation. */
343
+ clientLocation?: ClientLocationCapture;
344
+ /** Optional coarse device signals for risk / device recognition. */
345
+ deviceSignals?: DeviceSignalsCapture;
346
+ signal?: AbortSignal;
347
+ fetch?: typeof fetch;
348
+ }
349
+
350
+ export interface VerifyEmailOtpResult {
351
+ accessToken: string;
352
+ refreshToken?: string;
353
+ /** Effective session policy from the envelope, `null` on older auth-core. */
354
+ sessionPolicy: SessionPolicy | null;
355
+ user: AuthioUser;
356
+ }
357
+
358
+ interface EmailOtpVerifyResponse {
359
+ decision?: string;
360
+ challenge_id?: string;
361
+ access_token: string;
362
+ refresh_token?: string;
363
+ session_policy?: RawSessionPolicy;
364
+ user: {
365
+ id: string;
366
+ email: string;
367
+ email_verified?: boolean;
368
+ emailVerified?: boolean;
369
+ name?: string;
370
+ avatar_url?: string;
371
+ avatarUrl?: string;
372
+ };
373
+ }
374
+
375
+ /**
376
+ * POSTs `/v1/auth/email-otp/verify` with the code the user typed —
377
+ * mirrors the hosted Lobby's verify body shape. On success returns
378
+ * `{ accessToken, refreshToken, user }`; auth-core also sets the
379
+ * session cookie via `Set-Cookie` (the request runs with
380
+ * `credentials: "include"`), which is the canonical storage.
381
+ *
382
+ * Throws `AuthioError`:
383
+ *
384
+ * - `invalid_code` for a wrong/expired code (auth-core's code).
385
+ * - `step_up_required` when the risk engine withholds the session
386
+ * pending a second factor — finish the sign-in on the hosted UI.
387
+ * - Whatever else auth-core returns (rate-limit, policy, etc.).
388
+ */
389
+ export async function verifyEmailOtp(
390
+ opts: VerifyEmailOtpOptions,
391
+ ): Promise<VerifyEmailOtpResult> {
392
+ const verifyRes = await authioFetch<EmailOtpVerifyResponse>({
393
+ apiUrl: opts.apiUrl,
394
+ projectId: opts.projectId,
395
+ path: "/v1/auth/email-otp/verify",
396
+ method: "POST",
397
+ body: {
398
+ email: opts.email,
399
+ code: opts.code,
400
+ ...(opts.redirectUri ? { redirect_uri: opts.redirectUri } : {}),
401
+ ...(opts.next ? { next: opts.next } : {}),
402
+ ...(opts.organizationId ? { organization_id: opts.organizationId } : {}),
403
+ ...(opts.clientLocation ? { client_location: opts.clientLocation } : {}),
404
+ ...(opts.deviceSignals ? { device_signals: opts.deviceSignals } : {}),
405
+ },
232
406
  credentials: "include",
233
407
  signal: opts.signal,
234
408
  fetchImpl: opts.fetch,
235
409
  });
236
410
 
411
+ // The risk engine may withhold the session and demand a second factor.
412
+ // A pure SPA can't run the step-up ceremony itself — surface a typed
413
+ // error so callers can bounce the user to the hosted step-up page.
414
+ if (verifyRes.decision === "step_up") {
415
+ throw new AuthioError({
416
+ code: "step_up_required",
417
+ message:
418
+ "Additional verification is required. Complete the step-up challenge on the hosted sign-in page.",
419
+ status: 200,
420
+ });
421
+ }
422
+
237
423
  return {
238
424
  accessToken: verifyRes.access_token,
239
425
  refreshToken: verifyRes.refresh_token,
426
+ sessionPolicy: coerceSessionPolicy(verifyRes.session_policy),
240
427
  user: {
241
428
  id: verifyRes.user.id,
242
429
  email: verifyRes.user.email,
package/src/telemetry.ts CHANGED
@@ -20,6 +20,10 @@
20
20
  * - `refresh_scheduled`: a future silent refresh has been timer-
21
21
  * scheduled. `runAt` is the unix millisecond at which the refresh
22
22
  * will fire (subject to the visibilitychange deferral).
23
+ * - `refresh_deferred`: a scheduled refresh was held back — `hidden`
24
+ * when the tab is in the background, `idle` when the user has not
25
+ * interacted since the last refresh and the session policy has an
26
+ * inactivity timeout. `refresh_resumed` follows when it re-arms.
23
27
  * - `sign_in_started` / `sign_in_completed` / `sign_in_failed`: the
24
28
  * three terminal states of a sign-in attempt. `method` says which
25
29
  * surface initiated it.
@@ -42,6 +46,13 @@ export type AuthioTelemetryEvent =
42
46
  attempt: number;
43
47
  }
44
48
  | { kind: "refresh_scheduled"; timestamp: number; runAt: number }
49
+ | {
50
+ kind: "refresh_deferred";
51
+ timestamp: number;
52
+ /** `hidden`: background tab. `idle`: no user activity under an inactivity policy. */
53
+ reason: "hidden" | "idle";
54
+ }
55
+ | { kind: "refresh_resumed"; timestamp: number }
45
56
  | {
46
57
  kind: "sign_in_started";
47
58
  timestamp: number;
package/src/types.ts CHANGED
@@ -25,6 +25,61 @@ export interface AuthioUser {
25
25
  */
26
26
  export type AuthioStatus = "loading" | "authenticated" | "unauthenticated";
27
27
 
28
+ /**
29
+ * Effective session-lifecycle policy for the current session, as reported
30
+ * by auth-core in the `session_policy` field of every session envelope
31
+ * (sign-in, refresh, switch-org). Values are minutes; `0` means "no limit
32
+ * at this layer". `null` on the context when auth-core predates the field.
33
+ *
34
+ * The SDK uses `idleTimeoutMin` to decide whether a timer-driven silent
35
+ * refresh should be held back while the user is inactive — see the
36
+ * `idleRefresh` provider prop.
37
+ */
38
+ export interface SessionPolicy {
39
+ idleTimeoutMin: number;
40
+ absoluteMaxMin: number;
41
+ accessTokenTtlMin: number;
42
+ }
43
+
44
+ /** Wire shape of `session_policy` on auth-core envelopes. */
45
+ export interface RawSessionPolicy {
46
+ idle_timeout_min?: number;
47
+ absolute_max_min?: number;
48
+ access_token_ttl_min?: number;
49
+ }
50
+
51
+ /**
52
+ * Normalise a raw `session_policy` object. Returns `null` when the field
53
+ * is absent or malformed (older auth-core), so callers can keep the
54
+ * legacy always-refresh behaviour.
55
+ */
56
+ export function coerceSessionPolicy(
57
+ raw: RawSessionPolicy | null | undefined,
58
+ ): SessionPolicy | null {
59
+ if (!raw || typeof raw !== "object") return null;
60
+ const n = (v: unknown): number =>
61
+ typeof v === "number" && Number.isFinite(v) && v > 0 ? Math.floor(v) : 0;
62
+ return {
63
+ idleTimeoutMin: n(raw.idle_timeout_min),
64
+ absoluteMaxMin: n(raw.absolute_max_min),
65
+ accessTokenTtlMin: n(raw.access_token_ttl_min),
66
+ };
67
+ }
68
+
69
+ /**
70
+ * How the silent-refresh timer behaves while the user is inactive.
71
+ *
72
+ * - `"defer"` (default): when the effective policy has an inactivity
73
+ * timeout (`sessionPolicy.idleTimeoutMin > 0`) and there has been no
74
+ * user interaction since the last refresh, the scheduled refresh is
75
+ * held until the next interaction. Without an inactivity policy the
76
+ * refresh always runs — identical to previous SDK versions.
77
+ * - `"always"`: never hold a refresh for inactivity (tab-hidden
78
+ * deferral still applies). Escape hatch for apps whose background
79
+ * work needs a warm token even when nobody is at the keyboard.
80
+ */
81
+ export type AuthioIdleRefreshMode = "defer" | "always";
82
+
28
83
  export type AuthioStorageMode =
29
84
  | "memory"
30
85
  | "localStorage"
@@ -35,6 +90,12 @@ export interface AuthioContextValue {
35
90
  user: AuthioUser | null;
36
91
  status: AuthioStatus;
37
92
  accessToken: string | null;
93
+ /**
94
+ * Effective session-lifecycle policy reported by auth-core on the last
95
+ * envelope, or `null` when unknown (no session yet, or an auth-core
96
+ * that predates `session_policy`).
97
+ */
98
+ sessionPolicy: SessionPolicy | null;
38
99
  /** Same `apiUrl` passed to `<AuthioProvider>`. */
39
100
  apiUrl: string;
40
101
  /** Same `projectId` passed to `<AuthioProvider>`. */
@@ -94,6 +155,8 @@ export interface AuthioContextValue {
94
155
  accessToken: string;
95
156
  refreshToken?: string | null;
96
157
  user?: AuthioUser | null;
158
+ /** Policy from the sign-in envelope, when the helper surfaced one. */
159
+ sessionPolicy?: SessionPolicy | null;
97
160
  }) => Promise<void>;
98
161
  }
99
162
 
@@ -129,6 +192,14 @@ export interface AuthioProviderProps {
129
192
  * a background tab.
130
193
  */
131
194
  refreshLeadSeconds?: number;
195
+ /**
196
+ * Silent-refresh behaviour while the user is inactive. Defaults to
197
+ * `"defer"`: under a project/org inactivity policy the timer-driven
198
+ * refresh waits for the next user interaction instead of keeping the
199
+ * session warm on an idle tab. Projects without an inactivity policy
200
+ * are unaffected. See {@link AuthioIdleRefreshMode}.
201
+ */
202
+ idleRefresh?: AuthioIdleRefreshMode;
132
203
  /**
133
204
  * Optional sink for SDK telemetry (refresh outcomes, sign-in
134
205
  * starts/completes, token verification results). Useful for
package/src/version.ts CHANGED
@@ -1,4 +1,4 @@
1
1
  /** Published @useauthio/react version — keep in sync with package.json. */
2
- export const SDK_VERSION = "0.2.2";
2
+ export const SDK_VERSION = "0.3.0";
3
3
 
4
4
  export const SDK_USER_AGENT = `react/${SDK_VERSION}` as const;