@khanglvm/relay 0.22.0 → 0.22.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. package/docs/AGENT.md +1 -1
  2. package/package.json +1 -1
  3. package/src/cli/args.js +4 -2
  4. package/src/cli/ask.js +4 -3
  5. package/src/cli/boards.js +10 -7
  6. package/src/cli/git.js +5 -3
  7. package/src/cli/help.js +1 -0
  8. package/src/cli/io.js +21 -0
  9. package/src/cli/mcp.js +12 -1
  10. package/src/file-access.js +117 -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 +18 -13
  17. package/src/server/files.js +10 -0
  18. package/src/spec/blocks/a2ui.js +1 -1
  19. package/src/spec/blocks/chart.js +1 -1
  20. package/src/spec/blocks/code.js +4 -4
  21. package/src/spec/blocks/diagram.js +3 -3
  22. package/src/spec/blocks/git-conflict.js +2 -2
  23. package/src/spec/blocks/image.js +6 -5
  24. package/src/spec/blocks/markdown.js +2 -2
  25. package/src/spec/blocks/pdf.js +4 -10
  26. package/src/spec/blocks/table.js +5 -4
  27. package/src/spec/blocks/video.js +4 -10
  28. package/src/spec/blocks/widgets.js +6 -6
  29. package/src/spec/normalize.js +18 -11
  30. package/src/spec/pick.js +4 -4
  31. package/src/spec/sources.js +19 -24
  32. package/src/store.js +6 -1
  33. package/types/file-access.d.ts +62 -0
  34. package/types/mcp/boards.d.ts +2 -1
  35. package/types/mcp/serve.d.ts +5 -2
  36. package/types/mcp/store.d.ts +6 -3
  37. package/types/mcp/tools.d.ts +2 -0
  38. package/types/spec/blocks/a2ui.d.ts +1 -1
  39. package/types/spec/blocks/chart.d.ts +1 -1
  40. package/types/spec/blocks/code.d.ts +2 -2
  41. package/types/spec/blocks/diagram.d.ts +3 -3
  42. package/types/spec/blocks/git-conflict.d.ts +1 -1
  43. package/types/spec/blocks/image.d.ts +2 -2
  44. package/types/spec/blocks/markdown.d.ts +1 -1
  45. package/types/spec/blocks/pdf.d.ts +1 -1
  46. package/types/spec/blocks/table.d.ts +1 -1
  47. package/types/spec/blocks/video.d.ts +1 -1
  48. package/types/spec/blocks/widgets.d.ts +4 -4
  49. package/types/spec/normalize.d.ts +7 -1
  50. package/types/spec/pick.d.ts +1 -1
  51. package/types/spec/sources.d.ts +5 -4
  52. package/types/store.d.ts +8 -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. 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
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@khanglvm/relay",
3
- "version": "0.22.0",
3
+ "version": "0.22.1",
4
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).",
5
5
  "keywords": [
6
6
  "ai-agents",
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
@@ -4,7 +4,7 @@ import { openUrl } from '../open.js';
4
4
  import { assertSpecReady, normalizeSpec, questionFromInline } from '../spec/index.js';
5
5
  import { HOME, 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: src.fileRoots });
141
143
  return runOrDetach(record, args);
142
144
  }
143
145
 
@@ -154,13 +156,14 @@ 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
+ const fileRoots = [...new Set([...(record.fileRoots ?? [record.cwd]), ...cliFileRoots(args)])];
157
160
  let spec;
158
161
  if (args.file) {
159
162
  const raw =
160
163
  args.file === '-'
161
164
  ? parseJson(await readStdin(), 'stdin')
162
165
  : parseJson(readFileOrThrow(args.file), args.file);
163
- spec = normalizeSpec(raw);
166
+ spec = normalizeSpec(raw, { fileRoots });
164
167
  } else if (args.title || args.intro || args.q.length) {
165
168
  // Patch the CURRENT spec, then re-normalize so it's a clean normalized spec.
166
169
  const raw = { ...record.spec };
@@ -169,7 +172,7 @@ export async function cmdUpdate(args) {
169
172
  if (args.q.length) {
170
173
  raw.questions = [...(raw.questions || []), ...args.q.map((s, i) => questionFromInline(s, i))];
171
174
  }
172
- spec = normalizeSpec(raw);
175
+ spec = normalizeSpec(raw, { fileRoots });
173
176
  } else {
174
177
  throw new CliError('update needs --file <spec.json>, --title, --intro, or -q "...".', 4);
175
178
  }
@@ -180,7 +183,7 @@ export async function cmdUpdate(args) {
180
183
  res = await fetch(new URL('/api/update', controlUrl(running)), {
181
184
  method: 'POST',
182
185
  headers: { 'content-type': 'application/json', 'x-relay-token': running.token || '' },
183
- body: JSON.stringify({ spec }),
186
+ body: JSON.stringify({ spec, fileRoots }),
184
187
  });
185
188
  } catch (err) {
186
189
  throw new CliError(`could not reach board "${id}" at ${running.url}: ${String((err && err.message) || err)}`, 5);
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
@@ -71,6 +71,7 @@ USAGE
71
71
  a local desktop host (Claude Desktop, Codex) instead of a browser tab
72
72
  rly mcp --http [--port N] serve over Streamable HTTP for web/mobile/remote hosts
73
73
  [--host H --token-file PATH --allow-origin ORIGIN]
74
+ [--root PATH ...] folders a spec may read local files from (none by default over HTTP; also $RLY_FILE_ROOTS)
74
75
  (token: --token-file, $RLY_MCP_TOKEN, or --token, which shows in the process list)
75
76
  rly mcp config | install --target print host setup, or write it (claude | codex)
76
77
 
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 } 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,16 @@ 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, [process.cwd()]) });
39
+ }
40
+
41
+ /**
42
+ * Where a spec may read local files. A local stdio host gets the working
43
+ * directory; an HTTP server gets nothing unless the operator passes `--root` or
44
+ * `$RLY_FILE_ROOTS`, because its clients are remote.
45
+ */
46
+ function mcpFileRoots(args, defaults) {
47
+ return [...defaults, ...args.root, ...envFileRoots()].map((p) => path.resolve(expandHome(p)));
37
48
  }
38
49
 
39
50
  /**
@@ -0,0 +1,117 @@
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
+ /** Roots named by `RLY_FILE_ROOTS`. */
60
+ export function envFileRoots(env = process.env) {
61
+ return String(env[FILE_ROOTS_ENV] || '').split(path.delimiter).filter(Boolean);
62
+ }
63
+
64
+ /**
65
+ * @param {{ cwd?: string, roots?: string[] }} [options] `roots` of `[]` means no local file may be read.
66
+ * @returns {FileAccess}
67
+ */
68
+ export function createFileAccess({ cwd = process.cwd(), roots = [cwd] } = {}) {
69
+ return { cwd, roots: realRoots(roots, cwd) };
70
+ }
71
+
72
+ /** True when `target` is a root or lies under one. Both are real paths. */
73
+ export function isInsideRoots(target, roots) {
74
+ return roots.some((root) => {
75
+ const rel = path.relative(root, target);
76
+ return rel === '' || (rel !== '..' && !rel.startsWith(`..${path.sep}`) && !path.isAbsolute(rel));
77
+ });
78
+ }
79
+
80
+ /**
81
+ * Resolves a path a spec names and says whether it may be read.
82
+ * @param {FileAccess} access
83
+ * @param {unknown} raw the path as written; `~` and relative paths are expanded
84
+ * @param {{ allowDirectory?: boolean }} [options] directories are refused unless a caller opens them in an app
85
+ * @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
86
+ */
87
+ export function checkReadable(access, raw, { allowDirectory = false } = {}) {
88
+ const text = typeof raw === 'string' ? raw.trim() : '';
89
+ if (!text || text.includes('\0')) return { ok: false, reason: 'invalid', resolved: text };
90
+ const resolved = path.resolve(access.cwd, expandHome(text));
91
+ const real = realpathOrAncestor(resolved);
92
+ if (!isInsideRoots(real, access.roots)) return { ok: false, reason: 'outside', resolved: real };
93
+ let stat;
94
+ try { stat = fs.statSync(real); } catch { return { ok: false, reason: 'missing', resolved: real }; }
95
+ if (!stat.isFile() && !(allowDirectory && stat.isDirectory())) return { ok: false, reason: 'not-file', resolved: real };
96
+ return { ok: true, file: real, stat };
97
+ }
98
+
99
+ /**
100
+ * The real path of a file a spec names, or a CliError worded for the agent.
101
+ * @param {FileAccess} access
102
+ * @param {unknown} raw
103
+ * @param {string} where which block, e.g. `board.blocks[0]`
104
+ * @param {string} field which field, e.g. `codeFile`
105
+ * @returns {{ file: string, stat: fs.Stats }}
106
+ */
107
+ export function resolveReadable(access, raw, where, field) {
108
+ const checked = checkReadable(access, raw);
109
+ if (checked.ok) return { file: /** @type {string} */ (checked.file), stat: /** @type {fs.Stats} */ (checked.stat) };
110
+ const given = typeof raw === 'string' ? raw : String(raw);
111
+ const prefix = `${where}: ${field}: `;
112
+ if (checked.reason === 'outside') {
113
+ throw new CliError(`${prefix}path outside allowed roots (\"${given}\" resolves to ${checked.resolved}); ${FIX_HINT}.`);
114
+ }
115
+ if (checked.reason === 'not-file') throw new CliError(`${prefix}\"${given}\" is not a regular file (resolved: ${checked.resolved}).`);
116
+ throw new CliError(`${prefix}cannot read \"${given}\" (resolved: ${checked.resolved})`);
117
+ }
@@ -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
@@ -267,6 +268,7 @@ export async function runBoard({ id, port = 0, open = true, timeoutSec = 86400,
267
268
  return sendJson(res, 400, { error: err && err.message ? err.message : String(err) });
268
269
  }
269
270
  record.spec = next;
271
+ if (Array.isArray(body.fileRoots)) record.fileRoots = body.fileRoots.filter((r) => typeof r === 'string');
270
272
  rev++;
271
273
  saveBoard(record);
272
274
  sendJson(res, 200, { ok: true, rev });
@@ -326,13 +328,17 @@ export async function runBoard({ id, port = 0, open = true, timeoutSec = 86400,
326
328
  const blockId = decodeURIComponent(pathname.slice('/video/b/'.length));
327
329
  const block = findBlock(record.spec, blockId, 'video');
328
330
  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');
331
+ const video = checkReadable(recordFileAccess(record), block.file);
332
+ if (!video.ok) return sendJson(res, 404, { error: `no local video block "${blockId}"` });
333
+ streamFile(req, res, video.file, block.mime || 'application/octet-stream');
330
334
  } else if ((req.method === 'GET' || req.method === 'HEAD') && pathname.startsWith('/pdf/b/')) {
331
335
  // Local PDF bytes, Range-streamed for the browser's built-in PDF viewer.
332
336
  const blockId = decodeURIComponent(pathname.slice('/pdf/b/'.length));
333
337
  const block = findBlock(record.spec, blockId, 'pdf');
334
338
  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');
339
+ const pdf = checkReadable(recordFileAccess(record), block.file);
340
+ if (!pdf.ok) return sendJson(res, 404, { error: `no local pdf block "${blockId}"` });
341
+ streamFile(req, res, pdf.file, block.mime || 'application/pdf');
336
342
  } else if (req.method === 'GET' && pathname === '/html/board') {
337
343
  // Legacy alias → the board's first html block.
338
344
  const block = firstBoardHtml(record.spec);
@@ -368,24 +374,23 @@ export async function runBoard({ id, port = 0, open = true, timeoutSec = 86400,
368
374
  if (!buildOpenAllowlist(record.spec, baseCwd).has(target)) {
369
375
  return sendJson(res, 403, { error: 'this path is not referenced on the board' });
370
376
  }
371
- let stat = null;
372
- try {
373
- stat = fs.statSync(target);
374
- } catch {
375
- stat = null;
377
+ const checked = checkReadable(recordFileAccess(record), target, { allowDirectory: true });
378
+ if (!checked.ok) {
379
+ if (checked.reason === 'missing') return sendJson(res, 404, { error: 'file not found', path: target });
380
+ 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
381
  }
377
- if (!stat) return sendJson(res, 404, { error: 'file not found', path: target });
382
+ const { file: real, stat } = checked;
378
383
  if (pathname === '/api/file-preview') {
379
- return sendJson(res, 200, { ok: true, ...filePreview(target, stat, splitFileReference(raw)) });
384
+ return sendJson(res, 200, { ok: true, ...filePreview(real, stat, splitFileReference(raw)) });
380
385
  }
381
386
  if (pathname === '/api/file-content') {
382
- const media = mediaType(target);
387
+ const media = mediaType(real);
383
388
  if (!stat.isFile() || !media) return sendJson(res, 415, { error: 'this file type cannot be streamed' });
384
389
  res.setHeader('X-Content-Type-Options', 'nosniff');
385
390
  res.setHeader('Content-Security-Policy', "sandbox; default-src 'none'");
386
- return streamFile(req, res, target, media[1]);
391
+ return streamFile(req, res, real, media[1]);
387
392
  }
388
- if (!openUrl(target)) return sendJson(res, 500, { error: 'could not open the file' });
393
+ if (!openUrl(real)) return sendJson(res, 500, { error: 'could not open the file' });
389
394
  sendJson(res, 200, { ok: true, path: target, name: path.basename(target) });
390
395
  } else if (req.method === 'POST' && pathname === '/api/draft') {
391
396
  if (record.spec.responseRequired === false) return sendJson(res, 409, { error: 'display-only boards do not collect feedback' });
@@ -3,6 +3,7 @@ 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';
7
8
  import { sendJson } from './http.js';
8
9
 
@@ -35,6 +36,15 @@ function looksLikeLocalPath(s) {
35
36
  return false;
36
37
  }
37
38
 
39
+ /**
40
+ * The file roots a stored board was created under. Boards saved before roots
41
+ * existed fall back to their authoring directory.
42
+ */
43
+ export function recordFileAccess(record) {
44
+ const cwd = record.cwd || process.cwd();
45
+ return createFileAccess({ cwd, roots: Array.isArray(record.fileRoots) ? record.fileRoots : [cwd] });
46
+ }
47
+
38
48
  // Expands ~ / file:// and resolves a (possibly relative) path to an absolute,
39
49
  // normalized one against the board's authoring cwd. null on a malformed URL.
40
50
  export function resolveLocalPath(raw, baseCwd) {
@@ -5,7 +5,7 @@ import { asStr, clampInt } from '../sources.js';
5
5
  import { BLOCK_HEIGHT } from '../constants.js';
6
6
 
7
7
  // Normalizes one a2ui block. `id` is the already-assigned block id.
8
- export function normalizeA2uiBlock(rawBlock, id, cwd, where, hasHeight) {
8
+ export function normalizeA2uiBlock(rawBlock, id, files, where, hasHeight) {
9
9
  // A live A2UI v1.0 widget: Express text (compiled in assertSpecReady) or
10
10
  // ready JSON components, checked against Relay's catalog either way.
11
11
  const hasExpress = rawBlock.express !== undefined && rawBlock.express !== null;
@@ -7,7 +7,7 @@ import { BLOCK_HEIGHT, CHART_KINDS, CHART_KIND_FIELDS, CHART_SERIES_FIELDS } fro
7
7
  const firstDefined = (raw, names) => raw[names.find((n) => raw[n] !== undefined)];
8
8
 
9
9
  // Normalizes one chart block. `id` is the already-assigned block id.
10
- export function normalizeChartBlock(raw, id, cwd, where, hasHeight) {
10
+ export function normalizeChartBlock(raw, id, files, where, hasHeight) {
11
11
  const rawBlock = { ...raw, kind: firstDefined(raw, CHART_KIND_FIELDS), series: firstDefined(raw, CHART_SERIES_FIELDS) };
12
12
  const hasConfig = rawBlock.config && typeof rawBlock.config === 'object' && !Array.isArray(rawBlock.config);
13
13
  const hasShorthand =
@@ -5,8 +5,8 @@ import { asStr, clampInt, readTextSource } from '../sources.js';
5
5
  import { BLOCK_HEIGHT } from '../constants.js';
6
6
 
7
7
  // Normalizes one code block. `id` is the already-assigned block id.
8
- export function normalizeCodeBlock(rawBlock, id, cwd, where, hasHeight) {
9
- const code = readTextSource(rawBlock, 'code', 'codeFile', cwd, where);
8
+ export function normalizeCodeBlock(rawBlock, id, files, where, hasHeight) {
9
+ const code = readTextSource(rawBlock, 'code', 'codeFile', files, where);
10
10
  if (!code) throw new CliError(`${where}: code block needs a "code" string or a readable "codeFile".`);
11
11
  const block = { id, type: 'code', code };
12
12
  if (rawBlock.lang !== undefined) block.lang = asStr(rawBlock.lang);
@@ -21,8 +21,8 @@ export function normalizeCodeBlock(rawBlock, id, cwd, where, hasHeight) {
21
21
  }
22
22
 
23
23
  // Normalizes one diff block. `id` is the already-assigned block id.
24
- export function normalizeDiffBlock(rawBlock, id, cwd, where, hasHeight) {
25
- const diff = readTextSource(rawBlock, 'diff', 'diffFile', cwd, where);
24
+ export function normalizeDiffBlock(rawBlock, id, files, where, hasHeight) {
25
+ const diff = readTextSource(rawBlock, 'diff', 'diffFile', files, where);
26
26
  if (!diff.trim()) throw new CliError(`${where}: diff block needs a non-empty "diff" string (unified diff) or a readable "diffFile".`);
27
27
  const block = { id, type: 'diff', diff };
28
28
  if (rawBlock.lang !== undefined) block.lang = asStr(rawBlock.lang);
@@ -4,7 +4,7 @@ import { asStr, clampInt } from '../sources.js';
4
4
  import { BLOCK_HEIGHT } from '../constants.js';
5
5
 
6
6
  // Normalizes one mermaid block. `id` is the already-assigned block id.
7
- export function normalizeMermaidBlock(rawBlock, id, cwd, where, hasHeight) {
7
+ export function normalizeMermaidBlock(rawBlock, id, files, where, hasHeight) {
8
8
  const code = asStr(rawBlock.code);
9
9
  if (!code.trim()) throw new CliError(`${where}: mermaid block needs a non-empty "code" string.`);
10
10
  const block = { id, type: 'mermaid', code };
@@ -14,7 +14,7 @@ export function normalizeMermaidBlock(rawBlock, id, cwd, where, hasHeight) {
14
14
  }
15
15
 
16
16
  // Normalizes one graphviz block. `id` is the already-assigned block id.
17
- export function normalizeGraphvizBlock(rawBlock, id, cwd, where, hasHeight) {
17
+ export function normalizeGraphvizBlock(rawBlock, id, files, where, hasHeight) {
18
18
  const dot = asStr(rawBlock.dot);
19
19
  if (!dot.trim()) throw new CliError(`${where}: graphviz block needs a non-empty "dot" string.`);
20
20
  const block = { id, type: 'graphviz', dot };
@@ -23,7 +23,7 @@ export function normalizeGraphvizBlock(rawBlock, id, cwd, where, hasHeight) {
23
23
  }
24
24
 
25
25
  // Normalizes one plantuml block. `id` is the already-assigned block id.
26
- export function normalizePlantumlBlock(rawBlock, id, cwd, where, hasHeight) {
26
+ export function normalizePlantumlBlock(rawBlock, id, files, where, hasHeight) {
27
27
  const code = asStr(rawBlock.code);
28
28
  if (!code.trim()) throw new CliError(`${where}: plantuml block needs a non-empty "code" string.`);
29
29
  const block = { id, type: 'plantuml', code };
@@ -80,8 +80,8 @@ function parseGitConflictContent(content, where) {
80
80
  }
81
81
 
82
82
  // Normalizes one git-conflict block. `id` is the already-assigned block id.
83
- export function normalizeGitConflictBlock(rawBlock, id, cwd, where, hasHeight) {
84
- const src = readAnyTextSource(rawBlock, ['content', 'text'], ['file', 'path', 'src'], cwd, where, 'git conflict file');
83
+ export function normalizeGitConflictBlock(rawBlock, id, files, where, hasHeight) {
84
+ const src = readAnyTextSource(rawBlock, ['content', 'text'], ['file', 'path', 'src'], files, where, 'git conflict file');
85
85
  if (!src.text.trim()) {
86
86
  throw new CliError(`${where}: git-conflict block needs inline "content"/"text" or a readable local "file"/"path".`);
87
87
  }