@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/dist/plugin.js ADDED
@@ -0,0 +1,242 @@
1
+ import { AndroidConfig, WarningAggregator, createRunOncePlugin, withAndroidManifest, withEntitlementsPlist, withInfoPlist, withStringsXml, } from "expo/config-plugins";
2
+ const HOSTNAME_PATTERN = /^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)+$/i;
3
+ /** design.md §15.9: "React Native custom schemeはreverse-DNS形式を必須にする." */
4
+ const REVERSE_DNS_SCHEME_PATTERN = /^[a-z][a-z0-9-]*(\.[a-z][a-z0-9-]*)+$/i;
5
+ const MIN_IOS_DEPLOYMENT_TARGET = 15.1;
6
+ /**
7
+ * `expo/config-plugins`' own `PluginError` reserves its `code` values for the
8
+ * plugin-loading machinery itself (`PLUGIN_NOT_FOUND`, etc.), none of which
9
+ * fit application-level config validation, so these throw a plain `Error`
10
+ * instead — still a hard, uncaught failure of `expo prebuild`'s config
11
+ * evaluation step, i.e. a build-time error (design.md §21.5).
12
+ */
13
+ const validateProps = (props) => {
14
+ if (props.clientId.trim().length === 0) {
15
+ throw new Error("auth-platform/react-native config plugin: `clientId` must not be empty");
16
+ }
17
+ if (!HOSTNAME_PATTERN.test(props.rpDomain)) {
18
+ throw new Error(`auth-platform/react-native config plugin: \`rpDomain\` must be a bare hostname (got ${JSON.stringify(props.rpDomain)})`);
19
+ }
20
+ if (props.callbackPath.trim().length === 0 ||
21
+ props.callbackPath.includes("://") ||
22
+ props.callbackPath.startsWith("/")) {
23
+ throw new Error(`auth-platform/react-native config plugin: \`callbackPath\` must be a bare relative path with no leading slash (got ${JSON.stringify(props.callbackPath)})`);
24
+ }
25
+ };
26
+ /** design.md §21.5: "unsupported deploymentをbuild-time errorにする." */
27
+ const validateScheme = (scheme) => {
28
+ if (scheme === undefined) {
29
+ throw new Error("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");
30
+ }
31
+ const primary = Array.isArray(scheme) ? scheme[0] : scheme;
32
+ if (primary === undefined || !REVERSE_DNS_SCHEME_PATTERN.test(primary)) {
33
+ throw new Error(`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)})`);
34
+ }
35
+ return primary;
36
+ };
37
+ const validateIosDeploymentTarget = (deploymentTarget) => {
38
+ if (deploymentTarget === undefined)
39
+ return;
40
+ const parsed = Number.parseFloat(deploymentTarget);
41
+ if (Number.isNaN(parsed))
42
+ return;
43
+ if (parsed < MIN_IOS_DEPLOYMENT_TARGET) {
44
+ throw new Error(`auth-platform/react-native config plugin: ios.deploymentTarget ${deploymentTarget} is below the design.md §3.2 floor (iOS ${MIN_IOS_DEPLOYMENT_TARGET}+)`);
45
+ }
46
+ };
47
+ const MIN_ANDROID_MIN_SDK_VERSION = 28;
48
+ const MIN_ANDROID_COMPILE_SDK_VERSION = 34;
49
+ /**
50
+ * design.md §3.2 floor (minSdk 28, compileSdk 34); §21.5 turns unsupported
51
+ * deployments into build-time errors. Expo sets these via the
52
+ * `expo-build-properties` plugin entry in `config.plugins`
53
+ * (`["expo-build-properties", { android: { minSdkVersion, compileSdkVersion } }]`),
54
+ * so only an *explicitly set* value below the floor throws — unset passes
55
+ * (Expo's own default already satisfies the floor). Malformed entries
56
+ * (bare strings, wrong arity/name, non-object props) are ignored.
57
+ */
58
+ export const validateAndroidSdkVersions = (plugins) => {
59
+ if (plugins === undefined)
60
+ return;
61
+ for (const rawEntry of plugins) {
62
+ if (!Array.isArray(rawEntry))
63
+ continue;
64
+ const entry = rawEntry;
65
+ if (entry.length < 2)
66
+ continue;
67
+ const [name, props] = entry;
68
+ if (name !== "expo-build-properties")
69
+ continue;
70
+ if (typeof props !== "object" || props === null || !("android" in props))
71
+ continue;
72
+ const android = props.android;
73
+ if (typeof android !== "object" || android === null)
74
+ continue;
75
+ const minSdkVersion = "minSdkVersion" in android ? android.minSdkVersion : undefined;
76
+ if (typeof minSdkVersion === "number" && minSdkVersion < MIN_ANDROID_MIN_SDK_VERSION) {
77
+ throw new Error(`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}+)`);
78
+ }
79
+ const compileSdkVersion = "compileSdkVersion" in android ? android.compileSdkVersion : undefined;
80
+ if (typeof compileSdkVersion === "number" &&
81
+ compileSdkVersion < MIN_ANDROID_COMPILE_SDK_VERSION) {
82
+ throw new Error(`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}+)`);
83
+ }
84
+ }
85
+ };
86
+ // ---------------------------------------------------------------------------
87
+ // iOS
88
+ // ---------------------------------------------------------------------------
89
+ export const ASSOCIATED_DOMAINS_KEY = "com.apple.developer.associated-domains";
90
+ /**
91
+ * Pure merge logic, extracted out of the `withEntitlementsPlist` mod callback
92
+ * so it is directly unit-testable: Expo's mod system defers the actual
93
+ * plist/manifest file mutation to `expo prebuild`'s mod-compilation step
94
+ * (`compileModsAsync`), so calling the exported plugin function in a unit
95
+ * test does NOT synchronously produce a mutated `config.ios`/`config.android`
96
+ * — only queues the mod. This function is what actually runs once compiled.
97
+ */
98
+ export const mergeAssociatedDomains = (existing, rpDomain) => {
99
+ const current = Array.isArray(existing)
100
+ ? existing.filter((entry) => typeof entry === "string")
101
+ : [];
102
+ const required = [`webcredentials:${rpDomain}`, `applinks:${rpDomain}`];
103
+ return [...new Set([...current, ...required])];
104
+ };
105
+ const withAssociatedDomains = (config, props) => withEntitlementsPlist(config, (modConfig) => {
106
+ modConfig.modResults[ASSOCIATED_DOMAINS_KEY] = mergeAssociatedDomains(modConfig.modResults[ASSOCIATED_DOMAINS_KEY], props.rpDomain);
107
+ return modConfig;
108
+ });
109
+ export const mergeUrlScheme = (existing, scheme) => {
110
+ const current = existing ?? [];
111
+ const alreadyRegistered = current.some((entry) => Array.isArray(entry.CFBundleURLSchemes) && entry.CFBundleURLSchemes.includes(scheme));
112
+ return alreadyRegistered ? [...current] : [...current, { CFBundleURLSchemes: [scheme] }];
113
+ };
114
+ const withUrlScheme = (config, { scheme }) => withInfoPlist(config, (modConfig) => {
115
+ const urlTypes = Array.isArray(modConfig.modResults.CFBundleURLTypes)
116
+ ? modConfig.modResults.CFBundleURLTypes
117
+ : [];
118
+ modConfig.modResults.CFBundleURLTypes = mergeUrlScheme(urlTypes, scheme);
119
+ return modConfig;
120
+ });
121
+ // ---------------------------------------------------------------------------
122
+ // Android
123
+ // ---------------------------------------------------------------------------
124
+ const schemeIntentFilter = (scheme) => ({
125
+ action: [{ $: { "android:name": "android.intent.action.VIEW" } }],
126
+ category: [
127
+ { $: { "android:name": "android.intent.category.DEFAULT" } },
128
+ { $: { "android:name": "android.intent.category.BROWSABLE" } },
129
+ ],
130
+ data: [{ $: { "android:scheme": scheme } }],
131
+ });
132
+ const appLinkIntentFilter = (rpDomain, callbackPath) => ({
133
+ $: { "android:autoVerify": "true" },
134
+ action: [{ $: { "android:name": "android.intent.action.VIEW" } }],
135
+ category: [
136
+ { $: { "android:name": "android.intent.category.DEFAULT" } },
137
+ { $: { "android:name": "android.intent.category.BROWSABLE" } },
138
+ ],
139
+ data: [
140
+ {
141
+ $: {
142
+ "android:scheme": "https",
143
+ "android:host": rpDomain,
144
+ "android:pathPrefix": `/${callbackPath}`,
145
+ },
146
+ },
147
+ ],
148
+ });
149
+ /**
150
+ * Pure merge logic (see `mergeAssociatedDomains`'s doc comment on why this is extracted).
151
+ *
152
+ * The HTTPS App Link filter pins `callbackPath` in its `android:pathPrefix`,
153
+ * so a host-only existence check would leave a stale filter behind when
154
+ * `callbackPath` changes (and never add the fresh one): every existing HTTPS
155
+ * filter for `rpDomain` is dropped, then the fresh one is pushed.
156
+ */
157
+ export const mergeAndroidIntentFilters = (existing, props) => {
158
+ const hasData = (filter, match) => (filter.data ?? []).some(match);
159
+ const hasSchemeFilter = existing.some((filter) => hasData(filter, (data) => data.$["android:scheme"] === props.scheme && data.$["android:host"] === undefined));
160
+ const nextFilters = existing.filter((filter) => !hasData(filter, (data) => data.$["android:host"] === props.rpDomain && data.$["android:scheme"] === "https"));
161
+ if (!hasSchemeFilter)
162
+ nextFilters.push(schemeIntentFilter(props.scheme));
163
+ nextFilters.push(appLinkIntentFilter(props.rpDomain, props.callbackPath));
164
+ return nextFilters;
165
+ };
166
+ const withAndroidIntentFilters = (config, props) => withAndroidManifest(config, (modConfig) => {
167
+ const manifest = modConfig.modResults;
168
+ const mainActivity = AndroidConfig.Manifest.getMainActivityOrThrow(manifest);
169
+ mainActivity["intent-filter"] = mergeAndroidIntentFilters(mainActivity["intent-filter"] ?? [], props);
170
+ return modConfig;
171
+ });
172
+ export const ASSET_STATEMENTS_RESOURCE_NAME = "asset_statements";
173
+ /**
174
+ * Android Credential Manager (design.md §21.5, §17): `asset_statements` is how
175
+ * Android's passkey provider verifies this app is authorized for `rpDomain`,
176
+ * mirroring the app's Digital Asset Links statement
177
+ * (`https://<rpDomain>/.well-known/assetlinks.json`, registered against the
178
+ * app's signing fingerprint on the platform dashboard per design.md §21.5's
179
+ * closing note). Pure merge logic (see `mergeAssociatedDomains`'s doc comment
180
+ * on why this is extracted).
181
+ */
182
+ export const mergeAssetStatementsResource = (existing, rpDomain) => {
183
+ const filtered = existing.filter((entry) => entry.$.name !== ASSET_STATEMENTS_RESOURCE_NAME);
184
+ const assetStatements = JSON.stringify([
185
+ { include: `https://${rpDomain}/.well-known/assetlinks.json` },
186
+ ]);
187
+ return [
188
+ ...filtered,
189
+ { _: assetStatements, $: { name: ASSET_STATEMENTS_RESOURCE_NAME, translatable: "false" } },
190
+ ];
191
+ };
192
+ const withCredentialManagerAssetStatements = (config, { rpDomain }) => withStringsXml(config, (modConfig) => {
193
+ modConfig.modResults.resources.string = mergeAssetStatementsResource(modConfig.modResults.resources.string ?? [], rpDomain);
194
+ return modConfig;
195
+ });
196
+ /**
197
+ * Android Credential Manager linkage (design.md §21.5, §17): the manifest's
198
+ * main `<application>` must point at the `asset_statements` string resource
199
+ * above, or Android's passkey Credential Manager provider never reads the
200
+ * Digital Asset Links statement. Pure merge logic (see
201
+ * `mergeAssociatedDomains`'s doc comment on why this is extracted): ensures
202
+ * exactly one `asset_statements` `<meta-data>` entry (replacing a stale
203
+ * same-name entry, preserving siblings).
204
+ */
205
+ export const mergeAssetStatementsMetaData = (existing) => {
206
+ const siblings = (existing ?? []).filter((entry) => entry.$["android:name"] !== ASSET_STATEMENTS_RESOURCE_NAME);
207
+ return [
208
+ ...siblings,
209
+ {
210
+ $: {
211
+ "android:name": ASSET_STATEMENTS_RESOURCE_NAME,
212
+ "android:resource": `@string/${ASSET_STATEMENTS_RESOURCE_NAME}`,
213
+ },
214
+ },
215
+ ];
216
+ };
217
+ const withAssetStatementsMetaData = (config) => withAndroidManifest(config, (modConfig) => {
218
+ const manifest = modConfig.modResults;
219
+ const mainApplication = AndroidConfig.Manifest.getMainApplicationOrThrow(manifest);
220
+ mainApplication["meta-data"] = mergeAssetStatementsMetaData(mainApplication["meta-data"]);
221
+ return modConfig;
222
+ });
223
+ // ---------------------------------------------------------------------------
224
+ // Composition
225
+ // ---------------------------------------------------------------------------
226
+ const withAuthPlatformReactNative = (config, props) => {
227
+ validateProps(props);
228
+ const scheme = validateScheme(config.scheme);
229
+ validateIosDeploymentTarget(config.ios?.deploymentTarget);
230
+ validateAndroidSdkVersions(config.plugins);
231
+ if (config.android?.package === undefined) {
232
+ WarningAggregator.addWarningAndroid("auth-platform-react-native", "android.package is not set; Android App Links / Credential Manager verification requires it before a production build.");
233
+ }
234
+ let nextConfig = withAssociatedDomains(config, props);
235
+ nextConfig = withUrlScheme(nextConfig, { scheme });
236
+ nextConfig = withAndroidIntentFilters(nextConfig, { ...props, scheme });
237
+ nextConfig = withCredentialManagerAssetStatements(nextConfig, { rpDomain: props.rpDomain });
238
+ nextConfig = withAssetStatementsMetaData(nextConfig);
239
+ return nextConfig;
240
+ };
241
+ const PLUGIN_VERSION = "0.1.0";
242
+ export default createRunOncePlugin(withAuthPlatformReactNative, "auth-platform-react-native", PLUGIN_VERSION);
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,210 @@
1
+ import { describe, expect, test } from "vitest";
2
+ import { ASSET_STATEMENTS_RESOURCE_NAME, mergeAndroidIntentFilters, mergeAssetStatementsMetaData, mergeAssetStatementsResource, mergeAssociatedDomains, mergeUrlScheme, validateAndroidSdkVersions, } from "./plugin.js";
3
+ import plugin from "./plugin.js";
4
+ const PROPS = {
5
+ clientId: "cli_xxx",
6
+ rpDomain: "auth.customer.example",
7
+ callbackPath: "oauth/callback",
8
+ };
9
+ const baseConfig = (overrides) => ({
10
+ name: "customer-app",
11
+ slug: "customer-app",
12
+ scheme: "com.customer.app",
13
+ ...overrides,
14
+ });
15
+ describe("auth-platform-react-native config plugin — validation (design.md §21.5)", () => {
16
+ test("a well-formed config does not throw", () => {
17
+ expect(() => plugin(baseConfig(), PROPS)).not.toThrow();
18
+ });
19
+ test("throws a build-time error when expo.scheme is missing", () => {
20
+ const configWithoutScheme = { name: "customer-app", slug: "customer-app" };
21
+ expect(() => plugin(configWithoutScheme, PROPS)).toThrow(/scheme is required/);
22
+ });
23
+ test("throws when expo.scheme is not reverse-DNS (design.md §15.9)", () => {
24
+ expect(() => plugin(baseConfig({ scheme: "notreversedns" }), PROPS)).toThrow(/reverse-DNS/);
25
+ });
26
+ test("throws when rpDomain is not a bare hostname", () => {
27
+ expect(() => plugin(baseConfig(), { ...PROPS, rpDomain: "https://auth.customer.example/" })).toThrow(/bare hostname/);
28
+ });
29
+ test("throws when callbackPath has a leading slash", () => {
30
+ expect(() => plugin(baseConfig(), { ...PROPS, callbackPath: "/oauth/callback" })).toThrow(/no leading slash/);
31
+ });
32
+ test("throws when clientId is empty", () => {
33
+ expect(() => plugin(baseConfig(), { ...PROPS, clientId: "" })).toThrow(/clientId/);
34
+ });
35
+ test("throws when the iOS deployment target is explicitly below design.md §3.2's 15.1 floor", () => {
36
+ expect(() => plugin(baseConfig({ ios: { deploymentTarget: "14.0" } }), PROPS)).toThrow(/15\.1/);
37
+ });
38
+ test("accepts an iOS deployment target at/above the floor", () => {
39
+ expect(() => plugin(baseConfig({ ios: { deploymentTarget: "15.1" } }), PROPS)).not.toThrow();
40
+ });
41
+ });
42
+ describe("mergeAssociatedDomains", () => {
43
+ test("adds both webcredentials and applinks entries", () => {
44
+ expect(mergeAssociatedDomains(undefined, "auth.customer.example")).toEqual([
45
+ "webcredentials:auth.customer.example",
46
+ "applinks:auth.customer.example",
47
+ ]);
48
+ });
49
+ test("preserves an existing, unrelated domain", () => {
50
+ const result = mergeAssociatedDomains(["webcredentials:other.example"], "auth.customer.example");
51
+ expect(result).toContain("webcredentials:other.example");
52
+ expect(result).toContain("webcredentials:auth.customer.example");
53
+ });
54
+ test("is idempotent", () => {
55
+ const once = mergeAssociatedDomains(undefined, "auth.customer.example");
56
+ const twice = mergeAssociatedDomains(once, "auth.customer.example");
57
+ expect(twice.filter((d) => d === "webcredentials:auth.customer.example")).toHaveLength(1);
58
+ expect(twice).toHaveLength(2);
59
+ });
60
+ test("ignores non-string entries in a malformed existing entitlement", () => {
61
+ expect(mergeAssociatedDomains([1, null, "webcredentials:kept.example"], "auth.customer.example")).toContain("webcredentials:kept.example");
62
+ });
63
+ });
64
+ describe("mergeUrlScheme", () => {
65
+ test("registers the scheme when absent", () => {
66
+ expect(mergeUrlScheme(undefined, "com.customer.app")).toEqual([
67
+ { CFBundleURLSchemes: ["com.customer.app"] },
68
+ ]);
69
+ });
70
+ test("does not duplicate an already-registered scheme", () => {
71
+ const existing = [{ CFBundleURLSchemes: ["com.customer.app"] }];
72
+ expect(mergeUrlScheme(existing, "com.customer.app")).toEqual(existing);
73
+ });
74
+ test("preserves other URL type entries", () => {
75
+ const existing = [{ CFBundleURLSchemes: ["other-scheme"] }];
76
+ const result = mergeUrlScheme(existing, "com.customer.app");
77
+ expect(result).toHaveLength(2);
78
+ });
79
+ });
80
+ describe("mergeAndroidIntentFilters", () => {
81
+ test("adds a custom-scheme filter and an autoVerify HTTPS App Link filter", () => {
82
+ const result = mergeAndroidIntentFilters([], { ...PROPS, scheme: "com.customer.app" });
83
+ expect(result).toHaveLength(2);
84
+ const linkFilter = result.find((f) => f.$?.["android:autoVerify"] === "true");
85
+ expect(linkFilter?.data?.[0]?.$["android:host"]).toBe("auth.customer.example");
86
+ expect(linkFilter?.data?.[0]?.$["android:pathPrefix"]).toBe("/oauth/callback");
87
+ const schemeFilter = result.find((f) => f.$?.["android:autoVerify"] === undefined);
88
+ expect(schemeFilter?.data?.[0]?.$["android:scheme"]).toBe("com.customer.app");
89
+ });
90
+ test("does not duplicate filters already present", () => {
91
+ const once = mergeAndroidIntentFilters([], { ...PROPS, scheme: "com.customer.app" });
92
+ const twice = mergeAndroidIntentFilters(once, { ...PROPS, scheme: "com.customer.app" });
93
+ expect(twice).toHaveLength(2);
94
+ });
95
+ test("preserves an unrelated pre-existing intent filter", () => {
96
+ const unrelated = { action: [{ $: { "android:name": "android.intent.action.MAIN" } }] };
97
+ const result = mergeAndroidIntentFilters([unrelated], { ...PROPS, scheme: "com.customer.app" });
98
+ expect(result).toContainEqual(unrelated);
99
+ expect(result).toHaveLength(3);
100
+ });
101
+ test("replaces a stale HTTPS filter when callbackPath changes instead of duplicating it", () => {
102
+ const stale = mergeAndroidIntentFilters([], {
103
+ ...PROPS,
104
+ callbackPath: "old/callback",
105
+ scheme: "com.customer.app",
106
+ });
107
+ const result = mergeAndroidIntentFilters(stale, { ...PROPS, scheme: "com.customer.app" });
108
+ const linkFilters = result.filter((f) => f.$?.["android:autoVerify"] === "true");
109
+ expect(linkFilters).toHaveLength(1);
110
+ expect(linkFilters[0]?.data?.[0]?.$["android:pathPrefix"]).toBe("/oauth/callback");
111
+ expect(result).toHaveLength(2);
112
+ });
113
+ });
114
+ describe("mergeAssetStatementsResource", () => {
115
+ test("adds an asset_statements string resource pointing at the rpDomain's assetlinks.json", () => {
116
+ const result = mergeAssetStatementsResource([], "auth.customer.example");
117
+ expect(result).toHaveLength(1);
118
+ expect(result[0]?.$.name).toBe(ASSET_STATEMENTS_RESOURCE_NAME);
119
+ expect(JSON.parse(result[0]?._ ?? "[]")).toEqual([
120
+ { include: "https://auth.customer.example/.well-known/assetlinks.json" },
121
+ ]);
122
+ });
123
+ test("replaces a stale asset_statements entry rather than duplicating it", () => {
124
+ const stale = { _: "[]", $: { name: ASSET_STATEMENTS_RESOURCE_NAME, translatable: "false" } };
125
+ const result = mergeAssetStatementsResource([stale], "auth.customer.example");
126
+ expect(result).toHaveLength(1);
127
+ expect(result[0]?._).not.toBe("[]");
128
+ });
129
+ test("preserves unrelated string resources", () => {
130
+ const other = { _: "value", $: { name: "app_name" } };
131
+ const result = mergeAssetStatementsResource([other], "auth.customer.example");
132
+ expect(result).toContainEqual(other);
133
+ });
134
+ });
135
+ describe("validateAndroidSdkVersions (design.md §3.2: minSdk 28, compileSdk 34)", () => {
136
+ test("throws a build-time error mentioning 28 when minSdkVersion is 27", () => {
137
+ expect(() => validateAndroidSdkVersions([["expo-build-properties", { android: { minSdkVersion: 27 } }]])).toThrow(/28/);
138
+ });
139
+ test("throws a build-time error mentioning 34 when compileSdkVersion is 33", () => {
140
+ expect(() => validateAndroidSdkVersions([
141
+ ["expo-build-properties", { android: { compileSdkVersion: 33 } }],
142
+ ])).toThrow(/34/);
143
+ });
144
+ test("passes at exactly the floor and above", () => {
145
+ expect(() => validateAndroidSdkVersions([
146
+ ["expo-build-properties", { android: { minSdkVersion: 28, compileSdkVersion: 34 } }],
147
+ ["expo-build-properties", { android: { minSdkVersion: 34, compileSdkVersion: 35 } }],
148
+ ])).not.toThrow();
149
+ });
150
+ test("passes when versions are unset", () => {
151
+ expect(() => validateAndroidSdkVersions(undefined)).not.toThrow();
152
+ expect(() => validateAndroidSdkVersions([])).not.toThrow();
153
+ expect(() => validateAndroidSdkVersions(["expo-build-properties"])).not.toThrow();
154
+ expect(() => validateAndroidSdkVersions([["expo-build-properties", { ios: {} }]])).not.toThrow();
155
+ expect(() => validateAndroidSdkVersions([["expo-build-properties", { android: {} }]])).not.toThrow();
156
+ });
157
+ test("ignores malformed plugin entries", () => {
158
+ expect(() => validateAndroidSdkVersions([
159
+ "expo-router",
160
+ [],
161
+ ["expo-build-properties"],
162
+ ["other-plugin", { android: { minSdkVersion: 21 } }],
163
+ ["expo-build-properties", null],
164
+ ["expo-build-properties", { android: null }],
165
+ ["expo-build-properties", { android: { minSdkVersion: "27" } }],
166
+ ])).not.toThrow();
167
+ });
168
+ test("is enforced through the plugin entrypoint", () => {
169
+ expect(() => plugin(baseConfig({ plugins: [["expo-build-properties", { android: { minSdkVersion: 27 } }]] }), PROPS)).toThrow(/28/);
170
+ expect(() => plugin(baseConfig({
171
+ plugins: [["expo-build-properties", { android: { minSdkVersion: 28 } }]],
172
+ }), PROPS)).not.toThrow();
173
+ });
174
+ });
175
+ describe("mergeAssetStatementsMetaData", () => {
176
+ test("adds exactly one asset_statements meta-data entry", () => {
177
+ const result = mergeAssetStatementsMetaData(undefined);
178
+ expect(result).toEqual([
179
+ {
180
+ $: {
181
+ "android:name": ASSET_STATEMENTS_RESOURCE_NAME,
182
+ "android:resource": `@string/${ASSET_STATEMENTS_RESOURCE_NAME}`,
183
+ },
184
+ },
185
+ ]);
186
+ });
187
+ test("is idempotent on re-run", () => {
188
+ const once = mergeAssetStatementsMetaData(undefined);
189
+ const twice = mergeAssetStatementsMetaData(once);
190
+ expect(twice).toHaveLength(1);
191
+ expect(twice).toEqual(once);
192
+ });
193
+ test("preserves sibling meta-data entries", () => {
194
+ const sibling = {
195
+ $: {
196
+ "android:name": "com.google.firebase.messaging.default_notification_icon",
197
+ "android:resource": "@drawable/ic_notification",
198
+ },
199
+ };
200
+ const result = mergeAssetStatementsMetaData([sibling]);
201
+ expect(result).toContainEqual(sibling);
202
+ expect(result).toHaveLength(2);
203
+ });
204
+ test("replaces a stale same-name entry rather than duplicating it", () => {
205
+ const stale = { $: { "android:name": ASSET_STATEMENTS_RESOURCE_NAME, "android:value": "x" } };
206
+ const result = mergeAssetStatementsMetaData([stale]);
207
+ expect(result).toHaveLength(1);
208
+ expect(result[0]?.$["android:resource"]).toBe(`@string/${ASSET_STATEMENTS_RESOURCE_NAME}`);
209
+ });
210
+ });
@@ -0,0 +1,14 @@
1
+ import type { ReactNode } from "react";
2
+ import type { ReactNativeAuthClient } from "./types.js";
3
+ /**
4
+ * `<AuthProvider client={authClient}><App/></AuthProvider>` (design.md §21.4).
5
+ * The client is expected to already be configured (either via
6
+ * `createReactNativeAuthClient(config)` or an explicit `.configure()` call)
7
+ * before it is passed in; the provider itself only wires context, it does not
8
+ * own the client's lifecycle.
9
+ */
10
+ export interface AuthProviderProps {
11
+ readonly client: ReactNativeAuthClient;
12
+ readonly children?: ReactNode;
13
+ }
14
+ export declare const AuthProvider: ({ client, children }: AuthProviderProps) => ReactNode;
@@ -0,0 +1,5 @@
1
+ import { jsx as _jsx } from "react/jsx-runtime";
2
+ import { AuthContext } from "./context.js";
3
+ export const AuthProvider = ({ client, children }) => (
4
+ // React 19 convention: the context object itself is the provider.
5
+ _jsx(AuthContext, { value: client, children: children }));
@@ -0,0 +1,54 @@
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
+ /** Refresh token record key (design.md §21.6). */
21
+ export declare const refreshRecordKey: (environmentId: string, clientId: string) => string;
22
+ /** Transient PKCE transaction record key (design.md §21.6). */
23
+ export declare const pendingTransactionKey: (environmentId: string, clientId: string) => string;
24
+ /** Minimal session metadata persisted alongside the refresh token (design.md §21.6). */
25
+ export interface PersistedRefreshRecord {
26
+ readonly refreshToken: string;
27
+ /**
28
+ * Locally-minted stable id carried across same-lineage refresh rotations.
29
+ * contracts-public's `tokenResponseSchema` (design.md §15) exposes no
30
+ * distinct `family_id` on the wire — only an opaque `refresh_token` string
31
+ * — so this is a client-local bookkeeping value (not a security boundary;
32
+ * the server's own `RefreshFamilyDO`/`refresh_family_index`, design.md
33
+ * §12.7, is the source of truth for family-based revocation).
34
+ */
35
+ readonly familyId: string;
36
+ readonly userId: string;
37
+ readonly scope: string;
38
+ readonly clientId: string;
39
+ readonly createdAt: number;
40
+ readonly lastRefreshedAt: number;
41
+ }
42
+ /** Transient PKCE state for an in-flight auth transaction (design.md §21.6, §16.1, §20.6). */
43
+ export interface PersistedPendingTransaction {
44
+ readonly transactionId: string;
45
+ readonly state: string;
46
+ readonly codeVerifier: string;
47
+ readonly redirectUri: string;
48
+ readonly createdAt: number;
49
+ /** Correlates `sendEmailCode`/`verifyEmailCode` (design.md §21.3 — `verifyEmailCode` takes only `challengeId`). */
50
+ readonly challengeId?: string;
51
+ }
52
+ /** Never trusts SecureStore contents blindly (IMPL_NOTES §1): hand-narrowed, not `as`-cast. */
53
+ export declare const parsePersistedRefreshRecord: (value: unknown) => PersistedRefreshRecord | null;
54
+ export declare const parsePersistedPendingTransaction: (value: unknown) => PersistedPendingTransaction | null;
@@ -0,0 +1,55 @@
1
+ /**
2
+ * Expo SecureStore keys accept only alphanumeric characters plus `.`, `_`, and
3
+ * `-`. The design's colon-delimited namespace is therefore encoded with
4
+ * hyphens while retaining the same environment/client/suffix boundaries.
5
+ */
6
+ const secureStoreKey = (environmentId, clientId, suffix) => `example-auth-${environmentId}-${clientId}-${suffix}`;
7
+ /** Refresh token record key (design.md §21.6). */
8
+ export const refreshRecordKey = (environmentId, clientId) => secureStoreKey(environmentId, clientId, "refresh");
9
+ /** Transient PKCE transaction record key (design.md §21.6). */
10
+ export const pendingTransactionKey = (environmentId, clientId) => secureStoreKey(environmentId, clientId, "pkce");
11
+ const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
12
+ /** Never trusts SecureStore contents blindly (IMPL_NOTES §1): hand-narrowed, not `as`-cast. */
13
+ export const parsePersistedRefreshRecord = (value) => {
14
+ if (!isRecord(value))
15
+ return null;
16
+ const { refreshToken, familyId, userId, scope, clientId, createdAt, lastRefreshedAt } = value;
17
+ if (typeof refreshToken !== "string" || refreshToken.length === 0)
18
+ return null;
19
+ if (typeof familyId !== "string" || familyId.length === 0)
20
+ return null;
21
+ if (typeof userId !== "string" || userId.length === 0)
22
+ return null;
23
+ if (typeof scope !== "string")
24
+ return null;
25
+ if (typeof clientId !== "string" || clientId.length === 0)
26
+ return null;
27
+ if (typeof createdAt !== "number" || typeof lastRefreshedAt !== "number")
28
+ return null;
29
+ return { refreshToken, familyId, userId, scope, clientId, createdAt, lastRefreshedAt };
30
+ };
31
+ export const parsePersistedPendingTransaction = (value) => {
32
+ if (!isRecord(value))
33
+ return null;
34
+ const { transactionId, state, codeVerifier, redirectUri, createdAt, challengeId } = value;
35
+ if (typeof transactionId !== "string" || transactionId.length === 0)
36
+ return null;
37
+ if (typeof state !== "string" || state.length === 0)
38
+ return null;
39
+ if (typeof codeVerifier !== "string" || codeVerifier.length === 0)
40
+ return null;
41
+ if (typeof redirectUri !== "string" || redirectUri.length === 0)
42
+ return null;
43
+ if (typeof createdAt !== "number")
44
+ return null;
45
+ if (challengeId !== undefined && typeof challengeId !== "string")
46
+ return null;
47
+ return {
48
+ transactionId,
49
+ state,
50
+ codeVerifier,
51
+ redirectUri,
52
+ createdAt,
53
+ ...(challengeId !== undefined ? { challengeId } : {}),
54
+ };
55
+ };
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,69 @@
1
+ import { describe, expect, test } from "vitest";
2
+ import { parsePersistedPendingTransaction, parsePersistedRefreshRecord, pendingTransactionKey, refreshRecordKey, } from "./secure-store.js";
3
+ describe("refreshRecordKey / pendingTransactionKey", () => {
4
+ test("refresh key uses the SecureStore-safe design namespace", () => {
5
+ expect(refreshRecordKey("env_abc", "cli_xxx")).toBe("example-auth-env_abc-cli_xxx-refresh");
6
+ });
7
+ test("pending transaction key uses the same namespace, a distinct suffix", () => {
8
+ expect(pendingTransactionKey("env_abc", "cli_xxx")).toBe("example-auth-env_abc-cli_xxx-pkce");
9
+ });
10
+ test("keys are distinct from one another", () => {
11
+ expect(refreshRecordKey("env_abc", "cli_xxx")).not.toBe(pendingTransactionKey("env_abc", "cli_xxx"));
12
+ });
13
+ });
14
+ const VALID_REFRESH_RECORD = {
15
+ refreshToken: "rt-secret",
16
+ familyId: "fam-1",
17
+ userId: "usr_abc",
18
+ scope: "openid profile email offline_access",
19
+ clientId: "cli_xxx",
20
+ createdAt: 1000,
21
+ lastRefreshedAt: 2000,
22
+ };
23
+ describe("parsePersistedRefreshRecord", () => {
24
+ test("accepts a well-formed record", () => {
25
+ expect(parsePersistedRefreshRecord(VALID_REFRESH_RECORD)).toEqual(VALID_REFRESH_RECORD);
26
+ });
27
+ test("rejects non-objects", () => {
28
+ expect(parsePersistedRefreshRecord(null)).toBeNull();
29
+ expect(parsePersistedRefreshRecord("a string")).toBeNull();
30
+ expect(parsePersistedRefreshRecord([1, 2, 3])).toBeNull();
31
+ });
32
+ test("rejects a record missing refreshToken", () => {
33
+ const { refreshToken: _refreshToken, ...rest } = VALID_REFRESH_RECORD;
34
+ expect(parsePersistedRefreshRecord(rest)).toBeNull();
35
+ });
36
+ test("rejects a record whose refreshToken is empty", () => {
37
+ expect(parsePersistedRefreshRecord({ ...VALID_REFRESH_RECORD, refreshToken: "" })).toBeNull();
38
+ });
39
+ test("NEVER accepts an accessToken field as a substitute for the real shape (design.md §21.6)", () => {
40
+ // An access-token-shaped payload must not accidentally validate as a refresh record.
41
+ expect(parsePersistedRefreshRecord({ accessToken: "at-secret", expiresAt: 123 })).toBeNull();
42
+ });
43
+ test("rejects wrong-typed timestamps", () => {
44
+ expect(parsePersistedRefreshRecord({ ...VALID_REFRESH_RECORD, createdAt: "1000" })).toBeNull();
45
+ });
46
+ });
47
+ const VALID_PENDING = {
48
+ transactionId: "txn_abc",
49
+ state: "state-value",
50
+ codeVerifier: "verifier-value",
51
+ redirectUri: "com.customer.app:/oauth/callback",
52
+ createdAt: 1000,
53
+ };
54
+ describe("parsePersistedPendingTransaction", () => {
55
+ test("accepts a well-formed record without challengeId", () => {
56
+ expect(parsePersistedPendingTransaction(VALID_PENDING)).toEqual(VALID_PENDING);
57
+ });
58
+ test("accepts a well-formed record with challengeId", () => {
59
+ const withChallenge = { ...VALID_PENDING, challengeId: "chal_1" };
60
+ expect(parsePersistedPendingTransaction(withChallenge)).toEqual(withChallenge);
61
+ });
62
+ test("rejects a record whose challengeId is the wrong type", () => {
63
+ expect(parsePersistedPendingTransaction({ ...VALID_PENDING, challengeId: 123 })).toBeNull();
64
+ });
65
+ test("rejects a record missing a required field", () => {
66
+ const { state: _state, ...rest } = VALID_PENDING;
67
+ expect(parsePersistedPendingTransaction(rest)).toBeNull();
68
+ });
69
+ });