@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.
- package/LICENSE +202 -0
- package/app.plugin.js +9 -0
- package/dist/adapters/expo-crypto-port.d.ts +3 -0
- package/dist/adapters/expo-crypto-port.js +8 -0
- package/dist/adapters/expo-linking-port.d.ts +3 -0
- package/dist/adapters/expo-linking-port.js +21 -0
- package/dist/adapters/expo-secure-store-port.d.ts +11 -0
- package/dist/adapters/expo-secure-store-port.js +15 -0
- package/dist/adapters/expo-web-browser-port.d.ts +7 -0
- package/dist/adapters/expo-web-browser-port.js +9 -0
- package/dist/adapters/react-native-app-state-port.d.ts +8 -0
- package/dist/adapters/react-native-app-state-port.js +13 -0
- package/dist/adapters/react-native-passkeys-adapter.d.ts +2 -0
- package/dist/adapters/react-native-passkeys-adapter.js +112 -0
- package/dist/adapters/react-native-passkeys-adapter.test.d.ts +1 -0
- package/dist/adapters/react-native-passkeys-adapter.test.js +76 -0
- package/dist/base64url.d.ts +20 -0
- package/dist/base64url.js +89 -0
- package/dist/base64url.test.d.ts +1 -0
- package/dist/base64url.test.js +36 -0
- package/dist/browser-port.d.ts +17 -0
- package/dist/browser-port.js +1 -0
- package/dist/client.d.ts +43 -0
- package/dist/client.js +871 -0
- package/dist/client.test.d.ts +1 -0
- package/dist/client.test.js +995 -0
- package/dist/context.d.ts +8 -0
- package/dist/context.js +17 -0
- package/dist/crypto-port.d.ts +16 -0
- package/dist/crypto-port.js +1 -0
- package/dist/errors.d.ts +113 -0
- package/dist/errors.js +82 -0
- package/dist/errors.test.d.ts +1 -0
- package/dist/errors.test.js +81 -0
- package/dist/hooks.d.ts +93 -0
- package/dist/hooks.js +191 -0
- package/dist/http.d.ts +41 -0
- package/dist/http.js +102 -0
- package/dist/index.d.ts +22 -0
- package/dist/index.js +29 -0
- package/dist/jwt.d.ts +1 -0
- package/dist/jwt.js +23 -0
- package/dist/lifecycle-ports.d.ts +29 -0
- package/dist/lifecycle-ports.js +1 -0
- package/dist/linking-port.d.ts +15 -0
- package/dist/linking-port.js +1 -0
- package/dist/passkey-adapter.d.ts +20 -0
- package/dist/passkey-adapter.js +1 -0
- package/dist/pkce.d.ts +32 -0
- package/dist/pkce.js +41 -0
- package/dist/pkce.test.d.ts +1 -0
- package/dist/pkce.test.js +66 -0
- package/dist/plugin.d.ts +89 -0
- package/dist/plugin.js +242 -0
- package/dist/plugin.test.d.ts +1 -0
- package/dist/plugin.test.js +210 -0
- package/dist/provider.d.ts +14 -0
- package/dist/provider.js +5 -0
- package/dist/secure-store.d.ts +54 -0
- package/dist/secure-store.js +55 -0
- package/dist/secure-store.test.d.ts +1 -0
- package/dist/secure-store.test.js +69 -0
- package/dist/types.d.ts +177 -0
- package/dist/types.js +1 -0
- package/package.json +69 -0
- package/src/adapters/expo-crypto-port.ts +11 -0
- package/src/adapters/expo-linking-port.ts +23 -0
- package/src/adapters/expo-secure-store-port.ts +20 -0
- package/src/adapters/expo-web-browser-port.ts +16 -0
- package/src/adapters/react-native-app-state-port.ts +15 -0
- package/src/adapters/react-native-passkeys-adapter.test.ts +87 -0
- package/src/adapters/react-native-passkeys-adapter.ts +138 -0
- package/src/base64url.test.ts +47 -0
- package/src/base64url.ts +92 -0
- package/src/browser-port.ts +19 -0
- package/src/client.test.ts +1275 -0
- package/src/client.ts +1329 -0
- package/src/context.ts +20 -0
- package/src/crypto-port.ts +16 -0
- package/src/errors.test.ts +94 -0
- package/src/errors.ts +216 -0
- package/src/hooks.ts +374 -0
- package/src/http.ts +159 -0
- package/src/index.ts +101 -0
- package/src/jwt.ts +24 -0
- package/src/lifecycle-ports.ts +32 -0
- package/src/linking-port.ts +16 -0
- package/src/passkey-adapter.ts +20 -0
- package/src/pkce.test.ts +84 -0
- package/src/pkce.ts +62 -0
- package/src/plugin.test.ts +303 -0
- package/src/plugin.ts +387 -0
- package/src/provider.tsx +20 -0
- package/src/secure-store.test.ts +91 -0
- package/src/secure-store.ts +102 -0
- package/src/types.ts +181 -0
package/dist/http.js
ADDED
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
import { OAUTH_ERROR_CODES, err, ok } from "@smartcrab/contracts-public";
|
|
2
|
+
import { parseOAuthErrorWire, parseProblemDetailsWire } from "./errors.js";
|
|
3
|
+
const OAUTH_ERROR_CODE_SET = new Set(OAUTH_ERROR_CODES);
|
|
4
|
+
export const isOAuthErrorCode = (value) => OAUTH_ERROR_CODE_SET.has(value);
|
|
5
|
+
const parseRetryAfterSeconds = (response) => {
|
|
6
|
+
const raw = response.headers.get("retry-after");
|
|
7
|
+
if (raw === null)
|
|
8
|
+
return undefined;
|
|
9
|
+
if (!/^[0-9]+$/.test(raw.trim()))
|
|
10
|
+
return undefined;
|
|
11
|
+
return Number.parseInt(raw.trim(), 10);
|
|
12
|
+
};
|
|
13
|
+
const invalidResponse = (message, status) => err({
|
|
14
|
+
type: "invalid_response",
|
|
15
|
+
message,
|
|
16
|
+
...(status !== undefined ? { status } : {}),
|
|
17
|
+
});
|
|
18
|
+
const toNetworkError = (cause) => err({
|
|
19
|
+
type: "network_error",
|
|
20
|
+
message: cause instanceof Error ? cause.message : "Network request failed",
|
|
21
|
+
retryable: true,
|
|
22
|
+
});
|
|
23
|
+
/** `JSON.parse` without a try statement: the throw becomes a rejection inside the promise chain. */
|
|
24
|
+
const parseJsonBody = (text, status) => Promise.resolve()
|
|
25
|
+
.then(() => JSON.parse(text))
|
|
26
|
+
.then((value) => ok(value), () => invalidResponse("Response body was not valid JSON", status));
|
|
27
|
+
/**
|
|
28
|
+
* Executes one JSON request and validates the response against `schema`.
|
|
29
|
+
* Error precedence on non-2xx: 429 -> `rate_limited`; a valid Problem
|
|
30
|
+
* Details body -> `problem_details`; a valid OAuth error body ->
|
|
31
|
+
* `oauth_error`; anything else -> `invalid_response`.
|
|
32
|
+
*/
|
|
33
|
+
export const requestJson = async (fetchPort, request, schema) => {
|
|
34
|
+
const headers = {
|
|
35
|
+
accept: "application/json",
|
|
36
|
+
...(request.body !== undefined ? { "content-type": "application/json" } : {}),
|
|
37
|
+
...(request.accessToken !== undefined
|
|
38
|
+
? { authorization: `Bearer ${request.accessToken}` }
|
|
39
|
+
: {}),
|
|
40
|
+
};
|
|
41
|
+
const responseOutcome = await fetchPort(request.url, {
|
|
42
|
+
method: request.method,
|
|
43
|
+
headers,
|
|
44
|
+
...(request.body !== undefined ? { body: JSON.stringify(request.body) } : {}),
|
|
45
|
+
}).then((response) => ok(response), toNetworkError);
|
|
46
|
+
if (!responseOutcome.ok)
|
|
47
|
+
return responseOutcome;
|
|
48
|
+
const response = responseOutcome.value;
|
|
49
|
+
const textOutcome = await response
|
|
50
|
+
.text()
|
|
51
|
+
.then((text) => ok(text), toNetworkError);
|
|
52
|
+
if (!textOutcome.ok)
|
|
53
|
+
return textOutcome;
|
|
54
|
+
const text = textOutcome.value;
|
|
55
|
+
const jsonOutcome = text.length === 0 ? ok(undefined) : await parseJsonBody(text, response.status);
|
|
56
|
+
if (!jsonOutcome.ok)
|
|
57
|
+
return jsonOutcome;
|
|
58
|
+
const json = jsonOutcome.value;
|
|
59
|
+
if (response.status === 429) {
|
|
60
|
+
const retryAfterSeconds = parseRetryAfterSeconds(response);
|
|
61
|
+
const problem = parseProblemDetailsWire(json);
|
|
62
|
+
return err({
|
|
63
|
+
type: "rate_limited",
|
|
64
|
+
retryable: true,
|
|
65
|
+
...(retryAfterSeconds !== undefined ? { retryAfterSeconds } : {}),
|
|
66
|
+
...(problem !== null && problem.requestId !== undefined
|
|
67
|
+
? { requestId: problem.requestId }
|
|
68
|
+
: {}),
|
|
69
|
+
});
|
|
70
|
+
}
|
|
71
|
+
if (!response.ok) {
|
|
72
|
+
const problem = parseProblemDetailsWire(json);
|
|
73
|
+
if (problem !== null) {
|
|
74
|
+
return err({
|
|
75
|
+
type: "problem_details",
|
|
76
|
+
problemType: problem.type,
|
|
77
|
+
code: problem.code ?? "unknown_error",
|
|
78
|
+
title: problem.title,
|
|
79
|
+
status: problem.status,
|
|
80
|
+
...(problem.detail !== undefined ? { detail: problem.detail } : {}),
|
|
81
|
+
...(problem.requestId !== undefined ? { requestId: problem.requestId } : {}),
|
|
82
|
+
});
|
|
83
|
+
}
|
|
84
|
+
const oauthError = parseOAuthErrorWire(json);
|
|
85
|
+
if (oauthError !== null && isOAuthErrorCode(oauthError.error)) {
|
|
86
|
+
return err({
|
|
87
|
+
type: "oauth_error",
|
|
88
|
+
code: oauthError.error,
|
|
89
|
+
status: response.status,
|
|
90
|
+
...(oauthError.description !== undefined ? { description: oauthError.description } : {}),
|
|
91
|
+
});
|
|
92
|
+
}
|
|
93
|
+
return invalidResponse(`HTTP ${response.status} error body was neither Problem Details nor an OAuth error`, response.status);
|
|
94
|
+
}
|
|
95
|
+
const parsed = schema.safeParse(json);
|
|
96
|
+
if (!parsed.success) {
|
|
97
|
+
return invalidResponse("Response body did not match the public API contract", response.status);
|
|
98
|
+
}
|
|
99
|
+
return ok(parsed.data);
|
|
100
|
+
};
|
|
101
|
+
/** Builds `base + path` (all routes this SDK calls take no query string). */
|
|
102
|
+
export const buildUrl = (baseUrl, path) => `${baseUrl}${path}`;
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
export declare const createReactNativeAuthClient: (initialConfig?: import("./types.js").ReactNativeAuthConfig) => import("./types.js").ReactNativeAuthClient;
|
|
2
|
+
export type { AccessTokenRequest, AuthResult, AuthSession, AuthStateListener, AuthStateSnapshot, DeviceSession, EmailCodeChallenge, Passkey, ReactNativeAuthClient, ReactNativeAuthConfig, RegisterPasskeyInput, UpdateUserProfileInput, UserProfile, } from "./types.js";
|
|
3
|
+
/**
|
|
4
|
+
* Re-exported so downstream packages (e.g. `@smartcrab/ui-react-native`,
|
|
5
|
+
* which does not itself depend on `@smartcrab/contracts-public`) can
|
|
6
|
+
* name the exact type `signInWithSocial`/`linkSocialAccount` take, without
|
|
7
|
+
* needing their own dependency on contracts-public.
|
|
8
|
+
*/
|
|
9
|
+
export type { SocialProvider } from "@smartcrab/contracts-public";
|
|
10
|
+
export { ReactNativeAuthClientError } from "./errors.js";
|
|
11
|
+
export type { InvalidFlowStateError, InvalidResponseError, NetworkFailureError, NotAuthenticatedError, NotConfiguredError, OAuthFailureError, PasskeyNotSupportedError, PasskeyOperationError, PasskeyOperationFailureReason, ProblemDetailsError, RateLimitedError, ReactNativeAuthError, SocialCancelledError, StateMismatchError, } from "./errors.js";
|
|
12
|
+
/** Native adapter boundary (design.md §21.2) — never leaks react-native-passkeys types. */
|
|
13
|
+
export type { PasskeyNativeAdapter } from "./passkey-adapter.js";
|
|
14
|
+
export type { SecureStorePort } from "./secure-store.js";
|
|
15
|
+
export type { WebBrowserAuthResult, WebBrowserPort, WebBrowserResultType } from "./browser-port.js";
|
|
16
|
+
export type { LinkingPort, ParsedCallbackUrl } from "./linking-port.js";
|
|
17
|
+
export type { CryptoPort } from "./crypto-port.js";
|
|
18
|
+
export type { AppStatePort, AppStateStatus, AppStateSubscription, NetworkStatusPort, } from "./lifecycle-ports.js";
|
|
19
|
+
export { AuthProvider } from "./provider.js";
|
|
20
|
+
export type { AuthProviderProps } from "./provider.js";
|
|
21
|
+
export { useAuth, useEmailOtp, usePasskey, useSession, useSessionList, useSocialSignIn, useUser, } from "./hooks.js";
|
|
22
|
+
export type { UseAuthResult, UseEmailOtpResult, UsePasskeyResult, UseSessionListResult, UseSessionResult, UseSocialSignInResult, UseUserResult, } from "./hooks.js";
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `@smartcrab/react-native` (design.md §21). Public entry point —
|
|
3
|
+
* `./plugin` (the Expo Config Plugin, design.md §21.5) is a separate subpath
|
|
4
|
+
* export and is intentionally not re-exported here.
|
|
5
|
+
*
|
|
6
|
+
* This is the ONLY file in the package that imports the `adapters/*` modules
|
|
7
|
+
* (which in turn import `expo-*`/`react-native`/`react-native-passkeys`) —
|
|
8
|
+
* see `client.ts`'s top doc comment for why that boundary is load-bearing for
|
|
9
|
+
* this package's own test suite, not just a style preference.
|
|
10
|
+
*/
|
|
11
|
+
import { expoWebBrowserPort } from "./adapters/expo-web-browser-port.js";
|
|
12
|
+
import { expoCryptoPort } from "./adapters/expo-crypto-port.js";
|
|
13
|
+
import { expoLinkingPort } from "./adapters/expo-linking-port.js";
|
|
14
|
+
import { reactNativeAppStatePort } from "./adapters/react-native-app-state-port.js";
|
|
15
|
+
import { reactNativePasskeysAdapter } from "./adapters/react-native-passkeys-adapter.js";
|
|
16
|
+
import { expoSecureStorePort } from "./adapters/expo-secure-store-port.js";
|
|
17
|
+
import { createReactNativeAuthClientFactory } from "./client.js";
|
|
18
|
+
export const createReactNativeAuthClient = createReactNativeAuthClientFactory({
|
|
19
|
+
secureStore: expoSecureStorePort,
|
|
20
|
+
passkeyAdapter: reactNativePasskeysAdapter,
|
|
21
|
+
browser: expoWebBrowserPort,
|
|
22
|
+
linking: expoLinkingPort,
|
|
23
|
+
crypto: expoCryptoPort,
|
|
24
|
+
appState: reactNativeAppStatePort,
|
|
25
|
+
});
|
|
26
|
+
export { ReactNativeAuthClientError } from "./errors.js";
|
|
27
|
+
// -- React API (design.md §21.4) --------------------------------------------
|
|
28
|
+
export { AuthProvider } from "./provider.js";
|
|
29
|
+
export { useAuth, useEmailOtp, usePasskey, useSession, useSessionList, useSocialSignIn, useUser, } from "./hooks.js";
|
package/dist/jwt.d.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare const decodeJwtSubClaim: (jwt: string) => string | null;
|
package/dist/jwt.js
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { base64UrlDecodeToUtf8String } from "./base64url.js";
|
|
2
|
+
/**
|
|
3
|
+
* Decodes (WITHOUT signature verification) the `sub` claim from a compact
|
|
4
|
+
* JWT's payload segment, purely to label the local `AuthSession`/SecureStore
|
|
5
|
+
* metadata with a user id (design.md §21.6 "session metadataの最小集合").
|
|
6
|
+
* This is not a trust boundary: the token was just issued to this same
|
|
7
|
+
* client over TLS by the token endpoint it requested it from, and resource
|
|
8
|
+
* servers independently verify the signature themselves (design.md §15.8) —
|
|
9
|
+
* this client never uses the decoded claims for an authorization decision.
|
|
10
|
+
*/
|
|
11
|
+
const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
12
|
+
export const decodeJwtSubClaim = (jwt) => {
|
|
13
|
+
const parts = jwt.split(".");
|
|
14
|
+
const payloadSegment = parts[1];
|
|
15
|
+
if (payloadSegment === undefined)
|
|
16
|
+
return null;
|
|
17
|
+
const json = base64UrlDecodeToUtf8String(payloadSegment);
|
|
18
|
+
const parsed = JSON.parse(json);
|
|
19
|
+
if (!isRecord(parsed))
|
|
20
|
+
return null;
|
|
21
|
+
const sub = parsed["sub"];
|
|
22
|
+
return typeof sub === "string" && sub.length > 0 ? sub : null;
|
|
23
|
+
};
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* App lifecycle ports (design.md §21.7).
|
|
3
|
+
*
|
|
4
|
+
* `AppStatePort` drives "foreground復帰時にtoken expiryを確認": React
|
|
5
|
+
* Native's `AppState` is a declared peer dependency (design.md §21.1) and is
|
|
6
|
+
* always available, so a default implementation ships.
|
|
7
|
+
*
|
|
8
|
+
* `NetworkStatusPort` drives "network復帰時に1回だけrefresh": no
|
|
9
|
+
* connectivity-detection package (e.g. `@react-native-community/netinfo`) is
|
|
10
|
+
* among design.md §21.1's peer dependencies, so this SDK cannot ship a real
|
|
11
|
+
* default for it without adding an undeclared dependency. It is therefore an
|
|
12
|
+
* OPTIONAL, injectable port (`ReactNativeAuthConfig.networkStatus`) —
|
|
13
|
+
* consuming apps that install a connectivity package wire it in; when
|
|
14
|
+
* omitted, only the foreground trigger runs. This is a deliberate, documented
|
|
15
|
+
* deviation from a literal reading of §21.7 (see IMPL_NOTES §0.1: "逸脱が必要
|
|
16
|
+
* な場合はコード内に理由をコメントし、最終報告で必ず申告する").
|
|
17
|
+
*/
|
|
18
|
+
export interface AppStateSubscription {
|
|
19
|
+
remove(): void;
|
|
20
|
+
}
|
|
21
|
+
export type AppStateStatus = "active" | "background" | "inactive" | "unknown" | "extension";
|
|
22
|
+
export interface AppStatePort {
|
|
23
|
+
readonly currentState: AppStateStatus;
|
|
24
|
+
addEventListener(type: "change", handler: (state: AppStateStatus) => void): AppStateSubscription;
|
|
25
|
+
}
|
|
26
|
+
export interface NetworkStatusPort {
|
|
27
|
+
/** Invokes `listener(true)` on transition to online, `listener(false)` on transition to offline. */
|
|
28
|
+
subscribe(listener: (online: boolean) => void): () => void;
|
|
29
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Deep-link callback parsing (design.md §20.6, §21.3): the social/hosted
|
|
3
|
+
* authorization callback returns to a custom scheme or Universal/App Link
|
|
4
|
+
* URL, which this port turns into a flat query-parameter map.
|
|
5
|
+
*/
|
|
6
|
+
export interface ParsedCallbackUrl {
|
|
7
|
+
readonly queryParams: Readonly<Record<string, string>>;
|
|
8
|
+
}
|
|
9
|
+
export interface LinkingPort {
|
|
10
|
+
parse(url: string): ParsedCallbackUrl;
|
|
11
|
+
/** The deep link the app was most recently launched/resumed with, if any. */
|
|
12
|
+
getInitialURL(): Promise<string | null>;
|
|
13
|
+
/** Subscribes to deep links received while the app is already running. */
|
|
14
|
+
addEventListener(handler: (url: string) => void): () => void;
|
|
15
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Native adapter boundary (design.md §21.2, verbatim):
|
|
3
|
+
*
|
|
4
|
+
* > 第三者native moduleのAPIをSDK公開面へ直接露出しない。
|
|
5
|
+
*
|
|
6
|
+
* `react-native-passkeys` types never appear here or anywhere in this
|
|
7
|
+
* package's public surface (`index.ts`) — only plain JSON strings cross this
|
|
8
|
+
* boundary. `create`/`get` may reject with the native module's own exception
|
|
9
|
+
* shape (including `react-native-passkeys`' `NotSupportedError`/
|
|
10
|
+
* `UnknownError`, a `DOMException`-like object on web, or a plain `Error`);
|
|
11
|
+
* normalizing that into a public `PasskeyOperationError` code is the
|
|
12
|
+
* *client's* job (design.md: "native module固有の例外は公開error codeへ正規化
|
|
13
|
+
* する"), not the adapter's — this interface intentionally carries no error
|
|
14
|
+
* type of its own.
|
|
15
|
+
*/
|
|
16
|
+
export interface PasskeyNativeAdapter {
|
|
17
|
+
isSupported(): Promise<boolean>;
|
|
18
|
+
create(optionsJson: string): Promise<string>;
|
|
19
|
+
get(optionsJson: string): Promise<string>;
|
|
20
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
package/dist/pkce.d.ts
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import type { CryptoPort } from "./crypto-port.js";
|
|
2
|
+
/**
|
|
3
|
+
* PKCE (RFC 7636) and anti-replay value generation for the React Native SDK
|
|
4
|
+
* (design.md §20.6, §21.3, §16.1). `S256` only — `plain` is never offered
|
|
5
|
+
* (design.md §15.3).
|
|
6
|
+
*/
|
|
7
|
+
export interface PkcePair {
|
|
8
|
+
/** RFC 7636 §4.1 verifier: 43 chars from 32 random bytes, unreserved charset. */
|
|
9
|
+
readonly verifier: string;
|
|
10
|
+
/** RFC 7636 §4.2 S256 challenge: base64url(SHA-256(verifier)), 43 chars. */
|
|
11
|
+
readonly challenge: string;
|
|
12
|
+
readonly method: "S256";
|
|
13
|
+
}
|
|
14
|
+
/** Transaction `state` (design.md §16.1: the server stores only a MAC of it). */
|
|
15
|
+
export declare const generateState: (crypto: CryptoPort) => string;
|
|
16
|
+
/** OIDC `nonce` for ID token replay protection. */
|
|
17
|
+
export declare const generateNonce: (crypto: CryptoPort) => string;
|
|
18
|
+
/**
|
|
19
|
+
* Generates a verifier/challenge pair. 32 random bytes -> 43 base64url chars,
|
|
20
|
+
* inside RFC 7636 §4.1's 43-128 window and matching contracts-public's
|
|
21
|
+
* `codeVerifierSchema` charset exactly.
|
|
22
|
+
*/
|
|
23
|
+
export declare const generatePkcePair: (crypto: CryptoPort) => Promise<PkcePair>;
|
|
24
|
+
/**
|
|
25
|
+
* Constant-time-ish string comparison for `state` verification (design.md
|
|
26
|
+
* §21.3's PKCE/state flow). Real constant-time comparison over variable
|
|
27
|
+
* -length JS strings is not achievable in pure JS without engine-specific
|
|
28
|
+
* guarantees; this at least avoids the short-circuiting `===` comparison and
|
|
29
|
+
* always walks the full (max) length so timing does not trivially reveal how
|
|
30
|
+
* many leading characters matched.
|
|
31
|
+
*/
|
|
32
|
+
export declare const constantTimeEqual: (a: string, b: string) => boolean;
|
package/dist/pkce.js
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import { base64UrlEncodeBytes, standardBase64ToBase64Url } from "./base64url.js";
|
|
2
|
+
const randomBase64Url = (crypto, byteLength) => base64UrlEncodeBytes(crypto.getRandomBytes(byteLength));
|
|
3
|
+
/** Transaction `state` (design.md §16.1: the server stores only a MAC of it). */
|
|
4
|
+
export const generateState = (crypto) => randomBase64Url(crypto, 32);
|
|
5
|
+
/** OIDC `nonce` for ID token replay protection. */
|
|
6
|
+
export const generateNonce = (crypto) => randomBase64Url(crypto, 32);
|
|
7
|
+
/**
|
|
8
|
+
* Generates a verifier/challenge pair. 32 random bytes -> 43 base64url chars,
|
|
9
|
+
* inside RFC 7636 §4.1's 43-128 window and matching contracts-public's
|
|
10
|
+
* `codeVerifierSchema` charset exactly.
|
|
11
|
+
*/
|
|
12
|
+
export const generatePkcePair = async (crypto) => {
|
|
13
|
+
const verifier = randomBase64Url(crypto, 32);
|
|
14
|
+
const digestBase64 = await crypto.sha256Base64(verifier);
|
|
15
|
+
const challenge = standardBase64ToBase64Url(digestBase64);
|
|
16
|
+
if (challenge === null) {
|
|
17
|
+
// The native crypto module violated its own documented contract (a
|
|
18
|
+
// base64-encoded digest); this is an integrity check on a third-party
|
|
19
|
+
// native module boundary, not a predictable business error.
|
|
20
|
+
throw new Error("CryptoPort.sha256Base64 returned a value that is not valid base64");
|
|
21
|
+
}
|
|
22
|
+
return { verifier, challenge, method: "S256" };
|
|
23
|
+
};
|
|
24
|
+
/**
|
|
25
|
+
* Constant-time-ish string comparison for `state` verification (design.md
|
|
26
|
+
* §21.3's PKCE/state flow). Real constant-time comparison over variable
|
|
27
|
+
* -length JS strings is not achievable in pure JS without engine-specific
|
|
28
|
+
* guarantees; this at least avoids the short-circuiting `===` comparison and
|
|
29
|
+
* always walks the full (max) length so timing does not trivially reveal how
|
|
30
|
+
* many leading characters matched.
|
|
31
|
+
*/
|
|
32
|
+
export const constantTimeEqual = (a, b) => {
|
|
33
|
+
const length = Math.max(a.length, b.length);
|
|
34
|
+
let diff = a.length === b.length ? 0 : 1;
|
|
35
|
+
for (let i = 0; i < length; i += 1) {
|
|
36
|
+
const charA = a.charCodeAt(i) || 0;
|
|
37
|
+
const charB = b.charCodeAt(i) || 0;
|
|
38
|
+
diff |= charA ^ charB;
|
|
39
|
+
}
|
|
40
|
+
return diff === 0;
|
|
41
|
+
};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import { describe, expect, test } from "vitest";
|
|
2
|
+
import { base64UrlEncodeBytes } from "./base64url.js";
|
|
3
|
+
import { constantTimeEqual, generateNonce, generatePkcePair, generateState } from "./pkce.js";
|
|
4
|
+
/** Standard (padded) base64, matching what `expo-crypto`'s `digestStringAsync(..., { encoding: BASE64 })` returns. */
|
|
5
|
+
const bytesToStandardBase64 = (bytes) => btoa(String.fromCharCode(...bytes));
|
|
6
|
+
/** Real SHA-256 via the platform's Web Crypto global — ground truth, not just self-consistency. */
|
|
7
|
+
const sha256StandardBase64 = async (data) => {
|
|
8
|
+
const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(data));
|
|
9
|
+
return bytesToStandardBase64(new Uint8Array(digest));
|
|
10
|
+
};
|
|
11
|
+
/** Deterministic fake `CryptoPort` backed by the real Web Crypto digest. */
|
|
12
|
+
const fakeCrypto = (seed) => ({
|
|
13
|
+
getRandomBytes: (byteCount) => new Uint8Array(Array.from({ length: byteCount }, (_, i) => (seed + i * 7) % 256)),
|
|
14
|
+
sha256Base64: sha256StandardBase64,
|
|
15
|
+
});
|
|
16
|
+
describe("generatePkcePair", () => {
|
|
17
|
+
test("S256 challenge is base64url(SHA-256(verifier))", async () => {
|
|
18
|
+
const pair = await generatePkcePair(fakeCrypto(1));
|
|
19
|
+
const expectedDigest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(pair.verifier));
|
|
20
|
+
const expectedChallenge = base64UrlEncodeBytes(new Uint8Array(expectedDigest));
|
|
21
|
+
expect(pair.challenge).toBe(expectedChallenge);
|
|
22
|
+
expect(pair.method).toBe("S256");
|
|
23
|
+
});
|
|
24
|
+
test("verifier matches RFC 7636 §4.1 charset and length (43 chars from 32 random bytes)", async () => {
|
|
25
|
+
const pair = await generatePkcePair(fakeCrypto(2));
|
|
26
|
+
expect(pair.verifier).toHaveLength(43);
|
|
27
|
+
expect(pair.verifier).toMatch(/^[A-Za-z0-9._~-]{43,128}$/);
|
|
28
|
+
});
|
|
29
|
+
test("challenge is 43 base64url characters with no padding", async () => {
|
|
30
|
+
const pair = await generatePkcePair(fakeCrypto(3));
|
|
31
|
+
expect(pair.challenge).toHaveLength(43);
|
|
32
|
+
expect(pair.challenge).toMatch(/^[A-Za-z0-9_-]{43}$/);
|
|
33
|
+
});
|
|
34
|
+
test("different seeds produce different verifiers", async () => {
|
|
35
|
+
const a = await generatePkcePair(fakeCrypto(10));
|
|
36
|
+
const b = await generatePkcePair(fakeCrypto(20));
|
|
37
|
+
expect(a.verifier).not.toBe(b.verifier);
|
|
38
|
+
});
|
|
39
|
+
test("throws when the crypto port returns a non-base64 digest (integrity check, not a business error)", async () => {
|
|
40
|
+
const brokenCrypto = {
|
|
41
|
+
getRandomBytes: (n) => new Uint8Array(n),
|
|
42
|
+
sha256Base64: () => Promise.resolve("not base64!!"),
|
|
43
|
+
};
|
|
44
|
+
await expect(generatePkcePair(brokenCrypto)).rejects.toThrow();
|
|
45
|
+
});
|
|
46
|
+
});
|
|
47
|
+
describe("generateState / generateNonce", () => {
|
|
48
|
+
test("produce 43-character base64url strings", () => {
|
|
49
|
+
expect(generateState(fakeCrypto(5))).toHaveLength(43);
|
|
50
|
+
expect(generateNonce(fakeCrypto(5))).toHaveLength(43);
|
|
51
|
+
});
|
|
52
|
+
});
|
|
53
|
+
describe("constantTimeEqual", () => {
|
|
54
|
+
test("true for identical strings", () => {
|
|
55
|
+
expect(constantTimeEqual("abc123", "abc123")).toBe(true);
|
|
56
|
+
});
|
|
57
|
+
test("false for different strings of the same length", () => {
|
|
58
|
+
expect(constantTimeEqual("abc123", "abc124")).toBe(false);
|
|
59
|
+
});
|
|
60
|
+
test("false for different lengths", () => {
|
|
61
|
+
expect(constantTimeEqual("abc", "abcd")).toBe(false);
|
|
62
|
+
});
|
|
63
|
+
test("false against an empty string", () => {
|
|
64
|
+
expect(constantTimeEqual("abc", "")).toBe(false);
|
|
65
|
+
});
|
|
66
|
+
});
|
package/dist/plugin.d.ts
ADDED
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
import { AndroidConfig } from "expo/config-plugins";
|
|
2
|
+
import type { ConfigPlugin, InfoPlist } from "expo/config-plugins";
|
|
3
|
+
type ManifestIntentFilter = AndroidConfig.Manifest.ManifestIntentFilter;
|
|
4
|
+
/**
|
|
5
|
+
* Expo Config Plugin (design.md §21.5), exported as `@smartcrab/react-native/plugin`.
|
|
6
|
+
*
|
|
7
|
+
* ```ts
|
|
8
|
+
* plugins: [["@smartcrab/react-native/plugin", { clientId, rpDomain, callbackPath }]]
|
|
9
|
+
* ```
|
|
10
|
+
*
|
|
11
|
+
* Does, per design.md §21.5:
|
|
12
|
+
* - iOS Associated Domains: `webcredentials:<rpDomain>` + `applinks:<rpDomain>` (Universal Link domain)
|
|
13
|
+
* - iOS `CFBundleURLTypes`: ensures the app's custom scheme (`expo.scheme`) is registered
|
|
14
|
+
* - Android intent filters: the custom scheme + an `autoVerify` HTTPS App Link for `<rpDomain><callbackPath>`
|
|
15
|
+
* - Android Credential Manager: an `asset_statements` string resource pointing at `<rpDomain>`'s
|
|
16
|
+
* `.well-known/assetlinks.json`, which Android's passkey Credential Manager provider reads
|
|
17
|
+
* - Validates `react-native-passkeys`-relevant config and turns unsupported deployments into
|
|
18
|
+
* build-time errors (a missing/malformed `expo.scheme`, or an explicit iOS deployment target
|
|
19
|
+
* below design.md §3.2's 15.1 floor)
|
|
20
|
+
*
|
|
21
|
+
* Apple Team ID / Bundle ID / Android package / signing fingerprints are registered with the
|
|
22
|
+
* platform's dashboard/CLI, not here (design.md §21.5) — this plugin only shapes the native
|
|
23
|
+
* project files that must agree with that registration.
|
|
24
|
+
*/
|
|
25
|
+
export interface AuthPlatformReactNativePluginProps {
|
|
26
|
+
readonly clientId: string;
|
|
27
|
+
/** The Relying Party domain, e.g. `auth.customer.example` — a bare host, no scheme/path. */
|
|
28
|
+
readonly rpDomain: string;
|
|
29
|
+
/** Path segment the OAuth/social callback lands on, e.g. `oauth/callback` (no leading slash). */
|
|
30
|
+
readonly callbackPath: string;
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* design.md §3.2 floor (minSdk 28, compileSdk 34); §21.5 turns unsupported
|
|
34
|
+
* deployments into build-time errors. Expo sets these via the
|
|
35
|
+
* `expo-build-properties` plugin entry in `config.plugins`
|
|
36
|
+
* (`["expo-build-properties", { android: { minSdkVersion, compileSdkVersion } }]`),
|
|
37
|
+
* so only an *explicitly set* value below the floor throws — unset passes
|
|
38
|
+
* (Expo's own default already satisfies the floor). Malformed entries
|
|
39
|
+
* (bare strings, wrong arity/name, non-object props) are ignored.
|
|
40
|
+
*/
|
|
41
|
+
export declare const validateAndroidSdkVersions: (plugins: readonly unknown[] | undefined) => void;
|
|
42
|
+
export declare const ASSOCIATED_DOMAINS_KEY = "com.apple.developer.associated-domains";
|
|
43
|
+
/**
|
|
44
|
+
* Pure merge logic, extracted out of the `withEntitlementsPlist` mod callback
|
|
45
|
+
* so it is directly unit-testable: Expo's mod system defers the actual
|
|
46
|
+
* plist/manifest file mutation to `expo prebuild`'s mod-compilation step
|
|
47
|
+
* (`compileModsAsync`), so calling the exported plugin function in a unit
|
|
48
|
+
* test does NOT synchronously produce a mutated `config.ios`/`config.android`
|
|
49
|
+
* — only queues the mod. This function is what actually runs once compiled.
|
|
50
|
+
*/
|
|
51
|
+
export declare const mergeAssociatedDomains: (existing: unknown, rpDomain: string) => string[];
|
|
52
|
+
type UrlTypeEntry = NonNullable<InfoPlist["CFBundleURLTypes"]>[number];
|
|
53
|
+
export declare const mergeUrlScheme: (existing: readonly UrlTypeEntry[] | undefined, scheme: string) => UrlTypeEntry[];
|
|
54
|
+
/**
|
|
55
|
+
* Pure merge logic (see `mergeAssociatedDomains`'s doc comment on why this is extracted).
|
|
56
|
+
*
|
|
57
|
+
* The HTTPS App Link filter pins `callbackPath` in its `android:pathPrefix`,
|
|
58
|
+
* so a host-only existence check would leave a stale filter behind when
|
|
59
|
+
* `callbackPath` changes (and never add the fresh one): every existing HTTPS
|
|
60
|
+
* filter for `rpDomain` is dropped, then the fresh one is pushed.
|
|
61
|
+
*/
|
|
62
|
+
export declare const mergeAndroidIntentFilters: (existing: readonly ManifestIntentFilter[], props: AuthPlatformReactNativePluginProps & {
|
|
63
|
+
scheme: string;
|
|
64
|
+
}) => ManifestIntentFilter[];
|
|
65
|
+
type ResourceItemXML = NonNullable<AndroidConfig.Resources.ResourceXML["resources"]["string"]>[number];
|
|
66
|
+
export declare const ASSET_STATEMENTS_RESOURCE_NAME = "asset_statements";
|
|
67
|
+
/**
|
|
68
|
+
* Android Credential Manager (design.md §21.5, §17): `asset_statements` is how
|
|
69
|
+
* Android's passkey provider verifies this app is authorized for `rpDomain`,
|
|
70
|
+
* mirroring the app's Digital Asset Links statement
|
|
71
|
+
* (`https://<rpDomain>/.well-known/assetlinks.json`, registered against the
|
|
72
|
+
* app's signing fingerprint on the platform dashboard per design.md §21.5's
|
|
73
|
+
* closing note). Pure merge logic (see `mergeAssociatedDomains`'s doc comment
|
|
74
|
+
* on why this is extracted).
|
|
75
|
+
*/
|
|
76
|
+
export declare const mergeAssetStatementsResource: (existing: readonly ResourceItemXML[], rpDomain: string) => ResourceItemXML[];
|
|
77
|
+
type ManifestMetaData = AndroidConfig.Manifest.ManifestMetaData;
|
|
78
|
+
/**
|
|
79
|
+
* Android Credential Manager linkage (design.md §21.5, §17): the manifest's
|
|
80
|
+
* main `<application>` must point at the `asset_statements` string resource
|
|
81
|
+
* above, or Android's passkey Credential Manager provider never reads the
|
|
82
|
+
* Digital Asset Links statement. Pure merge logic (see
|
|
83
|
+
* `mergeAssociatedDomains`'s doc comment on why this is extracted): ensures
|
|
84
|
+
* exactly one `asset_statements` `<meta-data>` entry (replacing a stale
|
|
85
|
+
* same-name entry, preserving siblings).
|
|
86
|
+
*/
|
|
87
|
+
export declare const mergeAssetStatementsMetaData: (existing: readonly ManifestMetaData[] | undefined) => ManifestMetaData[];
|
|
88
|
+
declare const _default: ConfigPlugin<AuthPlatformReactNativePluginProps>;
|
|
89
|
+
export default _default;
|