@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/hooks.ts ADDED
@@ -0,0 +1,374 @@
1
+ import { useCallback, useEffect, useMemo, useState, useSyncExternalStore } from "react";
2
+ import { useAuthClient } from "./context.js";
3
+ import { ReactNativeAuthClientError } from "./errors.js";
4
+ import type {
5
+ AccessTokenRequest,
6
+ AuthResult,
7
+ AuthSession,
8
+ AuthStateSnapshot,
9
+ DeviceSession,
10
+ EmailCodeChallenge,
11
+ Passkey,
12
+ RegisterPasskeyInput,
13
+ UpdateUserProfileInput,
14
+ UserProfile,
15
+ } from "./types.js";
16
+ import type { SocialProvider } from "@smartcrab/contracts-public";
17
+
18
+ /**
19
+ * The React hook surface (design.md §21.4). Every hook binds
20
+ * `client.subscribe`/`client.getSnapshot` via `useSyncExternalStore` so
21
+ * re-renders happen exactly when the underlying auth state changes, plus
22
+ * `useState`-managed local state for hooks that fetch their own data
23
+ * (`useSession`, `useUser`, `usePasskey`).
24
+ *
25
+ * No `try`/`catch` statements here (design.md §5.2 scans this package, unlike
26
+ * `ui-react-native`/`sdk-react`, which are excluded): fallible calls that need
27
+ * to land in local component state use `.then(onFulfilled, onRejected)`
28
+ * instead. Ceremony actions (`usePasskey`'s `signIn`/`register`) additionally
29
+ * flip `isLoading` for the ceremony's duration; other simple pass-throughs
30
+ * return the client's promise directly — it rejects with
31
+ * `ReactNativeAuthClientError`, which the *calling UI component's* event
32
+ * handler (design.md §5.2 exempts UI) is free to catch with a plain
33
+ * `try`/`catch`.
34
+ */
35
+
36
+ // ---------------------------------------------------------------------------
37
+ // useAuth
38
+ // ---------------------------------------------------------------------------
39
+
40
+ export interface UseAuthResult {
41
+ readonly snapshot: AuthStateSnapshot;
42
+ readonly isSignedIn: boolean;
43
+ readonly passkeySupported: boolean;
44
+ readonly signInWithPasskey: () => Promise<AuthResult>;
45
+ readonly signInWithSocial: (input: { provider: SocialProvider }) => Promise<AuthResult>;
46
+ readonly sendEmailCode: (input: { email: string }) => Promise<EmailCodeChallenge>;
47
+ readonly verifyEmailCode: (input: { challengeId: string; code: string }) => Promise<AuthResult>;
48
+ readonly getAccessToken: (input?: AccessTokenRequest) => Promise<string>;
49
+ readonly signOut: () => Promise<void>;
50
+ readonly signOutAll: () => Promise<void>;
51
+ }
52
+
53
+ /** Main facade (design.md §21.4's `useAuth`, matches §21.8's sample destructuring). */
54
+ export const useAuth = (): UseAuthResult => {
55
+ const client = useAuthClient();
56
+ const snapshot = useSyncExternalStore(client.subscribe, client.getSnapshot);
57
+ return useMemo<UseAuthResult>(
58
+ () => ({
59
+ snapshot,
60
+ isSignedIn: snapshot.status === "signed_in",
61
+ passkeySupported: snapshot.passkeySupported,
62
+ signInWithPasskey: () => client.signInWithPasskey(),
63
+ signInWithSocial: (input) => client.signInWithSocial(input),
64
+ sendEmailCode: (input) => client.sendEmailCode(input),
65
+ verifyEmailCode: (input) => client.verifyEmailCode(input),
66
+ getAccessToken: (input) => client.getAccessToken(input),
67
+ signOut: () => client.signOut(),
68
+ signOutAll: () => client.signOutAll(),
69
+ }),
70
+ [client, snapshot],
71
+ );
72
+ };
73
+
74
+ // ---------------------------------------------------------------------------
75
+ // useSession
76
+ // ---------------------------------------------------------------------------
77
+
78
+ export interface UseSessionResult {
79
+ readonly session: AuthSession | null;
80
+ readonly isLoading: boolean;
81
+ readonly reload: () => Promise<AuthSession | null>;
82
+ }
83
+
84
+ /** Session metadata (design.md §21.4's `useSession`), reloaded whenever sign-in status changes. */
85
+ export const useSession = (): UseSessionResult => {
86
+ const client = useAuthClient();
87
+ const snapshot = useSyncExternalStore(client.subscribe, client.getSnapshot);
88
+ const [session, setSession] = useState<AuthSession | null>(null);
89
+ const [isLoading, setIsLoading] = useState(true);
90
+
91
+ const reload = useCallback((): Promise<AuthSession | null> => {
92
+ setIsLoading(true);
93
+ return client.getSession().then((next) => {
94
+ setSession(next);
95
+ setIsLoading(false);
96
+ return next;
97
+ });
98
+ }, [client]);
99
+
100
+ useEffect(() => {
101
+ void reload();
102
+ // Reload whenever the client's own sign-in status flips; `reload` is
103
+ // stable across renders for a given `client` (see its `useCallback`).
104
+ }, [reload, snapshot.status]);
105
+
106
+ return useMemo<UseSessionResult>(
107
+ () => ({ session, isLoading, reload }),
108
+ [session, isLoading, reload],
109
+ );
110
+ };
111
+
112
+ // ---------------------------------------------------------------------------
113
+ // useUser
114
+ // ---------------------------------------------------------------------------
115
+
116
+ export interface UseUserResult {
117
+ readonly user: UserProfile | null;
118
+ readonly isLoading: boolean;
119
+ readonly error: ReactNativeAuthClientError | null;
120
+ readonly reload: () => Promise<UserProfile | null>;
121
+ readonly update: (input: UpdateUserProfileInput) => Promise<UserProfile>;
122
+ }
123
+
124
+ /** Signed-in user's profile (design.md §21.4's `useUser`); loads on sign-in, clears on sign-out. */
125
+ export const useUser = (): UseUserResult => {
126
+ const client = useAuthClient();
127
+ const snapshot = useSyncExternalStore(client.subscribe, client.getSnapshot);
128
+ const [user, setUser] = useState<UserProfile | null>(null);
129
+ const [isLoading, setIsLoading] = useState(false);
130
+ const [error, setError] = useState<ReactNativeAuthClientError | null>(null);
131
+
132
+ const reload = useCallback((): Promise<UserProfile | null> => {
133
+ setIsLoading(true);
134
+ setError(null);
135
+ return client.getMe().then(
136
+ (profile) => {
137
+ setUser(profile);
138
+ setIsLoading(false);
139
+ return profile;
140
+ },
141
+ (cause: unknown) => {
142
+ setIsLoading(false);
143
+ setUser(null);
144
+ if (cause instanceof ReactNativeAuthClientError) setError(cause);
145
+ return null;
146
+ },
147
+ );
148
+ }, [client]);
149
+
150
+ useEffect(() => {
151
+ if (snapshot.status === "signed_in") {
152
+ void reload();
153
+ } else {
154
+ setUser(null);
155
+ setError(null);
156
+ }
157
+ }, [snapshot.status, reload]);
158
+
159
+ const update = useCallback(
160
+ (input: UpdateUserProfileInput): Promise<UserProfile> =>
161
+ client.updateMe(input).then((profile) => {
162
+ setUser(profile);
163
+ return profile;
164
+ }),
165
+ [client],
166
+ );
167
+
168
+ return useMemo<UseUserResult>(
169
+ () => ({ user, isLoading, error, reload, update }),
170
+ [user, isLoading, error, reload, update],
171
+ );
172
+ };
173
+
174
+ // ---------------------------------------------------------------------------
175
+ // usePasskey
176
+ // ---------------------------------------------------------------------------
177
+
178
+ export interface UsePasskeyResult {
179
+ /** Runtime WebAuthn capability (design.md §21.2) — prebuilt UI hides passkey affordances when false. */
180
+ readonly passkeySupported: boolean;
181
+ readonly passkeys: readonly Passkey[];
182
+ readonly isLoading: boolean;
183
+ readonly error: ReactNativeAuthClientError | null;
184
+ readonly reload: () => Promise<Passkey[]>;
185
+ readonly signIn: () => Promise<AuthResult>;
186
+ readonly register: (input?: RegisterPasskeyInput) => Promise<Passkey>;
187
+ readonly remove: (passkeyId: string) => Promise<void>;
188
+ }
189
+
190
+ /** Passkey ceremonies + self-service management (design.md §21.4's `usePasskey`). */
191
+ export const usePasskey = (): UsePasskeyResult => {
192
+ const client = useAuthClient();
193
+ const snapshot = useSyncExternalStore(client.subscribe, client.getSnapshot);
194
+ const [passkeys, setPasskeys] = useState<Passkey[]>([]);
195
+ const [isLoading, setIsLoading] = useState(false);
196
+ const [error, setError] = useState<ReactNativeAuthClientError | null>(null);
197
+
198
+ const reload = useCallback((): Promise<Passkey[]> => {
199
+ setIsLoading(true);
200
+ setError(null);
201
+ return client.listPasskeys().then(
202
+ (list) => {
203
+ setPasskeys(list);
204
+ setIsLoading(false);
205
+ return list;
206
+ },
207
+ (cause: unknown) => {
208
+ setIsLoading(false);
209
+ if (cause instanceof ReactNativeAuthClientError) setError(cause);
210
+ return [];
211
+ },
212
+ );
213
+ }, [client]);
214
+
215
+ useEffect(() => {
216
+ if (snapshot.status === "signed_in") {
217
+ void reload();
218
+ } else {
219
+ setPasskeys([]);
220
+ setError(null);
221
+ }
222
+ }, [snapshot.status, reload]);
223
+
224
+ const ceremony = useCallback(<T>(run: Promise<T>): Promise<T> => {
225
+ setIsLoading(true);
226
+ return run
227
+ .then((value) => {
228
+ setError(null);
229
+ return value;
230
+ })
231
+ .catch((cause: unknown) => {
232
+ if (cause instanceof ReactNativeAuthClientError) setError(cause);
233
+ throw cause;
234
+ })
235
+ .finally(() => setIsLoading(false));
236
+ }, []);
237
+
238
+ const register = useCallback(
239
+ (input?: RegisterPasskeyInput): Promise<Passkey> =>
240
+ ceremony(client.registerPasskey(input)).then((created) => {
241
+ setPasskeys((current) => [...current, created]);
242
+ return created;
243
+ }),
244
+ [client, ceremony],
245
+ );
246
+
247
+ const signIn = useCallback(
248
+ (): Promise<AuthResult> => ceremony(client.signInWithPasskey()),
249
+ [client, ceremony],
250
+ );
251
+
252
+ const remove = useCallback(
253
+ (passkeyId: string): Promise<void> =>
254
+ client.deletePasskey(passkeyId).then(() => {
255
+ setPasskeys((current) => current.filter((passkey) => passkey.passkeyId !== passkeyId));
256
+ }),
257
+ [client],
258
+ );
259
+
260
+ return useMemo<UsePasskeyResult>(
261
+ () => ({
262
+ passkeySupported: snapshot.passkeySupported,
263
+ passkeys,
264
+ isLoading,
265
+ error,
266
+ reload,
267
+ signIn,
268
+ register,
269
+ remove,
270
+ }),
271
+ [snapshot.passkeySupported, passkeys, isLoading, error, reload, signIn, register, remove],
272
+ );
273
+ };
274
+
275
+ // ---------------------------------------------------------------------------
276
+ // useEmailOtp
277
+ // ---------------------------------------------------------------------------
278
+
279
+ export interface UseEmailOtpResult {
280
+ readonly sendCode: (email: string) => Promise<EmailCodeChallenge>;
281
+ readonly verifyCode: (input: { challengeId: string; code: string }) => Promise<AuthResult>;
282
+ }
283
+
284
+ /** Email OTP sign-in (design.md §21.4's `useEmailOtp`; backs `<EmailOtpForm/>`, design.md §21.4). */
285
+ export const useEmailOtp = (): UseEmailOtpResult => {
286
+ const client = useAuthClient();
287
+ return useMemo<UseEmailOtpResult>(
288
+ () => ({
289
+ sendCode: (email: string) => client.sendEmailCode({ email }),
290
+ verifyCode: (input) => client.verifyEmailCode(input),
291
+ }),
292
+ [client],
293
+ );
294
+ };
295
+
296
+ // ---------------------------------------------------------------------------
297
+ // useSocialSignIn
298
+ // ---------------------------------------------------------------------------
299
+
300
+ export interface UseSocialSignInResult {
301
+ readonly signIn: (provider: SocialProvider) => Promise<AuthResult>;
302
+ readonly link: (provider: SocialProvider) => Promise<void>;
303
+ }
304
+
305
+ /** Social sign-in / account linking (design.md §21.4's `useSocialSignIn`; §20.6 system-browser flow). */
306
+ export const useSocialSignIn = (): UseSocialSignInResult => {
307
+ const client = useAuthClient();
308
+ return useMemo<UseSocialSignInResult>(
309
+ () => ({
310
+ signIn: (provider: SocialProvider) => client.signInWithSocial({ provider }),
311
+ link: (provider: SocialProvider) => client.linkSocialAccount({ provider }),
312
+ }),
313
+ [client],
314
+ );
315
+ };
316
+
317
+ // ---------------------------------------------------------------------------
318
+ // useSessionList (an additional headless helper backing `<SessionList/>`, design.md §21.4)
319
+ // ---------------------------------------------------------------------------
320
+
321
+ export interface UseSessionListResult {
322
+ readonly sessions: readonly DeviceSession[];
323
+ readonly isLoading: boolean;
324
+ readonly error: ReactNativeAuthClientError | null;
325
+ readonly reload: () => Promise<DeviceSession[]>;
326
+ readonly revoke: (sessionId: string) => Promise<void>;
327
+ }
328
+
329
+ export const useSessionList = (): UseSessionListResult => {
330
+ const client = useAuthClient();
331
+ const snapshot = useSyncExternalStore(client.subscribe, client.getSnapshot);
332
+ const [sessions, setSessions] = useState<DeviceSession[]>([]);
333
+ const [isLoading, setIsLoading] = useState(false);
334
+ const [error, setError] = useState<ReactNativeAuthClientError | null>(null);
335
+
336
+ const reload = useCallback((): Promise<DeviceSession[]> => {
337
+ setIsLoading(true);
338
+ setError(null);
339
+ return client.listSessions().then(
340
+ (list) => {
341
+ setSessions(list);
342
+ setIsLoading(false);
343
+ return list;
344
+ },
345
+ (cause: unknown) => {
346
+ setIsLoading(false);
347
+ if (cause instanceof ReactNativeAuthClientError) setError(cause);
348
+ return [];
349
+ },
350
+ );
351
+ }, [client]);
352
+
353
+ useEffect(() => {
354
+ if (snapshot.status === "signed_in") {
355
+ void reload();
356
+ } else {
357
+ setSessions([]);
358
+ setError(null);
359
+ }
360
+ }, [snapshot.status, reload]);
361
+
362
+ const revoke = useCallback(
363
+ (sessionId: string): Promise<void> =>
364
+ client.revokeSession(sessionId).then(() => {
365
+ setSessions((current) => current.filter((session) => session.sessionId !== sessionId));
366
+ }),
367
+ [client],
368
+ );
369
+
370
+ return useMemo<UseSessionListResult>(
371
+ () => ({ sessions, isLoading, error, reload, revoke }),
372
+ [sessions, isLoading, error, reload, revoke],
373
+ );
374
+ };
package/src/http.ts ADDED
@@ -0,0 +1,159 @@
1
+ import type { Outcome } from "@smartcrab/contracts-public";
2
+ import { OAUTH_ERROR_CODES, err, ok } from "@smartcrab/contracts-public";
3
+ import type { OAuthErrorCode } from "@smartcrab/contracts-public";
4
+ import { parseOAuthErrorWire, parseProblemDetailsWire } from "./errors.js";
5
+ import type { ReactNativeAuthError } from "./errors.js";
6
+
7
+ /**
8
+ * HTTP transport for the public authentication API (design.md §16.2) and the
9
+ * token endpoint (design.md §15.1).
10
+ *
11
+ * Exception boundaries are promise rejection handlers (`.then(onOk, onErr)`),
12
+ * never `try`/`catch` statements: `scripts/check-backend-error-style.ts`
13
+ * (design.md §5.2) scans this package and rejects direct try-catch. Success
14
+ * responses are always validated against a contracts-public zod schema — the
15
+ * wire is never trusted (IMPL_NOTES §1).
16
+ */
17
+
18
+ /** Structural view of a zod schema's `safeParse` (this package has no direct zod dependency). */
19
+ export interface WireSchema<T> {
20
+ safeParse(input: unknown): { success: true; data: T } | { success: false; error: unknown };
21
+ }
22
+
23
+ export type FetchPort = (url: string, init: RequestInit) => Promise<Response>;
24
+
25
+ export type HttpMethod = "GET" | "POST" | "PATCH" | "DELETE";
26
+
27
+ export interface JsonRequest {
28
+ readonly method: HttpMethod;
29
+ readonly url: string;
30
+ readonly body?: unknown;
31
+ readonly accessToken?: string;
32
+ }
33
+
34
+ const OAUTH_ERROR_CODE_SET: ReadonlySet<string> = new Set(OAUTH_ERROR_CODES);
35
+
36
+ export const isOAuthErrorCode = (value: string): value is OAuthErrorCode =>
37
+ OAUTH_ERROR_CODE_SET.has(value);
38
+
39
+ const parseRetryAfterSeconds = (response: Response): number | undefined => {
40
+ const raw = response.headers.get("retry-after");
41
+ if (raw === null) return undefined;
42
+ if (!/^[0-9]+$/.test(raw.trim())) return undefined;
43
+ return Number.parseInt(raw.trim(), 10);
44
+ };
45
+
46
+ const invalidResponse = (message: string, status?: number): Outcome<never, ReactNativeAuthError> =>
47
+ err({
48
+ type: "invalid_response",
49
+ message,
50
+ ...(status !== undefined ? { status } : {}),
51
+ });
52
+
53
+ const toNetworkError = (cause: unknown): Outcome<never, ReactNativeAuthError> =>
54
+ err({
55
+ type: "network_error",
56
+ message: cause instanceof Error ? cause.message : "Network request failed",
57
+ retryable: true,
58
+ });
59
+
60
+ /** `JSON.parse` without a try statement: the throw becomes a rejection inside the promise chain. */
61
+ const parseJsonBody = (
62
+ text: string,
63
+ status: number,
64
+ ): Promise<Outcome<unknown, ReactNativeAuthError>> =>
65
+ Promise.resolve()
66
+ .then((): unknown => JSON.parse(text))
67
+ .then(
68
+ (value) => ok(value),
69
+ () => invalidResponse("Response body was not valid JSON", status),
70
+ );
71
+
72
+ /**
73
+ * Executes one JSON request and validates the response against `schema`.
74
+ * Error precedence on non-2xx: 429 -> `rate_limited`; a valid Problem
75
+ * Details body -> `problem_details`; a valid OAuth error body ->
76
+ * `oauth_error`; anything else -> `invalid_response`.
77
+ */
78
+ export const requestJson = async <T>(
79
+ fetchPort: FetchPort,
80
+ request: JsonRequest,
81
+ schema: WireSchema<T>,
82
+ ): Promise<Outcome<T, ReactNativeAuthError>> => {
83
+ const headers: Record<string, string> = {
84
+ accept: "application/json",
85
+ ...(request.body !== undefined ? { "content-type": "application/json" } : {}),
86
+ ...(request.accessToken !== undefined
87
+ ? { authorization: `Bearer ${request.accessToken}` }
88
+ : {}),
89
+ };
90
+
91
+ const responseOutcome = await fetchPort(request.url, {
92
+ method: request.method,
93
+ headers,
94
+ ...(request.body !== undefined ? { body: JSON.stringify(request.body) } : {}),
95
+ }).then((response) => ok<Response, ReactNativeAuthError>(response), toNetworkError);
96
+ if (!responseOutcome.ok) return responseOutcome;
97
+ const response = responseOutcome.value;
98
+
99
+ const textOutcome = await response
100
+ .text()
101
+ .then((text) => ok<string, ReactNativeAuthError>(text), toNetworkError);
102
+ if (!textOutcome.ok) return textOutcome;
103
+ const text = textOutcome.value;
104
+
105
+ const jsonOutcome: Outcome<unknown, ReactNativeAuthError> =
106
+ text.length === 0 ? ok(undefined) : await parseJsonBody(text, response.status);
107
+ if (!jsonOutcome.ok) return jsonOutcome;
108
+ const json = jsonOutcome.value;
109
+
110
+ if (response.status === 429) {
111
+ const retryAfterSeconds = parseRetryAfterSeconds(response);
112
+ const problem = parseProblemDetailsWire(json);
113
+ return err({
114
+ type: "rate_limited",
115
+ retryable: true,
116
+ ...(retryAfterSeconds !== undefined ? { retryAfterSeconds } : {}),
117
+ ...(problem !== null && problem.requestId !== undefined
118
+ ? { requestId: problem.requestId }
119
+ : {}),
120
+ });
121
+ }
122
+
123
+ if (!response.ok) {
124
+ const problem = parseProblemDetailsWire(json);
125
+ if (problem !== null) {
126
+ return err({
127
+ type: "problem_details",
128
+ problemType: problem.type,
129
+ code: problem.code ?? "unknown_error",
130
+ title: problem.title,
131
+ status: problem.status,
132
+ ...(problem.detail !== undefined ? { detail: problem.detail } : {}),
133
+ ...(problem.requestId !== undefined ? { requestId: problem.requestId } : {}),
134
+ });
135
+ }
136
+ const oauthError = parseOAuthErrorWire(json);
137
+ if (oauthError !== null && isOAuthErrorCode(oauthError.error)) {
138
+ return err({
139
+ type: "oauth_error",
140
+ code: oauthError.error,
141
+ status: response.status,
142
+ ...(oauthError.description !== undefined ? { description: oauthError.description } : {}),
143
+ });
144
+ }
145
+ return invalidResponse(
146
+ `HTTP ${response.status} error body was neither Problem Details nor an OAuth error`,
147
+ response.status,
148
+ );
149
+ }
150
+
151
+ const parsed = schema.safeParse(json);
152
+ if (!parsed.success) {
153
+ return invalidResponse("Response body did not match the public API contract", response.status);
154
+ }
155
+ return ok(parsed.data);
156
+ };
157
+
158
+ /** Builds `base + path` (all routes this SDK calls take no query string). */
159
+ export const buildUrl = (baseUrl: string, path: string): string => `${baseUrl}${path}`;
package/src/index.ts ADDED
@@ -0,0 +1,101 @@
1
+ /**
2
+ * `@smartcrab/react-native` (design.md §21). Public entry point —
3
+ * `./plugin` (the Expo Config Plugin, design.md §21.5) is a separate subpath
4
+ * export and is intentionally not re-exported here.
5
+ *
6
+ * This is the ONLY file in the package that imports the `adapters/*` modules
7
+ * (which in turn import `expo-*`/`react-native`/`react-native-passkeys`) —
8
+ * see `client.ts`'s top doc comment for why that boundary is load-bearing for
9
+ * this package's own test suite, not just a style preference.
10
+ */
11
+ import { expoWebBrowserPort } from "./adapters/expo-web-browser-port.js";
12
+ import { expoCryptoPort } from "./adapters/expo-crypto-port.js";
13
+ import { expoLinkingPort } from "./adapters/expo-linking-port.js";
14
+ import { reactNativeAppStatePort } from "./adapters/react-native-app-state-port.js";
15
+ import { reactNativePasskeysAdapter } from "./adapters/react-native-passkeys-adapter.js";
16
+ import { expoSecureStorePort } from "./adapters/expo-secure-store-port.js";
17
+ import { createReactNativeAuthClientFactory } from "./client.js";
18
+
19
+ export const createReactNativeAuthClient = createReactNativeAuthClientFactory({
20
+ secureStore: expoSecureStorePort,
21
+ passkeyAdapter: reactNativePasskeysAdapter,
22
+ browser: expoWebBrowserPort,
23
+ linking: expoLinkingPort,
24
+ crypto: expoCryptoPort,
25
+ appState: reactNativeAppStatePort,
26
+ });
27
+ export type {
28
+ AccessTokenRequest,
29
+ AuthResult,
30
+ AuthSession,
31
+ AuthStateListener,
32
+ AuthStateSnapshot,
33
+ DeviceSession,
34
+ EmailCodeChallenge,
35
+ Passkey,
36
+ ReactNativeAuthClient,
37
+ ReactNativeAuthConfig,
38
+ RegisterPasskeyInput,
39
+ UpdateUserProfileInput,
40
+ UserProfile,
41
+ } from "./types.js";
42
+ /**
43
+ * Re-exported so downstream packages (e.g. `@smartcrab/ui-react-native`,
44
+ * which does not itself depend on `@smartcrab/contracts-public`) can
45
+ * name the exact type `signInWithSocial`/`linkSocialAccount` take, without
46
+ * needing their own dependency on contracts-public.
47
+ */
48
+ export type { SocialProvider } from "@smartcrab/contracts-public";
49
+
50
+ export { ReactNativeAuthClientError } from "./errors.js";
51
+ export type {
52
+ InvalidFlowStateError,
53
+ InvalidResponseError,
54
+ NetworkFailureError,
55
+ NotAuthenticatedError,
56
+ NotConfiguredError,
57
+ OAuthFailureError,
58
+ PasskeyNotSupportedError,
59
+ PasskeyOperationError,
60
+ PasskeyOperationFailureReason,
61
+ ProblemDetailsError,
62
+ RateLimitedError,
63
+ ReactNativeAuthError,
64
+ SocialCancelledError,
65
+ StateMismatchError,
66
+ } from "./errors.js";
67
+
68
+ /** Native adapter boundary (design.md §21.2) — never leaks react-native-passkeys types. */
69
+ export type { PasskeyNativeAdapter } from "./passkey-adapter.js";
70
+ export type { SecureStorePort } from "./secure-store.js";
71
+ export type { WebBrowserAuthResult, WebBrowserPort, WebBrowserResultType } from "./browser-port.js";
72
+ export type { LinkingPort, ParsedCallbackUrl } from "./linking-port.js";
73
+ export type { CryptoPort } from "./crypto-port.js";
74
+ export type {
75
+ AppStatePort,
76
+ AppStateStatus,
77
+ AppStateSubscription,
78
+ NetworkStatusPort,
79
+ } from "./lifecycle-ports.js";
80
+
81
+ // -- React API (design.md §21.4) --------------------------------------------
82
+ export { AuthProvider } from "./provider.js";
83
+ export type { AuthProviderProps } from "./provider.js";
84
+ export {
85
+ useAuth,
86
+ useEmailOtp,
87
+ usePasskey,
88
+ useSession,
89
+ useSessionList,
90
+ useSocialSignIn,
91
+ useUser,
92
+ } from "./hooks.js";
93
+ export type {
94
+ UseAuthResult,
95
+ UseEmailOtpResult,
96
+ UsePasskeyResult,
97
+ UseSessionListResult,
98
+ UseSessionResult,
99
+ UseSocialSignInResult,
100
+ UseUserResult,
101
+ } from "./hooks.js";
package/src/jwt.ts ADDED
@@ -0,0 +1,24 @@
1
+ import { base64UrlDecodeToUtf8String } from "./base64url.js";
2
+
3
+ /**
4
+ * Decodes (WITHOUT signature verification) the `sub` claim from a compact
5
+ * JWT's payload segment, purely to label the local `AuthSession`/SecureStore
6
+ * metadata with a user id (design.md §21.6 "session metadataの最小集合").
7
+ * This is not a trust boundary: the token was just issued to this same
8
+ * client over TLS by the token endpoint it requested it from, and resource
9
+ * servers independently verify the signature themselves (design.md §15.8) —
10
+ * this client never uses the decoded claims for an authorization decision.
11
+ */
12
+ const isRecord = (value: unknown): value is Record<string, unknown> =>
13
+ typeof value === "object" && value !== null && !Array.isArray(value);
14
+
15
+ export const decodeJwtSubClaim = (jwt: string): string | null => {
16
+ const parts = jwt.split(".");
17
+ const payloadSegment = parts[1];
18
+ if (payloadSegment === undefined) return null;
19
+ const json = base64UrlDecodeToUtf8String(payloadSegment);
20
+ const parsed: unknown = JSON.parse(json);
21
+ if (!isRecord(parsed)) return null;
22
+ const sub = parsed["sub"];
23
+ return typeof sub === "string" && sub.length > 0 ? sub : null;
24
+ };
@@ -0,0 +1,32 @@
1
+ /**
2
+ * App lifecycle ports (design.md §21.7).
3
+ *
4
+ * `AppStatePort` drives "foreground復帰時にtoken expiryを確認": React
5
+ * Native's `AppState` is a declared peer dependency (design.md §21.1) and is
6
+ * always available, so a default implementation ships.
7
+ *
8
+ * `NetworkStatusPort` drives "network復帰時に1回だけrefresh": no
9
+ * connectivity-detection package (e.g. `@react-native-community/netinfo`) is
10
+ * among design.md §21.1's peer dependencies, so this SDK cannot ship a real
11
+ * default for it without adding an undeclared dependency. It is therefore an
12
+ * OPTIONAL, injectable port (`ReactNativeAuthConfig.networkStatus`) —
13
+ * consuming apps that install a connectivity package wire it in; when
14
+ * omitted, only the foreground trigger runs. This is a deliberate, documented
15
+ * deviation from a literal reading of §21.7 (see IMPL_NOTES §0.1: "逸脱が必要
16
+ * な場合はコード内に理由をコメントし、最終報告で必ず申告する").
17
+ */
18
+ export interface AppStateSubscription {
19
+ remove(): void;
20
+ }
21
+
22
+ export type AppStateStatus = "active" | "background" | "inactive" | "unknown" | "extension";
23
+
24
+ export interface AppStatePort {
25
+ readonly currentState: AppStateStatus;
26
+ addEventListener(type: "change", handler: (state: AppStateStatus) => void): AppStateSubscription;
27
+ }
28
+
29
+ export interface NetworkStatusPort {
30
+ /** Invokes `listener(true)` on transition to online, `listener(false)` on transition to offline. */
31
+ subscribe(listener: (online: boolean) => void): () => void;
32
+ }