@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
package/README.md CHANGED
@@ -79,10 +79,13 @@ The scaffolded worker learns who a caller is one of two ways, chosen by the
79
79
  Inference bills the deployer, through the worker gateway secrets `GATEWAY_ID` and
80
80
  `CF_AIG_TOKEN`.
81
81
  - **`public` (the open, first-party-signup service).** First-party username/password
82
- accounts behind an opaque server-side session cookie. Every user brings their own AI
83
- Gateway credentials (mandatory BYOK), so **the worker holds no gateway secrets and
84
- visitor inference never bills the host**. Do not set `GATEWAY_ID` / `CF_AIG_TOKEN` on
85
- a public worker; they are ignored in this mode. No Cloudflare Access needed.
82
+ accounts behind an opaque server-side session cookie. Every user brings their own
83
+ Cloudflare account ID, AI Gateway slug, and API token (mandatory BYOK), so the worker
84
+ holds no gateway secrets and gateway-routed inference bills the visitor's account.
85
+ The exception is the few Workers AI paths AI Gateway cannot proxy (live voice,
86
+ Deepgram STT, six image models), which run on the host's `AI` binding and bill the
87
+ host. Do not set `GATEWAY_ID` / `CF_AIG_TOKEN` on a public worker; they are ignored in
88
+ this mode. No Cloudflare Access needed.
86
89
 
87
90
  Either way, one stable opaque account id scopes history and R2 ownership, so cross-user
88
91
  access is impossible even if an id is guessed.
package/index.js CHANGED
@@ -127,6 +127,7 @@ Next steps:
127
127
  npm run db:migrate:remote
128
128
  npx wrangler r2 bucket create skyphusion-llm
129
129
  npx wrangler vectorize create skyphusion-llm-vec --dimensions=768 --metric=cosine
130
+ npx wrangler vectorize create-metadata-index skyphusion-llm-vec --property-name=user_email --type=string
130
131
  5. Set the worker secrets (access mode, the default):
131
132
  npx wrangler secret put GATEWAY_ID (your AI Gateway slug)
132
133
  npx wrangler secret put CF_AIG_TOKEN (AI Gateway Run token, for paid models)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@skyphusion/create-prism",
3
- "version": "1.0.0",
3
+ "version": "1.2.0",
4
4
  "description": "Scaffold a new prism deployment: a multimodal AI playground on Cloudflare Workers.",
5
5
  "license": "AGPL-3.0-only",
6
6
  "author": "Conrad Rockenhaus",
@@ -79,6 +79,21 @@ By submitting a contribution, you agree that your work will be licensed under AG
79
79
  Sign off every commit with `git commit -s`. That appends a `Signed-off-by:` line certifying the
80
80
  [Developer Certificate of Origin](https://developercertificate.org/) (DCO): a lightweight,
81
81
  per-commit affirmation that you wrote the patch or otherwise have the right to submit it under the
82
- project's license. We use the DCO instead of a CLA. The name and email must be real and match the
83
- commit author; unsigned commits may be asked to amend with `git commit --amend -s` (or
84
- `git rebase --signoff` for a series) before merge.
82
+ project's license. We use the DCO instead of a CLA. Use a real name and email.
83
+
84
+ This is checked, not just asked for. The `dco` workflow (`.github/workflows/dco.yml`) runs on every
85
+ pull request and fails if any non-merge commit in the PR lacks a `Signed-off-by:` trailer whose
86
+ email matches the commit author email (case-insensitive). A PR that adds no non-merge commits
87
+ fails, because there is nothing to certify. Only pull requests opened by the `dependabot[bot]`
88
+ account are exempt; the exemption follows the account that opened the PR, not the commit author
89
+ email, so a bot-looking email on your own commits is still checked. It applies to everyone,
90
+ maintainers included; history already on `main` is not re-checked.
91
+
92
+ If the check fails, sign off the branch and force-push; the job summary prints the exact command:
93
+
94
+ ```bash
95
+ git rebase --signoff <fork-point> # or: git commit --amend -s --no-edit (single commit)
96
+ git push --force-with-lease
97
+ ```
98
+
99
+ To stop forgetting, use an alias such as `git config --global alias.cs 'commit -s'`.
@@ -8,6 +8,8 @@ redeploy.
8
8
 
9
9
  **Migration philosophy (read this first).** `schema.sql` is the canonical full schema for standing up a *fresh* database. It contains non-idempotent `ALTER TABLE` statements, so re-running it against a database that already has tables will raise `SQLITE_ERROR: duplicate column name` and, because `wrangler d1 execute --file` runs the whole file as one transaction, abort and roll back the entire run. **Never re-run `schema.sql` against an existing database.** To upgrade an existing deployment, apply only the delta for each version you're crossing, using the explicit commands below (or, for releases that ship one, the per-release `migrate-vX.Y.Z.sql` delta file). Apply each version's delta in order, then redeploy.
10
10
 
11
+ **v1.1.0 (account-scoped BYOK): BREAKING for existing BYOK users, no DDL.** `account_id` is a new key in the existing `user_prefs.prefs_json` blob. Every public-mode user saved before v1.1.0 (slug + token only) is refused with HTTP 412 `gateway_account_id_required` on every inference route until they add their 32-hex Cloudflare account ID under Account > AI Gateway, and their token must hold Workers AI Read as well as AI Gateway Run. A user who upgrades and does nothing loses inference. Tell your users before you tag. Access-mode installs using worker secrets are unaffected.
12
+
11
13
  v0.13.0 onward touched the D1 schema only at v0.20.0, v0.20.2, and v0.20.3; everything else in the v0.13.0 to v0.20.0 range is code-only. The pre-v0.13.0 migrations (v0.7.0 to v0.10.0) are below for anyone upgrading from very old deployments.
12
14
 
13
15
  For v0.7.0 (video generation):
@@ -24,6 +26,7 @@ For v0.8.0 (RAG Pass 1):
24
26
 
25
27
  ```
26
28
  npx wrangler vectorize create skyphusion-llm-vec --dimensions=768 --metric=cosine
29
+ npx wrangler vectorize create-metadata-index skyphusion-llm-vec --property-name=user_email --type=string
27
30
  # Create the documents and chunks tables explicitly. (Historically this step
28
31
  # was "--file=schema.sql"; that is no longer safe because today's schema.sql
29
32
  # also carries later non-idempotent ALTERs. Use the explicit DDL below.)
@@ -195,3 +198,52 @@ statement and continues. Fresh installs get all of the above from `schema.sql` a
195
198
  none of these deltas.
196
199
 
197
200
  All other releases are code/frontend-only with no D1 migration.
201
+
202
+ ## Vectorize metadata filter for RAG retrieval (fleet-chezmoi#1636)
203
+
204
+ **Why.** Retrieval used to query Vectorize globally and scope by user only in the D1 join. On a shared
205
+ index, a user with a small share of the vectors can get a top-K made entirely of other users' vectors,
206
+ which the join then drops, so they see no results even when their own documents match.
207
+ `VEC_METADATA_FILTER = "on"` filters the Vectorize query on `user_email` as well. The D1 join stays,
208
+ as the second layer of scope.
209
+
210
+ **It is off by default, and the order matters.** A Vectorize metadata index is not retroactive. Turn
211
+ the filter on before the backfill, and every vector written before the index existed is invisible to it:
212
+ retrieval returns nothing.
213
+
214
+ 1. Create the metadata index (once):
215
+
216
+ ```bash
217
+ npx wrangler vectorize create-metadata-index skyphusion-llm-vec --property-name=user_email --type=string
218
+ ```
219
+
220
+ Vectors upserted from now on are indexed automatically.
221
+
222
+ 2. If the index already holds vectors, re-upsert them. The script reads every id from D1
223
+ `chunks.vector_id`, fetches each vector, and writes it back with the same id, values and metadata.
224
+ Nothing is re-embedded. It refuses to run until step 1 is done, prints counts only (never an id or a
225
+ value), and is safe to re-run.
226
+
227
+ ```bash
228
+ CLOUDFLARE_API_TOKEN=... CLOUDFLARE_ACCOUNT_ID=... \
229
+ node scripts/vectorize-backfill-metadata.mjs --index skyphusion-llm-vec --d1 <D1 database uuid> --dry-run
230
+ CLOUDFLARE_API_TOKEN=... CLOUDFLARE_ACCOUNT_ID=... \
231
+ node scripts/vectorize-backfill-metadata.mjs --index skyphusion-llm-vec --d1 <D1 database uuid>
232
+ ```
233
+
234
+ The token needs Vectorize Edit and D1 Read. Exit 0 means every D1 id was re-upserted. Exit 1 means
235
+ some ids had no vector (`gaps`) or no `user_email` metadata (`missing_metadata`); do not turn the
236
+ filter on until that is understood. Exit 2 means it refused or could not read, and nothing was written.
237
+
238
+ 3. Verify, then set `VEC_METADATA_FILTER = "on"` (a plain var) and deploy. Check that a user with
239
+ documents still gets results, and that the index `info` vector count matches the script's `upserted`
240
+ count. Allow a few seconds after the upsert for Vectorize to apply it.
241
+
242
+ A fresh deployment that creates the metadata index before its first upload needs only step 1, then the
243
+ var.
244
+
245
+ **Caveat:** a string metadata index matches on the first 64 bytes of the value. Public-mode identities
246
+ (`usr_` plus 24 hex characters) are well inside that. In access mode, two emails sharing their first 64
247
+ bytes would share an index entry. The D1 join still scopes their results correctly, so the worst case
248
+ for those users is the old global behaviour, not a disclosure.
249
+
@@ -4,7 +4,7 @@
4
4
  [![Typecheck](https://github.com/skyphusion-labs/prism/actions/workflows/typecheck.yml/badge.svg)](https://github.com/skyphusion-labs/prism/actions/workflows/typecheck.yml)
5
5
  [![Voice chat](https://img.shields.io/badge/%F0%9F%8E%99%EF%B8%8F_voice_chat-speak_%26_hear_chat_models-6d8cff)](#voice-chat)
6
6
 
7
- A multimodal AI playground deployed as a single Cloudflare Worker. **Live demo:** https://play.skyphusion.org (free signup, bring your own AI Gateway). Catalog breadth is live at `GET /api/models` (and `src/models.ts`): **93** models (44 chat + 21 image + 19 video + 3 TTS + 4 STT + 1 music + 1 live voice); the tables under [Features](#features) list every id. Native clients hit the commercial plane ([prism-control-plane](https://github.com/skyphusion-labs/prism-control-plane)); this Worker is the playground surface (RAG, projects, compact, web search). **Hands-free voice chat**, cross-model artifact reuse, RAG, projects, Discord ingestion, web search, SSE streaming, and multi-turn conversations (with optional **compact**). One web UI with first-party accounts, per-user history, R2 for all binary artifacts.
7
+ A multimodal AI playground deployed as a single Cloudflare Worker. **Live demo:** https://play.skyphusion.org (free signup, bring your own AI Gateway; a short list of demo capabilities is funded by the host, see [Who pays for what](#who-pays-for-what)). Catalog breadth is live at `GET /api/models` (and `src/models.ts`): **93** models (44 chat + 21 image + 19 video + 3 TTS + 4 STT + 1 music + 1 live voice); the tables under [Features](#features) list every id. Native clients hit the commercial plane ([prism-control-plane](https://github.com/skyphusion-labs/prism-control-plane)); this Worker is the playground surface (RAG, projects, compact, web search). **Hands-free voice chat**, cross-model artifact reuse, RAG, projects, Discord ingestion, web search, SSE streaming, and multi-turn conversations (with optional **compact**). One web UI with first-party accounts, per-user history, R2 for all binary artifacts.
8
8
 
9
9
  ```mermaid
10
10
  flowchart TB
@@ -70,8 +70,8 @@ A working template for the Cloudflare AI stack and a self-hosted multimodal play
70
70
 
71
71
  One Worker, no framework, no build step beyond TypeScript. The interesting parts are the patterns, not the model count:
72
72
 
73
- - **Unified `env.AI.run()` binding** drives every modality through one call surface: chat, vision input, image gen, TTS, STT, conversational STT + voice chat (Flux over a WebSocket), video gen, and music gen. Paid third-party models bill through **Cloudflare Unified Billing** on your AI Gateway.
74
- - **Per-provider dispatch helpers** for Anthropic Claude, xAI Grok, and Google Gemini, each transforming our internal `messages` shape into the provider's native format while authorizing keylessly via `cf-aig-authorization`. OpenAI chat and Workers AI ride the `env.AI.run` binding directly. **Sole deployer BYOK carve-out (v0.174.0):** optional `OPENAI_API_KEY` lets `openai/gpt-image-*` call `api.openai.com` for transparent PNG (the CF proxy 7003-rejects `background`/`output_format`). When unset, those models stay opaque on Unified Billing. Do not set this key on public multi-tenant deploys.
73
+ - **Unified `env.AI.run()` binding** drives every modality through one call surface: chat, vision input, image gen, TTS, STT, conversational STT + voice chat (Flux over a WebSocket), video gen, and music gen. Paid third-party models bill through **Cloudflare Unified Billing** on your AI Gateway. The binding can only reach the worker's own Cloudflare account, so in public mode (v1.1.0) the same `aiRun` seam swaps to the Cloudflare REST API (`/accounts/{account_id}/ai/run`) on each user's own account; see [Who pays for what](#who-pays-for-what).
74
+ - **Per-provider dispatch helpers** for Anthropic Claude, xAI Grok, and Google Gemini, each transforming our internal `messages` shape into the provider's native format while authorizing keylessly via `cf-aig-authorization`. OpenAI chat and Workers AI ride the `env.AI.run` binding directly. **Sole deployer BYOK carve-out (v0.174.0):** optional `OPENAI_API_KEY` lets `openai/gpt-image-*` call `api.openai.com` for transparent PNG (the CF proxy 7003-rejects `background`/`output_format`). When unset, those models stay opaque on Unified Billing. Public mode (`AUTH_MODE=public`) ignores the key even if set (v1.0.5, prism#193).
75
75
  - **SSE streaming** (v0.13.0+) for chat models across providers: Anthropic native SSE, Workers AI / OpenAI-compatible SSE (incl. Moonshot K3), xAI, OpenAI Chat Completions and Responses API (v0.173.0), and Gemini.
76
76
  - **AI Gateway** wraps every call for observability, caching, and rate-limiting.
77
77
  - **D1** holds chat metadata, multi-turn conversation history, and RAG chunk text. **R2** holds all binary artifacts. **Vectorize** holds RAG embeddings (768-dim BGE-base). The chat row references R2 keys; nothing binary touches D1.
@@ -241,7 +241,7 @@ One Worker, no framework, no build step beyond TypeScript. The interesting parts
241
241
 
242
242
  **UI (focus-mode redesign, v0.110.0+):** a single centered conversation column with a floating composer; the sidebar (searchable history, projects, documents) is a slide-in overlay; a searchable model picker (type to filter, v0.111.0); a ⚙ popover for the system prompt + retrieval toggles and an account menu in the top bar; a paperclip attach button and a voice-chat mic; conversation header **compact** / **expand** when a thread has enough turns (v0.175.7). Capability-aware mode switching (vision-only attachment types; image-mode re-skins to "negative prompt"; TTS / STT / video / music / voice hide irrelevant inputs), FLUX.2 reference-image attach UI (v0.16.0), per-turn web-search toggle (v0.17.0), per-user replay-able history with attachments and generated artifacts, Enter to send / Shift+Enter for newline. Mobile-optimized (safe-area insets, touch targets, no iOS zoom).
243
243
 
244
- **Auth (two modes via `AUTH_MODE`):** **public** (the hosted product) is first-party username/password signup with an opaque session cookie and mandatory per-user BYOK: each user brings their own AI Gateway, the worker holds no gateway secrets, and inference bills the user, never the host. **access** (the default, for private self-host) puts Cloudflare Access on the worker URL and scopes per-user history and R2 ownership via `Cf-Access-Authenticated-User-Email` (free up to 50 seats on Zero Trust). See [Running the public service](#running-the-public-service).
244
+ **Auth (two modes via `AUTH_MODE`):** **public** (the hosted product) is first-party username/password signup with an opaque session cookie and mandatory per-user BYOK: each user supplies their Cloudflare account ID, AI Gateway slug, and API token, and the worker ignores its own gateway and OpenAI secrets. A handful of Workers AI (`@cf/*`) paths that cannot ride a gateway still run on the host's `AI` binding and bill the host; see [Who pays for what](#who-pays-for-what). **access** (the default, for private self-host) puts Cloudflare Access on the worker URL and scopes per-user history and R2 ownership via `Cf-Access-Authenticated-User-Email` (free up to 50 seats on Zero Trust). See [Running the public service](#running-the-public-service).
245
245
 
246
246
  ## Stack
247
247
 
@@ -318,7 +318,7 @@ echo "CF_AIG_TOKEN=your-cloudflare-api-token" >> .dev.vars
318
318
 
319
319
  Then enable Unified Billing for each provider you plan to use: Dashboard > AI > AI Gateway > your gateway > Settings. Without credits, proxied models fail with `2021: Invalid User Credentials`.
320
320
 
321
- OpenAI chat never uses a deployer key. The **only** optional deployer secret is `OPENAI_API_KEY` (v0.174.0): when set, `openai/gpt-image-*` call `api.openai.com` for transparent PNG; when unset they stay opaque on Unified Billing. Leave it unset on public multi-tenant deploys so visitors cannot burn host credits.
321
+ OpenAI chat never uses a deployer key. The **only** optional deployer secret is `OPENAI_API_KEY` (v0.174.0): when set, `openai/gpt-image-*` call `api.openai.com` for transparent PNG; when unset they stay opaque on Unified Billing. Public mode (`AUTH_MODE=public`) ignores the key even if set (v1.0.5, prism#193), so it cannot bill the host for a visitor's image.
322
322
 
323
323
  > **Public service:** to run the open, first-party-signup instance instead (no worker gateway secrets; every user brings their own AI Gateway), see [Running the public service](#running-the-public-service), and skip steps 1, 1b, and 6.
324
324
 
@@ -357,8 +357,13 @@ For RAG over PDFs and spreadsheets:
357
357
 
358
358
  ```
359
359
  npx wrangler vectorize create skyphusion-llm-vec --dimensions=768 --metric=cosine
360
+ npx wrangler vectorize create-metadata-index skyphusion-llm-vec --property-name=user_email --type=string
360
361
  ```
361
362
 
363
+ The second command adds a `user_email` metadata index, which lets retrieval filter by user inside Vectorize
364
+ (`VEC_METADATA_FILTER = "on"`). Create it now, before any upload: an index added later does not cover
365
+ vectors already written, and those need the backfill in [MIGRATIONS.md](MIGRATIONS.md).
366
+
362
367
  The `VEC` binding is already in the template. If you don't intend to use RAG, the worker still functions; the binding just goes unused.
363
368
 
364
369
  ### 5. First deploy
@@ -418,7 +423,8 @@ npm run dev
418
423
  ## Running the public service
419
424
 
420
425
  Run Prism as an open, self-serve service: anyone signs up with a username and password, and each user
421
- brings their own Cloudflare AI Gateway so their model usage bills their own account, never yours. This
426
+ brings their own Cloudflare account and AI Gateway for inference. A short list of Workers AI (`@cf/*`) paths
427
+ that cannot ride a gateway still run on your `AI` binding and bill you; see [Who pays for what](#who-pays-for-what). This
422
428
  is how play.skyphusion.org runs. It is a **mode of the same worker** (`AUTH_MODE=public`), not a second
423
429
  deployment.
424
430
 
@@ -429,7 +435,7 @@ deployment.
429
435
  | `AUTH_MODE` | `access` (default; may be unset) | `public` |
430
436
  | Sign-in | Cloudflare Access (email OTP / OAuth) | First-party username + password signup |
431
437
  | Worker gateway secrets | `GATEWAY_ID` + `CF_AIG_TOKEN` (yours; you pay inference) | **None** (omit both; ignored even if set) |
432
- | Who pays for inference | You (the deployer) | Each user, via their own AI Gateway |
438
+ | Who pays for inference | You (the deployer) | Each user, on their own Cloudflare account (v1.1.0), except the gateway-bypass Workers AI paths: you |
433
439
  | Cloudflare Access app | Required | **Not used** |
434
440
 
435
441
  Everything else (D1, R2, Vectorize, deploy) is the same as the [Quickstart](#quickstart): do steps 2 to
@@ -445,8 +451,9 @@ AUTH_MODE = "public"
445
451
  ```
446
452
 
447
453
  In public mode the worker runs its own username/password accounts and reads identity from an opaque
448
- session cookie. It never reads `GATEWAY_ID` / `CF_AIG_TOKEN`, so a stray gateway secret cannot make the
449
- host pay for a visitor's inference; gateway credentials come only from each user's own settings.
454
+ session cookie. It never reads `GATEWAY_ID` / `CF_AIG_TOKEN` / `OPENAI_API_KEY` (the last from v1.0.5), so a
455
+ stray deployer secret cannot make the host pay for a visitor's partner-model inference; gateway credentials
456
+ come only from each user's own settings.
450
457
 
451
458
  ### 2. Do not set worker gateway secrets, and do not put Access in front
452
459
 
@@ -470,14 +477,39 @@ npm run deploy
470
477
  ### How users get set up (mandatory BYOK)
471
478
 
472
479
  1. Open the URL and **sign up** with a username and password (no email, no Access login).
473
- 2. Open **Account > AI Gateway**; create a Cloudflare AI Gateway in the [Cloudflare dashboard](https://developers.cloudflare.com/ai-gateway/) if needed, and enable Unified Billing for the providers you want.
474
- 3. Paste the gateway **slug** and a Cloudflare API token with **AI Gateway Run** permission.
475
- 4. Run models. Until a user configures their gateway, paid and proxied models fail closed with a clear "configure your AI Gateway" prompt (HTTP 412), so no call ever bills the host.
480
+ 2. Open **Account > AI Gateway**; create a Cloudflare AI Gateway in the [Cloudflare dashboard](https://developers.cloudflare.com/ai-gateway/) if needed, and load Unified Billing credits on that account.
481
+ 3. Paste the Cloudflare **account ID** (32 hex characters, from the dashboard), the gateway **slug**, and an API token scoped to that account with **Workers AI Read** (the REST API refuses a token that holds only AI Gateway permissions) and **AI Gateway Run** (the provider-native gateway endpoints). All three are required.
482
+ 4. Run models. Until a user configures all three, every model fails closed with HTTP 412 and a code naming what is missing (`gateway_not_configured`, `gateway_account_id_required`, `cf_aig_token_required`). The gate controls who may run inference; it does not change which account the gateway-bypass paths bill (see below).
483
+
484
+ **Why the account ID is required (v1.1.0).** Before v1.1.0 a user stored only a slug and a token, and every call resolved that slug on the worker's own `AI` binding. Cloudflare pins a binding's gateway to the worker's account ("Must be in the same account as your Worker"), and an AI Gateway URL is `.../v1/{account_id}/{gateway_id}/{provider}`, so the account was always the host's: a user's own gateway was unreachable, and those calls either failed or billed the host, never the user. Users saved under that shape keep their slug and token but are refused with `gateway_account_id_required` until they add the account ID; nothing falls back to the host.
476
485
 
477
486
  ### Who pays for what
478
487
 
479
488
  - **You (the host)** pay Cloudflare for Workers, D1, R2, and Vectorize: the storage and compute for the service itself.
480
- - **Each user** pays for their own model inference through Unified Billing on the AI Gateway they configured.
489
+ - **Each user** pays for every call that goes through the `aiRun` seam or a provider-native gateway endpoint, on their own Cloudflare account and gateway (v1.1.0): all partner models (Anthropic, xAI, Google, OpenAI, and the other Unified Billing providers, including image, video, and music), Workers AI chat, TTS, Whisper STT, FLUX.1 / Lucid Origin image gen, and the RAG embeddings (`@cf/baai/bge-base-en-v1.5`) behind document upload and retrieval.
490
+ - **You (the host)** pay for the Workers AI paths that call the worker's `AI` binding directly because AI Gateway cannot proxy them, which means the user's account cannot be reached either: the six stream-incompatible image models (FLUX.2 Klein 9B / Klein 4B / Dev, Leonardo Phoenix 1.0, Dreamshaper 8 LCM, SDXL), Deepgram file STT, and the live-voice Flux socket. Bound this with Workers AI limits on your account or remove those models from `src/models.ts` on your instance.
491
+ - **Control-plane users** (`pcp_` key) bill chat through prism-control-plane under its own metering, not through either account above. That plane stores no chat text. Media it generates, and reference images uploaded to it, are kept 30 days and then deleted ([its retention section](https://github.com/skyphusion-labs/prism-control-plane/blob/main/docs/CONTRACT.md)).
492
+
493
+ **How it works.** In `AUTH_MODE=public`, the host funds a named set of demo capabilities on purpose. Every other inference call bills the user's own Cloudflare account.
494
+
495
+ The 412 gate (`gateway_account_id_required`) decides who may run inference. It does not decide which account pays. The `AI` binding always runs on the worker's own account, and Cloudflare does not let a binding reach another account. The gateway-bypass paths use the binding, so they bill the host. The `aiRun` paths use the REST API with the user's token, so they bill the user.
496
+
497
+ This table was read from the code on `main` (v1.1.1). It shows what the code does, not what a deployed worker runs.
498
+
499
+ | Capability | Code path | Billed to |
500
+ |---|---|---|
501
+ | FLUX.2 Klein 9B, Klein 4B, Dev; Leonardo Phoenix 1.0; Dreamshaper 8 LCM; SDXL | `bypassGateway` in `src/routes/chat.ts` calls `env.AI.run` | **Host** |
502
+ | Deepgram Nova-3 file speech-to-text | `viaDeepgram` in `src/routes/chat.ts` calls `env.AI.run` | **Host** |
503
+ | Live voice (Deepgram Flux websocket) | `src/stt-session.ts` calls `env.AI.run` | **Host** |
504
+ | Workers AI chat, TTS, Whisper, FLUX.1 schnell, Lucid Origin | `aiRun`, which uses the REST API on the user's account | User |
505
+ | RAG embeddings (`@cf/baai/bge-base-en-v1.5`) | `aiRun` in `src/routes/rag.ts` | User |
506
+ | Partner models through `aiRun` (OpenAI, Anthropic, xAI, Google, video, music) | `aiRun`, including the long-run Workflow | User |
507
+ | Anthropic and xAI legacy provider-native path | `gatewayProviderUrl` builds the URL from the user's account ID | User |
508
+ | Control-plane chat (`pcp_` key) | prism-control-plane | Its own metering |
509
+
510
+ The Anthropic, xAI and `aiRun` partner-model rows were Unverified in PR #195. Reading `resolveGateway` closes them. In public mode it returns credentials only with an account ID, so those calls always carry the user's account.
511
+
512
+ **Review trigger.** If daily Workers AI neurons pass 5,000, a cap proposal gets written. Nothing enforces this number. It starts a decision and does not limit use. The free allocation is 10,000 neurons per day. Measured use was 8,635 neurons in the 30 days to 2026-10-08, so the cost today is zero. That window ran almost entirely before v1.1.0, when chat and embeddings also ran on the binding. v1.1.0 is deployed on play (`/health` reported `1.1.0` on 2026-10-08), so the host-funded set is now the three rows above. The 8,635 figure predates it and has not been re-measured against the new shape. `main` may be ahead of the deployed version.
481
513
 
482
514
  ### Abuse controls and policies
483
515
 
@@ -785,7 +817,7 @@ This is a Cloudflare-proxied (third-party) model, so it requires Unified Billing
785
817
 
786
818
  ## Image generation
787
819
 
788
- **21** image models in `src/models.ts` (or `GET /api/models?type=image`): Google Nano Banana Pro / 2 / Lite, Imagen 4, GPT Image 1.5 / 2, Recraft V4 / V4.1 / V4.1 Pro, xAI Grok Imagine Image (+ Quality), ByteDance Seedream 5 Pro / Lite, FLUX 2 Klein 9B/4B, FLUX 2 Dev, FLUX-1 schnell, Lucid Origin, Phoenix 1.0, Dreamshaper 8 LCM, Stable Diffusion XL. The eight FLUX/Leonardo/Lykon/Stability models run through Workers AI (no Unified Billing required); the rest are proxied partner models on Unified Billing (need CF credits). GPT Image 1.5 / 2 are opaque on the proxy by default; **optional deployer BYOK (v0.174.0):** set `OPENAI_API_KEY` for transparent PNG via `api.openai.com` (leave unset on public multi-tenant play).
820
+ **21** image models in `src/models.ts` (or `GET /api/models?type=image`): Google Nano Banana Pro / 2 / Lite, Imagen 4, GPT Image 1.5 / 2, Recraft V4 / V4.1 / V4.1 Pro, xAI Grok Imagine Image (+ Quality), ByteDance Seedream 5 Pro / Lite, FLUX 2 Klein 9B/4B, FLUX 2 Dev, FLUX-1 schnell, Lucid Origin, Phoenix 1.0, Dreamshaper 8 LCM, Stable Diffusion XL. The eight FLUX/Leonardo/Lykon/Stability models run through Workers AI (no Unified Billing required); the rest are proxied partner models on Unified Billing (need CF credits). GPT Image 1.5 / 2 are opaque on the proxy by default; **optional deployer BYOK (v0.174.0):** set `OPENAI_API_KEY` for transparent PNG via `api.openai.com` (ignored in public mode, v1.0.5).
789
821
 
790
822
  ### Google Nano Banana Pro (Unified Billing, v0.21.2)
791
823
 
@@ -802,7 +834,7 @@ This is a Cloudflare-proxied (third-party) model, so it requires Unified Billing
802
834
 
803
835
  - **Recraft V4** (`recraft/recraftv4`, Unified Billing) is opaque and art-directed (strong composition and text rendering). The CF proxy exposes no alpha control, only an opaque `background_color`. It returns WebP; the worker stores it with the response content-type, so no format is hardcoded.
804
836
 
805
- - **GPT Image 1.5 / 2** (`openai/gpt-image-1.5`, `openai/gpt-image-2`) are opaque through the Unified Billing proxy by default (`{ prompt, quality, size }`; proxy 7003-rejects `background`/`output_format`). **Optional BYOK (v0.174.0):** when `OPENAI_API_KEY` is set, `runImage` calls `api.openai.com` via `src/providers/openai-image.ts` for transparent PNG. Leave the secret unset on public play.
837
+ - **GPT Image 1.5 / 2** (`openai/gpt-image-1.5`, `openai/gpt-image-2`) are opaque through the Unified Billing proxy by default (`{ prompt, quality, size }`; proxy 7003-rejects `background`/`output_format`). **Optional BYOK (v0.174.0):** when `OPENAI_API_KEY` is set, `runImage` calls `api.openai.com` via `src/providers/openai-image.ts` for transparent PNG. Public mode ignores the secret (v1.0.5, prism#193).
806
838
  - **xAI Grok Imagine** (`xai/grok-imagine-image`, `-quality`): request `response_format: "b64_json"` on Unified Billing (CF-managed ZDR credentials reject URL format). `extractProxiedImageAsset` accepts URL or inline base64.
807
839
  - **Recraft** (`recraft/recraftv4*`): bare `{ prompt }` only (v0.174.1/v0.174.2); legacy `style` enums and Pro `1024x1024` size are rejected upstream.
808
840
 
@@ -838,6 +870,8 @@ The retrieved chunks appear above the model's response with filename, chunk inde
838
870
  ```
839
871
  # Create the Vectorize index (768 dimensions for BGE-base, cosine similarity)
840
872
  npx wrangler vectorize create skyphusion-llm-vec --dimensions=768 --metric=cosine
873
+ # ...and its user_email metadata index, before any document is uploaded
874
+ npx wrangler vectorize create-metadata-index skyphusion-llm-vec --property-name=user_email --type=string
841
875
 
842
876
  # Apply the full schema to a FRESH database. schema.sql is the canonical
843
877
  # full schema for new deployments. Do NOT re-run it against a database that
@@ -1041,7 +1075,7 @@ See [SECURITY.md](SECURITY.md) for vulnerability reporting.
1041
1075
 
1042
1076
  ## Acknowledgements
1043
1077
 
1044
- Built and maintained by [SkyPhusion](https://x.com/SkyPhusion).
1078
+ Built and maintained by [SkyPhusion](https://x.com/rockrockenhaus).
1045
1079
 
1046
1080
  Built on Cloudflare Workers, Workers AI, AI Gateway, D1, R2, Vectorize, Workflows, and Cloudflare Access. Image generation models courtesy of Black Forest Labs and Leonardo.Ai. Text-to-speech via Deepgram. Speech-to-text via OpenAI Whisper. Web search via self-hosted SearXNG and Wikipedia.
1047
1081
 
@@ -27,8 +27,11 @@ The hosted instance is offered freely so people can try the Cloudflare AI stack.
27
27
 
28
28
  ## You pay for your own model inference
29
29
 
30
- The hosted instance does not pay for the models you run. You configure your own Cloudflare AI Gateway,
31
- and model inference is billed to **your** Cloudflare Unified Billing account. That means:
30
+ The hosted instance does not pay for the models you run, with one narrow exception below. You configure
31
+ your own Cloudflare account ID, AI Gateway, and API token, and model inference is billed to **your**
32
+ Cloudflare account. The exception: live voice chat, Deepgram file transcription, and six image models
33
+ cannot be routed through an AI Gateway, so they run on our Cloudflare account (the privacy notice lists
34
+ them). Using those does not bill you. Otherwise:
32
35
 
33
36
  - **Your gateway spend is yours.** You are solely responsible for the cost of the model calls you make
34
37
  and for keeping your own AI Gateway credentials and billing in order. Skyphusion Labs does not
@@ -37,8 +37,12 @@ lose it, we have no way to email you a reset.
37
37
  - **Your content:** the prompts and chats you write, and the images, video, music, and voice you
38
38
  generate, plus any documents you add for retrieval (RAG). These are stored in the instance D1
39
39
  database and R2 bucket, keyed to your account by a stable, opaque account id.
40
- - **Your AI Gateway settings:** the gateway slug and Cloudflare AI Gateway token you enter so the
41
- instance can run models on **your** account (see "How model inference is billed and routed" below).
40
+ - **Your AI Gateway settings:** the Cloudflare account ID, the gateway slug, and the Cloudflare AI
41
+ Gateway token you enter so the instance can run models on **your** account (see "How model inference
42
+ is billed and routed" below).
43
+ - **Your control-plane client key, if you enter one:** the `pcp_` key that switches chat onto the
44
+ Skyphusion-operated metered route (see "Metered chat through play-proxy" below). You only have one if
45
+ Skyphusion Labs issued it to you.
42
46
  - **Operational records** mechanically required to run the service: request and job state, and
43
47
  abuse-control counters (see "Abuse controls" below).
44
48
 
@@ -51,23 +55,105 @@ reference R2 keys.
51
55
 
52
56
  ## How model inference is billed and routed (bring your own gateway)
53
57
 
54
- The hosted instance does **not** pay for your model inference. Before you can run a paid or proxied
55
- model you enter your own **Cloudflare AI Gateway** slug and an AI Gateway token in Account settings.
56
- The instance stores those in its D1 database and uses them to send your model requests through **your**
57
- AI Gateway, so inference is billed to **your** Cloudflare Unified Billing account, not ours. The
58
- hosted worker has no gateway credentials of its own; with your settings unset, paid model calls fail
59
- closed with a clear prompt to configure your gateway, rather than silently billing anyone else.
60
-
61
- Treat the AI Gateway token you enter as you would any API credential. It is held in the instance
62
- database solely to authorize your model calls, and deleting your account (below) removes it along with
63
- everything else.
64
-
65
- ## Abuse controls (transient IP processing)
58
+ Before you can run a model you enter three things in Account settings: your **Cloudflare account ID**,
59
+ your **AI Gateway** slug, and a Cloudflare API token for that account. The instance stores them in its D1
60
+ database and uses them to send your model requests to **your** Cloudflare account and gateway, so that
61
+ inference is billed to **your** Cloudflare account, not ours. With any of the three missing, model calls
62
+ fail closed with a prompt naming what is missing, rather than running on our account. (The one route
63
+ that does not need the three is metered chat through play-proxy, below, which only exists if you have
64
+ entered a control-plane client key; everything other than chat still fails closed without them.)
65
+
66
+ **One exception: a few models run on our Cloudflare account.** Some Workers AI models cannot be routed
67
+ through an AI Gateway at all, so the instance runs them on its own Cloudflare account: live voice chat,
68
+ Deepgram file transcription, and six image models (FLUX.2 Klein 9B / Klein 4B / Dev, Leonardo Phoenix
69
+ 1.0, Dreamshaper 8 LCM, Stable Diffusion XL). For those, your prompt or audio goes to Cloudflare Workers
70
+ AI under our account rather than yours, and we pay for them.
71
+
72
+ **Correction (v1.1.0).** Earlier versions of this notice said your requests went through your gateway
73
+ whenever you entered a slug and token. That was not true: without an account ID the instance could only
74
+ address gateways on our own Cloudflare account, so those requests never reached your gateway. The
75
+ instance now requires the account ID and routes to your account; settings saved without one are refused
76
+ until you add it.
77
+
78
+ Treat the API token you enter as you would any API credential. It is held in the instance database
79
+ solely to authorize your model calls, and deleting your account (below) removes it along with
80
+ everything else. Your account ID is not a secret (it appears in every gateway URL) but is stored and
81
+ deleted the same way.
82
+
83
+ ## Metered chat through play-proxy (optional; a Skyphusion-operated route)
84
+
85
+ This section applies only if you have entered a **control-plane client key** (it starts with `pcp_`)
86
+ under Account settings > AI Gateway. Skyphusion Labs issues those keys by enrollment; if you never
87
+ entered one, nothing in this section happens and chat runs through your own gateway as described above.
88
+
89
+ **Correction.** Earlier versions of this notice did not mention this route at all, and said every model
90
+ request went through the gateway you configure. That was incomplete: the route has existed since Prism
91
+ v0.175.0 and the key has been stored with your gateway settings since then. The route itself is
92
+ unchanged; this section is the disclosure that was missing.
93
+
94
+ **Where your chat goes.** While a key is saved, your chat turns, and the conversation compaction that
95
+ summarizes older turns, are sent to `https://play-proxy.skyphusion.org`, a service called
96
+ prism-control-plane that Skyphusion Labs operates on its own Cloudflare account, instead of to your
97
+ gateway. That hostname is fixed in the software and checked against an allowlist on every call; you
98
+ cannot point it elsewhere from your account, and neither can anyone holding your key. Inference on this
99
+ route is metered against the control-plane account the key belongs to, not billed to your Cloudflare
100
+ account.
101
+
102
+ **What is sent.** For each chat turn: the model you chose; the system prompt in effect for that
103
+ conversation, which includes any compaction digest of earlier turns and, when you have retrieval or web
104
+ search switched on for the turn, the document excerpts and search snippets retrieved for it; the text of
105
+ the earlier turns still in context; your current message, including text extracted from any attachment;
106
+ and your client key, as the credential. Images are not forwarded on this route: a turn with an image
107
+ attached is refused with an error naming the control-plane route, rather than sent. Image, video, music,
108
+ and voice generation, transcription, document ingestion, and web search never use this route; they stay
109
+ exactly as described elsewhere in this notice.
110
+
111
+ **What comes back, and what this instance keeps.** The model's reply, token counts, and a request id.
112
+ The reply is stored with the turn in your chat the same way as on any other route, and the request id is
113
+ stored on that chat row. Both are deleted with your account.
114
+
115
+ **What the control plane keeps.** prism-control-plane is open source (AGPL-3.0-only) and publishes its
116
+ own retention statement as a binding part of its contract: it never stores prompt or completion text,
117
+ and a test in that repository fails the build if a column that could hold message text is ever added.
118
+ Its usage ledger keeps, per request, the token counts, the cost, the model id, the status, a request id,
119
+ and the id of the client key that made the call, plus a last-seen time on the key. That ledger is a
120
+ billing record; the control plane does not publish a deletion window for it, and deleting your Prism
121
+ account removes the key from this instance but does not touch that ledger. Read the statement itself:
122
+ [Privacy invariant in `docs/CONTRACT.md`](https://github.com/skyphusion-labs/prism-control-plane/blob/main/docs/CONTRACT.md#privacy-invariant-binding-on-every-version-of-this-contract)
123
+ and the matching section of its
124
+ [README](https://github.com/skyphusion-labs/prism-control-plane/blob/main/README.md#privacy-invariant).
125
+
126
+ **Beyond the control plane.** The control plane forwards your request to the provider that serves the
127
+ model you chose (the catalog names the provider) through an AI Gateway on Skyphusion Labs' Cloudflare
128
+ account with payload logging hard-wired off, so neither we nor Cloudflare keep the prompt or completion
129
+ bodies there. Cloudflare keeps a metadata row for each call (token counts, model, provider, status, cost,
130
+ duration; no content) under its own AI Gateway log retention. The model provider receives your prompt
131
+ content in order to return a result and handles it under its own terms, exactly as it would through
132
+ your own gateway.
133
+
134
+ **The key itself.** It is stored in the instance database alongside your gateway settings, shown back to
135
+ you only masked, cleared whenever you choose "clear control plane key" in Account settings, and deleted
136
+ with your account (below).
137
+
138
+ ## Abuse controls (bounded IP processing for signup and login)
66
139
 
67
140
  To keep signup and login from being abused, the instance rate-limits those requests. It does this by
68
141
  counting recent attempts against the caller's IP address (the address Cloudflare reports at the edge)
69
- and, for login, the username being tried. IP addresses are processed for this abuse-control purpose
70
- only; we do not use them to profile you, build a history, or track you across sessions.
142
+ and, for login, the username being tried. A counter row holds that key, a count, and the start of its
143
+ counting window, and nothing else. IP addresses are processed for this abuse-control purpose only; we
144
+ do not use them to profile you, build a history, or track you across sessions.
145
+
146
+ **How long a counter lives: at most 24 hours.** The counting windows are short (15 minutes for login,
147
+ 1 hour for signup); 24 hours is the outer bound on how long a row can sit in the database before it is
148
+ removed, and it is deliberately far longer than any counting window so a prune can never discard a
149
+ counter a rate-limit decision still depends on. A successful login clears its own counter immediately,
150
+ and every signup or login attempt deletes every counter older than 24 hours, so an address that stops
151
+ coming back is erased by the next attempt from anyone. The deletion runs on the write path itself, not
152
+ on a scheduled job, so a self-hosted instance inherits the same bound with no extra configuration.
153
+
154
+ **Correction (v1.1.1).** Earlier versions of this notice called this processing "transient" without
155
+ saying what that meant, and in fact nothing removed a counter that never saw a successful login: those
156
+ rows persisted indefinitely. v1.1.1 added the 24-hour bound above.
71
157
 
72
158
  ## What we do not do
73
159
 
@@ -80,24 +166,38 @@ not sell your data and we do not share it, with the single exception of the abus
80
166
  The hosted instance runs on Cloudflare (Workers, D1, R2, Vectorize). Your model requests are sent
81
167
  through the AI Gateway **you** configure, on your own Cloudflare account; the model providers reachable
82
168
  through that gateway receive your prompt content in order to return a result, and handle it under their
83
- own and your gateway's terms rather than ours.
169
+ own and your gateway's terms rather than ours. There are two exceptions: the short list of models above
170
+ that run on our Cloudflare account, which Cloudflare Workers AI processes under our account; and, only
171
+ if you have entered a control-plane client key, chat through play-proxy as described in "Metered chat
172
+ through play-proxy" above.
84
173
 
85
174
  **Web search is opt-in and does not use any third-party search API.** Prism has a per-turn web search
86
- toggle. When you switch it on for a turn, the text of that one query is sent to the instance's own
87
- self-hosted search service (SearXNG, run by Skyphusion Labs) and to keyless public sources such as
88
- Wikipedia. No third-party search-API provider (and no per-provider API key) is in the path. The
89
- snippets that come back are stored with the turn as retrieved context, the same way your RAG chunks
90
- are. Your chat history, your uploaded documents, and your generated media are never sent out for
91
- search. Leave the toggle off and no query leaves the instance.
175
+ toggle. When you switch it on for a turn, the text of that one query is sent to keyless public sources,
176
+ today Wikipedia (the public MediaWiki search endpoint). The software can also query a SearXNG metasearch
177
+ instance, but **the hosted instance has no SearXNG service**: the one Skyphusion Labs ran at
178
+ search.skyphusion.org was retired with the September 2026 infrastructure change and that hostname no
179
+ longer resolves, so on this instance the SearXNG source returns nothing and the query reaches Wikipedia
180
+ alone. No third-party search-API provider (and no per-provider API key) is in the path. The snippets
181
+ that come back are stored with the turn as retrieved context, the same way your RAG chunks are. Your
182
+ chat history, your uploaded documents, and your generated media are never sent out for search. Leave
183
+ the toggle off and no query leaves the instance.
184
+
185
+ **Correction (2026-10-13).** Earlier versions of this notice said the query also went to a self-hosted
186
+ SearXNG service run by Skyphusion Labs. That service no longer exists, and the paragraph above describes
187
+ the instance as it runs today. If a search service is stood up again, this notice will be updated to
188
+ name it.
92
189
 
93
190
  ## Deleting your data
94
191
 
95
192
  Account deletion is built into the app. From Account settings you delete your account (re-entering your
96
193
  password to confirm), and it **cascades**: it removes your account record and sessions, your chats and
97
- conversations, every generated artifact and uploaded document in R2, your RAG embeddings in Vectorize,
98
- your projects, and your stored AI Gateway settings. Deletion is on you and takes effect on the
99
- instance; we do not keep a shadow copy. If you self-host Prism instead, deletion is entirely in your
100
- hands on your own instance.
194
+ conversations (including the compaction digests of your conversations, which v1.1.1 added to the
195
+ cascade; before it, account deletion left those digests behind), every generated artifact and uploaded
196
+ document in R2, your RAG embeddings in Vectorize,
197
+ your projects, and your stored AI Gateway settings, including any control-plane client key. Deletion is
198
+ on you and takes effect on the instance; we do not keep a shadow copy. What the control plane's billing
199
+ ledger holds about calls made with your key is not on this instance; see "What the control plane keeps"
200
+ above. If you self-host Prism instead, deletion is entirely in your hands on your own instance.
101
201
 
102
202
  ## The one bright line
103
203
 
@@ -0,0 +1,58 @@
1
+ -- 0004: CSP violation collector (fleet-chezmoi#1646).
2
+ --
3
+ -- Two tables, and the split is the point. `csp_report_buckets` is a rate-limit
4
+ -- counter and could have reused `auth_attempts`, which already has exactly this
5
+ -- shape and a prefixed bucket-key namespace. It deliberately does not.
6
+ --
7
+ -- WHY: the collector's write endpoint is UNAUTHENTICATED by construction, because
8
+ -- browsers post CSP reports without credentials. Pointing an unauthenticated
9
+ -- public write path at the same table the LOGIN limiter depends on means a flood
10
+ -- against the collector contends with sign-in. One extra table is a cheap price
11
+ -- for not coupling a public write path to the auth path.
12
+ --
13
+ -- Apply to an existing database with:
14
+ -- npx wrangler d1 execute skyphusion-llm --remote --file=migrations/0004_csp_reports.sql
15
+ -- Fresh databases get this from schema.sql.
16
+
17
+ -- Collected violations. Every column is a BOUNDED projection of an
18
+ -- attacker-controlled report body; nothing is stored verbatim.
19
+ --
20
+ -- NOT STORED, deliberately: `script-sample`. It can carry fragments of inline
21
+ -- script from a page that handles a credential, and a violation is diagnosable
22
+ -- from the directive plus the blocked URI without it.
23
+ CREATE TABLE IF NOT EXISTS csp_reports (
24
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
25
+ received_at TEXT NOT NULL DEFAULT (datetime('now')),
26
+ -- document_uri is stored with query and fragment STRIPPED. The SPA puts
27
+ -- nothing in URLs (measured), so this costs nothing today and stops the
28
+ -- collector becoming the first place a URL-borne value is persisted.
29
+ document_uri TEXT,
30
+ referrer TEXT,
31
+ violated_directive TEXT,
32
+ effective_directive TEXT,
33
+ blocked_uri TEXT,
34
+ disposition TEXT,
35
+ status_code INTEGER,
36
+ source_file TEXT,
37
+ line_number INTEGER,
38
+ column_number INTEGER
39
+ );
40
+
41
+ -- Read path is operator-only and deliberately has no HTTP endpoint: there is no
42
+ -- admin role on this product, so an authenticated read route would let any
43
+ -- signed-up user read operator diagnostics from a credential-handling page.
44
+ -- Operators query with:
45
+ -- npx wrangler d1 execute skyphusion-llm --remote \
46
+ -- --command "SELECT received_at, effective_directive, blocked_uri, document_uri
47
+ -- FROM csp_reports ORDER BY id DESC LIMIT 50;"
48
+ CREATE INDEX IF NOT EXISTS idx_csp_reports_received ON csp_reports(received_at);
49
+
50
+ -- Rate-limit buckets for the collector, isolated from auth_attempts per the note
51
+ -- above. `dropped` is what makes shedding VISIBLE: without it a rate-limited
52
+ -- estate and a quiet one produce an identical empty table.
53
+ CREATE TABLE IF NOT EXISTS csp_report_buckets (
54
+ bucket_key TEXT PRIMARY KEY,
55
+ count INTEGER NOT NULL DEFAULT 0,
56
+ dropped INTEGER NOT NULL DEFAULT 0,
57
+ window_start TEXT NOT NULL DEFAULT (datetime('now'))
58
+ );
@@ -0,0 +1,23 @@
1
+ -- 0005: index the auth_attempts prune column (prism#192).
2
+ --
3
+ -- WHY THIS EXISTS: src/rate-limit.ts now prunes auth_attempts on write, the way
4
+ -- src/routes/csp-report.ts prunes csp_reports, because the hosted privacy
5
+ -- notice calls that section "transient IP processing" and nothing was actually
6
+ -- making it transient. Rows were removed only by a SUCCESSFUL login clearing
7
+ -- its own bucket, so a signup bucket, or a login:<ip>:<username> bucket that
8
+ -- never saw a success, persisted indefinitely.
9
+ --
10
+ -- The prune filters on window_start, which was unindexed; auth_attempts has
11
+ -- only its bucket_key primary key. csp_reports already carries
12
+ -- idx_csp_reports_received for exactly the same reason, so this matches the
13
+ -- established pattern rather than inventing one. The table is small (one row
14
+ -- per IP / username bucket), but the prune runs on EVERY signup and login
15
+ -- attempt, which is the hot path the limiter is supposed to protect.
16
+ --
17
+ -- No data change and no new column: safe to re-apply.
18
+ --
19
+ -- Apply to an existing database with:
20
+ -- npx wrangler d1 execute skyphusion-llm --remote --file=migrations/0005_auth_attempts_retention.sql
21
+ -- Fresh databases get this from schema.sql.
22
+
23
+ CREATE INDEX IF NOT EXISTS idx_auth_attempts_window ON auth_attempts(window_start);