@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
package/src/client.ts ADDED
@@ -0,0 +1,1329 @@
1
+ import type {
2
+ AuthorizationCodeGrantRequest,
3
+ MeIdentityLinkRequest,
4
+ MePasskeyRegistrationVerifyRequest,
5
+ MeUpdateRequest,
6
+ MeUser,
7
+ Outcome,
8
+ PasskeyAuthenticationCredential,
9
+ PasskeyAuthenticationOptionsResponse,
10
+ PasskeyRegistrationCredential,
11
+ PasskeyRegistrationOptionsResponse,
12
+ PasskeySummary,
13
+ MeSessionSummary as WireDeviceSession,
14
+ RefreshTokenGrantRequest,
15
+ SocialProvider,
16
+ TokenResponse,
17
+ TransactionCreateRequest,
18
+ } from "@smartcrab/contracts-public";
19
+ import {
20
+ emailChallengeResponseSchema,
21
+ emailVerifyResponseSchema,
22
+ err,
23
+ meIdentityLinkResponseSchema,
24
+ mePasskeyDeleteResponseSchema,
25
+ mePasskeyRegistrationOptionsResponseSchema,
26
+ mePasskeyRegistrationVerifyResponseSchema,
27
+ mePasskeysListResponseSchema,
28
+ meSessionRevokeResponseSchema,
29
+ meSessionsListResponseSchema,
30
+ meSessionsRevokeAllResponseSchema,
31
+ meUpdateResponseSchema,
32
+ meUserSchema,
33
+ ok,
34
+ passkeyAuthenticationCredentialSchema,
35
+ passkeyAuthenticationOptionsResponseSchema,
36
+ passkeyAuthenticationVerifyResponseSchema,
37
+ passkeyRegistrationCredentialSchema,
38
+ revocationResponseSchema,
39
+ socialStartResponseSchema,
40
+ tokenResponseSchema,
41
+ transactionCompleteResponseSchema,
42
+ transactionCreateResponseSchema,
43
+ } from "@smartcrab/contracts-public";
44
+ import type { WebBrowserAuthResult, WebBrowserPort } from "./browser-port.js";
45
+ import type { CryptoPort } from "./crypto-port.js";
46
+ import type { ReactNativeAuthError } from "./errors.js";
47
+ import { ReactNativeAuthClientError } from "./errors.js";
48
+ import type { FetchPort, WireSchema } from "./http.js";
49
+ import { buildUrl, requestJson } from "./http.js";
50
+ import { base64UrlEncodeBytes } from "./base64url.js";
51
+ import { decodeJwtSubClaim } from "./jwt.js";
52
+ import type { AppStatePort, AppStateStatus, NetworkStatusPort } from "./lifecycle-ports.js";
53
+ import type { LinkingPort } from "./linking-port.js";
54
+ import { constantTimeEqual, generatePkcePair, generateState } from "./pkce.js";
55
+ import type { PkcePair } from "./pkce.js";
56
+ import type { PasskeyNativeAdapter } from "./passkey-adapter.js";
57
+ import type {
58
+ PersistedPendingTransaction,
59
+ PersistedRefreshRecord,
60
+ SecureStorePort,
61
+ } from "./secure-store.js";
62
+ import {
63
+ parsePersistedPendingTransaction,
64
+ parsePersistedRefreshRecord,
65
+ pendingTransactionKey,
66
+ refreshRecordKey,
67
+ } from "./secure-store.js";
68
+ import type {
69
+ AccessTokenRequest,
70
+ AuthResult,
71
+ AuthSession,
72
+ AuthStateListener,
73
+ AuthStateSnapshot,
74
+ DeviceSession,
75
+ EmailCodeChallenge,
76
+ Passkey,
77
+ ReactNativeAuthClient,
78
+ ReactNativeAuthConfig,
79
+ RegisterPasskeyInput,
80
+ UpdateUserProfileInput,
81
+ UserProfile,
82
+ } from "./types.js";
83
+
84
+ /**
85
+ * `createReactNativeAuthClient` (design.md §21.3, §21.8).
86
+ *
87
+ * ## Endpoint base resolution
88
+ *
89
+ * The SDK receives only the canonical issuer in its required configuration.
90
+ * OIDC endpoints use that issuer verbatim (`${issuer}/oauth2/*`, per §15.1).
91
+ * Headless `/v1/*` endpoints use the same canonical host and environment path
92
+ * (`${issuer}/v1/*`); the auth Worker resolves that path with the same
93
+ * environment-directory checks as the OIDC surface.
94
+ *
95
+ * ## Why this file imports no `expo-*`/`react-native`/`react-native-passkeys` module
96
+ *
97
+ * `react-native`'s own entry point (and several Expo modules) use Flow
98
+ * syntax that only Metro's Babel pipeline understands; a generic bundler
99
+ * (including Vite/Rolldown, which `vitest` uses) fails to even parse them.
100
+ * Since ES module graphs are resolved statically, merely having a *reachable*
101
+ * `import ... from "react-native"` anywhere client.ts pulls in — even one
102
+ * never actually exercised at runtime by a given test — breaks every test
103
+ * file that (transitively) imports this module. `createReactNativeAuthClient`
104
+ * (below) is therefore a *factory of factories*: this file exports
105
+ * `createReactNativeAuthClientFactory(defaults: NativePortDefaults)`, which
106
+ * knows nothing about any native module and takes its defaults purely as data;
107
+ * `index.ts` (the package's real public entry point, which tests never
108
+ * import) is the only place that imports the `adapters/*` modules and
109
+ * supplies the real defaults. Test files call the factory directly with fake
110
+ * ports instead (design.md §21's assignment notes: "mock every expo/react
111
+ * -native module via injected adapter boundaries").
112
+ *
113
+ * ## Internal error model
114
+ *
115
+ * Every internal step resolves to `Outcome<T, ReactNativeAuthError>` (no
116
+ * direct `try`/`catch` anywhere in this file — `scripts/check-backend-error
117
+ * -style.ts`, design.md §5.2, scans this package). `ReactNativeAuthClient`'s
118
+ * public methods match design.md §21.3's verbatim bare-`Promise<T>` /
119
+ * rejects-on-failure signatures; the one place a failed `Outcome` is turned
120
+ * into a thrown `ReactNativeAuthClientError` is the public-method boundary
121
+ * itself (`resolveOrThrow`), mirroring IMPL_NOTES §2's "境界では Result を
122
+ * 必ず解決する" applied to this SDK's own public surface.
123
+ */
124
+
125
+ const DEFAULT_SCOPES = ["openid", "profile", "email", "offline_access"] as const;
126
+
127
+ /** design.md §21.6: "期限60秒未満でrefreshする." */
128
+ const ACCESS_TOKEN_REFRESH_SKEW_MS = 60_000;
129
+
130
+ const ISSUER_PATTERN = /^(https:\/\/[^/]+)\/e\/([A-Za-z0-9_-]+)\/?$/;
131
+
132
+ const parseIssuer = (issuer: string): { origin: string; environmentId: string } | null => {
133
+ const match = ISSUER_PATTERN.exec(issuer);
134
+ if (match === null) return null;
135
+ const origin = match[1];
136
+ const environmentId = match[2];
137
+ if (origin === undefined || environmentId === undefined) return null;
138
+ return { origin, environmentId };
139
+ };
140
+
141
+ const normalizeResource = (resource: ReactNativeAuthConfig["resource"]): string[] | undefined => {
142
+ if (resource === undefined) return undefined;
143
+ return typeof resource === "string" ? [resource] : [...resource];
144
+ };
145
+
146
+ interface InMemoryAccessToken {
147
+ readonly token: string;
148
+ readonly expiresAt: number;
149
+ }
150
+
151
+ interface InMemorySession {
152
+ readonly userId: string;
153
+ readonly scope: string;
154
+ readonly familyId: string;
155
+ }
156
+
157
+ /** Internal, mutable per-client state. Never exported — only `client.ts` touches it. */
158
+ interface InternalContext {
159
+ readonly config: ReactNativeAuthConfig;
160
+ readonly apiBaseUrl: string;
161
+ readonly issuer: string;
162
+ readonly environmentId: string;
163
+ readonly scope: string;
164
+ readonly resource: string[] | undefined;
165
+ readonly fetchPort: FetchPort;
166
+ readonly now: () => number;
167
+ readonly secureStore: SecureStorePort;
168
+ readonly passkeyAdapter: PasskeyNativeAdapter;
169
+ readonly browser: WebBrowserPort;
170
+ readonly linking: LinkingPort;
171
+ readonly crypto: CryptoPort;
172
+ readonly appState: AppStatePort;
173
+ readonly networkStatus: NetworkStatusPort | undefined;
174
+ readonly refreshKey: string;
175
+ readonly pendingKey: string;
176
+ accessToken: InMemoryAccessToken | null;
177
+ currentSession: InMemorySession | null;
178
+ hasRefreshToken: boolean;
179
+ passkeySupported: boolean;
180
+ pendingTransaction: PersistedPendingTransaction | null;
181
+ refreshInFlight: Promise<Outcome<AuthSession, ReactNativeAuthError>> | null;
182
+ /**
183
+ * A passkey ceremony (options → native → verify) is running (design.md
184
+ * §21.2): a second concurrent ceremony resolves `passkey_error/in_progress`
185
+ * instead of racing the first through the native sheet.
186
+ */
187
+ passkeyInFlight: boolean;
188
+ readonly listeners: Set<AuthStateListener>;
189
+ snapshot: AuthStateSnapshot;
190
+ appStateSubscription: { remove(): void } | null;
191
+ networkStatusUnsubscribe: (() => void) | null;
192
+ lastAppState: AppStateStatus;
193
+ lastOnline: boolean;
194
+ }
195
+
196
+ // ---------------------------------------------------------------------------
197
+ // Snapshot / notification
198
+ // ---------------------------------------------------------------------------
199
+
200
+ const buildSnapshot = (ctx: InternalContext): AuthStateSnapshot => ({
201
+ status: ctx.currentSession !== null ? "signed_in" : "signed_out",
202
+ passkeySupported: ctx.passkeySupported,
203
+ hasRefreshToken: ctx.hasRefreshToken,
204
+ ...(ctx.accessToken !== null ? { accessTokenExpiresAt: ctx.accessToken.expiresAt } : {}),
205
+ ...(ctx.currentSession !== null ? { scope: ctx.currentSession.scope } : {}),
206
+ });
207
+
208
+ const notify = (ctx: InternalContext): void => {
209
+ ctx.snapshot = buildSnapshot(ctx);
210
+ for (const listener of ctx.listeners) {
211
+ listener(ctx.snapshot);
212
+ }
213
+ };
214
+
215
+ const toAuthSession = (ctx: InternalContext): AuthSession => {
216
+ if (ctx.currentSession === null) {
217
+ // Internal invariant: every caller of this checks `currentSession` first.
218
+ throw new Error("toAuthSession() called with no active session");
219
+ }
220
+ return {
221
+ userId: ctx.currentSession.userId,
222
+ scope: ctx.currentSession.scope,
223
+ hasRefreshToken: ctx.hasRefreshToken,
224
+ accessTokenExpiresAt: ctx.accessToken?.expiresAt ?? null,
225
+ };
226
+ };
227
+
228
+ const isExpiringSoon = (expiresAt: number, now: number): boolean =>
229
+ expiresAt - now < ACCESS_TOKEN_REFRESH_SKEW_MS;
230
+
231
+ // ---------------------------------------------------------------------------
232
+ // Passkey capability + ceremony
233
+ // ---------------------------------------------------------------------------
234
+
235
+ const checkPasskeySupport = async (ctx: InternalContext): Promise<boolean> => {
236
+ const supported = await ctx.passkeyAdapter.isSupported();
237
+ const changed = supported !== ctx.passkeySupported;
238
+ ctx.passkeySupported = supported;
239
+ if (changed) notify(ctx);
240
+ return supported;
241
+ };
242
+
243
+ const errorMessage = (cause: unknown): string =>
244
+ cause instanceof Error ? cause.message : "Unknown passkey ceremony failure";
245
+
246
+ /**
247
+ * Normalizes a native `react-native-passkeys` (or DOMException-like) exception (design.md §21.2).
248
+ *
249
+ * iOS/web reject with a DOMException-like `.name`. Android
250
+ * (`react-native-passkeys@0.4.1`) rejects through Expo's
251
+ * `promise.reject(code, message)`: a plain `Error` whose `message` is one of
252
+ * `UserCancelled`/`Interrupted`/`NotConfigured`/`UnknownError`/`NotSupported`/
253
+ * `NoCredentials`, or `DomError: <DOMExceptionName> - <text>`; `.code` may
254
+ * carry the same signal, so both are matched.
255
+ *
256
+ * `NotConfigured` (a broken assetlinks/provider setup) is deliberately NOT
257
+ * `passkey_not_supported`: it falls through to `passkey_error/failed` with
258
+ * the native message preserved so the misconfiguration stays diagnosable.
259
+ */
260
+ export const normalizePasskeyException = (cause: unknown): ReactNativeAuthError => {
261
+ const signals = [
262
+ ...(cause instanceof Error ? [cause.name] : []),
263
+ ...androidRejectionSignals(cause),
264
+ ];
265
+ if (signals.some((signal) => NOT_SUPPORTED_SIGNAL.test(signal))) {
266
+ return { type: "passkey_not_supported" };
267
+ }
268
+ if (signals.some((signal) => CANCELLED_SIGNAL.test(signal))) {
269
+ return { type: "passkey_error", reason: "cancelled", message: errorMessage(cause) };
270
+ }
271
+ return { type: "passkey_error", reason: "failed", message: errorMessage(cause) };
272
+ };
273
+
274
+ const NOT_SUPPORTED_SIGNAL = /^(NotSupportedError|NotSupported)$|^DomError: NotSupportedError\b/;
275
+ const CANCELLED_SIGNAL =
276
+ /^(NotAllowedError|AbortError|UserCancelled|Interrupted|NoCredentials)$|^DomError: (NotAllowedError|AbortError)\b/;
277
+
278
+ /** `message` and `.code` of an Expo `promise.reject(code, message)` rejection, as plain strings. */
279
+ const androidRejectionSignals = (cause: unknown): readonly string[] => {
280
+ if (typeof cause === "string") return [cause];
281
+ if (typeof cause !== "object" || cause === null) return [];
282
+ const signals: string[] = [];
283
+ if ("message" in cause && typeof cause.message === "string") signals.push(cause.message);
284
+ if ("code" in cause && typeof cause.code === "string") signals.push(cause.code);
285
+ return signals;
286
+ };
287
+
288
+ const parsePasskeyCredentialJson = async <T>(
289
+ json: string,
290
+ schema: WireSchema<T>,
291
+ ): Promise<Outcome<T, ReactNativeAuthError>> =>
292
+ Promise.resolve()
293
+ .then((): unknown => JSON.parse(json))
294
+ .then(
295
+ (parsed) => {
296
+ const result = schema.safeParse(parsed);
297
+ if (!result.success) {
298
+ return err<T, ReactNativeAuthError>({
299
+ type: "passkey_error",
300
+ reason: "failed",
301
+ message:
302
+ "Native passkey adapter returned a credential that did not match the expected shape",
303
+ });
304
+ }
305
+ return ok<T, ReactNativeAuthError>(result.data);
306
+ },
307
+ () =>
308
+ err<T, ReactNativeAuthError>({
309
+ type: "passkey_error",
310
+ reason: "failed",
311
+ message: "Native passkey adapter returned invalid JSON",
312
+ }),
313
+ );
314
+
315
+ const runPasskeyCreate = async (
316
+ ctx: InternalContext,
317
+ options: PasskeyRegistrationOptionsResponse,
318
+ ): Promise<Outcome<PasskeyRegistrationCredential, ReactNativeAuthError>> => {
319
+ const rawOutcome = await Promise.resolve()
320
+ .then(() => ctx.passkeyAdapter.create(JSON.stringify(options)))
321
+ .then(
322
+ (json) => ok<string, ReactNativeAuthError>(json),
323
+ (cause: unknown) => err<string, ReactNativeAuthError>(normalizePasskeyException(cause)),
324
+ );
325
+ if (!rawOutcome.ok) return rawOutcome;
326
+ return parsePasskeyCredentialJson(rawOutcome.value, passkeyRegistrationCredentialSchema);
327
+ };
328
+
329
+ const runPasskeyGet = async (
330
+ ctx: InternalContext,
331
+ options: PasskeyAuthenticationOptionsResponse,
332
+ ): Promise<Outcome<PasskeyAuthenticationCredential, ReactNativeAuthError>> => {
333
+ const rawOutcome = await Promise.resolve()
334
+ .then(() => ctx.passkeyAdapter.get(JSON.stringify(options)))
335
+ .then(
336
+ (json) => ok<string, ReactNativeAuthError>(json),
337
+ (cause: unknown) => err<string, ReactNativeAuthError>(normalizePasskeyException(cause)),
338
+ );
339
+ if (!rawOutcome.ok) return rawOutcome;
340
+ return parsePasskeyCredentialJson(rawOutcome.value, passkeyAuthenticationCredentialSchema);
341
+ };
342
+
343
+ // ---------------------------------------------------------------------------
344
+ // SecureStore-backed persistence
345
+ // ---------------------------------------------------------------------------
346
+
347
+ const loadRefreshRecord = async (ctx: InternalContext): Promise<PersistedRefreshRecord | null> => {
348
+ const raw = await ctx.secureStore.getItemAsync(ctx.refreshKey);
349
+ if (raw === null) return null;
350
+ return Promise.resolve()
351
+ .then((): unknown => JSON.parse(raw))
352
+ .then(
353
+ (parsed) => parsePersistedRefreshRecord(parsed),
354
+ () => null,
355
+ );
356
+ };
357
+
358
+ const saveRefreshRecord = async (
359
+ ctx: InternalContext,
360
+ record: PersistedRefreshRecord,
361
+ ): Promise<void> => {
362
+ await ctx.secureStore.setItemAsync(ctx.refreshKey, JSON.stringify(record));
363
+ ctx.hasRefreshToken = true;
364
+ };
365
+
366
+ const loadPendingTransaction = async (
367
+ ctx: InternalContext,
368
+ ): Promise<PersistedPendingTransaction | null> => {
369
+ if (ctx.pendingTransaction !== null) return ctx.pendingTransaction;
370
+ const raw = await ctx.secureStore.getItemAsync(ctx.pendingKey);
371
+ if (raw === null) return null;
372
+ const parsed = await Promise.resolve()
373
+ .then((): unknown => JSON.parse(raw))
374
+ .then(
375
+ (value) => parsePersistedPendingTransaction(value),
376
+ () => null,
377
+ );
378
+ if (parsed !== null) ctx.pendingTransaction = parsed;
379
+ return parsed;
380
+ };
381
+
382
+ const savePendingTransaction = async (
383
+ ctx: InternalContext,
384
+ pending: PersistedPendingTransaction,
385
+ ): Promise<void> => {
386
+ ctx.pendingTransaction = pending;
387
+ await ctx.secureStore.setItemAsync(ctx.pendingKey, JSON.stringify(pending));
388
+ };
389
+
390
+ const clearPendingTransaction = async (ctx: InternalContext): Promise<void> => {
391
+ ctx.pendingTransaction = null;
392
+ await ctx.secureStore.deleteItemAsync(ctx.pendingKey);
393
+ };
394
+
395
+ /** Full local session destruction (design.md §21.7: `invalid_grant` -> wipe entirely). */
396
+ const wipeSession = async (ctx: InternalContext): Promise<void> => {
397
+ ctx.accessToken = null;
398
+ ctx.currentSession = null;
399
+ ctx.hasRefreshToken = false;
400
+ await ctx.secureStore.deleteItemAsync(ctx.refreshKey);
401
+ notify(ctx);
402
+ };
403
+
404
+ const generateFamilyId = (ctx: InternalContext): string =>
405
+ base64UrlEncodeBytes(ctx.crypto.getRandomBytes(16));
406
+
407
+ /** Applies a successful token response to in-memory + persisted state (design.md §21.6). */
408
+ const applySession = async (
409
+ ctx: InternalContext,
410
+ tokenResponse: TokenResponse,
411
+ familyId: string,
412
+ ): Promise<Outcome<AuthSession, ReactNativeAuthError>> => {
413
+ const subOutcome = await Promise.resolve()
414
+ .then(() => decodeJwtSubClaim(tokenResponse.access_token))
415
+ .then(
416
+ (sub) => ok<string | null, ReactNativeAuthError>(sub),
417
+ () =>
418
+ err<string | null, ReactNativeAuthError>({
419
+ type: "invalid_response",
420
+ message: "access token is not a decodable JWT",
421
+ }),
422
+ );
423
+ if (!subOutcome.ok) return subOutcome;
424
+ if (subOutcome.value === null) {
425
+ return err({ type: "invalid_response", message: "access token is missing a `sub` claim" });
426
+ }
427
+ const userId = subOutcome.value;
428
+ const nowMs = ctx.now();
429
+ ctx.accessToken = {
430
+ token: tokenResponse.access_token,
431
+ expiresAt: nowMs + tokenResponse.expires_in * 1000,
432
+ };
433
+ ctx.currentSession = { userId, scope: tokenResponse.scope, familyId };
434
+ if (tokenResponse.refresh_token !== undefined) {
435
+ const existing = await loadRefreshRecord(ctx);
436
+ const record: PersistedRefreshRecord = {
437
+ refreshToken: tokenResponse.refresh_token,
438
+ familyId,
439
+ userId,
440
+ scope: tokenResponse.scope,
441
+ clientId: ctx.config.clientId,
442
+ createdAt: existing?.createdAt ?? nowMs,
443
+ lastRefreshedAt: nowMs,
444
+ };
445
+ await saveRefreshRecord(ctx, record);
446
+ }
447
+ const session = toAuthSession(ctx);
448
+ notify(ctx);
449
+ return ok(session);
450
+ };
451
+
452
+ // ---------------------------------------------------------------------------
453
+ // Refresh (design.md §21.6, §21.7): process-wide mutex per refresh key
454
+ // ---------------------------------------------------------------------------
455
+
456
+ interface RefreshResult {
457
+ readonly familyId: string;
458
+ readonly tokenResponse: TokenResponse;
459
+ readonly session: AuthSession;
460
+ }
461
+
462
+ interface RefreshFlight {
463
+ readonly client: InternalContext;
464
+ readonly promise: Promise<Outcome<RefreshResult, ReactNativeAuthError>>;
465
+ }
466
+
467
+ const refreshFlightsByKey = new Map<string, RefreshFlight>();
468
+
469
+ const performRefresh = async (
470
+ ctx: InternalContext,
471
+ ): Promise<Outcome<RefreshResult, ReactNativeAuthError>> => {
472
+ const record = await loadRefreshRecord(ctx);
473
+ if (record === null) return err({ type: "not_authenticated" });
474
+
475
+ const body: RefreshTokenGrantRequest = {
476
+ grant_type: "refresh_token",
477
+ refresh_token: record.refreshToken,
478
+ client_id: ctx.config.clientId,
479
+ };
480
+ const outcome = await requestJson(
481
+ ctx.fetchPort,
482
+ { method: "POST", url: `${ctx.issuer}/oauth2/token`, body },
483
+ tokenResponseSchema,
484
+ );
485
+ if (!outcome.ok) {
486
+ if (outcome.error.type === "oauth_error" && outcome.error.code === "invalid_grant") {
487
+ // design.md §21.7: "refresh 失敗が invalid_grant なら local session を完全削除."
488
+ await wipeSession(ctx);
489
+ }
490
+ // Every other failure (network_error, invalid_response, rate_limited,
491
+ // server_error/temporarily_unavailable) is transient: the persisted
492
+ // refresh token is left untouched (design.md §21.7).
493
+ return outcome;
494
+ }
495
+
496
+ const sessionOutcome = await applySession(ctx, outcome.value, record.familyId);
497
+ if (!sessionOutcome.ok) return sessionOutcome;
498
+ return ok({
499
+ familyId: record.familyId,
500
+ tokenResponse: outcome.value,
501
+ session: sessionOutcome.value,
502
+ });
503
+ };
504
+
505
+ const getOrStartRefreshFlight = (ctx: InternalContext): RefreshFlight => {
506
+ const current = refreshFlightsByKey.get(ctx.refreshKey);
507
+ if (current !== undefined) return current;
508
+
509
+ const promise = performRefresh(ctx).finally(() => {
510
+ if (refreshFlightsByKey.get(ctx.refreshKey)?.client === ctx) {
511
+ refreshFlightsByKey.delete(ctx.refreshKey);
512
+ }
513
+ });
514
+ const flight = { client: ctx, promise };
515
+ refreshFlightsByKey.set(ctx.refreshKey, flight);
516
+ return flight;
517
+ };
518
+
519
+ const performSharedRefresh = async (
520
+ ctx: InternalContext,
521
+ ): Promise<Outcome<AuthSession, ReactNativeAuthError>> => {
522
+ const flight = getOrStartRefreshFlight(ctx);
523
+ const outcome = await flight.promise;
524
+ if (!outcome.ok) {
525
+ if (
526
+ flight.client !== ctx &&
527
+ outcome.error.type === "oauth_error" &&
528
+ outcome.error.code === "invalid_grant"
529
+ ) {
530
+ await wipeSession(ctx);
531
+ }
532
+ return outcome;
533
+ }
534
+ if (flight.client === ctx) return ok(outcome.value.session);
535
+ return applySession(ctx, outcome.value.tokenResponse, outcome.value.familyId);
536
+ };
537
+
538
+ /**
539
+ * Serializes refresh attempts across client instances that share the same
540
+ * Environment/client SecureStore key. Each waiting instance applies the
541
+ * returned token response to its own in-memory session after the shared grant
542
+ * has been persisted by the request owner.
543
+ */
544
+ const ensureFreshAccessToken = (
545
+ ctx: InternalContext,
546
+ forceRefresh: boolean,
547
+ ): Promise<Outcome<AuthSession, ReactNativeAuthError>> => {
548
+ if (
549
+ !forceRefresh &&
550
+ ctx.accessToken !== null &&
551
+ !isExpiringSoon(ctx.accessToken.expiresAt, ctx.now())
552
+ ) {
553
+ return Promise.resolve(ok(toAuthSession(ctx)));
554
+ }
555
+ if (ctx.refreshInFlight !== null) return ctx.refreshInFlight;
556
+ const inFlight = performSharedRefresh(ctx).finally(() => {
557
+ ctx.refreshInFlight = null;
558
+ });
559
+ ctx.refreshInFlight = inFlight;
560
+ return inFlight;
561
+ };
562
+
563
+ const withAccessToken = async <T>(
564
+ ctx: InternalContext,
565
+ fn: (accessToken: string) => Promise<Outcome<T, ReactNativeAuthError>>,
566
+ ): Promise<Outcome<T, ReactNativeAuthError>> => {
567
+ const tokenOutcome = await ensureFreshAccessToken(ctx, false);
568
+ if (!tokenOutcome.ok) return tokenOutcome;
569
+ if (ctx.accessToken === null) return err({ type: "not_authenticated" });
570
+ return fn(ctx.accessToken.token);
571
+ };
572
+
573
+ // ---------------------------------------------------------------------------
574
+ // Transaction lifecycle (design.md §16, §20.6)
575
+ // ---------------------------------------------------------------------------
576
+
577
+ interface BegunTransaction {
578
+ readonly transactionId: string;
579
+ readonly pkce: PkcePair;
580
+ readonly state: string;
581
+ }
582
+
583
+ const beginTransaction = async (
584
+ ctx: InternalContext,
585
+ ): Promise<Outcome<BegunTransaction, ReactNativeAuthError>> => {
586
+ const pkce = await generatePkcePair(ctx.crypto);
587
+ const state = generateState(ctx.crypto);
588
+ const body: TransactionCreateRequest = {
589
+ client_id: ctx.config.clientId,
590
+ redirect_uri: ctx.config.redirectUri,
591
+ code_challenge: pkce.challenge,
592
+ code_challenge_method: "S256",
593
+ state,
594
+ scope: ctx.scope,
595
+ ...(ctx.resource !== undefined ? { resource: ctx.resource } : {}),
596
+ response_mode: "native_return",
597
+ };
598
+ const outcome = await requestJson(
599
+ ctx.fetchPort,
600
+ { method: "POST", url: buildUrl(ctx.apiBaseUrl, "/v1/auth/transactions"), body },
601
+ transactionCreateResponseSchema,
602
+ );
603
+ if (!outcome.ok) return outcome;
604
+ return ok({ transactionId: outcome.value.transaction_id, pkce, state });
605
+ };
606
+
607
+ /** `.../complete` + code exchange, shared by every sign-in path (design.md §16.3). */
608
+ const completeAndExchange = async (
609
+ ctx: InternalContext,
610
+ transactionId: string,
611
+ expectedState: string,
612
+ codeVerifier: string,
613
+ ): Promise<Outcome<TokenResponse, ReactNativeAuthError>> => {
614
+ const completeOutcome = await requestJson(
615
+ ctx.fetchPort,
616
+ {
617
+ method: "POST",
618
+ url: buildUrl(ctx.apiBaseUrl, `/v1/auth/transactions/${transactionId}/complete`),
619
+ body: {},
620
+ },
621
+ transactionCompleteResponseSchema,
622
+ );
623
+ if (!completeOutcome.ok) return completeOutcome;
624
+ if (!constantTimeEqual(completeOutcome.value.state, expectedState)) {
625
+ return err({ type: "state_mismatch" });
626
+ }
627
+ const body: AuthorizationCodeGrantRequest = {
628
+ grant_type: "authorization_code",
629
+ code: completeOutcome.value.authorization_code,
630
+ redirect_uri: ctx.config.redirectUri,
631
+ code_verifier: codeVerifier,
632
+ client_id: ctx.config.clientId,
633
+ };
634
+ return requestJson(
635
+ ctx.fetchPort,
636
+ { method: "POST", url: `${ctx.issuer}/oauth2/token`, body },
637
+ tokenResponseSchema,
638
+ );
639
+ };
640
+
641
+ // ---------------------------------------------------------------------------
642
+ // Public-method implementations (internal, Outcome-returning)
643
+ // ---------------------------------------------------------------------------
644
+
645
+ const toPublicPasskey = (summary: PasskeySummary): Passkey => ({
646
+ passkeyId: summary.passkey_id,
647
+ name: summary.name,
648
+ createdAt: summary.created_at,
649
+ lastUsedAt: summary.last_used_at,
650
+ deviceType: summary.device_type,
651
+ backedUp: summary.backed_up,
652
+ });
653
+
654
+ const toPublicUserProfile = (user: MeUser): UserProfile => ({
655
+ userId: user.user_id,
656
+ email: user.email,
657
+ emailVerified: user.email_verified,
658
+ name: user.name,
659
+ avatarUrl: user.avatar_url,
660
+ locale: user.locale,
661
+ timezone: user.timezone,
662
+ status: user.status,
663
+ createdAt: user.created_at,
664
+ lastLoginAt: user.last_login_at,
665
+ });
666
+
667
+ const toPublicDeviceSession = (summary: WireDeviceSession): DeviceSession => ({
668
+ sessionId: summary.session_id,
669
+ clientId: summary.client_id,
670
+ deviceName: summary.device_name,
671
+ createdAt: summary.created_at,
672
+ lastActiveAt: summary.last_active_at,
673
+ current: summary.current,
674
+ });
675
+
676
+ /**
677
+ * Runs one passkey ceremony (options → native sheet → verify) at a time
678
+ * (design.md §21.2): a second concurrent call resolves `passkey_error/in_progress`
679
+ * instead of racing the first through the native sheet. Promise-chain
680
+ * `finally`, like the refresh mutex below — no `try`/`catch` in this file.
681
+ */
682
+ const withPasskeyCeremony = async <T>(
683
+ ctx: InternalContext,
684
+ run: () => Promise<Outcome<T, ReactNativeAuthError>>,
685
+ ): Promise<Outcome<T, ReactNativeAuthError>> => {
686
+ const supported = await checkPasskeySupport(ctx);
687
+ if (!supported) return err({ type: "passkey_not_supported" });
688
+ if (ctx.passkeyInFlight) {
689
+ return err({
690
+ type: "passkey_error",
691
+ reason: "in_progress",
692
+ message: "A passkey ceremony is already in progress",
693
+ });
694
+ }
695
+ ctx.passkeyInFlight = true;
696
+ return run().finally(() => {
697
+ ctx.passkeyInFlight = false;
698
+ });
699
+ };
700
+
701
+ /**
702
+ * Pins the ceremony's RP ID to the domain baked into the app binary (iOS
703
+ * webcredentials / Android asset_statements) so an Environment's custom
704
+ * domain never changes the RP a shipped build must use.
705
+ */
706
+ const passkeyOptionsBody = (ctx: InternalContext): { rp_id?: string } =>
707
+ ctx.config.rpDomain === undefined ? {} : { rp_id: ctx.config.rpDomain };
708
+
709
+ const signInWithPasskeyInternal = (
710
+ ctx: InternalContext,
711
+ ): Promise<Outcome<AuthResult, ReactNativeAuthError>> =>
712
+ withPasskeyCeremony(ctx, () => runSignInWithPasskeyCeremony(ctx));
713
+
714
+ const runSignInWithPasskeyCeremony = async (
715
+ ctx: InternalContext,
716
+ ): Promise<Outcome<AuthResult, ReactNativeAuthError>> => {
717
+ const txOutcome = await beginTransaction(ctx);
718
+ if (!txOutcome.ok) return txOutcome;
719
+ const { transactionId, pkce, state } = txOutcome.value;
720
+
721
+ const optionsOutcome = await requestJson(
722
+ ctx.fetchPort,
723
+ {
724
+ method: "POST",
725
+ url: buildUrl(
726
+ ctx.apiBaseUrl,
727
+ `/v1/auth/transactions/${transactionId}/passkeys/authentication/options`,
728
+ ),
729
+ body: passkeyOptionsBody(ctx),
730
+ },
731
+ passkeyAuthenticationOptionsResponseSchema,
732
+ );
733
+ if (!optionsOutcome.ok) return optionsOutcome;
734
+
735
+ const credentialOutcome = await runPasskeyGet(ctx, optionsOutcome.value);
736
+ if (!credentialOutcome.ok) return credentialOutcome;
737
+
738
+ const verifyOutcome = await requestJson(
739
+ ctx.fetchPort,
740
+ {
741
+ method: "POST",
742
+ url: buildUrl(
743
+ ctx.apiBaseUrl,
744
+ `/v1/auth/transactions/${transactionId}/passkeys/authentication/verify`,
745
+ ),
746
+ body: { credential: credentialOutcome.value },
747
+ },
748
+ passkeyAuthenticationVerifyResponseSchema,
749
+ );
750
+ if (!verifyOutcome.ok) return verifyOutcome;
751
+
752
+ const tokenOutcome = await completeAndExchange(ctx, transactionId, state, pkce.verifier);
753
+ if (!tokenOutcome.ok) return tokenOutcome;
754
+
755
+ const sessionOutcome = await applySession(ctx, tokenOutcome.value, generateFamilyId(ctx));
756
+ if (!sessionOutcome.ok) return sessionOutcome;
757
+ return ok({ session: sessionOutcome.value });
758
+ };
759
+
760
+ const registerPasskeyInternal = (
761
+ ctx: InternalContext,
762
+ input: RegisterPasskeyInput | undefined,
763
+ ): Promise<Outcome<Passkey, ReactNativeAuthError>> =>
764
+ withPasskeyCeremony(ctx, () => runRegisterPasskeyCeremony(ctx, input));
765
+
766
+ const runRegisterPasskeyCeremony = async (
767
+ ctx: InternalContext,
768
+ input: RegisterPasskeyInput | undefined,
769
+ ): Promise<Outcome<Passkey, ReactNativeAuthError>> => {
770
+ return withAccessToken(ctx, async (accessToken) => {
771
+ const optionsOutcome = await requestJson(
772
+ ctx.fetchPort,
773
+ {
774
+ method: "POST",
775
+ url: buildUrl(ctx.apiBaseUrl, "/v1/me/passkeys/registration/options"),
776
+ body: passkeyOptionsBody(ctx),
777
+ accessToken,
778
+ },
779
+ mePasskeyRegistrationOptionsResponseSchema,
780
+ );
781
+ if (!optionsOutcome.ok) return optionsOutcome;
782
+
783
+ const credentialOutcome = await runPasskeyCreate(ctx, optionsOutcome.value);
784
+ if (!credentialOutcome.ok) return credentialOutcome;
785
+
786
+ const body: MePasskeyRegistrationVerifyRequest = {
787
+ credential: credentialOutcome.value,
788
+ ...(input?.name !== undefined ? { name: input.name } : {}),
789
+ };
790
+ const verifyOutcome = await requestJson(
791
+ ctx.fetchPort,
792
+ {
793
+ method: "POST",
794
+ url: buildUrl(ctx.apiBaseUrl, "/v1/me/passkeys/registration/verify"),
795
+ body,
796
+ accessToken,
797
+ },
798
+ mePasskeyRegistrationVerifyResponseSchema,
799
+ );
800
+ if (!verifyOutcome.ok) return verifyOutcome;
801
+ return ok(toPublicPasskey(verifyOutcome.value.passkey));
802
+ });
803
+ };
804
+
805
+ const sendEmailCodeInternal = async (
806
+ ctx: InternalContext,
807
+ email: string,
808
+ ): Promise<Outcome<EmailCodeChallenge, ReactNativeAuthError>> => {
809
+ const txOutcome = await beginTransaction(ctx);
810
+ if (!txOutcome.ok) return txOutcome;
811
+ const { transactionId, pkce, state } = txOutcome.value;
812
+
813
+ const startOutcome = await requestJson(
814
+ ctx.fetchPort,
815
+ {
816
+ method: "POST",
817
+ url: buildUrl(ctx.apiBaseUrl, `/v1/auth/transactions/${transactionId}/email/start`),
818
+ body: { email },
819
+ },
820
+ emailChallengeResponseSchema,
821
+ );
822
+ if (!startOutcome.ok) return startOutcome;
823
+
824
+ await savePendingTransaction(ctx, {
825
+ transactionId,
826
+ state,
827
+ codeVerifier: pkce.verifier,
828
+ redirectUri: ctx.config.redirectUri,
829
+ createdAt: ctx.now(),
830
+ challengeId: startOutcome.value.challenge_id,
831
+ });
832
+ return ok({
833
+ challengeId: startOutcome.value.challenge_id,
834
+ expiresAt: startOutcome.value.expires_at,
835
+ });
836
+ };
837
+
838
+ const verifyEmailCodeInternal = async (
839
+ ctx: InternalContext,
840
+ input: { challengeId: string; code: string },
841
+ ): Promise<Outcome<AuthResult, ReactNativeAuthError>> => {
842
+ const pending = await loadPendingTransaction(ctx);
843
+ if (pending === null || pending.challengeId !== input.challengeId) {
844
+ return err({
845
+ type: "invalid_flow_state",
846
+ message: "No pending email code challenge matches this challengeId",
847
+ });
848
+ }
849
+
850
+ const verifyOutcome = await requestJson(
851
+ ctx.fetchPort,
852
+ {
853
+ method: "POST",
854
+ url: buildUrl(ctx.apiBaseUrl, `/v1/auth/transactions/${pending.transactionId}/email/verify`),
855
+ body: { challenge_id: input.challengeId, code: input.code },
856
+ },
857
+ emailVerifyResponseSchema,
858
+ );
859
+ if (!verifyOutcome.ok) {
860
+ await clearPendingTransaction(ctx);
861
+ return verifyOutcome;
862
+ }
863
+
864
+ const tokenOutcome = await completeAndExchange(
865
+ ctx,
866
+ pending.transactionId,
867
+ pending.state,
868
+ pending.codeVerifier,
869
+ );
870
+ if (!tokenOutcome.ok) {
871
+ await clearPendingTransaction(ctx);
872
+ return tokenOutcome;
873
+ }
874
+
875
+ const sessionOutcome = await applySession(ctx, tokenOutcome.value, generateFamilyId(ctx));
876
+ if (!sessionOutcome.ok) {
877
+ await clearPendingTransaction(ctx);
878
+ return sessionOutcome;
879
+ }
880
+ await clearPendingTransaction(ctx);
881
+ return ok({ session: sessionOutcome.value });
882
+ };
883
+
884
+ const openSystemBrowser = async (
885
+ ctx: InternalContext,
886
+ url: string,
887
+ ): Promise<Outcome<WebBrowserAuthResult, ReactNativeAuthError>> =>
888
+ Promise.resolve()
889
+ .then(() => ctx.browser.openAuthSessionAsync(url, ctx.config.redirectUri))
890
+ .then(
891
+ (result) => ok<WebBrowserAuthResult, ReactNativeAuthError>(result),
892
+ (cause: unknown) =>
893
+ err<WebBrowserAuthResult, ReactNativeAuthError>({
894
+ type: "network_error",
895
+ message: cause instanceof Error ? cause.message : "Failed to open the system browser",
896
+ retryable: true,
897
+ }),
898
+ );
899
+
900
+ const signInWithSocialInternal = async (
901
+ ctx: InternalContext,
902
+ provider: SocialProvider,
903
+ ): Promise<Outcome<AuthResult, ReactNativeAuthError>> => {
904
+ const txOutcome = await beginTransaction(ctx);
905
+ if (!txOutcome.ok) return txOutcome;
906
+ const { transactionId, pkce, state } = txOutcome.value;
907
+
908
+ await savePendingTransaction(ctx, {
909
+ transactionId,
910
+ state,
911
+ codeVerifier: pkce.verifier,
912
+ redirectUri: ctx.config.redirectUri,
913
+ createdAt: ctx.now(),
914
+ });
915
+
916
+ const startOutcome = await requestJson(
917
+ ctx.fetchPort,
918
+ {
919
+ method: "POST",
920
+ url: buildUrl(
921
+ ctx.apiBaseUrl,
922
+ `/v1/auth/transactions/${transactionId}/social/${provider}/start`,
923
+ ),
924
+ body: {},
925
+ },
926
+ socialStartResponseSchema,
927
+ );
928
+ if (!startOutcome.ok) {
929
+ await clearPendingTransaction(ctx);
930
+ return startOutcome;
931
+ }
932
+
933
+ // design.md §20.6: system browser only — embedding a WebView is forbidden.
934
+ const browserOutcome = await openSystemBrowser(ctx, startOutcome.value.authorization_url);
935
+ if (!browserOutcome.ok) {
936
+ await clearPendingTransaction(ctx);
937
+ return browserOutcome;
938
+ }
939
+ if (browserOutcome.value.type !== "success") {
940
+ await clearPendingTransaction(ctx);
941
+ return err({ type: "social_cancelled" });
942
+ }
943
+
944
+ const callbackUrl = browserOutcome.value.url;
945
+ if (callbackUrl === undefined) {
946
+ await clearPendingTransaction(ctx);
947
+ return err({ type: "state_mismatch" });
948
+ }
949
+ const callbackState = await Promise.resolve()
950
+ .then(() => ctx.linking.parse(callbackUrl).queryParams["state"])
951
+ .catch(() => undefined);
952
+ if (callbackState === undefined || !constantTimeEqual(callbackState, state)) {
953
+ await clearPendingTransaction(ctx);
954
+ return err({ type: "state_mismatch" });
955
+ }
956
+
957
+ const tokenOutcome = await completeAndExchange(ctx, transactionId, state, pkce.verifier);
958
+ if (!tokenOutcome.ok) {
959
+ await clearPendingTransaction(ctx);
960
+ return tokenOutcome;
961
+ }
962
+
963
+ const sessionOutcome = await applySession(ctx, tokenOutcome.value, generateFamilyId(ctx));
964
+ if (!sessionOutcome.ok) return sessionOutcome;
965
+ await clearPendingTransaction(ctx);
966
+ return ok({ session: sessionOutcome.value });
967
+ };
968
+
969
+ const linkSocialAccountInternal = (
970
+ ctx: InternalContext,
971
+ provider: SocialProvider,
972
+ ): Promise<Outcome<void, ReactNativeAuthError>> =>
973
+ withAccessToken(ctx, async (accessToken) => {
974
+ const body: MeIdentityLinkRequest = { redirect_uri: ctx.config.redirectUri };
975
+ const linkOutcome = await requestJson(
976
+ ctx.fetchPort,
977
+ {
978
+ method: "POST",
979
+ url: buildUrl(ctx.apiBaseUrl, `/v1/me/identities/${provider}/link`),
980
+ body,
981
+ accessToken,
982
+ },
983
+ meIdentityLinkResponseSchema,
984
+ );
985
+ if (!linkOutcome.ok) return linkOutcome;
986
+
987
+ const browserOutcome = await openSystemBrowser(ctx, linkOutcome.value.authorization_url);
988
+ if (!browserOutcome.ok) return browserOutcome;
989
+ if (browserOutcome.value.type !== "success") return err({ type: "social_cancelled" });
990
+ return ok(undefined);
991
+ });
992
+
993
+ const listPasskeysInternal = (
994
+ ctx: InternalContext,
995
+ ): Promise<Outcome<Passkey[], ReactNativeAuthError>> =>
996
+ withAccessToken(ctx, async (accessToken) => {
997
+ const outcome = await requestJson(
998
+ ctx.fetchPort,
999
+ { method: "GET", url: buildUrl(ctx.apiBaseUrl, "/v1/me/passkeys"), accessToken },
1000
+ mePasskeysListResponseSchema,
1001
+ );
1002
+ if (!outcome.ok) return outcome;
1003
+ return ok(outcome.value.passkeys.map(toPublicPasskey));
1004
+ });
1005
+
1006
+ const deletePasskeyInternal = (
1007
+ ctx: InternalContext,
1008
+ passkeyId: string,
1009
+ ): Promise<Outcome<void, ReactNativeAuthError>> =>
1010
+ withAccessToken(ctx, async (accessToken) => {
1011
+ const outcome = await requestJson(
1012
+ ctx.fetchPort,
1013
+ {
1014
+ method: "DELETE",
1015
+ url: buildUrl(ctx.apiBaseUrl, `/v1/me/passkeys/${passkeyId}`),
1016
+ accessToken,
1017
+ },
1018
+ mePasskeyDeleteResponseSchema,
1019
+ );
1020
+ if (!outcome.ok) return outcome;
1021
+ return ok(undefined);
1022
+ });
1023
+
1024
+ const listSessionsInternal = (
1025
+ ctx: InternalContext,
1026
+ ): Promise<Outcome<DeviceSession[], ReactNativeAuthError>> =>
1027
+ withAccessToken(ctx, async (accessToken) => {
1028
+ const outcome = await requestJson(
1029
+ ctx.fetchPort,
1030
+ { method: "GET", url: buildUrl(ctx.apiBaseUrl, "/v1/me/sessions"), accessToken },
1031
+ meSessionsListResponseSchema,
1032
+ );
1033
+ if (!outcome.ok) return outcome;
1034
+ return ok(outcome.value.sessions.map(toPublicDeviceSession));
1035
+ });
1036
+
1037
+ const revokeSessionInternal = (
1038
+ ctx: InternalContext,
1039
+ sessionId: string,
1040
+ ): Promise<Outcome<void, ReactNativeAuthError>> =>
1041
+ withAccessToken(ctx, async (accessToken) => {
1042
+ const outcome = await requestJson(
1043
+ ctx.fetchPort,
1044
+ {
1045
+ method: "DELETE",
1046
+ url: buildUrl(ctx.apiBaseUrl, `/v1/me/sessions/${sessionId}`),
1047
+ accessToken,
1048
+ },
1049
+ meSessionRevokeResponseSchema,
1050
+ );
1051
+ if (!outcome.ok) return outcome;
1052
+ return ok(undefined);
1053
+ });
1054
+
1055
+ const getMeInternal = (ctx: InternalContext): Promise<Outcome<UserProfile, ReactNativeAuthError>> =>
1056
+ withAccessToken(ctx, async (accessToken) => {
1057
+ const outcome = await requestJson(
1058
+ ctx.fetchPort,
1059
+ { method: "GET", url: buildUrl(ctx.apiBaseUrl, "/v1/me"), accessToken },
1060
+ meUserSchema,
1061
+ );
1062
+ if (!outcome.ok) return outcome;
1063
+ return ok(toPublicUserProfile(outcome.value));
1064
+ });
1065
+
1066
+ const updateMeInternal = (
1067
+ ctx: InternalContext,
1068
+ input: UpdateUserProfileInput,
1069
+ ): Promise<Outcome<UserProfile, ReactNativeAuthError>> =>
1070
+ withAccessToken(ctx, async (accessToken) => {
1071
+ const body: MeUpdateRequest = {
1072
+ ...(input.name !== undefined ? { name: input.name } : {}),
1073
+ ...(input.avatarUrl !== undefined ? { avatar_url: input.avatarUrl } : {}),
1074
+ ...(input.locale !== undefined ? { locale: input.locale } : {}),
1075
+ ...(input.timezone !== undefined ? { timezone: input.timezone } : {}),
1076
+ };
1077
+ const outcome = await requestJson(
1078
+ ctx.fetchPort,
1079
+ { method: "PATCH", url: buildUrl(ctx.apiBaseUrl, "/v1/me"), body, accessToken },
1080
+ meUpdateResponseSchema,
1081
+ );
1082
+ if (!outcome.ok) return outcome;
1083
+ return ok(toPublicUserProfile(outcome.value));
1084
+ });
1085
+
1086
+ /** Best-effort revoke, then unconditional local wipe (design.md §21.7: sign-out is never blocked by the network). */
1087
+ const signOutInternal = async (ctx: InternalContext): Promise<void> => {
1088
+ const record = await loadRefreshRecord(ctx);
1089
+ if (record !== null) {
1090
+ await requestJson(
1091
+ ctx.fetchPort,
1092
+ {
1093
+ method: "POST",
1094
+ url: `${ctx.issuer}/oauth2/revoke`,
1095
+ body: {
1096
+ token: record.refreshToken,
1097
+ token_type_hint: "refresh_token",
1098
+ client_id: ctx.config.clientId,
1099
+ },
1100
+ },
1101
+ revocationResponseSchema,
1102
+ );
1103
+ }
1104
+ await wipeSession(ctx);
1105
+ };
1106
+
1107
+ const signOutAllInternal = async (ctx: InternalContext): Promise<void> => {
1108
+ const tokenOutcome = await ensureFreshAccessToken(ctx, false);
1109
+ if (tokenOutcome.ok && ctx.accessToken !== null) {
1110
+ await requestJson(
1111
+ ctx.fetchPort,
1112
+ {
1113
+ method: "DELETE",
1114
+ url: buildUrl(ctx.apiBaseUrl, "/v1/me/sessions"),
1115
+ accessToken: ctx.accessToken.token,
1116
+ },
1117
+ meSessionsRevokeAllResponseSchema,
1118
+ );
1119
+ }
1120
+ await signOutInternal(ctx);
1121
+ };
1122
+
1123
+ // ---------------------------------------------------------------------------
1124
+ // App lifecycle wiring (design.md §21.7)
1125
+ // ---------------------------------------------------------------------------
1126
+
1127
+ const wireLifecycle = (ctx: InternalContext): void => {
1128
+ ctx.appStateSubscription = ctx.appState.addEventListener("change", (state) => {
1129
+ // design.md §21.7: "foreground復帰時にtoken expiryを確認" — only on the
1130
+ // background/inactive -> active transition, and only when a session
1131
+ // exists at all (an unauthenticated app has nothing to refresh).
1132
+ if (state === "active" && ctx.lastAppState !== "active" && ctx.currentSession !== null) {
1133
+ // Intentionally not awaited: this is a fire-and-forget background
1134
+ // check. `ensureFreshAccessToken` never rejects (it always resolves to
1135
+ // an `Outcome`) and already applies every side effect (session
1136
+ // refresh/wipe + listener notification) internally, so there is
1137
+ // nothing further for this handler to do with the resolved value.
1138
+ void ensureFreshAccessToken(ctx, false);
1139
+ }
1140
+ ctx.lastAppState = state;
1141
+ });
1142
+ ctx.networkStatusUnsubscribe =
1143
+ ctx.networkStatus?.subscribe((online) => {
1144
+ // design.md §21.7: "network復帰時に1回だけrefresh" — the mutex in
1145
+ // `ensureFreshAccessToken` already guarantees at most one in-flight
1146
+ // token-endpoint call; the offline -> online edge guard here avoids
1147
+ // even attempting one when nothing changed.
1148
+ if (online && !ctx.lastOnline && ctx.currentSession !== null) {
1149
+ void ensureFreshAccessToken(ctx, false);
1150
+ }
1151
+ ctx.lastOnline = online;
1152
+ }) ?? null;
1153
+ };
1154
+
1155
+ // ---------------------------------------------------------------------------
1156
+ // Factory
1157
+ // ---------------------------------------------------------------------------
1158
+
1159
+ const resolveOrThrow = <T>(outcome: Outcome<T, ReactNativeAuthError>): T => {
1160
+ if (!outcome.ok) throw new ReactNativeAuthClientError(outcome.error);
1161
+ return outcome.value;
1162
+ };
1163
+
1164
+ /**
1165
+ * The real implementation of every port `ReactNativeAuthConfig` lets a
1166
+ * consumer override (design.md §21.1's peer dependencies). Supplied by
1167
+ * `index.ts` in production (see this file's top doc comment for why that
1168
+ * import boundary matters); test files supply fakes for all six instead.
1169
+ */
1170
+ export interface NativePortDefaults {
1171
+ readonly secureStore: SecureStorePort;
1172
+ readonly passkeyAdapter: PasskeyNativeAdapter;
1173
+ readonly browser: WebBrowserPort;
1174
+ readonly linking: LinkingPort;
1175
+ readonly crypto: CryptoPort;
1176
+ readonly appState: AppStatePort;
1177
+ }
1178
+
1179
+ /**
1180
+ * Builds `createReactNativeAuthClient` (design.md §21.3, §21.8) given the
1181
+ * real native port defaults. Pass the config up front (matching §21.8's
1182
+ * sample) or omit it and call `.configure()` before using any other method.
1183
+ */
1184
+ export const createReactNativeAuthClientFactory =
1185
+ (defaults: NativePortDefaults) =>
1186
+ (initialConfig?: ReactNativeAuthConfig): ReactNativeAuthClient => {
1187
+ let ctx: InternalContext | null = null;
1188
+
1189
+ const requireConfigured = (): InternalContext => {
1190
+ if (ctx === null) throw new ReactNativeAuthClientError({ type: "not_configured" });
1191
+ return ctx;
1192
+ };
1193
+
1194
+ const configure = (config: ReactNativeAuthConfig): void => {
1195
+ const parsedIssuer = parseIssuer(config.issuer);
1196
+ const environmentId = config.environmentId ?? parsedIssuer?.environmentId;
1197
+ if (environmentId === undefined) {
1198
+ throw new Error(
1199
+ `ReactNativeAuthConfig.issuer must look like "https://host/e/<environmentId>" (got ${JSON.stringify(config.issuer)}); pass environmentId explicitly to override parsing.`,
1200
+ );
1201
+ }
1202
+ const apiBaseUrl = parsedIssuer
1203
+ ? `${parsedIssuer.origin}/e/${parsedIssuer.environmentId}`
1204
+ : config.issuer;
1205
+
1206
+ ctx?.appStateSubscription?.remove();
1207
+ ctx?.networkStatusUnsubscribe?.();
1208
+
1209
+ const appState = config.appState ?? defaults.appState;
1210
+ const newCtx: InternalContext = {
1211
+ config,
1212
+ apiBaseUrl,
1213
+ issuer: config.issuer,
1214
+ environmentId,
1215
+ scope: (config.scopes ?? DEFAULT_SCOPES).join(" "),
1216
+ resource: normalizeResource(config.resource),
1217
+ fetchPort: config.fetch ?? fetch,
1218
+ now: config.now ?? (() => Date.now()),
1219
+ secureStore: config.secureStore ?? defaults.secureStore,
1220
+ passkeyAdapter: config.passkeyAdapter ?? defaults.passkeyAdapter,
1221
+ browser: config.browser ?? defaults.browser,
1222
+ linking: config.linking ?? defaults.linking,
1223
+ crypto: config.crypto ?? defaults.crypto,
1224
+ appState,
1225
+ networkStatus: config.networkStatus,
1226
+ refreshKey: refreshRecordKey(environmentId, config.clientId),
1227
+ pendingKey: pendingTransactionKey(environmentId, config.clientId),
1228
+ accessToken: null,
1229
+ currentSession: null,
1230
+ hasRefreshToken: false,
1231
+ passkeySupported: false,
1232
+ pendingTransaction: null,
1233
+ refreshInFlight: null,
1234
+ passkeyInFlight: false,
1235
+ listeners: new Set(),
1236
+ snapshot: { status: "signed_out", passkeySupported: false, hasRefreshToken: false },
1237
+ appStateSubscription: null,
1238
+ networkStatusUnsubscribe: null,
1239
+ lastAppState: appState.currentState,
1240
+ lastOnline: true,
1241
+ };
1242
+ ctx = newCtx;
1243
+ wireLifecycle(newCtx);
1244
+ // design.md §21.2: "SDK起動時と...capabilityを確認." Not awaited: `configure`
1245
+ // is synchronous per design.md §21.3's verbatim signature; the check
1246
+ // completes shortly after and notifies subscribers if it changes
1247
+ // anything (mirrors the lifecycle handlers' fire-and-forget pattern).
1248
+ void checkPasskeySupport(newCtx);
1249
+ };
1250
+
1251
+ if (initialConfig !== undefined) configure(initialConfig);
1252
+
1253
+ return {
1254
+ configure,
1255
+
1256
+ getSession: async (): Promise<AuthSession | null> => {
1257
+ const activeCtx = requireConfigured();
1258
+ if (activeCtx.currentSession !== null) return toAuthSession(activeCtx);
1259
+ const record = await loadRefreshRecord(activeCtx);
1260
+ if (record === null) return null;
1261
+ activeCtx.currentSession = {
1262
+ userId: record.userId,
1263
+ scope: record.scope,
1264
+ familyId: record.familyId,
1265
+ };
1266
+ activeCtx.hasRefreshToken = true;
1267
+ notify(activeCtx);
1268
+ return toAuthSession(activeCtx);
1269
+ },
1270
+
1271
+ getAccessToken: async (input?: AccessTokenRequest): Promise<string> => {
1272
+ const activeCtx = requireConfigured();
1273
+ const outcome = await ensureFreshAccessToken(activeCtx, input?.forceRefresh ?? false);
1274
+ resolveOrThrow(outcome);
1275
+ if (activeCtx.accessToken === null) {
1276
+ throw new ReactNativeAuthClientError({ type: "not_authenticated" });
1277
+ }
1278
+ return activeCtx.accessToken.token;
1279
+ },
1280
+
1281
+ signInWithPasskey: async (): Promise<AuthResult> =>
1282
+ resolveOrThrow(await signInWithPasskeyInternal(requireConfigured())),
1283
+
1284
+ registerPasskey: async (input?: RegisterPasskeyInput): Promise<Passkey> =>
1285
+ resolveOrThrow(await registerPasskeyInternal(requireConfigured(), input)),
1286
+
1287
+ sendEmailCode: async (input: { email: string }): Promise<EmailCodeChallenge> =>
1288
+ resolveOrThrow(await sendEmailCodeInternal(requireConfigured(), input.email)),
1289
+
1290
+ verifyEmailCode: async (input: { challengeId: string; code: string }): Promise<AuthResult> =>
1291
+ resolveOrThrow(await verifyEmailCodeInternal(requireConfigured(), input)),
1292
+
1293
+ signInWithSocial: async (input: { provider: SocialProvider }): Promise<AuthResult> =>
1294
+ resolveOrThrow(await signInWithSocialInternal(requireConfigured(), input.provider)),
1295
+
1296
+ linkSocialAccount: async (input: { provider: SocialProvider }): Promise<void> =>
1297
+ resolveOrThrow(await linkSocialAccountInternal(requireConfigured(), input.provider)),
1298
+
1299
+ listPasskeys: async (): Promise<Passkey[]> =>
1300
+ resolveOrThrow(await listPasskeysInternal(requireConfigured())),
1301
+
1302
+ deletePasskey: async (passkeyId: string): Promise<void> =>
1303
+ resolveOrThrow(await deletePasskeyInternal(requireConfigured(), passkeyId)),
1304
+
1305
+ listSessions: async (): Promise<DeviceSession[]> =>
1306
+ resolveOrThrow(await listSessionsInternal(requireConfigured())),
1307
+
1308
+ revokeSession: async (sessionId: string): Promise<void> =>
1309
+ resolveOrThrow(await revokeSessionInternal(requireConfigured(), sessionId)),
1310
+
1311
+ signOut: async (): Promise<void> => signOutInternal(requireConfigured()),
1312
+
1313
+ signOutAll: async (): Promise<void> => signOutAllInternal(requireConfigured()),
1314
+
1315
+ subscribe: (listener: AuthStateListener): (() => void) => {
1316
+ const activeCtx = requireConfigured();
1317
+ activeCtx.listeners.add(listener);
1318
+ return () => activeCtx.listeners.delete(listener);
1319
+ },
1320
+
1321
+ getSnapshot: (): AuthStateSnapshot => requireConfigured().snapshot,
1322
+
1323
+ getMe: async (): Promise<UserProfile> =>
1324
+ resolveOrThrow(await getMeInternal(requireConfigured())),
1325
+
1326
+ updateMe: async (input: UpdateUserProfileInput): Promise<UserProfile> =>
1327
+ resolveOrThrow(await updateMeInternal(requireConfigured(), input)),
1328
+ };
1329
+ };