@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
@@ -6,6 +6,20 @@
6
6
  // pure function so it is unit-testable without D1; the DB layer only does the
7
7
  // epoch conversion and the upsert.
8
8
 
9
+ // prism#192: how long a rate-limit bucket may survive its own window.
10
+ //
11
+ // Before this, rows were removed only by resetRateLimit on a SUCCESSFUL login,
12
+ // so a `signup:<ip>` bucket, or any `login:<ip>:<username>` bucket that never
13
+ // saw a success, lived in D1 forever. The hosted privacy notice heads that
14
+ // section "transient IP processing", and indefinite retention of failed-login
15
+ // IP-plus-username pairs is not transient.
16
+ //
17
+ // 24h is deliberately far beyond the longest live window (SIGNUP_WINDOW, 1h in
18
+ // src/auth.ts), so a prune can never discard a bucket a limiter decision still
19
+ // depends on: past its window rateLimitDecision already treats the row as a
20
+ // fresh start, making an aged row functionally dead weight.
21
+ export const AUTH_ATTEMPT_RETENTION_HOURS = 24;
22
+
9
23
  export interface RateLimitDecision {
10
24
  allowed: boolean;
11
25
  nextCount: number;
@@ -65,6 +79,18 @@ export async function checkRateLimit(
65
79
  .bind(bucketKey, decision.nextCount, decision.nextWindowStart)
66
80
  .run();
67
81
 
82
+ // Retention as an executed deletion, not an intention -- the csp_reports
83
+ // pattern (src/routes/csp-report.ts). Prune-on-write needs no cron, no new
84
+ // trigger and no binding, and it cannot drift out of sync with the write path
85
+ // because it IS the write path. That matters here specifically: the shipped
86
+ // wrangler.example.toml has `crons = []` and there is no scheduled handler,
87
+ // so anything cron-shaped would be retention that never actually runs, and a
88
+ // self-host would silently inherit indefinite retention.
89
+ await db
90
+ .prepare(`DELETE FROM auth_attempts WHERE window_start < datetime('now', ?)`)
91
+ .bind(`-${AUTH_ATTEMPT_RETENTION_HOURS} hours`)
92
+ .run();
93
+
68
94
  return decision.allowed;
69
95
  }
70
96
 
@@ -17,7 +17,7 @@ import { callXai, callXaiStream } from "../providers/xai";
17
17
  import { callWorkersAIStream } from "../providers/workers-ai";
18
18
  import { callOpenAI, callOpenAIStream } from "../providers/openai";
19
19
  import { callGemini, callGeminiStream } from "../providers/google";
20
- import { generateOpenAIImage } from "../providers/openai-image";
20
+ import { generateOpenAIImage, resolveOpenAIImageKey } from "../providers/openai-image";
21
21
  import { buildProxiedImageParams } from "../proxied-image-params";
22
22
  import {
23
23
  json,
@@ -529,13 +529,24 @@ export async function runChat(request: Request, env: Env, model: ModelEntry, bod
529
529
 
530
530
  export async function runImage(request: Request, env: Env, model: ModelEntry, body: ChatRequest): Promise<Response> {
531
531
  const userEmail = await getUserEmail(request, env);
532
- let aiCtx: AiContext | null = null;
532
+
533
+ // Resolve the caller's own gateway credentials before any inference runs.
534
+ //
535
+ // This is deliberately NOT conditional on which transport the model uses.
536
+ // Some @cf image models call the binding directly because the gateway cannot
537
+ // proxy their request or response shapes (see the bypass block further down);
538
+ // that is a TRANSPORT property of the model and must not decide
539
+ // AUTHORIZATION of the caller. Resolving here, unconditionally, makes this
540
+ // the single seam every branch below passes through, so a model that later
541
+ // needs some new transport cannot acquire a new way around the gate along
542
+ // with it.
543
+ //
544
+ // requireCfToken is the one thing that legitimately varies: proxied models
545
+ // additionally need a Cloudflare AI Gateway token, @cf models do not.
533
546
  const needsProxiedGateway = !!model.provider;
534
- if (needsProxiedGateway) {
535
- const ctxOrErr = await requireAiContext(env, userEmail, { requireCfToken: true });
536
- if (ctxOrErr instanceof Response) return ctxOrErr;
537
- aiCtx = ctxOrErr;
538
- }
547
+ const ctxOrErr = await requireAiContext(env, userEmail, { requireCfToken: needsProxiedGateway });
548
+ if (ctxOrErr instanceof Response) return ctxOrErr;
549
+ const aiCtx: AiContext = ctxOrErr;
539
550
 
540
551
  // Image gen splits two ways. Proxied models (those with a `provider`:
541
552
  // nano-banana/google, gpt-image-1.5/openai, recraftv4/recraft) go through the
@@ -555,20 +566,22 @@ export async function runImage(request: Request, env: Env, model: ModelEntry, bo
555
566
  // sole OpenAI transparent-PNG carve-out: when OPENAI_API_KEY is set on
556
567
  // openai/* image models, call api.openai.com directly (proxy rejects
557
568
  // background/output_format). No other provider uses a deployer key.
569
+ // Public mode ignores the key (prism#193, v1.0.5): see resolveOpenAIImageKey.
558
570
  //
559
571
  // Unified Billing response shapes:
560
572
  // URL: { state, result: { image: "https://..." } } or images[]
561
573
  // inline: { state, result: { image: "<b64|data-uri>" } } // xAI Grok Imagine
562
574
  // xAI requires response_format:b64_json (ZDR-managed credentials reject
563
575
  // URL output). extractProxiedImageAsset normalizes both.
564
- if (model.provider === "openai" && env.OPENAI_API_KEY) {
565
- const gen = await generateOpenAIImage(env.OPENAI_API_KEY, model.id, body.user_input);
576
+ const openaiImageKey = model.provider === "openai" ? resolveOpenAIImageKey(env) : null;
577
+ if (openaiImageKey) {
578
+ const gen = await generateOpenAIImage(openaiImageKey, model.id, body.user_input);
566
579
  bytes = gen.bytes;
567
580
  mime = gen.mime;
568
581
  logId = null; // direct OpenAI; no AI Gateway log
569
582
  } else {
570
- const result = await aiRun(aiCtx!, model.id, buildProxiedImageParams(model.provider, body.user_input));
571
- logId = aiLogId(aiCtx!);
583
+ const result = await aiRun(aiCtx, model.id, buildProxiedImageParams(model.provider, body.user_input));
584
+ logId = aiLogId(aiCtx);
572
585
 
573
586
  const failure = detectProviderFailure(result);
574
587
  if (failure) {
@@ -684,14 +697,14 @@ export async function runImage(request: Request, env: Env, model: ModelEntry, bo
684
697
  // populates ai_gateway_log_id for observability).
685
698
  let result: unknown;
686
699
  if (bypassGateway) {
700
+ // Transport bypass only. Credentials were resolved at the top of
701
+ // runImage, so this call is authorized on exactly the same terms as
702
+ // every other path here. What it skips is the gateway TRANSPORT, and
703
+ // with it the gateway's observability, which is why ai_gateway_log_id
704
+ // stays null on the persisted row below.
687
705
  type BypassRunFn = (model: string, params: unknown) => Promise<unknown>;
688
706
  result = await (env.AI as unknown as { run: BypassRunFn }).run(model.id, runParams);
689
707
  } else {
690
- if (!aiCtx) {
691
- const ctxOrErr = await requireAiContext(env, userEmail, { requireCfToken: false });
692
- if (ctxOrErr instanceof Response) return ctxOrErr;
693
- aiCtx = ctxOrErr;
694
- }
695
708
  result = await aiRun(aiCtx, model.id, runParams);
696
709
  logId = aiLogId(aiCtx);
697
710
  }
@@ -0,0 +1,163 @@
1
+ // POST /api/csp-report -- the CSP violation collector (fleet-chezmoi#1646).
2
+ //
3
+ // THIS ROUTE IS UNAUTHENTICATED AND CANNOT BE OTHERWISE. Browsers post CSP
4
+ // reports without credentials, so a token gate would collect nothing. Every
5
+ // design choice below follows from that: anyone can post here, at any volume,
6
+ // with any body, so the body is capped, the projection is a fixed field set,
7
+ // every field is length-bounded, the rate is limited, and shedding is counted
8
+ // rather than silent.
9
+ //
10
+ // The pure half (policy string, field caps, report projection) is in src/csp.ts
11
+ // and is unit-tested without D1. This file does the window and the insert.
12
+
13
+ import type { Env } from "../env";
14
+ import { rateLimitDecision } from "../rate-limit";
15
+ import {
16
+ CSP_FIELD_CAPS,
17
+ CSP_RATE_LIMIT,
18
+ CSP_RATE_WINDOW_SECONDS,
19
+ CSP_REPORT_MAX_BYTES,
20
+ CSP_RETENTION_DAYS,
21
+ extractCspReport,
22
+ } from "../csp";
23
+
24
+ /**
25
+ * Reports are fire-and-forget from the browser's side; nothing reads the body.
26
+ * Every return is 204 with no body EXCEPT the refusals we want to be able to
27
+ * test and count, which carry a status that says which refusal fired.
28
+ */
29
+ const NO_CONTENT = () => new Response(null, { status: 204 });
30
+
31
+ /**
32
+ * Rate-limit window against the collector's OWN bucket table.
33
+ *
34
+ * Deliberately not `checkRateLimit` from src/rate-limit.ts: that writes to
35
+ * `auth_attempts`, and pointing an unauthenticated public write path at the
36
+ * table the login limiter depends on couples a flood here to sign-in there.
37
+ * The pure decision function IS reused, so the window semantics cannot drift
38
+ * from the audited ones.
39
+ */
40
+ async function windowFor(
41
+ db: D1Database,
42
+ bucketKey: string,
43
+ ): Promise<{ allowed: boolean }> {
44
+ const row = await db
45
+ .prepare(
46
+ `SELECT count, CAST(strftime('%s', window_start) AS INTEGER) AS ws
47
+ FROM csp_report_buckets WHERE bucket_key = ?`,
48
+ )
49
+ .bind(bucketKey)
50
+ .first<{ count: number; ws: number }>();
51
+ const nowRow = await db
52
+ .prepare(`SELECT CAST(strftime('%s','now') AS INTEGER) AS now`)
53
+ .first<{ now: number }>();
54
+ const now = nowRow?.now ?? 0;
55
+
56
+ const d = rateLimitDecision(
57
+ now,
58
+ row?.ws ?? null,
59
+ row?.count ?? 0,
60
+ CSP_RATE_LIMIT,
61
+ CSP_RATE_WINDOW_SECONDS,
62
+ );
63
+
64
+ // `dropped` is what makes shedding visible. Without it a rate-limited estate
65
+ // and a quiet one produce an identical empty csp_reports table, and the
66
+ // difference between "nothing is violating" and "we threw it away" is the
67
+ // whole question this collector exists to answer.
68
+ await db
69
+ .prepare(
70
+ `INSERT INTO csp_report_buckets (bucket_key, count, dropped, window_start)
71
+ VALUES (?, ?, ?, datetime(?, 'unixepoch'))
72
+ ON CONFLICT(bucket_key) DO UPDATE SET
73
+ count = excluded.count,
74
+ dropped = csp_report_buckets.dropped + excluded.dropped,
75
+ window_start = excluded.window_start`,
76
+ )
77
+ .bind(bucketKey, d.nextCount, d.allowed ? 0 : 1, d.nextWindowStart)
78
+ .run();
79
+
80
+ return { allowed: d.allowed };
81
+ }
82
+
83
+ export async function handleCspReport(request: Request, env: Env): Promise<Response> {
84
+ // 1. Size. Refuse PAST the cap rather than accepting a truncated record.
85
+ // A collector that stores a mangled row past its limit is worse than one
86
+ // that refuses, because the mangled row looks like a real observation.
87
+ // Content-Length is a claim, so it is checked as a cheap early refusal AND
88
+ // the actual bytes are measured after reading; a lying or absent header
89
+ // cannot get a oversized body past the second check.
90
+ const declared = Number(request.headers.get("content-length") ?? "0");
91
+ if (Number.isFinite(declared) && declared > CSP_REPORT_MAX_BYTES) {
92
+ return new Response(null, { status: 413 });
93
+ }
94
+
95
+ let raw: string;
96
+ try {
97
+ raw = await request.text();
98
+ } catch {
99
+ return new Response(null, { status: 400 });
100
+ }
101
+ if (raw.length > CSP_REPORT_MAX_BYTES) {
102
+ return new Response(null, { status: 413 });
103
+ }
104
+
105
+ // 2. Parse. Malformed is refused, not stored as an empty row.
106
+ let parsed: unknown;
107
+ try {
108
+ parsed = JSON.parse(raw);
109
+ } catch {
110
+ return new Response(null, { status: 400 });
111
+ }
112
+
113
+ // 3. Project to the bounded row. null means neither wire shape was present,
114
+ // which is a malformed report rather than a violation with no detail.
115
+ const row = extractCspReport(parsed);
116
+ if (!row) return new Response(null, { status: 400 });
117
+
118
+ // 4. Rate limit. Keyed on the connecting IP; CF-Connecting-IP is set by the
119
+ // edge and is not client-settable on this path. A missing header buckets
120
+ // to "unknown", which shares one window rather than bypassing the limit.
121
+ const ip = request.headers.get("cf-connecting-ip") || "unknown";
122
+ const { allowed } = await windowFor(env.DB, `csp:${ip}`.slice(0, 128));
123
+ if (!allowed) {
124
+ // 429 rather than a silent 204: a shed report must be distinguishable from
125
+ // an accepted one by the sender too, not only in our own counter.
126
+ return new Response(null, { status: 429 });
127
+ }
128
+
129
+ await env.DB.prepare(
130
+ `INSERT INTO csp_reports
131
+ (document_uri, referrer, violated_directive, effective_directive,
132
+ blocked_uri, disposition, status_code, source_file, line_number, column_number)
133
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
134
+ )
135
+ .bind(
136
+ row.document_uri,
137
+ row.referrer,
138
+ row.violated_directive,
139
+ row.effective_directive,
140
+ row.blocked_uri,
141
+ row.disposition,
142
+ row.status_code,
143
+ row.source_file,
144
+ row.line_number,
145
+ row.column_number,
146
+ )
147
+ .run();
148
+
149
+ // 5. Retention as an executed deletion, not an intention. Prune-on-write
150
+ // needs no cron, no new trigger and no binding, and it cannot drift out of
151
+ // sync with the write path because it IS the write path.
152
+ await env.DB.prepare(
153
+ `DELETE FROM csp_reports WHERE received_at < datetime('now', ?)`,
154
+ )
155
+ .bind(`-${CSP_RETENTION_DAYS} days`)
156
+ .run();
157
+
158
+ return NO_CONTENT();
159
+ }
160
+
161
+ // Re-exported so the route table and the tests agree on the cap without a
162
+ // second copy of the number.
163
+ export { CSP_REPORT_MAX_BYTES, CSP_FIELD_CAPS };
@@ -4,6 +4,7 @@
4
4
 
5
5
  import type { Env } from "../env";
6
6
  import { probeD1Schema } from "../health-schema";
7
+ import { VERSION } from "../version";
7
8
  import { json } from "./shared";
8
9
 
9
10
  // ---------- Health checks ----------
@@ -97,8 +98,12 @@ export async function handleHealthDeep(env: Env): Promise<Response> {
97
98
  }
98
99
 
99
100
  const allOk = Object.values(checks).every((c) => c.ok);
101
+ // `version` rides on the readiness payload too, and it matters most when this
102
+ // endpoint is answering 503: a readiness probe goes red for reasons that have
103
+ // nothing to do with which build is running, and that is exactly the moment an
104
+ // operator needs to know which build it is.
100
105
  return json(
101
- { ok: allOk, ts: Date.now(), checks },
106
+ { ok: allOk, ts: Date.now(), version: VERSION, checks },
102
107
  { status: allOk ? 200 : 503 }
103
108
  );
104
109
  }
@@ -1,11 +1,16 @@
1
1
  // Per-user AI Gateway preference routes (GET/PATCH /api/prefs). Stores the
2
- // user gateway slug + Unified Billing token in D1 user_prefs; the token is
3
- // never echoed back raw (maskSecret). Optional control_plane_key (pcp_) for
2
+ // user's Cloudflare account id (v1.1.0), gateway slug, and Unified Billing
3
+ // token in D1 user_prefs; the token is never echoed back raw (maskSecret). Optional control_plane_key (pcp_) for
4
4
  // metered chat via allowlisted play-proxy (URL is never user-set).
5
5
 
6
6
  import type { Env } from "../env";
7
7
  import { loadUserPrefs, saveUserPrefs, type UserPrefsJson } from "../user-prefs";
8
- import { loadGatewayStatus, maskSecret } from "../gateway-credentials";
8
+ import {
9
+ isValidGatewayId,
10
+ loadGatewayStatus,
11
+ maskSecret,
12
+ normalizeAccountId,
13
+ } from "../gateway-credentials";
9
14
  import {
10
15
  DEFAULT_CONTROL_PLANE_URL,
11
16
  looksLikeClientKey,
@@ -29,6 +34,8 @@ export async function handlePrefsGet(request: Request, env: Env): Promise<Respon
29
34
  const prefs = await loadUserPrefs(env.DB, userEmail);
30
35
  const status = await loadGatewayStatus(env, userEmail);
31
36
  return json({
37
+ account_id: status.account_id,
38
+ account_id_required: status.account_id_required,
32
39
  gateway_id: status.gateway_id,
33
40
  cf_aig_token_set: status.cf_aig_token_set,
34
41
  cf_aig_token_preview: maskSecret(prefs?.cf_aig_token),
@@ -41,6 +48,7 @@ export async function handlePrefsGet(request: Request, env: Env): Promise<Respon
41
48
  export async function handlePrefsPatch(request: Request, env: Env): Promise<Response> {
42
49
  const userEmail = await getUserEmail(request, env);
43
50
  let body: {
51
+ account_id?: string;
44
52
  gateway_id?: string;
45
53
  cf_aig_token?: string;
46
54
  clear_cf_aig_token?: boolean;
@@ -54,7 +62,38 @@ export async function handlePrefsPatch(request: Request, env: Env): Promise<Resp
54
62
  }
55
63
 
56
64
  const patch: UserPrefsJson = {};
57
- if (body.gateway_id !== undefined) patch.gateway_id = body.gateway_id;
65
+ if (body.account_id !== undefined) {
66
+ if (typeof body.account_id !== "string") {
67
+ return json({ error: "account_id must be a string", code: "invalid_account_id" }, { status: 400 });
68
+ }
69
+ // Empty clears it; anything else must be a real account id, since it
70
+ // becomes a path segment in every request we send on the user's behalf.
71
+ if (body.account_id.trim() && !normalizeAccountId(body.account_id)) {
72
+ return json(
73
+ {
74
+ error: "account_id must be your 32-character Cloudflare account ID (hex), from the Cloudflare dashboard.",
75
+ code: "invalid_account_id",
76
+ },
77
+ { status: 400 },
78
+ );
79
+ }
80
+ patch.account_id = body.account_id;
81
+ }
82
+ if (body.gateway_id !== undefined) {
83
+ if (typeof body.gateway_id !== "string") {
84
+ return json({ error: "gateway_id must be a string", code: "invalid_gateway_id" }, { status: 400 });
85
+ }
86
+ if (body.gateway_id.trim() && !isValidGatewayId(body.gateway_id)) {
87
+ return json(
88
+ {
89
+ error: "gateway_id must be your AI Gateway slug: letters, digits, '-' or '_', up to 64 characters.",
90
+ code: "invalid_gateway_id",
91
+ },
92
+ { status: 400 },
93
+ );
94
+ }
95
+ patch.gateway_id = body.gateway_id;
96
+ }
58
97
  if (body.cf_aig_token !== undefined) patch.cf_aig_token = body.cf_aig_token;
59
98
  if (body.clear_cf_aig_token) patch.cf_aig_token = "";
60
99
  if (body.control_plane_key !== undefined) {
@@ -76,7 +115,7 @@ export async function handlePrefsPatch(request: Request, env: Env): Promise<Resp
76
115
  if (Object.keys(patch).length === 0) {
77
116
  return json(
78
117
  {
79
- error: "Provide gateway_id, cf_aig_token, and/or control_plane_key to update",
118
+ error: "Provide account_id, gateway_id, cf_aig_token, and/or control_plane_key to update",
80
119
  },
81
120
  { status: 400 },
82
121
  );
@@ -85,6 +124,8 @@ export async function handlePrefsPatch(request: Request, env: Env): Promise<Resp
85
124
  const merged = await saveUserPrefs(env.DB, userEmail, patch);
86
125
  const status = await loadGatewayStatus(env, userEmail);
87
126
  return json({
127
+ account_id: status.account_id,
128
+ account_id_required: status.account_id_required,
88
129
  gateway_id: status.gateway_id,
89
130
  cf_aig_token_set: status.cf_aig_token_set,
90
131
  cf_aig_token_preview: maskSecret(merged.cf_aig_token),
@@ -9,7 +9,7 @@ import { getDocumentProxy } from "unpdf";
9
9
  import * as XLSX from "xlsx";
10
10
  import type { Env } from "../env";
11
11
  import { aiRun, type AiContext } from "../ai-binding";
12
- import { loadGatewayCredentials, GATEWAY_NOT_CONFIGURED_MSG } from "../gateway-credentials";
12
+ import { requireGatewayCredentials } from "../gateway-credentials";
13
13
  import { chunkText } from "../chunking";
14
14
  import { searchSearxngWeb } from "../searxng";
15
15
  import { r2Put, r2DeleteSafe } from "./shared";
@@ -221,10 +221,7 @@ export async function extractChunks(bytes: Uint8Array, mime: string, filename: s
221
221
 
222
222
  export async function embedBatch(env: Env, userEmail: string, texts: string[]): Promise<number[][]> {
223
223
  if (texts.length === 0) return [];
224
- const gateway = await loadGatewayCredentials(env, userEmail);
225
- if (!gateway?.gatewayId) {
226
- throw new Error(GATEWAY_NOT_CONFIGURED_MSG);
227
- }
224
+ const gateway = await requireGatewayCredentials(env, userEmail);
228
225
  const aiCtx: AiContext = { env, gateway };
229
226
  const result = await aiRun(aiCtx, EMBED_MODEL, { text: texts }) as {
230
227
  shape?: [number, number];
@@ -239,13 +236,26 @@ export async function embedBatch(env: Env, userEmail: string, texts: string[]):
239
236
  // ---------- RAG: retrieval (Pass 2) ----------
240
237
  //
241
238
  // Embeds the user prompt, queries Vectorize for the top-K nearest chunks,
242
- // then looks up source text in D1. We filter by user_email in the D1 JOIN
243
- // (not in the Vectorize filter param) so this works without a metadata
244
- // index on the Vectorize side - simpler for single-user deployments.
245
- // Vectorize score ordering is preserved.
239
+ // then looks up source text in D1. Tenant scope is the user_email filter in
240
+ // the D1 JOIN, always. Vectorize score ordering is preserved.
241
+ //
242
+ // With VEC_METADATA_FILTER on (fleet-chezmoi#1636), the Vectorize query is
243
+ // ALSO filtered on user_email, so the top-K is drawn from the caller's own
244
+ // vectors. Without it the query is global, and a caller with a small share of
245
+ // a large index can get a top-K made entirely of other users' vectors, which
246
+ // the D1 join then drops: zero results even when their own documents match.
247
+ // The flag needs a user_email metadata index plus a re-upsert of existing
248
+ // vectors first (scripts/vectorize-backfill-metadata.mjs), so it defaults off
249
+ // and a deployment that has not done both keeps the global query.
246
250
 
247
251
  export const RETRIEVE_TOP_K = 5;
248
252
 
253
+ /** VEC_METADATA_FILTER is on only for an explicit "on" / "1" / "true" (fleet-chezmoi#1636). */
254
+ export function vecMetadataFilterOn(env: Pick<Env, "VEC_METADATA_FILTER">): boolean {
255
+ const v = (env.VEC_METADATA_FILTER ?? "").trim().toLowerCase();
256
+ return v === "on" || v === "1" || v === "true";
257
+ }
258
+
249
259
  export async function retrieveContext(
250
260
  env: Env,
251
261
  userEmail: string,
@@ -273,8 +283,9 @@ export async function retrieveContext(
273
283
  return { chunks: [], error: `embed failed: ${m}` };
274
284
  }
275
285
 
276
- // 2) Query Vectorize. No metadata filter - we scope by user in D1 below.
277
- // When projectId is set, we overfetch (3x topK) at the Vectorize stage
286
+ // 2) Query Vectorize. Filtered on user_email when VEC_METADATA_FILTER is on;
287
+ // global otherwise. Either way the D1 join below is the tenant scope and
288
+ // stays, as the second layer. When projectId is set, we overfetch (3x topK) at the Vectorize stage
278
289
  // and filter by project membership in D1, since Vectorize doesn't know
279
290
  // about project membership. Without overfetch, a small topK that all
280
291
  // misses the project would return zero results even when the project
@@ -282,7 +293,12 @@ export async function retrieveContext(
282
293
  const vectorizeTopK = projectId !== undefined ? topK * 3 : topK;
283
294
  let matches: { id: string; score: number }[];
284
295
  try {
285
- const q = await env.VEC.query(queryVec, { topK: vectorizeTopK });
296
+ const q = await env.VEC.query(
297
+ queryVec,
298
+ vecMetadataFilterOn(env)
299
+ ? { topK: vectorizeTopK, filter: { user_email: userEmail } }
300
+ : { topK: vectorizeTopK },
301
+ );
286
302
  matches = (q?.matches ?? []).map((m) => ({ id: m.id, score: m.score }));
287
303
  } catch (err) {
288
304
  const m = err instanceof Error ? err.message : String(err);
@@ -340,11 +356,33 @@ export async function retrieveContext(
340
356
  // 1. user_email mismatch (vectors written under a different identity).
341
357
  // 2. With projectId set: matches were real but none of the matched
342
358
  // documents are members of the requested project.
359
+ // Two messages, deliberately carrying different things.
360
+ //
361
+ // The Vectorize query above is global: it has no metadata filter, because
362
+ // the tenant scope is the D1 join (see the note at the top of this
363
+ // section, which is why this works without a Vectorize metadata index).
364
+ // So `ids` holds whatever the shared index returned, and vector ids are
365
+ // minted as `${userEmail}:${docId}:${chunkIndex}`. On a deployment with
366
+ // more than one tenant, ids in that list can belong to somebody else --
367
+ // which is precisely the case this branch exists to report on.
368
+ //
369
+ // The operator diagnostic keeps them. It is what makes a silent retrieval
370
+ // failure debuggable, and it goes to a log the operator already owns.
343
371
  const idSample = ids.slice(0, 3).join(", ");
344
372
  const scope = projectId !== undefined ? ` project_id=${projectId},` : "";
345
- const msg = `Vectorize returned ${matches.length} matches but D1 join returned 0. user_email='${userEmail}',${scope} sample vector_ids=[${idSample}]. Check whether vectors were upserted under a different user identity, or whether the project has any document members.`;
346
- console.warn("retrieveContext:", msg);
347
- return { chunks: [], error: msg };
373
+ console.warn(
374
+ "retrieveContext:",
375
+ `Vectorize returned ${matches.length} matches but D1 join returned 0. user_email='${userEmail}',${scope} sample vector_ids=[${idSample}]. Check whether vectors were upserted under a different user identity, or whether the project has any document members.`,
376
+ );
377
+
378
+ // The caller gets a true statement about their own retrieval and nothing
379
+ // derived from the shared index. Whatever is returned here is handed to
380
+ // the client verbatim as `retrieval_error` (src/routes/chat.ts), so this
381
+ // string is API output rather than a log line, and is written as such.
382
+ const clientMsg = projectId !== undefined
383
+ ? "No indexed documents in this project matched the query."
384
+ : "No indexed documents matched the query.";
385
+ return { chunks: [], error: clientMsg };
348
386
  }
349
387
 
350
388
  // 4) Merge scores back in, preserve Vectorize ordering. When projectId
@@ -11,15 +11,15 @@ import type { InputAttachment } from "../types";
11
11
  import { extFromMime, bytesToBase64 } from "../utils";
12
12
  import { type AiContext } from "../ai-binding";
13
13
  import {
14
- loadGatewayCredentials,
15
- GATEWAY_NOT_CONFIGURED_MSG,
14
+ resolveGateway,
15
+ gatewayProblemMessage,
16
16
  CF_AIG_TOKEN_REQUIRED_MSG,
17
17
  } from "../gateway-credentials";
18
18
  import {
19
19
  resolveControlPlane,
20
20
  type ControlPlaneCredentials,
21
21
  } from "../control-plane";
22
- import { loadUserPrefs } from "../user-prefs";
22
+ import { loadUserPrefs, type UserPrefsJson } from "../user-prefs";
23
23
  import { resolveIdentity } from "../auth";
24
24
 
25
25
  // ---------- Types ----------
@@ -139,14 +139,27 @@ export async function requireAiContext(
139
139
  userEmail: string,
140
140
  opts?: { requireCfToken?: boolean },
141
141
  ): Promise<AiContext | Response> {
142
- const gateway = await loadGatewayCredentials(env, userEmail);
143
- if (!gateway?.gatewayId) {
144
- return json({ error: GATEWAY_NOT_CONFIGURED_MSG, code: "gateway_not_configured" }, { status: 412 });
142
+ const prefs = await loadUserPrefs(env.DB, userEmail);
143
+ return aiContextFromPrefs(prefs, env, opts);
144
+ }
145
+
146
+ // v1.1.0: every refusal carries its own code so the SPA can say what is
147
+ // missing. gateway_account_id_required is the pre-v1.1.0 shape (slug + token,
148
+ // no account id) in public mode: refused, never resolved on our binding.
149
+ export function aiContextFromPrefs(
150
+ prefs: UserPrefsJson | null,
151
+ env: Env,
152
+ opts?: { requireCfToken?: boolean },
153
+ ): AiContext | Response {
154
+ const { creds, problem } = resolveGateway(prefs, env);
155
+ if (!creds) {
156
+ const code = problem ?? "gateway_not_configured";
157
+ return json({ error: gatewayProblemMessage(code), code }, { status: 412 });
145
158
  }
146
- if (opts?.requireCfToken && !gateway.cfAigToken) {
159
+ if (opts?.requireCfToken && !creds.cfAigToken) {
147
160
  return json({ error: CF_AIG_TOKEN_REQUIRED_MSG, code: "cf_aig_token_required" }, { status: 412 });
148
161
  }
149
- return { env, gateway };
162
+ return { env, gateway: creds };
150
163
  }
151
164
 
152
165
  /**
@@ -168,7 +181,7 @@ export async function requireInferenceBackend(
168
181
  const cp = resolveControlPlane(prefs, env);
169
182
  if (cp) return { kind: "control_plane", cp };
170
183
 
171
- const gatewayOrErr = await requireAiContext(env, userEmail, opts);
184
+ const gatewayOrErr = aiContextFromPrefs(prefs, env, opts);
172
185
  if (gatewayOrErr instanceof Response) return gatewayOrErr;
173
186
  return { kind: "gateway", ctx: gatewayOrErr };
174
187
  }
@@ -9,7 +9,7 @@ import { WorkflowEntrypoint, WorkflowStep } from "cloudflare:workers";
9
9
  import type { WorkflowEvent } from "cloudflare:workers";
10
10
  import type { Env } from "../env";
11
11
  import { aiRun, type AiContext } from "../ai-binding";
12
- import { loadGatewayCredentials, GATEWAY_NOT_CONFIGURED_MSG } from "../gateway-credentials";
12
+ import { requireGatewayCredentials } from "../gateway-credentials";
13
13
  import { buildGenParams } from "../longrun-params";
14
14
  import { unzip } from "../zip";
15
15
  import { r2Put, r2KeyToDataUri, r2DeleteSafe } from "./shared";
@@ -231,10 +231,7 @@ export class LongRunWorkflow extends WorkflowEntrypoint<Env, LongRunParams> {
231
231
  : imageUrl;
232
232
  const params = buildGenParams(kind, { modelId, prompt, lyrics, imageUrl: resolvedImage });
233
233
 
234
- const gateway = await loadGatewayCredentials(this.env, userEmail);
235
- if (!gateway?.gatewayId) {
236
- throw new Error(GATEWAY_NOT_CONFIGURED_MSG);
237
- }
234
+ const gateway = await requireGatewayCredentials(this.env, userEmail);
238
235
  const aiCtx: AiContext = { env: this.env, gateway };
239
236
  const result = await aiRun(aiCtx, modelId, params) as LongRunResult;
240
237
 
@@ -17,6 +17,7 @@ import { DurableObject } from "cloudflare:workers";
17
17
  import type { Env } from "./env";
18
18
  import { buildTranscript, sanitizeCloseCode } from "./stt-util";
19
19
  import { resolveIdentity } from "./auth";
20
+ import { requireAiContext } from "./routes/shared";
20
21
 
21
22
  export const FLUX_STT_MODEL = "@cf/deepgram/flux";
22
23
 
@@ -45,6 +46,21 @@ export class SttSession extends DurableObject<Env> {
45
46
  // src/index.ts. The session cookie rides the same-origin WS upgrade, so
46
47
  // resolveIdentity derives the owner the same way as every HTTP route.
47
48
  const userEmail = (await resolveIdentity(request, this.env)) ?? "anonymous";
49
+
50
+ // The live-voice socket is an inference path like any other, so it
51
+ // resolves the caller's own gateway credentials before opening anything
52
+ // upstream. This calls requireAiContext -- the same gate every HTTP
53
+ // inference route uses -- rather than restating the condition here, so
54
+ // this path cannot drift away from the others.
55
+ //
56
+ // The upstream flux socket does bypass the gateway TRANSPORT: the binding
57
+ // opens it with { websocket: true }, which the gateway cannot proxy. That
58
+ // is a transport property and carries no authorization meaning. An
59
+ // unconfigured caller is refused here, before any upstream session exists
60
+ // and before this DO records session metadata for it.
61
+ const ctxOrErr = await requireAiContext(this.env, userEmail, { requireCfToken: false });
62
+ if (ctxOrErr instanceof Response) return ctxOrErr;
63
+
48
64
  this.ctx.storage.sql.exec(
49
65
  `INSERT OR REPLACE INTO meta (k, v) VALUES ('user', ?), ('model', ?), ('started_at', ?)`,
50
66
  userEmail,