@thready-web/dsh-bot-plugin 0.1.0-beta.10 → 0.1.0-beta.12
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 +19 -2
- package/dist/approvals.js +19 -1
- package/dist/canvas-compose.js +73 -0
- package/dist/canvas-http.js +379 -0
- package/dist/canvas-skills.js +56 -0
- package/dist/canvas-store.js +1015 -0
- package/dist/canvas-tools.js +380 -0
- package/dist/card-log.js +216 -0
- package/dist/context.js +6 -3
- package/dist/deleting.js +54 -0
- package/dist/desk-ledger.js +18 -0
- package/dist/desk.js +30 -5
- package/dist/http-plugin.js +2 -1
- package/dist/http.js +218 -3
- package/dist/inbox.js +24 -2
- package/dist/index.js +75 -12
- package/dist/questions.js +10 -0
- package/dist/runtime-registry.js +20 -0
- package/dist/session-delete-job.js +77 -0
- package/dist/session-files.js +33 -1
- package/dist/session-wipe.js +204 -0
- package/dist/store.js +46 -3
- package/dist/triggers.js +8 -0
- package/dist/work-admit.js +9 -20
- package/dist/work-child.js +27 -10
- package/dist/work-http.js +19 -0
- package/dist/work-ledger.js +5 -1
- package/dist/work-mock.js +10 -0
- package/dist/work-tickets.js +5 -3
- package/dist/work-tools.js +11 -9
- package/dist/work-worker.js +245 -6
- package/dist/worker-handles.js +33 -0
- package/dist/workspace-files.js +98 -17
- package/package.json +2 -1
- package/public/assets/{SourceEditor-BEQaScgR.js → SourceEditor-BjtoMvcX.js} +3 -3
- package/public/assets/{cssMode-gpcjCFFS.js → cssMode--96PQtWh.js} +1 -1
- package/public/assets/{freemarker2-C1qemGIt.js → freemarker2-Bz-HlISL.js} +1 -1
- package/public/assets/{handlebars-sZqIfAlP.js → handlebars-D9ScJ8AM.js} +1 -1
- package/public/assets/{html-Bn1WXB8L.js → html-Czc0jojJ.js} +1 -1
- package/public/assets/{htmlMode-CvQyXnaW.js → htmlMode-CCww5Z1w.js} +1 -1
- package/public/assets/index-DRCgKxWk.css +1 -0
- package/public/assets/index-ztUdW074.js +72 -0
- package/public/assets/{javascript-Ox4Jg12j.js → javascript-B-yRZSiz.js} +1 -1
- package/public/assets/{jsonMode-DMR7R2dQ.js → jsonMode-ASWsY833.js} +1 -1
- package/public/assets/{liquid-B6HxtpBd.js → liquid-BGoox2vJ.js} +1 -1
- package/public/assets/{mdx--jDhmrXq.js → mdx-DHgvnl_U.js} +1 -1
- package/public/assets/{python-YjG50skX.js → python-BJvVD30_.js} +1 -1
- package/public/assets/{razor-CEcFE3UK.js → razor-0PwR35mu.js} +1 -1
- package/public/assets/{tsMode-g4kTQl09.js → tsMode-3ETp8Gdh.js} +1 -1
- package/public/assets/{typescript-CnHeFmPW.js → typescript-BT0iTK6K.js} +1 -1
- package/public/assets/{xml-BFXMY9nb.js → xml-BTaNc_uT.js} +1 -1
- package/public/assets/{yaml-DNm87nSf.js → yaml-Dr7LW3tK.js} +1 -1
- package/public/index.html +2 -2
- package/skills/ui/baseline-ui/SKILL.md +85 -0
- package/skills/ui/bencium-innovative-ux-designer/SKILL.md +227 -0
- package/skills/ui/better-ui/SKILL.md +133 -0
- package/skills/ui/design-lab/SKILL.md +920 -0
- package/skills/ui/frontend-design/SKILL.md +71 -0
- package/skills/ui/impeccable/SKILL.md +93 -0
- package/skills/ui/interface-design/SKILL.md +320 -0
- package/skills/ui/sources.json +66 -0
- package/skills/ui/ui-design/SKILL.md +41 -0
- package/skills/ui/ui-skills-root/SKILL.md +59 -0
- package/skills/ui/visual-design-foundations/SKILL.md +318 -0
- package/skills/ui/web-design-guidelines/SKILL.md +39 -0
- package/public/assets/index-DRNkUrer.css +0 -1
- package/public/assets/index-DhL5Kdlz.js +0 -63
|
@@ -0,0 +1,1015 @@
|
|
|
1
|
+
import { randomBytes } from 'node:crypto';
|
|
2
|
+
import { chmodSync, mkdirSync } from 'node:fs';
|
|
3
|
+
import { dirname } from 'node:path';
|
|
4
|
+
import { DatabaseSync } from 'node:sqlite';
|
|
5
|
+
import { asStoreFailure, toolError } from "./errors.js";
|
|
6
|
+
import { sha256 } from "./fs-safe.js";
|
|
7
|
+
/** Hard caps from the canvas plan. Adjusting them still has to keep a ceiling. */
|
|
8
|
+
export const CANVAS_MAX_FILE_BYTES = Math.floor(1.5 * 1024 * 1024);
|
|
9
|
+
export const CANVAS_MAX_PACKAGE_BYTES = 8 * 1024 * 1024;
|
|
10
|
+
export const CANVAS_MAX_FILES = 64;
|
|
11
|
+
export const CANVAS_KEEP_REVISIONS = 20;
|
|
12
|
+
export const CANVAS_TOKEN_TTL_MS = 15 * 60 * 1000;
|
|
13
|
+
export const CANVAS_MAX_JSON_BYTES = 12 * 1024 * 1024;
|
|
14
|
+
const SESSION_ID = /^[A-Za-z0-9][A-Za-z0-9._-]{0,200}$/;
|
|
15
|
+
const CANVAS_ID = /^cnv_[A-Za-z0-9_-]{16}$/;
|
|
16
|
+
const TYPES = new Map([
|
|
17
|
+
['text/html', ['.html', '.htm']],
|
|
18
|
+
['text/css', ['.css']],
|
|
19
|
+
['image/png', ['.png']],
|
|
20
|
+
['image/jpeg', ['.jpg', '.jpeg']],
|
|
21
|
+
['image/gif', ['.gif']],
|
|
22
|
+
['image/webp', ['.webp']],
|
|
23
|
+
['font/woff', ['.woff']],
|
|
24
|
+
['font/woff2', ['.woff2']],
|
|
25
|
+
['font/ttf', ['.ttf']],
|
|
26
|
+
['font/otf', ['.otf']],
|
|
27
|
+
]);
|
|
28
|
+
const SCHEMA = `
|
|
29
|
+
PRAGMA foreign_keys = ON;
|
|
30
|
+
|
|
31
|
+
CREATE TABLE IF NOT EXISTS canvases (
|
|
32
|
+
id TEXT PRIMARY KEY,
|
|
33
|
+
session_id TEXT NOT NULL,
|
|
34
|
+
ticket_id TEXT,
|
|
35
|
+
title TEXT NOT NULL DEFAULT '',
|
|
36
|
+
stable_revision INTEGER,
|
|
37
|
+
preview_revision INTEGER,
|
|
38
|
+
fence_generation INTEGER NOT NULL DEFAULT 0,
|
|
39
|
+
created_by TEXT NOT NULL,
|
|
40
|
+
created_at TEXT NOT NULL
|
|
41
|
+
);
|
|
42
|
+
CREATE INDEX IF NOT EXISTS canvases_session ON canvases(session_id, created_at);
|
|
43
|
+
|
|
44
|
+
CREATE TABLE IF NOT EXISTS canvas_revisions (
|
|
45
|
+
canvas_id TEXT NOT NULL REFERENCES canvases(id),
|
|
46
|
+
revision INTEGER NOT NULL,
|
|
47
|
+
parent INTEGER,
|
|
48
|
+
kind TEXT NOT NULL CHECK (kind IN ('snapshot','delta','failed')),
|
|
49
|
+
entry TEXT,
|
|
50
|
+
status TEXT NOT NULL CHECK (status IN ('preview','stable','failed')),
|
|
51
|
+
hash TEXT,
|
|
52
|
+
error TEXT,
|
|
53
|
+
created_at TEXT NOT NULL,
|
|
54
|
+
PRIMARY KEY (canvas_id, revision)
|
|
55
|
+
);
|
|
56
|
+
|
|
57
|
+
CREATE TABLE IF NOT EXISTS canvas_blobs (
|
|
58
|
+
hash TEXT PRIMARY KEY,
|
|
59
|
+
bytes BLOB NOT NULL,
|
|
60
|
+
size INTEGER NOT NULL
|
|
61
|
+
);
|
|
62
|
+
|
|
63
|
+
CREATE TABLE IF NOT EXISTS canvas_files (
|
|
64
|
+
canvas_id TEXT NOT NULL,
|
|
65
|
+
revision INTEGER NOT NULL,
|
|
66
|
+
path TEXT NOT NULL,
|
|
67
|
+
hash TEXT NOT NULL,
|
|
68
|
+
media_type TEXT NOT NULL,
|
|
69
|
+
size INTEGER NOT NULL,
|
|
70
|
+
PRIMARY KEY (canvas_id, revision, path),
|
|
71
|
+
FOREIGN KEY (canvas_id, revision) REFERENCES canvas_revisions(canvas_id, revision)
|
|
72
|
+
);
|
|
73
|
+
|
|
74
|
+
CREATE TABLE IF NOT EXISTS canvas_tokens (
|
|
75
|
+
id TEXT PRIMARY KEY,
|
|
76
|
+
canvas_id TEXT NOT NULL REFERENCES canvases(id),
|
|
77
|
+
token_hash TEXT NOT NULL UNIQUE,
|
|
78
|
+
min_revision INTEGER NOT NULL,
|
|
79
|
+
max_revision INTEGER NOT NULL,
|
|
80
|
+
expires_at TEXT NOT NULL,
|
|
81
|
+
revoked_at TEXT
|
|
82
|
+
);
|
|
83
|
+
|
|
84
|
+
CREATE TABLE IF NOT EXISTS canvas_drafts (
|
|
85
|
+
canvas_id TEXT NOT NULL,
|
|
86
|
+
path TEXT NOT NULL,
|
|
87
|
+
media_type TEXT NOT NULL,
|
|
88
|
+
bytes BLOB NOT NULL,
|
|
89
|
+
updated_at TEXT NOT NULL,
|
|
90
|
+
PRIMARY KEY (canvas_id, path)
|
|
91
|
+
);
|
|
92
|
+
|
|
93
|
+
CREATE TABLE IF NOT EXISTS canvas_ticket_publishes (
|
|
94
|
+
ticket_id TEXT PRIMARY KEY,
|
|
95
|
+
canvas_id TEXT NOT NULL,
|
|
96
|
+
revision INTEGER NOT NULL
|
|
97
|
+
);
|
|
98
|
+
`;
|
|
99
|
+
/**
|
|
100
|
+
* Relative canvas path. Rejects traversal, absolute paths, encoding, and dotfiles.
|
|
101
|
+
* The media route checks the raw URL before this runs.
|
|
102
|
+
*/
|
|
103
|
+
export function normalizeCanvasPath(input) {
|
|
104
|
+
if (typeof input !== 'string' || input.length === 0 || input.length > 200)
|
|
105
|
+
return null;
|
|
106
|
+
if (input.includes('\0') || input.includes('\\') || input.includes('%') || input.includes('..'))
|
|
107
|
+
return null;
|
|
108
|
+
if (input.startsWith('/'))
|
|
109
|
+
return null;
|
|
110
|
+
const parts = input.split('/');
|
|
111
|
+
if (parts.some(part => part === '' || part === '.' || part === '..' || part.startsWith('.') || part.length > 120))
|
|
112
|
+
return null;
|
|
113
|
+
return parts.join('/');
|
|
114
|
+
}
|
|
115
|
+
function nowIso() {
|
|
116
|
+
return new Date().toISOString();
|
|
117
|
+
}
|
|
118
|
+
function extensionOf(path) {
|
|
119
|
+
const name = path.slice(path.lastIndexOf('/') + 1);
|
|
120
|
+
const dot = name.lastIndexOf('.');
|
|
121
|
+
return dot < 0 ? '' : name.slice(dot).toLowerCase();
|
|
122
|
+
}
|
|
123
|
+
function rasterOk(type, bytes) {
|
|
124
|
+
if (type === 'image/jpeg')
|
|
125
|
+
return bytes.length >= 3 && bytes[0] === 0xff && bytes[1] === 0xd8 && bytes[2] === 0xff;
|
|
126
|
+
if (type === 'image/png')
|
|
127
|
+
return bytes.length >= 8 && bytes.subarray(0, 8).equals(Buffer.from('89504e470d0a1a0a', 'hex'));
|
|
128
|
+
if (type === 'image/gif')
|
|
129
|
+
return bytes.length >= 6 && /^GIF8[79]a/.test(bytes.subarray(0, 6).toString('ascii'));
|
|
130
|
+
if (type === 'image/webp')
|
|
131
|
+
return (bytes.length >= 12 &&
|
|
132
|
+
bytes.subarray(0, 4).toString('ascii') === 'RIFF' &&
|
|
133
|
+
bytes.subarray(8, 12).toString('ascii') === 'WEBP');
|
|
134
|
+
return true;
|
|
135
|
+
}
|
|
136
|
+
/** Auxiliary check. The sandbox and CSP stay in force even if this misses something. */
|
|
137
|
+
function activeContent(type, bytes) {
|
|
138
|
+
if (type.startsWith('font/')) {
|
|
139
|
+
const head = bytes.subarray(0, 64).toString('utf8').trimStart();
|
|
140
|
+
if (head.startsWith('<'))
|
|
141
|
+
return 'Font files cannot be markup.';
|
|
142
|
+
return null;
|
|
143
|
+
}
|
|
144
|
+
if (type !== 'text/html' && type !== 'text/css')
|
|
145
|
+
return null;
|
|
146
|
+
const text = bytes.toString('utf8');
|
|
147
|
+
const lower = text.toLowerCase();
|
|
148
|
+
if (lower.includes('<script') ||
|
|
149
|
+
lower.includes('javascript:') ||
|
|
150
|
+
lower.includes('data:') ||
|
|
151
|
+
lower.includes('<svg') ||
|
|
152
|
+
lower.includes('<base') ||
|
|
153
|
+
lower.includes('<iframe') ||
|
|
154
|
+
lower.includes('<object') ||
|
|
155
|
+
lower.includes('<embed') ||
|
|
156
|
+
lower.includes('<meta'))
|
|
157
|
+
return 'Canvas documents cannot include scripts, SVG, or document controls.';
|
|
158
|
+
if (/https?:\/\//i.test(text) || text.includes('//') || /url\(\s*['"]?\s*(?:[a-z]+:|\/\/)/i.test(text))
|
|
159
|
+
return 'Canvas documents cannot reference external URLs.';
|
|
160
|
+
if (type === 'text/css' && /@import/i.test(text))
|
|
161
|
+
return 'Canvas stylesheets cannot use @import.';
|
|
162
|
+
return null;
|
|
163
|
+
}
|
|
164
|
+
function shorterThanCurrent(file, previous) {
|
|
165
|
+
if (file.type.toLowerCase() !== 'text/html')
|
|
166
|
+
return null;
|
|
167
|
+
if (previous == null || previous < 1)
|
|
168
|
+
return null;
|
|
169
|
+
if (file.bytes.length * 2 >= previous)
|
|
170
|
+
return null;
|
|
171
|
+
return `${file.path} is much shorter than the current revision (${file.bytes.length} bytes vs ${previous}).`;
|
|
172
|
+
}
|
|
173
|
+
function stageProblem(file) {
|
|
174
|
+
const path = normalizeCanvasPath(file?.path);
|
|
175
|
+
if (!path)
|
|
176
|
+
return 'A canvas path is not allowed.';
|
|
177
|
+
const type = typeof file.type === 'string' ? file.type.toLowerCase() : '';
|
|
178
|
+
const extensions = TYPES.get(type);
|
|
179
|
+
if (!extensions || !extensions.includes(extensionOf(path)))
|
|
180
|
+
return `File type is not allowed for ${path}.`;
|
|
181
|
+
if (!Buffer.isBuffer(file.bytes))
|
|
182
|
+
return `Missing bytes for ${path}.`;
|
|
183
|
+
if (file.bytes.length > CANVAS_MAX_FILE_BYTES)
|
|
184
|
+
return `${path} exceeds the 1.5 MiB file cap.`;
|
|
185
|
+
if (!rasterOk(type, file.bytes))
|
|
186
|
+
return `${path} does not match its image type.`;
|
|
187
|
+
const active = activeContent(type, file.bytes);
|
|
188
|
+
if (active)
|
|
189
|
+
return active;
|
|
190
|
+
if (type === 'text/html' && !/<\/html\s*>/i.test(file.bytes.toString('utf8')))
|
|
191
|
+
return `${path} is incomplete HTML. It needs a closing </html> tag.`;
|
|
192
|
+
return null;
|
|
193
|
+
}
|
|
194
|
+
function checkFiles(entry, files) {
|
|
195
|
+
const entryPath = normalizeCanvasPath(entry);
|
|
196
|
+
if (!entryPath)
|
|
197
|
+
return toolError('VALIDATION', 'entry path is not allowed.');
|
|
198
|
+
if (!Array.isArray(files) || files.length === 0 || files.length > CANVAS_MAX_FILES)
|
|
199
|
+
return toolError('VALIDATION', 'A canvas revision needs between 1 and 64 files.');
|
|
200
|
+
const seen = new Set();
|
|
201
|
+
const manifest = [];
|
|
202
|
+
let total = 0;
|
|
203
|
+
for (const file of files) {
|
|
204
|
+
const problem = stageProblem(file);
|
|
205
|
+
if (problem)
|
|
206
|
+
return toolError('VALIDATION', problem);
|
|
207
|
+
const path = normalizeCanvasPath(file.path);
|
|
208
|
+
if (!path || seen.has(path))
|
|
209
|
+
return toolError('VALIDATION', `Duplicate canvas path ${path ?? ''}.`);
|
|
210
|
+
seen.add(path);
|
|
211
|
+
const type = file.type.toLowerCase();
|
|
212
|
+
total += file.bytes.length;
|
|
213
|
+
if (total > CANVAS_MAX_PACKAGE_BYTES)
|
|
214
|
+
return toolError('VALIDATION', 'The canvas package exceeds 8 MiB.');
|
|
215
|
+
manifest.push({ path, hash: `sha256:${sha256(file.bytes)}`, bytes: file.bytes.length, type });
|
|
216
|
+
}
|
|
217
|
+
if (!manifest.some(item => item.path === entryPath && item.type === 'text/html'))
|
|
218
|
+
return toolError('VALIDATION', 'entry must be an HTML file in this revision.');
|
|
219
|
+
if ((files.find(file => normalizeCanvasPath(file.path) === entryPath)?.bytes.length ?? 0) === 0)
|
|
220
|
+
return toolError('VALIDATION', 'entry HTML is empty.');
|
|
221
|
+
return manifest;
|
|
222
|
+
}
|
|
223
|
+
function manifestHash(items) {
|
|
224
|
+
const ordered = [...items].sort((left, right) => (left.path < right.path ? -1 : left.path > right.path ? 1 : 0));
|
|
225
|
+
return sha256(JSON.stringify(ordered));
|
|
226
|
+
}
|
|
227
|
+
function migrateCanvas(db) {
|
|
228
|
+
const columns = db.prepare('PRAGMA table_info(canvases)').all();
|
|
229
|
+
if (!columns.some(column => column.name === 'idempotency_key')) {
|
|
230
|
+
db.exec('ALTER TABLE canvases ADD COLUMN idempotency_key TEXT');
|
|
231
|
+
}
|
|
232
|
+
if (!columns.some(column => column.name === 'writer_ticket_id')) {
|
|
233
|
+
db.exec('ALTER TABLE canvases ADD COLUMN writer_ticket_id TEXT');
|
|
234
|
+
}
|
|
235
|
+
db.exec('CREATE UNIQUE INDEX IF NOT EXISTS canvas_idempotency ON canvases(session_id, idempotency_key) WHERE idempotency_key IS NOT NULL');
|
|
236
|
+
}
|
|
237
|
+
/**
|
|
238
|
+
* Canvas metadata, staged drafts, and deduplicated blobs.
|
|
239
|
+
* Manual HTTP publish and the canvas worker both write here.
|
|
240
|
+
* @param {string} file
|
|
241
|
+
*/
|
|
242
|
+
export function openCanvasStore(file) {
|
|
243
|
+
mkdirSync(dirname(file), { recursive: true, mode: 0o700 });
|
|
244
|
+
const db = new DatabaseSync(file);
|
|
245
|
+
db.exec('PRAGMA foreign_keys = ON');
|
|
246
|
+
db.exec('PRAGMA journal_mode = WAL');
|
|
247
|
+
db.exec('PRAGMA busy_timeout = 5000');
|
|
248
|
+
db.exec(SCHEMA);
|
|
249
|
+
migrateCanvas(db);
|
|
250
|
+
try {
|
|
251
|
+
chmodSync(file, 0o600);
|
|
252
|
+
}
|
|
253
|
+
catch {
|
|
254
|
+
/* the directory mode still limits it */
|
|
255
|
+
}
|
|
256
|
+
const store = new CanvasStore(db);
|
|
257
|
+
store.seed();
|
|
258
|
+
return store;
|
|
259
|
+
}
|
|
260
|
+
export class CanvasStore {
|
|
261
|
+
db;
|
|
262
|
+
tails;
|
|
263
|
+
notices;
|
|
264
|
+
publishListeners;
|
|
265
|
+
constructor(db) {
|
|
266
|
+
this.db = db;
|
|
267
|
+
this.tails = new Map();
|
|
268
|
+
this.notices = new Map();
|
|
269
|
+
this.publishListeners = new Set();
|
|
270
|
+
}
|
|
271
|
+
/** Fired after a preview revision commits. A listener must not fail the publish. */
|
|
272
|
+
onPublished(listener) {
|
|
273
|
+
this.publishListeners.add(listener);
|
|
274
|
+
return () => {
|
|
275
|
+
this.publishListeners.delete(listener);
|
|
276
|
+
};
|
|
277
|
+
}
|
|
278
|
+
close() {
|
|
279
|
+
this.db.close();
|
|
280
|
+
}
|
|
281
|
+
/** Drop canvases owned by these sessions, then blobs no remaining file uses. */
|
|
282
|
+
deleteSessions(sessionIds) {
|
|
283
|
+
const ids = [...new Set(sessionIds.filter(id => id !== ''))];
|
|
284
|
+
if (ids.length === 0)
|
|
285
|
+
return;
|
|
286
|
+
const marks = ids.map(() => '?').join(', ');
|
|
287
|
+
let canvasIds = [];
|
|
288
|
+
this.db.exec('BEGIN IMMEDIATE');
|
|
289
|
+
try {
|
|
290
|
+
canvasIds = this.db.prepare(`SELECT id FROM canvases WHERE session_id IN (${marks})`).all(...ids).map(row => row.id);
|
|
291
|
+
if (canvasIds.length > 0) {
|
|
292
|
+
const canvasMarks = canvasIds.map(() => '?').join(', ');
|
|
293
|
+
this.db.prepare(`DELETE FROM canvas_files WHERE canvas_id IN (${canvasMarks})`).run(...canvasIds);
|
|
294
|
+
this.db.prepare(`DELETE FROM canvas_drafts WHERE canvas_id IN (${canvasMarks})`).run(...canvasIds);
|
|
295
|
+
this.db.prepare(`DELETE FROM canvas_tokens WHERE canvas_id IN (${canvasMarks})`).run(...canvasIds);
|
|
296
|
+
this.db.prepare(`DELETE FROM canvas_revisions WHERE canvas_id IN (${canvasMarks})`).run(...canvasIds);
|
|
297
|
+
this.db.prepare(`DELETE FROM canvases WHERE id IN (${canvasMarks})`).run(...canvasIds);
|
|
298
|
+
}
|
|
299
|
+
this.db.prepare('DELETE FROM canvas_blobs WHERE hash NOT IN (SELECT hash FROM canvas_files)').run();
|
|
300
|
+
this.db.exec('COMMIT');
|
|
301
|
+
}
|
|
302
|
+
catch (error) {
|
|
303
|
+
try {
|
|
304
|
+
this.db.exec('ROLLBACK');
|
|
305
|
+
}
|
|
306
|
+
catch {
|
|
307
|
+
/* already rolled back */
|
|
308
|
+
}
|
|
309
|
+
throw error;
|
|
310
|
+
}
|
|
311
|
+
for (const [id, notice] of this.notices) {
|
|
312
|
+
if (ids.includes(notice.sessionId) || canvasIds.includes(id))
|
|
313
|
+
this.notices.delete(id);
|
|
314
|
+
}
|
|
315
|
+
}
|
|
316
|
+
/** Latest renderable revision per canvas, so a restarted process can still notify. */
|
|
317
|
+
seed() {
|
|
318
|
+
const rows = this.db
|
|
319
|
+
.prepare(`SELECT id, session_id, preview_revision, fence_generation
|
|
320
|
+
FROM canvases WHERE preview_revision IS NOT NULL`)
|
|
321
|
+
.all();
|
|
322
|
+
for (const row of rows) {
|
|
323
|
+
const revision = this.db
|
|
324
|
+
.prepare(`SELECT revision, parent, kind, status FROM canvas_revisions WHERE canvas_id = ? AND revision = ?`)
|
|
325
|
+
.get(row.id, row.preview_revision);
|
|
326
|
+
if (!revision || revision.status === 'failed' || revision.kind === 'failed')
|
|
327
|
+
continue;
|
|
328
|
+
this.remember(row.session_id, row.id, revision, row.fence_generation);
|
|
329
|
+
}
|
|
330
|
+
}
|
|
331
|
+
/** Compact notices for one session. Bodies stay on the media route. */
|
|
332
|
+
live(sessionId) {
|
|
333
|
+
if (!SESSION_ID.test(sessionId))
|
|
334
|
+
return { ok: true, events: [] };
|
|
335
|
+
const rows = this.db
|
|
336
|
+
.prepare(`SELECT c.id AS canvas_id, c.fence_generation, r.revision, r.parent, r.kind
|
|
337
|
+
FROM canvases c
|
|
338
|
+
JOIN canvas_revisions r ON r.canvas_id = c.id AND r.revision = c.preview_revision
|
|
339
|
+
WHERE c.session_id = ? AND r.kind IN ('snapshot', 'delta') AND r.status != 'failed'
|
|
340
|
+
ORDER BY c.id ASC`)
|
|
341
|
+
.all(sessionId);
|
|
342
|
+
return {
|
|
343
|
+
ok: true,
|
|
344
|
+
events: rows.map(row => ({
|
|
345
|
+
type: 'canvas.revision',
|
|
346
|
+
canvasId: String(row.canvas_id),
|
|
347
|
+
revision: Number(row.revision),
|
|
348
|
+
baseRevision: row.parent == null ? null : Number(row.parent),
|
|
349
|
+
kind: row.kind,
|
|
350
|
+
stamp: `${row.canvas_id}:${row.revision}:${row.fence_generation}`,
|
|
351
|
+
})),
|
|
352
|
+
};
|
|
353
|
+
}
|
|
354
|
+
create(input) {
|
|
355
|
+
if (typeof input.sessionId !== 'string' || !SESSION_ID.test(input.sessionId))
|
|
356
|
+
return toolError('VALIDATION', 'sessionId is not allowed.');
|
|
357
|
+
if (input.title != null && typeof input.title !== 'string')
|
|
358
|
+
return toolError('VALIDATION', 'title is not allowed.');
|
|
359
|
+
const title = typeof input.title === 'string' ? input.title.trim() : '';
|
|
360
|
+
if (title.length > 120)
|
|
361
|
+
return toolError('VALIDATION', 'title is too long.');
|
|
362
|
+
const ticketId = input.ticketId ?? null;
|
|
363
|
+
if (ticketId != null && (typeof ticketId !== 'string' || ticketId.length > 80))
|
|
364
|
+
return toolError('VALIDATION', 'ticketId is not allowed.');
|
|
365
|
+
const idempotencyKey = input.idempotencyKey ?? null;
|
|
366
|
+
if (idempotencyKey != null && (idempotencyKey.length < 8 || idempotencyKey.length > 128))
|
|
367
|
+
return toolError('VALIDATION', 'idempotencyKey is not allowed.');
|
|
368
|
+
if (idempotencyKey) {
|
|
369
|
+
const existing = this.findIdempotent(input.sessionId, idempotencyKey);
|
|
370
|
+
if (existing)
|
|
371
|
+
return { ok: true, canvas: this.canvasRow(existing) };
|
|
372
|
+
}
|
|
373
|
+
const id = `cnv_${randomBytes(12).toString('base64url')}`;
|
|
374
|
+
const createdAt = nowIso();
|
|
375
|
+
try {
|
|
376
|
+
this.db
|
|
377
|
+
.prepare(`INSERT INTO canvases (
|
|
378
|
+
id, session_id, ticket_id, title, stable_revision, preview_revision, fence_generation, created_by, created_at, idempotency_key
|
|
379
|
+
) VALUES (?, ?, ?, ?, NULL, NULL, 0, ?, ?, ?)`)
|
|
380
|
+
.run(id, input.sessionId, ticketId, title, input.createdBy ?? 'user', createdAt, idempotencyKey);
|
|
381
|
+
}
|
|
382
|
+
catch (error) {
|
|
383
|
+
if (idempotencyKey) {
|
|
384
|
+
const existing = this.findIdempotent(input.sessionId, idempotencyKey);
|
|
385
|
+
if (existing)
|
|
386
|
+
return { ok: true, canvas: this.canvasRow(existing) };
|
|
387
|
+
}
|
|
388
|
+
return asStoreFailure(error);
|
|
389
|
+
}
|
|
390
|
+
return { ok: true, canvas: this.canvasRow(id) };
|
|
391
|
+
}
|
|
392
|
+
findIdempotent(sessionId, key) {
|
|
393
|
+
const row = this.db
|
|
394
|
+
.prepare('SELECT id FROM canvases WHERE session_id = ? AND idempotency_key = ?')
|
|
395
|
+
.get(sessionId, key);
|
|
396
|
+
return typeof row?.id === 'string' ? row.id : null;
|
|
397
|
+
}
|
|
398
|
+
attachTicket(canvasId, ticketId) {
|
|
399
|
+
if (!CANVAS_ID.test(canvasId) || ticketId.length < 1 || ticketId.length > 80)
|
|
400
|
+
return;
|
|
401
|
+
this.db
|
|
402
|
+
.prepare('UPDATE canvases SET ticket_id = ? WHERE id = ? AND (ticket_id IS NULL OR ticket_id = ?)')
|
|
403
|
+
.run(ticketId, canvasId, ticketId);
|
|
404
|
+
}
|
|
405
|
+
canvasIdForTicket(ticketId) {
|
|
406
|
+
if (!ticketId || ticketId.length > 80)
|
|
407
|
+
return null;
|
|
408
|
+
const row = this.db
|
|
409
|
+
.prepare('SELECT id FROM canvases WHERE ticket_id = ? OR writer_ticket_id = ?')
|
|
410
|
+
.get(ticketId, ticketId);
|
|
411
|
+
return typeof row?.id === 'string' ? row.id : null;
|
|
412
|
+
}
|
|
413
|
+
/** The session that opened this preview. A follow-up ticket does not move the card. */
|
|
414
|
+
ownedBy(sessionId, canvasId) {
|
|
415
|
+
if (!CANVAS_ID.test(canvasId))
|
|
416
|
+
return false;
|
|
417
|
+
const row = this.db.prepare('SELECT session_id FROM canvases WHERE id = ?').get(canvasId);
|
|
418
|
+
return row?.session_id === sessionId;
|
|
419
|
+
}
|
|
420
|
+
attachWriter(canvasId, ticketId) {
|
|
421
|
+
if (!CANVAS_ID.test(canvasId) || ticketId.length < 1 || ticketId.length > 80)
|
|
422
|
+
return;
|
|
423
|
+
this.db.prepare('UPDATE canvases SET writer_ticket_id = ? WHERE id = ?').run(ticketId, canvasId);
|
|
424
|
+
}
|
|
425
|
+
writeDraft(canvasId, files, remove = []) {
|
|
426
|
+
if (!CANVAS_ID.test(canvasId))
|
|
427
|
+
return Promise.resolve(toolError('NOT_FOUND', 'No such canvas.'));
|
|
428
|
+
return this.locked(canvasId, () => {
|
|
429
|
+
const canvas = this.rawCanvas(canvasId);
|
|
430
|
+
if (!canvas)
|
|
431
|
+
return toolError('NOT_FOUND', 'No such canvas.');
|
|
432
|
+
const staged = [];
|
|
433
|
+
const seen = new Set();
|
|
434
|
+
for (const file of files) {
|
|
435
|
+
const problem = stageProblem(file);
|
|
436
|
+
if (problem)
|
|
437
|
+
return toolError('VALIDATION', problem);
|
|
438
|
+
const path = normalizeCanvasPath(file.path);
|
|
439
|
+
if (!path || seen.has(path))
|
|
440
|
+
return toolError('VALIDATION', `Duplicate canvas path ${path ?? ''}.`);
|
|
441
|
+
seen.add(path);
|
|
442
|
+
const previous = this.fileSizeAt(canvasId, canvas.preview_revision == null ? null : Number(canvas.preview_revision), path);
|
|
443
|
+
const short = shorterThanCurrent({ path, type: file.type, bytes: file.bytes }, previous);
|
|
444
|
+
if (short)
|
|
445
|
+
return toolError('VALIDATION', short);
|
|
446
|
+
staged.push({ path, type: file.type.toLowerCase(), bytes: file.bytes });
|
|
447
|
+
}
|
|
448
|
+
const dropping = [];
|
|
449
|
+
for (const item of remove) {
|
|
450
|
+
const path = normalizeCanvasPath(item);
|
|
451
|
+
if (!path)
|
|
452
|
+
return toolError('VALIDATION', 'A canvas path is not allowed.');
|
|
453
|
+
dropping.push(path);
|
|
454
|
+
}
|
|
455
|
+
const existing = this.db
|
|
456
|
+
.prepare('SELECT path, length(bytes) AS size FROM canvas_drafts WHERE canvas_id = ?')
|
|
457
|
+
.all(canvasId);
|
|
458
|
+
const next = new Map(existing.map(row => [String(row.path), Number(row.size)]));
|
|
459
|
+
for (const path of dropping)
|
|
460
|
+
next.delete(path);
|
|
461
|
+
for (const file of staged)
|
|
462
|
+
next.set(file.path, file.bytes.length);
|
|
463
|
+
if (next.size > CANVAS_MAX_FILES)
|
|
464
|
+
return toolError('VALIDATION', 'A canvas revision needs between 1 and 64 files.');
|
|
465
|
+
let total = 0;
|
|
466
|
+
for (const size of next.values())
|
|
467
|
+
total += size;
|
|
468
|
+
if (total > CANVAS_MAX_PACKAGE_BYTES)
|
|
469
|
+
return toolError('VALIDATION', 'The canvas package exceeds 8 MiB.');
|
|
470
|
+
const updatedAt = nowIso();
|
|
471
|
+
this.transaction(() => {
|
|
472
|
+
const del = this.db.prepare('DELETE FROM canvas_drafts WHERE canvas_id = ? AND path = ?');
|
|
473
|
+
for (const path of dropping)
|
|
474
|
+
del.run(canvasId, path);
|
|
475
|
+
const upsert = this.db.prepare(`INSERT INTO canvas_drafts (canvas_id, path, media_type, bytes, updated_at)
|
|
476
|
+
VALUES (?, ?, ?, ?, ?)
|
|
477
|
+
ON CONFLICT(canvas_id, path) DO UPDATE SET
|
|
478
|
+
media_type = excluded.media_type,
|
|
479
|
+
bytes = excluded.bytes,
|
|
480
|
+
updated_at = excluded.updated_at`);
|
|
481
|
+
for (const file of staged)
|
|
482
|
+
upsert.run(canvasId, file.path, file.type, file.bytes, updatedAt);
|
|
483
|
+
});
|
|
484
|
+
return { ok: true, files: [...next.keys()].sort() };
|
|
485
|
+
});
|
|
486
|
+
}
|
|
487
|
+
publishDraft(canvasId, ticketId) {
|
|
488
|
+
if (!CANVAS_ID.test(canvasId))
|
|
489
|
+
return Promise.resolve(toolError('NOT_FOUND', 'No such canvas.'));
|
|
490
|
+
return this.locked(canvasId, () => {
|
|
491
|
+
try {
|
|
492
|
+
const canvas = this.rawCanvas(canvasId);
|
|
493
|
+
if (!canvas)
|
|
494
|
+
return toolError('NOT_FOUND', 'No such canvas.');
|
|
495
|
+
if (typeof ticketId === 'string' && ticketId !== '') {
|
|
496
|
+
if (ticketId.length > 80)
|
|
497
|
+
return toolError('VALIDATION', 'ticket id is not allowed.');
|
|
498
|
+
const prior = this.db
|
|
499
|
+
.prepare('SELECT ticket_id FROM canvas_ticket_publishes WHERE ticket_id = ?')
|
|
500
|
+
.get(ticketId);
|
|
501
|
+
if (prior)
|
|
502
|
+
return toolError('VALIDATION', 'This ticket already published. Call canvas_publish once, after every file is staged.');
|
|
503
|
+
}
|
|
504
|
+
const rows = this.db
|
|
505
|
+
.prepare('SELECT path, media_type, bytes FROM canvas_drafts WHERE canvas_id = ? ORDER BY path ASC')
|
|
506
|
+
.all(canvasId);
|
|
507
|
+
const files = rows.map(row => ({
|
|
508
|
+
path: String(row.path),
|
|
509
|
+
type: String(row.media_type),
|
|
510
|
+
bytes: Buffer.from(row.bytes),
|
|
511
|
+
}));
|
|
512
|
+
const preview = canvas.preview_revision == null ? null : Number(canvas.preview_revision);
|
|
513
|
+
const published = this.publishLocked({
|
|
514
|
+
canvasId,
|
|
515
|
+
kind: preview == null ? 'snapshot' : 'delta',
|
|
516
|
+
baseRevision: preview,
|
|
517
|
+
entry: 'index.html',
|
|
518
|
+
expectedFence: Number(canvas.fence_generation),
|
|
519
|
+
files,
|
|
520
|
+
});
|
|
521
|
+
if (published.ok === true && typeof ticketId === 'string' && ticketId !== '') {
|
|
522
|
+
this.db
|
|
523
|
+
.prepare('INSERT INTO canvas_ticket_publishes (ticket_id, canvas_id, revision) VALUES (?, ?, ?)')
|
|
524
|
+
.run(ticketId, canvasId, published.revision);
|
|
525
|
+
}
|
|
526
|
+
const kind = preview == null ? 'snapshot' : 'delta';
|
|
527
|
+
return this.emitPublished(published, kind);
|
|
528
|
+
}
|
|
529
|
+
catch (error) {
|
|
530
|
+
return asStoreFailure(error);
|
|
531
|
+
}
|
|
532
|
+
});
|
|
533
|
+
}
|
|
534
|
+
list(sessionId) {
|
|
535
|
+
if (!SESSION_ID.test(sessionId))
|
|
536
|
+
return toolError('VALIDATION', 'sessionId is not allowed.');
|
|
537
|
+
const rows = this.db
|
|
538
|
+
.prepare(`SELECT id FROM canvases WHERE session_id = ? ORDER BY created_at ASC, id ASC`)
|
|
539
|
+
.all(sessionId);
|
|
540
|
+
return { ok: true, canvases: rows.map(row => this.canvasRow(row.id)) };
|
|
541
|
+
}
|
|
542
|
+
get(canvasId) {
|
|
543
|
+
if (!CANVAS_ID.test(canvasId))
|
|
544
|
+
return toolError('NOT_FOUND', 'No such canvas.');
|
|
545
|
+
const canvas = this.canvasRow(canvasId);
|
|
546
|
+
if (!canvas)
|
|
547
|
+
return toolError('NOT_FOUND', 'No such canvas.');
|
|
548
|
+
const revisions = this.db
|
|
549
|
+
.prepare(`SELECT revision, parent, kind, entry, status, hash, error, created_at
|
|
550
|
+
FROM canvas_revisions WHERE canvas_id = ? ORDER BY revision ASC`)
|
|
551
|
+
.all(canvasId)
|
|
552
|
+
.map(row => ({
|
|
553
|
+
revision: row.revision,
|
|
554
|
+
parent: row.parent,
|
|
555
|
+
kind: row.kind,
|
|
556
|
+
entry: row.entry,
|
|
557
|
+
status: row.status,
|
|
558
|
+
hash: row.hash ? `sha256:${row.hash}` : null,
|
|
559
|
+
error: row.error,
|
|
560
|
+
createdAt: row.created_at,
|
|
561
|
+
}));
|
|
562
|
+
return { ok: true, canvas, revisions };
|
|
563
|
+
}
|
|
564
|
+
manifest(canvasId, revision) {
|
|
565
|
+
const found = this.revisionFiles(canvasId, revision);
|
|
566
|
+
if (found.ok === false)
|
|
567
|
+
return found;
|
|
568
|
+
return {
|
|
569
|
+
ok: true,
|
|
570
|
+
kind: found.kind,
|
|
571
|
+
revision: found.revision,
|
|
572
|
+
baseRevision: found.parent,
|
|
573
|
+
entry: found.entry,
|
|
574
|
+
manifest: found.manifest,
|
|
575
|
+
};
|
|
576
|
+
}
|
|
577
|
+
publish(input) {
|
|
578
|
+
return this.locked(input.canvasId, () => {
|
|
579
|
+
try {
|
|
580
|
+
return this.emitPublished(this.publishLocked(input), input.kind);
|
|
581
|
+
}
|
|
582
|
+
catch (error) {
|
|
583
|
+
return asStoreFailure(error);
|
|
584
|
+
}
|
|
585
|
+
});
|
|
586
|
+
}
|
|
587
|
+
fail(input) {
|
|
588
|
+
return this.locked(input.canvasId, () => {
|
|
589
|
+
const canvas = this.rawCanvas(input.canvasId);
|
|
590
|
+
if (!canvas)
|
|
591
|
+
return toolError('NOT_FOUND', 'No such canvas.');
|
|
592
|
+
if (Number(canvas.fence_generation) !== input.expectedFence)
|
|
593
|
+
return toolError('CAS_CONFLICT', 'The canvas fence changed.');
|
|
594
|
+
const message = input.message.trim();
|
|
595
|
+
if (message === '' || message.length > 500)
|
|
596
|
+
return toolError('VALIDATION', 'failure message is required.');
|
|
597
|
+
const revision = this.nextRevision(input.canvasId);
|
|
598
|
+
const createdAt = nowIso();
|
|
599
|
+
this.transaction(() => {
|
|
600
|
+
this.db
|
|
601
|
+
.prepare(`INSERT INTO canvas_revisions (
|
|
602
|
+
canvas_id, revision, parent, kind, entry, status, hash, error, created_at
|
|
603
|
+
) VALUES (?, ?, ?, 'failed', NULL, 'failed', NULL, ?, ?)`)
|
|
604
|
+
.run(input.canvasId, revision, canvas.preview_revision, message, createdAt);
|
|
605
|
+
this.db
|
|
606
|
+
.prepare('UPDATE canvases SET fence_generation = ? WHERE id = ?')
|
|
607
|
+
.run(input.expectedFence + 1, input.canvasId);
|
|
608
|
+
this.prune(input.canvasId, createdAt);
|
|
609
|
+
});
|
|
610
|
+
return { ok: true, revision, fence: input.expectedFence + 1, canvas: this.canvasRow(input.canvasId) };
|
|
611
|
+
});
|
|
612
|
+
}
|
|
613
|
+
adopt(input) {
|
|
614
|
+
return this.locked(input.canvasId, () => {
|
|
615
|
+
const canvas = this.rawCanvas(input.canvasId);
|
|
616
|
+
if (!canvas)
|
|
617
|
+
return toolError('NOT_FOUND', 'No such canvas.');
|
|
618
|
+
const revision = this.db
|
|
619
|
+
.prepare('SELECT status FROM canvas_revisions WHERE canvas_id = ? AND revision = ?')
|
|
620
|
+
.get(input.canvasId, input.revision);
|
|
621
|
+
if (!revision)
|
|
622
|
+
return toolError('NOT_FOUND', 'No such revision.');
|
|
623
|
+
if (revision.status === 'failed')
|
|
624
|
+
return toolError('VALIDATION', 'A failed revision cannot be adopted.');
|
|
625
|
+
this.db.prepare('UPDATE canvases SET stable_revision = ? WHERE id = ?').run(input.revision, input.canvasId);
|
|
626
|
+
this.db
|
|
627
|
+
.prepare(`UPDATE canvas_revisions SET status = 'preview' WHERE canvas_id = ? AND status = 'stable'`)
|
|
628
|
+
.run(input.canvasId);
|
|
629
|
+
this.db
|
|
630
|
+
.prepare(`UPDATE canvas_revisions SET status = 'stable' WHERE canvas_id = ? AND revision = ?`)
|
|
631
|
+
.run(input.canvasId, input.revision);
|
|
632
|
+
return { ok: true, stableRevision: input.revision, canvas: this.canvasRow(input.canvasId) };
|
|
633
|
+
});
|
|
634
|
+
}
|
|
635
|
+
mint(input) {
|
|
636
|
+
const canvas = this.rawCanvas(input.canvasId);
|
|
637
|
+
if (!canvas)
|
|
638
|
+
return toolError('NOT_FOUND', 'No such canvas.');
|
|
639
|
+
if (!Number.isInteger(input.minRevision) ||
|
|
640
|
+
!Number.isInteger(input.maxRevision) ||
|
|
641
|
+
input.minRevision < 1 ||
|
|
642
|
+
input.maxRevision < input.minRevision)
|
|
643
|
+
return toolError('VALIDATION', 'revision range is not allowed.');
|
|
644
|
+
const known = this.db
|
|
645
|
+
.prepare(`SELECT COUNT(*) AS n FROM canvas_revisions
|
|
646
|
+
WHERE canvas_id = ? AND revision BETWEEN ? AND ? AND status != 'failed'`)
|
|
647
|
+
.get(input.canvasId, input.minRevision, input.maxRevision).n;
|
|
648
|
+
if (Number(known) < 1)
|
|
649
|
+
return toolError('NOT_FOUND', 'No renderable revision in that range.');
|
|
650
|
+
const token = randomBytes(24).toString('base64url');
|
|
651
|
+
const tokenId = `ctok_${randomBytes(9).toString('base64url')}`;
|
|
652
|
+
const ttl = input.ttlMs ?? CANVAS_TOKEN_TTL_MS;
|
|
653
|
+
if (!Number.isInteger(ttl) || ttl < 1_000 || ttl > CANVAS_TOKEN_TTL_MS)
|
|
654
|
+
return toolError('VALIDATION', 'token ttl is not allowed.');
|
|
655
|
+
const expiresAt = new Date(Date.now() + ttl).toISOString();
|
|
656
|
+
this.db
|
|
657
|
+
.prepare(`INSERT INTO canvas_tokens (id, canvas_id, token_hash, min_revision, max_revision, expires_at, revoked_at)
|
|
658
|
+
VALUES (?, ?, ?, ?, ?, ?, NULL)`)
|
|
659
|
+
.run(tokenId, input.canvasId, sha256(token), input.minRevision, input.maxRevision, expiresAt);
|
|
660
|
+
return {
|
|
661
|
+
ok: true,
|
|
662
|
+
token,
|
|
663
|
+
tokenId,
|
|
664
|
+
expiresAt,
|
|
665
|
+
minRevision: input.minRevision,
|
|
666
|
+
maxRevision: input.maxRevision,
|
|
667
|
+
};
|
|
668
|
+
}
|
|
669
|
+
revoke(input) {
|
|
670
|
+
if (!CANVAS_ID.test(input.canvasId))
|
|
671
|
+
return toolError('NOT_FOUND', 'No such canvas.');
|
|
672
|
+
const result = this.db
|
|
673
|
+
.prepare(`UPDATE canvas_tokens SET revoked_at = ? WHERE id = ? AND canvas_id = ? AND revoked_at IS NULL`)
|
|
674
|
+
.run(nowIso(), input.tokenId, input.canvasId);
|
|
675
|
+
if (Number(result.changes) < 1)
|
|
676
|
+
return toolError('NOT_FOUND', 'No such token.');
|
|
677
|
+
return { ok: true };
|
|
678
|
+
}
|
|
679
|
+
/**
|
|
680
|
+
* Capability-token read. Callers must not consult the login cookie.
|
|
681
|
+
*/
|
|
682
|
+
readMedia(input) {
|
|
683
|
+
const path = normalizeCanvasPath(input.path);
|
|
684
|
+
if (!path || !/^[A-Za-z0-9_-]{20,128}$/.test(input.token))
|
|
685
|
+
return toolError('VALIDATION', 'canvas media path is not allowed.');
|
|
686
|
+
const token = this.db
|
|
687
|
+
.prepare(`SELECT canvas_id, min_revision, max_revision, expires_at, revoked_at
|
|
688
|
+
FROM canvas_tokens WHERE token_hash = ?`)
|
|
689
|
+
.get(sha256(input.token));
|
|
690
|
+
if (!token || token.revoked_at || token.expires_at <= nowIso())
|
|
691
|
+
return toolError('FORBIDDEN', 'canvas media token is not valid.');
|
|
692
|
+
if (input.revision < token.min_revision || input.revision > token.max_revision)
|
|
693
|
+
return toolError('FORBIDDEN', 'canvas media token is not valid.');
|
|
694
|
+
const file = this.db
|
|
695
|
+
.prepare(`SELECT f.media_type, b.bytes, b.size
|
|
696
|
+
FROM canvas_files f
|
|
697
|
+
JOIN canvas_blobs b ON b.hash = f.hash
|
|
698
|
+
WHERE f.canvas_id = ? AND f.revision = ? AND f.path = ?`)
|
|
699
|
+
.get(token.canvas_id, input.revision, path);
|
|
700
|
+
if (!file)
|
|
701
|
+
return toolError('NOT_FOUND', 'No such canvas file.');
|
|
702
|
+
const bytes = Buffer.from(file.bytes);
|
|
703
|
+
if (bytes.length !== file.size || !rasterOk(file.media_type, bytes))
|
|
704
|
+
return toolError('NOT_FOUND', 'No such canvas file.');
|
|
705
|
+
return { ok: true, type: file.media_type, bytes, canvasId: token.canvas_id };
|
|
706
|
+
}
|
|
707
|
+
publishLocked(input) {
|
|
708
|
+
if (input.kind !== 'snapshot' && input.kind !== 'delta')
|
|
709
|
+
return toolError('VALIDATION', 'kind must be snapshot or delta.');
|
|
710
|
+
if (!Number.isInteger(input.expectedFence) || input.expectedFence < 0)
|
|
711
|
+
return toolError('VALIDATION', 'expectedFence is required.');
|
|
712
|
+
const canvas = this.rawCanvas(input.canvasId);
|
|
713
|
+
if (!canvas)
|
|
714
|
+
return toolError('NOT_FOUND', 'No such canvas.');
|
|
715
|
+
if (Number(canvas.fence_generation) !== input.expectedFence)
|
|
716
|
+
return toolError('CAS_CONFLICT', 'The canvas fence changed.');
|
|
717
|
+
const checked = checkFiles(input.entry, input.files);
|
|
718
|
+
if (!Array.isArray(checked))
|
|
719
|
+
return checked;
|
|
720
|
+
const entry = normalizeCanvasPath(input.entry);
|
|
721
|
+
if (!entry)
|
|
722
|
+
return toolError('VALIDATION', 'entry path is not allowed.');
|
|
723
|
+
let parent = null;
|
|
724
|
+
if (input.kind === 'delta') {
|
|
725
|
+
if (canvas.preview_revision == null)
|
|
726
|
+
return toolError('VALIDATION', 'A delta needs a snapshot first.');
|
|
727
|
+
if (Number(canvas.preview_revision) !== input.baseRevision)
|
|
728
|
+
return toolError('CAS_CONFLICT', 'baseRevision is not the current preview.');
|
|
729
|
+
parent = Number(canvas.preview_revision);
|
|
730
|
+
}
|
|
731
|
+
for (const file of input.files) {
|
|
732
|
+
const path = normalizeCanvasPath(file.path);
|
|
733
|
+
if (!path)
|
|
734
|
+
continue;
|
|
735
|
+
const previous = parent == null ? null : this.fileSizeAt(input.canvasId, parent, path);
|
|
736
|
+
const short = shorterThanCurrent(file, previous);
|
|
737
|
+
if (short)
|
|
738
|
+
return toolError('VALIDATION', short);
|
|
739
|
+
}
|
|
740
|
+
const revision = this.nextRevision(input.canvasId);
|
|
741
|
+
const createdAt = nowIso();
|
|
742
|
+
const hash = manifestHash(checked);
|
|
743
|
+
this.transaction(() => {
|
|
744
|
+
this.db
|
|
745
|
+
.prepare(`INSERT INTO canvas_revisions (
|
|
746
|
+
canvas_id, revision, parent, kind, entry, status, hash, error, created_at
|
|
747
|
+
) VALUES (?, ?, ?, ?, ?, 'preview', ?, NULL, ?)`)
|
|
748
|
+
.run(input.canvasId, revision, parent, input.kind, entry, hash, createdAt);
|
|
749
|
+
const insertBlob = this.db.prepare('INSERT INTO canvas_blobs (hash, bytes, size) VALUES (?, ?, ?) ON CONFLICT(hash) DO NOTHING');
|
|
750
|
+
const insertFile = this.db.prepare(`INSERT INTO canvas_files (canvas_id, revision, path, hash, media_type, size)
|
|
751
|
+
VALUES (?, ?, ?, ?, ?, ?)`);
|
|
752
|
+
for (const file of input.files) {
|
|
753
|
+
const path = normalizeCanvasPath(file.path);
|
|
754
|
+
const item = checked.find(candidate => candidate.path === path);
|
|
755
|
+
if (!path || !item)
|
|
756
|
+
throw new Error('manifest drifted');
|
|
757
|
+
const digest = item.hash.slice('sha256:'.length);
|
|
758
|
+
insertBlob.run(digest, file.bytes, file.bytes.length);
|
|
759
|
+
insertFile.run(input.canvasId, revision, path, digest, item.type, file.bytes.length);
|
|
760
|
+
}
|
|
761
|
+
this.db
|
|
762
|
+
.prepare('UPDATE canvases SET preview_revision = ?, fence_generation = ? WHERE id = ?')
|
|
763
|
+
.run(revision, input.expectedFence + 1, input.canvasId);
|
|
764
|
+
this.prune(input.canvasId, createdAt);
|
|
765
|
+
});
|
|
766
|
+
const stored = this.db
|
|
767
|
+
.prepare('SELECT revision, parent, kind, status FROM canvas_revisions WHERE canvas_id = ? AND revision = ?')
|
|
768
|
+
.get(input.canvasId, revision);
|
|
769
|
+
this.remember(canvas.session_id, input.canvasId, stored, input.expectedFence + 1);
|
|
770
|
+
return {
|
|
771
|
+
ok: true,
|
|
772
|
+
revision,
|
|
773
|
+
kind: input.kind,
|
|
774
|
+
baseRevision: parent,
|
|
775
|
+
entry,
|
|
776
|
+
fence: input.expectedFence + 1,
|
|
777
|
+
manifest: checked,
|
|
778
|
+
canvas: this.canvasRow(input.canvasId),
|
|
779
|
+
};
|
|
780
|
+
}
|
|
781
|
+
remember(sessionId, canvasId, revision, fence) {
|
|
782
|
+
if (revision.kind !== 'snapshot' && revision.kind !== 'delta')
|
|
783
|
+
return;
|
|
784
|
+
this.notices.set(canvasId, {
|
|
785
|
+
sessionId,
|
|
786
|
+
wire: {
|
|
787
|
+
type: 'canvas.revision',
|
|
788
|
+
canvasId,
|
|
789
|
+
revision: revision.revision,
|
|
790
|
+
baseRevision: revision.parent,
|
|
791
|
+
kind: revision.kind,
|
|
792
|
+
stamp: `${canvasId}:${revision.revision}:${fence}`,
|
|
793
|
+
},
|
|
794
|
+
});
|
|
795
|
+
}
|
|
796
|
+
fileSizeAt(canvasId, revision, path) {
|
|
797
|
+
if (revision == null)
|
|
798
|
+
return null;
|
|
799
|
+
const row = this.db
|
|
800
|
+
.prepare('SELECT size FROM canvas_files WHERE canvas_id = ? AND revision = ? AND path = ?')
|
|
801
|
+
.get(canvasId, revision, path);
|
|
802
|
+
return row ? Number(row.size) : null;
|
|
803
|
+
}
|
|
804
|
+
previewPaths(canvasId) {
|
|
805
|
+
const canvas = this.rawCanvas(canvasId);
|
|
806
|
+
if (!canvas || canvas.preview_revision == null)
|
|
807
|
+
return [];
|
|
808
|
+
return this.db
|
|
809
|
+
.prepare('SELECT path FROM canvas_files WHERE canvas_id = ? AND revision = ? ORDER BY path ASC')
|
|
810
|
+
.all(canvasId, Number(canvas.preview_revision))
|
|
811
|
+
.map(row => String(row.path));
|
|
812
|
+
}
|
|
813
|
+
/** Current preview. HTML and CSS include text. Other files are path, type, and size only. */
|
|
814
|
+
previewListing(canvasId) {
|
|
815
|
+
const canvas = this.rawCanvas(canvasId);
|
|
816
|
+
if (!canvas)
|
|
817
|
+
return toolError('NOT_FOUND', 'No such canvas.');
|
|
818
|
+
const revision = canvas.preview_revision == null ? null : Number(canvas.preview_revision);
|
|
819
|
+
if (revision == null)
|
|
820
|
+
return { ok: true, revision: null, files: [] };
|
|
821
|
+
const rows = this.db
|
|
822
|
+
.prepare(`SELECT f.path, f.media_type, f.size, b.bytes
|
|
823
|
+
FROM canvas_files f
|
|
824
|
+
JOIN canvas_blobs b ON b.hash = f.hash
|
|
825
|
+
WHERE f.canvas_id = ? AND f.revision = ?
|
|
826
|
+
ORDER BY f.path ASC`)
|
|
827
|
+
.all(canvasId, revision);
|
|
828
|
+
return {
|
|
829
|
+
ok: true,
|
|
830
|
+
revision,
|
|
831
|
+
files: rows.map(row => {
|
|
832
|
+
const type = String(row.media_type);
|
|
833
|
+
const item = { path: String(row.path), type, bytes: Number(row.size) };
|
|
834
|
+
if (type === 'text/html' || type === 'text/css')
|
|
835
|
+
item.text = Buffer.from(row.bytes).toString('utf8');
|
|
836
|
+
return item;
|
|
837
|
+
}),
|
|
838
|
+
};
|
|
839
|
+
}
|
|
840
|
+
/** Staged bytes win. Otherwise the current preview file. */
|
|
841
|
+
currentFile(canvasId, path) {
|
|
842
|
+
const draft = this.db
|
|
843
|
+
.prepare('SELECT media_type, bytes FROM canvas_drafts WHERE canvas_id = ? AND path = ?')
|
|
844
|
+
.get(canvasId, path);
|
|
845
|
+
if (draft)
|
|
846
|
+
return { type: String(draft.media_type), bytes: Buffer.from(draft.bytes) };
|
|
847
|
+
const canvas = this.rawCanvas(canvasId);
|
|
848
|
+
const revision = canvas?.preview_revision == null ? null : Number(canvas.preview_revision);
|
|
849
|
+
if (revision == null)
|
|
850
|
+
return null;
|
|
851
|
+
const row = this.db
|
|
852
|
+
.prepare(`SELECT f.media_type, b.bytes
|
|
853
|
+
FROM canvas_files f
|
|
854
|
+
JOIN canvas_blobs b ON b.hash = f.hash
|
|
855
|
+
WHERE f.canvas_id = ? AND f.revision = ? AND f.path = ?`)
|
|
856
|
+
.get(canvasId, revision, path);
|
|
857
|
+
if (!row)
|
|
858
|
+
return null;
|
|
859
|
+
return { type: String(row.media_type), bytes: Buffer.from(row.bytes) };
|
|
860
|
+
}
|
|
861
|
+
revisionFiles(canvasId, revision) {
|
|
862
|
+
if (!CANVAS_ID.test(canvasId) || !Number.isInteger(revision) || revision < 1)
|
|
863
|
+
return toolError('NOT_FOUND', 'No such revision.');
|
|
864
|
+
const row = this.db
|
|
865
|
+
.prepare(`SELECT revision, parent, kind, entry, status, error FROM canvas_revisions
|
|
866
|
+
WHERE canvas_id = ? AND revision = ?`)
|
|
867
|
+
.get(canvasId, revision);
|
|
868
|
+
if (!row)
|
|
869
|
+
return toolError('NOT_FOUND', 'No such revision.');
|
|
870
|
+
if (row.status === 'failed' || row.kind === 'failed')
|
|
871
|
+
return toolError('VALIDATION', row.error || 'This revision failed.');
|
|
872
|
+
const files = this.db
|
|
873
|
+
.prepare(`SELECT path, hash, size, media_type FROM canvas_files
|
|
874
|
+
WHERE canvas_id = ? AND revision = ? ORDER BY path ASC`)
|
|
875
|
+
.all(canvasId, revision);
|
|
876
|
+
return {
|
|
877
|
+
ok: true,
|
|
878
|
+
revision: row.revision,
|
|
879
|
+
parent: row.parent,
|
|
880
|
+
kind: row.kind,
|
|
881
|
+
entry: row.entry,
|
|
882
|
+
manifest: files.map(file => ({
|
|
883
|
+
path: file.path,
|
|
884
|
+
hash: `sha256:${file.hash}`,
|
|
885
|
+
bytes: file.size,
|
|
886
|
+
type: file.media_type,
|
|
887
|
+
})),
|
|
888
|
+
};
|
|
889
|
+
}
|
|
890
|
+
prune(canvasId, now) {
|
|
891
|
+
const canvas = this.rawCanvas(canvasId);
|
|
892
|
+
if (!canvas)
|
|
893
|
+
return;
|
|
894
|
+
const revisions = this.db
|
|
895
|
+
.prepare('SELECT revision FROM canvas_revisions WHERE canvas_id = ? ORDER BY revision DESC')
|
|
896
|
+
.all(canvasId)
|
|
897
|
+
.map(row => row.revision);
|
|
898
|
+
const keep = new Set(revisions.slice(0, CANVAS_KEEP_REVISIONS));
|
|
899
|
+
if (canvas.stable_revision != null)
|
|
900
|
+
keep.add(canvas.stable_revision);
|
|
901
|
+
if (canvas.preview_revision != null)
|
|
902
|
+
keep.add(canvas.preview_revision);
|
|
903
|
+
const tokens = this.db
|
|
904
|
+
.prepare(`SELECT min_revision, max_revision FROM canvas_tokens
|
|
905
|
+
WHERE canvas_id = ? AND revoked_at IS NULL AND expires_at > ?`)
|
|
906
|
+
.all(canvasId, now);
|
|
907
|
+
for (const token of tokens) {
|
|
908
|
+
for (const revision of revisions) {
|
|
909
|
+
if (revision >= token.min_revision && revision <= token.max_revision)
|
|
910
|
+
keep.add(revision);
|
|
911
|
+
}
|
|
912
|
+
}
|
|
913
|
+
for (const revision of revisions) {
|
|
914
|
+
if (keep.has(revision))
|
|
915
|
+
continue;
|
|
916
|
+
this.db.prepare('DELETE FROM canvas_files WHERE canvas_id = ? AND revision = ?').run(canvasId, revision);
|
|
917
|
+
this.db.prepare('DELETE FROM canvas_revisions WHERE canvas_id = ? AND revision = ?').run(canvasId, revision);
|
|
918
|
+
}
|
|
919
|
+
this.db.prepare('DELETE FROM canvas_blobs WHERE hash NOT IN (SELECT hash FROM canvas_files)').run();
|
|
920
|
+
}
|
|
921
|
+
nextRevision(canvasId) {
|
|
922
|
+
const row = this.db.prepare('SELECT MAX(revision) AS n FROM canvas_revisions WHERE canvas_id = ?').get(canvasId);
|
|
923
|
+
return Number(row?.n ?? 0) + 1;
|
|
924
|
+
}
|
|
925
|
+
rawCanvas(canvasId) {
|
|
926
|
+
if (!CANVAS_ID.test(canvasId))
|
|
927
|
+
return null;
|
|
928
|
+
return this.db
|
|
929
|
+
.prepare(`SELECT id, session_id, ticket_id, title, stable_revision, preview_revision, fence_generation, created_at
|
|
930
|
+
FROM canvases WHERE id = ?`)
|
|
931
|
+
.get(canvasId);
|
|
932
|
+
}
|
|
933
|
+
/** Current preview of each canvas. Older revisions are not replayed as extra cards. */
|
|
934
|
+
publishedPreviews() {
|
|
935
|
+
const rows = this.db
|
|
936
|
+
.prepare(`SELECT c.id, c.session_id, c.title, c.ticket_id, r.revision, r.kind
|
|
937
|
+
FROM canvases c
|
|
938
|
+
JOIN canvas_revisions r ON r.canvas_id = c.id AND r.revision = c.preview_revision
|
|
939
|
+
WHERE c.preview_revision IS NOT NULL AND r.status != 'failed' AND r.kind IN ('snapshot', 'delta')`)
|
|
940
|
+
.all();
|
|
941
|
+
return rows.flatMap(row => {
|
|
942
|
+
const kind = row.kind === 'delta' ? 'delta' : row.kind === 'snapshot' ? 'snapshot' : null;
|
|
943
|
+
if (!kind || typeof row.id !== 'string' || typeof row.revision !== 'number')
|
|
944
|
+
return [];
|
|
945
|
+
return [
|
|
946
|
+
{
|
|
947
|
+
canvasId: row.id,
|
|
948
|
+
sessionId: typeof row.session_id === 'string' ? row.session_id : '',
|
|
949
|
+
revision: row.revision,
|
|
950
|
+
kind,
|
|
951
|
+
title: typeof row.title === 'string' ? row.title : '',
|
|
952
|
+
ticketId: typeof row.ticket_id === 'string' ? row.ticket_id : null,
|
|
953
|
+
},
|
|
954
|
+
];
|
|
955
|
+
});
|
|
956
|
+
}
|
|
957
|
+
emitPublished(result, kind) {
|
|
958
|
+
if (result?.ok !== true || typeof result.revision !== 'number' || !result.canvas)
|
|
959
|
+
return result;
|
|
960
|
+
const event = {
|
|
961
|
+
canvasId: result.canvas.id,
|
|
962
|
+
sessionId: result.canvas.sessionId,
|
|
963
|
+
revision: result.revision,
|
|
964
|
+
kind,
|
|
965
|
+
title: result.canvas.title,
|
|
966
|
+
ticketId: result.canvas.ticketId,
|
|
967
|
+
};
|
|
968
|
+
for (const listener of this.publishListeners) {
|
|
969
|
+
try {
|
|
970
|
+
listener(event);
|
|
971
|
+
}
|
|
972
|
+
catch {
|
|
973
|
+
/* the revision is already committed */
|
|
974
|
+
}
|
|
975
|
+
}
|
|
976
|
+
return result;
|
|
977
|
+
}
|
|
978
|
+
canvasRow(canvasId) {
|
|
979
|
+
const row = this.rawCanvas(canvasId);
|
|
980
|
+
if (!row)
|
|
981
|
+
return null;
|
|
982
|
+
return {
|
|
983
|
+
id: row.id,
|
|
984
|
+
sessionId: row.session_id,
|
|
985
|
+
ticketId: row.ticket_id ?? null,
|
|
986
|
+
title: row.title,
|
|
987
|
+
stableRevision: row.stable_revision ?? null,
|
|
988
|
+
previewRevision: row.preview_revision ?? null,
|
|
989
|
+
fence: Number(row.fence_generation),
|
|
990
|
+
createdAt: row.created_at,
|
|
991
|
+
};
|
|
992
|
+
}
|
|
993
|
+
transaction(run) {
|
|
994
|
+
this.db.exec('BEGIN IMMEDIATE');
|
|
995
|
+
try {
|
|
996
|
+
run();
|
|
997
|
+
this.db.exec('COMMIT');
|
|
998
|
+
}
|
|
999
|
+
catch (error) {
|
|
1000
|
+
try {
|
|
1001
|
+
this.db.exec('ROLLBACK');
|
|
1002
|
+
}
|
|
1003
|
+
catch {
|
|
1004
|
+
/* already rolled back */
|
|
1005
|
+
}
|
|
1006
|
+
throw error;
|
|
1007
|
+
}
|
|
1008
|
+
}
|
|
1009
|
+
locked(canvasId, fn) {
|
|
1010
|
+
const previous = this.tails.get(canvasId) ?? Promise.resolve();
|
|
1011
|
+
const run = previous.then(fn, fn);
|
|
1012
|
+
this.tails.set(canvasId, run.then(() => undefined, () => undefined));
|
|
1013
|
+
return run;
|
|
1014
|
+
}
|
|
1015
|
+
}
|