@khanglvm/relay 0.22.1 → 0.23.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.
- package/README.md +7 -0
- package/docs/AGENT.md +7 -2
- package/docs/SETUP.md +7 -0
- package/package.json +2 -2
- package/src/cli/args.js +1 -1
- package/src/cli/boards.js +5 -4
- package/src/cli/help.js +3 -1
- package/src/cli/mcp.js +19 -2
- package/src/file-access.js +91 -12
- package/src/file-preview.js +9 -7
- package/src/mcp/boards.js +1 -0
- package/src/mcp/serve.js +9 -5
- package/src/mcp/server.js +5 -1
- package/src/mcp/store.js +6 -3
- package/src/mcp/tools.js +2 -1
- package/src/mcp-ui/board/draft.js +30 -0
- package/src/mcp-ui/board/lifecycle.js +4 -3
- package/src/mcp-ui/board/state.js +4 -0
- package/src/retention.js +116 -0
- package/src/server/board.js +21 -27
- package/src/server/files.js +50 -20
- package/src/server/http.js +13 -4
- package/src/spec/blocks/image.js +2 -5
- package/src/spec/blocks/table.js +2 -5
- package/src/spec/sources.js +4 -22
- package/src/store.js +48 -6
- package/src/ui/manifest.js +1 -0
- package/types/file-access.d.ts +43 -3
- package/types/mcp/serve.d.ts +13 -7
- package/types/mcp/store.d.ts +7 -2
- package/types/mcp/tools.d.ts +2 -0
- package/types/retention.d.ts +33 -0
- package/types/spec/blocks/code.d.ts +2 -2
- package/types/spec/blocks/markdown.d.ts +1 -1
- package/types/spec/sources.d.ts +2 -2
- package/types/store.d.ts +13 -2
package/src/retention.js
ADDED
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
// How long boards stay on disk, and the sweep that removes the ones past it.
|
|
2
|
+
// The sweep takes plain paths and callbacks, so store.js wires it to the relay home.
|
|
3
|
+
import fs from 'node:fs';
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
import { CliError } from './util.js';
|
|
6
|
+
|
|
7
|
+
export const RETENTION_ENV = 'RLY_RETENTION_DAYS';
|
|
8
|
+
export const DEFAULT_RETENTION_DAYS = 30;
|
|
9
|
+
|
|
10
|
+
const DAY_MS = 24 * 60 * 60 * 1000;
|
|
11
|
+
// Boards are swept at most once an hour per relay home, however many boards are created.
|
|
12
|
+
const SWEEP_INTERVAL_MS = 60 * 60 * 1000;
|
|
13
|
+
// A sweep that died without releasing its lock is taken over after this long.
|
|
14
|
+
const STALE_LOCK_MS = 10 * 60 * 1000;
|
|
15
|
+
// A temp file left by a write that crashed before its rename.
|
|
16
|
+
const STALE_TEMP_MS = DAY_MS;
|
|
17
|
+
const LOCK_NAME = 'prune.lock';
|
|
18
|
+
const STAMP_NAME = 'prune.stamp';
|
|
19
|
+
const OFF_WORDS = new Set(['0', 'off', 'never', 'none', 'false', 'no']);
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* The retention window in days; 0 means boards are kept forever.
|
|
23
|
+
* The option wins over `RLY_RETENTION_DAYS`, which wins over the 30-day default.
|
|
24
|
+
* @param {unknown} [option] a number of days, a numeric string, or `0`, `false` or "off" to keep every board
|
|
25
|
+
* @param {Record<string, string | undefined>} [env]
|
|
26
|
+
*/
|
|
27
|
+
export function resolveRetentionDays(option, env = process.env) {
|
|
28
|
+
const fromEnv = env[RETENTION_ENV];
|
|
29
|
+
const raw = option !== undefined && option !== null && option !== '' ? option : fromEnv;
|
|
30
|
+
if (raw === undefined || raw === null || raw === '') return DEFAULT_RETENTION_DAYS;
|
|
31
|
+
if (raw === false) return 0;
|
|
32
|
+
const text = String(raw).trim().toLowerCase();
|
|
33
|
+
if (OFF_WORDS.has(text)) return 0;
|
|
34
|
+
const days = Number(text);
|
|
35
|
+
if (!Number.isFinite(days) || days < 0) {
|
|
36
|
+
const source = option !== undefined && option !== null && option !== '' ? 'retentionDays' : RETENTION_ENV;
|
|
37
|
+
throw new CliError(`${source} must be a number of days (0 or "off" keeps every board), got "${text}".`);
|
|
38
|
+
}
|
|
39
|
+
return days;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** Takes the sweep lock; false when another process holds it. */
|
|
43
|
+
function takeLock(lockDir) {
|
|
44
|
+
try {
|
|
45
|
+
fs.mkdirSync(lockDir);
|
|
46
|
+
return true;
|
|
47
|
+
} catch (err) {
|
|
48
|
+
if (err?.code !== 'EEXIST') return false;
|
|
49
|
+
}
|
|
50
|
+
try {
|
|
51
|
+
if (Date.now() - fs.statSync(lockDir).mtimeMs > STALE_LOCK_MS) fs.rmdirSync(lockDir);
|
|
52
|
+
} catch { /* the holder finished, or another process took it over first */ }
|
|
53
|
+
return false;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
const releaseLock = (lockDir) => { try { fs.rmdirSync(lockDir); } catch { /* already gone */ } };
|
|
57
|
+
|
|
58
|
+
/** True when the last sweep of this home was less than an hour ago. */
|
|
59
|
+
function sweptRecently(stampFile, now) {
|
|
60
|
+
try { return now - fs.statSync(stampFile).mtimeMs < SWEEP_INTERVAL_MS; } catch { return false; }
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
const isOlderThan = (file, ms, now) => {
|
|
64
|
+
try { return now - fs.statSync(file).mtimeMs > ms; } catch { return false; }
|
|
65
|
+
};
|
|
66
|
+
|
|
67
|
+
/** Ids of board files not touched for `days`; every save and draft updates a board file. */
|
|
68
|
+
function expiredBoardIds(boardsDir, days, now, keep) {
|
|
69
|
+
const expired = [];
|
|
70
|
+
for (const name of fs.readdirSync(boardsDir)) {
|
|
71
|
+
const match = /^(b-[a-z0-9]+)\.json$/i.exec(name);
|
|
72
|
+
if (match && !keep.has(match[1]) && isOlderThan(path.join(boardsDir, name), days * DAY_MS, now)) expired.push(match[1]);
|
|
73
|
+
}
|
|
74
|
+
return expired;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
function removeStaleTempFiles(dir, now) {
|
|
78
|
+
for (const name of fs.readdirSync(dir)) {
|
|
79
|
+
const file = path.join(dir, name);
|
|
80
|
+
if (!name.endsWith('.tmp') || !isOlderThan(file, STALE_TEMP_MS, now)) continue;
|
|
81
|
+
try { fs.unlinkSync(file); } catch { /* removed by another process */ }
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* Removes boards whose files have not changed for `days`. Several processes can
|
|
87
|
+
* share one relay home: a lock directory keeps two sweeps apart, and a stamp
|
|
88
|
+
* file keeps a busy home from sweeping on every new board. A board a running
|
|
89
|
+
* server still serves, and any board younger than the window, stays.
|
|
90
|
+
* @param {object} options
|
|
91
|
+
* @param {string} options.home the relay home; holds the lock and the stamp
|
|
92
|
+
* @param {string} options.boardsDir
|
|
93
|
+
* @param {number} options.days window in days; 0 or less does nothing
|
|
94
|
+
* @param {Set<string>} [options.keep] ids that must stay, such as boards with a live server
|
|
95
|
+
* @param {(id: string) => boolean} options.remove deletes one board and its sidecar files
|
|
96
|
+
* @param {number} [options.now] ms since the epoch
|
|
97
|
+
* @param {boolean} [options.force] sweep even when one ran in the last hour
|
|
98
|
+
* @returns {string[]} the ids removed
|
|
99
|
+
*/
|
|
100
|
+
export function pruneBoards({ home, boardsDir, days, keep = new Set(), remove, now = Date.now(), force = false }) {
|
|
101
|
+
if (!(days > 0)) return [];
|
|
102
|
+
const lockDir = path.join(home, LOCK_NAME);
|
|
103
|
+
const stampFile = path.join(home, STAMP_NAME);
|
|
104
|
+
if (!takeLock(lockDir)) return [];
|
|
105
|
+
try {
|
|
106
|
+
if (!force && sweptRecently(stampFile, now)) return [];
|
|
107
|
+
// A board saved since the scan is checked again, so a draft that lands mid-sweep keeps its board.
|
|
108
|
+
const removed = expiredBoardIds(boardsDir, days, now, keep)
|
|
109
|
+
.filter((id) => isOlderThan(path.join(boardsDir, `${id}.json`), days * DAY_MS, now) && remove(id));
|
|
110
|
+
removeStaleTempFiles(boardsDir, now);
|
|
111
|
+
fs.writeFileSync(stampFile, new Date(now).toISOString());
|
|
112
|
+
return removed;
|
|
113
|
+
} finally {
|
|
114
|
+
releaseLock(lockDir);
|
|
115
|
+
}
|
|
116
|
+
}
|
package/src/server/board.js
CHANGED
|
@@ -3,7 +3,6 @@ import crypto from 'node:crypto';
|
|
|
3
3
|
import fs from 'node:fs';
|
|
4
4
|
import http from 'node:http';
|
|
5
5
|
import path from 'node:path';
|
|
6
|
-
import { filePreview, mediaType, splitFileReference } from '../file-preview.js';
|
|
7
6
|
import { resolveLink } from '../link.js';
|
|
8
7
|
import { openUrl } from '../open.js';
|
|
9
8
|
import { assertSpecReady, cleanAnswers } from '../spec/index.js';
|
|
@@ -14,8 +13,8 @@ import { isDirectLocalRequest, readBody, sameOrigin, sendDataImage, sendFromDir,
|
|
|
14
13
|
import { UI_DIR, VENDOR_DIR } from './paths.js';
|
|
15
14
|
import { findBlock, findHtmlBlock, firstBoardHtml, firstQuestionHtml, sanitizeAnnotations, sanitizeBlockEdits } from './sanitize.js';
|
|
16
15
|
import { ARTIFACT_MAX_BYTES, ARTIFACT_MIMES, artifactBytesMatch, runOnResult } from './result.js';
|
|
17
|
-
import {
|
|
18
|
-
import { buildOpenAllowlist, recordFileAccess, resolveLocalPath, streamFile } from './files.js';
|
|
16
|
+
import { openReadable } from '../file-access.js';
|
|
17
|
+
import { buildOpenAllowlist, recordFileAccess, resolveLocalPath, respondWithOpenedFile, streamFile } from './files.js';
|
|
19
18
|
|
|
20
19
|
// Serves one board on 127.0.0.1 and resolves `done` when it finishes
|
|
21
20
|
// (submitted / acknowledged / timeout / cancelled). The result is also
|
|
@@ -54,6 +53,10 @@ export async function runBoard({ id, port = 0, open = true, timeoutSec = 86400,
|
|
|
54
53
|
saveBoard(record);
|
|
55
54
|
}
|
|
56
55
|
|
|
56
|
+
// Security: the roots are the ones the board was created under. Nothing a
|
|
57
|
+
// request carries can widen them, because the spec's pdf and video paths are
|
|
58
|
+
// streamed from disk and `/api/update` stores a spec without re-reading it.
|
|
59
|
+
const fileAccess = recordFileAccess(record);
|
|
57
60
|
const startedAt = Date.now();
|
|
58
61
|
// Mutation token: only `rly update` (which reads the running-file record)
|
|
59
62
|
// can authenticate to POST /api/update. Never embedded in the page/boot.
|
|
@@ -257,6 +260,7 @@ export async function runBoard({ id, port = 0, open = true, timeoutSec = 86400,
|
|
|
257
260
|
} else if (req.method === 'POST' && pathname === '/api/update') {
|
|
258
261
|
if (req.headers['x-relay-token'] !== token) return sendJson(res, 403, { error: 'forbidden' });
|
|
259
262
|
const body = JSON.parse((await readBody(req)) || '{}');
|
|
263
|
+
if (body.fileRoots !== undefined) return sendJson(res, 400, { error: 'file roots are set when a board is created and cannot change on update' });
|
|
260
264
|
const next = body.spec;
|
|
261
265
|
if (next === null || typeof next !== 'object' || Array.isArray(next) ||
|
|
262
266
|
!Array.isArray(next.questions) || !Array.isArray(next.blocks)) {
|
|
@@ -268,7 +272,6 @@ export async function runBoard({ id, port = 0, open = true, timeoutSec = 86400,
|
|
|
268
272
|
return sendJson(res, 400, { error: err && err.message ? err.message : String(err) });
|
|
269
273
|
}
|
|
270
274
|
record.spec = next;
|
|
271
|
-
if (Array.isArray(body.fileRoots)) record.fileRoots = body.fileRoots.filter((r) => typeof r === 'string');
|
|
272
275
|
rev++;
|
|
273
276
|
saveBoard(record);
|
|
274
277
|
sendJson(res, 200, { ok: true, rev });
|
|
@@ -328,17 +331,17 @@ export async function runBoard({ id, port = 0, open = true, timeoutSec = 86400,
|
|
|
328
331
|
const blockId = decodeURIComponent(pathname.slice('/video/b/'.length));
|
|
329
332
|
const block = findBlock(record.spec, blockId, 'video');
|
|
330
333
|
if (!block || typeof block.file !== 'string') return sendJson(res, 404, { error: `no local video block "${blockId}"` });
|
|
331
|
-
const video =
|
|
332
|
-
if (!video.ok) return sendJson(res, 404, { error: `no local video block "${blockId}"` });
|
|
333
|
-
streamFile(req, res, video
|
|
334
|
+
const video = openReadable(fileAccess, block.file);
|
|
335
|
+
if (!video.ok || video.fd === null) return sendJson(res, 404, { error: `no local video block "${blockId}"` });
|
|
336
|
+
streamFile(req, res, video, block.mime || 'application/octet-stream');
|
|
334
337
|
} else if ((req.method === 'GET' || req.method === 'HEAD') && pathname.startsWith('/pdf/b/')) {
|
|
335
338
|
// Local PDF bytes, Range-streamed for the browser's built-in PDF viewer.
|
|
336
339
|
const blockId = decodeURIComponent(pathname.slice('/pdf/b/'.length));
|
|
337
340
|
const block = findBlock(record.spec, blockId, 'pdf');
|
|
338
341
|
if (!block || typeof block.file !== 'string') return sendJson(res, 404, { error: `no local pdf block "${blockId}"` });
|
|
339
|
-
const pdf =
|
|
340
|
-
if (!pdf.ok) return sendJson(res, 404, { error: `no local pdf block "${blockId}"` });
|
|
341
|
-
streamFile(req, res, pdf
|
|
342
|
+
const pdf = openReadable(fileAccess, block.file);
|
|
343
|
+
if (!pdf.ok || pdf.fd === null) return sendJson(res, 404, { error: `no local pdf block "${blockId}"` });
|
|
344
|
+
streamFile(req, res, pdf, block.mime || 'application/pdf');
|
|
342
345
|
} else if (req.method === 'GET' && pathname === '/html/board') {
|
|
343
346
|
// Legacy alias → the board's first html block.
|
|
344
347
|
const block = firstBoardHtml(record.spec);
|
|
@@ -365,6 +368,9 @@ export async function runBoard({ id, port = 0, open = true, timeoutSec = 86400,
|
|
|
365
368
|
if (!sameOrigin(req, actualPort, [advertisedHost], [publicLink?.origin])) return sendJson(res, 403, { error: 'cross-origin requests cannot open files' });
|
|
366
369
|
const access = accessFor(req, reqUrl);
|
|
367
370
|
if (access.role !== 'owner' && access.role !== 'collab') return sendJson(res, 403, { error: 'this share cannot open local files' });
|
|
371
|
+
// Security: /api/open launches the file's app on this machine, which can
|
|
372
|
+
// run a script or an .app bundle, so only the person at this machine may.
|
|
373
|
+
if (pathname === '/api/open' && access.role !== 'owner') return sendJson(res, 403, { error: 'only the board owner on this machine can open files in an app' });
|
|
368
374
|
const body = req.method === 'POST' ? JSON.parse((await readBody(req)) || '{}') : { path: reqUrl.searchParams.get('path') };
|
|
369
375
|
const raw = typeof body.path === 'string' ? body.path : '';
|
|
370
376
|
if (!raw.trim()) return sendJson(res, 400, { error: 'missing "path"' });
|
|
@@ -374,24 +380,12 @@ export async function runBoard({ id, port = 0, open = true, timeoutSec = 86400,
|
|
|
374
380
|
if (!buildOpenAllowlist(record.spec, baseCwd).has(target)) {
|
|
375
381
|
return sendJson(res, 403, { error: 'this path is not referenced on the board' });
|
|
376
382
|
}
|
|
377
|
-
const
|
|
378
|
-
if (!
|
|
379
|
-
if (
|
|
380
|
-
return sendJson(res, 403, { error:
|
|
383
|
+
const opened = openReadable(fileAccess, target, { allowDirectory: true });
|
|
384
|
+
if (!opened.ok) {
|
|
385
|
+
if (opened.reason === 'missing') return sendJson(res, 404, { error: 'file not found', path: target });
|
|
386
|
+
return sendJson(res, 403, { error: opened.reason === 'outside' ? 'this path is outside the board\'s file roots' : 'this path is not a file or folder' });
|
|
381
387
|
}
|
|
382
|
-
|
|
383
|
-
if (pathname === '/api/file-preview') {
|
|
384
|
-
return sendJson(res, 200, { ok: true, ...filePreview(real, stat, splitFileReference(raw)) });
|
|
385
|
-
}
|
|
386
|
-
if (pathname === '/api/file-content') {
|
|
387
|
-
const media = mediaType(real);
|
|
388
|
-
if (!stat.isFile() || !media) return sendJson(res, 415, { error: 'this file type cannot be streamed' });
|
|
389
|
-
res.setHeader('X-Content-Type-Options', 'nosniff');
|
|
390
|
-
res.setHeader('Content-Security-Policy', "sandbox; default-src 'none'");
|
|
391
|
-
return streamFile(req, res, real, media[1]);
|
|
392
|
-
}
|
|
393
|
-
if (!openUrl(real)) return sendJson(res, 500, { error: 'could not open the file' });
|
|
394
|
-
sendJson(res, 200, { ok: true, path: target, name: path.basename(target) });
|
|
388
|
+
respondWithOpenedFile(req, res, pathname, opened, raw, target);
|
|
395
389
|
} else if (req.method === 'POST' && pathname === '/api/draft') {
|
|
396
390
|
if (record.spec.responseRequired === false) return sendJson(res, 409, { error: 'display-only boards do not collect feedback' });
|
|
397
391
|
const access = accessFor(req, reqUrl);
|
package/src/server/files.js
CHANGED
|
@@ -4,7 +4,9 @@ import os from 'node:os';
|
|
|
4
4
|
import path from 'node:path';
|
|
5
5
|
import { fileURLToPath } from 'node:url';
|
|
6
6
|
import { createFileAccess } from '../file-access.js';
|
|
7
|
-
import { splitFileReference } from '../file-preview.js';
|
|
7
|
+
import { filePreview, mediaType, splitFileReference } from '../file-preview.js';
|
|
8
|
+
import { openUrl } from '../open.js';
|
|
9
|
+
import { boardFileRoots } from '../store.js';
|
|
8
10
|
import { sendJson } from './http.js';
|
|
9
11
|
|
|
10
12
|
// ---------- local-file links (POST /api/open) ----------
|
|
@@ -36,13 +38,9 @@ function looksLikeLocalPath(s) {
|
|
|
36
38
|
return false;
|
|
37
39
|
}
|
|
38
40
|
|
|
39
|
-
/**
|
|
40
|
-
* The file roots a stored board was created under. Boards saved before roots
|
|
41
|
-
* existed fall back to their authoring directory.
|
|
42
|
-
*/
|
|
41
|
+
/** The file access of a stored board: its authoring folder and the roots it was created under. */
|
|
43
42
|
export function recordFileAccess(record) {
|
|
44
|
-
|
|
45
|
-
return createFileAccess({ cwd, roots: Array.isArray(record.fileRoots) ? record.fileRoots : [cwd] });
|
|
43
|
+
return createFileAccess({ cwd: record.cwd || process.cwd(), roots: boardFileRoots(record) });
|
|
46
44
|
}
|
|
47
45
|
|
|
48
46
|
// Expands ~ / file:// and resolves a (possibly relative) path to an absolute,
|
|
@@ -99,17 +97,13 @@ export function buildOpenAllowlist(spec, baseCwd) {
|
|
|
99
97
|
return set;
|
|
100
98
|
}
|
|
101
99
|
|
|
102
|
-
// Streams
|
|
103
|
-
//
|
|
104
|
-
// single "bytes=start-end" range;
|
|
105
|
-
// for a HEAD probe (sends headers,
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
stat = fs.statSync(filePath);
|
|
110
|
-
} catch {
|
|
111
|
-
return sendJson(res, 404, { error: 'file not found' });
|
|
112
|
-
}
|
|
100
|
+
// Streams an opened file (`openReadable`'s `fd` and `stat`) with HTTP Range
|
|
101
|
+
// support so a <video>/<audio> element can seek and the browser can request byte
|
|
102
|
+
// ranges instead of the whole clip. Honors a single "bytes=start-end" range;
|
|
103
|
+
// falls back to the full body otherwise. Safe for a HEAD probe (sends headers,
|
|
104
|
+
// no body). Takes ownership of the descriptor and closes it on every path.
|
|
105
|
+
export function streamFile(req, res, opened, contentType) {
|
|
106
|
+
const { fd, stat } = opened;
|
|
113
107
|
const total = stat.size;
|
|
114
108
|
const range = req.headers.range;
|
|
115
109
|
const baseHeaders = {
|
|
@@ -133,6 +127,7 @@ export function streamFile(req, res, filePath, contentType) {
|
|
|
133
127
|
}
|
|
134
128
|
}
|
|
135
129
|
if (start > end || start >= total) {
|
|
130
|
+
fs.closeSync(fd);
|
|
136
131
|
res.writeHead(416, { 'content-range': `bytes */${total}`, 'cache-control': 'no-store' });
|
|
137
132
|
return res.end();
|
|
138
133
|
}
|
|
@@ -141,11 +136,46 @@ export function streamFile(req, res, filePath, contentType) {
|
|
|
141
136
|
}
|
|
142
137
|
baseHeaders['content-length'] = String(end - start + 1);
|
|
143
138
|
res.writeHead(status, baseHeaders);
|
|
144
|
-
if (req.method === 'HEAD'
|
|
145
|
-
|
|
139
|
+
if (req.method === 'HEAD' || total === 0) {
|
|
140
|
+
fs.closeSync(fd);
|
|
141
|
+
return res.end();
|
|
142
|
+
}
|
|
143
|
+
const stream = fs.createReadStream('', { fd, start, end });
|
|
146
144
|
stream.on('error', () => {
|
|
147
145
|
if (!res.headersSent) sendJson(res, 500, { error: 'stream error' });
|
|
148
146
|
else res.destroy();
|
|
149
147
|
});
|
|
148
|
+
res.on('close', () => stream.destroy());
|
|
150
149
|
stream.pipe(res);
|
|
151
150
|
}
|
|
151
|
+
|
|
152
|
+
export function closeOpened(opened) {
|
|
153
|
+
if (opened.fd !== null && opened.fd !== undefined) fs.closeSync(opened.fd);
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/**
|
|
157
|
+
* Answers /api/file-preview, /api/file-content and /api/open for a file that
|
|
158
|
+
* `openReadable` already checked. Every branch closes the descriptor.
|
|
159
|
+
*/
|
|
160
|
+
export function respondWithOpenedFile(req, res, pathname, opened, raw, target) {
|
|
161
|
+
const { file: real, stat } = opened;
|
|
162
|
+
if (pathname === '/api/file-content') {
|
|
163
|
+
const media = mediaType(real);
|
|
164
|
+
if (!stat.isFile() || !media) {
|
|
165
|
+
closeOpened(opened);
|
|
166
|
+
return sendJson(res, 415, { error: 'this file type cannot be streamed' });
|
|
167
|
+
}
|
|
168
|
+
res.setHeader('X-Content-Type-Options', 'nosniff');
|
|
169
|
+
res.setHeader('Content-Security-Policy', "sandbox; default-src 'none'");
|
|
170
|
+
return streamFile(req, res, opened, media[1]);
|
|
171
|
+
}
|
|
172
|
+
try {
|
|
173
|
+
if (pathname === '/api/file-preview') {
|
|
174
|
+
return sendJson(res, 200, { ok: true, ...filePreview(opened, splitFileReference(raw)) });
|
|
175
|
+
}
|
|
176
|
+
if (!openUrl(real)) return sendJson(res, 500, { error: 'could not open the file' });
|
|
177
|
+
sendJson(res, 200, { ok: true, path: target, name: path.basename(target) });
|
|
178
|
+
} finally {
|
|
179
|
+
closeOpened(opened);
|
|
180
|
+
}
|
|
181
|
+
}
|
package/src/server/http.js
CHANGED
|
@@ -4,16 +4,25 @@ import path from 'node:path';
|
|
|
4
4
|
|
|
5
5
|
const PROXY_HEADERS = ['forwarded', 'x-forwarded-for', 'x-forwarded-host', 'x-forwarded-proto', 'x-real-ip'];
|
|
6
6
|
|
|
7
|
-
// Security:
|
|
8
|
-
//
|
|
9
|
-
//
|
|
10
|
-
//
|
|
7
|
+
// Security: the board listens on every interface, and Host is the caller's to
|
|
8
|
+
// write, so the owner must also arrive on a loopback socket. A local reverse
|
|
9
|
+
// proxy can send a loopback Host (a link gateway sends `Host: localhost:PORT`),
|
|
10
|
+
// so a request carrying proxy headers is never the tokenless owner. A proxy that
|
|
11
|
+
// adds none is covered by the control token runBoard requires for the owner
|
|
12
|
+
// while a link is set.
|
|
11
13
|
export function isDirectLocalRequest(req) {
|
|
14
|
+
if (!isLoopbackAddress(req.socket?.remoteAddress)) return false;
|
|
12
15
|
const host = String(req.headers.host || '').split(':')[0];
|
|
13
16
|
if (host !== '127.0.0.1' && host !== 'localhost') return false;
|
|
14
17
|
return !PROXY_HEADERS.some((name) => req.headers[name] !== undefined);
|
|
15
18
|
}
|
|
16
19
|
|
|
20
|
+
/** True for 127.0.0.0/8 and ::1, including the IPv4-mapped form a dual-stack socket reports. */
|
|
21
|
+
export function isLoopbackAddress(address) {
|
|
22
|
+
const a = String(address || '').replace(/^::ffff:/i, '');
|
|
23
|
+
return a === '::1' || /^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(a);
|
|
24
|
+
}
|
|
25
|
+
|
|
17
26
|
// True when an Origin header (if present) belongs to this board's own server.
|
|
18
27
|
// Same-origin fetches send no Origin or our own; a foreign Origin is a
|
|
19
28
|
// cross-site POST and must not be allowed to open a local file.
|
package/src/spec/blocks/image.js
CHANGED
|
@@ -1,7 +1,6 @@
|
|
|
1
1
|
// The image block, and the image reader that compare blocks share.
|
|
2
|
-
import fs from 'node:fs';
|
|
3
2
|
import path from 'node:path';
|
|
4
|
-
import {
|
|
3
|
+
import { readReadable } from '../../file-access.js';
|
|
5
4
|
import { CliError } from '../../util.js';
|
|
6
5
|
import { asStr, clampInt } from '../sources.js';
|
|
7
6
|
import { BLOCK_HEIGHT, IMAGE_MAX_BYTES, IMAGE_MIMES } from '../constants.js';
|
|
@@ -16,9 +15,7 @@ export function resolveImageSrc(srcRaw, files, where, field) {
|
|
|
16
15
|
const ext = path.extname(src).slice(1).toLowerCase();
|
|
17
16
|
const mime = IMAGE_MIMES[ext];
|
|
18
17
|
if (!mime) throw new CliError(`${where}: ${field}: unsupported image extension ".${ext}" — use ${Object.keys(IMAGE_MIMES).join('/')}, or an http(s)/data URL.`);
|
|
19
|
-
const {
|
|
20
|
-
let buf;
|
|
21
|
-
try { buf = fs.readFileSync(p); } catch { throw new CliError(`${where}: ${field}: cannot read image "${src}" (resolved: ${p})`); }
|
|
18
|
+
const { buf } = readReadable(files, src, where, field);
|
|
22
19
|
if (buf.length > IMAGE_MAX_BYTES) throw new CliError(`${where}: ${field}: image "${src}" is ${(buf.length / 1024 / 1024).toFixed(1)}MB — max ${IMAGE_MAX_BYTES / 1024 / 1024}MB.`);
|
|
23
20
|
return `data:${mime};base64,${buf.toString('base64')}`;
|
|
24
21
|
}
|
package/src/spec/blocks/table.js
CHANGED
|
@@ -1,7 +1,6 @@
|
|
|
1
1
|
// The table block: CSV, TSV and JSON row files, and normalization.
|
|
2
|
-
import fs from 'node:fs';
|
|
3
2
|
import path from 'node:path';
|
|
4
|
-
import {
|
|
3
|
+
import { readReadable } from '../../file-access.js';
|
|
5
4
|
import { CliError } from '../../util.js';
|
|
6
5
|
import { BLOCK_HEIGHT, TEXT_FILE_MAX_BYTES } from '../constants.js';
|
|
7
6
|
import { asStr, clampInt } from '../sources.js';
|
|
@@ -40,9 +39,7 @@ function parseDelimited(text, delim) {
|
|
|
40
39
|
// CSV/TSV: first row = header → column keys. JSON: an array of objects (columns
|
|
41
40
|
// from the union of keys) or arrays (needs explicit "columns").
|
|
42
41
|
function loadRowsFile(file, files, where) {
|
|
43
|
-
const { file: p } =
|
|
44
|
-
let buf;
|
|
45
|
-
try { buf = fs.readFileSync(p); } catch { throw new CliError(`${where}: cannot read rowsFile "${file}" (resolved: ${p})`); }
|
|
42
|
+
const { file: p, buf } = readReadable(files, file, where, 'rowsFile');
|
|
46
43
|
if (buf.length > TEXT_FILE_MAX_BYTES) {
|
|
47
44
|
throw new CliError(`${where}: rowsFile "${file}" is ${(buf.length / 1024).toFixed(0)}KB — max ${TEXT_FILE_MAX_BYTES / 1024}KB.`);
|
|
48
45
|
}
|
package/src/spec/sources.js
CHANGED
|
@@ -1,6 +1,5 @@
|
|
|
1
1
|
// Readers for text that a block takes inline or from a file next to the spec.
|
|
2
|
-
import
|
|
3
|
-
import { resolveReadable } from '../file-access.js';
|
|
2
|
+
import { readReadable } from '../file-access.js';
|
|
4
3
|
import { CliError } from '../util.js';
|
|
5
4
|
import { TEXT_FILE_MAX_BYTES } from './constants.js';
|
|
6
5
|
|
|
@@ -26,12 +25,7 @@ export function readBlockHtml(block, files, where) {
|
|
|
26
25
|
|
|
27
26
|
function readHtmlFile(obj, files, where) {
|
|
28
27
|
if (typeof obj.htmlFile !== 'string' || !obj.htmlFile.trim()) return '';
|
|
29
|
-
|
|
30
|
-
try {
|
|
31
|
-
return fs.readFileSync(file, 'utf8');
|
|
32
|
-
} catch {
|
|
33
|
-
throw new CliError(`${where}: cannot read htmlFile "${obj.htmlFile}" (resolved: ${file})`);
|
|
34
|
-
}
|
|
28
|
+
return readReadable(files, obj.htmlFile, where, 'htmlFile').buf.toString('utf8');
|
|
35
29
|
}
|
|
36
30
|
|
|
37
31
|
// Reads a code/diff block body from an inline string field or a local file.
|
|
@@ -40,13 +34,7 @@ function readHtmlFile(obj, files, where) {
|
|
|
40
34
|
export function readTextSource(block, inlineKey, fileKey, files, where) {
|
|
41
35
|
if (typeof block[inlineKey] === 'string' && block[inlineKey] !== '') return block[inlineKey];
|
|
42
36
|
if (typeof block[fileKey] === 'string' && block[fileKey].trim()) {
|
|
43
|
-
const {
|
|
44
|
-
let buf;
|
|
45
|
-
try {
|
|
46
|
-
buf = fs.readFileSync(p);
|
|
47
|
-
} catch {
|
|
48
|
-
throw new CliError(`${where}: cannot read ${fileKey} "${block[fileKey]}" (resolved: ${p})`);
|
|
49
|
-
}
|
|
37
|
+
const { buf } = readReadable(files, block[fileKey], where, fileKey);
|
|
50
38
|
if (buf.length > TEXT_FILE_MAX_BYTES) {
|
|
51
39
|
throw new CliError(`${where}: ${fileKey} "${block[fileKey]}" is ${(buf.length / 1024).toFixed(0)}KB — max ${TEXT_FILE_MAX_BYTES / 1024}KB.`);
|
|
52
40
|
}
|
|
@@ -61,13 +49,7 @@ export function readAnyTextSource(block, inlineKeys, fileKeys, files, where, lab
|
|
|
61
49
|
}
|
|
62
50
|
for (const key of fileKeys) {
|
|
63
51
|
if (typeof block[key] === 'string' && block[key].trim()) {
|
|
64
|
-
const { file: p } =
|
|
65
|
-
let buf;
|
|
66
|
-
try {
|
|
67
|
-
buf = fs.readFileSync(p);
|
|
68
|
-
} catch {
|
|
69
|
-
throw new CliError(`${where}: cannot read ${label} "${block[key]}" (resolved: ${p})`);
|
|
70
|
-
}
|
|
52
|
+
const { file: p, buf } = readReadable(files, block[key], where, label);
|
|
71
53
|
if (buf.length > TEXT_FILE_MAX_BYTES) {
|
|
72
54
|
throw new CliError(`${where}: ${label} "${block[key]}" is ${(buf.length / 1024).toFixed(0)}KB — max ${TEXT_FILE_MAX_BYTES / 1024}KB.`);
|
|
73
55
|
}
|
package/src/store.js
CHANGED
|
@@ -2,6 +2,7 @@ import fs from 'node:fs';
|
|
|
2
2
|
import path from 'node:path';
|
|
3
3
|
import os from 'node:os';
|
|
4
4
|
import crypto from 'node:crypto';
|
|
5
|
+
import { pruneBoards, resolveRetentionDays } from './retention.js';
|
|
5
6
|
|
|
6
7
|
// All state lives under one dir so multiple boards/instances never collide.
|
|
7
8
|
// RLY_HOME override exists for tests and sandboxed agents.
|
|
@@ -20,6 +21,21 @@ export function newId() {
|
|
|
20
21
|
return `b-${t}${r}`;
|
|
21
22
|
}
|
|
22
23
|
|
|
24
|
+
/**
|
|
25
|
+
* Writes through a temp file in the same folder and renames it over the target,
|
|
26
|
+
* so a crash mid-write leaves the old file, never half a new one.
|
|
27
|
+
*/
|
|
28
|
+
function writeFileAtomic(file, data) {
|
|
29
|
+
const temp = `${file}.${process.pid}.${crypto.randomBytes(4).toString('hex')}.tmp`;
|
|
30
|
+
try {
|
|
31
|
+
fs.writeFileSync(temp, data);
|
|
32
|
+
fs.renameSync(temp, file);
|
|
33
|
+
} catch (err) {
|
|
34
|
+
try { fs.unlinkSync(temp); } catch { /* never written */ }
|
|
35
|
+
throw err;
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
|
|
23
39
|
const boardPath = (id) => path.join(BOARDS_DIR, `${id}.json`);
|
|
24
40
|
const runningPath = (id) => path.join(RUNNING_DIR, `${id}.json`);
|
|
25
41
|
export const artifactDirPath = (id) => path.join(BOARDS_DIR, `${id}.artifacts`);
|
|
@@ -36,11 +52,16 @@ export function saveBoardArtifact(id, bytes, ext = 'png') {
|
|
|
36
52
|
return target;
|
|
37
53
|
}
|
|
38
54
|
|
|
55
|
+
/** The roots a stored board was created under; a board saved before roots existed keeps its authoring folder. */
|
|
56
|
+
export function boardFileRoots(record) {
|
|
57
|
+
return Array.isArray(record.fileRoots) ? record.fileRoots : [record.cwd || process.cwd()];
|
|
58
|
+
}
|
|
59
|
+
|
|
39
60
|
/**
|
|
40
61
|
* @param {any} spec a normalized spec
|
|
41
|
-
* @param {{ fileRoots?: string[] }} [options] the roots the spec was read under; the live server opens only files inside them
|
|
62
|
+
* @param {{ fileRoots?: string[], retentionDays?: number | string | boolean }} [options] `fileRoots`: the roots the spec was read under; the live server opens only files inside them. `retentionDays`: how long old boards stay (see `resolveRetentionDays`)
|
|
42
63
|
*/
|
|
43
|
-
export function createBoard(spec, { fileRoots } = {}) {
|
|
64
|
+
export function createBoard(spec, { fileRoots, retentionDays } = {}) {
|
|
44
65
|
ensureDirs();
|
|
45
66
|
const record = {
|
|
46
67
|
id: newId(),
|
|
@@ -56,12 +77,33 @@ export function createBoard(spec, { fileRoots } = {}) {
|
|
|
56
77
|
result: null,
|
|
57
78
|
};
|
|
58
79
|
saveBoard(record);
|
|
80
|
+
pruneOldBoards(resolveRetentionDays(retentionDays));
|
|
59
81
|
return record;
|
|
60
82
|
}
|
|
61
83
|
|
|
84
|
+
/**
|
|
85
|
+
* Removes boards unchanged for `days`, except those a live server still serves.
|
|
86
|
+
* A failed sweep never blocks the board being created, so errors stay here.
|
|
87
|
+
* @returns {string[]} the ids removed
|
|
88
|
+
*/
|
|
89
|
+
export function pruneOldBoards(days, { force = false } = {}) {
|
|
90
|
+
try {
|
|
91
|
+
return pruneBoards({
|
|
92
|
+
home: HOME,
|
|
93
|
+
boardsDir: BOARDS_DIR,
|
|
94
|
+
days,
|
|
95
|
+
keep: new Set(listRunning().map((r) => r.id)),
|
|
96
|
+
remove: deleteBoard,
|
|
97
|
+
force,
|
|
98
|
+
});
|
|
99
|
+
} catch {
|
|
100
|
+
return [];
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
|
|
62
104
|
export function saveBoard(record) {
|
|
63
105
|
ensureDirs();
|
|
64
|
-
|
|
106
|
+
writeFileAtomic(boardPath(record.id), JSON.stringify(record, null, 2));
|
|
65
107
|
}
|
|
66
108
|
|
|
67
109
|
export function loadBoard(id) {
|
|
@@ -80,7 +122,7 @@ export function saveResultFile(id, result) {
|
|
|
80
122
|
try {
|
|
81
123
|
ensureDirs();
|
|
82
124
|
const p = path.join(BOARDS_DIR, `${id}.result.json`);
|
|
83
|
-
|
|
125
|
+
writeFileAtomic(p, JSON.stringify(result, null, 2));
|
|
84
126
|
return p;
|
|
85
127
|
} catch {
|
|
86
128
|
return null;
|
|
@@ -115,7 +157,7 @@ export function listBoards(limit = 20) {
|
|
|
115
157
|
|
|
116
158
|
export function saveRunning(info) {
|
|
117
159
|
ensureDirs();
|
|
118
|
-
|
|
160
|
+
writeFileAtomic(runningPath(info.id), JSON.stringify(info, null, 2));
|
|
119
161
|
}
|
|
120
162
|
|
|
121
163
|
export function loadRunning(id) {
|
|
@@ -154,7 +196,7 @@ export function loadPref() {
|
|
|
154
196
|
|
|
155
197
|
export function savePref(patch) {
|
|
156
198
|
ensureDirs();
|
|
157
|
-
|
|
199
|
+
writeFileAtomic(prefPath(), JSON.stringify({ ...loadPref(), ...patch }, null, 2));
|
|
158
200
|
}
|
|
159
201
|
|
|
160
202
|
export function isAlive(pid) {
|
package/src/ui/manifest.js
CHANGED
package/types/file-access.d.ts
CHANGED
|
@@ -20,6 +20,12 @@ export declare const FILE_ROOTS_ENV = "RLY_FILE_ROOTS";
|
|
|
20
20
|
export declare function expandHome(p: any): any;
|
|
21
21
|
/** Real paths of the roots that exist; a root that does not exist grants nothing. */
|
|
22
22
|
export declare function realRoots(list: any, cwd: any): any[];
|
|
23
|
+
/**
|
|
24
|
+
* True when `dir` is a filesystem root or the home directory. Such a folder is
|
|
25
|
+
* too wide to grant by default: a desktop host often starts a stdio server at
|
|
26
|
+
* `/`, which would let a spec read the whole disk. Passing it as `--root` still works.
|
|
27
|
+
*/
|
|
28
|
+
export declare function isBroadRoot(dir: any): boolean;
|
|
23
29
|
/** Roots named by `RLY_FILE_ROOTS`. */
|
|
24
30
|
export declare function envFileRoots(env?: NodeJS.ProcessEnv): string[];
|
|
25
31
|
/**
|
|
@@ -37,7 +43,7 @@ export declare function isInsideRoots(target: any, roots: any): any;
|
|
|
37
43
|
* @param {FileAccess} access
|
|
38
44
|
* @param {unknown} raw the path as written; `~` and relative paths are expanded
|
|
39
45
|
* @param {{ allowDirectory?: boolean }} [options] directories are refused unless a caller opens them in an app
|
|
40
|
-
* @returns {{ ok: boolean, file?: string, stat?: fs.Stats, reason?: 'invalid' | 'outside' | 'missing' | 'not-file'
|
|
46
|
+
* @returns {{ ok: boolean, file?: string, stat?: fs.Stats, reason?: 'invalid' | 'outside' | 'missing' | 'not-file' | 'changed' }} `file` and `stat` when ok; otherwise the `reason`, which callers keep to themselves
|
|
41
47
|
*/
|
|
42
48
|
export declare function checkReadable(access: FileAccess, raw: unknown, { allowDirectory }?: {
|
|
43
49
|
allowDirectory?: boolean;
|
|
@@ -45,11 +51,32 @@ export declare function checkReadable(access: FileAccess, raw: unknown, { allowD
|
|
|
45
51
|
ok: boolean;
|
|
46
52
|
file?: string;
|
|
47
53
|
stat?: fs.Stats;
|
|
48
|
-
reason?: 'invalid' | 'outside' | 'missing' | 'not-file';
|
|
49
|
-
|
|
54
|
+
reason?: 'invalid' | 'outside' | 'missing' | 'not-file' | 'changed';
|
|
55
|
+
};
|
|
56
|
+
/**
|
|
57
|
+
* Like `checkReadable`, but also opens a regular file, and keeps the open
|
|
58
|
+
* descriptor as the only way to read it. A path checked and then read by name
|
|
59
|
+
* can be swapped for a symlink in between; the descriptor cannot. After the
|
|
60
|
+
* open, the path must still resolve to the same file inside the roots, or the
|
|
61
|
+
* read is refused. A directory (when allowed) comes back with `fd: null`.
|
|
62
|
+
* The caller closes `fd`, or hands it to `streamFile`, which does.
|
|
63
|
+
* @param {FileAccess} access
|
|
64
|
+
* @param {unknown} raw
|
|
65
|
+
* @param {{ allowDirectory?: boolean }} [options]
|
|
66
|
+
* @returns {{ ok: boolean, file?: string, stat?: fs.Stats, fd?: number | null, reason?: 'invalid' | 'outside' | 'missing' | 'not-file' | 'changed' }}
|
|
67
|
+
*/
|
|
68
|
+
export declare function openReadable(access: FileAccess, raw: unknown, options?: {
|
|
69
|
+
allowDirectory?: boolean;
|
|
70
|
+
}): {
|
|
71
|
+
ok: boolean;
|
|
72
|
+
file?: string;
|
|
73
|
+
stat?: fs.Stats;
|
|
74
|
+
fd?: number | null;
|
|
75
|
+
reason?: 'invalid' | 'outside' | 'missing' | 'not-file' | 'changed';
|
|
50
76
|
};
|
|
51
77
|
/**
|
|
52
78
|
* The real path of a file a spec names, or a CliError worded for the agent.
|
|
79
|
+
* Use `readReadable` to read it.
|
|
53
80
|
* @param {FileAccess} access
|
|
54
81
|
* @param {unknown} raw
|
|
55
82
|
* @param {string} where which block, e.g. `board.blocks[0]`
|
|
@@ -60,3 +87,16 @@ export declare function resolveReadable(access: FileAccess, raw: unknown, where:
|
|
|
60
87
|
file: string;
|
|
61
88
|
stat: fs.Stats;
|
|
62
89
|
};
|
|
90
|
+
/**
|
|
91
|
+
* The bytes of a file a spec names, read through one opened descriptor.
|
|
92
|
+
* @param {FileAccess} access
|
|
93
|
+
* @param {unknown} raw
|
|
94
|
+
* @param {string} where which block, e.g. `board.blocks[0]`
|
|
95
|
+
* @param {string} field which field, e.g. `codeFile`
|
|
96
|
+
* @returns {{ file: string, stat: fs.Stats, buf: Buffer }}
|
|
97
|
+
*/
|
|
98
|
+
export declare function readReadable(access: FileAccess, raw: unknown, where: string, field: string): {
|
|
99
|
+
file: string;
|
|
100
|
+
stat: fs.Stats;
|
|
101
|
+
buf: Buffer;
|
|
102
|
+
};
|