@khanglvm/relay 0.22.1 → 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.
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, 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.
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.1",
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/boards.js CHANGED
@@ -2,7 +2,7 @@
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
7
  import { cliFileRoots, mustLoad, parseJson, printJson, readFileOrThrow, readStdin, runOrDetach } from './io.js';
8
8
 
@@ -139,7 +139,7 @@ export async function cmdReuse(args) {
139
139
  console.log(JSON.stringify(src.spec, null, 2));
140
140
  return 0;
141
141
  }
142
- const record = createBoard(src.spec, { fileRoots: src.fileRoots });
142
+ const record = createBoard(src.spec, { fileRoots: boardFileRoots(src) });
143
143
  return runOrDetach(record, args);
144
144
  }
145
145
 
@@ -156,7 +156,8 @@ export async function cmdUpdate(args) {
156
156
  throw new CliError(`board "${id}" is not running — \`rly reopen ${id}\` to serve it, then update.`, 5);
157
157
  }
158
158
 
159
- const fileRoots = [...new Set([...(record.fileRoots ?? [record.cwd]), ...cliFileRoots(args)])];
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);
160
161
  let spec;
161
162
  if (args.file) {
162
163
  const raw =
@@ -183,7 +184,7 @@ export async function cmdUpdate(args) {
183
184
  res = await fetch(new URL('/api/update', controlUrl(running)), {
184
185
  method: 'POST',
185
186
  headers: { 'content-type': 'application/json', 'x-relay-token': running.token || '' },
186
- body: JSON.stringify({ spec, fileRoots }),
187
+ body: JSON.stringify({ spec }),
187
188
  });
188
189
  } catch (err) {
189
190
  throw new CliError(`could not reach board "${id}" at ${running.url}: ${String((err && err.message) || err)}`, 5);
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)
package/src/cli/mcp.js CHANGED
@@ -2,7 +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
+ import { envFileRoots, expandHome, isBroadRoot } from '../file-access.js';
6
6
  import { mcpConfig } from '../mcp/config.js';
7
7
  import { CliError } from '../util.js';
8
8
  import { parseArgs } from './args.js';
@@ -35,7 +35,15 @@ export async function cmdMcp(rest) {
35
35
  // Default: be the stdio server. main() never resolves this, so the CLI's
36
36
  // post-run exit timer never arms — the server lives until stdin closes.
37
37
  const { runMcp } = await import('../mcp/serve.js');
38
- return runMcp({ fileRoots: mcpFileRoots(args, [process.cwd()]) });
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 [];
39
47
  }
40
48
 
41
49
  /**
@@ -56,6 +56,18 @@ export function realRoots(list, cwd) {
56
56
  return [...new Set(out)];
57
57
  }
58
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
+
59
71
  /** Roots named by `RLY_FILE_ROOTS`. */
60
72
  export function envFileRoots(env = process.env) {
61
73
  return String(env[FILE_ROOTS_ENV] || '').split(path.delimiter).filter(Boolean);
@@ -54,6 +54,10 @@ export async function runBoard({ id, port = 0, open = true, timeoutSec = 86400,
54
54
  saveBoard(record);
55
55
  }
56
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);
57
61
  const startedAt = Date.now();
58
62
  // Mutation token: only `rly update` (which reads the running-file record)
59
63
  // can authenticate to POST /api/update. Never embedded in the page/boot.
@@ -257,6 +261,7 @@ export async function runBoard({ id, port = 0, open = true, timeoutSec = 86400,
257
261
  } else if (req.method === 'POST' && pathname === '/api/update') {
258
262
  if (req.headers['x-relay-token'] !== token) return sendJson(res, 403, { error: 'forbidden' });
259
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' });
260
265
  const next = body.spec;
261
266
  if (next === null || typeof next !== 'object' || Array.isArray(next) ||
262
267
  !Array.isArray(next.questions) || !Array.isArray(next.blocks)) {
@@ -268,7 +273,6 @@ export async function runBoard({ id, port = 0, open = true, timeoutSec = 86400,
268
273
  return sendJson(res, 400, { error: err && err.message ? err.message : String(err) });
269
274
  }
270
275
  record.spec = next;
271
- if (Array.isArray(body.fileRoots)) record.fileRoots = body.fileRoots.filter((r) => typeof r === 'string');
272
276
  rev++;
273
277
  saveBoard(record);
274
278
  sendJson(res, 200, { ok: true, rev });
@@ -328,7 +332,7 @@ export async function runBoard({ id, port = 0, open = true, timeoutSec = 86400,
328
332
  const blockId = decodeURIComponent(pathname.slice('/video/b/'.length));
329
333
  const block = findBlock(record.spec, blockId, 'video');
330
334
  if (!block || typeof block.file !== 'string') return sendJson(res, 404, { error: `no local video block "${blockId}"` });
331
- const video = checkReadable(recordFileAccess(record), block.file);
335
+ const video = checkReadable(fileAccess, block.file);
332
336
  if (!video.ok) return sendJson(res, 404, { error: `no local video block "${blockId}"` });
333
337
  streamFile(req, res, video.file, block.mime || 'application/octet-stream');
334
338
  } else if ((req.method === 'GET' || req.method === 'HEAD') && pathname.startsWith('/pdf/b/')) {
@@ -336,7 +340,7 @@ export async function runBoard({ id, port = 0, open = true, timeoutSec = 86400,
336
340
  const blockId = decodeURIComponent(pathname.slice('/pdf/b/'.length));
337
341
  const block = findBlock(record.spec, blockId, 'pdf');
338
342
  if (!block || typeof block.file !== 'string') return sendJson(res, 404, { error: `no local pdf block "${blockId}"` });
339
- const pdf = checkReadable(recordFileAccess(record), block.file);
343
+ const pdf = checkReadable(fileAccess, block.file);
340
344
  if (!pdf.ok) return sendJson(res, 404, { error: `no local pdf block "${blockId}"` });
341
345
  streamFile(req, res, pdf.file, block.mime || 'application/pdf');
342
346
  } else if (req.method === 'GET' && pathname === '/html/board') {
@@ -365,6 +369,9 @@ export async function runBoard({ id, port = 0, open = true, timeoutSec = 86400,
365
369
  if (!sameOrigin(req, actualPort, [advertisedHost], [publicLink?.origin])) return sendJson(res, 403, { error: 'cross-origin requests cannot open files' });
366
370
  const access = accessFor(req, reqUrl);
367
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' });
368
375
  const body = req.method === 'POST' ? JSON.parse((await readBody(req)) || '{}') : { path: reqUrl.searchParams.get('path') };
369
376
  const raw = typeof body.path === 'string' ? body.path : '';
370
377
  if (!raw.trim()) return sendJson(res, 400, { error: 'missing "path"' });
@@ -374,7 +381,7 @@ export async function runBoard({ id, port = 0, open = true, timeoutSec = 86400,
374
381
  if (!buildOpenAllowlist(record.spec, baseCwd).has(target)) {
375
382
  return sendJson(res, 403, { error: 'this path is not referenced on the board' });
376
383
  }
377
- const checked = checkReadable(recordFileAccess(record), target, { allowDirectory: true });
384
+ const checked = checkReadable(fileAccess, target, { allowDirectory: true });
378
385
  if (!checked.ok) {
379
386
  if (checked.reason === 'missing') return sendJson(res, 404, { error: 'file not found', path: target });
380
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' });
@@ -5,6 +5,7 @@ import path from 'node:path';
5
5
  import { fileURLToPath } from 'node:url';
6
6
  import { createFileAccess } from '../file-access.js';
7
7
  import { splitFileReference } from '../file-preview.js';
8
+ import { boardFileRoots } from '../store.js';
8
9
  import { sendJson } from './http.js';
9
10
 
10
11
  // ---------- local-file links (POST /api/open) ----------
@@ -36,13 +37,9 @@ function looksLikeLocalPath(s) {
36
37
  return false;
37
38
  }
38
39
 
39
- /**
40
- * The file roots a stored board was created under. Boards saved before roots
41
- * existed fall back to their authoring directory.
42
- */
40
+ /** The file access of a stored board: its authoring folder and the roots it was created under. */
43
41
  export function recordFileAccess(record) {
44
- const cwd = record.cwd || process.cwd();
45
- return createFileAccess({ cwd, roots: Array.isArray(record.fileRoots) ? record.fileRoots : [cwd] });
42
+ return createFileAccess({ cwd: record.cwd || process.cwd(), roots: boardFileRoots(record) });
46
43
  }
47
44
 
48
45
  // Expands ~ / file:// and resolves a (possibly relative) path to an absolute,
@@ -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.
package/src/store.js CHANGED
@@ -36,6 +36,11 @@ export function saveBoardArtifact(id, bytes, ext = 'png') {
36
36
  return target;
37
37
  }
38
38
 
39
+ /** The roots a stored board was created under; a board saved before roots existed keeps its authoring folder. */
40
+ export function boardFileRoots(record) {
41
+ return Array.isArray(record.fileRoots) ? record.fileRoots : [record.cwd || process.cwd()];
42
+ }
43
+
39
44
  /**
40
45
  * @param {any} spec a normalized spec
41
46
  * @param {{ fileRoots?: string[] }} [options] the roots the spec was read under; the live server opens only files inside them
@@ -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
  /**
package/types/store.d.ts CHANGED
@@ -5,6 +5,8 @@ export declare function ensureDirs(): void;
5
5
  export declare function newId(): string;
6
6
  export declare const artifactDirPath: (id: any) => string;
7
7
  export declare function saveBoardArtifact(id: any, bytes: any, ext?: string): string;
8
+ /** The roots a stored board was created under; a board saved before roots existed keeps its authoring folder. */
9
+ export declare function boardFileRoots(record: any): any;
8
10
  /**
9
11
  * @param {any} spec a normalized spec
10
12
  * @param {{ fileRoots?: string[] }} [options] the roots the spec was read under; the live server opens only files inside them