@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.
@@ -0,0 +1,107 @@
1
+ import { describe, expect, test, vi } from "vitest";
2
+ import type { MeSessionSummary } from "@smartcrab/browser";
3
+ import { err, ok } from "@smartcrab/browser";
4
+ import { createSessionListController } from "./sessions-controller.js";
5
+ import type { SessionListClient } from "./sessions-controller.js";
6
+
7
+ /**
8
+ * Session list controller tests (`useSession` backing, design.md §24).
9
+ * Renderer-free per the package's documented constraint.
10
+ */
11
+
12
+ const SESSION_A: MeSessionSummary = {
13
+ session_id: `ses_${"a".repeat(32)}`,
14
+ client_id: `cli_${"a".repeat(32)}`,
15
+ device_name: "Chrome on macOS",
16
+ created_at: "2026-08-01T08:00:00Z",
17
+ last_active_at: "2026-08-05T07:00:00Z",
18
+ current: true,
19
+ };
20
+
21
+ const SESSION_B: MeSessionSummary = {
22
+ ...SESSION_A,
23
+ session_id: `ses_${"b".repeat(32)}`,
24
+ current: false,
25
+ };
26
+
27
+ const createClient = (): SessionListClient => ({
28
+ listMySessions: vi.fn<SessionListClient["listMySessions"]>(async () =>
29
+ ok({ sessions: [SESSION_A, SESSION_B] }),
30
+ ),
31
+ revokeMySession: vi.fn<SessionListClient["revokeMySession"]>(async () =>
32
+ ok({ session_id: SESSION_B.session_id, revoked: true }),
33
+ ),
34
+ revokeAllMySessions: vi.fn<SessionListClient["revokeAllMySessions"]>(async () =>
35
+ ok({ revoked: true }),
36
+ ),
37
+ });
38
+
39
+ describe("createSessionListController", () => {
40
+ test("load populates the list", async () => {
41
+ const client = createClient();
42
+ const controller = createSessionListController(client);
43
+ const outcome = await controller.load();
44
+ expect(outcome).toEqual({ ok: true, value: [SESSION_A, SESSION_B] });
45
+ expect(controller.getSnapshot()).toEqual({
46
+ status: "loaded",
47
+ sessions: [SESSION_A, SESSION_B],
48
+ error: null,
49
+ });
50
+ });
51
+
52
+ test("concurrent loads dedupe to one request", async () => {
53
+ const client = createClient();
54
+ const controller = createSessionListController(client);
55
+ await Promise.all([controller.load(), controller.load()]);
56
+ expect(client.listMySessions).toHaveBeenCalledTimes(1);
57
+ });
58
+
59
+ test("revoke drops the session from the cached list without a reload", async () => {
60
+ const client = createClient();
61
+ const controller = createSessionListController(client);
62
+ await controller.load();
63
+ const outcome = await controller.revoke(SESSION_B.session_id);
64
+ expect(outcome).toEqual({ ok: true, value: { revoked: true } });
65
+ expect(client.revokeMySession).toHaveBeenCalledWith(SESSION_B.session_id);
66
+ expect(controller.getSnapshot().sessions).toEqual([SESSION_A]);
67
+ });
68
+
69
+ test("a failed revoke propagates the error and leaves the list intact", async () => {
70
+ const client = createClient();
71
+ client.revokeMySession = vi.fn<SessionListClient["revokeMySession"]>(async () =>
72
+ err({
73
+ type: "problem_details",
74
+ problemType: "https://x/not-found",
75
+ code: "not_found",
76
+ title: "Not Found",
77
+ status: 404,
78
+ }),
79
+ );
80
+ const controller = createSessionListController(client);
81
+ await controller.load();
82
+ const outcome = await controller.revoke(SESSION_B.session_id);
83
+ expect(outcome.ok).toBe(false);
84
+ if (!outcome.ok) expect(outcome.error).toMatchObject({ code: "not_found" });
85
+ expect(controller.getSnapshot().sessions).toEqual([SESSION_A, SESSION_B]);
86
+ });
87
+
88
+ test("revokeAll resets the list to idle (design.md §24.3: current session dies too)", async () => {
89
+ const client = createClient();
90
+ const controller = createSessionListController(client);
91
+ await controller.load();
92
+ const outcome = await controller.revokeAll();
93
+ expect(outcome).toEqual({ ok: true, value: { revoked: true } });
94
+ expect(controller.getSnapshot()).toEqual({ status: "idle", sessions: null, error: null });
95
+ });
96
+
97
+ test("not_authenticated on load resets to idle", async () => {
98
+ const client = createClient();
99
+ client.listMySessions = vi.fn<SessionListClient["listMySessions"]>(async () =>
100
+ err({ type: "not_authenticated" }),
101
+ );
102
+ const controller = createSessionListController(client);
103
+ const outcome = await controller.load();
104
+ expect(outcome).toEqual({ ok: false, error: { type: "not_authenticated" } });
105
+ expect(controller.getSnapshot()).toEqual({ status: "idle", sessions: null, error: null });
106
+ });
107
+ });
@@ -0,0 +1,120 @@
1
+ import type {
2
+ BrowserAuthClient,
3
+ BrowserAuthError,
4
+ MeSessionSummary,
5
+ Outcome,
6
+ } from "@smartcrab/browser";
7
+ import { err, ok } from "@smartcrab/browser";
8
+
9
+ /**
10
+ * Headless controller for the `/v1/me/sessions` surface (design.md §16.2,
11
+ * §24). React-free so it is unit-testable without a renderer; `useSession`
12
+ * binds it.
13
+ */
14
+
15
+ export type SessionListStatus = "idle" | "loading" | "loaded" | "error";
16
+
17
+ export interface SessionListSnapshot {
18
+ readonly status: SessionListStatus;
19
+ readonly sessions: readonly MeSessionSummary[] | null;
20
+ readonly error: BrowserAuthError | null;
21
+ }
22
+
23
+ export type SessionListListener = (snapshot: SessionListSnapshot) => void;
24
+
25
+ export type SessionListClient = Pick<
26
+ BrowserAuthClient,
27
+ "listMySessions" | "revokeMySession" | "revokeAllMySessions"
28
+ >;
29
+
30
+ export interface SessionListController {
31
+ getSnapshot(): SessionListSnapshot;
32
+ subscribe(listener: SessionListListener): () => void;
33
+ load(): Promise<Outcome<readonly MeSessionSummary[], BrowserAuthError>>;
34
+ /** Revokes one session and drops it from the cached list (design.md §24). */
35
+ revoke(sessionId: string): Promise<Outcome<{ revoked: true }, BrowserAuthError>>;
36
+ /**
37
+ * Revokes ALL sessions including the current one (design.md §24.3). The
38
+ * local list resets to `idle`; the client's own tokens die server-side with
39
+ * the current session.
40
+ */
41
+ revokeAll(): Promise<Outcome<{ revoked: true }, BrowserAuthError>>;
42
+ clear(): void;
43
+ }
44
+
45
+ const IDLE: SessionListSnapshot = { status: "idle", sessions: null, error: null };
46
+
47
+ export const createSessionListController = (client: SessionListClient): SessionListController => {
48
+ let snapshot: SessionListSnapshot = IDLE;
49
+ const listeners = new Set<SessionListListener>();
50
+ let inflight: Promise<Outcome<readonly MeSessionSummary[], BrowserAuthError>> | null = null;
51
+
52
+ const transition = (next: SessionListSnapshot): void => {
53
+ snapshot = next;
54
+ for (const listener of listeners) {
55
+ listener(snapshot);
56
+ }
57
+ };
58
+
59
+ const load = (): Promise<Outcome<readonly MeSessionSummary[], BrowserAuthError>> => {
60
+ if (inflight !== null) return inflight;
61
+ const pending = (async (): Promise<Outcome<readonly MeSessionSummary[], BrowserAuthError>> => {
62
+ transition({ status: "loading", sessions: snapshot.sessions, error: null });
63
+ const outcome = await client.listMySessions();
64
+ if (!outcome.ok) {
65
+ if (outcome.error.type === "not_authenticated") {
66
+ transition(IDLE);
67
+ } else {
68
+ transition({ status: "error", sessions: snapshot.sessions, error: outcome.error });
69
+ }
70
+ return outcome;
71
+ }
72
+ transition({ status: "loaded", sessions: outcome.value.sessions, error: null });
73
+ return ok(outcome.value.sessions);
74
+ })();
75
+ inflight = pending;
76
+ const clearInflight = (): void => {
77
+ if (inflight === pending) inflight = null;
78
+ };
79
+ void pending.then(clearInflight, clearInflight);
80
+ return pending;
81
+ };
82
+
83
+ const revoke = async (
84
+ sessionId: string,
85
+ ): Promise<Outcome<{ revoked: true }, BrowserAuthError>> => {
86
+ const outcome = await client.revokeMySession(sessionId);
87
+ if (!outcome.ok) return err(outcome.error);
88
+ const current = snapshot.sessions;
89
+ if (current !== null) {
90
+ transition({
91
+ ...snapshot,
92
+ sessions: current.filter((session) => session.session_id !== sessionId),
93
+ });
94
+ }
95
+ return ok({ revoked: true });
96
+ };
97
+
98
+ const revokeAll = async (): Promise<Outcome<{ revoked: true }, BrowserAuthError>> => {
99
+ const outcome = await client.revokeAllMySessions();
100
+ if (!outcome.ok) return err(outcome.error);
101
+ transition(IDLE);
102
+ return ok({ revoked: true });
103
+ };
104
+
105
+ const clear = (): void => {
106
+ transition(IDLE);
107
+ };
108
+
109
+ return {
110
+ getSnapshot: () => snapshot,
111
+ subscribe: (listener) => {
112
+ listeners.add(listener);
113
+ return () => listeners.delete(listener);
114
+ },
115
+ load,
116
+ revoke,
117
+ revokeAll,
118
+ clear,
119
+ };
120
+ };
@@ -0,0 +1,271 @@
1
+ import { describe, expect, test, vi } from "vitest";
2
+ import type { AuthenticatedSession, BrowserAuthError } from "@smartcrab/browser";
3
+ import { err, ok } from "@smartcrab/browser";
4
+ import { createSignInFlow } from "./sign-in-flow.js";
5
+ import type { SignInFlowClient, SignInFlowSnapshot } from "./sign-in-flow.js";
6
+
7
+ /**
8
+ * Sign-in flow machine tests (design.md §16 transaction model, §21.4 hook
9
+ * backing). No renderer: react-dom is intentionally not a dependency of this
10
+ * package, so the hooks' logic is tested here at the controller level via a
11
+ * structural fake of the narrow client slice.
12
+ */
13
+
14
+ const TXN_ID = `txn_${"b".repeat(32)}`;
15
+ const AUTH_CODE = `ac_${"g".repeat(32)}`;
16
+ const REDIRECT_URI = "https://app.example.com/oauth/callback";
17
+
18
+ const SESSION: AuthenticatedSession = {
19
+ accessTokenExpiresAt: 1_900_000_000_000,
20
+ scope: "openid profile email",
21
+ hasRefreshToken: true,
22
+ };
23
+
24
+ const COMPLETE = { authorization_code: AUTH_CODE, state: "state-1", redirect_uri: REDIRECT_URI };
25
+
26
+ const createFakeClient = () => {
27
+ const client: SignInFlowClient = {
28
+ createTransaction: vi.fn<SignInFlowClient["createTransaction"]>(async () =>
29
+ ok({
30
+ transactionId: TXN_ID,
31
+ state: "state-1",
32
+ expiresAt: "2026-08-05T08:10:00Z",
33
+ availableMethods: ["passkey", "email_otp", "google"],
34
+ }),
35
+ ),
36
+ cancelTransaction: vi.fn<SignInFlowClient["cancelTransaction"]>(async () =>
37
+ ok({ transaction_id: TXN_ID, status: "failed" }),
38
+ ),
39
+ startEmailOtp: vi.fn<SignInFlowClient["startEmailOtp"]>(async () =>
40
+ ok({ challenge_id: "chal_1", expires_at: "2026-08-05T08:05:00Z" }),
41
+ ),
42
+ resendEmailOtp: vi.fn<SignInFlowClient["resendEmailOtp"]>(async () =>
43
+ ok({ challenge_id: "chal_2", expires_at: "2026-08-05T08:06:00Z" }),
44
+ ),
45
+ verifyEmailOtp: vi.fn<SignInFlowClient["verifyEmailOtp"]>(async () =>
46
+ ok({ transaction_id: TXN_ID, status: "authenticated" }),
47
+ ),
48
+ startPasskeyRegistration: vi.fn<SignInFlowClient["startPasskeyRegistration"]>(async () =>
49
+ ok({
50
+ transaction_id: TXN_ID,
51
+ status: "authenticated",
52
+ passkey: {
53
+ passkey_id: `psk_${"e".repeat(32)}`,
54
+ name: null,
55
+ created_at: "2026-08-05T08:00:00Z",
56
+ last_used_at: null,
57
+ device_type: "multi_device",
58
+ backed_up: true,
59
+ },
60
+ }),
61
+ ),
62
+ startPasskeyAuthentication: vi.fn<SignInFlowClient["startPasskeyAuthentication"]>(async () =>
63
+ ok({ transaction_id: TXN_ID, status: "authenticated" }),
64
+ ),
65
+ startSocialSignIn: vi.fn<SignInFlowClient["startSocialSignIn"]>(async () =>
66
+ ok({ authorization_url: "https://accounts.google.com/o/oauth2/v2/auth?x=1" }),
67
+ ),
68
+ completeTransaction: vi.fn<SignInFlowClient["completeTransaction"]>(async () => ok(COMPLETE)),
69
+ exchangeAuthorizationCode: vi.fn<SignInFlowClient["exchangeAuthorizationCode"]>(async () =>
70
+ ok(SESSION),
71
+ ),
72
+ };
73
+ return client;
74
+ };
75
+
76
+ const networkError = (): BrowserAuthError => ({
77
+ type: "network_error",
78
+ message: "down",
79
+ retryable: true,
80
+ });
81
+
82
+ const collectEvents = (flow: ReturnType<typeof createSignInFlow>): SignInFlowSnapshot[] => {
83
+ const events: SignInFlowSnapshot[] = [];
84
+ flow.subscribe((snapshot) => events.push(snapshot));
85
+ return events;
86
+ };
87
+
88
+ describe("createSignInFlow — state machine (design.md §16)", () => {
89
+ test("starts idle with a referentially stable snapshot", () => {
90
+ const flow = createSignInFlow(createFakeClient());
91
+ expect(flow.getSnapshot()).toEqual({ state: { step: "idle" }, pendingAction: null });
92
+ // useSyncExternalStore contract: same object until a transition occurs.
93
+ expect(flow.getSnapshot()).toBe(flow.getSnapshot());
94
+ });
95
+
96
+ test("begin creates a transaction and lands on awaiting_method", async () => {
97
+ const client = createFakeClient();
98
+ const flow = createSignInFlow(client);
99
+ const events = collectEvents(flow);
100
+
101
+ const outcome = await flow.begin();
102
+ expect(outcome.ok).toBe(true);
103
+ expect(client.createTransaction).toHaveBeenCalledTimes(1);
104
+
105
+ const snapshot = flow.getSnapshot();
106
+ expect(snapshot.pendingAction).toBeNull();
107
+ expect(snapshot.state).toMatchObject({
108
+ step: "awaiting_method",
109
+ transactionId: TXN_ID,
110
+ methods: ["passkey", "email_otp", "google"],
111
+ });
112
+ // The transition path exposed the pending action while in flight.
113
+ expect(events.map((e) => [e.state.step, e.pendingAction])).toEqual([
114
+ ["starting", "begin"],
115
+ ["awaiting_method", null],
116
+ ]);
117
+ });
118
+
119
+ test("begin twice is an invalid_flow_state caller error, not a crash", async () => {
120
+ const flow = createSignInFlow(createFakeClient());
121
+ await flow.begin();
122
+ const second = await flow.begin();
123
+ expect(second).toEqual({
124
+ ok: false,
125
+ error: { type: "invalid_flow_state", expected: "idle|failed", actual: "awaiting_method" },
126
+ });
127
+ });
128
+
129
+ test("a failed begin lands in failed with the client error", async () => {
130
+ const client = createFakeClient();
131
+ client.createTransaction = vi.fn<SignInFlowClient["createTransaction"]>(async () =>
132
+ err(networkError()),
133
+ );
134
+ const flow = createSignInFlow(client);
135
+ const outcome = await flow.begin();
136
+ expect(outcome.ok).toBe(false);
137
+ expect(flow.getSnapshot().state).toEqual({ step: "failed", error: networkError() });
138
+ });
139
+
140
+ test("email OTP: send → resend → verify drives complete+exchange to signed_in", async () => {
141
+ const client = createFakeClient();
142
+ const flow = createSignInFlow(client);
143
+ await flow.begin();
144
+
145
+ const sent = await flow.sendEmailCode("user@example.com");
146
+ expect(sent).toEqual({ ok: true, value: { challengeId: "chal_1" } });
147
+ expect(client.startEmailOtp).toHaveBeenCalledWith(TXN_ID, { email: "user@example.com" });
148
+ expect(flow.getSnapshot().state).toMatchObject({
149
+ step: "email_challenge_sent",
150
+ challengeId: "chal_1",
151
+ email: "user@example.com",
152
+ });
153
+
154
+ const resent = await flow.resendEmailCode();
155
+ expect(resent).toEqual({ ok: true, value: { challengeId: "chal_2" } });
156
+ expect(client.resendEmailOtp).toHaveBeenCalledWith(TXN_ID, { challenge_id: "chal_1" });
157
+ expect(flow.getSnapshot().state).toMatchObject({
158
+ step: "email_challenge_sent",
159
+ challengeId: "chal_2",
160
+ });
161
+
162
+ const verified = await flow.verifyEmailCode("123456");
163
+ expect(verified).toEqual({ ok: true, value: SESSION });
164
+ expect(client.verifyEmailOtp).toHaveBeenCalledWith(TXN_ID, {
165
+ challenge_id: "chal_2",
166
+ code: "123456",
167
+ });
168
+ // design.md §16.3: verify never returns tokens; complete issues the code,
169
+ // exchange swaps it via the stored PKCE verifier.
170
+ expect(client.completeTransaction).toHaveBeenCalledWith(TXN_ID);
171
+ expect(client.exchangeAuthorizationCode).toHaveBeenCalledWith({
172
+ code: AUTH_CODE,
173
+ state: "state-1",
174
+ });
175
+ expect(flow.getSnapshot().state).toEqual({ step: "signed_in", session: SESSION });
176
+ });
177
+
178
+ test("verifyEmailCode without a challenge is a guarded caller error", async () => {
179
+ const flow = createSignInFlow(createFakeClient());
180
+ const outcome = await flow.verifyEmailCode("123456");
181
+ expect(outcome).toEqual({
182
+ ok: false,
183
+ error: { type: "invalid_flow_state", expected: "email_challenge_sent", actual: "idle" },
184
+ });
185
+ });
186
+
187
+ test("a wrong code failure surfaces the server error and preserves retry via reset", async () => {
188
+ const client = createFakeClient();
189
+ client.verifyEmailOtp = vi.fn<SignInFlowClient["verifyEmailOtp"]>(async () =>
190
+ err({
191
+ type: "problem_details",
192
+ problemType: "https://x/invalid-request",
193
+ code: "invalid_request",
194
+ title: "Bad Request",
195
+ status: 400,
196
+ }),
197
+ );
198
+ const flow = createSignInFlow(client);
199
+ await flow.begin();
200
+ await flow.sendEmailCode("user@example.com");
201
+ const outcome = await flow.verifyEmailCode("000000");
202
+ expect(outcome.ok).toBe(false);
203
+ expect(flow.getSnapshot().state).toMatchObject({
204
+ step: "failed",
205
+ error: { code: "invalid_request" },
206
+ });
207
+
208
+ flow.reset();
209
+ expect(flow.getSnapshot().state).toEqual({ step: "idle" });
210
+ });
211
+
212
+ test("signInWithPasskey runs the ceremony then finalizes", async () => {
213
+ const client = createFakeClient();
214
+ const flow = createSignInFlow(client);
215
+ await flow.begin();
216
+ const outcome = await flow.signInWithPasskey();
217
+ expect(outcome).toEqual({ ok: true, value: SESSION });
218
+ expect(client.startPasskeyAuthentication).toHaveBeenCalledWith(TXN_ID);
219
+ expect(client.completeTransaction).toHaveBeenCalledWith(TXN_ID);
220
+ expect(flow.getSnapshot().state).toEqual({ step: "signed_in", session: SESSION });
221
+ });
222
+
223
+ test("registerPasskey forwards the optional name", async () => {
224
+ const client = createFakeClient();
225
+ const flow = createSignInFlow(client);
226
+ await flow.begin();
227
+ await flow.registerPasskey({ name: "MacBook" });
228
+ expect(client.startPasskeyRegistration).toHaveBeenCalledWith(TXN_ID, { name: "MacBook" });
229
+ });
230
+
231
+ test("signInWithSocial stays resumable after the top-level redirect", async () => {
232
+ const client = createFakeClient();
233
+ const flow = createSignInFlow(client);
234
+ await flow.begin();
235
+ const outcome = await flow.signInWithSocial("google");
236
+ expect(outcome).toEqual({ ok: true, value: { redirected: true } });
237
+ expect(client.startSocialSignIn).toHaveBeenCalledWith(TXN_ID, "google");
238
+ // The page is navigating away; the flow remains at method selection.
239
+ expect(flow.getSnapshot().state).toMatchObject({ step: "awaiting_method" });
240
+ });
241
+
242
+ test("cancel from a live transaction calls the server and resets to idle", async () => {
243
+ const client = createFakeClient();
244
+ const flow = createSignInFlow(client);
245
+ await flow.begin();
246
+ await flow.sendEmailCode("user@example.com");
247
+ const outcome = await flow.cancel();
248
+ expect(outcome).toEqual({ ok: true, value: { cancelled: true } });
249
+ expect(client.cancelTransaction).toHaveBeenCalledWith(TXN_ID);
250
+ expect(flow.getSnapshot().state).toEqual({ step: "idle" });
251
+ });
252
+
253
+ test("cancel from idle performs no server call", async () => {
254
+ const client = createFakeClient();
255
+ const flow = createSignInFlow(client);
256
+ const outcome = await flow.cancel();
257
+ expect(outcome).toEqual({ ok: true, value: { cancelled: true } });
258
+ expect(client.cancelTransaction).not.toHaveBeenCalled();
259
+ });
260
+
261
+ test("unsubscribed listeners stop receiving transitions", async () => {
262
+ const flow = createSignInFlow(createFakeClient());
263
+ const events: SignInFlowSnapshot[] = [];
264
+ const unsubscribe = flow.subscribe((snapshot) => events.push(snapshot));
265
+ await flow.begin();
266
+ const count = events.length;
267
+ unsubscribe();
268
+ await flow.sendEmailCode("user@example.com");
269
+ expect(events).toHaveLength(count);
270
+ });
271
+ });