@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/plugin.ts ADDED
@@ -0,0 +1,387 @@
1
+ import {
2
+ AndroidConfig,
3
+ WarningAggregator,
4
+ createRunOncePlugin,
5
+ withAndroidManifest,
6
+ withEntitlementsPlist,
7
+ withInfoPlist,
8
+ withStringsXml,
9
+ } from "expo/config-plugins";
10
+ import type { AndroidManifest, ConfigPlugin, InfoPlist } from "expo/config-plugins";
11
+
12
+ type ManifestIntentFilter = AndroidConfig.Manifest.ManifestIntentFilter;
13
+ type ManifestIntentFilterData = NonNullable<ManifestIntentFilter["data"]>[number];
14
+
15
+ /**
16
+ * Expo Config Plugin (design.md §21.5), exported as `@smartcrab/react-native/plugin`.
17
+ *
18
+ * ```ts
19
+ * plugins: [["@smartcrab/react-native/plugin", { clientId, rpDomain, callbackPath }]]
20
+ * ```
21
+ *
22
+ * Does, per design.md §21.5:
23
+ * - iOS Associated Domains: `webcredentials:<rpDomain>` + `applinks:<rpDomain>` (Universal Link domain)
24
+ * - iOS `CFBundleURLTypes`: ensures the app's custom scheme (`expo.scheme`) is registered
25
+ * - Android intent filters: the custom scheme + an `autoVerify` HTTPS App Link for `<rpDomain><callbackPath>`
26
+ * - Android Credential Manager: an `asset_statements` string resource pointing at `<rpDomain>`'s
27
+ * `.well-known/assetlinks.json`, which Android's passkey Credential Manager provider reads
28
+ * - Validates `react-native-passkeys`-relevant config and turns unsupported deployments into
29
+ * build-time errors (a missing/malformed `expo.scheme`, or an explicit iOS deployment target
30
+ * below design.md §3.2's 15.1 floor)
31
+ *
32
+ * Apple Team ID / Bundle ID / Android package / signing fingerprints are registered with the
33
+ * platform's dashboard/CLI, not here (design.md §21.5) — this plugin only shapes the native
34
+ * project files that must agree with that registration.
35
+ */
36
+ export interface AuthPlatformReactNativePluginProps {
37
+ readonly clientId: string;
38
+ /** The Relying Party domain, e.g. `auth.customer.example` — a bare host, no scheme/path. */
39
+ readonly rpDomain: string;
40
+ /** Path segment the OAuth/social callback lands on, e.g. `oauth/callback` (no leading slash). */
41
+ readonly callbackPath: string;
42
+ }
43
+
44
+ const HOSTNAME_PATTERN = /^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)+$/i;
45
+ /** design.md §15.9: "React Native custom schemeはreverse-DNS形式を必須にする." */
46
+ const REVERSE_DNS_SCHEME_PATTERN = /^[a-z][a-z0-9-]*(\.[a-z][a-z0-9-]*)+$/i;
47
+ const MIN_IOS_DEPLOYMENT_TARGET = 15.1;
48
+
49
+ /**
50
+ * `expo/config-plugins`' own `PluginError` reserves its `code` values for the
51
+ * plugin-loading machinery itself (`PLUGIN_NOT_FOUND`, etc.), none of which
52
+ * fit application-level config validation, so these throw a plain `Error`
53
+ * instead — still a hard, uncaught failure of `expo prebuild`'s config
54
+ * evaluation step, i.e. a build-time error (design.md §21.5).
55
+ */
56
+ const validateProps = (props: AuthPlatformReactNativePluginProps): void => {
57
+ if (props.clientId.trim().length === 0) {
58
+ throw new Error("auth-platform/react-native config plugin: `clientId` must not be empty");
59
+ }
60
+ if (!HOSTNAME_PATTERN.test(props.rpDomain)) {
61
+ throw new Error(
62
+ `auth-platform/react-native config plugin: \`rpDomain\` must be a bare hostname (got ${JSON.stringify(props.rpDomain)})`,
63
+ );
64
+ }
65
+ if (
66
+ props.callbackPath.trim().length === 0 ||
67
+ props.callbackPath.includes("://") ||
68
+ props.callbackPath.startsWith("/")
69
+ ) {
70
+ throw new Error(
71
+ `auth-platform/react-native config plugin: \`callbackPath\` must be a bare relative path with no leading slash (got ${JSON.stringify(props.callbackPath)})`,
72
+ );
73
+ }
74
+ };
75
+
76
+ /** design.md §21.5: "unsupported deploymentをbuild-time errorにする." */
77
+ const validateScheme = (scheme: string | string[] | undefined): string => {
78
+ if (scheme === undefined) {
79
+ throw new Error(
80
+ "auth-platform/react-native config plugin: expo.scheme is required (React Native passkey/social callbacks need a registered custom scheme, design.md §15.9/§21.7) but was not set",
81
+ );
82
+ }
83
+ const primary = Array.isArray(scheme) ? scheme[0] : scheme;
84
+ if (primary === undefined || !REVERSE_DNS_SCHEME_PATTERN.test(primary)) {
85
+ throw new Error(
86
+ `auth-platform/react-native config plugin: expo.scheme must be reverse-DNS (design.md §15.9), e.g. "com.customer.app" (got ${JSON.stringify(scheme)})`,
87
+ );
88
+ }
89
+ return primary;
90
+ };
91
+
92
+ const validateIosDeploymentTarget = (deploymentTarget: string | undefined): void => {
93
+ if (deploymentTarget === undefined) return;
94
+ const parsed = Number.parseFloat(deploymentTarget);
95
+ if (Number.isNaN(parsed)) return;
96
+ if (parsed < MIN_IOS_DEPLOYMENT_TARGET) {
97
+ throw new Error(
98
+ `auth-platform/react-native config plugin: ios.deploymentTarget ${deploymentTarget} is below the design.md §3.2 floor (iOS ${MIN_IOS_DEPLOYMENT_TARGET}+)`,
99
+ );
100
+ }
101
+ };
102
+
103
+ const MIN_ANDROID_MIN_SDK_VERSION = 28;
104
+ const MIN_ANDROID_COMPILE_SDK_VERSION = 34;
105
+
106
+ /**
107
+ * design.md §3.2 floor (minSdk 28, compileSdk 34); §21.5 turns unsupported
108
+ * deployments into build-time errors. Expo sets these via the
109
+ * `expo-build-properties` plugin entry in `config.plugins`
110
+ * (`["expo-build-properties", { android: { minSdkVersion, compileSdkVersion } }]`),
111
+ * so only an *explicitly set* value below the floor throws — unset passes
112
+ * (Expo's own default already satisfies the floor). Malformed entries
113
+ * (bare strings, wrong arity/name, non-object props) are ignored.
114
+ */
115
+ export const validateAndroidSdkVersions = (plugins: readonly unknown[] | undefined): void => {
116
+ if (plugins === undefined) return;
117
+ for (const rawEntry of plugins) {
118
+ if (!Array.isArray(rawEntry)) continue;
119
+ const entry: readonly unknown[] = rawEntry;
120
+ if (entry.length < 2) continue;
121
+ const [name, props] = entry;
122
+ if (name !== "expo-build-properties") continue;
123
+ if (typeof props !== "object" || props === null || !("android" in props)) continue;
124
+ const android: unknown = props.android;
125
+ if (typeof android !== "object" || android === null) continue;
126
+ const minSdkVersion: unknown = "minSdkVersion" in android ? android.minSdkVersion : undefined;
127
+ if (typeof minSdkVersion === "number" && minSdkVersion < MIN_ANDROID_MIN_SDK_VERSION) {
128
+ throw new Error(
129
+ `auth-platform/react-native config plugin: expo-build-properties android.minSdkVersion ${minSdkVersion} is below the design.md §3.2 floor (Android minSdk ${MIN_ANDROID_MIN_SDK_VERSION}+)`,
130
+ );
131
+ }
132
+ const compileSdkVersion: unknown =
133
+ "compileSdkVersion" in android ? android.compileSdkVersion : undefined;
134
+ if (
135
+ typeof compileSdkVersion === "number" &&
136
+ compileSdkVersion < MIN_ANDROID_COMPILE_SDK_VERSION
137
+ ) {
138
+ throw new Error(
139
+ `auth-platform/react-native config plugin: expo-build-properties android.compileSdkVersion ${compileSdkVersion} is below the design.md §3.2 floor (Android compileSdk ${MIN_ANDROID_COMPILE_SDK_VERSION}+)`,
140
+ );
141
+ }
142
+ }
143
+ };
144
+
145
+ // ---------------------------------------------------------------------------
146
+ // iOS
147
+ // ---------------------------------------------------------------------------
148
+
149
+ export const ASSOCIATED_DOMAINS_KEY = "com.apple.developer.associated-domains";
150
+
151
+ /**
152
+ * Pure merge logic, extracted out of the `withEntitlementsPlist` mod callback
153
+ * so it is directly unit-testable: Expo's mod system defers the actual
154
+ * plist/manifest file mutation to `expo prebuild`'s mod-compilation step
155
+ * (`compileModsAsync`), so calling the exported plugin function in a unit
156
+ * test does NOT synchronously produce a mutated `config.ios`/`config.android`
157
+ * — only queues the mod. This function is what actually runs once compiled.
158
+ */
159
+ export const mergeAssociatedDomains = (existing: unknown, rpDomain: string): string[] => {
160
+ const current = Array.isArray(existing)
161
+ ? existing.filter((entry): entry is string => typeof entry === "string")
162
+ : [];
163
+ const required = [`webcredentials:${rpDomain}`, `applinks:${rpDomain}`];
164
+ return [...new Set([...current, ...required])];
165
+ };
166
+
167
+ const withAssociatedDomains: ConfigPlugin<AuthPlatformReactNativePluginProps> = (config, props) =>
168
+ withEntitlementsPlist(config, (modConfig) => {
169
+ modConfig.modResults[ASSOCIATED_DOMAINS_KEY] = mergeAssociatedDomains(
170
+ modConfig.modResults[ASSOCIATED_DOMAINS_KEY],
171
+ props.rpDomain,
172
+ );
173
+ return modConfig;
174
+ });
175
+
176
+ type UrlTypeEntry = NonNullable<InfoPlist["CFBundleURLTypes"]>[number];
177
+
178
+ export const mergeUrlScheme = (
179
+ existing: readonly UrlTypeEntry[] | undefined,
180
+ scheme: string,
181
+ ): UrlTypeEntry[] => {
182
+ const current = existing ?? [];
183
+ const alreadyRegistered = current.some(
184
+ (entry) => Array.isArray(entry.CFBundleURLSchemes) && entry.CFBundleURLSchemes.includes(scheme),
185
+ );
186
+ return alreadyRegistered ? [...current] : [...current, { CFBundleURLSchemes: [scheme] }];
187
+ };
188
+
189
+ const withUrlScheme: ConfigPlugin<{ scheme: string }> = (config, { scheme }) =>
190
+ withInfoPlist(config, (modConfig) => {
191
+ const urlTypes = Array.isArray(modConfig.modResults.CFBundleURLTypes)
192
+ ? modConfig.modResults.CFBundleURLTypes
193
+ : [];
194
+ modConfig.modResults.CFBundleURLTypes = mergeUrlScheme(urlTypes, scheme);
195
+ return modConfig;
196
+ });
197
+
198
+ // ---------------------------------------------------------------------------
199
+ // Android
200
+ // ---------------------------------------------------------------------------
201
+
202
+ const schemeIntentFilter = (scheme: string): ManifestIntentFilter => ({
203
+ action: [{ $: { "android:name": "android.intent.action.VIEW" } }],
204
+ category: [
205
+ { $: { "android:name": "android.intent.category.DEFAULT" } },
206
+ { $: { "android:name": "android.intent.category.BROWSABLE" } },
207
+ ],
208
+ data: [{ $: { "android:scheme": scheme } }],
209
+ });
210
+
211
+ const appLinkIntentFilter = (rpDomain: string, callbackPath: string): ManifestIntentFilter => ({
212
+ $: { "android:autoVerify": "true" },
213
+ action: [{ $: { "android:name": "android.intent.action.VIEW" } }],
214
+ category: [
215
+ { $: { "android:name": "android.intent.category.DEFAULT" } },
216
+ { $: { "android:name": "android.intent.category.BROWSABLE" } },
217
+ ],
218
+ data: [
219
+ {
220
+ $: {
221
+ "android:scheme": "https",
222
+ "android:host": rpDomain,
223
+ "android:pathPrefix": `/${callbackPath}`,
224
+ },
225
+ },
226
+ ],
227
+ });
228
+
229
+ /**
230
+ * Pure merge logic (see `mergeAssociatedDomains`'s doc comment on why this is extracted).
231
+ *
232
+ * The HTTPS App Link filter pins `callbackPath` in its `android:pathPrefix`,
233
+ * so a host-only existence check would leave a stale filter behind when
234
+ * `callbackPath` changes (and never add the fresh one): every existing HTTPS
235
+ * filter for `rpDomain` is dropped, then the fresh one is pushed.
236
+ */
237
+ export const mergeAndroidIntentFilters = (
238
+ existing: readonly ManifestIntentFilter[],
239
+ props: AuthPlatformReactNativePluginProps & { scheme: string },
240
+ ): ManifestIntentFilter[] => {
241
+ const hasData = (
242
+ filter: ManifestIntentFilter,
243
+ match: (data: ManifestIntentFilterData) => boolean,
244
+ ) => (filter.data ?? []).some(match);
245
+ const hasSchemeFilter = existing.some((filter) =>
246
+ hasData(
247
+ filter,
248
+ (data) => data.$["android:scheme"] === props.scheme && data.$["android:host"] === undefined,
249
+ ),
250
+ );
251
+ const nextFilters = existing.filter(
252
+ (filter) =>
253
+ !hasData(
254
+ filter,
255
+ (data) => data.$["android:host"] === props.rpDomain && data.$["android:scheme"] === "https",
256
+ ),
257
+ );
258
+ if (!hasSchemeFilter) nextFilters.push(schemeIntentFilter(props.scheme));
259
+ nextFilters.push(appLinkIntentFilter(props.rpDomain, props.callbackPath));
260
+ return nextFilters;
261
+ };
262
+
263
+ const withAndroidIntentFilters: ConfigPlugin<
264
+ AuthPlatformReactNativePluginProps & { scheme: string }
265
+ > = (config, props) =>
266
+ withAndroidManifest(config, (modConfig) => {
267
+ const manifest: AndroidManifest = modConfig.modResults;
268
+ const mainActivity = AndroidConfig.Manifest.getMainActivityOrThrow(manifest);
269
+ mainActivity["intent-filter"] = mergeAndroidIntentFilters(
270
+ mainActivity["intent-filter"] ?? [],
271
+ props,
272
+ );
273
+ return modConfig;
274
+ });
275
+
276
+ type ResourceItemXML = NonNullable<
277
+ AndroidConfig.Resources.ResourceXML["resources"]["string"]
278
+ >[number];
279
+
280
+ export const ASSET_STATEMENTS_RESOURCE_NAME = "asset_statements";
281
+
282
+ /**
283
+ * Android Credential Manager (design.md §21.5, §17): `asset_statements` is how
284
+ * Android's passkey provider verifies this app is authorized for `rpDomain`,
285
+ * mirroring the app's Digital Asset Links statement
286
+ * (`https://<rpDomain>/.well-known/assetlinks.json`, registered against the
287
+ * app's signing fingerprint on the platform dashboard per design.md §21.5's
288
+ * closing note). Pure merge logic (see `mergeAssociatedDomains`'s doc comment
289
+ * on why this is extracted).
290
+ */
291
+ export const mergeAssetStatementsResource = (
292
+ existing: readonly ResourceItemXML[],
293
+ rpDomain: string,
294
+ ): ResourceItemXML[] => {
295
+ const filtered = existing.filter((entry) => entry.$.name !== ASSET_STATEMENTS_RESOURCE_NAME);
296
+ const assetStatements = JSON.stringify([
297
+ { include: `https://${rpDomain}/.well-known/assetlinks.json` },
298
+ ]);
299
+ return [
300
+ ...filtered,
301
+ { _: assetStatements, $: { name: ASSET_STATEMENTS_RESOURCE_NAME, translatable: "false" } },
302
+ ];
303
+ };
304
+
305
+ const withCredentialManagerAssetStatements: ConfigPlugin<{ rpDomain: string }> = (
306
+ config,
307
+ { rpDomain },
308
+ ) =>
309
+ withStringsXml(config, (modConfig) => {
310
+ modConfig.modResults.resources.string = mergeAssetStatementsResource(
311
+ modConfig.modResults.resources.string ?? [],
312
+ rpDomain,
313
+ );
314
+ return modConfig;
315
+ });
316
+
317
+ type ManifestMetaData = AndroidConfig.Manifest.ManifestMetaData;
318
+
319
+ /**
320
+ * Android Credential Manager linkage (design.md §21.5, §17): the manifest's
321
+ * main `<application>` must point at the `asset_statements` string resource
322
+ * above, or Android's passkey Credential Manager provider never reads the
323
+ * Digital Asset Links statement. Pure merge logic (see
324
+ * `mergeAssociatedDomains`'s doc comment on why this is extracted): ensures
325
+ * exactly one `asset_statements` `<meta-data>` entry (replacing a stale
326
+ * same-name entry, preserving siblings).
327
+ */
328
+ export const mergeAssetStatementsMetaData = (
329
+ existing: readonly ManifestMetaData[] | undefined,
330
+ ): ManifestMetaData[] => {
331
+ const siblings = (existing ?? []).filter(
332
+ (entry) => entry.$["android:name"] !== ASSET_STATEMENTS_RESOURCE_NAME,
333
+ );
334
+ return [
335
+ ...siblings,
336
+ {
337
+ $: {
338
+ "android:name": ASSET_STATEMENTS_RESOURCE_NAME,
339
+ "android:resource": `@string/${ASSET_STATEMENTS_RESOURCE_NAME}`,
340
+ },
341
+ },
342
+ ];
343
+ };
344
+
345
+ const withAssetStatementsMetaData: ConfigPlugin = (config) =>
346
+ withAndroidManifest(config, (modConfig) => {
347
+ const manifest: AndroidManifest = modConfig.modResults;
348
+ const mainApplication = AndroidConfig.Manifest.getMainApplicationOrThrow(manifest);
349
+ mainApplication["meta-data"] = mergeAssetStatementsMetaData(mainApplication["meta-data"]);
350
+ return modConfig;
351
+ });
352
+
353
+ // ---------------------------------------------------------------------------
354
+ // Composition
355
+ // ---------------------------------------------------------------------------
356
+
357
+ const withAuthPlatformReactNative: ConfigPlugin<AuthPlatformReactNativePluginProps> = (
358
+ config,
359
+ props,
360
+ ) => {
361
+ validateProps(props);
362
+ const scheme = validateScheme(config.scheme);
363
+ validateIosDeploymentTarget(config.ios?.deploymentTarget);
364
+ validateAndroidSdkVersions(config.plugins);
365
+
366
+ if (config.android?.package === undefined) {
367
+ WarningAggregator.addWarningAndroid(
368
+ "auth-platform-react-native",
369
+ "android.package is not set; Android App Links / Credential Manager verification requires it before a production build.",
370
+ );
371
+ }
372
+
373
+ let nextConfig = withAssociatedDomains(config, props);
374
+ nextConfig = withUrlScheme(nextConfig, { scheme });
375
+ nextConfig = withAndroidIntentFilters(nextConfig, { ...props, scheme });
376
+ nextConfig = withCredentialManagerAssetStatements(nextConfig, { rpDomain: props.rpDomain });
377
+ nextConfig = withAssetStatementsMetaData(nextConfig);
378
+ return nextConfig;
379
+ };
380
+
381
+ const PLUGIN_VERSION = "0.1.0";
382
+
383
+ export default createRunOncePlugin(
384
+ withAuthPlatformReactNative,
385
+ "auth-platform-react-native",
386
+ PLUGIN_VERSION,
387
+ );
@@ -0,0 +1,20 @@
1
+ import type { ReactNode } from "react";
2
+ import { AuthContext } from "./context.js";
3
+ import type { ReactNativeAuthClient } from "./types.js";
4
+
5
+ /**
6
+ * `<AuthProvider client={authClient}><App/></AuthProvider>` (design.md §21.4).
7
+ * The client is expected to already be configured (either via
8
+ * `createReactNativeAuthClient(config)` or an explicit `.configure()` call)
9
+ * before it is passed in; the provider itself only wires context, it does not
10
+ * own the client's lifecycle.
11
+ */
12
+ export interface AuthProviderProps {
13
+ readonly client: ReactNativeAuthClient;
14
+ readonly children?: ReactNode;
15
+ }
16
+
17
+ export const AuthProvider = ({ client, children }: AuthProviderProps): ReactNode => (
18
+ // React 19 convention: the context object itself is the provider.
19
+ <AuthContext value={client}>{children}</AuthContext>
20
+ );
@@ -0,0 +1,91 @@
1
+ import { describe, expect, test } from "vitest";
2
+ import {
3
+ parsePersistedPendingTransaction,
4
+ parsePersistedRefreshRecord,
5
+ pendingTransactionKey,
6
+ refreshRecordKey,
7
+ } from "./secure-store.js";
8
+
9
+ describe("refreshRecordKey / pendingTransactionKey", () => {
10
+ test("refresh key uses the SecureStore-safe design namespace", () => {
11
+ expect(refreshRecordKey("env_abc", "cli_xxx")).toBe("example-auth-env_abc-cli_xxx-refresh");
12
+ });
13
+
14
+ test("pending transaction key uses the same namespace, a distinct suffix", () => {
15
+ expect(pendingTransactionKey("env_abc", "cli_xxx")).toBe("example-auth-env_abc-cli_xxx-pkce");
16
+ });
17
+
18
+ test("keys are distinct from one another", () => {
19
+ expect(refreshRecordKey("env_abc", "cli_xxx")).not.toBe(
20
+ pendingTransactionKey("env_abc", "cli_xxx"),
21
+ );
22
+ });
23
+ });
24
+
25
+ const VALID_REFRESH_RECORD = {
26
+ refreshToken: "rt-secret",
27
+ familyId: "fam-1",
28
+ userId: "usr_abc",
29
+ scope: "openid profile email offline_access",
30
+ clientId: "cli_xxx",
31
+ createdAt: 1000,
32
+ lastRefreshedAt: 2000,
33
+ };
34
+
35
+ describe("parsePersistedRefreshRecord", () => {
36
+ test("accepts a well-formed record", () => {
37
+ expect(parsePersistedRefreshRecord(VALID_REFRESH_RECORD)).toEqual(VALID_REFRESH_RECORD);
38
+ });
39
+
40
+ test("rejects non-objects", () => {
41
+ expect(parsePersistedRefreshRecord(null)).toBeNull();
42
+ expect(parsePersistedRefreshRecord("a string")).toBeNull();
43
+ expect(parsePersistedRefreshRecord([1, 2, 3])).toBeNull();
44
+ });
45
+
46
+ test("rejects a record missing refreshToken", () => {
47
+ const { refreshToken: _refreshToken, ...rest } = VALID_REFRESH_RECORD;
48
+ expect(parsePersistedRefreshRecord(rest)).toBeNull();
49
+ });
50
+
51
+ test("rejects a record whose refreshToken is empty", () => {
52
+ expect(parsePersistedRefreshRecord({ ...VALID_REFRESH_RECORD, refreshToken: "" })).toBeNull();
53
+ });
54
+
55
+ test("NEVER accepts an accessToken field as a substitute for the real shape (design.md §21.6)", () => {
56
+ // An access-token-shaped payload must not accidentally validate as a refresh record.
57
+ expect(parsePersistedRefreshRecord({ accessToken: "at-secret", expiresAt: 123 })).toBeNull();
58
+ });
59
+
60
+ test("rejects wrong-typed timestamps", () => {
61
+ expect(parsePersistedRefreshRecord({ ...VALID_REFRESH_RECORD, createdAt: "1000" })).toBeNull();
62
+ });
63
+ });
64
+
65
+ const VALID_PENDING = {
66
+ transactionId: "txn_abc",
67
+ state: "state-value",
68
+ codeVerifier: "verifier-value",
69
+ redirectUri: "com.customer.app:/oauth/callback",
70
+ createdAt: 1000,
71
+ };
72
+
73
+ describe("parsePersistedPendingTransaction", () => {
74
+ test("accepts a well-formed record without challengeId", () => {
75
+ expect(parsePersistedPendingTransaction(VALID_PENDING)).toEqual(VALID_PENDING);
76
+ });
77
+
78
+ test("accepts a well-formed record with challengeId", () => {
79
+ const withChallenge = { ...VALID_PENDING, challengeId: "chal_1" };
80
+ expect(parsePersistedPendingTransaction(withChallenge)).toEqual(withChallenge);
81
+ });
82
+
83
+ test("rejects a record whose challengeId is the wrong type", () => {
84
+ expect(parsePersistedPendingTransaction({ ...VALID_PENDING, challengeId: 123 })).toBeNull();
85
+ });
86
+
87
+ test("rejects a record missing a required field", () => {
88
+ const { state: _state, ...rest } = VALID_PENDING;
89
+ expect(parsePersistedPendingTransaction(rest)).toBeNull();
90
+ });
91
+ });
@@ -0,0 +1,102 @@
1
+ /**
2
+ * SecureStore discipline (design.md §21.6).
3
+ *
4
+ * Persisted (SecureStore):
5
+ * - refresh token
6
+ * - token family id
7
+ * - minimal session metadata (user id, scope, client id, timestamps)
8
+ * - transient PKCE transaction data (verifier/state/transaction id), cleared
9
+ * once the transaction is consumed or abandoned
10
+ *
11
+ * NEVER persisted: access token, full user profile, provider access tokens,
12
+ * OTP codes. The access token lives in the client's in-memory closure only
13
+ * (`client.ts`); nothing in this module ever touches it.
14
+ */
15
+ export interface SecureStorePort {
16
+ getItemAsync(key: string): Promise<string | null>;
17
+ setItemAsync(key: string, value: string): Promise<void>;
18
+ deleteItemAsync(key: string): Promise<void>;
19
+ }
20
+
21
+ /**
22
+ * Expo SecureStore keys accept only alphanumeric characters plus `.`, `_`, and
23
+ * `-`. The design's colon-delimited namespace is therefore encoded with
24
+ * hyphens while retaining the same environment/client/suffix boundaries.
25
+ */
26
+ const secureStoreKey = (environmentId: string, clientId: string, suffix: string): string =>
27
+ `example-auth-${environmentId}-${clientId}-${suffix}`;
28
+
29
+ /** Refresh token record key (design.md §21.6). */
30
+ export const refreshRecordKey = (environmentId: string, clientId: string): string =>
31
+ secureStoreKey(environmentId, clientId, "refresh");
32
+
33
+ /** Transient PKCE transaction record key (design.md §21.6). */
34
+ export const pendingTransactionKey = (environmentId: string, clientId: string): string =>
35
+ secureStoreKey(environmentId, clientId, "pkce");
36
+
37
+ /** Minimal session metadata persisted alongside the refresh token (design.md §21.6). */
38
+ export interface PersistedRefreshRecord {
39
+ readonly refreshToken: string;
40
+ /**
41
+ * Locally-minted stable id carried across same-lineage refresh rotations.
42
+ * contracts-public's `tokenResponseSchema` (design.md §15) exposes no
43
+ * distinct `family_id` on the wire — only an opaque `refresh_token` string
44
+ * — so this is a client-local bookkeeping value (not a security boundary;
45
+ * the server's own `RefreshFamilyDO`/`refresh_family_index`, design.md
46
+ * §12.7, is the source of truth for family-based revocation).
47
+ */
48
+ readonly familyId: string;
49
+ readonly userId: string;
50
+ readonly scope: string;
51
+ readonly clientId: string;
52
+ readonly createdAt: number;
53
+ readonly lastRefreshedAt: number;
54
+ }
55
+
56
+ /** Transient PKCE state for an in-flight auth transaction (design.md §21.6, §16.1, §20.6). */
57
+ export interface PersistedPendingTransaction {
58
+ readonly transactionId: string;
59
+ readonly state: string;
60
+ readonly codeVerifier: string;
61
+ readonly redirectUri: string;
62
+ readonly createdAt: number;
63
+ /** Correlates `sendEmailCode`/`verifyEmailCode` (design.md §21.3 — `verifyEmailCode` takes only `challengeId`). */
64
+ readonly challengeId?: string;
65
+ }
66
+
67
+ const isRecord = (value: unknown): value is Record<string, unknown> =>
68
+ typeof value === "object" && value !== null && !Array.isArray(value);
69
+
70
+ /** Never trusts SecureStore contents blindly (IMPL_NOTES §1): hand-narrowed, not `as`-cast. */
71
+ export const parsePersistedRefreshRecord = (value: unknown): PersistedRefreshRecord | null => {
72
+ if (!isRecord(value)) return null;
73
+ const { refreshToken, familyId, userId, scope, clientId, createdAt, lastRefreshedAt } = value;
74
+ if (typeof refreshToken !== "string" || refreshToken.length === 0) return null;
75
+ if (typeof familyId !== "string" || familyId.length === 0) return null;
76
+ if (typeof userId !== "string" || userId.length === 0) return null;
77
+ if (typeof scope !== "string") return null;
78
+ if (typeof clientId !== "string" || clientId.length === 0) return null;
79
+ if (typeof createdAt !== "number" || typeof lastRefreshedAt !== "number") return null;
80
+ return { refreshToken, familyId, userId, scope, clientId, createdAt, lastRefreshedAt };
81
+ };
82
+
83
+ export const parsePersistedPendingTransaction = (
84
+ value: unknown,
85
+ ): PersistedPendingTransaction | null => {
86
+ if (!isRecord(value)) return null;
87
+ const { transactionId, state, codeVerifier, redirectUri, createdAt, challengeId } = value;
88
+ if (typeof transactionId !== "string" || transactionId.length === 0) return null;
89
+ if (typeof state !== "string" || state.length === 0) return null;
90
+ if (typeof codeVerifier !== "string" || codeVerifier.length === 0) return null;
91
+ if (typeof redirectUri !== "string" || redirectUri.length === 0) return null;
92
+ if (typeof createdAt !== "number") return null;
93
+ if (challengeId !== undefined && typeof challengeId !== "string") return null;
94
+ return {
95
+ transactionId,
96
+ state,
97
+ codeVerifier,
98
+ redirectUri,
99
+ createdAt,
100
+ ...(challengeId !== undefined ? { challengeId } : {}),
101
+ };
102
+ };