@skyphusion/create-prism 1.0.0 → 1.2.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.
Files changed (54) hide show
  1. package/README.md +7 -4
  2. package/index.js +1 -0
  3. package/package.json +1 -1
  4. package/template/CONTRIBUTING.md +18 -3
  5. package/template/MIGRATIONS.md +52 -0
  6. package/template/README.md +50 -16
  7. package/template/docs/legal/INSTANCE-ACCEPTABLE-USE.md +5 -2
  8. package/template/docs/legal/INSTANCE-PRIVACY.md +127 -27
  9. package/template/migrations/0004_csp_reports.sql +58 -0
  10. package/template/migrations/0005_auth_attempts_retention.sql +23 -0
  11. package/template/package.json +6 -6
  12. package/template/public/app.js +42 -7
  13. package/template/public/index.html +24 -9
  14. package/template/public/stt.css +25 -0
  15. package/template/public/stt.html +1 -21
  16. package/template/public/styles.css +49 -0
  17. package/template/public/url-safety.js +66 -0
  18. package/template/schema.sql +64 -0
  19. package/template/src/ai-binding.ts +125 -3
  20. package/template/src/auth.ts +6 -0
  21. package/template/src/csp.ts +253 -0
  22. package/template/src/env.ts +11 -0
  23. package/template/src/gateway-credentials.ts +118 -22
  24. package/template/src/index.ts +79 -2
  25. package/template/src/providers/anthropic.ts +4 -4
  26. package/template/src/providers/openai-image.ts +10 -0
  27. package/template/src/providers/xai.ts +4 -4
  28. package/template/src/rate-limit.ts +26 -0
  29. package/template/src/routes/chat.ts +29 -16
  30. package/template/src/routes/csp-report.ts +163 -0
  31. package/template/src/routes/health.ts +6 -1
  32. package/template/src/routes/prefs.ts +46 -5
  33. package/template/src/routes/rag.ts +53 -15
  34. package/template/src/routes/shared.ts +22 -9
  35. package/template/src/routes/workflow.ts +2 -5
  36. package/template/src/stt-session.ts +16 -0
  37. package/template/src/user-prefs.ts +16 -3
  38. package/template/src/version.ts +18 -0
  39. package/template/tests/ai-binding-rest.test.ts +154 -0
  40. package/template/tests/csp.test.ts +449 -0
  41. package/template/tests/gateway-credentials.test.ts +101 -3
  42. package/template/tests/openai-image.test.ts +21 -1
  43. package/template/tests/public-url-safety.test.ts +360 -0
  44. package/template/tests/rag-metadata-filter.test.ts +135 -0
  45. package/template/tests/rag-retrieval-diagnostic.test.ts +142 -0
  46. package/template/tests/skip-link.test.ts +164 -0
  47. package/template/tests/vectorize-backfill-metadata.test.ts +166 -0
  48. package/template/tests/version.test.ts +47 -0
  49. package/template/tests-integration/auth.test.ts +346 -2
  50. package/template/tests-integration/csp-report.test.ts +232 -0
  51. package/template/tests-integration/pdf-extract.test.ts +71 -0
  52. package/template/tests-integration/worker.test.ts +154 -0
  53. package/template/vitest.workers.config.ts +19 -4
  54. package/template/wrangler.example.toml +45 -2
@@ -2,7 +2,10 @@ import { describe, expect, it } from "vitest";
2
2
  import {
3
3
  buildGatewayStatus,
4
4
  gatewaySource,
5
+ isValidGatewayId,
5
6
  maskSecret,
7
+ normalizeAccountId,
8
+ resolveGateway,
6
9
  resolveGatewayFromParts,
7
10
  } from "../src/gateway-credentials";
8
11
  import type { Env } from "../src/env";
@@ -24,7 +27,7 @@ describe("resolveGatewayFromParts", () => {
24
27
  { gateway_id: "user-gw", cf_aig_token: "user-token" },
25
28
  env({ GATEWAY_ID: "worker-gw", CF_AIG_TOKEN: "worker-token" }),
26
29
  );
27
- expect(resolved).toEqual({ gatewayId: "user-gw", cfAigToken: "user-token" });
30
+ expect(resolved).toEqual({ gatewayId: "user-gw", cfAigToken: "user-token", accountId: null });
28
31
  });
29
32
 
30
33
  it("falls back to worker secrets for unset user fields", () => {
@@ -32,7 +35,7 @@ describe("resolveGatewayFromParts", () => {
32
35
  { gateway_id: "user-gw" },
33
36
  env({ GATEWAY_ID: "worker-gw", CF_AIG_TOKEN: "worker-token" }),
34
37
  );
35
- expect(resolved).toEqual({ gatewayId: "user-gw", cfAigToken: "worker-token" });
38
+ expect(resolved).toEqual({ gatewayId: "user-gw", cfAigToken: "worker-token", accountId: null });
36
39
  });
37
40
  });
38
41
 
@@ -75,7 +78,7 @@ describe("buildGatewayStatus", () => {
75
78
  expect(s.control_plane_key_set).toBe(false);
76
79
  });
77
80
 
78
- it("counts gateway id alone as configured (BYOK path)", () => {
81
+ it("access mode: counts gateway id alone as configured (host-account binding)", () => {
79
82
  const s = buildGatewayStatus({ gateway_id: "my-gw" }, env());
80
83
  expect(s.configured).toBe(true);
81
84
  expect(s.gateway_id).toBe("my-gw");
@@ -100,3 +103,98 @@ describe("buildGatewayStatus", () => {
100
103
  expect(s.control_plane_key_set).toBe(true);
101
104
  });
102
105
  });
106
+
107
+ // v1.1.0: the account id is what routes a call to the user's own gateway. The
108
+ // AI binding can only reach this worker's account, so user credentials without
109
+ // one must never resolve in public mode.
110
+ const ACCT = "0123456789abcdef0123456789abcdef";
111
+ const PUBLIC = { AUTH_MODE: "public" } as Partial<Env>;
112
+
113
+ describe("normalizeAccountId / isValidGatewayId", () => {
114
+ it("accepts 32 hex and lowercases", () => {
115
+ expect(normalizeAccountId(ACCT)).toBe(ACCT);
116
+ expect(normalizeAccountId(` ${ACCT.toUpperCase()} `)).toBe(ACCT);
117
+ });
118
+
119
+ it("rejects anything that is not 32 hex", () => {
120
+ for (const bad of ["", "abc", ACCT + "0", ACCT.slice(1) + "g", "../" + ACCT.slice(3), null, undefined]) {
121
+ expect(normalizeAccountId(bad as string)).toBeNull();
122
+ }
123
+ });
124
+
125
+ it("pins the gateway slug charset (it becomes a URL segment and a header)", () => {
126
+ expect(isValidGatewayId("my-gw_1")).toBe(true);
127
+ for (const bad of ["", "../other", "a/b", "gw?x=1", "-lead", "a".repeat(65), "gw\r\nx: y"]) {
128
+ expect(isValidGatewayId(bad)).toBe(false);
129
+ }
130
+ });
131
+ });
132
+
133
+ describe("resolveGateway (v1.1.0 account scoping)", () => {
134
+ it("public mode: slug + token without an account id is refused, not resolved on our binding", () => {
135
+ const r = resolveGateway({ gateway_id: "gw", cf_aig_token: "tok" }, env(PUBLIC));
136
+ expect(r.creds).toBeNull();
137
+ expect(r.problem).toBe("gateway_account_id_required");
138
+ });
139
+
140
+ it("public mode: a lone slug (the pre-v1.1.0 minimum) is also account_id_required", () => {
141
+ expect(resolveGateway({ gateway_id: "gw" }, env(PUBLIC)).problem).toBe("gateway_account_id_required");
142
+ });
143
+
144
+ it("public mode: nothing saved is plain not-configured", () => {
145
+ expect(resolveGateway(null, env(PUBLIC)).problem).toBe("gateway_not_configured");
146
+ });
147
+
148
+ it("resolves full user credentials to the user's account", () => {
149
+ const r = resolveGateway({ account_id: ACCT, gateway_id: "gw", cf_aig_token: "tok" }, env(PUBLIC));
150
+ expect(r).toEqual({ creds: { gatewayId: "gw", cfAigToken: "tok", accountId: ACCT }, problem: null });
151
+ });
152
+
153
+ it("requires the token once an account id is set (REST needs it for every call)", () => {
154
+ const r = resolveGateway({ account_id: ACCT, gateway_id: "gw" }, env(PUBLIC));
155
+ expect(r.problem).toBe("cf_aig_token_required");
156
+ });
157
+
158
+ it("requires the slug once an account id is set", () => {
159
+ const r = resolveGateway({ account_id: ACCT, cf_aig_token: "tok" }, env(PUBLIC));
160
+ expect(r.problem).toBe("gateway_not_configured");
161
+ });
162
+
163
+ it("access mode: an account-scoped user never borrows worker secrets", () => {
164
+ const r = resolveGateway(
165
+ { account_id: ACCT, gateway_id: "gw" },
166
+ env({ GATEWAY_ID: "worker-gw", CF_AIG_TOKEN: "worker-token" }),
167
+ );
168
+ expect(r.creds).toBeNull();
169
+ expect(r.problem).toBe("cf_aig_token_required");
170
+ });
171
+
172
+ it("an invalid stored account id is treated as absent (public: refused)", () => {
173
+ const r = resolveGateway({ account_id: "nope", gateway_id: "gw", cf_aig_token: "tok" }, env(PUBLIC));
174
+ expect(r.problem).toBe("gateway_account_id_required");
175
+ });
176
+ });
177
+
178
+ describe("buildGatewayStatus (v1.1.0)", () => {
179
+ it("flags a pre-v1.1.0 public user and still echoes their saved slug", () => {
180
+ const s = buildGatewayStatus({ gateway_id: "gw", cf_aig_token: "tok" }, env(PUBLIC));
181
+ expect(s.configured).toBe(false);
182
+ expect(s.account_id_required).toBe(true);
183
+ expect(s.gateway_id).toBe("gw");
184
+ expect(s.cf_aig_token_set).toBe(true);
185
+ expect(s.account_id).toBeNull();
186
+ });
187
+
188
+ it("is configured with all three, account id echoed", () => {
189
+ const s = buildGatewayStatus({ account_id: ACCT, gateway_id: "gw", cf_aig_token: "tok" }, env(PUBLIC));
190
+ expect(s.configured).toBe(true);
191
+ expect(s.account_id_required).toBe(false);
192
+ expect(s.account_id).toBe(ACCT);
193
+ });
194
+
195
+ it("a pcp_ key alone still configures a pre-v1.1.0 user (chat via control plane)", () => {
196
+ const s = buildGatewayStatus({ gateway_id: "gw", control_plane_key: VALID_PCP }, env(PUBLIC));
197
+ expect(s.configured).toBe(true);
198
+ expect(s.account_id_required).toBe(true);
199
+ });
200
+ });
@@ -2,7 +2,8 @@
2
2
  // Network is stubbed; we only assert the request OpenAI receives.
3
3
 
4
4
  import { describe, it, expect, vi, afterEach } from "vitest";
5
- import { generateOpenAIImage } from "../src/providers/openai-image";
5
+ import { generateOpenAIImage, resolveOpenAIImageKey } from "../src/providers/openai-image";
6
+ import type { Env } from "../src/env";
6
7
 
7
8
  afterEach(() => {
8
9
  vi.unstubAllGlobals();
@@ -45,3 +46,22 @@ describe("generateOpenAIImage", () => {
45
46
  .rejects.toThrow(/OpenAI image API 429: billing hard limit/);
46
47
  });
47
48
  });
49
+
50
+ // prism#193 (v1.0.5): the deployer key is off-limits in public mode.
51
+ describe("resolveOpenAIImageKey", () => {
52
+ const envOf = (e: Partial<Env>) => e as Env;
53
+
54
+ it("returns null in public mode even when OPENAI_API_KEY is set", () => {
55
+ expect(resolveOpenAIImageKey(envOf({ AUTH_MODE: "public", OPENAI_API_KEY: "sk-host" }))).toBeNull();
56
+ });
57
+
58
+ it("returns the key in access mode and when AUTH_MODE is unset", () => {
59
+ expect(resolveOpenAIImageKey(envOf({ AUTH_MODE: "access", OPENAI_API_KEY: "sk-host" }))).toBe("sk-host");
60
+ expect(resolveOpenAIImageKey(envOf({ OPENAI_API_KEY: "sk-host" }))).toBe("sk-host");
61
+ });
62
+
63
+ it("returns null when the key is unset or blank", () => {
64
+ expect(resolveOpenAIImageKey(envOf({}))).toBeNull();
65
+ expect(resolveOpenAIImageKey(envOf({ OPENAI_API_KEY: " " }))).toBeNull();
66
+ });
67
+ });
@@ -0,0 +1,360 @@
1
+ // Tests for the SPA link-scheme allowlist (public/url-safety.js) and its
2
+ // wiring into the transcript renderer and the credential modal.
3
+ //
4
+ // TWO KINDS OF ASSERTION LIVE HERE AND THEY ARE NOT EQUALLY STRONG. Said
5
+ // plainly so nobody reads the file as more than it is:
6
+ //
7
+ // 1. BEHAVIOURAL. safeHref is the shipped artifact, read off disk and
8
+ // actually executed against real inputs. These are real tests.
9
+ // 2. WIRING. public/app.js touches the DOM at top level, so it cannot be
10
+ // evaluated outside a browser without adding a DOM harness dependency
11
+ // this project does not carry. The assertions that the renderer and the
12
+ // modal CALL the guard are therefore source-level, and a source
13
+ // assertion proves a string is present, never that the code runs. Every
14
+ // one of them carries a positive control so a matcher that has stopped
15
+ // matching anything fails loudly instead of reading as a pass.
16
+ //
17
+ // The class guard at the bottom is the part that survives us: it enumerates
18
+ // every interpolated href in app.js and fails when a new one appears, so the
19
+ // next unguarded link sink trips a test instead of shipping.
20
+
21
+ import { describe, it, expect } from "vitest";
22
+ import { readFileSync } from "node:fs";
23
+ import { fileURLToPath } from "node:url";
24
+ import { dirname, join } from "node:path";
25
+
26
+ const HERE = dirname(fileURLToPath(import.meta.url));
27
+ const guardSrc = readFileSync(join(HERE, "../public/url-safety.js"), "utf8");
28
+ const appSrc = readFileSync(join(HERE, "../public/app.js"), "utf8");
29
+ const indexSrc = readFileSync(join(HERE, "../public/index.html"), "utf8");
30
+
31
+ // Evaluate the SHIPPED guard file in a fake window, exactly as a browser
32
+ // would run it: an IIFE that assigns onto window. Nothing is reimplemented
33
+ // here, so a change to the shipped file changes what these tests measure.
34
+ function loadGuard(): (raw: unknown) => string {
35
+ const fakeWindow: Record<string, unknown> = {};
36
+ new Function("window", guardSrc)(fakeWindow);
37
+ const fn = fakeWindow.safeHref;
38
+ // Refuse rather than skip. If the guard were renamed or its file emptied,
39
+ // every assertion below would otherwise pass against undefined behaviour
40
+ // and this suite would report green about a guard that is not there.
41
+ if (typeof fn !== "function") {
42
+ throw new Error(
43
+ "public/url-safety.js did not define window.safeHref. The suite cannot " +
44
+ "test a guard it could not load; fix the extractor or the file, do " +
45
+ "not weaken this check.",
46
+ );
47
+ }
48
+ return fn as (raw: unknown) => string;
49
+ }
50
+
51
+ describe("public/url-safety.js loads", () => {
52
+ it("is non-empty and defines window.safeHref", () => {
53
+ expect(guardSrc.length).toBeGreaterThan(0);
54
+ expect(typeof loadGuard()).toBe("function");
55
+ });
56
+ });
57
+
58
+ describe("safeHref refuses non-web schemes", () => {
59
+ const safeHref = loadGuard();
60
+
61
+ // The case the guard exists for. escapeHtml() leaves this string untouched
62
+ // because it contains none of & < > " ' -- which is why escaping alone was
63
+ // never sufficient on an href.
64
+ it("refuses javascript:", () => {
65
+ expect(safeHref("javascript:alert(1)")).toBe("#");
66
+ });
67
+
68
+ // Scheme comparison is case-insensitive in the URL parser. A naive
69
+ // startsWith("javascript:") check passes this one straight through.
70
+ it("refuses javascript: regardless of case", () => {
71
+ expect(safeHref("JavaScript:alert(1)")).toBe("#");
72
+ expect(safeHref("JAVASCRIPT:alert(1)")).toBe("#");
73
+ });
74
+
75
+ // The variant that makes parsing non-negotiable: the URL parser removes
76
+ // embedded tab/LF/CR before resolving the scheme, so this IS javascript:
77
+ // to a browser while being a different string to any line-based matcher.
78
+ it("refuses javascript: with embedded control characters", () => {
79
+ expect(safeHref("java\nscript:alert(1)")).toBe("#");
80
+ expect(safeHref("java\tscript:alert(1)")).toBe("#");
81
+ expect(safeHref("java\rscript:alert(1)")).toBe("#");
82
+ });
83
+
84
+ // Leading whitespace is stripped by the parser for the same reason.
85
+ it("refuses javascript: behind leading whitespace", () => {
86
+ expect(safeHref(" javascript:alert(1)")).toBe("#");
87
+ expect(safeHref("\njavascript:alert(1)")).toBe("#");
88
+ });
89
+
90
+ it("refuses data:, vbscript:, blob: and file:", () => {
91
+ expect(safeHref("data:text/html,<h1>x</h1>")).toBe("#");
92
+ expect(safeHref("vbscript:msgbox(1)")).toBe("#");
93
+ expect(safeHref("blob:https://example.com/abc")).toBe("#");
94
+ expect(safeHref("file:///etc/passwd")).toBe("#");
95
+ });
96
+
97
+ it("refuses empty, blank, and non-string input", () => {
98
+ expect(safeHref("")).toBe("#");
99
+ expect(safeHref(" ")).toBe("#");
100
+ expect(safeHref(null)).toBe("#");
101
+ expect(safeHref(undefined)).toBe("#");
102
+ expect(safeHref(42)).toBe("#");
103
+ expect(safeHref({ toString: () => "https://example.com" })).toBe("#");
104
+ });
105
+
106
+ it("refuses relative references rather than resolving them against a base", () => {
107
+ expect(safeHref("/api/artifact/x")).toBe("#");
108
+ expect(safeHref("example.com")).toBe("#");
109
+ });
110
+ });
111
+
112
+ // THE POSITIVE CONTROL FOR THE WHOLE GUARD. Without this block a safeHref
113
+ // that returned "#" unconditionally would satisfy every assertion above, and
114
+ // a guard that refuses everything reads exactly like a guard that works
115
+ // while silently breaking every real web-search citation in the transcript.
116
+ describe("safeHref permits real web URLs (positive control)", () => {
117
+ const safeHref = loadGuard();
118
+
119
+ it("returns http and https URLs unchanged", () => {
120
+ const cases = [
121
+ "https://en.wikipedia.org/?curid=12345",
122
+ "http://example.com/a/b?c=d#e",
123
+ "https://example.com/path%20with%20escape",
124
+ "https://user:pass@example.com:8443/x",
125
+ ];
126
+ for (const c of cases) expect(safeHref(c)).toBe(c);
127
+ });
128
+
129
+ // Returned unchanged, NOT normalised: the href and the link text rendered
130
+ // beside it must stay byte-identical, and escapeHtml downstream is what
131
+ // handles a quote inside an otherwise legitimate URL.
132
+ it("does not normalise the value it accepts", () => {
133
+ const raw = "https://example.com/a//b/../c?z=1&y=2";
134
+ expect(safeHref(raw)).toBe(raw);
135
+ expect(safeHref(raw)).not.toBe(new URL(raw).href);
136
+ });
137
+ });
138
+
139
+ describe("wiring: the transcript renderer calls the guard", () => {
140
+ // Positive control first: prove the matcher can find the sink at all, so a
141
+ // renamed CSS class or a reflowed template cannot turn a broken search into
142
+ // a silent pass on the assertion below.
143
+ it("the retrieved-web link sink is findable in app.js", () => {
144
+ expect(appSrc).toMatch(/class="rc-text"><a href=/);
145
+ });
146
+
147
+ it("the retrieved-web href is passed through safeHref", () => {
148
+ expect(appSrc).toMatch(/class="rc-text"><a href="\$\{escapeHtml\(window\.safeHref\(/);
149
+ });
150
+
151
+ // Both guards, not one. escapeHtml answers "can this break out of the
152
+ // attribute", safeHref answers "what does this navigate to", and dropping
153
+ // either leaves a real hole.
154
+ it("keeps escapeHtml on the same sink", () => {
155
+ expect(appSrc).toMatch(/href="\$\{escapeHtml\(window\.safeHref\(c\.url\)\)\}"/);
156
+ });
157
+
158
+ it("index.html loads url-safety.js before app.js", () => {
159
+ const guardAt = indexSrc.indexOf("/url-safety.js");
160
+ const appAt = indexSrc.indexOf("/app.js");
161
+ expect(guardAt).toBeGreaterThan(-1);
162
+ expect(appAt).toBeGreaterThan(-1);
163
+ expect(guardAt).toBeLessThan(appAt);
164
+ });
165
+ });
166
+
167
+ describe("wiring: the credential modal clears its inputs on every close path", () => {
168
+ // Extract closeGatewayModal's body rather than searching the whole file,
169
+ // so a clear that happens somewhere else entirely cannot satisfy this.
170
+ function closeGatewayModalBody(): string {
171
+ const m = appSrc.match(/function closeGatewayModal\(\)\s*\{([\s\S]*?)\n\}/);
172
+ if (!m) {
173
+ throw new Error(
174
+ "could not locate closeGatewayModal in public/app.js; the extractor " +
175
+ "is stale and this suite would otherwise assert nothing",
176
+ );
177
+ }
178
+ return m[1];
179
+ }
180
+
181
+ it("the extractor finds a non-empty function body (control)", () => {
182
+ expect(closeGatewayModalBody().trim().length).toBeGreaterThan(0);
183
+ });
184
+
185
+ it("clears the AI Gateway token input", () => {
186
+ expect(closeGatewayModalBody()).toMatch(/gatewayModalToken\.value = ""/);
187
+ });
188
+
189
+ it("clears the control-plane key input", () => {
190
+ expect(closeGatewayModalBody()).toMatch(/gatewayModalCpKey\.value = ""/);
191
+ });
192
+
193
+ // The reason the clear lives in closeGatewayModal rather than at the call
194
+ // sites: every dismissal routes through it (save success, cancel button,
195
+ // backdrop, the X affordance, Escape). Assert that stays true, because the
196
+ // structural property is what makes the fix hold rather than five edits.
197
+ it("every gateway-modal dismissal still routes through closeGatewayModal", () => {
198
+ const closers = appSrc.match(/closeGatewayModal\(\)/g) || [];
199
+ // 1 declaration + save-success + cancel listener + data-modal-close + Escape
200
+ expect(closers.length).toBeGreaterThanOrEqual(4);
201
+ expect(appSrc).toMatch(/modalId === "gateway-modal"\) closeGatewayModal\(\)/);
202
+ expect(appSrc).toMatch(/gatewayModalCancel\.addEventListener\("click", closeGatewayModal\)/);
203
+ expect(appSrc).toMatch(/!gatewayModal\.hidden\) closeGatewayModal\(\)/);
204
+ });
205
+ });
206
+
207
+ // The account-deletion modal is the third credential input and it has the same
208
+ // dismissal shape, established by enumeration rather than by analogy with the
209
+ // gateway modal: all four of its dismissal paths (the backdrop and the close
210
+ // affordance via data-modal-close, Escape, and the cancel button) route through
211
+ // closeAccountDeleteModal, and the success path calls location.reload(), which
212
+ // tears the page down along with the value.
213
+ //
214
+ // Note what is deliberately NOT asserted: the input is not cleared on a FAILED
215
+ // delete. A wrong password leaves the modal open with the value intact so the
216
+ // user can correct it, which is the right behaviour and would be worse if
217
+ // "clear it everywhere" were applied without thinking.
218
+ describe("wiring: the account-deletion modal clears its password on every close path", () => {
219
+ function closeAccountDeleteModalBody(): string {
220
+ const m = appSrc.match(/function closeAccountDeleteModal\(\)\s*\{([\s\S]*?)\n\}/);
221
+ if (!m) {
222
+ throw new Error(
223
+ "could not locate closeAccountDeleteModal in public/app.js; the " +
224
+ "extractor is stale and this suite would otherwise assert nothing",
225
+ );
226
+ }
227
+ return m[1];
228
+ }
229
+
230
+ it("the extractor finds a non-empty function body (control)", () => {
231
+ expect(closeAccountDeleteModalBody().trim().length).toBeGreaterThan(0);
232
+ });
233
+
234
+ it("clears the password input", () => {
235
+ expect(closeAccountDeleteModalBody()).toMatch(/accountDeletePassword\.value = ""/);
236
+ });
237
+
238
+ it("every dismissal still routes through closeAccountDeleteModal", () => {
239
+ expect(appSrc).toMatch(/modalId === "account-delete-modal"\) closeAccountDeleteModal\(\)/);
240
+ expect(appSrc).toMatch(
241
+ /accountDeleteCancel\.addEventListener\("click", closeAccountDeleteModal\)/,
242
+ );
243
+ expect(appSrc).toMatch(/!accountDeleteModal\.hidden\) closeAccountDeleteModal\(\)/);
244
+ });
245
+ });
246
+
247
+ // CLASS GUARD over the credential inputs themselves. Same intent as the href
248
+ // guard below: the point is the NEXT password input somebody adds, not the
249
+ // three that exist today.
250
+ //
251
+ // THE POPULATION IS DELIBERATELY NOT "every password input". Two of the five
252
+ // live on the auth SCREEN rather than in a modal: they have no dismissal path
253
+ // to hang a clear on, and the success path replaces the whole document via
254
+ // location.reload(). Demanding a clear there would fire on correct code, and a
255
+ // guard that refuses on healthy code is one people learn to switch off. So the
256
+ // class is "password inputs inside a dismissable modal", the exclusions are
257
+ // declared by id with the reason attached, and the total is pinned so a sixth
258
+ // input cannot join either group silently.
259
+ describe("class guard: every modal-resident credential input is cleared on close", () => {
260
+ const CLEARED_ON_CLOSE = [
261
+ "gateway-modal-token",
262
+ "gateway-modal-cp-key",
263
+ "account-delete-password",
264
+ ];
265
+ // No dismissal path exists for these; the auth screen is torn down by
266
+ // location.reload() on success, and on failure the value must survive so the
267
+ // user can correct a typo.
268
+ const NOT_MODAL_RESIDENT = ["auth-password", "auth-password2"];
269
+
270
+ const passwordIds = [...indexSrc.matchAll(/<input id="([^"]+)" type="password"/g)].map(
271
+ (m) => m[1],
272
+ );
273
+
274
+ it("the enumerator finds password inputs at all (control)", () => {
275
+ expect(passwordIds.length).toBeGreaterThan(0);
276
+ });
277
+
278
+ it("the population is exactly the five accounted for", () => {
279
+ // A sixth fails here and forces whoever added it into one of the two
280
+ // lists above, with a reason, rather than inheriting neither.
281
+ expect(passwordIds.sort()).toEqual(
282
+ [...CLEARED_ON_CLOSE, ...NOT_MODAL_RESIDENT].sort(),
283
+ );
284
+ });
285
+
286
+ // SCOPED TO THE CLOSE FUNCTION, NOT THE FILE. The whole-file version of this
287
+ // assertion passes today for a reason that has nothing to do with the
288
+ // property: every one of these inputs is ALSO cleared when its modal OPENS,
289
+ // so a substring search over app.js is green whether or not anything clears
290
+ // on close. It is green in both worlds, which makes it no assertion at all.
291
+ // Extract the close function and look only inside it.
292
+ function closeBody(fn: string): string {
293
+ const m = appSrc.match(new RegExp(`function ${fn}\\(\\)\\s*\\{([\\s\\S]*?)\\n\\}`));
294
+ if (!m) {
295
+ throw new Error(`could not extract ${fn} from public/app.js; extractor is stale`);
296
+ }
297
+ return m[1];
298
+ }
299
+
300
+ it("each modal-resident input is cleared INSIDE its own modal's close function", () => {
301
+ const closerFor: Record<string, [string, string]> = {
302
+ "gateway-modal-token": ["closeGatewayModal", "gatewayModalToken"],
303
+ "gateway-modal-cp-key": ["closeGatewayModal", "gatewayModalCpKey"],
304
+ "account-delete-password": ["closeAccountDeleteModal", "accountDeletePassword"],
305
+ };
306
+ for (const id of CLEARED_ON_CLOSE) {
307
+ const entry = closerFor[id];
308
+ expect(entry, `no closer mapped for ${id}`).toBeTruthy();
309
+ const [fn, v] = entry;
310
+ expect(
311
+ closeBody(fn).includes(`${v}.value = ""`),
312
+ `${id} is modal-resident but ${fn} does not clear ${v}`,
313
+ ).toBe(true);
314
+ }
315
+ });
316
+ });
317
+
318
+ // CLASS GUARD. The point of this block is the NEXT link sink, not this one.
319
+ // Enumerate every interpolated href in app.js and require each to be
320
+ // accounted for; a new one fails here and forces whoever adds it to say
321
+ // which category it is in, rather than inheriting escaping-only by default.
322
+ describe("class guard: every interpolated href in app.js is accounted for", () => {
323
+ // Deliberately a flat character class rather than a nested quantifier that
324
+ // would tolerate braces inside the expression. The permissive version of
325
+ // this pattern nests a quantified group inside another quantifier, which
326
+ // backtracks exponentially on a crafted input -- and a test-only matcher is
327
+ // still a matcher, so it gets the same treatment as shipped code.
328
+ //
329
+ // The narrower pattern costs nothing today: none of the four interpolations
330
+ // contains a brace. If one ever does, this captures a truncated expression
331
+ // that matches neither accounted-for category, so the guard fails LOUD and
332
+ // names the expression rather than silently waving the new sink through.
333
+ // That is the correct failure direction for a guard whose whole job is to
334
+ // refuse things it does not recognise.
335
+ const hrefExprs = [...appSrc.matchAll(/href="\$\{([^}]*)\}"/g)].map((m) => m[1]);
336
+
337
+ it("the enumerator finds the hrefs it is supposed to (control)", () => {
338
+ // A zero here means the matcher broke, not that the file is clean.
339
+ expect(hrefExprs.length).toBeGreaterThan(0);
340
+ });
341
+
342
+ it("finds exactly the four known interpolated hrefs", () => {
343
+ // Three artifact download links plus the one web-search citation. Raise
344
+ // this number only together with a decision about the new sink.
345
+ expect(hrefExprs.length).toBe(4);
346
+ });
347
+
348
+ it("each is either an internally-constructed artifact URL or scheme-guarded", () => {
349
+ for (const expr of hrefExprs) {
350
+ const isArtifact = /escapeHtml\(url\)/.test(expr);
351
+ const isGuarded = /window\.safeHref\(/.test(expr);
352
+ expect(
353
+ isArtifact || isGuarded,
354
+ `unaccounted href interpolation: \${${expr}} -- an href built from a ` +
355
+ "value this worker did not construct needs window.safeHref, not " +
356
+ "escapeHtml alone",
357
+ ).toBe(true);
358
+ }
359
+ });
360
+ });
@@ -0,0 +1,135 @@
1
+ // VEC_METADATA_FILTER: retrieval filtered by user in Vectorize itself (skyphusion-labs/fleet-chezmoi#1636).
2
+ //
3
+ // THE DEFECT. With a global Vectorize query, a caller holding a small share of a large index can get a
4
+ // top-K made entirely of other users' vectors. The D1 join (the tenant scope) drops all of them, and the
5
+ // caller sees nothing even though their own document matches. The flag filters the query on user_email.
6
+ //
7
+ // The fake index below HONOURS the filter the way Vectorize does: unfiltered, it returns the global
8
+ // top-K; filtered, only vectors whose metadata matches. The fake D1 honours the join's user_email
9
+ // scope. Only env.AI / env.VEC / env.DB are stubbed; retrieveContext is the shipped function.
10
+
11
+ import { describe, it, expect, vi, afterEach } from "vitest";
12
+ import { retrieveContext, vecMetadataFilterOn } from "../src/routes/rag";
13
+ import type { Env } from "../src/env";
14
+
15
+ const CALLER = "usr_0123456789abcdef01234567";
16
+ const STRANGER = "usr_fedcba9876543210fedcba98";
17
+
18
+ interface StoredVector {
19
+ id: string;
20
+ score: number;
21
+ owner: string;
22
+ }
23
+
24
+ /** Five foreign vectors scoring above the caller's one: the crowding shape. */
25
+ const CROWDED: StoredVector[] = [
26
+ ...[0, 1, 2, 3, 4].map((i) => ({ id: `${STRANGER}:9:${i}`, score: 0.95 - i * 0.01, owner: STRANGER })),
27
+ { id: `${CALLER}:1:0`, score: 0.6, owner: CALLER },
28
+ ];
29
+
30
+ type QueryOpts = { topK: number; filter?: Record<string, string> };
31
+
32
+ function fakeEnv(index: StoredVector[], flag?: string) {
33
+ const queries: QueryOpts[] = [];
34
+ const joinSql: string[] = [];
35
+ const env = {
36
+ VEC_METADATA_FILTER: flag,
37
+ AI: { run: async () => ({ shape: [1, 3], data: [[0.1, 0.2, 0.3]] }) },
38
+ VEC: {
39
+ query: async (_v: number[], opts: QueryOpts) => {
40
+ queries.push(opts);
41
+ const pool = opts.filter ? index.filter((v) => v.owner === opts.filter!.user_email) : index;
42
+ const top = [...pool].sort((a, b) => b.score - a.score).slice(0, opts.topK);
43
+ return { matches: top.map((v) => ({ id: v.id, score: v.score })) };
44
+ },
45
+ },
46
+ DB: {
47
+ prepare(sql: string) {
48
+ const isPrefs = sql.includes("user_prefs");
49
+ if (!isPrefs) joinSql.push(sql);
50
+ return {
51
+ bind(...args: unknown[]) {
52
+ return {
53
+ async first() {
54
+ return isPrefs ? { prefs_json: JSON.stringify({ gateway_id: "gw" }) } : null;
55
+ },
56
+ async all() {
57
+ // The tenant scope: only the bound user_email's own vectors join.
58
+ const user = args[0] as string;
59
+ const ids = args.slice(1) as string[];
60
+ const rows = index
61
+ .filter((v) => v.owner === user && ids.includes(v.id))
62
+ .map((v) => ({ document_id: 1, chunk_index: 0, text: "own text", vector_id: v.id, filename: "own.txt", page: null, sheet: null }));
63
+ return { results: rows };
64
+ },
65
+ };
66
+ },
67
+ };
68
+ },
69
+ },
70
+ } as unknown as Env;
71
+ return { env, queries, joinSql };
72
+ }
73
+
74
+ afterEach(() => vi.restoreAllMocks());
75
+
76
+ describe("vecMetadataFilterOn", () => {
77
+ it("is on only for an explicit on / 1 / true", () => {
78
+ for (const v of ["on", "1", "true", " ON "]) expect(vecMetadataFilterOn({ VEC_METADATA_FILTER: v }), v).toBe(true);
79
+ for (const v of [undefined, "", "off", "0", "yes", "false"]) expect(vecMetadataFilterOn({ VEC_METADATA_FILTER: v }), String(v)).toBe(false);
80
+ });
81
+ });
82
+
83
+ describe("retrieveContext with VEC_METADATA_FILTER", () => {
84
+ it("OFF (the default): the query is global, and the D1 join still scopes", async () => {
85
+ vi.spyOn(console, "warn").mockImplementation(() => {});
86
+ const { env, queries, joinSql } = fakeEnv(CROWDED);
87
+ await retrieveContext(env, CALLER, "q");
88
+ expect(queries).toHaveLength(1);
89
+ expect(queries[0].filter).toBeUndefined();
90
+ expect(joinSql.some((s) => s.includes("c.user_email = ?"))).toBe(true);
91
+ });
92
+
93
+ it("ON: the query carries filter { user_email: caller }, and the D1 join still scopes", async () => {
94
+ const { env, queries, joinSql } = fakeEnv(CROWDED, "on");
95
+ await retrieveContext(env, CALLER, "q");
96
+ expect(queries[0].filter).toEqual({ user_email: CALLER });
97
+ expect(joinSql.some((s) => s.includes("c.user_email = ?"))).toBe(true);
98
+ });
99
+
100
+ it("THE DEFECT, OFF: a crowded index gives the caller nothing although their own vector matches", async () => {
101
+ vi.spyOn(console, "warn").mockImplementation(() => {});
102
+ const { env } = fakeEnv(CROWDED);
103
+ const { chunks } = await retrieveContext(env, CALLER, "q");
104
+ expect(chunks).toEqual([]);
105
+ });
106
+
107
+ it("POSITIVE, ON: the same crowded index returns the caller's own chunk", async () => {
108
+ const { env } = fakeEnv(CROWDED, "on");
109
+ const { chunks } = await retrieveContext(env, CALLER, "q");
110
+ expect(chunks.map((c) => c.filename)).toEqual(["own.txt"]);
111
+ });
112
+
113
+ it("NEGATIVE CONTROL, ON: a caller who owns nothing gets nothing, and no foreign vector is returned", async () => {
114
+ const nobody = "usr_000000000000000000000000";
115
+ const { env, queries } = fakeEnv(CROWDED, "on");
116
+ const query = env.VEC.query.bind(env.VEC);
117
+ let seen: { id: string }[] = [];
118
+ (env.VEC as unknown as { query: typeof query }).query = async (v, o) => {
119
+ const r = await query(v, o);
120
+ seen = r.matches;
121
+ return r;
122
+ };
123
+ const { chunks } = await retrieveContext(env, nobody, "q");
124
+ expect(queries[0].filter).toEqual({ user_email: nobody });
125
+ expect(seen).toEqual([]);
126
+ expect(chunks).toEqual([]);
127
+ });
128
+
129
+ it("ON with a project: the overfetch stays 3x topK and is drawn from the caller's own vectors", async () => {
130
+ vi.spyOn(console, "warn").mockImplementation(() => {});
131
+ const { env, queries } = fakeEnv(CROWDED, "on");
132
+ await retrieveContext(env, CALLER, "q", 5, 42);
133
+ expect(queries[0]).toEqual({ topK: 15, filter: { user_email: CALLER } });
134
+ });
135
+ });