@gusnips/react 0.9.29 → 0.9.31

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/package.json CHANGED
@@ -1,13 +1,13 @@
1
1
  {
2
2
  "name": "@gusnips/react",
3
- "version": "0.9.29",
3
+ "version": "0.9.31",
4
4
  "description": "The headless runtime under a Vite + React SPA: typed fetch client with single-flight refresh, auth store, query defaults, route guards, error boundary, stale-tab recovery, i18n bootstrap.",
5
5
  "type": "module",
6
6
  "license": "MIT",
7
7
  "author": "Gustavo Salomé",
8
- "homepage": "https://github.com/gusnips/frontkit/tree/main/react#readme",
8
+ "homepage": "https://github.com/gusnips/kit/tree/main/react#readme",
9
9
  "bugs": {
10
- "url": "https://github.com/gusnips/frontkit/issues"
10
+ "url": "https://github.com/gusnips/kit/issues"
11
11
  },
12
12
  "exports": {
13
13
  ".": {
@@ -49,6 +49,10 @@
49
49
  "./oauth": {
50
50
  "types": "./dist/oauth.d.ts",
51
51
  "default": "./dist/oauth.js"
52
+ },
53
+ "./keys": {
54
+ "types": "./dist/keys.d.ts",
55
+ "default": "./dist/keys.js"
52
56
  }
53
57
  },
54
58
  "types": "./dist/index.d.ts",
@@ -149,7 +153,7 @@
149
153
  },
150
154
  "repository": {
151
155
  "type": "git",
152
- "url": "git+https://github.com/gusnips/frontkit.git",
156
+ "url": "git+https://github.com/gusnips/kit.git",
153
157
  "directory": "react"
154
158
  }
155
159
  }
@@ -0,0 +1,253 @@
1
+ // @vitest-environment happy-dom
2
+ import { QueryClient, QueryClientProvider, useMutation, useQuery } from "@tanstack/react-query";
3
+ import { act, createElement, useLayoutEffect } from "react";
4
+ import { createRoot } from "react-dom/client";
5
+ import { renderToString } from "react-dom/server";
6
+ import { afterEach, describe, expect, it, vi } from "vitest";
7
+ import {
8
+ createKeyLifecycle,
9
+ KeyScopeChangedError,
10
+ useKeyReveals,
11
+ type KeyLifecycle,
12
+ type RevealedKey,
13
+ } from "./keys.ts";
14
+
15
+ interface KeyRecord {
16
+ id: string;
17
+ name: string;
18
+ prefix: string;
19
+ }
20
+
21
+ vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
22
+
23
+ const cleanups: (() => void)[] = [];
24
+ afterEach(() => {
25
+ for (const cleanup of cleanups.splice(0)) cleanup();
26
+ document.body.replaceChildren();
27
+ });
28
+
29
+ function minted(id: string): RevealedKey<KeyRecord> {
30
+ const key = `sk_live_${id}_${"x".repeat(24)}`;
31
+ return { record: { id, name: `key ${id}`, prefix: key.slice(0, 10) }, key };
32
+ }
33
+
34
+ /** A request the test answers by hand, to hold it in flight across a navigation. */
35
+ function deferred<T>() {
36
+ let resolve!: (value: T) => void;
37
+ const promise = new Promise<T>((yes) => {
38
+ resolve = yes;
39
+ });
40
+ return { promise, resolve };
41
+ }
42
+
43
+ function lifecycleIn(scope: string | null = "account-1:workspace-1") {
44
+ const keys = createKeyLifecycle<KeyRecord>();
45
+ keys.setScope(scope);
46
+ // Each test leaves the window as it found it: no unread secrets means no unload listener.
47
+ cleanups.push(() => keys.setScope(null));
48
+ return keys;
49
+ }
50
+
51
+ /** The prompt shows only when a listener cancels the event. */
52
+ function closingPrompts(): boolean {
53
+ const event = new Event("beforeunload", { cancelable: true });
54
+ window.dispatchEvent(event);
55
+ return event.defaultPrevented;
56
+ }
57
+
58
+ describe("createKeyLifecycle", () => {
59
+ it("keeps every unread secret, newest first, and resolves only the record", async () => {
60
+ const keys = lifecycleIn();
61
+ const first = await keys.create(async () => minted("a"));
62
+ await keys.create(async () => minted("b"));
63
+
64
+ expect(first).toEqual(minted("a").record);
65
+ expect(keys.getSnapshot().map((one) => one.key)).toEqual([minted("b").key, minted("a").key]);
66
+ keys.dismiss("b");
67
+ expect(keys.getSnapshot()).toEqual([minted("a")]);
68
+ });
69
+
70
+ it("refuses a record that still holds the secret", async () => {
71
+ const keys = lifecycleIn();
72
+ // The whole answer passed as the record: the shape every donor's mutation cache ended up with.
73
+ const { record, key } = minted("a");
74
+ const answer = { ...record, key };
75
+ await expect(keys.create(async () => ({ record: answer, key }))).rejects.toThrow(
76
+ "still holds the secret",
77
+ );
78
+ expect(keys.getSnapshot()).toEqual([]);
79
+ });
80
+
81
+ it("sends nothing before a scope is set", async () => {
82
+ const keys = lifecycleIn(null);
83
+ const request = vi.fn(async () => minted("a"));
84
+ await expect(keys.create(request)).rejects.toThrow("setScope");
85
+ await expect(keys.revoke("a", request)).rejects.toThrow("setScope");
86
+ expect(request).not.toHaveBeenCalled();
87
+ });
88
+
89
+ it("a new scope forgets every secret and refuses answers from the old one", async () => {
90
+ const keys = lifecycleIn("account-1:workspace-1");
91
+ await keys.create(async () => minted("a"));
92
+ keys.setScope("account-1:workspace-1");
93
+ expect(keys.getSnapshot()).toHaveLength(1);
94
+
95
+ const late = deferred<RevealedKey<KeyRecord>>();
96
+ const creating = keys.create(() => late.promise);
97
+ // Signed out and straight back in as the same account: still not the scope that asked.
98
+ keys.setScope(null);
99
+ keys.setScope("account-1:workspace-1");
100
+ late.resolve(minted("b"));
101
+
102
+ const refused = await creating.catch((error: unknown) => error);
103
+ expect(refused).toBeInstanceOf(KeyScopeChangedError);
104
+ expect(refused).toMatchObject({ operation: "create" });
105
+ expect(keys.getSnapshot()).toEqual([]);
106
+ });
107
+
108
+ it("a failed revoke keeps the secret, and a success forgets only that key", async () => {
109
+ const keys = lifecycleIn();
110
+ await keys.create(async () => minted("a"));
111
+ await keys.create(async () => minted("b"));
112
+
113
+ await expect(
114
+ keys.revoke("a", async () => Promise.reject(new Error("offline"))),
115
+ ).rejects.toThrow("offline");
116
+ expect(keys.getSnapshot()).toHaveLength(2);
117
+
118
+ await keys.revoke("a", async () => undefined);
119
+ expect(keys.getSnapshot()).toEqual([minted("b")]);
120
+ });
121
+
122
+ it("a revoke answered after the scope changed forgets nothing in the new one", async () => {
123
+ const keys = lifecycleIn("account-1:workspace-1");
124
+ const late = deferred<void>();
125
+ const revoking = keys.revoke("a", () => late.promise);
126
+ keys.setScope("account-1:workspace-2");
127
+ await keys.create(async () => minted("a"));
128
+ late.resolve();
129
+
130
+ await expect(revoking).rejects.toMatchObject({ operation: "revoke" });
131
+ expect(keys.getSnapshot()).toEqual([minted("a")]);
132
+ });
133
+
134
+ it("asks before the tab closes only while a secret is unread, per lifecycle", async () => {
135
+ const one = lifecycleIn();
136
+ const other = lifecycleIn();
137
+ expect(closingPrompts()).toBe(false);
138
+
139
+ await one.create(async () => minted("a"));
140
+ await other.create(async () => minted("b"));
141
+ expect(closingPrompts()).toBe(true);
142
+
143
+ other.dismiss("b");
144
+ expect(closingPrompts()).toBe(true);
145
+ one.setScope(null);
146
+ expect(closingPrompts()).toBe(false);
147
+ });
148
+ });
149
+
150
+ describe("with react-query", () => {
151
+ function app(keys: KeyLifecycle<KeyRecord>, server: { list: KeyRecord[] }) {
152
+ const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
153
+ const element = document.createElement("div");
154
+ document.body.append(element);
155
+ const root = createRoot(element);
156
+ cleanups.push(() => act(() => root.unmount()));
157
+ let route: "keys" | "docs" = "keys";
158
+ let mint: ((request: () => Promise<RevealedKey<KeyRecord>>) => void) | undefined;
159
+ let shown: readonly RevealedKey<KeyRecord>[] = [];
160
+
161
+ function KeysPage() {
162
+ useQuery({ queryKey: ["keys"], queryFn: async () => server.list });
163
+ const create = useMutation({
164
+ mutationFn: (request: () => Promise<RevealedKey<KeyRecord>>) => keys.create(request),
165
+ onSuccess: () => client.invalidateQueries({ queryKey: ["keys"] }),
166
+ });
167
+ const reveals = useKeyReveals(keys);
168
+ useLayoutEffect(() => {
169
+ mint = create.mutate;
170
+ shown = reveals;
171
+ });
172
+ return createElement("p", null, reveals.map((one) => one.key).join(","));
173
+ }
174
+
175
+ const render = () =>
176
+ root.render(
177
+ createElement(
178
+ QueryClientProvider,
179
+ { client },
180
+ route === "keys" ? createElement(KeysPage) : createElement("p", null, "docs"),
181
+ ),
182
+ );
183
+ act(render);
184
+
185
+ return {
186
+ client,
187
+ element,
188
+ get shown() {
189
+ return shown;
190
+ },
191
+ mint(request: () => Promise<RevealedKey<KeyRecord>>) {
192
+ act(() => mint?.(request));
193
+ },
194
+ go(next: "keys" | "docs") {
195
+ route = next;
196
+ act(render);
197
+ },
198
+ };
199
+ }
200
+
201
+ it("a create in flight still reveals its secret after the page unmounts", async () => {
202
+ const keys = lifecycleIn();
203
+ const screen = app(keys, { list: [] });
204
+ const late = deferred<RevealedKey<KeyRecord>>();
205
+ screen.mint(() => late.promise);
206
+
207
+ screen.go("docs");
208
+ await act(async () => late.resolve(minted("a")));
209
+ expect(keys.getSnapshot()).toEqual([minted("a")]);
210
+
211
+ screen.go("keys");
212
+ expect(screen.shown).toEqual([minted("a")]);
213
+ expect(screen.element.textContent).toBe(minted("a").key);
214
+ });
215
+
216
+ it("no secret reaches the mutation cache or the list cache", async () => {
217
+ const keys = lifecycleIn();
218
+ const server = { list: [] as KeyRecord[] };
219
+ const screen = app(keys, server);
220
+ const { record, key } = minted("a");
221
+
222
+ screen.mint(async () => {
223
+ server.list = [record];
224
+ return { record, key };
225
+ });
226
+ await act(() =>
227
+ vi.waitFor(() => expect(screen.client.getQueryData(["keys"])).toEqual([record])),
228
+ );
229
+
230
+ const caches = JSON.stringify([
231
+ screen.client
232
+ .getMutationCache()
233
+ .getAll()
234
+ .map((mutation) => mutation.state),
235
+ screen.client
236
+ .getQueryCache()
237
+ .getAll()
238
+ .map((query) => query.state),
239
+ ]);
240
+ expect(caches).toContain(record.prefix);
241
+ expect(caches).not.toContain(key);
242
+ expect(keys.getSnapshot()).toEqual([{ record, key }]);
243
+ });
244
+
245
+ it("a prerender prints no secret", async () => {
246
+ const keys = lifecycleIn();
247
+ await keys.create(async () => minted("a"));
248
+ function Reveals() {
249
+ return createElement("p", null, useKeyReveals(keys).length);
250
+ }
251
+ expect(renderToString(createElement(Reveals))).toBe("<p>0</p>");
252
+ });
253
+ });
package/src/keys.ts ADDED
@@ -0,0 +1,144 @@
1
+ import { useSyncExternalStore } from "react";
2
+
3
+ /**
4
+ * A new API key, the one time the server sends its secret. Three products wrote this flow, and
5
+ * each knew one part the others missed:
6
+ *
7
+ * - One kept unread secrets in a list outside the page, so a second key did not overwrite the
8
+ * first and a trip to the docs did not lose either. The tab asked before closing only while one
9
+ * was unread, and signing out forgot them all.
10
+ * - One kept the secret out of the list cache, folding only the record into it.
11
+ * - None kept it out of react-query's MUTATION cache. Each `mutationFn` resolved the whole answer,
12
+ * secret included, so `mutation.data` held it, one of them under a comment promising it did not.
13
+ *
14
+ * So `create` takes the secret here and resolves only the record, and the request is the caller's.
15
+ * Forms, permissions, list queries, invalidation and copy feedback stay in the product.
16
+ */
17
+
18
+ /** What your create request resolves: the record your list shows, and the secret beside it. */
19
+ export interface RevealedKey<Record> {
20
+ readonly record: Record;
21
+ readonly key: string;
22
+ }
23
+
24
+ /** The account or workspace changed while a create or revoke was in flight. */
25
+ export class KeyScopeChangedError extends Error {
26
+ readonly operation: "create" | "revoke";
27
+
28
+ constructor(operation: "create" | "revoke") {
29
+ super(
30
+ operation === "create"
31
+ ? "The account or workspace changed before the new key could be shown. If nobody saved it, revoke it from that workspace's keys."
32
+ : "The account or workspace changed while the key was being revoked. Check that workspace's keys to see whether it worked.",
33
+ );
34
+ this.name = "KeyScopeChangedError";
35
+ this.operation = operation;
36
+ }
37
+ }
38
+
39
+ export interface KeyLifecycle<Record> {
40
+ /**
41
+ * Who and where keys are made for: the signed-in account and the workspace, joined into one
42
+ * string, or `null` once signed out. Call it from your auth and workspace subscription, never
43
+ * from the keys page, which may not be mounted. A new scope forgets every unread secret and
44
+ * rejects requests started under the old one, including when the same account signs back in.
45
+ */
46
+ setScope(scope: string | null): void;
47
+ /**
48
+ * Run your create request, keep its secret here, and resolve only the record. Use it as a
49
+ * `mutationFn`: neither the result nor the variables carry the secret, and the reveal still
50
+ * lands when the page that asked has unmounted.
51
+ */
52
+ create(request: () => Promise<RevealedKey<Record>>): Promise<Record>;
53
+ /** Run your revoke request. Only a success, in the same scope, forgets that key's secret. */
54
+ revoke(id: string, request: () => Promise<unknown>): Promise<void>;
55
+ /** The person saved it. Wire this to "Done", never to a copy: a copy can fail. */
56
+ dismiss(id: string): void;
57
+ /** Unread secrets, newest first. */
58
+ getSnapshot(): readonly RevealedKey<Record>[];
59
+ subscribe(listener: () => void): () => void;
60
+ }
61
+
62
+ /**
63
+ * One per app, created at module scope, outside every route. Memory only: never storage, the URL
64
+ * or a query cache, so a reload loses an unread secret, and the tab asks before closing while one
65
+ * is unread. The listener comes and goes with the secrets because a page with a `beforeunload`
66
+ * listener is kept out of some browsers' back-forward cache.
67
+ */
68
+ export function createKeyLifecycle<Record extends { readonly id: string }>(): KeyLifecycle<Record> {
69
+ let revealed: readonly RevealedKey<Record>[] = [];
70
+ let scope: string | null = null;
71
+ let generation = 0;
72
+ const listeners = new Set<() => void>();
73
+
74
+ // Per instance, so two lifecycles never remove each other's prompt.
75
+ function askBeforeLeaving(event: BeforeUnloadEvent): void {
76
+ event.preventDefault();
77
+ // Older Chrome and Safari prompt only when this is set too. The browser picks the words.
78
+ event.returnValue = "";
79
+ }
80
+
81
+ function publish(next: readonly RevealedKey<Record>[]): void {
82
+ const wasUnread = revealed.length > 0;
83
+ revealed = next;
84
+ if (wasUnread !== next.length > 0 && typeof window !== "undefined") {
85
+ if (next.length > 0) window.addEventListener("beforeunload", askBeforeLeaving);
86
+ else window.removeEventListener("beforeunload", askBeforeLeaving);
87
+ }
88
+ for (const listener of listeners) listener();
89
+ }
90
+
91
+ /** Runs `request` under the current scope and refuses an answer that outlived it. */
92
+ async function scoped<T>(operation: "create" | "revoke", request: () => Promise<T>): Promise<T> {
93
+ if (scope === null)
94
+ throw new Error("Call setScope with the signed-in account and workspace first.");
95
+ const started = generation;
96
+ const answer = await request();
97
+ if (started !== generation) throw new KeyScopeChangedError(operation);
98
+ return answer;
99
+ }
100
+
101
+ function dismiss(id: string): void {
102
+ const next = revealed.filter((one) => one.record.id !== id);
103
+ if (next.length !== revealed.length) publish(next);
104
+ }
105
+
106
+ return {
107
+ setScope(next) {
108
+ if (scope === next) return;
109
+ scope = next;
110
+ generation++;
111
+ if (revealed.length > 0) publish([]);
112
+ },
113
+ async create(request) {
114
+ const { record, key } = await scoped("create", request);
115
+ // The record goes on to react-query and often into the list cache. A request that passed
116
+ // the whole answer as the record would put the secret there, which is the bug this exists
117
+ // to end, so say so on the first try instead.
118
+ if (JSON.stringify(record).includes(key))
119
+ throw new Error("The record still holds the secret. Resolve it without the key field.");
120
+ publish([{ record, key }, ...revealed]);
121
+ return record;
122
+ },
123
+ async revoke(id, request) {
124
+ await scoped("revoke", request);
125
+ dismiss(id);
126
+ },
127
+ dismiss,
128
+ getSnapshot: () => revealed,
129
+ subscribe(listener) {
130
+ listeners.add(listener);
131
+ return () => listeners.delete(listener);
132
+ },
133
+ };
134
+ }
135
+
136
+ // The server has no unread secrets, and a prerender must never print one.
137
+ const none: readonly never[] = [];
138
+
139
+ /** Unread secrets, newest first. Unmounting the component forgets nothing. */
140
+ export function useKeyReveals<Record>(
141
+ lifecycle: KeyLifecycle<Record>,
142
+ ): readonly RevealedKey<Record>[] {
143
+ return useSyncExternalStore(lifecycle.subscribe, lifecycle.getSnapshot, () => none);
144
+ }
package/src/oauth.test.ts CHANGED
@@ -1,12 +1,15 @@
1
1
  // @vitest-environment happy-dom
2
2
  import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
3
- import { act, createElement } from "react";
3
+ import { act, createElement, type ChangeEvent } from "react";
4
4
  import { createRoot, type Root } from "react-dom/client";
5
5
  import { afterEach, describe, expect, it, vi } from "vitest";
6
+ import { createApiClient } from "./api-client.ts";
6
7
  import {
8
+ createOAuthConsoleApi,
7
9
  formatUserCode,
8
10
  useConsentRequest,
9
11
  useDeviceApproval,
12
+ useDeviceCodeField,
10
13
  type ConsentApi,
11
14
  type ConsentView,
12
15
  type DeviceApi,
@@ -97,6 +100,17 @@ describe("useConsentRequest", () => {
97
100
  expect(page.current.leaving).toBe(true);
98
101
  });
99
102
 
103
+ it("hands the page whatever its server adds to the view, typed", async () => {
104
+ const api: ConsentApi<string, { spaces: string[] }> = {
105
+ describe: async () => ({ ...VIEW, spaces: ["ws-1", "ws-2"] }),
106
+ approve: async () => ({ ok: true, redirectTo: "https://claude.ai/cb" }),
107
+ };
108
+ const page = mount(() => useConsentRequest(api, "?client_id=x"));
109
+ await settle();
110
+ const { state } = page.current;
111
+ expect(state.status === "ready" ? state.view.spaces : null).toEqual(["ws-1", "ws-2"]);
112
+ });
113
+
100
114
  it("shows a refusal as a state and never redirects on it", async () => {
101
115
  const assign = vi.spyOn(window.location, "assign").mockImplementation(() => {});
102
116
  const page = mount(() =>
@@ -173,14 +187,14 @@ const DEVICE: DeviceView = {
173
187
  expiresAt: "2026-10-16T12:10:00.000Z",
174
188
  };
175
189
 
176
- describe("useDeviceApproval", () => {
177
- function deviceApi(overrides: Partial<DeviceApi> = {}) {
178
- return {
179
- describe: vi.fn<DeviceApi["describe"]>(overrides.describe ?? (async () => DEVICE)),
180
- decide: vi.fn<DeviceApi["decide"]>(overrides.decide ?? (async () => ({ ok: true }))),
181
- };
182
- }
190
+ function deviceApi(overrides: Partial<DeviceApi> = {}) {
191
+ return {
192
+ describe: vi.fn<DeviceApi["describe"]>(overrides.describe ?? (async () => DEVICE)),
193
+ decide: vi.fn<DeviceApi["decide"]>(overrides.decide ?? (async () => ({ ok: true }))),
194
+ };
195
+ }
183
196
 
197
+ describe("useDeviceApproval", () => {
184
198
  it("starts from the link's code, asks the server, and stays approved after the yes", async () => {
185
199
  const api = deviceApi();
186
200
  const page = mount(() => useDeviceApproval(api, "?code=wdjb-mjht"));
@@ -191,7 +205,7 @@ describe("useDeviceApproval", () => {
191
205
 
192
206
  act(() => page.current.approve());
193
207
  await settle();
194
- expect(api.decide).toHaveBeenCalledWith("WDJBMJHT", "approve");
208
+ expect(api.decide).toHaveBeenCalledWith("WDJBMJHT", "approve", undefined);
195
209
  expect(page.current.state).toEqual({ status: "approved" });
196
210
 
197
211
  // A refetch on focus would now hear "unknown code". It must not be asked.
@@ -218,11 +232,13 @@ describe("useDeviceApproval", () => {
218
232
  });
219
233
 
220
234
  it("says no, and shows a code the server does not know as refused", async () => {
221
- const said = mount(() => useDeviceApproval(deviceApi(), "?code=WDJBMJHT"));
235
+ const api = deviceApi();
236
+ const said = mount(() => useDeviceApproval(api, "?code=WDJBMJHT"));
222
237
  await settle();
223
238
  act(() => said.current.deny());
224
239
  await settle();
225
240
  expect(said.current.state).toEqual({ status: "denied" });
241
+ expect(api.decide).toHaveBeenCalledWith("WDJBMJHT", "deny", undefined);
226
242
 
227
243
  const unknown: OAuthRefusal = { ok: false, reason: "unknown-code", message: "expired" };
228
244
  const gone = mount(() =>
@@ -246,6 +262,137 @@ describe("useDeviceApproval", () => {
246
262
  });
247
263
  });
248
264
 
265
+ describe("useDeviceApproval with a choice", () => {
266
+ it("sends the page's choice with the yes, and names the pressed button until it answers", async () => {
267
+ let release!: () => void;
268
+ const decide = vi.fn<DeviceApi<string>["decide"]>(
269
+ () =>
270
+ new Promise((resolve) => {
271
+ release = () => resolve({ ok: true });
272
+ }),
273
+ );
274
+ const page = mount(() =>
275
+ useDeviceApproval({ describe: async () => DEVICE, decide }, "?code=WDJBMJHT"),
276
+ );
277
+ await settle();
278
+ expect(page.current.pending).toBeNull();
279
+
280
+ act(() => page.current.approve("ws-1"));
281
+ await settle();
282
+ expect(decide).toHaveBeenCalledWith("WDJBMJHT", "approve", "ws-1");
283
+ expect(page.current.pending).toBe("approve");
284
+
285
+ release();
286
+ await settle();
287
+ expect(page.current.pending).toBeNull();
288
+ expect(page.current.state).toEqual({ status: "approved" });
289
+ });
290
+ });
291
+
292
+ /** The one part of a change event the field reads. A test-only cast: the hook takes React's own. */
293
+ const changeTo = (value: string) => ({ target: { value } }) as ChangeEvent<HTMLInputElement>;
294
+
295
+ describe("useDeviceCodeField", () => {
296
+ it("wires the field to its status line and keeps the code in the address until decided", async () => {
297
+ window.history.replaceState({ idx: 3 }, "", "/device?from=mail&code=wdjbmjht");
298
+ const api = deviceApi();
299
+ const page = mount(() => {
300
+ const device = useDeviceApproval(api, window.location.search);
301
+ return { device, field: useDeviceCodeField(device) };
302
+ });
303
+ await settle();
304
+ const { inputProps, statusProps } = page.current.field;
305
+ expect(inputProps).toMatchObject({
306
+ value: "WDJB-MJHT",
307
+ autoFocus: false,
308
+ disabled: false,
309
+ "aria-invalid": false,
310
+ "aria-describedby": statusProps.id,
311
+ });
312
+ expect(inputProps.id).not.toBe(statusProps.id);
313
+ expect(window.location.search).toBe("?from=mail&code=WDJB-MJHT");
314
+ // Replaced with the router's own entry state, or its next Back lands on the wrong page.
315
+ expect(window.history.state).toEqual({ idx: 3 });
316
+ expect(window.history.length).toBe(1);
317
+
318
+ act(() => page.current.field.inputProps.onChange(changeTo("bcda")));
319
+ expect(page.current.field.inputProps["aria-invalid"]).toBe(true);
320
+ expect(window.location.search).toBe("?from=mail&code=BCDA");
321
+
322
+ act(() => page.current.field.inputProps.onChange(changeTo("wdjb mjht")));
323
+ await settle();
324
+ act(() => page.current.device.approve());
325
+ await settle();
326
+ expect(page.current.device.state).toEqual({ status: "approved" });
327
+ // The server no longer knows the code: a reload must not ask about it and say it is wrong.
328
+ expect(window.location.search).toBe("?from=mail");
329
+ });
330
+
331
+ it("focuses the field only when it starts empty", () => {
332
+ window.history.replaceState(null, "", "/device");
333
+ const page = mount(() => useDeviceCodeField(useDeviceApproval(deviceApi(), "")));
334
+ expect(page.current.inputProps.autoFocus).toBe(true);
335
+ expect(window.location.search).toBe("");
336
+ });
337
+ });
338
+
339
+ describe("createOAuthConsoleApi", () => {
340
+ function client() {
341
+ const sent: { url: string; method?: string; body?: BodyInit | null }[] = [];
342
+ vi.spyOn(globalThis, "fetch").mockImplementation(async (url, init) => {
343
+ sent.push({ url: String(url), method: init?.method, body: init?.body });
344
+ return new Response(JSON.stringify({ data: { ok: true } }), {
345
+ headers: { "Content-Type": "application/json" },
346
+ });
347
+ });
348
+ const http = createApiClient({
349
+ baseUrl: "https://api.test",
350
+ session: {
351
+ getToken: async () => "token",
352
+ refresh: async () => ({ token: "token", reachedAuth: true }),
353
+ signOut: async () => {},
354
+ },
355
+ onSessionDead: () => {},
356
+ });
357
+ return { http, sent };
358
+ }
359
+
360
+ it("calls the server's console routes through the app's own client", async () => {
361
+ const { http, sent } = client();
362
+ const api = createOAuthConsoleApi<string>(http, "/auth/oauth");
363
+ await api.consent.describe("client_id=x&state=s");
364
+ await api.consent.approve("client_id=x&state=s", "ws-1");
365
+ await api.device.describe("WDJBMJHT");
366
+ await api.device.decide("WDJBMJHT", "approve", "ws-1");
367
+ await api.device.decide("WDJBMJHT", "deny");
368
+ expect(sent).toEqual([
369
+ { url: "https://api.test/auth/oauth/request?client_id=x&state=s", method: "GET" },
370
+ {
371
+ url: "https://api.test/auth/oauth/approve",
372
+ method: "POST",
373
+ body: '{"query":"client_id=x&state=s","choice":"ws-1"}',
374
+ },
375
+ { url: "https://api.test/auth/oauth/device?code=WDJBMJHT", method: "GET" },
376
+ {
377
+ url: "https://api.test/auth/oauth/device",
378
+ method: "POST",
379
+ body: '{"code":"WDJBMJHT","decision":"approve","choice":"ws-1"}',
380
+ },
381
+ {
382
+ url: "https://api.test/auth/oauth/device",
383
+ method: "POST",
384
+ body: '{"code":"WDJBMJHT","decision":"deny"}',
385
+ },
386
+ ]);
387
+ });
388
+
389
+ it("sends no choice when the page has none", async () => {
390
+ const { http, sent } = client();
391
+ await createOAuthConsoleApi(http, "/app/oauth").consent.approve("client_id=x");
392
+ expect(sent[0]?.body).toBe('{"query":"client_id=x"}');
393
+ });
394
+ });
395
+
249
396
  describe("formatUserCode", () => {
250
397
  it("writes what the field shows", () => {
251
398
  expect(formatUserCode("")).toBe("");