@khanglvm/relay 0.19.0 → 0.20.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (131) hide show
  1. package/bin/rly.js +1 -1
  2. package/package.json +4 -4
  3. package/src/cli/args.js +46 -0
  4. package/src/cli/ask.js +12 -0
  5. package/src/cli/boards.js +326 -0
  6. package/src/cli/config.js +56 -0
  7. package/src/cli/context.js +13 -0
  8. package/src/cli/git.js +183 -0
  9. package/src/cli/help.js +90 -0
  10. package/src/cli/index.js +103 -0
  11. package/src/cli/install.js +197 -0
  12. package/src/cli/io.js +186 -0
  13. package/src/cli/mcp.js +94 -0
  14. package/src/cli/share.js +45 -0
  15. package/src/cli/skill.js +192 -0
  16. package/src/cli/upgrade.js +130 -0
  17. package/src/cli/wait.js +172 -0
  18. package/src/file-preview.js +1 -1
  19. package/src/index.js +1 -1
  20. package/src/mcp-ui/board/block-ctx.js +43 -0
  21. package/src/mcp-ui/board/bridge.js +165 -0
  22. package/src/mcp-ui/board/controls.js +310 -0
  23. package/src/mcp-ui/board/core.js +20 -0
  24. package/src/mcp-ui/board/lifecycle.js +118 -0
  25. package/src/mcp-ui/board/normalize.js +95 -0
  26. package/src/mcp-ui/board/render.js +200 -0
  27. package/src/mcp-ui/board/state.js +106 -0
  28. package/src/mcp-ui/board/vendors.js +86 -0
  29. package/src/mcp.js +12 -18
  30. package/src/{server.js → server/board.js} +15 -778
  31. package/src/server/files.js +141 -0
  32. package/src/server/http.js +114 -0
  33. package/src/server/index.js +2 -0
  34. package/src/server/page.js +183 -0
  35. package/src/server/paths.js +7 -0
  36. package/src/server/result.js +58 -0
  37. package/src/server/reviews.js +41 -0
  38. package/src/server/sanitize.js +231 -0
  39. package/src/spec/blocks/a2ui.js +25 -0
  40. package/src/spec/blocks/chart.js +49 -0
  41. package/src/spec/blocks/code.js +38 -0
  42. package/src/spec/blocks/diagram.js +39 -0
  43. package/src/spec/blocks/git-conflict.js +106 -0
  44. package/src/spec/blocks/image.js +32 -0
  45. package/src/spec/blocks/index.js +33 -0
  46. package/src/spec/blocks/markdown.js +13 -0
  47. package/src/spec/blocks/pdf.js +38 -0
  48. package/src/spec/blocks/table.js +122 -0
  49. package/src/spec/blocks/video.js +68 -0
  50. package/src/spec/blocks/widgets.js +98 -0
  51. package/src/spec/constants.js +65 -0
  52. package/src/spec/index.js +5 -0
  53. package/src/spec/normalize.js +285 -0
  54. package/src/spec/ready.js +106 -0
  55. package/src/spec/schema.js +182 -0
  56. package/src/spec/sources.js +83 -0
  57. package/src/ui/annotate/api.js +149 -0
  58. package/src/ui/annotate/badges.js +77 -0
  59. package/src/ui/annotate/chrome.js +158 -0
  60. package/src/ui/annotate/core.js +134 -0
  61. package/src/ui/annotate/highlights.js +129 -0
  62. package/src/ui/annotate/mutations.js +127 -0
  63. package/src/ui/annotate/popover.js +206 -0
  64. package/src/ui/annotate/summary.js +67 -0
  65. package/src/ui/app/annotations.js +88 -0
  66. package/src/ui/app/autosave.js +44 -0
  67. package/src/ui/app/core.js +74 -0
  68. package/src/ui/app/drafts.js +201 -0
  69. package/src/ui/app/heartbeat.js +150 -0
  70. package/src/ui/app/iframe-bridge.js +64 -0
  71. package/src/ui/app/persistence.js +117 -0
  72. package/src/ui/app/prefilled.js +21 -0
  73. package/src/ui/app/presence.js +38 -0
  74. package/src/ui/app/question-color.js +67 -0
  75. package/src/ui/app/questions.js +360 -0
  76. package/src/ui/app/render.js +135 -0
  77. package/src/ui/app/share.js +108 -0
  78. package/src/ui/app/submit.js +109 -0
  79. package/src/ui/app/theme.js +63 -0
  80. package/src/ui/blocks/api.js +1 -0
  81. package/src/ui/blocks/chart.js +222 -0
  82. package/src/ui/blocks/code.js +138 -0
  83. package/src/ui/blocks/compare.js +82 -0
  84. package/src/ui/blocks/core.js +74 -0
  85. package/src/ui/blocks/diff.js +361 -0
  86. package/src/ui/blocks/dispatch.js +111 -0
  87. package/src/ui/blocks/file-links.js +180 -0
  88. package/src/ui/blocks/git-conflict.js +151 -0
  89. package/src/ui/blocks/graphviz.js +57 -0
  90. package/src/ui/blocks/html.js +45 -0
  91. package/src/ui/blocks/image.js +371 -0
  92. package/src/ui/blocks/kpi.js +26 -0
  93. package/src/ui/blocks/markdown.js +223 -0
  94. package/src/ui/blocks/mermaid.js +242 -0
  95. package/src/ui/blocks/palette.js +59 -0
  96. package/src/ui/blocks/pdf.js +21 -0
  97. package/src/ui/blocks/plantuml.js +152 -0
  98. package/src/ui/blocks/table.js +155 -0
  99. package/src/ui/blocks/typography.js +25 -0
  100. package/src/ui/blocks/vendor.js +43 -0
  101. package/src/ui/blocks/video.js +43 -0
  102. package/src/ui/blocks/viewer-fullscreen.js +146 -0
  103. package/src/ui/blocks/viewer.js +324 -0
  104. package/src/ui/kit.js +1 -0
  105. package/src/ui/manifest.js +140 -0
  106. package/types/index.d.ts +1 -1
  107. package/types/spec/blocks/a2ui.d.ts +4 -0
  108. package/types/spec/blocks/chart.d.ts +4 -0
  109. package/types/spec/blocks/code.d.ts +10 -0
  110. package/types/spec/blocks/diagram.d.ts +15 -0
  111. package/types/spec/blocks/git-conflict.d.ts +7 -0
  112. package/types/spec/blocks/image.d.ts +5 -0
  113. package/types/spec/blocks/index.d.ts +30 -0
  114. package/types/spec/blocks/markdown.d.ts +5 -0
  115. package/types/spec/blocks/pdf.d.ts +4 -0
  116. package/types/spec/blocks/table.d.ts +9 -0
  117. package/types/spec/blocks/video.d.ts +4 -0
  118. package/types/spec/blocks/widgets.d.ts +21 -0
  119. package/types/spec/constants.d.ts +67 -0
  120. package/types/spec/index.d.ts +4 -0
  121. package/types/spec/normalize.d.ts +17 -0
  122. package/types/spec/ready.d.ts +1 -0
  123. package/types/{spec.d.ts → spec/schema.d.ts} +0 -20
  124. package/types/spec/sources.d.ts +14 -0
  125. package/types/ui/manifest.d.ts +62 -0
  126. package/src/cli.js +0 -1767
  127. package/src/mcp-ui/board.js +0 -1162
  128. package/src/spec.js +0 -1224
  129. package/src/ui/annotate.js +0 -1055
  130. package/src/ui/app.js +0 -1643
  131. package/src/ui/blocks.js +0 -3260
@@ -0,0 +1,141 @@
1
+ // Local files a board may open or stream: path detection, allowlist and range streaming.
2
+ import fs from 'node:fs';
3
+ import os from 'node:os';
4
+ import path from 'node:path';
5
+ import { fileURLToPath } from 'node:url';
6
+ import { splitFileReference } from '../file-preview.js';
7
+ import { sendJson } from './http.js';
8
+
9
+ // ---------- local-file links (POST /api/open) ----------
10
+ // The markdown renderer turns file paths an agent writes (~/x, ./x, /abs/x,
11
+ // file://…) into click-to-open links. Clicking POSTs the raw path here; the
12
+ // server resolves it against the board's authoring cwd and opens it in the OS
13
+ // default app — BUT only if the path is one the board actually references
14
+ // (allowlist below). That keeps a cross-site/blind POST from opening arbitrary
15
+ // files: the only openable paths are ones the agent already put on the board.
16
+ //
17
+ // FILE_PATH_RE / looksLikeLocalPath MUST stay in sync with the same logic in
18
+ // ui/blocks.js, so the set the server allows matches the set the page links.
19
+ const FILE_PATH_RE =
20
+ /(?<![\w@:./])(?:file:\/\/\/?[^\s)<>"'`*]+|~\/[^\s)<>"'`*]+|\.{1,2}\/[^\s)<>"'`*]+|\/[^\s)<>"'`*]+|[A-Za-z]:[\\/][^\s)<>"'`*]+)/g;
21
+
22
+ function looksLikeLocalPath(s) {
23
+ if (typeof s !== 'string') return false;
24
+ const t = s.trim();
25
+ if (!t || /\s/.test(t)) return false;
26
+ if (/^file:\/\//i.test(t)) return true;
27
+ if (/^[A-Za-z]:[\\/]/.test(t)) return true; // windows drive
28
+ if (t === '~' || /^~\//.test(t)) return true;
29
+ if (/^\.\.?\//.test(t)) return true; // ./ or ../
30
+ if (t.startsWith('/')) {
31
+ // a lone "/" or a one-segment "/word" is more likely punctuation/URL — only
32
+ // treat as a file when it has ≥2 segments or a file extension.
33
+ return /\/[^/]+\/[^/]/.test(t) || /\.[A-Za-z0-9]{1,8}$/.test(t);
34
+ }
35
+ return false;
36
+ }
37
+
38
+ // Expands ~ / file:// and resolves a (possibly relative) path to an absolute,
39
+ // normalized one against the board's authoring cwd. null on a malformed URL.
40
+ export function resolveLocalPath(raw, baseCwd) {
41
+ let p = splitFileReference(raw).path;
42
+ if (!p) return null;
43
+ if (/^file:\/\//i.test(p)) {
44
+ try {
45
+ p = fileURLToPath(p);
46
+ } catch {
47
+ return null;
48
+ }
49
+ } else if (p === '~' || p.startsWith('~/')) {
50
+ p = path.join(os.homedir(), p.slice(1));
51
+ }
52
+ if (!path.isAbsolute(p)) p = path.resolve(baseCwd || process.cwd(), p);
53
+ return path.normalize(p);
54
+ }
55
+
56
+ // Every markdown source the page runs through its inline renderer (intro + any
57
+ // markdown block, board / question / option scoped). These are the only places
58
+ // file paths become clickable, so they define the open allowlist.
59
+ function collectMarkdownSources(spec) {
60
+ const out = [];
61
+ if (typeof spec.intro === 'string') out.push(spec.intro);
62
+ const addBlocks = (blocks) => {
63
+ for (const b of Array.isArray(blocks) ? blocks : []) {
64
+ if (b && b.type === 'markdown' && typeof b.md === 'string') out.push(b.md);
65
+ }
66
+ };
67
+ addBlocks(spec.blocks);
68
+ for (const q of spec.questions || []) {
69
+ addBlocks(q.blocks);
70
+ for (const o of Array.isArray(q.options) ? q.options : []) {
71
+ if (o) addBlocks(o.blocks);
72
+ }
73
+ }
74
+ return out;
75
+ }
76
+
77
+ // The set of absolute paths the board references and is therefore allowed to
78
+ // open. Rebuilt per request (specs are small) so it tracks live `rly update`s.
79
+ export function buildOpenAllowlist(spec, baseCwd) {
80
+ const set = new Set();
81
+ const text = collectMarkdownSources(spec).join('\n');
82
+ const re = new RegExp(FILE_PATH_RE.source, 'g');
83
+ let m;
84
+ while ((m = re.exec(text))) {
85
+ if (!looksLikeLocalPath(m[0])) continue;
86
+ const abs = resolveLocalPath(m[0], baseCwd);
87
+ if (abs) set.add(abs);
88
+ }
89
+ return set;
90
+ }
91
+
92
+ // Streams a file with HTTP Range support so a <video>/<audio> element can seek
93
+ // and the browser can request byte ranges instead of the whole clip. Honors a
94
+ // single "bytes=start-end" range; falls back to the full body otherwise. Safe
95
+ // for a HEAD probe (sends headers, no body).
96
+ export function streamFile(req, res, filePath, contentType) {
97
+ let stat;
98
+ try {
99
+ stat = fs.statSync(filePath);
100
+ } catch {
101
+ return sendJson(res, 404, { error: 'file not found' });
102
+ }
103
+ const total = stat.size;
104
+ const range = req.headers.range;
105
+ const baseHeaders = {
106
+ 'content-type': contentType,
107
+ 'accept-ranges': 'bytes',
108
+ 'cache-control': 'no-store',
109
+ };
110
+ let start = 0;
111
+ let end = total - 1;
112
+ let status = 200;
113
+ if (range) {
114
+ const m = /^bytes=(\d*)-(\d*)$/.exec(range.trim());
115
+ if (m) {
116
+ if (m[1] === '' && m[2] === '') {
117
+ // "bytes=-" — unsatisfiable
118
+ } else if (m[1] === '') {
119
+ start = Math.max(0, total - Number(m[2])); // suffix range
120
+ } else {
121
+ start = Number(m[1]);
122
+ if (m[2] !== '') end = Math.min(end, Number(m[2]));
123
+ }
124
+ }
125
+ if (start > end || start >= total) {
126
+ res.writeHead(416, { 'content-range': `bytes */${total}`, 'cache-control': 'no-store' });
127
+ return res.end();
128
+ }
129
+ status = 206;
130
+ baseHeaders['content-range'] = `bytes ${start}-${end}/${total}`;
131
+ }
132
+ baseHeaders['content-length'] = String(end - start + 1);
133
+ res.writeHead(status, baseHeaders);
134
+ if (req.method === 'HEAD') return res.end();
135
+ const stream = fs.createReadStream(filePath, { start, end });
136
+ stream.on('error', () => {
137
+ if (!res.headersSent) sendJson(res, 500, { error: 'stream error' });
138
+ else res.destroy();
139
+ });
140
+ stream.pipe(res);
141
+ }
@@ -0,0 +1,114 @@
1
+ // Small HTTP helpers: origin checks, JSON/HTML/JS replies and body reading.
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+
5
+ const PROXY_HEADERS = ['forwarded', 'x-forwarded-for', 'x-forwarded-host', 'x-forwarded-proto', 'x-real-ip'];
6
+
7
+ // Security: a local reverse proxy can send a loopback Host (the devlink gateway
8
+ // sends `Host: localhost:PORT`), so a request carrying proxy headers is never the
9
+ // tokenless owner. A proxy that adds none is covered by the control token runBoard
10
+ // requires for the owner while a link is set.
11
+ export function isDirectLocalRequest(req) {
12
+ const host = String(req.headers.host || '').split(':')[0];
13
+ if (host !== '127.0.0.1' && host !== 'localhost') return false;
14
+ return !PROXY_HEADERS.some((name) => req.headers[name] !== undefined);
15
+ }
16
+
17
+ // True when an Origin header (if present) belongs to this board's own server.
18
+ // Same-origin fetches send no Origin or our own; a foreign Origin is a
19
+ // cross-site POST and must not be allowed to open a local file.
20
+ export function sameOrigin(req, port, extraHosts = [], extraOrigins = []) {
21
+ if (req.headers['sec-fetch-site'] === 'cross-site') return false;
22
+ const origin = req.headers.origin;
23
+ if (!origin) return true;
24
+ try {
25
+ const u = new URL(origin);
26
+ if (extraOrigins.includes(u.origin)) return true;
27
+ if (u.port !== String(port)) return false;
28
+ return new Set(['127.0.0.1', 'localhost', ...extraHosts.filter(Boolean)]).has(u.hostname);
29
+ } catch {
30
+ return false;
31
+ }
32
+ }
33
+
34
+ export function sendJson(res, code, obj) {
35
+ if (res.headersSent) return;
36
+ res.writeHead(code, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' });
37
+ res.end(JSON.stringify(obj));
38
+ }
39
+
40
+ export function sendHtml(res, body, headers = {}) {
41
+ res.writeHead(200, { 'content-type': 'text/html; charset=utf-8', 'cache-control': 'no-store', ...headers });
42
+ res.end(body);
43
+ }
44
+
45
+ export function sendJs(res, body) {
46
+ res.writeHead(200, { 'content-type': 'application/javascript; charset=utf-8', 'cache-control': 'no-store' });
47
+ res.end(body);
48
+ }
49
+
50
+ // Serves a file from a fixed directory, rejecting any path that escapes it
51
+ // (no traversal). Returns false (404 not written) when the file is missing.
52
+ export function sendFromDir(res, dir, name, contentType) {
53
+ const target = path.resolve(dir, name);
54
+ if (target !== dir && !target.startsWith(dir + path.sep)) return false;
55
+ let body;
56
+ try {
57
+ body = fs.readFileSync(target);
58
+ } catch {
59
+ return false;
60
+ }
61
+ res.writeHead(200, { 'content-type': contentType, 'cache-control': 'no-store' });
62
+ res.end(body);
63
+ return true;
64
+ }
65
+
66
+ export function readBody(req, limit = 5 * 1024 * 1024) {
67
+ return new Promise((resolve, reject) => {
68
+ let size = 0;
69
+ const chunks = [];
70
+ req.on('data', (c) => {
71
+ size += c.length;
72
+ if (size > limit) {
73
+ reject(new Error('payload too large'));
74
+ req.destroy();
75
+ } else {
76
+ chunks.push(c);
77
+ }
78
+ });
79
+ req.on('end', () => resolve(Buffer.concat(chunks).toString('utf8')));
80
+ req.on('error', reject);
81
+ });
82
+ }
83
+
84
+ // Loaded into every custom-HTML iframe so users can hover any element to leave a
85
+ // comment (relayKit.annotate.auto). Idempotent with an author-added /kit.js, and
86
+ // a no-op when the author opts out via data-relay-annotate="off".
87
+ const ANNOTATE_BOOTSTRAP =
88
+ '<script>(function(){function go(){try{window.relayKit&&window.relayKit.annotate&&window.relayKit.annotate.auto();}catch(e){}}' +
89
+ 'if(window.relayKit&&window.relayKit.annotate)return go();' +
90
+ "var s=document.createElement('script');s.src='/kit.js';s.onload=go;s.onerror=go;" +
91
+ '(document.head||document.documentElement).appendChild(s);})();<\/script>';
92
+
93
+ // Insert a snippet right before </body> (else </html>, else append).
94
+ function injectBeforeBodyEnd(html, snippet) {
95
+ const lower = html.toLowerCase();
96
+ let idx = lower.lastIndexOf('</body>');
97
+ if (idx === -1) idx = lower.lastIndexOf('</html>');
98
+ if (idx === -1) return html + snippet;
99
+ return html.slice(0, idx) + snippet + html.slice(idx);
100
+ }
101
+
102
+ // Custom-HTML fragments (no <html> tag) get wrapped in a minimal document that
103
+ // matches the user's theme, so e.g. "<b>hi</b>" doesn't paint a stark white
104
+ // block in dark mode. Full documents are served verbatim — their authors can
105
+ // read the ?theme=light|dark query param themselves. The annotate bootstrap is
106
+ // omitted for read-only shares so their iframe content has no false comment
107
+ // affordances; existing feedback remains visible in the parent comments rail.
108
+ export function wrapFragment(content, theme, annotate = true) {
109
+ if (/<html[\s>]/i.test(content)) return annotate ? injectBeforeBodyEnd(content, ANNOTATE_BOOTSTRAP) : content;
110
+ const dark = theme === 'dark';
111
+ const bg = dark ? '#282624' : '#ffffff';
112
+ const fg = dark ? '#edeae4' : '#1c1b19';
113
+ 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>`;
114
+ }
@@ -0,0 +1,2 @@
1
+ // The board server: serves one board's page and API until it finishes.
2
+ export { runBoard } from './board.js';
@@ -0,0 +1,183 @@
1
+ // Builds the board page: client payload, vendor checks and the share host.
2
+ import fs from 'node:fs';
3
+ import os from 'node:os';
4
+ import path from 'node:path';
5
+ import { loadPref } from '../store.js';
6
+ import { SRC_DIR, fillPage } from '../ui/manifest.js';
7
+ import { VENDOR_DIR } from './paths.js';
8
+
9
+ const escapeHtml = (s) =>
10
+ s.replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
11
+
12
+ // Concurrently authored UI assets (blocks/annotate) may not exist yet at this
13
+ // phase's runtime — read-guard so the server still boots with empty fallbacks.
14
+ //
15
+ // Successful reads are cached for the lifetime of the process. A running board
16
+ // thus serves one consistent UI snapshot taken at first request: if the relay
17
+ // package is updated on disk (e.g. `rly upgrade`) while this server is live, it
18
+ // keeps serving its own version instead of mixing new assets with old in-memory
19
+ // server logic. Empty/failed reads are NOT cached, preserving the boot-time
20
+ // fallback for assets authored concurrently during a build.
21
+ const _uiCache = new Map();
22
+ function readUi(file) {
23
+ const hit = _uiCache.get(file);
24
+ if (hit) return hit;
25
+ let content = '';
26
+ try {
27
+ content = fs.readFileSync(path.join(SRC_DIR, file), 'utf8');
28
+ } catch {
29
+ return '';
30
+ }
31
+ if (content) _uiCache.set(file, content);
32
+ return content;
33
+ }
34
+
35
+ // Strips block bodies for the client payload: html blocks ship only metadata
36
+ // (their bodies are served via /html/b/<id>), embedded images ship only
37
+ // metadata (bytes served via /img/b/<id>), streamed local media ships only
38
+ // metadata (bytes served via /video/b/<id> or /pdf/b/<id>), everything else
39
+ // ships as-is.
40
+ function clientBlock(b) {
41
+ // Cross-block fields preserved when we ship metadata-only (ref = reference-link
42
+ // target name; pins = image coordinate comments). The default `return b` path
43
+ // already carries them.
44
+ const extra = {};
45
+ if (b && b.ref !== undefined) extra.ref = b.ref;
46
+ if (b && b.type === 'html') {
47
+ return { id: b.id, type: 'html', height: b.height, hasHtml: Boolean(b.html), ...extra };
48
+ }
49
+ if (b && b.type === 'image' && typeof b.src === 'string' && b.src.startsWith('data:')) {
50
+ return { id: b.id, type: 'image', alt: b.alt, height: b.height, hasData: true, ...(b.pins ? { pins: true } : {}), ...extra };
51
+ }
52
+ // Local video: the absolute file path stays server-side; the client gets a
53
+ // flag + mime and loads the bytes (Range-streamed) from /video/b/<id>.
54
+ if (b && b.type === 'video' && typeof b.file === 'string') {
55
+ return { id: b.id, type: 'video', title: b.title, height: b.height, mime: b.mime, hasFile: true, ...extra };
56
+ }
57
+ if (b && b.type === 'pdf' && typeof b.file === 'string') {
58
+ return { id: b.id, type: 'pdf', title: b.title, height: b.height, mime: b.mime, hasFile: true, ...extra };
59
+ }
60
+ return b;
61
+ }
62
+
63
+ // One question for the client payload: strip block bodies at the question
64
+ // level AND inside each option's blocks.
65
+ function clientQuestion(q) {
66
+ const out = { ...q, blocks: (q.blocks || []).map(clientBlock) };
67
+ if (Array.isArray(q.options)) {
68
+ out.options = q.options.map((o) =>
69
+ o && Array.isArray(o.blocks) && o.blocks.length ? { ...o, blocks: o.blocks.map(clientBlock) } : o
70
+ );
71
+ }
72
+ return out;
73
+ }
74
+
75
+ // True when any block in the spec needs a given vendored library.
76
+ function specNeeds(spec, type) {
77
+ const has = (blocks) => Array.isArray(blocks) && blocks.some((b) => b && b.type === type);
78
+ if (has(spec.blocks)) return true;
79
+ return spec.questions.some(
80
+ (q) => has(q.blocks) || (Array.isArray(q.options) && q.options.some((o) => o && has(o.blocks)))
81
+ );
82
+ }
83
+
84
+ function vendorPresent(file) {
85
+ try {
86
+ return fs.existsSync(path.join(VENDOR_DIR, file));
87
+ } catch {
88
+ return false;
89
+ }
90
+ }
91
+
92
+ function cleanShareHost(raw) {
93
+ const s = String(raw || '').trim();
94
+ if (!s) return null;
95
+ let host = s;
96
+ try {
97
+ host = s.includes('://') ? new URL(s).hostname : s;
98
+ } catch {
99
+ host = s;
100
+ }
101
+ host = host.replace(/^https?:\/\//, '').split('/')[0].split(':')[0].trim();
102
+ if (!host || host === '127.0.0.1' || host === 'localhost') return null;
103
+ return host;
104
+ }
105
+
106
+ function isPrivateIpv4(address) {
107
+ if (!/^(\d{1,3}\.){3}\d{1,3}$/.test(address)) return false;
108
+ const parts = address.split('.').map((n) => Number(n));
109
+ if (parts.some((n) => !Number.isInteger(n) || n < 0 || n > 255)) return false;
110
+ return (
111
+ parts[0] === 10 ||
112
+ (parts[0] === 172 && parts[1] >= 16 && parts[1] <= 31) ||
113
+ (parts[0] === 192 && parts[1] === 168)
114
+ );
115
+ }
116
+
117
+ export function shareHost() {
118
+ const forced = cleanShareHost(process.env.RLY_SHARE_HOST);
119
+ if (forced) return forced;
120
+ const candidates = [];
121
+ const nets = os.networkInterfaces();
122
+ for (const list of Object.values(nets)) {
123
+ for (const net of list || []) {
124
+ if (!net || net.internal || net.family !== 'IPv4') continue;
125
+ candidates.push(net.address);
126
+ }
127
+ }
128
+ return candidates.find(isPrivateIpv4) || candidates[0] || null;
129
+ }
130
+
131
+ export function buildPage(record, rev, { access = null, draftRev = 0 } = {}) {
132
+ const html = fs.readFileSync(path.join(SRC_DIR, 'ui', 'index.html'), 'utf8');
133
+ const spec = record.spec;
134
+ // Block bodies (html) are served via /html/b/* iframes, so strip them from
135
+ // the embedded payload and only ship metadata.
136
+ const clientSpec = {
137
+ ...spec,
138
+ blocks: (spec.blocks || []).map(clientBlock),
139
+ questions: spec.questions.map(clientQuestion),
140
+ };
141
+ // Tell the client which vendored libraries to lazy-load — true only when a
142
+ // block needs it AND the vendored asset is actually present.
143
+ // Filenames must match what the clients request (blocks.js / kit.js load
144
+ // /vendor/chart.umd.js and /vendor/mermaid.min.js).
145
+ const vendor = {
146
+ chart: specNeeds(spec, 'chart') && vendorPresent('chart.umd.js'),
147
+ mermaid: specNeeds(spec, 'mermaid') && vendorPresent('mermaid.min.js'),
148
+ viz: specNeeds(spec, 'graphviz') && vendorPresent('viz-standalone.js'),
149
+ };
150
+ // Prefill from the LIVE draft at request time (drafts autosave in real time),
151
+ // so a mid-fill page reload restores everything the user already entered.
152
+ // Reviewer answers are an independent, reference-only draft. They must never
153
+ // prefill from or overwrite the owner's final-answer draft. Read-only viewers
154
+ // see the owner's current state but cannot mutate it.
155
+ const reviewDrafts = record.reviewDrafts && typeof record.reviewDrafts === 'object' ? record.reviewDrafts : {};
156
+ const sourceDraft = access && access.role === 'review'
157
+ ? (reviewDrafts[access.reviewSessionId] || null)
158
+ : record.draft;
159
+ const prefill = sourceDraft
160
+ ? {
161
+ answers: sourceDraft.answers || {},
162
+ comment: sourceDraft.comment || '',
163
+ notes: sourceDraft.notes || {},
164
+ annotations: sourceDraft.annotations || [],
165
+ blockEdits: sourceDraft.blockEdits || {},
166
+ // The server draft's save time, so the client can pick the NEWER of this
167
+ // vs. its localStorage mirror (a tab that kept typing while the server
168
+ // was unreachable holds fresher input than the last server save).
169
+ updatedAt: sourceDraft.updatedAt || null,
170
+ }
171
+ : null;
172
+ const boot = { boardId: record.id, spec: clientSpec, prefill, pref: loadPref(), vendor, rev, draftRev, access };
173
+ const json = JSON.stringify(boot).replace(/</g, '\\u003c');
174
+ return fillPage(html, { title: escapeHtml(spec.title), bootJson: json, entry: 'app' }, readUi);
175
+ }
176
+
177
+ export function buildLockedPage(title = 'Relay board') {
178
+ return '<!doctype html><html><head><meta charset="utf-8">' +
179
+ '<meta name="viewport" content="width=device-width, initial-scale=1">' +
180
+ '<title>' + escapeHtml(title) + '</title>' +
181
+ '<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>' +
182
+ '</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>';
183
+ }
@@ -0,0 +1,7 @@
1
+ // Where the server finds the UI sources and the vendored browser libraries.
2
+ import path from 'node:path';
3
+ import { fileURLToPath } from 'node:url';
4
+
5
+ export const UI_DIR = path.join(path.dirname(fileURLToPath(import.meta.url)), '..', 'ui');
6
+ const PKG_ROOT = path.join(path.dirname(fileURLToPath(import.meta.url)), '..', '..');
7
+ export const VENDOR_DIR = path.join(PKG_ROOT, 'vendor');
@@ -0,0 +1,58 @@
1
+ // Artifact checks and the on-result hook that runs when a board finishes.
2
+ import { spawn } from 'node:child_process';
3
+
4
+ export const ARTIFACT_MAX_BYTES = 4 * 1024 * 1024;
5
+ export const ARTIFACT_MIMES = {
6
+ 'image/png': 'png',
7
+ 'image/jpeg': 'jpg',
8
+ 'image/webp': 'webp',
9
+ };
10
+
11
+ export function artifactBytesMatch(mime, bytes) {
12
+ if (!Buffer.isBuffer(bytes) || bytes.length < 4) return false;
13
+ if (mime === 'image/png') return bytes.subarray(0, 8).equals(Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]));
14
+ if (mime === 'image/jpeg') return bytes[0] === 0xff && bytes[1] === 0xd8 && bytes[bytes.length - 2] === 0xff && bytes[bytes.length - 1] === 0xd9;
15
+ if (mime === 'image/webp') return bytes.subarray(0, 4).toString('ascii') === 'RIFF' && bytes.subarray(8, 12).toString('ascii') === 'WEBP';
16
+ return false;
17
+ }
18
+
19
+ // Push-wake: run the agent's own local shell command after a board finishes.
20
+ // The full result JSON is written to the command's stdin; RLY_BOARD_ID /
21
+ // RLY_STATUS / RLY_URL are exported. Failures are swallowed (best effort) —
22
+ // only a stderr note when not quiet. A 30s kill timer prevents a hung command
23
+ // from keeping the process alive.
24
+ export function runOnResult(cmd, result, { quiet = false } = {}) {
25
+ if (typeof cmd !== 'string' || !cmd.trim()) return;
26
+ try {
27
+ const child = spawn('/bin/sh', ['-c', cmd], {
28
+ env: {
29
+ ...process.env,
30
+ RLY_BOARD_ID: result.boardId || '',
31
+ RLY_STATUS: result.status || '',
32
+ RLY_URL: result.url || '',
33
+ },
34
+ stdio: ['pipe', 'ignore', 'ignore'],
35
+ });
36
+ child.on('error', () => {
37
+ if (!quiet) process.stderr.write(`[relay] --on-result command failed to spawn\n`);
38
+ });
39
+ try {
40
+ child.stdin.write(JSON.stringify(result));
41
+ child.stdin.end();
42
+ } catch {
43
+ // best effort — stdin may already be gone
44
+ }
45
+ const killTimer = setTimeout(() => {
46
+ try {
47
+ child.kill('SIGKILL');
48
+ } catch {
49
+ // already gone
50
+ }
51
+ }, 30000);
52
+ killTimer.unref();
53
+ child.on('close', () => clearTimeout(killTimer));
54
+ child.unref();
55
+ } catch {
56
+ if (!quiet) process.stderr.write(`[relay] --on-result command failed to run\n`);
57
+ }
58
+ }
@@ -0,0 +1,41 @@
1
+ // Share-link state and the per-reviewer side review sessions.
2
+ import crypto from 'node:crypto';
3
+
4
+ export const SHARE_STATE_VERSION = 2;
5
+ const REVIEW_SESSION_COOKIE = 'relay_review_session';
6
+
7
+ export function reviewSessionId(req) {
8
+ if (req._relayReviewSessionId) return req._relayReviewSessionId;
9
+ const explicit = String(req.headers['x-relay-review-session'] || '');
10
+ const cookies = String(req.headers.cookie || '').split(';').map((s) => s.trim());
11
+ const cookie = cookies.find((s) => s.startsWith(REVIEW_SESSION_COOKIE + '='));
12
+ let value = explicit || (cookie ? decodeURIComponent(cookie.slice(REVIEW_SESSION_COOKIE.length + 1)) : '');
13
+ if (!/^[A-Za-z0-9_-]{8,80}$/.test(value)) value = 'rv-' + crypto.randomBytes(12).toString('hex');
14
+ req._relayReviewSessionId = value;
15
+ return value;
16
+ }
17
+
18
+ export function reviewSessionCookie(sessionId) {
19
+ return `${REVIEW_SESSION_COOKIE}=${encodeURIComponent(sessionId)}; Path=/; HttpOnly; SameSite=Strict; Max-Age=2592000`;
20
+ }
21
+
22
+ export function sideReviewState(record) {
23
+ const drafts = record.reviewDrafts && typeof record.reviewDrafts === 'object' ? record.reviewDrafts : {};
24
+ const submissions = Array.isArray(record.sideReviews) ? record.sideReviews : [];
25
+ return {
26
+ referenceOnly: true,
27
+ note: 'Side reviews are reference only. Wait for the board owner (or owner-authorized collaborator) to submit the final answer.',
28
+ submissions,
29
+ drafts,
30
+ };
31
+ }
32
+
33
+ export function pruneReviewDrafts(record, max = 50) {
34
+ const drafts = record.reviewDrafts && typeof record.reviewDrafts === 'object' ? record.reviewDrafts : {};
35
+ const entries = Object.entries(drafts).sort((a, b) => {
36
+ const at = Date.parse(a[1] && a[1].updatedAt || '') || 0;
37
+ const bt = Date.parse(b[1] && b[1].updatedAt || '') || 0;
38
+ return bt - at;
39
+ });
40
+ record.reviewDrafts = Object.fromEntries(entries.slice(0, max));
41
+ }