@skyphusion/create-prism 1.0.4 → 1.3.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 +10 -8
- package/index.js +3 -2
- package/package.json +1 -1
- package/template/CONTRIBUTING.md +18 -3
- package/template/MIGRATIONS.md +52 -0
- package/template/README.md +79 -52
- package/template/docs/legal/INSTANCE-ACCEPTABLE-USE.md +5 -2
- package/template/docs/legal/INSTANCE-PRIVACY.md +128 -27
- package/template/migrations/0005_auth_attempts_retention.sql +23 -0
- package/template/package.json +6 -6
- package/template/public/app.js +21 -8
- package/template/public/index.html +23 -9
- package/template/public/styles.css +45 -7
- package/template/public/url-safety.js +6 -6
- 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 +38 -10
- 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 +18 -9
- package/template/src/routes/prefs.ts +46 -5
- package/template/src/routes/rag.ts +135 -61
- package/template/src/routes/shared.ts +27 -11
- package/template/src/routes/workflow.ts +2 -5
- package/template/src/skyphusion-search.ts +108 -0
- 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/skyphusion-search.test.ts +144 -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 +26 -11
- package/template/src/searxng.ts +0 -75
- package/template/tests/searxng.test.ts +0 -51
|
@@ -43,6 +43,7 @@ const ALL_TABLES = [
|
|
|
43
43
|
"users",
|
|
44
44
|
"sessions",
|
|
45
45
|
"auth_attempts",
|
|
46
|
+
"conversation_compact",
|
|
46
47
|
];
|
|
47
48
|
|
|
48
49
|
const anyEnv = env as unknown as { AUTH_MODE?: string; GATEWAY_ID?: string; CF_AIG_TOKEN?: string };
|
|
@@ -61,6 +62,9 @@ afterEach(() => {
|
|
|
61
62
|
delete anyEnv.CF_AIG_TOKEN;
|
|
62
63
|
});
|
|
63
64
|
|
|
65
|
+
// v1.1.0: a user's Cloudflare account id (any 32 hex will do under the stubs).
|
|
66
|
+
const USER_ACCT = "0123456789abcdef0123456789abcdef";
|
|
67
|
+
|
|
64
68
|
const WORKERS_AI_CHAT = MODELS.find((m) => m.type === "chat" && !m.provider)!.id;
|
|
65
69
|
const STREAM_CHAT = MODELS.find((m) => m.type === "chat" && m.streaming && !m.provider)?.id
|
|
66
70
|
?? MODELS.find((m) => m.type === "chat" && m.streaming)!.id;
|
|
@@ -212,6 +216,43 @@ describe("public-mode gate: uniform 401 unauthenticated", () => {
|
|
|
212
216
|
expect(Array.isArray(((await res.json()) as { chats: unknown[] }).chats)).toBe(true);
|
|
213
217
|
});
|
|
214
218
|
|
|
219
|
+
// The saved slug becomes a path segment in a gateway.ai.cloudflare.com URL and a
|
|
220
|
+
// request header value. Before this was validated, .trim() was the only transform,
|
|
221
|
+
// so an arbitrary string reached the binding as a gateway id.
|
|
222
|
+
it("rejects a gateway_id that is not a slug, and stores nothing", async () => {
|
|
223
|
+
const cookie = await signup("nadia", "password123", "203.0.113.50");
|
|
224
|
+
for (const bad of ["not a slug", "has/slash", "a".repeat(65), "semi;colon", "../traverse"]) {
|
|
225
|
+
const res = await req("/api/prefs", { method: "PATCH", cookie, body: { gateway_id: bad } });
|
|
226
|
+
expect(res.status).toBe(400);
|
|
227
|
+
expect(((await res.json()) as { code?: string }).code).toBe("invalid_gateway_id");
|
|
228
|
+
}
|
|
229
|
+
// Nothing was written by any of the rejected attempts.
|
|
230
|
+
const prefs = (await (await req("/api/prefs", { cookie })).json()) as { gateway_id: string | null };
|
|
231
|
+
expect(prefs.gateway_id).toBeNull();
|
|
232
|
+
});
|
|
233
|
+
|
|
234
|
+
it("still accepts a well-formed slug", async () => {
|
|
235
|
+
const cookie = await signup("omar", "password123", "203.0.113.51");
|
|
236
|
+
const res = await req("/api/prefs", { method: "PATCH", cookie, body: { gateway_id: "my-gw_1" } });
|
|
237
|
+
expect(res.status).not.toBe(400);
|
|
238
|
+
const prefs = (await (await req("/api/prefs", { cookie })).json()) as { gateway_id: string | null };
|
|
239
|
+
expect(prefs.gateway_id).toBe("my-gw_1");
|
|
240
|
+
});
|
|
241
|
+
|
|
242
|
+
// Whitespace tolerance on the slug was untested: every other gateway_id in
|
|
243
|
+
// this file is already whitespace-free, so nothing pinned what happens to a
|
|
244
|
+
// padded one. Normalization lives in saveUserPrefs (user-prefs.ts), NOT in
|
|
245
|
+
// this route, which is why the route storing body.gateway_id raw and storing
|
|
246
|
+
// it trimmed are observably identical. This asserts the endpoint contract so
|
|
247
|
+
// that a future change moving or dropping that trim is caught here.
|
|
248
|
+
it("accepts a padded slug and stores it trimmed", async () => {
|
|
249
|
+
const cookie = await signup("priya", "password123", "203.0.113.52");
|
|
250
|
+
const res = await req("/api/prefs", { method: "PATCH", cookie, body: { gateway_id: " padded-gw " } });
|
|
251
|
+
expect(res.status).not.toBe(400);
|
|
252
|
+
const prefs = (await (await req("/api/prefs", { cookie })).json()) as { gateway_id: string | null };
|
|
253
|
+
expect(prefs.gateway_id).toBe("padded-gw");
|
|
254
|
+
});
|
|
255
|
+
|
|
215
256
|
it("isolates prefs between two accounts", async () => {
|
|
216
257
|
const aCookie = await signup("hank", "password123", "203.0.113.10");
|
|
217
258
|
const bCookie = await signup("iris", "password123", "203.0.113.11");
|
|
@@ -259,9 +300,13 @@ describe("fail-closed gateway in public mode", () => {
|
|
|
259
300
|
expect(b.gateway.configured).toBe(false);
|
|
260
301
|
});
|
|
261
302
|
|
|
262
|
-
it("positive control: once the user sets
|
|
303
|
+
it("positive control: once the user sets account id + gateway + token, the 412 no longer fires", async () => {
|
|
263
304
|
const cookie = await signup("liam", "password123");
|
|
264
|
-
await req("/api/prefs", {
|
|
305
|
+
await req("/api/prefs", {
|
|
306
|
+
method: "PATCH",
|
|
307
|
+
cookie,
|
|
308
|
+
body: { account_id: USER_ACCT, gateway_id: "liam-gw", cf_aig_token: "liam-token" },
|
|
309
|
+
});
|
|
265
310
|
let status: number;
|
|
266
311
|
try {
|
|
267
312
|
status = (
|
|
@@ -274,6 +319,206 @@ describe("fail-closed gateway in public mode", () => {
|
|
|
274
319
|
});
|
|
275
320
|
});
|
|
276
321
|
|
|
322
|
+
// prism#193: OPENAI_API_KEY is a deployer secret, so in public mode it must be
|
|
323
|
+
// ignored exactly like GATEWAY_ID / CF_AIG_TOKEN. The user here has a fully
|
|
324
|
+
// configured BYOK gateway so the credential gate passes and the request reaches
|
|
325
|
+
// the image dispatch branch; the only question is which transport it picks.
|
|
326
|
+
describe("OPENAI_API_KEY is ignored in public mode (prism#193)", () => {
|
|
327
|
+
const GPT_IMAGE = MODELS.find((m) => m.type === "image" && m.provider === "openai")!.id;
|
|
328
|
+
const keyEnv = env as unknown as { OPENAI_API_KEY?: string };
|
|
329
|
+
const realFetch = globalThis.fetch;
|
|
330
|
+
let openaiCalls: string[];
|
|
331
|
+
|
|
332
|
+
beforeEach(() => {
|
|
333
|
+
openaiCalls = [];
|
|
334
|
+
keyEnv.OPENAI_API_KEY = "sk-host-owned";
|
|
335
|
+
globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => {
|
|
336
|
+
const url = input instanceof Request ? input.url : String(input);
|
|
337
|
+
if (url.startsWith("https://api.openai.com/")) {
|
|
338
|
+
openaiCalls.push(url);
|
|
339
|
+
return new Response(JSON.stringify({ error: { message: "stubbed" } }), { status: 500 });
|
|
340
|
+
}
|
|
341
|
+
// v1.1.0: an account-scoped user dispatches over REST to their own
|
|
342
|
+
// account; answer it locally so the test never leaves the sandbox.
|
|
343
|
+
if (url.startsWith("https://api.cloudflare.com/")) {
|
|
344
|
+
return new Response(JSON.stringify({ success: false, errors: [{ message: "stubbed" }] }), {
|
|
345
|
+
status: 500,
|
|
346
|
+
headers: { "content-type": "application/json" },
|
|
347
|
+
});
|
|
348
|
+
}
|
|
349
|
+
return realFetch(input, init);
|
|
350
|
+
}) as typeof fetch;
|
|
351
|
+
});
|
|
352
|
+
|
|
353
|
+
afterEach(() => {
|
|
354
|
+
delete keyEnv.OPENAI_API_KEY;
|
|
355
|
+
globalThis.fetch = realFetch;
|
|
356
|
+
});
|
|
357
|
+
|
|
358
|
+
async function runGptImage(headers: Record<string, string>): Promise<void> {
|
|
359
|
+
const h = new Headers({ "content-type": "application/json", "cf-connecting-ip": "203.0.113.40", ...headers });
|
|
360
|
+
await SELF.fetch("https://prism.test/api/prefs", {
|
|
361
|
+
method: "PATCH",
|
|
362
|
+
headers: h,
|
|
363
|
+
// v1.1.0: account id included, or public mode would 412 before the
|
|
364
|
+
// image branch and this test would pass without testing anything.
|
|
365
|
+
body: JSON.stringify({ account_id: USER_ACCT, gateway_id: "user-gw", cf_aig_token: "user-token" }),
|
|
366
|
+
});
|
|
367
|
+
try {
|
|
368
|
+
await SELF.fetch("https://prism.test/api/chat", {
|
|
369
|
+
method: "POST",
|
|
370
|
+
headers: h,
|
|
371
|
+
body: JSON.stringify({ model: GPT_IMAGE, user_input: "a red kite" }),
|
|
372
|
+
});
|
|
373
|
+
} catch {
|
|
374
|
+
// The inert AI stub makes the gateway path throw; that is fine, the
|
|
375
|
+
// assertion is only about whether api.openai.com was dialed.
|
|
376
|
+
}
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
it("public mode: a configured user's gpt-image request never dials api.openai.com with the host key", async () => {
|
|
380
|
+
const cookie = await signup("olga", "password123");
|
|
381
|
+
await runGptImage({ cookie });
|
|
382
|
+
expect(openaiCalls).toEqual([]);
|
|
383
|
+
});
|
|
384
|
+
|
|
385
|
+
it("positive control: access mode still uses the deployer key (the stub can see the call)", async () => {
|
|
386
|
+
anyEnv.AUTH_MODE = "access";
|
|
387
|
+
await runGptImage({ "cf-access-authenticated-user-email": "owner@example.com" });
|
|
388
|
+
expect(openaiCalls.length).toBe(1);
|
|
389
|
+
});
|
|
390
|
+
});
|
|
391
|
+
|
|
392
|
+
// v1.1.0: BYOK must reach the user's own Cloudflare account. The AI binding is
|
|
393
|
+
// pinned to the worker's account, so these assert (1) the pre-v1.1.0 shape is
|
|
394
|
+
// refused with its own code rather than resolved on our binding, and (2) a
|
|
395
|
+
// fully configured user is dispatched over HTTP to THEIR account id. The AI
|
|
396
|
+
// stub here is an inert {}: any path that touched the host binding would throw,
|
|
397
|
+
// so a 200 with stubbed fetch proves the binding was never used.
|
|
398
|
+
describe("account-scoped BYOK (v1.1.0)", () => {
|
|
399
|
+
const LEGACY_ANTHROPIC = MODELS.find((m) => m.provider === "anthropic" && !m.binding)!.id;
|
|
400
|
+
const BINDING_ANTHROPIC = MODELS.find((m) => m.provider === "anthropic" && m.binding)!.id;
|
|
401
|
+
const realFetch = globalThis.fetch;
|
|
402
|
+
let calls: Array<{ url: string; headers: Headers; body: string }>;
|
|
403
|
+
|
|
404
|
+
const anthropicMessage = {
|
|
405
|
+
id: "msg_1",
|
|
406
|
+
type: "message",
|
|
407
|
+
role: "assistant",
|
|
408
|
+
model: "stub",
|
|
409
|
+
content: [{ type: "text", text: "hello from your account" }],
|
|
410
|
+
stop_reason: "end_turn",
|
|
411
|
+
usage: { input_tokens: 3, output_tokens: 5 },
|
|
412
|
+
};
|
|
413
|
+
|
|
414
|
+
beforeEach(() => {
|
|
415
|
+
calls = [];
|
|
416
|
+
globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => {
|
|
417
|
+
const url = input instanceof Request ? input.url : String(input);
|
|
418
|
+
if (url.startsWith("https://gateway.ai.cloudflare.com/") || url.startsWith("https://api.cloudflare.com/")) {
|
|
419
|
+
calls.push({ url, headers: new Headers(init?.headers), body: String(init?.body ?? "") });
|
|
420
|
+
const payload = url.startsWith("https://api.cloudflare.com/")
|
|
421
|
+
? { success: true, errors: [], result: anthropicMessage }
|
|
422
|
+
: anthropicMessage;
|
|
423
|
+
return new Response(JSON.stringify(payload), {
|
|
424
|
+
headers: { "content-type": "application/json", "cf-aig-log-id": "user-log-1" },
|
|
425
|
+
});
|
|
426
|
+
}
|
|
427
|
+
return realFetch(input, init);
|
|
428
|
+
}) as typeof fetch;
|
|
429
|
+
});
|
|
430
|
+
|
|
431
|
+
afterEach(() => {
|
|
432
|
+
globalThis.fetch = realFetch;
|
|
433
|
+
});
|
|
434
|
+
|
|
435
|
+
async function configure(cookie: string, body: Record<string, unknown>): Promise<Response> {
|
|
436
|
+
return req("/api/prefs", { method: "PATCH", cookie, body });
|
|
437
|
+
}
|
|
438
|
+
|
|
439
|
+
it("pre-v1.1.0 shape (slug + token, no account id): 412 gateway_account_id_required, nothing dialed", async () => {
|
|
440
|
+
const cookie = await signup("petra", "password123");
|
|
441
|
+
await configure(cookie, { gateway_id: "petra-gw", cf_aig_token: "petra-token" });
|
|
442
|
+
for (const model of [LEGACY_ANTHROPIC, BINDING_ANTHROPIC, WORKERS_AI_CHAT]) {
|
|
443
|
+
const res = await req("/api/chat", { method: "POST", cookie, body: { model, user_input: "hi" } });
|
|
444
|
+
expect(res.status).toBe(412);
|
|
445
|
+
const body = (await res.json()) as { code: string; error: string };
|
|
446
|
+
expect(body.code).toBe("gateway_account_id_required");
|
|
447
|
+
expect(body.error).toMatch(/account ID/);
|
|
448
|
+
}
|
|
449
|
+
expect(calls).toEqual([]);
|
|
450
|
+
});
|
|
451
|
+
|
|
452
|
+
it("boot and prefs flag the pre-v1.1.0 user and keep their saved slug", async () => {
|
|
453
|
+
const cookie = await signup("quinn", "password123");
|
|
454
|
+
await configure(cookie, { gateway_id: "quinn-gw", cf_aig_token: "quinn-token" });
|
|
455
|
+
const b = (await boot(cookie)) as BootEnvelope & {
|
|
456
|
+
gateway: { account_id_required: boolean; gateway_id: string | null };
|
|
457
|
+
};
|
|
458
|
+
expect(b.gateway.configured).toBe(false);
|
|
459
|
+
expect(b.gateway.account_id_required).toBe(true);
|
|
460
|
+
expect(b.gateway.gateway_id).toBe("quinn-gw");
|
|
461
|
+
|
|
462
|
+
// Adding only the account id completes the migration.
|
|
463
|
+
const res = await configure(cookie, { account_id: USER_ACCT.toUpperCase() });
|
|
464
|
+
expect(res.status).toBe(200);
|
|
465
|
+
const prefs = (await res.json()) as { configured: boolean; account_id: string; account_id_required: boolean };
|
|
466
|
+
expect(prefs.configured).toBe(true);
|
|
467
|
+
expect(prefs.account_id).toBe(USER_ACCT); // normalized to lowercase
|
|
468
|
+
expect(prefs.account_id_required).toBe(false);
|
|
469
|
+
});
|
|
470
|
+
|
|
471
|
+
it("rejects a malformed account id or gateway slug with 400", async () => {
|
|
472
|
+
const cookie = await signup("rhea", "password123");
|
|
473
|
+
const badAcct = await configure(cookie, { account_id: "not-an-account" });
|
|
474
|
+
expect(badAcct.status).toBe(400);
|
|
475
|
+
expect(((await badAcct.json()) as { code: string }).code).toBe("invalid_account_id");
|
|
476
|
+
const badGw = await configure(cookie, { gateway_id: "../other-gw" });
|
|
477
|
+
expect(badGw.status).toBe(400);
|
|
478
|
+
expect(((await badGw.json()) as { code: string }).code).toBe("invalid_gateway_id");
|
|
479
|
+
});
|
|
480
|
+
|
|
481
|
+
it("account id without a token: 412 cf_aig_token_required", async () => {
|
|
482
|
+
const cookie = await signup("sven", "password123");
|
|
483
|
+
await configure(cookie, { account_id: USER_ACCT, gateway_id: "sven-gw" });
|
|
484
|
+
const res = await req("/api/chat", { method: "POST", cookie, body: { model: WORKERS_AI_CHAT, user_input: "hi" } });
|
|
485
|
+
expect(res.status).toBe(412);
|
|
486
|
+
expect(((await res.json()) as { code: string }).code).toBe("cf_aig_token_required");
|
|
487
|
+
});
|
|
488
|
+
|
|
489
|
+
it("legacy provider path dials gateway.ai.cloudflare.com under the USER's account id", async () => {
|
|
490
|
+
const cookie = await signup("tara", "password123");
|
|
491
|
+
await configure(cookie, { account_id: USER_ACCT, gateway_id: "tara-gw", cf_aig_token: "tara-token" });
|
|
492
|
+
const res = await req("/api/chat", { method: "POST", cookie, body: { model: LEGACY_ANTHROPIC, user_input: "hi" } });
|
|
493
|
+
expect(res.status).toBe(200);
|
|
494
|
+
expect(calls.length).toBe(1);
|
|
495
|
+
expect(calls[0].url).toBe(`https://gateway.ai.cloudflare.com/v1/${USER_ACCT}/tara-gw/anthropic/v1/messages`);
|
|
496
|
+
expect(calls[0].headers.get("cf-aig-authorization")).toBe("Bearer tara-token");
|
|
497
|
+
expect(calls[0].headers.get("x-api-key")).toBeNull();
|
|
498
|
+
});
|
|
499
|
+
|
|
500
|
+
it("binding-catalog path goes to the USER's account over REST, never the host binding", async () => {
|
|
501
|
+
const cookie = await signup("uma", "password123");
|
|
502
|
+
await configure(cookie, { account_id: USER_ACCT, gateway_id: "uma-gw", cf_aig_token: "uma-token" });
|
|
503
|
+
const res = await req("/api/chat", { method: "POST", cookie, body: { model: BINDING_ANTHROPIC, user_input: "hi" } });
|
|
504
|
+
expect(res.status).toBe(200);
|
|
505
|
+
expect(calls.length).toBe(1);
|
|
506
|
+
expect(calls[0].url).toBe(`https://api.cloudflare.com/client/v4/accounts/${USER_ACCT}/ai/run`);
|
|
507
|
+
expect(calls[0].headers.get("authorization")).toBe("Bearer uma-token");
|
|
508
|
+
expect(calls[0].headers.get("cf-aig-gateway-id")).toBe("uma-gw");
|
|
509
|
+
expect((JSON.parse(calls[0].body) as { model: string }).model).toBe(BINDING_ANTHROPIC);
|
|
510
|
+
});
|
|
511
|
+
|
|
512
|
+
it("Workers AI chat through aiRun also bills the USER's account (model-in-path)", async () => {
|
|
513
|
+
const cookie = await signup("vera", "password123");
|
|
514
|
+
await configure(cookie, { account_id: USER_ACCT, gateway_id: "vera-gw", cf_aig_token: "vera-token" });
|
|
515
|
+
await req("/api/chat", { method: "POST", cookie, body: { model: WORKERS_AI_CHAT, user_input: "hi" } });
|
|
516
|
+
expect(calls.length).toBe(1);
|
|
517
|
+
expect(calls[0].url).toBe(`https://api.cloudflare.com/client/v4/accounts/${USER_ACCT}/ai/run/${WORKERS_AI_CHAT}`);
|
|
518
|
+
expect(calls[0].headers.get("cf-aig-gateway-id")).toBe("vera-gw");
|
|
519
|
+
});
|
|
520
|
+
});
|
|
521
|
+
|
|
277
522
|
describe("DELETE /api/account cascade", () => {
|
|
278
523
|
it("requires password re-entry and cascades the account's data", async () => {
|
|
279
524
|
const cookie = await signup("mona", "password123");
|
|
@@ -369,3 +614,102 @@ describe("rate limiting", () => {
|
|
|
369
614
|
expect(row!.count).toBeGreaterThanOrEqual(5);
|
|
370
615
|
});
|
|
371
616
|
});
|
|
617
|
+
|
|
618
|
+
// prism#192 claim 1: the deletion cascade skipped conversation_compact, whose
|
|
619
|
+
// `summary` column is a model-written digest of the user's own chat turns.
|
|
620
|
+
// INSTANCE-PRIVACY.md says deletion "cascades ... we do not keep a shadow
|
|
621
|
+
// copy", so a surviving summary row contradicts the published notice.
|
|
622
|
+
describe("DELETE /api/account also cascades conversation_compact (prism#192)", () => {
|
|
623
|
+
it("removes the user's compact summaries, and leaves another user's alone", async () => {
|
|
624
|
+
const cookie = await signup("rosa", "password123", "203.0.113.61");
|
|
625
|
+
const userId = (
|
|
626
|
+
await env.DB.prepare(`SELECT id FROM users WHERE username_lc = 'rosa'`).first<{ id: string }>()
|
|
627
|
+
)!.id;
|
|
628
|
+
const otherCookie = await signup("sage", "password123", "203.0.113.62");
|
|
629
|
+
const otherId = (
|
|
630
|
+
await env.DB.prepare(`SELECT id FROM users WHERE username_lc = 'sage'`).first<{ id: string }>()
|
|
631
|
+
)!.id;
|
|
632
|
+
|
|
633
|
+
for (const [conv, who] of [["conv-rosa", userId], ["conv-sage", otherId]] as const) {
|
|
634
|
+
await env.DB.prepare(
|
|
635
|
+
`INSERT INTO conversation_compact
|
|
636
|
+
(conversation_id, user_email, summary, through_turn_index, model)
|
|
637
|
+
VALUES (?, ?, ?, 4, 'm')`,
|
|
638
|
+
)
|
|
639
|
+
.bind(conv, who, "a model-written digest of the user's earlier turns")
|
|
640
|
+
.run();
|
|
641
|
+
}
|
|
642
|
+
|
|
643
|
+
// Precondition: the row the cascade must remove really is there, so a later
|
|
644
|
+
// zero cannot be an insert that silently failed.
|
|
645
|
+
const before = await env.DB.prepare(
|
|
646
|
+
`SELECT COUNT(*) AS n FROM conversation_compact WHERE user_email = ?`,
|
|
647
|
+
).bind(userId).first<{ n: number }>();
|
|
648
|
+
expect(before!.n).toBe(1);
|
|
649
|
+
|
|
650
|
+
const del = await req("/api/account", { method: "DELETE", cookie, body: { password: "password123" } });
|
|
651
|
+
expect(del.status).toBe(200);
|
|
652
|
+
|
|
653
|
+
const after = await env.DB.prepare(
|
|
654
|
+
`SELECT COUNT(*) AS n FROM conversation_compact WHERE user_email = ?`,
|
|
655
|
+
).bind(userId).first<{ n: number }>();
|
|
656
|
+
expect(after!.n).toBe(0);
|
|
657
|
+
|
|
658
|
+
// Positive control: the cascade is scoped, not a table wipe. If this ever
|
|
659
|
+
// reads 0 the DELETE lost its WHERE clause and the test above would still
|
|
660
|
+
// pass, which is the reading that would prove the assertion worthless.
|
|
661
|
+
const survivor = await env.DB.prepare(
|
|
662
|
+
`SELECT COUNT(*) AS n FROM conversation_compact WHERE user_email = ?`,
|
|
663
|
+
).bind(otherId).first<{ n: number }>();
|
|
664
|
+
expect(survivor!.n).toBe(1);
|
|
665
|
+
expect((await boot(otherCookie)).authenticated).toBe(true);
|
|
666
|
+
});
|
|
667
|
+
});
|
|
668
|
+
|
|
669
|
+
// prism#192 claim 2: auth_attempts rows were pruned only by a successful login
|
|
670
|
+
// clearing its own bucket, so a signup bucket or a never-succeeding
|
|
671
|
+
// login:<ip>:<username> bucket persisted indefinitely. The notice heads that
|
|
672
|
+
// section "transient IP processing". There is no cron (`crons = []`) and no
|
|
673
|
+
// scheduled handler, so retention has to be an executed deletion on the write
|
|
674
|
+
// path, the same way src/routes/csp-report.ts does it.
|
|
675
|
+
describe("auth_attempts retention is pruned on write (prism#192)", () => {
|
|
676
|
+
it("drops a bucket older than the window and keeps a live one", async () => {
|
|
677
|
+
await signup("tess", "password123", "198.51.100.41");
|
|
678
|
+
|
|
679
|
+
// A stale bucket from an IP that never came back, aged past retention.
|
|
680
|
+
await env.DB.prepare(
|
|
681
|
+
`INSERT INTO auth_attempts (bucket_key, count, window_start)
|
|
682
|
+
VALUES ('signup:198.51.100.99', 7, datetime('now', '-30 days'))`,
|
|
683
|
+
).run();
|
|
684
|
+
// A bucket inside the retention window, which must SURVIVE. Without this
|
|
685
|
+
// the test would also pass if the prune deleted the whole table.
|
|
686
|
+
await env.DB.prepare(
|
|
687
|
+
`INSERT INTO auth_attempts (bucket_key, count, window_start)
|
|
688
|
+
VALUES ('signup:198.51.100.98', 3, datetime('now', '-10 minutes'))`,
|
|
689
|
+
).run();
|
|
690
|
+
|
|
691
|
+
const staleBefore = await env.DB.prepare(
|
|
692
|
+
`SELECT count FROM auth_attempts WHERE bucket_key = 'signup:198.51.100.99'`,
|
|
693
|
+
).first();
|
|
694
|
+
expect(staleBefore).not.toBeNull(); // the instrument can see the row it will look for
|
|
695
|
+
|
|
696
|
+
// Any subsequent limiter write is what performs the prune.
|
|
697
|
+
const res = await req("/api/auth/login", {
|
|
698
|
+
method: "POST",
|
|
699
|
+
body: { username: "tess", password: "wrongpassword" },
|
|
700
|
+
ip: "198.51.100.41",
|
|
701
|
+
});
|
|
702
|
+
expect([200, 401, 429]).toContain(res.status);
|
|
703
|
+
|
|
704
|
+
expect(
|
|
705
|
+
await env.DB.prepare(
|
|
706
|
+
`SELECT count FROM auth_attempts WHERE bucket_key = 'signup:198.51.100.99'`,
|
|
707
|
+
).first(),
|
|
708
|
+
).toBeNull();
|
|
709
|
+
expect(
|
|
710
|
+
await env.DB.prepare(
|
|
711
|
+
`SELECT count FROM auth_attempts WHERE bucket_key = 'signup:198.51.100.98'`,
|
|
712
|
+
).first(),
|
|
713
|
+
).not.toBeNull();
|
|
714
|
+
});
|
|
715
|
+
});
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
// PDF text extraction through the shipped extractPdfChunks, in workerd (the production runtime).
|
|
2
|
+
//
|
|
3
|
+
// WHY THIS EXISTS. extractPdfChunks (src/routes/rag.ts) is the only caller of unpdf, and it is what
|
|
4
|
+
// document upload, the zip import and the Discord import reach for every PDF. Until this file, no
|
|
5
|
+
// committed test exercised it: the suite only proved the module LOADS, because src/index.ts imports
|
|
6
|
+
// rag.ts, which imports unpdf. unpdf 1.8.1 -> 2.1.0 (a major, #221) was about to ship on that
|
|
7
|
+
// untested path, so this pins the behaviour prism depends on: per-page text, in page order, tagged
|
|
8
|
+
// with its 1-based page number.
|
|
9
|
+
//
|
|
10
|
+
// THE FIXTURE IS BUILT HERE, not committed as a binary: a minimal two-page PDF with one Helvetica
|
|
11
|
+
// text run per page and a correct xref, so the expected strings are visible in this file and nobody
|
|
12
|
+
// has to trust an opaque blob. Same shape as the probe measured before the v1.2.0 release.
|
|
13
|
+
|
|
14
|
+
import { describe, expect, it } from "vitest";
|
|
15
|
+
import { extractPdfChunks } from "../src/routes/rag";
|
|
16
|
+
|
|
17
|
+
const PAGE_TEXT = ["PRISMPROBE alpha page one", "PRISMPROBE beta page two"];
|
|
18
|
+
|
|
19
|
+
function minimalPdf(pages: string[]): Uint8Array {
|
|
20
|
+
const objs: string[] = [];
|
|
21
|
+
objs.push("<< /Type /Catalog /Pages 2 0 R >>");
|
|
22
|
+
const kids = pages.map((_, i) => `${3 + i * 2} 0 R`).join(" ");
|
|
23
|
+
objs.push(`<< /Type /Pages /Kids [${kids}] /Count ${pages.length} >>`);
|
|
24
|
+
const fontNum = 3 + pages.length * 2;
|
|
25
|
+
pages.forEach((text, i) => {
|
|
26
|
+
objs.push(
|
|
27
|
+
`<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Contents ${4 + i * 2} 0 R ` +
|
|
28
|
+
`/Resources << /Font << /F1 ${fontNum} 0 R >> >> >>`,
|
|
29
|
+
);
|
|
30
|
+
const stream = `BT /F1 24 Tf 72 700 Td (${text}) Tj ET`;
|
|
31
|
+
objs.push(`<< /Length ${stream.length} >>\nstream\n${stream}\nendstream`);
|
|
32
|
+
});
|
|
33
|
+
objs.push("<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>");
|
|
34
|
+
|
|
35
|
+
// ASCII only, so string length is byte length and the xref offsets are exact.
|
|
36
|
+
let out = "%PDF-1.4\n";
|
|
37
|
+
const offsets: number[] = [];
|
|
38
|
+
objs.forEach((body, n) => {
|
|
39
|
+
offsets.push(out.length);
|
|
40
|
+
out += `${n + 1} 0 obj\n${body}\nendobj\n`;
|
|
41
|
+
});
|
|
42
|
+
const xref = out.length;
|
|
43
|
+
out += `xref\n0 ${objs.length + 1}\n0000000000 65535 f \n`;
|
|
44
|
+
for (const off of offsets) out += `${String(off).padStart(10, "0")} 00000 n \n`;
|
|
45
|
+
out += `trailer\n<< /Size ${objs.length + 1} /Root 1 0 R >>\nstartxref\n${xref}\n%%EOF\n`;
|
|
46
|
+
return new TextEncoder().encode(out);
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
describe("extractPdfChunks (unpdf), in workerd", () => {
|
|
50
|
+
it("extracts each page's text in order, tagged with its 1-based page number", async () => {
|
|
51
|
+
const chunks = await extractPdfChunks(minimalPdf(PAGE_TEXT));
|
|
52
|
+
expect(chunks).toEqual([
|
|
53
|
+
{ text: PAGE_TEXT[0], page: 1 },
|
|
54
|
+
{ text: PAGE_TEXT[1], page: 2 },
|
|
55
|
+
]);
|
|
56
|
+
});
|
|
57
|
+
|
|
58
|
+
it("skips a page with no text layer instead of emitting an empty chunk", async () => {
|
|
59
|
+
// The middle page draws nothing: an empty text layer, the shape of a scanned page.
|
|
60
|
+
const pdf = minimalPdf([PAGE_TEXT[0], "", PAGE_TEXT[1]]);
|
|
61
|
+
const chunks = await extractPdfChunks(pdf);
|
|
62
|
+
expect(chunks).toEqual([
|
|
63
|
+
{ text: PAGE_TEXT[0], page: 1 },
|
|
64
|
+
{ text: PAGE_TEXT[1], page: 3 },
|
|
65
|
+
]);
|
|
66
|
+
});
|
|
67
|
+
|
|
68
|
+
it("rejects bytes that are not a PDF, rather than returning an empty success", async () => {
|
|
69
|
+
await expect(extractPdfChunks(new TextEncoder().encode("not a pdf at all"))).rejects.toThrow();
|
|
70
|
+
});
|
|
71
|
+
});
|
|
@@ -46,10 +46,26 @@ bucket_name = "skyphusion-llm"
|
|
|
46
46
|
# @cf/baai/bge-base-en-v1.5; cosine similarity.
|
|
47
47
|
# Create with:
|
|
48
48
|
# npx wrangler vectorize create skyphusion-llm-vec --dimensions=768 --metric=cosine
|
|
49
|
+
# npx wrangler vectorize create-metadata-index skyphusion-llm-vec --property-name=user_email --type=string
|
|
50
|
+
# The metadata index lets retrieval filter by user in Vectorize itself
|
|
51
|
+
# (VEC_METADATA_FILTER, below). Create it before the first document upload: an
|
|
52
|
+
# index added later does not cover vectors already written. See MIGRATIONS.md.
|
|
49
53
|
[[vectorize]]
|
|
50
54
|
binding = "VEC"
|
|
51
55
|
index_name = "skyphusion-llm-vec"
|
|
52
56
|
|
|
57
|
+
# Opt-in web search. Service binding to the skyphusion-search Worker,
|
|
58
|
+
# named entrypoint SearchEntrypoint, method search(question). Source
|
|
59
|
+
# repo skyphusion-labs/search-mcp. This is not POST /ask: that route
|
|
60
|
+
# checks Origin and Turnstile. Self-hosters who do not run that worker
|
|
61
|
+
# delete this block: wrangler deploy fails when the named service does
|
|
62
|
+
# not exist. With the binding absent, that source reports status
|
|
63
|
+
# "absent" and Wikipedia still runs.
|
|
64
|
+
[[services]]
|
|
65
|
+
binding = "SEARCH"
|
|
66
|
+
service = "skyphusion-search"
|
|
67
|
+
entrypoint = "SearchEntrypoint"
|
|
68
|
+
|
|
53
69
|
# Static frontend (HTML, CSS, JS).
|
|
54
70
|
[assets]
|
|
55
71
|
directory = "./public"
|
|
@@ -165,6 +181,10 @@ enabled = true
|
|
|
165
181
|
# commented vars header (CI uncomments every "# [vars]" line and TOML breaks).
|
|
166
182
|
# CONTROL_PLANE_URL = "https://play-proxy.skyphusion.org"
|
|
167
183
|
# CONTROL_PLANE_ALLOW_LOCALHOST = "true"
|
|
184
|
+
# RAG retrieval filtered by user in Vectorize (fleet-chezmoi#1636). Off unless
|
|
185
|
+
# "on". Needs the user_email metadata index AND, on an index that already holds
|
|
186
|
+
# vectors, scripts/vectorize-backfill-metadata.mjs run after it. See MIGRATIONS.md.
|
|
187
|
+
# VEC_METADATA_FILTER = "on"
|
|
168
188
|
|
|
169
189
|
# Note: GATEWAY_ID is set as a worker secret rather than a var in this file
|
|
170
190
|
# (v0.12.0+). This keeps deployer-specific values out of the committed template.
|
|
@@ -174,8 +194,10 @@ enabled = true
|
|
|
174
194
|
# GATEWAY_ID=your-gateway-slug
|
|
175
195
|
#
|
|
176
196
|
# Public mode (v0.167.0+): omit GATEWAY_ID and CF_AIG_TOKEN on the worker.
|
|
177
|
-
# Each visitor stores their own gateway slug
|
|
178
|
-
# (/api/prefs in D1 user_prefs).
|
|
197
|
+
# Each visitor stores their own Cloudflare account id, gateway slug, and token
|
|
198
|
+
# via Account > AI Gateway (/api/prefs in D1 user_prefs); v1.1.0 requires the
|
|
199
|
+
# account id, since the AI binding can only reach this worker's own account.
|
|
200
|
+
# No Cloudflare Access needed when AUTH_MODE=public.
|
|
179
201
|
#
|
|
180
202
|
# Other worker secrets (also set via `npx wrangler secret put <NAME>`):
|
|
181
203
|
# OPENAI_API_KEY (optional sole BYOK carve-out, v0.174.0): when set,
|
|
@@ -185,12 +207,5 @@ enabled = true
|
|
|
185
207
|
# CF_AIG_TOKEN (required for Anthropic, xAI, OpenAI chat, Google, and proxied
|
|
186
208
|
# image/video/music on Unified Billing when using worker-level
|
|
187
209
|
# credentials; optional in public demo mode where users supply
|
|
188
|
-
# their own token via /api/prefs; v0.93.0+)
|
|
189
|
-
#
|
|
190
|
-
# for the opt-in web-search source, e.g. https://search.skyphusion.org.
|
|
191
|
-
# May be a plain [vars] entry instead of a secret. Skipped when
|
|
192
|
-
# unset; Wikipedia still runs keyless),
|
|
193
|
-
# SEARXNG_ACCESS_CLIENT_ID / SEARXNG_ACCESS_CLIENT_SECRET (optional, v0.166.0;
|
|
194
|
-
# Cloudflare Access service-token halves for a gated SearXNG
|
|
195
|
-
# instance. Sent as CF-Access-Client-Id / CF-Access-Client-Secret
|
|
196
|
-
# only when BOTH are set; leave unset for an un-gated instance).
|
|
210
|
+
# their own token via /api/prefs; v0.93.0+).
|
|
211
|
+
# Web search uses the SEARCH service binding above. It does not take a secret.
|
package/template/src/searxng.ts
DELETED
|
@@ -1,75 +0,0 @@
|
|
|
1
|
-
// SearXNG web retrieval (v0.166.0).
|
|
2
|
-
//
|
|
3
|
-
// Self-hosted metasearch source, slotted in beside the keyless Wikipedia
|
|
4
|
-
// retriever (replacing the retired Tavily + Brave SaaS sources, prism#93).
|
|
5
|
-
// Requests the JSON API: GET {SEARXNG_URL}/search?q=...&format=json.
|
|
6
|
-
//
|
|
7
|
-
// When the instance is gated by Cloudflare Access (our deploy at
|
|
8
|
-
// search.skyphusion.org is), a per-function Access service token is sent as
|
|
9
|
-
// the standard CF-Access-Client-Id / CF-Access-Client-Secret headers. A
|
|
10
|
-
// self-hoster running an un-gated instance sets neither, and no Access headers
|
|
11
|
-
// are sent.
|
|
12
|
-
|
|
13
|
-
export interface SearxngHit {
|
|
14
|
-
title: string;
|
|
15
|
-
url: string;
|
|
16
|
-
snippet: string;
|
|
17
|
-
}
|
|
18
|
-
|
|
19
|
-
// Pure parser for the SearXNG JSON response. The relevant shape is
|
|
20
|
-
// { results: [ { url, title, content }, ... ] }; other top-level keys
|
|
21
|
-
// (query, number_of_results, suggestions, ...) are ignored. Rows missing a
|
|
22
|
-
// url or title are dropped; content is the snippet (may be absent).
|
|
23
|
-
export function mapSearxngResults(data: unknown, maxResults: number): SearxngHit[] {
|
|
24
|
-
const root = data as {
|
|
25
|
-
results?: Array<{ title?: string; url?: string; content?: string }>;
|
|
26
|
-
};
|
|
27
|
-
const items = root.results ?? [];
|
|
28
|
-
return items
|
|
29
|
-
.filter((r) => r.url && r.title)
|
|
30
|
-
.slice(0, maxResults)
|
|
31
|
-
.map((r) => ({
|
|
32
|
-
title: r.title!,
|
|
33
|
-
url: r.url!,
|
|
34
|
-
snippet: normalizeSearxngSnippet(r.content ?? ""),
|
|
35
|
-
}));
|
|
36
|
-
}
|
|
37
|
-
|
|
38
|
-
function normalizeSearxngSnippet(text: string): string {
|
|
39
|
-
return text.replace(/\s+/g, " ").trim();
|
|
40
|
-
}
|
|
41
|
-
|
|
42
|
-
export async function searchSearxngWeb(
|
|
43
|
-
baseUrl: string,
|
|
44
|
-
query: string,
|
|
45
|
-
opts: {
|
|
46
|
-
maxResults: number;
|
|
47
|
-
timeoutMs: number;
|
|
48
|
-
accessClientId?: string;
|
|
49
|
-
accessClientSecret?: string;
|
|
50
|
-
},
|
|
51
|
-
): Promise<SearxngHit[]> {
|
|
52
|
-
// baseUrl may or may not carry a trailing slash; URL() with an absolute
|
|
53
|
-
// "/search" path normalizes either way.
|
|
54
|
-
const url = new URL("/search", baseUrl);
|
|
55
|
-
url.searchParams.set("q", query);
|
|
56
|
-
url.searchParams.set("format", "json");
|
|
57
|
-
|
|
58
|
-
const headers: Record<string, string> = { Accept: "application/json" };
|
|
59
|
-
// Access service-token headers are sent ONLY when both halves are set, so an
|
|
60
|
-
// un-gated self-hosted instance is reached with no headers.
|
|
61
|
-
if (opts.accessClientId && opts.accessClientSecret) {
|
|
62
|
-
headers["CF-Access-Client-Id"] = opts.accessClientId;
|
|
63
|
-
headers["CF-Access-Client-Secret"] = opts.accessClientSecret;
|
|
64
|
-
}
|
|
65
|
-
|
|
66
|
-
const resp = await fetch(url.toString(), {
|
|
67
|
-
headers,
|
|
68
|
-
signal: AbortSignal.timeout(opts.timeoutMs),
|
|
69
|
-
});
|
|
70
|
-
if (!resp.ok) {
|
|
71
|
-
throw new Error(`SearXNG ${resp.status}: ${(await resp.text()).slice(0, 200)}`);
|
|
72
|
-
}
|
|
73
|
-
const data: unknown = await resp.json();
|
|
74
|
-
return mapSearxngResults(data, opts.maxResults);
|
|
75
|
-
}
|
|
@@ -1,51 +0,0 @@
|
|
|
1
|
-
import { describe, it, expect } from "vitest";
|
|
2
|
-
import { mapSearxngResults } from "../src/searxng";
|
|
3
|
-
|
|
4
|
-
describe("mapSearxngResults", () => {
|
|
5
|
-
it("maps results into title/url/snippet hits", () => {
|
|
6
|
-
const data = {
|
|
7
|
-
query: "cloudflare workers",
|
|
8
|
-
number_of_results: 2,
|
|
9
|
-
results: [
|
|
10
|
-
{ title: "Example", url: "https://example.com/a", content: "First hit." },
|
|
11
|
-
{ title: "Other", url: "https://example.com/b", content: "Second hit." },
|
|
12
|
-
],
|
|
13
|
-
};
|
|
14
|
-
expect(mapSearxngResults(data, 5)).toEqual([
|
|
15
|
-
{ title: "Example", url: "https://example.com/a", snippet: "First hit." },
|
|
16
|
-
{ title: "Other", url: "https://example.com/b", snippet: "Second hit." },
|
|
17
|
-
]);
|
|
18
|
-
});
|
|
19
|
-
|
|
20
|
-
it("drops rows missing title or url and respects maxResults", () => {
|
|
21
|
-
const data = {
|
|
22
|
-
results: [
|
|
23
|
-
{ title: "Keep", url: "https://example.com/keep", content: "ok" },
|
|
24
|
-
{ title: "No URL", content: "skip" },
|
|
25
|
-
{ url: "https://example.com/no-title", content: "skip" },
|
|
26
|
-
{ title: "Third", url: "https://example.com/third", content: "ok" },
|
|
27
|
-
],
|
|
28
|
-
};
|
|
29
|
-
expect(mapSearxngResults(data, 1)).toEqual([
|
|
30
|
-
{ title: "Keep", url: "https://example.com/keep", snippet: "ok" },
|
|
31
|
-
]);
|
|
32
|
-
});
|
|
33
|
-
|
|
34
|
-
it("collapses whitespace in snippets and tolerates a missing content field", () => {
|
|
35
|
-
const data = {
|
|
36
|
-
results: [
|
|
37
|
-
{ title: "Spacey", url: "https://example.com/s", content: " multi line\n\ttext " },
|
|
38
|
-
{ title: "NoContent", url: "https://example.com/n" },
|
|
39
|
-
],
|
|
40
|
-
};
|
|
41
|
-
expect(mapSearxngResults(data, 5)).toEqual([
|
|
42
|
-
{ title: "Spacey", url: "https://example.com/s", snippet: "multi line text" },
|
|
43
|
-
{ title: "NoContent", url: "https://example.com/n", snippet: "" },
|
|
44
|
-
]);
|
|
45
|
-
});
|
|
46
|
-
|
|
47
|
-
it("returns an empty array when results is missing", () => {
|
|
48
|
-
expect(mapSearxngResults({}, 5)).toEqual([]);
|
|
49
|
-
expect(mapSearxngResults({ results: [] }, 5)).toEqual([]);
|
|
50
|
-
});
|
|
51
|
-
});
|