@skyphusion/create-prism 0.1.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/LICENSE +235 -0
- package/NOTICE +3 -0
- package/README.md +114 -0
- package/index.js +195 -0
- package/package.json +44 -0
- package/template/CONTRIBUTING.md +80 -0
- package/template/LICENSE +235 -0
- package/template/MIGRATIONS.md +197 -0
- package/template/NOTICE +3 -0
- package/template/README.md +875 -0
- package/template/docs/legal/INSTANCE-ACCEPTABLE-USE.md +98 -0
- package/template/docs/legal/INSTANCE-PRIVACY.md +112 -0
- package/template/docs/legal/README.md +11 -0
- package/template/docs/screenshot-desktop.jpg +0 -0
- package/template/docs/screenshot-mobile.jpg +0 -0
- package/template/gitignore +23 -0
- package/template/migrate-v0.164.0.sql +6 -0
- package/template/migrate-v0.167.0.sql +44 -0
- package/template/migrate-v0.20.0.sql +40 -0
- package/template/migrate-v0.20.2.sql +19 -0
- package/template/migrate-v0.20.3.sql +36 -0
- package/template/migrations/0001_init.sql +134 -0
- package/template/package.json +32 -0
- package/template/public/app.js +2778 -0
- package/template/public/apple-touch-icon.png +0 -0
- package/template/public/favicon-16.png +0 -0
- package/template/public/favicon-32.png +0 -0
- package/template/public/favicon.svg +5 -0
- package/template/public/icon-192.png +0 -0
- package/template/public/icon-512.png +0 -0
- package/template/public/index.html +329 -0
- package/template/public/manifest.webmanifest +14 -0
- package/template/public/streaming-client.js +207 -0
- package/template/public/stt.html +68 -0
- package/template/public/stt.js +16 -0
- package/template/public/styles.css +2068 -0
- package/template/public/voice-widget.js +195 -0
- package/template/schema.sql +283 -0
- package/template/src/ai-binding.ts +33 -0
- package/template/src/auth-kdf.ts +106 -0
- package/template/src/auth.ts +315 -0
- package/template/src/chunking.ts +161 -0
- package/template/src/discord.ts +353 -0
- package/template/src/env.ts +55 -0
- package/template/src/gateway-credentials.ts +97 -0
- package/template/src/health-schema.ts +25 -0
- package/template/src/index.ts +4180 -0
- package/template/src/longrun-params.ts +135 -0
- package/template/src/models.ts +214 -0
- package/template/src/output-extract.ts +128 -0
- package/template/src/parsers/anthropic-sse.ts +56 -0
- package/template/src/parsers/gemini-sse.ts +62 -0
- package/template/src/parsers/openai-sse.ts +60 -0
- package/template/src/parsers/sse-framer.ts +39 -0
- package/template/src/parsers/types.ts +16 -0
- package/template/src/parsers/workers-ai-sse.ts +43 -0
- package/template/src/parsers/xai-sse.ts +40 -0
- package/template/src/providers/anthropic.ts +208 -0
- package/template/src/providers/google.ts +150 -0
- package/template/src/providers/openai.ts +69 -0
- package/template/src/providers/workers-ai.ts +83 -0
- package/template/src/providers/xai.ts +159 -0
- package/template/src/proxied-image-params.ts +43 -0
- package/template/src/rate-limit.ts +77 -0
- package/template/src/searxng.ts +75 -0
- package/template/src/session.ts +114 -0
- package/template/src/stt-session.ts +206 -0
- package/template/src/stt-util.ts +19 -0
- package/template/src/types.ts +56 -0
- package/template/src/user-prefs.ts +63 -0
- package/template/src/utils.ts +73 -0
- package/template/src/zip.ts +137 -0
- package/template/tests/anthropic-sse.test.ts +149 -0
- package/template/tests/auth-kdf.test.ts +59 -0
- package/template/tests/auth-unit.test.ts +97 -0
- package/template/tests/chunking.test.ts +217 -0
- package/template/tests/discord.test.ts +184 -0
- package/template/tests/gateway-credentials.test.ts +65 -0
- package/template/tests/gemini-sse.test.ts +75 -0
- package/template/tests/google-gemini.test.ts +65 -0
- package/template/tests/health-schema.test.ts +35 -0
- package/template/tests/longrun-params.test.ts +128 -0
- package/template/tests/openai-sse.test.ts +71 -0
- package/template/tests/output-extract.test.ts +171 -0
- package/template/tests/proxied-image-params.test.ts +51 -0
- package/template/tests/rate-limit.test.ts +45 -0
- package/template/tests/searxng.test.ts +51 -0
- package/template/tests/sse-framer.test.ts +113 -0
- package/template/tests/stt-session.test.ts +35 -0
- package/template/tests/utils.test.ts +39 -0
- package/template/tests/workers-ai-sse.test.ts +67 -0
- package/template/tests/xai-sse.test.ts +60 -0
- package/template/tests/zip.test.ts +145 -0
- package/template/tests-integration/auth.test.ts +371 -0
- package/template/tests-integration/worker.test.ts +322 -0
- package/template/tsconfig.json +18 -0
- package/template/vitest.config.ts +18 -0
- package/template/vitest.node.config.ts +19 -0
- package/template/vitest.workers.config.ts +47 -0
- package/template/wrangler.example.toml +151 -0
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
import { describe, it, expect } from "vitest";
|
|
2
|
+
import { isZip, unzip } from "../src/zip";
|
|
3
|
+
|
|
4
|
+
// v0.25.0: tests for the zero-dependency ZIP reader. We hand-build archives so
|
|
5
|
+
// the central-directory parsing, the stored vs deflate paths, directory
|
|
6
|
+
// skipping, and the limit guards are all exercised. CompressionStream /
|
|
7
|
+
// DecompressionStream are available natively in the Node test runtime.
|
|
8
|
+
|
|
9
|
+
const LIMITS = { maxEntries: 200, maxTotalBytes: 50 * 1024 * 1024, maxFileBytes: 10 * 1024 * 1024 };
|
|
10
|
+
|
|
11
|
+
function concat(parts: Uint8Array[]): Uint8Array {
|
|
12
|
+
const len = parts.reduce((s, p) => s + p.length, 0);
|
|
13
|
+
const out = new Uint8Array(len);
|
|
14
|
+
let o = 0;
|
|
15
|
+
for (const p of parts) { out.set(p, o); o += p.length; }
|
|
16
|
+
return out;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
async function deflateRaw(data: Uint8Array): Promise<Uint8Array> {
|
|
20
|
+
const cs = new CompressionStream("deflate-raw");
|
|
21
|
+
const stream = new Response(data).body!.pipeThrough(cs);
|
|
22
|
+
return new Uint8Array(await new Response(stream).arrayBuffer());
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
interface InFile { name: string; data: Uint8Array; method?: 0 | 8 }
|
|
26
|
+
|
|
27
|
+
// Build a minimal but spec-valid zip. CRC fields are left zero (the reader
|
|
28
|
+
// ignores them). Method 8 entries are deflate-raw compressed.
|
|
29
|
+
async function buildZip(files: InFile[]): Promise<Uint8Array> {
|
|
30
|
+
const enc = new TextEncoder();
|
|
31
|
+
const local: Uint8Array[] = [];
|
|
32
|
+
const central: Uint8Array[] = [];
|
|
33
|
+
let offset = 0;
|
|
34
|
+
|
|
35
|
+
for (const f of files) {
|
|
36
|
+
const method = f.method ?? 0;
|
|
37
|
+
const nameBytes = enc.encode(f.name);
|
|
38
|
+
const stored = method === 8 ? await deflateRaw(f.data) : f.data;
|
|
39
|
+
|
|
40
|
+
const lh = new Uint8Array(30 + nameBytes.length);
|
|
41
|
+
const ldv = new DataView(lh.buffer);
|
|
42
|
+
ldv.setUint32(0, 0x04034b50, true);
|
|
43
|
+
ldv.setUint16(4, 20, true);
|
|
44
|
+
ldv.setUint16(8, method, true);
|
|
45
|
+
ldv.setUint32(18, stored.length, true);
|
|
46
|
+
ldv.setUint32(22, f.data.length, true);
|
|
47
|
+
ldv.setUint16(26, nameBytes.length, true);
|
|
48
|
+
lh.set(nameBytes, 30);
|
|
49
|
+
const localOffset = offset;
|
|
50
|
+
local.push(lh, stored);
|
|
51
|
+
offset += lh.length + stored.length;
|
|
52
|
+
|
|
53
|
+
const ch = new Uint8Array(46 + nameBytes.length);
|
|
54
|
+
const cdv = new DataView(ch.buffer);
|
|
55
|
+
cdv.setUint32(0, 0x02014b50, true);
|
|
56
|
+
cdv.setUint16(4, 20, true);
|
|
57
|
+
cdv.setUint16(6, 20, true);
|
|
58
|
+
cdv.setUint16(10, method, true);
|
|
59
|
+
cdv.setUint32(20, stored.length, true);
|
|
60
|
+
cdv.setUint32(24, f.data.length, true);
|
|
61
|
+
cdv.setUint16(28, nameBytes.length, true);
|
|
62
|
+
cdv.setUint32(42, localOffset, true);
|
|
63
|
+
ch.set(nameBytes, 46);
|
|
64
|
+
central.push(ch);
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
const cdStart = offset;
|
|
68
|
+
const cdLen = central.reduce((s, c) => s + c.length, 0);
|
|
69
|
+
const eocd = new Uint8Array(22);
|
|
70
|
+
const edv = new DataView(eocd.buffer);
|
|
71
|
+
edv.setUint32(0, 0x06054b50, true);
|
|
72
|
+
edv.setUint16(8, files.length, true);
|
|
73
|
+
edv.setUint16(10, files.length, true);
|
|
74
|
+
edv.setUint32(12, cdLen, true);
|
|
75
|
+
edv.setUint32(16, cdStart, true);
|
|
76
|
+
|
|
77
|
+
return concat([...local, ...central, eocd]);
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
const td = (b: Uint8Array) => new TextDecoder().decode(b);
|
|
81
|
+
const te = (s: string) => new TextEncoder().encode(s);
|
|
82
|
+
|
|
83
|
+
describe("isZip", () => {
|
|
84
|
+
it("detects the local-file-header magic", async () => {
|
|
85
|
+
const zip = await buildZip([{ name: "a.txt", data: te("hi") }]);
|
|
86
|
+
expect(isZip(zip)).toBe(true);
|
|
87
|
+
});
|
|
88
|
+
it("rejects non-zip bytes", () => {
|
|
89
|
+
expect(isZip(te("not a zip at all"))).toBe(false);
|
|
90
|
+
expect(isZip(new Uint8Array([0x50, 0x4b]))).toBe(false);
|
|
91
|
+
});
|
|
92
|
+
});
|
|
93
|
+
|
|
94
|
+
describe("unzip", () => {
|
|
95
|
+
it("reads stored entries", async () => {
|
|
96
|
+
const zip = await buildZip([
|
|
97
|
+
{ name: "a.txt", data: te("alpha") },
|
|
98
|
+
{ name: "b/c.txt", data: te("charlie") },
|
|
99
|
+
]);
|
|
100
|
+
const { entries, skipped } = await unzip(zip, LIMITS);
|
|
101
|
+
expect(skipped).toEqual([]);
|
|
102
|
+
expect(entries.map((e) => e.name)).toEqual(["a.txt", "b/c.txt"]);
|
|
103
|
+
expect(td(entries[0].bytes)).toBe("alpha");
|
|
104
|
+
expect(td(entries[1].bytes)).toBe("charlie");
|
|
105
|
+
});
|
|
106
|
+
|
|
107
|
+
it("inflates deflate entries", async () => {
|
|
108
|
+
const big = "the quick brown fox ".repeat(500);
|
|
109
|
+
const zip = await buildZip([{ name: "doc.txt", data: te(big), method: 8 }]);
|
|
110
|
+
const { entries } = await unzip(zip, LIMITS);
|
|
111
|
+
expect(entries).toHaveLength(1);
|
|
112
|
+
expect(td(entries[0].bytes)).toBe(big);
|
|
113
|
+
});
|
|
114
|
+
|
|
115
|
+
it("skips directory entries", async () => {
|
|
116
|
+
const zip = await buildZip([
|
|
117
|
+
{ name: "folder/", data: new Uint8Array(0) },
|
|
118
|
+
{ name: "folder/x.txt", data: te("x") },
|
|
119
|
+
]);
|
|
120
|
+
const { entries } = await unzip(zip, LIMITS);
|
|
121
|
+
expect(entries.map((e) => e.name)).toEqual(["folder/x.txt"]);
|
|
122
|
+
});
|
|
123
|
+
|
|
124
|
+
it("skips entries over the per-file size limit", async () => {
|
|
125
|
+
const zip = await buildZip([
|
|
126
|
+
{ name: "small.txt", data: te("ok") },
|
|
127
|
+
{ name: "big.txt", data: te("0123456789") },
|
|
128
|
+
]);
|
|
129
|
+
const { entries, skipped } = await unzip(zip, { ...LIMITS, maxFileBytes: 5 });
|
|
130
|
+
expect(entries.map((e) => e.name)).toEqual(["small.txt"]);
|
|
131
|
+
expect(skipped).toEqual([{ name: "big.txt", reason: "uncompressed size 10 over per-file limit" }]);
|
|
132
|
+
});
|
|
133
|
+
|
|
134
|
+
it("throws when the entry count exceeds the limit", async () => {
|
|
135
|
+
const zip = await buildZip([
|
|
136
|
+
{ name: "a.txt", data: te("a") },
|
|
137
|
+
{ name: "b.txt", data: te("b") },
|
|
138
|
+
]);
|
|
139
|
+
await expect(unzip(zip, { ...LIMITS, maxEntries: 1 })).rejects.toThrow(/over the limit/);
|
|
140
|
+
});
|
|
141
|
+
|
|
142
|
+
it("throws on bytes with no end-of-central-directory record", async () => {
|
|
143
|
+
await expect(unzip(te("garbage"), LIMITS)).rejects.toThrow(/not a valid zip/);
|
|
144
|
+
});
|
|
145
|
+
});
|
|
@@ -0,0 +1,371 @@
|
|
|
1
|
+
// Workers-runtime integration tests for the first-party auth plane
|
|
2
|
+
// (v0.167.0, issue #80). Runs the real fetch handler in workerd with local
|
|
3
|
+
// Miniflare D1 + R2. AUTH_MODE is flipped to "public" for these tests (the
|
|
4
|
+
// existing worker.test.ts suite keeps the default "access" mode), so the
|
|
5
|
+
// signup/login/boot-envelope/gate/fail-closed/account-delete paths are all
|
|
6
|
+
// exercised against the shipped handler, not stubs.
|
|
7
|
+
//
|
|
8
|
+
// Boot contract: there is NO /api/session endpoint; GET /api/models is the
|
|
9
|
+
// unauthenticated boot probe and carries { mode, authenticated, user, username }.
|
|
10
|
+
|
|
11
|
+
import { env, SELF } from "cloudflare:test";
|
|
12
|
+
import { afterEach, beforeEach, describe, expect, it } from "vitest";
|
|
13
|
+
import { MODELS } from "../src/models";
|
|
14
|
+
import schemaSql from "../schema.sql?raw";
|
|
15
|
+
|
|
16
|
+
async function applySchema(db: D1Database): Promise<void> {
|
|
17
|
+
const statements = schemaSql
|
|
18
|
+
.split("\n")
|
|
19
|
+
.map((line) => line.replace(/--.*$/, ""))
|
|
20
|
+
.join("\n")
|
|
21
|
+
.split(";")
|
|
22
|
+
.map((s) => s.trim())
|
|
23
|
+
.filter((s) => s.length > 0);
|
|
24
|
+
for (const stmt of statements) {
|
|
25
|
+
try {
|
|
26
|
+
await db.prepare(stmt).run();
|
|
27
|
+
} catch (e) {
|
|
28
|
+
const msg = String((e as { message?: string })?.message ?? e);
|
|
29
|
+
if (/duplicate column name|already exists/i.test(msg)) continue;
|
|
30
|
+
throw e;
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
const ALL_TABLES = [
|
|
36
|
+
"chats",
|
|
37
|
+
"user_prefs",
|
|
38
|
+
"documents",
|
|
39
|
+
"chunks",
|
|
40
|
+
"projects",
|
|
41
|
+
"project_documents",
|
|
42
|
+
"project_messages",
|
|
43
|
+
"users",
|
|
44
|
+
"sessions",
|
|
45
|
+
"auth_attempts",
|
|
46
|
+
];
|
|
47
|
+
|
|
48
|
+
const anyEnv = env as unknown as { AUTH_MODE?: string; GATEWAY_ID?: string; CF_AIG_TOKEN?: string };
|
|
49
|
+
|
|
50
|
+
beforeEach(async () => {
|
|
51
|
+
await applySchema(env.DB);
|
|
52
|
+
for (const t of ALL_TABLES) await env.DB.prepare(`DELETE FROM ${t}`).run();
|
|
53
|
+
anyEnv.AUTH_MODE = "public";
|
|
54
|
+
delete anyEnv.GATEWAY_ID;
|
|
55
|
+
delete anyEnv.CF_AIG_TOKEN;
|
|
56
|
+
});
|
|
57
|
+
|
|
58
|
+
afterEach(() => {
|
|
59
|
+
delete anyEnv.AUTH_MODE;
|
|
60
|
+
delete anyEnv.GATEWAY_ID;
|
|
61
|
+
delete anyEnv.CF_AIG_TOKEN;
|
|
62
|
+
});
|
|
63
|
+
|
|
64
|
+
const WORKERS_AI_CHAT = MODELS.find((m) => m.type === "chat" && !m.provider)!.id;
|
|
65
|
+
const STREAM_CHAT = MODELS.find((m) => m.type === "chat" && m.streaming && !m.provider)?.id
|
|
66
|
+
?? MODELS.find((m) => m.type === "chat" && m.streaming)!.id;
|
|
67
|
+
|
|
68
|
+
function cookieFrom(res: Response): string {
|
|
69
|
+
const sc = res.headers.get("set-cookie");
|
|
70
|
+
if (!sc) throw new Error("no set-cookie on response");
|
|
71
|
+
return sc.split(";")[0]; // "__Host-prism_session=<token>"
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
interface ReqOpts {
|
|
75
|
+
method?: string;
|
|
76
|
+
body?: unknown;
|
|
77
|
+
cookie?: string;
|
|
78
|
+
ip?: string;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
function req(path: string, opts: ReqOpts = {}): Promise<Response> {
|
|
82
|
+
const headers = new Headers();
|
|
83
|
+
if (opts.body !== undefined) headers.set("content-type", "application/json");
|
|
84
|
+
if (opts.cookie) headers.set("cookie", opts.cookie);
|
|
85
|
+
headers.set("cf-connecting-ip", opts.ip ?? "203.0.113.7");
|
|
86
|
+
return SELF.fetch(`https://prism.test${path}`, {
|
|
87
|
+
method: opts.method ?? "GET",
|
|
88
|
+
headers,
|
|
89
|
+
body: opts.body !== undefined ? JSON.stringify(opts.body) : undefined,
|
|
90
|
+
});
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
interface BootEnvelope {
|
|
94
|
+
mode: string;
|
|
95
|
+
authenticated: boolean;
|
|
96
|
+
user: string | null;
|
|
97
|
+
username: string | null;
|
|
98
|
+
gateway: { source: string; configured: boolean };
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
async function boot(cookie?: string): Promise<BootEnvelope> {
|
|
102
|
+
return (await (await req("/api/models", { cookie })).json()) as BootEnvelope;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
async function signup(username: string, password: string, ip?: string): Promise<string> {
|
|
106
|
+
const res = await req("/api/auth/signup", { method: "POST", body: { username, password }, ip });
|
|
107
|
+
expect(res.status).toBe(201);
|
|
108
|
+
return cookieFrom(res);
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
describe("GET /api/models boot envelope (no /api/session)", () => {
|
|
112
|
+
it("is reachable unauthenticated and reports mode + authenticated=false + user null", async () => {
|
|
113
|
+
const res = await req("/api/models");
|
|
114
|
+
expect(res.status).toBe(200);
|
|
115
|
+
const body = (await res.json()) as BootEnvelope & { models: unknown[] };
|
|
116
|
+
expect(body.mode).toBe("public");
|
|
117
|
+
expect(body.authenticated).toBe(false);
|
|
118
|
+
expect(body.user).toBeNull();
|
|
119
|
+
expect(body.username).toBeNull();
|
|
120
|
+
expect(Array.isArray(body.models)).toBe(true);
|
|
121
|
+
});
|
|
122
|
+
|
|
123
|
+
it("reports authenticated + username once signed up", async () => {
|
|
124
|
+
const cookie = await signup("alice", "password123");
|
|
125
|
+
const b = await boot(cookie);
|
|
126
|
+
expect(b.authenticated).toBe(true);
|
|
127
|
+
expect(b.username).toBe("alice");
|
|
128
|
+
expect(b.user).toMatch(/^usr_/);
|
|
129
|
+
});
|
|
130
|
+
});
|
|
131
|
+
|
|
132
|
+
describe("signup / login / logout", () => {
|
|
133
|
+
it("signup opens a session; login on a fresh cookie also works", async () => {
|
|
134
|
+
await signup("bob", "password123");
|
|
135
|
+
const loginRes = await req("/api/auth/login", {
|
|
136
|
+
method: "POST",
|
|
137
|
+
body: { username: "bob", password: "password123" },
|
|
138
|
+
});
|
|
139
|
+
expect(loginRes.status).toBe(200);
|
|
140
|
+
const cookie = cookieFrom(loginRes);
|
|
141
|
+
expect((await boot(cookie)).authenticated).toBe(true);
|
|
142
|
+
});
|
|
143
|
+
|
|
144
|
+
it("rejects a duplicate username (case-insensitive)", async () => {
|
|
145
|
+
await signup("Carol", "password123");
|
|
146
|
+
const dup = await req("/api/auth/signup", {
|
|
147
|
+
method: "POST",
|
|
148
|
+
body: { username: "carol", password: "password123" },
|
|
149
|
+
});
|
|
150
|
+
expect(dup.status).toBe(409);
|
|
151
|
+
});
|
|
152
|
+
|
|
153
|
+
it("stores the cased username but compares lowercased", async () => {
|
|
154
|
+
const cookie = await signup("MixedCase", "password123");
|
|
155
|
+
expect((await boot(cookie)).username).toBe("MixedCase");
|
|
156
|
+
const dup = await req("/api/auth/signup", {
|
|
157
|
+
method: "POST",
|
|
158
|
+
body: { username: "mixedcase", password: "password123" },
|
|
159
|
+
});
|
|
160
|
+
expect(dup.status).toBe(409);
|
|
161
|
+
});
|
|
162
|
+
|
|
163
|
+
it("rejects a wrong password with a generic 401", async () => {
|
|
164
|
+
await signup("dave", "password123");
|
|
165
|
+
const res = await req("/api/auth/login", {
|
|
166
|
+
method: "POST",
|
|
167
|
+
body: { username: "dave", password: "wrongpassword" },
|
|
168
|
+
});
|
|
169
|
+
expect(res.status).toBe(401);
|
|
170
|
+
});
|
|
171
|
+
|
|
172
|
+
it("logout revokes the session server-side", async () => {
|
|
173
|
+
const cookie = await signup("erin", "password123");
|
|
174
|
+
await req("/api/auth/logout", { method: "POST", cookie });
|
|
175
|
+
expect((await boot(cookie)).authenticated).toBe(false);
|
|
176
|
+
});
|
|
177
|
+
|
|
178
|
+
it("enforces the validation contract with a stable code", async () => {
|
|
179
|
+
const shortPw = await req("/api/auth/signup", {
|
|
180
|
+
method: "POST",
|
|
181
|
+
body: { username: "frank", password: "short1234" }, // 9 chars
|
|
182
|
+
});
|
|
183
|
+
expect(shortPw.status).toBe(400);
|
|
184
|
+
const dotUser = await req("/api/auth/signup", {
|
|
185
|
+
method: "POST",
|
|
186
|
+
body: { username: "has.dot", password: "password123" },
|
|
187
|
+
});
|
|
188
|
+
expect(dotUser.status).toBe(400);
|
|
189
|
+
const shortUser = await req("/api/auth/signup", {
|
|
190
|
+
method: "POST",
|
|
191
|
+
body: { username: "no", password: "password123" },
|
|
192
|
+
});
|
|
193
|
+
expect(shortUser.status).toBe(400);
|
|
194
|
+
});
|
|
195
|
+
});
|
|
196
|
+
|
|
197
|
+
describe("public-mode gate: uniform 401 unauthenticated", () => {
|
|
198
|
+
it("blocks /api/* without a session, with code unauthenticated", async () => {
|
|
199
|
+
const res = await req("/api/history");
|
|
200
|
+
expect(res.status).toBe(401);
|
|
201
|
+
expect(((await res.json()) as { code: string }).code).toBe("unauthenticated");
|
|
202
|
+
});
|
|
203
|
+
|
|
204
|
+
it("does NOT block GET /api/models (the boot probe stays reachable)", async () => {
|
|
205
|
+
expect((await req("/api/models")).status).toBe(200);
|
|
206
|
+
});
|
|
207
|
+
|
|
208
|
+
it("allows /api/history with a session, scoped to the account", async () => {
|
|
209
|
+
const cookie = await signup("gwen", "password123");
|
|
210
|
+
const res = await req("/api/history", { cookie });
|
|
211
|
+
expect(res.status).toBe(200);
|
|
212
|
+
expect(Array.isArray(((await res.json()) as { chats: unknown[] }).chats)).toBe(true);
|
|
213
|
+
});
|
|
214
|
+
|
|
215
|
+
it("isolates prefs between two accounts", async () => {
|
|
216
|
+
const aCookie = await signup("hank", "password123", "203.0.113.10");
|
|
217
|
+
const bCookie = await signup("iris", "password123", "203.0.113.11");
|
|
218
|
+
await req("/api/prefs", { method: "PATCH", cookie: aCookie, body: { gateway_id: "hank-gw" } });
|
|
219
|
+
const bPrefs = (await (await req("/api/prefs", { cookie: bCookie })).json()) as { gateway_id: string | null };
|
|
220
|
+
expect(bPrefs.gateway_id).toBeNull(); // iris does not see hank's prefs
|
|
221
|
+
});
|
|
222
|
+
});
|
|
223
|
+
|
|
224
|
+
describe("fail-closed gateway in public mode", () => {
|
|
225
|
+
it("ignores worker secrets: chat 412 gateway_not_configured even when GATEWAY_ID/CF_AIG_TOKEN are set", async () => {
|
|
226
|
+
anyEnv.GATEWAY_ID = "host-gateway";
|
|
227
|
+
anyEnv.CF_AIG_TOKEN = "host-token";
|
|
228
|
+
const cookie = await signup("jack", "password123");
|
|
229
|
+
const res = await req("/api/chat", {
|
|
230
|
+
method: "POST",
|
|
231
|
+
cookie,
|
|
232
|
+
body: { model: WORKERS_AI_CHAT, user_input: "hi" },
|
|
233
|
+
});
|
|
234
|
+
expect(res.status).toBe(412);
|
|
235
|
+
const body = (await res.json()) as { error: string; code: string };
|
|
236
|
+
expect(body.code).toBe("gateway_not_configured");
|
|
237
|
+
});
|
|
238
|
+
|
|
239
|
+
it("stream path returns 412 as a clean JSON body BEFORE the event-stream opens", async () => {
|
|
240
|
+
const cookie = await signup("jade", "password123");
|
|
241
|
+
const res = await req("/api/chat/stream", {
|
|
242
|
+
method: "POST",
|
|
243
|
+
cookie,
|
|
244
|
+
body: { model: STREAM_CHAT, user_input: "hi" },
|
|
245
|
+
});
|
|
246
|
+
expect(res.status).toBe(412);
|
|
247
|
+
// The refusal is a JSON body, not a text/event-stream that already opened.
|
|
248
|
+
expect(res.headers.get("content-type") ?? "").toContain("application/json");
|
|
249
|
+
const body = (await res.json()) as { code: string };
|
|
250
|
+
expect(body.code).toBe("gateway_not_configured");
|
|
251
|
+
});
|
|
252
|
+
|
|
253
|
+
it("source is never worker/mixed in public mode even with worker secrets present", async () => {
|
|
254
|
+
anyEnv.GATEWAY_ID = "host-gateway";
|
|
255
|
+
anyEnv.CF_AIG_TOKEN = "host-token";
|
|
256
|
+
const cookie = await signup("kate", "password123");
|
|
257
|
+
const b = await boot(cookie);
|
|
258
|
+
expect(b.gateway.source).toBe("none");
|
|
259
|
+
expect(b.gateway.configured).toBe(false);
|
|
260
|
+
});
|
|
261
|
+
|
|
262
|
+
it("positive control: once the user sets a gateway, the 412 no longer fires", async () => {
|
|
263
|
+
const cookie = await signup("liam", "password123");
|
|
264
|
+
await req("/api/prefs", { method: "PATCH", cookie, body: { gateway_id: "liam-gw" } });
|
|
265
|
+
let status: number;
|
|
266
|
+
try {
|
|
267
|
+
status = (
|
|
268
|
+
await req("/api/chat", { method: "POST", cookie, body: { model: WORKERS_AI_CHAT, user_input: "hi" } })
|
|
269
|
+
).status;
|
|
270
|
+
} catch {
|
|
271
|
+
status = 500;
|
|
272
|
+
}
|
|
273
|
+
expect(status).not.toBe(412);
|
|
274
|
+
});
|
|
275
|
+
});
|
|
276
|
+
|
|
277
|
+
describe("DELETE /api/account cascade", () => {
|
|
278
|
+
it("requires password re-entry and cascades the account's data", async () => {
|
|
279
|
+
const cookie = await signup("mona", "password123");
|
|
280
|
+
const userId = (
|
|
281
|
+
await env.DB.prepare(`SELECT id FROM users WHERE username_lc = 'mona'`).first<{ id: string }>()
|
|
282
|
+
)!.id;
|
|
283
|
+
|
|
284
|
+
await env.DB.prepare(
|
|
285
|
+
`INSERT INTO chats (user_email, model, model_type, user_input, output, output_artifact)
|
|
286
|
+
VALUES (?, 'm', 'image', 'hi', '', ?)`,
|
|
287
|
+
)
|
|
288
|
+
.bind(userId, JSON.stringify({ key: "out/mona.png", mime: "image/png", type: "image" }))
|
|
289
|
+
.run();
|
|
290
|
+
await env.R2.put("out/mona.png", new Uint8Array([1, 2, 3]), { customMetadata: { user_email: userId } });
|
|
291
|
+
await req("/api/prefs", { method: "PATCH", cookie, body: { gateway_id: "mona-gw" } });
|
|
292
|
+
|
|
293
|
+
const otherCookie = await signup("nell", "password123", "203.0.113.20");
|
|
294
|
+
const otherId = (
|
|
295
|
+
await env.DB.prepare(`SELECT id FROM users WHERE username_lc = 'nell'`).first<{ id: string }>()
|
|
296
|
+
)!.id;
|
|
297
|
+
|
|
298
|
+
const bad = await req("/api/account", { method: "DELETE", cookie, body: { password: "nope" } });
|
|
299
|
+
expect(bad.status).toBe(403);
|
|
300
|
+
|
|
301
|
+
const del = await req("/api/account", { method: "DELETE", cookie, body: { password: "password123" } });
|
|
302
|
+
expect(del.status).toBe(200);
|
|
303
|
+
expect(del.headers.get("set-cookie")).toContain("Max-Age=0");
|
|
304
|
+
|
|
305
|
+
expect(await env.DB.prepare(`SELECT id FROM users WHERE id = ?`).bind(userId).first()).toBeNull();
|
|
306
|
+
for (const [table, col] of [["chats", "user_email"], ["user_prefs", "user_email"], ["sessions", "user_id"]] as const) {
|
|
307
|
+
const row = await env.DB.prepare(`SELECT COUNT(*) AS n FROM ${table} WHERE ${col} = ?`).bind(userId).first<{ n: number }>();
|
|
308
|
+
expect(row!.n).toBe(0);
|
|
309
|
+
}
|
|
310
|
+
expect(await env.R2.get("out/mona.png")).toBeNull();
|
|
311
|
+
|
|
312
|
+
// The other account is untouched.
|
|
313
|
+
expect(await env.DB.prepare(`SELECT id FROM users WHERE id = ?`).bind(otherId).first()).not.toBeNull();
|
|
314
|
+
expect((await boot(otherCookie)).authenticated).toBe(true);
|
|
315
|
+
});
|
|
316
|
+
});
|
|
317
|
+
|
|
318
|
+
describe("login rate limit resets on success", () => {
|
|
319
|
+
it("successful logins beyond the failed cap never lock out, and clear the bucket", async () => {
|
|
320
|
+
await signup("pia", "password123", "198.51.100.9");
|
|
321
|
+
// More than LOGIN_LIMIT (5) SUCCESSFUL logins in one window must all pass.
|
|
322
|
+
for (let i = 0; i < 7; i++) {
|
|
323
|
+
const res = await req("/api/auth/login", {
|
|
324
|
+
method: "POST",
|
|
325
|
+
body: { username: "pia", password: "password123" },
|
|
326
|
+
ip: "198.51.100.9",
|
|
327
|
+
});
|
|
328
|
+
expect(res.status).toBe(200);
|
|
329
|
+
}
|
|
330
|
+
// Bucket is cleared after a success (not left accumulating).
|
|
331
|
+
const row = await env.DB.prepare(`SELECT count FROM auth_attempts WHERE bucket_key = ?`)
|
|
332
|
+
.bind("login:198.51.100.9:pia")
|
|
333
|
+
.first<{ count: number }>();
|
|
334
|
+
expect(row).toBeNull();
|
|
335
|
+
});
|
|
336
|
+
|
|
337
|
+
it("a burst of failures still locks out, then a later success would reset it", async () => {
|
|
338
|
+
await signup("quinn", "password123", "198.51.100.12");
|
|
339
|
+
let locked = false;
|
|
340
|
+
for (let i = 0; i < 8; i++) {
|
|
341
|
+
const res = await req("/api/auth/login", {
|
|
342
|
+
method: "POST",
|
|
343
|
+
body: { username: "quinn", password: "wrongpassword" },
|
|
344
|
+
ip: "198.51.100.12",
|
|
345
|
+
});
|
|
346
|
+
if (res.status === 429) { locked = true; break; }
|
|
347
|
+
}
|
|
348
|
+
expect(locked).toBe(true); // failures alone still trip the limiter
|
|
349
|
+
});
|
|
350
|
+
});
|
|
351
|
+
|
|
352
|
+
describe("rate limiting", () => {
|
|
353
|
+
it("positive control: the counter records and eventually 429s repeated logins", async () => {
|
|
354
|
+
await signup("olive", "password123", "198.51.100.5");
|
|
355
|
+
let sawLimit = false;
|
|
356
|
+
for (let i = 0; i < 8; i++) {
|
|
357
|
+
const res = await req("/api/auth/login", {
|
|
358
|
+
method: "POST",
|
|
359
|
+
body: { username: "olive", password: "wrongpassword" },
|
|
360
|
+
ip: "198.51.100.5",
|
|
361
|
+
});
|
|
362
|
+
if (res.status === 429) { sawLimit = true; break; }
|
|
363
|
+
}
|
|
364
|
+
expect(sawLimit).toBe(true);
|
|
365
|
+
const row = await env.DB.prepare(`SELECT count FROM auth_attempts WHERE bucket_key = ?`)
|
|
366
|
+
.bind("login:198.51.100.5:olive")
|
|
367
|
+
.first<{ count: number }>();
|
|
368
|
+
expect(row).not.toBeNull();
|
|
369
|
+
expect(row!.count).toBeGreaterThanOrEqual(5);
|
|
370
|
+
});
|
|
371
|
+
});
|