@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.
Files changed (40) hide show
  1. package/README.md +7 -4
  2. package/index.js +1 -0
  3. package/package.json +1 -1
  4. package/template/CONTRIBUTING.md +18 -3
  5. package/template/MIGRATIONS.md +52 -0
  6. package/template/README.md +50 -16
  7. package/template/docs/legal/INSTANCE-ACCEPTABLE-USE.md +5 -2
  8. package/template/docs/legal/INSTANCE-PRIVACY.md +127 -27
  9. package/template/migrations/0005_auth_attempts_retention.sql +23 -0
  10. package/template/package.json +6 -6
  11. package/template/public/app.js +19 -6
  12. package/template/public/index.html +23 -9
  13. package/template/public/styles.css +45 -7
  14. package/template/schema.sql +6 -0
  15. package/template/src/ai-binding.ts +125 -3
  16. package/template/src/auth.ts +6 -0
  17. package/template/src/env.ts +11 -0
  18. package/template/src/gateway-credentials.ts +118 -22
  19. package/template/src/index.ts +2 -0
  20. package/template/src/providers/anthropic.ts +4 -4
  21. package/template/src/providers/openai-image.ts +10 -0
  22. package/template/src/providers/xai.ts +4 -4
  23. package/template/src/rate-limit.ts +26 -0
  24. package/template/src/routes/chat.ts +5 -3
  25. package/template/src/routes/prefs.ts +46 -5
  26. package/template/src/routes/rag.ts +28 -12
  27. package/template/src/routes/shared.ts +22 -9
  28. package/template/src/routes/workflow.ts +2 -5
  29. package/template/src/user-prefs.ts +16 -3
  30. package/template/src/version.ts +1 -1
  31. package/template/tests/ai-binding-rest.test.ts +154 -0
  32. package/template/tests/csp.test.ts +11 -6
  33. package/template/tests/gateway-credentials.test.ts +101 -3
  34. package/template/tests/openai-image.test.ts +21 -1
  35. package/template/tests/rag-metadata-filter.test.ts +135 -0
  36. package/template/tests/skip-link.test.ts +164 -0
  37. package/template/tests/vectorize-backfill-metadata.test.ts +166 -0
  38. package/template/tests-integration/auth.test.ts +346 -2
  39. package/template/tests-integration/pdf-extract.test.ts +71 -0
  40. package/template/wrangler.example.toml +12 -2
@@ -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
- const baseUrl = await (ctx.env.AI as unknown as {
96
- gateway: (id: string) => { getUrl: (provider: string) => Promise<string> };
97
- }).gateway(ctx.gateway.gatewayId).getUrl("anthropic");
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
- const baseUrl = await (ctx.env.AI as unknown as {
42
- gateway: (id: string) => { getUrl: (provider: string) => Promise<string> };
43
- }).gateway(ctx.gateway.gatewayId).getUrl("grok");
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\//, "");
@@ -6,6 +6,20 @@
6
6
  // pure function so it is unit-testable without D1; the DB layer only does the
7
7
  // epoch conversion and the upsert.
8
8
 
9
+ // prism#192: how long a rate-limit bucket may survive its own window.
10
+ //
11
+ // Before this, rows were removed only by resetRateLimit on a SUCCESSFUL login,
12
+ // so a `signup:<ip>` bucket, or any `login:<ip>:<username>` bucket that never
13
+ // saw a success, lived in D1 forever. The hosted privacy notice heads that
14
+ // section "transient IP processing", and indefinite retention of failed-login
15
+ // IP-plus-username pairs is not transient.
16
+ //
17
+ // 24h is deliberately far beyond the longest live window (SIGNUP_WINDOW, 1h in
18
+ // src/auth.ts), so a prune can never discard a bucket a limiter decision still
19
+ // depends on: past its window rateLimitDecision already treats the row as a
20
+ // fresh start, making an aged row functionally dead weight.
21
+ export const AUTH_ATTEMPT_RETENTION_HOURS = 24;
22
+
9
23
  export interface RateLimitDecision {
10
24
  allowed: boolean;
11
25
  nextCount: number;
@@ -65,6 +79,18 @@ export async function checkRateLimit(
65
79
  .bind(bucketKey, decision.nextCount, decision.nextWindowStart)
66
80
  .run();
67
81
 
82
+ // Retention as an executed deletion, not an intention -- the csp_reports
83
+ // pattern (src/routes/csp-report.ts). Prune-on-write needs no cron, no new
84
+ // trigger and no binding, and it cannot drift out of sync with the write path
85
+ // because it IS the write path. That matters here specifically: the shipped
86
+ // wrangler.example.toml has `crons = []` and there is no scheduled handler,
87
+ // so anything cron-shaped would be retention that never actually runs, and a
88
+ // self-host would silently inherit indefinite retention.
89
+ await db
90
+ .prepare(`DELETE FROM auth_attempts WHERE window_start < datetime('now', ?)`)
91
+ .bind(`-${AUTH_ATTEMPT_RETENTION_HOURS} hours`)
92
+ .run();
93
+
68
94
  return decision.allowed;
69
95
  }
70
96
 
@@ -17,7 +17,7 @@ import { callXai, callXaiStream } from "../providers/xai";
17
17
  import { callWorkersAIStream } from "../providers/workers-ai";
18
18
  import { callOpenAI, callOpenAIStream } from "../providers/openai";
19
19
  import { callGemini, callGeminiStream } from "../providers/google";
20
- import { generateOpenAIImage } from "../providers/openai-image";
20
+ import { generateOpenAIImage, resolveOpenAIImageKey } from "../providers/openai-image";
21
21
  import { buildProxiedImageParams } from "../proxied-image-params";
22
22
  import {
23
23
  json,
@@ -566,14 +566,16 @@ export async function runImage(request: Request, env: Env, model: ModelEntry, bo
566
566
  // sole OpenAI transparent-PNG carve-out: when OPENAI_API_KEY is set on
567
567
  // openai/* image models, call api.openai.com directly (proxy rejects
568
568
  // background/output_format). No other provider uses a deployer key.
569
+ // Public mode ignores the key (prism#193, v1.0.5): see resolveOpenAIImageKey.
569
570
  //
570
571
  // Unified Billing response shapes:
571
572
  // URL: { state, result: { image: "https://..." } } or images[]
572
573
  // inline: { state, result: { image: "<b64|data-uri>" } } // xAI Grok Imagine
573
574
  // xAI requires response_format:b64_json (ZDR-managed credentials reject
574
575
  // URL output). extractProxiedImageAsset normalizes both.
575
- if (model.provider === "openai" && env.OPENAI_API_KEY) {
576
- const gen = await generateOpenAIImage(env.OPENAI_API_KEY, model.id, body.user_input);
576
+ const openaiImageKey = model.provider === "openai" ? resolveOpenAIImageKey(env) : null;
577
+ if (openaiImageKey) {
578
+ const gen = await generateOpenAIImage(openaiImageKey, model.id, body.user_input);
577
579
  bytes = gen.bytes;
578
580
  mime = gen.mime;
579
581
  logId = null; // direct OpenAI; no AI Gateway log
@@ -1,11 +1,16 @@
1
1
  // Per-user AI Gateway preference routes (GET/PATCH /api/prefs). Stores the
2
- // user gateway slug + Unified Billing token in D1 user_prefs; the token is
3
- // never echoed back raw (maskSecret). Optional control_plane_key (pcp_) for
2
+ // user's Cloudflare account id (v1.1.0), gateway slug, and Unified Billing
3
+ // token in D1 user_prefs; the token is never echoed back raw (maskSecret). Optional control_plane_key (pcp_) for
4
4
  // metered chat via allowlisted play-proxy (URL is never user-set).
5
5
 
6
6
  import type { Env } from "../env";
7
7
  import { loadUserPrefs, saveUserPrefs, type UserPrefsJson } from "../user-prefs";
8
- import { loadGatewayStatus, maskSecret } from "../gateway-credentials";
8
+ import {
9
+ isValidGatewayId,
10
+ loadGatewayStatus,
11
+ maskSecret,
12
+ normalizeAccountId,
13
+ } from "../gateway-credentials";
9
14
  import {
10
15
  DEFAULT_CONTROL_PLANE_URL,
11
16
  looksLikeClientKey,
@@ -29,6 +34,8 @@ export async function handlePrefsGet(request: Request, env: Env): Promise<Respon
29
34
  const prefs = await loadUserPrefs(env.DB, userEmail);
30
35
  const status = await loadGatewayStatus(env, userEmail);
31
36
  return json({
37
+ account_id: status.account_id,
38
+ account_id_required: status.account_id_required,
32
39
  gateway_id: status.gateway_id,
33
40
  cf_aig_token_set: status.cf_aig_token_set,
34
41
  cf_aig_token_preview: maskSecret(prefs?.cf_aig_token),
@@ -41,6 +48,7 @@ export async function handlePrefsGet(request: Request, env: Env): Promise<Respon
41
48
  export async function handlePrefsPatch(request: Request, env: Env): Promise<Response> {
42
49
  const userEmail = await getUserEmail(request, env);
43
50
  let body: {
51
+ account_id?: string;
44
52
  gateway_id?: string;
45
53
  cf_aig_token?: string;
46
54
  clear_cf_aig_token?: boolean;
@@ -54,7 +62,38 @@ export async function handlePrefsPatch(request: Request, env: Env): Promise<Resp
54
62
  }
55
63
 
56
64
  const patch: UserPrefsJson = {};
57
- if (body.gateway_id !== undefined) patch.gateway_id = body.gateway_id;
65
+ if (body.account_id !== undefined) {
66
+ if (typeof body.account_id !== "string") {
67
+ return json({ error: "account_id must be a string", code: "invalid_account_id" }, { status: 400 });
68
+ }
69
+ // Empty clears it; anything else must be a real account id, since it
70
+ // becomes a path segment in every request we send on the user's behalf.
71
+ if (body.account_id.trim() && !normalizeAccountId(body.account_id)) {
72
+ return json(
73
+ {
74
+ error: "account_id must be your 32-character Cloudflare account ID (hex), from the Cloudflare dashboard.",
75
+ code: "invalid_account_id",
76
+ },
77
+ { status: 400 },
78
+ );
79
+ }
80
+ patch.account_id = body.account_id;
81
+ }
82
+ if (body.gateway_id !== undefined) {
83
+ if (typeof body.gateway_id !== "string") {
84
+ return json({ error: "gateway_id must be a string", code: "invalid_gateway_id" }, { status: 400 });
85
+ }
86
+ if (body.gateway_id.trim() && !isValidGatewayId(body.gateway_id)) {
87
+ return json(
88
+ {
89
+ error: "gateway_id must be your AI Gateway slug: letters, digits, '-' or '_', up to 64 characters.",
90
+ code: "invalid_gateway_id",
91
+ },
92
+ { status: 400 },
93
+ );
94
+ }
95
+ patch.gateway_id = body.gateway_id;
96
+ }
58
97
  if (body.cf_aig_token !== undefined) patch.cf_aig_token = body.cf_aig_token;
59
98
  if (body.clear_cf_aig_token) patch.cf_aig_token = "";
60
99
  if (body.control_plane_key !== undefined) {
@@ -76,7 +115,7 @@ export async function handlePrefsPatch(request: Request, env: Env): Promise<Resp
76
115
  if (Object.keys(patch).length === 0) {
77
116
  return json(
78
117
  {
79
- error: "Provide gateway_id, cf_aig_token, and/or control_plane_key to update",
118
+ error: "Provide account_id, gateway_id, cf_aig_token, and/or control_plane_key to update",
80
119
  },
81
120
  { status: 400 },
82
121
  );
@@ -85,6 +124,8 @@ export async function handlePrefsPatch(request: Request, env: Env): Promise<Resp
85
124
  const merged = await saveUserPrefs(env.DB, userEmail, patch);
86
125
  const status = await loadGatewayStatus(env, userEmail);
87
126
  return json({
127
+ account_id: status.account_id,
128
+ account_id_required: status.account_id_required,
88
129
  gateway_id: status.gateway_id,
89
130
  cf_aig_token_set: status.cf_aig_token_set,
90
131
  cf_aig_token_preview: maskSecret(merged.cf_aig_token),
@@ -9,7 +9,7 @@ import { getDocumentProxy } from "unpdf";
9
9
  import * as XLSX from "xlsx";
10
10
  import type { Env } from "../env";
11
11
  import { aiRun, type AiContext } from "../ai-binding";
12
- import { loadGatewayCredentials, GATEWAY_NOT_CONFIGURED_MSG } from "../gateway-credentials";
12
+ import { requireGatewayCredentials } from "../gateway-credentials";
13
13
  import { chunkText } from "../chunking";
14
14
  import { searchSearxngWeb } from "../searxng";
15
15
  import { r2Put, r2DeleteSafe } from "./shared";
@@ -221,10 +221,7 @@ export async function extractChunks(bytes: Uint8Array, mime: string, filename: s
221
221
 
222
222
  export async function embedBatch(env: Env, userEmail: string, texts: string[]): Promise<number[][]> {
223
223
  if (texts.length === 0) return [];
224
- const gateway = await loadGatewayCredentials(env, userEmail);
225
- if (!gateway?.gatewayId) {
226
- throw new Error(GATEWAY_NOT_CONFIGURED_MSG);
227
- }
224
+ const gateway = await requireGatewayCredentials(env, userEmail);
228
225
  const aiCtx: AiContext = { env, gateway };
229
226
  const result = await aiRun(aiCtx, EMBED_MODEL, { text: texts }) as {
230
227
  shape?: [number, number];
@@ -239,13 +236,26 @@ export async function embedBatch(env: Env, userEmail: string, texts: string[]):
239
236
  // ---------- RAG: retrieval (Pass 2) ----------
240
237
  //
241
238
  // Embeds the user prompt, queries Vectorize for the top-K nearest chunks,
242
- // then looks up source text in D1. We filter by user_email in the D1 JOIN
243
- // (not in the Vectorize filter param) so this works without a metadata
244
- // index on the Vectorize side - simpler for single-user deployments.
245
- // Vectorize score ordering is preserved.
239
+ // then looks up source text in D1. Tenant scope is the user_email filter in
240
+ // the D1 JOIN, always. Vectorize score ordering is preserved.
241
+ //
242
+ // With VEC_METADATA_FILTER on (fleet-chezmoi#1636), the Vectorize query is
243
+ // ALSO filtered on user_email, so the top-K is drawn from the caller's own
244
+ // vectors. Without it the query is global, and a caller with a small share of
245
+ // a large index can get a top-K made entirely of other users' vectors, which
246
+ // the D1 join then drops: zero results even when their own documents match.
247
+ // The flag needs a user_email metadata index plus a re-upsert of existing
248
+ // vectors first (scripts/vectorize-backfill-metadata.mjs), so it defaults off
249
+ // and a deployment that has not done both keeps the global query.
246
250
 
247
251
  export const RETRIEVE_TOP_K = 5;
248
252
 
253
+ /** VEC_METADATA_FILTER is on only for an explicit "on" / "1" / "true" (fleet-chezmoi#1636). */
254
+ export function vecMetadataFilterOn(env: Pick<Env, "VEC_METADATA_FILTER">): boolean {
255
+ const v = (env.VEC_METADATA_FILTER ?? "").trim().toLowerCase();
256
+ return v === "on" || v === "1" || v === "true";
257
+ }
258
+
249
259
  export async function retrieveContext(
250
260
  env: Env,
251
261
  userEmail: string,
@@ -273,8 +283,9 @@ export async function retrieveContext(
273
283
  return { chunks: [], error: `embed failed: ${m}` };
274
284
  }
275
285
 
276
- // 2) Query Vectorize. No metadata filter - we scope by user in D1 below.
277
- // When projectId is set, we overfetch (3x topK) at the Vectorize stage
286
+ // 2) Query Vectorize. Filtered on user_email when VEC_METADATA_FILTER is on;
287
+ // global otherwise. Either way the D1 join below is the tenant scope and
288
+ // stays, as the second layer. When projectId is set, we overfetch (3x topK) at the Vectorize stage
278
289
  // and filter by project membership in D1, since Vectorize doesn't know
279
290
  // about project membership. Without overfetch, a small topK that all
280
291
  // misses the project would return zero results even when the project
@@ -282,7 +293,12 @@ export async function retrieveContext(
282
293
  const vectorizeTopK = projectId !== undefined ? topK * 3 : topK;
283
294
  let matches: { id: string; score: number }[];
284
295
  try {
285
- const q = await env.VEC.query(queryVec, { topK: vectorizeTopK });
296
+ const q = await env.VEC.query(
297
+ queryVec,
298
+ vecMetadataFilterOn(env)
299
+ ? { topK: vectorizeTopK, filter: { user_email: userEmail } }
300
+ : { topK: vectorizeTopK },
301
+ );
286
302
  matches = (q?.matches ?? []).map((m) => ({ id: m.id, score: m.score }));
287
303
  } catch (err) {
288
304
  const m = err instanceof Error ? err.message : String(err);
@@ -11,15 +11,15 @@ import type { InputAttachment } from "../types";
11
11
  import { extFromMime, bytesToBase64 } from "../utils";
12
12
  import { type AiContext } from "../ai-binding";
13
13
  import {
14
- loadGatewayCredentials,
15
- GATEWAY_NOT_CONFIGURED_MSG,
14
+ resolveGateway,
15
+ gatewayProblemMessage,
16
16
  CF_AIG_TOKEN_REQUIRED_MSG,
17
17
  } from "../gateway-credentials";
18
18
  import {
19
19
  resolveControlPlane,
20
20
  type ControlPlaneCredentials,
21
21
  } from "../control-plane";
22
- import { loadUserPrefs } from "../user-prefs";
22
+ import { loadUserPrefs, type UserPrefsJson } from "../user-prefs";
23
23
  import { resolveIdentity } from "../auth";
24
24
 
25
25
  // ---------- Types ----------
@@ -139,14 +139,27 @@ export async function requireAiContext(
139
139
  userEmail: string,
140
140
  opts?: { requireCfToken?: boolean },
141
141
  ): Promise<AiContext | Response> {
142
- const gateway = await loadGatewayCredentials(env, userEmail);
143
- if (!gateway?.gatewayId) {
144
- return json({ error: GATEWAY_NOT_CONFIGURED_MSG, code: "gateway_not_configured" }, { status: 412 });
142
+ const prefs = await loadUserPrefs(env.DB, userEmail);
143
+ return aiContextFromPrefs(prefs, env, opts);
144
+ }
145
+
146
+ // v1.1.0: every refusal carries its own code so the SPA can say what is
147
+ // missing. gateway_account_id_required is the pre-v1.1.0 shape (slug + token,
148
+ // no account id) in public mode: refused, never resolved on our binding.
149
+ export function aiContextFromPrefs(
150
+ prefs: UserPrefsJson | null,
151
+ env: Env,
152
+ opts?: { requireCfToken?: boolean },
153
+ ): AiContext | Response {
154
+ const { creds, problem } = resolveGateway(prefs, env);
155
+ if (!creds) {
156
+ const code = problem ?? "gateway_not_configured";
157
+ return json({ error: gatewayProblemMessage(code), code }, { status: 412 });
145
158
  }
146
- if (opts?.requireCfToken && !gateway.cfAigToken) {
159
+ if (opts?.requireCfToken && !creds.cfAigToken) {
147
160
  return json({ error: CF_AIG_TOKEN_REQUIRED_MSG, code: "cf_aig_token_required" }, { status: 412 });
148
161
  }
149
- return { env, gateway };
162
+ return { env, gateway: creds };
150
163
  }
151
164
 
152
165
  /**
@@ -168,7 +181,7 @@ export async function requireInferenceBackend(
168
181
  const cp = resolveControlPlane(prefs, env);
169
182
  if (cp) return { kind: "control_plane", cp };
170
183
 
171
- const gatewayOrErr = await requireAiContext(env, userEmail, opts);
184
+ const gatewayOrErr = aiContextFromPrefs(prefs, env, opts);
172
185
  if (gatewayOrErr instanceof Response) return gatewayOrErr;
173
186
  return { kind: "gateway", ctx: gatewayOrErr };
174
187
  }
@@ -9,7 +9,7 @@ import { WorkflowEntrypoint, WorkflowStep } from "cloudflare:workers";
9
9
  import type { WorkflowEvent } from "cloudflare:workers";
10
10
  import type { Env } from "../env";
11
11
  import { aiRun, type AiContext } from "../ai-binding";
12
- import { loadGatewayCredentials, GATEWAY_NOT_CONFIGURED_MSG } from "../gateway-credentials";
12
+ import { requireGatewayCredentials } from "../gateway-credentials";
13
13
  import { buildGenParams } from "../longrun-params";
14
14
  import { unzip } from "../zip";
15
15
  import { r2Put, r2KeyToDataUri, r2DeleteSafe } from "./shared";
@@ -231,10 +231,7 @@ export class LongRunWorkflow extends WorkflowEntrypoint<Env, LongRunParams> {
231
231
  : imageUrl;
232
232
  const params = buildGenParams(kind, { modelId, prompt, lyrics, imageUrl: resolvedImage });
233
233
 
234
- const gateway = await loadGatewayCredentials(this.env, userEmail);
235
- if (!gateway?.gatewayId) {
236
- throw new Error(GATEWAY_NOT_CONFIGURED_MSG);
237
- }
234
+ const gateway = await requireGatewayCredentials(this.env, userEmail);
238
235
  const aiCtx: AiContext = { env: this.env, gateway };
239
236
  const result = await aiRun(aiCtx, modelId, params) as LongRunResult;
240
237
 
@@ -1,10 +1,16 @@
1
1
  // Per-user preferences stored in D1 (v0.164.0).
2
2
  //
3
- // JSON blob keyed by Cloudflare Access email. Gateway fields are the first
4
- // use case for a public demo deployment where each visitor brings their own
5
- // AI Gateway slug and CF_AIG_TOKEN.
3
+ // JSON blob keyed by the caller's identity (Access email or public account
4
+ // id). Gateway fields are the first use case for a public demo deployment
5
+ // where each visitor brings their own AI Gateway.
6
+ //
7
+ // v1.1.0: account_id added. Being a key in the JSON blob, it needs no DDL;
8
+ // pre-v1.1.0 rows simply lack it and resolve as "account id required" in
9
+ // public mode (see resolveGateway in gateway-credentials.ts).
6
10
 
7
11
  export interface UserPrefsJson {
12
+ /** v1.1.0: Cloudflare account id (32 hex) that owns gateway_id. */
13
+ account_id?: string;
8
14
  gateway_id?: string;
9
15
  cf_aig_token?: string;
10
16
  /**
@@ -43,6 +49,13 @@ export async function saveUserPrefs(
43
49
  const existing = (await loadUserPrefs(db, userEmail)) ?? {};
44
50
  const merged: UserPrefsJson = { ...existing };
45
51
 
52
+ if (patch.account_id !== undefined) {
53
+ // Callers validate before saving; stored lowercase so comparisons and
54
+ // the URL builder see one canonical form.
55
+ const trimmed = patch.account_id.trim().toLowerCase();
56
+ if (trimmed) merged.account_id = trimmed;
57
+ else delete merged.account_id;
58
+ }
46
59
  if (patch.gateway_id !== undefined) {
47
60
  const trimmed = patch.gateway_id.trim();
48
61
  if (trimmed) merged.gateway_id = trimmed;
@@ -15,4 +15,4 @@
15
15
  // That distinction is the entire point. In prism-mcp the advertised version was a literal and
16
16
  // the test asserting it carried a TRANSCRIBED duplicate, so the assertion only ever proved
17
17
  // that someone had typed the same thing twice, and a correct version bump went red.
18
- export const VERSION = "1.0.4";
18
+ export const VERSION = "1.2.0";
@@ -0,0 +1,154 @@
1
+ // Unit tests for the account-scoped transport in src/ai-binding.ts (v1.1.0).
2
+ //
3
+ // The AI binding is pinned to the worker's own Cloudflare account, so a user's
4
+ // gateway is only reachable over HTTP. These pin the request each transport
5
+ // builds and prove an account-scoped context never touches the binding.
6
+
7
+ import { afterEach, describe, expect, it, vi } from "vitest";
8
+ import {
9
+ aiLogId,
10
+ aiRun,
11
+ buildRestRunRequest,
12
+ gatewayProviderUrl,
13
+ unwrapRestResponse,
14
+ type AiContext,
15
+ } from "../src/ai-binding";
16
+ import type { Env } from "../src/env";
17
+
18
+ const ACCT = "0123456789abcdef0123456789abcdef";
19
+
20
+ // A binding that fails the test if anything reaches it.
21
+ function trapBinding(): Env["AI"] {
22
+ const trap = () => { throw new Error("host AI binding was called"); };
23
+ return { run: trap, gateway: trap, aiGatewayLogId: "host-log" } as unknown as Env["AI"];
24
+ }
25
+
26
+ function userCtx(): AiContext {
27
+ return {
28
+ env: { AI: trapBinding() } as Env,
29
+ gateway: { gatewayId: "user-gw", cfAigToken: "user-token", accountId: ACCT },
30
+ };
31
+ }
32
+
33
+ afterEach(() => { vi.unstubAllGlobals(); });
34
+
35
+ describe("buildRestRunRequest", () => {
36
+ it("partner models use the /ai/run envelope on the user's account", () => {
37
+ const { url, init } = buildRestRunRequest(ACCT, userCtx().gateway, "openai/gpt-5.5", { messages: [] });
38
+ expect(url).toBe(`https://api.cloudflare.com/client/v4/accounts/${ACCT}/ai/run`);
39
+ const h = init.headers as Record<string, string>;
40
+ expect(h.authorization).toBe("Bearer user-token");
41
+ expect(h["cf-aig-gateway-id"]).toBe("user-gw");
42
+ expect(JSON.parse(init.body as string)).toEqual({ model: "openai/gpt-5.5", input: { messages: [] } });
43
+ });
44
+
45
+ it("Workers AI models use the model-in-path endpoint with bare params", () => {
46
+ const { url, init } = buildRestRunRequest(ACCT, userCtx().gateway, "@cf/baai/bge-base-en-v1.5", { text: ["a"] });
47
+ expect(url).toBe(`https://api.cloudflare.com/client/v4/accounts/${ACCT}/ai/run/@cf/baai/bge-base-en-v1.5`);
48
+ expect(JSON.parse(init.body as string)).toEqual({ text: ["a"] });
49
+ });
50
+ });
51
+
52
+ describe("aiRun transport selection", () => {
53
+ it("account-scoped: fetches the user's account and never touches the binding", async () => {
54
+ const fetchMock = vi.fn(async () => new Response(
55
+ JSON.stringify({ success: true, result: { response: "hi" }, errors: [] }),
56
+ { headers: { "content-type": "application/json", "cf-aig-log-id": "user-log" } },
57
+ ));
58
+ vi.stubGlobal("fetch", fetchMock);
59
+ const ctx = userCtx();
60
+ const out = await aiRun(ctx, "openai/gpt-5.5", { messages: [] });
61
+ expect(out).toEqual({ response: "hi" });
62
+ expect(fetchMock).toHaveBeenCalledTimes(1);
63
+ expect(aiLogId(ctx)).toBe("user-log");
64
+ });
65
+
66
+ it("account-scoped aiLogId never reads the host binding's log id", () => {
67
+ expect(aiLogId(userCtx())).toBeNull();
68
+ });
69
+
70
+ it("host context (accountId null) still uses the binding with the gateway id", async () => {
71
+ const run = vi.fn(async () => ({ ok: 1 }));
72
+ const ctx: AiContext = {
73
+ env: { AI: { run } } as unknown as Env,
74
+ gateway: { gatewayId: "host-gw", cfAigToken: "", accountId: null },
75
+ };
76
+ await aiRun(ctx, "@cf/x/y", { a: 1 });
77
+ expect(run).toHaveBeenCalledWith("@cf/x/y", { a: 1 }, { gateway: { id: "host-gw" } });
78
+ });
79
+ });
80
+
81
+ describe("gatewayProviderUrl", () => {
82
+ it("builds the provider-native URL from the user's account", async () => {
83
+ expect(await gatewayProviderUrl(userCtx(), "anthropic"))
84
+ .toBe(`https://gateway.ai.cloudflare.com/v1/${ACCT}/user-gw/anthropic`);
85
+ });
86
+
87
+ it("encodes a hostile stored slug rather than letting it rewrite the path", async () => {
88
+ const ctx = userCtx();
89
+ ctx.gateway.gatewayId = "../evil";
90
+ expect(await gatewayProviderUrl(ctx, "grok"))
91
+ .toBe(`https://gateway.ai.cloudflare.com/v1/${ACCT}/..%2Fevil/grok`);
92
+ });
93
+
94
+ it("host context delegates to the binding's getUrl", async () => {
95
+ const getUrl = vi.fn(async (p: string) => `https://gateway.ai.cloudflare.com/v1/host/host-gw/${p}`);
96
+ const ctx: AiContext = {
97
+ env: { AI: { gateway: () => ({ getUrl }) } } as unknown as Env,
98
+ gateway: { gatewayId: "host-gw", cfAigToken: "t", accountId: null },
99
+ };
100
+ expect(await gatewayProviderUrl(ctx, "anthropic")).toContain("/host/host-gw/anthropic");
101
+ });
102
+ });
103
+
104
+ describe("unwrapRestResponse", () => {
105
+ it("unwraps the Cloudflare API envelope", async () => {
106
+ const r = new Response(JSON.stringify({ success: true, result: { data: [[1]] } }), {
107
+ headers: { "content-type": "application/json" },
108
+ });
109
+ expect(await unwrapRestResponse(r, ACCT, false)).toEqual({ data: [[1]] });
110
+ });
111
+
112
+ it("passes non-envelope JSON through untouched", async () => {
113
+ const r = new Response(JSON.stringify({ type: "message", content: [] }), {
114
+ headers: { "content-type": "application/json" },
115
+ });
116
+ expect(await unwrapRestResponse(r, ACCT, false)).toEqual({ type: "message", content: [] });
117
+ });
118
+
119
+ it("throws on success:false with the API's message", async () => {
120
+ const r = new Response(JSON.stringify({ success: false, errors: [{ message: "no credits" }] }), {
121
+ headers: { "content-type": "application/json" },
122
+ });
123
+ await expect(unwrapRestResponse(r, ACCT, false)).rejects.toThrow(/no credits/);
124
+ });
125
+
126
+ it("a 401 names the permissions and the account, so the failure is actionable", async () => {
127
+ const r = new Response(JSON.stringify({ success: false, errors: [{ code: 10000, message: "Authentication error" }] }), {
128
+ status: 401,
129
+ headers: { "content-type": "application/json" },
130
+ });
131
+ await expect(unwrapRestResponse(r, ACCT, false))
132
+ .rejects.toThrow(new RegExp(`401: 10000 Authentication error.*Workers AI Read.*${ACCT}`));
133
+ });
134
+
135
+ it("returns the body stream for SSE", async () => {
136
+ const r = new Response("data: {}\n\n", { headers: { "content-type": "text/event-stream" } });
137
+ expect(await unwrapRestResponse(r, ACCT, false)).toBeInstanceOf(ReadableStream);
138
+ });
139
+
140
+ it("raw mode returns binary responses as-is", async () => {
141
+ const r = new Response(new Uint8Array([1, 2]), { headers: { "content-type": "audio/mpeg" } });
142
+ const out = await unwrapRestResponse(r, ACCT, true) as Response;
143
+ expect(new Uint8Array(await out.arrayBuffer())).toEqual(new Uint8Array([1, 2]));
144
+ });
145
+
146
+ it("raw mode turns a JSON { audio: base64 } result into audio bytes", async () => {
147
+ const r = new Response(JSON.stringify({ success: true, result: { audio: "AQI=" } }), {
148
+ headers: { "content-type": "application/json" },
149
+ });
150
+ const out = await unwrapRestResponse(r, ACCT, true) as Response;
151
+ expect(out.headers.get("content-type")).toBe("audio/mpeg");
152
+ expect(new Uint8Array(await out.arrayBuffer())).toEqual(new Uint8Array([1, 2]));
153
+ });
154
+ });
@@ -372,9 +372,12 @@ describe("the served documents carry no inline CSS", () => {
372
372
  });
373
373
 
374
374
  // index.html:47 was the collector's first genuine finding:
375
- // style-src-attr | inline | line 47. The offscreen positioning moved to
376
- // the `.seo-skip` rule in styles.css; the element and its behaviour are
377
- // unchanged, and it is still the first focusable element in the body.
375
+ // style-src-attr | inline | line 47. The offscreen positioning moved to a
376
+ // stylesheet rule, where it stays. fc#1700 then renamed that rule from
377
+ // `.seo-skip` to `.skip-link` and gave it the `:focus` reveal it never had;
378
+ // the CSP invariant asserted here is unchanged by that, and the element is
379
+ // still the first focusable element in the body. The accessibility half is
380
+ // asserted in tests/skip-link.test.ts, not here.
378
381
  it("index.html has no inline style attribute", () => {
379
382
  expect(INLINE_STYLE_ATTR.test(pub("index.html"))).toBe(false);
380
383
  });
@@ -405,9 +408,11 @@ describe("the served documents carry no inline CSS", () => {
405
408
 
406
409
  it("the offscreen positioning the skip link lost is present in styles.css", () => {
407
410
  const css = pub("styles.css");
408
- expect(css).toMatch(/\.seo-skip\s*\{[^}]*position:\s*absolute/);
409
- expect(css).toMatch(/\.seo-skip\s*\{[^}]*left:\s*-9999px/);
410
- expect(pub("index.html")).toContain('class="seo-skip"');
411
+ expect(css).toMatch(/\.skip-link\s*\{[^}]*position:\s*absolute/);
412
+ expect(css).toMatch(/\.skip-link\s*\{[^}]*left:\s*-9999px/);
413
+ expect(pub("index.html")).toContain('class="skip-link"');
414
+ // No inline style attribute crept back onto the element itself.
415
+ expect(pub("index.html")).not.toMatch(/<a class="skip-link"[^>]*\sstyle\s*=/);
411
416
  });
412
417
  });
413
418