@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/src/headless.tsx
ADDED
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
import type { AuthenticatedSession, BrowserAuthError, SocialProvider } from "@smartcrab/browser";
|
|
2
|
+
import { useState } from "react";
|
|
3
|
+
import type { ReactNode } from "react";
|
|
4
|
+
import { useEmailOtp, usePasskey, useSocialSignIn } from "./hooks.js";
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Headless UI components for the web (design.md §3.1: "React | Hooks、
|
|
8
|
+
* Provider、UIコンポーネント").
|
|
9
|
+
*
|
|
10
|
+
* These are the behavior-only counterparts of `@smartcrab/ui-web`'s
|
|
11
|
+
* styled hosted-login kit: they render NOTHING themselves — no DOM, no
|
|
12
|
+
* styling, no theme tokens. Customers compose fully custom UIs by passing a
|
|
13
|
+
* render function as `children` and wiring the provided state/handlers to
|
|
14
|
+
* their own elements.
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
// ---------------------------------------------------------------------------
|
|
18
|
+
// PasskeyButton
|
|
19
|
+
// ---------------------------------------------------------------------------
|
|
20
|
+
|
|
21
|
+
export interface PasskeyButtonRenderProps {
|
|
22
|
+
/** Wire to your button's onClick. Runs the full ceremony through the sign-in flow. */
|
|
23
|
+
readonly onClick: () => void;
|
|
24
|
+
/** True while a ceremony is running or passkeys are unavailable — disable your button. */
|
|
25
|
+
readonly disabled: boolean;
|
|
26
|
+
/** Runtime WebAuthn capability (design.md §21.2: render nothing when false). */
|
|
27
|
+
readonly isSupported: boolean;
|
|
28
|
+
readonly pending: boolean;
|
|
29
|
+
readonly error: BrowserAuthError | null;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export interface PasskeyButtonProps {
|
|
33
|
+
/** Ceremony kind: `sign-in` (discoverable credential) or `register` (design.md §17). */
|
|
34
|
+
readonly mode?: "sign-in" | "register";
|
|
35
|
+
/** Optional authenticator label for `register` mode (design.md §12.5 `passkeys.name`). */
|
|
36
|
+
readonly name?: string;
|
|
37
|
+
readonly onComplete?: (session: AuthenticatedSession) => void;
|
|
38
|
+
readonly children: (props: PasskeyButtonRenderProps) => ReactNode;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** Headless passkey button: ceremony wiring only, zero rendering opinions. */
|
|
42
|
+
export const PasskeyButton = ({
|
|
43
|
+
mode = "sign-in",
|
|
44
|
+
name,
|
|
45
|
+
onComplete,
|
|
46
|
+
children,
|
|
47
|
+
}: PasskeyButtonProps): ReactNode => {
|
|
48
|
+
const {
|
|
49
|
+
isSupported,
|
|
50
|
+
isCeremonyActive,
|
|
51
|
+
pendingAction,
|
|
52
|
+
error,
|
|
53
|
+
signInWithPasskey,
|
|
54
|
+
registerPasskey,
|
|
55
|
+
} = usePasskey();
|
|
56
|
+
const pending = isCeremonyActive || pendingAction === "passkey";
|
|
57
|
+
const onClick = (): void => {
|
|
58
|
+
const action =
|
|
59
|
+
mode === "register"
|
|
60
|
+
? registerPasskey(name !== undefined ? { name } : undefined)
|
|
61
|
+
: signInWithPasskey();
|
|
62
|
+
void action.then((outcome) => {
|
|
63
|
+
if (outcome.ok) onComplete?.(outcome.value);
|
|
64
|
+
});
|
|
65
|
+
};
|
|
66
|
+
return children({
|
|
67
|
+
onClick,
|
|
68
|
+
disabled: pending || !isSupported,
|
|
69
|
+
isSupported,
|
|
70
|
+
pending,
|
|
71
|
+
error,
|
|
72
|
+
});
|
|
73
|
+
};
|
|
74
|
+
|
|
75
|
+
// ---------------------------------------------------------------------------
|
|
76
|
+
// EmailOtpForm
|
|
77
|
+
// ---------------------------------------------------------------------------
|
|
78
|
+
|
|
79
|
+
export type EmailOtpFormStep = "enter_email" | "enter_code";
|
|
80
|
+
|
|
81
|
+
export interface EmailOtpFormRenderProps {
|
|
82
|
+
readonly step: EmailOtpFormStep;
|
|
83
|
+
readonly email: string;
|
|
84
|
+
readonly setEmail: (value: string) => void;
|
|
85
|
+
readonly code: string;
|
|
86
|
+
readonly setCode: (value: string) => void;
|
|
87
|
+
/** Sends the code for the current `email` value. */
|
|
88
|
+
readonly send: () => void;
|
|
89
|
+
readonly resend: () => void;
|
|
90
|
+
/** Verifies the current `code` value, then completes sign-in. */
|
|
91
|
+
readonly verify: () => void;
|
|
92
|
+
readonly pendingAction: "send_email" | "resend_email" | "verify_email" | null;
|
|
93
|
+
readonly error: BrowserAuthError | null;
|
|
94
|
+
/** Challenge metadata once sent (expiry drives resend cooldown UIs, design.md §18.2). */
|
|
95
|
+
readonly challengeExpiresAt: string | null;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
export interface EmailOtpFormProps {
|
|
99
|
+
readonly onSignedIn?: (session: AuthenticatedSession) => void;
|
|
100
|
+
readonly children: (props: EmailOtpFormRenderProps) => ReactNode;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* Headless email-OTP form state machine: owns the two text fields' local
|
|
105
|
+
* state and maps the sign-in flow's steps onto `enter_email`/`enter_code`.
|
|
106
|
+
* All mutation goes through the render props.
|
|
107
|
+
*/
|
|
108
|
+
export const EmailOtpForm = ({ onSignedIn, children }: EmailOtpFormProps): ReactNode => {
|
|
109
|
+
const { challenge, pendingAction, error, send, resend, verify } = useEmailOtp();
|
|
110
|
+
const [email, setEmail] = useState("");
|
|
111
|
+
const [code, setCode] = useState("");
|
|
112
|
+
|
|
113
|
+
const step: EmailOtpFormStep = challenge === null ? "enter_email" : "enter_code";
|
|
114
|
+
|
|
115
|
+
return children({
|
|
116
|
+
step,
|
|
117
|
+
email,
|
|
118
|
+
setEmail,
|
|
119
|
+
code,
|
|
120
|
+
setCode,
|
|
121
|
+
send: () => {
|
|
122
|
+
void send(email);
|
|
123
|
+
},
|
|
124
|
+
resend: () => {
|
|
125
|
+
void resend();
|
|
126
|
+
},
|
|
127
|
+
verify: () => {
|
|
128
|
+
void verify(code).then((outcome) => {
|
|
129
|
+
if (outcome.ok) onSignedIn?.(outcome.value);
|
|
130
|
+
});
|
|
131
|
+
},
|
|
132
|
+
pendingAction:
|
|
133
|
+
pendingAction === "send_email" ||
|
|
134
|
+
pendingAction === "resend_email" ||
|
|
135
|
+
pendingAction === "verify_email"
|
|
136
|
+
? pendingAction
|
|
137
|
+
: null,
|
|
138
|
+
error,
|
|
139
|
+
challengeExpiresAt: challenge?.expiresAt ?? null,
|
|
140
|
+
});
|
|
141
|
+
};
|
|
142
|
+
|
|
143
|
+
// ---------------------------------------------------------------------------
|
|
144
|
+
// SocialButtons
|
|
145
|
+
// ---------------------------------------------------------------------------
|
|
146
|
+
|
|
147
|
+
export interface SocialButtonsRenderProps {
|
|
148
|
+
readonly providers: readonly SocialProvider[];
|
|
149
|
+
/** Starts the top-level redirect for a provider (design.md §20, §22.3). */
|
|
150
|
+
readonly signIn: (provider: SocialProvider) => void;
|
|
151
|
+
readonly pending: boolean;
|
|
152
|
+
readonly error: BrowserAuthError | null;
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
export interface SocialButtonsProps {
|
|
156
|
+
/** Which providers to offer; typically filtered by `getPublicConfig().available_methods`. */
|
|
157
|
+
readonly providers: readonly SocialProvider[];
|
|
158
|
+
readonly children: (props: SocialButtonsRenderProps) => ReactNode;
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/** Headless social provider list: redirect wiring only. */
|
|
162
|
+
export const SocialButtons = ({ providers, children }: SocialButtonsProps): ReactNode => {
|
|
163
|
+
const { signIn, pending, error } = useSocialSignIn();
|
|
164
|
+
return children({
|
|
165
|
+
providers,
|
|
166
|
+
signIn: (provider) => {
|
|
167
|
+
void signIn(provider);
|
|
168
|
+
},
|
|
169
|
+
pending,
|
|
170
|
+
error,
|
|
171
|
+
});
|
|
172
|
+
};
|
package/src/hooks.ts
ADDED
|
@@ -0,0 +1,267 @@
|
|
|
1
|
+
import type {
|
|
2
|
+
AuthenticatedSession,
|
|
3
|
+
BrowserAuthClient,
|
|
4
|
+
BrowserAuthError,
|
|
5
|
+
BrowserAuthSnapshot,
|
|
6
|
+
MeSessionSummary,
|
|
7
|
+
MeUpdateRequest,
|
|
8
|
+
MeUser,
|
|
9
|
+
Outcome,
|
|
10
|
+
SocialProvider,
|
|
11
|
+
} from "@smartcrab/browser";
|
|
12
|
+
import { useEffect, useMemo, useSyncExternalStore } from "react";
|
|
13
|
+
import { useAuthContextValue } from "./context.js";
|
|
14
|
+
import type { PendingAction, SignInFlow, SignInFlowState } from "./sign-in-flow.js";
|
|
15
|
+
import type { SignInFlowError } from "./sign-in-flow.js";
|
|
16
|
+
import type { SessionListStatus } from "./sessions-controller.js";
|
|
17
|
+
import type { UserProfileStatus } from "./user-controller.js";
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* The React hook surface (design.md §3.1 client matrix, §21.4 hook list).
|
|
21
|
+
*
|
|
22
|
+
* Every hook is a thin `useSyncExternalStore` binding over the headless
|
|
23
|
+
* controllers (sign-in flow, user profile, session list) created by
|
|
24
|
+
* `<AuthProvider>`; all behavior lives in the controllers so it stays
|
|
25
|
+
* testable without a renderer.
|
|
26
|
+
*/
|
|
27
|
+
|
|
28
|
+
const useStoreSnapshot = <Snapshot>(
|
|
29
|
+
subscribe: (onStoreChange: () => void) => () => void,
|
|
30
|
+
getSnapshot: () => Snapshot,
|
|
31
|
+
): Snapshot => useSyncExternalStore(subscribe, getSnapshot, getSnapshot);
|
|
32
|
+
|
|
33
|
+
/** Raw client escape hatch (advanced flows: hosted redirect, config, custom calls). */
|
|
34
|
+
export const useAuthClient = (): BrowserAuthClient => useAuthContextValue().client;
|
|
35
|
+
|
|
36
|
+
/** Current auth snapshot (signed-in status, expiry metadata — never raw tokens). */
|
|
37
|
+
export const useAuthState = (): BrowserAuthSnapshot => {
|
|
38
|
+
const { client } = useAuthContextValue();
|
|
39
|
+
return useStoreSnapshot(client.subscribe, client.getSnapshot);
|
|
40
|
+
};
|
|
41
|
+
|
|
42
|
+
const flowError = (state: SignInFlowState): BrowserAuthError | null =>
|
|
43
|
+
state.step === "failed" ? state.error : null;
|
|
44
|
+
|
|
45
|
+
export interface UseAuthResult {
|
|
46
|
+
readonly snapshot: BrowserAuthSnapshot;
|
|
47
|
+
readonly isSignedIn: boolean;
|
|
48
|
+
/** Headless sign-in flow state (transaction step machine, design.md §16). */
|
|
49
|
+
readonly flowState: SignInFlowState;
|
|
50
|
+
readonly pendingAction: PendingAction;
|
|
51
|
+
readonly flowError: BrowserAuthError | null;
|
|
52
|
+
readonly begin: SignInFlow["begin"];
|
|
53
|
+
readonly sendEmailCode: SignInFlow["sendEmailCode"];
|
|
54
|
+
readonly resendEmailCode: SignInFlow["resendEmailCode"];
|
|
55
|
+
readonly verifyEmailCode: SignInFlow["verifyEmailCode"];
|
|
56
|
+
readonly signInWithPasskey: SignInFlow["signInWithPasskey"];
|
|
57
|
+
readonly registerPasskey: SignInFlow["registerPasskey"];
|
|
58
|
+
readonly signInWithSocial: SignInFlow["signInWithSocial"];
|
|
59
|
+
readonly cancelSignIn: SignInFlow["cancel"];
|
|
60
|
+
readonly resetSignIn: SignInFlow["reset"];
|
|
61
|
+
readonly getAccessToken: BrowserAuthClient["getAccessToken"];
|
|
62
|
+
readonly refreshSession: BrowserAuthClient["refreshSession"];
|
|
63
|
+
readonly restoreSession: BrowserAuthClient["restoreSession"];
|
|
64
|
+
readonly signOut: BrowserAuthClient["signOut"];
|
|
65
|
+
/** Hosted redirect resume: pass the full callback URL after an authorize/social round-trip. */
|
|
66
|
+
readonly handleRedirectCallback: BrowserAuthClient["handleHostedAuthorizationCallback"];
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** Main facade (design.md §21.4 `useAuth`). */
|
|
70
|
+
export const useAuth = (): UseAuthResult => {
|
|
71
|
+
const { client, flow } = useAuthContextValue();
|
|
72
|
+
const snapshot = useStoreSnapshot(client.subscribe, client.getSnapshot);
|
|
73
|
+
const flowSnapshot = useStoreSnapshot(flow.subscribe, flow.getSnapshot);
|
|
74
|
+
return useMemo<UseAuthResult>(
|
|
75
|
+
() => ({
|
|
76
|
+
snapshot,
|
|
77
|
+
isSignedIn: snapshot.status === "signed_in",
|
|
78
|
+
flowState: flowSnapshot.state,
|
|
79
|
+
pendingAction: flowSnapshot.pendingAction,
|
|
80
|
+
flowError: flowError(flowSnapshot.state),
|
|
81
|
+
begin: flow.begin,
|
|
82
|
+
sendEmailCode: flow.sendEmailCode,
|
|
83
|
+
resendEmailCode: flow.resendEmailCode,
|
|
84
|
+
verifyEmailCode: flow.verifyEmailCode,
|
|
85
|
+
signInWithPasskey: flow.signInWithPasskey,
|
|
86
|
+
registerPasskey: flow.registerPasskey,
|
|
87
|
+
signInWithSocial: flow.signInWithSocial,
|
|
88
|
+
cancelSignIn: flow.cancel,
|
|
89
|
+
resetSignIn: flow.reset,
|
|
90
|
+
getAccessToken: client.getAccessToken,
|
|
91
|
+
refreshSession: client.refreshSession,
|
|
92
|
+
restoreSession: client.restoreSession,
|
|
93
|
+
signOut: client.signOut,
|
|
94
|
+
handleRedirectCallback: client.handleHostedAuthorizationCallback,
|
|
95
|
+
}),
|
|
96
|
+
[client, flow, snapshot, flowSnapshot],
|
|
97
|
+
);
|
|
98
|
+
};
|
|
99
|
+
|
|
100
|
+
export interface UseUserResult {
|
|
101
|
+
readonly status: UserProfileStatus;
|
|
102
|
+
readonly user: MeUser | null;
|
|
103
|
+
readonly error: BrowserAuthError | null;
|
|
104
|
+
readonly reload: () => Promise<Outcome<MeUser, BrowserAuthError>>;
|
|
105
|
+
readonly update: (patch: MeUpdateRequest) => Promise<Outcome<MeUser, BrowserAuthError>>;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/**
|
|
109
|
+
* Signed-in user's profile (design.md §21.4 `useUser`). Auto-loads when the
|
|
110
|
+
* client transitions to `signed_in` and clears on sign-out.
|
|
111
|
+
*/
|
|
112
|
+
export const useUser = (): UseUserResult => {
|
|
113
|
+
const { client, userProfile } = useAuthContextValue();
|
|
114
|
+
const authSnapshot = useStoreSnapshot(client.subscribe, client.getSnapshot);
|
|
115
|
+
const profile = useStoreSnapshot(userProfile.subscribe, userProfile.getSnapshot);
|
|
116
|
+
useEffect(() => {
|
|
117
|
+
if (authSnapshot.status === "signed_in") {
|
|
118
|
+
void userProfile.load();
|
|
119
|
+
} else {
|
|
120
|
+
userProfile.clear();
|
|
121
|
+
}
|
|
122
|
+
}, [authSnapshot.status, userProfile]);
|
|
123
|
+
return useMemo<UseUserResult>(
|
|
124
|
+
() => ({
|
|
125
|
+
status: profile.status,
|
|
126
|
+
user: profile.user,
|
|
127
|
+
error: profile.error,
|
|
128
|
+
reload: userProfile.load,
|
|
129
|
+
update: userProfile.update,
|
|
130
|
+
}),
|
|
131
|
+
[profile, userProfile],
|
|
132
|
+
);
|
|
133
|
+
};
|
|
134
|
+
|
|
135
|
+
export interface UseSessionResult {
|
|
136
|
+
readonly snapshot: BrowserAuthSnapshot;
|
|
137
|
+
readonly status: SessionListStatus;
|
|
138
|
+
readonly sessions: readonly MeSessionSummary[] | null;
|
|
139
|
+
readonly error: BrowserAuthError | null;
|
|
140
|
+
readonly reload: () => Promise<Outcome<readonly MeSessionSummary[], BrowserAuthError>>;
|
|
141
|
+
readonly revoke: (sessionId: string) => Promise<Outcome<{ revoked: true }, BrowserAuthError>>;
|
|
142
|
+
readonly revokeAll: () => Promise<Outcome<{ revoked: true }, BrowserAuthError>>;
|
|
143
|
+
readonly refreshSession: BrowserAuthClient["refreshSession"];
|
|
144
|
+
readonly signOut: BrowserAuthClient["signOut"];
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
/**
|
|
148
|
+
* Auth state plus the device-session list (design.md §21.4 `useSession`,
|
|
149
|
+
* §24). Auto-loads the list while signed in.
|
|
150
|
+
*/
|
|
151
|
+
export const useSession = (): UseSessionResult => {
|
|
152
|
+
const { client, sessionList } = useAuthContextValue();
|
|
153
|
+
const snapshot = useStoreSnapshot(client.subscribe, client.getSnapshot);
|
|
154
|
+
const list = useStoreSnapshot(sessionList.subscribe, sessionList.getSnapshot);
|
|
155
|
+
useEffect(() => {
|
|
156
|
+
if (snapshot.status === "signed_in") {
|
|
157
|
+
void sessionList.load();
|
|
158
|
+
} else {
|
|
159
|
+
sessionList.clear();
|
|
160
|
+
}
|
|
161
|
+
}, [snapshot.status, sessionList]);
|
|
162
|
+
return useMemo<UseSessionResult>(
|
|
163
|
+
() => ({
|
|
164
|
+
snapshot,
|
|
165
|
+
status: list.status,
|
|
166
|
+
sessions: list.sessions,
|
|
167
|
+
error: list.error,
|
|
168
|
+
reload: sessionList.load,
|
|
169
|
+
revoke: sessionList.revoke,
|
|
170
|
+
revokeAll: sessionList.revokeAll,
|
|
171
|
+
refreshSession: client.refreshSession,
|
|
172
|
+
signOut: client.signOut,
|
|
173
|
+
}),
|
|
174
|
+
[client, sessionList, snapshot, list],
|
|
175
|
+
);
|
|
176
|
+
};
|
|
177
|
+
|
|
178
|
+
export interface UsePasskeyResult {
|
|
179
|
+
/** Runtime capability (design.md §21.2: hide passkey UI when false). */
|
|
180
|
+
readonly isSupported: boolean;
|
|
181
|
+
readonly isCeremonyActive: boolean;
|
|
182
|
+
readonly pendingAction: PendingAction;
|
|
183
|
+
readonly error: BrowserAuthError | null;
|
|
184
|
+
readonly signInWithPasskey: () => Promise<Outcome<AuthenticatedSession, SignInFlowError>>;
|
|
185
|
+
readonly registerPasskey: (input?: {
|
|
186
|
+
readonly name?: string;
|
|
187
|
+
}) => Promise<Outcome<AuthenticatedSession, SignInFlowError>>;
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
/** Passkey ceremonies (design.md §21.4 `usePasskey`, §17). */
|
|
191
|
+
export const usePasskey = (): UsePasskeyResult => {
|
|
192
|
+
const { client, flow } = useAuthContextValue();
|
|
193
|
+
const flowSnapshot = useStoreSnapshot(flow.subscribe, flow.getSnapshot);
|
|
194
|
+
return useMemo<UsePasskeyResult>(
|
|
195
|
+
() => ({
|
|
196
|
+
isSupported: client.isPasskeySupported(),
|
|
197
|
+
isCeremonyActive: flowSnapshot.state.step === "ceremony",
|
|
198
|
+
pendingAction: flowSnapshot.pendingAction,
|
|
199
|
+
error: flowError(flowSnapshot.state),
|
|
200
|
+
signInWithPasskey: flow.signInWithPasskey,
|
|
201
|
+
registerPasskey: flow.registerPasskey,
|
|
202
|
+
}),
|
|
203
|
+
[client, flow, flowSnapshot],
|
|
204
|
+
);
|
|
205
|
+
};
|
|
206
|
+
|
|
207
|
+
export interface EmailOtpChallenge {
|
|
208
|
+
readonly challengeId: string;
|
|
209
|
+
readonly email: string;
|
|
210
|
+
readonly expiresAt: string;
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
export interface UseEmailOtpResult {
|
|
214
|
+
/** Present once a code has been sent (design.md §18). */
|
|
215
|
+
readonly challenge: EmailOtpChallenge | null;
|
|
216
|
+
readonly pendingAction: PendingAction;
|
|
217
|
+
readonly error: BrowserAuthError | null;
|
|
218
|
+
readonly send: (email: string) => Promise<Outcome<{ challengeId: string }, SignInFlowError>>;
|
|
219
|
+
readonly resend: () => Promise<Outcome<{ challengeId: string }, SignInFlowError>>;
|
|
220
|
+
readonly verify: (code: string) => Promise<Outcome<AuthenticatedSession, SignInFlowError>>;
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
/** Email OTP sub-flow (design.md §21.4 `useEmailOtp`, §18). */
|
|
224
|
+
export const useEmailOtp = (): UseEmailOtpResult => {
|
|
225
|
+
const { flow } = useAuthContextValue();
|
|
226
|
+
const flowSnapshot = useStoreSnapshot(flow.subscribe, flow.getSnapshot);
|
|
227
|
+
return useMemo<UseEmailOtpResult>(() => {
|
|
228
|
+
const state = flowSnapshot.state;
|
|
229
|
+
return {
|
|
230
|
+
challenge:
|
|
231
|
+
state.step === "email_challenge_sent"
|
|
232
|
+
? {
|
|
233
|
+
challengeId: state.challengeId,
|
|
234
|
+
email: state.email,
|
|
235
|
+
expiresAt: state.challengeExpiresAt,
|
|
236
|
+
}
|
|
237
|
+
: null,
|
|
238
|
+
pendingAction: flowSnapshot.pendingAction,
|
|
239
|
+
error: flowError(state),
|
|
240
|
+
send: flow.sendEmailCode,
|
|
241
|
+
resend: flow.resendEmailCode,
|
|
242
|
+
verify: flow.verifyEmailCode,
|
|
243
|
+
};
|
|
244
|
+
}, [flow, flowSnapshot]);
|
|
245
|
+
};
|
|
246
|
+
|
|
247
|
+
export interface UseSocialSignInResult {
|
|
248
|
+
readonly signIn: (
|
|
249
|
+
provider: SocialProvider,
|
|
250
|
+
) => Promise<Outcome<{ redirected: true }, SignInFlowError>>;
|
|
251
|
+
readonly pending: boolean;
|
|
252
|
+
readonly error: BrowserAuthError | null;
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
/** Social sign-in via top-level redirect (design.md §21.4 `useSocialSignIn`, §20). */
|
|
256
|
+
export const useSocialSignIn = (): UseSocialSignInResult => {
|
|
257
|
+
const { flow } = useAuthContextValue();
|
|
258
|
+
const flowSnapshot = useStoreSnapshot(flow.subscribe, flow.getSnapshot);
|
|
259
|
+
return useMemo<UseSocialSignInResult>(
|
|
260
|
+
() => ({
|
|
261
|
+
signIn: flow.signInWithSocial,
|
|
262
|
+
pending: flowSnapshot.pendingAction === "social",
|
|
263
|
+
error: flowError(flowSnapshot.state),
|
|
264
|
+
}),
|
|
265
|
+
[flow, flowSnapshot],
|
|
266
|
+
);
|
|
267
|
+
};
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
import { describe, expect, test } from "vitest";
|
|
2
|
+
import {
|
|
3
|
+
AuthProvider,
|
|
4
|
+
EmailOtpForm,
|
|
5
|
+
PasskeyButton,
|
|
6
|
+
SocialButtons,
|
|
7
|
+
createSessionListController,
|
|
8
|
+
createSignInFlow,
|
|
9
|
+
createUserProfileController,
|
|
10
|
+
useAuth,
|
|
11
|
+
useAuthClient,
|
|
12
|
+
useAuthState,
|
|
13
|
+
useEmailOtp,
|
|
14
|
+
usePasskey,
|
|
15
|
+
useSession,
|
|
16
|
+
useSocialSignIn,
|
|
17
|
+
useUser,
|
|
18
|
+
} from "./index.js";
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* Hook-layer smoke tests.
|
|
22
|
+
*
|
|
23
|
+
* Renderer constraint (documented in index.ts): this package has no
|
|
24
|
+
* react-dom / react-test-renderer dependency, so components cannot be
|
|
25
|
+
* mounted in tests. The hooks are thin `useSyncExternalStore` bindings over
|
|
26
|
+
* the controllers, which ARE fully tested (sign-in-flow.test.ts,
|
|
27
|
+
* user-controller.test.ts, sessions-controller.test.ts). What remains
|
|
28
|
+
* testable here: the public surface exists with the right shapes, and hooks
|
|
29
|
+
* fail fast outside a React render.
|
|
30
|
+
*/
|
|
31
|
+
describe("public surface", () => {
|
|
32
|
+
test("provider, hooks, headless components and controller factories are exported", () => {
|
|
33
|
+
for (const value of [
|
|
34
|
+
AuthProvider,
|
|
35
|
+
useAuth,
|
|
36
|
+
useAuthClient,
|
|
37
|
+
useAuthState,
|
|
38
|
+
useUser,
|
|
39
|
+
useSession,
|
|
40
|
+
usePasskey,
|
|
41
|
+
useEmailOtp,
|
|
42
|
+
useSocialSignIn,
|
|
43
|
+
PasskeyButton,
|
|
44
|
+
EmailOtpForm,
|
|
45
|
+
SocialButtons,
|
|
46
|
+
createSignInFlow,
|
|
47
|
+
createUserProfileController,
|
|
48
|
+
createSessionListController,
|
|
49
|
+
]) {
|
|
50
|
+
expect(typeof value).toBe("function");
|
|
51
|
+
}
|
|
52
|
+
});
|
|
53
|
+
|
|
54
|
+
test("hooks cannot run outside a React render (dispatcher invariant)", () => {
|
|
55
|
+
// React itself throws "Invalid hook call" — this proves the hook is
|
|
56
|
+
// genuinely wired through React rather than silently executing detached.
|
|
57
|
+
expect(() => useAuth()).toThrow();
|
|
58
|
+
expect(() => useSession()).toThrow();
|
|
59
|
+
});
|
|
60
|
+
});
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
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 type { AuthProviderProps } from "./provider.js";
|
|
22
|
+
export { AuthContext, useAuthContextValue } from "./context.js";
|
|
23
|
+
export type { AuthContextValue } from "./context.js";
|
|
24
|
+
export {
|
|
25
|
+
useAuth,
|
|
26
|
+
useAuthClient,
|
|
27
|
+
useAuthState,
|
|
28
|
+
useEmailOtp,
|
|
29
|
+
usePasskey,
|
|
30
|
+
useSession,
|
|
31
|
+
useSocialSignIn,
|
|
32
|
+
useUser,
|
|
33
|
+
} from "./hooks.js";
|
|
34
|
+
export type {
|
|
35
|
+
EmailOtpChallenge,
|
|
36
|
+
UseAuthResult,
|
|
37
|
+
UseEmailOtpResult,
|
|
38
|
+
UsePasskeyResult,
|
|
39
|
+
UseSessionResult,
|
|
40
|
+
UseSocialSignInResult,
|
|
41
|
+
UseUserResult,
|
|
42
|
+
} from "./hooks.js";
|
|
43
|
+
export { createSignInFlow } from "./sign-in-flow.js";
|
|
44
|
+
export type {
|
|
45
|
+
InvalidFlowStateError,
|
|
46
|
+
PendingAction,
|
|
47
|
+
SignInFlow,
|
|
48
|
+
SignInFlowClient,
|
|
49
|
+
SignInFlowError,
|
|
50
|
+
SignInFlowListener,
|
|
51
|
+
SignInFlowSnapshot,
|
|
52
|
+
SignInFlowState,
|
|
53
|
+
} from "./sign-in-flow.js";
|
|
54
|
+
export { createUserProfileController } from "./user-controller.js";
|
|
55
|
+
export type {
|
|
56
|
+
UserProfileClient,
|
|
57
|
+
UserProfileController,
|
|
58
|
+
UserProfileListener,
|
|
59
|
+
UserProfileSnapshot,
|
|
60
|
+
UserProfileStatus,
|
|
61
|
+
} from "./user-controller.js";
|
|
62
|
+
export { createSessionListController } from "./sessions-controller.js";
|
|
63
|
+
export type {
|
|
64
|
+
SessionListClient,
|
|
65
|
+
SessionListController,
|
|
66
|
+
SessionListListener,
|
|
67
|
+
SessionListSnapshot,
|
|
68
|
+
SessionListStatus,
|
|
69
|
+
} from "./sessions-controller.js";
|
|
70
|
+
export { EmailOtpForm, PasskeyButton, SocialButtons } from "./headless.js";
|
|
71
|
+
export type {
|
|
72
|
+
EmailOtpFormProps,
|
|
73
|
+
EmailOtpFormRenderProps,
|
|
74
|
+
EmailOtpFormStep,
|
|
75
|
+
PasskeyButtonProps,
|
|
76
|
+
PasskeyButtonRenderProps,
|
|
77
|
+
SocialButtonsProps,
|
|
78
|
+
SocialButtonsRenderProps,
|
|
79
|
+
} from "./headless.js";
|
package/src/provider.tsx
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import type { BrowserAuthClient } from "@smartcrab/browser";
|
|
2
|
+
import { useMemo } from "react";
|
|
3
|
+
import type { ReactNode } from "react";
|
|
4
|
+
import { AuthContext } from "./context.js";
|
|
5
|
+
import type { AuthContextValue } from "./context.js";
|
|
6
|
+
import { createSignInFlow } from "./sign-in-flow.js";
|
|
7
|
+
import { createSessionListController } from "./sessions-controller.js";
|
|
8
|
+
import { createUserProfileController } from "./user-controller.js";
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* `<AuthProvider client={...}>` (design.md §21.4).
|
|
12
|
+
*
|
|
13
|
+
* Creates the headless controllers (sign-in flow, profile, session list)
|
|
14
|
+
* once per client instance and shares them with every hook. All state is
|
|
15
|
+
* auth-state-driven; nothing here touches Web Storage — token rules live in
|
|
16
|
+
* `@smartcrab/browser` (design.md §22.3).
|
|
17
|
+
*/
|
|
18
|
+
export interface AuthProviderProps {
|
|
19
|
+
readonly client: BrowserAuthClient;
|
|
20
|
+
readonly children?: ReactNode;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export const AuthProvider = ({ client, children }: AuthProviderProps): ReactNode => {
|
|
24
|
+
const value = useMemo<AuthContextValue>(
|
|
25
|
+
() => ({
|
|
26
|
+
client,
|
|
27
|
+
flow: createSignInFlow(client),
|
|
28
|
+
userProfile: createUserProfileController(client),
|
|
29
|
+
sessionList: createSessionListController(client),
|
|
30
|
+
}),
|
|
31
|
+
[client],
|
|
32
|
+
);
|
|
33
|
+
// React 19 convention: the context object itself is the provider.
|
|
34
|
+
return <AuthContext value={value}>{children}</AuthContext>;
|
|
35
|
+
};
|