@skyphusion/create-prism 1.2.0 → 1.3.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.
- package/README.md +3 -4
- package/index.js +2 -2
- package/package.json +1 -1
- package/template/MIGRATIONS.md +30 -0
- package/template/README.md +29 -36
- package/template/docs/legal/INSTANCE-PRIVACY.md +11 -10
- package/template/public/app.js +2 -2
- package/template/public/url-safety.js +6 -6
- package/template/src/env.ts +27 -10
- package/template/src/routes/chat.ts +13 -6
- package/template/src/routes/projects.ts +5 -4
- package/template/src/routes/rag.ts +146 -65
- package/template/src/routes/shared.ts +5 -2
- package/template/src/skyphusion-search.ts +108 -0
- package/template/src/vector-id.ts +27 -0
- package/template/src/version.ts +1 -1
- package/template/tests/log-identity-guard.test.ts +88 -0
- package/template/tests/rag-retrieval-diagnostic.test.ts +89 -80
- package/template/tests/rag-vector-id.test.ts +154 -0
- package/template/tests/skyphusion-search.test.ts +144 -0
- package/template/tests/vectorize-rekey-vector-ids.test.ts +141 -0
- package/template/wrangler.example.toml +14 -9
- package/template/src/searxng.ts +0 -75
- package/template/tests/searxng.test.ts +0 -51
|
@@ -11,8 +11,9 @@ import type { Env } from "../env";
|
|
|
11
11
|
import { aiRun, type AiContext } from "../ai-binding";
|
|
12
12
|
import { requireGatewayCredentials } from "../gateway-credentials";
|
|
13
13
|
import { chunkText } from "../chunking";
|
|
14
|
-
import {
|
|
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) ----------
|
|
@@ -66,10 +67,9 @@ export function mimeFromName(name: string): string {
|
|
|
66
67
|
}
|
|
67
68
|
|
|
68
69
|
// v0.17.0: web-search retrieval limits and timeouts. Each upstream is
|
|
69
|
-
// time-bounded per source so a slow
|
|
70
|
+
// time-bounded per source so a slow web source does not block Wikipedia.
|
|
70
71
|
// Counts kept small to bound context-token spend when the toggle is on.
|
|
71
|
-
|
|
72
|
-
export const SEARXNG_MAX_RESULTS = 5;
|
|
72
|
+
export const SEARCH_MAX_RESULTS = 5;
|
|
73
73
|
export const WIKIPEDIA_MAX_RESULTS = 3;
|
|
74
74
|
export const WEB_SEARCH_TIMEOUT_MS = 8000;
|
|
75
75
|
|
|
@@ -256,6 +256,26 @@ export function vecMetadataFilterOn(env: Pick<Env, "VEC_METADATA_FILTER">): bool
|
|
|
256
256
|
return v === "on" || v === "1" || v === "true";
|
|
257
257
|
}
|
|
258
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
|
+
|
|
259
279
|
export async function retrieveContext(
|
|
260
280
|
env: Env,
|
|
261
281
|
userEmail: string,
|
|
@@ -358,21 +378,23 @@ export async function retrieveContext(
|
|
|
358
378
|
// documents are members of the requested project.
|
|
359
379
|
// Two messages, deliberately carrying different things.
|
|
360
380
|
//
|
|
361
|
-
//
|
|
362
|
-
//
|
|
363
|
-
//
|
|
364
|
-
//
|
|
365
|
-
//
|
|
366
|
-
//
|
|
367
|
-
//
|
|
368
|
-
//
|
|
369
|
-
//
|
|
370
|
-
|
|
371
|
-
const
|
|
372
|
-
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}` : "";
|
|
373
392
|
console.warn(
|
|
374
393
|
"retrieveContext:",
|
|
375
|
-
`
|
|
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.",
|
|
376
398
|
);
|
|
377
399
|
|
|
378
400
|
// The caller gets a true statement about their own retrieval and nothing
|
|
@@ -430,58 +452,117 @@ export function formatRetrievalForSystemPrompt(chunks: RetrievedChunk[]): string
|
|
|
430
452
|
|
|
431
453
|
// ---------- Web search (v0.17.0) ----------
|
|
432
454
|
//
|
|
433
|
-
// Optional retrieval source:
|
|
434
|
-
// Wikipedia for lore / reference. Both run in
|
|
435
|
-
// kill the other. Per-source timeouts
|
|
436
|
-
// upstream from blocking the
|
|
455
|
+
// Optional retrieval source: the skyphusion-search Worker (service binding
|
|
456
|
+
// SEARCH) for corpus hits, Wikipedia for lore / reference. Both run in
|
|
457
|
+
// parallel; failure of one does not kill the other. Per-source timeouts
|
|
458
|
+
// (WEB_SEARCH_TIMEOUT_MS) prevent a slow upstream from blocking the turn.
|
|
437
459
|
//
|
|
438
|
-
//
|
|
439
|
-
//
|
|
440
|
-
//
|
|
460
|
+
// SEARCH absent is its own status ("absent"), not a failure and not zero
|
|
461
|
+
// hits. A thrown RPC error is "failed". The error string is the RPC
|
|
462
|
+
// message: empty_question, question_too_long, rate_limited,
|
|
463
|
+
// search_unavailable, or whatever else was thrown. An empty chunks
|
|
464
|
+
// array is "ok" with count 0. Callers read `sources` to tell those
|
|
465
|
+
// apart. `error` is set only when the web source failed, so a
|
|
466
|
+
// Wikipedia miss does not look like a web-source failure. Wikipedia
|
|
467
|
+
// itself is unchanged: same MediaWiki request, and its hits still
|
|
468
|
+
// return when the web source fails or is absent.
|
|
441
469
|
//
|
|
442
470
|
// Results are persisted to the existing retrieved_context column alongside
|
|
443
471
|
// RAG chunks, with source_type discriminator. The frontend renders branches
|
|
444
472
|
// on source_type to show the source URL for web results.
|
|
445
473
|
|
|
446
|
-
export
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
// Each upstream is wrapped in its own timeout + catch so a single failure
|
|
454
|
-
// doesn't abort the other. Partial results are better than nothing.
|
|
455
|
-
const searxngPromise: Promise<RetrievedWebResult[]> = env.SEARXNG_URL
|
|
456
|
-
? searchSearxng(env, q).catch(() => [])
|
|
457
|
-
: Promise.resolve([]);
|
|
458
|
-
const wikipediaPromise: Promise<RetrievedWebResult[]> = searchWikipedia(q).catch(() => []);
|
|
459
|
-
|
|
460
|
-
const [searxng, wikipedia] = await Promise.all([searxngPromise, wikipediaPromise]);
|
|
461
|
-
const results = [...searxng, ...wikipedia];
|
|
462
|
-
|
|
463
|
-
// Empty results is fine; it just means the query didn't match anything in
|
|
464
|
-
// any source. Real per-source failures are swallowed by the .catch above
|
|
465
|
-
// so the other source can still return its hits.
|
|
466
|
-
return { results, error: null };
|
|
474
|
+
export type WebSourceStatus = "ok" | "failed" | "absent";
|
|
475
|
+
|
|
476
|
+
export interface WebSourceReport {
|
|
477
|
+
status: WebSourceStatus;
|
|
478
|
+
count: number;
|
|
479
|
+
error?: string;
|
|
467
480
|
}
|
|
468
481
|
|
|
469
|
-
export
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
482
|
+
export interface WebSearchOutcome {
|
|
483
|
+
results: RetrievedWebResult[];
|
|
484
|
+
error: string | null;
|
|
485
|
+
sources: {
|
|
486
|
+
web: WebSourceReport;
|
|
487
|
+
wikipedia: WebSourceReport;
|
|
488
|
+
};
|
|
489
|
+
}
|
|
490
|
+
|
|
491
|
+
export function noWebSearch(): WebSearchOutcome {
|
|
492
|
+
return {
|
|
493
|
+
results: [],
|
|
494
|
+
error: null,
|
|
495
|
+
sources: {
|
|
496
|
+
web: { status: "ok", count: 0 },
|
|
497
|
+
wikipedia: { status: "ok", count: 0 },
|
|
498
|
+
},
|
|
499
|
+
};
|
|
500
|
+
}
|
|
501
|
+
|
|
502
|
+
interface SourceRun {
|
|
503
|
+
results: RetrievedWebResult[];
|
|
504
|
+
status: WebSourceStatus;
|
|
505
|
+
error?: string;
|
|
506
|
+
}
|
|
507
|
+
|
|
508
|
+
function reportSource(run: SourceRun): WebSourceReport {
|
|
509
|
+
const report: WebSourceReport = { status: run.status, count: run.results.length };
|
|
510
|
+
if (run.error) report.error = run.error;
|
|
511
|
+
return report;
|
|
512
|
+
}
|
|
513
|
+
|
|
514
|
+
async function runWebSource(env: Env, query: string): Promise<SourceRun> {
|
|
515
|
+
if (!env.SEARCH) return { results: [], status: "absent" };
|
|
516
|
+
try {
|
|
517
|
+
const hits = await askSkyphusionSearch(env.SEARCH, query, {
|
|
518
|
+
timeoutMs: WEB_SEARCH_TIMEOUT_MS,
|
|
519
|
+
maxResults: SEARCH_MAX_RESULTS,
|
|
520
|
+
});
|
|
521
|
+
return {
|
|
522
|
+
status: "ok",
|
|
523
|
+
results: hits.map((hit): RetrievedWebResult => ({
|
|
524
|
+
source_type: "web",
|
|
525
|
+
source: "skyphusion-search",
|
|
526
|
+
url: hit.url,
|
|
527
|
+
title: hit.title,
|
|
528
|
+
snippet: hit.snippet,
|
|
529
|
+
...(hit.score !== undefined ? { score: hit.score } : {}),
|
|
530
|
+
})),
|
|
531
|
+
};
|
|
532
|
+
} catch (err) {
|
|
533
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
534
|
+
return { results: [], status: "failed", error: message };
|
|
535
|
+
}
|
|
536
|
+
}
|
|
537
|
+
|
|
538
|
+
async function runWikipedia(query: string): Promise<SourceRun> {
|
|
539
|
+
try {
|
|
540
|
+
return { results: await searchWikipedia(query), status: "ok" };
|
|
541
|
+
} catch (err) {
|
|
542
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
543
|
+
return { results: [], status: "failed", error: message };
|
|
544
|
+
}
|
|
545
|
+
}
|
|
546
|
+
|
|
547
|
+
export async function searchWeb(env: Env, query: string): Promise<WebSearchOutcome> {
|
|
548
|
+
const q = query.trim();
|
|
549
|
+
if (!q) return noWebSearch();
|
|
550
|
+
|
|
551
|
+
const [web, wiki] = await Promise.all([runWebSource(env, q), runWikipedia(q)]);
|
|
552
|
+
if (web.status === "failed") {
|
|
553
|
+
console.error("searchWeb: skyphusion-search failed:", web.error ?? "unknown");
|
|
554
|
+
}
|
|
555
|
+
if (wiki.status === "failed") {
|
|
556
|
+
console.error("searchWeb: wikipedia failed:", wiki.error ?? "unknown");
|
|
557
|
+
}
|
|
558
|
+
return {
|
|
559
|
+
results: [...web.results, ...wiki.results],
|
|
560
|
+
error: web.status === "failed" ? (web.error ?? "web search failed") : null,
|
|
561
|
+
sources: {
|
|
562
|
+
web: reportSource(web),
|
|
563
|
+
wikipedia: reportSource(wiki),
|
|
564
|
+
},
|
|
565
|
+
};
|
|
485
566
|
}
|
|
486
567
|
|
|
487
568
|
export async function searchWikipedia(query: string): Promise<RetrievedWebResult[]> {
|
|
@@ -552,7 +633,7 @@ export function stripWikipediaSnippet(html: string): string {
|
|
|
552
633
|
|
|
553
634
|
export function webSourceSystemLabel(source: RetrievedWebResult["source"]): string {
|
|
554
635
|
switch (source) {
|
|
555
|
-
case "
|
|
636
|
+
case "skyphusion-search": return "Web";
|
|
556
637
|
case "wikipedia": return "Wikipedia";
|
|
557
638
|
}
|
|
558
639
|
}
|
|
@@ -602,7 +683,7 @@ export async function ingestDocument(env: Env, userEmail: string, filename: stri
|
|
|
602
683
|
// Store raw bytes in R2 for audit / future re-processing.
|
|
603
684
|
const r2Key = await r2Put(env, "in", mime, bytes, userEmail);
|
|
604
685
|
|
|
605
|
-
// Insert document row first so we have its ID for
|
|
686
|
+
// Insert document row first so we have its ID for the chunk metadata.
|
|
606
687
|
const docInsert = await env.DB.prepare(
|
|
607
688
|
`INSERT INTO documents
|
|
608
689
|
(user_email, filename, mime, r2_key, size_bytes, total_chars, chunk_count)
|
|
@@ -619,7 +700,7 @@ export async function ingestDocument(env: Env, userEmail: string, filename: stri
|
|
|
619
700
|
|
|
620
701
|
// Embed in batches and upsert to Vectorize. We tag every vector with
|
|
621
702
|
// user_email + document_id so we can filter on retrieval and clean up on delete.
|
|
622
|
-
// Vector
|
|
703
|
+
// Vector ids are random and carry no identity (src/vector-id.ts, prism#232).
|
|
623
704
|
const vectorIdsWritten: string[] = [];
|
|
624
705
|
const chunkRowsToInsert: {
|
|
625
706
|
chunk_index: number;
|
|
@@ -639,7 +720,7 @@ export async function ingestDocument(env: Env, userEmail: string, filename: stri
|
|
|
639
720
|
|
|
640
721
|
const vectorizePayload = batch.map((c, i) => {
|
|
641
722
|
const idx = b + i;
|
|
642
|
-
const vid =
|
|
723
|
+
const vid = mintVectorId();
|
|
643
724
|
chunkRowsToInsert.push({
|
|
644
725
|
chunk_index: idx,
|
|
645
726
|
text: c.text,
|
|
@@ -32,7 +32,7 @@ export interface ChatRequest {
|
|
|
32
32
|
image_url?: string; // v0.21.5: source image for image-to-video models (hh1-i2v); a fetchable URL
|
|
33
33
|
image_key?: string; // v0.21.6: source image as an R2 key (e.g. a prior nano-banana output) for image-to-video chaining
|
|
34
34
|
use_docs?: boolean; // Pass 2: when true, retrieve top-K chunks from Vectorize and inject as context
|
|
35
|
-
use_web_search?: boolean; // v0.17.0: when true, query
|
|
35
|
+
use_web_search?: boolean; // v0.17.0: when true, query skyphusion-search + Wikipedia and inject snippets as context
|
|
36
36
|
conversation_id?: string; // Multi-turn: when present, continue an existing conversation
|
|
37
37
|
project_id?: number; // v0.20.0: when present, scope RAG retrieval to the project's docs
|
|
38
38
|
// and apply the project's system_prompt as default if system_prompt is empty
|
|
@@ -55,7 +55,10 @@ export interface RetrievedChunk {
|
|
|
55
55
|
// retrieved_context column. The frontend renders branches on source_type.
|
|
56
56
|
export interface RetrievedWebResult {
|
|
57
57
|
source_type: "web";
|
|
58
|
-
|
|
58
|
+
// "skyphusion-search" is the service-binding corpus source. Older rows
|
|
59
|
+
// stored "searxng"; the UI still labels those as web. New writes use
|
|
60
|
+
// "skyphusion-search" only.
|
|
61
|
+
source: "skyphusion-search" | "wikipedia";
|
|
59
62
|
url: string;
|
|
60
63
|
title: string;
|
|
61
64
|
snippet: string; // already HTML-stripped
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
// skyphusion-search retrieval, via the SEARCH service binding.
|
|
2
|
+
//
|
|
3
|
+
// Contract pinned from skyphusion-labs/search-mcp (PR #147). The worker
|
|
4
|
+
// exports a named entrypoint SearchEntrypoint. The caller selects it
|
|
5
|
+
// with wrangler `entrypoint = "SearchEntrypoint"` on the service
|
|
6
|
+
// binding. Internet fetch still hits the default export, so this client
|
|
7
|
+
// does not call POST /ask and does not send an Origin header.
|
|
8
|
+
//
|
|
9
|
+
// search(question: string) returns { chunks }. Fields used here match
|
|
10
|
+
// AiSearchChunk: score, text, item.key, item.metadata.repo,
|
|
11
|
+
// item.metadata.path. Chunks carry no URL. A hit links to
|
|
12
|
+
// https://github.com/skyphusion-labs/<repo>/blob/main/<path>, the
|
|
13
|
+
// public corpus that worker indexes. metadata.path wins over the R2
|
|
14
|
+
// key. A path taken from the key drops a trailing ".txt" that corpus
|
|
15
|
+
// ingest adds (same rule as search-mcp src/mcp.ts mapSearchChunks).
|
|
16
|
+
//
|
|
17
|
+
// The question must be a non-empty string of at most 2000 characters
|
|
18
|
+
// after trim. A bad call throws Error with one of these messages:
|
|
19
|
+
// empty_question, question_too_long, rate_limited, search_unavailable.
|
|
20
|
+
// The caller reports that message as sources.web error and status
|
|
21
|
+
// "failed". An empty chunks array is zero hits, not a failure. A
|
|
22
|
+
// missing binding is "absent", and the caller decides that before
|
|
23
|
+
// this function runs.
|
|
24
|
+
|
|
25
|
+
import type { SearchChunk, SearchEntrypoint } from "./env";
|
|
26
|
+
|
|
27
|
+
const GITHUB_BLOB = "https://github.com/skyphusion-labs";
|
|
28
|
+
const PATH_SEGMENT = /^[A-Za-z0-9._-]+$/;
|
|
29
|
+
|
|
30
|
+
export interface SearchHit {
|
|
31
|
+
title: string;
|
|
32
|
+
url: string;
|
|
33
|
+
snippet: string;
|
|
34
|
+
score?: number;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
function repoAndPath(chunk: SearchChunk): { repo: string; path: string } | null {
|
|
38
|
+
const meta = chunk.item?.metadata;
|
|
39
|
+
const key = typeof chunk.item?.key === "string" ? chunk.item.key.trim() : "";
|
|
40
|
+
const slash = key.indexOf("/");
|
|
41
|
+
const keyRepo = slash > 0 ? key.slice(0, slash) : "";
|
|
42
|
+
const keyPath = slash > 0 ? key.slice(slash + 1).replace(/\.txt$/, "") : "";
|
|
43
|
+
const repo = (typeof meta?.repo === "string" ? meta.repo.trim() : "") || keyRepo;
|
|
44
|
+
const path = (typeof meta?.path === "string" ? meta.path.trim() : "") || keyPath;
|
|
45
|
+
if (!repo || !path) return null;
|
|
46
|
+
return { repo, path };
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
function corpusUrl(repo: string, path: string): string | null {
|
|
50
|
+
if (!PATH_SEGMENT.test(repo)) return null;
|
|
51
|
+
const parts = path.split("/");
|
|
52
|
+
// "." and ".." match the segment pattern (dots and nothing else) and must
|
|
53
|
+
// still be refused, or a key can climb out of the repo path.
|
|
54
|
+
if (parts.some((seg) => seg === "." || seg === ".." || !PATH_SEGMENT.test(seg))) return null;
|
|
55
|
+
return `${GITHUB_BLOB}/${repo}/blob/main/${parts.map((seg) => encodeURIComponent(seg)).join("/")}`;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
export function mapSearchChunks(chunks: readonly SearchChunk[], maxResults: number): SearchHit[] {
|
|
59
|
+
const out: SearchHit[] = [];
|
|
60
|
+
const seen = new Set<string>();
|
|
61
|
+
const cap = Math.max(0, maxResults);
|
|
62
|
+
for (const chunk of chunks) {
|
|
63
|
+
if (!chunk || typeof chunk !== "object") continue;
|
|
64
|
+
const id = repoAndPath(chunk);
|
|
65
|
+
if (!id) continue;
|
|
66
|
+
const url = corpusUrl(id.repo, id.path);
|
|
67
|
+
if (!url || seen.has(url)) continue;
|
|
68
|
+
seen.add(url);
|
|
69
|
+
const snippet = typeof chunk.text === "string"
|
|
70
|
+
? chunk.text.replace(/\s+/g, " ").trim()
|
|
71
|
+
: "";
|
|
72
|
+
const hit: SearchHit = { title: `${id.repo}/${id.path}`, url, snippet };
|
|
73
|
+
if (typeof chunk.score === "number" && Number.isFinite(chunk.score)) hit.score = chunk.score;
|
|
74
|
+
out.push(hit);
|
|
75
|
+
if (out.length >= cap) break;
|
|
76
|
+
}
|
|
77
|
+
return out;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
// The RPC method takes no AbortSignal. Race a timer so a stuck call still
|
|
81
|
+
// fails this source inside the caller's timeout, then clear the timer so
|
|
82
|
+
// a fast call does not hold the process open.
|
|
83
|
+
function withTimeout<T>(work: Promise<T>, ms: number): Promise<T> {
|
|
84
|
+
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
85
|
+
const timeout = new Promise<never>((_, reject) => {
|
|
86
|
+
timer = setTimeout(() => reject(new Error("skyphusion-search timeout")), ms);
|
|
87
|
+
});
|
|
88
|
+
// If the timer wins, a later rejection of `work` must not surface as
|
|
89
|
+
// unhandled. The race below still rejects with the original error when
|
|
90
|
+
// `work` loses first.
|
|
91
|
+
void work.catch(() => {});
|
|
92
|
+
return Promise.race([work, timeout]).finally(() => {
|
|
93
|
+
if (timer !== undefined) clearTimeout(timer);
|
|
94
|
+
});
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
export async function askSkyphusionSearch(
|
|
98
|
+
binding: Service<SearchEntrypoint>,
|
|
99
|
+
query: string,
|
|
100
|
+
opts: { timeoutMs: number; maxResults: number },
|
|
101
|
+
): Promise<SearchHit[]> {
|
|
102
|
+
const question = query.trim();
|
|
103
|
+
const result = await withTimeout(binding.search(question), opts.timeoutMs);
|
|
104
|
+
if (!result || !Array.isArray(result.chunks)) {
|
|
105
|
+
throw new Error("search_unavailable");
|
|
106
|
+
}
|
|
107
|
+
return mapSearchChunks(result.chunks, opts.maxResults);
|
|
108
|
+
}
|
|
@@ -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
|
+
}
|
package/template/src/version.ts
CHANGED
|
@@ -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.
|
|
18
|
+
export const VERSION = "1.3.1";
|
|
@@ -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
|
+
});
|