@khanglvm/relay 0.19.0 → 0.20.1
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 +11 -4
- package/bin/rly.js +1 -1
- package/package.json +4 -4
- package/src/cli/args.js +46 -0
- package/src/cli/ask.js +12 -0
- package/src/cli/boards.js +326 -0
- package/src/cli/config.js +56 -0
- package/src/cli/context.js +13 -0
- package/src/cli/git.js +183 -0
- package/src/cli/help.js +91 -0
- package/src/cli/index.js +103 -0
- package/src/cli/install.js +197 -0
- package/src/cli/io.js +186 -0
- package/src/cli/mcp.js +94 -0
- package/src/cli/share.js +45 -0
- package/src/cli/skill.js +192 -0
- package/src/cli/upgrade.js +130 -0
- package/src/cli/wait.js +172 -0
- package/src/file-preview.js +1 -1
- package/src/index.js +1 -1
- package/src/link.js +57 -9
- package/src/mcp-ui/board/block-ctx.js +43 -0
- package/src/mcp-ui/board/bridge.js +165 -0
- package/src/mcp-ui/board/controls.js +310 -0
- package/src/mcp-ui/board/core.js +20 -0
- package/src/mcp-ui/board/lifecycle.js +118 -0
- package/src/mcp-ui/board/normalize.js +95 -0
- package/src/mcp-ui/board/render.js +200 -0
- package/src/mcp-ui/board/state.js +106 -0
- package/src/mcp-ui/board/vendors.js +86 -0
- package/src/mcp.js +12 -18
- package/src/{server.js → server/board.js} +16 -779
- package/src/server/files.js +141 -0
- package/src/server/http.js +114 -0
- package/src/server/index.js +2 -0
- package/src/server/page.js +183 -0
- package/src/server/paths.js +7 -0
- package/src/server/result.js +58 -0
- package/src/server/reviews.js +41 -0
- package/src/server/sanitize.js +231 -0
- package/src/spec/blocks/a2ui.js +25 -0
- package/src/spec/blocks/chart.js +49 -0
- package/src/spec/blocks/code.js +38 -0
- package/src/spec/blocks/diagram.js +39 -0
- package/src/spec/blocks/git-conflict.js +106 -0
- package/src/spec/blocks/image.js +32 -0
- package/src/spec/blocks/index.js +33 -0
- package/src/spec/blocks/markdown.js +13 -0
- package/src/spec/blocks/pdf.js +38 -0
- package/src/spec/blocks/table.js +122 -0
- package/src/spec/blocks/video.js +68 -0
- package/src/spec/blocks/widgets.js +98 -0
- package/src/spec/constants.js +65 -0
- package/src/spec/index.js +5 -0
- package/src/spec/normalize.js +285 -0
- package/src/spec/ready.js +106 -0
- package/src/spec/schema.js +182 -0
- package/src/spec/sources.js +83 -0
- package/src/store.js +1 -1
- package/src/ui/annotate/api.js +149 -0
- package/src/ui/annotate/badges.js +77 -0
- package/src/ui/annotate/chrome.js +158 -0
- package/src/ui/annotate/core.js +134 -0
- package/src/ui/annotate/highlights.js +129 -0
- package/src/ui/annotate/mutations.js +127 -0
- package/src/ui/annotate/popover.js +206 -0
- package/src/ui/annotate/summary.js +67 -0
- package/src/ui/app/annotations.js +88 -0
- package/src/ui/app/autosave.js +44 -0
- package/src/ui/app/core.js +74 -0
- package/src/ui/app/drafts.js +201 -0
- package/src/ui/app/heartbeat.js +150 -0
- package/src/ui/app/iframe-bridge.js +64 -0
- package/src/ui/app/persistence.js +117 -0
- package/src/ui/app/prefilled.js +21 -0
- package/src/ui/app/presence.js +38 -0
- package/src/ui/app/question-color.js +67 -0
- package/src/ui/app/questions.js +360 -0
- package/src/ui/app/render.js +135 -0
- package/src/ui/app/share.js +108 -0
- package/src/ui/app/submit.js +109 -0
- package/src/ui/app/theme.js +63 -0
- package/src/ui/blocks/api.js +1 -0
- package/src/ui/blocks/chart.js +222 -0
- package/src/ui/blocks/code.js +138 -0
- package/src/ui/blocks/compare.js +82 -0
- package/src/ui/blocks/core.js +74 -0
- package/src/ui/blocks/diff.js +361 -0
- package/src/ui/blocks/dispatch.js +111 -0
- package/src/ui/blocks/file-links.js +180 -0
- package/src/ui/blocks/git-conflict.js +151 -0
- package/src/ui/blocks/graphviz.js +57 -0
- package/src/ui/blocks/html.js +45 -0
- package/src/ui/blocks/image.js +371 -0
- package/src/ui/blocks/kpi.js +26 -0
- package/src/ui/blocks/markdown.js +223 -0
- package/src/ui/blocks/mermaid.js +242 -0
- package/src/ui/blocks/palette.js +59 -0
- package/src/ui/blocks/pdf.js +21 -0
- package/src/ui/blocks/plantuml.js +152 -0
- package/src/ui/blocks/table.js +155 -0
- package/src/ui/blocks/typography.js +25 -0
- package/src/ui/blocks/vendor.js +43 -0
- package/src/ui/blocks/video.js +43 -0
- package/src/ui/blocks/viewer-fullscreen.js +146 -0
- package/src/ui/blocks/viewer.js +324 -0
- package/src/ui/kit.js +1 -0
- package/src/ui/manifest.js +140 -0
- package/types/index.d.ts +1 -1
- package/types/spec/blocks/a2ui.d.ts +4 -0
- package/types/spec/blocks/chart.d.ts +4 -0
- package/types/spec/blocks/code.d.ts +10 -0
- package/types/spec/blocks/diagram.d.ts +15 -0
- package/types/spec/blocks/git-conflict.d.ts +7 -0
- package/types/spec/blocks/image.d.ts +5 -0
- package/types/spec/blocks/index.d.ts +30 -0
- package/types/spec/blocks/markdown.d.ts +5 -0
- package/types/spec/blocks/pdf.d.ts +4 -0
- package/types/spec/blocks/table.d.ts +9 -0
- package/types/spec/blocks/video.d.ts +4 -0
- package/types/spec/blocks/widgets.d.ts +21 -0
- package/types/spec/constants.d.ts +67 -0
- package/types/spec/index.d.ts +4 -0
- package/types/spec/normalize.d.ts +17 -0
- package/types/spec/ready.d.ts +1 -0
- package/types/{spec.d.ts → spec/schema.d.ts} +0 -20
- package/types/spec/sources.d.ts +14 -0
- package/types/ui/manifest.d.ts +62 -0
- package/src/cli.js +0 -1767
- package/src/mcp-ui/board.js +0 -1162
- package/src/spec.js +0 -1224
- package/src/ui/annotate.js +0 -1055
- package/src/ui/app.js +0 -1643
- package/src/ui/blocks.js +0 -3260
|
@@ -1,783 +1,20 @@
|
|
|
1
|
-
|
|
1
|
+
// code-craft: allow-size runBoard is one closure over the live board state (rev, status, shares, presence); its route handlers read and write that state directly, so splitting them out would need a shared state object and change how it is passed.
|
|
2
|
+
import crypto from 'node:crypto';
|
|
2
3
|
import fs from 'node:fs';
|
|
3
|
-
import
|
|
4
|
+
import http from 'node:http';
|
|
4
5
|
import path from 'node:path';
|
|
5
|
-
import
|
|
6
|
-
import {
|
|
7
|
-
import {
|
|
8
|
-
import {
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
} from './store.js';
|
|
18
|
-
import { openUrl } from './open.js';
|
|
19
|
-
import { assertSpecReady } from './spec.js';
|
|
20
|
-
import { assertSafeJson } from './a2ui/compile.js';
|
|
21
|
-
import { resolveLink } from './link.js';
|
|
22
|
-
import { splitFileReference, filePreview, mediaType } from './file-preview.js';
|
|
23
|
-
|
|
24
|
-
const UI_DIR = path.join(path.dirname(fileURLToPath(import.meta.url)), 'ui');
|
|
25
|
-
const PKG_ROOT = path.join(path.dirname(fileURLToPath(import.meta.url)), '..');
|
|
26
|
-
const VENDOR_DIR = path.join(PKG_ROOT, 'vendor');
|
|
27
|
-
const ARTIFACT_MAX_BYTES = 4 * 1024 * 1024;
|
|
28
|
-
const ARTIFACT_MIMES = {
|
|
29
|
-
'image/png': 'png',
|
|
30
|
-
'image/jpeg': 'jpg',
|
|
31
|
-
'image/webp': 'webp',
|
|
32
|
-
};
|
|
33
|
-
|
|
34
|
-
const escapeHtml = (s) =>
|
|
35
|
-
s.replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]));
|
|
36
|
-
|
|
37
|
-
// Concurrently authored UI assets (blocks/annotate) may not exist yet at this
|
|
38
|
-
// phase's runtime — read-guard so the server still boots with empty fallbacks.
|
|
39
|
-
//
|
|
40
|
-
// Successful reads are cached for the lifetime of the process. A running board
|
|
41
|
-
// thus serves one consistent UI snapshot taken at first request: if the relay
|
|
42
|
-
// package is updated on disk (e.g. `rly upgrade`) while this server is live, it
|
|
43
|
-
// keeps serving its own version instead of mixing new assets with old in-memory
|
|
44
|
-
// server logic. Empty/failed reads are NOT cached, preserving the boot-time
|
|
45
|
-
// fallback for assets authored concurrently during a build.
|
|
46
|
-
const _uiCache = new Map();
|
|
47
|
-
function readUi(name) {
|
|
48
|
-
const hit = _uiCache.get(name);
|
|
49
|
-
if (hit) return hit;
|
|
50
|
-
let content = '';
|
|
51
|
-
try {
|
|
52
|
-
content = fs.readFileSync(path.join(UI_DIR, name), 'utf8');
|
|
53
|
-
} catch {
|
|
54
|
-
return '';
|
|
55
|
-
}
|
|
56
|
-
if (content) _uiCache.set(name, content);
|
|
57
|
-
return content;
|
|
58
|
-
}
|
|
59
|
-
|
|
60
|
-
// Strips block bodies for the client payload: html blocks ship only metadata
|
|
61
|
-
// (their bodies are served via /html/b/<id>), embedded images ship only
|
|
62
|
-
// metadata (bytes served via /img/b/<id>), streamed local media ships only
|
|
63
|
-
// metadata (bytes served via /video/b/<id> or /pdf/b/<id>), everything else
|
|
64
|
-
// ships as-is.
|
|
65
|
-
function clientBlock(b) {
|
|
66
|
-
// Cross-block fields preserved when we ship metadata-only (ref = reference-link
|
|
67
|
-
// target name; pins = image coordinate comments). The default `return b` path
|
|
68
|
-
// already carries them.
|
|
69
|
-
const extra = {};
|
|
70
|
-
if (b && b.ref !== undefined) extra.ref = b.ref;
|
|
71
|
-
if (b && b.type === 'html') {
|
|
72
|
-
return { id: b.id, type: 'html', height: b.height, hasHtml: Boolean(b.html), ...extra };
|
|
73
|
-
}
|
|
74
|
-
if (b && b.type === 'image' && typeof b.src === 'string' && b.src.startsWith('data:')) {
|
|
75
|
-
return { id: b.id, type: 'image', alt: b.alt, height: b.height, hasData: true, ...(b.pins ? { pins: true } : {}), ...extra };
|
|
76
|
-
}
|
|
77
|
-
// Local video: the absolute file path stays server-side; the client gets a
|
|
78
|
-
// flag + mime and loads the bytes (Range-streamed) from /video/b/<id>.
|
|
79
|
-
if (b && b.type === 'video' && typeof b.file === 'string') {
|
|
80
|
-
return { id: b.id, type: 'video', title: b.title, height: b.height, mime: b.mime, hasFile: true, ...extra };
|
|
81
|
-
}
|
|
82
|
-
if (b && b.type === 'pdf' && typeof b.file === 'string') {
|
|
83
|
-
return { id: b.id, type: 'pdf', title: b.title, height: b.height, mime: b.mime, hasFile: true, ...extra };
|
|
84
|
-
}
|
|
85
|
-
return b;
|
|
86
|
-
}
|
|
87
|
-
|
|
88
|
-
// One question for the client payload: strip block bodies at the question
|
|
89
|
-
// level AND inside each option's blocks.
|
|
90
|
-
function clientQuestion(q) {
|
|
91
|
-
const out = { ...q, blocks: (q.blocks || []).map(clientBlock) };
|
|
92
|
-
if (Array.isArray(q.options)) {
|
|
93
|
-
out.options = q.options.map((o) =>
|
|
94
|
-
o && Array.isArray(o.blocks) && o.blocks.length ? { ...o, blocks: o.blocks.map(clientBlock) } : o
|
|
95
|
-
);
|
|
96
|
-
}
|
|
97
|
-
return out;
|
|
98
|
-
}
|
|
99
|
-
|
|
100
|
-
// True when any block in the spec needs a given vendored library.
|
|
101
|
-
function specNeeds(spec, type) {
|
|
102
|
-
const has = (blocks) => Array.isArray(blocks) && blocks.some((b) => b && b.type === type);
|
|
103
|
-
if (has(spec.blocks)) return true;
|
|
104
|
-
return spec.questions.some(
|
|
105
|
-
(q) => has(q.blocks) || (Array.isArray(q.options) && q.options.some((o) => o && has(o.blocks)))
|
|
106
|
-
);
|
|
107
|
-
}
|
|
108
|
-
|
|
109
|
-
function vendorPresent(file) {
|
|
110
|
-
try {
|
|
111
|
-
return fs.existsSync(path.join(VENDOR_DIR, file));
|
|
112
|
-
} catch {
|
|
113
|
-
return false;
|
|
114
|
-
}
|
|
115
|
-
}
|
|
116
|
-
|
|
117
|
-
function cleanShareHost(raw) {
|
|
118
|
-
const s = String(raw || '').trim();
|
|
119
|
-
if (!s) return null;
|
|
120
|
-
let host = s;
|
|
121
|
-
try {
|
|
122
|
-
host = s.includes('://') ? new URL(s).hostname : s;
|
|
123
|
-
} catch {
|
|
124
|
-
host = s;
|
|
125
|
-
}
|
|
126
|
-
host = host.replace(/^https?:\/\//, '').split('/')[0].split(':')[0].trim();
|
|
127
|
-
if (!host || host === '127.0.0.1' || host === 'localhost') return null;
|
|
128
|
-
return host;
|
|
129
|
-
}
|
|
130
|
-
|
|
131
|
-
function isPrivateIpv4(address) {
|
|
132
|
-
if (!/^(\d{1,3}\.){3}\d{1,3}$/.test(address)) return false;
|
|
133
|
-
const parts = address.split('.').map((n) => Number(n));
|
|
134
|
-
if (parts.some((n) => !Number.isInteger(n) || n < 0 || n > 255)) return false;
|
|
135
|
-
return (
|
|
136
|
-
parts[0] === 10 ||
|
|
137
|
-
(parts[0] === 172 && parts[1] >= 16 && parts[1] <= 31) ||
|
|
138
|
-
(parts[0] === 192 && parts[1] === 168)
|
|
139
|
-
);
|
|
140
|
-
}
|
|
141
|
-
|
|
142
|
-
function shareHost() {
|
|
143
|
-
const forced = cleanShareHost(process.env.RLY_SHARE_HOST);
|
|
144
|
-
if (forced) return forced;
|
|
145
|
-
const candidates = [];
|
|
146
|
-
const nets = os.networkInterfaces();
|
|
147
|
-
for (const list of Object.values(nets)) {
|
|
148
|
-
for (const net of list || []) {
|
|
149
|
-
if (!net || net.internal || net.family !== 'IPv4') continue;
|
|
150
|
-
candidates.push(net.address);
|
|
151
|
-
}
|
|
152
|
-
}
|
|
153
|
-
return candidates.find(isPrivateIpv4) || candidates[0] || null;
|
|
154
|
-
}
|
|
155
|
-
|
|
156
|
-
function buildPage(record, rev, { access = null, draftRev = 0 } = {}) {
|
|
157
|
-
const html = fs.readFileSync(path.join(UI_DIR, 'index.html'), 'utf8');
|
|
158
|
-
const css = readUi('style.css');
|
|
159
|
-
const blocksCss = readUi('blocks.css') + '\n' + readUi('a2ui.css');
|
|
160
|
-
const annotateCss = readUi('annotate.css');
|
|
161
|
-
const blocksJs = readUi('a2ui-state.js') + '\n' + readUi('a2ui.js') + '\n' + readUi('blocks.js');
|
|
162
|
-
const annotateJs = readUi('annotate.js');
|
|
163
|
-
const appJs = readUi('app.js');
|
|
164
|
-
const spec = record.spec;
|
|
165
|
-
// Block bodies (html) are served via /html/b/* iframes, so strip them from
|
|
166
|
-
// the embedded payload and only ship metadata.
|
|
167
|
-
const clientSpec = {
|
|
168
|
-
...spec,
|
|
169
|
-
blocks: (spec.blocks || []).map(clientBlock),
|
|
170
|
-
questions: spec.questions.map(clientQuestion),
|
|
171
|
-
};
|
|
172
|
-
// Tell the client which vendored libraries to lazy-load — true only when a
|
|
173
|
-
// block needs it AND the vendored asset is actually present.
|
|
174
|
-
// Filenames must match what the clients request (blocks.js / kit.js load
|
|
175
|
-
// /vendor/chart.umd.js and /vendor/mermaid.min.js).
|
|
176
|
-
const vendor = {
|
|
177
|
-
chart: specNeeds(spec, 'chart') && vendorPresent('chart.umd.js'),
|
|
178
|
-
mermaid: specNeeds(spec, 'mermaid') && vendorPresent('mermaid.min.js'),
|
|
179
|
-
viz: specNeeds(spec, 'graphviz') && vendorPresent('viz-standalone.js'),
|
|
180
|
-
};
|
|
181
|
-
// Prefill from the LIVE draft at request time (drafts autosave in real time),
|
|
182
|
-
// so a mid-fill page reload restores everything the user already entered.
|
|
183
|
-
// Reviewer answers are an independent, reference-only draft. They must never
|
|
184
|
-
// prefill from or overwrite the owner's final-answer draft. Read-only viewers
|
|
185
|
-
// see the owner's current state but cannot mutate it.
|
|
186
|
-
const reviewDrafts = record.reviewDrafts && typeof record.reviewDrafts === 'object' ? record.reviewDrafts : {};
|
|
187
|
-
const sourceDraft = access && access.role === 'review'
|
|
188
|
-
? (reviewDrafts[access.reviewSessionId] || null)
|
|
189
|
-
: record.draft;
|
|
190
|
-
const prefill = sourceDraft
|
|
191
|
-
? {
|
|
192
|
-
answers: sourceDraft.answers || {},
|
|
193
|
-
comment: sourceDraft.comment || '',
|
|
194
|
-
notes: sourceDraft.notes || {},
|
|
195
|
-
annotations: sourceDraft.annotations || [],
|
|
196
|
-
blockEdits: sourceDraft.blockEdits || {},
|
|
197
|
-
// The server draft's save time, so the client can pick the NEWER of this
|
|
198
|
-
// vs. its localStorage mirror (a tab that kept typing while the server
|
|
199
|
-
// was unreachable holds fresher input than the last server save).
|
|
200
|
-
updatedAt: sourceDraft.updatedAt || null,
|
|
201
|
-
}
|
|
202
|
-
: null;
|
|
203
|
-
const boot = { boardId: record.id, spec: clientSpec, prefill, pref: loadPref(), vendor, rev, draftRev, access };
|
|
204
|
-
const json = JSON.stringify(boot).replace(/</g, '\\u003c');
|
|
205
|
-
return html
|
|
206
|
-
.split('__TITLE__').join(escapeHtml(spec.title))
|
|
207
|
-
.split('/*__CSS__*/').join(css)
|
|
208
|
-
.split('/*__BLOCKS_CSS__*/').join(blocksCss)
|
|
209
|
-
.split('/*__ANNOTATE_CSS__*/').join(annotateCss)
|
|
210
|
-
.split('/*__BLOCKS_JS__*/').join(blocksJs)
|
|
211
|
-
.split('/*__ANNOTATE_JS__*/').join(annotateJs)
|
|
212
|
-
.split('/*__APP_JS__*/').join(appJs)
|
|
213
|
-
.split('__BOOT_JSON__').join(json);
|
|
214
|
-
}
|
|
215
|
-
|
|
216
|
-
function buildLockedPage(title = 'Relay board') {
|
|
217
|
-
return '<!doctype html><html><head><meta charset="utf-8">' +
|
|
218
|
-
'<meta name="viewport" content="width=device-width, initial-scale=1">' +
|
|
219
|
-
'<title>' + escapeHtml(title) + '</title>' +
|
|
220
|
-
'<style>body{margin:0;font:16px/1.5 -apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif;background:#fcfbf9;color:#1c1b19;display:grid;min-height:100vh;place-items:center}.box{max-width:420px;padding:28px;text-align:center}.title{font-size:22px;font-weight:650;margin-bottom:8px}.sub{color:#57534e}</style>' +
|
|
221
|
-
'</head><body><div class="box"><div class="title">Share link not active</div><div class="sub">Ask the board owner to use Share and choose a permission before opening this board from another device.</div></div></body></html>';
|
|
222
|
-
}
|
|
223
|
-
|
|
224
|
-
const SHARE_STATE_VERSION = 2;
|
|
225
|
-
const REVIEW_SESSION_COOKIE = 'relay_review_session';
|
|
226
|
-
|
|
227
|
-
function reviewSessionId(req) {
|
|
228
|
-
if (req._relayReviewSessionId) return req._relayReviewSessionId;
|
|
229
|
-
const explicit = String(req.headers['x-relay-review-session'] || '');
|
|
230
|
-
const cookies = String(req.headers.cookie || '').split(';').map((s) => s.trim());
|
|
231
|
-
const cookie = cookies.find((s) => s.startsWith(REVIEW_SESSION_COOKIE + '='));
|
|
232
|
-
let value = explicit || (cookie ? decodeURIComponent(cookie.slice(REVIEW_SESSION_COOKIE.length + 1)) : '');
|
|
233
|
-
if (!/^[A-Za-z0-9_-]{8,80}$/.test(value)) value = 'rv-' + crypto.randomBytes(12).toString('hex');
|
|
234
|
-
req._relayReviewSessionId = value;
|
|
235
|
-
return value;
|
|
236
|
-
}
|
|
237
|
-
|
|
238
|
-
function reviewSessionCookie(sessionId) {
|
|
239
|
-
return `${REVIEW_SESSION_COOKIE}=${encodeURIComponent(sessionId)}; Path=/; HttpOnly; SameSite=Strict; Max-Age=2592000`;
|
|
240
|
-
}
|
|
241
|
-
|
|
242
|
-
function sideReviewState(record) {
|
|
243
|
-
const drafts = record.reviewDrafts && typeof record.reviewDrafts === 'object' ? record.reviewDrafts : {};
|
|
244
|
-
const submissions = Array.isArray(record.sideReviews) ? record.sideReviews : [];
|
|
245
|
-
return {
|
|
246
|
-
referenceOnly: true,
|
|
247
|
-
note: 'Side reviews are reference only. Wait for the board owner (or owner-authorized collaborator) to submit the final answer.',
|
|
248
|
-
submissions,
|
|
249
|
-
drafts,
|
|
250
|
-
};
|
|
251
|
-
}
|
|
252
|
-
|
|
253
|
-
function pruneReviewDrafts(record, max = 50) {
|
|
254
|
-
const drafts = record.reviewDrafts && typeof record.reviewDrafts === 'object' ? record.reviewDrafts : {};
|
|
255
|
-
const entries = Object.entries(drafts).sort((a, b) => {
|
|
256
|
-
const at = Date.parse(a[1] && a[1].updatedAt || '') || 0;
|
|
257
|
-
const bt = Date.parse(b[1] && b[1].updatedAt || '') || 0;
|
|
258
|
-
return bt - at;
|
|
259
|
-
});
|
|
260
|
-
record.reviewDrafts = Object.fromEntries(entries.slice(0, max));
|
|
261
|
-
}
|
|
262
|
-
|
|
263
|
-
// Validates + sanitizes one annotation's threaded replies. Keeps only
|
|
264
|
-
// well-formed {author, text, createdAt} entries; caps at 50; coerces author.
|
|
265
|
-
function sanitizeReplies(value) {
|
|
266
|
-
if (!Array.isArray(value)) return [];
|
|
267
|
-
const out = [];
|
|
268
|
-
for (const r of value) {
|
|
269
|
-
if (out.length >= 50) break;
|
|
270
|
-
if (r === null || typeof r !== 'object' || Array.isArray(r)) continue;
|
|
271
|
-
if (typeof r.text !== 'string' || r.text.length > 5000) continue;
|
|
272
|
-
const author = r.author === 'agent' ? 'agent' : 'user';
|
|
273
|
-
const createdAt = typeof r.createdAt === 'string' ? r.createdAt : new Date().toISOString();
|
|
274
|
-
out.push({ author, text: r.text, createdAt });
|
|
275
|
-
}
|
|
276
|
-
return out;
|
|
277
|
-
}
|
|
278
|
-
|
|
279
|
-
// Validates + sanitizes an incoming annotations array (from draft/submit).
|
|
280
|
-
// Drops anything that isn't a well-formed annotation object; caps at 500.
|
|
281
|
-
// Each annotation may carry an optional author ('user'|'agent', default
|
|
282
|
-
// 'user') and a threaded replies array (validated + capped at 50).
|
|
283
|
-
function sanitizeAnnotationCrop(value, boardId) {
|
|
284
|
-
if (!value || typeof value !== 'object' || Array.isArray(value) || !boardId) return null;
|
|
285
|
-
const rawPath = typeof value.path === 'string' ? value.path : '';
|
|
286
|
-
if (!rawPath) return null;
|
|
287
|
-
const base = path.resolve(artifactDirPath(boardId)) + path.sep;
|
|
288
|
-
const resolved = path.resolve(rawPath);
|
|
289
|
-
if (!resolved.startsWith(base)) return null;
|
|
290
|
-
let stat;
|
|
291
|
-
try { stat = fs.statSync(resolved); } catch { return null; }
|
|
292
|
-
if (!stat.isFile() || stat.size < 1 || stat.size > ARTIFACT_MAX_BYTES) return null;
|
|
293
|
-
const mime = ARTIFACT_MIMES[value.mime] ? value.mime : 'image/png';
|
|
294
|
-
return {
|
|
295
|
-
path: resolved,
|
|
296
|
-
name: path.basename(resolved),
|
|
297
|
-
mime,
|
|
298
|
-
bytes: stat.size,
|
|
299
|
-
width: Math.max(1, Math.min(10000, Number.parseInt(value.width, 10) || 1)),
|
|
300
|
-
height: Math.max(1, Math.min(10000, Number.parseInt(value.height, 10) || 1)),
|
|
301
|
-
};
|
|
302
|
-
}
|
|
303
|
-
|
|
304
|
-
function sanitizeAnnotationTarget(value, boardId) {
|
|
305
|
-
const clean = { ...value };
|
|
306
|
-
delete clean.cropDataUrl;
|
|
307
|
-
if (clean.kind !== 'image-region') {
|
|
308
|
-
delete clean.crop;
|
|
309
|
-
return clean;
|
|
310
|
-
}
|
|
311
|
-
const unit = (v) => Math.max(0, Math.min(1, Number(v) || 0));
|
|
312
|
-
clean.x = unit(clean.x);
|
|
313
|
-
clean.y = unit(clean.y);
|
|
314
|
-
clean.w = unit(clean.w);
|
|
315
|
-
clean.h = unit(clean.h);
|
|
316
|
-
if (clean.x + clean.w > 1) clean.w = 1 - clean.x;
|
|
317
|
-
if (clean.y + clean.h > 1) clean.h = 1 - clean.y;
|
|
318
|
-
clean.label = limitString(clean.label, 200);
|
|
319
|
-
if (clean.side !== 'before' && clean.side !== 'after') delete clean.side;
|
|
320
|
-
const crop = sanitizeAnnotationCrop(clean.crop, boardId);
|
|
321
|
-
if (crop) clean.crop = crop;
|
|
322
|
-
else delete clean.crop;
|
|
323
|
-
return clean;
|
|
324
|
-
}
|
|
325
|
-
|
|
326
|
-
function sanitizeAnnotations(value, boardId) {
|
|
327
|
-
if (!Array.isArray(value)) return [];
|
|
328
|
-
const out = [];
|
|
329
|
-
for (const a of value) {
|
|
330
|
-
if (out.length >= 500) break;
|
|
331
|
-
if (a === null || typeof a !== 'object' || Array.isArray(a)) continue;
|
|
332
|
-
if (typeof a.text !== 'string' || a.text.length > 5000) continue;
|
|
333
|
-
if (a.target === null || typeof a.target !== 'object' || Array.isArray(a.target)) continue;
|
|
334
|
-
const clean = {
|
|
335
|
-
...a,
|
|
336
|
-
target: sanitizeAnnotationTarget(a.target, boardId),
|
|
337
|
-
author: a.author === 'agent' ? 'agent' : 'user',
|
|
338
|
-
};
|
|
339
|
-
if (a.replies !== undefined) clean.replies = sanitizeReplies(a.replies);
|
|
340
|
-
out.push(clean);
|
|
341
|
-
}
|
|
342
|
-
return out;
|
|
343
|
-
}
|
|
344
|
-
|
|
345
|
-
function limitString(v, max) {
|
|
346
|
-
return typeof v === 'string' ? v.slice(0, max) : '';
|
|
347
|
-
}
|
|
348
|
-
|
|
349
|
-
function sanitizeConflictResolution(value) {
|
|
350
|
-
if (!value || typeof value !== 'object' || Array.isArray(value)) return null;
|
|
351
|
-
if (value.type !== 'git-conflict-resolution') return null;
|
|
352
|
-
const out = {
|
|
353
|
-
type: 'git-conflict-resolution',
|
|
354
|
-
filename: limitString(value.filename, 500),
|
|
355
|
-
file: limitString(value.file, 1200),
|
|
356
|
-
resolved: value.resolved === true,
|
|
357
|
-
resolutions: {},
|
|
358
|
-
content: limitString(value.content, 512 * 1024),
|
|
359
|
-
};
|
|
360
|
-
const raw = value.resolutions && typeof value.resolutions === 'object' && !Array.isArray(value.resolutions)
|
|
361
|
-
? value.resolutions
|
|
362
|
-
: {};
|
|
363
|
-
let n = 0;
|
|
364
|
-
for (const id of Object.keys(raw)) {
|
|
365
|
-
if (n >= 200) break;
|
|
366
|
-
const r = raw[id];
|
|
367
|
-
if (!r || typeof r !== 'object' || Array.isArray(r)) continue;
|
|
368
|
-
const choice = limitString(r.choice, 30);
|
|
369
|
-
if (!['ours', 'theirs', 'both', 'custom'].includes(choice)) continue;
|
|
370
|
-
out.resolutions[limitString(id, 80)] = {
|
|
371
|
-
choice,
|
|
372
|
-
value: limitString(r.value, 128 * 1024),
|
|
373
|
-
};
|
|
374
|
-
n++;
|
|
375
|
-
}
|
|
376
|
-
return Object.keys(out.resolutions).length ? out : null;
|
|
377
|
-
}
|
|
378
|
-
|
|
379
|
-
function sanitizeDiffReview(value) {
|
|
380
|
-
if (!value || typeof value !== 'object' || Array.isArray(value)) return null;
|
|
381
|
-
if (value.type !== 'diff-review') return null;
|
|
382
|
-
const out = {
|
|
383
|
-
type: 'diff-review',
|
|
384
|
-
reviewKind: limitString(value.reviewKind, 80),
|
|
385
|
-
commit: limitString(value.commit, 120),
|
|
386
|
-
title: limitString(value.title, 500),
|
|
387
|
-
resolved: value.resolved === true,
|
|
388
|
-
hunks: {},
|
|
389
|
-
};
|
|
390
|
-
const raw = value.hunks && typeof value.hunks === 'object' && !Array.isArray(value.hunks)
|
|
391
|
-
? value.hunks
|
|
392
|
-
: {};
|
|
393
|
-
let n = 0;
|
|
394
|
-
for (const id of Object.keys(raw)) {
|
|
395
|
-
if (n >= 500) break;
|
|
396
|
-
const h = raw[id];
|
|
397
|
-
if (!h || typeof h !== 'object' || Array.isArray(h)) continue;
|
|
398
|
-
const choice = limitString(h.choice, 30);
|
|
399
|
-
if (!['apply', 'skip', 'hold'].includes(choice)) continue;
|
|
400
|
-
out.hunks[limitString(id, 80)] = {
|
|
401
|
-
choice,
|
|
402
|
-
file: limitString(h.file, 1200),
|
|
403
|
-
header: limitString(h.header, 500),
|
|
404
|
-
};
|
|
405
|
-
n++;
|
|
406
|
-
}
|
|
407
|
-
return Object.keys(out.hunks).length ? out : null;
|
|
408
|
-
}
|
|
409
|
-
|
|
410
|
-
// An a2ui block's state: the widget's data model (inputs the user changed) and
|
|
411
|
-
// the button events they fired, in order. Bounded like every other edit.
|
|
412
|
-
const A2UI_STATE_MAX_BYTES = 64 * 1024;
|
|
413
|
-
const A2UI_EVENTS_MAX = 50;
|
|
414
|
-
function sanitizeA2uiState(value) {
|
|
415
|
-
if (!value || typeof value !== 'object' || Array.isArray(value) || value.type !== 'a2ui') return null;
|
|
416
|
-
try {
|
|
417
|
-
assertSafeJson(value.data ?? {}, 'a2ui state');
|
|
418
|
-
const events = (Array.isArray(value.events) ? value.events : []).slice(-A2UI_EVENTS_MAX).flatMap((e) => {
|
|
419
|
-
if (!e || typeof e !== 'object' || typeof e.name !== 'string' || !/^[a-z][a-z0-9_-]{0,39}$/.test(e.name)) return [];
|
|
420
|
-
const context = e.context && typeof e.context === 'object' && !Array.isArray(e.context) ? e.context : {};
|
|
421
|
-
assertSafeJson(context, 'a2ui event');
|
|
422
|
-
if (JSON.stringify(context).length > 4096) return [];
|
|
423
|
-
return [{ name: e.name, context, at: limitString(e.at, 40) }];
|
|
424
|
-
});
|
|
425
|
-
const data = value.data && typeof value.data === 'object' && !Array.isArray(value.data) ? value.data : {};
|
|
426
|
-
if (JSON.stringify(data).length > A2UI_STATE_MAX_BYTES) return null;
|
|
427
|
-
return { type: 'a2ui', data, events };
|
|
428
|
-
} catch {
|
|
429
|
-
return null;
|
|
430
|
-
}
|
|
431
|
-
}
|
|
432
|
-
|
|
433
|
-
// Validates + sanitizes an incoming blockEdits map (from draft/submit).
|
|
434
|
-
// String values are editable Mermaid source. Structured git-conflict-resolution
|
|
435
|
-
// and diff-review values carry bounded per-hunk choices. Caps prevent a draft
|
|
436
|
-
// from bloating board storage; invalid entries are dropped.
|
|
437
|
-
function sanitizeBlockEdits(value) {
|
|
438
|
-
if (value === null || typeof value !== 'object' || Array.isArray(value)) return {};
|
|
439
|
-
const out = {};
|
|
440
|
-
let n = 0;
|
|
441
|
-
for (const key of Object.keys(value)) {
|
|
442
|
-
if (n >= 50) break;
|
|
443
|
-
if (typeof key !== 'string') continue;
|
|
444
|
-
const v = value[key];
|
|
445
|
-
if (typeof v === 'string') {
|
|
446
|
-
if (v.length > 20000) continue;
|
|
447
|
-
out[key] = v;
|
|
448
|
-
} else {
|
|
449
|
-
const edit = sanitizeConflictResolution(v) || sanitizeDiffReview(v) || sanitizeA2uiState(v);
|
|
450
|
-
if (!edit) continue;
|
|
451
|
-
out[key] = edit;
|
|
452
|
-
}
|
|
453
|
-
n++;
|
|
454
|
-
}
|
|
455
|
-
return out;
|
|
456
|
-
}
|
|
457
|
-
|
|
458
|
-
// Resolves a block by id + type from the board, any question, or any option.
|
|
459
|
-
function findBlock(spec, blockId, type) {
|
|
460
|
-
const scan = (blocks) => (Array.isArray(blocks) ? blocks.find((b) => b && b.id === blockId && b.type === type) : undefined);
|
|
461
|
-
const board = scan(spec.blocks);
|
|
462
|
-
if (board) return board;
|
|
463
|
-
for (const q of spec.questions) {
|
|
464
|
-
const hit = scan(q.blocks);
|
|
465
|
-
if (hit) return hit;
|
|
466
|
-
for (const o of Array.isArray(q.options) ? q.options : []) {
|
|
467
|
-
const opt = o && scan(o.blocks);
|
|
468
|
-
if (opt) return opt;
|
|
469
|
-
}
|
|
470
|
-
}
|
|
471
|
-
return undefined;
|
|
472
|
-
}
|
|
473
|
-
|
|
474
|
-
function findHtmlBlock(spec, blockId) {
|
|
475
|
-
return findBlock(spec, blockId, 'html');
|
|
476
|
-
}
|
|
477
|
-
|
|
478
|
-
// The board's first html block (legacy /html/board alias).
|
|
479
|
-
function firstBoardHtml(spec) {
|
|
480
|
-
return (spec.blocks || []).find((b) => b && b.type === 'html');
|
|
481
|
-
}
|
|
482
|
-
|
|
483
|
-
// A question's first html block (legacy /html/q/<id> alias).
|
|
484
|
-
function firstQuestionHtml(q) {
|
|
485
|
-
return (q.blocks || []).find((b) => b && b.type === 'html');
|
|
486
|
-
}
|
|
487
|
-
|
|
488
|
-
// ---------- local-file links (POST /api/open) ----------
|
|
489
|
-
// The markdown renderer turns file paths an agent writes (~/x, ./x, /abs/x,
|
|
490
|
-
// file://…) into click-to-open links. Clicking POSTs the raw path here; the
|
|
491
|
-
// server resolves it against the board's authoring cwd and opens it in the OS
|
|
492
|
-
// default app — BUT only if the path is one the board actually references
|
|
493
|
-
// (allowlist below). That keeps a cross-site/blind POST from opening arbitrary
|
|
494
|
-
// files: the only openable paths are ones the agent already put on the board.
|
|
495
|
-
//
|
|
496
|
-
// FILE_PATH_RE / looksLikeLocalPath MUST stay in sync with the same logic in
|
|
497
|
-
// ui/blocks.js, so the set the server allows matches the set the page links.
|
|
498
|
-
const FILE_PATH_RE =
|
|
499
|
-
/(?<![\w@:./])(?:file:\/\/\/?[^\s)<>"'`*]+|~\/[^\s)<>"'`*]+|\.{1,2}\/[^\s)<>"'`*]+|\/[^\s)<>"'`*]+|[A-Za-z]:[\\/][^\s)<>"'`*]+)/g;
|
|
500
|
-
|
|
501
|
-
function looksLikeLocalPath(s) {
|
|
502
|
-
if (typeof s !== 'string') return false;
|
|
503
|
-
const t = s.trim();
|
|
504
|
-
if (!t || /\s/.test(t)) return false;
|
|
505
|
-
if (/^file:\/\//i.test(t)) return true;
|
|
506
|
-
if (/^[A-Za-z]:[\\/]/.test(t)) return true; // windows drive
|
|
507
|
-
if (t === '~' || /^~\//.test(t)) return true;
|
|
508
|
-
if (/^\.\.?\//.test(t)) return true; // ./ or ../
|
|
509
|
-
if (t.startsWith('/')) {
|
|
510
|
-
// a lone "/" or a one-segment "/word" is more likely punctuation/URL — only
|
|
511
|
-
// treat as a file when it has ≥2 segments or a file extension.
|
|
512
|
-
return /\/[^/]+\/[^/]/.test(t) || /\.[A-Za-z0-9]{1,8}$/.test(t);
|
|
513
|
-
}
|
|
514
|
-
return false;
|
|
515
|
-
}
|
|
516
|
-
|
|
517
|
-
// Expands ~ / file:// and resolves a (possibly relative) path to an absolute,
|
|
518
|
-
// normalized one against the board's authoring cwd. null on a malformed URL.
|
|
519
|
-
function resolveLocalPath(raw, baseCwd) {
|
|
520
|
-
let p = splitFileReference(raw).path;
|
|
521
|
-
if (!p) return null;
|
|
522
|
-
if (/^file:\/\//i.test(p)) {
|
|
523
|
-
try {
|
|
524
|
-
p = fileURLToPath(p);
|
|
525
|
-
} catch {
|
|
526
|
-
return null;
|
|
527
|
-
}
|
|
528
|
-
} else if (p === '~' || p.startsWith('~/')) {
|
|
529
|
-
p = path.join(os.homedir(), p.slice(1));
|
|
530
|
-
}
|
|
531
|
-
if (!path.isAbsolute(p)) p = path.resolve(baseCwd || process.cwd(), p);
|
|
532
|
-
return path.normalize(p);
|
|
533
|
-
}
|
|
534
|
-
|
|
535
|
-
// Every markdown source the page runs through its inline renderer (intro + any
|
|
536
|
-
// markdown block, board / question / option scoped). These are the only places
|
|
537
|
-
// file paths become clickable, so they define the open allowlist.
|
|
538
|
-
function collectMarkdownSources(spec) {
|
|
539
|
-
const out = [];
|
|
540
|
-
if (typeof spec.intro === 'string') out.push(spec.intro);
|
|
541
|
-
const addBlocks = (blocks) => {
|
|
542
|
-
for (const b of Array.isArray(blocks) ? blocks : []) {
|
|
543
|
-
if (b && b.type === 'markdown' && typeof b.md === 'string') out.push(b.md);
|
|
544
|
-
}
|
|
545
|
-
};
|
|
546
|
-
addBlocks(spec.blocks);
|
|
547
|
-
for (const q of spec.questions || []) {
|
|
548
|
-
addBlocks(q.blocks);
|
|
549
|
-
for (const o of Array.isArray(q.options) ? q.options : []) {
|
|
550
|
-
if (o) addBlocks(o.blocks);
|
|
551
|
-
}
|
|
552
|
-
}
|
|
553
|
-
return out;
|
|
554
|
-
}
|
|
555
|
-
|
|
556
|
-
// The set of absolute paths the board references and is therefore allowed to
|
|
557
|
-
// open. Rebuilt per request (specs are small) so it tracks live `rly update`s.
|
|
558
|
-
function buildOpenAllowlist(spec, baseCwd) {
|
|
559
|
-
const set = new Set();
|
|
560
|
-
const text = collectMarkdownSources(spec).join('\n');
|
|
561
|
-
const re = new RegExp(FILE_PATH_RE.source, 'g');
|
|
562
|
-
let m;
|
|
563
|
-
while ((m = re.exec(text))) {
|
|
564
|
-
if (!looksLikeLocalPath(m[0])) continue;
|
|
565
|
-
const abs = resolveLocalPath(m[0], baseCwd);
|
|
566
|
-
if (abs) set.add(abs);
|
|
567
|
-
}
|
|
568
|
-
return set;
|
|
569
|
-
}
|
|
570
|
-
|
|
571
|
-
const PROXY_HEADERS = ['forwarded', 'x-forwarded-for', 'x-forwarded-host', 'x-forwarded-proto', 'x-real-ip'];
|
|
572
|
-
|
|
573
|
-
// Security: a local reverse proxy can send a loopback Host (the devlink gateway
|
|
574
|
-
// sends `Host: localhost:PORT`), so a request carrying proxy headers is never the
|
|
575
|
-
// tokenless owner. A proxy that adds none is covered by the control token runBoard
|
|
576
|
-
// requires for the owner while a link is set.
|
|
577
|
-
function isDirectLocalRequest(req) {
|
|
578
|
-
const host = String(req.headers.host || '').split(':')[0];
|
|
579
|
-
if (host !== '127.0.0.1' && host !== 'localhost') return false;
|
|
580
|
-
return !PROXY_HEADERS.some((name) => req.headers[name] !== undefined);
|
|
581
|
-
}
|
|
582
|
-
|
|
583
|
-
// True when an Origin header (if present) belongs to this board's own server.
|
|
584
|
-
// Same-origin fetches send no Origin or our own; a foreign Origin is a
|
|
585
|
-
// cross-site POST and must not be allowed to open a local file.
|
|
586
|
-
function sameOrigin(req, port, extraHosts = [], extraOrigins = []) {
|
|
587
|
-
if (req.headers['sec-fetch-site'] === 'cross-site') return false;
|
|
588
|
-
const origin = req.headers.origin;
|
|
589
|
-
if (!origin) return true;
|
|
590
|
-
try {
|
|
591
|
-
const u = new URL(origin);
|
|
592
|
-
if (extraOrigins.includes(u.origin)) return true;
|
|
593
|
-
if (u.port !== String(port)) return false;
|
|
594
|
-
return new Set(['127.0.0.1', 'localhost', ...extraHosts.filter(Boolean)]).has(u.hostname);
|
|
595
|
-
} catch {
|
|
596
|
-
return false;
|
|
597
|
-
}
|
|
598
|
-
}
|
|
599
|
-
|
|
600
|
-
function sendJson(res, code, obj) {
|
|
601
|
-
if (res.headersSent) return;
|
|
602
|
-
res.writeHead(code, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' });
|
|
603
|
-
res.end(JSON.stringify(obj));
|
|
604
|
-
}
|
|
605
|
-
|
|
606
|
-
function sendHtml(res, body, headers = {}) {
|
|
607
|
-
res.writeHead(200, { 'content-type': 'text/html; charset=utf-8', 'cache-control': 'no-store', ...headers });
|
|
608
|
-
res.end(body);
|
|
609
|
-
}
|
|
610
|
-
|
|
611
|
-
function sendJs(res, body) {
|
|
612
|
-
res.writeHead(200, { 'content-type': 'application/javascript; charset=utf-8', 'cache-control': 'no-store' });
|
|
613
|
-
res.end(body);
|
|
614
|
-
}
|
|
615
|
-
|
|
616
|
-
// Serves a file from a fixed directory, rejecting any path that escapes it
|
|
617
|
-
// (no traversal). Returns false (404 not written) when the file is missing.
|
|
618
|
-
function sendFromDir(res, dir, name, contentType) {
|
|
619
|
-
const target = path.resolve(dir, name);
|
|
620
|
-
if (target !== dir && !target.startsWith(dir + path.sep)) return false;
|
|
621
|
-
let body;
|
|
622
|
-
try {
|
|
623
|
-
body = fs.readFileSync(target);
|
|
624
|
-
} catch {
|
|
625
|
-
return false;
|
|
626
|
-
}
|
|
627
|
-
res.writeHead(200, { 'content-type': contentType, 'cache-control': 'no-store' });
|
|
628
|
-
res.end(body);
|
|
629
|
-
return true;
|
|
630
|
-
}
|
|
631
|
-
|
|
632
|
-
// Streams a file with HTTP Range support so a <video>/<audio> element can seek
|
|
633
|
-
// and the browser can request byte ranges instead of the whole clip. Honors a
|
|
634
|
-
// single "bytes=start-end" range; falls back to the full body otherwise. Safe
|
|
635
|
-
// for a HEAD probe (sends headers, no body).
|
|
636
|
-
function streamFile(req, res, filePath, contentType) {
|
|
637
|
-
let stat;
|
|
638
|
-
try {
|
|
639
|
-
stat = fs.statSync(filePath);
|
|
640
|
-
} catch {
|
|
641
|
-
return sendJson(res, 404, { error: 'file not found' });
|
|
642
|
-
}
|
|
643
|
-
const total = stat.size;
|
|
644
|
-
const range = req.headers.range;
|
|
645
|
-
const baseHeaders = {
|
|
646
|
-
'content-type': contentType,
|
|
647
|
-
'accept-ranges': 'bytes',
|
|
648
|
-
'cache-control': 'no-store',
|
|
649
|
-
};
|
|
650
|
-
let start = 0;
|
|
651
|
-
let end = total - 1;
|
|
652
|
-
let status = 200;
|
|
653
|
-
if (range) {
|
|
654
|
-
const m = /^bytes=(\d*)-(\d*)$/.exec(range.trim());
|
|
655
|
-
if (m) {
|
|
656
|
-
if (m[1] === '' && m[2] === '') {
|
|
657
|
-
// "bytes=-" — unsatisfiable
|
|
658
|
-
} else if (m[1] === '') {
|
|
659
|
-
start = Math.max(0, total - Number(m[2])); // suffix range
|
|
660
|
-
} else {
|
|
661
|
-
start = Number(m[1]);
|
|
662
|
-
if (m[2] !== '') end = Math.min(end, Number(m[2]));
|
|
663
|
-
}
|
|
664
|
-
}
|
|
665
|
-
if (start > end || start >= total) {
|
|
666
|
-
res.writeHead(416, { 'content-range': `bytes */${total}`, 'cache-control': 'no-store' });
|
|
667
|
-
return res.end();
|
|
668
|
-
}
|
|
669
|
-
status = 206;
|
|
670
|
-
baseHeaders['content-range'] = `bytes ${start}-${end}/${total}`;
|
|
671
|
-
}
|
|
672
|
-
baseHeaders['content-length'] = String(end - start + 1);
|
|
673
|
-
res.writeHead(status, baseHeaders);
|
|
674
|
-
if (req.method === 'HEAD') return res.end();
|
|
675
|
-
const stream = fs.createReadStream(filePath, { start, end });
|
|
676
|
-
stream.on('error', () => {
|
|
677
|
-
if (!res.headersSent) sendJson(res, 500, { error: 'stream error' });
|
|
678
|
-
else res.destroy();
|
|
679
|
-
});
|
|
680
|
-
stream.pipe(res);
|
|
681
|
-
}
|
|
682
|
-
|
|
683
|
-
// Loaded into every custom-HTML iframe so users can hover any element to leave a
|
|
684
|
-
// comment (relayKit.annotate.auto). Idempotent with an author-added /kit.js, and
|
|
685
|
-
// a no-op when the author opts out via data-relay-annotate="off".
|
|
686
|
-
const ANNOTATE_BOOTSTRAP =
|
|
687
|
-
'<script>(function(){function go(){try{window.relayKit&&window.relayKit.annotate&&window.relayKit.annotate.auto();}catch(e){}}' +
|
|
688
|
-
'if(window.relayKit&&window.relayKit.annotate)return go();' +
|
|
689
|
-
"var s=document.createElement('script');s.src='/kit.js';s.onload=go;s.onerror=go;" +
|
|
690
|
-
'(document.head||document.documentElement).appendChild(s);})();<\/script>';
|
|
691
|
-
|
|
692
|
-
// Insert a snippet right before </body> (else </html>, else append).
|
|
693
|
-
function injectBeforeBodyEnd(html, snippet) {
|
|
694
|
-
const lower = html.toLowerCase();
|
|
695
|
-
let idx = lower.lastIndexOf('</body>');
|
|
696
|
-
if (idx === -1) idx = lower.lastIndexOf('</html>');
|
|
697
|
-
if (idx === -1) return html + snippet;
|
|
698
|
-
return html.slice(0, idx) + snippet + html.slice(idx);
|
|
699
|
-
}
|
|
700
|
-
|
|
701
|
-
// Custom-HTML fragments (no <html> tag) get wrapped in a minimal document that
|
|
702
|
-
// matches the user's theme, so e.g. "<b>hi</b>" doesn't paint a stark white
|
|
703
|
-
// block in dark mode. Full documents are served verbatim — their authors can
|
|
704
|
-
// read the ?theme=light|dark query param themselves. The annotate bootstrap is
|
|
705
|
-
// omitted for read-only shares so their iframe content has no false comment
|
|
706
|
-
// affordances; existing feedback remains visible in the parent comments rail.
|
|
707
|
-
function wrapFragment(content, theme, annotate = true) {
|
|
708
|
-
if (/<html[\s>]/i.test(content)) return annotate ? injectBeforeBodyEnd(content, ANNOTATE_BOOTSTRAP) : content;
|
|
709
|
-
const dark = theme === 'dark';
|
|
710
|
-
const bg = dark ? '#282624' : '#ffffff';
|
|
711
|
-
const fg = dark ? '#edeae4' : '#1c1b19';
|
|
712
|
-
return `<!doctype html><html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><style>:root{color-scheme:${dark ? 'dark' : 'light'}}body{margin:12px;font:14px/1.5 -apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,"Helvetica Neue",Arial,sans-serif;background:${bg};color:${fg}}</style></head><body>${content}${annotate ? ANNOTATE_BOOTSTRAP : ''}</body></html>`;
|
|
713
|
-
}
|
|
714
|
-
|
|
715
|
-
function readBody(req, limit = 5 * 1024 * 1024) {
|
|
716
|
-
return new Promise((resolve, reject) => {
|
|
717
|
-
let size = 0;
|
|
718
|
-
const chunks = [];
|
|
719
|
-
req.on('data', (c) => {
|
|
720
|
-
size += c.length;
|
|
721
|
-
if (size > limit) {
|
|
722
|
-
reject(new Error('payload too large'));
|
|
723
|
-
req.destroy();
|
|
724
|
-
} else {
|
|
725
|
-
chunks.push(c);
|
|
726
|
-
}
|
|
727
|
-
});
|
|
728
|
-
req.on('end', () => resolve(Buffer.concat(chunks).toString('utf8')));
|
|
729
|
-
req.on('error', reject);
|
|
730
|
-
});
|
|
731
|
-
}
|
|
732
|
-
|
|
733
|
-
function artifactBytesMatch(mime, bytes) {
|
|
734
|
-
if (!Buffer.isBuffer(bytes) || bytes.length < 4) return false;
|
|
735
|
-
if (mime === 'image/png') return bytes.subarray(0, 8).equals(Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]));
|
|
736
|
-
if (mime === 'image/jpeg') return bytes[0] === 0xff && bytes[1] === 0xd8 && bytes[bytes.length - 2] === 0xff && bytes[bytes.length - 1] === 0xd9;
|
|
737
|
-
if (mime === 'image/webp') return bytes.subarray(0, 4).toString('ascii') === 'RIFF' && bytes.subarray(8, 12).toString('ascii') === 'WEBP';
|
|
738
|
-
return false;
|
|
739
|
-
}
|
|
740
|
-
|
|
741
|
-
// Push-wake: run the agent's own local shell command after a board finishes.
|
|
742
|
-
// The full result JSON is written to the command's stdin; RLY_BOARD_ID /
|
|
743
|
-
// RLY_STATUS / RLY_URL are exported. Failures are swallowed (best effort) —
|
|
744
|
-
// only a stderr note when not quiet. A 30s kill timer prevents a hung command
|
|
745
|
-
// from keeping the process alive.
|
|
746
|
-
function runOnResult(cmd, result, { quiet = false } = {}) {
|
|
747
|
-
if (typeof cmd !== 'string' || !cmd.trim()) return;
|
|
748
|
-
try {
|
|
749
|
-
const child = spawn('/bin/sh', ['-c', cmd], {
|
|
750
|
-
env: {
|
|
751
|
-
...process.env,
|
|
752
|
-
RLY_BOARD_ID: result.boardId || '',
|
|
753
|
-
RLY_STATUS: result.status || '',
|
|
754
|
-
RLY_URL: result.url || '',
|
|
755
|
-
},
|
|
756
|
-
stdio: ['pipe', 'ignore', 'ignore'],
|
|
757
|
-
});
|
|
758
|
-
child.on('error', () => {
|
|
759
|
-
if (!quiet) process.stderr.write(`[relay] --on-result command failed to spawn\n`);
|
|
760
|
-
});
|
|
761
|
-
try {
|
|
762
|
-
child.stdin.write(JSON.stringify(result));
|
|
763
|
-
child.stdin.end();
|
|
764
|
-
} catch {
|
|
765
|
-
// best effort — stdin may already be gone
|
|
766
|
-
}
|
|
767
|
-
const killTimer = setTimeout(() => {
|
|
768
|
-
try {
|
|
769
|
-
child.kill('SIGKILL');
|
|
770
|
-
} catch {
|
|
771
|
-
// already gone
|
|
772
|
-
}
|
|
773
|
-
}, 30000);
|
|
774
|
-
killTimer.unref();
|
|
775
|
-
child.on('close', () => clearTimeout(killTimer));
|
|
776
|
-
child.unref();
|
|
777
|
-
} catch {
|
|
778
|
-
if (!quiet) process.stderr.write(`[relay] --on-result command failed to run\n`);
|
|
779
|
-
}
|
|
780
|
-
}
|
|
6
|
+
import { filePreview, mediaType, splitFileReference } from '../file-preview.js';
|
|
7
|
+
import { resolveLink } from '../link.js';
|
|
8
|
+
import { openUrl } from '../open.js';
|
|
9
|
+
import { assertSpecReady } from '../spec/index.js';
|
|
10
|
+
import { loadBoard, removeRunning, saveBoard, saveBoardArtifact, savePref, saveRunning } from '../store.js';
|
|
11
|
+
import { SHARE_STATE_VERSION, pruneReviewDrafts, reviewSessionCookie, reviewSessionId, sideReviewState } from './reviews.js';
|
|
12
|
+
import { buildLockedPage, buildPage, shareHost } from './page.js';
|
|
13
|
+
import { isDirectLocalRequest, readBody, sameOrigin, sendFromDir, sendHtml, sendJs, sendJson, wrapFragment } from './http.js';
|
|
14
|
+
import { UI_DIR, VENDOR_DIR } from './paths.js';
|
|
15
|
+
import { findBlock, findHtmlBlock, firstBoardHtml, firstQuestionHtml, sanitizeAnnotations, sanitizeBlockEdits } from './sanitize.js';
|
|
16
|
+
import { ARTIFACT_MAX_BYTES, ARTIFACT_MIMES, artifactBytesMatch, runOnResult } from './result.js';
|
|
17
|
+
import { buildOpenAllowlist, resolveLocalPath, streamFile } from './files.js';
|
|
781
18
|
|
|
782
19
|
// Serves one board on 127.0.0.1 and resolves `done` when it finishes
|
|
783
20
|
// (submitted / acknowledged / timeout / cancelled). The result is also
|
|
@@ -850,7 +87,7 @@ export async function runBoard({ id, port = 0, open = true, timeoutSec = 86400,
|
|
|
850
87
|
const presenceByRole = { owner: null, collab: null, review: null, read: null };
|
|
851
88
|
let actualPort = 0;
|
|
852
89
|
let url = '';
|
|
853
|
-
// The cross-device origin from a link setting (
|
|
90
|
+
// The cross-device origin from a link setting (a link provider or a URL template), once resolved.
|
|
854
91
|
let publicLink = null;
|
|
855
92
|
const advertisedHost = shareHost();
|
|
856
93
|
const accessFor = (req, reqUrl = null) => {
|