@gusnips/react 0.9.29 → 0.9.30

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/README.md CHANGED
@@ -743,6 +743,73 @@ and send a stranger the link, and that sentence is the only guard against it. On
743
743
  page stays decided: it never asks the server again, because the server no longer knows the code,
744
744
  and asking on the next focus would tell someone who just said yes that their code is wrong.
745
745
 
746
+ ## A new API key, shown once
747
+
748
+ ```ts
749
+ import { createKeyLifecycle } from "@gusnips/react/keys";
750
+
751
+ export const apiKeys = createKeyLifecycle<ApiKey>();
752
+ ```
753
+
754
+ Make it once, beside your query client, outside every route. It keeps each new key's secret in
755
+ memory until the person presses Done. A second key never replaces the first, and a trip to your
756
+ docs and back loses neither.
757
+
758
+ Tell it who is signed in, and where, from the code that already hears about sign-in and workspace
759
+ changes:
760
+
761
+ ```ts
762
+ apiKeys.setScope(user ? `${user.id}:${workspaceId}` : null);
763
+ ```
764
+
765
+ A new scope forgets every unread secret. A request started before the change rejects with
766
+ `KeyScopeChangedError` instead of showing its secret, even when the same account signs straight
767
+ back in. Build the scope from ids, never from an access token: a token refresh is not a new person.
768
+
769
+ Send your create request through it:
770
+
771
+ ```ts
772
+ const create = useMutation({
773
+ mutationFn: (name: string) =>
774
+ apiKeys.create(async () => {
775
+ const { key, ...record } = await api.post<NewApiKey>("/keys", { name });
776
+ return { record, key };
777
+ }),
778
+ onSuccess: () => queryClient.invalidateQueries({ queryKey: ["keys"] }),
779
+ });
780
+ ```
781
+
782
+ `create` keeps the secret and resolves only the record. In three products we read, `mutation.data`
783
+ held the whole answer, so the secret stayed in react-query's cache for as long as the cache kept
784
+ the mutation. A record that still contains the secret is refused, so that mistake shows on the
785
+ first try. The reveal lands even when the page that asked has unmounted.
786
+
787
+ Show what is unread, and let the person say they saved it:
788
+
789
+ ```tsx
790
+ const reveals = useKeyReveals(apiKeys);
791
+
792
+ return reveals.map(({ record, key }) => (
793
+ <KeyReveal key={record.id} secret={key} onDone={() => apiKeys.dismiss(record.id)} />
794
+ ));
795
+ ```
796
+
797
+ Copy with `useCopy`, and keep Done separate: a copy can fail, and the secret must stay on screen
798
+ when it does. Revoke goes through the same object:
799
+
800
+ ```ts
801
+ mutationFn: (id: string) => apiKeys.revoke(id, () => api.delete(`/keys/${id}`)),
802
+ ```
803
+
804
+ Only a successful revoke forgets that key's secret. A failed one leaves it on screen, because the
805
+ key still works.
806
+
807
+ Nothing is written to storage or the URL, so a reload loses an unread secret. While one is unread
808
+ the tab asks before it closes, and the listener goes away with the last one, because a page with
809
+ a `beforeunload` listener is kept out of some browsers' back-forward cache. Draw the list through
810
+ `queryView`, so a failed refresh keeps the rows instead of saying there are no keys. Forms,
811
+ permissions, plan limits and every word on the page stay yours.
812
+
746
813
  ## Also here
747
814
 
748
815
  `ErrorBoundary`, an SSE reader split into a platform-free parser and a stream wrapper,
@@ -825,6 +892,7 @@ lives behind a subpath, so you install a dependency only if you import the thing
825
892
  | `@gusnips/react/theme` | `createTheme`, `startTheme` | react |
826
893
  | `@gusnips/react/commands` | slash matching and `useSlashCommands` | react |
827
894
  | `@gusnips/react/oauth` | `useConsentRequest`, `useDeviceApproval` | @tanstack/react-query |
895
+ | `@gusnips/react/keys` | `createKeyLifecycle`, `useKeyReveals` | react |
828
896
 
829
897
  The rule behind that table: **a peer marked optional must not be reachable from the main entry
830
898
  point.** An optional peer the barrel imports anyway is not optional: it is a required one whose
package/dist/keys.d.ts ADDED
@@ -0,0 +1,58 @@
1
+ /**
2
+ * A new API key, the one time the server sends its secret. Three products wrote this flow, and
3
+ * each knew one part the others missed:
4
+ *
5
+ * - One kept unread secrets in a list outside the page, so a second key did not overwrite the
6
+ * first and a trip to the docs did not lose either. The tab asked before closing only while one
7
+ * was unread, and signing out forgot them all.
8
+ * - One kept the secret out of the list cache, folding only the record into it.
9
+ * - None kept it out of react-query's MUTATION cache. Each `mutationFn` resolved the whole answer,
10
+ * secret included, so `mutation.data` held it, one of them under a comment promising it did not.
11
+ *
12
+ * So `create` takes the secret here and resolves only the record, and the request is the caller's.
13
+ * Forms, permissions, list queries, invalidation and copy feedback stay in the product.
14
+ */
15
+ /** What your create request resolves: the record your list shows, and the secret beside it. */
16
+ export interface RevealedKey<Record> {
17
+ readonly record: Record;
18
+ readonly key: string;
19
+ }
20
+ /** The account or workspace changed while a create or revoke was in flight. */
21
+ export declare class KeyScopeChangedError extends Error {
22
+ readonly operation: "create" | "revoke";
23
+ constructor(operation: "create" | "revoke");
24
+ }
25
+ export interface KeyLifecycle<Record> {
26
+ /**
27
+ * Who and where keys are made for: the signed-in account and the workspace, joined into one
28
+ * string, or `null` once signed out. Call it from your auth and workspace subscription, never
29
+ * from the keys page, which may not be mounted. A new scope forgets every unread secret and
30
+ * rejects requests started under the old one, including when the same account signs back in.
31
+ */
32
+ setScope(scope: string | null): void;
33
+ /**
34
+ * Run your create request, keep its secret here, and resolve only the record. Use it as a
35
+ * `mutationFn`: neither the result nor the variables carry the secret, and the reveal still
36
+ * lands when the page that asked has unmounted.
37
+ */
38
+ create(request: () => Promise<RevealedKey<Record>>): Promise<Record>;
39
+ /** Run your revoke request. Only a success, in the same scope, forgets that key's secret. */
40
+ revoke(id: string, request: () => Promise<unknown>): Promise<void>;
41
+ /** The person saved it. Wire this to "Done", never to a copy: a copy can fail. */
42
+ dismiss(id: string): void;
43
+ /** Unread secrets, newest first. */
44
+ getSnapshot(): readonly RevealedKey<Record>[];
45
+ subscribe(listener: () => void): () => void;
46
+ }
47
+ /**
48
+ * One per app, created at module scope, outside every route. Memory only: never storage, the URL
49
+ * or a query cache, so a reload loses an unread secret, and the tab asks before closing while one
50
+ * is unread. The listener comes and goes with the secrets because a page with a `beforeunload`
51
+ * listener is kept out of some browsers' back-forward cache.
52
+ */
53
+ export declare function createKeyLifecycle<Record extends {
54
+ readonly id: string;
55
+ }>(): KeyLifecycle<Record>;
56
+ /** Unread secrets, newest first. Unmounting the component forgets nothing. */
57
+ export declare function useKeyReveals<Record>(lifecycle: KeyLifec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C9E,wBAAgB,aAAa,CAAC,MAAM,EAClC,SAAS,EAAE,YAAY,CAAC,MAAM,CAAC,GAC9B,SAAS,WAAW,CAAC,MAAM,CAAC,EAAE,CAEhC"}
package/dist/keys.js ADDED
@@ -0,0 +1,94 @@
1
+ import { useSyncExternalStore } from "react";
2
+ /** The account or workspace changed while a create or revoke was in flight. */
3
+ export class KeyScopeChangedError extends Error {
4
+ operation;
5
+ constructor(operation) {
6
+ super(operation === "create"
7
+ ? "The account or workspace changed before the new key could be shown. If nobody saved it, revoke it from that workspace's keys."
8
+ : "The account or workspace changed while the key was being revoked. Check that workspace's keys to see whether it worked.");
9
+ this.name = "KeyScopeChangedError";
10
+ this.operation = operation;
11
+ }
12
+ }
13
+ /**
14
+ * One per app, created at module scope, outside every route. Memory only: never storage, the URL
15
+ * or a query cache, so a reload loses an unread secret, and the tab asks before closing while one
16
+ * is unread. The listener comes and goes with the secrets because a page with a `beforeunload`
17
+ * listener is kept out of some browsers' back-forward cache.
18
+ */
19
+ export function createKeyLifecycle() {
20
+ let revealed = [];
21
+ let scope = null;
22
+ let generation = 0;
23
+ const listeners = new Set();
24
+ // Per instance, so two lifecycles never remove each other's prompt.
25
+ function askBeforeLeaving(event) {
26
+ event.preventDefault();
27
+ // Older Chrome and Safari prompt only when this is set too. The browser picks the words.
28
+ event.returnValue = "";
29
+ }
30
+ function publish(next) {
31
+ const wasUnread = revealed.length > 0;
32
+ revealed = next;
33
+ if (wasUnread !== next.length > 0 && typeof window !== "undefined") {
34
+ if (next.length > 0)
35
+ window.addEventListener("beforeunload", askBeforeLeaving);
36
+ else
37
+ window.removeEventListener("beforeunload", askBeforeLeaving);
38
+ }
39
+ for (const listener of listeners)
40
+ listener();
41
+ }
42
+ /** Runs `request` under the current scope and refuses an answer that outlived it. */
43
+ async function scoped(operation, request) {
44
+ if (scope === null)
45
+ throw new Error("Call setScope with the signed-in account and workspace first.");
46
+ const started = generation;
47
+ const answer = await request();
48
+ if (started !== generation)
49
+ throw new KeyScopeChangedError(operation);
50
+ return answer;
51
+ }
52
+ function dismiss(id) {
53
+ const next = revealed.filter((one) => one.record.id !== id);
54
+ if (next.length !== revealed.length)
55
+ publish(next);
56
+ }
57
+ return {
58
+ setScope(next) {
59
+ if (scope === next)
60
+ return;
61
+ scope = next;
62
+ generation++;
63
+ if (revealed.length > 0)
64
+ publish([]);
65
+ },
66
+ async create(request) {
67
+ const { record, key } = await scoped("create", request);
68
+ // The record goes on to react-query and often into the list cache. A request that passed
69
+ // the whole answer as the record would put the secret there, which is the bug this exists
70
+ // to end, so say so on the first try instead.
71
+ if (JSON.stringify(record).includes(key))
72
+ throw new Error("The record still holds the secret. Resolve it without the key field.");
73
+ publish([{ record, key }, ...revealed]);
74
+ return record;
75
+ },
76
+ async revoke(id, request) {
77
+ await scoped("revoke", request);
78
+ dismiss(id);
79
+ },
80
+ dismiss,
81
+ getSnapshot: () => revealed,
82
+ subscribe(listener) {
83
+ listeners.add(listener);
84
+ return () => listeners.delete(listener);
85
+ },
86
+ };
87
+ }
88
+ // The server has no unread secrets, and a prerender must never print one.
89
+ const none = [];
90
+ /** Unread secrets, newest first. Unmounting the component forgets nothing. */
91
+ export function useKeyReveals(lifecycle) {
92
+ return useSyncExternalStore(lifecycle.subscribe, lifecycle.getSnapshot, () => none);
93
+ }
94
+ //# sourceMappingURL=keys.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"keys.js","sourceRoot":"","sources":["../src/keys.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,oBAAoB,EAAE,MAAM,OAAO,CAAC;AAuB7C,+EAA+E;AAC/E,MAAM,OAAO,oBAAqB,SAAQ,KAAK;IACpC,SAAS,CAAsB;IAExC,YAAY,SAA8B;QACxC,KAAK,CACH,SAAS,KAAK,QAAQ;YACpB,CAAC,CAAC,+HAA+H;YACjI,CAAC,CAAC,yHAAyH,CAC9H,CAAC;QACF,IAAI,CAAC,IAAI,GAAG,sBAAsB,CAAC;QACnC,IAAI,CAAC,SAAS,G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AAC,MAAM,CAAC,QAAQ,CAAC,CAAC;QAC1C,CAAC;KACF,CAAC;AACJ,CAAC;AAED,0EAA0E;AAC1E,MAAM,IAAI,GAAqB,EAAE,CAAC;AAElC,8EAA8E;AAC9E,MAAM,UAAU,aAAa,CAC3B,SAA+B;IAE/B,OAAO,oBAAoB,CAAC,SAAS,CAAC,SAAS,EAAE,SAAS,CAAC,WAAW,EAAE,GAAG,EAAE,CAAC,IAAI,CAAC,CAAC;AACtF,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@gusnips/react",
3
- "version": "0.9.29",
3
+ "version": "0.9.30",
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",
@@ -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",
@@ -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
+ }
@@ -1,10 +1,15 @@
1
1
  // @vitest-environment happy-dom
2
2
  import { createClient } from "@supabase/supabase-js";
3
- import { afterEach, describe, expect, it } from "vitest";
3
+ import { Window } from "happy-dom";
4
+ import { afterEach, describe, expect, it, vi } from "vitest";
4
5
  import { supabaseAuthStorage } from "./supabase-session.ts";
5
6
 
6
7
  // A real browser `localStorage` and a real auth-js, so what is measured is the choice supabase-js
7
8
  // makes for itself, not this file's idea of it. The Node tests beside this one can only stub it.
9
+ // Node 26 has a `localStorage` of its own, `undefined` without `--localstorage-file`, and vitest
10
+ // leaves it in front of happy-dom's (`window` is the global, so it reads Node's too). A browser
11
+ // has one, so take a happy-dom window's and put it where a browser keeps it.
12
+ vi.stubGlobal("localStorage", new Window().localStorage);
8
13
  const PROJECT_URL = "https://abcdefghijklmnop.supabase.co";
9
14
  const USER_ID = "11111111-1111-4111-8111-111111111111";
10
15