@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.
Files changed (100) hide show
  1. package/LICENSE +235 -0
  2. package/NOTICE +3 -0
  3. package/README.md +114 -0
  4. package/index.js +195 -0
  5. package/package.json +44 -0
  6. package/template/CONTRIBUTING.md +80 -0
  7. package/template/LICENSE +235 -0
  8. package/template/MIGRATIONS.md +197 -0
  9. package/template/NOTICE +3 -0
  10. package/template/README.md +875 -0
  11. package/template/docs/legal/INSTANCE-ACCEPTABLE-USE.md +98 -0
  12. package/template/docs/legal/INSTANCE-PRIVACY.md +112 -0
  13. package/template/docs/legal/README.md +11 -0
  14. package/template/docs/screenshot-desktop.jpg +0 -0
  15. package/template/docs/screenshot-mobile.jpg +0 -0
  16. package/template/gitignore +23 -0
  17. package/template/migrate-v0.164.0.sql +6 -0
  18. package/template/migrate-v0.167.0.sql +44 -0
  19. package/template/migrate-v0.20.0.sql +40 -0
  20. package/template/migrate-v0.20.2.sql +19 -0
  21. package/template/migrate-v0.20.3.sql +36 -0
  22. package/template/migrations/0001_init.sql +134 -0
  23. package/template/package.json +32 -0
  24. package/template/public/app.js +2778 -0
  25. package/template/public/apple-touch-icon.png +0 -0
  26. package/template/public/favicon-16.png +0 -0
  27. package/template/public/favicon-32.png +0 -0
  28. package/template/public/favicon.svg +5 -0
  29. package/template/public/icon-192.png +0 -0
  30. package/template/public/icon-512.png +0 -0
  31. package/template/public/index.html +329 -0
  32. package/template/public/manifest.webmanifest +14 -0
  33. package/template/public/streaming-client.js +207 -0
  34. package/template/public/stt.html +68 -0
  35. package/template/public/stt.js +16 -0
  36. package/template/public/styles.css +2068 -0
  37. package/template/public/voice-widget.js +195 -0
  38. package/template/schema.sql +283 -0
  39. package/template/src/ai-binding.ts +33 -0
  40. package/template/src/auth-kdf.ts +106 -0
  41. package/template/src/auth.ts +315 -0
  42. package/template/src/chunking.ts +161 -0
  43. package/template/src/discord.ts +353 -0
  44. package/template/src/env.ts +55 -0
  45. package/template/src/gateway-credentials.ts +97 -0
  46. package/template/src/health-schema.ts +25 -0
  47. package/template/src/index.ts +4180 -0
  48. package/template/src/longrun-params.ts +135 -0
  49. package/template/src/models.ts +214 -0
  50. package/template/src/output-extract.ts +128 -0
  51. package/template/src/parsers/anthropic-sse.ts +56 -0
  52. package/template/src/parsers/gemini-sse.ts +62 -0
  53. package/template/src/parsers/openai-sse.ts +60 -0
  54. package/template/src/parsers/sse-framer.ts +39 -0
  55. package/template/src/parsers/types.ts +16 -0
  56. package/template/src/parsers/workers-ai-sse.ts +43 -0
  57. package/template/src/parsers/xai-sse.ts +40 -0
  58. package/template/src/providers/anthropic.ts +208 -0
  59. package/template/src/providers/google.ts +150 -0
  60. package/template/src/providers/openai.ts +69 -0
  61. package/template/src/providers/workers-ai.ts +83 -0
  62. package/template/src/providers/xai.ts +159 -0
  63. package/template/src/proxied-image-params.ts +43 -0
  64. package/template/src/rate-limit.ts +77 -0
  65. package/template/src/searxng.ts +75 -0
  66. package/template/src/session.ts +114 -0
  67. package/template/src/stt-session.ts +206 -0
  68. package/template/src/stt-util.ts +19 -0
  69. package/template/src/types.ts +56 -0
  70. package/template/src/user-prefs.ts +63 -0
  71. package/template/src/utils.ts +73 -0
  72. package/template/src/zip.ts +137 -0
  73. package/template/tests/anthropic-sse.test.ts +149 -0
  74. package/template/tests/auth-kdf.test.ts +59 -0
  75. package/template/tests/auth-unit.test.ts +97 -0
  76. package/template/tests/chunking.test.ts +217 -0
  77. package/template/tests/discord.test.ts +184 -0
  78. package/template/tests/gateway-credentials.test.ts +65 -0
  79. package/template/tests/gemini-sse.test.ts +75 -0
  80. package/template/tests/google-gemini.test.ts +65 -0
  81. package/template/tests/health-schema.test.ts +35 -0
  82. package/template/tests/longrun-params.test.ts +128 -0
  83. package/template/tests/openai-sse.test.ts +71 -0
  84. package/template/tests/output-extract.test.ts +171 -0
  85. package/template/tests/proxied-image-params.test.ts +51 -0
  86. package/template/tests/rate-limit.test.ts +45 -0
  87. package/template/tests/searxng.test.ts +51 -0
  88. package/template/tests/sse-framer.test.ts +113 -0
  89. package/template/tests/stt-session.test.ts +35 -0
  90. package/template/tests/utils.test.ts +39 -0
  91. package/template/tests/workers-ai-sse.test.ts +67 -0
  92. package/template/tests/xai-sse.test.ts +60 -0
  93. package/template/tests/zip.test.ts +145 -0
  94. package/template/tests-integration/auth.test.ts +371 -0
  95. package/template/tests-integration/worker.test.ts +322 -0
  96. package/template/tsconfig.json +18 -0
  97. package/template/vitest.config.ts +18 -0
  98. package/template/vitest.node.config.ts +19 -0
  99. package/template/vitest.workers.config.ts +47 -0
  100. package/template/wrangler.example.toml +151 -0
@@ -0,0 +1,195 @@
1
+ // Voice/STT building blocks (v0.108.0; createMicStreamer added v0.118.0).
2
+ //
3
+ // createMicStreamer: low-level mic capture -> linear16 PCM @ 16 kHz -> the
4
+ // /api/stt/stream WebSocket (SttSession DO -> @cf/deepgram/flux), parsing the
5
+ // Deepgram turn/event JSON frames. Returns { stop, setMuted }. Shared by the
6
+ // standalone STT panel (/stt.html) and the hands-free voice-chat loop in app.js.
7
+ //
8
+ // createVoiceWidget: the standalone STT panel UI (live captions + committed
9
+ // turns), built on createMicStreamer.
10
+ (function () {
11
+ "use strict";
12
+
13
+ // Deepgram Flux nests turn events under {type:"TurnInfo", event:"EndOfTurn"|
14
+ // "Update"|"StartOfTurn"|...}. (It used to be flat {type:"EndOfTurn"}; the API
15
+ // changed.) Normalize to the event name, tolerating both shapes.
16
+ window.fluxEventName = function fluxEventName(ev) {
17
+ if (!ev) return "";
18
+ if (ev.type === "TurnInfo") return ev.event || "";
19
+ return ev.type || ev.event || "";
20
+ };
21
+
22
+ window.createMicStreamer = function createMicStreamer(opts) {
23
+ const onEvent = (opts && opts.onEvent) || function () {};
24
+ const onStatus = (opts && opts.onStatus) || function () {};
25
+ const onClose = (opts && opts.onClose) || function () {};
26
+ let ws = null, audioCtx = null, source = null, processor = null, stream = null;
27
+ let muted = false, stopped = false;
28
+
29
+ function beginCapture() {
30
+ const Ctx = window.AudioContext || window.webkitAudioContext;
31
+ audioCtx = new Ctx({ sampleRate: 16000 });
32
+ source = audioCtx.createMediaStreamSource(stream);
33
+ // ScriptProcessor: deprecated but dependency-free + universal.
34
+ processor = audioCtx.createScriptProcessor(4096, 1, 1);
35
+ source.connect(processor);
36
+ processor.connect(audioCtx.destination);
37
+ processor.onaudioprocess = (e) => {
38
+ if (muted || !ws || ws.readyState !== WebSocket.OPEN) return;
39
+ const f32 = e.inputBuffer.getChannelData(0);
40
+ const i16 = new Int16Array(f32.length);
41
+ for (let i = 0; i < f32.length; i++) {
42
+ const s = Math.max(-1, Math.min(1, f32[i]));
43
+ i16[i] = s < 0 ? s * 0x8000 : s * 0x7fff;
44
+ }
45
+ ws.send(i16.buffer);
46
+ };
47
+ }
48
+
49
+ function teardownAudio() {
50
+ try { if (processor) { processor.disconnect(); processor.onaudioprocess = null; } } catch (_) {}
51
+ try { if (source) source.disconnect(); } catch (_) {}
52
+ try { if (audioCtx) audioCtx.close(); } catch (_) {}
53
+ try { if (stream) stream.getTracks().forEach((t) => t.stop()); } catch (_) {}
54
+ processor = source = audioCtx = stream = null;
55
+ }
56
+
57
+ async function start() {
58
+ onStatus("requesting microphone…");
59
+ try {
60
+ stream = await navigator.mediaDevices.getUserMedia({
61
+ audio: { channelCount: 1, echoCancellation: true, noiseSuppression: true },
62
+ });
63
+ } catch (err) {
64
+ onStatus("microphone denied: " + (err && err.message ? err.message : err));
65
+ stop();
66
+ return;
67
+ }
68
+ onStatus("connecting…");
69
+ const proto = location.protocol === "https:" ? "wss:" : "ws:";
70
+ ws = new WebSocket(`${proto}//${location.host}/api/stt/stream`);
71
+ ws.binaryType = "arraybuffer";
72
+ ws.onopen = () => { onStatus("listening"); beginCapture(); };
73
+ ws.onmessage = (e) => {
74
+ if (typeof e.data !== "string") return; // events are JSON text; ignore binary
75
+ let ev;
76
+ try { ev = JSON.parse(e.data); } catch { return; }
77
+ onEvent(ev);
78
+ };
79
+ ws.onerror = () => onStatus("socket error");
80
+ ws.onclose = (e) => { teardownAudio(); if (!stopped) onClose(e); };
81
+ }
82
+
83
+ function stop() {
84
+ stopped = true;
85
+ teardownAudio();
86
+ try { if (ws && ws.readyState <= 1) ws.close(1000, "client stop"); } catch (_) {}
87
+ ws = null;
88
+ }
89
+
90
+ start();
91
+ // setMuted pauses sending PCM (e.g. while the assistant is speaking) without
92
+ // tearing down the socket, so the session/turn context stays intact.
93
+ return { stop, setMuted: (m) => { muted = !!m; } };
94
+ };
95
+
96
+ window.createVoiceWidget = function createVoiceWidget(els) {
97
+ const { startBtn, statusEl, liveEl, turnsEl, debugEl } = els;
98
+ let streamer = null;
99
+ let running = false;
100
+ let interim = "";
101
+
102
+ function setStatus(s) { if (statusEl) statusEl.textContent = s; }
103
+
104
+ function debug(obj) {
105
+ if (!debugEl) return;
106
+ const row = document.createElement("div");
107
+ row.className = "stt-debug-row";
108
+ row.textContent = typeof obj === "string" ? obj : JSON.stringify(obj);
109
+ debugEl.prepend(row);
110
+ while (debugEl.childElementCount > 200) debugEl.removeChild(debugEl.lastChild);
111
+ }
112
+
113
+ function renderLive() {
114
+ liveEl.innerHTML = "";
115
+ if (interim) {
116
+ const span = document.createElement("span");
117
+ span.className = "stt-live-interim";
118
+ span.textContent = interim;
119
+ liveEl.appendChild(span);
120
+ } else {
121
+ liveEl.innerHTML = '<span class="stt-status">(listening…)</span>';
122
+ }
123
+ }
124
+
125
+ function commitTurn(text, meta) {
126
+ if (!text) return;
127
+ const div = document.createElement("div");
128
+ div.className = "stt-turn";
129
+ div.textContent = text;
130
+ if (meta) {
131
+ const m = document.createElement("div");
132
+ m.className = "stt-meta";
133
+ m.textContent = meta;
134
+ div.appendChild(m);
135
+ }
136
+ turnsEl.prepend(div);
137
+ }
138
+
139
+ function transcriptOf(ev) {
140
+ if (typeof ev.transcript === "string") return ev.transcript;
141
+ if (Array.isArray(ev.words)) return ev.words.map((w) => w.word ?? w.text ?? "").join(" ").trim();
142
+ if (typeof ev.text === "string") return ev.text;
143
+ return "";
144
+ }
145
+
146
+ function handleEvent(ev) {
147
+ debug(ev);
148
+ const type = window.fluxEventName(ev);
149
+ const text = transcriptOf(ev);
150
+ switch (type) {
151
+ case "StartOfTurn":
152
+ interim = ""; renderLive(); break;
153
+ case "Update":
154
+ case "EagerEndOfTurn":
155
+ interim = text; renderLive(); break;
156
+ case "TurnResumed":
157
+ renderLive(); break;
158
+ case "EndOfTurn": {
159
+ const conf = ev.end_of_turn_confidence;
160
+ commitTurn(text || interim, conf != null ? `end of turn · confidence ${conf}` : "end of turn");
161
+ interim = ""; renderLive(); break;
162
+ }
163
+ default:
164
+ if (text) { interim = text; renderLive(); }
165
+ break;
166
+ }
167
+ }
168
+
169
+ function start() {
170
+ if (running) return;
171
+ running = true;
172
+ startBtn.textContent = "Stop";
173
+ startBtn.classList.add("is-live");
174
+ interim = ""; renderLive();
175
+ streamer = window.createMicStreamer({
176
+ onEvent: handleEvent,
177
+ onStatus: (s) => setStatus(s === "listening" ? "listening, speak now" : s),
178
+ onClose: (e) => { setStatus(`closed (code ${e.code}${e.reason ? ", " + e.reason : ""}) · saved to history`); stop(); },
179
+ });
180
+ }
181
+
182
+ function stop() {
183
+ running = false;
184
+ startBtn.textContent = "Start listening";
185
+ startBtn.classList.remove("is-live");
186
+ if (streamer) { streamer.stop(); streamer = null; }
187
+ if (statusEl && statusEl.textContent.startsWith("listening")) setStatus("stopped");
188
+ }
189
+
190
+ startBtn.addEventListener("click", () => (running ? stop() : start()));
191
+ window.addEventListener("beforeunload", stop);
192
+
193
+ return { stop, isRunning: () => running };
194
+ };
195
+ })();
@@ -0,0 +1,283 @@
1
+ -- Chat history. One row per call to /api/chat.
2
+ --
3
+ -- user_email is set from the Cf-Access-Authenticated-User-Email header
4
+ -- injected by Cloudflare Access; local dev defaults to 'anonymous'.
5
+ --
6
+ -- model_type is 'chat' | 'image' | 'tts' | 'video'. Drives output rendering
7
+ -- on the client and dispatch logic on the server.
8
+ --
9
+ -- For model_type='video', the row is created with status='pending' and a
10
+ -- job_id pointing at the upstream provider's operation. The frontend polls
11
+ -- /api/job/:id, which advances the row to 'done' (downloading the bytes
12
+ -- into R2 + recording the output_artifact) or 'failed' (recording the error
13
+ -- in job_error).
14
+ --
15
+ -- output holds text for chat models, '' for image/tts/video.
16
+ -- output_artifact is JSON { key, mime, type } pointing to an R2 object for
17
+ -- non-text outputs (generated images, generated audio, generated video).
18
+ --
19
+ -- attachments is a JSON array as documented in the worker; audio attachments
20
+ -- store only the transcript, the raw audio is dropped.
21
+
22
+ CREATE TABLE IF NOT EXISTS chats (
23
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
24
+ user_email TEXT NOT NULL,
25
+ created_at TEXT NOT NULL DEFAULT (datetime('now')),
26
+ model TEXT NOT NULL,
27
+ model_type TEXT NOT NULL DEFAULT 'chat',
28
+ system_prompt TEXT,
29
+ user_input TEXT NOT NULL,
30
+ output TEXT NOT NULL DEFAULT '',
31
+ output_artifact TEXT,
32
+ attachments TEXT,
33
+ tokens_in INTEGER,
34
+ tokens_out INTEGER,
35
+ latency_ms INTEGER,
36
+ ai_gateway_log_id TEXT,
37
+ status TEXT NOT NULL DEFAULT 'done',
38
+ job_id TEXT,
39
+ job_provider TEXT,
40
+ job_error TEXT,
41
+ job_started_at TEXT,
42
+ retrieved_context TEXT,
43
+ -- Multi-turn (v0.10.0): chats with the same conversation_id form one thread.
44
+ -- turn_index is monotonically increasing within a conversation.
45
+ -- For backward compat, legacy rows are backfilled as conversation_id='legacy-<id>', turn_index=0.
46
+ conversation_id TEXT,
47
+ turn_index INTEGER
48
+ );
49
+
50
+ CREATE INDEX IF NOT EXISTS idx_chats_conversation
51
+ ON chats(conversation_id, turn_index);
52
+
53
+ CREATE INDEX IF NOT EXISTS idx_chats_user_created
54
+ ON chats(user_email, created_at DESC);
55
+
56
+ CREATE INDEX IF NOT EXISTS idx_chats_pending
57
+ ON chats(status, user_email) WHERE status = 'pending';
58
+
59
+ -- ---------- RAG: documents and chunks ----------
60
+ --
61
+ -- A document is one user-uploaded file (.txt or .md). Its raw bytes live
62
+ -- in R2 under the in/ prefix; this row tracks metadata. A document is
63
+ -- chunked at upload time and each chunk gets embedded and stored in
64
+ -- Vectorize. chunk rows link D1 text to Vectorize vector IDs so we can
65
+ -- do vector -> text lookups at retrieval time.
66
+ --
67
+ -- D1 doesn't honor PRAGMA foreign_keys, so the FK relationship below is
68
+ -- documentation only; the application code handles cascade-on-delete.
69
+
70
+ CREATE TABLE IF NOT EXISTS documents (
71
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
72
+ user_email TEXT NOT NULL,
73
+ created_at TEXT NOT NULL DEFAULT (datetime('now')),
74
+ filename TEXT NOT NULL,
75
+ mime TEXT NOT NULL,
76
+ r2_key TEXT NOT NULL,
77
+ size_bytes INTEGER NOT NULL,
78
+ total_chars INTEGER NOT NULL DEFAULT 0,
79
+ chunk_count INTEGER NOT NULL DEFAULT 0
80
+ );
81
+
82
+ CREATE INDEX IF NOT EXISTS idx_documents_user_created
83
+ ON documents(user_email, created_at DESC);
84
+
85
+ CREATE TABLE IF NOT EXISTS chunks (
86
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
87
+ document_id INTEGER NOT NULL,
88
+ user_email TEXT NOT NULL,
89
+ chunk_index INTEGER NOT NULL,
90
+ text TEXT NOT NULL,
91
+ vector_id TEXT NOT NULL,
92
+ page INTEGER, -- for PDFs: the source page (1-indexed)
93
+ sheet TEXT, -- for XLSX/XLS: the source sheet name
94
+ FOREIGN KEY (document_id) REFERENCES documents(id) ON DELETE CASCADE
95
+ );
96
+
97
+ CREATE INDEX IF NOT EXISTS idx_chunks_doc ON chunks(document_id);
98
+ CREATE INDEX IF NOT EXISTS idx_chunks_vector ON chunks(vector_id);
99
+ CREATE INDEX IF NOT EXISTS idx_chunks_user ON chunks(user_email);
100
+
101
+ -- ---------- Projects (v0.20.0) ----------
102
+ --
103
+ -- A project groups documents (and eventually conversations, in v0.20.1)
104
+ -- under a shared system prompt and retrieval scope. Documents can belong
105
+ -- to multiple projects via the project_documents join table.
106
+ --
107
+ -- system_prompt: when set, becomes the default system prompt for chats
108
+ -- created within this project. A per-turn system_prompt on the chat
109
+ -- request overrides this entirely (no append). Empty string and NULL
110
+ -- are equivalent semantically.
111
+ --
112
+ -- slug: derived from name at create time, used as a stable identifier
113
+ -- in URLs/storage. Auto-suffixed on collision per user_email
114
+ -- (mudd, mudd-2, mudd-3, ...). Renaming the project does not change the
115
+ -- slug, so frontends can safely use slug as a URL fragment.
116
+ --
117
+ -- Per-user scoping: all projects rows have a user_email; cross-user
118
+ -- access is enforced in application code (D1 doesn't honor FKs).
119
+
120
+ CREATE TABLE IF NOT EXISTS projects (
121
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
122
+ user_email TEXT NOT NULL,
123
+ name TEXT NOT NULL,
124
+ slug TEXT NOT NULL,
125
+ description TEXT,
126
+ system_prompt TEXT,
127
+ created_at TEXT NOT NULL DEFAULT (datetime('now')),
128
+ updated_at TEXT NOT NULL DEFAULT (datetime('now'))
129
+ );
130
+
131
+ CREATE INDEX IF NOT EXISTS idx_projects_user
132
+ ON projects(user_email, created_at DESC);
133
+
134
+ -- Slug uniqueness is per-user, not global. Two different users can both
135
+ -- have a project slugged 'mudd'.
136
+ CREATE UNIQUE INDEX IF NOT EXISTS idx_projects_slug_user
137
+ ON projects(user_email, slug);
138
+
139
+ -- ---------- Project membership (v0.20.0) ----------
140
+ --
141
+ -- Many-to-many: a document can live in multiple projects, a project
142
+ -- contains multiple documents. (project_id, document_id) is the natural
143
+ -- primary key. Both FK relationships cascade on delete via application
144
+ -- code (D1 ignores PRAGMA foreign_keys); deleting a project or document
145
+ -- cleans up its membership rows.
146
+ --
147
+ -- user_email lives on the projects and documents rows; this table doesn't
148
+ -- duplicate it. Cross-user membership is rejected by the route handlers
149
+ -- before insert.
150
+
151
+ CREATE TABLE IF NOT EXISTS project_documents (
152
+ project_id INTEGER NOT NULL,
153
+ document_id INTEGER NOT NULL,
154
+ added_at TEXT NOT NULL DEFAULT (datetime('now')),
155
+ PRIMARY KEY (project_id, document_id),
156
+ FOREIGN KEY (project_id) REFERENCES projects(id) ON DELETE CASCADE,
157
+ FOREIGN KEY (document_id) REFERENCES documents(id) ON DELETE CASCADE
158
+ );
159
+
160
+ CREATE INDEX IF NOT EXISTS idx_project_documents_doc
161
+ ON project_documents(document_id);
162
+
163
+ -- ---------- Conversation -> project association (v0.20.2) ----------
164
+ --
165
+ -- Adds project_id to existing chats rows so a chat turn can record which
166
+ -- project (if any) it was sent within. Nullable: pre-v0.20.2 rows and any
167
+ -- chat started without an active project carry NULL.
168
+ --
169
+ -- "Move chat to project" updates all rows in a conversation_id atomically,
170
+ -- so within one conversation the project_id is uniform. The conversation
171
+ -- list endpoint reads project_id from the conversation's earliest turn and
172
+ -- exposes it on the row so the sidebar can render a project chip.
173
+ --
174
+ -- This is an ALTER, so it's NOT idempotent like the CREATE TABLE IF NOT
175
+ -- EXISTS additions above. wrangler d1 execute is idempotent at the
176
+ -- migration-run level but ALTER would error on re-run. To make this safe
177
+ -- to re-apply, the ALTER is wrapped in a check against PRAGMA table_info.
178
+ -- Cleanest path: a fresh schema.sql apply on a database that already has
179
+ -- this column is a no-op.
180
+
181
+ -- Idempotent column add. SQLite doesn't support IF NOT EXISTS on ALTER TABLE
182
+ -- ADD COLUMN, so we use a defensive pattern: try the ALTER, catch the
183
+ -- "duplicate column" error at the app layer. For schema.sql re-runs on
184
+ -- already-migrated DBs, the ALTER will fail with "duplicate column name"
185
+ -- and `wrangler d1 execute` will treat it as a non-fatal warning per
186
+ -- statement, continuing to the next. The CREATE INDEX below is naturally
187
+ -- idempotent via IF NOT EXISTS.
188
+ ALTER TABLE chats ADD COLUMN project_id INTEGER;
189
+
190
+ CREATE INDEX IF NOT EXISTS idx_chats_project
191
+ ON chats(project_id, created_at DESC) WHERE project_id IS NOT NULL;
192
+
193
+ -- ---------- Discord ingestion (v0.20.3) ----------
194
+ --
195
+ -- project_messages stores raw Discord messages parsed from a DCE JSON export,
196
+ -- first-class, so the corpus can be re-chunked later (e.g. with an improved
197
+ -- chunker) without re-uploading the export. Retrieval does NOT read this
198
+ -- table; it reads chunks. This table exists purely for re-processing and
199
+ -- audit.
200
+ --
201
+ -- Tied to both the project (the import target) and the document (the uploaded
202
+ -- export file). Both cascade on delete via application code, consistent with
203
+ -- the rest of the schema (D1 ignores PRAGMA foreign_keys).
204
+
205
+ CREATE TABLE IF NOT EXISTS project_messages (
206
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
207
+ project_id INTEGER NOT NULL,
208
+ document_id INTEGER NOT NULL,
209
+ user_email TEXT NOT NULL,
210
+ message_id TEXT NOT NULL, -- Discord snowflake
211
+ channel TEXT NOT NULL,
212
+ author TEXT NOT NULL, -- display name (nickname or name)
213
+ author_id TEXT,
214
+ is_bot INTEGER NOT NULL DEFAULT 0,
215
+ sent_at TEXT NOT NULL, -- ISO8601
216
+ content TEXT NOT NULL,
217
+ FOREIGN KEY (project_id) REFERENCES projects(id) ON DELETE CASCADE,
218
+ FOREIGN KEY (document_id) REFERENCES documents(id) ON DELETE CASCADE
219
+ );
220
+
221
+ CREATE INDEX IF NOT EXISTS idx_project_messages_proj
222
+ ON project_messages(project_id, sent_at);
223
+ CREATE INDEX IF NOT EXISTS idx_project_messages_doc
224
+ ON project_messages(document_id);
225
+
226
+ -- Chunk metadata for conversation/Discord chunks (v0.20.3). Reuses the
227
+ -- existing chunks table, adding nullable columns analogous to page/sheet.
228
+ -- Document chunks leave these NULL; Discord chunks populate them. v0.20.4
229
+ -- retrieval filters (author/channel/date) will read these columns.
230
+ --
231
+ -- ALTER TABLE ADD COLUMN is not idempotent in SQLite; re-applying schema.sql
232
+ -- on an already-migrated DB surfaces "duplicate column name" per statement,
233
+ -- which wrangler d1 execute treats as a non-fatal warning and continues past.
234
+ ALTER TABLE chunks ADD COLUMN channel TEXT;
235
+ ALTER TABLE chunks ADD COLUMN authors TEXT; -- comma-joined distinct authors
236
+ ALTER TABLE chunks ADD COLUMN sent_at_start TEXT; -- ISO8601 earliest message
237
+ ALTER TABLE chunks ADD COLUMN sent_at_end TEXT; -- ISO8601 latest message
238
+
239
+ -- ---------- Per-user preferences (v0.164.0) ----------
240
+ --
241
+ -- JSON blob keyed by Cloudflare Access email. Public demo deployments store
242
+ -- each visitor's AI Gateway slug and CF API token here so the worker itself
243
+ -- needs no GATEWAY_ID / CF_AIG_TOKEN secrets.
244
+
245
+ CREATE TABLE IF NOT EXISTS user_prefs (
246
+ user_email TEXT PRIMARY KEY,
247
+ prefs_json TEXT NOT NULL DEFAULT '{}',
248
+ updated_at TEXT NOT NULL DEFAULT (datetime('now'))
249
+ );
250
+
251
+ -- ---------- First-party auth plane (v0.167.0, issue #80) ----------
252
+ --
253
+ -- Public-deployment accounts. In public mode (AUTH_MODE=public) the ownership
254
+ -- columns above (chats.user_email, documents.user_email, projects.user_email,
255
+ -- chunks.user_email, project_messages.user_email, user_prefs.user_email) hold
256
+ -- the opaque users.id string rather than a Cloudflare Access email; the column
257
+ -- name stays legacy and no existing row is migrated. See migrate-v0.167.0.sql
258
+ -- for the standalone delta and src/auth.ts / src/session.ts / src/rate-limit.ts
259
+ -- for the code that uses these.
260
+
261
+ CREATE TABLE IF NOT EXISTS users (
262
+ id TEXT PRIMARY KEY,
263
+ username TEXT NOT NULL,
264
+ username_lc TEXT NOT NULL UNIQUE,
265
+ password_hash TEXT NOT NULL,
266
+ email TEXT,
267
+ created_at TEXT NOT NULL DEFAULT (datetime('now'))
268
+ );
269
+
270
+ CREATE TABLE IF NOT EXISTS sessions (
271
+ token_hash TEXT PRIMARY KEY,
272
+ user_id TEXT NOT NULL,
273
+ created_at TEXT NOT NULL DEFAULT (datetime('now')),
274
+ expires_at TEXT NOT NULL
275
+ );
276
+
277
+ CREATE INDEX IF NOT EXISTS idx_sessions_user ON sessions(user_id);
278
+
279
+ CREATE TABLE IF NOT EXISTS auth_attempts (
280
+ bucket_key TEXT PRIMARY KEY,
281
+ count INTEGER NOT NULL DEFAULT 0,
282
+ window_start TEXT NOT NULL DEFAULT (datetime('now'))
283
+ );
@@ -0,0 +1,33 @@
1
+ // env.AI binding wrappers (v0.19.3; per-user gateway v0.164.0).
2
+ //
3
+ // Extracted from src/index.ts so provider modules and other code paths that
4
+ // call env.AI.run share one binding wrapper rather than each constructing its
5
+ // own opts object.
6
+ //
7
+ // `aiRun` is the standard call path: pass model, params, optional flag to
8
+ // return the raw Response (rather than a parsed object) for binary-output
9
+ // models like TTS.
10
+ //
11
+ // `aiLogId` reads the Cloudflare AI Gateway log ID from the env.AI binding
12
+ // after a call, when one exists.
13
+
14
+ import type { Env } from "./env";
15
+ import type { GatewayCredentials } from "./gateway-credentials";
16
+
17
+ export interface AiContext {
18
+ env: Env;
19
+ gateway: GatewayCredentials;
20
+ }
21
+
22
+ type RunOpts = { gateway: { id: string }; returnRawResponse?: boolean };
23
+ type RunFn = (model: string, params: unknown, opts?: RunOpts) => Promise<unknown>;
24
+
25
+ export function aiRun(ctx: AiContext, model: string, params: unknown, returnRaw = false): Promise<unknown> {
26
+ const opts: RunOpts = { gateway: { id: ctx.gateway.gatewayId } };
27
+ if (returnRaw) opts.returnRawResponse = true;
28
+ return (ctx.env.AI as unknown as { run: RunFn }).run(model, params, opts);
29
+ }
30
+
31
+ export function aiLogId(ctx: AiContext): string | null {
32
+ return (ctx.env.AI as unknown as { aiGatewayLogId?: string }).aiGatewayLogId ?? null;
33
+ }
@@ -0,0 +1,106 @@
1
+ // Password hashing for first-party auth (v0.167.0, issue #80).
2
+ //
3
+ // PBKDF2-HMAC-SHA-256 via WebCrypto SubtleCrypto: zero runtime dependency and
4
+ // available in the Workers runtime. scrypt/argon2 would each need a new runtime
5
+ // dep (CONTRIBUTING requires justification) and PBKDF2-native is adequate for
6
+ // the first cut. The stored value is a PHC-style string so the cost parameters
7
+ // travel with each hash and can be upgraded per-user on the next login (e.g. to
8
+ // an Argon2-WASM verifier later) without a schema migration:
9
+ //
10
+ // pbkdf2$sha256$<iterations>$<salt_b64>$<hash_b64>
11
+ //
12
+ // 600000 iterations is the OWASP 2023 floor for PBKDF2-HMAC-SHA256; it lands
13
+ // around 50-100ms on the paid Workers CPU budget, well inside the request CPU
14
+ // limit. Salt is 16 random bytes; the derived key is 32 bytes.
15
+
16
+ const KDF_ALGO = "pbkdf2";
17
+ const KDF_HASH = "sha256";
18
+ export const PBKDF2_ITERATIONS = 600000;
19
+ const SALT_BYTES = 16;
20
+ const KEY_BYTES = 32;
21
+
22
+ function toB64(bytes: Uint8Array): string {
23
+ let bin = "";
24
+ for (let i = 0; i < bytes.length; i++) bin += String.fromCharCode(bytes[i]);
25
+ return btoa(bin);
26
+ }
27
+
28
+ function fromB64(b64: string): Uint8Array {
29
+ const bin = atob(b64);
30
+ const out = new Uint8Array(bin.length);
31
+ for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);
32
+ return out;
33
+ }
34
+
35
+ // Fixed-length XOR-accumulate comparison. Workers has no crypto timingSafeEqual,
36
+ // so we compare two equal-length byte arrays in constant time relative to their
37
+ // length: unequal lengths return false immediately (a length leak is not a hash
38
+ // leak), equal lengths always walk the whole buffer.
39
+ export function constantTimeEqual(a: Uint8Array, b: Uint8Array): boolean {
40
+ if (a.length !== b.length) return false;
41
+ let diff = 0;
42
+ for (let i = 0; i < a.length; i++) diff |= a[i] ^ b[i];
43
+ return diff === 0;
44
+ }
45
+
46
+ async function deriveBits(
47
+ password: string,
48
+ salt: Uint8Array,
49
+ iterations: number,
50
+ keyBytes: number,
51
+ ): Promise<Uint8Array> {
52
+ const enc = new TextEncoder();
53
+ const keyMaterial = await crypto.subtle.importKey(
54
+ "raw",
55
+ enc.encode(password),
56
+ "PBKDF2",
57
+ false,
58
+ ["deriveBits"],
59
+ );
60
+ const bits = await crypto.subtle.deriveBits(
61
+ { name: "PBKDF2", hash: "SHA-256", salt, iterations },
62
+ keyMaterial,
63
+ keyBytes * 8,
64
+ );
65
+ return new Uint8Array(bits);
66
+ }
67
+
68
+ // Hash a password into a self-describing PHC string. A fresh random salt is
69
+ // generated per call, so two identical passwords never share a stored hash.
70
+ export async function hashPassword(password: string): Promise<string> {
71
+ const salt = crypto.getRandomValues(new Uint8Array(SALT_BYTES));
72
+ const derived = await deriveBits(password, salt, PBKDF2_ITERATIONS, KEY_BYTES);
73
+ return `${KDF_ALGO}$${KDF_HASH}$${PBKDF2_ITERATIONS}$${toB64(salt)}$${toB64(derived)}`;
74
+ }
75
+
76
+ interface ParsedPhc {
77
+ iterations: number;
78
+ salt: Uint8Array;
79
+ hash: Uint8Array;
80
+ }
81
+
82
+ // Parse a stored PHC string. Returns null on any structural mismatch (unknown
83
+ // algo/hash, non-numeric iterations, bad base64) so verify fails closed rather
84
+ // than throwing on a corrupt row.
85
+ export function parsePhc(stored: string): ParsedPhc | null {
86
+ const parts = stored.split("$");
87
+ if (parts.length !== 5) return null;
88
+ const [algo, hashName, iterStr, saltB64, hashB64] = parts;
89
+ if (algo !== KDF_ALGO || hashName !== KDF_HASH) return null;
90
+ const iterations = Number(iterStr);
91
+ if (!Number.isInteger(iterations) || iterations <= 0) return null;
92
+ try {
93
+ return { iterations, salt: fromB64(saltB64), hash: fromB64(hashB64) };
94
+ } catch {
95
+ return null;
96
+ }
97
+ }
98
+
99
+ // Verify a candidate password against a stored PHC string. Constant-time on the
100
+ // digest compare; returns false for any malformed stored value.
101
+ export async function verifyPassword(password: string, stored: string): Promise<boolean> {
102
+ const parsed = parsePhc(stored);
103
+ if (!parsed) return false;
104
+ const derived = await deriveBits(password, parsed.salt, parsed.iterations, parsed.hash.length);
105
+ return constantTimeEqual(derived, parsed.hash);
106
+ }