@khanglvm/relay 0.22.0 → 0.22.2

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 (53) hide show
  1. package/docs/AGENT.md +4 -1
  2. package/package.json +2 -2
  3. package/src/cli/args.js +4 -2
  4. package/src/cli/ask.js +4 -3
  5. package/src/cli/boards.js +11 -7
  6. package/src/cli/git.js +5 -3
  7. package/src/cli/help.js +3 -1
  8. package/src/cli/io.js +21 -0
  9. package/src/cli/mcp.js +20 -1
  10. package/src/file-access.js +129 -0
  11. package/src/file-preview.js +1 -1
  12. package/src/mcp/boards.js +4 -3
  13. package/src/mcp/serve.js +4 -4
  14. package/src/mcp/store.js +2 -2
  15. package/src/mcp/tools.js +2 -1
  16. package/src/server/board.js +25 -13
  17. package/src/server/files.js +7 -0
  18. package/src/server/http.js +13 -4
  19. package/src/spec/blocks/a2ui.js +1 -1
  20. package/src/spec/blocks/chart.js +1 -1
  21. package/src/spec/blocks/code.js +4 -4
  22. package/src/spec/blocks/diagram.js +3 -3
  23. package/src/spec/blocks/git-conflict.js +2 -2
  24. package/src/spec/blocks/image.js +6 -5
  25. package/src/spec/blocks/markdown.js +2 -2
  26. package/src/spec/blocks/pdf.js +4 -10
  27. package/src/spec/blocks/table.js +5 -4
  28. package/src/spec/blocks/video.js +4 -10
  29. package/src/spec/blocks/widgets.js +6 -6
  30. package/src/spec/normalize.js +18 -11
  31. package/src/spec/pick.js +4 -4
  32. package/src/spec/sources.js +19 -24
  33. package/src/store.js +11 -1
  34. package/types/file-access.d.ts +68 -0
  35. package/types/mcp/boards.d.ts +2 -1
  36. package/types/mcp/serve.d.ts +5 -2
  37. package/types/mcp/store.d.ts +6 -3
  38. package/types/mcp/tools.d.ts +2 -0
  39. package/types/spec/blocks/a2ui.d.ts +1 -1
  40. package/types/spec/blocks/chart.d.ts +1 -1
  41. package/types/spec/blocks/code.d.ts +2 -2
  42. package/types/spec/blocks/diagram.d.ts +3 -3
  43. package/types/spec/blocks/git-conflict.d.ts +1 -1
  44. package/types/spec/blocks/image.d.ts +2 -2
  45. package/types/spec/blocks/markdown.d.ts +1 -1
  46. package/types/spec/blocks/pdf.d.ts +1 -1
  47. package/types/spec/blocks/table.d.ts +1 -1
  48. package/types/spec/blocks/video.d.ts +1 -1
  49. package/types/spec/blocks/widgets.d.ts +4 -4
  50. package/types/spec/normalize.d.ts +7 -1
  51. package/types/spec/pick.d.ts +1 -1
  52. package/types/spec/sources.d.ts +5 -4
  53. package/types/store.d.ts +10 -1
package/docs/AGENT.md CHANGED
@@ -148,7 +148,7 @@ Tools:
148
148
 
149
149
  The flow: call `relay_board`, tell the person the board is on screen, and carry on or wait. When they submit, the host posts a one-line message naming the board. Read the answers with `relay_result`. Do not ask the same questions again in chat.
150
150
 
151
- `rly mcp` speaks stdio to a local desktop host. `rly mcp --http [--port N] [--token-file PATH] [--allow-origin ORIGIN]` serves Streamable HTTP at `/mcp` for hosts that connect over a network. The bearer token comes from `--token-file`, `RLY_MCP_TOKEN` or `--token`; the flag shows in `ps`, so prefer the file or the variable. Boards are stored in the relay home of the machine that runs the server, so `codeFile` and local images resolve there and nowhere else. A host that draws A2UI can show the whole board natively instead of the iframe. It declares the board catalog, `https://github.com/khanglvm/relay/a2ui/catalog/board/v1`, under `extensions.a2ui["1.0"].supportedCatalogIds` when it connects, or per call in `_meta.a2ui`; the call wins over the connection. `relay_view` then returns the board as A2UI messages (`application/a2ui+json`, `application/json+a2ui` is accepted when declared) and the host sends button events to `a2ui_action` with the surface's data model. The catalog is `src/a2ui/board-catalog.json`; `toA2ui(spec)` and `fromA2ui(dataModel, spec)` from `@khanglvm/relay/a2ui-board` convert in both directions, and the result matches what the web board stores. Hosts that did not declare it keep the iframe.
151
+ `rly mcp` speaks stdio to a local desktop host. `rly mcp --http [--port N] [--token-file PATH] [--allow-origin ORIGIN]` serves Streamable HTTP at `/mcp` for hosts that connect over a network. The bearer token comes from `--token-file`, `RLY_MCP_TOKEN` or `--token`; the flag shows in `ps`, so prefer the file or the variable. Boards are stored in the relay home of the machine that runs the server, so `codeFile` and local images resolve there and nowhere else, and only under the server's file roots: none over HTTP unless the operator passes `--root PATH` (repeatable) or `RLY_FILE_ROOTS`, the working directory over stdio (but not when it is `/` or the home directory, where desktop hosts often start it). A host that draws A2UI can show the whole board natively instead of the iframe. It declares the board catalog, `https://github.com/khanglvm/relay/a2ui/catalog/board/v1`, under `extensions.a2ui["1.0"].supportedCatalogIds` when it connects, or per call in `_meta.a2ui`; the call wins over the connection. `relay_view` then returns the board as A2UI messages (`application/a2ui+json`, `application/json+a2ui` is accepted when declared) and the host sends button events to `a2ui_action` with the surface's data model. The catalog is `src/a2ui/board-catalog.json`; `toA2ui(spec)` and `fromA2ui(dataModel, spec)` from `@khanglvm/relay/a2ui-board` convert in both directions, and the result matches what the web board stores. Hosts that did not declare it keep the iframe.
152
152
 
153
153
  To add the tools to a server you already run, call `registerRelay(server, {store, assetUrl, linkUrl})` from `@khanglvm/relay/mcp`.
154
154
 
@@ -837,6 +837,9 @@ ignored. A small toast "Board updated by the agent" appears for 4 seconds.
837
837
 
838
838
  Stdout: `{"status":"updated","boardId":"…","rev":2,"url":"…"}`.
839
839
 
840
+ The new spec reads local files only under the roots the board was created with;
841
+ `--root` is refused on update, so start a new board with `rly ask --root PATH` to read elsewhere.
842
+
840
843
  **Caution:** the page reloads for the user. Batch your changes into one `rly update`
841
844
  call rather than calling it repeatedly in a loop.
842
845
 
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@khanglvm/relay",
3
- "version": "0.22.0",
4
- "description": "Question boards with rich blocks (markdown, charts, mermaid, tables, code, diffs, video, sandboxed HTML), clickable local file-links, and element-level annotations for AI coding agents (Claude Code, Codex, \u2026): ask users structured questions, present interactive visuals, collect inline comments, read answers as JSON \u2014 in a local browser board OR rendered INLINE inside the Claude & Codex apps as an MCP App (SEP-1865).",
3
+ "version": "0.22.2",
4
+ "description": "Question boards with rich blocks (markdown, charts, mermaid, tables, code, diffs, video, sandboxed HTML), clickable local file-links, and element-level annotations for AI coding agents (Claude Code, Codex, …): ask users structured questions, present interactive visuals, collect inline comments, read answers as JSON — in a local browser board OR rendered INLINE inside the Claude & Codex apps as an MCP App (SEP-1865).",
5
5
  "keywords": [
6
6
  "ai-agents",
7
7
  "claude-code",
package/src/cli/args.js CHANGED
@@ -5,7 +5,7 @@ const VALUED_FLAGS = new Set([
5
5
  'file', 'html', 'html-file', 'title', 'intro', 'timeout', 'port',
6
6
  'submit-label', 'height', 'limit', 'target', 'id', 'replies',
7
7
  'on-result', 'notify-cmd', 'idle-grace', 'scope', 'range',
8
- 'host', 'token', 'token-file', 'allow-origin', 'role', 'public-url', 'link', 'link-command',
8
+ 'host', 'token', 'token-file', 'root', 'allow-origin', 'role', 'public-url', 'link', 'link-command',
9
9
  ]);
10
10
 
11
11
  function camel(key) {
@@ -13,7 +13,7 @@ function camel(key) {
13
13
  }
14
14
 
15
15
  export function parseArgs(argv) {
16
- const args = { _: [], q: [] };
16
+ const args = { _: [], q: [], root: [] };
17
17
  for (let i = 0; i < argv.length; i++) {
18
18
  const t = argv[i];
19
19
  if (t === '-q' || t === '--question') {
@@ -35,6 +35,8 @@ export function parseArgs(argv) {
35
35
  }
36
36
  if (key === 'no-open') {
37
37
  args.open = false;
38
+ } else if (key === 'root') {
39
+ args.root.push(val);
38
40
  } else {
39
41
  args[camel(key)] = val;
40
42
  }
package/src/cli/ask.js CHANGED
@@ -1,12 +1,13 @@
1
1
  // rly ask: build a board from a spec and serve it.
2
2
  import { assertSpecReady, normalizeSpec } from '../spec/index.js';
3
3
  import { createBoard } from '../store.js';
4
- import { resolveSpecInput, runOrDetach } from './io.js';
4
+ import { cliFileRoots, resolveSpecInput, runOrDetach } from './io.js';
5
5
 
6
6
  export async function cmdAsk(args, mode) {
7
7
  const raw = await resolveSpecInput(args, mode);
8
- const spec = normalizeSpec(raw);
8
+ const fileRoots = cliFileRoots(args);
9
+ const spec = normalizeSpec(raw, { fileRoots });
9
10
  await assertSpecReady(spec);
10
- const record = createBoard(spec);
11
+ const record = createBoard(spec, { fileRoots });
11
12
  return runOrDetach(record, spec.responseRequired === false ? { ...args, detach: true } : args);
12
13
  }
package/src/cli/boards.js CHANGED
@@ -2,9 +2,9 @@
2
2
  import path from 'node:path';
3
3
  import { openUrl } from '../open.js';
4
4
  import { assertSpecReady, normalizeSpec, questionFromInline } from '../spec/index.js';
5
- import { HOME, controlUrl, createBoard, deleteBoard, isAlive, listBoards, listRunning, loadBoard, loadRunning, removeRunning, saveBoard } from '../store.js';
5
+ import { HOME, boardFileRoots, controlUrl, createBoard, deleteBoard, isAlive, listBoards, listRunning, loadBoard, loadRunning, removeRunning, saveBoard } from '../store.js';
6
6
  import { CliError, pollFor } from '../util.js';
7
- import { mustLoad, parseJson, printJson, readFileOrThrow, readStdin, runOrDetach } from './io.js';
7
+ import { cliFileRoots, mustLoad, parseJson, printJson, readFileOrThrow, readStdin, runOrDetach } from './io.js';
8
8
 
9
9
  // `rly view <file.md> [more.md …]` — quick read-only board that renders files
10
10
  // with purpose-built blocks (markdown, data tables, PDF). With 2+ files a small
@@ -25,9 +25,11 @@ export async function cmdView(args) {
25
25
  const raw = { blocks };
26
26
  raw.title = args.title || (multi ? `${files.length} files` : path.basename(files[0]));
27
27
  raw.submitLabel = args.submitLabel || 'Done';
28
- const spec = normalizeSpec(raw); // reads + validates each file, clear error if unreadable
28
+ // The files were named on the command line, so their folders are allowed.
29
+ const fileRoots = cliFileRoots(args, files.map((f) => path.dirname(f)));
30
+ const spec = normalizeSpec(raw, { fileRoots }); // reads + validates each file, clear error if unreadable
29
31
  await assertSpecReady(spec);
30
- const record = createBoard(spec);
32
+ const record = createBoard(spec, { fileRoots });
31
33
  return runOrDetach(record, args);
32
34
  }
33
35
 
@@ -137,7 +139,7 @@ export async function cmdReuse(args) {
137
139
  console.log(JSON.stringify(src.spec, null, 2));
138
140
  return 0;
139
141
  }
140
- const record = createBoard(src.spec);
142
+ const record = createBoard(src.spec, { fileRoots: boardFileRoots(src) });
141
143
  return runOrDetach(record, args);
142
144
  }
143
145
 
@@ -154,13 +156,15 @@ export async function cmdUpdate(args) {
154
156
  throw new CliError(`board "${id}" is not running — \`rly reopen ${id}\` to serve it, then update.`, 5);
155
157
  }
156
158
 
159
+ if (args.root.length) throw new CliError('update cannot add file roots: they are set when the board is created. Start a new board with `rly ask --root PATH`.', 4);
160
+ const fileRoots = boardFileRoots(record);
157
161
  let spec;
158
162
  if (args.file) {
159
163
  const raw =
160
164
  args.file === '-'
161
165
  ? parseJson(await readStdin(), 'stdin')
162
166
  : parseJson(readFileOrThrow(args.file), args.file);
163
- spec = normalizeSpec(raw);
167
+ spec = normalizeSpec(raw, { fileRoots });
164
168
  } else if (args.title || args.intro || args.q.length) {
165
169
  // Patch the CURRENT spec, then re-normalize so it's a clean normalized spec.
166
170
  const raw = { ...record.spec };
@@ -169,7 +173,7 @@ export async function cmdUpdate(args) {
169
173
  if (args.q.length) {
170
174
  raw.questions = [...(raw.questions || []), ...args.q.map((s, i) => questionFromInline(s, i))];
171
175
  }
172
- spec = normalizeSpec(raw);
176
+ spec = normalizeSpec(raw, { fileRoots });
173
177
  } else {
174
178
  throw new CliError('update needs --file <spec.json>, --title, --intro, or -q "...".', 4);
175
179
  }
package/src/cli/git.js CHANGED
@@ -6,7 +6,7 @@ import { assertSpecReady, normalizeSpec } from '../spec/index.js';
6
6
  import { createBoard } from '../store.js';
7
7
  import { CliError } from '../util.js';
8
8
  import { parseArgs } from './args.js';
9
- import { printJson, runOrDetach } from './io.js';
9
+ import { cliFileRoots, printJson, runOrDetach } from './io.js';
10
10
 
11
11
  // `rly diff [git args…]` — run `git diff` for the user and open the result as a
12
12
  // diff-block board in one step (sugar like `rly view`). Everything that isn't a
@@ -176,8 +176,10 @@ export async function cmdGit(rest) {
176
176
  : reviewDiffCount
177
177
  ? 'Review commit code hunks on the board. Apply, skip, or hold each hunk; submit returns commit actions plus diff-review hunk choices as JSON.'
178
178
  : 'Pick commit actions and order on the board. Submit returns the selected actions and rank order as JSON.');
179
- const spec = normalizeSpec({ title, intro, blocks, questions, submitLabel: 'Submit git choices' });
179
+ // Conflict files named on the command line are the person's own choice.
180
+ const fileRoots = cliFileRoots(args, args._.map((p) => path.dirname(p)));
181
+ const spec = normalizeSpec({ title, intro, blocks, questions, submitLabel: 'Submit git choices' }, { fileRoots });
180
182
  await assertSpecReady(spec);
181
- const record = createBoard(spec);
183
+ const record = createBoard(spec, { fileRoots });
182
184
  return runOrDetach(record, args);
183
185
  }
package/src/cli/help.js CHANGED
@@ -52,7 +52,8 @@ USAGE
52
52
  disconnected browser tab auto-reconnects & re-saves (no new tab
53
53
  unless --open). Use when a tab shows "connection lost".
54
54
  rly reuse <id> [--dump] re-run a past board as a new board (--dump prints its spec)
55
- rly update <id> --file spec.json live-mutate a RUNNING board (or --title/--intro/-q); page reloads
55
+ rly update <id> --file spec.json live-mutate a RUNNING board (or --title/--intro/-q); page reloads;
56
+ files are read under the roots the board was created with
56
57
  rly stop <id> | --all stop running board(s) (status: cancelled, draft preserved)
57
58
  rly history [--limit n] [--json] saved boards
58
59
  rly spec <id> print a saved board's spec JSON (edit, then ask --file again)
@@ -71,6 +72,7 @@ USAGE
71
72
  a local desktop host (Claude Desktop, Codex) instead of a browser tab
72
73
  rly mcp --http [--port N] serve over Streamable HTTP for web/mobile/remote hosts
73
74
  [--host H --token-file PATH --allow-origin ORIGIN]
75
+ [--root PATH ...] folders a spec may read local files from (none by default over HTTP; also $RLY_FILE_ROOTS)
74
76
  (token: --token-file, $RLY_MCP_TOKEN, or --token, which shows in the process list)
75
77
  rly mcp config | install --target print host setup, or write it (claude | codex)
76
78
 
package/src/cli/io.js CHANGED
@@ -2,6 +2,7 @@
2
2
  import { spawn } from 'node:child_process';
3
3
  import fs from 'node:fs';
4
4
  import path from 'node:path';
5
+ import { envFileRoots, expandHome } from '../file-access.js';
5
6
  import { linkSetting, loadConfig, serializeLink } from '../link.js';
6
7
  import { runBoard } from '../server/index.js';
7
8
  import { assertSpecReady, questionFromInline } from '../spec/index.js';
@@ -9,6 +10,26 @@ import { HOME, loadBoard, loadRunning, saveBoard, saveResultFile } from '../stor
9
10
  import { CliError, pollFor } from '../util.js';
10
11
  import { BIN, DEFAULT_BOARD_TIMEOUT_SEC } from './context.js';
11
12
 
13
+ /**
14
+ * The directories a CLI-built spec may read local files from: where the person
15
+ * ran the command, the spec file's directory, the `--html-file` directory, every
16
+ * `--root`, `$RLY_FILE_ROOTS`, and `extra` for paths the command itself was given.
17
+ * @param {Record<string, any>} args parsed flags
18
+ * @param {string[]} [extra]
19
+ * @returns {string[]} absolute paths
20
+ */
21
+ export function cliFileRoots(args, extra = []) {
22
+ const given = [
23
+ process.cwd(),
24
+ args.file && args.file !== '-' ? path.dirname(args.file) : '',
25
+ typeof args.htmlFile === 'string' ? path.dirname(args.htmlFile) : '',
26
+ ...(Array.isArray(args.root) ? args.root : []),
27
+ ...envFileRoots(),
28
+ ...extra,
29
+ ];
30
+ return given.filter(Boolean).map((p) => path.resolve(expandHome(p)));
31
+ }
32
+
12
33
  export function printJson(obj) {
13
34
  process.stdout.write(JSON.stringify(obj, null, 2) + '\n');
14
35
  }
package/src/cli/mcp.js CHANGED
@@ -2,6 +2,7 @@
2
2
  import fs from 'node:fs';
3
3
  import os from 'node:os';
4
4
  import path from 'node:path';
5
+ import { envFileRoots, expandHome, isBroadRoot } from '../file-access.js';
5
6
  import { mcpConfig } from '../mcp/config.js';
6
7
  import { CliError } from '../util.js';
7
8
  import { parseArgs } from './args.js';
@@ -24,6 +25,7 @@ export async function cmdMcp(rest) {
24
25
  const envPort = process.env.PORT || process.env.RLY_MCP_PORT;
25
26
  const { runMcpHttp } = await import('../mcp/serve.js');
26
27
  return runMcpHttp({
28
+ fileRoots: mcpFileRoots(args, []),
27
29
  port: args.port ? Number(args.port) : (envPort ? Number(envPort) : undefined),
28
30
  host: typeof args.host === 'string' ? args.host : (process.env.RLY_MCP_HOST || '127.0.0.1'),
29
31
  token: resolveToken(args),
@@ -33,7 +35,24 @@ export async function cmdMcp(rest) {
33
35
  // Default: be the stdio server. main() never resolves this, so the CLI's
34
36
  // post-run exit timer never arms — the server lives until stdin closes.
35
37
  const { runMcp } = await import('../mcp/serve.js');
36
- return runMcp();
38
+ return runMcp({ fileRoots: mcpFileRoots(args, stdioDefaultRoots(process.cwd())) });
39
+ }
40
+
41
+ /** The working directory as the stdio root, unless it is `/` or the home directory. */
42
+ function stdioDefaultRoots(cwd) {
43
+ if (!isBroadRoot(cwd)) return [cwd];
44
+ // stdout is the MCP channel, so the notice goes to stderr.
45
+ process.stderr.write(`relay mcp: the working directory ${cwd} is too wide to read files from by default; pass --root PATH to allow a folder.\n`);
46
+ return [];
47
+ }
48
+
49
+ /**
50
+ * Where a spec may read local files. A local stdio host gets the working
51
+ * directory; an HTTP server gets nothing unless the operator passes `--root` or
52
+ * `$RLY_FILE_ROOTS`, because its clients are remote.
53
+ */
54
+ function mcpFileRoots(args, defaults) {
55
+ return [...defaults, ...args.root, ...envFileRoots()].map((p) => path.resolve(expandHome(p)));
37
56
  }
38
57
 
39
58
  /**
@@ -0,0 +1,129 @@
1
+ // The one place a spec's local-file reads are allowed or refused. Specs are
2
+ // untrusted (an MCP client over HTTP writes them), so every path they name is
3
+ // resolved through realpath and must land inside a configured root.
4
+ import fs from 'node:fs';
5
+ import os from 'node:os';
6
+ import path from 'node:path';
7
+ import { CliError } from './util.js';
8
+
9
+ /**
10
+ * @typedef {object} FileAccess
11
+ * @property {string} cwd Directory that relative spec paths resolve against.
12
+ * @property {string[]} roots Real paths a spec may read from; a root may be a single file.
13
+ */
14
+
15
+ /** Env var with extra roots, separated by the platform's path delimiter (":" on macOS and Linux). */
16
+ export const FILE_ROOTS_ENV = 'RLY_FILE_ROOTS';
17
+
18
+ const FIX_HINT = 'pass --root PATH (or set RLY_FILE_ROOTS), or fileRoots in registerRelay, to allow it';
19
+
20
+ /** Expands a leading `~` to the home directory. */
21
+ export function expandHome(p) {
22
+ if (p === '~') return os.homedir();
23
+ if (/^~[\\/]/.test(p)) return path.join(os.homedir(), p.slice(2));
24
+ return p;
25
+ }
26
+
27
+ /**
28
+ * Real path of `p`, or of its nearest existing ancestor plus the rest when `p`
29
+ * does not exist. A missing path under an allowed root can then be told apart
30
+ * from one outside every root without touching the outside path.
31
+ */
32
+ function realpathOrAncestor(p) {
33
+ const rest = [];
34
+ let cur = p;
35
+ for (;;) {
36
+ try {
37
+ return path.join(fs.realpathSync.native(cur), ...rest);
38
+ } catch (err) {
39
+ const parent = path.dirname(cur);
40
+ if (parent === cur || (err && err.code !== 'ENOENT' && err.code !== 'ENOTDIR')) return p;
41
+ rest.unshift(path.basename(cur));
42
+ cur = parent;
43
+ }
44
+ }
45
+ }
46
+
47
+ /** Real paths of the roots that exist; a root that does not exist grants nothing. */
48
+ export function realRoots(list, cwd) {
49
+ const out = [];
50
+ for (const raw of list) {
51
+ if (typeof raw !== 'string' || !raw.trim()) continue;
52
+ try {
53
+ out.push(fs.realpathSync.native(path.resolve(cwd, expandHome(raw.trim()))));
54
+ } catch { /* a root that is not there yet grants nothing */ }
55
+ }
56
+ return [...new Set(out)];
57
+ }
58
+
59
+ /**
60
+ * True when `dir` is a filesystem root or the home directory. Such a folder is
61
+ * too wide to grant by default: a desktop host often starts a stdio server at
62
+ * `/`, which would let a spec read the whole disk. Passing it as `--root` still works.
63
+ */
64
+ export function isBroadRoot(dir) {
65
+ let real;
66
+ try { real = fs.realpathSync.native(path.resolve(dir)); } catch { return false; }
67
+ if (path.parse(real).root === real) return true;
68
+ try { return real === fs.realpathSync.native(os.homedir()); } catch { return false; }
69
+ }
70
+
71
+ /** Roots named by `RLY_FILE_ROOTS`. */
72
+ export function envFileRoots(env = process.env) {
73
+ return String(env[FILE_ROOTS_ENV] || '').split(path.delimiter).filter(Boolean);
74
+ }
75
+
76
+ /**
77
+ * @param {{ cwd?: string, roots?: string[] }} [options] `roots` of `[]` means no local file may be read.
78
+ * @returns {FileAccess}
79
+ */
80
+ export function createFileAccess({ cwd = process.cwd(), roots = [cwd] } = {}) {
81
+ return { cwd, roots: realRoots(roots, cwd) };
82
+ }
83
+
84
+ /** True when `target` is a root or lies under one. Both are real paths. */
85
+ export function isInsideRoots(target, roots) {
86
+ return roots.some((root) => {
87
+ const rel = path.relative(root, target);
88
+ return rel === '' || (rel !== '..' && !rel.startsWith(`..${path.sep}`) && !path.isAbsolute(rel));
89
+ });
90
+ }
91
+
92
+ /**
93
+ * Resolves a path a spec names and says whether it may be read.
94
+ * @param {FileAccess} access
95
+ * @param {unknown} raw the path as written; `~` and relative paths are expanded
96
+ * @param {{ allowDirectory?: boolean }} [options] directories are refused unless a caller opens them in an app
97
+ * @returns {{ ok: boolean, file?: string, stat?: fs.Stats, reason?: 'invalid' | 'outside' | 'missing' | 'not-file', resolved?: string }} `file` and `stat` when ok; otherwise `reason` and the real path it was refused at
98
+ */
99
+ export function checkReadable(access, raw, { allowDirectory = false } = {}) {
100
+ const text = typeof raw === 'string' ? raw.trim() : '';
101
+ if (!text || text.includes('\0')) return { ok: false, reason: 'invalid', resolved: text };
102
+ const resolved = path.resolve(access.cwd, expandHome(text));
103
+ const real = realpathOrAncestor(resolved);
104
+ if (!isInsideRoots(real, access.roots)) return { ok: false, reason: 'outside', resolved: real };
105
+ let stat;
106
+ try { stat = fs.statSync(real); } catch { return { ok: false, reason: 'missing', resolved: real }; }
107
+ if (!stat.isFile() && !(allowDirectory && stat.isDirectory())) return { ok: false, reason: 'not-file', resolved: real };
108
+ return { ok: true, file: real, stat };
109
+ }
110
+
111
+ /**
112
+ * The real path of a file a spec names, or a CliError worded for the agent.
113
+ * @param {FileAccess} access
114
+ * @param {unknown} raw
115
+ * @param {string} where which block, e.g. `board.blocks[0]`
116
+ * @param {string} field which field, e.g. `codeFile`
117
+ * @returns {{ file: string, stat: fs.Stats }}
118
+ */
119
+ export function resolveReadable(access, raw, where, field) {
120
+ const checked = checkReadable(access, raw);
121
+ if (checked.ok) return { file: /** @type {string} */ (checked.file), stat: /** @type {fs.Stats} */ (checked.stat) };
122
+ const given = typeof raw === 'string' ? raw : String(raw);
123
+ const prefix = `${where}: ${field}: `;
124
+ if (checked.reason === 'outside') {
125
+ throw new CliError(`${prefix}path outside allowed roots (\"${given}\" resolves to ${checked.resolved}); ${FIX_HINT}.`);
126
+ }
127
+ if (checked.reason === 'not-file') throw new CliError(`${prefix}\"${given}\" is not a regular file (resolved: ${checked.resolved}).`);
128
+ throw new CliError(`${prefix}cannot read \"${given}\" (resolved: ${checked.resolved})`);
129
+ }
@@ -53,7 +53,7 @@ export function filePreview(target, stat, reference) {
53
53
  let kind = /^(md|markdown|mdown)$/.test(ext) ? 'markdown' : /^(html|htm)$/.test(ext) ? 'html' : 'code';
54
54
  if (!reference.line && /^(csv|tsv)$/.test(ext)) {
55
55
  try {
56
- const block = normalizeSpec({ blocks: [{ type: 'table', rowsFile: target, sortable: true, filterable: true }] }).blocks[0];
56
+ const block = normalizeSpec({ blocks: [{ type: 'table', rowsFile: target, sortable: true, filterable: true }] }, { fileRoots: [target] }).blocks[0];
57
57
  return { ...base, kind: 'table', block, text, lang };
58
58
  } catch { /* malformed tables remain readable as source */ }
59
59
  }
package/src/mcp/boards.js CHANGED
@@ -27,15 +27,16 @@ export const modeOf = (spec) => (spec.responseRequired === false ? 'show' : 'ask
27
27
  * CliError so the tool can answer with an isError result the model can fix.
28
28
  * @param {import('./store.js').RelayStore} store
29
29
  * @param {Record<string, any>} args
30
- * @param {{ displayOnly?: boolean }} [options]
30
+ * @param {{ displayOnly?: boolean, fileRoots?: string[] }} [options] `fileRoots` are the only places a spec may read local files from; none by default
31
31
  */
32
32
  export async function createMcpBoard(store, args, options = {}) {
33
+ const fileRoots = options.fileRoots ?? [];
33
34
  const raw = { ...args };
34
35
  const hasQuestions = Array.isArray(raw.questions) && raw.questions.length > 0;
35
36
  if (options.displayOnly || (!hasQuestions && raw.responseRequired === undefined)) raw.responseRequired = false;
36
- const spec = normalizeSpec(raw);
37
+ const spec = normalizeSpec(raw, { fileRoots });
37
38
  await assertSpecReady(spec);
38
- const record = await store.create(spec);
39
+ const record = await store.create(spec, { fileRoots });
39
40
  return { record, spec, mode: modeOf(spec) };
40
41
  }
41
42
 
package/src/mcp/serve.js CHANGED
@@ -7,11 +7,11 @@ import { loadServerKey } from './token.js';
7
7
  const escapeHtml = (s) => String(s).replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[c]);
8
8
 
9
9
  /** Serves MCP over this process's stdin and stdout until the host closes stdin. */
10
- export async function runMcp() {
10
+ export async function runMcp({ fileRoots = [] } = {}) {
11
11
  const { serveStdio } = await import('@modelcontextprotocol/server/stdio');
12
12
  const { createRelayServer } = await import('./server.js');
13
13
  const tokenKey = loadServerKey();
14
- const handle = serveStdio(() => createRelayServer({ tokenKey }), { onerror: (e) => process.stderr.write(`relay mcp: ${e.message}\n`) });
14
+ const handle = serveStdio(() => createRelayServer({ tokenKey, fileRoots }), { onerror: (e) => process.stderr.write(`relay mcp: ${e.message}\n`) });
15
15
  // Resolves only once the host disconnects, so the CLI's exit timer never fires.
16
16
  return new Promise((resolve) => {
17
17
  const finish = () => handle.close().finally(() => resolve(0));
@@ -90,12 +90,12 @@ const bearerOk = (header = '', token) => /^bearer /i.test(header) && safeEqual(h
90
90
  * Serves MCP over Streamable HTTP. Localhost by default; a bearer token and an
91
91
  * allowed Origin are the controls for anything wider.
92
92
  */
93
- export async function runMcpHttp({ port = DEFAULT_HTTP_PORT, host = '127.0.0.1', token = '', allowOrigin = '' } = {}) {
93
+ export async function runMcpHttp({ port = DEFAULT_HTTP_PORT, host = '127.0.0.1', token = '', allowOrigin = '', fileRoots = [] } = {}) {
94
94
  const { createMcpHandler } = await import('@modelcontextprotocol/server');
95
95
  const { toNodeHandler } = await import('@modelcontextprotocol/node');
96
96
  const { createRelayServer } = await import('./server.js');
97
97
  const tokenKey = loadServerKey();
98
- const handler = createMcpHandler(() => createRelayServer({ tokenKey }), { onerror: (e) => process.stderr.write(`relay mcp: ${e.message}\n`) });
98
+ const handler = createMcpHandler(() => createRelayServer({ tokenKey, fileRoots }), { onerror: (e) => process.stderr.write(`relay mcp: ${e.message}\n`) });
99
99
  const serve = toNodeHandler(handler, { onerror: (e) => process.stderr.write(`relay mcp: ${e.message}\n`) });
100
100
 
101
101
  const server = http.createServer(requestListener({ serve, token, allowOrigin, endpoint: `http://${host === '0.0.0.0' ? 'localhost' : host}:${port}${HTTP_PATH}` }));
package/src/mcp/store.js CHANGED
@@ -12,7 +12,7 @@ import { createBoard, loadBoard, saveBoard, saveResultFile } from '../store.js';
12
12
 
13
13
  /**
14
14
  * @typedef {object} RelayStore
15
- * @property {(spec: any) => BoardRecord | Promise<BoardRecord>} create
15
+ * @property {(spec: any, options?: { fileRoots?: string[] }) => BoardRecord | Promise<BoardRecord>} create
16
16
  * @property {(id: string) => BoardRecord | null | Promise<BoardRecord | null>} get
17
17
  * @property {(id: string, patch: Partial<BoardRecord>) => BoardRecord | null | Promise<BoardRecord | null>} update
18
18
  */
@@ -21,7 +21,7 @@ import { createBoard, loadBoard, saveBoard, saveResultFile } from '../store.js';
21
21
  export function fileStore() {
22
22
  const get = (id) => (/^b-[a-z0-9]+$/i.test(String(id)) ? loadBoard(id) : null);
23
23
  return {
24
- create: (spec) => createBoard(spec),
24
+ create: (spec, options) => createBoard(spec, options),
25
25
  get,
26
26
  update(id, patch) {
27
27
  const record = get(id);
package/src/mcp/tools.js CHANGED
@@ -36,6 +36,7 @@ const json = (value, structured) => ({ content: [{ type: 'text', text: JSON.stri
36
36
  * @param {any} server an McpServer
37
37
  * @param {object} [options]
38
38
  * @param {import('./store.js').RelayStore} [options.store] where boards live; defaults to the relay home on disk
39
+ * @param {string[]} [options.fileRoots] folders a spec may read local files from (`codeFile`, images, `rowsFile`...); none by default, so a remote client cannot read the server's disk
39
40
  * @param {string | Buffer} [options.tokenKey] the secret behind board tokens; defaults to a key file in the relay home
40
41
  * @param {(name: string) => string} [options.assetUrl] URL of a vendor file, for hosts that can fetch it
41
42
  * @param {(boardId: string) => string} [options.linkUrl] a URL where a person can open the board outside the host
@@ -70,7 +71,7 @@ function registerBoardTools({ server, options, store, key }) {
70
71
  const openBoard = (displayOnly) => async (args) => {
71
72
  let made;
72
73
  try {
73
- made = await createMcpBoard(store, args, { displayOnly });
74
+ made = await createMcpBoard(store, args, { displayOnly, fileRoots: options.fileRoots });
74
75
  } catch (err) {
75
76
  return specError(err);
76
77
  }
@@ -14,7 +14,8 @@ import { isDirectLocalRequest, readBody, sameOrigin, sendDataImage, sendFromDir,
14
14
  import { UI_DIR, VENDOR_DIR } from './paths.js';
15
15
  import { findBlock, findHtmlBlock, firstBoardHtml, firstQuestionHtml, sanitizeAnnotations, sanitizeBlockEdits } from './sanitize.js';
16
16
  import { ARTIFACT_MAX_BYTES, ARTIFACT_MIMES, artifactBytesMatch, runOnResult } from './result.js';
17
- import { buildOpenAllowlist, resolveLocalPath, streamFile } from './files.js';
17
+ import { checkReadable } from '../file-access.js';
18
+ import { buildOpenAllowlist, recordFileAccess, resolveLocalPath, streamFile } from './files.js';
18
19
 
19
20
  // Serves one board on 127.0.0.1 and resolves `done` when it finishes
20
21
  // (submitted / acknowledged / timeout / cancelled). The result is also
@@ -53,6 +54,10 @@ export async function runBoard({ id, port = 0, open = true, timeoutSec = 86400,
53
54
  saveBoard(record);
54
55
  }
55
56
 
57
+ // Security: the roots are the ones the board was created under. Nothing a
58
+ // request carries can widen them, because the spec's pdf and video paths are
59
+ // streamed from disk and `/api/update` stores a spec without re-reading it.
60
+ const fileAccess = recordFileAccess(record);
56
61
  const startedAt = Date.now();
57
62
  // Mutation token: only `rly update` (which reads the running-file record)
58
63
  // can authenticate to POST /api/update. Never embedded in the page/boot.
@@ -256,6 +261,7 @@ export async function runBoard({ id, port = 0, open = true, timeoutSec = 86400,
256
261
  } else if (req.method === 'POST' && pathname === '/api/update') {
257
262
  if (req.headers['x-relay-token'] !== token) return sendJson(res, 403, { error: 'forbidden' });
258
263
  const body = JSON.parse((await readBody(req)) || '{}');
264
+ if (body.fileRoots !== undefined) return sendJson(res, 400, { error: 'file roots are set when a board is created and cannot change on update' });
259
265
  const next = body.spec;
260
266
  if (next === null || typeof next !== 'object' || Array.isArray(next) ||
261
267
  !Array.isArray(next.questions) || !Array.isArray(next.blocks)) {
@@ -326,13 +332,17 @@ export async function runBoard({ id, port = 0, open = true, timeoutSec = 86400,
326
332
  const blockId = decodeURIComponent(pathname.slice('/video/b/'.length));
327
333
  const block = findBlock(record.spec, blockId, 'video');
328
334
  if (!block || typeof block.file !== 'string') return sendJson(res, 404, { error: `no local video block "${blockId}"` });
329
- streamFile(req, res, block.file, block.mime || 'application/octet-stream');
335
+ const video = checkReadable(fileAccess, block.file);
336
+ if (!video.ok) return sendJson(res, 404, { error: `no local video block "${blockId}"` });
337
+ streamFile(req, res, video.file, block.mime || 'application/octet-stream');
330
338
  } else if ((req.method === 'GET' || req.method === 'HEAD') && pathname.startsWith('/pdf/b/')) {
331
339
  // Local PDF bytes, Range-streamed for the browser's built-in PDF viewer.
332
340
  const blockId = decodeURIComponent(pathname.slice('/pdf/b/'.length));
333
341
  const block = findBlock(record.spec, blockId, 'pdf');
334
342
  if (!block || typeof block.file !== 'string') return sendJson(res, 404, { error: `no local pdf block "${blockId}"` });
335
- streamFile(req, res, block.file, block.mime || 'application/pdf');
343
+ const pdf = checkReadable(fileAccess, block.file);
344
+ if (!pdf.ok) return sendJson(res, 404, { error: `no local pdf block "${blockId}"` });
345
+ streamFile(req, res, pdf.file, block.mime || 'application/pdf');
336
346
  } else if (req.method === 'GET' && pathname === '/html/board') {
337
347
  // Legacy alias → the board's first html block.
338
348
  const block = firstBoardHtml(record.spec);
@@ -359,6 +369,9 @@ export async function runBoard({ id, port = 0, open = true, timeoutSec = 86400,
359
369
  if (!sameOrigin(req, actualPort, [advertisedHost], [publicLink?.origin])) return sendJson(res, 403, { error: 'cross-origin requests cannot open files' });
360
370
  const access = accessFor(req, reqUrl);
361
371
  if (access.role !== 'owner' && access.role !== 'collab') return sendJson(res, 403, { error: 'this share cannot open local files' });
372
+ // Security: /api/open launches the file's app on this machine, which can
373
+ // run a script or an .app bundle, so only the person at this machine may.
374
+ 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' });
362
375
  const body = req.method === 'POST' ? JSON.parse((await readBody(req)) || '{}') : { path: reqUrl.searchParams.get('path') };
363
376
  const raw = typeof body.path === 'string' ? body.path : '';
364
377
  if (!raw.trim()) return sendJson(res, 400, { error: 'missing "path"' });
@@ -368,24 +381,23 @@ export async function runBoard({ id, port = 0, open = true, timeoutSec = 86400,
368
381
  if (!buildOpenAllowlist(record.spec, baseCwd).has(target)) {
369
382
  return sendJson(res, 403, { error: 'this path is not referenced on the board' });
370
383
  }
371
- let stat = null;
372
- try {
373
- stat = fs.statSync(target);
374
- } catch {
375
- stat = null;
384
+ const checked = checkReadable(fileAccess, target, { allowDirectory: true });
385
+ if (!checked.ok) {
386
+ if (checked.reason === 'missing') return sendJson(res, 404, { error: 'file not found', path: target });
387
+ return sendJson(res, 403, { error: checked.reason === 'outside' ? 'this path is outside the board\'s file roots' : 'this path is not a file or folder' });
376
388
  }
377
- if (!stat) return sendJson(res, 404, { error: 'file not found', path: target });
389
+ const { file: real, stat } = checked;
378
390
  if (pathname === '/api/file-preview') {
379
- return sendJson(res, 200, { ok: true, ...filePreview(target, stat, splitFileReference(raw)) });
391
+ return sendJson(res, 200, { ok: true, ...filePreview(real, stat, splitFileReference(raw)) });
380
392
  }
381
393
  if (pathname === '/api/file-content') {
382
- const media = mediaType(target);
394
+ const media = mediaType(real);
383
395
  if (!stat.isFile() || !media) return sendJson(res, 415, { error: 'this file type cannot be streamed' });
384
396
  res.setHeader('X-Content-Type-Options', 'nosniff');
385
397
  res.setHeader('Content-Security-Policy', "sandbox; default-src 'none'");
386
- return streamFile(req, res, target, media[1]);
398
+ return streamFile(req, res, real, media[1]);
387
399
  }
388
- if (!openUrl(target)) return sendJson(res, 500, { error: 'could not open the file' });
400
+ if (!openUrl(real)) return sendJson(res, 500, { error: 'could not open the file' });
389
401
  sendJson(res, 200, { ok: true, path: target, name: path.basename(target) });
390
402
  } else if (req.method === 'POST' && pathname === '/api/draft') {
391
403
  if (record.spec.responseRequired === false) return sendJson(res, 409, { error: 'display-only boards do not collect feedback' });
@@ -3,7 +3,9 @@ import fs from 'node:fs';
3
3
  import os from 'node:os';
4
4
  import path from 'node:path';
5
5
  import { fileURLToPath } from 'node:url';
6
+ import { createFileAccess } from '../file-access.js';
6
7
  import { splitFileReference } from '../file-preview.js';
8
+ import { boardFileRoots } from '../store.js';
7
9
  import { sendJson } from './http.js';
8
10
 
9
11
  // ---------- local-file links (POST /api/open) ----------
@@ -35,6 +37,11 @@ function looksLikeLocalPath(s) {
35
37
  return false;
36
38
  }
37
39
 
40
+ /** The file access of a stored board: its authoring folder and the roots it was created under. */
41
+ export function recordFileAccess(record) {
42
+ return createFileAccess({ cwd: record.cwd || process.cwd(), roots: boardFileRoots(record) });
43
+ }
44
+
38
45
  // Expands ~ / file:// and resolves a (possibly relative) path to an absolute,
39
46
  // normalized one against the board's authoring cwd. null on a malformed URL.
40
47
  export function resolveLocalPath(raw, baseCwd) {
@@ -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: a local reverse proxy can send a loopback Host (a link 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.
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.