@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
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import type { ReactNativeAuthClient } from "./types.js";
|
|
2
|
+
/**
|
|
3
|
+
* Dependency context for the React Native React API (design.md §21.4).
|
|
4
|
+
* One `<AuthProvider client={...}>` per client instance; every hook resolves
|
|
5
|
+
* its dependency through here.
|
|
6
|
+
*/
|
|
7
|
+
export declare const AuthContext: import("react").Context<ReactNativeAuthClient | null>;
|
|
8
|
+
export declare const useAuthClient: () => ReactNativeAuthClient;
|
package/dist/context.js
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { createContext, useContext } from "react";
|
|
2
|
+
/**
|
|
3
|
+
* Dependency context for the React Native React API (design.md §21.4).
|
|
4
|
+
* One `<AuthProvider client={...}>` per client instance; every hook resolves
|
|
5
|
+
* its dependency through here.
|
|
6
|
+
*/
|
|
7
|
+
export const AuthContext = createContext(null);
|
|
8
|
+
export const useAuthClient = () => {
|
|
9
|
+
const client = useContext(AuthContext);
|
|
10
|
+
if (client === null) {
|
|
11
|
+
// Programmer error (missing <AuthProvider>) — surfaced loudly, the usual
|
|
12
|
+
// React convention for required-provider hooks (mirrors
|
|
13
|
+
// `@smartcrab/sdk-react`'s `useAuthContextValue`).
|
|
14
|
+
throw new Error("Auth hooks must be used inside <AuthProvider client={...}>");
|
|
15
|
+
}
|
|
16
|
+
return client;
|
|
17
|
+
};
|
|
@@ -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 @@
|
|
|
1
|
+
export {};
|
package/dist/errors.d.ts
ADDED
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
import type { OAuthErrorCode } from "@smartcrab/contracts-public";
|
|
2
|
+
/**
|
|
3
|
+
* Error model for `@smartcrab/react-native` (design.md §21.2, §21.3, §32).
|
|
4
|
+
*
|
|
5
|
+
* `ReactNativeAuthClient`'s public methods return bare `Promise<T>` per
|
|
6
|
+
* design.md §21.3's verbatim interface (they reject, not resolve-to-Outcome).
|
|
7
|
+
* Internally, every fallible step resolves to `Outcome<T, ReactNativeAuthError>`
|
|
8
|
+
* (no direct `try`/`catch` — `scripts/check-backend-error-style.ts`, design.md
|
|
9
|
+
* §5.2, scans this package); only at the public method boundary is a failed
|
|
10
|
+
* `Outcome` converted into a rejected promise via `ReactNativeAuthClientError`
|
|
11
|
+
* (design.md §5.2's "境界では Result を必ず解決する" applied to this SDK's own
|
|
12
|
+
* public surface).
|
|
13
|
+
*/
|
|
14
|
+
export interface NetworkFailureError {
|
|
15
|
+
readonly type: "network_error";
|
|
16
|
+
readonly message: string;
|
|
17
|
+
readonly retryable: true;
|
|
18
|
+
}
|
|
19
|
+
export interface InvalidResponseError {
|
|
20
|
+
readonly type: "invalid_response";
|
|
21
|
+
readonly message: string;
|
|
22
|
+
/** HTTP status of the offending response, when one was received at all. */
|
|
23
|
+
readonly status?: number;
|
|
24
|
+
}
|
|
25
|
+
export interface RateLimitedError {
|
|
26
|
+
readonly type: "rate_limited";
|
|
27
|
+
readonly retryable: true;
|
|
28
|
+
readonly retryAfterSeconds?: number;
|
|
29
|
+
readonly requestId?: string;
|
|
30
|
+
}
|
|
31
|
+
export interface ProblemDetailsError {
|
|
32
|
+
readonly type: "problem_details";
|
|
33
|
+
/** `type` URI from the RFC 9457 Problem Details body. */
|
|
34
|
+
readonly problemType: string;
|
|
35
|
+
/** Platform snake_case error code (`code` extension member). */
|
|
36
|
+
readonly code: string;
|
|
37
|
+
readonly title: string;
|
|
38
|
+
readonly status: number;
|
|
39
|
+
readonly detail?: string;
|
|
40
|
+
readonly requestId?: string;
|
|
41
|
+
}
|
|
42
|
+
export interface OAuthFailureError {
|
|
43
|
+
readonly type: "oauth_error";
|
|
44
|
+
readonly code: OAuthErrorCode;
|
|
45
|
+
readonly description?: string;
|
|
46
|
+
readonly status?: number;
|
|
47
|
+
}
|
|
48
|
+
/** An authorization/complete/social callback carried a `state` this client never issued (design.md §32.1). */
|
|
49
|
+
export interface StateMismatchError {
|
|
50
|
+
readonly type: "state_mismatch";
|
|
51
|
+
}
|
|
52
|
+
export interface NotAuthenticatedError {
|
|
53
|
+
readonly type: "not_authenticated";
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* Runtime WebAuthn capability is false (design.md §21.2): the standard UI
|
|
57
|
+
* hides passkey affordances on this code, never attempting a ceremony.
|
|
58
|
+
*/
|
|
59
|
+
export interface PasskeyNotSupportedError {
|
|
60
|
+
readonly type: "passkey_not_supported";
|
|
61
|
+
}
|
|
62
|
+
/**
|
|
63
|
+
* Why a passkey ceremony failed (design.md §21.2): `cancelled` (the user
|
|
64
|
+
* walked away), `failed` (anything else, with the native message preserved),
|
|
65
|
+
* `in_progress` (a second ceremony was attempted while one was already
|
|
66
|
+
* running — the caller should await the first instead of retrying).
|
|
67
|
+
*/
|
|
68
|
+
export type PasskeyOperationFailureReason = "cancelled" | "failed" | "in_progress";
|
|
69
|
+
/** A native `react-native-passkeys` ceremony exception, normalized (design.md §21.2). */
|
|
70
|
+
export interface PasskeyOperationError {
|
|
71
|
+
readonly type: "passkey_error";
|
|
72
|
+
readonly reason: PasskeyOperationFailureReason;
|
|
73
|
+
readonly message: string;
|
|
74
|
+
}
|
|
75
|
+
/** The system browser session was dismissed/cancelled by the user (design.md §20.6). */
|
|
76
|
+
export interface SocialCancelledError {
|
|
77
|
+
readonly type: "social_cancelled";
|
|
78
|
+
}
|
|
79
|
+
/** Caller misuse: e.g. `verifyEmailCode` with no matching prior `sendEmailCode` challenge. */
|
|
80
|
+
export interface InvalidFlowStateError {
|
|
81
|
+
readonly type: "invalid_flow_state";
|
|
82
|
+
readonly message: string;
|
|
83
|
+
}
|
|
84
|
+
/** A method that requires `configure()` first was called before it. */
|
|
85
|
+
export interface NotConfiguredError {
|
|
86
|
+
readonly type: "not_configured";
|
|
87
|
+
}
|
|
88
|
+
export type ReactNativeAuthError = NetworkFailureError | InvalidResponseError | RateLimitedError | ProblemDetailsError | OAuthFailureError | StateMismatchError | NotAuthenticatedError | PasskeyNotSupportedError | PasskeyOperationError | SocialCancelledError | InvalidFlowStateError | NotConfiguredError;
|
|
89
|
+
/**
|
|
90
|
+
* Thrown by every `ReactNativeAuthClient` public method on failure (design.md
|
|
91
|
+
* §21.3 specifies bare `Promise<T>` returns, i.e. rejection on failure). The
|
|
92
|
+
* typed `code` lets callers branch programmatically without string-matching
|
|
93
|
+
* `message` (e.g. the prebuilt UI hides `<PasskeyButton/>` on
|
|
94
|
+
* `passkey_not_supported`, design.md §21.2).
|
|
95
|
+
*/
|
|
96
|
+
export declare class ReactNativeAuthClientError extends Error {
|
|
97
|
+
readonly code: ReactNativeAuthError;
|
|
98
|
+
constructor(code: ReactNativeAuthError);
|
|
99
|
+
}
|
|
100
|
+
export interface ProblemDetailsWire {
|
|
101
|
+
readonly type: string;
|
|
102
|
+
readonly title: string;
|
|
103
|
+
readonly status: number;
|
|
104
|
+
readonly detail?: string;
|
|
105
|
+
readonly code?: string;
|
|
106
|
+
readonly requestId?: string;
|
|
107
|
+
}
|
|
108
|
+
export declare const parseProblemDetailsWire: (value: unknown) => ProblemDetailsWire | null;
|
|
109
|
+
export interface OAuthErrorWire {
|
|
110
|
+
readonly error: string;
|
|
111
|
+
readonly description?: string;
|
|
112
|
+
}
|
|
113
|
+
export declare const parseOAuthErrorWire: (value: unknown) => OAuthErrorWire | null;
|
package/dist/errors.js
ADDED
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Thrown by every `ReactNativeAuthClient` public method on failure (design.md
|
|
3
|
+
* §21.3 specifies bare `Promise<T>` returns, i.e. rejection on failure). The
|
|
4
|
+
* typed `code` lets callers branch programmatically without string-matching
|
|
5
|
+
* `message` (e.g. the prebuilt UI hides `<PasskeyButton/>` on
|
|
6
|
+
* `passkey_not_supported`, design.md §21.2).
|
|
7
|
+
*/
|
|
8
|
+
export class ReactNativeAuthClientError extends Error {
|
|
9
|
+
code;
|
|
10
|
+
constructor(code) {
|
|
11
|
+
super(describeReactNativeAuthError(code));
|
|
12
|
+
this.name = "ReactNativeAuthClientError";
|
|
13
|
+
this.code = code;
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
const describeReactNativeAuthError = (error) => {
|
|
17
|
+
switch (error.type) {
|
|
18
|
+
case "network_error":
|
|
19
|
+
return `Network error: ${error.message}`;
|
|
20
|
+
case "invalid_response":
|
|
21
|
+
return `Invalid response: ${error.message}`;
|
|
22
|
+
case "rate_limited":
|
|
23
|
+
return "Rate limited";
|
|
24
|
+
case "problem_details":
|
|
25
|
+
return `${error.code}: ${error.title}`;
|
|
26
|
+
case "oauth_error":
|
|
27
|
+
return `OAuth error: ${error.code}`;
|
|
28
|
+
case "state_mismatch":
|
|
29
|
+
return "Callback state did not match the originating request";
|
|
30
|
+
case "not_authenticated":
|
|
31
|
+
return "Not authenticated";
|
|
32
|
+
case "passkey_not_supported":
|
|
33
|
+
return "Passkeys are not supported on this device/OS version";
|
|
34
|
+
case "passkey_error":
|
|
35
|
+
return `Passkey ceremony ${error.reason}: ${error.message}`;
|
|
36
|
+
case "social_cancelled":
|
|
37
|
+
return "Social sign-in was cancelled";
|
|
38
|
+
case "invalid_flow_state":
|
|
39
|
+
return error.message;
|
|
40
|
+
case "not_configured":
|
|
41
|
+
return "configure() must be called before using the auth client";
|
|
42
|
+
}
|
|
43
|
+
};
|
|
44
|
+
const isPlainObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
45
|
+
export const parseProblemDetailsWire = (value) => {
|
|
46
|
+
if (!isPlainObject(value))
|
|
47
|
+
return null;
|
|
48
|
+
if (typeof value["type"] !== "string" || typeof value["title"] !== "string")
|
|
49
|
+
return null;
|
|
50
|
+
if (typeof value["status"] !== "number" || !Number.isInteger(value["status"]))
|
|
51
|
+
return null;
|
|
52
|
+
const detail = value["detail"];
|
|
53
|
+
const code = value["code"];
|
|
54
|
+
const requestId = value["request_id"];
|
|
55
|
+
if (detail !== undefined && typeof detail !== "string")
|
|
56
|
+
return null;
|
|
57
|
+
if (code !== undefined && typeof code !== "string")
|
|
58
|
+
return null;
|
|
59
|
+
if (requestId !== undefined && typeof requestId !== "string")
|
|
60
|
+
return null;
|
|
61
|
+
return {
|
|
62
|
+
type: value["type"],
|
|
63
|
+
title: value["title"],
|
|
64
|
+
status: value["status"],
|
|
65
|
+
...(detail !== undefined ? { detail } : {}),
|
|
66
|
+
...(code !== undefined ? { code } : {}),
|
|
67
|
+
...(requestId !== undefined ? { requestId } : {}),
|
|
68
|
+
};
|
|
69
|
+
};
|
|
70
|
+
export const parseOAuthErrorWire = (value) => {
|
|
71
|
+
if (!isPlainObject(value))
|
|
72
|
+
return null;
|
|
73
|
+
if (typeof value["error"] !== "string" || value["error"].length === 0)
|
|
74
|
+
return null;
|
|
75
|
+
const description = value["error_description"];
|
|
76
|
+
if (description !== undefined && typeof description !== "string")
|
|
77
|
+
return null;
|
|
78
|
+
return {
|
|
79
|
+
error: value["error"],
|
|
80
|
+
...(description !== undefined ? { description } : {}),
|
|
81
|
+
};
|
|
82
|
+
};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
import { describe, expect, test } from "vitest";
|
|
2
|
+
import { ReactNativeAuthClientError, parseOAuthErrorWire, parseProblemDetailsWire, } from "./errors.js";
|
|
3
|
+
describe("ReactNativeAuthClientError", () => {
|
|
4
|
+
test("carries the typed error code and a human-readable message", () => {
|
|
5
|
+
const error = new ReactNativeAuthClientError({ type: "passkey_not_supported" });
|
|
6
|
+
expect(error.code).toEqual({ type: "passkey_not_supported" });
|
|
7
|
+
expect(error.name).toBe("ReactNativeAuthClientError");
|
|
8
|
+
expect(error).toBeInstanceOf(Error);
|
|
9
|
+
expect(error.message.length).toBeGreaterThan(0);
|
|
10
|
+
});
|
|
11
|
+
test("is distinguishable via instanceof after being thrown/caught", () => {
|
|
12
|
+
const thrower = () => {
|
|
13
|
+
throw new ReactNativeAuthClientError({ type: "not_authenticated" });
|
|
14
|
+
};
|
|
15
|
+
expect(thrower).toThrow(ReactNativeAuthClientError);
|
|
16
|
+
});
|
|
17
|
+
});
|
|
18
|
+
describe("passkey_error reasons", () => {
|
|
19
|
+
test("in_progress describes the concurrent-ceremony guard", () => {
|
|
20
|
+
const error = new ReactNativeAuthClientError({
|
|
21
|
+
type: "passkey_error",
|
|
22
|
+
reason: "in_progress",
|
|
23
|
+
message: "A passkey ceremony is already in progress",
|
|
24
|
+
});
|
|
25
|
+
expect(error.code).toEqual({
|
|
26
|
+
type: "passkey_error",
|
|
27
|
+
reason: "in_progress",
|
|
28
|
+
message: "A passkey ceremony is already in progress",
|
|
29
|
+
});
|
|
30
|
+
expect(error.message).toContain("in_progress");
|
|
31
|
+
});
|
|
32
|
+
});
|
|
33
|
+
describe("parseProblemDetailsWire", () => {
|
|
34
|
+
test("accepts a minimal RFC 9457 body", () => {
|
|
35
|
+
const parsed = parseProblemDetailsWire({
|
|
36
|
+
type: "about:blank",
|
|
37
|
+
title: "Bad Request",
|
|
38
|
+
status: 400,
|
|
39
|
+
});
|
|
40
|
+
expect(parsed).toEqual({ type: "about:blank", title: "Bad Request", status: 400 });
|
|
41
|
+
});
|
|
42
|
+
test("accepts optional detail/code/request_id", () => {
|
|
43
|
+
const parsed = parseProblemDetailsWire({
|
|
44
|
+
type: "about:blank",
|
|
45
|
+
title: "Bad Request",
|
|
46
|
+
status: 400,
|
|
47
|
+
detail: "email is invalid",
|
|
48
|
+
code: "invalid_request",
|
|
49
|
+
request_id: "req_abc",
|
|
50
|
+
});
|
|
51
|
+
expect(parsed).toEqual({
|
|
52
|
+
type: "about:blank",
|
|
53
|
+
title: "Bad Request",
|
|
54
|
+
status: 400,
|
|
55
|
+
detail: "email is invalid",
|
|
56
|
+
code: "invalid_request",
|
|
57
|
+
requestId: "req_abc",
|
|
58
|
+
});
|
|
59
|
+
});
|
|
60
|
+
test("rejects non-object / missing required fields", () => {
|
|
61
|
+
expect(parseProblemDetailsWire(null)).toBeNull();
|
|
62
|
+
expect(parseProblemDetailsWire({ type: "about:blank" })).toBeNull();
|
|
63
|
+
expect(parseProblemDetailsWire({ type: "about:blank", title: "x", status: "400" })).toBeNull();
|
|
64
|
+
});
|
|
65
|
+
});
|
|
66
|
+
describe("parseOAuthErrorWire", () => {
|
|
67
|
+
test("accepts a minimal RFC 6749 §5.2 error body", () => {
|
|
68
|
+
expect(parseOAuthErrorWire({ error: "invalid_grant" })).toEqual({ error: "invalid_grant" });
|
|
69
|
+
});
|
|
70
|
+
test("accepts an optional description", () => {
|
|
71
|
+
expect(parseOAuthErrorWire({ error: "invalid_grant", error_description: "expired" })).toEqual({
|
|
72
|
+
error: "invalid_grant",
|
|
73
|
+
description: "expired",
|
|
74
|
+
});
|
|
75
|
+
});
|
|
76
|
+
test("rejects a missing/empty error field", () => {
|
|
77
|
+
expect(parseOAuthErrorWire({})).toBeNull();
|
|
78
|
+
expect(parseOAuthErrorWire({ error: "" })).toBeNull();
|
|
79
|
+
expect(parseOAuthErrorWire(null)).toBeNull();
|
|
80
|
+
});
|
|
81
|
+
});
|
package/dist/hooks.d.ts
ADDED
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
import { ReactNativeAuthClientError } from "./errors.js";
|
|
2
|
+
import type { AccessTokenRequest, AuthResult, AuthSession, AuthStateSnapshot, DeviceSession, EmailCodeChallenge, Passkey, RegisterPasskeyInput, UpdateUserProfileInput, UserProfile } from "./types.js";
|
|
3
|
+
import type { SocialProvider } from "@smartcrab/contracts-public";
|
|
4
|
+
/**
|
|
5
|
+
* The React hook surface (design.md §21.4). Every hook binds
|
|
6
|
+
* `client.subscribe`/`client.getSnapshot` via `useSyncExternalStore` so
|
|
7
|
+
* re-renders happen exactly when the underlying auth state changes, plus
|
|
8
|
+
* `useState`-managed local state for hooks that fetch their own data
|
|
9
|
+
* (`useSession`, `useUser`, `usePasskey`).
|
|
10
|
+
*
|
|
11
|
+
* No `try`/`catch` statements here (design.md §5.2 scans this package, unlike
|
|
12
|
+
* `ui-react-native`/`sdk-react`, which are excluded): fallible calls that need
|
|
13
|
+
* to land in local component state use `.then(onFulfilled, onRejected)`
|
|
14
|
+
* instead. Ceremony actions (`usePasskey`'s `signIn`/`register`) additionally
|
|
15
|
+
* flip `isLoading` for the ceremony's duration; other simple pass-throughs
|
|
16
|
+
* return the client's promise directly — it rejects with
|
|
17
|
+
* `ReactNativeAuthClientError`, which the *calling UI component's* event
|
|
18
|
+
* handler (design.md §5.2 exempts UI) is free to catch with a plain
|
|
19
|
+
* `try`/`catch`.
|
|
20
|
+
*/
|
|
21
|
+
export interface UseAuthResult {
|
|
22
|
+
readonly snapshot: AuthStateSnapshot;
|
|
23
|
+
readonly isSignedIn: boolean;
|
|
24
|
+
readonly passkeySupported: boolean;
|
|
25
|
+
readonly signInWithPasskey: () => Promise<AuthResult>;
|
|
26
|
+
readonly signInWithSocial: (input: {
|
|
27
|
+
provider: SocialProvider;
|
|
28
|
+
}) => Promise<AuthResult>;
|
|
29
|
+
readonly sendEmailCode: (input: {
|
|
30
|
+
email: string;
|
|
31
|
+
}) => Promise<EmailCodeChallenge>;
|
|
32
|
+
readonly verifyEmailCode: (input: {
|
|
33
|
+
challengeId: string;
|
|
34
|
+
code: string;
|
|
35
|
+
}) => Promise<AuthResult>;
|
|
36
|
+
readonly getAccessToken: (input?: AccessTokenRequest) => Promise<string>;
|
|
37
|
+
readonly signOut: () => Promise<void>;
|
|
38
|
+
readonly signOutAll: () => Promise<void>;
|
|
39
|
+
}
|
|
40
|
+
/** Main facade (design.md §21.4's `useAuth`, matches §21.8's sample destructuring). */
|
|
41
|
+
export declare const useAuth: () => UseAuthResult;
|
|
42
|
+
export interface UseSessionResult {
|
|
43
|
+
readonly session: AuthSession | null;
|
|
44
|
+
readonly isLoading: boolean;
|
|
45
|
+
readonly reload: () => Promise<AuthSession | null>;
|
|
46
|
+
}
|
|
47
|
+
/** Session metadata (design.md §21.4's `useSession`), reloaded whenever sign-in status changes. */
|
|
48
|
+
export declare const useSession: () => UseSessionResult;
|
|
49
|
+
export interface UseUserResult {
|
|
50
|
+
readonly user: UserProfile | null;
|
|
51
|
+
readonly isLoading: boolean;
|
|
52
|
+
readonly error: ReactNativeAuthClientError | null;
|
|
53
|
+
readonly reload: () => Promise<UserProfile | null>;
|
|
54
|
+
readonly update: (input: UpdateUserProfileInput) => Promise<UserProfile>;
|
|
55
|
+
}
|
|
56
|
+
/** Signed-in user's profile (design.md §21.4's `useUser`); loads on sign-in, clears on sign-out. */
|
|
57
|
+
export declare const useUser: () => UseUserResult;
|
|
58
|
+
export interface UsePasskeyResult {
|
|
59
|
+
/** Runtime WebAuthn capability (design.md §21.2) — prebuilt UI hides passkey affordances when false. */
|
|
60
|
+
readonly passkeySupported: boolean;
|
|
61
|
+
readonly passkeys: readonly Passkey[];
|
|
62
|
+
readonly isLoading: boolean;
|
|
63
|
+
readonly error: ReactNativeAuthClientError | null;
|
|
64
|
+
readonly reload: () => Promise<Passkey[]>;
|
|
65
|
+
readonly signIn: () => Promise<AuthResult>;
|
|
66
|
+
readonly register: (input?: RegisterPasskeyInput) => Promise<Passkey>;
|
|
67
|
+
readonly remove: (passkeyId: string) => Promise<void>;
|
|
68
|
+
}
|
|
69
|
+
/** Passkey ceremonies + self-service management (design.md §21.4's `usePasskey`). */
|
|
70
|
+
export declare const usePasskey: () => UsePasskeyResult;
|
|
71
|
+
export interface UseEmailOtpResult {
|
|
72
|
+
readonly sendCode: (email: string) => Promise<EmailCodeChallenge>;
|
|
73
|
+
readonly verifyCode: (input: {
|
|
74
|
+
challengeId: string;
|
|
75
|
+
code: string;
|
|
76
|
+
}) => Promise<AuthResult>;
|
|
77
|
+
}
|
|
78
|
+
/** Email OTP sign-in (design.md §21.4's `useEmailOtp`; backs `<EmailOtpForm/>`, design.md §21.4). */
|
|
79
|
+
export declare const useEmailOtp: () => UseEmailOtpResult;
|
|
80
|
+
export interface UseSocialSignInResult {
|
|
81
|
+
readonly signIn: (provider: SocialProvider) => Promise<AuthResult>;
|
|
82
|
+
readonly link: (provider: SocialProvider) => Promise<void>;
|
|
83
|
+
}
|
|
84
|
+
/** Social sign-in / account linking (design.md §21.4's `useSocialSignIn`; §20.6 system-browser flow). */
|
|
85
|
+
export declare const useSocialSignIn: () => UseSocialSignInResult;
|
|
86
|
+
export interface UseSessionListResult {
|
|
87
|
+
readonly sessions: readonly DeviceSession[];
|
|
88
|
+
readonly isLoading: boolean;
|
|
89
|
+
readonly error: ReactNativeAuthClientError | null;
|
|
90
|
+
readonly reload: () => Promise<DeviceSession[]>;
|
|
91
|
+
readonly revoke: (sessionId: string) => Promise<void>;
|
|
92
|
+
}
|
|
93
|
+
export declare const useSessionList: () => UseSessionListResult;
|
package/dist/hooks.js
ADDED
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
import { useCallback, useEffect, useMemo, useState, useSyncExternalStore } from "react";
|
|
2
|
+
import { useAuthClient } from "./context.js";
|
|
3
|
+
import { ReactNativeAuthClientError } from "./errors.js";
|
|
4
|
+
/** Main facade (design.md §21.4's `useAuth`, matches §21.8's sample destructuring). */
|
|
5
|
+
export const useAuth = () => {
|
|
6
|
+
const client = useAuthClient();
|
|
7
|
+
const snapshot = useSyncExternalStore(client.subscribe, client.getSnapshot);
|
|
8
|
+
return useMemo(() => ({
|
|
9
|
+
snapshot,
|
|
10
|
+
isSignedIn: snapshot.status === "signed_in",
|
|
11
|
+
passkeySupported: snapshot.passkeySupported,
|
|
12
|
+
signInWithPasskey: () => client.signInWithPasskey(),
|
|
13
|
+
signInWithSocial: (input) => client.signInWithSocial(input),
|
|
14
|
+
sendEmailCode: (input) => client.sendEmailCode(input),
|
|
15
|
+
verifyEmailCode: (input) => client.verifyEmailCode(input),
|
|
16
|
+
getAccessToken: (input) => client.getAccessToken(input),
|
|
17
|
+
signOut: () => client.signOut(),
|
|
18
|
+
signOutAll: () => client.signOutAll(),
|
|
19
|
+
}), [client, snapshot]);
|
|
20
|
+
};
|
|
21
|
+
/** Session metadata (design.md §21.4's `useSession`), reloaded whenever sign-in status changes. */
|
|
22
|
+
export const useSession = () => {
|
|
23
|
+
const client = useAuthClient();
|
|
24
|
+
const snapshot = useSyncExternalStore(client.subscribe, client.getSnapshot);
|
|
25
|
+
const [session, setSession] = useState(null);
|
|
26
|
+
const [isLoading, setIsLoading] = useState(true);
|
|
27
|
+
const reload = useCallback(() => {
|
|
28
|
+
setIsLoading(true);
|
|
29
|
+
return client.getSession().then((next) => {
|
|
30
|
+
setSession(next);
|
|
31
|
+
setIsLoading(false);
|
|
32
|
+
return next;
|
|
33
|
+
});
|
|
34
|
+
}, [client]);
|
|
35
|
+
useEffect(() => {
|
|
36
|
+
void reload();
|
|
37
|
+
// Reload whenever the client's own sign-in status flips; `reload` is
|
|
38
|
+
// stable across renders for a given `client` (see its `useCallback`).
|
|
39
|
+
}, [reload, snapshot.status]);
|
|
40
|
+
return useMemo(() => ({ session, isLoading, reload }), [session, isLoading, reload]);
|
|
41
|
+
};
|
|
42
|
+
/** Signed-in user's profile (design.md §21.4's `useUser`); loads on sign-in, clears on sign-out. */
|
|
43
|
+
export const useUser = () => {
|
|
44
|
+
const client = useAuthClient();
|
|
45
|
+
const snapshot = useSyncExternalStore(client.subscribe, client.getSnapshot);
|
|
46
|
+
const [user, setUser] = useState(null);
|
|
47
|
+
const [isLoading, setIsLoading] = useState(false);
|
|
48
|
+
const [error, setError] = useState(null);
|
|
49
|
+
const reload = useCallback(() => {
|
|
50
|
+
setIsLoading(true);
|
|
51
|
+
setError(null);
|
|
52
|
+
return client.getMe().then((profile) => {
|
|
53
|
+
setUser(profile);
|
|
54
|
+
setIsLoading(false);
|
|
55
|
+
return profile;
|
|
56
|
+
}, (cause) => {
|
|
57
|
+
setIsLoading(false);
|
|
58
|
+
setUser(null);
|
|
59
|
+
if (cause instanceof ReactNativeAuthClientError)
|
|
60
|
+
setError(cause);
|
|
61
|
+
return null;
|
|
62
|
+
});
|
|
63
|
+
}, [client]);
|
|
64
|
+
useEffect(() => {
|
|
65
|
+
if (snapshot.status === "signed_in") {
|
|
66
|
+
void reload();
|
|
67
|
+
}
|
|
68
|
+
else {
|
|
69
|
+
setUser(null);
|
|
70
|
+
setError(null);
|
|
71
|
+
}
|
|
72
|
+
}, [snapshot.status, reload]);
|
|
73
|
+
const update = useCallback((input) => client.updateMe(input).then((profile) => {
|
|
74
|
+
setUser(profile);
|
|
75
|
+
return profile;
|
|
76
|
+
}), [client]);
|
|
77
|
+
return useMemo(() => ({ user, isLoading, error, reload, update }), [user, isLoading, error, reload, update]);
|
|
78
|
+
};
|
|
79
|
+
/** Passkey ceremonies + self-service management (design.md §21.4's `usePasskey`). */
|
|
80
|
+
export const usePasskey = () => {
|
|
81
|
+
const client = useAuthClient();
|
|
82
|
+
const snapshot = useSyncExternalStore(client.subscribe, client.getSnapshot);
|
|
83
|
+
const [passkeys, setPasskeys] = useState([]);
|
|
84
|
+
const [isLoading, setIsLoading] = useState(false);
|
|
85
|
+
const [error, setError] = useState(null);
|
|
86
|
+
const reload = useCallback(() => {
|
|
87
|
+
setIsLoading(true);
|
|
88
|
+
setError(null);
|
|
89
|
+
return client.listPasskeys().then((list) => {
|
|
90
|
+
setPasskeys(list);
|
|
91
|
+
setIsLoading(false);
|
|
92
|
+
return list;
|
|
93
|
+
}, (cause) => {
|
|
94
|
+
setIsLoading(false);
|
|
95
|
+
if (cause instanceof ReactNativeAuthClientError)
|
|
96
|
+
setError(cause);
|
|
97
|
+
return [];
|
|
98
|
+
});
|
|
99
|
+
}, [client]);
|
|
100
|
+
useEffect(() => {
|
|
101
|
+
if (snapshot.status === "signed_in") {
|
|
102
|
+
void reload();
|
|
103
|
+
}
|
|
104
|
+
else {
|
|
105
|
+
setPasskeys([]);
|
|
106
|
+
setError(null);
|
|
107
|
+
}
|
|
108
|
+
}, [snapshot.status, reload]);
|
|
109
|
+
const ceremony = useCallback((run) => {
|
|
110
|
+
setIsLoading(true);
|
|
111
|
+
return run
|
|
112
|
+
.then((value) => {
|
|
113
|
+
setError(null);
|
|
114
|
+
return value;
|
|
115
|
+
})
|
|
116
|
+
.catch((cause) => {
|
|
117
|
+
if (cause instanceof ReactNativeAuthClientError)
|
|
118
|
+
setError(cause);
|
|
119
|
+
throw cause;
|
|
120
|
+
})
|
|
121
|
+
.finally(() => setIsLoading(false));
|
|
122
|
+
}, []);
|
|
123
|
+
const register = useCallback((input) => ceremony(client.registerPasskey(input)).then((created) => {
|
|
124
|
+
setPasskeys((current) => [...current, created]);
|
|
125
|
+
return created;
|
|
126
|
+
}), [client, ceremony]);
|
|
127
|
+
const signIn = useCallback(() => ceremony(client.signInWithPasskey()), [client, ceremony]);
|
|
128
|
+
const remove = useCallback((passkeyId) => client.deletePasskey(passkeyId).then(() => {
|
|
129
|
+
setPasskeys((current) => current.filter((passkey) => passkey.passkeyId !== passkeyId));
|
|
130
|
+
}), [client]);
|
|
131
|
+
return useMemo(() => ({
|
|
132
|
+
passkeySupported: snapshot.passkeySupported,
|
|
133
|
+
passkeys,
|
|
134
|
+
isLoading,
|
|
135
|
+
error,
|
|
136
|
+
reload,
|
|
137
|
+
signIn,
|
|
138
|
+
register,
|
|
139
|
+
remove,
|
|
140
|
+
}), [snapshot.passkeySupported, passkeys, isLoading, error, reload, signIn, register, remove]);
|
|
141
|
+
};
|
|
142
|
+
/** Email OTP sign-in (design.md §21.4's `useEmailOtp`; backs `<EmailOtpForm/>`, design.md §21.4). */
|
|
143
|
+
export const useEmailOtp = () => {
|
|
144
|
+
const client = useAuthClient();
|
|
145
|
+
return useMemo(() => ({
|
|
146
|
+
sendCode: (email) => client.sendEmailCode({ email }),
|
|
147
|
+
verifyCode: (input) => client.verifyEmailCode(input),
|
|
148
|
+
}), [client]);
|
|
149
|
+
};
|
|
150
|
+
/** Social sign-in / account linking (design.md §21.4's `useSocialSignIn`; §20.6 system-browser flow). */
|
|
151
|
+
export const useSocialSignIn = () => {
|
|
152
|
+
const client = useAuthClient();
|
|
153
|
+
return useMemo(() => ({
|
|
154
|
+
signIn: (provider) => client.signInWithSocial({ provider }),
|
|
155
|
+
link: (provider) => client.linkSocialAccount({ provider }),
|
|
156
|
+
}), [client]);
|
|
157
|
+
};
|
|
158
|
+
export const useSessionList = () => {
|
|
159
|
+
const client = useAuthClient();
|
|
160
|
+
const snapshot = useSyncExternalStore(client.subscribe, client.getSnapshot);
|
|
161
|
+
const [sessions, setSessions] = useState([]);
|
|
162
|
+
const [isLoading, setIsLoading] = useState(false);
|
|
163
|
+
const [error, setError] = useState(null);
|
|
164
|
+
const reload = useCallback(() => {
|
|
165
|
+
setIsLoading(true);
|
|
166
|
+
setError(null);
|
|
167
|
+
return client.listSessions().then((list) => {
|
|
168
|
+
setSessions(list);
|
|
169
|
+
setIsLoading(false);
|
|
170
|
+
return list;
|
|
171
|
+
}, (cause) => {
|
|
172
|
+
setIsLoading(false);
|
|
173
|
+
if (cause instanceof ReactNativeAuthClientError)
|
|
174
|
+
setError(cause);
|
|
175
|
+
return [];
|
|
176
|
+
});
|
|
177
|
+
}, [client]);
|
|
178
|
+
useEffect(() => {
|
|
179
|
+
if (snapshot.status === "signed_in") {
|
|
180
|
+
void reload();
|
|
181
|
+
}
|
|
182
|
+
else {
|
|
183
|
+
setSessions([]);
|
|
184
|
+
setError(null);
|
|
185
|
+
}
|
|
186
|
+
}, [snapshot.status, reload]);
|
|
187
|
+
const revoke = useCallback((sessionId) => client.revokeSession(sessionId).then(() => {
|
|
188
|
+
setSessions((current) => current.filter((session) => session.sessionId !== sessionId));
|
|
189
|
+
}), [client]);
|
|
190
|
+
return useMemo(() => ({ sessions, isLoading, error, reload, revoke }), [sessions, isLoading, error, reload, revoke]);
|
|
191
|
+
};
|
package/dist/http.d.ts
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import type { Outcome } from "@smartcrab/contracts-public";
|
|
2
|
+
import type { OAuthErrorCode } from "@smartcrab/contracts-public";
|
|
3
|
+
import type { ReactNativeAuthError } from "./errors.js";
|
|
4
|
+
/**
|
|
5
|
+
* HTTP transport for the public authentication API (design.md §16.2) and the
|
|
6
|
+
* token endpoint (design.md §15.1).
|
|
7
|
+
*
|
|
8
|
+
* Exception boundaries are promise rejection handlers (`.then(onOk, onErr)`),
|
|
9
|
+
* never `try`/`catch` statements: `scripts/check-backend-error-style.ts`
|
|
10
|
+
* (design.md §5.2) scans this package and rejects direct try-catch. Success
|
|
11
|
+
* responses are always validated against a contracts-public zod schema — the
|
|
12
|
+
* wire is never trusted (IMPL_NOTES §1).
|
|
13
|
+
*/
|
|
14
|
+
/** Structural view of a zod schema's `safeParse` (this package has no direct zod dependency). */
|
|
15
|
+
export interface WireSchema<T> {
|
|
16
|
+
safeParse(input: unknown): {
|
|
17
|
+
success: true;
|
|
18
|
+
data: T;
|
|
19
|
+
} | {
|
|
20
|
+
success: false;
|
|
21
|
+
error: unknown;
|
|
22
|
+
};
|
|
23
|
+
}
|
|
24
|
+
export type FetchPort = (url: string, init: RequestInit) => Promise<Response>;
|
|
25
|
+
export type HttpMethod = "GET" | "POST" | "PATCH" | "DELETE";
|
|
26
|
+
export interface JsonRequest {
|
|
27
|
+
readonly method: HttpMethod;
|
|
28
|
+
readonly url: string;
|
|
29
|
+
readonly body?: unknown;
|
|
30
|
+
readonly accessToken?: string;
|
|
31
|
+
}
|
|
32
|
+
export declare const isOAuthErrorCode: (value: string) => value is OAuthErrorCode;
|
|
33
|
+
/**
|
|
34
|
+
* Executes one JSON request and validates the response against `schema`.
|
|
35
|
+
* Error precedence on non-2xx: 429 -> `rate_limited`; a valid Problem
|
|
36
|
+
* Details body -> `problem_details`; a valid OAuth error body ->
|
|
37
|
+
* `oauth_error`; anything else -> `invalid_response`.
|
|
38
|
+
*/
|
|
39
|
+
export declare const requestJson: <T>(fetchPort: FetchPort, request: JsonRequest, schema: WireSchema<T>) => Promise<Outcome<T, ReactNativeAuthError>>;
|
|
40
|
+
/** Builds `base + path` (all routes this SDK calls take no query string). */
|
|
41
|
+
export declare const buildUrl: (baseUrl: string, path: string) => string;
|