@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.
- package/README.md +7 -4
- package/index.js +1 -0
- package/package.json +1 -1
- package/template/CONTRIBUTING.md +18 -3
- package/template/MIGRATIONS.md +52 -0
- package/template/README.md +50 -16
- package/template/docs/legal/INSTANCE-ACCEPTABLE-USE.md +5 -2
- package/template/docs/legal/INSTANCE-PRIVACY.md +127 -27
- package/template/migrations/0004_csp_reports.sql +58 -0
- package/template/migrations/0005_auth_attempts_retention.sql +23 -0
- package/template/package.json +6 -6
- package/template/public/app.js +42 -7
- package/template/public/index.html +24 -9
- package/template/public/stt.css +25 -0
- package/template/public/stt.html +1 -21
- package/template/public/styles.css +49 -0
- package/template/public/url-safety.js +66 -0
- package/template/schema.sql +64 -0
- package/template/src/ai-binding.ts +125 -3
- package/template/src/auth.ts +6 -0
- package/template/src/csp.ts +253 -0
- package/template/src/env.ts +11 -0
- package/template/src/gateway-credentials.ts +118 -22
- package/template/src/index.ts +79 -2
- package/template/src/providers/anthropic.ts +4 -4
- package/template/src/providers/openai-image.ts +10 -0
- package/template/src/providers/xai.ts +4 -4
- package/template/src/rate-limit.ts +26 -0
- package/template/src/routes/chat.ts +29 -16
- package/template/src/routes/csp-report.ts +163 -0
- package/template/src/routes/health.ts +6 -1
- package/template/src/routes/prefs.ts +46 -5
- package/template/src/routes/rag.ts +53 -15
- package/template/src/routes/shared.ts +22 -9
- package/template/src/routes/workflow.ts +2 -5
- package/template/src/stt-session.ts +16 -0
- package/template/src/user-prefs.ts +16 -3
- package/template/src/version.ts +18 -0
- package/template/tests/ai-binding-rest.test.ts +154 -0
- package/template/tests/csp.test.ts +449 -0
- package/template/tests/gateway-credentials.test.ts +101 -3
- package/template/tests/openai-image.test.ts +21 -1
- package/template/tests/public-url-safety.test.ts +360 -0
- package/template/tests/rag-metadata-filter.test.ts +135 -0
- package/template/tests/rag-retrieval-diagnostic.test.ts +142 -0
- package/template/tests/skip-link.test.ts +164 -0
- package/template/tests/vectorize-backfill-metadata.test.ts +166 -0
- package/template/tests/version.test.ts +47 -0
- package/template/tests-integration/auth.test.ts +346 -2
- package/template/tests-integration/csp-report.test.ts +232 -0
- package/template/tests-integration/pdf-extract.test.ts +71 -0
- package/template/tests-integration/worker.test.ts +154 -0
- package/template/vitest.workers.config.ts +19 -4
- package/template/wrangler.example.toml +45 -2
|
@@ -43,6 +43,7 @@ const ALL_TABLES = [
|
|
|
43
43
|
"users",
|
|
44
44
|
"sessions",
|
|
45
45
|
"auth_attempts",
|
|
46
|
+
"conversation_compact",
|
|
46
47
|
];
|
|
47
48
|
|
|
48
49
|
const anyEnv = env as unknown as { AUTH_MODE?: string; GATEWAY_ID?: string; CF_AIG_TOKEN?: string };
|
|
@@ -61,6 +62,9 @@ afterEach(() => {
|
|
|
61
62
|
delete anyEnv.CF_AIG_TOKEN;
|
|
62
63
|
});
|
|
63
64
|
|
|
65
|
+
// v1.1.0: a user's Cloudflare account id (any 32 hex will do under the stubs).
|
|
66
|
+
const USER_ACCT = "0123456789abcdef0123456789abcdef";
|
|
67
|
+
|
|
64
68
|
const WORKERS_AI_CHAT = MODELS.find((m) => m.type === "chat" && !m.provider)!.id;
|
|
65
69
|
const STREAM_CHAT = MODELS.find((m) => m.type === "chat" && m.streaming && !m.provider)?.id
|
|
66
70
|
?? MODELS.find((m) => m.type === "chat" && m.streaming)!.id;
|
|
@@ -212,6 +216,43 @@ describe("public-mode gate: uniform 401 unauthenticated", () => {
|
|
|
212
216
|
expect(Array.isArray(((await res.json()) as { chats: unknown[] }).chats)).toBe(true);
|
|
213
217
|
});
|
|
214
218
|
|
|
219
|
+
// The saved slug becomes a path segment in a gateway.ai.cloudflare.com URL and a
|
|
220
|
+
// request header value. Before this was validated, .trim() was the only transform,
|
|
221
|
+
// so an arbitrary string reached the binding as a gateway id.
|
|
222
|
+
it("rejects a gateway_id that is not a slug, and stores nothing", async () => {
|
|
223
|
+
const cookie = await signup("nadia", "password123", "203.0.113.50");
|
|
224
|
+
for (const bad of ["not a slug", "has/slash", "a".repeat(65), "semi;colon", "../traverse"]) {
|
|
225
|
+
const res = await req("/api/prefs", { method: "PATCH", cookie, body: { gateway_id: bad } });
|
|
226
|
+
expect(res.status).toBe(400);
|
|
227
|
+
expect(((await res.json()) as { code?: string }).code).toBe("invalid_gateway_id");
|
|
228
|
+
}
|
|
229
|
+
// Nothing was written by any of the rejected attempts.
|
|
230
|
+
const prefs = (await (await req("/api/prefs", { cookie })).json()) as { gateway_id: string | null };
|
|
231
|
+
expect(prefs.gateway_id).toBeNull();
|
|
232
|
+
});
|
|
233
|
+
|
|
234
|
+
it("still accepts a well-formed slug", async () => {
|
|
235
|
+
const cookie = await signup("omar", "password123", "203.0.113.51");
|
|
236
|
+
const res = await req("/api/prefs", { method: "PATCH", cookie, body: { gateway_id: "my-gw_1" } });
|
|
237
|
+
expect(res.status).not.toBe(400);
|
|
238
|
+
const prefs = (await (await req("/api/prefs", { cookie })).json()) as { gateway_id: string | null };
|
|
239
|
+
expect(prefs.gateway_id).toBe("my-gw_1");
|
|
240
|
+
});
|
|
241
|
+
|
|
242
|
+
// Whitespace tolerance on the slug was untested: every other gateway_id in
|
|
243
|
+
// this file is already whitespace-free, so nothing pinned what happens to a
|
|
244
|
+
// padded one. Normalization lives in saveUserPrefs (user-prefs.ts), NOT in
|
|
245
|
+
// this route, which is why the route storing body.gateway_id raw and storing
|
|
246
|
+
// it trimmed are observably identical. This asserts the endpoint contract so
|
|
247
|
+
// that a future change moving or dropping that trim is caught here.
|
|
248
|
+
it("accepts a padded slug and stores it trimmed", async () => {
|
|
249
|
+
const cookie = await signup("priya", "password123", "203.0.113.52");
|
|
250
|
+
const res = await req("/api/prefs", { method: "PATCH", cookie, body: { gateway_id: " padded-gw " } });
|
|
251
|
+
expect(res.status).not.toBe(400);
|
|
252
|
+
const prefs = (await (await req("/api/prefs", { cookie })).json()) as { gateway_id: string | null };
|
|
253
|
+
expect(prefs.gateway_id).toBe("padded-gw");
|
|
254
|
+
});
|
|
255
|
+
|
|
215
256
|
it("isolates prefs between two accounts", async () => {
|
|
216
257
|
const aCookie = await signup("hank", "password123", "203.0.113.10");
|
|
217
258
|
const bCookie = await signup("iris", "password123", "203.0.113.11");
|
|
@@ -259,9 +300,13 @@ describe("fail-closed gateway in public mode", () => {
|
|
|
259
300
|
expect(b.gateway.configured).toBe(false);
|
|
260
301
|
});
|
|
261
302
|
|
|
262
|
-
it("positive control: once the user sets
|
|
303
|
+
it("positive control: once the user sets account id + gateway + token, the 412 no longer fires", async () => {
|
|
263
304
|
const cookie = await signup("liam", "password123");
|
|
264
|
-
await req("/api/prefs", {
|
|
305
|
+
await req("/api/prefs", {
|
|
306
|
+
method: "PATCH",
|
|
307
|
+
cookie,
|
|
308
|
+
body: { account_id: USER_ACCT, gateway_id: "liam-gw", cf_aig_token: "liam-token" },
|
|
309
|
+
});
|
|
265
310
|
let status: number;
|
|
266
311
|
try {
|
|
267
312
|
status = (
|
|
@@ -274,6 +319,206 @@ describe("fail-closed gateway in public mode", () => {
|
|
|
274
319
|
});
|
|
275
320
|
});
|
|
276
321
|
|
|
322
|
+
// prism#193: OPENAI_API_KEY is a deployer secret, so in public mode it must be
|
|
323
|
+
// ignored exactly like GATEWAY_ID / CF_AIG_TOKEN. The user here has a fully
|
|
324
|
+
// configured BYOK gateway so the credential gate passes and the request reaches
|
|
325
|
+
// the image dispatch branch; the only question is which transport it picks.
|
|
326
|
+
describe("OPENAI_API_KEY is ignored in public mode (prism#193)", () => {
|
|
327
|
+
const GPT_IMAGE = MODELS.find((m) => m.type === "image" && m.provider === "openai")!.id;
|
|
328
|
+
const keyEnv = env as unknown as { OPENAI_API_KEY?: string };
|
|
329
|
+
const realFetch = globalThis.fetch;
|
|
330
|
+
let openaiCalls: string[];
|
|
331
|
+
|
|
332
|
+
beforeEach(() => {
|
|
333
|
+
openaiCalls = [];
|
|
334
|
+
keyEnv.OPENAI_API_KEY = "sk-host-owned";
|
|
335
|
+
globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => {
|
|
336
|
+
const url = input instanceof Request ? input.url : String(input);
|
|
337
|
+
if (url.startsWith("https://api.openai.com/")) {
|
|
338
|
+
openaiCalls.push(url);
|
|
339
|
+
return new Response(JSON.stringify({ error: { message: "stubbed" } }), { status: 500 });
|
|
340
|
+
}
|
|
341
|
+
// v1.1.0: an account-scoped user dispatches over REST to their own
|
|
342
|
+
// account; answer it locally so the test never leaves the sandbox.
|
|
343
|
+
if (url.startsWith("https://api.cloudflare.com/")) {
|
|
344
|
+
return new Response(JSON.stringify({ success: false, errors: [{ message: "stubbed" }] }), {
|
|
345
|
+
status: 500,
|
|
346
|
+
headers: { "content-type": "application/json" },
|
|
347
|
+
});
|
|
348
|
+
}
|
|
349
|
+
return realFetch(input, init);
|
|
350
|
+
}) as typeof fetch;
|
|
351
|
+
});
|
|
352
|
+
|
|
353
|
+
afterEach(() => {
|
|
354
|
+
delete keyEnv.OPENAI_API_KEY;
|
|
355
|
+
globalThis.fetch = realFetch;
|
|
356
|
+
});
|
|
357
|
+
|
|
358
|
+
async function runGptImage(headers: Record<string, string>): Promise<void> {
|
|
359
|
+
const h = new Headers({ "content-type": "application/json", "cf-connecting-ip": "203.0.113.40", ...headers });
|
|
360
|
+
await SELF.fetch("https://prism.test/api/prefs", {
|
|
361
|
+
method: "PATCH",
|
|
362
|
+
headers: h,
|
|
363
|
+
// v1.1.0: account id included, or public mode would 412 before the
|
|
364
|
+
// image branch and this test would pass without testing anything.
|
|
365
|
+
body: JSON.stringify({ account_id: USER_ACCT, gateway_id: "user-gw", cf_aig_token: "user-token" }),
|
|
366
|
+
});
|
|
367
|
+
try {
|
|
368
|
+
await SELF.fetch("https://prism.test/api/chat", {
|
|
369
|
+
method: "POST",
|
|
370
|
+
headers: h,
|
|
371
|
+
body: JSON.stringify({ model: GPT_IMAGE, user_input: "a red kite" }),
|
|
372
|
+
});
|
|
373
|
+
} catch {
|
|
374
|
+
// The inert AI stub makes the gateway path throw; that is fine, the
|
|
375
|
+
// assertion is only about whether api.openai.com was dialed.
|
|
376
|
+
}
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
it("public mode: a configured user's gpt-image request never dials api.openai.com with the host key", async () => {
|
|
380
|
+
const cookie = await signup("olga", "password123");
|
|
381
|
+
await runGptImage({ cookie });
|
|
382
|
+
expect(openaiCalls).toEqual([]);
|
|
383
|
+
});
|
|
384
|
+
|
|
385
|
+
it("positive control: access mode still uses the deployer key (the stub can see the call)", async () => {
|
|
386
|
+
anyEnv.AUTH_MODE = "access";
|
|
387
|
+
await runGptImage({ "cf-access-authenticated-user-email": "owner@example.com" });
|
|
388
|
+
expect(openaiCalls.length).toBe(1);
|
|
389
|
+
});
|
|
390
|
+
});
|
|
391
|
+
|
|
392
|
+
// v1.1.0: BYOK must reach the user's own Cloudflare account. The AI binding is
|
|
393
|
+
// pinned to the worker's account, so these assert (1) the pre-v1.1.0 shape is
|
|
394
|
+
// refused with its own code rather than resolved on our binding, and (2) a
|
|
395
|
+
// fully configured user is dispatched over HTTP to THEIR account id. The AI
|
|
396
|
+
// stub here is an inert {}: any path that touched the host binding would throw,
|
|
397
|
+
// so a 200 with stubbed fetch proves the binding was never used.
|
|
398
|
+
describe("account-scoped BYOK (v1.1.0)", () => {
|
|
399
|
+
const LEGACY_ANTHROPIC = MODELS.find((m) => m.provider === "anthropic" && !m.binding)!.id;
|
|
400
|
+
const BINDING_ANTHROPIC = MODELS.find((m) => m.provider === "anthropic" && m.binding)!.id;
|
|
401
|
+
const realFetch = globalThis.fetch;
|
|
402
|
+
let calls: Array<{ url: string; headers: Headers; body: string }>;
|
|
403
|
+
|
|
404
|
+
const anthropicMessage = {
|
|
405
|
+
id: "msg_1",
|
|
406
|
+
type: "message",
|
|
407
|
+
role: "assistant",
|
|
408
|
+
model: "stub",
|
|
409
|
+
content: [{ type: "text", text: "hello from your account" }],
|
|
410
|
+
stop_reason: "end_turn",
|
|
411
|
+
usage: { input_tokens: 3, output_tokens: 5 },
|
|
412
|
+
};
|
|
413
|
+
|
|
414
|
+
beforeEach(() => {
|
|
415
|
+
calls = [];
|
|
416
|
+
globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => {
|
|
417
|
+
const url = input instanceof Request ? input.url : String(input);
|
|
418
|
+
if (url.startsWith("https://gateway.ai.cloudflare.com/") || url.startsWith("https://api.cloudflare.com/")) {
|
|
419
|
+
calls.push({ url, headers: new Headers(init?.headers), body: String(init?.body ?? "") });
|
|
420
|
+
const payload = url.startsWith("https://api.cloudflare.com/")
|
|
421
|
+
? { success: true, errors: [], result: anthropicMessage }
|
|
422
|
+
: anthropicMessage;
|
|
423
|
+
return new Response(JSON.stringify(payload), {
|
|
424
|
+
headers: { "content-type": "application/json", "cf-aig-log-id": "user-log-1" },
|
|
425
|
+
});
|
|
426
|
+
}
|
|
427
|
+
return realFetch(input, init);
|
|
428
|
+
}) as typeof fetch;
|
|
429
|
+
});
|
|
430
|
+
|
|
431
|
+
afterEach(() => {
|
|
432
|
+
globalThis.fetch = realFetch;
|
|
433
|
+
});
|
|
434
|
+
|
|
435
|
+
async function configure(cookie: string, body: Record<string, unknown>): Promise<Response> {
|
|
436
|
+
return req("/api/prefs", { method: "PATCH", cookie, body });
|
|
437
|
+
}
|
|
438
|
+
|
|
439
|
+
it("pre-v1.1.0 shape (slug + token, no account id): 412 gateway_account_id_required, nothing dialed", async () => {
|
|
440
|
+
const cookie = await signup("petra", "password123");
|
|
441
|
+
await configure(cookie, { gateway_id: "petra-gw", cf_aig_token: "petra-token" });
|
|
442
|
+
for (const model of [LEGACY_ANTHROPIC, BINDING_ANTHROPIC, WORKERS_AI_CHAT]) {
|
|
443
|
+
const res = await req("/api/chat", { method: "POST", cookie, body: { model, user_input: "hi" } });
|
|
444
|
+
expect(res.status).toBe(412);
|
|
445
|
+
const body = (await res.json()) as { code: string; error: string };
|
|
446
|
+
expect(body.code).toBe("gateway_account_id_required");
|
|
447
|
+
expect(body.error).toMatch(/account ID/);
|
|
448
|
+
}
|
|
449
|
+
expect(calls).toEqual([]);
|
|
450
|
+
});
|
|
451
|
+
|
|
452
|
+
it("boot and prefs flag the pre-v1.1.0 user and keep their saved slug", async () => {
|
|
453
|
+
const cookie = await signup("quinn", "password123");
|
|
454
|
+
await configure(cookie, { gateway_id: "quinn-gw", cf_aig_token: "quinn-token" });
|
|
455
|
+
const b = (await boot(cookie)) as BootEnvelope & {
|
|
456
|
+
gateway: { account_id_required: boolean; gateway_id: string | null };
|
|
457
|
+
};
|
|
458
|
+
expect(b.gateway.configured).toBe(false);
|
|
459
|
+
expect(b.gateway.account_id_required).toBe(true);
|
|
460
|
+
expect(b.gateway.gateway_id).toBe("quinn-gw");
|
|
461
|
+
|
|
462
|
+
// Adding only the account id completes the migration.
|
|
463
|
+
const res = await configure(cookie, { account_id: USER_ACCT.toUpperCase() });
|
|
464
|
+
expect(res.status).toBe(200);
|
|
465
|
+
const prefs = (await res.json()) as { configured: boolean; account_id: string; account_id_required: boolean };
|
|
466
|
+
expect(prefs.configured).toBe(true);
|
|
467
|
+
expect(prefs.account_id).toBe(USER_ACCT); // normalized to lowercase
|
|
468
|
+
expect(prefs.account_id_required).toBe(false);
|
|
469
|
+
});
|
|
470
|
+
|
|
471
|
+
it("rejects a malformed account id or gateway slug with 400", async () => {
|
|
472
|
+
const cookie = await signup("rhea", "password123");
|
|
473
|
+
const badAcct = await configure(cookie, { account_id: "not-an-account" });
|
|
474
|
+
expect(badAcct.status).toBe(400);
|
|
475
|
+
expect(((await badAcct.json()) as { code: string }).code).toBe("invalid_account_id");
|
|
476
|
+
const badGw = await configure(cookie, { gateway_id: "../other-gw" });
|
|
477
|
+
expect(badGw.status).toBe(400);
|
|
478
|
+
expect(((await badGw.json()) as { code: string }).code).toBe("invalid_gateway_id");
|
|
479
|
+
});
|
|
480
|
+
|
|
481
|
+
it("account id without a token: 412 cf_aig_token_required", async () => {
|
|
482
|
+
const cookie = await signup("sven", "password123");
|
|
483
|
+
await configure(cookie, { account_id: USER_ACCT, gateway_id: "sven-gw" });
|
|
484
|
+
const res = await req("/api/chat", { method: "POST", cookie, body: { model: WORKERS_AI_CHAT, user_input: "hi" } });
|
|
485
|
+
expect(res.status).toBe(412);
|
|
486
|
+
expect(((await res.json()) as { code: string }).code).toBe("cf_aig_token_required");
|
|
487
|
+
});
|
|
488
|
+
|
|
489
|
+
it("legacy provider path dials gateway.ai.cloudflare.com under the USER's account id", async () => {
|
|
490
|
+
const cookie = await signup("tara", "password123");
|
|
491
|
+
await configure(cookie, { account_id: USER_ACCT, gateway_id: "tara-gw", cf_aig_token: "tara-token" });
|
|
492
|
+
const res = await req("/api/chat", { method: "POST", cookie, body: { model: LEGACY_ANTHROPIC, user_input: "hi" } });
|
|
493
|
+
expect(res.status).toBe(200);
|
|
494
|
+
expect(calls.length).toBe(1);
|
|
495
|
+
expect(calls[0].url).toBe(`https://gateway.ai.cloudflare.com/v1/${USER_ACCT}/tara-gw/anthropic/v1/messages`);
|
|
496
|
+
expect(calls[0].headers.get("cf-aig-authorization")).toBe("Bearer tara-token");
|
|
497
|
+
expect(calls[0].headers.get("x-api-key")).toBeNull();
|
|
498
|
+
});
|
|
499
|
+
|
|
500
|
+
it("binding-catalog path goes to the USER's account over REST, never the host binding", async () => {
|
|
501
|
+
const cookie = await signup("uma", "password123");
|
|
502
|
+
await configure(cookie, { account_id: USER_ACCT, gateway_id: "uma-gw", cf_aig_token: "uma-token" });
|
|
503
|
+
const res = await req("/api/chat", { method: "POST", cookie, body: { model: BINDING_ANTHROPIC, user_input: "hi" } });
|
|
504
|
+
expect(res.status).toBe(200);
|
|
505
|
+
expect(calls.length).toBe(1);
|
|
506
|
+
expect(calls[0].url).toBe(`https://api.cloudflare.com/client/v4/accounts/${USER_ACCT}/ai/run`);
|
|
507
|
+
expect(calls[0].headers.get("authorization")).toBe("Bearer uma-token");
|
|
508
|
+
expect(calls[0].headers.get("cf-aig-gateway-id")).toBe("uma-gw");
|
|
509
|
+
expect((JSON.parse(calls[0].body) as { model: string }).model).toBe(BINDING_ANTHROPIC);
|
|
510
|
+
});
|
|
511
|
+
|
|
512
|
+
it("Workers AI chat through aiRun also bills the USER's account (model-in-path)", async () => {
|
|
513
|
+
const cookie = await signup("vera", "password123");
|
|
514
|
+
await configure(cookie, { account_id: USER_ACCT, gateway_id: "vera-gw", cf_aig_token: "vera-token" });
|
|
515
|
+
await req("/api/chat", { method: "POST", cookie, body: { model: WORKERS_AI_CHAT, user_input: "hi" } });
|
|
516
|
+
expect(calls.length).toBe(1);
|
|
517
|
+
expect(calls[0].url).toBe(`https://api.cloudflare.com/client/v4/accounts/${USER_ACCT}/ai/run/${WORKERS_AI_CHAT}`);
|
|
518
|
+
expect(calls[0].headers.get("cf-aig-gateway-id")).toBe("vera-gw");
|
|
519
|
+
});
|
|
520
|
+
});
|
|
521
|
+
|
|
277
522
|
describe("DELETE /api/account cascade", () => {
|
|
278
523
|
it("requires password re-entry and cascades the account's data", async () => {
|
|
279
524
|
const cookie = await signup("mona", "password123");
|
|
@@ -369,3 +614,102 @@ describe("rate limiting", () => {
|
|
|
369
614
|
expect(row!.count).toBeGreaterThanOrEqual(5);
|
|
370
615
|
});
|
|
371
616
|
});
|
|
617
|
+
|
|
618
|
+
// prism#192 claim 1: the deletion cascade skipped conversation_compact, whose
|
|
619
|
+
// `summary` column is a model-written digest of the user's own chat turns.
|
|
620
|
+
// INSTANCE-PRIVACY.md says deletion "cascades ... we do not keep a shadow
|
|
621
|
+
// copy", so a surviving summary row contradicts the published notice.
|
|
622
|
+
describe("DELETE /api/account also cascades conversation_compact (prism#192)", () => {
|
|
623
|
+
it("removes the user's compact summaries, and leaves another user's alone", async () => {
|
|
624
|
+
const cookie = await signup("rosa", "password123", "203.0.113.61");
|
|
625
|
+
const userId = (
|
|
626
|
+
await env.DB.prepare(`SELECT id FROM users WHERE username_lc = 'rosa'`).first<{ id: string }>()
|
|
627
|
+
)!.id;
|
|
628
|
+
const otherCookie = await signup("sage", "password123", "203.0.113.62");
|
|
629
|
+
const otherId = (
|
|
630
|
+
await env.DB.prepare(`SELECT id FROM users WHERE username_lc = 'sage'`).first<{ id: string }>()
|
|
631
|
+
)!.id;
|
|
632
|
+
|
|
633
|
+
for (const [conv, who] of [["conv-rosa", userId], ["conv-sage", otherId]] as const) {
|
|
634
|
+
await env.DB.prepare(
|
|
635
|
+
`INSERT INTO conversation_compact
|
|
636
|
+
(conversation_id, user_email, summary, through_turn_index, model)
|
|
637
|
+
VALUES (?, ?, ?, 4, 'm')`,
|
|
638
|
+
)
|
|
639
|
+
.bind(conv, who, "a model-written digest of the user's earlier turns")
|
|
640
|
+
.run();
|
|
641
|
+
}
|
|
642
|
+
|
|
643
|
+
// Precondition: the row the cascade must remove really is there, so a later
|
|
644
|
+
// zero cannot be an insert that silently failed.
|
|
645
|
+
const before = await env.DB.prepare(
|
|
646
|
+
`SELECT COUNT(*) AS n FROM conversation_compact WHERE user_email = ?`,
|
|
647
|
+
).bind(userId).first<{ n: number }>();
|
|
648
|
+
expect(before!.n).toBe(1);
|
|
649
|
+
|
|
650
|
+
const del = await req("/api/account", { method: "DELETE", cookie, body: { password: "password123" } });
|
|
651
|
+
expect(del.status).toBe(200);
|
|
652
|
+
|
|
653
|
+
const after = await env.DB.prepare(
|
|
654
|
+
`SELECT COUNT(*) AS n FROM conversation_compact WHERE user_email = ?`,
|
|
655
|
+
).bind(userId).first<{ n: number }>();
|
|
656
|
+
expect(after!.n).toBe(0);
|
|
657
|
+
|
|
658
|
+
// Positive control: the cascade is scoped, not a table wipe. If this ever
|
|
659
|
+
// reads 0 the DELETE lost its WHERE clause and the test above would still
|
|
660
|
+
// pass, which is the reading that would prove the assertion worthless.
|
|
661
|
+
const survivor = await env.DB.prepare(
|
|
662
|
+
`SELECT COUNT(*) AS n FROM conversation_compact WHERE user_email = ?`,
|
|
663
|
+
).bind(otherId).first<{ n: number }>();
|
|
664
|
+
expect(survivor!.n).toBe(1);
|
|
665
|
+
expect((await boot(otherCookie)).authenticated).toBe(true);
|
|
666
|
+
});
|
|
667
|
+
});
|
|
668
|
+
|
|
669
|
+
// prism#192 claim 2: auth_attempts rows were pruned only by a successful login
|
|
670
|
+
// clearing its own bucket, so a signup bucket or a never-succeeding
|
|
671
|
+
// login:<ip>:<username> bucket persisted indefinitely. The notice heads that
|
|
672
|
+
// section "transient IP processing". There is no cron (`crons = []`) and no
|
|
673
|
+
// scheduled handler, so retention has to be an executed deletion on the write
|
|
674
|
+
// path, the same way src/routes/csp-report.ts does it.
|
|
675
|
+
describe("auth_attempts retention is pruned on write (prism#192)", () => {
|
|
676
|
+
it("drops a bucket older than the window and keeps a live one", async () => {
|
|
677
|
+
await signup("tess", "password123", "198.51.100.41");
|
|
678
|
+
|
|
679
|
+
// A stale bucket from an IP that never came back, aged past retention.
|
|
680
|
+
await env.DB.prepare(
|
|
681
|
+
`INSERT INTO auth_attempts (bucket_key, count, window_start)
|
|
682
|
+
VALUES ('signup:198.51.100.99', 7, datetime('now', '-30 days'))`,
|
|
683
|
+
).run();
|
|
684
|
+
// A bucket inside the retention window, which must SURVIVE. Without this
|
|
685
|
+
// the test would also pass if the prune deleted the whole table.
|
|
686
|
+
await env.DB.prepare(
|
|
687
|
+
`INSERT INTO auth_attempts (bucket_key, count, window_start)
|
|
688
|
+
VALUES ('signup:198.51.100.98', 3, datetime('now', '-10 minutes'))`,
|
|
689
|
+
).run();
|
|
690
|
+
|
|
691
|
+
const staleBefore = await env.DB.prepare(
|
|
692
|
+
`SELECT count FROM auth_attempts WHERE bucket_key = 'signup:198.51.100.99'`,
|
|
693
|
+
).first();
|
|
694
|
+
expect(staleBefore).not.toBeNull(); // the instrument can see the row it will look for
|
|
695
|
+
|
|
696
|
+
// Any subsequent limiter write is what performs the prune.
|
|
697
|
+
const res = await req("/api/auth/login", {
|
|
698
|
+
method: "POST",
|
|
699
|
+
body: { username: "tess", password: "wrongpassword" },
|
|
700
|
+
ip: "198.51.100.41",
|
|
701
|
+
});
|
|
702
|
+
expect([200, 401, 429]).toContain(res.status);
|
|
703
|
+
|
|
704
|
+
expect(
|
|
705
|
+
await env.DB.prepare(
|
|
706
|
+
`SELECT count FROM auth_attempts WHERE bucket_key = 'signup:198.51.100.99'`,
|
|
707
|
+
).first(),
|
|
708
|
+
).toBeNull();
|
|
709
|
+
expect(
|
|
710
|
+
await env.DB.prepare(
|
|
711
|
+
`SELECT count FROM auth_attempts WHERE bucket_key = 'signup:198.51.100.98'`,
|
|
712
|
+
).first(),
|
|
713
|
+
).not.toBeNull();
|
|
714
|
+
});
|
|
715
|
+
});
|
|
@@ -0,0 +1,232 @@
|
|
|
1
|
+
// CSP collector against the real fetch handler and real local D1
|
|
2
|
+
// (fleet-chezmoi#1646).
|
|
3
|
+
//
|
|
4
|
+
// WHAT THIS SUITE CAN AND CANNOT SEE, stated up front because one of the
|
|
5
|
+
// properties that matters most is NOT provable here:
|
|
6
|
+
//
|
|
7
|
+
// - It CAN prove the handler's behaviour end to end: refusal past the body
|
|
8
|
+
// cap, refusal of malformed input, the bounded projection actually landing
|
|
9
|
+
// in D1, the rate limit, and that shedding is counted rather than silent.
|
|
10
|
+
// - It CANNOT prove the route is reachable without a session. This pool binds
|
|
11
|
+
// no AUTH_MODE, so `authMode(env)` is not "public" and the public-mode gate
|
|
12
|
+
// never executes. An "unauthenticated access works" assertion here would
|
|
13
|
+
// pass identically whether the route sat above or below that gate, which
|
|
14
|
+
// makes it no assertion at all. The route-ordering property is asserted
|
|
15
|
+
// against the source in tests/csp.test.ts instead, with a control.
|
|
16
|
+
// - It CANNOT prove the policy header lands on the HTML document, because
|
|
17
|
+
// ASSETS is mocked as a 404 Fetcher with no HTML. It CAN prove the
|
|
18
|
+
// non-HTML branch, and the HTML branch is covered by the live browser
|
|
19
|
+
// acceptance recorded on the PR. Since the promotion to enforcing, that
|
|
20
|
+
// acceptance also has to show a violation actually BLOCKED, which no
|
|
21
|
+
// assertion in this pool can observe: a policy string is not a refusal.
|
|
22
|
+
|
|
23
|
+
import { env, SELF } from "cloudflare:test";
|
|
24
|
+
import { beforeEach, describe, expect, it } from "vitest";
|
|
25
|
+
import schemaSql from "../schema.sql?raw";
|
|
26
|
+
import { CSP_HEADER, CSP_HEADER_REPORT_ONLY } from "../src/csp";
|
|
27
|
+
|
|
28
|
+
const ORIGIN = "https://play.example.org";
|
|
29
|
+
const REPORT_URL = `${ORIGIN}/api/csp-report`;
|
|
30
|
+
|
|
31
|
+
async function applySchema(db: D1Database): Promise<void> {
|
|
32
|
+
const statements = schemaSql
|
|
33
|
+
.split("\n")
|
|
34
|
+
.map((line) => line.replace(/--.*$/, ""))
|
|
35
|
+
.join("\n")
|
|
36
|
+
.split(";")
|
|
37
|
+
.map((s) => s.trim())
|
|
38
|
+
.filter((s) => s.length > 0);
|
|
39
|
+
for (const stmt of statements) {
|
|
40
|
+
try {
|
|
41
|
+
await db.prepare(stmt).run();
|
|
42
|
+
} catch (e) {
|
|
43
|
+
const msg = String((e as { message?: string })?.message ?? e);
|
|
44
|
+
if (/duplicate column name|already exists/i.test(msg)) continue;
|
|
45
|
+
throw e;
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function legacyReport(overrides: Record<string, unknown> = {}) {
|
|
51
|
+
return {
|
|
52
|
+
"csp-report": {
|
|
53
|
+
"document-uri": `${ORIGIN}/`,
|
|
54
|
+
"violated-directive": "style-src 'self'",
|
|
55
|
+
"effective-directive": "style-src-attr",
|
|
56
|
+
"blocked-uri": "inline",
|
|
57
|
+
disposition: "report",
|
|
58
|
+
"status-code": 200,
|
|
59
|
+
...overrides,
|
|
60
|
+
},
|
|
61
|
+
};
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
function post(body: string, headers: Record<string, string> = {}) {
|
|
65
|
+
return SELF.fetch(REPORT_URL, {
|
|
66
|
+
method: "POST",
|
|
67
|
+
headers: { "content-type": "application/csp-report", ...headers },
|
|
68
|
+
body,
|
|
69
|
+
});
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
async function rowCount(): Promise<number> {
|
|
73
|
+
const r = await env.DB.prepare(`SELECT COUNT(*) AS n FROM csp_reports`).first<{ n: number }>();
|
|
74
|
+
return r?.n ?? 0;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
describe("POST /api/csp-report", () => {
|
|
78
|
+
beforeEach(async () => {
|
|
79
|
+
await applySchema(env.DB);
|
|
80
|
+
await env.DB.prepare(`DELETE FROM csp_reports`).run();
|
|
81
|
+
await env.DB.prepare(`DELETE FROM csp_report_buckets`).run();
|
|
82
|
+
});
|
|
83
|
+
|
|
84
|
+
it("accepts a real report and persists the bounded projection", async () => {
|
|
85
|
+
const res = await post(JSON.stringify(legacyReport()));
|
|
86
|
+
expect(res.status).toBe(204);
|
|
87
|
+
|
|
88
|
+
const row = await env.DB.prepare(
|
|
89
|
+
`SELECT document_uri, effective_directive, blocked_uri, disposition, status_code
|
|
90
|
+
FROM csp_reports ORDER BY id DESC LIMIT 1`,
|
|
91
|
+
).first<Record<string, unknown>>();
|
|
92
|
+
|
|
93
|
+
expect(row).toBeTruthy();
|
|
94
|
+
expect(row!.document_uri).toBe(`${ORIGIN}/`);
|
|
95
|
+
expect(row!.effective_directive).toBe("style-src-attr");
|
|
96
|
+
expect(row!.blocked_uri).toBe("inline");
|
|
97
|
+
expect(row!.status_code).toBe(200);
|
|
98
|
+
});
|
|
99
|
+
|
|
100
|
+
it("strips query and fragment from the stored document_uri", async () => {
|
|
101
|
+
await post(JSON.stringify(legacyReport({ "document-uri": `${ORIGIN}/x?tok=SECRETVALUE#f` })));
|
|
102
|
+
const row = await env.DB.prepare(
|
|
103
|
+
`SELECT document_uri FROM csp_reports ORDER BY id DESC LIMIT 1`,
|
|
104
|
+
).first<{ document_uri: string }>();
|
|
105
|
+
expect(row!.document_uri).toBe(`${ORIGIN}/x`);
|
|
106
|
+
expect(row!.document_uri).not.toContain("SECRETVALUE");
|
|
107
|
+
});
|
|
108
|
+
|
|
109
|
+
it("never persists script-sample end to end", async () => {
|
|
110
|
+
await post(
|
|
111
|
+
JSON.stringify(legacyReport({ "script-sample": "const t = 'SUPER SECRET VALUE'" })),
|
|
112
|
+
);
|
|
113
|
+
const row = await env.DB.prepare(
|
|
114
|
+
`SELECT * FROM csp_reports ORDER BY id DESC LIMIT 1`,
|
|
115
|
+
).first<Record<string, unknown>>();
|
|
116
|
+
expect(JSON.stringify(row)).not.toContain("SUPER SECRET");
|
|
117
|
+
});
|
|
118
|
+
|
|
119
|
+
// THE CAP MUST REFUSE, NOT TRUNCATE. A collector that stores a mangled row
|
|
120
|
+
// past its limit is worse than one that refuses, because the mangled row
|
|
121
|
+
// looks like a real observation. So the assertion is not merely "413": it is
|
|
122
|
+
// "413 AND nothing was written".
|
|
123
|
+
it("refuses past the body cap and writes nothing", async () => {
|
|
124
|
+
const before = await rowCount();
|
|
125
|
+
const huge = JSON.stringify(legacyReport({ referrer: "z".repeat(20000) }));
|
|
126
|
+
const res = await post(huge);
|
|
127
|
+
expect(res.status).toBe(413);
|
|
128
|
+
expect(await rowCount()).toBe(before);
|
|
129
|
+
});
|
|
130
|
+
|
|
131
|
+
it("refuses an oversized body even when content-length lies", async () => {
|
|
132
|
+
// content-length is a claim. The post-read byte check is what actually
|
|
133
|
+
// bounds it, so a header understating the size must not get past.
|
|
134
|
+
const before = await rowCount();
|
|
135
|
+
const huge = JSON.stringify(legacyReport({ referrer: "z".repeat(20000) }));
|
|
136
|
+
const res = await post(huge, { "content-length": "10" });
|
|
137
|
+
expect(res.status).toBe(413);
|
|
138
|
+
expect(await rowCount()).toBe(before);
|
|
139
|
+
});
|
|
140
|
+
|
|
141
|
+
it("refuses malformed JSON without writing a row", async () => {
|
|
142
|
+
const before = await rowCount();
|
|
143
|
+
const res = await post("{not json");
|
|
144
|
+
expect(res.status).toBe(400);
|
|
145
|
+
expect(await rowCount()).toBe(before);
|
|
146
|
+
});
|
|
147
|
+
|
|
148
|
+
it("refuses a well-formed body that is not a CSP report, without writing an empty row", async () => {
|
|
149
|
+
// An all-null row would record "a violation happened with no detail",
|
|
150
|
+
// which is indistinguishable from the collector mangling its input.
|
|
151
|
+
const before = await rowCount();
|
|
152
|
+
const res = await post(JSON.stringify({ hello: "world" }));
|
|
153
|
+
expect(res.status).toBe(400);
|
|
154
|
+
expect(await rowCount()).toBe(before);
|
|
155
|
+
});
|
|
156
|
+
|
|
157
|
+
it("does not answer GET", async () => {
|
|
158
|
+
const res = await SELF.fetch(REPORT_URL, { method: "GET" });
|
|
159
|
+
expect(res.status).not.toBe(204);
|
|
160
|
+
});
|
|
161
|
+
|
|
162
|
+
// SHEDDING MUST BE VISIBLE. Without the counter, a rate-limited estate and a
|
|
163
|
+
// quiet one produce an identical empty table.
|
|
164
|
+
it("rate limits, and counts what it drops", async () => {
|
|
165
|
+
const body = JSON.stringify(legacyReport());
|
|
166
|
+
let sawLimit = false;
|
|
167
|
+
for (let i = 0; i < 70; i++) {
|
|
168
|
+
const res = await post(body, { "cf-connecting-ip": "203.0.113.9" });
|
|
169
|
+
if (res.status === 429) {
|
|
170
|
+
sawLimit = true;
|
|
171
|
+
break;
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
expect(sawLimit).toBe(true);
|
|
175
|
+
|
|
176
|
+
const bucket = await env.DB.prepare(
|
|
177
|
+
`SELECT count, dropped FROM csp_report_buckets WHERE bucket_key = ?`,
|
|
178
|
+
)
|
|
179
|
+
.bind("csp:203.0.113.9")
|
|
180
|
+
.first<{ count: number; dropped: number }>();
|
|
181
|
+
|
|
182
|
+
expect(bucket).toBeTruthy();
|
|
183
|
+
expect(bucket!.dropped).toBeGreaterThan(0);
|
|
184
|
+
});
|
|
185
|
+
|
|
186
|
+
it("buckets per client rather than globally", async () => {
|
|
187
|
+
const body = JSON.stringify(legacyReport());
|
|
188
|
+
await post(body, { "cf-connecting-ip": "203.0.113.1" });
|
|
189
|
+
await post(body, { "cf-connecting-ip": "203.0.113.2" });
|
|
190
|
+
const rows = await env.DB.prepare(
|
|
191
|
+
`SELECT bucket_key FROM csp_report_buckets ORDER BY bucket_key`,
|
|
192
|
+
).all<{ bucket_key: string }>();
|
|
193
|
+
const keys = (rows.results || []).map((r) => r.bucket_key);
|
|
194
|
+
expect(keys).toContain("csp:203.0.113.1");
|
|
195
|
+
expect(keys).toContain("csp:203.0.113.2");
|
|
196
|
+
});
|
|
197
|
+
});
|
|
198
|
+
|
|
199
|
+
describe("security headers on the static surface", () => {
|
|
200
|
+
it("sets HSTS without preload on the assets fallthrough", async () => {
|
|
201
|
+
const res = await SELF.fetch(`${ORIGIN}/some-static-path`);
|
|
202
|
+
const hsts = res.headers.get("strict-transport-security");
|
|
203
|
+
expect(hsts).toBeTruthy();
|
|
204
|
+
expect(hsts).toContain("max-age=");
|
|
205
|
+
// preload is the genuinely irreversible one and is deliberately absent.
|
|
206
|
+
expect(hsts).not.toContain("preload");
|
|
207
|
+
});
|
|
208
|
+
|
|
209
|
+
// ASSETS is mocked as a non-HTML 404 here, so this asserts the NON-HTML
|
|
210
|
+
// branch: a policy on a subresource governs nothing and is not emitted. The
|
|
211
|
+
// HTML branch is covered by the live browser acceptance on the PR, because
|
|
212
|
+
// this pool has no HTML to serve.
|
|
213
|
+
//
|
|
214
|
+
// BOTH header names are checked, and that is the point rather than
|
|
215
|
+
// belt-and-braces. After the promotion, an assertion that looks only for the
|
|
216
|
+
// RETIRED report-only name passes by finding nothing, which is exactly what
|
|
217
|
+
// it would do if the enforcing header were being sprayed onto every
|
|
218
|
+
// subresource. A check whose subject no longer exists cannot fail.
|
|
219
|
+
it("does not put a document policy on a non-HTML response, under EITHER header name", async () => {
|
|
220
|
+
const res = await SELF.fetch(`${ORIGIN}/some-static-path`);
|
|
221
|
+
expect(res.headers.get(CSP_HEADER)).toBeNull();
|
|
222
|
+
expect(res.headers.get(CSP_HEADER_REPORT_ONLY)).toBeNull();
|
|
223
|
+
});
|
|
224
|
+
|
|
225
|
+
// Control for the two assertions above: this response really does carry
|
|
226
|
+
// headers, so the nulls are a measured absence rather than an empty response
|
|
227
|
+
// object that would report null for anything asked of it.
|
|
228
|
+
it("control: the same response carries a header we know is set", async () => {
|
|
229
|
+
const res = await SELF.fetch(`${ORIGIN}/some-static-path`);
|
|
230
|
+
expect(res.headers.get("strict-transport-security")).toBeTruthy();
|
|
231
|
+
});
|
|
232
|
+
});
|