@smartcrab/react-native 0.1.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.
Files changed (96) hide show
  1. package/LICENSE +202 -0
  2. package/app.plugin.js +9 -0
  3. package/dist/adapters/expo-crypto-port.d.ts +3 -0
  4. package/dist/adapters/expo-crypto-port.js +8 -0
  5. package/dist/adapters/expo-linking-port.d.ts +3 -0
  6. package/dist/adapters/expo-linking-port.js +21 -0
  7. package/dist/adapters/expo-secure-store-port.d.ts +11 -0
  8. package/dist/adapters/expo-secure-store-port.js +15 -0
  9. package/dist/adapters/expo-web-browser-port.d.ts +7 -0
  10. package/dist/adapters/expo-web-browser-port.js +9 -0
  11. package/dist/adapters/react-native-app-state-port.d.ts +8 -0
  12. package/dist/adapters/react-native-app-state-port.js +13 -0
  13. package/dist/adapters/react-native-passkeys-adapter.d.ts +2 -0
  14. package/dist/adapters/react-native-passkeys-adapter.js +112 -0
  15. package/dist/adapters/react-native-passkeys-adapter.test.d.ts +1 -0
  16. package/dist/adapters/react-native-passkeys-adapter.test.js +76 -0
  17. package/dist/base64url.d.ts +20 -0
  18. package/dist/base64url.js +89 -0
  19. package/dist/base64url.test.d.ts +1 -0
  20. package/dist/base64url.test.js +36 -0
  21. package/dist/browser-port.d.ts +17 -0
  22. package/dist/browser-port.js +1 -0
  23. package/dist/client.d.ts +43 -0
  24. package/dist/client.js +871 -0
  25. package/dist/client.test.d.ts +1 -0
  26. package/dist/client.test.js +995 -0
  27. package/dist/context.d.ts +8 -0
  28. package/dist/context.js +17 -0
  29. package/dist/crypto-port.d.ts +16 -0
  30. package/dist/crypto-port.js +1 -0
  31. package/dist/errors.d.ts +113 -0
  32. package/dist/errors.js +82 -0
  33. package/dist/errors.test.d.ts +1 -0
  34. package/dist/errors.test.js +81 -0
  35. package/dist/hooks.d.ts +93 -0
  36. package/dist/hooks.js +191 -0
  37. package/dist/http.d.ts +41 -0
  38. package/dist/http.js +102 -0
  39. package/dist/index.d.ts +22 -0
  40. package/dist/index.js +29 -0
  41. package/dist/jwt.d.ts +1 -0
  42. package/dist/jwt.js +23 -0
  43. package/dist/lifecycle-ports.d.ts +29 -0
  44. package/dist/lifecycle-ports.js +1 -0
  45. package/dist/linking-port.d.ts +15 -0
  46. package/dist/linking-port.js +1 -0
  47. package/dist/passkey-adapter.d.ts +20 -0
  48. package/dist/passkey-adapter.js +1 -0
  49. package/dist/pkce.d.ts +32 -0
  50. package/dist/pkce.js +41 -0
  51. package/dist/pkce.test.d.ts +1 -0
  52. package/dist/pkce.test.js +66 -0
  53. package/dist/plugin.d.ts +89 -0
  54. package/dist/plugin.js +242 -0
  55. package/dist/plugin.test.d.ts +1 -0
  56. package/dist/plugin.test.js +210 -0
  57. package/dist/provider.d.ts +14 -0
  58. package/dist/provider.js +5 -0
  59. package/dist/secure-store.d.ts +54 -0
  60. package/dist/secure-store.js +55 -0
  61. package/dist/secure-store.test.d.ts +1 -0
  62. package/dist/secure-store.test.js +69 -0
  63. package/dist/types.d.ts +177 -0
  64. package/dist/types.js +1 -0
  65. package/package.json +69 -0
  66. package/src/adapters/expo-crypto-port.ts +11 -0
  67. package/src/adapters/expo-linking-port.ts +23 -0
  68. package/src/adapters/expo-secure-store-port.ts +20 -0
  69. package/src/adapters/expo-web-browser-port.ts +16 -0
  70. package/src/adapters/react-native-app-state-port.ts +15 -0
  71. package/src/adapters/react-native-passkeys-adapter.test.ts +87 -0
  72. package/src/adapters/react-native-passkeys-adapter.ts +138 -0
  73. package/src/base64url.test.ts +47 -0
  74. package/src/base64url.ts +92 -0
  75. package/src/browser-port.ts +19 -0
  76. package/src/client.test.ts +1275 -0
  77. package/src/client.ts +1329 -0
  78. package/src/context.ts +20 -0
  79. package/src/crypto-port.ts +16 -0
  80. package/src/errors.test.ts +94 -0
  81. package/src/errors.ts +216 -0
  82. package/src/hooks.ts +374 -0
  83. package/src/http.ts +159 -0
  84. package/src/index.ts +101 -0
  85. package/src/jwt.ts +24 -0
  86. package/src/lifecycle-ports.ts +32 -0
  87. package/src/linking-port.ts +16 -0
  88. package/src/passkey-adapter.ts +20 -0
  89. package/src/pkce.test.ts +84 -0
  90. package/src/pkce.ts +62 -0
  91. package/src/plugin.test.ts +303 -0
  92. package/src/plugin.ts +387 -0
  93. package/src/provider.tsx +20 -0
  94. package/src/secure-store.test.ts +91 -0
  95. package/src/secure-store.ts +102 -0
  96. package/src/types.ts +181 -0
@@ -0,0 +1,995 @@
1
+ import { describe, expect, test, vi } from "vitest";
2
+ import { base64UrlEncodeBytes } from "./base64url.js";
3
+ import { createReactNativeAuthClientFactory, normalizePasskeyException } from "./client.js";
4
+ import { ReactNativeAuthClientError } from "./errors.js";
5
+ import { pendingTransactionKey, refreshRecordKey } from "./secure-store.js";
6
+ // ---------------------------------------------------------------------------
7
+ // Test fixtures / fakes
8
+ // ---------------------------------------------------------------------------
9
+ /** `[a-z2-7]{32}` bodies throughout: the exact base32url charset `@smartcrab/identifiers`' `idPattern` requires. */
10
+ const fakeId = (prefix) => `${prefix}_${"a".repeat(32)}`;
11
+ const ENVIRONMENT_ID = "env_abcdefghijklmnopqrstuvwxyzabcdef";
12
+ const ISSUER = `https://id.example-auth.com/e/${ENVIRONMENT_ID}`;
13
+ const CLIENT_ID = fakeId("cli");
14
+ const REDIRECT_URI = "com.customer.app:/oauth/callback";
15
+ /** design.md §15.1: OAuth2 endpoints hang off the issuer verbatim, `/e/<environmentId>` path included. */
16
+ const TOKEN_PATH = `/e/${ENVIRONMENT_ID}/oauth2/token`;
17
+ const REVOKE_PATH = `/e/${ENVIRONMENT_ID}/oauth2/revoke`;
18
+ const base64UrlEncode = (text) => base64UrlEncodeBytes(new TextEncoder().encode(text));
19
+ /** An unsigned-but-well-shaped JWT: only the payload's `sub` claim matters to this client. */
20
+ const makeAccessToken = (sub) => `${base64UrlEncode(JSON.stringify({ alg: "ES256", typ: "at+jwt" }))}.${base64UrlEncode(JSON.stringify({ sub }))}.sig`;
21
+ const tokenResponseBody = (sub, refreshToken = "refresh-token-1") => ({
22
+ access_token: makeAccessToken(sub),
23
+ token_type: "Bearer",
24
+ expires_in: 300,
25
+ ...(refreshToken !== null ? { refresh_token: refreshToken } : {}),
26
+ scope: "openid profile email offline_access",
27
+ });
28
+ const jsonResponse = (status, body) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
29
+ const createFakeFetch = () => {
30
+ const calls = [];
31
+ const routes = new Map();
32
+ return {
33
+ calls,
34
+ on: (method, path, handler) => routes.set(`${method} ${path}`, handler),
35
+ fetchPort: async (url, init) => {
36
+ const method = init.method ?? "GET";
37
+ const rawPath = new URL(url).pathname;
38
+ const apiPrefix = `/e/${ENVIRONMENT_ID}`;
39
+ const path = rawPath.startsWith(`${apiPrefix}/v1`)
40
+ ? rawPath.slice(apiPrefix.length) || "/"
41
+ : rawPath;
42
+ const bodyText = typeof init.body === "string" ? init.body : undefined;
43
+ const body = bodyText !== undefined ? JSON.parse(bodyText) : undefined;
44
+ calls.push({ method, path, body });
45
+ const handler = routes.get(`${method} ${path}`);
46
+ if (handler === undefined) {
47
+ throw new Error(`Unhandled fake fetch route: ${method} ${path}`);
48
+ }
49
+ return handler(init);
50
+ },
51
+ };
52
+ };
53
+ const createFakeSecureStore = () => {
54
+ const store = new Map();
55
+ const writes = [];
56
+ return {
57
+ store,
58
+ writes,
59
+ getItemAsync: (key) => Promise.resolve(store.get(key) ?? null),
60
+ setItemAsync: (key, value) => {
61
+ store.set(key, value);
62
+ writes.push({ key, value });
63
+ return Promise.resolve();
64
+ },
65
+ deleteItemAsync: (key) => {
66
+ store.delete(key);
67
+ return Promise.resolve();
68
+ },
69
+ };
70
+ };
71
+ /**
72
+ * Deterministic, non-cryptographic fake. `sha256Base64` still returns a
73
+ * fixed-size (32-byte) digest stand-in — a real hash's defining property,
74
+ * and the one this file's endpoint-shape assertions rely on (a S256
75
+ * `code_challenge` is always 43 base64url chars) — it just isn't a *real*
76
+ * SHA-256. Real S256 correctness against ground truth is pkce.test.ts's job.
77
+ */
78
+ const fakePseudoDigest = (data) => {
79
+ const bytes = new Uint8Array(32);
80
+ for (let i = 0; i < data.length; i += 1) {
81
+ const index = i % 32;
82
+ bytes[index] = ((bytes[index] ?? 0) + data.charCodeAt(i)) % 256;
83
+ }
84
+ return bytes;
85
+ };
86
+ const fakeCrypto = {
87
+ getRandomBytes: (byteCount) => new Uint8Array(Array.from({ length: byteCount }, (_, i) => i % 256)),
88
+ sha256Base64: (data) => Promise.resolve(btoa(String.fromCharCode(...fakePseudoDigest(data)))),
89
+ };
90
+ const createFakePasskeyAdapter = (overrides) => ({
91
+ supported: overrides?.supported ?? true,
92
+ isSupported() {
93
+ return Promise.resolve(this.supported);
94
+ },
95
+ create: overrides?.create ??
96
+ (() => Promise.resolve(JSON.stringify({
97
+ id: "reg-id",
98
+ rawId: "reg-raw-id",
99
+ type: "public-key",
100
+ response: { clientDataJSON: "client-data", attestationObject: "attestation-obj" },
101
+ }))),
102
+ get: overrides?.get ??
103
+ (() => Promise.resolve(JSON.stringify({
104
+ id: "auth-id",
105
+ rawId: "auth-raw-id",
106
+ type: "public-key",
107
+ response: {
108
+ clientDataJSON: "client-data",
109
+ authenticatorData: "authenticator-data",
110
+ signature: "signature",
111
+ },
112
+ }))),
113
+ });
114
+ const createFakeBrowser = (result) => ({
115
+ openAuthSessionAsync: () => Promise.resolve(result),
116
+ });
117
+ const createFakeLinking = () => ({
118
+ parse: (url) => {
119
+ const parsed = new URL(url);
120
+ const queryParams = {};
121
+ parsed.searchParams.forEach((value, key) => {
122
+ queryParams[key] = value;
123
+ });
124
+ return { queryParams };
125
+ },
126
+ getInitialURL: () => Promise.resolve(null),
127
+ addEventListener: () => () => { },
128
+ });
129
+ const createFakeAppState = (initial) => {
130
+ let current = initial;
131
+ let handler = null;
132
+ return {
133
+ get currentState() {
134
+ return current;
135
+ },
136
+ addEventListener: (_type, h) => {
137
+ handler = h;
138
+ return { remove: () => (handler = null) };
139
+ },
140
+ trigger: (state) => {
141
+ current = state;
142
+ handler?.(state);
143
+ },
144
+ };
145
+ };
146
+ const createFakeNetworkStatus = () => {
147
+ let listener = null;
148
+ return {
149
+ subscribe: (l) => {
150
+ listener = l;
151
+ return () => (listener = null);
152
+ },
153
+ trigger: (online) => listener?.(online),
154
+ };
155
+ };
156
+ const flushMicrotasks = () => new Promise((resolve) => setTimeout(resolve, 10));
157
+ /**
158
+ * Every test's `harness.config` sets all six port fields explicitly, so
159
+ * `config.xxx ?? defaults.xxx` in `client.ts` always short-circuits to the
160
+ * left side — these "defaults" are structurally required by
161
+ * `createReactNativeAuthClientFactory` but never actually consulted here.
162
+ * Reusing the same fakes keeps this file from needing a `react-native`/
163
+ * `expo-*`-backed default (which would break `vitest`'s parser — see
164
+ * `client.ts`'s top doc comment).
165
+ */
166
+ const createReactNativeAuthClient = createReactNativeAuthClientFactory({
167
+ secureStore: createFakeSecureStore(),
168
+ passkeyAdapter: createFakePasskeyAdapter(),
169
+ browser: createFakeBrowser({ type: "dismiss" }),
170
+ linking: createFakeLinking(),
171
+ crypto: fakeCrypto,
172
+ appState: createFakeAppState("active"),
173
+ });
174
+ const createHarness = (overrides) => {
175
+ const fetch = createFakeFetch();
176
+ const secureStore = createFakeSecureStore();
177
+ const passkeyAdapter = createFakePasskeyAdapter({
178
+ supported: overrides?.passkeySupported ?? true,
179
+ });
180
+ const appState = createFakeAppState(overrides?.appStateInitial ?? "active");
181
+ const networkStatus = createFakeNetworkStatus();
182
+ const harness = {
183
+ fetch,
184
+ secureStore,
185
+ passkeyAdapter,
186
+ appState,
187
+ networkStatus,
188
+ browser: createFakeBrowser({ type: "success", url: REDIRECT_URI }),
189
+ config: {
190
+ issuer: ISSUER,
191
+ clientId: CLIENT_ID,
192
+ redirectUri: REDIRECT_URI,
193
+ fetch: fetch.fetchPort,
194
+ secureStore,
195
+ passkeyAdapter,
196
+ get browser() {
197
+ return harness.browser;
198
+ },
199
+ linking: createFakeLinking(),
200
+ crypto: fakeCrypto,
201
+ appState,
202
+ networkStatus,
203
+ now: () => 1_000_000,
204
+ },
205
+ };
206
+ return harness;
207
+ };
208
+ const seedRefreshRecord = async (harness, patch) => {
209
+ const record = {
210
+ refreshToken: "seeded-refresh-token",
211
+ familyId: "fam-1",
212
+ userId: fakeId("usr"),
213
+ scope: "openid profile email offline_access",
214
+ clientId: CLIENT_ID,
215
+ createdAt: 0,
216
+ lastRefreshedAt: 0,
217
+ ...patch,
218
+ };
219
+ await harness.secureStore.setItemAsync(refreshRecordKey(ENVIRONMENT_ID, CLIENT_ID), JSON.stringify(record));
220
+ };
221
+ // ---------------------------------------------------------------------------
222
+ // Exact endpoint calls + schema validation (design.md §16)
223
+ // ---------------------------------------------------------------------------
224
+ describe("signInWithPasskey", () => {
225
+ test("calls the exact §16 transaction + passkey endpoints with schema-validated payloads", async () => {
226
+ const harness = createHarness();
227
+ const client = createReactNativeAuthClient(harness.config);
228
+ const userId = fakeId("usr");
229
+ harness.fetch.on("POST", "/v1/auth/transactions", () => jsonResponse(200, {
230
+ transaction_id: fakeId("txn"),
231
+ expires_at: "2026-08-02T08:10:00Z",
232
+ available_methods: ["passkey", "email_otp"],
233
+ }));
234
+ harness.fetch.on("POST", `/v1/auth/transactions/${fakeId("txn")}/passkeys/authentication/options`, () => jsonResponse(200, {
235
+ challenge: "challenge-value",
236
+ rpId: "auth.example.com",
237
+ userVerification: "required",
238
+ }));
239
+ harness.fetch.on("POST", `/v1/auth/transactions/${fakeId("txn")}/passkeys/authentication/verify`, () => jsonResponse(200, { transaction_id: fakeId("txn"), status: "authenticated" }));
240
+ harness.fetch.on("POST", `/v1/auth/transactions/${fakeId("txn")}/complete`, (init) => {
241
+ const body = JSON.parse(String(init.body));
242
+ expect(body).toEqual({});
243
+ // The fake crypto is deterministic but this test doesn't need to predict
244
+ // the exact state value: echo back whatever the transaction-create call
245
+ // just sent, which is already recorded by the time `.../complete` runs.
246
+ const createCall = harness.fetch.calls.find((c) => c.method === "POST" && c.path === "/v1/auth/transactions");
247
+ const state = createCall?.body?.["state"];
248
+ return jsonResponse(200, {
249
+ authorization_code: fakeId("ac"),
250
+ state,
251
+ redirect_uri: REDIRECT_URI,
252
+ });
253
+ });
254
+ harness.fetch.on("POST", TOKEN_PATH, () => jsonResponse(200, tokenResponseBody(userId)));
255
+ const result = await client.signInWithPasskey();
256
+ expect(result.session.userId).toBe(userId);
257
+ expect(result.session.hasRefreshToken).toBe(true);
258
+ const createCall = harness.fetch.calls.find((c) => c.method === "POST" && c.path === "/v1/auth/transactions");
259
+ expect(createCall).toBeDefined();
260
+ const createBody = createCall?.body;
261
+ expect(createBody["client_id"]).toBe(CLIENT_ID);
262
+ expect(createBody["redirect_uri"]).toBe(REDIRECT_URI);
263
+ expect(createBody["code_challenge_method"]).toBe("S256");
264
+ expect(typeof createBody["code_challenge"]).toBe("string");
265
+ expect(createBody["code_challenge"]).toHaveLength(43);
266
+ expect(createBody["response_mode"]).toBe("native_return");
267
+ const tokenCall = harness.fetch.calls.find((c) => c.path === TOKEN_PATH);
268
+ const tokenBody = tokenCall?.body;
269
+ expect(tokenBody["grant_type"]).toBe("authorization_code");
270
+ expect(tokenBody["redirect_uri"]).toBe(REDIRECT_URI);
271
+ expect(tokenBody["client_id"]).toBe(CLIENT_ID);
272
+ });
273
+ });
274
+ describe("signInWithPasskey — passkey capability", () => {
275
+ test("rejects with passkey_not_supported and never calls the network when unsupported", async () => {
276
+ const harness = createHarness({ passkeySupported: false });
277
+ const client = createReactNativeAuthClient(harness.config);
278
+ await expect(client.signInWithPasskey()).rejects.toMatchObject({
279
+ code: { type: "passkey_not_supported" },
280
+ });
281
+ expect(harness.fetch.calls).toHaveLength(0);
282
+ expect(client.getSnapshot().passkeySupported).toBe(false);
283
+ });
284
+ test("normalizes a NotSupportedError from the native adapter to passkey_not_supported", async () => {
285
+ const harness = createHarness();
286
+ harness.passkeyAdapter.get = () => {
287
+ const error = new Error("no platform authenticator");
288
+ error.name = "NotSupportedError";
289
+ return Promise.reject(error);
290
+ };
291
+ harness.fetch.on("POST", "/v1/auth/transactions", () => jsonResponse(200, {
292
+ transaction_id: fakeId("txn"),
293
+ expires_at: "2026-08-02T08:10:00Z",
294
+ available_methods: ["passkey"],
295
+ }));
296
+ harness.fetch.on("POST", `/v1/auth/transactions/${fakeId("txn")}/passkeys/authentication/options`, () => jsonResponse(200, {
297
+ challenge: "challenge-value",
298
+ rpId: "auth.example.com",
299
+ userVerification: "required",
300
+ }));
301
+ const client = createReactNativeAuthClient(harness.config);
302
+ await expect(client.signInWithPasskey()).rejects.toMatchObject({
303
+ code: { type: "passkey_not_supported" },
304
+ });
305
+ });
306
+ test("normalizes a NotAllowedError (user cancellation) to passkey_error/cancelled", async () => {
307
+ const harness = createHarness();
308
+ harness.passkeyAdapter.get = () => {
309
+ const error = new Error("user dismissed the sheet");
310
+ error.name = "NotAllowedError";
311
+ return Promise.reject(error);
312
+ };
313
+ harness.fetch.on("POST", "/v1/auth/transactions", () => jsonResponse(200, {
314
+ transaction_id: fakeId("txn"),
315
+ expires_at: "2026-08-02T08:10:00Z",
316
+ available_methods: ["passkey"],
317
+ }));
318
+ harness.fetch.on("POST", `/v1/auth/transactions/${fakeId("txn")}/passkeys/authentication/options`, () => jsonResponse(200, {
319
+ challenge: "challenge-value",
320
+ rpId: "auth.example.com",
321
+ userVerification: "required",
322
+ }));
323
+ const client = createReactNativeAuthClient(harness.config);
324
+ await expect(client.signInWithPasskey()).rejects.toMatchObject({
325
+ code: { type: "passkey_error", reason: "cancelled" },
326
+ });
327
+ });
328
+ test("normalizes an unrecognized native exception to passkey_error/failed", async () => {
329
+ const harness = createHarness();
330
+ harness.passkeyAdapter.get = () => Promise.reject(new Error("boom"));
331
+ harness.fetch.on("POST", "/v1/auth/transactions", () => jsonResponse(200, {
332
+ transaction_id: fakeId("txn"),
333
+ expires_at: "2026-08-02T08:10:00Z",
334
+ available_methods: ["passkey"],
335
+ }));
336
+ harness.fetch.on("POST", `/v1/auth/transactions/${fakeId("txn")}/passkeys/authentication/options`, () => jsonResponse(200, {
337
+ challenge: "challenge-value",
338
+ rpId: "auth.example.com",
339
+ userVerification: "required",
340
+ }));
341
+ const client = createReactNativeAuthClient(harness.config);
342
+ await expect(client.signInWithPasskey()).rejects.toMatchObject({
343
+ code: { type: "passkey_error", reason: "failed" },
344
+ });
345
+ });
346
+ test("a malformed credential returned by the native adapter is rejected (never trusted blindly)", async () => {
347
+ const harness = createHarness();
348
+ harness.passkeyAdapter.get = () => Promise.resolve(JSON.stringify({ not: "a credential" }));
349
+ harness.fetch.on("POST", "/v1/auth/transactions", () => jsonResponse(200, {
350
+ transaction_id: fakeId("txn"),
351
+ expires_at: "2026-08-02T08:10:00Z",
352
+ available_methods: ["passkey"],
353
+ }));
354
+ harness.fetch.on("POST", `/v1/auth/transactions/${fakeId("txn")}/passkeys/authentication/options`, () => jsonResponse(200, {
355
+ challenge: "challenge-value",
356
+ rpId: "auth.example.com",
357
+ userVerification: "required",
358
+ }));
359
+ const client = createReactNativeAuthClient(harness.config);
360
+ await expect(client.signInWithPasskey()).rejects.toMatchObject({
361
+ code: { type: "passkey_error", reason: "failed" },
362
+ });
363
+ });
364
+ });
365
+ // ---------------------------------------------------------------------------
366
+ // Android react-native-passkeys rejections + ceremony guard (design.md §21.2)
367
+ // ---------------------------------------------------------------------------
368
+ describe("normalizePasskeyException", () => {
369
+ const error = (message, extra = {}) => Object.assign(new Error(message), extra);
370
+ test.each([
371
+ [
372
+ "Android UserCancelled",
373
+ error("UserCancelled"),
374
+ { type: "passkey_error", reason: "cancelled" },
375
+ ],
376
+ ["Android Interrupted", error("Interrupted"), { type: "passkey_error", reason: "cancelled" }],
377
+ [
378
+ "Android NoCredentials",
379
+ error("NoCredentials"),
380
+ { type: "passkey_error", reason: "cancelled" },
381
+ ],
382
+ [
383
+ "Android code-only signal",
384
+ error("boom", { code: "NotSupported" }),
385
+ { type: "passkey_not_supported" },
386
+ ],
387
+ ["Android NotSupported", error("NotSupported"), { type: "passkey_not_supported" }],
388
+ [
389
+ "Android NotConfigured keeps its message",
390
+ error("NotConfigured"),
391
+ { type: "passkey_error", reason: "failed", message: "NotConfigured" },
392
+ ],
393
+ ["Android UnknownError", error("UnknownError"), { type: "passkey_error", reason: "failed" }],
394
+ [
395
+ "Android DomError NotAllowedError",
396
+ error("DomError: NotAllowedError - The operation was cancelled"),
397
+ { type: "passkey_error", reason: "cancelled" },
398
+ ],
399
+ [
400
+ "Android DomError AbortError",
401
+ error("DomError: AbortError - Aborted"),
402
+ { type: "passkey_error", reason: "cancelled" },
403
+ ],
404
+ [
405
+ "Android DomError NotSupportedError",
406
+ error("DomError: NotSupportedError - Not supported"),
407
+ { type: "passkey_not_supported" },
408
+ ],
409
+ [
410
+ "Android DomError InvalidStateError",
411
+ error("DomError: InvalidStateError - Gone"),
412
+ { type: "passkey_error", reason: "failed" },
413
+ ],
414
+ [
415
+ "iOS NotAllowedError name",
416
+ error("native message", { name: "NotAllowedError" }),
417
+ { type: "passkey_error", reason: "cancelled" },
418
+ ],
419
+ [
420
+ "iOS AbortError name",
421
+ error("native message", { name: "AbortError" }),
422
+ { type: "passkey_error", reason: "cancelled" },
423
+ ],
424
+ [
425
+ "iOS NotSupportedError name",
426
+ error("native message", { name: "NotSupportedError" }),
427
+ { type: "passkey_not_supported" },
428
+ ],
429
+ ["non-Error cause", null, { type: "passkey_error", reason: "failed" }],
430
+ ])("%s", (_label, cause, expected) => {
431
+ expect(normalizePasskeyException(cause)).toMatchObject(expected);
432
+ });
433
+ test("an Android UserCancelled rejection surfaces end-to-end as cancelled", async () => {
434
+ const harness = createHarness();
435
+ harness.passkeyAdapter.get = () => Promise.reject(new Error("UserCancelled"));
436
+ harness.fetch.on("POST", "/v1/auth/transactions", () => jsonResponse(200, {
437
+ transaction_id: fakeId("txn"),
438
+ expires_at: "2026-08-02T08:10:00Z",
439
+ available_methods: ["passkey"],
440
+ }));
441
+ harness.fetch.on("POST", `/v1/auth/transactions/${fakeId("txn")}/passkeys/authentication/options`, () => jsonResponse(200, {
442
+ challenge: "challenge-value",
443
+ rpId: "auth.example.com",
444
+ userVerification: "required",
445
+ }));
446
+ const client = createReactNativeAuthClient(harness.config);
447
+ await expect(client.signInWithPasskey()).rejects.toMatchObject({
448
+ code: { type: "passkey_error", reason: "cancelled", message: "UserCancelled" },
449
+ });
450
+ });
451
+ });
452
+ describe("passkey ceremony guard", () => {
453
+ const wireSignInHappyPath = (harness, userId) => {
454
+ harness.fetch.on("POST", "/v1/auth/transactions", () => jsonResponse(200, {
455
+ transaction_id: fakeId("txn"),
456
+ expires_at: "2026-08-02T08:10:00Z",
457
+ available_methods: ["passkey"],
458
+ }));
459
+ harness.fetch.on("POST", `/v1/auth/transactions/${fakeId("txn")}/passkeys/authentication/options`, () => jsonResponse(200, {
460
+ challenge: "challenge-value",
461
+ rpId: "auth.example.com",
462
+ userVerification: "required",
463
+ }));
464
+ harness.fetch.on("POST", `/v1/auth/transactions/${fakeId("txn")}/passkeys/authentication/verify`, () => jsonResponse(200, { transaction_id: fakeId("txn"), status: "authenticated" }));
465
+ harness.fetch.on("POST", `/v1/auth/transactions/${fakeId("txn")}/complete`, (init) => {
466
+ const body = JSON.parse(String(init.body));
467
+ const createCall = harness.fetch.calls.find((c) => c.method === "POST" && c.path === "/v1/auth/transactions");
468
+ const state = createCall?.body?.["state"];
469
+ expect(body).toEqual({});
470
+ return jsonResponse(200, {
471
+ authorization_code: fakeId("ac"),
472
+ state,
473
+ redirect_uri: REDIRECT_URI,
474
+ });
475
+ });
476
+ harness.fetch.on("POST", TOKEN_PATH, () => jsonResponse(200, tokenResponseBody(userId)));
477
+ };
478
+ const authenticationCredentialJson = () => JSON.stringify({
479
+ id: "auth-id",
480
+ rawId: "auth-raw-id",
481
+ type: "public-key",
482
+ response: {
483
+ clientDataJSON: "client-data",
484
+ authenticatorData: "authenticator-data",
485
+ signature: "signature",
486
+ },
487
+ });
488
+ const optionsBodies = (harness) => harness.fetch.calls.filter((c) => c.path.endsWith("/options")).map((c) => c.body);
489
+ test("pins rp_id to the configured rpDomain on sign-in and registration options", async () => {
490
+ const harness = createHarness();
491
+ wireSignInHappyPath(harness, fakeId("usr"));
492
+ harness.fetch.on("POST", "/v1/me/passkeys/registration/options", () => jsonResponse(500, { error: "server_error" }));
493
+ const client = createReactNativeAuthClient({ ...harness.config, rpDomain: "rp.example.com" });
494
+ await client.signInWithPasskey();
495
+ await expect(client.registerPasskey()).rejects.toBeDefined();
496
+ expect(optionsBodies(harness)).toEqual([
497
+ { rp_id: "rp.example.com" },
498
+ { rp_id: "rp.example.com" },
499
+ ]);
500
+ });
501
+ test("omits rp_id when rpDomain is not configured", async () => {
502
+ const harness = createHarness();
503
+ wireSignInHappyPath(harness, fakeId("usr"));
504
+ const client = createReactNativeAuthClient(harness.config);
505
+ await client.signInWithPasskey();
506
+ expect(optionsBodies(harness)).toEqual([{}]);
507
+ });
508
+ test("two concurrent signInWithPasskey() run one native get; the second is in_progress", async () => {
509
+ const harness = createHarness();
510
+ const userId = fakeId("usr");
511
+ wireSignInHappyPath(harness, userId);
512
+ const gate = { resolve: null };
513
+ let getCalls = 0;
514
+ harness.passkeyAdapter.get = () => {
515
+ getCalls += 1;
516
+ return new Promise((resolve) => {
517
+ gate.resolve = resolve;
518
+ });
519
+ };
520
+ const client = createReactNativeAuthClient(harness.config);
521
+ const first = client.signInWithPasskey();
522
+ const second = client.signInWithPasskey();
523
+ await expect(second).rejects.toMatchObject({
524
+ code: { type: "passkey_error", reason: "in_progress" },
525
+ });
526
+ // The losing call settles as soon as it observes the flag while the
527
+ // winner is still walking its fetch chain — let it reach the native
528
+ // adapter before asserting exactly one native call ran.
529
+ await flushMicrotasks();
530
+ expect(getCalls).toBe(1);
531
+ if (gate.resolve === null)
532
+ throw new Error("native get was never invoked");
533
+ gate.resolve(authenticationCredentialJson());
534
+ const result = await first;
535
+ expect(result.session.userId).toBe(userId);
536
+ harness.passkeyAdapter.get = () => Promise.resolve(authenticationCredentialJson());
537
+ const again = await client.signInWithPasskey();
538
+ expect(again.session.userId).toBe(userId);
539
+ expect(getCalls).toBe(1);
540
+ });
541
+ });
542
+ // ---------------------------------------------------------------------------
543
+ // Email OTP flow + state mismatch
544
+ // ---------------------------------------------------------------------------
545
+ describe("sendEmailCode / verifyEmailCode", () => {
546
+ const wireUpHappyPath = (harness, userId) => {
547
+ harness.fetch.on("POST", "/v1/auth/transactions", () => jsonResponse(200, {
548
+ transaction_id: fakeId("txn"),
549
+ expires_at: "2026-08-02T08:10:00Z",
550
+ available_methods: ["email_otp"],
551
+ }));
552
+ harness.fetch.on("POST", `/v1/auth/transactions/${fakeId("txn")}/email/start`, (init) => {
553
+ const body = JSON.parse(String(init.body));
554
+ expect(body).toEqual({ email: "user@example.com" });
555
+ return jsonResponse(200, { challenge_id: "chal_1", expires_at: "2026-08-02T08:10:00Z" });
556
+ });
557
+ harness.fetch.on("POST", `/v1/auth/transactions/${fakeId("txn")}/email/verify`, (init) => {
558
+ const body = JSON.parse(String(init.body));
559
+ expect(body).toEqual({ challenge_id: "chal_1", code: "123456" });
560
+ return jsonResponse(200, { transaction_id: fakeId("txn"), status: "authenticated" });
561
+ });
562
+ harness.fetch.on("POST", TOKEN_PATH, () => jsonResponse(200, tokenResponseBody(userId)));
563
+ };
564
+ test("full round trip signs the user in and persists only the refresh token", async () => {
565
+ const harness = createHarness();
566
+ const userId = fakeId("usr");
567
+ wireUpHappyPath(harness, userId);
568
+ let capturedState = "";
569
+ harness.fetch.on("POST", `/v1/auth/transactions/${fakeId("txn")}/complete`, () => jsonResponse(200, {
570
+ authorization_code: fakeId("ac"),
571
+ state: capturedState,
572
+ redirect_uri: REDIRECT_URI,
573
+ }));
574
+ const client = createReactNativeAuthClient(harness.config);
575
+ const challenge = await client.sendEmailCode({ email: "user@example.com" });
576
+ expect(challenge.challengeId).toBe("chal_1");
577
+ const createCall = harness.fetch.calls.find((c) => c.path === "/v1/auth/transactions");
578
+ capturedState = (createCall?.body)["state"];
579
+ const result = await client.verifyEmailCode({
580
+ challengeId: challenge.challengeId,
581
+ code: "123456",
582
+ });
583
+ expect(result.session.userId).toBe(userId);
584
+ // design.md §21.6: only the refresh key was ever written, and its value
585
+ // never contains an access token.
586
+ expect([...harness.secureStore.store.keys()]).toEqual([
587
+ refreshRecordKey(ENVIRONMENT_ID, CLIENT_ID),
588
+ ]);
589
+ for (const write of harness.secureStore.writes) {
590
+ expect(write.value).not.toContain("access_token");
591
+ expect(JSON.parse(write.value)).not.toHaveProperty("accessToken");
592
+ }
593
+ });
594
+ test("verifyEmailCode with an unknown challengeId fails as invalid_flow_state, not a network call", async () => {
595
+ const harness = createHarness();
596
+ const client = createReactNativeAuthClient(harness.config);
597
+ await expect(client.verifyEmailCode({ challengeId: "never-requested", code: "123456" })).rejects.toMatchObject({
598
+ code: { type: "invalid_flow_state" },
599
+ });
600
+ });
601
+ test("state mismatch on the complete response rejects the callback (design.md §32.1)", async () => {
602
+ const harness = createHarness();
603
+ wireUpHappyPath(harness, fakeId("usr"));
604
+ harness.fetch.on("POST", `/v1/auth/transactions/${fakeId("txn")}/complete`, () => jsonResponse(200, {
605
+ authorization_code: fakeId("ac"),
606
+ state: "an-attacker-supplied-state",
607
+ redirect_uri: REDIRECT_URI,
608
+ }));
609
+ const client = createReactNativeAuthClient(harness.config);
610
+ const challenge = await client.sendEmailCode({ email: "user@example.com" });
611
+ await expect(client.verifyEmailCode({ challengeId: challenge.challengeId, code: "123456" })).rejects.toMatchObject({
612
+ code: { type: "state_mismatch" },
613
+ });
614
+ // The pending transaction is cleared even on failure, per this client's cleanup contract.
615
+ expect(harness.secureStore.store.has(pendingTransactionKey(ENVIRONMENT_ID, CLIENT_ID))).toBe(false);
616
+ });
617
+ test("a malformed email/start response is rejected, never silently accepted", async () => {
618
+ const harness = createHarness();
619
+ harness.fetch.on("POST", "/v1/auth/transactions", () => jsonResponse(200, {
620
+ transaction_id: fakeId("txn"),
621
+ expires_at: "2026-08-02T08:10:00Z",
622
+ available_methods: ["email_otp"],
623
+ }));
624
+ harness.fetch.on("POST", `/v1/auth/transactions/${fakeId("txn")}/email/start`, () => jsonResponse(200, { nonsense: true }));
625
+ const client = createReactNativeAuthClient(harness.config);
626
+ await expect(client.sendEmailCode({ email: "user@example.com" })).rejects.toMatchObject({
627
+ code: { type: "invalid_response" },
628
+ });
629
+ });
630
+ });
631
+ // ---------------------------------------------------------------------------
632
+ // Social sign-in: system browser only, callback state pre-check
633
+ // ---------------------------------------------------------------------------
634
+ describe("signInWithSocial", () => {
635
+ test("opens the system browser (never a WebView) and completes the transaction on success", async () => {
636
+ const harness = createHarness();
637
+ const userId = fakeId("usr");
638
+ harness.fetch.on("POST", "/v1/auth/transactions", () => jsonResponse(200, {
639
+ transaction_id: fakeId("txn"),
640
+ expires_at: "2026-08-02T08:10:00Z",
641
+ available_methods: ["google"],
642
+ }));
643
+ harness.fetch.on("POST", `/v1/auth/transactions/${fakeId("txn")}/social/google/start`, () => jsonResponse(200, { authorization_url: "https://accounts.google.com/authorize?x=1" }));
644
+ // Echoes back whatever state the transaction-create call just sent, exactly
645
+ // like the real server would (design.md §16.1's MAC-verified round trip) —
646
+ // this test does not need to predict the fake crypto's exact output.
647
+ harness.fetch.on("POST", `/v1/auth/transactions/${fakeId("txn")}/complete`, () => {
648
+ const createCall = harness.fetch.calls.find((c) => c.method === "POST" && c.path === "/v1/auth/transactions");
649
+ const state = createCall?.body?.["state"];
650
+ return jsonResponse(200, {
651
+ authorization_code: fakeId("ac"),
652
+ state,
653
+ redirect_uri: REDIRECT_URI,
654
+ });
655
+ });
656
+ harness.fetch.on("POST", TOKEN_PATH, () => jsonResponse(200, tokenResponseBody(userId)));
657
+ const openAuthSessionAsync = vi.fn((_url, redirectUrl) => Promise.resolve({
658
+ type: "success",
659
+ // The callback URL carries back the SAME state the client generated,
660
+ // matching how the platform's own social callback redirect behaves.
661
+ url: `${redirectUrl}?state=${harness.fetch.calls.find((c) => c.path === "/v1/auth/transactions")?.body?.["state"] ?? ""}`,
662
+ }));
663
+ harness.browser = { openAuthSessionAsync };
664
+ const client = createReactNativeAuthClient(harness.config);
665
+ const result = await client.signInWithSocial({ provider: "google" });
666
+ expect(result.session.userId).toBe(userId);
667
+ expect(openAuthSessionAsync).toHaveBeenCalledWith("https://accounts.google.com/authorize?x=1", REDIRECT_URI);
668
+ });
669
+ test("a mismatched state on the callback URL itself rejects before calling complete", async () => {
670
+ const harness = createHarness();
671
+ harness.fetch.on("POST", "/v1/auth/transactions", () => jsonResponse(200, {
672
+ transaction_id: fakeId("txn"),
673
+ expires_at: "2026-08-02T08:10:00Z",
674
+ available_methods: ["google"],
675
+ }));
676
+ harness.fetch.on("POST", `/v1/auth/transactions/${fakeId("txn")}/social/google/start`, () => jsonResponse(200, { authorization_url: "https://accounts.google.com/authorize?x=1" }));
677
+ let completeCalled = false;
678
+ harness.fetch.on("POST", `/v1/auth/transactions/${fakeId("txn")}/complete`, () => {
679
+ completeCalled = true;
680
+ return jsonResponse(200, {
681
+ authorization_code: fakeId("ac"),
682
+ state: "whatever",
683
+ redirect_uri: REDIRECT_URI,
684
+ });
685
+ });
686
+ harness.browser = createFakeBrowser({
687
+ type: "success",
688
+ url: `${REDIRECT_URI}?state=totally-wrong-state`,
689
+ });
690
+ const client = createReactNativeAuthClient(harness.config);
691
+ await expect(client.signInWithSocial({ provider: "google" })).rejects.toMatchObject({
692
+ code: { type: "state_mismatch" },
693
+ });
694
+ expect(completeCalled).toBe(false);
695
+ });
696
+ test("a success callback without state is rejected before calling complete", async () => {
697
+ const harness = createHarness();
698
+ harness.fetch.on("POST", "/v1/auth/transactions", () => jsonResponse(200, {
699
+ transaction_id: fakeId("txn"),
700
+ expires_at: "2026-08-02T08:10:00Z",
701
+ available_methods: ["google"],
702
+ }));
703
+ harness.fetch.on("POST", `/v1/auth/transactions/${fakeId("txn")}/social/google/start`, () => jsonResponse(200, { authorization_url: "https://accounts.google.com/authorize?x=1" }));
704
+ let completeCalled = false;
705
+ harness.fetch.on("POST", `/v1/auth/transactions/${fakeId("txn")}/complete`, () => {
706
+ completeCalled = true;
707
+ return jsonResponse(200, {
708
+ authorization_code: fakeId("ac"),
709
+ state: "whatever",
710
+ redirect_uri: REDIRECT_URI,
711
+ });
712
+ });
713
+ harness.browser = createFakeBrowser({ type: "success", url: REDIRECT_URI });
714
+ const client = createReactNativeAuthClient(harness.config);
715
+ await expect(client.signInWithSocial({ provider: "google" })).rejects.toMatchObject({
716
+ code: { type: "state_mismatch" },
717
+ });
718
+ expect(completeCalled).toBe(false);
719
+ });
720
+ test("a cancelled/dismissed browser session rejects as social_cancelled", async () => {
721
+ const harness = createHarness();
722
+ harness.fetch.on("POST", "/v1/auth/transactions", () => jsonResponse(200, {
723
+ transaction_id: fakeId("txn"),
724
+ expires_at: "2026-08-02T08:10:00Z",
725
+ available_methods: ["google"],
726
+ }));
727
+ harness.fetch.on("POST", `/v1/auth/transactions/${fakeId("txn")}/social/google/start`, () => jsonResponse(200, { authorization_url: "https://accounts.google.com/authorize?x=1" }));
728
+ harness.browser = createFakeBrowser({ type: "dismiss" });
729
+ const client = createReactNativeAuthClient(harness.config);
730
+ await expect(client.signInWithSocial({ provider: "google" })).rejects.toMatchObject({
731
+ code: { type: "social_cancelled" },
732
+ });
733
+ });
734
+ });
735
+ // ---------------------------------------------------------------------------
736
+ // Refresh: mutex, invalid_grant wipe, transient-failure preservation
737
+ // ---------------------------------------------------------------------------
738
+ describe("getAccessToken / refresh", () => {
739
+ test("concurrent calls are serialized through one refresh (token endpoint called exactly once)", async () => {
740
+ const harness = createHarness();
741
+ await seedRefreshRecord(harness);
742
+ let tokenCalls = 0;
743
+ harness.fetch.on("POST", TOKEN_PATH, () => {
744
+ tokenCalls += 1;
745
+ return jsonResponse(200, tokenResponseBody(fakeId("usr")));
746
+ });
747
+ const client = createReactNativeAuthClient(harness.config);
748
+ const [a, b, c] = await Promise.all([
749
+ client.getAccessToken(),
750
+ client.getAccessToken(),
751
+ client.getAccessToken(),
752
+ ]);
753
+ expect(tokenCalls).toBe(1);
754
+ expect(a).toBe(b);
755
+ expect(b).toBe(c);
756
+ });
757
+ test("separate clients sharing one SecureStore share the process-wide refresh grant", async () => {
758
+ const harness = createHarness();
759
+ await seedRefreshRecord(harness);
760
+ let tokenCalls = 0;
761
+ harness.fetch.on("POST", TOKEN_PATH, () => {
762
+ tokenCalls += 1;
763
+ return jsonResponse(200, tokenResponseBody(fakeId("usr")));
764
+ });
765
+ const firstClient = createReactNativeAuthClient(harness.config);
766
+ const secondClient = createReactNativeAuthClient({
767
+ ...harness.config,
768
+ secureStore: harness.secureStore,
769
+ });
770
+ const refreshes = Promise.all([firstClient.getAccessToken(), secondClient.getAccessToken()]);
771
+ await flushMicrotasks();
772
+ const [firstToken, secondToken] = await refreshes;
773
+ expect(tokenCalls).toBe(1);
774
+ expect(firstToken).toBe(secondToken);
775
+ expect(firstClient.getSnapshot().status).toBe("signed_in");
776
+ expect(secondClient.getSnapshot().status).toBe("signed_in");
777
+ });
778
+ test("invalid_grant fully destroys the local session (design.md §21.7)", async () => {
779
+ const harness = createHarness();
780
+ await seedRefreshRecord(harness);
781
+ harness.fetch.on("POST", TOKEN_PATH, () => jsonResponse(400, { error: "invalid_grant" }));
782
+ const client = createReactNativeAuthClient(harness.config);
783
+ await expect(client.getAccessToken()).rejects.toMatchObject({
784
+ code: { type: "oauth_error", code: "invalid_grant" },
785
+ });
786
+ expect(harness.secureStore.store.has(refreshRecordKey(ENVIRONMENT_ID, CLIENT_ID))).toBe(false);
787
+ expect(client.getSnapshot().status).toBe("signed_out");
788
+ });
789
+ test("a transient network failure does NOT wipe the persisted session (design.md §21.7)", async () => {
790
+ const harness = createHarness();
791
+ await seedRefreshRecord(harness);
792
+ harness.fetch.on("POST", TOKEN_PATH, () => Promise.reject(new Error("network down")));
793
+ const client = createReactNativeAuthClient(harness.config);
794
+ await expect(client.getAccessToken()).rejects.toMatchObject({
795
+ code: { type: "network_error" },
796
+ });
797
+ expect(harness.secureStore.store.has(refreshRecordKey(ENVIRONMENT_ID, CLIENT_ID))).toBe(true);
798
+ });
799
+ test("a 5xx server_error also does NOT wipe the persisted session", async () => {
800
+ const harness = createHarness();
801
+ await seedRefreshRecord(harness);
802
+ harness.fetch.on("POST", TOKEN_PATH, () => jsonResponse(500, { error: "server_error" }));
803
+ const client = createReactNativeAuthClient(harness.config);
804
+ await expect(client.getAccessToken()).rejects.toMatchObject({
805
+ code: { type: "oauth_error", code: "server_error" },
806
+ });
807
+ expect(harness.secureStore.store.has(refreshRecordKey(ENVIRONMENT_ID, CLIENT_ID))).toBe(true);
808
+ });
809
+ test("no persisted session resolves not_authenticated without any network call", async () => {
810
+ const harness = createHarness();
811
+ const client = createReactNativeAuthClient(harness.config);
812
+ await expect(client.getAccessToken()).rejects.toMatchObject({
813
+ code: { type: "not_authenticated" },
814
+ });
815
+ expect(harness.fetch.calls).toHaveLength(0);
816
+ });
817
+ });
818
+ // ---------------------------------------------------------------------------
819
+ // App lifecycle: foreground + network-recovery triggers
820
+ // ---------------------------------------------------------------------------
821
+ describe("app lifecycle (design.md §21.7)", () => {
822
+ test("returning to the foreground re-checks token expiry and refreshes when stale", async () => {
823
+ const harness = createHarness({ appStateInitial: "background" });
824
+ await seedRefreshRecord(harness);
825
+ let tokenCalls = 0;
826
+ harness.fetch.on("POST", TOKEN_PATH, () => {
827
+ tokenCalls += 1;
828
+ return jsonResponse(200, tokenResponseBody(fakeId("usr")));
829
+ });
830
+ const client = createReactNativeAuthClient(harness.config);
831
+ // Hydrate `currentSession` from storage first (getSession reads locally, no network).
832
+ await client.getSession();
833
+ harness.appState.trigger("active");
834
+ await flushMicrotasks();
835
+ expect(tokenCalls).toBe(1);
836
+ });
837
+ test("a repeated 'active' event (no background/foreground edge) does not trigger another refresh", async () => {
838
+ const harness = createHarness({ appStateInitial: "active" });
839
+ await seedRefreshRecord(harness);
840
+ let tokenCalls = 0;
841
+ harness.fetch.on("POST", TOKEN_PATH, () => {
842
+ tokenCalls += 1;
843
+ return jsonResponse(200, tokenResponseBody(fakeId("usr")));
844
+ });
845
+ const client = createReactNativeAuthClient(harness.config);
846
+ await client.getSession();
847
+ harness.appState.trigger("active");
848
+ await flushMicrotasks();
849
+ expect(tokenCalls).toBe(0);
850
+ });
851
+ test("network recovery triggers at most one refresh", async () => {
852
+ const harness = createHarness();
853
+ await seedRefreshRecord(harness);
854
+ let tokenCalls = 0;
855
+ harness.fetch.on("POST", TOKEN_PATH, () => {
856
+ tokenCalls += 1;
857
+ return jsonResponse(200, tokenResponseBody(fakeId("usr")));
858
+ });
859
+ const client = createReactNativeAuthClient(harness.config);
860
+ await client.getSession();
861
+ harness.networkStatus.trigger(false);
862
+ harness.networkStatus.trigger(true);
863
+ await flushMicrotasks();
864
+ // Firing "online" again without an intervening "offline" must not queue a second refresh.
865
+ harness.networkStatus.trigger(true);
866
+ await flushMicrotasks();
867
+ expect(tokenCalls).toBe(1);
868
+ });
869
+ test("without a signed-in session, lifecycle events never touch the network", async () => {
870
+ const harness = createHarness({ appStateInitial: "background" });
871
+ const client = createReactNativeAuthClient(harness.config);
872
+ void client; // constructed to wire lifecycle listeners; no session exists yet.
873
+ harness.appState.trigger("active");
874
+ harness.networkStatus.trigger(true);
875
+ await flushMicrotasks();
876
+ expect(harness.fetch.calls).toHaveLength(0);
877
+ });
878
+ });
879
+ // ---------------------------------------------------------------------------
880
+ // Self-service (/v1/me) endpoints
881
+ // ---------------------------------------------------------------------------
882
+ describe("self-service endpoints", () => {
883
+ test("listPasskeys / deletePasskey / listSessions / revokeSession call exact Bearer-authenticated routes", async () => {
884
+ const harness = createHarness();
885
+ await seedRefreshRecord(harness);
886
+ harness.fetch.on("POST", TOKEN_PATH, () => jsonResponse(200, tokenResponseBody(fakeId("usr"))));
887
+ harness.fetch.on("GET", "/v1/me/passkeys", () => jsonResponse(200, {
888
+ passkeys: [
889
+ {
890
+ passkey_id: fakeId("psk"),
891
+ name: "iPhone",
892
+ created_at: "2026-08-02T08:10:00Z",
893
+ last_used_at: null,
894
+ device_type: "multi_device",
895
+ backed_up: true,
896
+ },
897
+ ],
898
+ }));
899
+ harness.fetch.on("DELETE", `/v1/me/passkeys/${fakeId("psk")}`, () => jsonResponse(200, { passkey_id: fakeId("psk"), deleted: true }));
900
+ harness.fetch.on("GET", "/v1/me/sessions", () => jsonResponse(200, {
901
+ sessions: [
902
+ {
903
+ session_id: fakeId("ses"),
904
+ client_id: CLIENT_ID,
905
+ device_name: null,
906
+ created_at: "2026-08-02T08:10:00Z",
907
+ last_active_at: "2026-08-02T08:10:00Z",
908
+ current: true,
909
+ },
910
+ ],
911
+ }));
912
+ harness.fetch.on("DELETE", `/v1/me/sessions/${fakeId("ses")}`, () => jsonResponse(200, { session_id: fakeId("ses"), revoked: true }));
913
+ const client = createReactNativeAuthClient(harness.config);
914
+ const passkeys = await client.listPasskeys();
915
+ expect(passkeys).toEqual([
916
+ {
917
+ passkeyId: fakeId("psk"),
918
+ name: "iPhone",
919
+ createdAt: "2026-08-02T08:10:00Z",
920
+ lastUsedAt: null,
921
+ deviceType: "multi_device",
922
+ backedUp: true,
923
+ },
924
+ ]);
925
+ await client.deletePasskey(fakeId("psk"));
926
+ const sessions = await client.listSessions();
927
+ expect(sessions).toHaveLength(1);
928
+ await client.revokeSession(fakeId("ses"));
929
+ const authHeaders = harness.fetch.calls
930
+ .filter((c) => c.path.startsWith("/v1/me/"))
931
+ .map((c) => c.method + " " + c.path);
932
+ expect(authHeaders).toEqual([
933
+ "GET /v1/me/passkeys",
934
+ `DELETE /v1/me/passkeys/${fakeId("psk")}`,
935
+ "GET /v1/me/sessions",
936
+ `DELETE /v1/me/sessions/${fakeId("ses")}`,
937
+ ]);
938
+ });
939
+ test("registerPasskey requires an authenticated session", async () => {
940
+ const harness = createHarness();
941
+ const client = createReactNativeAuthClient(harness.config);
942
+ await expect(client.registerPasskey()).rejects.toMatchObject({
943
+ code: { type: "not_authenticated" },
944
+ });
945
+ });
946
+ test("signOut revokes the refresh token best-effort and always wipes locally", async () => {
947
+ const harness = createHarness();
948
+ await seedRefreshRecord(harness, { refreshToken: "to-be-revoked" });
949
+ let revokeBody = null;
950
+ harness.fetch.on("POST", REVOKE_PATH, (init) => {
951
+ revokeBody = JSON.parse(String(init.body));
952
+ return jsonResponse(200, {});
953
+ });
954
+ const client = createReactNativeAuthClient(harness.config);
955
+ await client.signOut();
956
+ expect(revokeBody).toMatchObject({ token: "to-be-revoked", token_type_hint: "refresh_token" });
957
+ expect(harness.secureStore.store.size).toBe(0);
958
+ expect(client.getSnapshot().status).toBe("signed_out");
959
+ });
960
+ test("signOut still wipes locally even when the revoke call fails (best-effort)", async () => {
961
+ const harness = createHarness();
962
+ await seedRefreshRecord(harness);
963
+ harness.fetch.on("POST", REVOKE_PATH, () => Promise.reject(new Error("network down")));
964
+ const client = createReactNativeAuthClient(harness.config);
965
+ await client.signOut();
966
+ expect(harness.secureStore.store.size).toBe(0);
967
+ });
968
+ });
969
+ // ---------------------------------------------------------------------------
970
+ // configure() / getSnapshot() / subscribe()
971
+ // ---------------------------------------------------------------------------
972
+ describe("configure / subscribe", () => {
973
+ test("throws not_configured when used before configure()", async () => {
974
+ const client = createReactNativeAuthClient();
975
+ await expect(client.getSession()).rejects.toBeInstanceOf(ReactNativeAuthClientError);
976
+ await expect(client.getSession()).rejects.toMatchObject({ code: { type: "not_configured" } });
977
+ });
978
+ test("notifies subscribers when the auth state changes", async () => {
979
+ const harness = createHarness();
980
+ await seedRefreshRecord(harness);
981
+ const client = createReactNativeAuthClient(harness.config);
982
+ const seen = [];
983
+ const unsubscribe = client.subscribe((snapshot) => seen.push(snapshot.status));
984
+ await client.getSession();
985
+ unsubscribe();
986
+ expect(seen).toContain("signed_in");
987
+ });
988
+ test("rejects an issuer that does not carry a parseable /e/<environmentId> segment", () => {
989
+ expect(() => createReactNativeAuthClient({
990
+ issuer: "https://id.example-auth.com",
991
+ clientId: CLIENT_ID,
992
+ redirectUri: REDIRECT_URI,
993
+ })).toThrow();
994
+ });
995
+ });