@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
|
@@ -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
|
-
//
|
|
377
|
-
//
|
|
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(/\.
|
|
409
|
-
expect(css).toMatch(/\.
|
|
410
|
-
expect(pub("index.html")).toContain('class="
|
|
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
|
|
|
@@ -2,7 +2,10 @@ import { describe, expect, it } from "vitest";
|
|
|
2
2
|
import {
|
|
3
3
|
buildGatewayStatus,
|
|
4
4
|
gatewaySource,
|
|
5
|
+
isValidGatewayId,
|
|
5
6
|
maskSecret,
|
|
7
|
+
normalizeAccountId,
|
|
8
|
+
resolveGateway,
|
|
6
9
|
resolveGatewayFromParts,
|
|
7
10
|
} from "../src/gateway-credentials";
|
|
8
11
|
import type { Env } from "../src/env";
|
|
@@ -24,7 +27,7 @@ describe("resolveGatewayFromParts", () => {
|
|
|
24
27
|
{ gateway_id: "user-gw", cf_aig_token: "user-token" },
|
|
25
28
|
env({ GATEWAY_ID: "worker-gw", CF_AIG_TOKEN: "worker-token" }),
|
|
26
29
|
);
|
|
27
|
-
expect(resolved).toEqual({ gatewayId: "user-gw", cfAigToken: "user-token" });
|
|
30
|
+
expect(resolved).toEqual({ gatewayId: "user-gw", cfAigToken: "user-token", accountId: null });
|
|
28
31
|
});
|
|
29
32
|
|
|
30
33
|
it("falls back to worker secrets for unset user fields", () => {
|
|
@@ -32,7 +35,7 @@ describe("resolveGatewayFromParts", () => {
|
|
|
32
35
|
{ gateway_id: "user-gw" },
|
|
33
36
|
env({ GATEWAY_ID: "worker-gw", CF_AIG_TOKEN: "worker-token" }),
|
|
34
37
|
);
|
|
35
|
-
expect(resolved).toEqual({ gatewayId: "user-gw", cfAigToken: "worker-token" });
|
|
38
|
+
expect(resolved).toEqual({ gatewayId: "user-gw", cfAigToken: "worker-token", accountId: null });
|
|
36
39
|
});
|
|
37
40
|
});
|
|
38
41
|
|
|
@@ -75,7 +78,7 @@ describe("buildGatewayStatus", () => {
|
|
|
75
78
|
expect(s.control_plane_key_set).toBe(false);
|
|
76
79
|
});
|
|
77
80
|
|
|
78
|
-
it("counts gateway id alone as configured (
|
|
81
|
+
it("access mode: counts gateway id alone as configured (host-account binding)", () => {
|
|
79
82
|
const s = buildGatewayStatus({ gateway_id: "my-gw" }, env());
|
|
80
83
|
expect(s.configured).toBe(true);
|
|
81
84
|
expect(s.gateway_id).toBe("my-gw");
|
|
@@ -100,3 +103,98 @@ describe("buildGatewayStatus", () => {
|
|
|
100
103
|
expect(s.control_plane_key_set).toBe(true);
|
|
101
104
|
});
|
|
102
105
|
});
|
|
106
|
+
|
|
107
|
+
// v1.1.0: the account id is what routes a call to the user's own gateway. The
|
|
108
|
+
// AI binding can only reach this worker's account, so user credentials without
|
|
109
|
+
// one must never resolve in public mode.
|
|
110
|
+
const ACCT = "0123456789abcdef0123456789abcdef";
|
|
111
|
+
const PUBLIC = { AUTH_MODE: "public" } as Partial<Env>;
|
|
112
|
+
|
|
113
|
+
describe("normalizeAccountId / isValidGatewayId", () => {
|
|
114
|
+
it("accepts 32 hex and lowercases", () => {
|
|
115
|
+
expect(normalizeAccountId(ACCT)).toBe(ACCT);
|
|
116
|
+
expect(normalizeAccountId(` ${ACCT.toUpperCase()} `)).toBe(ACCT);
|
|
117
|
+
});
|
|
118
|
+
|
|
119
|
+
it("rejects anything that is not 32 hex", () => {
|
|
120
|
+
for (const bad of ["", "abc", ACCT + "0", ACCT.slice(1) + "g", "../" + ACCT.slice(3), null, undefined]) {
|
|
121
|
+
expect(normalizeAccountId(bad as string)).toBeNull();
|
|
122
|
+
}
|
|
123
|
+
});
|
|
124
|
+
|
|
125
|
+
it("pins the gateway slug charset (it becomes a URL segment and a header)", () => {
|
|
126
|
+
expect(isValidGatewayId("my-gw_1")).toBe(true);
|
|
127
|
+
for (const bad of ["", "../other", "a/b", "gw?x=1", "-lead", "a".repeat(65), "gw\r\nx: y"]) {
|
|
128
|
+
expect(isValidGatewayId(bad)).toBe(false);
|
|
129
|
+
}
|
|
130
|
+
});
|
|
131
|
+
});
|
|
132
|
+
|
|
133
|
+
describe("resolveGateway (v1.1.0 account scoping)", () => {
|
|
134
|
+
it("public mode: slug + token without an account id is refused, not resolved on our binding", () => {
|
|
135
|
+
const r = resolveGateway({ gateway_id: "gw", cf_aig_token: "tok" }, env(PUBLIC));
|
|
136
|
+
expect(r.creds).toBeNull();
|
|
137
|
+
expect(r.problem).toBe("gateway_account_id_required");
|
|
138
|
+
});
|
|
139
|
+
|
|
140
|
+
it("public mode: a lone slug (the pre-v1.1.0 minimum) is also account_id_required", () => {
|
|
141
|
+
expect(resolveGateway({ gateway_id: "gw" }, env(PUBLIC)).problem).toBe("gateway_account_id_required");
|
|
142
|
+
});
|
|
143
|
+
|
|
144
|
+
it("public mode: nothing saved is plain not-configured", () => {
|
|
145
|
+
expect(resolveGateway(null, env(PUBLIC)).problem).toBe("gateway_not_configured");
|
|
146
|
+
});
|
|
147
|
+
|
|
148
|
+
it("resolves full user credentials to the user's account", () => {
|
|
149
|
+
const r = resolveGateway({ account_id: ACCT, gateway_id: "gw", cf_aig_token: "tok" }, env(PUBLIC));
|
|
150
|
+
expect(r).toEqual({ creds: { gatewayId: "gw", cfAigToken: "tok", accountId: ACCT }, problem: null });
|
|
151
|
+
});
|
|
152
|
+
|
|
153
|
+
it("requires the token once an account id is set (REST needs it for every call)", () => {
|
|
154
|
+
const r = resolveGateway({ account_id: ACCT, gateway_id: "gw" }, env(PUBLIC));
|
|
155
|
+
expect(r.problem).toBe("cf_aig_token_required");
|
|
156
|
+
});
|
|
157
|
+
|
|
158
|
+
it("requires the slug once an account id is set", () => {
|
|
159
|
+
const r = resolveGateway({ account_id: ACCT, cf_aig_token: "tok" }, env(PUBLIC));
|
|
160
|
+
expect(r.problem).toBe("gateway_not_configured");
|
|
161
|
+
});
|
|
162
|
+
|
|
163
|
+
it("access mode: an account-scoped user never borrows worker secrets", () => {
|
|
164
|
+
const r = resolveGateway(
|
|
165
|
+
{ account_id: ACCT, gateway_id: "gw" },
|
|
166
|
+
env({ GATEWAY_ID: "worker-gw", CF_AIG_TOKEN: "worker-token" }),
|
|
167
|
+
);
|
|
168
|
+
expect(r.creds).toBeNull();
|
|
169
|
+
expect(r.problem).toBe("cf_aig_token_required");
|
|
170
|
+
});
|
|
171
|
+
|
|
172
|
+
it("an invalid stored account id is treated as absent (public: refused)", () => {
|
|
173
|
+
const r = resolveGateway({ account_id: "nope", gateway_id: "gw", cf_aig_token: "tok" }, env(PUBLIC));
|
|
174
|
+
expect(r.problem).toBe("gateway_account_id_required");
|
|
175
|
+
});
|
|
176
|
+
});
|
|
177
|
+
|
|
178
|
+
describe("buildGatewayStatus (v1.1.0)", () => {
|
|
179
|
+
it("flags a pre-v1.1.0 public user and still echoes their saved slug", () => {
|
|
180
|
+
const s = buildGatewayStatus({ gateway_id: "gw", cf_aig_token: "tok" }, env(PUBLIC));
|
|
181
|
+
expect(s.configured).toBe(false);
|
|
182
|
+
expect(s.account_id_required).toBe(true);
|
|
183
|
+
expect(s.gateway_id).toBe("gw");
|
|
184
|
+
expect(s.cf_aig_token_set).toBe(true);
|
|
185
|
+
expect(s.account_id).toBeNull();
|
|
186
|
+
});
|
|
187
|
+
|
|
188
|
+
it("is configured with all three, account id echoed", () => {
|
|
189
|
+
const s = buildGatewayStatus({ account_id: ACCT, gateway_id: "gw", cf_aig_token: "tok" }, env(PUBLIC));
|
|
190
|
+
expect(s.configured).toBe(true);
|
|
191
|
+
expect(s.account_id_required).toBe(false);
|
|
192
|
+
expect(s.account_id).toBe(ACCT);
|
|
193
|
+
});
|
|
194
|
+
|
|
195
|
+
it("a pcp_ key alone still configures a pre-v1.1.0 user (chat via control plane)", () => {
|
|
196
|
+
const s = buildGatewayStatus({ gateway_id: "gw", control_plane_key: VALID_PCP }, env(PUBLIC));
|
|
197
|
+
expect(s.configured).toBe(true);
|
|
198
|
+
expect(s.account_id_required).toBe(true);
|
|
199
|
+
});
|
|
200
|
+
});
|
|
@@ -2,7 +2,8 @@
|
|
|
2
2
|
// Network is stubbed; we only assert the request OpenAI receives.
|
|
3
3
|
|
|
4
4
|
import { describe, it, expect, vi, afterEach } from "vitest";
|
|
5
|
-
import { generateOpenAIImage } from "../src/providers/openai-image";
|
|
5
|
+
import { generateOpenAIImage, resolveOpenAIImageKey } from "../src/providers/openai-image";
|
|
6
|
+
import type { Env } from "../src/env";
|
|
6
7
|
|
|
7
8
|
afterEach(() => {
|
|
8
9
|
vi.unstubAllGlobals();
|
|
@@ -45,3 +46,22 @@ describe("generateOpenAIImage", () => {
|
|
|
45
46
|
.rejects.toThrow(/OpenAI image API 429: billing hard limit/);
|
|
46
47
|
});
|
|
47
48
|
});
|
|
49
|
+
|
|
50
|
+
// prism#193 (v1.0.5): the deployer key is off-limits in public mode.
|
|
51
|
+
describe("resolveOpenAIImageKey", () => {
|
|
52
|
+
const envOf = (e: Partial<Env>) => e as Env;
|
|
53
|
+
|
|
54
|
+
it("returns null in public mode even when OPENAI_API_KEY is set", () => {
|
|
55
|
+
expect(resolveOpenAIImageKey(envOf({ AUTH_MODE: "public", OPENAI_API_KEY: "sk-host" }))).toBeNull();
|
|
56
|
+
});
|
|
57
|
+
|
|
58
|
+
it("returns the key in access mode and when AUTH_MODE is unset", () => {
|
|
59
|
+
expect(resolveOpenAIImageKey(envOf({ AUTH_MODE: "access", OPENAI_API_KEY: "sk-host" }))).toBe("sk-host");
|
|
60
|
+
expect(resolveOpenAIImageKey(envOf({ OPENAI_API_KEY: "sk-host" }))).toBe("sk-host");
|
|
61
|
+
});
|
|
62
|
+
|
|
63
|
+
it("returns null when the key is unset or blank", () => {
|
|
64
|
+
expect(resolveOpenAIImageKey(envOf({}))).toBeNull();
|
|
65
|
+
expect(resolveOpenAIImageKey(envOf({ OPENAI_API_KEY: " " }))).toBeNull();
|
|
66
|
+
});
|
|
67
|
+
});
|
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
// VEC_METADATA_FILTER: retrieval filtered by user in Vectorize itself (skyphusion-labs/fleet-chezmoi#1636).
|
|
2
|
+
//
|
|
3
|
+
// THE DEFECT. With a global Vectorize query, a caller holding a small share of a large index can get a
|
|
4
|
+
// top-K made entirely of other users' vectors. The D1 join (the tenant scope) drops all of them, and the
|
|
5
|
+
// caller sees nothing even though their own document matches. The flag filters the query on user_email.
|
|
6
|
+
//
|
|
7
|
+
// The fake index below HONOURS the filter the way Vectorize does: unfiltered, it returns the global
|
|
8
|
+
// top-K; filtered, only vectors whose metadata matches. The fake D1 honours the join's user_email
|
|
9
|
+
// scope. Only env.AI / env.VEC / env.DB are stubbed; retrieveContext is the shipped function.
|
|
10
|
+
|
|
11
|
+
import { describe, it, expect, vi, afterEach } from "vitest";
|
|
12
|
+
import { retrieveContext, vecMetadataFilterOn } from "../src/routes/rag";
|
|
13
|
+
import type { Env } from "../src/env";
|
|
14
|
+
|
|
15
|
+
const CALLER = "usr_0123456789abcdef01234567";
|
|
16
|
+
const STRANGER = "usr_fedcba9876543210fedcba98";
|
|
17
|
+
|
|
18
|
+
interface StoredVector {
|
|
19
|
+
id: string;
|
|
20
|
+
score: number;
|
|
21
|
+
owner: string;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** Five foreign vectors scoring above the caller's one: the crowding shape. */
|
|
25
|
+
const CROWDED: StoredVector[] = [
|
|
26
|
+
...[0, 1, 2, 3, 4].map((i) => ({ id: `${STRANGER}:9:${i}`, score: 0.95 - i * 0.01, owner: STRANGER })),
|
|
27
|
+
{ id: `${CALLER}:1:0`, score: 0.6, owner: CALLER },
|
|
28
|
+
];
|
|
29
|
+
|
|
30
|
+
type QueryOpts = { topK: number; filter?: Record<string, string> };
|
|
31
|
+
|
|
32
|
+
function fakeEnv(index: StoredVector[], flag?: string) {
|
|
33
|
+
const queries: QueryOpts[] = [];
|
|
34
|
+
const joinSql: string[] = [];
|
|
35
|
+
const env = {
|
|
36
|
+
VEC_METADATA_FILTER: flag,
|
|
37
|
+
AI: { run: async () => ({ shape: [1, 3], data: [[0.1, 0.2, 0.3]] }) },
|
|
38
|
+
VEC: {
|
|
39
|
+
query: async (_v: number[], opts: QueryOpts) => {
|
|
40
|
+
queries.push(opts);
|
|
41
|
+
const pool = opts.filter ? index.filter((v) => v.owner === opts.filter!.user_email) : index;
|
|
42
|
+
const top = [...pool].sort((a, b) => b.score - a.score).slice(0, opts.topK);
|
|
43
|
+
return { matches: top.map((v) => ({ id: v.id, score: v.score })) };
|
|
44
|
+
},
|
|
45
|
+
},
|
|
46
|
+
DB: {
|
|
47
|
+
prepare(sql: string) {
|
|
48
|
+
const isPrefs = sql.includes("user_prefs");
|
|
49
|
+
if (!isPrefs) joinSql.push(sql);
|
|
50
|
+
return {
|
|
51
|
+
bind(...args: unknown[]) {
|
|
52
|
+
return {
|
|
53
|
+
async first() {
|
|
54
|
+
return isPrefs ? { prefs_json: JSON.stringify({ gateway_id: "gw" }) } : null;
|
|
55
|
+
},
|
|
56
|
+
async all() {
|
|
57
|
+
// The tenant scope: only the bound user_email's own vectors join.
|
|
58
|
+
const user = args[0] as string;
|
|
59
|
+
const ids = args.slice(1) as string[];
|
|
60
|
+
const rows = index
|
|
61
|
+
.filter((v) => v.owner === user && ids.includes(v.id))
|
|
62
|
+
.map((v) => ({ document_id: 1, chunk_index: 0, text: "own text", vector_id: v.id, filename: "own.txt", page: null, sheet: null }));
|
|
63
|
+
return { results: rows };
|
|
64
|
+
},
|
|
65
|
+
};
|
|
66
|
+
},
|
|
67
|
+
};
|
|
68
|
+
},
|
|
69
|
+
},
|
|
70
|
+
} as unknown as Env;
|
|
71
|
+
return { env, queries, joinSql };
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
afterEach(() => vi.restoreAllMocks());
|
|
75
|
+
|
|
76
|
+
describe("vecMetadataFilterOn", () => {
|
|
77
|
+
it("is on only for an explicit on / 1 / true", () => {
|
|
78
|
+
for (const v of ["on", "1", "true", " ON "]) expect(vecMetadataFilterOn({ VEC_METADATA_FILTER: v }), v).toBe(true);
|
|
79
|
+
for (const v of [undefined, "", "off", "0", "yes", "false"]) expect(vecMetadataFilterOn({ VEC_METADATA_FILTER: v }), String(v)).toBe(false);
|
|
80
|
+
});
|
|
81
|
+
});
|
|
82
|
+
|
|
83
|
+
describe("retrieveContext with VEC_METADATA_FILTER", () => {
|
|
84
|
+
it("OFF (the default): the query is global, and the D1 join still scopes", async () => {
|
|
85
|
+
vi.spyOn(console, "warn").mockImplementation(() => {});
|
|
86
|
+
const { env, queries, joinSql } = fakeEnv(CROWDED);
|
|
87
|
+
await retrieveContext(env, CALLER, "q");
|
|
88
|
+
expect(queries).toHaveLength(1);
|
|
89
|
+
expect(queries[0].filter).toBeUndefined();
|
|
90
|
+
expect(joinSql.some((s) => s.includes("c.user_email = ?"))).toBe(true);
|
|
91
|
+
});
|
|
92
|
+
|
|
93
|
+
it("ON: the query carries filter { user_email: caller }, and the D1 join still scopes", async () => {
|
|
94
|
+
const { env, queries, joinSql } = fakeEnv(CROWDED, "on");
|
|
95
|
+
await retrieveContext(env, CALLER, "q");
|
|
96
|
+
expect(queries[0].filter).toEqual({ user_email: CALLER });
|
|
97
|
+
expect(joinSql.some((s) => s.includes("c.user_email = ?"))).toBe(true);
|
|
98
|
+
});
|
|
99
|
+
|
|
100
|
+
it("THE DEFECT, OFF: a crowded index gives the caller nothing although their own vector matches", async () => {
|
|
101
|
+
vi.spyOn(console, "warn").mockImplementation(() => {});
|
|
102
|
+
const { env } = fakeEnv(CROWDED);
|
|
103
|
+
const { chunks } = await retrieveContext(env, CALLER, "q");
|
|
104
|
+
expect(chunks).toEqual([]);
|
|
105
|
+
});
|
|
106
|
+
|
|
107
|
+
it("POSITIVE, ON: the same crowded index returns the caller's own chunk", async () => {
|
|
108
|
+
const { env } = fakeEnv(CROWDED, "on");
|
|
109
|
+
const { chunks } = await retrieveContext(env, CALLER, "q");
|
|
110
|
+
expect(chunks.map((c) => c.filename)).toEqual(["own.txt"]);
|
|
111
|
+
});
|
|
112
|
+
|
|
113
|
+
it("NEGATIVE CONTROL, ON: a caller who owns nothing gets nothing, and no foreign vector is returned", async () => {
|
|
114
|
+
const nobody = "usr_000000000000000000000000";
|
|
115
|
+
const { env, queries } = fakeEnv(CROWDED, "on");
|
|
116
|
+
const query = env.VEC.query.bind(env.VEC);
|
|
117
|
+
let seen: { id: string }[] = [];
|
|
118
|
+
(env.VEC as unknown as { query: typeof query }).query = async (v, o) => {
|
|
119
|
+
const r = await query(v, o);
|
|
120
|
+
seen = r.matches;
|
|
121
|
+
return r;
|
|
122
|
+
};
|
|
123
|
+
const { chunks } = await retrieveContext(env, nobody, "q");
|
|
124
|
+
expect(queries[0].filter).toEqual({ user_email: nobody });
|
|
125
|
+
expect(seen).toEqual([]);
|
|
126
|
+
expect(chunks).toEqual([]);
|
|
127
|
+
});
|
|
128
|
+
|
|
129
|
+
it("ON with a project: the overfetch stays 3x topK and is drawn from the caller's own vectors", async () => {
|
|
130
|
+
vi.spyOn(console, "warn").mockImplementation(() => {});
|
|
131
|
+
const { env, queries } = fakeEnv(CROWDED, "on");
|
|
132
|
+
await retrieveContext(env, CALLER, "q", 5, 42);
|
|
133
|
+
expect(queries[0]).toEqual({ topK: 15, filter: { user_email: CALLER } });
|
|
134
|
+
});
|
|
135
|
+
});
|
|
@@ -0,0 +1,164 @@
|
|
|
1
|
+
// The skip link, as an artifact check (fleet-chezmoi#1700).
|
|
2
|
+
//
|
|
3
|
+
// WHAT THIS GUARD CAN SEE: the template and the stylesheet. It is a text read,
|
|
4
|
+
// so it proves the rules and attributes are present and self-consistent.
|
|
5
|
+
//
|
|
6
|
+
// WHAT IT STRUCTURALLY CANNOT SEE, stated here rather than in a PR comment: it
|
|
7
|
+
// cannot prove the focused link is VISIBLE. A `:focus` rule with a non-negative
|
|
8
|
+
// `left` can still be painted under something, clipped, or transparent, and no
|
|
9
|
+
// file read would notice. That half was measured against a real browser with a
|
|
10
|
+
// real Tab press (report on the PR) and stays a separate act. What this guard
|
|
11
|
+
// buys is that the measured state cannot silently regress: every field below
|
|
12
|
+
// was in its failing state before #1700, so the suite has been watched going
|
|
13
|
+
// red on the real defect rather than assumed capable of it.
|
|
14
|
+
|
|
15
|
+
import { readFileSync } from "node:fs";
|
|
16
|
+
import { dirname, join } from "node:path";
|
|
17
|
+
import { fileURLToPath } from "node:url";
|
|
18
|
+
import { describe, expect, it } from "vitest";
|
|
19
|
+
|
|
20
|
+
const pub = (f: string) =>
|
|
21
|
+
readFileSync(join(dirname(fileURLToPath(import.meta.url)), "../public/", f), "utf8");
|
|
22
|
+
|
|
23
|
+
// Anything that takes sequential keyboard focus by default, plus an explicit
|
|
24
|
+
// positive tabindex. Deliberately crude: it only has to find the FIRST one.
|
|
25
|
+
const FOCUSABLE = /<(?:a\s[^>]*href|button|input|select|textarea)\b/i;
|
|
26
|
+
|
|
27
|
+
/** The body, so head <link>/<script> can never be mistaken for page content. */
|
|
28
|
+
function body(html: string): string {
|
|
29
|
+
const m = html.match(/<body[^>]*>([\s\S]*)<\/body>/i);
|
|
30
|
+
if (!m) throw new Error("no <body> in index.html");
|
|
31
|
+
return m[1];
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** The declaration block of a rule whose selector matches exactly. */
|
|
35
|
+
function rule(css: string, selector: string): string | null {
|
|
36
|
+
const re = new RegExp(
|
|
37
|
+
`(?:^|})\\s*${selector.replace(/[.#*+?^$()|[\]\\]/g, "\\$&")}\\s*\\{([^}]*)\\}`,
|
|
38
|
+
"m",
|
|
39
|
+
);
|
|
40
|
+
const m = css.match(re);
|
|
41
|
+
return m ? m[1] : null;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** The opening tag that carries id="<id>", or null. */
|
|
45
|
+
function tagWithId(html: string, id: string): string | null {
|
|
46
|
+
const m = html.match(new RegExp(`<[a-z][^>]*\\sid="${id}"[^>]*>`, "i"));
|
|
47
|
+
return m ? m[0] : null;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
describe("control: the matchers discriminate", () => {
|
|
51
|
+
it("FOCUSABLE fires on focusable markup and not on inert markup", () => {
|
|
52
|
+
expect(FOCUSABLE.test('<a href="#x">y</a>')).toBe(true);
|
|
53
|
+
expect(FOCUSABLE.test("<button type=\"button\">y</button>")).toBe(true);
|
|
54
|
+
expect(FOCUSABLE.test('<input id="u">')).toBe(true);
|
|
55
|
+
// The negative half: these must NOT read as a focus stop, or "the skip link
|
|
56
|
+
// is first" would pass on a page where it is not.
|
|
57
|
+
expect(FOCUSABLE.test("<div><span>hello</span><!-- a comment --></div>")).toBe(false);
|
|
58
|
+
expect(FOCUSABLE.test('<a name="anchor">no href</a>')).toBe(false);
|
|
59
|
+
});
|
|
60
|
+
|
|
61
|
+
it("rule() extracts the block it names and not a longhand neighbour", () => {
|
|
62
|
+
const css = ".skip-link { left: -9999px; }\n.skip-link:focus { left: 8px; }\n";
|
|
63
|
+
expect(rule(css, ".skip-link")).toContain("-9999px");
|
|
64
|
+
expect(rule(css, ".skip-link")).not.toContain("8px");
|
|
65
|
+
expect(rule(css, ".skip-link:focus")).toContain("8px");
|
|
66
|
+
expect(rule(css, ".nope")).toBeNull();
|
|
67
|
+
});
|
|
68
|
+
|
|
69
|
+
it("tagWithId finds the tag and reports a missing id as missing", () => {
|
|
70
|
+
expect(tagWithId('<main class="c" id="main-content" tabindex="-1">', "main-content"))
|
|
71
|
+
.toContain("tabindex");
|
|
72
|
+
expect(tagWithId("<main>", "main-content")).toBeNull();
|
|
73
|
+
});
|
|
74
|
+
});
|
|
75
|
+
|
|
76
|
+
describe("the skip link is the first thing a keyboard user reaches", () => {
|
|
77
|
+
it("is the first focusable element in the body", () => {
|
|
78
|
+
const b = body(pub("index.html"));
|
|
79
|
+
const at = b.search(FOCUSABLE);
|
|
80
|
+
expect(at).toBeGreaterThan(-1);
|
|
81
|
+
// The first focus stop in the document is the skip link itself.
|
|
82
|
+
expect(b.slice(at, at + 200)).toContain('class="skip-link"');
|
|
83
|
+
});
|
|
84
|
+
|
|
85
|
+
it("has a non-empty text label, so the focus stop is identifiable", () => {
|
|
86
|
+
const m = pub("index.html").match(/<a class="skip-link"[^>]*>([^<]*)<\/a>/);
|
|
87
|
+
expect(m).not.toBeNull();
|
|
88
|
+
const label = (m as RegExpMatchArray)[1].trim();
|
|
89
|
+
expect(label.length).toBeGreaterThan(0);
|
|
90
|
+
// An `aria-hidden` skip link would be a focus stop with no name at all.
|
|
91
|
+
expect(pub("index.html")).not.toMatch(/<a class="skip-link"[^>]*aria-hidden/);
|
|
92
|
+
});
|
|
93
|
+
});
|
|
94
|
+
|
|
95
|
+
describe("the skip link goes somewhere that exists and is rendered", () => {
|
|
96
|
+
const html = pub("index.html");
|
|
97
|
+
const href = (html.match(/<a class="skip-link"[^>]*href="#([^"]+)"/) || [])[1];
|
|
98
|
+
|
|
99
|
+
it("targets a same-document fragment", () => {
|
|
100
|
+
expect(href).toBeTruthy();
|
|
101
|
+
});
|
|
102
|
+
|
|
103
|
+
it("the target id is present in the document", () => {
|
|
104
|
+
expect(tagWithId(html, href as string)).not.toBeNull();
|
|
105
|
+
});
|
|
106
|
+
|
|
107
|
+
// The defect this one exists for: the link used to point at #auth-screen,
|
|
108
|
+
// which carries `hidden` and is revealed only in public mode with no session.
|
|
109
|
+
// On every signed-in page it therefore aimed focus at a hidden element.
|
|
110
|
+
it("the target is not hidden by default", () => {
|
|
111
|
+
const tag = tagWithId(html, href as string) as string;
|
|
112
|
+
expect(tag).not.toMatch(/\shidden(\s|>|=)/);
|
|
113
|
+
});
|
|
114
|
+
|
|
115
|
+
it("the target accepts programmatic focus", () => {
|
|
116
|
+
const tag = tagWithId(html, href as string) as string;
|
|
117
|
+
expect(tag).toMatch(/tabindex="-1"/);
|
|
118
|
+
});
|
|
119
|
+
});
|
|
120
|
+
|
|
121
|
+
describe("focus moves the link on-screen", () => {
|
|
122
|
+
const css = pub("styles.css");
|
|
123
|
+
|
|
124
|
+
// The #177 / fc#1646 CSP invariant: the offscreen positioning is a stylesheet
|
|
125
|
+
// rule, never an inline style attribute. Enforcing style-src-attr drops the
|
|
126
|
+
// attribute and renders the link on the page.
|
|
127
|
+
it("the offscreen positioning is in the stylesheet", () => {
|
|
128
|
+
const base = rule(css, ".skip-link");
|
|
129
|
+
expect(base).not.toBeNull();
|
|
130
|
+
expect(base as string).toMatch(/position:\s*absolute/);
|
|
131
|
+
expect(base as string).toMatch(/left:\s*-9999px/);
|
|
132
|
+
expect(pub("index.html")).not.toMatch(/<a class="skip-link"[^>]*\sstyle\s*=/);
|
|
133
|
+
});
|
|
134
|
+
|
|
135
|
+
// The whole point of #1700. Before the fix there was NO :focus rule at all,
|
|
136
|
+
// and the element's box was measured still at x = -9999 after .focus().
|
|
137
|
+
it("a :focus rule exists and its left is not offscreen", () => {
|
|
138
|
+
const focused = rule(css, ".skip-link:focus");
|
|
139
|
+
expect(focused).not.toBeNull();
|
|
140
|
+
const left = (focused as string).match(/left:\s*(-?[\d.]+)/);
|
|
141
|
+
expect(left).not.toBeNull();
|
|
142
|
+
expect(Number((left as RegExpMatchArray)[1])).toBeGreaterThanOrEqual(0);
|
|
143
|
+
});
|
|
144
|
+
|
|
145
|
+
it("the revealed link is painted above the auth screen and the sidebar", () => {
|
|
146
|
+
const base = rule(css, ".skip-link") as string;
|
|
147
|
+
const z = base.match(/z-index:\s*(\d+)/);
|
|
148
|
+
expect(z).not.toBeNull();
|
|
149
|
+
// .auth-screen is z-index 100; a reveal underneath it is not a reveal.
|
|
150
|
+
expect(Number((z as RegExpMatchArray)[1])).toBeGreaterThan(100);
|
|
151
|
+
});
|
|
152
|
+
});
|
|
153
|
+
|
|
154
|
+
describe("the auth gate state has no block to bypass", () => {
|
|
155
|
+
// body.auth-active .layout is display:none, so the sidebar and the skip
|
|
156
|
+
// target are both out of the layout. A skip link there would be a focus stop
|
|
157
|
+
// pointing at nothing, which is the defect #1700 fixed, re-introduced.
|
|
158
|
+
it("the skip link leaves the tab order while the auth gate is up", () => {
|
|
159
|
+
const css = pub("styles.css");
|
|
160
|
+
expect(rule(css, "body.auth-active .skip-link")).toMatch(/display:\s*none/);
|
|
161
|
+
// Control: the rule this one depends on is still what makes the shell absent.
|
|
162
|
+
expect(rule(css, "body.auth-active .layout")).toMatch(/display:\s*none/);
|
|
163
|
+
});
|
|
164
|
+
});
|