@skyphusion/create-prism 0.175.6 → 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.
@@ -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
+ });
@@ -11,6 +11,7 @@
11
11
  import { env, SELF } from "cloudflare:test";
12
12
  import { beforeEach, describe, expect, it } from "vitest";
13
13
  import { MODELS } from "../src/models";
14
+ import { VERSION } from "../src/version";
14
15
  import schemaSql from "../schema.sql?raw";
15
16
 
16
17
  const ALICE = "alice@example.com";
@@ -120,6 +121,29 @@ describe("routing + 404 fallthrough", () => {
120
121
  expect(body.ok).toBe(true);
121
122
  });
122
123
 
124
+ it("GET /health puts the serving version on the wire, unauthenticated", async () => {
125
+ // The deploy-verification surface (fleet-chezmoi#1641). This asserts the WIRE, which is a
126
+ // different failure mode from "the literal drifted from package.json" -- that one is owned by
127
+ // tests/version.test.ts, which reads package.json off disk. Breaking the literal reddens that
128
+ // file and leaves this one green; dropping this field reddens this one and leaves that file
129
+ // green, which is what makes them two assertions rather than one check wearing two names.
130
+ //
131
+ // Compared against VERSION rather than a typed literal, so this test cannot itself become a
132
+ // second copy of the version string to forget at release time.
133
+ const res = await req("/health");
134
+ const body = (await res.json()) as { version?: string };
135
+ expect(body.version).toBe(VERSION);
136
+ });
137
+
138
+ it("GET /health/deep carries the version alongside its checks", async () => {
139
+ // Readiness answers 503 for reasons unrelated to which build is running, so the build
140
+ // identifier has to be present on this payload whatever the status code says.
141
+ const res = await req("/health/deep");
142
+ const body = (await res.json()) as { version?: string; checks?: unknown };
143
+ expect(body.version).toBe(VERSION);
144
+ expect(body.checks).toBeDefined();
145
+ });
146
+
123
147
  it("GET /api/models matches the models route", async () => {
124
148
  const res = await req("/api/models", { email: ALICE });
125
149
  expect(res.status).toBe(200);
@@ -327,3 +351,133 @@ describe("gateway 412 refusal path", () => {
327
351
  expect(status).not.toBe(412);
328
352
  });
329
353
  });
354
+
355
+ // ---------------------------------------------------------------------------
356
+ // Inference gate coverage across transports (skyphusion-labs/fleet-chezmoi#1611)
357
+ //
358
+ // The 412 suite above proves the gate fires for one chat model. These assert it
359
+ // holds for every model in the catalog that reaches an image inference path,
360
+ // including the @cf models whose request/response shapes force the call to
361
+ // bypass the AI Gateway transport.
362
+ //
363
+ // The population is DERIVED from MODELS rather than enumerated here. A hand
364
+ // list would have to be extended by whoever adds the next model, which is
365
+ // exactly the maintenance step that does not happen; deriving it means a model
366
+ // landing later with some new transport is covered on the day it lands.
367
+ // ---------------------------------------------------------------------------
368
+
369
+ const IMAGE_MODELS = MODELS.filter((m) => m.type === "image");
370
+ const CF_IMAGE_MODELS = IMAGE_MODELS.filter((m) => !m.provider);
371
+ const PROXIED_IMAGE_MODELS = IMAGE_MODELS.filter((m) => !!m.provider);
372
+
373
+ describe("inference gate: image models, every transport", () => {
374
+ it("harness control: the catalog yields both image transport classes", () => {
375
+ // If either filter stops matching the catalog these counts go to zero and
376
+ // the per-model assertions below vanish silently, passing vacuously. This
377
+ // asserts the population exists so an empty run reads as a harness failure
378
+ // rather than as a clean result.
379
+ expect(IMAGE_MODELS.length).toBeGreaterThan(0);
380
+ expect(CF_IMAGE_MODELS.length).toBeGreaterThan(0);
381
+ expect(PROXIED_IMAGE_MODELS.length).toBeGreaterThan(0);
382
+ });
383
+
384
+ for (const model of IMAGE_MODELS) {
385
+ it(`refuses ${model.id} with 412 when no gateway id resolves`, async () => {
386
+ const res = await req("/api/chat", {
387
+ email: ALICE,
388
+ method: "POST",
389
+ body: { model: model.id, user_input: "a cat" },
390
+ });
391
+ expect(res.status).toBe(412);
392
+ const body = (await res.json()) as { code?: string };
393
+ // Assert WHICH refusal fired. A bare "the request failed" is satisfied
394
+ // by the stubbed AI binding throwing on dispatch, which is the opposite
395
+ // of the gate doing its job: it would mean the request got past the gate
396
+ // and only failed because this harness has no real binding.
397
+ expect(body.code).toBe("gateway_not_configured");
398
+ });
399
+ }
400
+
401
+ it("positive control: a @cf image model dispatches once a gateway id is set", async () => {
402
+ // Proves the 412s above are a real refusal and not an always-on wall. Past
403
+ // the gate the inert AI stub makes dispatch fail; the only claim here is
404
+ // that the failure is no longer the gate.
405
+ const model = CF_IMAGE_MODELS[0]!;
406
+ await req("/api/prefs", {
407
+ email: ALICE,
408
+ method: "PATCH",
409
+ body: { gateway_id: "alice-gw" },
410
+ });
411
+ let status: number;
412
+ try {
413
+ status = (
414
+ await req("/api/chat", {
415
+ email: ALICE,
416
+ method: "POST",
417
+ body: { model: model.id, user_input: "a cat" },
418
+ })
419
+ ).status;
420
+ } catch {
421
+ status = 500;
422
+ }
423
+ expect(status).not.toBe(412);
424
+ });
425
+
426
+ it("proxied image models still require a CF token, and say so distinctly", async () => {
427
+ // The two refusals must stay distinguishable: a gateway id alone satisfies
428
+ // a @cf model (control above) but not a proxied one. If these ever collapse
429
+ // into one code, the control above stops proving anything about @cf models.
430
+ const model = PROXIED_IMAGE_MODELS[0]!;
431
+ await req("/api/prefs", {
432
+ email: BOB,
433
+ method: "PATCH",
434
+ body: { gateway_id: "bob-gw" },
435
+ });
436
+ const res = await req("/api/chat", {
437
+ email: BOB,
438
+ method: "POST",
439
+ body: { model: model.id, user_input: "a cat" },
440
+ });
441
+ expect(res.status).toBe(412);
442
+ const body = (await res.json()) as { code?: string };
443
+ expect(body.code).toBe("cf_aig_token_required");
444
+ });
445
+ });
446
+
447
+ describe("inference gate: live-voice WebSocket upgrade", () => {
448
+ // This path runs inside the SttSession Durable Object rather than in a route
449
+ // handler, and opens its upstream through the same AI binding. It is the one
450
+ // inference entry point that is not an /api/chat dispatch, which is exactly
451
+ // why it needs its own assertion rather than being assumed covered.
452
+ function upgrade(email?: string): Promise<Response> {
453
+ const headers = new Headers({ Upgrade: "websocket" });
454
+ if (email) headers.set("cf-access-authenticated-user-email", email);
455
+ return SELF.fetch("https://prism.test/api/stt/stream", { headers });
456
+ }
457
+
458
+ it("refuses the upgrade with 412 when no gateway id resolves", async () => {
459
+ const res = await upgrade(ALICE);
460
+ expect(res.status).toBe(412);
461
+ const body = (await res.json()) as { code?: string };
462
+ expect(body.code).toBe("gateway_not_configured");
463
+ });
464
+
465
+ it("positive control: past the gate the upgrade reaches the upstream open", async () => {
466
+ // Proves the 412 above is the credential gate and not simply "this path
467
+ // never works in a test". With a gateway id set the DO gets as far as
468
+ // opening the upstream flux socket, which fails against the inert AI stub
469
+ // and surfaces as 502 -- a different failure, at a later stage.
470
+ await req("/api/prefs", {
471
+ email: ALICE,
472
+ method: "PATCH",
473
+ body: { gateway_id: "alice-gw" },
474
+ });
475
+ let status: number;
476
+ try {
477
+ status = (await upgrade(ALICE)).status;
478
+ } catch {
479
+ status = 500;
480
+ }
481
+ expect(status).not.toBe(412);
482
+ });
483
+ });
@@ -11,9 +11,14 @@ import { cloudflareTest } from "@cloudflare/vitest-pool-workers";
11
11
  // Bindings are Miniflare-local and fork-safe (no secrets, no network):
12
12
  // - DB (D1) and R2 are real local Miniflare simulators; the schema is
13
13
  // applied per test from schema.sql (see tests-integration/worker.test.ts).
14
- // - AI, VEC, LONGRUN, STT_SESSION are inert JSON stubs. The routes under
15
- // test never call them; the gateway 412 gate short-circuits before any
16
- // env.AI.run, so no Workers AI / gateway network call is ever made.
14
+ // - AI, VEC and LONGRUN are inert JSON stubs. The routes under test never
15
+ // reach them: the gateway credential gate short-circuits before any
16
+ // env.AI.run, so no Workers AI / gateway network call is ever made. That
17
+ // is asserted rather than assumed -- see the inference-gate suites, which
18
+ // fail if any path dispatches before resolving credentials.
19
+ // - STT_SESSION is a real SQLite-backed Durable Object (class SttSession),
20
+ // mirroring wrangler.example.toml, so the live-voice upgrade path is
21
+ // reachable from a test at all.
17
22
  // - ASSETS is a mock Fetcher returning 404, so the "no route matched"
18
23
  // fallthrough is observable without shipping the public/ tree into the
19
24
  // runtime.
@@ -32,7 +37,17 @@ export default defineConfig({
32
37
  AI: {},
33
38
  VEC: {},
34
39
  LONGRUN: {},
35
- STT_SESSION: {},
40
+ },
41
+ // STT_SESSION is a REAL Durable Object here, not a JSON stub, mirroring
42
+ // the [[durable_objects.bindings]] block in wrangler.example.toml
43
+ // (class SttSession, SQLite-backed). The live-voice upgrade path runs
44
+ // inside the DO, so a stub binding made that path structurally
45
+ // untestable: nothing could reach the code under test. AI stays an
46
+ // inert stub, so a session that gets past the credential gate fails at
47
+ // the upstream open -- which is what makes the gate's refusal
48
+ // distinguishable from a dispatch failure.
49
+ durableObjects: {
50
+ STT_SESSION: { className: "SttSession", useSQLite: true },
36
51
  },
37
52
  serviceBindings: {
38
53
  ASSETS: () => new Response("assets-fallthrough", { status: 404 }),
@@ -54,6 +54,39 @@ index_name = "skyphusion-llm-vec"
54
54
  [assets]
55
55
  directory = "./public"
56
56
  binding = "ASSETS"
57
+ # REQUIRED for the security headers to exist at all (fleet-chezmoi#1646).
58
+ #
59
+ # Workers Assets serves a matching static file WITHOUT invoking the Worker. So
60
+ # with this line absent, `/` is answered entirely by the asset layer, the fetch
61
+ # handler never runs for the HTML document, and the Content-Security-Policy and
62
+ # HSTS headers it sets are dead code on exactly the responses that need them.
63
+ #
64
+ # That is not a theory: it was measured. Before this line, `curl -D - /` on a
65
+ # local dev server returned the HTML with NO policy header; after it, the policy
66
+ # is present, with a non-HTML asset checked as a control to confirm the document
67
+ # policy is not being sprayed onto subresources.
68
+ #
69
+ # Scoped to the HTML documents ONLY rather than set to `true`. Every path listed
70
+ # here stops being served from the asset fast path and costs a Worker
71
+ # invocation, so the list is the real documents plus the root.
72
+ #
73
+ # `/stt` IS THE STT DOCUMENT AND `/stt.html` IS NOT. Measured on a local dev
74
+ # server: `/stt.html` answers `307 -> /stt`, and `/stt` answers `200 text/html`
75
+ # with NO policy header, because only the redirecting path was listed here.
76
+ # Workers Assets `html_handling` drops the `.html` extension by default, so the
77
+ # path a browser actually holds the document at is the extensionless one. The
78
+ # same is true of `/index.html`, which `307`s to `/`; that one was covered only
79
+ # because `/` was listed beside it. Both spellings are kept: a deployer who
80
+ # turns `html_handling` off serves the `.html` path directly.
81
+ #
82
+ # The failure mode is the reason this comment is long: a listed path that only
83
+ # redirects produces no error anywhere. The page simply never carries a policy,
84
+ # never reports a violation, and an empty collector reads as a clean page.
85
+ #
86
+ # DEPLOYERS: wrangler.toml is gitignored and per-deployer, so this template
87
+ # change does NOT reach a live deploy on its own. Copy this line into your own
88
+ # wrangler.toml before deploying, or the CSP ships and silently never applies.
89
+ run_worker_first = ["/", "/index.html", "/stt", "/stt.html"]
57
90
 
58
91
  # Cloudflare Workflow for long-running Unified Billing video and music gen
59
92
  # (v0.12.0). env.AI.run for these models blocks until completion (30s-3min),