@useauthio/react 0.3.0 → 0.3.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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@useauthio/react",
3
- "version": "0.3.0",
3
+ "version": "0.3.1",
4
4
  "description": "React SDK for Authio: hooks, gates, and sign-in helpers for pure SPAs.",
5
5
  "author": "Authio",
6
6
  "license": "MIT",
@@ -51,7 +51,7 @@
51
51
  "tsup": "^8.3.0",
52
52
  "typescript": "^5.6.0",
53
53
  "vitest": "^4.1.0",
54
- "vite": "^6.0.0"
54
+ "vite": "^6.4.4"
55
55
  },
56
56
  "scripts": {
57
57
  "build": "tsup",
@@ -1,5 +1,6 @@
1
1
  import React, { useState } from "react";
2
2
  import { usePasskeys } from "./usePasskeys";
3
+ import { AuthioError } from "./errors";
3
4
 
4
5
  export interface PasskeyManagerProps {
5
6
  className?: string;
@@ -30,7 +31,7 @@ export function PasskeyManager({
30
31
  try {
31
32
  await rename(id, nickname);
32
33
  } catch (err) {
33
- setActionError(err instanceof Error ? err.message : "Rename failed");
34
+ setActionError(err instanceof AuthioError ? err.message : "We couldn't rename that passkey. Please try again.");
34
35
  } finally {
35
36
  setBusyId(null);
36
37
  }
@@ -42,7 +43,7 @@ export function PasskeyManager({
42
43
  try {
43
44
  await revoke(id);
44
45
  } catch (err) {
45
- setActionError(err instanceof Error ? err.message : "Revoke failed");
46
+ setActionError(err instanceof AuthioError ? err.message : "We couldn't remove that passkey. Please try again.");
46
47
  } finally {
47
48
  setBusyId(null);
48
49
  }
@@ -55,7 +56,7 @@ export function PasskeyManager({
55
56
  await enroll({ returnUrl: enrollReturnUrl, next: enrollNext });
56
57
  } catch (err) {
57
58
  setEnrolling(false);
58
- setActionError(err instanceof Error ? err.message : "Could not start enrollment");
59
+ setActionError(err instanceof AuthioError ? err.message : "We couldn't start passkey setup. Please try again.");
59
60
  }
60
61
  }
61
62
 
package/src/errors.ts CHANGED
@@ -2,34 +2,256 @@ import { AuthioError } from "@useauthio/node";
2
2
 
3
3
  export { AuthioError };
4
4
 
5
+ // ------------------------------------------------------------
6
+ // User-facing copy. Every message the SDK produces on its own must be
7
+ // plain English and tell the user what to do next. Raw JS / browser
8
+ // error text (e.g. "Failed to fetch", "The operation either timed out
9
+ // or was not allowed") is kept on `cause` for debugging, never shown.
10
+ // ------------------------------------------------------------
11
+
12
+ export const AUTHIO_MESSAGES = {
13
+ network_error:
14
+ "We couldn't reach the sign-in service. Check your internet connection and try again.",
15
+ timeout:
16
+ "The sign-in service took too long to respond. Please try again.",
17
+ aborted: "The request was cancelled before it finished. Please try again.",
18
+ invalid_response:
19
+ "We couldn't finish signing you in because the sign-in service sent an unexpected response. Please try again.",
20
+ step_up_required:
21
+ "For your security, we need one more check before signing you in.",
22
+ sign_in_denied:
23
+ "We couldn't sign you in. If you think this is a mistake, contact support or your administrator.",
24
+ rate_limited: "Too many attempts. Please wait a moment and try again.",
25
+ server_error:
26
+ "Something went wrong on our side. Please try again in a moment.",
27
+ request_failed: "We couldn't complete that request. Please try again.",
28
+ webauthn_cancelled:
29
+ "Passkey sign-in was cancelled or timed out. Please try again.",
30
+ webauthn_registration_cancelled:
31
+ "Passkey setup was cancelled or timed out. Please try again.",
32
+ webauthn_already_registered:
33
+ "This device already has a passkey for your account.",
34
+ webauthn_unsupported:
35
+ "This browser doesn't support passkeys. Try a different browser, or sign in another way.",
36
+ not_signed_in: "You need to be signed in to do that. Please sign in and try again.",
37
+ token_rejected:
38
+ "We couldn't verify your sign-in. Please sign in again.",
39
+ } as const;
40
+
41
+ /** Attach the underlying error for debugging without exposing its text. */
42
+ function withCause<E extends Error>(err: E, cause: unknown): E {
43
+ if (cause !== undefined) {
44
+ Object.defineProperty(err, "cause", {
45
+ value: cause,
46
+ enumerable: false,
47
+ configurable: true,
48
+ writable: true,
49
+ });
50
+ }
51
+ return err;
52
+ }
53
+
5
54
  /**
6
55
  * Wrap a native fetch rejection (network error, abort, timeout) in
7
56
  * an `AuthioError` so consumers always get a typed `code` to switch
8
- * on. Already-typed `AuthioError` instances pass through unchanged.
57
+ * on and a readable `message`. Already-typed `AuthioError` instances
58
+ * pass through unchanged. The original error is kept on `cause`.
9
59
  */
10
60
  export function wrapFetchError(
11
61
  err: unknown,
12
62
  fallbackCode = "network_error",
13
63
  ): AuthioError {
14
64
  if (err instanceof AuthioError) return err;
15
- if (err instanceof Error && err.name === "AbortError") {
16
- return new AuthioError({
17
- code: "aborted",
18
- message: err.message || "Request aborted",
19
- status: 0,
65
+ // DOMException is not `instanceof Error` in every runtime, so read
66
+ // name/message structurally.
67
+ const e = (err && typeof err === "object" ? err : {}) as {
68
+ name?: unknown;
69
+ message?: unknown;
70
+ };
71
+ const name = typeof e.name === "string" ? e.name : "";
72
+ const rawMessage = typeof e.message === "string" ? e.message : "";
73
+ const isTimeout = name === "TimeoutError" || /timed? ?out/i.test(rawMessage);
74
+ if (isTimeout) {
75
+ return withCause(
76
+ new AuthioError({
77
+ code: "timeout",
78
+ message: AUTHIO_MESSAGES.timeout,
79
+ status: 0,
80
+ }),
81
+ err,
82
+ );
83
+ }
84
+ if (name === "AbortError") {
85
+ return withCause(
86
+ new AuthioError({
87
+ code: "aborted",
88
+ message: AUTHIO_MESSAGES.aborted,
89
+ status: 0,
90
+ }),
91
+ err,
92
+ );
93
+ }
94
+ const message =
95
+ fallbackCode === "network_error"
96
+ ? AUTHIO_MESSAGES.network_error
97
+ : AUTHIO_MESSAGES.request_failed;
98
+ return withCause(
99
+ new AuthioError({ code: fallbackCode, message, status: 0 }),
100
+ err,
101
+ );
102
+ }
103
+
104
+ /** Readable fallback when auth-core returned an error without a message. */
105
+ export function messageForStatus(status: number): string {
106
+ if (status === 429) return AUTHIO_MESSAGES.rate_limited;
107
+ if (status >= 500) return AUTHIO_MESSAGES.server_error;
108
+ return AUTHIO_MESSAGES.request_failed;
109
+ }
110
+
111
+ // ------------------------------------------------------------
112
+ // Risk-engine outcomes
113
+ // ------------------------------------------------------------
114
+
115
+ /**
116
+ * Thrown (code `step_up_required`) when auth-core's risk engine wants
117
+ * one more verification step before it will issue a session. No session
118
+ * exists yet. Send the user to `stepUpUrl` (the hosted step-up page) to
119
+ * finish signing in:
120
+ *
121
+ * ```ts
122
+ * catch (err) {
123
+ * if (err instanceof AuthioStepUpRequiredError && err.stepUpUrl) {
124
+ * window.location.assign(err.stepUpUrl);
125
+ * }
126
+ * }
127
+ * ```
128
+ *
129
+ * `stepUpUrl` is `undefined` on auth-core versions that predate the
130
+ * field or when no hosted UI is configured for the project.
131
+ */
132
+ export class AuthioStepUpRequiredError extends AuthioError {
133
+ readonly stepUpUrl?: string;
134
+ readonly challengeId?: string;
135
+ readonly requiredMethod?: string;
136
+ readonly reasons: string[];
137
+ readonly enrollmentRequired: boolean;
138
+ /** auth-core's own explanation of the step, when it sent one. */
139
+ readonly serverMessage?: string;
140
+
141
+ constructor(opts: {
142
+ status: number;
143
+ stepUpUrl?: string;
144
+ challengeId?: string;
145
+ requiredMethod?: string;
146
+ reasons?: string[];
147
+ enrollmentRequired?: boolean;
148
+ serverMessage?: string;
149
+ requestId?: string;
150
+ }) {
151
+ super({
152
+ code: "step_up_required",
153
+ message: AUTHIO_MESSAGES.step_up_required,
154
+ status: opts.status,
155
+ requestId: opts.requestId,
156
+ });
157
+ this.name = "AuthioStepUpRequiredError";
158
+ this.stepUpUrl = opts.stepUpUrl;
159
+ this.challengeId = opts.challengeId;
160
+ this.requiredMethod = opts.requiredMethod;
161
+ this.reasons = opts.reasons ?? [];
162
+ this.enrollmentRequired = Boolean(opts.enrollmentRequired);
163
+ this.serverMessage = opts.serverMessage;
164
+ }
165
+ }
166
+
167
+ /**
168
+ * Thrown (code `sign_in_denied`) when auth-core's risk engine or a
169
+ * project policy (country, network type, risk score) refuses the
170
+ * sign-in outright. `message` is auth-core's human-readable reason;
171
+ * `denyCode` is its stable machine code (e.g. `blocked_by_geo_policy`).
172
+ */
173
+ export class AuthioSignInDeniedError extends AuthioError {
174
+ readonly denyCode?: string;
175
+ readonly reasons: string[];
176
+
177
+ constructor(opts: {
178
+ status: number;
179
+ message?: string;
180
+ denyCode?: string;
181
+ reasons?: string[];
182
+ requestId?: string;
183
+ }) {
184
+ super({
185
+ code: "sign_in_denied",
186
+ message: nonEmpty(opts.message) ?? AUTHIO_MESSAGES.sign_in_denied,
187
+ status: opts.status,
188
+ requestId: opts.requestId,
189
+ });
190
+ this.name = "AuthioSignInDeniedError";
191
+ this.denyCode = opts.denyCode;
192
+ this.reasons = opts.reasons ?? [];
193
+ }
194
+ }
195
+
196
+ /** True when `err` is a step-up-required error from any SDK helper. */
197
+ export function isStepUpRequired(
198
+ err: unknown,
199
+ ): err is AuthioStepUpRequiredError {
200
+ return err instanceof AuthioStepUpRequiredError;
201
+ }
202
+
203
+ /** Wire shape of auth-core's risk fields (step_up / block bodies). */
204
+ export interface RiskDecisionBody {
205
+ decision?: string;
206
+ challenge_id?: string;
207
+ required_method?: string;
208
+ reasons?: unknown;
209
+ step_up_url?: string;
210
+ enrollment_required?: boolean;
211
+ message?: string;
212
+ code?: string;
213
+ error?: string;
214
+ request_id?: string;
215
+ }
216
+
217
+ /**
218
+ * Turn a risk-engine body into a typed error, or `null` when the body
219
+ * is not a step_up / deny decision. Used for both 2xx (step_up is a
220
+ * 200) and non-2xx (deny is a 403) responses.
221
+ */
222
+ export function riskDecisionError(
223
+ body: RiskDecisionBody | null | undefined,
224
+ status: number,
225
+ ): AuthioError | null {
226
+ if (!body || typeof body !== "object") return null;
227
+ const decision = typeof body.decision === "string" ? body.decision : "";
228
+ const reasons = Array.isArray(body.reasons)
229
+ ? body.reasons.filter((r): r is string => typeof r === "string")
230
+ : [];
231
+ if (decision === "step_up" || body.code === "step_up_required") {
232
+ return new AuthioStepUpRequiredError({
233
+ status,
234
+ stepUpUrl: nonEmpty(body.step_up_url),
235
+ challengeId: nonEmpty(body.challenge_id),
236
+ requiredMethod: nonEmpty(body.required_method),
237
+ reasons,
238
+ enrollmentRequired: body.enrollment_required === true,
239
+ serverMessage: nonEmpty(body.message),
240
+ requestId: body.request_id,
20
241
  });
21
242
  }
22
- if (err instanceof Error && /timeout/i.test(err.message)) {
23
- return new AuthioError({
24
- code: "timeout",
25
- message: err.message,
26
- status: 0,
243
+ if (decision === "block" || decision === "deny") {
244
+ return new AuthioSignInDeniedError({
245
+ status,
246
+ message: body.message,
247
+ denyCode: nonEmpty(body.code) ?? nonEmpty(body.error),
248
+ reasons,
249
+ requestId: body.request_id,
27
250
  });
28
251
  }
29
- const message = err instanceof Error ? err.message : "Unknown network error";
30
- return new AuthioError({
31
- code: fallbackCode,
32
- message,
33
- status: 0,
34
- });
252
+ return null;
253
+ }
254
+
255
+ function nonEmpty(v: unknown): string | undefined {
256
+ return typeof v === "string" && v.trim() !== "" ? v : undefined;
35
257
  }
package/src/fetch.ts CHANGED
@@ -1,5 +1,11 @@
1
1
  import { AuthioError } from "@useauthio/node";
2
- import { wrapFetchError } from "./errors";
2
+ import {
3
+ AUTHIO_MESSAGES,
4
+ messageForStatus,
5
+ riskDecisionError,
6
+ wrapFetchError,
7
+ type RiskDecisionBody,
8
+ } from "./errors";
3
9
  import { SDK_USER_AGENT } from "./version";
4
10
 
5
11
  const DEFAULT_TIMEOUT_MS = 10_000;
@@ -28,7 +34,10 @@ export interface AuthioFetchOptions {
28
34
  * - `application/json` content type; body is `JSON.stringify`'d.
29
35
  * - 2xx → parses JSON body (or returns undefined on 204).
30
36
  * - !2xx → reads the auth-core error envelope (`{ code, message }`)
31
- * and throws a typed `AuthioError`.
37
+ * and throws a typed `AuthioError`. Risk-engine denies (403
38
+ * `decision: "block"`) throw `AuthioSignInDeniedError`
39
+ * (`sign_in_denied`). When auth-core sends no message, a readable
40
+ * status-based message is used instead.
32
41
  * - Network / abort / timeout failures throw `AuthioError` via
33
42
  * `wrapFetchError`. Callers never see a raw `TypeError: fetch failed`.
34
43
  */
@@ -78,17 +87,19 @@ export async function authioFetch<T = unknown>(
78
87
  }
79
88
 
80
89
  if (!res.ok) {
81
- const body = (await res.json().catch(() => ({}))) as {
82
- code?: string;
83
- error?: string;
84
- message?: string;
85
- request_id?: string;
86
- };
90
+ const raw: unknown = await res.json().catch(() => ({}));
91
+ const body = (raw && typeof raw === "object" ? raw : {}) as RiskDecisionBody;
92
+ // Risk-engine deny (403 decision:"block") and 403 step-up variants
93
+ // become typed sign_in_denied / step_up_required errors.
94
+ const risk = riskDecisionError(body, res.status);
95
+ if (risk) throw risk;
96
+ const message =
97
+ typeof body.message === "string" && body.message.trim() !== ""
98
+ ? body.message
99
+ : messageForStatus(res.status);
87
100
  throw new AuthioError({
88
101
  code: body.code ?? body.error ?? "request_failed",
89
- message:
90
- body.message ??
91
- `Request to ${opts.path} failed with status ${res.status}`,
102
+ message,
92
103
  status: res.status,
93
104
  requestId: body.request_id,
94
105
  });
@@ -102,7 +113,7 @@ export async function authioFetch<T = unknown>(
102
113
  } catch {
103
114
  throw new AuthioError({
104
115
  code: "invalid_response",
105
- message: `Response from ${opts.path} was not valid JSON`,
116
+ message: AUTHIO_MESSAGES.invalid_response,
106
117
  status: res.status,
107
118
  });
108
119
  }
package/src/index.ts CHANGED
@@ -73,7 +73,14 @@ export {
73
73
  } from "./device-signals";
74
74
  export type { DeviceSignalsCapture } from "./device-signals";
75
75
 
76
- export { AuthioError, wrapFetchError } from "./errors";
76
+ export {
77
+ AuthioError,
78
+ AuthioStepUpRequiredError,
79
+ AuthioSignInDeniedError,
80
+ isStepUpRequired,
81
+ wrapFetchError,
82
+ AUTHIO_MESSAGES,
83
+ } from "./errors";
77
84
 
78
85
  export type {
79
86
  AuthioUser,
@@ -9,6 +9,8 @@ export interface MintLobbySignInUrlOptions {
9
9
  next?: string;
10
10
  /** Org scope for org_policies.disabled_methods on the Lobby surface. */
11
11
  organizationId?: string;
12
+ /** Opaque, consent-gated proof minted by @useauthio/xray. */
13
+ xrayVisitorProof?: string;
12
14
  fetchImpl?: typeof fetch;
13
15
  }
14
16
 
@@ -42,6 +44,9 @@ export async function mintLobbySignInUrl(
42
44
  ...(opts.organizationId
43
45
  ? { organization_id: opts.organizationId }
44
46
  : {}),
47
+ ...(opts.xrayVisitorProof
48
+ ? { xray_visitor_proof: opts.xrayVisitorProof }
49
+ : {}),
45
50
  }),
46
51
  },
47
52
  );
@@ -67,5 +72,8 @@ export async function mintLobbySignInUrl(
67
72
  if (opts.organizationId) {
68
73
  target.searchParams.set("organization_id", opts.organizationId);
69
74
  }
75
+ if (opts.xrayVisitorProof) {
76
+ target.searchParams.set("xray_visitor_proof", opts.xrayVisitorProof);
77
+ }
70
78
  return target.toString();
71
79
  }
package/src/passkeys.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  import { AuthioError } from "@useauthio/node";
2
2
  import { startRegistration } from "@simplewebauthn/browser";
3
3
  import { authioFetch } from "./fetch";
4
+ import { AUTHIO_MESSAGES } from "./errors";
4
5
  import { isBrowser } from "./ssr";
5
6
 
6
7
  export interface AuthioPasskey {
@@ -120,7 +121,8 @@ export async function enrollPasskey(opts: EnrollPasskeyOptions): Promise<void> {
120
121
  if (!isBrowser()) {
121
122
  throw new AuthioError({
122
123
  code: "not_in_browser",
123
- message: "enrollPasskey can only be invoked in a browser environment.",
124
+ message:
125
+ "Passkey setup only works in a web browser. Call enrollPasskey from client-side code.",
124
126
  status: 0,
125
127
  });
126
128
  }
@@ -150,7 +152,8 @@ export async function addPasskey(opts: AddPasskeyOptions): Promise<void> {
150
152
  if (!isBrowser()) {
151
153
  throw new AuthioError({
152
154
  code: "not_in_browser",
153
- message: "addPasskey can only be invoked in a browser environment.",
155
+ message:
156
+ "Passkey setup only works in a web browser. Call addPasskey from client-side code.",
154
157
  status: 0,
155
158
  });
156
159
  }
@@ -175,14 +178,21 @@ export async function addPasskey(opts: AddPasskeyOptions): Promise<void> {
175
178
  try {
176
179
  attestation = await startRegistration({ optionsJSON: options });
177
180
  } catch (err) {
178
- throw new AuthioError({
179
- code: "webauthn_cancelled",
180
- message:
181
- err instanceof Error
182
- ? err.message
183
- : "Passkey registration cancelled by user.",
181
+ // Browser/WebAuthn text is not user-friendly; keep it on `cause`.
182
+ const already =
183
+ err instanceof Error &&
184
+ (err.name === "InvalidStateError" ||
185
+ (err as { code?: string }).code ===
186
+ "ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED");
187
+ const e = new AuthioError({
188
+ code: already ? "webauthn_already_registered" : "webauthn_cancelled",
189
+ message: already
190
+ ? AUTHIO_MESSAGES.webauthn_already_registered
191
+ : AUTHIO_MESSAGES.webauthn_registration_cancelled,
184
192
  status: 0,
185
193
  });
194
+ Object.defineProperty(e, "cause", { value: err, enumerable: false });
195
+ throw e;
186
196
  }
187
197
 
188
198
  await authioFetch<{ ok?: boolean }>({
package/src/provider.tsx CHANGED
@@ -517,7 +517,8 @@ export function AuthioProvider(props: AuthioProviderProps): React.ReactElement {
517
517
  setStatus("unauthenticated");
518
518
  throw new AuthioError({
519
519
  code: "token_rejected",
520
- message: "Authio rejected the handed-off access token signature.",
520
+ message:
521
+ "We couldn't verify your sign-in. Please sign in again.",
521
522
  status: 0,
522
523
  });
523
524
  }