@smartcrab/react-native 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (96) hide show
  1. package/LICENSE +202 -0
  2. package/app.plugin.js +9 -0
  3. package/dist/adapters/expo-crypto-port.d.ts +3 -0
  4. package/dist/adapters/expo-crypto-port.js +8 -0
  5. package/dist/adapters/expo-linking-port.d.ts +3 -0
  6. package/dist/adapters/expo-linking-port.js +21 -0
  7. package/dist/adapters/expo-secure-store-port.d.ts +11 -0
  8. package/dist/adapters/expo-secure-store-port.js +15 -0
  9. package/dist/adapters/expo-web-browser-port.d.ts +7 -0
  10. package/dist/adapters/expo-web-browser-port.js +9 -0
  11. package/dist/adapters/react-native-app-state-port.d.ts +8 -0
  12. package/dist/adapters/react-native-app-state-port.js +13 -0
  13. package/dist/adapters/react-native-passkeys-adapter.d.ts +2 -0
  14. package/dist/adapters/react-native-passkeys-adapter.js +112 -0
  15. package/dist/adapters/react-native-passkeys-adapter.test.d.ts +1 -0
  16. package/dist/adapters/react-native-passkeys-adapter.test.js +76 -0
  17. package/dist/base64url.d.ts +20 -0
  18. package/dist/base64url.js +89 -0
  19. package/dist/base64url.test.d.ts +1 -0
  20. package/dist/base64url.test.js +36 -0
  21. package/dist/browser-port.d.ts +17 -0
  22. package/dist/browser-port.js +1 -0
  23. package/dist/client.d.ts +43 -0
  24. package/dist/client.js +871 -0
  25. package/dist/client.test.d.ts +1 -0
  26. package/dist/client.test.js +995 -0
  27. package/dist/context.d.ts +8 -0
  28. package/dist/context.js +17 -0
  29. package/dist/crypto-port.d.ts +16 -0
  30. package/dist/crypto-port.js +1 -0
  31. package/dist/errors.d.ts +113 -0
  32. package/dist/errors.js +82 -0
  33. package/dist/errors.test.d.ts +1 -0
  34. package/dist/errors.test.js +81 -0
  35. package/dist/hooks.d.ts +93 -0
  36. package/dist/hooks.js +191 -0
  37. package/dist/http.d.ts +41 -0
  38. package/dist/http.js +102 -0
  39. package/dist/index.d.ts +22 -0
  40. package/dist/index.js +29 -0
  41. package/dist/jwt.d.ts +1 -0
  42. package/dist/jwt.js +23 -0
  43. package/dist/lifecycle-ports.d.ts +29 -0
  44. package/dist/lifecycle-ports.js +1 -0
  45. package/dist/linking-port.d.ts +15 -0
  46. package/dist/linking-port.js +1 -0
  47. package/dist/passkey-adapter.d.ts +20 -0
  48. package/dist/passkey-adapter.js +1 -0
  49. package/dist/pkce.d.ts +32 -0
  50. package/dist/pkce.js +41 -0
  51. package/dist/pkce.test.d.ts +1 -0
  52. package/dist/pkce.test.js +66 -0
  53. package/dist/plugin.d.ts +89 -0
  54. package/dist/plugin.js +242 -0
  55. package/dist/plugin.test.d.ts +1 -0
  56. package/dist/plugin.test.js +210 -0
  57. package/dist/provider.d.ts +14 -0
  58. package/dist/provider.js +5 -0
  59. package/dist/secure-store.d.ts +54 -0
  60. package/dist/secure-store.js +55 -0
  61. package/dist/secure-store.test.d.ts +1 -0
  62. package/dist/secure-store.test.js +69 -0
  63. package/dist/types.d.ts +177 -0
  64. package/dist/types.js +1 -0
  65. package/package.json +69 -0
  66. package/src/adapters/expo-crypto-port.ts +11 -0
  67. package/src/adapters/expo-linking-port.ts +23 -0
  68. package/src/adapters/expo-secure-store-port.ts +20 -0
  69. package/src/adapters/expo-web-browser-port.ts +16 -0
  70. package/src/adapters/react-native-app-state-port.ts +15 -0
  71. package/src/adapters/react-native-passkeys-adapter.test.ts +87 -0
  72. package/src/adapters/react-native-passkeys-adapter.ts +138 -0
  73. package/src/base64url.test.ts +47 -0
  74. package/src/base64url.ts +92 -0
  75. package/src/browser-port.ts +19 -0
  76. package/src/client.test.ts +1275 -0
  77. package/src/client.ts +1329 -0
  78. package/src/context.ts +20 -0
  79. package/src/crypto-port.ts +16 -0
  80. package/src/errors.test.ts +94 -0
  81. package/src/errors.ts +216 -0
  82. package/src/hooks.ts +374 -0
  83. package/src/http.ts +159 -0
  84. package/src/index.ts +101 -0
  85. package/src/jwt.ts +24 -0
  86. package/src/lifecycle-ports.ts +32 -0
  87. package/src/linking-port.ts +16 -0
  88. package/src/passkey-adapter.ts +20 -0
  89. package/src/pkce.test.ts +84 -0
  90. package/src/pkce.ts +62 -0
  91. package/src/plugin.test.ts +303 -0
  92. package/src/plugin.ts +387 -0
  93. package/src/provider.tsx +20 -0
  94. package/src/secure-store.test.ts +91 -0
  95. package/src/secure-store.ts +102 -0
  96. package/src/types.ts +181 -0
@@ -0,0 +1,177 @@
1
+ import type { ClientId, SocialProvider } from "@smartcrab/contracts-public";
2
+ import type { WebBrowserPort } from "./browser-port.js";
3
+ import type { CryptoPort } from "./crypto-port.js";
4
+ import type { FetchPort } from "./http.js";
5
+ import type { AppStatePort, NetworkStatusPort } from "./lifecycle-ports.js";
6
+ import type { LinkingPort } from "./linking-port.js";
7
+ import type { PasskeyNativeAdapter } from "./passkey-adapter.js";
8
+ import type { SecureStorePort } from "./secure-store.js";
9
+ /**
10
+ * Public types for `@smartcrab/react-native` (design.md §21.3, §21.8).
11
+ *
12
+ * `ReactNativeAuthConfig`'s required fields are exactly the ones design.md
13
+ * §21.8's sample supplies (`issuer`, `clientId`, `redirectUri`); every other
14
+ * field (scopes, resource, and every injectable port) is optional with a
15
+ * production default backed by the corresponding peer dependency, so tests
16
+ * can substitute fakes without loading any native module.
17
+ */
18
+ export interface ReactNativeAuthConfig {
19
+ /** OIDC issuer, e.g. `https://id.example-auth.com/e/env_xxx` (design.md §21.8, §15.1). */
20
+ readonly issuer: string;
21
+ readonly clientId: ClientId;
22
+ /** Must be byte-for-byte registered on the client (design.md §15.9), e.g. `com.customer.app:/oauth/callback`. */
23
+ readonly redirectUri: string;
24
+ /** Defaults to `["openid", "profile", "email", "offline_access"]` (design.md §21.8 sample). */
25
+ readonly scopes?: readonly string[];
26
+ /** RFC 8707 resource indicator(s) (design.md §16.1); a single string is normalized to a one-element array. */
27
+ readonly resource?: string | readonly string[];
28
+ /**
29
+ * Overrides the environment id this client would otherwise parse from
30
+ * `issuer`'s `/e/<environmentId>` path segment (design.md §21.6's
31
+ * SecureStore key format). Only needed when `issuer` does not follow that
32
+ * shape.
33
+ */
34
+ readonly environmentId?: string;
35
+ /**
36
+ * The passkey RP domain this app binary is built for (the config plugin's
37
+ * `rpDomain`: iOS `webcredentials:` / Android `asset_statements`). When set,
38
+ * every passkey options request pins `rp_id` to it.
39
+ */
40
+ readonly rpDomain?: string;
41
+ /** Defaults to the global `fetch`. */
42
+ readonly fetch?: FetchPort;
43
+ /** Clock override for tests (epoch ms). */
44
+ readonly now?: () => number;
45
+ /** Defaults to an `expo-secure-store`-backed port (design.md §21.6). */
46
+ readonly secureStore?: SecureStorePort;
47
+ /** Defaults to a `react-native-passkeys`-backed adapter (design.md §21.2). */
48
+ readonly passkeyAdapter?: PasskeyNativeAdapter;
49
+ /** Defaults to an `expo-web-browser`-backed port (design.md §20.6: system browser only). */
50
+ readonly browser?: WebBrowserPort;
51
+ /** Defaults to an `expo-linking`-backed port. */
52
+ readonly linking?: LinkingPort;
53
+ /** Defaults to an `expo-crypto`-backed port (design.md §21.1). */
54
+ readonly crypto?: CryptoPort;
55
+ /** Defaults to React Native's own `AppState` (design.md §21.7 foreground trigger). */
56
+ readonly appState?: AppStatePort;
57
+ /**
58
+ * OPTIONAL: no connectivity-detection peer dependency is declared
59
+ * (design.md §21.1), so there is no production default. Supply one (e.g.
60
+ * backed by `@react-native-community/netinfo`) to get the network-recovery
61
+ * refresh trigger described in design.md §21.7; omitted, only the
62
+ * foreground trigger runs.
63
+ */
64
+ readonly networkStatus?: NetworkStatusPort;
65
+ }
66
+ /** Session metadata (design.md §21.3). The access token itself is never exposed here — use `getAccessToken()`. */
67
+ export interface AuthSession {
68
+ readonly userId: string;
69
+ readonly scope: string;
70
+ readonly hasRefreshToken: boolean;
71
+ /** `null` when no access token is currently held in memory (e.g. immediately after an app relaunch). */
72
+ readonly accessTokenExpiresAt: number | null;
73
+ }
74
+ export interface AuthResult {
75
+ readonly session: AuthSession;
76
+ }
77
+ /** Public projection of a passkey (design.md §21.3; mirrors contracts-public's `PasskeySummary`, camelCased). */
78
+ export interface Passkey {
79
+ readonly passkeyId: string;
80
+ readonly name: string | null;
81
+ readonly createdAt: string;
82
+ readonly lastUsedAt: string | null;
83
+ readonly deviceType: "single_device" | "multi_device" | null;
84
+ readonly backedUp: boolean;
85
+ }
86
+ /** Public projection of another signed-in device/session (design.md §21.3; mirrors `MeSessionSummary`). */
87
+ export interface DeviceSession {
88
+ readonly sessionId: string;
89
+ readonly clientId: string;
90
+ readonly deviceName: string | null;
91
+ readonly createdAt: string;
92
+ readonly lastActiveAt: string;
93
+ readonly current: boolean;
94
+ }
95
+ export interface EmailCodeChallenge {
96
+ readonly challengeId: string;
97
+ readonly expiresAt: string;
98
+ }
99
+ export interface AccessTokenRequest {
100
+ /** Forces a refresh even if the in-memory access token is not yet within the expiry skew. */
101
+ readonly forceRefresh?: boolean;
102
+ }
103
+ export interface RegisterPasskeyInput {
104
+ readonly name?: string;
105
+ }
106
+ export interface AuthStateSnapshot {
107
+ readonly status: "signed_out" | "signed_in";
108
+ /** Runtime WebAuthn capability (design.md §21.2): the prebuilt UI hides `<PasskeyButton/>` when false. */
109
+ readonly passkeySupported: boolean;
110
+ readonly hasRefreshToken: boolean;
111
+ readonly accessTokenExpiresAt?: number;
112
+ readonly scope?: string;
113
+ }
114
+ export type AuthStateListener = (snapshot: AuthStateSnapshot) => void;
115
+ /** Public profile (design.md §16.2 `GET/PATCH /v1/me`; mirrors contracts-public's `MeUser`, camelCased). */
116
+ export interface UserProfile {
117
+ readonly userId: string;
118
+ readonly email: string | null;
119
+ readonly emailVerified: boolean;
120
+ readonly name: string | null;
121
+ readonly avatarUrl: string | null;
122
+ readonly locale: string | null;
123
+ readonly timezone: string | null;
124
+ readonly status: "active" | "blocked" | "pending_deletion";
125
+ readonly createdAt: string;
126
+ readonly lastLoginAt: string | null;
127
+ }
128
+ export interface UpdateUserProfileInput {
129
+ readonly name?: string;
130
+ readonly avatarUrl?: string;
131
+ readonly locale?: string;
132
+ readonly timezone?: string;
133
+ }
134
+ /**
135
+ * `ReactNativeAuthClient` (design.md §21.3, verbatim member-for-member — every
136
+ * method design.md §21.3 lists is present with an identical signature).
137
+ *
138
+ * Two categories of members go beyond that list, both additive/non-breaking:
139
+ * - `getSnapshot`: a `useSyncExternalStore`-compatible synchronous read used
140
+ * by the React bindings (design.md §21.4).
141
+ * - `getMe`/`updateMe`: design.md §21.4 lists a `useUser()` hook, and §16.2
142
+ * documents `GET/PATCH /v1/me`, but §21.3's client interface snippet has no
143
+ * corresponding method — these back that hook. Documented here as a
144
+ * deliberate gap-fill, not a deviation from any §21.3 member.
145
+ */
146
+ export interface ReactNativeAuthClient {
147
+ configure(config: ReactNativeAuthConfig): void;
148
+ getSession(): Promise<AuthSession | null>;
149
+ getAccessToken(input?: AccessTokenRequest): Promise<string>;
150
+ signInWithPasskey(): Promise<AuthResult>;
151
+ registerPasskey(input?: RegisterPasskeyInput): Promise<Passkey>;
152
+ sendEmailCode(input: {
153
+ email: string;
154
+ }): Promise<EmailCodeChallenge>;
155
+ verifyEmailCode(input: {
156
+ challengeId: string;
157
+ code: string;
158
+ }): Promise<AuthResult>;
159
+ signInWithSocial(input: {
160
+ provider: SocialProvider;
161
+ }): Promise<AuthResult>;
162
+ linkSocialAccount(input: {
163
+ provider: SocialProvider;
164
+ }): Promise<void>;
165
+ listPasskeys(): Promise<Passkey[]>;
166
+ deletePasskey(passkeyId: string): Promise<void>;
167
+ listSessions(): Promise<DeviceSession[]>;
168
+ revokeSession(sessionId: string): Promise<void>;
169
+ signOut(): Promise<void>;
170
+ signOutAll(): Promise<void>;
171
+ subscribe(listener: AuthStateListener): () => void;
172
+ /** Synchronous snapshot read for `useSyncExternalStore` (design.md §21.4). */
173
+ getSnapshot(): AuthStateSnapshot;
174
+ /** Backs `useUser()` (design.md §21.4); see the interface doc comment above. */
175
+ getMe(): Promise<UserProfile>;
176
+ updateMe(input: UpdateUserProfileInput): Promise<UserProfile>;
177
+ }
package/dist/types.js ADDED
@@ -0,0 +1 @@
1
+ export {};
package/package.json ADDED
@@ -0,0 +1,69 @@
1
+ {
2
+ "name": "@smartcrab/react-native",
3
+ "version": "0.1.0",
4
+ "license": "Apache-2.0",
5
+ "type": "module",
6
+ "main": "./dist/index.js",
7
+ "types": "./dist/index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "types": "./src/index.ts",
11
+ "development": "./src/index.ts",
12
+ "import": "./dist/index.js",
13
+ "default": "./dist/index.js"
14
+ },
15
+ "./plugin": {
16
+ "types": "./src/plugin.ts",
17
+ "development": "./src/plugin.ts",
18
+ "import": "./dist/plugin.js",
19
+ "default": "./dist/plugin.js"
20
+ },
21
+ "./*": {
22
+ "types": "./src/*.ts",
23
+ "development": "./src/*.ts",
24
+ "import": "./dist/*.js",
25
+ "default": "./dist/*.js"
26
+ }
27
+ },
28
+ "files": [
29
+ "app.plugin.js",
30
+ "dist",
31
+ "src"
32
+ ],
33
+ "publishConfig": {
34
+ "access": "public"
35
+ },
36
+ "dependencies": {
37
+ "@smartcrab/contracts-public": "0.1.0"
38
+ },
39
+ "peerDependencies": {
40
+ "react": ">=19",
41
+ "react-native": ">=0.79",
42
+ "expo": ">=55",
43
+ "expo-secure-store": ">=13",
44
+ "expo-web-browser": ">=14",
45
+ "expo-auth-session": ">=6",
46
+ "expo-linking": ">=7",
47
+ "expo-crypto": ">=14",
48
+ "react-native-passkeys": ">=0.3"
49
+ },
50
+ "devDependencies": {
51
+ "typescript": "5.9.3",
52
+ "vitest": "4.1.11",
53
+ "react": "19.2.8",
54
+ "react-native": "0.86.2",
55
+ "expo": "57.0.10",
56
+ "expo-secure-store": "57.0.1",
57
+ "expo-web-browser": "57.0.2",
58
+ "expo-auth-session": "57.0.6",
59
+ "expo-linking": "57.0.5",
60
+ "expo-crypto": "57.0.1",
61
+ "react-native-passkeys": "0.4.1",
62
+ "@types/react": "19.2.18"
63
+ },
64
+ "scripts": {
65
+ "typecheck": "tsc --noEmit",
66
+ "test": "vitest run --passWithNoTests",
67
+ "build": "tsc -p tsconfig.build.json"
68
+ }
69
+ }
@@ -0,0 +1,11 @@
1
+ import * as Crypto from "expo-crypto";
2
+ import type { CryptoPort } from "../crypto-port.js";
3
+
4
+ /** Default `CryptoPort`: `expo-crypto` (design.md §21.1 peer dependency). */
5
+ export const expoCryptoPort: CryptoPort = {
6
+ getRandomBytes: (byteCount) => Crypto.getRandomBytes(byteCount),
7
+ sha256Base64: (data) =>
8
+ Crypto.digestStringAsync(Crypto.CryptoDigestAlgorithm.SHA256, data, {
9
+ encoding: Crypto.CryptoEncoding.BASE64,
10
+ }),
11
+ };
@@ -0,0 +1,23 @@
1
+ import * as Linking from "expo-linking";
2
+ import type { LinkingPort, ParsedCallbackUrl } from "../linking-port.js";
3
+
4
+ /** Default `LinkingPort`: `expo-linking` (design.md §21.1, §20.6). */
5
+ export const expoLinkingPort: LinkingPort = {
6
+ parse: (url): ParsedCallbackUrl => {
7
+ const parsed = Linking.parse(url);
8
+ const queryParams: Record<string, string> = {};
9
+ if (parsed.queryParams !== null) {
10
+ for (const [key, value] of Object.entries(parsed.queryParams)) {
11
+ if (typeof value === "string") {
12
+ queryParams[key] = value;
13
+ }
14
+ }
15
+ }
16
+ return { queryParams };
17
+ },
18
+ getInitialURL: () => Linking.getInitialURL(),
19
+ addEventListener: (handler) => {
20
+ const subscription = Linking.addEventListener("url", (event) => handler(event.url));
21
+ return () => subscription.remove();
22
+ },
23
+ };
@@ -0,0 +1,20 @@
1
+ import * as SecureStore from "expo-secure-store";
2
+ import type { SecureStorePort } from "../secure-store.js";
3
+
4
+ /**
5
+ * Default `SecureStorePort`: `expo-secure-store` (design.md §21.1, §21.6).
6
+ *
7
+ * `AFTER_FIRST_UNLOCK` keeps the refresh token readable for background token
8
+ * refresh (e.g. a network-recovery-triggered refresh, design.md §21.7) while
9
+ * still requiring the device to have been unlocked at least once since boot;
10
+ * it is never `ALWAYS`/`ALWAYS_THIS_DEVICE_ONLY` (both deprecated by Expo in
11
+ * favor of protections that survive a stolen, still-unlocked device less).
12
+ */
13
+ export const expoSecureStorePort: SecureStorePort = {
14
+ getItemAsync: (key) =>
15
+ SecureStore.getItemAsync(key, { keychainAccessible: SecureStore.AFTER_FIRST_UNLOCK }),
16
+ setItemAsync: (key, value) =>
17
+ SecureStore.setItemAsync(key, value, { keychainAccessible: SecureStore.AFTER_FIRST_UNLOCK }),
18
+ deleteItemAsync: (key) =>
19
+ SecureStore.deleteItemAsync(key, { keychainAccessible: SecureStore.AFTER_FIRST_UNLOCK }),
20
+ };
@@ -0,0 +1,16 @@
1
+ import * as WebBrowser from "expo-web-browser";
2
+ import type { WebBrowserAuthResult } from "../browser-port.js";
3
+ import type { WebBrowserPort } from "../browser-port.js";
4
+
5
+ /**
6
+ * Default `WebBrowserPort`: `expo-web-browser`'s auth session API (design.md
7
+ * §20.6, §21.1). `preferEphemeralSession` avoids sharing cookies with the
8
+ * user's normal browsing session for the duration of the sign-in ceremony.
9
+ */
10
+ export const expoWebBrowserPort: WebBrowserPort = {
11
+ openAuthSessionAsync: (url, redirectUrl) =>
12
+ WebBrowser.openAuthSessionAsync(url, redirectUrl, { preferEphemeralSession: true }).then(
13
+ (result): WebBrowserAuthResult =>
14
+ result.type === "success" ? { type: "success", url: result.url } : { type: result.type },
15
+ ),
16
+ };
@@ -0,0 +1,15 @@
1
+ import { AppState } from "react-native";
2
+ import type { AppStatePort } from "../lifecycle-ports.js";
3
+
4
+ /**
5
+ * Default `AppStatePort`: React Native's own `AppState` (design.md §21.1,
6
+ * §21.7). RN's `AppStateStatus` union is structurally identical to this
7
+ * package's own (`active`/`background`/`inactive`/`unknown`/`extension`), so
8
+ * this passes through without any cast.
9
+ */
10
+ export const reactNativeAppStatePort: AppStatePort = {
11
+ get currentState() {
12
+ return AppState.currentState;
13
+ },
14
+ addEventListener: (type, handler) => AppState.addEventListener(type, handler),
15
+ };
@@ -0,0 +1,87 @@
1
+ import { describe, expect, test, vi } from "vitest";
2
+
3
+ const mocks = vi.hoisted(() => ({
4
+ create: vi.fn(),
5
+ get: vi.fn(),
6
+ isSupported: vi.fn(() => true),
7
+ }));
8
+
9
+ vi.mock("react-native-passkeys", () => mocks);
10
+
11
+ import { reactNativePasskeysAdapter } from "./react-native-passkeys-adapter.js";
12
+
13
+ const registrationOptions = {
14
+ rp: { id: "auth.example", name: "Auth Example" },
15
+ user: { id: "dXNlcg", name: "user@example.com", displayName: "User" },
16
+ challenge: "Y2hhbGxlbmdl",
17
+ pubKeyCredParams: [{ type: "public-key" as const, alg: -7 }],
18
+ authenticatorSelection: {
19
+ residentKey: "required" as const,
20
+ userVerification: "required" as const,
21
+ },
22
+ attestation: "none" as const,
23
+ };
24
+
25
+ const authenticationOptions = {
26
+ challenge: "Y2hhbGxlbmdl",
27
+ rpId: "auth.example",
28
+ userVerification: "required" as const,
29
+ };
30
+
31
+ describe("reactNativePasskeysAdapter", () => {
32
+ test("omits nullable optional fields from native registration responses", async () => {
33
+ mocks.create.mockResolvedValueOnce({
34
+ id: "Y3JlZGVudGlhbA",
35
+ rawId: "Y3JlZGVudGlhbA",
36
+ type: "public-key",
37
+ response: {
38
+ clientDataJSON: "Y2xpZW50LWRhdGE",
39
+ attestationObject: "YXR0ZXN0YXRpb24",
40
+ transports: null,
41
+ },
42
+ authenticatorAttachment: null,
43
+ clientExtensionResults: null,
44
+ });
45
+
46
+ const result = await reactNativePasskeysAdapter.create(JSON.stringify(registrationOptions));
47
+
48
+ expect(JSON.parse(result)).toEqual({
49
+ id: "Y3JlZGVudGlhbA",
50
+ rawId: "Y3JlZGVudGlhbA",
51
+ type: "public-key",
52
+ response: {
53
+ clientDataJSON: "Y2xpZW50LWRhdGE",
54
+ attestationObject: "YXR0ZXN0YXRpb24",
55
+ },
56
+ });
57
+ });
58
+
59
+ test("omits nullable optional fields from native authentication responses", async () => {
60
+ mocks.get.mockResolvedValueOnce({
61
+ id: "Y3JlZGVudGlhbA",
62
+ rawId: "Y3JlZGVudGlhbA",
63
+ type: "public-key",
64
+ response: {
65
+ clientDataJSON: "Y2xpZW50LWRhdGE",
66
+ authenticatorData: "YXV0aGVudGljYXRvcg",
67
+ signature: "c2lnbmF0dXJl",
68
+ userHandle: null,
69
+ },
70
+ authenticatorAttachment: null,
71
+ clientExtensionResults: null,
72
+ });
73
+
74
+ const result = await reactNativePasskeysAdapter.get(JSON.stringify(authenticationOptions));
75
+
76
+ expect(JSON.parse(result)).toEqual({
77
+ id: "Y3JlZGVudGlhbA",
78
+ rawId: "Y3JlZGVudGlhbA",
79
+ type: "public-key",
80
+ response: {
81
+ clientDataJSON: "Y2xpZW50LWRhdGE",
82
+ authenticatorData: "YXV0aGVudGljYXRvcg",
83
+ signature: "c2lnbmF0dXJl",
84
+ },
85
+ });
86
+ });
87
+ });
@@ -0,0 +1,138 @@
1
+ import type {
2
+ PasskeyAuthenticationOptionsResponse,
3
+ PasskeyRegistrationOptionsResponse,
4
+ } from "@smartcrab/contracts-public";
5
+ import {
6
+ passkeyAuthenticationOptionsResponseSchema,
7
+ passkeyRegistrationOptionsResponseSchema,
8
+ } from "@smartcrab/contracts-public";
9
+ import * as Passkeys from "react-native-passkeys";
10
+ import type { PasskeyNativeAdapter } from "../passkey-adapter.js";
11
+
12
+ /**
13
+ * Default `PasskeyNativeAdapter`: `react-native-passkeys` (design.md §21.1,
14
+ * §21.2). Converts between this package's JSON-string adapter boundary and
15
+ * `react-native-passkeys`' object API; its types never escape this file.
16
+ *
17
+ * The `optionsJson` input is always JSON this same SDK produced moments
18
+ * earlier from an already schema-validated server response (design.md §16.2
19
+ * `.../passkeys/registration/options` / `.../authentication/options`), so
20
+ * re-validating it here (via the same contracts-public response schemas,
21
+ * since the wire shape and the native module's request shape are identical)
22
+ * replaces an unvalidated `unknown -> object` cast with a real check, per
23
+ * IMPL_NOTES §1.
24
+ */
25
+
26
+ const parseJson = (json: string): unknown => JSON.parse(json);
27
+ const isPresent = <T>(value: T | null | undefined): value is T =>
28
+ value !== null && value !== undefined;
29
+
30
+ export const reactNativePasskeysAdapter: PasskeyNativeAdapter = {
31
+ isSupported: () => Promise.resolve(Passkeys.isSupported()),
32
+
33
+ create: (optionsJson) =>
34
+ Promise.resolve()
35
+ .then(() => parseJson(optionsJson))
36
+ .then((parsed) => {
37
+ const result = passkeyRegistrationOptionsResponseSchema.safeParse(parsed);
38
+ if (!result.success) {
39
+ throw new Error(
40
+ "PasskeyNativeAdapter.create received malformed registration options JSON",
41
+ );
42
+ }
43
+ return toCreationRequest(result.data);
44
+ })
45
+ .then((request) => Passkeys.create(request))
46
+ .then((response) => {
47
+ if (response === null) {
48
+ throw new Error("react-native-passkeys.create() returned null (ceremony cancelled)");
49
+ }
50
+ return JSON.stringify({
51
+ id: response.id,
52
+ rawId: response.rawId,
53
+ type: response.type,
54
+ response: {
55
+ clientDataJSON: response.response.clientDataJSON,
56
+ attestationObject: response.response.attestationObject,
57
+ ...(isPresent(response.response.transports)
58
+ ? { transports: response.response.transports }
59
+ : {}),
60
+ },
61
+ ...(isPresent(response.authenticatorAttachment)
62
+ ? { authenticatorAttachment: response.authenticatorAttachment }
63
+ : {}),
64
+ ...(isPresent(response.clientExtensionResults)
65
+ ? { clientExtensionResults: response.clientExtensionResults }
66
+ : {}),
67
+ });
68
+ }),
69
+
70
+ get: (optionsJson) =>
71
+ Promise.resolve()
72
+ .then(() => parseJson(optionsJson))
73
+ .then((parsed) => {
74
+ const result = passkeyAuthenticationOptionsResponseSchema.safeParse(parsed);
75
+ if (!result.success) {
76
+ throw new Error(
77
+ "PasskeyNativeAdapter.get received malformed authentication options JSON",
78
+ );
79
+ }
80
+ return toRequestOptions(result.data);
81
+ })
82
+ .then((request) => Passkeys.get(request))
83
+ .then((response) => {
84
+ if (response === null) {
85
+ throw new Error("react-native-passkeys.get() returned null (ceremony cancelled)");
86
+ }
87
+ return JSON.stringify({
88
+ id: response.id,
89
+ rawId: response.rawId,
90
+ type: response.type,
91
+ response: {
92
+ clientDataJSON: response.response.clientDataJSON,
93
+ authenticatorData: response.response.authenticatorData,
94
+ signature: response.response.signature,
95
+ ...(isPresent(response.response.userHandle)
96
+ ? { userHandle: response.response.userHandle }
97
+ : {}),
98
+ },
99
+ ...(isPresent(response.authenticatorAttachment)
100
+ ? { authenticatorAttachment: response.authenticatorAttachment }
101
+ : {}),
102
+ ...(isPresent(response.clientExtensionResults)
103
+ ? { clientExtensionResults: response.clientExtensionResults }
104
+ : {}),
105
+ });
106
+ }),
107
+ };
108
+
109
+ const toCreationRequest = (
110
+ options: PasskeyRegistrationOptionsResponse,
111
+ ): Parameters<typeof Passkeys.create>[0] => ({
112
+ rp: options.rp,
113
+ user: options.user,
114
+ challenge: options.challenge,
115
+ pubKeyCredParams: options.pubKeyCredParams,
116
+ ...(options.timeout !== undefined ? { timeout: options.timeout } : {}),
117
+ ...(options.excludeCredentials !== undefined
118
+ ? { excludeCredentials: options.excludeCredentials }
119
+ : {}),
120
+ authenticatorSelection: {
121
+ residentKey: options.authenticatorSelection.residentKey,
122
+ userVerification: options.authenticatorSelection.userVerification,
123
+ ...(options.authenticatorSelection.authenticatorAttachment !== undefined
124
+ ? { authenticatorAttachment: options.authenticatorSelection.authenticatorAttachment }
125
+ : {}),
126
+ },
127
+ attestation: options.attestation,
128
+ });
129
+
130
+ const toRequestOptions = (
131
+ options: PasskeyAuthenticationOptionsResponse,
132
+ ): Parameters<typeof Passkeys.get>[0] => ({
133
+ challenge: options.challenge,
134
+ ...(options.timeout !== undefined ? { timeout: options.timeout } : {}),
135
+ rpId: options.rpId,
136
+ ...(options.allowCredentials !== undefined ? { allowCredentials: options.allowCredentials } : {}),
137
+ userVerification: options.userVerification,
138
+ });
@@ -0,0 +1,47 @@
1
+ import { describe, expect, test } from "vitest";
2
+ import {
3
+ base64UrlDecodeToBytes,
4
+ base64UrlDecodeToUtf8String,
5
+ base64UrlEncodeBytes,
6
+ standardBase64ToBase64Url,
7
+ } from "./base64url.js";
8
+
9
+ describe("base64UrlEncodeBytes / base64UrlDecodeToBytes", () => {
10
+ test("round-trips arbitrary byte lengths", () => {
11
+ for (const length of [0, 1, 2, 3, 4, 5, 16, 32]) {
12
+ const bytes = new Uint8Array(Array.from({ length }, (_, i) => (i * 7) % 256));
13
+ const encoded = base64UrlEncodeBytes(bytes);
14
+ expect(encoded).not.toMatch(/[+/=]/);
15
+ expect(base64UrlDecodeToBytes(encoded)).toEqual(bytes);
16
+ }
17
+ });
18
+
19
+ test("32 random bytes encode to exactly 43 base64url characters (RFC 7636 verifier length)", () => {
20
+ const bytes = new Uint8Array(32).fill(1);
21
+ expect(base64UrlEncodeBytes(bytes)).toHaveLength(43);
22
+ });
23
+ });
24
+
25
+ describe("base64UrlDecodeToUtf8String", () => {
26
+ test("decodes ASCII", () => {
27
+ const encoded = base64UrlEncodeBytes(new TextEncoder().encode('{"sub":"usr_abc"}'));
28
+ expect(base64UrlDecodeToUtf8String(encoded)).toBe('{"sub":"usr_abc"}');
29
+ });
30
+
31
+ test("decodes multi-byte UTF-8", () => {
32
+ const text = "こんにちは";
33
+ const encoded = base64UrlEncodeBytes(new TextEncoder().encode(text));
34
+ expect(base64UrlDecodeToUtf8String(encoded)).toBe(text);
35
+ });
36
+ });
37
+
38
+ describe("standardBase64ToBase64Url", () => {
39
+ test("converts padding and URL-unsafe characters", () => {
40
+ expect(standardBase64ToBase64Url("YQ==")).toBe("YQ");
41
+ expect(standardBase64ToBase64Url("Pj4/Pw==")).toBe("Pj4_Pw");
42
+ });
43
+
44
+ test("rejects non-base64 input", () => {
45
+ expect(standardBase64ToBase64Url("not base64!!")).toBeNull();
46
+ });
47
+ });