@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.
- package/README.md +7 -4
- package/index.js +1 -0
- package/package.json +1 -1
- package/template/CONTRIBUTING.md +18 -3
- package/template/MIGRATIONS.md +52 -0
- package/template/README.md +50 -16
- package/template/docs/legal/INSTANCE-ACCEPTABLE-USE.md +5 -2
- package/template/docs/legal/INSTANCE-PRIVACY.md +127 -27
- package/template/migrations/0004_csp_reports.sql +58 -0
- package/template/migrations/0005_auth_attempts_retention.sql +23 -0
- package/template/package.json +6 -6
- package/template/public/app.js +42 -7
- package/template/public/index.html +24 -9
- package/template/public/stt.css +25 -0
- package/template/public/stt.html +1 -21
- package/template/public/styles.css +49 -0
- package/template/public/url-safety.js +66 -0
- package/template/schema.sql +64 -0
- package/template/src/ai-binding.ts +125 -3
- package/template/src/auth.ts +6 -0
- package/template/src/csp.ts +253 -0
- package/template/src/env.ts +11 -0
- package/template/src/gateway-credentials.ts +118 -22
- package/template/src/index.ts +79 -2
- package/template/src/providers/anthropic.ts +4 -4
- package/template/src/providers/openai-image.ts +10 -0
- package/template/src/providers/xai.ts +4 -4
- package/template/src/rate-limit.ts +26 -0
- package/template/src/routes/chat.ts +29 -16
- package/template/src/routes/csp-report.ts +163 -0
- package/template/src/routes/health.ts +6 -1
- package/template/src/routes/prefs.ts +46 -5
- package/template/src/routes/rag.ts +53 -15
- package/template/src/routes/shared.ts +22 -9
- package/template/src/routes/workflow.ts +2 -5
- package/template/src/stt-session.ts +16 -0
- package/template/src/user-prefs.ts +16 -3
- package/template/src/version.ts +18 -0
- package/template/tests/ai-binding-rest.test.ts +154 -0
- package/template/tests/csp.test.ts +449 -0
- package/template/tests/gateway-credentials.test.ts +101 -3
- package/template/tests/openai-image.test.ts +21 -1
- package/template/tests/public-url-safety.test.ts +360 -0
- package/template/tests/rag-metadata-filter.test.ts +135 -0
- package/template/tests/rag-retrieval-diagnostic.test.ts +142 -0
- package/template/tests/skip-link.test.ts +164 -0
- package/template/tests/vectorize-backfill-metadata.test.ts +166 -0
- package/template/tests/version.test.ts +47 -0
- package/template/tests-integration/auth.test.ts +346 -2
- package/template/tests-integration/csp-report.test.ts +232 -0
- package/template/tests-integration/pdf-extract.test.ts +71 -0
- package/template/tests-integration/worker.test.ts +154 -0
- package/template/vitest.workers.config.ts +19 -4
- package/template/wrangler.example.toml +45 -2
|
@@ -0,0 +1,253 @@
|
|
|
1
|
+
// Content-Security-Policy: the policy string, and the pure projection of a
|
|
2
|
+
// violation report into the bounded row we persist (fleet-chezmoi#1646).
|
|
3
|
+
//
|
|
4
|
+
// Everything here is a pure function so it is testable in the fast node suite
|
|
5
|
+
// without booting workerd or D1. The DB layer lives in routes/csp-report.ts and
|
|
6
|
+
// does nothing but the rate-limit window and the insert.
|
|
7
|
+
//
|
|
8
|
+
// THE POLICY IS NOW ENFORCING. Phase one shipped it report-only and
|
|
9
|
+
// deliberately stricter than the page was believed to need, so that every
|
|
10
|
+
// exception would be established by an OBSERVED violation rather than by a
|
|
11
|
+
// directive list derived from reading app.js. That phase is over and its
|
|
12
|
+
// output is the two grants in buildCspPolicy below.
|
|
13
|
+
//
|
|
14
|
+
// WORTH KEEPING: phase one's author predicted, in this comment, exactly two
|
|
15
|
+
// violations -- an inline style attribute on the skip link, and a data: image
|
|
16
|
+
// preview. The measurement found FOUR distinct ones. The skip link and the
|
|
17
|
+
// data: image were both real. A blob: URL on TTS playback was not predicted,
|
|
18
|
+
// and an inline <style> block on the STT page was not only unpredicted but
|
|
19
|
+
// could not have reported at all, because that document was being served
|
|
20
|
+
// outside `run_worker_first` and carried no policy header.
|
|
21
|
+
//
|
|
22
|
+
// So a careful reading of the source got 2 of 4, and the two it missed are the
|
|
23
|
+
// ones that would have hurt: one silences voice chat, and the other was
|
|
24
|
+
// invisible to the very instrument that was supposed to find it. That is the
|
|
25
|
+
// argument for the report-only phase, made by the phase itself, and it is the
|
|
26
|
+
// reason a future directive change owes an observation rather than a reading.
|
|
27
|
+
|
|
28
|
+
/** Max accepted request body, in bytes. A CSP report is small; this is generous. */
|
|
29
|
+
export const CSP_REPORT_MAX_BYTES = 8192;
|
|
30
|
+
|
|
31
|
+
/** Per-field character caps. Every value here is attacker-controlled. */
|
|
32
|
+
export const CSP_FIELD_CAPS = {
|
|
33
|
+
document_uri: 512,
|
|
34
|
+
referrer: 512,
|
|
35
|
+
violated_directive: 128,
|
|
36
|
+
effective_directive: 128,
|
|
37
|
+
blocked_uri: 512,
|
|
38
|
+
disposition: 32,
|
|
39
|
+
source_file: 512,
|
|
40
|
+
} as const;
|
|
41
|
+
|
|
42
|
+
/** Reports accepted per window, per client. */
|
|
43
|
+
export const CSP_RATE_LIMIT = 60;
|
|
44
|
+
/** Rate-limit window, seconds. */
|
|
45
|
+
export const CSP_RATE_WINDOW_SECONDS = 300;
|
|
46
|
+
/** Rows older than this are pruned on write. Deletion path, not an intention. */
|
|
47
|
+
export const CSP_RETENTION_DAYS = 30;
|
|
48
|
+
|
|
49
|
+
export interface CspReportRow {
|
|
50
|
+
document_uri: string | null;
|
|
51
|
+
referrer: string | null;
|
|
52
|
+
violated_directive: string | null;
|
|
53
|
+
effective_directive: string | null;
|
|
54
|
+
blocked_uri: string | null;
|
|
55
|
+
disposition: string | null;
|
|
56
|
+
status_code: number | null;
|
|
57
|
+
source_file: string | null;
|
|
58
|
+
line_number: number | null;
|
|
59
|
+
column_number: number | null;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** The response header name. ENFORCING, not `-Report-Only`.
|
|
63
|
+
*
|
|
64
|
+
* Exported so the name and the mode cannot drift apart in a caller: a policy
|
|
65
|
+
* built as enforcing and emitted under the report-only name is a strictly
|
|
66
|
+
* decorative control, and nothing about either string announces the mismatch.
|
|
67
|
+
*/
|
|
68
|
+
export const CSP_HEADER = "content-security-policy";
|
|
69
|
+
|
|
70
|
+
/** The header name phase one used. Kept ONLY so tests can assert it is gone.
|
|
71
|
+
*
|
|
72
|
+
* A retired name is a live hazard rather than trivia: a check that looks for
|
|
73
|
+
* the old header keeps passing after promotion by finding nothing, which is
|
|
74
|
+
* indistinguishable from the header being correctly absent. Asserting on this
|
|
75
|
+
* constant makes "the report-only header is no longer emitted" a claim a test
|
|
76
|
+
* can actually make.
|
|
77
|
+
*/
|
|
78
|
+
export const CSP_HEADER_REPORT_ONLY = "content-security-policy-report-only";
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* The ENFORCING policy served on HTML responses.
|
|
82
|
+
*
|
|
83
|
+
* PROMOTED FROM REPORT-ONLY on mackaye's ruling, fleet-chezmoi#1646 comment
|
|
84
|
+
* 5281677490, after the report-only phase measured what the page genuinely
|
|
85
|
+
* needs. Every exception below was established by a violation that was
|
|
86
|
+
* OBSERVED, never by reading app.js and deciding what looked necessary. That
|
|
87
|
+
* ordering is the whole point of having had a report-only phase, and it is
|
|
88
|
+
* cheap to quietly invert later, so the provenance of each grant is recorded
|
|
89
|
+
* here rather than in a merged PR nobody re-reads.
|
|
90
|
+
*
|
|
91
|
+
* ONLY `report-uri`, DELIBERATELY, AND THIS WAS MEASURED RATHER THAN REASONED.
|
|
92
|
+
*
|
|
93
|
+
* The obvious shape is to emit both: `report-uri` for browsers that never
|
|
94
|
+
* implemented the replacement, plus `report-to` with a companion
|
|
95
|
+
* `Reporting-Endpoints` header for those that did. That is what this shipped
|
|
96
|
+
* first, and it delivered NOTHING.
|
|
97
|
+
*
|
|
98
|
+
* Measured, with the two states separated rather than inferred. A
|
|
99
|
+
* `securitypolicyviolation` listener in the page proved violations were being
|
|
100
|
+
* REGISTERED by the browser while the collector received zero rows, so the
|
|
101
|
+
* violation was real and the DELIVERY was the failure. Removing `report-to`
|
|
102
|
+
* and the `Reporting-Endpoints` header, changing nothing else, made the
|
|
103
|
+
* identical violations arrive immediately. Re-adding `report-to` is a change
|
|
104
|
+
* that must be justified by watching a report arrive over it, not by noting
|
|
105
|
+
* that it is the modern directive.
|
|
106
|
+
*
|
|
107
|
+
* THE COLLECTOR STAYS WIRED UNDER ENFORCEMENT, and that is not leftovers. The
|
|
108
|
+
* stored `disposition` column now distinguishes `enforce` from `report`, so a
|
|
109
|
+
* directive this policy gets wrong shows up as a row naming the thing that was
|
|
110
|
+
* actually broken, instead of as a user reporting that a feature stopped
|
|
111
|
+
* working. Dropping `report-uri` at promotion would retire the instrument at
|
|
112
|
+
* the exact moment it starts describing real refusals.
|
|
113
|
+
*
|
|
114
|
+
* THE TWO GRANTS, each with the observation that produced it. Both were
|
|
115
|
+
* measured violating in a browser run whose off-origin positive control fired
|
|
116
|
+
* in the same run, so neither rests on a zero from an instrument that might
|
|
117
|
+
* simply have been blind.
|
|
118
|
+
*
|
|
119
|
+
* `img-src 'self' data:`
|
|
120
|
+
* Attachment thumbnails, extracted video-frame previews, and the downscale
|
|
121
|
+
* path that feeds them all render a `data:` URL the page produced itself
|
|
122
|
+
* from a local file. Observed as `img-src | data`.
|
|
123
|
+
*
|
|
124
|
+
* `media-src 'self' blob:`
|
|
125
|
+
* TTS playback constructs an `Audio` around a `blob:` URL minted from a
|
|
126
|
+
* same-origin response. Observed as `media-src | blob`.
|
|
127
|
+
*
|
|
128
|
+
* WHY GRANT RATHER THAN REWORK, since the rework reads as the more rigorous
|
|
129
|
+
* option and is the worse one: making the previews same-origin means uploading
|
|
130
|
+
* a user's local image to a server in order to show it back to them in their
|
|
131
|
+
* own browser. Prism is BYOK and privacy-primary. The policy exists to serve
|
|
132
|
+
* that posture, not to outrank it. And promoting with the two features broken
|
|
133
|
+
* is worse still, because a control that fires during healthy operation
|
|
134
|
+
* teaches everyone that its red means nothing, so the next red arrives
|
|
135
|
+
* pre-discounted and the policy eventually gets switched off.
|
|
136
|
+
*
|
|
137
|
+
* WHAT THE GRANTS DO NOT BUY, stated so a later reader does not have to
|
|
138
|
+
* re-derive the blast radius: neither admits script execution. `blob:` is
|
|
139
|
+
* same-origin-created by construction. `data:` here is scoped to `img-src`
|
|
140
|
+
* alone, whose realistic downside is UI spoofing rather than code execution.
|
|
141
|
+
*
|
|
142
|
+
* NOTHING ELSE WIDENED. `script-src` and `connect-src` are unchanged from the
|
|
143
|
+
* measured baseline, `object-src` stays `'none'`, and no `unsafe-inline` or
|
|
144
|
+
* `unsafe-eval` appears anywhere. Adding a directive to make a violation stop
|
|
145
|
+
* arriving is the inversion this whole exercise exists to prevent; tests assert
|
|
146
|
+
* each of those absences by name so a future grant has to be deliberate.
|
|
147
|
+
*/
|
|
148
|
+
export function buildCspPolicy(reportPath = "/api/csp-report"): string {
|
|
149
|
+
return [
|
|
150
|
+
"default-src 'self'",
|
|
151
|
+
"script-src 'self'",
|
|
152
|
+
"style-src 'self'",
|
|
153
|
+
// GRANTED: local file previews, never uploaded. Observed `img-src | data`.
|
|
154
|
+
"img-src 'self' data:",
|
|
155
|
+
"font-src 'self'",
|
|
156
|
+
"connect-src 'self'",
|
|
157
|
+
// GRANTED: TTS playback of a same-origin response. Observed `media-src | blob`.
|
|
158
|
+
"media-src 'self' blob:",
|
|
159
|
+
"object-src 'none'",
|
|
160
|
+
"base-uri 'self'",
|
|
161
|
+
"form-action 'self'",
|
|
162
|
+
"frame-ancestors 'self'",
|
|
163
|
+
`report-uri ${reportPath}`,
|
|
164
|
+
].join("; ");
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
function capped(v: unknown, max: number): string | null {
|
|
169
|
+
if (typeof v !== "string") return null;
|
|
170
|
+
const t = v.trim();
|
|
171
|
+
if (!t) return null;
|
|
172
|
+
return t.slice(0, max);
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
function intOrNull(v: unknown): number | null {
|
|
176
|
+
if (typeof v !== "number" || !Number.isFinite(v)) return null;
|
|
177
|
+
// Bound it: these are line/column/status numbers, not arbitrary integers.
|
|
178
|
+
const n = Math.trunc(v);
|
|
179
|
+
if (n < 0 || n > 100_000_000) return null;
|
|
180
|
+
return n;
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
/**
|
|
184
|
+
* Strip query and fragment from a document URI before storage.
|
|
185
|
+
*
|
|
186
|
+
* The SPA puts nothing in URLs, which was measured rather than assumed, so this
|
|
187
|
+
* changes nothing today. It exists so the collector cannot become the first
|
|
188
|
+
* place a URL-borne value gets persisted if that ever stops being true. An
|
|
189
|
+
* unparseable value is returned capped rather than dropped, because knowing a
|
|
190
|
+
* violation happened somewhere unrecognisable is still worth more than a null.
|
|
191
|
+
*/
|
|
192
|
+
export function stripUrlNoise(raw: unknown): string | null {
|
|
193
|
+
const s = capped(raw, CSP_FIELD_CAPS.document_uri);
|
|
194
|
+
if (s === null) return null;
|
|
195
|
+
try {
|
|
196
|
+
const u = new URL(s);
|
|
197
|
+
u.search = "";
|
|
198
|
+
u.hash = "";
|
|
199
|
+
return u.toString().slice(0, CSP_FIELD_CAPS.document_uri);
|
|
200
|
+
} catch {
|
|
201
|
+
return s;
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
/**
|
|
206
|
+
* Project a parsed report body into the bounded row.
|
|
207
|
+
*
|
|
208
|
+
* Accepts BOTH wire shapes and returns null when neither is present:
|
|
209
|
+
* - `report-uri`: {"csp-report": {...}} with hyphenated keys
|
|
210
|
+
* - `report-to`: [{"type":"csp-violation","body":{...}}] with underscored keys
|
|
211
|
+
*
|
|
212
|
+
* Returning null rather than an empty row matters: an empty row is a record
|
|
213
|
+
* that a violation occurred with no detail, which is indistinguishable from a
|
|
214
|
+
* collector that is mangling its input.
|
|
215
|
+
*/
|
|
216
|
+
export function extractCspReport(parsed: unknown): CspReportRow | null {
|
|
217
|
+
let b: Record<string, unknown> | null = null;
|
|
218
|
+
|
|
219
|
+
if (Array.isArray(parsed)) {
|
|
220
|
+
const entry = parsed.find(
|
|
221
|
+
(e) => e && typeof e === "object" && (e as Record<string, unknown>).type === "csp-violation",
|
|
222
|
+
) as Record<string, unknown> | undefined;
|
|
223
|
+
const body = entry?.body;
|
|
224
|
+
if (body && typeof body === "object") b = body as Record<string, unknown>;
|
|
225
|
+
} else if (parsed && typeof parsed === "object") {
|
|
226
|
+
const legacy = (parsed as Record<string, unknown>)["csp-report"];
|
|
227
|
+
if (legacy && typeof legacy === "object") b = legacy as Record<string, unknown>;
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
if (!b) return null;
|
|
231
|
+
|
|
232
|
+
// Hyphenated (report-uri) first, underscored (Reporting API) second.
|
|
233
|
+
const pick = (a: string, z: string): unknown => (b![a] !== undefined ? b![a] : b![z]);
|
|
234
|
+
|
|
235
|
+
return {
|
|
236
|
+
document_uri: stripUrlNoise(pick("document-uri", "documentURL")),
|
|
237
|
+
referrer: capped(pick("referrer", "referrer"), CSP_FIELD_CAPS.referrer),
|
|
238
|
+
violated_directive: capped(
|
|
239
|
+
pick("violated-directive", "violatedDirective"),
|
|
240
|
+
CSP_FIELD_CAPS.violated_directive,
|
|
241
|
+
),
|
|
242
|
+
effective_directive: capped(
|
|
243
|
+
pick("effective-directive", "effectiveDirective"),
|
|
244
|
+
CSP_FIELD_CAPS.effective_directive,
|
|
245
|
+
),
|
|
246
|
+
blocked_uri: capped(pick("blocked-uri", "blockedURL"), CSP_FIELD_CAPS.blocked_uri),
|
|
247
|
+
disposition: capped(pick("disposition", "disposition"), CSP_FIELD_CAPS.disposition),
|
|
248
|
+
status_code: intOrNull(pick("status-code", "statusCode")),
|
|
249
|
+
source_file: capped(pick("source-file", "sourceFile"), CSP_FIELD_CAPS.source_file),
|
|
250
|
+
line_number: intOrNull(pick("line-number", "lineNumber")),
|
|
251
|
+
column_number: intOrNull(pick("column-number", "columnNumber")),
|
|
252
|
+
};
|
|
253
|
+
}
|
package/template/src/env.ts
CHANGED
|
@@ -17,6 +17,17 @@ export interface Env {
|
|
|
17
17
|
DB: D1Database;
|
|
18
18
|
R2: R2Bucket;
|
|
19
19
|
VEC: VectorizeIndex;
|
|
20
|
+
/**
|
|
21
|
+
* Filter RAG retrieval by `user_email` in Vectorize itself (skyphusion-labs/fleet-chezmoi#1636).
|
|
22
|
+
* "on" (also "1" / "true") turns it on; anything else, including unset, is off.
|
|
23
|
+
*
|
|
24
|
+
* DEFAULT OFF, ON PURPOSE. The filter needs a `user_email` metadata index on the Vectorize index
|
|
25
|
+
* AND every existing vector re-upserted after that index exists (metadata indexes are not
|
|
26
|
+
* retroactive). Turned on before both are done, it hides every older vector and retrieval returns
|
|
27
|
+
* nothing. Order: create the metadata index, run scripts/vectorize-backfill-metadata.mjs, then set
|
|
28
|
+
* this. See MIGRATIONS.md.
|
|
29
|
+
*/
|
|
30
|
+
VEC_METADATA_FILTER?: string;
|
|
20
31
|
ASSETS: Fetcher;
|
|
21
32
|
// v0.167.0 (issue #80): deployment auth plane. "public" = first-party
|
|
22
33
|
// username/password accounts, session cookie identity, and fail-closed
|
|
@@ -2,11 +2,18 @@
|
|
|
2
2
|
//
|
|
3
3
|
// Supports two deployment modes:
|
|
4
4
|
// - Deployer secrets: GATEWAY_ID + CF_AIG_TOKEN on the worker (private install)
|
|
5
|
-
// - Public demo: no worker secrets; each user stores their own
|
|
6
|
-
// and
|
|
5
|
+
// - Public demo: no worker secrets; each user stores their own Cloudflare
|
|
6
|
+
// account id, gateway slug, and API token in D1 user_prefs
|
|
7
7
|
//
|
|
8
|
-
//
|
|
9
|
-
//
|
|
8
|
+
// v1.1.0: before this release a user stored only slug + token, and every call
|
|
9
|
+
// resolved that slug on the worker's AI binding, i.e. on OUR account (the
|
|
10
|
+
// binding cannot address another account). A user's own gateway was
|
|
11
|
+
// unreachable by construction. The account id is what makes it reachable, so
|
|
12
|
+
// it is required before user credentials count as configured.
|
|
13
|
+
//
|
|
14
|
+
// In access mode without a user account id, resolution merges user prefs over
|
|
15
|
+
// worker secrets field-by-field so a partial override still falls back to
|
|
16
|
+
// deployer defaults where unset.
|
|
10
17
|
//
|
|
11
18
|
// v0.167.0 (issue #80): when AUTH_MODE=public the worker secrets are ignored
|
|
12
19
|
// entirely (fail closed). A public deploy must never bill the host for visitor
|
|
@@ -20,10 +27,31 @@ import { loadUserPrefs, type UserPrefsJson } from "./user-prefs";
|
|
|
20
27
|
export interface GatewayCredentials {
|
|
21
28
|
gatewayId: string;
|
|
22
29
|
cfAigToken: string;
|
|
30
|
+
/**
|
|
31
|
+
* v1.1.0: the Cloudflare account that owns `gatewayId`. When set, every call
|
|
32
|
+
* leaves the worker over HTTP to that account (api.cloudflare.com REST or
|
|
33
|
+
* the gateway.ai.cloudflare.com provider endpoint) and bills it. When null,
|
|
34
|
+
* calls ride this worker's own AI binding, which Cloudflare pins to the
|
|
35
|
+
* worker's account ("Must be in the same account as your Worker"), so the
|
|
36
|
+
* deployer pays. Null is only reachable in access mode; public mode refuses
|
|
37
|
+
* credentials without an account id rather than fall back to ours.
|
|
38
|
+
*/
|
|
39
|
+
accountId: string | null;
|
|
23
40
|
}
|
|
24
41
|
|
|
25
42
|
export type GatewaySource = "user" | "worker" | "mixed" | "none";
|
|
26
43
|
|
|
44
|
+
/** Why no usable credentials resolved; each maps to one 412 code. */
|
|
45
|
+
export type GatewayProblem =
|
|
46
|
+
| "gateway_not_configured"
|
|
47
|
+
| "gateway_account_id_required"
|
|
48
|
+
| "cf_aig_token_required";
|
|
49
|
+
|
|
50
|
+
export interface GatewayResolution {
|
|
51
|
+
creds: GatewayCredentials | null;
|
|
52
|
+
problem: GatewayProblem | null;
|
|
53
|
+
}
|
|
54
|
+
|
|
27
55
|
export interface GatewayStatus {
|
|
28
56
|
/**
|
|
29
57
|
* True when the user can run inference: AI Gateway BYOK (gateway id) and/or
|
|
@@ -34,15 +62,51 @@ export interface GatewayStatus {
|
|
|
34
62
|
source: GatewaySource;
|
|
35
63
|
gateway_id: string | null;
|
|
36
64
|
cf_aig_token_set: boolean;
|
|
65
|
+
/** v1.1.0: stored Cloudflare account id (not a secret; it is in every gateway URL). */
|
|
66
|
+
account_id: string | null;
|
|
67
|
+
/**
|
|
68
|
+
* v1.1.0: true for a public-mode user saved under the pre-v1.1.0 shape
|
|
69
|
+
* (slug and/or token but no account id). Their calls are refused until
|
|
70
|
+
* they add it; the SPA uses this to say exactly that instead of a generic
|
|
71
|
+
* "not configured".
|
|
72
|
+
*/
|
|
73
|
+
account_id_required: boolean;
|
|
37
74
|
control_plane_configured: boolean;
|
|
38
75
|
control_plane_key_set: boolean;
|
|
39
76
|
}
|
|
40
77
|
|
|
41
78
|
export const GATEWAY_NOT_CONFIGURED_MSG =
|
|
42
|
-
"Inference not configured. Open Account > AI Gateway and either (1) enter your Cloudflare gateway slug
|
|
79
|
+
"Inference not configured. Open Account > AI Gateway and either (1) enter your Cloudflare account ID, gateway slug, and API token (BYOK), or (2) paste a prism-control-plane client key (pcp_…) to bill chat through play-proxy.";
|
|
43
80
|
|
|
44
81
|
export const CF_AIG_TOKEN_REQUIRED_MSG =
|
|
45
|
-
"This model requires a Cloudflare API token
|
|
82
|
+
"This model requires a Cloudflare API token (Workers AI Read + AI Gateway Run on your account). Add it under Account > AI Gateway.";
|
|
83
|
+
|
|
84
|
+
export const GATEWAY_ACCOUNT_ID_REQUIRED_MSG =
|
|
85
|
+
"Your AI Gateway settings are missing your Cloudflare account ID. Without it a gateway slug resolves on this instance's account, not yours, so model calls are refused until you add it. Open Account > AI Gateway and paste the 32-character account ID from your Cloudflare dashboard.";
|
|
86
|
+
|
|
87
|
+
export function gatewayProblemMessage(problem: GatewayProblem): string {
|
|
88
|
+
switch (problem) {
|
|
89
|
+
case "gateway_account_id_required": return GATEWAY_ACCOUNT_ID_REQUIRED_MSG;
|
|
90
|
+
case "cf_aig_token_required": return CF_AIG_TOKEN_REQUIRED_MSG;
|
|
91
|
+
default: return GATEWAY_NOT_CONFIGURED_MSG;
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
// Cloudflare account ids are 32 lowercase hex characters. Normalizes case so
|
|
96
|
+
// a pasted uppercase id still matches; returns null for anything else.
|
|
97
|
+
const ACCOUNT_ID_RE = /^[0-9a-f]{32}$/;
|
|
98
|
+
export function normalizeAccountId(raw: string | null | undefined): string | null {
|
|
99
|
+
const v = raw?.trim().toLowerCase() ?? "";
|
|
100
|
+
return ACCOUNT_ID_RE.test(v) ? v : null;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
// Gateway slugs become a URL path segment and a request header once they
|
|
104
|
+
// address a user account, so the charset is pinned at write time (and the
|
|
105
|
+
// URL builder still encodes it).
|
|
106
|
+
const GATEWAY_ID_RE = /^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/;
|
|
107
|
+
export function isValidGatewayId(raw: string): boolean {
|
|
108
|
+
return GATEWAY_ID_RE.test(raw.trim());
|
|
109
|
+
}
|
|
46
110
|
|
|
47
111
|
// True when this deployment is the public product; worker gateway secrets are
|
|
48
112
|
// then off-limits for billing resolution.
|
|
@@ -50,17 +114,41 @@ function isPublic(env: Env): boolean {
|
|
|
50
114
|
return env.AUTH_MODE === "public";
|
|
51
115
|
}
|
|
52
116
|
|
|
117
|
+
export function resolveGateway(prefs: UserPrefsJson | null, env: Env): GatewayResolution {
|
|
118
|
+
const userGateway = prefs?.gateway_id?.trim() || "";
|
|
119
|
+
const userToken = prefs?.cf_aig_token?.trim() || "";
|
|
120
|
+
const accountId = normalizeAccountId(prefs?.account_id);
|
|
121
|
+
|
|
122
|
+
// v1.1.0: account-scoped credentials are all-user. No field falls back to a
|
|
123
|
+
// worker secret, because the worker's token authorizes the worker's account
|
|
124
|
+
// and would be rejected by (or worse, meaningless against) the user's.
|
|
125
|
+
if (accountId) {
|
|
126
|
+
if (!userGateway) return { creds: null, problem: "gateway_not_configured" };
|
|
127
|
+
if (!userToken) return { creds: null, problem: "cf_aig_token_required" };
|
|
128
|
+
return { creds: { gatewayId: userGateway, cfAigToken: userToken, accountId }, problem: null };
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
// Public mode: user prefs only, no worker-secret fallback (fail closed), and
|
|
132
|
+
// no account id means no route to the user's gateway. Refuse rather than
|
|
133
|
+
// resolve the slug on the host binding.
|
|
134
|
+
if (isPublic(env)) {
|
|
135
|
+
if (userGateway || userToken) return { creds: null, problem: "gateway_account_id_required" };
|
|
136
|
+
return { creds: null, problem: "gateway_not_configured" };
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
// Access mode (private self-host): the slug names a gateway on this
|
|
140
|
+
// worker's own account and rides the binding. Deployer pays by design.
|
|
141
|
+
const gatewayId = userGateway || env.GATEWAY_ID?.trim() || "";
|
|
142
|
+
const cfAigToken = userToken || env.CF_AIG_TOKEN?.trim() || "";
|
|
143
|
+
if (!gatewayId) return { creds: null, problem: "gateway_not_configured" };
|
|
144
|
+
return { creds: { gatewayId, cfAigToken, accountId: null }, problem: null };
|
|
145
|
+
}
|
|
146
|
+
|
|
53
147
|
export function resolveGatewayFromParts(
|
|
54
148
|
prefs: UserPrefsJson | null,
|
|
55
149
|
env: Env,
|
|
56
150
|
): GatewayCredentials | null {
|
|
57
|
-
|
|
58
|
-
const workerGateway = isPublic(env) ? "" : (env.GATEWAY_ID?.trim() || "");
|
|
59
|
-
const workerToken = isPublic(env) ? "" : (env.CF_AIG_TOKEN?.trim() || "");
|
|
60
|
-
const gatewayId = (prefs?.gateway_id?.trim() || workerGateway);
|
|
61
|
-
const cfAigToken = (prefs?.cf_aig_token?.trim() || workerToken);
|
|
62
|
-
if (!gatewayId) return null;
|
|
63
|
-
return { gatewayId, cfAigToken };
|
|
151
|
+
return resolveGateway(prefs, env).creds;
|
|
64
152
|
}
|
|
65
153
|
|
|
66
154
|
export function gatewaySource(prefs: UserPrefsJson | null, env: Env): GatewaySource {
|
|
@@ -78,12 +166,16 @@ export function gatewaySource(prefs: UserPrefsJson | null, env: Env): GatewaySou
|
|
|
78
166
|
return "none";
|
|
79
167
|
}
|
|
80
168
|
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
169
|
+
/**
|
|
170
|
+
* Load credentials or throw the problem's user-facing message. For callers
|
|
171
|
+
* outside the HTTP gate (RAG embeddings, the long-run Workflow) that surface
|
|
172
|
+
* an Error rather than a 412.
|
|
173
|
+
*/
|
|
174
|
+
export async function requireGatewayCredentials(env: Env, userEmail: string): Promise<GatewayCredentials> {
|
|
85
175
|
const prefs = await loadUserPrefs(env.DB, userEmail);
|
|
86
|
-
|
|
176
|
+
const { creds, problem } = resolveGateway(prefs, env);
|
|
177
|
+
if (!creds) throw new Error(gatewayProblemMessage(problem ?? "gateway_not_configured"));
|
|
178
|
+
return creds;
|
|
87
179
|
}
|
|
88
180
|
|
|
89
181
|
/**
|
|
@@ -91,13 +183,17 @@ export async function loadGatewayCredentials(
|
|
|
91
183
|
* Control-plane pcp_ keys count as configured even with no gateway slug.
|
|
92
184
|
*/
|
|
93
185
|
export function buildGatewayStatus(prefs: UserPrefsJson | null, env: Env): GatewayStatus {
|
|
94
|
-
const
|
|
186
|
+
const { creds, problem } = resolveGateway(prefs, env);
|
|
95
187
|
const cp = resolveControlPlane(prefs, env);
|
|
96
188
|
return {
|
|
97
|
-
configured: !!
|
|
189
|
+
configured: !!creds || !!cp,
|
|
98
190
|
source: gatewaySource(prefs, env),
|
|
99
|
-
|
|
100
|
-
|
|
191
|
+
// Echo what the user saved even when it does not resolve yet, so a
|
|
192
|
+
// pre-v1.1.0 user sees their slug and only has to add the account id.
|
|
193
|
+
gateway_id: creds?.gatewayId ?? (prefs?.gateway_id?.trim() || null),
|
|
194
|
+
cf_aig_token_set: !!(creds?.cfAigToken || prefs?.cf_aig_token?.trim()),
|
|
195
|
+
account_id: normalizeAccountId(prefs?.account_id),
|
|
196
|
+
account_id_required: problem === "gateway_account_id_required",
|
|
101
197
|
control_plane_configured: !!cp,
|
|
102
198
|
control_plane_key_set: !!prefs?.control_plane_key?.trim(),
|
|
103
199
|
};
|
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
|
|
@@ -145,6 +169,8 @@ export default {
|
|
|
145
169
|
source: "none" as const,
|
|
146
170
|
gateway_id: null,
|
|
147
171
|
cf_aig_token_set: false,
|
|
172
|
+
account_id: null,
|
|
173
|
+
account_id_required: false,
|
|
148
174
|
control_plane_configured: false,
|
|
149
175
|
control_plane_key_set: false,
|
|
150
176
|
};
|
|
@@ -265,7 +291,58 @@ export default {
|
|
|
265
291
|
return handleArtifact(request, env, decodeURIComponent(a[1]));
|
|
266
292
|
}
|
|
267
293
|
|
|
268
|
-
|
|
294
|
+
// ---- Security headers on the static surface (fleet-chezmoi#1646) ----
|
|
295
|
+
//
|
|
296
|
+
// SCOPE, stated so it is not mistaken for more than it is: these are
|
|
297
|
+
// applied to the ASSETS responses, which is where the HTML and every
|
|
298
|
+
// static file come from. API responses returned above do NOT carry them.
|
|
299
|
+
// For CSP that is correct, since a policy only governs the document that
|
|
300
|
+
// carries it. For HSTS it is a known and deliberate gap in phase one: a
|
|
301
|
+
// browser that has loaded the page already holds the header, and widening
|
|
302
|
+
// it to every route is a separate change to every response path.
|
|
303
|
+
//
|
|
304
|
+
// The three headers this deploy already carries (x-frame-options,
|
|
305
|
+
// referrer-policy, x-content-type-options) are NOT set here. They are
|
|
306
|
+
// applied at the edge by a zone Transform Rule for every host on the
|
|
307
|
+
// zone, measured directly in the zone config. Setting them here would be
|
|
308
|
+
// a duplicate CERTAINTY rather than a duplicate risk, and a duplicated
|
|
309
|
+
// x-frame-options is worse than either value alone because agents
|
|
310
|
+
// disagree about which wins. Bringing that rule under declared config is
|
|
311
|
+
// fleet-chezmoi#1626; duplicating a control is not declaring it.
|
|
312
|
+
const assetRes = await env.ASSETS.fetch(request);
|
|
313
|
+
const isHtml = (assetRes.headers.get("content-type") || "").includes("text/html");
|
|
314
|
+
const headers = new Headers(assetRes.headers);
|
|
315
|
+
|
|
316
|
+
// ENFORCING as of the fleet-chezmoi#1646 promotion. Violations are now
|
|
317
|
+
// BLOCKED, and still posted to the collector routed above, which is what
|
|
318
|
+
// keeps this observable: the stored `disposition` reads `enforce` rather
|
|
319
|
+
// than `report`, so a directive this policy gets wrong arrives as a row
|
|
320
|
+
// naming what broke instead of as a user noticing a dead feature.
|
|
321
|
+
//
|
|
322
|
+
// The two exceptions the policy carries (`data:` on img-src, `blob:` on
|
|
323
|
+
// media-src) were each established by an OBSERVED violation during the
|
|
324
|
+
// report-only phase, never by reading the frontend and deciding what
|
|
325
|
+
// looked necessary. See src/csp.ts for the provenance of each.
|
|
326
|
+
//
|
|
327
|
+
// Note the header NAME comes from the same module as the policy. Building
|
|
328
|
+
// an enforcing policy and emitting it under the report-only name is a
|
|
329
|
+
// decorative control that no test reading only one of the two can catch.
|
|
330
|
+
if (isHtml) {
|
|
331
|
+
headers.set(CSP_HEADER, buildCspPolicy());
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
// HSTS. Phase-one max-age is deliberately SHORT (1 day). A long max-age is
|
|
335
|
+
// cached by every client that sees it and cannot be recalled, so shipping
|
|
336
|
+
// six months on first rollout commits the estate to a promise nobody has
|
|
337
|
+
// observed holding yet. Ramping is a one-line change once it has. No
|
|
338
|
+
// preload, which is the genuinely irreversible one.
|
|
339
|
+
headers.set("strict-transport-security", "max-age=86400; includeSubDomains");
|
|
340
|
+
|
|
341
|
+
return new Response(assetRes.body, {
|
|
342
|
+
status: assetRes.status,
|
|
343
|
+
statusText: assetRes.statusText,
|
|
344
|
+
headers,
|
|
345
|
+
});
|
|
269
346
|
},
|
|
270
347
|
|
|
271
348
|
};
|
|
@@ -18,7 +18,7 @@
|
|
|
18
18
|
// blocks with base64 source.
|
|
19
19
|
|
|
20
20
|
import type { AiContext } from "../ai-binding";
|
|
21
|
-
import { aiRun, aiLogId } from "../ai-binding";
|
|
21
|
+
import { aiRun, aiLogId, gatewayProviderUrl } from "../ai-binding";
|
|
22
22
|
import type { ModelEntry } from "../models";
|
|
23
23
|
import type { ProviderStreamEvent } from "../parsers/types";
|
|
24
24
|
import { CF_AIG_TOKEN_REQUIRED_MSG } from "../gateway-credentials";
|
|
@@ -92,9 +92,9 @@ async function prepareAnthropicRequest(
|
|
|
92
92
|
): Promise<{ url: string; headers: Record<string, string>; body: string }> {
|
|
93
93
|
const { system, messages: aMessages } = transformToAnthropic(messages, systemPrompt);
|
|
94
94
|
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
95
|
+
// v1.1.0: built from the caller's own account when the credentials carry
|
|
96
|
+
// one; the binding's getUrl would always name this worker's account.
|
|
97
|
+
const baseUrl = await gatewayProviderUrl(ctx, "anthropic");
|
|
98
98
|
|
|
99
99
|
// Strip the "anthropic/" prefix we use in our internal IDs; Anthropic's API
|
|
100
100
|
// expects just the model name (e.g. "claude-opus-4-6").
|
|
@@ -13,8 +13,18 @@
|
|
|
13
13
|
// GPT image models ALWAYS return base64 (data[0].b64_json); the `url` response
|
|
14
14
|
// format is unsupported for them. `background: "transparent"` with
|
|
15
15
|
// `output_format: "png"` yields an RGBA PNG.
|
|
16
|
+
import type { Env } from "../env";
|
|
16
17
|
import { base64ToBytes } from "../utils";
|
|
17
18
|
|
|
19
|
+
// The deployer key to use for transparent PNG, or null for the opaque proxy.
|
|
20
|
+
// prism#193 (v1.0.5): AUTH_MODE=public ignores OPENAI_API_KEY entirely, the
|
|
21
|
+
// same fail-closed rule gateway-credentials.ts applies to GATEWAY_ID /
|
|
22
|
+
// CF_AIG_TOKEN, so a stray host secret cannot bill the host for a visitor.
|
|
23
|
+
export function resolveOpenAIImageKey(env: Env): string | null {
|
|
24
|
+
if (env.AUTH_MODE === "public") return null;
|
|
25
|
+
return env.OPENAI_API_KEY?.trim() || null;
|
|
26
|
+
}
|
|
27
|
+
|
|
18
28
|
export interface GeneratedImage {
|
|
19
29
|
bytes: Uint8Array;
|
|
20
30
|
mime: string;
|
|
@@ -20,7 +20,7 @@
|
|
|
20
20
|
// rather than the older max_tokens field.
|
|
21
21
|
|
|
22
22
|
import type { AiContext } from "../ai-binding";
|
|
23
|
-
import { aiRun, aiLogId } from "../ai-binding";
|
|
23
|
+
import { aiRun, aiLogId, gatewayProviderUrl } from "../ai-binding";
|
|
24
24
|
import type { ModelEntry } from "../models";
|
|
25
25
|
import type { ProviderStreamEvent } from "../parsers/types";
|
|
26
26
|
import { CF_AIG_TOKEN_REQUIRED_MSG } from "../gateway-credentials";
|
|
@@ -38,9 +38,9 @@ async function prepareXaiRequest(
|
|
|
38
38
|
messages: Array<unknown>,
|
|
39
39
|
opts: { stream: boolean },
|
|
40
40
|
): Promise<{ url: string; headers: Record<string, string>; body: string }> {
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
41
|
+
// v1.1.0: built from the caller's own account when the credentials carry
|
|
42
|
+
// one; the binding's getUrl would always name this worker's account.
|
|
43
|
+
const baseUrl = await gatewayProviderUrl(ctx, "grok");
|
|
44
44
|
|
|
45
45
|
// Strip "xai/" prefix; xAI's API expects just the model name (e.g. "grok-4.3").
|
|
46
46
|
const modelName = model.id.replace(/^xai\//, "");
|