@smartcrab/react 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/dist/context.d.ts +20 -0
- package/dist/context.js +12 -0
- package/dist/headless.d.ts +73 -0
- package/dist/headless.js +72 -0
- package/dist/hooks.d.ts +108 -0
- package/dist/hooks.js +143 -0
- package/dist/index.d.ts +33 -0
- package/dist/index.js +26 -0
- package/dist/provider.d.ts +15 -0
- package/dist/provider.js +16 -0
- package/dist/sessions-controller.d.ts +33 -0
- package/dist/sessions-controller.js +73 -0
- package/dist/sign-in-flow.d.ts +91 -0
- package/dist/sign-in-flow.js +193 -0
- package/dist/user-controller.d.ts +24 -0
- package/dist/user-controller.js +67 -0
- package/package.json +46 -0
- package/src/context.ts +32 -0
- package/src/headless.tsx +172 -0
- package/src/hooks.ts +267 -0
- package/src/index.test.ts +60 -0
- package/src/index.ts +79 -0
- package/src/provider.tsx +35 -0
- package/src/sessions-controller.test.ts +107 -0
- package/src/sessions-controller.ts +120 -0
- package/src/sign-in-flow.test.ts +271 -0
- package/src/sign-in-flow.ts +341 -0
- package/src/user-controller.test.ts +112 -0
- package/src/user-controller.ts +106 -0
package/dist/index.js
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `@smartcrab/react` — the web React SDK (design.md §3.1 client matrix,
|
|
3
|
+
* §21.4 hook list), implemented over `@smartcrab/browser`.
|
|
4
|
+
*
|
|
5
|
+
* - `<AuthProvider client={...}>` plus hooks: `useAuth`, `useUser`,
|
|
6
|
+
* `useSession`, `usePasskey`, `useEmailOtp`, `useSocialSignIn`.
|
|
7
|
+
* - Headless, unstyled components (`PasskeyButton`, `EmailOtpForm`,
|
|
8
|
+
* `SocialButtons`): behavior-only render-prop components for fully custom
|
|
9
|
+
* UIs — distinct from `@smartcrab/ui-web`'s styled hosted-login kit.
|
|
10
|
+
* - All behavior lives in React-free controllers (`createSignInFlow`,
|
|
11
|
+
* `createUserProfileController`, `createSessionListController`); the hooks
|
|
12
|
+
* are thin `useSyncExternalStore` bindings over them.
|
|
13
|
+
*
|
|
14
|
+
* Testing constraint (documented per assignment): `react-dom` /
|
|
15
|
+
* `react-test-renderer` are intentionally not dependencies of this package,
|
|
16
|
+
* so no renderer exists in tests. Tests exercise the controllers and store
|
|
17
|
+
* semantics directly; the hook layer is a type-checked binding over that
|
|
18
|
+
* tested logic.
|
|
19
|
+
*/
|
|
20
|
+
export { AuthProvider } from "./provider.js";
|
|
21
|
+
export { AuthContext, useAuthContextValue } from "./context.js";
|
|
22
|
+
export { useAuth, useAuthClient, useAuthState, useEmailOtp, usePasskey, useSession, useSocialSignIn, useUser, } from "./hooks.js";
|
|
23
|
+
export { createSignInFlow } from "./sign-in-flow.js";
|
|
24
|
+
export { createUserProfileController } from "./user-controller.js";
|
|
25
|
+
export { createSessionListController } from "./sessions-controller.js";
|
|
26
|
+
export { EmailOtpForm, PasskeyButton, SocialButtons } from "./headless.js";
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import type { BrowserAuthClient } from "@smartcrab/browser";
|
|
2
|
+
import type { ReactNode } from "react";
|
|
3
|
+
/**
|
|
4
|
+
* `<AuthProvider client={...}>` (design.md §21.4).
|
|
5
|
+
*
|
|
6
|
+
* Creates the headless controllers (sign-in flow, profile, session list)
|
|
7
|
+
* once per client instance and shares them with every hook. All state is
|
|
8
|
+
* auth-state-driven; nothing here touches Web Storage — token rules live in
|
|
9
|
+
* `@smartcrab/browser` (design.md §22.3).
|
|
10
|
+
*/
|
|
11
|
+
export interface AuthProviderProps {
|
|
12
|
+
readonly client: BrowserAuthClient;
|
|
13
|
+
readonly children?: ReactNode;
|
|
14
|
+
}
|
|
15
|
+
export declare const AuthProvider: ({ client, children }: AuthProviderProps) => ReactNode;
|
package/dist/provider.js
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { jsx as _jsx } from "react/jsx-runtime";
|
|
2
|
+
import { useMemo } from "react";
|
|
3
|
+
import { AuthContext } from "./context.js";
|
|
4
|
+
import { createSignInFlow } from "./sign-in-flow.js";
|
|
5
|
+
import { createSessionListController } from "./sessions-controller.js";
|
|
6
|
+
import { createUserProfileController } from "./user-controller.js";
|
|
7
|
+
export const AuthProvider = ({ client, children }) => {
|
|
8
|
+
const value = useMemo(() => ({
|
|
9
|
+
client,
|
|
10
|
+
flow: createSignInFlow(client),
|
|
11
|
+
userProfile: createUserProfileController(client),
|
|
12
|
+
sessionList: createSessionListController(client),
|
|
13
|
+
}), [client]);
|
|
14
|
+
// React 19 convention: the context object itself is the provider.
|
|
15
|
+
return _jsx(AuthContext, { value: value, children: children });
|
|
16
|
+
};
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import type { BrowserAuthClient, BrowserAuthError, MeSessionSummary, Outcome } from "@smartcrab/browser";
|
|
2
|
+
/**
|
|
3
|
+
* Headless controller for the `/v1/me/sessions` surface (design.md §16.2,
|
|
4
|
+
* §24). React-free so it is unit-testable without a renderer; `useSession`
|
|
5
|
+
* binds it.
|
|
6
|
+
*/
|
|
7
|
+
export type SessionListStatus = "idle" | "loading" | "loaded" | "error";
|
|
8
|
+
export interface SessionListSnapshot {
|
|
9
|
+
readonly status: SessionListStatus;
|
|
10
|
+
readonly sessions: readonly MeSessionSummary[] | null;
|
|
11
|
+
readonly error: BrowserAuthError | null;
|
|
12
|
+
}
|
|
13
|
+
export type SessionListListener = (snapshot: SessionListSnapshot) => void;
|
|
14
|
+
export type SessionListClient = Pick<BrowserAuthClient, "listMySessions" | "revokeMySession" | "revokeAllMySessions">;
|
|
15
|
+
export interface SessionListController {
|
|
16
|
+
getSnapshot(): SessionListSnapshot;
|
|
17
|
+
subscribe(listener: SessionListListener): () => void;
|
|
18
|
+
load(): Promise<Outcome<readonly MeSessionSummary[], BrowserAuthError>>;
|
|
19
|
+
/** Revokes one session and drops it from the cached list (design.md §24). */
|
|
20
|
+
revoke(sessionId: string): Promise<Outcome<{
|
|
21
|
+
revoked: true;
|
|
22
|
+
}, BrowserAuthError>>;
|
|
23
|
+
/**
|
|
24
|
+
* Revokes ALL sessions including the current one (design.md §24.3). The
|
|
25
|
+
* local list resets to `idle`; the client's own tokens die server-side with
|
|
26
|
+
* the current session.
|
|
27
|
+
*/
|
|
28
|
+
revokeAll(): Promise<Outcome<{
|
|
29
|
+
revoked: true;
|
|
30
|
+
}, BrowserAuthError>>;
|
|
31
|
+
clear(): void;
|
|
32
|
+
}
|
|
33
|
+
export declare const createSessionListController: (client: SessionListClient) => SessionListController;
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
import { err, ok } from "@smartcrab/browser";
|
|
2
|
+
const IDLE = { status: "idle", sessions: null, error: null };
|
|
3
|
+
export const createSessionListController = (client) => {
|
|
4
|
+
let snapshot = IDLE;
|
|
5
|
+
const listeners = new Set();
|
|
6
|
+
let inflight = null;
|
|
7
|
+
const transition = (next) => {
|
|
8
|
+
snapshot = next;
|
|
9
|
+
for (const listener of listeners) {
|
|
10
|
+
listener(snapshot);
|
|
11
|
+
}
|
|
12
|
+
};
|
|
13
|
+
const load = () => {
|
|
14
|
+
if (inflight !== null)
|
|
15
|
+
return inflight;
|
|
16
|
+
const pending = (async () => {
|
|
17
|
+
transition({ status: "loading", sessions: snapshot.sessions, error: null });
|
|
18
|
+
const outcome = await client.listMySessions();
|
|
19
|
+
if (!outcome.ok) {
|
|
20
|
+
if (outcome.error.type === "not_authenticated") {
|
|
21
|
+
transition(IDLE);
|
|
22
|
+
}
|
|
23
|
+
else {
|
|
24
|
+
transition({ status: "error", sessions: snapshot.sessions, error: outcome.error });
|
|
25
|
+
}
|
|
26
|
+
return outcome;
|
|
27
|
+
}
|
|
28
|
+
transition({ status: "loaded", sessions: outcome.value.sessions, error: null });
|
|
29
|
+
return ok(outcome.value.sessions);
|
|
30
|
+
})();
|
|
31
|
+
inflight = pending;
|
|
32
|
+
const clearInflight = () => {
|
|
33
|
+
if (inflight === pending)
|
|
34
|
+
inflight = null;
|
|
35
|
+
};
|
|
36
|
+
void pending.then(clearInflight, clearInflight);
|
|
37
|
+
return pending;
|
|
38
|
+
};
|
|
39
|
+
const revoke = async (sessionId) => {
|
|
40
|
+
const outcome = await client.revokeMySession(sessionId);
|
|
41
|
+
if (!outcome.ok)
|
|
42
|
+
return err(outcome.error);
|
|
43
|
+
const current = snapshot.sessions;
|
|
44
|
+
if (current !== null) {
|
|
45
|
+
transition({
|
|
46
|
+
...snapshot,
|
|
47
|
+
sessions: current.filter((session) => session.session_id !== sessionId),
|
|
48
|
+
});
|
|
49
|
+
}
|
|
50
|
+
return ok({ revoked: true });
|
|
51
|
+
};
|
|
52
|
+
const revokeAll = async () => {
|
|
53
|
+
const outcome = await client.revokeAllMySessions();
|
|
54
|
+
if (!outcome.ok)
|
|
55
|
+
return err(outcome.error);
|
|
56
|
+
transition(IDLE);
|
|
57
|
+
return ok({ revoked: true });
|
|
58
|
+
};
|
|
59
|
+
const clear = () => {
|
|
60
|
+
transition(IDLE);
|
|
61
|
+
};
|
|
62
|
+
return {
|
|
63
|
+
getSnapshot: () => snapshot,
|
|
64
|
+
subscribe: (listener) => {
|
|
65
|
+
listeners.add(listener);
|
|
66
|
+
return () => listeners.delete(listener);
|
|
67
|
+
},
|
|
68
|
+
load,
|
|
69
|
+
revoke,
|
|
70
|
+
revokeAll,
|
|
71
|
+
clear,
|
|
72
|
+
};
|
|
73
|
+
};
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
import type { AuthenticatedSession, BrowserAuthClient, BrowserAuthError, BrowserTransaction, Outcome, SocialProvider } from "@smartcrab/browser";
|
|
2
|
+
/**
|
|
3
|
+
* Headless sign-in state machine over the transaction API (design.md §16),
|
|
4
|
+
* shared by every React hook/headless component in this package.
|
|
5
|
+
*
|
|
6
|
+
* It is deliberately React-free: the hooks bind `subscribe`/`getSnapshot`
|
|
7
|
+
* with `useSyncExternalStore`, and the machine itself stays unit-testable
|
|
8
|
+
* without a renderer (react-dom is intentionally not a dependency here).
|
|
9
|
+
*
|
|
10
|
+
* Flow: idle → starting → awaiting_method → (email_challenge_sent |
|
|
11
|
+
* ceremony) → completing → signed_in. Any step can land in `failed`;
|
|
12
|
+
* `reset()` returns to `idle`. Social sign-in leaves the page via top-level
|
|
13
|
+
* redirect (design.md §22.3), so it has no terminal state here — after the
|
|
14
|
+
* redirect back, the app calls `client.handleHostedAuthorizationCallback`.
|
|
15
|
+
*/
|
|
16
|
+
export type SignInFlowState = {
|
|
17
|
+
readonly step: "idle";
|
|
18
|
+
} | {
|
|
19
|
+
readonly step: "starting";
|
|
20
|
+
} | {
|
|
21
|
+
readonly step: "awaiting_method";
|
|
22
|
+
readonly transactionId: string;
|
|
23
|
+
readonly methods: BrowserTransaction["availableMethods"];
|
|
24
|
+
readonly expiresAt: string;
|
|
25
|
+
} | {
|
|
26
|
+
readonly step: "email_challenge_sent";
|
|
27
|
+
readonly transactionId: string;
|
|
28
|
+
readonly challengeId: string;
|
|
29
|
+
readonly email: string;
|
|
30
|
+
readonly challengeExpiresAt: string;
|
|
31
|
+
} | {
|
|
32
|
+
readonly step: "ceremony";
|
|
33
|
+
readonly transactionId: string;
|
|
34
|
+
readonly ceremony: "passkey_registration" | "passkey_authentication";
|
|
35
|
+
} | {
|
|
36
|
+
readonly step: "completing";
|
|
37
|
+
readonly transactionId: string;
|
|
38
|
+
} | {
|
|
39
|
+
readonly step: "signed_in";
|
|
40
|
+
readonly session: AuthenticatedSession;
|
|
41
|
+
} | {
|
|
42
|
+
readonly step: "failed";
|
|
43
|
+
readonly error: BrowserAuthError;
|
|
44
|
+
};
|
|
45
|
+
export type PendingAction = "begin" | "send_email" | "resend_email" | "verify_email" | "passkey" | "social" | "cancel" | null;
|
|
46
|
+
/** useSyncExternalStore-compatible snapshot: referentially stable between emissions. */
|
|
47
|
+
export interface SignInFlowSnapshot {
|
|
48
|
+
readonly state: SignInFlowState;
|
|
49
|
+
readonly pendingAction: PendingAction;
|
|
50
|
+
}
|
|
51
|
+
/** A flow misuse (e.g. `verifyEmailCode` before any challenge was sent) — a caller bug, not a wire error. */
|
|
52
|
+
export interface InvalidFlowStateError {
|
|
53
|
+
readonly type: "invalid_flow_state";
|
|
54
|
+
readonly expected: string;
|
|
55
|
+
readonly actual: string;
|
|
56
|
+
}
|
|
57
|
+
export type SignInFlowError = BrowserAuthError | InvalidFlowStateError;
|
|
58
|
+
export type SignInFlowListener = (snapshot: SignInFlowSnapshot) => void;
|
|
59
|
+
/** The narrow slice of the browser client the flow drives (structural, so tests inject a fake). */
|
|
60
|
+
export type SignInFlowClient = Pick<BrowserAuthClient, "createTransaction" | "cancelTransaction" | "startEmailOtp" | "resendEmailOtp" | "verifyEmailOtp" | "startPasskeyRegistration" | "startPasskeyAuthentication" | "startSocialSignIn" | "completeTransaction" | "exchangeAuthorizationCode">;
|
|
61
|
+
export interface SignInFlow {
|
|
62
|
+
getSnapshot(): SignInFlowSnapshot;
|
|
63
|
+
subscribe(listener: SignInFlowListener): () => void;
|
|
64
|
+
/** Creates the transaction and moves to `awaiting_method`. */
|
|
65
|
+
begin(): Promise<Outcome<BrowserTransaction, SignInFlowError>>;
|
|
66
|
+
sendEmailCode(email: string): Promise<Outcome<{
|
|
67
|
+
challengeId: string;
|
|
68
|
+
}, SignInFlowError>>;
|
|
69
|
+
resendEmailCode(): Promise<Outcome<{
|
|
70
|
+
challengeId: string;
|
|
71
|
+
}, SignInFlowError>>;
|
|
72
|
+
/** Verifies the code, then completes the transaction and exchanges the code. */
|
|
73
|
+
verifyEmailCode(code: string): Promise<Outcome<AuthenticatedSession, SignInFlowError>>;
|
|
74
|
+
/** Discoverable-credential passkey sign-in ceremony (design.md §17.2). */
|
|
75
|
+
signInWithPasskey(): Promise<Outcome<AuthenticatedSession, SignInFlowError>>;
|
|
76
|
+
/** Passkey registration ceremony during sign-up (design.md §17.1). */
|
|
77
|
+
registerPasskey(input?: {
|
|
78
|
+
readonly name?: string;
|
|
79
|
+
}): Promise<Outcome<AuthenticatedSession, SignInFlowError>>;
|
|
80
|
+
/** Starts social sign-in; performs a top-level redirect on success. */
|
|
81
|
+
signInWithSocial(provider: SocialProvider): Promise<Outcome<{
|
|
82
|
+
redirected: true;
|
|
83
|
+
}, SignInFlowError>>;
|
|
84
|
+
/** Best-effort server-side cancel, then back to `idle`. */
|
|
85
|
+
cancel(): Promise<Outcome<{
|
|
86
|
+
cancelled: true;
|
|
87
|
+
}, SignInFlowError>>;
|
|
88
|
+
/** Local-only reset (no server call). */
|
|
89
|
+
reset(): void;
|
|
90
|
+
}
|
|
91
|
+
export declare const createSignInFlow: (client: SignInFlowClient) => SignInFlow;
|
|
@@ -0,0 +1,193 @@
|
|
|
1
|
+
import { err, ok } from "@smartcrab/browser";
|
|
2
|
+
const invalidState = (expected, actual) => err({ type: "invalid_flow_state", expected, actual });
|
|
3
|
+
export const createSignInFlow = (client) => {
|
|
4
|
+
let snapshot = { state: { step: "idle" }, pendingAction: null };
|
|
5
|
+
const listeners = new Set();
|
|
6
|
+
const transition = (state, pendingAction = null) => {
|
|
7
|
+
snapshot = { state, pendingAction };
|
|
8
|
+
for (const listener of listeners) {
|
|
9
|
+
listener(snapshot);
|
|
10
|
+
}
|
|
11
|
+
};
|
|
12
|
+
const fail = (error) => {
|
|
13
|
+
transition({ step: "failed", error });
|
|
14
|
+
};
|
|
15
|
+
/** complete → exchange, shared by every verify path (design.md §16.3). */
|
|
16
|
+
const finalize = async (transactionId) => {
|
|
17
|
+
transition({ step: "completing", transactionId });
|
|
18
|
+
const completed = await client.completeTransaction(transactionId);
|
|
19
|
+
if (!completed.ok) {
|
|
20
|
+
fail(completed.error);
|
|
21
|
+
return completed;
|
|
22
|
+
}
|
|
23
|
+
const exchanged = await client.exchangeAuthorizationCode({
|
|
24
|
+
code: completed.value.authorization_code,
|
|
25
|
+
state: completed.value.state,
|
|
26
|
+
});
|
|
27
|
+
if (!exchanged.ok) {
|
|
28
|
+
fail(exchanged.error);
|
|
29
|
+
return exchanged;
|
|
30
|
+
}
|
|
31
|
+
transition({ step: "signed_in", session: exchanged.value });
|
|
32
|
+
return ok(exchanged.value);
|
|
33
|
+
};
|
|
34
|
+
const begin = async () => {
|
|
35
|
+
const { step } = snapshot.state;
|
|
36
|
+
if (step !== "idle" && step !== "failed") {
|
|
37
|
+
return invalidState("idle|failed", step);
|
|
38
|
+
}
|
|
39
|
+
transition({ step: "starting" }, "begin");
|
|
40
|
+
const outcome = await client.createTransaction();
|
|
41
|
+
if (!outcome.ok) {
|
|
42
|
+
fail(outcome.error);
|
|
43
|
+
return outcome;
|
|
44
|
+
}
|
|
45
|
+
transition({
|
|
46
|
+
step: "awaiting_method",
|
|
47
|
+
transactionId: outcome.value.transactionId,
|
|
48
|
+
methods: outcome.value.availableMethods,
|
|
49
|
+
expiresAt: outcome.value.expiresAt,
|
|
50
|
+
});
|
|
51
|
+
return outcome;
|
|
52
|
+
};
|
|
53
|
+
const sendEmailCode = async (email) => {
|
|
54
|
+
const state = snapshot.state;
|
|
55
|
+
if (state.step !== "awaiting_method") {
|
|
56
|
+
return invalidState("awaiting_method", state.step);
|
|
57
|
+
}
|
|
58
|
+
transition(state, "send_email");
|
|
59
|
+
const outcome = await client.startEmailOtp(state.transactionId, { email });
|
|
60
|
+
if (!outcome.ok) {
|
|
61
|
+
fail(outcome.error);
|
|
62
|
+
return outcome;
|
|
63
|
+
}
|
|
64
|
+
transition({
|
|
65
|
+
step: "email_challenge_sent",
|
|
66
|
+
transactionId: state.transactionId,
|
|
67
|
+
challengeId: outcome.value.challenge_id,
|
|
68
|
+
email,
|
|
69
|
+
challengeExpiresAt: outcome.value.expires_at,
|
|
70
|
+
});
|
|
71
|
+
return ok({ challengeId: outcome.value.challenge_id });
|
|
72
|
+
};
|
|
73
|
+
const resendEmailCode = async () => {
|
|
74
|
+
const state = snapshot.state;
|
|
75
|
+
if (state.step !== "email_challenge_sent") {
|
|
76
|
+
return invalidState("email_challenge_sent", state.step);
|
|
77
|
+
}
|
|
78
|
+
transition(state, "resend_email");
|
|
79
|
+
const outcome = await client.resendEmailOtp(state.transactionId, {
|
|
80
|
+
challenge_id: state.challengeId,
|
|
81
|
+
});
|
|
82
|
+
if (!outcome.ok) {
|
|
83
|
+
fail(outcome.error);
|
|
84
|
+
return outcome;
|
|
85
|
+
}
|
|
86
|
+
// design.md §18.2: resend invalidates the prior code — adopt the new challenge.
|
|
87
|
+
transition({
|
|
88
|
+
...state,
|
|
89
|
+
challengeId: outcome.value.challenge_id,
|
|
90
|
+
challengeExpiresAt: outcome.value.expires_at,
|
|
91
|
+
});
|
|
92
|
+
return ok({ challengeId: outcome.value.challenge_id });
|
|
93
|
+
};
|
|
94
|
+
const verifyEmailCode = async (code) => {
|
|
95
|
+
const state = snapshot.state;
|
|
96
|
+
if (state.step !== "email_challenge_sent") {
|
|
97
|
+
return invalidState("email_challenge_sent", state.step);
|
|
98
|
+
}
|
|
99
|
+
transition(state, "verify_email");
|
|
100
|
+
const outcome = await client.verifyEmailOtp(state.transactionId, {
|
|
101
|
+
challenge_id: state.challengeId,
|
|
102
|
+
code,
|
|
103
|
+
});
|
|
104
|
+
if (!outcome.ok) {
|
|
105
|
+
fail(outcome.error);
|
|
106
|
+
return outcome;
|
|
107
|
+
}
|
|
108
|
+
return finalize(state.transactionId);
|
|
109
|
+
};
|
|
110
|
+
const signInWithPasskey = async () => {
|
|
111
|
+
const state = snapshot.state;
|
|
112
|
+
if (state.step !== "awaiting_method") {
|
|
113
|
+
return invalidState("awaiting_method", state.step);
|
|
114
|
+
}
|
|
115
|
+
transition({ step: "ceremony", transactionId: state.transactionId, ceremony: "passkey_authentication" }, "passkey");
|
|
116
|
+
const outcome = await client.startPasskeyAuthentication(state.transactionId);
|
|
117
|
+
if (!outcome.ok) {
|
|
118
|
+
fail(outcome.error);
|
|
119
|
+
return outcome;
|
|
120
|
+
}
|
|
121
|
+
return finalize(state.transactionId);
|
|
122
|
+
};
|
|
123
|
+
const registerPasskey = async (input) => {
|
|
124
|
+
const state = snapshot.state;
|
|
125
|
+
if (state.step !== "awaiting_method") {
|
|
126
|
+
return invalidState("awaiting_method", state.step);
|
|
127
|
+
}
|
|
128
|
+
transition({ step: "ceremony", transactionId: state.transactionId, ceremony: "passkey_registration" }, "passkey");
|
|
129
|
+
const outcome = await client.startPasskeyRegistration(state.transactionId, input ?? {});
|
|
130
|
+
if (!outcome.ok) {
|
|
131
|
+
fail(outcome.error);
|
|
132
|
+
return outcome;
|
|
133
|
+
}
|
|
134
|
+
return finalize(state.transactionId);
|
|
135
|
+
};
|
|
136
|
+
const signInWithSocial = async (provider) => {
|
|
137
|
+
const state = snapshot.state;
|
|
138
|
+
if (state.step !== "awaiting_method") {
|
|
139
|
+
return invalidState("awaiting_method", state.step);
|
|
140
|
+
}
|
|
141
|
+
transition(state, "social");
|
|
142
|
+
const outcome = await client.startSocialSignIn(state.transactionId, provider);
|
|
143
|
+
if (!outcome.ok) {
|
|
144
|
+
fail(outcome.error);
|
|
145
|
+
return outcome;
|
|
146
|
+
}
|
|
147
|
+
// Success = the browser is navigating away (top-level redirect). The flow
|
|
148
|
+
// intentionally stays in `awaiting_method`: on the redirect back the page
|
|
149
|
+
// reloads and a fresh flow instance takes over.
|
|
150
|
+
transition(state);
|
|
151
|
+
return ok({ redirected: true });
|
|
152
|
+
};
|
|
153
|
+
const cancel = async () => {
|
|
154
|
+
const state = snapshot.state;
|
|
155
|
+
const transactionId = state.step === "awaiting_method" ||
|
|
156
|
+
state.step === "email_challenge_sent" ||
|
|
157
|
+
state.step === "ceremony" ||
|
|
158
|
+
state.step === "completing"
|
|
159
|
+
? state.transactionId
|
|
160
|
+
: null;
|
|
161
|
+
if (transactionId === null) {
|
|
162
|
+
transition({ step: "idle" });
|
|
163
|
+
return ok({ cancelled: true });
|
|
164
|
+
}
|
|
165
|
+
transition(state, "cancel");
|
|
166
|
+
const outcome = await client.cancelTransaction(transactionId);
|
|
167
|
+
if (!outcome.ok) {
|
|
168
|
+
fail(outcome.error);
|
|
169
|
+
return outcome;
|
|
170
|
+
}
|
|
171
|
+
transition({ step: "idle" });
|
|
172
|
+
return ok({ cancelled: true });
|
|
173
|
+
};
|
|
174
|
+
const reset = () => {
|
|
175
|
+
transition({ step: "idle" });
|
|
176
|
+
};
|
|
177
|
+
return {
|
|
178
|
+
getSnapshot: () => snapshot,
|
|
179
|
+
subscribe: (listener) => {
|
|
180
|
+
listeners.add(listener);
|
|
181
|
+
return () => listeners.delete(listener);
|
|
182
|
+
},
|
|
183
|
+
begin,
|
|
184
|
+
sendEmailCode,
|
|
185
|
+
resendEmailCode,
|
|
186
|
+
verifyEmailCode,
|
|
187
|
+
signInWithPasskey,
|
|
188
|
+
registerPasskey,
|
|
189
|
+
signInWithSocial,
|
|
190
|
+
cancel,
|
|
191
|
+
reset,
|
|
192
|
+
};
|
|
193
|
+
};
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import type { BrowserAuthClient, BrowserAuthError, MeUpdateRequest, MeUser, Outcome } from "@smartcrab/browser";
|
|
2
|
+
/**
|
|
3
|
+
* Headless controller for the `/v1/me` profile surface (design.md §16.2).
|
|
4
|
+
* React-free so it is unit-testable without a renderer; `useUser` binds it.
|
|
5
|
+
*/
|
|
6
|
+
export type UserProfileStatus = "idle" | "loading" | "loaded" | "error";
|
|
7
|
+
export interface UserProfileSnapshot {
|
|
8
|
+
readonly status: UserProfileStatus;
|
|
9
|
+
readonly user: MeUser | null;
|
|
10
|
+
readonly error: BrowserAuthError | null;
|
|
11
|
+
}
|
|
12
|
+
export type UserProfileListener = (snapshot: UserProfileSnapshot) => void;
|
|
13
|
+
export type UserProfileClient = Pick<BrowserAuthClient, "getMe" | "updateMe">;
|
|
14
|
+
export interface UserProfileController {
|
|
15
|
+
getSnapshot(): UserProfileSnapshot;
|
|
16
|
+
subscribe(listener: UserProfileListener): () => void;
|
|
17
|
+
/** (Re)loads the profile. A `not_authenticated` result resets to `idle`, not `error`. */
|
|
18
|
+
load(): Promise<Outcome<MeUser, BrowserAuthError>>;
|
|
19
|
+
/** Applies a profile patch (design.md §12.1: email changes go through the OTP flow, never here). */
|
|
20
|
+
update(patch: MeUpdateRequest): Promise<Outcome<MeUser, BrowserAuthError>>;
|
|
21
|
+
/** Drops the cached profile (e.g. on sign-out). */
|
|
22
|
+
clear(): void;
|
|
23
|
+
}
|
|
24
|
+
export declare const createUserProfileController: (client: UserProfileClient) => UserProfileController;
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
import { err, ok } from "@smartcrab/browser";
|
|
2
|
+
const IDLE = { status: "idle", user: null, error: null };
|
|
3
|
+
export const createUserProfileController = (client) => {
|
|
4
|
+
let snapshot = IDLE;
|
|
5
|
+
const listeners = new Set();
|
|
6
|
+
// Concurrent load() calls share one in-flight request, mirroring the
|
|
7
|
+
// client's own refresh dedupe (design.md §21.7).
|
|
8
|
+
let inflight = null;
|
|
9
|
+
const transition = (next) => {
|
|
10
|
+
snapshot = next;
|
|
11
|
+
for (const listener of listeners) {
|
|
12
|
+
listener(snapshot);
|
|
13
|
+
}
|
|
14
|
+
};
|
|
15
|
+
const load = () => {
|
|
16
|
+
if (inflight !== null)
|
|
17
|
+
return inflight;
|
|
18
|
+
const pending = (async () => {
|
|
19
|
+
transition({ status: "loading", user: snapshot.user, error: null });
|
|
20
|
+
const outcome = await client.getMe();
|
|
21
|
+
if (!outcome.ok) {
|
|
22
|
+
if (outcome.error.type === "not_authenticated") {
|
|
23
|
+
transition(IDLE);
|
|
24
|
+
}
|
|
25
|
+
else {
|
|
26
|
+
transition({ status: "error", user: snapshot.user, error: outcome.error });
|
|
27
|
+
}
|
|
28
|
+
return outcome;
|
|
29
|
+
}
|
|
30
|
+
transition({ status: "loaded", user: outcome.value, error: null });
|
|
31
|
+
return ok(outcome.value);
|
|
32
|
+
})();
|
|
33
|
+
inflight = pending;
|
|
34
|
+
const clearInflight = () => {
|
|
35
|
+
if (inflight === pending)
|
|
36
|
+
inflight = null;
|
|
37
|
+
};
|
|
38
|
+
void pending.then(clearInflight, clearInflight);
|
|
39
|
+
return pending;
|
|
40
|
+
};
|
|
41
|
+
const update = async (patch) => {
|
|
42
|
+
const outcome = await client.updateMe(patch);
|
|
43
|
+
if (!outcome.ok) {
|
|
44
|
+
if (outcome.error.type === "not_authenticated") {
|
|
45
|
+
transition(IDLE);
|
|
46
|
+
return outcome;
|
|
47
|
+
}
|
|
48
|
+
transition({ status: "error", user: snapshot.user, error: outcome.error });
|
|
49
|
+
return err(outcome.error);
|
|
50
|
+
}
|
|
51
|
+
transition({ status: "loaded", user: outcome.value, error: null });
|
|
52
|
+
return ok(outcome.value);
|
|
53
|
+
};
|
|
54
|
+
const clear = () => {
|
|
55
|
+
transition(IDLE);
|
|
56
|
+
};
|
|
57
|
+
return {
|
|
58
|
+
getSnapshot: () => snapshot,
|
|
59
|
+
subscribe: (listener) => {
|
|
60
|
+
listeners.add(listener);
|
|
61
|
+
return () => listeners.delete(listener);
|
|
62
|
+
},
|
|
63
|
+
load,
|
|
64
|
+
update,
|
|
65
|
+
clear,
|
|
66
|
+
};
|
|
67
|
+
};
|
package/package.json
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@smartcrab/react",
|
|
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
|
+
"./*": {
|
|
16
|
+
"types": "./src/*.ts",
|
|
17
|
+
"development": "./src/*.ts",
|
|
18
|
+
"import": "./dist/*.js",
|
|
19
|
+
"default": "./dist/*.js"
|
|
20
|
+
}
|
|
21
|
+
},
|
|
22
|
+
"files": [
|
|
23
|
+
"dist",
|
|
24
|
+
"src"
|
|
25
|
+
],
|
|
26
|
+
"publishConfig": {
|
|
27
|
+
"access": "public"
|
|
28
|
+
},
|
|
29
|
+
"dependencies": {
|
|
30
|
+
"@smartcrab/browser": "0.1.0"
|
|
31
|
+
},
|
|
32
|
+
"peerDependencies": {
|
|
33
|
+
"react": ">=19"
|
|
34
|
+
},
|
|
35
|
+
"devDependencies": {
|
|
36
|
+
"typescript": "5.9.3",
|
|
37
|
+
"vitest": "4.1.11",
|
|
38
|
+
"@types/react": "19.2.18",
|
|
39
|
+
"react": "19.2.8"
|
|
40
|
+
},
|
|
41
|
+
"scripts": {
|
|
42
|
+
"typecheck": "tsc --noEmit",
|
|
43
|
+
"test": "vitest run --passWithNoTests",
|
|
44
|
+
"build": "tsc -p tsconfig.build.json"
|
|
45
|
+
}
|
|
46
|
+
}
|
package/src/context.ts
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import type { BrowserAuthClient } from "@smartcrab/browser";
|
|
2
|
+
import { createContext, useContext } from "react";
|
|
3
|
+
import type { SignInFlow } from "./sign-in-flow.js";
|
|
4
|
+
import type { SessionListController } from "./sessions-controller.js";
|
|
5
|
+
import type { UserProfileController } from "./user-controller.js";
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Dependency context for the web React SDK (design.md §3.1, §21.4).
|
|
9
|
+
*
|
|
10
|
+
* One `AuthProvider` per client; all hooks/headless components consume this.
|
|
11
|
+
* The controllers are created once per client by the provider so that hook
|
|
12
|
+
* state survives re-renders but is rebuilt on client swap.
|
|
13
|
+
*/
|
|
14
|
+
export interface AuthContextValue {
|
|
15
|
+
readonly client: BrowserAuthClient;
|
|
16
|
+
readonly flow: SignInFlow;
|
|
17
|
+
readonly userProfile: UserProfileController;
|
|
18
|
+
readonly sessionList: SessionListController;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export const AuthContext = createContext<AuthContextValue | null>(null);
|
|
22
|
+
|
|
23
|
+
/** Internal: every public hook resolves its dependencies through here. */
|
|
24
|
+
export const useAuthContextValue = (): AuthContextValue => {
|
|
25
|
+
const value = useContext(AuthContext);
|
|
26
|
+
if (value === null) {
|
|
27
|
+
// Programmer error (missing <AuthProvider>), surfaced loudly — the React
|
|
28
|
+
// convention for required-provider hooks.
|
|
29
|
+
throw new Error("Auth hooks must be used inside <AuthProvider client={...}>");
|
|
30
|
+
}
|
|
31
|
+
return value;
|
|
32
|
+
};
|