@skyphusion/create-prism 1.0.4 → 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/0005_auth_attempts_retention.sql +23 -0
- package/template/package.json +6 -6
- package/template/public/app.js +19 -6
- package/template/public/index.html +23 -9
- package/template/public/styles.css +45 -7
- package/template/schema.sql +6 -0
- package/template/src/ai-binding.ts +125 -3
- package/template/src/auth.ts +6 -0
- package/template/src/env.ts +11 -0
- package/template/src/gateway-credentials.ts +118 -22
- package/template/src/index.ts +2 -0
- 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 +5 -3
- package/template/src/routes/prefs.ts +46 -5
- package/template/src/routes/rag.ts +28 -12
- package/template/src/routes/shared.ts +22 -9
- package/template/src/routes/workflow.ts +2 -5
- package/template/src/user-prefs.ts +16 -3
- package/template/src/version.ts +1 -1
- package/template/tests/ai-binding-rest.test.ts +154 -0
- package/template/tests/csp.test.ts +11 -6
- package/template/tests/gateway-credentials.test.ts +101 -3
- package/template/tests/openai-image.test.ts +21 -1
- package/template/tests/rag-metadata-filter.test.ts +135 -0
- package/template/tests/skip-link.test.ts +164 -0
- package/template/tests/vectorize-backfill-metadata.test.ts +166 -0
- package/template/tests-integration/auth.test.ts +346 -2
- package/template/tests-integration/pdf-extract.test.ts +71 -0
- package/template/wrangler.example.toml +12 -2
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
|
|
|
@@ -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,7 +2395,8 @@ 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() {
|
|
@@ -2412,7 +2421,9 @@ function showGatewayModalError(msg) {
|
|
|
2412
2421
|
|
|
2413
2422
|
async function saveGatewayModal() {
|
|
2414
2423
|
const gateway_id = gatewayModalId.value.trim();
|
|
2424
|
+
const account_id = gatewayModalAccount ? gatewayModalAccount.value.trim() : "";
|
|
2415
2425
|
const body = {};
|
|
2426
|
+
if (gatewayModalAccount) body.account_id = account_id;
|
|
2416
2427
|
if (gateway_id) body.gateway_id = gateway_id;
|
|
2417
2428
|
else body.gateway_id = "";
|
|
2418
2429
|
if (gatewayModalClear.checked) {
|
|
@@ -2426,8 +2437,8 @@ async function saveGatewayModal() {
|
|
|
2426
2437
|
body.control_plane_key = gatewayModalCpKey.value.trim();
|
|
2427
2438
|
}
|
|
2428
2439
|
const hasCp = body.control_plane_key || body.clear_control_plane_key;
|
|
2429
|
-
if (!gateway_id && !body.cf_aig_token && !body.clear_cf_aig_token && !hasCp) {
|
|
2430
|
-
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");
|
|
2431
2442
|
return;
|
|
2432
2443
|
}
|
|
2433
2444
|
try {
|
|
@@ -2437,6 +2448,8 @@ async function saveGatewayModal() {
|
|
|
2437
2448
|
source: prefs.source,
|
|
2438
2449
|
gateway_id: prefs.gateway_id,
|
|
2439
2450
|
cf_aig_token_set: prefs.cf_aig_token_set,
|
|
2451
|
+
account_id: prefs.account_id,
|
|
2452
|
+
account_id_required: !!prefs.account_id_required,
|
|
2440
2453
|
control_plane_configured: !!prefs.control_plane_configured,
|
|
2441
2454
|
};
|
|
2442
2455
|
renderGatewayBanner();
|
|
@@ -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">
|
|
@@ -25,17 +25,55 @@
|
|
|
25
25
|
|
|
26
26
|
* { box-sizing: border-box; }
|
|
27
27
|
|
|
28
|
-
/*
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
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 {
|
|
35
49
|
position: absolute;
|
|
36
50
|
left: -9999px;
|
|
51
|
+
top: 0;
|
|
52
|
+
z-index: 200; /* above .auth-screen (100) and the sidebar backdrop */
|
|
37
53
|
}
|
|
38
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
|
+
|
|
39
77
|
html, body {
|
|
40
78
|
margin: 0;
|
|
41
79
|
padding: 0;
|
package/template/schema.sql
CHANGED
|
@@ -298,6 +298,12 @@ 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);
|
|
301
307
|
-- 0004: CSP violation collector (fleet-chezmoi#1646).
|
|
302
308
|
--
|
|
303
309
|
-- Two tables, and the split is the point. `csp_report_buckets` is a rate-limit
|
|
@@ -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),
|
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