@skyphusion/create-prism 1.3.0 → 1.4.1

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.
@@ -6,7 +6,7 @@
6
6
 
7
7
  import type { Env } from "../env";
8
8
  import type { ModelType, ModelEntry } from "../models";
9
- import { MODELS } from "../models";
9
+ import { MODELS, OPENAI_COMPAT_CHAT_PROVIDERS } from "../models";
10
10
  import type { InputAttachment } from "../types";
11
11
  import type { ProviderStreamEvent } from "../parsers/types";
12
12
  import { parseDataUrl, base64ToBytes } from "../utils";
@@ -177,14 +177,15 @@ export async function handleChatStream(request: Request, env: Env, ctx: Executio
177
177
  // Anthropic + Workers AI + xAI + OpenAI + Google + Moonshot. Workers AI
178
178
  // catalog entries omit `provider` (default "workers-ai"); Unified Billing
179
179
  // providers set it explicitly. Keep this allowlist in lockstep with the
180
- // stream dispatch switch in runChatStream (v0.171.0: moonshotai).
180
+ // stream dispatch switch in runChatStream (v0.171.0: moonshotai; 2026-12 refresh:
181
+ // every OPENAI_COMPAT_CHAT_PROVIDERS member).
181
182
  const isWorkersAI = !model.provider;
182
183
  if (
183
184
  model.provider !== "anthropic" &&
184
185
  model.provider !== "xai" &&
185
186
  model.provider !== "openai" &&
186
187
  model.provider !== "google" &&
187
- model.provider !== "moonshotai" &&
188
+ !(model.provider && OPENAI_COMPAT_CHAT_PROVIDERS.has(model.provider)) &&
188
189
  !isWorkersAI
189
190
  ) {
190
191
  return json({ error: `Streaming for provider '${model.provider}' is not yet implemented.` }, { status: 501 });
@@ -456,7 +457,8 @@ export async function runChat(request: Request, env: Env, model: ModelEntry, bod
456
457
  result = r.raw;
457
458
  logId = r.logId;
458
459
  } else {
459
- // Workers AI hosted chat (and moonshotai Chat Completions via env.AI.run).
460
+ // Workers AI hosted chat, and OPENAI_COMPAT_CHAT_PROVIDERS Chat
461
+ // Completions via env.AI.run.
460
462
  result = await aiRun(aiCtx, model.id, { messages });
461
463
  logId = aiLogId(aiCtx);
462
464
  }
@@ -617,20 +619,17 @@ export async function runImage(request: Request, env: Env, model: ModelEntry, bo
617
619
  // The matrix:
618
620
  // FLUX-1 schnell, Lucid Origin - JSON in, JSON out (base64). Gateway path works.
619
621
  // FLUX-2 (Klein 9b/4b, Dev) - multipart in, JSON out (base64). Gateway can't proxy stream input.
620
- // Phoenix 1.0, Dreamshaper 8 LCM - JSON in, ReadableStream out. Gateway can't proxy stream output.
622
+ // Phoenix 1.0 - JSON in, ReadableStream out. Gateway can't proxy stream output.
621
623
  //
622
- // Solution: bypass the AI Gateway for the five problematic models by
624
+ // Solution: bypass the AI Gateway for the four problematic models by
623
625
  // calling env.AI.run directly without the gateway option, and detect
624
626
  // the response shape at runtime so we can drain a ReadableStream into
625
627
  // bytes or extract base64 from JSON as appropriate. Cost: no AI Gateway
626
628
  // observability/caching for these specific models (ai_gateway_log_id
627
629
  // stays null on the persisted row).
628
630
  const isFlux2 = model.id.startsWith("@cf/black-forest-labs/flux-2-");
629
- const isSdxl = model.id === "@cf/stabilityai/stable-diffusion-xl-base-1.0";
630
631
  const bypassGateway = isFlux2
631
- || model.id === "@cf/leonardo/phoenix-1.0"
632
- || model.id === "@cf/lykon/dreamshaper-8-lcm"
633
- || isSdxl; // SDXL returns a ReadableStream image; gateway can't proxy it
632
+ || model.id === "@cf/leonardo/phoenix-1.0";
634
633
 
635
634
  let runParams: unknown;
636
635
 
@@ -688,12 +687,6 @@ export async function runImage(request: Request, env: Env, model: ModelEntry, bo
688
687
  params.steps = 4;
689
688
  delete params.negative_prompt;
690
689
  }
691
- // SDXL's step field is `num_steps` (max 20), not `steps`; swap to avoid
692
- // sending an unknown/over-max field.
693
- if (isSdxl) {
694
- delete params.steps;
695
- params.num_steps = 20;
696
- }
697
690
  runParams = params;
698
691
  }
699
692
 
@@ -716,7 +709,7 @@ export async function runImage(request: Request, env: Env, model: ModelEntry, bo
716
709
 
717
710
  // Two response shapes are possible:
718
711
  // 1. JSON { image: "base64..." } - FLUX-1, FLUX-2, Lucid Origin
719
- // 2. ReadableStream of raw PNG bytes - Phoenix, Dreamshaper
712
+ // 2. ReadableStream of raw PNG bytes - Phoenix
720
713
  // Detect at runtime rather than mapping per-model; safer if Cloudflare
721
714
  // shifts a model from one shape to the other.
722
715
  if (result instanceof ReadableStream) {
@@ -737,9 +730,7 @@ export async function runImage(request: Request, env: Env, model: ModelEntry, bo
737
730
  bytes.set(c, offset);
738
731
  offset += c.length;
739
732
  }
740
- // All stream-output image models here emit PNG bytes. (The SDXL docs
741
- // claim image/jpg, but the binding's actual output is PNG, confirmed
742
- // live, so we don't special-case it.)
733
+ // All stream-output image models here emit PNG bytes.
743
734
  mime = "image/png";
744
735
  } else {
745
736
  const b64 = (result as { image?: string })?.image;
@@ -1441,9 +1432,10 @@ export async function runChatStream(request: Request, env: Env, model: ModelEntr
1441
1432
  streamGenerator = callAnthropicStream(aiCtx, model, effectiveSystemPrompt || undefined, messages, upstreamAbort.signal);
1442
1433
  } else if (model.provider === "xai") {
1443
1434
  streamGenerator = callXaiStream(aiCtx, model, messages, upstreamAbort.signal);
1444
- } else if (model.provider === "openai" || model.provider === "moonshotai") {
1445
- // OpenAI + Moonshot K3 (v0.171.0): both are Chat Completions over
1446
- // env.AI.run with OpenAI-compatible SSE.
1435
+ } else if (model.provider === "openai" || (model.provider && OPENAI_COMPAT_CHAT_PROVIDERS.has(model.provider))) {
1436
+ // OpenAI + the Chat Completions Unified Billing providers (Moonshot
1437
+ // v0.171.0; Alibaba, DeepSeek, MiniMax 2026-12 refresh): env.AI.run with
1438
+ // OpenAI-compatible SSE.
1447
1439
  streamGenerator = callOpenAIStream(aiCtx, model, messages, upstreamAbort.signal);
1448
1440
  } else if (model.provider === "google") {
1449
1441
  streamGenerator = callGeminiStream(aiCtx, model, effectiveSystemPrompt || undefined, messages, upstreamAbort.signal);
@@ -33,7 +33,9 @@ import {
33
33
  } from "../conversation-context";
34
34
 
35
35
  /** Default cheap Workers AI chat model for compact when the client omits model. */
36
- export const DEFAULT_COMPACT_MODEL = "@cf/meta/llama-3.2-3b-instruct";
36
+ // 2026-12 refresh: was @cf/meta/llama-3.2-3b-instruct, which Cloudflare retired on
37
+ // 2026-11-20 (HTTP 410, error 5028). Gemma 4 is CF's recommended small model.
38
+ export const DEFAULT_COMPACT_MODEL = "@cf/google/gemma-4-26b-a4b-it";
37
39
 
38
40
  export async function loadCompactState(
39
41
  env: Env,
@@ -8,6 +8,7 @@ import { parseDiscordExport, chunkDiscordMessages } from "../discord";
8
8
  import { json, getUserEmail, r2Put, r2DeleteSafe } from "./shared";
9
9
  import type { ChatRequest } from "./shared";
10
10
  import { embedBatch, DOC_MAX_BYTES, EMBED_BATCH_SIZE } from "./rag";
11
+ import { mintVectorId } from "../vector-id";
11
12
 
12
13
  // v0.20.0: project + project_documents join. A project groups documents
13
14
  // (and in v0.20.1, conversations) under a shared system_prompt and
@@ -121,7 +122,7 @@ export async function resolveProjectForChat(
121
122
  .first<ProjectRow>();
122
123
  if (!project) {
123
124
  console.warn(
124
- `Chat referenced unknown project_id=${body.project_id} for user_email='${userEmail}'; ` +
125
+ `Chat referenced unknown project_id=${body.project_id} (not found for this caller); ` +
125
126
  `falling back to no-project semantics (no system prompt fallback, no retrieval scoping).`
126
127
  );
127
128
  } else {
@@ -483,8 +484,8 @@ export async function handleDiscordImport(request: Request, env: Env, projectId:
483
484
  await env.DB.batch(stmts);
484
485
  }
485
486
 
486
- // Embed chunks and upsert to Vectorize. vector_id scheme matches documents:
487
- // `${userEmail}:${docId}:${chunkIndex}`.
487
+ // Embed chunks and upsert to Vectorize. Vector ids are random and carry no
488
+ // identity, the same as documents (src/vector-id.ts, prism#232).
488
489
  const vectorIdsWritten: string[] = [];
489
490
  const chunkRowsToInsert: {
490
491
  chunk_index: number;
@@ -505,7 +506,7 @@ export async function handleDiscordImport(request: Request, env: Env, projectId:
505
506
  }
506
507
  const payload = batch.map((c, i) => {
507
508
  const idx = b + i;
508
- const vid = `${userEmail}:${docId}:${idx}`;
509
+ const vid = mintVectorId();
509
510
  chunkRowsToInsert.push({
510
511
  chunk_index: idx,
511
512
  text: c.text,
@@ -13,6 +13,7 @@ import { requireGatewayCredentials } from "../gateway-credentials";
13
13
  import { chunkText } from "../chunking";
14
14
  import { askSkyphusionSearch } from "../skyphusion-search";
15
15
  import { r2Put, r2DeleteSafe } from "./shared";
16
+ import { mintVectorId } from "../vector-id";
16
17
  import type { RetrievedChunk, RetrievedWebResult } from "./shared";
17
18
 
18
19
  // ---------- RAG: document ingestion (Pass 1) ----------
@@ -255,6 +256,26 @@ export function vecMetadataFilterOn(env: Pick<Env, "VEC_METADATA_FILTER">): bool
255
256
  return v === "on" || v === "1" || v === "true";
256
257
  }
257
258
 
259
+ // Ownership census for the zero-join diagnostic (prism#233). Returns a log
260
+ // fragment of counts only: no identity and no vector id ever leaves here.
261
+ async function zeroJoinCensus(env: Env, userEmail: string, ids: string[]): Promise<string> {
262
+ try {
263
+ const placeholders = ids.map(() => "?").join(",");
264
+ const row = await env.DB.prepare(
265
+ `SELECT COUNT(*) AS held, COALESCE(SUM(user_email = ?), 0) AS own
266
+ FROM chunks WHERE vector_id IN (${placeholders})`
267
+ )
268
+ .bind(userEmail, ...ids)
269
+ .first<{ held: number; own: number }>();
270
+ if (!row) return "census=unavailable";
271
+ const held = Number(row.held) || 0;
272
+ const own = Number(row.own) || 0;
273
+ return `held_by_caller=${own} held_by_other_users=${held - own} not_in_d1=${Math.max(0, ids.length - held)}`;
274
+ } catch {
275
+ return "census=unavailable";
276
+ }
277
+ }
278
+
258
279
  export async function retrieveContext(
259
280
  env: Env,
260
281
  userEmail: string,
@@ -357,21 +378,23 @@ export async function retrieveContext(
357
378
  // documents are members of the requested project.
358
379
  // Two messages, deliberately carrying different things.
359
380
  //
360
- // The Vectorize query above is global: it has no metadata filter, because
361
- // the tenant scope is the D1 join (see the note at the top of this
362
- // section, which is why this works without a Vectorize metadata index).
363
- // So `ids` holds whatever the shared index returned, and vector ids are
364
- // minted as `${userEmail}:${docId}:${chunkIndex}`. On a deployment with
365
- // more than one tenant, ids in that list can belong to somebody else --
366
- // which is precisely the case this branch exists to report on.
367
- //
368
- // The operator diagnostic keeps them. It is what makes a silent retrieval
369
- // failure debuggable, and it goes to a log the operator already owns.
370
- const idSample = ids.slice(0, 3).join(", ");
371
- const scope = projectId !== undefined ? ` project_id=${projectId},` : "";
381
+ // OPERATOR LOG (prism#233): counts and opaque row ids only, never an
382
+ // identity. The Vectorize query can be global (VEC_METADATA_FILTER off),
383
+ // so the matched ids can belong to other users, and pre-prism#232 ids
384
+ // embed an email. Neither the ids nor the caller's identity are logged.
385
+ // An unkeyed hash of an email is not a substitute: it can be reversed by
386
+ // hashing candidate addresses. The census below answers the question the
387
+ // old log was for ("were these vectors written under another identity?")
388
+ // with counts: how many matched ids D1 holds for this caller, for other
389
+ // users, and not at all.
390
+ const census = await zeroJoinCensus(env, userEmail, ids);
391
+ const scope = projectId !== undefined ? ` project_id=${projectId}` : "";
372
392
  console.warn(
373
393
  "retrieveContext:",
374
- `Vectorize returned ${matches.length} matches but D1 join returned 0. user_email='${userEmail}',${scope} sample vector_ids=[${idSample}]. Check whether vectors were upserted under a different user identity, or whether the project has any document members.`,
394
+ `zero-join matches=${matches.length}${scope} ${census}. ` +
395
+ "held_by_other_users > 0: vectors were written under a different identity. " +
396
+ "held_by_caller > 0 with a project: the matched documents are not members of the project. " +
397
+ "not_in_d1 > 0: vectors with no D1 chunk row.",
375
398
  );
376
399
 
377
400
  // The caller gets a true statement about their own retrieval and nothing
@@ -660,7 +683,7 @@ export async function ingestDocument(env: Env, userEmail: string, filename: stri
660
683
  // Store raw bytes in R2 for audit / future re-processing.
661
684
  const r2Key = await r2Put(env, "in", mime, bytes, userEmail);
662
685
 
663
- // Insert document row first so we have its ID for vector_id generation.
686
+ // Insert document row first so we have its ID for the chunk metadata.
664
687
  const docInsert = await env.DB.prepare(
665
688
  `INSERT INTO documents
666
689
  (user_email, filename, mime, r2_key, size_bytes, total_chars, chunk_count)
@@ -677,7 +700,7 @@ export async function ingestDocument(env: Env, userEmail: string, filename: stri
677
700
 
678
701
  // Embed in batches and upsert to Vectorize. We tag every vector with
679
702
  // user_email + document_id so we can filter on retrieval and clean up on delete.
680
- // Vector IDs are scoped: `${userEmail}:${docId}:${chunkIndex}`.
703
+ // Vector ids are random and carry no identity (src/vector-id.ts, prism#232).
681
704
  const vectorIdsWritten: string[] = [];
682
705
  const chunkRowsToInsert: {
683
706
  chunk_index: number;
@@ -697,7 +720,7 @@ export async function ingestDocument(env: Env, userEmail: string, filename: stri
697
720
 
698
721
  const vectorizePayload = batch.map((c, i) => {
699
722
  const idx = b + i;
700
- const vid = `${userEmail}:${docId}:${idx}`;
723
+ const vid = mintVectorId();
701
724
  chunkRowsToInsert.push({
702
725
  chunk_index: idx,
703
726
  text: c.text,
@@ -0,0 +1,27 @@
1
+ // Vectorize vector ids for RAG chunks (prism#232).
2
+ //
3
+ // A vector id is visible outside D1: in the Vectorize index, in query results, and in any tool
4
+ // that lists or exports ids. So an id must not carry who owns the vector. Before prism#232 the
5
+ // id was `${userEmail}:${docId}:${chunkIndex}`, which put the raw email into every id in access
6
+ // mode. Ownership is carried by the vector's `user_email` metadata (retrieval filters on it) and
7
+ // by the D1 `chunks` row, never by the id.
8
+ //
9
+ // The new id is random: `c_` plus 32 hex digits from crypto.randomUUID(). It is 34 bytes, well
10
+ // under the Vectorize id limit, and it is stored in `chunks.vector_id`, which every reader
11
+ // (retrieval join, document delete, account delete) already uses as the source of truth. So
12
+ // old-format ids keep working without any change on the read side.
13
+
14
+ /** Prefix of every vector id minted after prism#232. */
15
+ export const VECTOR_ID_PREFIX = "c_";
16
+
17
+ const NEW_FORMAT = /^c_[0-9a-f]{32}$/;
18
+
19
+ /** Mint a fresh, non-identifying vector id. */
20
+ export function mintVectorId(): string {
21
+ return VECTOR_ID_PREFIX + crypto.randomUUID().replace(/-/g, "");
22
+ }
23
+
24
+ /** True for an id in the post-prism#232 random format. */
25
+ export function isOpaqueVectorId(id: string): boolean {
26
+ return NEW_FORMAT.test(id);
27
+ }
@@ -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.3.0";
18
+ export const VERSION = "1.4.1";
@@ -0,0 +1,111 @@
1
+ // Catalog pins for the 2026-12 catalog refresh.
2
+ //
3
+ // Why: Cloudflare retired 24 Workers AI models on 2026-11-20. Requests to them
4
+ // fail with HTTP 410 and error 5028. These pins keep a retired id from coming
5
+ // back into the picker, and keep the new entries on a dispatcher that serves
6
+ // them.
7
+
8
+ import { describe, it, expect } from "vitest";
9
+ import { MODELS, OPENAI_COMPAT_CHAT_PROVIDERS } from "../src/models";
10
+ import { DEFAULT_COMPACT_MODEL } from "../src/routes/conversations";
11
+ import { buildGenParams } from "../src/longrun-params";
12
+
13
+ const byId = (id: string) => MODELS.find((m) => m.id === id);
14
+
15
+ // The CF changelog 2026-11-05 "Planned model deprecations on Workers AI" list.
16
+ const RETIRED_2026_11_20 = [
17
+ "@cf/deepseek-ai/deepseek-r1-distill-qwen-32b",
18
+ "@cf/nvidia/nemotron-3-120b-a12b",
19
+ "@cf/deepseek-ai/deepseek-v4-pro-0813",
20
+ "@cf/deepseek-ai/deepseek-v4-flash-0731",
21
+ "@cf/qwen/qwq-32b",
22
+ "@cf/qwen/qwen3-30b-a3b-fp8",
23
+ "@cf/moonshotai/kimi-k2.6",
24
+ "@cf/moonshotai/kimi-k2.7-code",
25
+ "@cf/zai-org/glm-5.2",
26
+ "@cf/zai-org/glm-5.3-flash",
27
+ "@cf/meta-llama/llama-2-7b-chat-hf-lora",
28
+ "@cf/google/gemma-2b-it-lora",
29
+ "@cf/google/gemma-7b-it-lora",
30
+ "@cf/meta/llama-3.1-8b-instruct-fp8",
31
+ "@cf/meta/llama-3.2-1b-instruct",
32
+ "@cf/meta/llama-3.2-3b-instruct",
33
+ "@cf/myshell-ai/melotts",
34
+ "@cf/stabilityai/stable-diffusion-xl-base-1.0",
35
+ "@cf/runwayml/stable-diffusion-v1-5-inpainting",
36
+ "@cf/bytedance/stable-diffusion-xl-lightning",
37
+ "@cf/lykon/dreamshaper-8-lcm",
38
+ "@cf/openai/whisper-tiny-en",
39
+ "@cf/llava-hf/llava-1.5-7b-hf",
40
+ "@cf/google/embeddinggemma-300m",
41
+ ];
42
+
43
+ describe("2026-12 catalog refresh", () => {
44
+ it("carries no model that Cloudflare retired on 2026-11-20", () => {
45
+ for (const id of RETIRED_2026_11_20) expect(byId(id), id).toBeUndefined();
46
+ });
47
+
48
+ it("has no duplicate ids", () => {
49
+ const ids = MODELS.map((m) => m.id);
50
+ expect(new Set(ids).size).toBe(ids.length);
51
+ });
52
+
53
+ it("compacts with a live catalog chat model by default", () => {
54
+ const m = byId(DEFAULT_COMPACT_MODEL);
55
+ expect(m?.type).toBe("chat");
56
+ expect(m?.provider).toBeUndefined(); // Workers AI, no Unified Billing spend
57
+ });
58
+
59
+ it("puts new dotted Claude ids on the binding path", () => {
60
+ for (const id of [
61
+ "anthropic/claude-fable-5.2",
62
+ "anthropic/claude-opus-5.5",
63
+ "anthropic/claude-sonnet-5.5",
64
+ "anthropic/claude-haiku-5.5",
65
+ ]) {
66
+ const m = byId(id);
67
+ expect(m?.provider, id).toBe("anthropic");
68
+ expect(m?.binding, id).toBe(true);
69
+ expect(m?.streaming, id).toBe(true);
70
+ }
71
+ });
72
+
73
+ it("puts grok-4.7 on the xAI binding path", () => {
74
+ expect(byId("xai/grok-4.7")?.binding).toBe(true);
75
+ });
76
+
77
+ it("routes new third-party chat providers through the OpenAI-compatible path", () => {
78
+ for (const id of ["alibaba/qwen3.8-max", "deepseek/deepseek-v4-pro", "minimax/m3", "moonshotai/kimi-k3.1-pro"]) {
79
+ const m = byId(id);
80
+ expect(m?.type, id).toBe("chat");
81
+ expect(OPENAI_COMPAT_CHAT_PROVIDERS.has(m!.provider!), id).toBe(true);
82
+ expect(m?.capabilities, id).toEqual([]);
83
+ }
84
+ });
85
+
86
+ it("keeps GPT-6 ids on Chat Completions (no Responses flag)", () => {
87
+ for (const id of ["openai/gpt-6.2-astra", "openai/gpt-6.2-sol", "openai/gpt-6.1-terra", "openai/gpt-6-luna"]) {
88
+ expect(byId(id)?.api, id).toBeUndefined();
89
+ }
90
+ });
91
+
92
+ it("adds the Workers AI replacements CF recommends", () => {
93
+ for (const id of [
94
+ "@cf/deepseek-ai/deepseek-v4.1-flash-1017",
95
+ "@cf/zai-org/glm-5.3",
96
+ "@cf/qwen/qwen3.8-27b",
97
+ "@cf/google/gemma-4-26b-a4b-it",
98
+ ]) {
99
+ const m = byId(id);
100
+ expect(m?.type, id).toBe("chat");
101
+ expect(m?.provider, id).toBeUndefined();
102
+ }
103
+ });
104
+
105
+ it("sends Seedance 2.5 image-to-video the Seedance 2.0 shape", () => {
106
+ const p25 = buildGenParams("video", { prompt: "pan", imageUrl: "https://x/i.png", modelId: "bytedance/seedance-2.5" });
107
+ const p20 = buildGenParams("video", { prompt: "pan", imageUrl: "https://x/i.png", modelId: "bytedance/seedance-2.0" });
108
+ expect(p25).toEqual(p20);
109
+ expect(p25.image).toBe("https://x/i.png");
110
+ });
111
+ });
@@ -0,0 +1,88 @@
1
+ // prism#233: operator logs never carry a user identity.
2
+ //
3
+ // Two layers. A behavioural test drives a shipped log path with an access-mode identity. A source
4
+ // guard reads every console.* call in src/ (the whole argument list, across lines) and fails if it
5
+ // interpolates an identity variable. The guard is a string match, so it catches the common shape
6
+ // (`${userEmail}` in a log template), not every possible leak; the behavioural tests are the proof
7
+ // for the paths they drive.
8
+
9
+ import { describe, it, expect, vi, afterEach } from "vitest";
10
+ import { readdirSync, readFileSync, statSync } from "node:fs";
11
+ import { join } from "node:path";
12
+ import { resolveProjectForChat } from "../src/routes/projects";
13
+ import type { Env } from "../src/env";
14
+
15
+ const EMAIL = "carol@example.net";
16
+
17
+ afterEach(() => vi.restoreAllMocks());
18
+
19
+ /** Every console.* call in `text`, with its full argument list (balanced parens). */
20
+ export function consoleCalls(text: string): string[] {
21
+ const out: string[] = [];
22
+ const re = /console\.(?:warn|log|error|info|debug)\(/g;
23
+ let m: RegExpExecArray | null;
24
+ while ((m = re.exec(text))) {
25
+ let depth = 1;
26
+ let i = m.index + m[0].length;
27
+ for (; i < text.length && depth > 0; i++) {
28
+ if (text[i] === "(") depth++;
29
+ else if (text[i] === ")") depth--;
30
+ }
31
+ out.push(text.slice(m.index, i));
32
+ }
33
+ return out;
34
+ }
35
+
36
+ const IDENTITY_IN_LOG = /\$\{\s*(?:userEmail|email|identity|user_email)\b|user_email='/;
37
+
38
+ function srcFiles(dir: string): string[] {
39
+ return readdirSync(dir).flatMap((name) => {
40
+ const p = join(dir, name);
41
+ return statSync(p).isDirectory() ? srcFiles(p) : p.endsWith(".ts") ? [p] : [];
42
+ });
43
+ }
44
+
45
+ describe("source guard: no console.* call interpolates an identity", () => {
46
+ const files = srcFiles(join(__dirname, "..", "src"));
47
+
48
+ it("scans a real denominator", () => {
49
+ const calls = files.flatMap((f) => consoleCalls(readFileSync(f, "utf8")));
50
+ expect(files.length).toBeGreaterThan(20);
51
+ expect(calls.length).toBeGreaterThanOrEqual(5);
52
+ });
53
+
54
+ it("finds none in src/", () => {
55
+ const hits = files.flatMap((f) =>
56
+ consoleCalls(readFileSync(f, "utf8"))
57
+ .filter((c) => IDENTITY_IN_LOG.test(c))
58
+ .map((c) => `${f}: ${c.slice(0, 120)}`),
59
+ );
60
+ expect(hits).toEqual([]);
61
+ });
62
+
63
+ it("NEGATIVE CONTROL: goes red on both pre-prism#233 log shapes, across lines", () => {
64
+ const zeroJoin = "console.warn(\n \"retrieveContext:\",\n `Vectorize returned ${n} matches. user_email='${userEmail}', sample`,\n);";
65
+ const project = "console.warn(\n `Chat referenced unknown project_id=${id} for user_email='${userEmail}'; ` +\n `falling back`\n);";
66
+ for (const src of [zeroJoin, project]) {
67
+ const calls = consoleCalls(src);
68
+ expect(calls).toHaveLength(1);
69
+ expect(IDENTITY_IN_LOG.test(calls[0])).toBe(true);
70
+ }
71
+ expect(IDENTITY_IN_LOG.test("console.warn(`zero-join matches=${n} held_by_caller=${own}`)")).toBe(false);
72
+ });
73
+ });
74
+
75
+ describe("resolveProjectForChat: unknown project log", () => {
76
+ it("names the opaque project id and not the caller", async () => {
77
+ const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
78
+ const env = {
79
+ DB: { prepare: () => ({ bind: () => ({ first: async () => null }) }) },
80
+ } as unknown as Env;
81
+ const r = await resolveProjectForChat(env, EMAIL, { project_id: 77 } as never);
82
+ expect(r.project).toBeNull();
83
+ const log = warn.mock.calls.map((c) => c.join(" ")).join("\n");
84
+ expect(log).not.toContain(EMAIL);
85
+ expect(log).not.toMatch(/@/);
86
+ expect(log).toContain("project_id=77");
87
+ });
88
+ });