@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/context.ts ADDED
@@ -0,0 +1,20 @@
1
+ import { createContext, useContext } from "react";
2
+ import type { ReactNativeAuthClient } from "./types.js";
3
+
4
+ /**
5
+ * Dependency context for the React Native React API (design.md §21.4).
6
+ * One `<AuthProvider client={...}>` per client instance; every hook resolves
7
+ * its dependency through here.
8
+ */
9
+ export const AuthContext = createContext<ReactNativeAuthClient | null>(null);
10
+
11
+ export const useAuthClient = (): ReactNativeAuthClient => {
12
+ const client = useContext(AuthContext);
13
+ if (client === null) {
14
+ // Programmer error (missing <AuthProvider>) — surfaced loudly, the usual
15
+ // React convention for required-provider hooks (mirrors
16
+ // `@smartcrab/sdk-react`'s `useAuthContextValue`).
17
+ throw new Error("Auth hooks must be used inside <AuthProvider client={...}>");
18
+ }
19
+ return client;
20
+ };
@@ -0,0 +1,16 @@
1
+ /**
2
+ * Crypto boundary for PKCE (design.md §21.3, §16.1, RFC 7636).
3
+ *
4
+ * React Native / Hermes does not guarantee a WebCrypto `crypto.getRandomValues`
5
+ * / `crypto.subtle` global the way browsers and Workers do, which is exactly
6
+ * why `expo-crypto` is a declared peer dependency (design.md §21.1). Every
7
+ * random/digest operation in this package therefore goes through this small
8
+ * injectable port instead of a bare `crypto` global, so tests can supply a
9
+ * deterministic fake without loading a native module.
10
+ */
11
+ export interface CryptoPort {
12
+ /** Cryptographically secure random bytes. */
13
+ getRandomBytes(byteCount: number): Uint8Array;
14
+ /** SHA-256 digest of a UTF-8 string, returned as standard (padded) base64. */
15
+ sha256Base64(data: string): Promise<string>;
16
+ }
@@ -0,0 +1,94 @@
1
+ import { describe, expect, test } from "vitest";
2
+ import {
3
+ ReactNativeAuthClientError,
4
+ parseOAuthErrorWire,
5
+ parseProblemDetailsWire,
6
+ } from "./errors.js";
7
+
8
+ describe("ReactNativeAuthClientError", () => {
9
+ test("carries the typed error code and a human-readable message", () => {
10
+ const error = new ReactNativeAuthClientError({ type: "passkey_not_supported" });
11
+ expect(error.code).toEqual({ type: "passkey_not_supported" });
12
+ expect(error.name).toBe("ReactNativeAuthClientError");
13
+ expect(error).toBeInstanceOf(Error);
14
+ expect(error.message.length).toBeGreaterThan(0);
15
+ });
16
+
17
+ test("is distinguishable via instanceof after being thrown/caught", () => {
18
+ const thrower = (): never => {
19
+ throw new ReactNativeAuthClientError({ type: "not_authenticated" });
20
+ };
21
+ expect(thrower).toThrow(ReactNativeAuthClientError);
22
+ });
23
+ });
24
+
25
+ describe("passkey_error reasons", () => {
26
+ test("in_progress describes the concurrent-ceremony guard", () => {
27
+ const error = new ReactNativeAuthClientError({
28
+ type: "passkey_error",
29
+ reason: "in_progress",
30
+ message: "A passkey ceremony is already in progress",
31
+ });
32
+ expect(error.code).toEqual({
33
+ type: "passkey_error",
34
+ reason: "in_progress",
35
+ message: "A passkey ceremony is already in progress",
36
+ });
37
+ expect(error.message).toContain("in_progress");
38
+ });
39
+ });
40
+
41
+ describe("parseProblemDetailsWire", () => {
42
+ test("accepts a minimal RFC 9457 body", () => {
43
+ const parsed = parseProblemDetailsWire({
44
+ type: "about:blank",
45
+ title: "Bad Request",
46
+ status: 400,
47
+ });
48
+ expect(parsed).toEqual({ type: "about:blank", title: "Bad Request", status: 400 });
49
+ });
50
+
51
+ test("accepts optional detail/code/request_id", () => {
52
+ const parsed = parseProblemDetailsWire({
53
+ type: "about:blank",
54
+ title: "Bad Request",
55
+ status: 400,
56
+ detail: "email is invalid",
57
+ code: "invalid_request",
58
+ request_id: "req_abc",
59
+ });
60
+ expect(parsed).toEqual({
61
+ type: "about:blank",
62
+ title: "Bad Request",
63
+ status: 400,
64
+ detail: "email is invalid",
65
+ code: "invalid_request",
66
+ requestId: "req_abc",
67
+ });
68
+ });
69
+
70
+ test("rejects non-object / missing required fields", () => {
71
+ expect(parseProblemDetailsWire(null)).toBeNull();
72
+ expect(parseProblemDetailsWire({ type: "about:blank" })).toBeNull();
73
+ expect(parseProblemDetailsWire({ type: "about:blank", title: "x", status: "400" })).toBeNull();
74
+ });
75
+ });
76
+
77
+ describe("parseOAuthErrorWire", () => {
78
+ test("accepts a minimal RFC 6749 §5.2 error body", () => {
79
+ expect(parseOAuthErrorWire({ error: "invalid_grant" })).toEqual({ error: "invalid_grant" });
80
+ });
81
+
82
+ test("accepts an optional description", () => {
83
+ expect(parseOAuthErrorWire({ error: "invalid_grant", error_description: "expired" })).toEqual({
84
+ error: "invalid_grant",
85
+ description: "expired",
86
+ });
87
+ });
88
+
89
+ test("rejects a missing/empty error field", () => {
90
+ expect(parseOAuthErrorWire({})).toBeNull();
91
+ expect(parseOAuthErrorWire({ error: "" })).toBeNull();
92
+ expect(parseOAuthErrorWire(null)).toBeNull();
93
+ });
94
+ });
package/src/errors.ts ADDED
@@ -0,0 +1,216 @@
1
+ import type { OAuthErrorCode } from "@smartcrab/contracts-public";
2
+
3
+ /**
4
+ * Error model for `@smartcrab/react-native` (design.md §21.2, §21.3, §32).
5
+ *
6
+ * `ReactNativeAuthClient`'s public methods return bare `Promise<T>` per
7
+ * design.md §21.3's verbatim interface (they reject, not resolve-to-Outcome).
8
+ * Internally, every fallible step resolves to `Outcome<T, ReactNativeAuthError>`
9
+ * (no direct `try`/`catch` — `scripts/check-backend-error-style.ts`, design.md
10
+ * §5.2, scans this package); only at the public method boundary is a failed
11
+ * `Outcome` converted into a rejected promise via `ReactNativeAuthClientError`
12
+ * (design.md §5.2's "境界では Result を必ず解決する" applied to this SDK's own
13
+ * public surface).
14
+ */
15
+
16
+ export interface NetworkFailureError {
17
+ readonly type: "network_error";
18
+ readonly message: string;
19
+ readonly retryable: true;
20
+ }
21
+
22
+ export interface InvalidResponseError {
23
+ readonly type: "invalid_response";
24
+ readonly message: string;
25
+ /** HTTP status of the offending response, when one was received at all. */
26
+ readonly status?: number;
27
+ }
28
+
29
+ export interface RateLimitedError {
30
+ readonly type: "rate_limited";
31
+ readonly retryable: true;
32
+ readonly retryAfterSeconds?: number;
33
+ readonly requestId?: string;
34
+ }
35
+
36
+ export interface ProblemDetailsError {
37
+ readonly type: "problem_details";
38
+ /** `type` URI from the RFC 9457 Problem Details body. */
39
+ readonly problemType: string;
40
+ /** Platform snake_case error code (`code` extension member). */
41
+ readonly code: string;
42
+ readonly title: string;
43
+ readonly status: number;
44
+ readonly detail?: string;
45
+ readonly requestId?: string;
46
+ }
47
+
48
+ export interface OAuthFailureError {
49
+ readonly type: "oauth_error";
50
+ readonly code: OAuthErrorCode;
51
+ readonly description?: string;
52
+ readonly status?: number;
53
+ }
54
+
55
+ /** An authorization/complete/social callback carried a `state` this client never issued (design.md §32.1). */
56
+ export interface StateMismatchError {
57
+ readonly type: "state_mismatch";
58
+ }
59
+
60
+ export interface NotAuthenticatedError {
61
+ readonly type: "not_authenticated";
62
+ }
63
+
64
+ /**
65
+ * Runtime WebAuthn capability is false (design.md §21.2): the standard UI
66
+ * hides passkey affordances on this code, never attempting a ceremony.
67
+ */
68
+ export interface PasskeyNotSupportedError {
69
+ readonly type: "passkey_not_supported";
70
+ }
71
+
72
+ /**
73
+ * Why a passkey ceremony failed (design.md §21.2): `cancelled` (the user
74
+ * walked away), `failed` (anything else, with the native message preserved),
75
+ * `in_progress` (a second ceremony was attempted while one was already
76
+ * running — the caller should await the first instead of retrying).
77
+ */
78
+ export type PasskeyOperationFailureReason = "cancelled" | "failed" | "in_progress";
79
+
80
+ /** A native `react-native-passkeys` ceremony exception, normalized (design.md §21.2). */
81
+ export interface PasskeyOperationError {
82
+ readonly type: "passkey_error";
83
+ readonly reason: PasskeyOperationFailureReason;
84
+ readonly message: string;
85
+ }
86
+
87
+ /** The system browser session was dismissed/cancelled by the user (design.md §20.6). */
88
+ export interface SocialCancelledError {
89
+ readonly type: "social_cancelled";
90
+ }
91
+
92
+ /** Caller misuse: e.g. `verifyEmailCode` with no matching prior `sendEmailCode` challenge. */
93
+ export interface InvalidFlowStateError {
94
+ readonly type: "invalid_flow_state";
95
+ readonly message: string;
96
+ }
97
+
98
+ /** A method that requires `configure()` first was called before it. */
99
+ export interface NotConfiguredError {
100
+ readonly type: "not_configured";
101
+ }
102
+
103
+ export type ReactNativeAuthError =
104
+ | NetworkFailureError
105
+ | InvalidResponseError
106
+ | RateLimitedError
107
+ | ProblemDetailsError
108
+ | OAuthFailureError
109
+ | StateMismatchError
110
+ | NotAuthenticatedError
111
+ | PasskeyNotSupportedError
112
+ | PasskeyOperationError
113
+ | SocialCancelledError
114
+ | InvalidFlowStateError
115
+ | NotConfiguredError;
116
+
117
+ /**
118
+ * Thrown by every `ReactNativeAuthClient` public method on failure (design.md
119
+ * §21.3 specifies bare `Promise<T>` returns, i.e. rejection on failure). The
120
+ * typed `code` lets callers branch programmatically without string-matching
121
+ * `message` (e.g. the prebuilt UI hides `<PasskeyButton/>` on
122
+ * `passkey_not_supported`, design.md §21.2).
123
+ */
124
+ export class ReactNativeAuthClientError extends Error {
125
+ readonly code: ReactNativeAuthError;
126
+
127
+ constructor(code: ReactNativeAuthError) {
128
+ super(describeReactNativeAuthError(code));
129
+ this.name = "ReactNativeAuthClientError";
130
+ this.code = code;
131
+ }
132
+ }
133
+
134
+ const describeReactNativeAuthError = (error: ReactNativeAuthError): string => {
135
+ switch (error.type) {
136
+ case "network_error":
137
+ return `Network error: ${error.message}`;
138
+ case "invalid_response":
139
+ return `Invalid response: ${error.message}`;
140
+ case "rate_limited":
141
+ return "Rate limited";
142
+ case "problem_details":
143
+ return `${error.code}: ${error.title}`;
144
+ case "oauth_error":
145
+ return `OAuth error: ${error.code}`;
146
+ case "state_mismatch":
147
+ return "Callback state did not match the originating request";
148
+ case "not_authenticated":
149
+ return "Not authenticated";
150
+ case "passkey_not_supported":
151
+ return "Passkeys are not supported on this device/OS version";
152
+ case "passkey_error":
153
+ return `Passkey ceremony ${error.reason}: ${error.message}`;
154
+ case "social_cancelled":
155
+ return "Social sign-in was cancelled";
156
+ case "invalid_flow_state":
157
+ return error.message;
158
+ case "not_configured":
159
+ return "configure() must be called before using the auth client";
160
+ }
161
+ };
162
+
163
+ // ---------------------------------------------------------------------------
164
+ // Wire guards (this package cannot import `zod` directly — only
165
+ // `@smartcrab/contracts-public`'s schemas are available, see package.json
166
+ // — so the two error body shapes below are hand-rolled narrowing exactly like
167
+ // `@smartcrab/browser`'s `errors.ts`, not zod schemas).
168
+ // ---------------------------------------------------------------------------
169
+
170
+ export interface ProblemDetailsWire {
171
+ readonly type: string;
172
+ readonly title: string;
173
+ readonly status: number;
174
+ readonly detail?: string;
175
+ readonly code?: string;
176
+ readonly requestId?: string;
177
+ }
178
+
179
+ const isPlainObject = (value: unknown): value is Record<string, unknown> =>
180
+ typeof value === "object" && value !== null && !Array.isArray(value);
181
+
182
+ export const parseProblemDetailsWire = (value: unknown): ProblemDetailsWire | null => {
183
+ if (!isPlainObject(value)) return null;
184
+ if (typeof value["type"] !== "string" || typeof value["title"] !== "string") return null;
185
+ if (typeof value["status"] !== "number" || !Number.isInteger(value["status"])) return null;
186
+ const detail = value["detail"];
187
+ const code = value["code"];
188
+ const requestId = value["request_id"];
189
+ if (detail !== undefined && typeof detail !== "string") return null;
190
+ if (code !== undefined && typeof code !== "string") return null;
191
+ if (requestId !== undefined && typeof requestId !== "string") return null;
192
+ return {
193
+ type: value["type"],
194
+ title: value["title"],
195
+ status: value["status"],
196
+ ...(detail !== undefined ? { detail } : {}),
197
+ ...(code !== undefined ? { code } : {}),
198
+ ...(requestId !== undefined ? { requestId } : {}),
199
+ };
200
+ };
201
+
202
+ export interface OAuthErrorWire {
203
+ readonly error: string;
204
+ readonly description?: string;
205
+ }
206
+
207
+ export const parseOAuthErrorWire = (value: unknown): OAuthErrorWire | null => {
208
+ if (!isPlainObject(value)) return null;
209
+ if (typeof value["error"] !== "string" || value["error"].length === 0) return null;
210
+ const description = value["error_description"];
211
+ if (description !== undefined && typeof description !== "string") return null;
212
+ return {
213
+ error: value["error"],
214
+ ...(description !== undefined ? { description } : {}),
215
+ };
216
+ };