@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
@@ -0,0 +1,71 @@
1
+ // PDF text extraction through the shipped extractPdfChunks, in workerd (the production runtime).
2
+ //
3
+ // WHY THIS EXISTS. extractPdfChunks (src/routes/rag.ts) is the only caller of unpdf, and it is what
4
+ // document upload, the zip import and the Discord import reach for every PDF. Until this file, no
5
+ // committed test exercised it: the suite only proved the module LOADS, because src/index.ts imports
6
+ // rag.ts, which imports unpdf. unpdf 1.8.1 -> 2.1.0 (a major, #221) was about to ship on that
7
+ // untested path, so this pins the behaviour prism depends on: per-page text, in page order, tagged
8
+ // with its 1-based page number.
9
+ //
10
+ // THE FIXTURE IS BUILT HERE, not committed as a binary: a minimal two-page PDF with one Helvetica
11
+ // text run per page and a correct xref, so the expected strings are visible in this file and nobody
12
+ // has to trust an opaque blob. Same shape as the probe measured before the v1.2.0 release.
13
+
14
+ import { describe, expect, it } from "vitest";
15
+ import { extractPdfChunks } from "../src/routes/rag";
16
+
17
+ const PAGE_TEXT = ["PRISMPROBE alpha page one", "PRISMPROBE beta page two"];
18
+
19
+ function minimalPdf(pages: string[]): Uint8Array {
20
+ const objs: string[] = [];
21
+ objs.push("<< /Type /Catalog /Pages 2 0 R >>");
22
+ const kids = pages.map((_, i) => `${3 + i * 2} 0 R`).join(" ");
23
+ objs.push(`<< /Type /Pages /Kids [${kids}] /Count ${pages.length} >>`);
24
+ const fontNum = 3 + pages.length * 2;
25
+ pages.forEach((text, i) => {
26
+ objs.push(
27
+ `<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Contents ${4 + i * 2} 0 R ` +
28
+ `/Resources << /Font << /F1 ${fontNum} 0 R >> >> >>`,
29
+ );
30
+ const stream = `BT /F1 24 Tf 72 700 Td (${text}) Tj ET`;
31
+ objs.push(`<< /Length ${stream.length} >>\nstream\n${stream}\nendstream`);
32
+ });
33
+ objs.push("<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>");
34
+
35
+ // ASCII only, so string length is byte length and the xref offsets are exact.
36
+ let out = "%PDF-1.4\n";
37
+ const offsets: number[] = [];
38
+ objs.forEach((body, n) => {
39
+ offsets.push(out.length);
40
+ out += `${n + 1} 0 obj\n${body}\nendobj\n`;
41
+ });
42
+ const xref = out.length;
43
+ out += `xref\n0 ${objs.length + 1}\n0000000000 65535 f \n`;
44
+ for (const off of offsets) out += `${String(off).padStart(10, "0")} 00000 n \n`;
45
+ out += `trailer\n<< /Size ${objs.length + 1} /Root 1 0 R >>\nstartxref\n${xref}\n%%EOF\n`;
46
+ return new TextEncoder().encode(out);
47
+ }
48
+
49
+ describe("extractPdfChunks (unpdf), in workerd", () => {
50
+ it("extracts each page's text in order, tagged with its 1-based page number", async () => {
51
+ const chunks = await extractPdfChunks(minimalPdf(PAGE_TEXT));
52
+ expect(chunks).toEqual([
53
+ { text: PAGE_TEXT[0], page: 1 },
54
+ { text: PAGE_TEXT[1], page: 2 },
55
+ ]);
56
+ });
57
+
58
+ it("skips a page with no text layer instead of emitting an empty chunk", async () => {
59
+ // The middle page draws nothing: an empty text layer, the shape of a scanned page.
60
+ const pdf = minimalPdf([PAGE_TEXT[0], "", PAGE_TEXT[1]]);
61
+ const chunks = await extractPdfChunks(pdf);
62
+ expect(chunks).toEqual([
63
+ { text: PAGE_TEXT[0], page: 1 },
64
+ { text: PAGE_TEXT[1], page: 3 },
65
+ ]);
66
+ });
67
+
68
+ it("rejects bytes that are not a PDF, rather than returning an empty success", async () => {
69
+ await expect(extractPdfChunks(new TextEncoder().encode("not a pdf at all"))).rejects.toThrow();
70
+ });
71
+ });
@@ -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 }),
@@ -46,6 +46,10 @@ bucket_name = "skyphusion-llm"
46
46
  # @cf/baai/bge-base-en-v1.5; cosine similarity.
47
47
  # Create with:
48
48
  # npx wrangler vectorize create skyphusion-llm-vec --dimensions=768 --metric=cosine
49
+ # npx wrangler vectorize create-metadata-index skyphusion-llm-vec --property-name=user_email --type=string
50
+ # The metadata index lets retrieval filter by user in Vectorize itself
51
+ # (VEC_METADATA_FILTER, below). Create it before the first document upload: an
52
+ # index added later does not cover vectors already written. See MIGRATIONS.md.
49
53
  [[vectorize]]
50
54
  binding = "VEC"
51
55
  index_name = "skyphusion-llm-vec"
@@ -54,6 +58,39 @@ index_name = "skyphusion-llm-vec"
54
58
  [assets]
55
59
  directory = "./public"
56
60
  binding = "ASSETS"
61
+ # REQUIRED for the security headers to exist at all (fleet-chezmoi#1646).
62
+ #
63
+ # Workers Assets serves a matching static file WITHOUT invoking the Worker. So
64
+ # with this line absent, `/` is answered entirely by the asset layer, the fetch
65
+ # handler never runs for the HTML document, and the Content-Security-Policy and
66
+ # HSTS headers it sets are dead code on exactly the responses that need them.
67
+ #
68
+ # That is not a theory: it was measured. Before this line, `curl -D - /` on a
69
+ # local dev server returned the HTML with NO policy header; after it, the policy
70
+ # is present, with a non-HTML asset checked as a control to confirm the document
71
+ # policy is not being sprayed onto subresources.
72
+ #
73
+ # Scoped to the HTML documents ONLY rather than set to `true`. Every path listed
74
+ # here stops being served from the asset fast path and costs a Worker
75
+ # invocation, so the list is the real documents plus the root.
76
+ #
77
+ # `/stt` IS THE STT DOCUMENT AND `/stt.html` IS NOT. Measured on a local dev
78
+ # server: `/stt.html` answers `307 -> /stt`, and `/stt` answers `200 text/html`
79
+ # with NO policy header, because only the redirecting path was listed here.
80
+ # Workers Assets `html_handling` drops the `.html` extension by default, so the
81
+ # path a browser actually holds the document at is the extensionless one. The
82
+ # same is true of `/index.html`, which `307`s to `/`; that one was covered only
83
+ # because `/` was listed beside it. Both spellings are kept: a deployer who
84
+ # turns `html_handling` off serves the `.html` path directly.
85
+ #
86
+ # The failure mode is the reason this comment is long: a listed path that only
87
+ # redirects produces no error anywhere. The page simply never carries a policy,
88
+ # never reports a violation, and an empty collector reads as a clean page.
89
+ #
90
+ # DEPLOYERS: wrangler.toml is gitignored and per-deployer, so this template
91
+ # change does NOT reach a live deploy on its own. Copy this line into your own
92
+ # wrangler.toml before deploying, or the CSP ships and silently never applies.
93
+ run_worker_first = ["/", "/index.html", "/stt", "/stt.html"]
57
94
 
58
95
  # Cloudflare Workflow for long-running Unified Billing video and music gen
59
96
  # (v0.12.0). env.AI.run for these models blocks until completion (30s-3min),
@@ -132,6 +169,10 @@ enabled = true
132
169
  # commented vars header (CI uncomments every "# [vars]" line and TOML breaks).
133
170
  # CONTROL_PLANE_URL = "https://play-proxy.skyphusion.org"
134
171
  # CONTROL_PLANE_ALLOW_LOCALHOST = "true"
172
+ # RAG retrieval filtered by user in Vectorize (fleet-chezmoi#1636). Off unless
173
+ # "on". Needs the user_email metadata index AND, on an index that already holds
174
+ # vectors, scripts/vectorize-backfill-metadata.mjs run after it. See MIGRATIONS.md.
175
+ # VEC_METADATA_FILTER = "on"
135
176
 
136
177
  # Note: GATEWAY_ID is set as a worker secret rather than a var in this file
137
178
  # (v0.12.0+). This keeps deployer-specific values out of the committed template.
@@ -141,8 +182,10 @@ enabled = true
141
182
  # GATEWAY_ID=your-gateway-slug
142
183
  #
143
184
  # Public mode (v0.167.0+): omit GATEWAY_ID and CF_AIG_TOKEN on the worker.
144
- # Each visitor stores their own gateway slug + token via Account > AI Gateway
145
- # (/api/prefs in D1 user_prefs). No Cloudflare Access needed when AUTH_MODE=public.
185
+ # Each visitor stores their own Cloudflare account id, gateway slug, and token
186
+ # via Account > AI Gateway (/api/prefs in D1 user_prefs); v1.1.0 requires the
187
+ # account id, since the AI binding can only reach this worker's own account.
188
+ # No Cloudflare Access needed when AUTH_MODE=public.
146
189
  #
147
190
  # Other worker secrets (also set via `npx wrangler secret put <NAME>`):
148
191
  # OPENAI_API_KEY (optional sole BYOK carve-out, v0.174.0): when set,