@skyphusion/create-prism 1.0.0 → 1.0.4
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 +1 -1
- package/template/migrations/0004_csp_reports.sql +58 -0
- package/template/package.json +4 -4
- package/template/public/app.js +23 -1
- package/template/public/index.html +2 -1
- package/template/public/stt.css +25 -0
- package/template/public/stt.html +1 -21
- package/template/public/styles.css +11 -0
- package/template/public/url-safety.js +66 -0
- package/template/schema.sql +58 -0
- package/template/src/csp.ts +253 -0
- package/template/src/index.ts +77 -2
- package/template/src/routes/chat.ts +24 -13
- package/template/src/routes/csp-report.ts +163 -0
- package/template/src/routes/health.ts +6 -1
- package/template/src/routes/rag.ts +25 -3
- package/template/src/stt-session.ts +16 -0
- package/template/src/version.ts +18 -0
- package/template/tests/csp.test.ts +444 -0
- package/template/tests/public-url-safety.test.ts +360 -0
- package/template/tests/rag-retrieval-diagnostic.test.ts +142 -0
- package/template/tests/version.test.ts +47 -0
- package/template/tests-integration/csp-report.test.ts +232 -0
- package/template/tests-integration/worker.test.ts +154 -0
- package/template/vitest.workers.config.ts +19 -4
- package/template/wrangler.example.toml +33 -0
|
@@ -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,142 @@
|
|
|
1
|
+
// The zero-join retrieval diagnostic (skyphusion-labs/fleet-chezmoi#1608).
|
|
2
|
+
//
|
|
3
|
+
// retrieveContext queries Vectorize globally -- no metadata filter, because the
|
|
4
|
+
// tenant scope is the D1 join (see the design note above retrieveContext, which
|
|
5
|
+
// is deliberate: it avoids requiring a Vectorize metadata index). So the raw
|
|
6
|
+
// Vectorize result legitimately contains vector ids belonging to other tenants,
|
|
7
|
+
// and vector ids are minted as `${userEmail}:${docId}:${chunkIndex}`.
|
|
8
|
+
//
|
|
9
|
+
// That makes the zero-join branch the one place where foreign identifiers are
|
|
10
|
+
// in scope next to a string that gets returned to the caller. These assert the
|
|
11
|
+
// split: the operator log keeps the full diagnostic, the client half carries
|
|
12
|
+
// nothing derived from the shared index.
|
|
13
|
+
//
|
|
14
|
+
// Only env.AI / env.VEC / env.DB are stubbed -- the un-stubbable seams.
|
|
15
|
+
// Everything between them is the real shipped retrieveContext.
|
|
16
|
+
|
|
17
|
+
import { describe, it, expect, vi, afterEach } from "vitest";
|
|
18
|
+
import { retrieveContext } from "../src/routes/rag";
|
|
19
|
+
import type { Env } from "../src/env";
|
|
20
|
+
|
|
21
|
+
const CALLER = "alice@example.com";
|
|
22
|
+
const FOREIGN_IDS = [
|
|
23
|
+
"victim@example.com:7:0",
|
|
24
|
+
"usr_0123456789abcdef01234567:12:3",
|
|
25
|
+
"bob@example.com:99:2",
|
|
26
|
+
];
|
|
27
|
+
|
|
28
|
+
// A caller-visible string must contain none of these substrings. Kept as the
|
|
29
|
+
// identity half of the vector id rather than the whole id, so the assertion
|
|
30
|
+
// still fires if only the identity survives some future re-formatting.
|
|
31
|
+
const FOREIGN_IDENTITIES = ["victim@example.com", "usr_0123456789abcdef01234567", "bob@example.com"];
|
|
32
|
+
|
|
33
|
+
function fakeEnv(): Env {
|
|
34
|
+
return {
|
|
35
|
+
AI: {
|
|
36
|
+
run: async () => ({ shape: [1, 3], data: [[0.1, 0.2, 0.3]] }),
|
|
37
|
+
},
|
|
38
|
+
VEC: {
|
|
39
|
+
query: async () => ({
|
|
40
|
+
matches: FOREIGN_IDS.map((id, i) => ({ id, score: 0.9 - i * 0.01 })),
|
|
41
|
+
}),
|
|
42
|
+
},
|
|
43
|
+
DB: {
|
|
44
|
+
prepare(sql: string) {
|
|
45
|
+
const isPrefs = sql.includes("user_prefs");
|
|
46
|
+
return {
|
|
47
|
+
bind() {
|
|
48
|
+
return {
|
|
49
|
+
// loadUserPrefs -> gateway credentials, so embedBatch proceeds.
|
|
50
|
+
async first() {
|
|
51
|
+
return isPrefs ? { prefs_json: JSON.stringify({ gateway_id: "alice-gw" }) } : null;
|
|
52
|
+
},
|
|
53
|
+
// The tenant-scoped join finds none of the foreign vectors,
|
|
54
|
+
// which is the branch under test.
|
|
55
|
+
async all() {
|
|
56
|
+
return { results: [] };
|
|
57
|
+
},
|
|
58
|
+
};
|
|
59
|
+
},
|
|
60
|
+
};
|
|
61
|
+
},
|
|
62
|
+
},
|
|
63
|
+
} as unknown as Env;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
afterEach(() => {
|
|
67
|
+
vi.restoreAllMocks();
|
|
68
|
+
});
|
|
69
|
+
|
|
70
|
+
describe("retrieveContext zero-join diagnostic", () => {
|
|
71
|
+
it("returns a caller-visible message carrying no foreign identity", async () => {
|
|
72
|
+
const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
|
|
73
|
+
const { chunks, error } = await retrieveContext(fakeEnv(), CALLER, "quarterly revenue");
|
|
74
|
+
|
|
75
|
+
expect(chunks).toEqual([]);
|
|
76
|
+
|
|
77
|
+
// ORDER IS LOAD-BEARING. Do not swap these two blocks.
|
|
78
|
+
//
|
|
79
|
+
// The disclosure assertion runs FIRST so that it is the assertion that
|
|
80
|
+
// fires when the defect is present. With the pin first, driving the
|
|
81
|
+
// pre-fix code (888e6bb reversed) reddened this test on the pin's
|
|
82
|
+
// `toBe` line and short-circuited, so the loop below never executed:
|
|
83
|
+
// the suite detected the defect, but the assertion that names it had
|
|
84
|
+
// never been shown capable of failing.
|
|
85
|
+
for (const identity of FOREIGN_IDENTITIES) {
|
|
86
|
+
expect(error).not.toContain(identity);
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
// Pin the exact branch SECOND. This is the anti-vacuity control: on any
|
|
90
|
+
// earlier failure path ("embed failed: ...", "vectorize query failed:
|
|
91
|
+
// ...") the loop above passes for free, because those strings are also
|
|
92
|
+
// free of foreign identities and are not the case under test. Running it
|
|
93
|
+
// after preserves that guarantee while leaving the loop reachable.
|
|
94
|
+
expect(error).toBe("No indexed documents matched the query.");
|
|
95
|
+
|
|
96
|
+
// Control: the harness really did feed foreign ids in, so the absence
|
|
97
|
+
// above is a redaction rather than an empty input.
|
|
98
|
+
expect(warn).toHaveBeenCalled();
|
|
99
|
+
const logged = warn.mock.calls.map((c) => c.join(" ")).join("\n");
|
|
100
|
+
for (const identity of FOREIGN_IDENTITIES) {
|
|
101
|
+
expect(logged).toContain(identity);
|
|
102
|
+
}
|
|
103
|
+
});
|
|
104
|
+
|
|
105
|
+
it("keeps the operator diagnostic intact, not deleted", async () => {
|
|
106
|
+
// The diagnostic is the thing that makes a silent retrieval failure
|
|
107
|
+
// debuggable. The fix is a split, not a removal, and this is what would
|
|
108
|
+
// fail if a later cleanup "simplified" the console.warn away.
|
|
109
|
+
const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
|
|
110
|
+
await retrieveContext(fakeEnv(), CALLER, "quarterly revenue");
|
|
111
|
+
|
|
112
|
+
const logged = warn.mock.calls.map((c) => c.join(" ")).join("\n");
|
|
113
|
+
expect(logged).toContain("sample vector_ids=[");
|
|
114
|
+
expect(logged).toContain("D1 join returned 0");
|
|
115
|
+
expect(logged).toContain(CALLER);
|
|
116
|
+
});
|
|
117
|
+
|
|
118
|
+
it("scopes the project-filtered message the same way", async () => {
|
|
119
|
+
const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
|
|
120
|
+
const { error } = await retrieveContext(fakeEnv(), CALLER, "quarterly revenue", 5, 42);
|
|
121
|
+
|
|
122
|
+
// Same ordering rule as above: disclosure assertion first so it is
|
|
123
|
+
// reachable under the defect, branch pin second as the anti-vacuity
|
|
124
|
+
// control.
|
|
125
|
+
for (const identity of FOREIGN_IDENTITIES) {
|
|
126
|
+
expect(error).not.toContain(identity);
|
|
127
|
+
}
|
|
128
|
+
expect(error).toBe("No indexed documents in this project matched the query.");
|
|
129
|
+
expect(warn).toHaveBeenCalled();
|
|
130
|
+
});
|
|
131
|
+
|
|
132
|
+
it("harness control: the fixture really does supply foreign ids", () => {
|
|
133
|
+
// If FOREIGN_IDS were ever emptied, every not-toContain assertion above
|
|
134
|
+
// would pass while testing nothing.
|
|
135
|
+
expect(FOREIGN_IDS.length).toBeGreaterThan(0);
|
|
136
|
+
expect(FOREIGN_IDENTITIES.length).toBe(FOREIGN_IDS.length);
|
|
137
|
+
for (const id of FOREIGN_IDS) {
|
|
138
|
+
expect(id).toContain(":");
|
|
139
|
+
expect(id.split(":")[0]).not.toBe(CALLER);
|
|
140
|
+
}
|
|
141
|
+
});
|
|
142
|
+
});
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
// The version this Worker advertises must equal the version in package.json.
|
|
2
|
+
//
|
|
3
|
+
// THE EXPECTED VALUE IS DERIVED, NEVER TRANSCRIBED. This file reads package.json off disk and
|
|
4
|
+
// parses it; it does not carry a second hand-typed copy of the version string. That distinction
|
|
5
|
+
// is the whole reason this test is worth having. In prism-mcp the advertised version was a
|
|
6
|
+
// literal and the test asserting it carried a transcribed duplicate of the same string, so the
|
|
7
|
+
// assertion only ever proved that someone had typed the same thing twice -- and a correct
|
|
8
|
+
// version bump went red because one copy was updated and the other was not.
|
|
9
|
+
//
|
|
10
|
+
// SCOPE: this file owns "the literal agrees with package.json". Whether the Worker actually PUTS
|
|
11
|
+
// that value on the wire is a separate failure mode, asserted against the real fetch handler in
|
|
12
|
+
// tests-integration/worker.test.ts. Two assertions, two mutations: breaking the literal reddens
|
|
13
|
+
// this file and leaves the integration suite green; removing the field from the /health payload
|
|
14
|
+
// reddens the integration suite and leaves this file green. That pairing is what proves they are
|
|
15
|
+
// two assertions rather than one check wearing two names.
|
|
16
|
+
//
|
|
17
|
+
// This lives in the NODE project (vitest.node.config.ts) rather than the workers one because it
|
|
18
|
+
// reads the filesystem, which workerd has no business doing. The split is load-bearing for the
|
|
19
|
+
// pairing above, not incidental.
|
|
20
|
+
|
|
21
|
+
import { readFileSync } from "node:fs";
|
|
22
|
+
import { dirname, join } from "node:path";
|
|
23
|
+
import { fileURLToPath } from "node:url";
|
|
24
|
+
import { describe, expect, it } from "vitest";
|
|
25
|
+
import { VERSION } from "../src/version";
|
|
26
|
+
|
|
27
|
+
// Anchored to THIS FILE, not to process.cwd(): a suite run from a scratch worktree must read the
|
|
28
|
+
// package.json that sits beside the source it is asserting about, not whichever one the working
|
|
29
|
+
// directory happens to point at.
|
|
30
|
+
const pkgPath = join(dirname(fileURLToPath(import.meta.url)), "..", "package.json");
|
|
31
|
+
const pkg = JSON.parse(readFileSync(pkgPath, "utf8")) as { name?: string; version?: string };
|
|
32
|
+
|
|
33
|
+
describe("advertised version", () => {
|
|
34
|
+
// POSITIVE CONTROL, and it runs first on purpose: if package.json moved, was renamed, or
|
|
35
|
+
// stopped parsing, `pkg.version` is undefined and every assertion below would compare against
|
|
36
|
+
// nothing. An undefined expected value makes a drift test fail for a reason that has nothing to
|
|
37
|
+
// do with drift, so name that failure separately rather than letting it wear drift's clothes. A
|
|
38
|
+
// broken reader must not be able to look like either a pass or a version mismatch.
|
|
39
|
+
it("reads a real version out of package.json (control: the reader is not blind)", () => {
|
|
40
|
+
expect(pkg.name).toBe("prism");
|
|
41
|
+
expect(pkg.version).toMatch(/^\d+\.\d+\.\d+/);
|
|
42
|
+
});
|
|
43
|
+
|
|
44
|
+
it("matches package.json, so a release bump cannot leave the wire behind", () => {
|
|
45
|
+
expect(VERSION).toBe(pkg.version);
|
|
46
|
+
});
|
|
47
|
+
});
|