@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
package/template/package.json
CHANGED
|
@@ -17,16 +17,16 @@
|
|
|
17
17
|
"db:migrate:remote": "wrangler d1 execute skyphusion-llm --remote --file=schema.sql"
|
|
18
18
|
},
|
|
19
19
|
"dependencies": {
|
|
20
|
-
"unpdf": "^1.
|
|
20
|
+
"unpdf": "^2.1.0",
|
|
21
21
|
"xlsx": "https://cdn.sheetjs.com/xlsx-0.20.3/xlsx-0.20.3.tgz"
|
|
22
22
|
},
|
|
23
23
|
"devDependencies": {
|
|
24
|
-
"@cloudflare/vitest-pool-workers": "^0.
|
|
25
|
-
"@cloudflare/workers-types": "^5.
|
|
26
|
-
"@types/node": "^26.
|
|
27
|
-
"@vitest/coverage-v8": "^4.1.
|
|
24
|
+
"@cloudflare/vitest-pool-workers": "^0.23.0",
|
|
25
|
+
"@cloudflare/workers-types": "^5.20261108.1",
|
|
26
|
+
"@types/node": "^26.6.6",
|
|
27
|
+
"@vitest/coverage-v8": "^4.1.12",
|
|
28
28
|
"typescript": "^7.0.2",
|
|
29
29
|
"vitest": "^4.1.8",
|
|
30
|
-
"wrangler": "^4.
|
|
30
|
+
"wrangler": "^4.158.0"
|
|
31
31
|
}
|
|
32
32
|
}
|
package/template/public/app.js
CHANGED
|
@@ -374,8 +374,11 @@ function renderGatewayBanner() {
|
|
|
374
374
|
}
|
|
375
375
|
gatewayBanner.hidden = false;
|
|
376
376
|
if (gatewayBannerText) {
|
|
377
|
-
|
|
378
|
-
|
|
377
|
+
// v1.1.0: saved before account ids existed (slug + token only). Say the
|
|
378
|
+
// one thing that is missing rather than "not configured".
|
|
379
|
+
gatewayBannerText.textContent = g.account_id_required
|
|
380
|
+
? "Add your Cloudflare account ID under Account > AI Gateway. Without it your gateway is unreachable, so model calls are refused."
|
|
381
|
+
: "Inference not configured. Set AI Gateway (BYOK) or a control-plane pcp_ client key under Account settings.";
|
|
379
382
|
}
|
|
380
383
|
}
|
|
381
384
|
|
|
@@ -886,7 +889,7 @@ function renderRetrievedChunksHTML(chunks) {
|
|
|
886
889
|
<span class="rc-file">${escapeHtml(c.title || "?")}</span>
|
|
887
890
|
<span class="rc-meta">${escapeHtml(sourceLabel)}${score}</span>
|
|
888
891
|
</summary>
|
|
889
|
-
<pre class="rc-text"><a href="${escapeHtml(c.url
|
|
892
|
+
<pre class="rc-text"><a href="${escapeHtml(window.safeHref(c.url))}" target="_blank" rel="noopener noreferrer">${escapeHtml(c.url || "")}</a>
|
|
890
893
|
|
|
891
894
|
${escapeHtml(c.snippet || "")}</pre>
|
|
892
895
|
</details>`;
|
|
@@ -1508,7 +1511,8 @@ async function run() {
|
|
|
1508
1511
|
userInput.focus();
|
|
1509
1512
|
// #80 fail-closed: 412 = no AI Gateway BYOK and no control-plane pcp_ key.
|
|
1510
1513
|
// Open the account modal so either path can be configured.
|
|
1511
|
-
if (err.status === 412 || err.code === "gateway_not_configured" || err.code === "cf_aig_token_required"
|
|
1514
|
+
if (err.status === 412 || err.code === "gateway_not_configured" || err.code === "cf_aig_token_required"
|
|
1515
|
+
|| err.code === "gateway_account_id_required") {
|
|
1512
1516
|
openGatewayModal();
|
|
1513
1517
|
}
|
|
1514
1518
|
} finally {
|
|
@@ -2188,6 +2192,7 @@ const projectModalCancel = $("#project-modal-cancel");
|
|
|
2188
2192
|
const projectModalDelete = $("#project-modal-delete");
|
|
2189
2193
|
|
|
2190
2194
|
const gatewayModal = $("#gateway-modal");
|
|
2195
|
+
const gatewayModalAccount = $("#gateway-modal-account");
|
|
2191
2196
|
const gatewayModalId = $("#gateway-modal-id");
|
|
2192
2197
|
const gatewayModalToken = $("#gateway-modal-token");
|
|
2193
2198
|
const gatewayModalTokenHint= $("#gateway-modal-token-hint");
|
|
@@ -2354,6 +2359,7 @@ async function openGatewayModal() {
|
|
|
2354
2359
|
if (gatewayModalClearCp) gatewayModalClearCp.checked = false;
|
|
2355
2360
|
try {
|
|
2356
2361
|
const prefs = await api("/api/prefs");
|
|
2362
|
+
if (gatewayModalAccount) gatewayModalAccount.value = prefs.account_id || "";
|
|
2357
2363
|
gatewayModalId.value = prefs.gateway_id || "";
|
|
2358
2364
|
if (gatewayModalTokenHint) {
|
|
2359
2365
|
gatewayModalTokenHint.textContent = prefs.cf_aig_token_set
|
|
@@ -2377,6 +2383,8 @@ async function openGatewayModal() {
|
|
|
2377
2383
|
source: prefs.source,
|
|
2378
2384
|
gateway_id: prefs.gateway_id,
|
|
2379
2385
|
cf_aig_token_set: prefs.cf_aig_token_set,
|
|
2386
|
+
account_id: prefs.account_id,
|
|
2387
|
+
account_id_required: !!prefs.account_id_required,
|
|
2380
2388
|
control_plane_configured: !!prefs.control_plane_configured,
|
|
2381
2389
|
};
|
|
2382
2390
|
renderGatewayBanner();
|
|
@@ -2387,11 +2395,23 @@ async function openGatewayModal() {
|
|
|
2387
2395
|
gatewayModalError.hidden = false;
|
|
2388
2396
|
}
|
|
2389
2397
|
gatewayModal.hidden = false;
|
|
2390
|
-
|
|
2398
|
+
if (gatewayModalAccount && !gatewayModalAccount.value) gatewayModalAccount.focus();
|
|
2399
|
+
else gatewayModalId.focus();
|
|
2391
2400
|
}
|
|
2392
2401
|
|
|
2393
2402
|
function closeGatewayModal() {
|
|
2394
2403
|
if (gatewayModal) gatewayModal.hidden = true;
|
|
2404
|
+
// Drop the plaintext credentials out of the DOM on the way out, so no
|
|
2405
|
+
// client-side copy of either secret outlives the modal that collected
|
|
2406
|
+
// it. The clear lives HERE rather than at the call sites because every
|
|
2407
|
+
// dismissal already routes through this function (save success, the
|
|
2408
|
+
// cancel button, the backdrop, the X affordance, Escape): one clear on
|
|
2409
|
+
// the single chokepoint holds by construction, where five clears hold
|
|
2410
|
+
// only while all five stay correct. Adding a sixth dismissal path gets
|
|
2411
|
+
// this for free; tests/public-url-safety.test.ts asserts the routing
|
|
2412
|
+
// stays true so that stops being an assumption.
|
|
2413
|
+
if (gatewayModalToken) gatewayModalToken.value = "";
|
|
2414
|
+
if (gatewayModalCpKey) gatewayModalCpKey.value = "";
|
|
2395
2415
|
}
|
|
2396
2416
|
|
|
2397
2417
|
function showGatewayModalError(msg) {
|
|
@@ -2401,7 +2421,9 @@ function showGatewayModalError(msg) {
|
|
|
2401
2421
|
|
|
2402
2422
|
async function saveGatewayModal() {
|
|
2403
2423
|
const gateway_id = gatewayModalId.value.trim();
|
|
2424
|
+
const account_id = gatewayModalAccount ? gatewayModalAccount.value.trim() : "";
|
|
2404
2425
|
const body = {};
|
|
2426
|
+
if (gatewayModalAccount) body.account_id = account_id;
|
|
2405
2427
|
if (gateway_id) body.gateway_id = gateway_id;
|
|
2406
2428
|
else body.gateway_id = "";
|
|
2407
2429
|
if (gatewayModalClear.checked) {
|
|
@@ -2415,8 +2437,8 @@ async function saveGatewayModal() {
|
|
|
2415
2437
|
body.control_plane_key = gatewayModalCpKey.value.trim();
|
|
2416
2438
|
}
|
|
2417
2439
|
const hasCp = body.control_plane_key || body.clear_control_plane_key;
|
|
2418
|
-
if (!gateway_id && !body.cf_aig_token && !body.clear_cf_aig_token && !hasCp) {
|
|
2419
|
-
showGatewayModalError("enter
|
|
2440
|
+
if (!account_id && !gateway_id && !body.cf_aig_token && !body.clear_cf_aig_token && !hasCp) {
|
|
2441
|
+
showGatewayModalError("enter your account ID, gateway slug, API token, and/or control-plane key");
|
|
2420
2442
|
return;
|
|
2421
2443
|
}
|
|
2422
2444
|
try {
|
|
@@ -2426,6 +2448,8 @@ async function saveGatewayModal() {
|
|
|
2426
2448
|
source: prefs.source,
|
|
2427
2449
|
gateway_id: prefs.gateway_id,
|
|
2428
2450
|
cf_aig_token_set: prefs.cf_aig_token_set,
|
|
2451
|
+
account_id: prefs.account_id,
|
|
2452
|
+
account_id_required: !!prefs.account_id_required,
|
|
2429
2453
|
control_plane_configured: !!prefs.control_plane_configured,
|
|
2430
2454
|
};
|
|
2431
2455
|
renderGatewayBanner();
|
|
@@ -2848,6 +2872,17 @@ function openAccountDeleteModal() {
|
|
|
2848
2872
|
}
|
|
2849
2873
|
function closeAccountDeleteModal() {
|
|
2850
2874
|
if (accountDeleteModal) accountDeleteModal.hidden = true;
|
|
2875
|
+
// Drop the password out of the DOM on the way out, matching the AI Gateway
|
|
2876
|
+
// modal. All four dismissal paths route through here (the backdrop and the
|
|
2877
|
+
// close affordance via data-modal-close, Escape, and the cancel button), and
|
|
2878
|
+
// the success path calls location.reload(), so the value cannot outlive the
|
|
2879
|
+
// modal by either route.
|
|
2880
|
+
//
|
|
2881
|
+
// Deliberately NOT cleared on a failed delete: a wrong password leaves the
|
|
2882
|
+
// modal open with the value intact so the user can correct it. Clearing on
|
|
2883
|
+
// dismissal and clearing on every error are different rules, and only the
|
|
2884
|
+
// first one is wanted here.
|
|
2885
|
+
if (accountDeletePassword) accountDeletePassword.value = "";
|
|
2851
2886
|
}
|
|
2852
2887
|
async function submitAccountDelete() {
|
|
2853
2888
|
const password = accountDeletePassword ? accountDeletePassword.value : "";
|
|
@@ -44,10 +44,19 @@
|
|
|
44
44
|
</script>
|
|
45
45
|
</head>
|
|
46
46
|
<body>
|
|
47
|
-
|
|
47
|
+
<!-- fc#1700 skip link (WCAG 2.4.1 bypass blocks). Was an offscreen anchor
|
|
48
|
+
named seo-skip pointing at the conditionally-hidden auth panel, with no
|
|
49
|
+
:focus reveal anywhere: the first Tab on the page moved focus to an
|
|
50
|
+
element that stayed at x = -9999 and whose target was hidden. It now
|
|
51
|
+
names what it does, reveals itself on focus, and targets the main
|
|
52
|
+
content landmark. Kept first in the body; that position is the point. -->
|
|
53
|
+
<a class="skip-link" href="#main-content">Skip to main content</a>
|
|
48
54
|
<!-- #80 public-mode first-party auth. Hidden by default; the boot probe
|
|
49
|
-
(GET /api/
|
|
50
|
-
|
|
55
|
+
(GET /api/models, the single unauthenticated entry point, which carries
|
|
56
|
+
mode + authenticated alongside the catalog) reveals it only when
|
|
57
|
+
mode=public and no session. There is no GET /api/session route; this
|
|
58
|
+
comment named one until fc#1700. Access / self-host deploys report
|
|
59
|
+
mode=access and never show it. -->
|
|
51
60
|
<div id="auth-screen" class="auth-screen" hidden>
|
|
52
61
|
<form id="auth-form" class="auth-card" novalidate>
|
|
53
62
|
<div class="auth-brand">
|
|
@@ -85,9 +94,10 @@
|
|
|
85
94
|
<button type="submit" id="auth-submit" class="auth-submit">create account</button>
|
|
86
95
|
|
|
87
96
|
<p class="auth-foot">
|
|
88
|
-
Inference runs on your own Cloudflare account: after you sign in,
|
|
89
|
-
an AI Gateway
|
|
90
|
-
|
|
97
|
+
Inference runs on your own Cloudflare account: after you sign in, add your
|
|
98
|
+
account ID, an AI Gateway slug, and an API token under Account. Storage,
|
|
99
|
+
retrieval, live voice, Deepgram transcription, and six gateway-incompatible
|
|
100
|
+
Workers AI image models run on our account; all other model spend bills yours.
|
|
91
101
|
</p>
|
|
92
102
|
</form>
|
|
93
103
|
</div>
|
|
@@ -173,7 +183,7 @@
|
|
|
173
183
|
</header>
|
|
174
184
|
|
|
175
185
|
<div id="gateway-banner" class="gateway-banner" hidden>
|
|
176
|
-
<span id="gateway-banner-text">AI Gateway not configured. Set your gateway slug and
|
|
186
|
+
<span id="gateway-banner-text">AI Gateway not configured. Set your Cloudflare account ID, gateway slug, and API token to run models on your account.</span>
|
|
177
187
|
<button id="gateway-banner-btn" type="button">Configure</button>
|
|
178
188
|
</div>
|
|
179
189
|
|
|
@@ -198,7 +208,7 @@
|
|
|
198
208
|
</label>
|
|
199
209
|
</div>
|
|
200
210
|
|
|
201
|
-
<main class="conversation">
|
|
211
|
+
<main class="conversation" id="main-content" tabindex="-1">
|
|
202
212
|
<header class="conv-head">
|
|
203
213
|
<span id="conv-title">new conversation</span>
|
|
204
214
|
<span id="conv-compact-badge" class="conv-compact-badge" hidden title="Older turns are summarized for the model; full transcript still shown below">compacted</span>
|
|
@@ -277,7 +287,11 @@
|
|
|
277
287
|
<button class="modal-close" data-modal-close="gateway-modal" type="button" title="close">✕</button>
|
|
278
288
|
</header>
|
|
279
289
|
<div class="modal-body">
|
|
280
|
-
<p class="modal-hint">Connect your Cloudflare AI Gateway so model calls bill your account via Unified Billing. Create a gateway in the Cloudflare dashboard
|
|
290
|
+
<p class="modal-hint">Connect your Cloudflare AI Gateway so model calls bill your account via Unified Billing. Create a gateway in the Cloudflare dashboard and load credits, then paste your <strong>account ID</strong>, the gateway slug, and an API token scoped to that account with <strong>Workers AI Read</strong> and <strong>AI Gateway Run</strong>. All three are required: without the account ID a slug would resolve on this instance's account, so calls are refused instead.</p>
|
|
291
|
+
<label class="modal-field">
|
|
292
|
+
<span>Cloudflare account ID</span>
|
|
293
|
+
<input id="gateway-modal-account" type="text" autocomplete="off" spellcheck="false" maxlength="32" placeholder="32 hex characters, from your dashboard">
|
|
294
|
+
</label>
|
|
281
295
|
<label class="modal-field">
|
|
282
296
|
<span>gateway slug</span>
|
|
283
297
|
<input id="gateway-modal-id" type="text" autocomplete="off" placeholder="my-gateway-slug">
|
|
@@ -369,6 +383,7 @@
|
|
|
369
383
|
</div>
|
|
370
384
|
</div>
|
|
371
385
|
|
|
386
|
+
<script src="/url-safety.js"></script>
|
|
372
387
|
<script src="/voice-widget.js"></script>
|
|
373
388
|
<script src="/app.js"></script>
|
|
374
389
|
</body>
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
/* Conversational STT page chrome. Loaded by stt.html alongside styles.css.
|
|
2
|
+
These rules lived in an inline <style> block in stt.html until fc#1646.
|
|
3
|
+
An enforcing `style-src 'self'` blocks an inline <style> element, which
|
|
4
|
+
would have taken the entire layout of this page; an external sheet needs
|
|
5
|
+
no policy exception. Rules are unchanged, only relocated and dedented. */
|
|
6
|
+
|
|
7
|
+
.stt-layout { max-width: 820px; margin: 0 auto; padding: 1rem; }
|
|
8
|
+
.stt-controls { display: flex; align-items: center; gap: 1rem; margin: 1rem 0; }
|
|
9
|
+
#stt-start { font-size: 1rem; padding: 0.6rem 1.4rem; border-radius: 999px; cursor: pointer; }
|
|
10
|
+
#stt-start.is-live { background: #b3122c; color: #fff; }
|
|
11
|
+
.stt-status { opacity: 0.8; font-size: 0.9rem; }
|
|
12
|
+
.stt-live { min-height: 3.5rem; font-size: 1.25rem; line-height: 1.5; padding: 0.75rem 1rem;
|
|
13
|
+
border: 1px solid rgba(255,255,255,0.15); border-radius: 10px; margin-bottom: 1rem; }
|
|
14
|
+
.stt-live-interim { opacity: 0.55; font-style: italic; }
|
|
15
|
+
.stt-turns { display: flex; flex-direction: column; gap: 0.4rem; margin-bottom: 1.5rem; }
|
|
16
|
+
.stt-turn { padding: 0.5rem 0.75rem; border-radius: 8px; background: rgba(255,255,255,0.05); }
|
|
17
|
+
.stt-meta { font-size: 0.78rem; opacity: 0.6; }
|
|
18
|
+
.stt-debug { font-family: ui-monospace, monospace; font-size: 0.72rem; white-space: pre-wrap;
|
|
19
|
+
max-height: 220px; overflow-y: auto; background: rgba(0,0,0,0.25); padding: 0.5rem;
|
|
20
|
+
border-radius: 8px; }
|
|
21
|
+
.stt-debug-row { padding: 1px 0; border-bottom: 1px solid rgba(255,255,255,0.06); }
|
|
22
|
+
summary { cursor: pointer; opacity: 0.8; }
|
|
23
|
+
.stt-page-header { margin-bottom: 0.5rem; }
|
|
24
|
+
.stt-back { font-size: 0.85rem; opacity: 0.7; text-decoration: none; }
|
|
25
|
+
.stt-back:hover { opacity: 1; }
|
package/template/public/stt.html
CHANGED
|
@@ -11,27 +11,7 @@
|
|
|
11
11
|
<link rel="manifest" href="/manifest.webmanifest">
|
|
12
12
|
<meta name="theme-color" content="#0E1730">
|
|
13
13
|
<link rel="stylesheet" href="/styles.css">
|
|
14
|
-
<
|
|
15
|
-
.stt-layout { max-width: 820px; margin: 0 auto; padding: 1rem; }
|
|
16
|
-
.stt-controls { display: flex; align-items: center; gap: 1rem; margin: 1rem 0; }
|
|
17
|
-
#stt-start { font-size: 1rem; padding: 0.6rem 1.4rem; border-radius: 999px; cursor: pointer; }
|
|
18
|
-
#stt-start.is-live { background: #b3122c; color: #fff; }
|
|
19
|
-
.stt-status { opacity: 0.8; font-size: 0.9rem; }
|
|
20
|
-
.stt-live { min-height: 3.5rem; font-size: 1.25rem; line-height: 1.5; padding: 0.75rem 1rem;
|
|
21
|
-
border: 1px solid rgba(255,255,255,0.15); border-radius: 10px; margin-bottom: 1rem; }
|
|
22
|
-
.stt-live-interim { opacity: 0.55; font-style: italic; }
|
|
23
|
-
.stt-turns { display: flex; flex-direction: column; gap: 0.4rem; margin-bottom: 1.5rem; }
|
|
24
|
-
.stt-turn { padding: 0.5rem 0.75rem; border-radius: 8px; background: rgba(255,255,255,0.05); }
|
|
25
|
-
.stt-meta { font-size: 0.78rem; opacity: 0.6; }
|
|
26
|
-
.stt-debug { font-family: ui-monospace, monospace; font-size: 0.72rem; white-space: pre-wrap;
|
|
27
|
-
max-height: 220px; overflow-y: auto; background: rgba(0,0,0,0.25); padding: 0.5rem;
|
|
28
|
-
border-radius: 8px; }
|
|
29
|
-
.stt-debug-row { padding: 1px 0; border-bottom: 1px solid rgba(255,255,255,0.06); }
|
|
30
|
-
summary { cursor: pointer; opacity: 0.8; }
|
|
31
|
-
.stt-page-header { margin-bottom: 0.5rem; }
|
|
32
|
-
.stt-back { font-size: 0.85rem; opacity: 0.7; text-decoration: none; }
|
|
33
|
-
.stt-back:hover { opacity: 1; }
|
|
34
|
-
</style>
|
|
14
|
+
<link rel="stylesheet" href="/stt.css">
|
|
35
15
|
</head>
|
|
36
16
|
<body class="stt-body">
|
|
37
17
|
<!-- Conversational STT is a skyphusion-llm playground feature; standalone
|
|
@@ -25,6 +25,55 @@
|
|
|
25
25
|
|
|
26
26
|
* { box-sizing: border-box; }
|
|
27
27
|
|
|
28
|
+
/* Skip link (WCAG 2.4.1 bypass blocks), first focusable element in the body.
|
|
29
|
+
Offscreen until focused, on-screen while focused.
|
|
30
|
+
|
|
31
|
+
The offscreen declarations live here rather than in an inline `style`
|
|
32
|
+
attribute because an enforcing CSP drops style-src-attr: fc#1646 / #177
|
|
33
|
+
moved them out, and they stay out.
|
|
34
|
+
|
|
35
|
+
fc#1700 added the half that makes this an accessibility feature instead of
|
|
36
|
+
an invisible focus stop. Measured before the fix: the element was the first
|
|
37
|
+
focusable node in the body, and its bounding box was still x = -9999 AFTER
|
|
38
|
+
.focus(), so a keyboard user's first Tab on the credential page landed on a
|
|
39
|
+
link they could not see. The `:focus` rule below is what that measurement
|
|
40
|
+
was missing, so do not drop it without re-measuring.
|
|
41
|
+
|
|
42
|
+
The target is the main content landmark, not the auth panel: `#auth-screen`
|
|
43
|
+
is `hidden` until the public-mode boot probe reveals it, so the old href
|
|
44
|
+
aimed focus at a hidden element on every signed-in page. And when the gate
|
|
45
|
+
IS up, `body.auth-active .layout` is display:none, so there is no sidebar
|
|
46
|
+
to bypass and no target to land on: the link leaves the tab order entirely
|
|
47
|
+
in that state, which puts the first Tab on the auth form itself. */
|
|
48
|
+
.skip-link {
|
|
49
|
+
position: absolute;
|
|
50
|
+
left: -9999px;
|
|
51
|
+
top: 0;
|
|
52
|
+
z-index: 200; /* above .auth-screen (100) and the sidebar backdrop */
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
.skip-link:focus {
|
|
56
|
+
left: 8px;
|
|
57
|
+
top: 8px;
|
|
58
|
+
padding: 10px 16px;
|
|
59
|
+
background: var(--bg-elev2);
|
|
60
|
+
color: var(--fg);
|
|
61
|
+
border: 1px solid var(--accent);
|
|
62
|
+
border-radius: var(--radius-sm);
|
|
63
|
+
box-shadow: var(--shadow), var(--shadow-glow);
|
|
64
|
+
outline: 2px solid var(--accent-cyan);
|
|
65
|
+
outline-offset: 2px;
|
|
66
|
+
text-decoration: none;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/* No skip link while the auth gate is up: nothing to bypass, nowhere to go. */
|
|
70
|
+
body.auth-active .skip-link { display: none; }
|
|
71
|
+
|
|
72
|
+
/* The skip target takes programmatic focus (tabindex="-1") so the next Tab
|
|
73
|
+
continues from the main column instead of restarting at the top of the
|
|
74
|
+
document. It is not keyboard-reachable on its own, so it gets no ring. */
|
|
75
|
+
#main-content:focus { outline: none; }
|
|
76
|
+
|
|
28
77
|
html, body {
|
|
29
78
|
margin: 0;
|
|
30
79
|
padding: 0;
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
// URL safety for values this app did not construct.
|
|
2
|
+
//
|
|
3
|
+
// Web-search results reach the transcript carrying a `url` field that
|
|
4
|
+
// originates off-box. SearXNG hands upstream engine results through with a
|
|
5
|
+
// truthiness filter only (src/searxng.ts filters on `r.url && r.title` and
|
|
6
|
+
// never parses), src/routes/rag.ts maps them to source_type:"web", and the
|
|
7
|
+
// value is persisted in retrieved_context and replayed on every subsequent
|
|
8
|
+
// transcript render. So the string in an href there is not ours.
|
|
9
|
+
//
|
|
10
|
+
// WHY ESCAPING IS THE WRONG TOOL HERE. escapeHtml() replaces & < > " ' and is
|
|
11
|
+
// exactly right for stopping attribute injection. It does nothing whatever to
|
|
12
|
+
// a scheme: `javascript:alert(1)` contains none of those five characters and
|
|
13
|
+
// passes through escaping byte for byte. Escaping answers "can this break out
|
|
14
|
+
// of the attribute", and the question an href also has to answer is "what does
|
|
15
|
+
// this navigate to". Two different questions, two different guards, and both
|
|
16
|
+
// call sites keep both.
|
|
17
|
+
//
|
|
18
|
+
// PARSE, DO NOT PATTERN-MATCH. The URL parser strips leading and trailing
|
|
19
|
+
// C0/space, and removes embedded tab, LF and CR, before it resolves the
|
|
20
|
+
// scheme. So " JavaScript:x", "java\nscript:x" and "JAVASCRIPT:x" all
|
|
21
|
+
// normalise to protocol "javascript:" and are refused by the check below,
|
|
22
|
+
// while a hand-written regex sees three unrelated strings and will miss at
|
|
23
|
+
// least one of them. Delegating to the parser is what makes the guard
|
|
24
|
+
// complete rather than a list of the variants someone happened to think of.
|
|
25
|
+
//
|
|
26
|
+
// ALLOWLIST, NOT BLOCKLIST. An allowlist of the two schemes a web result can
|
|
27
|
+
// legitimately use cannot be outgrown; a blocklist of the dangerous ones has
|
|
28
|
+
// to be extended every time a browser ships a new scheme.
|
|
29
|
+
//
|
|
30
|
+
// Its own file, loaded as a classic script before app.js, the same shape
|
|
31
|
+
// voice-widget.js already uses for shared browser helpers. It is separate so
|
|
32
|
+
// that the SHIPPED function is addressable from a test: app.js touches the DOM
|
|
33
|
+
// at top level and cannot be evaluated outside a browser, so a guard living
|
|
34
|
+
// inside it could only ever be tested by a copy, and a copy is a second thing
|
|
35
|
+
// that drifts. tests/public-url-safety.test.ts evaluates THIS file and refuses
|
|
36
|
+
// to run at all if the function is missing or renamed, so the suite cannot
|
|
37
|
+
// pass vacuously against a guard that is no longer there.
|
|
38
|
+
(function () {
|
|
39
|
+
"use strict";
|
|
40
|
+
|
|
41
|
+
var ALLOWED_PROTOCOLS = ["http:", "https:"];
|
|
42
|
+
|
|
43
|
+
// Returns a value safe to place in an href attribute, or "#" when the input
|
|
44
|
+
// is not a plain web URL.
|
|
45
|
+
//
|
|
46
|
+
// On success it returns the ORIGINAL string rather than the parser's
|
|
47
|
+
// normalised form, so the href and the visible link text next to it stay
|
|
48
|
+
// byte-identical. That is deliberate: a link whose text and destination
|
|
49
|
+
// differ is its own problem, and normalisation would introduce one. The
|
|
50
|
+
// caller still passes the result through escapeHtml, which is what handles
|
|
51
|
+
// a quote inside an otherwise legitimate https URL.
|
|
52
|
+
window.safeHref = function safeHref(raw) {
|
|
53
|
+
if (typeof raw !== "string" || !raw.trim()) return "#";
|
|
54
|
+
var parsed;
|
|
55
|
+
try {
|
|
56
|
+
parsed = new URL(raw);
|
|
57
|
+
} catch (_) {
|
|
58
|
+
// Not an absolute URL. Every caller here passes an absolute one, so a
|
|
59
|
+
// parse failure is a refusal rather than a case to resolve against a
|
|
60
|
+
// base: guessing a base for an unparseable string is how you turn "I do
|
|
61
|
+
// not know what this is" into a confident wrong destination.
|
|
62
|
+
return "#";
|
|
63
|
+
}
|
|
64
|
+
return ALLOWED_PROTOCOLS.indexOf(parsed.protocol) === -1 ? "#" : raw;
|
|
65
|
+
};
|
|
66
|
+
})();
|
package/template/schema.sql
CHANGED
|
@@ -298,3 +298,67 @@ CREATE TABLE IF NOT EXISTS auth_attempts (
|
|
|
298
298
|
count INTEGER NOT NULL DEFAULT 0,
|
|
299
299
|
window_start TEXT NOT NULL DEFAULT (datetime('now'))
|
|
300
300
|
);
|
|
301
|
+
|
|
302
|
+
-- prism#192: src/rate-limit.ts prunes this table on write (the csp_reports
|
|
303
|
+
-- pattern) so "transient IP processing" in the hosted privacy notice is true of
|
|
304
|
+
-- the code. The prune filters window_start; index it, exactly as
|
|
305
|
+
-- idx_csp_reports_received does for the other prune-on-write table.
|
|
306
|
+
CREATE INDEX IF NOT EXISTS idx_auth_attempts_window ON auth_attempts(window_start);
|
|
307
|
+
-- 0004: CSP violation collector (fleet-chezmoi#1646).
|
|
308
|
+
--
|
|
309
|
+
-- Two tables, and the split is the point. `csp_report_buckets` is a rate-limit
|
|
310
|
+
-- counter and could have reused `auth_attempts`, which already has exactly this
|
|
311
|
+
-- shape and a prefixed bucket-key namespace. It deliberately does not.
|
|
312
|
+
--
|
|
313
|
+
-- WHY: the collector's write endpoint is UNAUTHENTICATED by construction, because
|
|
314
|
+
-- browsers post CSP reports without credentials. Pointing an unauthenticated
|
|
315
|
+
-- public write path at the same table the LOGIN limiter depends on means a flood
|
|
316
|
+
-- against the collector contends with sign-in. One extra table is a cheap price
|
|
317
|
+
-- for not coupling a public write path to the auth path.
|
|
318
|
+
--
|
|
319
|
+
-- Apply to an existing database with:
|
|
320
|
+
-- npx wrangler d1 execute skyphusion-llm --remote --file=migrations/0004_csp_reports.sql
|
|
321
|
+
-- Fresh databases get this from schema.sql.
|
|
322
|
+
|
|
323
|
+
-- Collected violations. Every column is a BOUNDED projection of an
|
|
324
|
+
-- attacker-controlled report body; nothing is stored verbatim.
|
|
325
|
+
--
|
|
326
|
+
-- NOT STORED, deliberately: `script-sample`. It can carry fragments of inline
|
|
327
|
+
-- script from a page that handles a credential, and a violation is diagnosable
|
|
328
|
+
-- from the directive plus the blocked URI without it.
|
|
329
|
+
CREATE TABLE IF NOT EXISTS csp_reports (
|
|
330
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
331
|
+
received_at TEXT NOT NULL DEFAULT (datetime('now')),
|
|
332
|
+
-- document_uri is stored with query and fragment STRIPPED. The SPA puts
|
|
333
|
+
-- nothing in URLs (measured), so this costs nothing today and stops the
|
|
334
|
+
-- collector becoming the first place a URL-borne value is persisted.
|
|
335
|
+
document_uri TEXT,
|
|
336
|
+
referrer TEXT,
|
|
337
|
+
violated_directive TEXT,
|
|
338
|
+
effective_directive TEXT,
|
|
339
|
+
blocked_uri TEXT,
|
|
340
|
+
disposition TEXT,
|
|
341
|
+
status_code INTEGER,
|
|
342
|
+
source_file TEXT,
|
|
343
|
+
line_number INTEGER,
|
|
344
|
+
column_number INTEGER
|
|
345
|
+
);
|
|
346
|
+
|
|
347
|
+
-- Read path is operator-only and deliberately has no HTTP endpoint: there is no
|
|
348
|
+
-- admin role on this product, so an authenticated read route would let any
|
|
349
|
+
-- signed-up user read operator diagnostics from a credential-handling page.
|
|
350
|
+
-- Operators query with:
|
|
351
|
+
-- npx wrangler d1 execute skyphusion-llm --remote \
|
|
352
|
+
-- --command "SELECT received_at, effective_directive, blocked_uri, document_uri
|
|
353
|
+
-- FROM csp_reports ORDER BY id DESC LIMIT 50;"
|
|
354
|
+
CREATE INDEX IF NOT EXISTS idx_csp_reports_received ON csp_reports(received_at);
|
|
355
|
+
|
|
356
|
+
-- Rate-limit buckets for the collector, isolated from auth_attempts per the note
|
|
357
|
+
-- above. `dropped` is what makes shedding VISIBLE: without it a rate-limited
|
|
358
|
+
-- estate and a quiet one produce an identical empty table.
|
|
359
|
+
CREATE TABLE IF NOT EXISTS csp_report_buckets (
|
|
360
|
+
bucket_key TEXT PRIMARY KEY,
|
|
361
|
+
count INTEGER NOT NULL DEFAULT 0,
|
|
362
|
+
dropped INTEGER NOT NULL DEFAULT 0,
|
|
363
|
+
window_start TEXT NOT NULL DEFAULT (datetime('now'))
|
|
364
|
+
);
|
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
// env.AI binding wrappers (v0.19.3; per-user gateway v0.164.0
|
|
1
|
+
// env.AI binding wrappers (v0.19.3; per-user gateway v0.164.0; account-scoped
|
|
2
|
+
// REST transport v1.1.0).
|
|
2
3
|
//
|
|
3
4
|
// Extracted from src/index.ts so provider modules and other code paths that
|
|
4
5
|
// call env.AI.run share one binding wrapper rather than each constructing its
|
|
@@ -8,26 +9,147 @@
|
|
|
8
9
|
// return the raw Response (rather than a parsed object) for binary-output
|
|
9
10
|
// models like TTS.
|
|
10
11
|
//
|
|
11
|
-
// `aiLogId` reads the Cloudflare AI Gateway log ID
|
|
12
|
-
//
|
|
12
|
+
// `aiLogId` reads the Cloudflare AI Gateway log ID after a call, when one
|
|
13
|
+
// exists.
|
|
14
|
+
//
|
|
15
|
+
// v1.1.0: two transports, chosen by the credentials, never by the model.
|
|
16
|
+
// - accountId null: env.AI.run on this worker's binding. Cloudflare pins the
|
|
17
|
+
// binding's gateway to the worker's own account and pre-authenticates it,
|
|
18
|
+
// so this bills the deployer. Access mode (private self-host) only.
|
|
19
|
+
// - accountId set: POST api.cloudflare.com/client/v4/accounts/{account}/ai/run
|
|
20
|
+
// with the user's token and cf-aig-gateway-id, which bills the user's
|
|
21
|
+
// account. This is the only way to reach another account's gateway; the
|
|
22
|
+
// binding cannot, whatever gateway id it is handed.
|
|
23
|
+
// `gatewayProviderUrl` applies the same split to the provider-native
|
|
24
|
+
// gateway.ai.cloudflare.com endpoints (legacy Anthropic / xAI paths).
|
|
13
25
|
|
|
14
26
|
import type { Env } from "./env";
|
|
15
27
|
import type { GatewayCredentials } from "./gateway-credentials";
|
|
28
|
+
import { base64ToBytes } from "./utils";
|
|
16
29
|
|
|
17
30
|
export interface AiContext {
|
|
18
31
|
env: Env;
|
|
19
32
|
gateway: GatewayCredentials;
|
|
33
|
+
/** v1.1.0: cf-aig-log-id from the last REST call (the binding tracks its own). */
|
|
34
|
+
lastLogId?: string | null;
|
|
20
35
|
}
|
|
21
36
|
|
|
22
37
|
type RunOpts = { gateway: { id: string }; returnRawResponse?: boolean };
|
|
23
38
|
type RunFn = (model: string, params: unknown, opts?: RunOpts) => Promise<unknown>;
|
|
24
39
|
|
|
40
|
+
export const CF_API_BASE = "https://api.cloudflare.com/client/v4";
|
|
41
|
+
export const AI_GATEWAY_BASE = "https://gateway.ai.cloudflare.com/v1";
|
|
42
|
+
|
|
25
43
|
export function aiRun(ctx: AiContext, model: string, params: unknown, returnRaw = false): Promise<unknown> {
|
|
44
|
+
if (ctx.gateway.accountId) return restRun(ctx, ctx.gateway.accountId, model, params, returnRaw);
|
|
26
45
|
const opts: RunOpts = { gateway: { id: ctx.gateway.gatewayId } };
|
|
27
46
|
if (returnRaw) opts.returnRawResponse = true;
|
|
28
47
|
return (ctx.env.AI as unknown as { run: RunFn }).run(model, params, opts);
|
|
29
48
|
}
|
|
30
49
|
|
|
31
50
|
export function aiLogId(ctx: AiContext): string | null {
|
|
51
|
+
// An account-scoped context never reads the binding: its log id belongs to
|
|
52
|
+
// whatever the binding last did on OUR account, not to this call.
|
|
53
|
+
if (ctx.gateway.accountId) return ctx.lastLogId ?? null;
|
|
32
54
|
return (ctx.env.AI as unknown as { aiGatewayLogId?: string }).aiGatewayLogId ?? null;
|
|
33
55
|
}
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* Base URL of a provider-native AI Gateway endpoint
|
|
59
|
+
* (https://gateway.ai.cloudflare.com/v1/{account}/{gateway}/{provider}).
|
|
60
|
+
* Account-scoped credentials build it from the user's account; otherwise the
|
|
61
|
+
* binding's getUrl supplies this worker's own account.
|
|
62
|
+
*/
|
|
63
|
+
export async function gatewayProviderUrl(ctx: AiContext, provider: string): Promise<string> {
|
|
64
|
+
const { accountId, gatewayId } = ctx.gateway;
|
|
65
|
+
if (accountId) {
|
|
66
|
+
return `${AI_GATEWAY_BASE}/${accountId}/${encodeURIComponent(gatewayId)}/${provider}`;
|
|
67
|
+
}
|
|
68
|
+
return (ctx.env.AI as unknown as {
|
|
69
|
+
gateway: (id: string) => { getUrl: (provider: string) => Promise<string> };
|
|
70
|
+
}).gateway(gatewayId).getUrl(provider);
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
// Workers AI (@cf/) models use the model-in-path endpoint, the one Cloudflare
|
|
74
|
+
// documents for billing @cf calls to the gateway's credits; partner models use
|
|
75
|
+
// the /ai/run envelope ({ model, input }). Both take cf-aig-gateway-id.
|
|
76
|
+
export function buildRestRunRequest(
|
|
77
|
+
accountId: string,
|
|
78
|
+
gateway: GatewayCredentials,
|
|
79
|
+
model: string,
|
|
80
|
+
params: unknown,
|
|
81
|
+
): { url: string; init: RequestInit } {
|
|
82
|
+
const base = `${CF_API_BASE}/accounts/${accountId}/ai/run`;
|
|
83
|
+
const isWorkersAi = model.startsWith("@cf/");
|
|
84
|
+
return {
|
|
85
|
+
url: isWorkersAi ? `${base}/${model}` : base,
|
|
86
|
+
init: {
|
|
87
|
+
method: "POST",
|
|
88
|
+
headers: {
|
|
89
|
+
"authorization": `Bearer ${gateway.cfAigToken}`,
|
|
90
|
+
"cf-aig-gateway-id": gateway.gatewayId,
|
|
91
|
+
"content-type": "application/json",
|
|
92
|
+
},
|
|
93
|
+
body: JSON.stringify(isWorkersAi ? params : { model, input: params }),
|
|
94
|
+
},
|
|
95
|
+
};
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
async function restRun(
|
|
99
|
+
ctx: AiContext,
|
|
100
|
+
accountId: string,
|
|
101
|
+
model: string,
|
|
102
|
+
params: unknown,
|
|
103
|
+
returnRaw: boolean,
|
|
104
|
+
): Promise<unknown> {
|
|
105
|
+
const { url, init } = buildRestRunRequest(accountId, ctx.gateway, model, params);
|
|
106
|
+
const resp = await fetch(url, init);
|
|
107
|
+
ctx.lastLogId = resp.headers.get("cf-aig-log-id");
|
|
108
|
+
return unwrapRestResponse(resp, accountId, returnRaw);
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
// Normalizes a REST response to what the binding would have returned, so no
|
|
112
|
+
// caller has to know which transport ran:
|
|
113
|
+
// - JSON: unwrap the Cloudflare API envelope ({ success, result, errors }).
|
|
114
|
+
// - SSE / binary: the body stream (the binding returns a ReadableStream).
|
|
115
|
+
// - returnRaw: a Response carrying the bytes (TTS reads arrayBuffer()).
|
|
116
|
+
export async function unwrapRestResponse(resp: Response, accountId: string, returnRaw: boolean): Promise<unknown> {
|
|
117
|
+
if (!resp.ok) {
|
|
118
|
+
const text = await resp.text().catch(() => "");
|
|
119
|
+
let detail = text.slice(0, 500);
|
|
120
|
+
try {
|
|
121
|
+
const parsed = JSON.parse(text) as { errors?: Array<{ code?: number; message?: string }> };
|
|
122
|
+
if (parsed.errors?.length) {
|
|
123
|
+
detail = parsed.errors.map((e) => `${e.code ?? ""} ${e.message ?? ""}`.trim()).join("; ");
|
|
124
|
+
}
|
|
125
|
+
} catch { /* non-JSON error body; keep the text */ }
|
|
126
|
+
let hint = "";
|
|
127
|
+
if (resp.status === 401 || resp.status === 403) {
|
|
128
|
+
hint = ` Check that your API token has Workers AI Read and AI Gateway Run on account ${accountId}.`;
|
|
129
|
+
}
|
|
130
|
+
throw new Error(`Cloudflare AI (your account) ${resp.status}: ${detail || resp.statusText}.${hint}`);
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
const ct = resp.headers.get("content-type") || "";
|
|
134
|
+
if (ct.includes("application/json")) {
|
|
135
|
+
const body = await resp.json() as { success?: boolean; result?: unknown; errors?: Array<{ message?: string }> };
|
|
136
|
+
let unwrapped: unknown = body;
|
|
137
|
+
if (body && typeof body === "object" && typeof body.success === "boolean") {
|
|
138
|
+
if (!body.success) {
|
|
139
|
+
const msg = body.errors?.map((e) => e.message).filter(Boolean).join("; ") || "request failed";
|
|
140
|
+
throw new Error(`Cloudflare AI (your account): ${msg}`);
|
|
141
|
+
}
|
|
142
|
+
unwrapped = body.result;
|
|
143
|
+
}
|
|
144
|
+
if (!returnRaw) return unwrapped;
|
|
145
|
+
// Raw callers want bytes. Some TTS models answer JSON { audio: base64 }.
|
|
146
|
+
const audio = (unwrapped as { audio?: unknown } | null)?.audio;
|
|
147
|
+
if (typeof audio === "string") {
|
|
148
|
+
return new Response(base64ToBytes(audio), { headers: { "content-type": "audio/mpeg" } });
|
|
149
|
+
}
|
|
150
|
+
throw new Error("Cloudflare AI (your account): expected binary output, got JSON without an audio field");
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
if (returnRaw) return resp;
|
|
154
|
+
return resp.body;
|
|
155
|
+
}
|
package/template/src/auth.ts
CHANGED
|
@@ -313,6 +313,12 @@ export async function cascadeDeleteUserData(env: Env, userId: string): Promise<v
|
|
|
313
313
|
env.DB.prepare(`DELETE FROM documents WHERE user_email = ?`).bind(userId),
|
|
314
314
|
env.DB.prepare(`DELETE FROM projects WHERE user_email = ?`).bind(userId),
|
|
315
315
|
env.DB.prepare(`DELETE FROM chats WHERE user_email = ?`).bind(userId),
|
|
316
|
+
// prism#192: conversation_compact holds a model-written SUMMARY of this
|
|
317
|
+
// user's chat turns, so leaving it behind is exactly the shadow copy
|
|
318
|
+
// INSTANCE-PRIVACY.md says deletion does not keep. Deleting a single
|
|
319
|
+
// conversation already removes its row (routes/conversations.ts); account
|
|
320
|
+
// deletion is the path that skipped it.
|
|
321
|
+
env.DB.prepare(`DELETE FROM conversation_compact WHERE user_email = ?`).bind(userId),
|
|
316
322
|
env.DB.prepare(`DELETE FROM user_prefs WHERE user_email = ?`).bind(userId),
|
|
317
323
|
env.DB.prepare(`DELETE FROM sessions WHERE user_id = ?`).bind(userId),
|
|
318
324
|
env.DB.prepare(`DELETE FROM users WHERE id = ?`).bind(userId),
|