@thready-web/dsh-bot-plugin 0.1.0-beta.1 → 0.1.0-beta.11
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 +109 -1
- package/client.js +646 -621
- package/dist/approvals.js +160 -0
- package/dist/authorization.js +225 -0
- package/dist/canvas-http.js +248 -0
- package/dist/canvas-skills.js +56 -0
- package/dist/canvas-store.js +794 -0
- package/dist/canvas-tools.js +211 -0
- package/dist/cli.js +32 -12
- package/dist/context.js +60 -17
- package/dist/cron.js +1 -1
- package/dist/cua-access.js +79 -0
- package/dist/desk.js +314 -37
- package/dist/engine.js +178 -84
- package/dist/fs-safe.js +1 -1
- package/dist/host.js +1 -0
- package/dist/http-plugin.js +14 -4
- package/dist/http.js +402 -85
- package/dist/inbox.js +51 -40
- package/dist/index.js +201 -47
- package/dist/live-diff.js +3 -1
- package/dist/live-snapshot.js +2 -13
- package/dist/log/canonical.js +37 -0
- package/dist/log/plan.js +62 -0
- package/dist/log/routes.js +144 -0
- package/dist/log/snapshot-service.js +76 -0
- package/dist/log/source.js +173 -0
- package/dist/memory-catalog.js +798 -0
- package/dist/permissions.js +86 -0
- package/dist/provision.js +2 -0
- package/dist/questions.js +407 -0
- package/dist/runtime-registry.js +4 -4
- package/dist/session-files.js +2 -2
- package/dist/session-previews.js +5 -1
- package/dist/store.js +20 -5
- package/dist/tools.js +150 -32
- package/dist/triggers.js +83 -39
- package/dist/work-admit.js +222 -25
- package/dist/work-child.js +17 -9
- package/dist/work-http.js +52 -2
- package/dist/work-ledger.js +256 -16
- package/dist/work-mock-host.js +9 -6
- package/dist/work-mock.js +29 -19
- package/dist/work-tickets.js +423 -96
- package/dist/work-tools.js +43 -6
- package/dist/work-worker.js +1033 -207
- package/dist/workspace-files.js +319 -0
- package/dist/workspace-image.js +91 -0
- package/fixtures/mock-llm.mjs +17 -2
- package/package.json +16 -5
- package/public/assets/SourceEditor-CJwK846Z.css +1 -0
- package/public/assets/SourceEditor-uu0G7jsM.js +669 -0
- package/public/assets/abap-CRCWOmpq.js +1 -0
- package/public/assets/apex-DnsZk_dE.js +1 -0
- package/public/assets/azcli-1IWB1ccx.js +1 -0
- package/public/assets/bat-DPkNLes8.js +1 -0
- package/public/assets/bicep-Corcdgou.js +2 -0
- package/public/assets/cameligo-CGrWLZr3.js +1 -0
- package/public/assets/clojure-D9WOWImG.js +1 -0
- package/public/assets/codicon-DCmgc-ay.ttf +0 -0
- package/public/assets/coffee-B7EJu28W.js +1 -0
- package/public/assets/cpp-SEyurbux.js +1 -0
- package/public/assets/csharp-BoL64M5l.js +1 -0
- package/public/assets/csp-C46ZqvIl.js +1 -0
- package/public/assets/css-DQU6DXDx.js +3 -0
- package/public/assets/css.worker-DYpkewsP.js +79 -0
- package/public/assets/cssMode-C5DAFF5H.js +4 -0
- package/public/assets/cypher-D84EuPTj.js +1 -0
- package/public/assets/dart-D8lhlL1r.js +1 -0
- package/public/assets/dockerfile-DLk6rpji.js +1 -0
- package/public/assets/ecl-BO6FnfXk.js +1 -0
- package/public/assets/editor.worker-B4pQIWZD.js +12 -0
- package/public/assets/elixir-BRjLKONM.js +1 -0
- package/public/assets/flow9-Cac8vKd7.js +1 -0
- package/public/assets/freemarker2-DExNwSiZ.js +3 -0
- package/public/assets/fsharp-fd1GTHhf.js +1 -0
- package/public/assets/go-O9LJTZXk.js +1 -0
- package/public/assets/graphql-LQdxqEYJ.js +1 -0
- package/public/assets/handlebars-BK7YAvpQ.js +1 -0
- package/public/assets/hcl-DxDQ3s82.js +1 -0
- package/public/assets/html-CdDm_zae.js +1 -0
- package/public/assets/html.worker-tnXziJOq.js +456 -0
- package/public/assets/htmlMode-CLdn9oa1.js +4 -0
- package/public/assets/index-BB-QDSf2.css +1 -0
- package/public/assets/index-CsX-_qbo.js +62 -0
- package/public/assets/ini-BvajGCUy.js +1 -0
- package/public/assets/java-SYsfObOQ.js +1 -0
- package/public/assets/javascript-mLl83_3W.js +1 -0
- package/public/assets/json.worker-aFakAbRR.js +44 -0
- package/public/assets/jsonMode-B1-bihFd.js +10 -0
- package/public/assets/julia-DQXNmw_w.js +1 -0
- package/public/assets/kotlin-qQ0MG-9I.js +1 -0
- package/public/assets/less-GGFNNJHn.js +2 -0
- package/public/assets/lexon-Canl7DCW.js +1 -0
- package/public/assets/liquid-Cv8m0HUb.js +1 -0
- package/public/assets/lua-D28Ae8-K.js +1 -0
- package/public/assets/m3-DPitgjJI.js +1 -0
- package/public/assets/markdown-B811l8j2.js +1 -0
- package/public/assets/mdx-Q12b91rL.js +1 -0
- package/public/assets/mips-CdjsipkG.js +1 -0
- package/public/assets/msdax-CYqgjx_P.js +1 -0
- package/public/assets/mysql-BHd6q0vd.js +1 -0
- package/public/assets/objective-c-B1aVtJYH.js +1 -0
- package/public/assets/pascal-BhNW15KB.js +1 -0
- package/public/assets/pascaligo-5jv8CcQD.js +1 -0
- package/public/assets/perl-DlYyT36c.js +1 -0
- package/public/assets/pgsql-Dy0bjov7.js +1 -0
- package/public/assets/php-120yhfDK.js +1 -0
- package/public/assets/pla-CjnFlu4u.js +1 -0
- package/public/assets/postiats-CQpG440k.js +1 -0
- package/public/assets/powerquery-DdJtto1Z.js +1 -0
- package/public/assets/powershell-Bu_VLpJB.js +1 -0
- package/public/assets/protobuf-IBS6jZEB.js +2 -0
- package/public/assets/pug-kFxLfcjb.js +1 -0
- package/public/assets/python-Kda811W0.js +1 -0
- package/public/assets/qsharp-q7JyzKFN.js +1 -0
- package/public/assets/r-BIFz-_sK.js +1 -0
- package/public/assets/razor-CRuCpdOW.js +1 -0
- package/public/assets/redis-CHOsPHWR.js +1 -0
- package/public/assets/redshift-CBifECDb.js +1 -0
- package/public/assets/restructuredtext-CghPJEOS.js +1 -0
- package/public/assets/ruby-CYWGW-b1.js +1 -0
- package/public/assets/rust-DMDD0SHb.js +1 -0
- package/public/assets/sb-BYAiYHFx.js +1 -0
- package/public/assets/scala-Bqvq8jcR.js +1 -0
- package/public/assets/scheme-Dhb-2j9p.js +1 -0
- package/public/assets/scss-CTwUZ5N7.js +3 -0
- package/public/assets/shell-CsDZo4DB.js +1 -0
- package/public/assets/solidity-CME5AdoB.js +1 -0
- package/public/assets/sophia-RYC1BQQz.js +1 -0
- package/public/assets/sparql-KEyrF7De.js +1 -0
- package/public/assets/sql-BdTr02Mf.js +1 -0
- package/public/assets/st-C7iG7M4S.js +1 -0
- package/public/assets/swift-D7IUmUK8.js +1 -0
- package/public/assets/systemverilog-DgMryOEJ.js +1 -0
- package/public/assets/tcl-PloMZuKG.js +1 -0
- package/public/assets/ts.worker-Bij5J2kb.js +51316 -0
- package/public/assets/tsMode-BGHcz-M3.js +11 -0
- package/public/assets/twig-BfRIq3la.js +1 -0
- package/public/assets/typescript-Db1e0DCT.js +1 -0
- package/public/assets/typespec-CzxlYoT_.js +1 -0
- package/public/assets/vb-BwAE3J76.js +1 -0
- package/public/assets/wgsl-B_1kOXbF.js +298 -0
- package/public/assets/xml-H3zzFmnd.js +1 -0
- package/public/assets/yaml-BQrKvmTF.js +1 -0
- 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 +35 -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-Be82iGwe.css +0 -1
- package/public/assets/index-ByU9a3Lh.js +0 -61
|
@@ -0,0 +1,794 @@
|
|
|
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
|
+
/**
|
|
94
|
+
* Relative canvas path. Rejects traversal, absolute paths, encoding, and dotfiles.
|
|
95
|
+
* The media route checks the raw URL before this runs.
|
|
96
|
+
*/
|
|
97
|
+
export function normalizeCanvasPath(input) {
|
|
98
|
+
if (typeof input !== 'string' || input.length === 0 || input.length > 200)
|
|
99
|
+
return null;
|
|
100
|
+
if (input.includes('\0') || input.includes('\\') || input.includes('%') || input.includes('..'))
|
|
101
|
+
return null;
|
|
102
|
+
if (input.startsWith('/'))
|
|
103
|
+
return null;
|
|
104
|
+
const parts = input.split('/');
|
|
105
|
+
if (parts.some(part => part === '' || part === '.' || part === '..' || part.startsWith('.') || part.length > 120))
|
|
106
|
+
return null;
|
|
107
|
+
return parts.join('/');
|
|
108
|
+
}
|
|
109
|
+
function nowIso() {
|
|
110
|
+
return new Date().toISOString();
|
|
111
|
+
}
|
|
112
|
+
function extensionOf(path) {
|
|
113
|
+
const name = path.slice(path.lastIndexOf('/') + 1);
|
|
114
|
+
const dot = name.lastIndexOf('.');
|
|
115
|
+
return dot < 0 ? '' : name.slice(dot).toLowerCase();
|
|
116
|
+
}
|
|
117
|
+
function rasterOk(type, bytes) {
|
|
118
|
+
if (type === 'image/jpeg')
|
|
119
|
+
return bytes.length >= 3 && bytes[0] === 0xff && bytes[1] === 0xd8 && bytes[2] === 0xff;
|
|
120
|
+
if (type === 'image/png')
|
|
121
|
+
return bytes.length >= 8 && bytes.subarray(0, 8).equals(Buffer.from('89504e470d0a1a0a', 'hex'));
|
|
122
|
+
if (type === 'image/gif')
|
|
123
|
+
return bytes.length >= 6 && /^GIF8[79]a/.test(bytes.subarray(0, 6).toString('ascii'));
|
|
124
|
+
if (type === 'image/webp')
|
|
125
|
+
return (bytes.length >= 12 &&
|
|
126
|
+
bytes.subarray(0, 4).toString('ascii') === 'RIFF' &&
|
|
127
|
+
bytes.subarray(8, 12).toString('ascii') === 'WEBP');
|
|
128
|
+
return true;
|
|
129
|
+
}
|
|
130
|
+
/** Auxiliary check. The sandbox and CSP stay in force even if this misses something. */
|
|
131
|
+
function activeContent(type, bytes) {
|
|
132
|
+
if (type.startsWith('font/')) {
|
|
133
|
+
const head = bytes.subarray(0, 64).toString('utf8').trimStart();
|
|
134
|
+
if (head.startsWith('<'))
|
|
135
|
+
return 'Font files cannot be markup.';
|
|
136
|
+
return null;
|
|
137
|
+
}
|
|
138
|
+
if (type !== 'text/html' && type !== 'text/css')
|
|
139
|
+
return null;
|
|
140
|
+
const text = bytes.toString('utf8');
|
|
141
|
+
const lower = text.toLowerCase();
|
|
142
|
+
if (lower.includes('<script') ||
|
|
143
|
+
lower.includes('javascript:') ||
|
|
144
|
+
lower.includes('data:') ||
|
|
145
|
+
lower.includes('<svg') ||
|
|
146
|
+
lower.includes('<base') ||
|
|
147
|
+
lower.includes('<iframe') ||
|
|
148
|
+
lower.includes('<object') ||
|
|
149
|
+
lower.includes('<embed') ||
|
|
150
|
+
lower.includes('<meta'))
|
|
151
|
+
return 'Canvas documents cannot include scripts, SVG, or document controls.';
|
|
152
|
+
if (/https?:\/\//i.test(text) || text.includes('//') || /url\(\s*['"]?\s*(?:[a-z]+:|\/\/)/i.test(text))
|
|
153
|
+
return 'Canvas documents cannot reference external URLs.';
|
|
154
|
+
if (type === 'text/css' && /@import/i.test(text))
|
|
155
|
+
return 'Canvas stylesheets cannot use @import.';
|
|
156
|
+
return null;
|
|
157
|
+
}
|
|
158
|
+
function stageProblem(file) {
|
|
159
|
+
const path = normalizeCanvasPath(file?.path);
|
|
160
|
+
if (!path)
|
|
161
|
+
return 'A canvas path is not allowed.';
|
|
162
|
+
const type = typeof file.type === 'string' ? file.type.toLowerCase() : '';
|
|
163
|
+
const extensions = TYPES.get(type);
|
|
164
|
+
if (!extensions || !extensions.includes(extensionOf(path)))
|
|
165
|
+
return `File type is not allowed for ${path}.`;
|
|
166
|
+
if (!Buffer.isBuffer(file.bytes))
|
|
167
|
+
return `Missing bytes for ${path}.`;
|
|
168
|
+
if (file.bytes.length > CANVAS_MAX_FILE_BYTES)
|
|
169
|
+
return `${path} exceeds the 1.5 MiB file cap.`;
|
|
170
|
+
if (!rasterOk(type, file.bytes))
|
|
171
|
+
return `${path} does not match its image type.`;
|
|
172
|
+
return activeContent(type, file.bytes);
|
|
173
|
+
}
|
|
174
|
+
function checkFiles(entry, files) {
|
|
175
|
+
const entryPath = normalizeCanvasPath(entry);
|
|
176
|
+
if (!entryPath)
|
|
177
|
+
return toolError('VALIDATION', 'entry path is not allowed.');
|
|
178
|
+
if (!Array.isArray(files) || files.length === 0 || files.length > CANVAS_MAX_FILES)
|
|
179
|
+
return toolError('VALIDATION', 'A canvas revision needs between 1 and 64 files.');
|
|
180
|
+
const seen = new Set();
|
|
181
|
+
const manifest = [];
|
|
182
|
+
let total = 0;
|
|
183
|
+
for (const file of files) {
|
|
184
|
+
const problem = stageProblem(file);
|
|
185
|
+
if (problem)
|
|
186
|
+
return toolError('VALIDATION', problem);
|
|
187
|
+
const path = normalizeCanvasPath(file.path);
|
|
188
|
+
if (!path || seen.has(path))
|
|
189
|
+
return toolError('VALIDATION', `Duplicate canvas path ${path ?? ''}.`);
|
|
190
|
+
seen.add(path);
|
|
191
|
+
const type = file.type.toLowerCase();
|
|
192
|
+
total += file.bytes.length;
|
|
193
|
+
if (total > CANVAS_MAX_PACKAGE_BYTES)
|
|
194
|
+
return toolError('VALIDATION', 'The canvas package exceeds 8 MiB.');
|
|
195
|
+
manifest.push({ path, hash: `sha256:${sha256(file.bytes)}`, bytes: file.bytes.length, type });
|
|
196
|
+
}
|
|
197
|
+
if (!manifest.some(item => item.path === entryPath && item.type === 'text/html'))
|
|
198
|
+
return toolError('VALIDATION', 'entry must be an HTML file in this revision.');
|
|
199
|
+
if ((files.find(file => normalizeCanvasPath(file.path) === entryPath)?.bytes.length ?? 0) === 0)
|
|
200
|
+
return toolError('VALIDATION', 'entry HTML is empty.');
|
|
201
|
+
return manifest;
|
|
202
|
+
}
|
|
203
|
+
function manifestHash(items) {
|
|
204
|
+
const ordered = [...items].sort((left, right) => (left.path < right.path ? -1 : left.path > right.path ? 1 : 0));
|
|
205
|
+
return sha256(JSON.stringify(ordered));
|
|
206
|
+
}
|
|
207
|
+
function migrateCanvas(db) {
|
|
208
|
+
const columns = db.prepare('PRAGMA table_info(canvases)').all();
|
|
209
|
+
if (!columns.some(column => column.name === 'idempotency_key')) {
|
|
210
|
+
db.exec('ALTER TABLE canvases ADD COLUMN idempotency_key TEXT');
|
|
211
|
+
}
|
|
212
|
+
db.exec('CREATE UNIQUE INDEX IF NOT EXISTS canvas_idempotency ON canvases(session_id, idempotency_key) WHERE idempotency_key IS NOT NULL');
|
|
213
|
+
}
|
|
214
|
+
/**
|
|
215
|
+
* Canvas metadata, staged drafts, and deduplicated blobs.
|
|
216
|
+
* Manual HTTP publish and the canvas worker both write here.
|
|
217
|
+
* @param {string} file
|
|
218
|
+
*/
|
|
219
|
+
export function openCanvasStore(file) {
|
|
220
|
+
mkdirSync(dirname(file), { recursive: true, mode: 0o700 });
|
|
221
|
+
const db = new DatabaseSync(file);
|
|
222
|
+
db.exec('PRAGMA foreign_keys = ON');
|
|
223
|
+
db.exec('PRAGMA journal_mode = WAL');
|
|
224
|
+
db.exec('PRAGMA busy_timeout = 5000');
|
|
225
|
+
db.exec(SCHEMA);
|
|
226
|
+
migrateCanvas(db);
|
|
227
|
+
try {
|
|
228
|
+
chmodSync(file, 0o600);
|
|
229
|
+
}
|
|
230
|
+
catch {
|
|
231
|
+
/* the directory mode still limits it */
|
|
232
|
+
}
|
|
233
|
+
const store = new CanvasStore(db);
|
|
234
|
+
store.seed();
|
|
235
|
+
return store;
|
|
236
|
+
}
|
|
237
|
+
export class CanvasStore {
|
|
238
|
+
db;
|
|
239
|
+
tails;
|
|
240
|
+
notices;
|
|
241
|
+
constructor(db) {
|
|
242
|
+
this.db = db;
|
|
243
|
+
this.tails = new Map();
|
|
244
|
+
this.notices = new Map();
|
|
245
|
+
}
|
|
246
|
+
close() {
|
|
247
|
+
this.db.close();
|
|
248
|
+
}
|
|
249
|
+
/** Latest renderable revision per canvas, so a restarted process can still notify. */
|
|
250
|
+
seed() {
|
|
251
|
+
const rows = this.db
|
|
252
|
+
.prepare(`SELECT id, session_id, preview_revision, fence_generation
|
|
253
|
+
FROM canvases WHERE preview_revision IS NOT NULL`)
|
|
254
|
+
.all();
|
|
255
|
+
for (const row of rows) {
|
|
256
|
+
const revision = this.db
|
|
257
|
+
.prepare(`SELECT revision, parent, kind, status FROM canvas_revisions WHERE canvas_id = ? AND revision = ?`)
|
|
258
|
+
.get(row.id, row.preview_revision);
|
|
259
|
+
if (!revision || revision.status === 'failed' || revision.kind === 'failed')
|
|
260
|
+
continue;
|
|
261
|
+
this.remember(row.session_id, row.id, revision, row.fence_generation);
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
/** Compact notices for one session. Bodies stay on the media route. */
|
|
265
|
+
live(sessionId) {
|
|
266
|
+
if (!SESSION_ID.test(sessionId))
|
|
267
|
+
return { ok: true, events: [] };
|
|
268
|
+
const rows = this.db
|
|
269
|
+
.prepare(`SELECT c.id AS canvas_id, c.fence_generation, r.revision, r.parent, r.kind
|
|
270
|
+
FROM canvases c
|
|
271
|
+
JOIN canvas_revisions r ON r.canvas_id = c.id AND r.revision = c.preview_revision
|
|
272
|
+
WHERE c.session_id = ? AND r.kind IN ('snapshot', 'delta') AND r.status != 'failed'
|
|
273
|
+
ORDER BY c.id ASC`)
|
|
274
|
+
.all(sessionId);
|
|
275
|
+
return {
|
|
276
|
+
ok: true,
|
|
277
|
+
events: rows.map(row => ({
|
|
278
|
+
type: 'canvas.revision',
|
|
279
|
+
canvasId: String(row.canvas_id),
|
|
280
|
+
revision: Number(row.revision),
|
|
281
|
+
baseRevision: row.parent == null ? null : Number(row.parent),
|
|
282
|
+
kind: row.kind,
|
|
283
|
+
stamp: `${row.canvas_id}:${row.revision}:${row.fence_generation}`,
|
|
284
|
+
})),
|
|
285
|
+
};
|
|
286
|
+
}
|
|
287
|
+
create(input) {
|
|
288
|
+
if (typeof input.sessionId !== 'string' || !SESSION_ID.test(input.sessionId))
|
|
289
|
+
return toolError('VALIDATION', 'sessionId is not allowed.');
|
|
290
|
+
if (input.title != null && typeof input.title !== 'string')
|
|
291
|
+
return toolError('VALIDATION', 'title is not allowed.');
|
|
292
|
+
const title = typeof input.title === 'string' ? input.title.trim() : '';
|
|
293
|
+
if (title.length > 120)
|
|
294
|
+
return toolError('VALIDATION', 'title is too long.');
|
|
295
|
+
const ticketId = input.ticketId ?? null;
|
|
296
|
+
if (ticketId != null && (typeof ticketId !== 'string' || ticketId.length > 80))
|
|
297
|
+
return toolError('VALIDATION', 'ticketId is not allowed.');
|
|
298
|
+
const idempotencyKey = input.idempotencyKey ?? null;
|
|
299
|
+
if (idempotencyKey != null && (idempotencyKey.length < 8 || idempotencyKey.length > 128))
|
|
300
|
+
return toolError('VALIDATION', 'idempotencyKey is not allowed.');
|
|
301
|
+
if (idempotencyKey) {
|
|
302
|
+
const existing = this.findIdempotent(input.sessionId, idempotencyKey);
|
|
303
|
+
if (existing)
|
|
304
|
+
return { ok: true, canvas: this.canvasRow(existing) };
|
|
305
|
+
}
|
|
306
|
+
const id = `cnv_${randomBytes(12).toString('base64url')}`;
|
|
307
|
+
const createdAt = nowIso();
|
|
308
|
+
try {
|
|
309
|
+
this.db
|
|
310
|
+
.prepare(`INSERT INTO canvases (
|
|
311
|
+
id, session_id, ticket_id, title, stable_revision, preview_revision, fence_generation, created_by, created_at, idempotency_key
|
|
312
|
+
) VALUES (?, ?, ?, ?, NULL, NULL, 0, ?, ?, ?)`)
|
|
313
|
+
.run(id, input.sessionId, ticketId, title, input.createdBy ?? 'user', createdAt, idempotencyKey);
|
|
314
|
+
}
|
|
315
|
+
catch (error) {
|
|
316
|
+
if (idempotencyKey) {
|
|
317
|
+
const existing = this.findIdempotent(input.sessionId, idempotencyKey);
|
|
318
|
+
if (existing)
|
|
319
|
+
return { ok: true, canvas: this.canvasRow(existing) };
|
|
320
|
+
}
|
|
321
|
+
return asStoreFailure(error);
|
|
322
|
+
}
|
|
323
|
+
return { ok: true, canvas: this.canvasRow(id) };
|
|
324
|
+
}
|
|
325
|
+
findIdempotent(sessionId, key) {
|
|
326
|
+
const row = this.db
|
|
327
|
+
.prepare('SELECT id FROM canvases WHERE session_id = ? AND idempotency_key = ?')
|
|
328
|
+
.get(sessionId, key);
|
|
329
|
+
return typeof row?.id === 'string' ? row.id : null;
|
|
330
|
+
}
|
|
331
|
+
attachTicket(canvasId, ticketId) {
|
|
332
|
+
if (!CANVAS_ID.test(canvasId) || ticketId.length < 1 || ticketId.length > 80)
|
|
333
|
+
return;
|
|
334
|
+
this.db
|
|
335
|
+
.prepare('UPDATE canvases SET ticket_id = ? WHERE id = ? AND (ticket_id IS NULL OR ticket_id = ?)')
|
|
336
|
+
.run(ticketId, canvasId, ticketId);
|
|
337
|
+
}
|
|
338
|
+
canvasIdForTicket(ticketId) {
|
|
339
|
+
if (!ticketId || ticketId.length > 80)
|
|
340
|
+
return null;
|
|
341
|
+
const row = this.db.prepare('SELECT id FROM canvases WHERE ticket_id = ?').get(ticketId);
|
|
342
|
+
return typeof row?.id === 'string' ? row.id : null;
|
|
343
|
+
}
|
|
344
|
+
writeDraft(canvasId, files, remove = []) {
|
|
345
|
+
if (!CANVAS_ID.test(canvasId))
|
|
346
|
+
return Promise.resolve(toolError('NOT_FOUND', 'No such canvas.'));
|
|
347
|
+
return this.locked(canvasId, () => {
|
|
348
|
+
if (!this.rawCanvas(canvasId))
|
|
349
|
+
return toolError('NOT_FOUND', 'No such canvas.');
|
|
350
|
+
const staged = [];
|
|
351
|
+
const seen = new Set();
|
|
352
|
+
for (const file of files) {
|
|
353
|
+
const problem = stageProblem(file);
|
|
354
|
+
if (problem)
|
|
355
|
+
return toolError('VALIDATION', problem);
|
|
356
|
+
const path = normalizeCanvasPath(file.path);
|
|
357
|
+
if (!path || seen.has(path))
|
|
358
|
+
return toolError('VALIDATION', `Duplicate canvas path ${path ?? ''}.`);
|
|
359
|
+
seen.add(path);
|
|
360
|
+
staged.push({ path, type: file.type.toLowerCase(), bytes: file.bytes });
|
|
361
|
+
}
|
|
362
|
+
const dropping = [];
|
|
363
|
+
for (const item of remove) {
|
|
364
|
+
const path = normalizeCanvasPath(item);
|
|
365
|
+
if (!path)
|
|
366
|
+
return toolError('VALIDATION', 'A canvas path is not allowed.');
|
|
367
|
+
dropping.push(path);
|
|
368
|
+
}
|
|
369
|
+
const existing = this.db
|
|
370
|
+
.prepare('SELECT path, length(bytes) AS size FROM canvas_drafts WHERE canvas_id = ?')
|
|
371
|
+
.all(canvasId);
|
|
372
|
+
const next = new Map(existing.map(row => [String(row.path), Number(row.size)]));
|
|
373
|
+
for (const path of dropping)
|
|
374
|
+
next.delete(path);
|
|
375
|
+
for (const file of staged)
|
|
376
|
+
next.set(file.path, file.bytes.length);
|
|
377
|
+
if (next.size > CANVAS_MAX_FILES)
|
|
378
|
+
return toolError('VALIDATION', 'A canvas revision needs between 1 and 64 files.');
|
|
379
|
+
let total = 0;
|
|
380
|
+
for (const size of next.values())
|
|
381
|
+
total += size;
|
|
382
|
+
if (total > CANVAS_MAX_PACKAGE_BYTES)
|
|
383
|
+
return toolError('VALIDATION', 'The canvas package exceeds 8 MiB.');
|
|
384
|
+
const updatedAt = nowIso();
|
|
385
|
+
this.transaction(() => {
|
|
386
|
+
const del = this.db.prepare('DELETE FROM canvas_drafts WHERE canvas_id = ? AND path = ?');
|
|
387
|
+
for (const path of dropping)
|
|
388
|
+
del.run(canvasId, path);
|
|
389
|
+
const upsert = this.db.prepare(`INSERT INTO canvas_drafts (canvas_id, path, media_type, bytes, updated_at)
|
|
390
|
+
VALUES (?, ?, ?, ?, ?)
|
|
391
|
+
ON CONFLICT(canvas_id, path) DO UPDATE SET
|
|
392
|
+
media_type = excluded.media_type,
|
|
393
|
+
bytes = excluded.bytes,
|
|
394
|
+
updated_at = excluded.updated_at`);
|
|
395
|
+
for (const file of staged)
|
|
396
|
+
upsert.run(canvasId, file.path, file.type, file.bytes, updatedAt);
|
|
397
|
+
});
|
|
398
|
+
return { ok: true, files: [...next.keys()].sort() };
|
|
399
|
+
});
|
|
400
|
+
}
|
|
401
|
+
publishDraft(canvasId) {
|
|
402
|
+
if (!CANVAS_ID.test(canvasId))
|
|
403
|
+
return Promise.resolve(toolError('NOT_FOUND', 'No such canvas.'));
|
|
404
|
+
return this.locked(canvasId, () => {
|
|
405
|
+
try {
|
|
406
|
+
const canvas = this.rawCanvas(canvasId);
|
|
407
|
+
if (!canvas)
|
|
408
|
+
return toolError('NOT_FOUND', 'No such canvas.');
|
|
409
|
+
const rows = this.db
|
|
410
|
+
.prepare('SELECT path, media_type, bytes FROM canvas_drafts WHERE canvas_id = ? ORDER BY path ASC')
|
|
411
|
+
.all(canvasId);
|
|
412
|
+
const files = rows.map(row => ({
|
|
413
|
+
path: String(row.path),
|
|
414
|
+
type: String(row.media_type),
|
|
415
|
+
bytes: Buffer.from(row.bytes),
|
|
416
|
+
}));
|
|
417
|
+
const preview = canvas.preview_revision == null ? null : Number(canvas.preview_revision);
|
|
418
|
+
return this.publishLocked({
|
|
419
|
+
canvasId,
|
|
420
|
+
kind: preview == null ? 'snapshot' : 'delta',
|
|
421
|
+
baseRevision: preview,
|
|
422
|
+
entry: 'index.html',
|
|
423
|
+
expectedFence: Number(canvas.fence_generation),
|
|
424
|
+
files,
|
|
425
|
+
});
|
|
426
|
+
}
|
|
427
|
+
catch (error) {
|
|
428
|
+
return asStoreFailure(error);
|
|
429
|
+
}
|
|
430
|
+
});
|
|
431
|
+
}
|
|
432
|
+
list(sessionId) {
|
|
433
|
+
if (!SESSION_ID.test(sessionId))
|
|
434
|
+
return toolError('VALIDATION', 'sessionId is not allowed.');
|
|
435
|
+
const rows = this.db
|
|
436
|
+
.prepare(`SELECT id FROM canvases WHERE session_id = ? ORDER BY created_at ASC, id ASC`)
|
|
437
|
+
.all(sessionId);
|
|
438
|
+
return { ok: true, canvases: rows.map(row => this.canvasRow(row.id)) };
|
|
439
|
+
}
|
|
440
|
+
get(canvasId) {
|
|
441
|
+
if (!CANVAS_ID.test(canvasId))
|
|
442
|
+
return toolError('NOT_FOUND', 'No such canvas.');
|
|
443
|
+
const canvas = this.canvasRow(canvasId);
|
|
444
|
+
if (!canvas)
|
|
445
|
+
return toolError('NOT_FOUND', 'No such canvas.');
|
|
446
|
+
const revisions = this.db
|
|
447
|
+
.prepare(`SELECT revision, parent, kind, entry, status, hash, error, created_at
|
|
448
|
+
FROM canvas_revisions WHERE canvas_id = ? ORDER BY revision ASC`)
|
|
449
|
+
.all(canvasId)
|
|
450
|
+
.map(row => ({
|
|
451
|
+
revision: row.revision,
|
|
452
|
+
parent: row.parent,
|
|
453
|
+
kind: row.kind,
|
|
454
|
+
entry: row.entry,
|
|
455
|
+
status: row.status,
|
|
456
|
+
hash: row.hash ? `sha256:${row.hash}` : null,
|
|
457
|
+
error: row.error,
|
|
458
|
+
createdAt: row.created_at,
|
|
459
|
+
}));
|
|
460
|
+
return { ok: true, canvas, revisions };
|
|
461
|
+
}
|
|
462
|
+
manifest(canvasId, revision) {
|
|
463
|
+
const found = this.revisionFiles(canvasId, revision);
|
|
464
|
+
if (found.ok === false)
|
|
465
|
+
return found;
|
|
466
|
+
return {
|
|
467
|
+
ok: true,
|
|
468
|
+
kind: found.kind,
|
|
469
|
+
revision: found.revision,
|
|
470
|
+
baseRevision: found.parent,
|
|
471
|
+
entry: found.entry,
|
|
472
|
+
manifest: found.manifest,
|
|
473
|
+
};
|
|
474
|
+
}
|
|
475
|
+
publish(input) {
|
|
476
|
+
return this.locked(input.canvasId, () => {
|
|
477
|
+
try {
|
|
478
|
+
return this.publishLocked(input);
|
|
479
|
+
}
|
|
480
|
+
catch (error) {
|
|
481
|
+
return asStoreFailure(error);
|
|
482
|
+
}
|
|
483
|
+
});
|
|
484
|
+
}
|
|
485
|
+
fail(input) {
|
|
486
|
+
return this.locked(input.canvasId, () => {
|
|
487
|
+
const canvas = this.rawCanvas(input.canvasId);
|
|
488
|
+
if (!canvas)
|
|
489
|
+
return toolError('NOT_FOUND', 'No such canvas.');
|
|
490
|
+
if (Number(canvas.fence_generation) !== input.expectedFence)
|
|
491
|
+
return toolError('CAS_CONFLICT', 'The canvas fence changed.');
|
|
492
|
+
const message = input.message.trim();
|
|
493
|
+
if (message === '' || message.length > 500)
|
|
494
|
+
return toolError('VALIDATION', 'failure message is required.');
|
|
495
|
+
const revision = this.nextRevision(input.canvasId);
|
|
496
|
+
const createdAt = nowIso();
|
|
497
|
+
this.transaction(() => {
|
|
498
|
+
this.db
|
|
499
|
+
.prepare(`INSERT INTO canvas_revisions (
|
|
500
|
+
canvas_id, revision, parent, kind, entry, status, hash, error, created_at
|
|
501
|
+
) VALUES (?, ?, ?, 'failed', NULL, 'failed', NULL, ?, ?)`)
|
|
502
|
+
.run(input.canvasId, revision, canvas.preview_revision, message, createdAt);
|
|
503
|
+
this.db
|
|
504
|
+
.prepare('UPDATE canvases SET fence_generation = ? WHERE id = ?')
|
|
505
|
+
.run(input.expectedFence + 1, input.canvasId);
|
|
506
|
+
this.prune(input.canvasId, createdAt);
|
|
507
|
+
});
|
|
508
|
+
return { ok: true, revision, fence: input.expectedFence + 1, canvas: this.canvasRow(input.canvasId) };
|
|
509
|
+
});
|
|
510
|
+
}
|
|
511
|
+
adopt(input) {
|
|
512
|
+
return this.locked(input.canvasId, () => {
|
|
513
|
+
const canvas = this.rawCanvas(input.canvasId);
|
|
514
|
+
if (!canvas)
|
|
515
|
+
return toolError('NOT_FOUND', 'No such canvas.');
|
|
516
|
+
const revision = this.db
|
|
517
|
+
.prepare('SELECT status FROM canvas_revisions WHERE canvas_id = ? AND revision = ?')
|
|
518
|
+
.get(input.canvasId, input.revision);
|
|
519
|
+
if (!revision)
|
|
520
|
+
return toolError('NOT_FOUND', 'No such revision.');
|
|
521
|
+
if (revision.status === 'failed')
|
|
522
|
+
return toolError('VALIDATION', 'A failed revision cannot be adopted.');
|
|
523
|
+
this.db.prepare('UPDATE canvases SET stable_revision = ? WHERE id = ?').run(input.revision, input.canvasId);
|
|
524
|
+
this.db
|
|
525
|
+
.prepare(`UPDATE canvas_revisions SET status = 'preview' WHERE canvas_id = ? AND status = 'stable'`)
|
|
526
|
+
.run(input.canvasId);
|
|
527
|
+
this.db
|
|
528
|
+
.prepare(`UPDATE canvas_revisions SET status = 'stable' WHERE canvas_id = ? AND revision = ?`)
|
|
529
|
+
.run(input.canvasId, input.revision);
|
|
530
|
+
return { ok: true, stableRevision: input.revision, canvas: this.canvasRow(input.canvasId) };
|
|
531
|
+
});
|
|
532
|
+
}
|
|
533
|
+
mint(input) {
|
|
534
|
+
const canvas = this.rawCanvas(input.canvasId);
|
|
535
|
+
if (!canvas)
|
|
536
|
+
return toolError('NOT_FOUND', 'No such canvas.');
|
|
537
|
+
if (!Number.isInteger(input.minRevision) ||
|
|
538
|
+
!Number.isInteger(input.maxRevision) ||
|
|
539
|
+
input.minRevision < 1 ||
|
|
540
|
+
input.maxRevision < input.minRevision)
|
|
541
|
+
return toolError('VALIDATION', 'revision range is not allowed.');
|
|
542
|
+
const known = this.db
|
|
543
|
+
.prepare(`SELECT COUNT(*) AS n FROM canvas_revisions
|
|
544
|
+
WHERE canvas_id = ? AND revision BETWEEN ? AND ? AND status != 'failed'`)
|
|
545
|
+
.get(input.canvasId, input.minRevision, input.maxRevision).n;
|
|
546
|
+
if (Number(known) < 1)
|
|
547
|
+
return toolError('NOT_FOUND', 'No renderable revision in that range.');
|
|
548
|
+
const token = randomBytes(24).toString('base64url');
|
|
549
|
+
const tokenId = `ctok_${randomBytes(9).toString('base64url')}`;
|
|
550
|
+
const ttl = input.ttlMs ?? CANVAS_TOKEN_TTL_MS;
|
|
551
|
+
if (!Number.isInteger(ttl) || ttl < 1_000 || ttl > CANVAS_TOKEN_TTL_MS)
|
|
552
|
+
return toolError('VALIDATION', 'token ttl is not allowed.');
|
|
553
|
+
const expiresAt = new Date(Date.now() + ttl).toISOString();
|
|
554
|
+
this.db
|
|
555
|
+
.prepare(`INSERT INTO canvas_tokens (id, canvas_id, token_hash, min_revision, max_revision, expires_at, revoked_at)
|
|
556
|
+
VALUES (?, ?, ?, ?, ?, ?, NULL)`)
|
|
557
|
+
.run(tokenId, input.canvasId, sha256(token), input.minRevision, input.maxRevision, expiresAt);
|
|
558
|
+
return {
|
|
559
|
+
ok: true,
|
|
560
|
+
token,
|
|
561
|
+
tokenId,
|
|
562
|
+
expiresAt,
|
|
563
|
+
minRevision: input.minRevision,
|
|
564
|
+
maxRevision: input.maxRevision,
|
|
565
|
+
};
|
|
566
|
+
}
|
|
567
|
+
revoke(input) {
|
|
568
|
+
if (!CANVAS_ID.test(input.canvasId))
|
|
569
|
+
return toolError('NOT_FOUND', 'No such canvas.');
|
|
570
|
+
const result = this.db
|
|
571
|
+
.prepare(`UPDATE canvas_tokens SET revoked_at = ? WHERE id = ? AND canvas_id = ? AND revoked_at IS NULL`)
|
|
572
|
+
.run(nowIso(), input.tokenId, input.canvasId);
|
|
573
|
+
if (Number(result.changes) < 1)
|
|
574
|
+
return toolError('NOT_FOUND', 'No such token.');
|
|
575
|
+
return { ok: true };
|
|
576
|
+
}
|
|
577
|
+
/**
|
|
578
|
+
* Capability-token read. Callers must not consult the login cookie.
|
|
579
|
+
*/
|
|
580
|
+
readMedia(input) {
|
|
581
|
+
const path = normalizeCanvasPath(input.path);
|
|
582
|
+
if (!path || !/^[A-Za-z0-9_-]{20,128}$/.test(input.token))
|
|
583
|
+
return toolError('VALIDATION', 'canvas media path is not allowed.');
|
|
584
|
+
const token = this.db
|
|
585
|
+
.prepare(`SELECT canvas_id, min_revision, max_revision, expires_at, revoked_at
|
|
586
|
+
FROM canvas_tokens WHERE token_hash = ?`)
|
|
587
|
+
.get(sha256(input.token));
|
|
588
|
+
if (!token || token.revoked_at || token.expires_at <= nowIso())
|
|
589
|
+
return toolError('FORBIDDEN', 'canvas media token is not valid.');
|
|
590
|
+
if (input.revision < token.min_revision || input.revision > token.max_revision)
|
|
591
|
+
return toolError('FORBIDDEN', 'canvas media token is not valid.');
|
|
592
|
+
const file = this.db
|
|
593
|
+
.prepare(`SELECT f.media_type, b.bytes, b.size
|
|
594
|
+
FROM canvas_files f
|
|
595
|
+
JOIN canvas_blobs b ON b.hash = f.hash
|
|
596
|
+
WHERE f.canvas_id = ? AND f.revision = ? AND f.path = ?`)
|
|
597
|
+
.get(token.canvas_id, input.revision, path);
|
|
598
|
+
if (!file)
|
|
599
|
+
return toolError('NOT_FOUND', 'No such canvas file.');
|
|
600
|
+
const bytes = Buffer.from(file.bytes);
|
|
601
|
+
if (bytes.length !== file.size || !rasterOk(file.media_type, bytes))
|
|
602
|
+
return toolError('NOT_FOUND', 'No such canvas file.');
|
|
603
|
+
return { ok: true, type: file.media_type, bytes, canvasId: token.canvas_id };
|
|
604
|
+
}
|
|
605
|
+
publishLocked(input) {
|
|
606
|
+
if (input.kind !== 'snapshot' && input.kind !== 'delta')
|
|
607
|
+
return toolError('VALIDATION', 'kind must be snapshot or delta.');
|
|
608
|
+
if (!Number.isInteger(input.expectedFence) || input.expectedFence < 0)
|
|
609
|
+
return toolError('VALIDATION', 'expectedFence is required.');
|
|
610
|
+
const canvas = this.rawCanvas(input.canvasId);
|
|
611
|
+
if (!canvas)
|
|
612
|
+
return toolError('NOT_FOUND', 'No such canvas.');
|
|
613
|
+
if (Number(canvas.fence_generation) !== input.expectedFence)
|
|
614
|
+
return toolError('CAS_CONFLICT', 'The canvas fence changed.');
|
|
615
|
+
const checked = checkFiles(input.entry, input.files);
|
|
616
|
+
if (!Array.isArray(checked))
|
|
617
|
+
return checked;
|
|
618
|
+
const entry = normalizeCanvasPath(input.entry);
|
|
619
|
+
if (!entry)
|
|
620
|
+
return toolError('VALIDATION', 'entry path is not allowed.');
|
|
621
|
+
let parent = null;
|
|
622
|
+
if (input.kind === 'delta') {
|
|
623
|
+
if (canvas.preview_revision == null)
|
|
624
|
+
return toolError('VALIDATION', 'A delta needs a snapshot first.');
|
|
625
|
+
if (Number(canvas.preview_revision) !== input.baseRevision)
|
|
626
|
+
return toolError('CAS_CONFLICT', 'baseRevision is not the current preview.');
|
|
627
|
+
parent = Number(canvas.preview_revision);
|
|
628
|
+
}
|
|
629
|
+
const revision = this.nextRevision(input.canvasId);
|
|
630
|
+
const createdAt = nowIso();
|
|
631
|
+
const hash = manifestHash(checked);
|
|
632
|
+
this.transaction(() => {
|
|
633
|
+
this.db
|
|
634
|
+
.prepare(`INSERT INTO canvas_revisions (
|
|
635
|
+
canvas_id, revision, parent, kind, entry, status, hash, error, created_at
|
|
636
|
+
) VALUES (?, ?, ?, ?, ?, 'preview', ?, NULL, ?)`)
|
|
637
|
+
.run(input.canvasId, revision, parent, input.kind, entry, hash, createdAt);
|
|
638
|
+
const insertBlob = this.db.prepare('INSERT INTO canvas_blobs (hash, bytes, size) VALUES (?, ?, ?) ON CONFLICT(hash) DO NOTHING');
|
|
639
|
+
const insertFile = this.db.prepare(`INSERT INTO canvas_files (canvas_id, revision, path, hash, media_type, size)
|
|
640
|
+
VALUES (?, ?, ?, ?, ?, ?)`);
|
|
641
|
+
for (const file of input.files) {
|
|
642
|
+
const path = normalizeCanvasPath(file.path);
|
|
643
|
+
const item = checked.find(candidate => candidate.path === path);
|
|
644
|
+
if (!path || !item)
|
|
645
|
+
throw new Error('manifest drifted');
|
|
646
|
+
const digest = item.hash.slice('sha256:'.length);
|
|
647
|
+
insertBlob.run(digest, file.bytes, file.bytes.length);
|
|
648
|
+
insertFile.run(input.canvasId, revision, path, digest, item.type, file.bytes.length);
|
|
649
|
+
}
|
|
650
|
+
this.db
|
|
651
|
+
.prepare('UPDATE canvases SET preview_revision = ?, fence_generation = ? WHERE id = ?')
|
|
652
|
+
.run(revision, input.expectedFence + 1, input.canvasId);
|
|
653
|
+
this.prune(input.canvasId, createdAt);
|
|
654
|
+
});
|
|
655
|
+
const stored = this.db
|
|
656
|
+
.prepare('SELECT revision, parent, kind, status FROM canvas_revisions WHERE canvas_id = ? AND revision = ?')
|
|
657
|
+
.get(input.canvasId, revision);
|
|
658
|
+
this.remember(canvas.session_id, input.canvasId, stored, input.expectedFence + 1);
|
|
659
|
+
return {
|
|
660
|
+
ok: true,
|
|
661
|
+
revision,
|
|
662
|
+
kind: input.kind,
|
|
663
|
+
baseRevision: parent,
|
|
664
|
+
entry,
|
|
665
|
+
fence: input.expectedFence + 1,
|
|
666
|
+
manifest: checked,
|
|
667
|
+
canvas: this.canvasRow(input.canvasId),
|
|
668
|
+
};
|
|
669
|
+
}
|
|
670
|
+
remember(sessionId, canvasId, revision, fence) {
|
|
671
|
+
if (revision.kind !== 'snapshot' && revision.kind !== 'delta')
|
|
672
|
+
return;
|
|
673
|
+
this.notices.set(canvasId, {
|
|
674
|
+
sessionId,
|
|
675
|
+
wire: {
|
|
676
|
+
type: 'canvas.revision',
|
|
677
|
+
canvasId,
|
|
678
|
+
revision: revision.revision,
|
|
679
|
+
baseRevision: revision.parent,
|
|
680
|
+
kind: revision.kind,
|
|
681
|
+
stamp: `${canvasId}:${revision.revision}:${fence}`,
|
|
682
|
+
},
|
|
683
|
+
});
|
|
684
|
+
}
|
|
685
|
+
revisionFiles(canvasId, revision) {
|
|
686
|
+
if (!CANVAS_ID.test(canvasId) || !Number.isInteger(revision) || revision < 1)
|
|
687
|
+
return toolError('NOT_FOUND', 'No such revision.');
|
|
688
|
+
const row = this.db
|
|
689
|
+
.prepare(`SELECT revision, parent, kind, entry, status, error FROM canvas_revisions
|
|
690
|
+
WHERE canvas_id = ? AND revision = ?`)
|
|
691
|
+
.get(canvasId, revision);
|
|
692
|
+
if (!row)
|
|
693
|
+
return toolError('NOT_FOUND', 'No such revision.');
|
|
694
|
+
if (row.status === 'failed' || row.kind === 'failed')
|
|
695
|
+
return toolError('VALIDATION', row.error || 'This revision failed.');
|
|
696
|
+
const files = this.db
|
|
697
|
+
.prepare(`SELECT path, hash, size, media_type FROM canvas_files
|
|
698
|
+
WHERE canvas_id = ? AND revision = ? ORDER BY path ASC`)
|
|
699
|
+
.all(canvasId, revision);
|
|
700
|
+
return {
|
|
701
|
+
ok: true,
|
|
702
|
+
revision: row.revision,
|
|
703
|
+
parent: row.parent,
|
|
704
|
+
kind: row.kind,
|
|
705
|
+
entry: row.entry,
|
|
706
|
+
manifest: files.map(file => ({
|
|
707
|
+
path: file.path,
|
|
708
|
+
hash: `sha256:${file.hash}`,
|
|
709
|
+
bytes: file.size,
|
|
710
|
+
type: file.media_type,
|
|
711
|
+
})),
|
|
712
|
+
};
|
|
713
|
+
}
|
|
714
|
+
prune(canvasId, now) {
|
|
715
|
+
const canvas = this.rawCanvas(canvasId);
|
|
716
|
+
if (!canvas)
|
|
717
|
+
return;
|
|
718
|
+
const revisions = this.db
|
|
719
|
+
.prepare('SELECT revision FROM canvas_revisions WHERE canvas_id = ? ORDER BY revision DESC')
|
|
720
|
+
.all(canvasId)
|
|
721
|
+
.map(row => row.revision);
|
|
722
|
+
const keep = new Set(revisions.slice(0, CANVAS_KEEP_REVISIONS));
|
|
723
|
+
if (canvas.stable_revision != null)
|
|
724
|
+
keep.add(canvas.stable_revision);
|
|
725
|
+
if (canvas.preview_revision != null)
|
|
726
|
+
keep.add(canvas.preview_revision);
|
|
727
|
+
const tokens = this.db
|
|
728
|
+
.prepare(`SELECT min_revision, max_revision FROM canvas_tokens
|
|
729
|
+
WHERE canvas_id = ? AND revoked_at IS NULL AND expires_at > ?`)
|
|
730
|
+
.all(canvasId, now);
|
|
731
|
+
for (const token of tokens) {
|
|
732
|
+
for (const revision of revisions) {
|
|
733
|
+
if (revision >= token.min_revision && revision <= token.max_revision)
|
|
734
|
+
keep.add(revision);
|
|
735
|
+
}
|
|
736
|
+
}
|
|
737
|
+
for (const revision of revisions) {
|
|
738
|
+
if (keep.has(revision))
|
|
739
|
+
continue;
|
|
740
|
+
this.db.prepare('DELETE FROM canvas_files WHERE canvas_id = ? AND revision = ?').run(canvasId, revision);
|
|
741
|
+
this.db.prepare('DELETE FROM canvas_revisions WHERE canvas_id = ? AND revision = ?').run(canvasId, revision);
|
|
742
|
+
}
|
|
743
|
+
this.db.prepare('DELETE FROM canvas_blobs WHERE hash NOT IN (SELECT hash FROM canvas_files)').run();
|
|
744
|
+
}
|
|
745
|
+
nextRevision(canvasId) {
|
|
746
|
+
const row = this.db.prepare('SELECT MAX(revision) AS n FROM canvas_revisions WHERE canvas_id = ?').get(canvasId);
|
|
747
|
+
return Number(row?.n ?? 0) + 1;
|
|
748
|
+
}
|
|
749
|
+
rawCanvas(canvasId) {
|
|
750
|
+
if (!CANVAS_ID.test(canvasId))
|
|
751
|
+
return null;
|
|
752
|
+
return this.db
|
|
753
|
+
.prepare(`SELECT id, session_id, ticket_id, title, stable_revision, preview_revision, fence_generation, created_at
|
|
754
|
+
FROM canvases WHERE id = ?`)
|
|
755
|
+
.get(canvasId);
|
|
756
|
+
}
|
|
757
|
+
canvasRow(canvasId) {
|
|
758
|
+
const row = this.rawCanvas(canvasId);
|
|
759
|
+
if (!row)
|
|
760
|
+
return null;
|
|
761
|
+
return {
|
|
762
|
+
id: row.id,
|
|
763
|
+
sessionId: row.session_id,
|
|
764
|
+
ticketId: row.ticket_id ?? null,
|
|
765
|
+
title: row.title,
|
|
766
|
+
stableRevision: row.stable_revision ?? null,
|
|
767
|
+
previewRevision: row.preview_revision ?? null,
|
|
768
|
+
fence: Number(row.fence_generation),
|
|
769
|
+
createdAt: row.created_at,
|
|
770
|
+
};
|
|
771
|
+
}
|
|
772
|
+
transaction(run) {
|
|
773
|
+
this.db.exec('BEGIN IMMEDIATE');
|
|
774
|
+
try {
|
|
775
|
+
run();
|
|
776
|
+
this.db.exec('COMMIT');
|
|
777
|
+
}
|
|
778
|
+
catch (error) {
|
|
779
|
+
try {
|
|
780
|
+
this.db.exec('ROLLBACK');
|
|
781
|
+
}
|
|
782
|
+
catch {
|
|
783
|
+
/* already rolled back */
|
|
784
|
+
}
|
|
785
|
+
throw error;
|
|
786
|
+
}
|
|
787
|
+
}
|
|
788
|
+
locked(canvasId, fn) {
|
|
789
|
+
const previous = this.tails.get(canvasId) ?? Promise.resolve();
|
|
790
|
+
const run = previous.then(fn, fn);
|
|
791
|
+
this.tails.set(canvasId, run.then(() => undefined, () => undefined));
|
|
792
|
+
return run;
|
|
793
|
+
}
|
|
794
|
+
}
|