@skyphusion/create-prism 1.0.0 → 1.0.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +1 -1
- package/template/migrations/0004_csp_reports.sql +58 -0
- package/template/package.json +4 -4
- package/template/public/app.js +23 -1
- package/template/public/index.html +2 -1
- package/template/public/stt.css +25 -0
- package/template/public/stt.html +1 -21
- package/template/public/styles.css +11 -0
- package/template/public/url-safety.js +66 -0
- package/template/schema.sql +58 -0
- package/template/src/csp.ts +253 -0
- package/template/src/index.ts +77 -2
- package/template/src/routes/chat.ts +24 -13
- package/template/src/routes/csp-report.ts +163 -0
- package/template/src/routes/health.ts +6 -1
- package/template/src/routes/rag.ts +25 -3
- package/template/src/stt-session.ts +16 -0
- package/template/src/version.ts +18 -0
- package/template/tests/csp.test.ts +444 -0
- package/template/tests/public-url-safety.test.ts +360 -0
- package/template/tests/rag-retrieval-diagnostic.test.ts +142 -0
- package/template/tests/version.test.ts +47 -0
- package/template/tests-integration/csp-report.test.ts +232 -0
- package/template/tests-integration/worker.test.ts +154 -0
- package/template/vitest.workers.config.ts +19 -4
- package/template/wrangler.example.toml +33 -0
package/template/src/index.ts
CHANGED
|
@@ -24,6 +24,7 @@ import {
|
|
|
24
24
|
} from "./auth";
|
|
25
25
|
import { json } from "./routes/shared";
|
|
26
26
|
import { handleHealthDeep } from "./routes/health";
|
|
27
|
+
import { VERSION } from "./version";
|
|
27
28
|
import { handlePrefsGet, handlePrefsPatch } from "./routes/prefs";
|
|
28
29
|
import {
|
|
29
30
|
handleChat,
|
|
@@ -62,6 +63,8 @@ import {
|
|
|
62
63
|
handleDiscordImport,
|
|
63
64
|
} from "./routes/projects";
|
|
64
65
|
import { handleArtifact } from "./routes/artifacts";
|
|
66
|
+
import { handleCspReport } from "./routes/csp-report";
|
|
67
|
+
import { CSP_HEADER, buildCspPolicy } from "./csp";
|
|
65
68
|
|
|
66
69
|
// Durable Object + Workflow classes must stay exported from the main entry so
|
|
67
70
|
// wrangler resolves each class_name against this module.
|
|
@@ -74,8 +77,19 @@ export default {
|
|
|
74
77
|
|
|
75
78
|
// Cheap liveness check. No binding access; sub-millisecond response.
|
|
76
79
|
// Use for high-frequency uptime polling (Kuma at 60s interval, etc).
|
|
80
|
+
//
|
|
81
|
+
// Carries `version` so "which code is serving?" is answerable from an
|
|
82
|
+
// unauthenticated surface. A green deploy workflow proves the upload
|
|
83
|
+
// succeeded, not that the running Worker is the code you think it is, and
|
|
84
|
+
// until this field existed that question needed an account-scoped
|
|
85
|
+
// Cloudflare token. It is on the LIVENESS probe deliberately: the answer
|
|
86
|
+
// is about the deploy, not about the bindings, so it must not require
|
|
87
|
+
// /health/deep's D1, R2 and Vectorize round-trips, and it has to survive
|
|
88
|
+
// the 503 path. Value comes from src/version.ts, pinned to package.json by
|
|
89
|
+
// a test that DERIVES the expected string rather than transcribing it.
|
|
90
|
+
// See fleet-chezmoi#1641.
|
|
77
91
|
if (url.pathname === "/health") {
|
|
78
|
-
return json({ ok: true, ts: Date.now() });
|
|
92
|
+
return json({ ok: true, ts: Date.now(), version: VERSION });
|
|
79
93
|
}
|
|
80
94
|
|
|
81
95
|
// Deep check: exercises D1, R2, Vectorize, and confirms the AI gateway
|
|
@@ -102,6 +116,16 @@ export default {
|
|
|
102
116
|
return handleLogout(request, env);
|
|
103
117
|
}
|
|
104
118
|
|
|
119
|
+
// CSP violation collector (fleet-chezmoi#1646). Sits above the gate
|
|
120
|
+
// deliberately: browsers post violation reports WITHOUT credentials, so a
|
|
121
|
+
// session-gated collector would collect nothing. That makes it an
|
|
122
|
+
// unauthenticated public write endpoint, and the handler is written for
|
|
123
|
+
// that: body cap with refusal past it, fixed bounded projection, per-IP
|
|
124
|
+
// rate limit with visible shedding, prune-on-write retention.
|
|
125
|
+
if (url.pathname === "/api/csp-report" && request.method === "POST") {
|
|
126
|
+
return handleCspReport(request, env);
|
|
127
|
+
}
|
|
128
|
+
|
|
105
129
|
// Public-mode gate: every other /api/* route requires a valid session.
|
|
106
130
|
// GET /api/models is exempt (it is the unauthenticated boot probe). Uniform
|
|
107
131
|
// 401 { code: "unauthenticated" } so the frontend routes the user to the
|
|
@@ -265,7 +289,58 @@ export default {
|
|
|
265
289
|
return handleArtifact(request, env, decodeURIComponent(a[1]));
|
|
266
290
|
}
|
|
267
291
|
|
|
268
|
-
|
|
292
|
+
// ---- Security headers on the static surface (fleet-chezmoi#1646) ----
|
|
293
|
+
//
|
|
294
|
+
// SCOPE, stated so it is not mistaken for more than it is: these are
|
|
295
|
+
// applied to the ASSETS responses, which is where the HTML and every
|
|
296
|
+
// static file come from. API responses returned above do NOT carry them.
|
|
297
|
+
// For CSP that is correct, since a policy only governs the document that
|
|
298
|
+
// carries it. For HSTS it is a known and deliberate gap in phase one: a
|
|
299
|
+
// browser that has loaded the page already holds the header, and widening
|
|
300
|
+
// it to every route is a separate change to every response path.
|
|
301
|
+
//
|
|
302
|
+
// The three headers this deploy already carries (x-frame-options,
|
|
303
|
+
// referrer-policy, x-content-type-options) are NOT set here. They are
|
|
304
|
+
// applied at the edge by a zone Transform Rule for every host on the
|
|
305
|
+
// zone, measured directly in the zone config. Setting them here would be
|
|
306
|
+
// a duplicate CERTAINTY rather than a duplicate risk, and a duplicated
|
|
307
|
+
// x-frame-options is worse than either value alone because agents
|
|
308
|
+
// disagree about which wins. Bringing that rule under declared config is
|
|
309
|
+
// fleet-chezmoi#1626; duplicating a control is not declaring it.
|
|
310
|
+
const assetRes = await env.ASSETS.fetch(request);
|
|
311
|
+
const isHtml = (assetRes.headers.get("content-type") || "").includes("text/html");
|
|
312
|
+
const headers = new Headers(assetRes.headers);
|
|
313
|
+
|
|
314
|
+
// ENFORCING as of the fleet-chezmoi#1646 promotion. Violations are now
|
|
315
|
+
// BLOCKED, and still posted to the collector routed above, which is what
|
|
316
|
+
// keeps this observable: the stored `disposition` reads `enforce` rather
|
|
317
|
+
// than `report`, so a directive this policy gets wrong arrives as a row
|
|
318
|
+
// naming what broke instead of as a user noticing a dead feature.
|
|
319
|
+
//
|
|
320
|
+
// The two exceptions the policy carries (`data:` on img-src, `blob:` on
|
|
321
|
+
// media-src) were each established by an OBSERVED violation during the
|
|
322
|
+
// report-only phase, never by reading the frontend and deciding what
|
|
323
|
+
// looked necessary. See src/csp.ts for the provenance of each.
|
|
324
|
+
//
|
|
325
|
+
// Note the header NAME comes from the same module as the policy. Building
|
|
326
|
+
// an enforcing policy and emitting it under the report-only name is a
|
|
327
|
+
// decorative control that no test reading only one of the two can catch.
|
|
328
|
+
if (isHtml) {
|
|
329
|
+
headers.set(CSP_HEADER, buildCspPolicy());
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
// HSTS. Phase-one max-age is deliberately SHORT (1 day). A long max-age is
|
|
333
|
+
// cached by every client that sees it and cannot be recalled, so shipping
|
|
334
|
+
// six months on first rollout commits the estate to a promise nobody has
|
|
335
|
+
// observed holding yet. Ramping is a one-line change once it has. No
|
|
336
|
+
// preload, which is the genuinely irreversible one.
|
|
337
|
+
headers.set("strict-transport-security", "max-age=86400; includeSubDomains");
|
|
338
|
+
|
|
339
|
+
return new Response(assetRes.body, {
|
|
340
|
+
status: assetRes.status,
|
|
341
|
+
statusText: assetRes.statusText,
|
|
342
|
+
headers,
|
|
343
|
+
});
|
|
269
344
|
},
|
|
270
345
|
|
|
271
346
|
};
|
|
@@ -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
|
-
|
|
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
|
-
|
|
535
|
-
|
|
536
|
-
|
|
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
|
|
@@ -567,8 +578,8 @@ export async function runImage(request: Request, env: Env, model: ModelEntry, bo
|
|
|
567
578
|
mime = gen.mime;
|
|
568
579
|
logId = null; // direct OpenAI; no AI Gateway log
|
|
569
580
|
} else {
|
|
570
|
-
const result = await aiRun(aiCtx
|
|
571
|
-
logId = aiLogId(aiCtx
|
|
581
|
+
const result = await aiRun(aiCtx, model.id, buildProxiedImageParams(model.provider, body.user_input));
|
|
582
|
+
logId = aiLogId(aiCtx);
|
|
572
583
|
|
|
573
584
|
const failure = detectProviderFailure(result);
|
|
574
585
|
if (failure) {
|
|
@@ -684,14 +695,14 @@ export async function runImage(request: Request, env: Env, model: ModelEntry, bo
|
|
|
684
695
|
// populates ai_gateway_log_id for observability).
|
|
685
696
|
let result: unknown;
|
|
686
697
|
if (bypassGateway) {
|
|
698
|
+
// Transport bypass only. Credentials were resolved at the top of
|
|
699
|
+
// runImage, so this call is authorized on exactly the same terms as
|
|
700
|
+
// every other path here. What it skips is the gateway TRANSPORT, and
|
|
701
|
+
// with it the gateway's observability, which is why ai_gateway_log_id
|
|
702
|
+
// stays null on the persisted row below.
|
|
687
703
|
type BypassRunFn = (model: string, params: unknown) => Promise<unknown>;
|
|
688
704
|
result = await (env.AI as unknown as { run: BypassRunFn }).run(model.id, runParams);
|
|
689
705
|
} 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
706
|
result = await aiRun(aiCtx, model.id, runParams);
|
|
696
707
|
logId = aiLogId(aiCtx);
|
|
697
708
|
}
|
|
@@ -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
|
}
|
|
@@ -340,11 +340,33 @@ export async function retrieveContext(
|
|
|
340
340
|
// 1. user_email mismatch (vectors written under a different identity).
|
|
341
341
|
// 2. With projectId set: matches were real but none of the matched
|
|
342
342
|
// documents are members of the requested project.
|
|
343
|
+
// Two messages, deliberately carrying different things.
|
|
344
|
+
//
|
|
345
|
+
// The Vectorize query above is global: it has no metadata filter, because
|
|
346
|
+
// the tenant scope is the D1 join (see the note at the top of this
|
|
347
|
+
// section, which is why this works without a Vectorize metadata index).
|
|
348
|
+
// So `ids` holds whatever the shared index returned, and vector ids are
|
|
349
|
+
// minted as `${userEmail}:${docId}:${chunkIndex}`. On a deployment with
|
|
350
|
+
// more than one tenant, ids in that list can belong to somebody else --
|
|
351
|
+
// which is precisely the case this branch exists to report on.
|
|
352
|
+
//
|
|
353
|
+
// The operator diagnostic keeps them. It is what makes a silent retrieval
|
|
354
|
+
// failure debuggable, and it goes to a log the operator already owns.
|
|
343
355
|
const idSample = ids.slice(0, 3).join(", ");
|
|
344
356
|
const scope = projectId !== undefined ? ` project_id=${projectId},` : "";
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
357
|
+
console.warn(
|
|
358
|
+
"retrieveContext:",
|
|
359
|
+
`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.`,
|
|
360
|
+
);
|
|
361
|
+
|
|
362
|
+
// The caller gets a true statement about their own retrieval and nothing
|
|
363
|
+
// derived from the shared index. Whatever is returned here is handed to
|
|
364
|
+
// the client verbatim as `retrieval_error` (src/routes/chat.ts), so this
|
|
365
|
+
// string is API output rather than a log line, and is written as such.
|
|
366
|
+
const clientMsg = projectId !== undefined
|
|
367
|
+
? "No indexed documents in this project matched the query."
|
|
368
|
+
: "No indexed documents matched the query.";
|
|
369
|
+
return { chunks: [], error: clientMsg };
|
|
348
370
|
}
|
|
349
371
|
|
|
350
372
|
// 4) Merge scores back in, preserve Vectorize ordering. When projectId
|
|
@@ -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,
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
// The version this Worker advertises on its unauthenticated health surfaces.
|
|
2
|
+
//
|
|
3
|
+
// WHY THIS FILE EXISTS: a green deploy workflow proves the UPLOAD succeeded, not that the
|
|
4
|
+
// running Worker is the code you think it is. Without a version on the wire, "is the fix
|
|
5
|
+
// actually serving?" is answerable only with an account-scoped Cloudflare token, from a
|
|
6
|
+
// system separate from the one serving traffic (fleet-chezmoi#1641).
|
|
7
|
+
//
|
|
8
|
+
// WHY A GUARDED LITERAL AND NOT `import pkg from "../package.json"`: importing package.json
|
|
9
|
+
// would bundle the dependency list into a Worker whose whole point here is to disclose one
|
|
10
|
+
// short string, and it would put the manifest on the deployed surface. The literal is a copy
|
|
11
|
+
// -- but it is a copy that CANNOT SHIP WRONG, because tests/version.test.ts reads package.json
|
|
12
|
+
// off disk and derives the expected value from it rather than carrying a second hand-typed
|
|
13
|
+
// copy of the same string.
|
|
14
|
+
//
|
|
15
|
+
// That distinction is the entire point. In prism-mcp the advertised version was a literal and
|
|
16
|
+
// the test asserting it carried a TRANSCRIBED duplicate, so the assertion only ever proved
|
|
17
|
+
// that someone had typed the same thing twice, and a correct version bump went red.
|
|
18
|
+
export const VERSION = "1.0.4";
|