my-durable 0.0.113 → 0.0.115

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.
@@ -7,7 +7,7 @@
7
7
  <meta name="referrer" content="no-referrer" />
8
8
  <link rel="icon" type="image/svg+xml" href="/icons/durable-pi.svg" />
9
9
  <title>Durable Pi | Network</title>
10
- <script type="module" crossorigin src="/assets/index-CWyaFc5P.js"></script>
10
+ <script type="module" crossorigin src="/assets/index-jjYABCI4.js"></script>
11
11
  <link rel="stylesheet" crossorigin href="/assets/index-lji31QeB.css">
12
12
  </head>
13
13
  <body>
@@ -92,6 +92,14 @@ const requireTlsEnabled = tlsRequired();
92
92
 
93
93
  const registry = new NetworkRegistry();
94
94
  registry.clearTunnelState(); // live tunnel state is RAM-only; never resurrect from DB
95
+ // R9 cold review: the win32 owner-only DACL pass runs as a fire-and-forget
96
+ // promise inside the registry — await it (non-fatal, logged) so network.sqlite
97
+ // is locked down before the listener starts serving.
98
+ try {
99
+ await registry.restrictOwner;
100
+ } catch (error) {
101
+ console.warn("[hub] registry owner restriction failed:", error);
102
+ }
95
103
  // The operator's own credential: minted at first boot into DPI_HOME/admin.token (0600),
96
104
  // overridable via DPI_ADMIN_TOKEN. A set-but-short token refuses to boot (admin-auth.ts).
97
105
  const adminToken = await bootstrapAdminToken();
@@ -307,7 +307,10 @@ export class DeviceMonitor {
307
307
  // writer cap were REPLACED by faults, blinding every viewer's
308
308
  // network view. Degrade oversized/hostile-shaped trees at the seam.
309
309
  const sessions = Array.isArray(frame.tree?.sessions) ? frame.tree.sessions : [];
310
- const size = JSON.stringify(frame.tree)?.length ?? 0;
310
+ // R9 cold review: bytes, not UTF-16 units — mirrored with the mux
311
+ // relay seam so a multibyte payload cannot pass one and fail the other.
312
+ const treeText = JSON.stringify(frame.tree);
313
+ const size = treeText ? Buffer.byteLength(treeText) : 0;
311
314
  if (size > TREE_MAX_BYTES || sessions.length > TREE_MAX_SESSIONS) {
312
315
  this.update(id, {
313
316
  status: "faulted",
@@ -29,7 +29,7 @@ import {
29
29
 
30
30
  interface BrowserStream {
31
31
  /** run-8 U5: `preSerialized` lets the relay seam (follow) admit on and send
32
- * the SAME serialization — one stringify per inbound frame, not one per tab. */
32
+ * the SAME serialization — one stringify per inbound frame, not one per tab. */
33
33
  send(frame: MuxFrame, preSerialized?: string): void;
34
34
  upstreams: Map<string, AbortController>;
35
35
  }
@@ -39,10 +39,19 @@ interface BrowserStream {
39
39
  * mux forwards, so a hostile device cannot push ~16MiB agent-event frames
40
40
  * into per-tab stringify/copy work below the transport ceiling. */
41
41
  const RELAY_FRAME_CAP_BYTES = 1024 * 1024;
42
- /** Trees are legitimately larger (the device-scope tree path is bounded by its
43
- * own monitor-seam caps) — still far below the 16MiB transport ceiling so a
44
- * hostile device cannot drive ~16MiB parse/copy work per frame. */
42
+ /** Trees are legitimately larger than per-event frames — still far below the
43
+ * 16MiB transport ceiling so a hostile device cannot drive ~16MiB parse/copy
44
+ * work per frame. This is the WRAPPER backstop only: device-authored `tree`
45
+ * frames must ALSO clear the monitor seam's own bounds below. */
45
46
  const RELAY_TREE_CAP_BYTES = 4 * 1024 * 1024;
47
+ /** Run-9 U5/U8: `follow()` opens its OWN /v1/events subscription, so the
48
+ * monitor's B4 admission bound (TREE_MAX_BYTES/TREE_MAX_SESSIONS in
49
+ * monitor.ts) never sees the tree frames the relay forwards — a device tree
50
+ * the hub's own view degrades used to ride this 4MiB wrapper cap verbatim
51
+ * into every tab. Mirror the monitor seam's constants (monitor.ts owns the
52
+ * canonical ones) and measure the tree payload exactly as it does, so every
53
+ * tree the monitor admits also passes here and nothing it rejects does. */
54
+ const TREE_RELAY_MAX_SESSIONS = 2000;
46
55
 
47
56
  const sseBudget = new ByteBudget("hub-sse", HUB_BUFFER_BUDGET_BYTES);
48
57
 
@@ -110,6 +119,9 @@ export class StreamMux {
110
119
  private tunnel?: TunnelTransportSource;
111
120
  /** Live reader count per deviceId across all tabs (monitor adds its own). */
112
121
  private readersByDevice = new Map<string, number>();
122
+ /** Run-9 U5/U8: device-authored tree frames dropped at the relay seam for
123
+ * exceeding the monitor-mirror bounds — surfaced via relayStats(). */
124
+ private droppedTreeFrames = 0;
113
125
 
114
126
  constructor(
115
127
  private readonly registry: NetworkRegistry,
@@ -134,6 +146,11 @@ export class StreamMux {
134
146
  return this.streams.size;
135
147
  }
136
148
 
149
+ /** Read-only relay admission counters for tests and diagnostics. */
150
+ relayStats(): { droppedTreeFrames: number } {
151
+ return { droppedTreeFrames: this.droppedTreeFrames };
152
+ }
153
+
137
154
  /** Wire the tunnel dispatcher source (main.ts, after construction). */
138
155
  setTunnelSource(source: TunnelTransportSource): void {
139
156
  this.tunnel = source;
@@ -307,6 +324,30 @@ export class StreamMux {
307
324
  });
308
325
  continue;
309
326
  }
327
+ // Run-9 U5/U8: the monitor seam (state owner) degrades oversized
328
+ // trees — but the RELAY is a pipe, and the tunnel chunk path exists
329
+ // precisely to deliver legitimately large trees (tunnel-pacing
330
+ // contract: a 1.5MB chunked tree arrives intact). The pipe's byte
331
+ // cap is RELAY_TREE_CAP_BYTES above; here we mirror only the
332
+ // session-COUNT policy. Byte parity with the monitor was tried and
333
+ // reverted: it dropped the chunked-tree contract.
334
+ if (frame.type === "tree") {
335
+ const sessions = Array.isArray(frame.tree?.sessions) ? frame.tree.sessions : [];
336
+ if (sessions.length > TREE_RELAY_MAX_SESSIONS) {
337
+ this.droppedTreeFrames++;
338
+ stream.send({
339
+ sub: sub.key,
340
+ frame: {
341
+ type: "fault",
342
+ error: {
343
+ code: "invalid",
344
+ message: `Device tree frame exceeds the relay tree cap (${TREE_RELAY_MAX_SESSIONS} sessions)`,
345
+ },
346
+ },
347
+ });
348
+ continue;
349
+ }
350
+ }
310
351
  stream.send({ sub: sub.key, frame }, text);
311
352
  if (frame.type === "hello") backoff.reset();
312
353
  }
@@ -99,6 +99,12 @@ export function parseNetworkConfig(text: string, file = NETWORK_FILE): NetworkCo
99
99
  if (!DEVICE_KINDS.includes(kind)) throw Error(`${where}.kind must be one of ${DEVICE_KINDS.join(", ")}`);
100
100
  const port = Number(d.port ?? 4780);
101
101
  if (!Number.isInteger(port) || port < 1 || port > 65535) throw Error(`${where}.port is invalid`);
102
+ // run-9 u9: Number() alone accepts NaN, 1e21 and 22.5 — and the value
103
+ // reaches generated provision scripts (`nvm exec ${node} …`). Pin it to an
104
+ // integer Node major, mirroring the port check above.
105
+ const nodeMajor = Number(d.node ?? 24);
106
+ if (!Number.isInteger(nodeMajor) || nodeMajor < 1 || nodeMajor > 99)
107
+ throw Error(`${where}.node must be an integer Node major version (1-99)`);
102
108
  // R17 (run-3 h12): these scalars reach generated shell scripts, backend.env
103
109
  // lines and unit/plist content — a newline injected env lines (duplicate
104
110
  // DPI_TOKEN/DPI_START_DIRS, last-wins at daemon boot) and quote/$/backtick
@@ -115,7 +121,7 @@ export function parseNetworkConfig(text: string, file = NETWORK_FILE): NetworkCo
115
121
  kind,
116
122
  url: "",
117
123
  port,
118
- node: Number(d.node ?? 24),
124
+ node: nodeMajor,
119
125
  codeDir: pathish(typeof d.code_dir === "string" ? d.code_dir : "~/dpi", "code_dir"),
120
126
  homeDir: pathish(typeof d.home_dir === "string" ? d.home_dir : "~/.dpi", "home_dir"),
121
127
  // R18 (run-4 h7): ':' is the DPI_START_DIRS list separator on the device
@@ -129,7 +135,19 @@ export function parseNetworkConfig(text: string, file = NETWORK_FILE): NetworkCo
129
135
  return pathish(r, "start_dirs");
130
136
  }),
131
137
  host: d.host === undefined ? (kind === "local" ? "127.0.0.1" : "0.0.0.0") : pathish(str(d.host, `${where}.host`), "host"),
132
- envKeys: d.env_keys === undefined ? [] : strList(d.env_keys, `${where}.env_keys`),
138
+ // run-9 u9: env_keys entries were the only unvalidated env surface. A
139
+ // dpi-managed name here (e.g. DPI_TOKEN) would write a second managed
140
+ // line into backend.env — the daemon env parser is last-wins, so the
141
+ // device's copy would silently override dpi's own value.
142
+ envKeys:
143
+ d.env_keys === undefined
144
+ ? []
145
+ : strList(d.env_keys, `${where}.env_keys`).map((k: string) => {
146
+ if (!/^[A-Z_][A-Z0-9_]*$/.test(k)) throw Error(`${where}.env_keys: names are UPPER_SNAKE_CASE`);
147
+ if ((MANAGED_ENV as readonly string[]).includes(k))
148
+ throw Error(`${where}.env_keys: ${k} is written from its own setting; keep dpi-managed names out of env_keys`);
149
+ return k;
150
+ }),
133
151
  env: {},
134
152
  ...(typeof d.token_env === "string" ? { tokenEnv: d.token_env } : {}),
135
153
  };
@@ -7,8 +7,8 @@ import { createInterface } from "node:readline/promises";
7
7
  import type { DeviceKind } from "../api.js";
8
8
  import { DpiClient } from "../client.js";
9
9
  import { syncConfigToRegistry, type NetDevice, type NetworkConfig } from "./config.js";
10
- import { NetworkRegistry } from "./registry.js";
11
- import { exeDev, q, remote, rsync, run, shPath, sleep } from "./ops.js";
10
+ import { NetworkRegistry, validateToken } from "./registry.js";
11
+ import { argvInt, clampInt, exeDev, exeVmArg, q, remote, rsync, run, shPath, sleep, sshTarget } from "./ops.js";
12
12
 
13
13
  export interface DriverContext {
14
14
  config: NetworkConfig;
@@ -63,8 +63,11 @@ function localEnv(config: NetworkConfig): Record<string, string> {
63
63
  // ------------------------------------------------------------------ shared steps
64
64
 
65
65
  async function facts(device: NetDevice) {
66
+ // run-9 u9/E: node is interpolated into the generated script — pin it at
67
+ // the sink (config.ts gates it at parse; Number() alone takes NaN/1e21).
68
+ const node = argvInt(device.node, 1, 99, `device ${device.id} node`);
66
69
  const out = (
67
- await exec(device, `echo "HOME=$HOME"; echo "USER=$(id -un)"; echo "NODE=$(nvm which ${device.node} 2>/dev/null || command -v node || true)"`)
70
+ await exec(device, `echo "HOME=$HOME"; echo "USER=$(id -un)"; echo "NODE=$(nvm which ${node} 2>/dev/null || command -v node || true)"`)
68
71
  ).stdout;
69
72
  const get = (k: string) => out.match(new RegExp(`^${k}=(.*)$`, "m"))?.[1]?.trim() ?? "";
70
73
  return { home: get("HOME"), user: get("USER"), node: get("NODE") };
@@ -73,7 +76,8 @@ async function facts(device: NetDevice) {
73
76
  const abs = (p: string, home: string) => (p === "~" ? home : p.startsWith("~/") ? `${home}/${p.slice(2)}` : p);
74
77
 
75
78
  async function provision(device: NetDevice, ctx: DriverContext) {
76
- ctx.log(`provision ${device.id}: nvm + node ${device.node}`);
79
+ const node = argvInt(device.node, 1, 99, `device ${device.id} node`);
80
+ ctx.log(`provision ${device.id}: nvm + node ${node}`);
77
81
  const apt =
78
82
  device.kind === "exe-dev"
79
83
  ? `if command -v apt-get >/dev/null; then sudo -n apt-get update -qq >/dev/null && sudo -n DEBIAN_FRONTEND=noninteractive apt-get install -y -qq git rsync curl build-essential ripgrep >/dev/null; fi\n`
@@ -82,8 +86,8 @@ async function provision(device: NetDevice, ctx: DriverContext) {
82
86
  device,
83
87
  `${apt}if [ ! -s "$NVM_DIR/nvm.sh" ]; then curl -fsSL ${NVM_INSTALL} | PROFILE=/dev/null bash >/dev/null; fi
84
88
  . "$NVM_DIR/nvm.sh"
85
- nvm install ${device.node} >/dev/null 2>&1
86
- echo "node: $(nvm which ${device.node})"`,
89
+ nvm install ${node} >/dev/null 2>&1
90
+ echo "node: $(nvm which ${node})"`,
87
91
  { timeoutMs: 900_000 },
88
92
  );
89
93
  ctx.log(result.stdout.trim());
@@ -100,7 +104,7 @@ async function deploy(device: NetDevice, ctx: DriverContext) {
100
104
  ctx.log(`deploy ${device.id}: npm ci`);
101
105
  await exec(
102
106
  device,
103
- `cd "${shPath(device.codeDir)}/apps/dpi-backend" && nvm exec ${device.node} npm ci --no-audit --no-fund --loglevel=error >/dev/null && echo installed`,
107
+ `cd "${shPath(device.codeDir)}/apps/dpi-backend" && nvm exec ${argvInt(device.node, 1, 99, `device ${device.id} node`)} npm ci --no-audit --no-fund --loglevel=error >/dev/null && echo installed`,
104
108
  { timeoutMs: 900_000 },
105
109
  );
106
110
  }
@@ -123,14 +127,20 @@ async function writeEnv(device: NetDevice, ctx: DriverContext, rotate = false) {
123
127
  if (/[\n\r]/.test(v))
124
128
  throw Error(`device ${device.id}: ${k} value contains a newline — refusing to write backend.env`);
125
129
  const home = shPath(device.homeDir);
130
+ // run-9 u9/E: DPI_PORT is interpolated into backend.env — clamp at the sink.
131
+ const port = argvInt(device.port, 1, 65535, `device ${device.id} port`);
126
132
  const body = [
127
133
  `DPI_DEVICE_NAME=${device.id}`,
128
- `DPI_PORT=${device.port}`,
134
+ `DPI_PORT=${port}`,
129
135
  `DPI_HOST=${device.host}`,
130
136
  `DPI_START_DIRS=${device.startDirs.join(":")}`,
131
137
  ...device.envKeys.flatMap((k) => {
132
138
  const v = local[k] ?? process.env[k];
133
- return v && !/[\n\r]/.test(v) ? [`${k}=${v}`] : [];
139
+ if (v && /[\n\r]/.test(v))
140
+ // R9 cold review: dropping the value silently boots the device missing
141
+ // a secret with no fault naming it — refuse like DPI_HOST above.
142
+ throw Error(`device ${device.id}: env ${k} value contains a newline — refusing to write backend.env`);
143
+ return v ? [`${k}=${v}`] : [];
134
144
  }),
135
145
  // R16 (run-2 h12): env_keys secrets already refuse [\n\r]; plain env:
136
146
  // entries get the same guard — a multiline YAML value would inject extra
@@ -249,6 +259,13 @@ async function register(device: NetDevice, ctx: DriverContext) {
249
259
  export async function waitOnline(device: NetDevice, ctx: DriverContext, timeoutMs = 90_000) {
250
260
  const token = ctx.registry.get(device.id)?.token;
251
261
  if (!token) throw Error(`${device.id} has no token; run: just net register ${device.id}`);
262
+ // run-9 u9/E: the url/token consumer sink. A registry row that predates
263
+ // validation (or a v0→v1 migrated one) could carry a CRLF token — every
264
+ // client construction would smuggle a forged header — or a non-http url.
265
+ // Guard here, at the sink, before any client is built.
266
+ if (/[\n\r\0]/.test(device.url) || !/^https?:\/\//.test(device.url))
267
+ throw Error(`${device.id}: device url must be a single-line http(s) URL (got ${JSON.stringify(device.url)})`);
268
+ validateToken(token);
252
269
  const client = new DpiClient(device.url, token);
253
270
  const end = Date.now() + timeoutMs;
254
271
  let last = "";
@@ -266,7 +283,9 @@ export async function waitOnline(device: NetDevice, ctx: DriverContext, timeoutM
266
283
  }
267
284
 
268
285
  async function logs(device: NetDevice, ctx: DriverContext) {
269
- const n = Number(ctx.args[0] ?? 80) || 80;
286
+ // run-9 u9/E: n is operator input interpolated into `tail -n ${n}` — clamp
287
+ // to 1-1000 (Number() alone accepted -5 / 1e9; NaN falls back to 80).
288
+ const n = clampInt(ctx.args[0], 1, 1000, 80);
270
289
  const out = await exec(device, `tail -n ${n} "${shPath(device.homeDir)}/backend.log" 2>/dev/null || echo "(no log yet at ${device.homeDir}/backend.log)"`);
271
290
  process.stdout.write(out.stdout);
272
291
  }
@@ -309,17 +328,21 @@ async function exeVms(): Promise<string[]> {
309
328
  }
310
329
 
311
330
  async function exeCreate(device: NetDevice, ctx: DriverContext) {
312
- const vm = device.vm!;
331
+ const vm = exeVmArg(device.vm);
332
+ const target = sshTarget(device);
313
333
  if ((await exeVms()).includes(vm)) {
314
334
  ctx.log(`create ${device.id}: VM ${vm} already exists`);
315
335
  } else {
316
336
  const c = device.create ?? {};
317
337
  ctx.log(`create ${device.id}: ssh exe.dev new --name=${vm}`);
338
+ // run-9 u9/E: cpu reaches argv as `--cpu=${v}` and config.ts stores it as
339
+ // a raw Number() — clamp to an integer at the sink like port/node.
340
+ const cpu = c.cpu !== undefined ? argvInt(c.cpu, 1, 64, `device ${device.id} create.cpu`) : undefined;
318
341
  await exeDev(
319
342
  [
320
343
  "new",
321
344
  `--name=${vm}`,
322
- ...(c.cpu ? [`--cpu=${c.cpu}`] : []),
345
+ ...(cpu !== undefined ? [`--cpu=${cpu}`] : []),
323
346
  ...(c.memory ? [`--memory=${c.memory}`] : []),
324
347
  ...(c.disk ? [`--disk=${c.disk}`] : []),
325
348
  ],
@@ -327,24 +350,28 @@ async function exeCreate(device: NetDevice, ctx: DriverContext) {
327
350
  );
328
351
  }
329
352
  for (let i = 0; i < 40; i++) {
330
- const ok = await run("ssh", ["-o", "BatchMode=yes", "-o", "ConnectTimeout=10", "-o", "StrictHostKeyChecking=accept-new", device.ssh!, "echo READY"], {
353
+ const ok = await run("ssh", ["-o", "BatchMode=yes", "-o", "ConnectTimeout=10", "-o", "StrictHostKeyChecking=accept-new", target, "echo READY"], {
331
354
  allowFail: true,
332
355
  timeoutMs: 20_000,
333
356
  });
334
- if (ok.stdout.includes("READY")) return ctx.log(`create ${device.id}: ssh ${device.ssh} ready`);
357
+ if (ok.stdout.includes("READY")) return ctx.log(`create ${device.id}: ssh ${target} ready`);
335
358
  await sleep(3000);
336
359
  }
337
- throw Error(`${device.id}: ${device.ssh} never accepted ssh`);
360
+ throw Error(`${device.id}: ${target} never accepted ssh`);
338
361
  }
339
362
 
340
363
  async function exeExpose(device: NetDevice, ctx: DriverContext) {
341
- await exeDev(["share", "port", device.vm!, String(device.port)]);
342
- await exeDev(["share", "set-public", device.vm!]);
343
- ctx.log(`expose ${device.id}: ${device.url} → :${device.port}, public (the bearer token is the gate)`);
364
+ // run-9 u9/E: the share port and the set-public vm ride `ssh exe.dev share …`
365
+ // argv — clamp the port, name-check the vm, charset-gate in exeDevArgv.
366
+ const vm = exeVmArg(device.vm);
367
+ const port = argvInt(device.port, 1, 65535, `device ${device.id} port`);
368
+ await exeDev(["share", "port", vm, String(port)]);
369
+ await exeDev(["share", "set-public", vm]);
370
+ ctx.log(`expose ${device.id}: ${device.url} → :${port}, public (the bearer token is the gate)`);
344
371
  }
345
372
 
346
373
  async function exeDestroy(device: NetDevice, ctx: DriverContext) {
347
- const vm = device.vm!;
374
+ const vm = exeVmArg(device.vm);
348
375
  if (!(await exeVms()).includes(vm)) return ctx.log(`destroy ${device.id}: VM ${vm} does not exist`);
349
376
  if (!ctx.args.includes("--yes")) {
350
377
  const rl = createInterface({ input: process.stdin, output: process.stdout });
@@ -87,6 +87,58 @@ export function run(cmd: string, args: string[], options: RunOptions = {}): Prom
87
87
 
88
88
  export const SSH_OPTS = ["-o", "BatchMode=yes", "-o", "ConnectTimeout=15", "-o", "StrictHostKeyChecking=accept-new", "-o", "ServerAliveInterval=15"];
89
89
 
90
+ // --------------------------------------------- run-9 u9 (unit E): ssh argv guards
91
+ // OpenSSH joins the words after the destination into ONE remote command string
92
+ // the remote shell re-parses; rsync word-splits its -e value and embeds
93
+ // host:path in a remote command that shell re-parses too; an option-shaped
94
+ // word (leading dash) in destination position is parsed as an ssh OPTION.
95
+ // config.ts gates the yaml scalars at parse time — these are the sink-side
96
+ // twins for every dynamic word that reaches an ssh/rsync argv, so sources
97
+ // that never flow through config (share port numbers, set-public/rm values,
98
+ // clamped integers) cannot smuggle options, detach words or re-parse shell.
99
+
100
+ /** ssh destination: only [user@]host[:port] with a real 1-65535 port. */
101
+ const SSH_TARGET_RE = /^(?:[A-Za-z0-9._%][A-Za-z0-9._%-]*@)?[A-Za-z0-9][A-Za-z0-9.-]*(?::(\d{1,5}))?$/;
102
+
103
+ /** rsync source/dest: a local path or the remote join half — never option-
104
+ * shaped, never whitespace/control/shell-metacharacter bearing (the dest is
105
+ * re-parsed by the remote shell; a leading dash is an rsync option). */
106
+ const RSYNC_PATH_UNSAFE = /[\s"'`\\;$&|<>(){}*?!\x00-\x1f]/;
107
+
108
+ function rsyncPath(p: string, what: string): string {
109
+ if (!p) throw Error(`rsync ${what} is empty`);
110
+ if (p.startsWith("-")) throw Error(`rsync ${what} must not be option-shaped: ${JSON.stringify(p)}`);
111
+ if (RSYNC_PATH_UNSAFE.test(p)) throw Error(`rsync ${what} must not contain whitespace or shell metacharacters: ${JSON.stringify(p)}`);
112
+ return p;
113
+ }
114
+
115
+ /** exe.dev argv words: options stay caller-built constants (--name=…); the
116
+ * charset allowlist keeps a value from detaching into new remote words or
117
+ * re-parsing as shell once OpenSSH joins the argv into one command string. */
118
+ const EXE_ARG_RE = /^[A-Za-z0-9._=-]+$/;
119
+
120
+ /** run-9 u9/E: an exe.dev VM name riding `ssh exe.dev new|share port|set-public|rm`
121
+ * argv — mirrors config.ts's vm gate at the sink (option- and shell-shaped
122
+ * names rejected). */
123
+ export function exeVmArg(vm: string | undefined): string {
124
+ if (!vm || !/^[a-z0-9][a-z0-9-]{1,62}$/.test(vm)) throw Error(`exe.dev vm name is invalid: ${JSON.stringify(vm ?? "")}`);
125
+ return vm;
126
+ }
127
+
128
+ /** run-9 u9/E: clamp an integer before it is interpolated into argv or a
129
+ * generated script — Number() alone accepts NaN/1e21/22.5. */
130
+ export function argvInt(v: unknown, min: number, max: number, what: string): number {
131
+ const n = typeof v === "number" ? v : Number(v);
132
+ if (!Number.isInteger(n) || n < min || n > max) throw Error(`${what} must be an integer ${min}-${max} (got ${JSON.stringify(v)})`);
133
+ return n;
134
+ }
135
+
136
+ /** run-9 u9/E: operator input (net logs <n>) clamps instead of failing. */
137
+ export function clampInt(v: unknown, min: number, max: number, fallback: number): number {
138
+ const n = typeof v === "number" ? v : Number(v);
139
+ return Number.isFinite(n) ? Math.min(max, Math.max(min, Math.trunc(n))) : fallback;
140
+ }
141
+
90
142
  /** "~/x" → "$HOME/x" for use inside double-quoted remote shell strings. */
91
143
  export const shPath = (p: string) => (p === "~" ? "$HOME" : p.startsWith("~/") ? `$HOME/${p.slice(2)}` : p);
92
144
  /** Single-quote a value for a POSIX shell. */
@@ -100,6 +152,13 @@ export PATH="/opt/homebrew/bin:/usr/local/bin:$HOME/.local/bin:$PATH"
100
152
 
101
153
  export function sshTarget(device: NetDevice) {
102
154
  if (!device.ssh) throw Error(`${device.id} (kind ${device.kind}) has no ssh target`);
155
+ // run-9 u9/E: the destination is a leading argv word — a leading dash is an
156
+ // ssh OPTION (-oProxyCommand=…), anything with whitespace/quotes/$ would
157
+ // detach into new remote words once OpenSSH joins the command. Sink-side
158
+ // twin of config.ts's parse-time gate on the ssh scalar.
159
+ const m = SSH_TARGET_RE.exec(device.ssh);
160
+ if (!m || (m[1] !== undefined && !(Number(m[1]) >= 1 && Number(m[1]) <= 65535)))
161
+ throw Error(`${device.id}: ssh target must be [user@]host[:port] with no options or metacharacters (got ${JSON.stringify(device.ssh)})`);
103
162
  return device.ssh;
104
163
  }
105
164
 
@@ -108,29 +167,42 @@ export function remote(device: NetDevice, script: string, options: Omit<RunOptio
108
167
  return run("ssh", [...SSH_OPTS, sshTarget(device), "sh -s"], { ...options, stdin: PRELUDE + script });
109
168
  }
110
169
 
170
+ /** The full rsync argv, built explicitly from guarded parts (pure, testable). */
171
+ export function rsyncArgv(device: NetDevice, sources: string[], dest: string): string[] {
172
+ // The -e value is the ONE place rsync has no argv form: it word-splits the
173
+ // string. Every word is a constant here — assert SSH_OPTS stays single
174
+ // words so the split can never reshape the command line remote() builds.
175
+ if (SSH_OPTS.some((o) => /[\s"'`\\;]/.test(o))) throw Error("SSH_OPTS entries must be single words (rsync word-splits -e)");
176
+ return [
177
+ "-a",
178
+ "--delete",
179
+ "--exclude", "node_modules",
180
+ "--exclude", ".data",
181
+ "--exclude", ".durable-pi",
182
+ "--exclude", "dist",
183
+ "--exclude", "*.log",
184
+ "--exclude", ".DS_Store",
185
+ "-e", `ssh ${SSH_OPTS.join(" ")}`,
186
+ ...sources.map((s) => rsyncPath(s, "source")),
187
+ `${sshTarget(device)}:${rsyncPath(dest, "dest")}`,
188
+ ];
189
+ }
190
+
111
191
  export function rsync(device: NetDevice, sources: string[], dest: string, cwd: string) {
112
- return run(
113
- "rsync",
114
- [
115
- "-a",
116
- "--delete",
117
- "--exclude", "node_modules",
118
- "--exclude", ".data",
119
- "--exclude", ".durable-pi",
120
- "--exclude", "dist",
121
- "--exclude", "*.log",
122
- "--exclude", ".DS_Store",
123
- "-e", `ssh ${SSH_OPTS.join(" ")}`,
124
- ...sources,
125
- `${sshTarget(device)}:${dest}`,
126
- ],
127
- { cwd, timeoutMs: 600_000 },
128
- );
192
+ return run("rsync", rsyncArgv(device, sources, dest), { cwd, timeoutMs: 600_000 });
193
+ }
194
+
195
+ /** The full exe.dev argv, built explicitly from guarded args (pure, testable). */
196
+ export function exeDevArgv(args: string[]): string[] {
197
+ for (const a of args)
198
+ if (!a || !EXE_ARG_RE.test(a))
199
+ throw Error(`exe.dev argument rejected (allowed charset [A-Za-z0-9._=-], no whitespace/metacharacters): ${JSON.stringify(a)}`);
200
+ return ["-o", "BatchMode=yes", "-o", "ConnectTimeout=15", "exe.dev", ...args, "--json"];
129
201
  }
130
202
 
131
203
  /** The exe.dev control plane (`ssh exe.dev <verb> --json`). */
132
204
  export async function exeDev<T = unknown>(args: string[], timeoutMs = 60_000): Promise<T> {
133
- const result = await run("ssh", ["-o", "BatchMode=yes", "-o", "ConnectTimeout=15", "exe.dev", ...args, "--json"], { timeoutMs });
205
+ const result = await run("ssh", exeDevArgv(args), { timeoutMs });
134
206
  const text = result.stdout.trim();
135
207
  try {
136
208
  return (text ? JSON.parse(text) : {}) as T;
@@ -10,17 +10,23 @@
10
10
  * crashes the caller: it reports and returns false so the boot can continue and
11
11
  * a later pass can retry.
12
12
  */
13
- import { chmodSync, closeSync, fsyncSync, mkdirSync, openSync, renameSync, rmSync, writeSync } from "node:fs";
13
+ import { chmodSync, closeSync, fsyncSync, openSync, renameSync, rmSync, writeSync } from "node:fs";
14
14
  import { execFile } from "node:child_process";
15
15
  import { basename, dirname, join } from "node:path";
16
16
  import { randomBytes } from "node:crypto";
17
+ import { ensurePrivateDir } from "./private-dir.js";
17
18
 
18
19
  export interface RestrictDeps {
19
20
  platform?: NodeJS.Platform;
20
21
  /** Injectable for tests: run a command, resolve stdout or reject. */
21
22
  execFile?: (cmd: string, args: string[]) => Promise<string>;
23
+ /** Injectable for tests: the temp-sibling name used for the atomic write. */
24
+ tempName?: (path: string) => string;
22
25
  }
23
26
 
27
+ /** icacls (like most argv parsers) reads a leading '-'/'/' word as a switch, not a filename. */
28
+ const optionShaped = (p: string) => p === "" || /^[-\/]/.test(p);
29
+
24
30
  /** orca's SIDs: SYSTEM and local Administrators can take ownership anyway. */
25
31
  const LOCAL_SYSTEM_SID = "S-1-5-18";
26
32
  const BUILTIN_ADMINISTRATORS_SID = "S-1-5-32-544";
@@ -49,6 +55,10 @@ export async function restrictToOwner(path: string, deps: RestrictDeps = {}): Pr
49
55
  const platform = deps.platform ?? process.platform;
50
56
  const exec = deps.execFile ?? execDefault;
51
57
  if (platform === "win32") {
58
+ if (optionShaped(path)) {
59
+ console.error(`private-file: refusing icacls on option-shaped path ${JSON.stringify(path)}`);
60
+ return false;
61
+ }
52
62
  try {
53
63
  const sid = await userSid({ execFile: exec });
54
64
  const grants = [LOCAL_SYSTEM_SID, BUILTIN_ADMINISTRATORS_SID, sid].map(
@@ -75,6 +85,10 @@ export async function restrictDirToOwner(path: string, deps: RestrictDeps = {}):
75
85
  const platform = deps.platform ?? process.platform;
76
86
  const exec = deps.execFile ?? execDefault;
77
87
  if (platform === "win32") {
88
+ if (optionShaped(path)) {
89
+ console.error(`private-file: refusing icacls on option-shaped path ${JSON.stringify(path)}`);
90
+ return false;
91
+ }
78
92
  try {
79
93
  const sid = await userSid({ execFile: exec });
80
94
  const grants = [LOCAL_SYSTEM_SID, BUILTIN_ADMINISTRATORS_SID, sid].map(
@@ -96,23 +110,31 @@ export async function restrictDirToOwner(path: string, deps: RestrictDeps = {}):
96
110
  }
97
111
  }
98
112
 
113
+ /** The unpublished sibling a write goes into first: `.<name>.<12 hex>.tmp` beside it. */
114
+ const tempSiblingName = (path: string) =>
115
+ join(dirname(path), `.${basename(path)}.${randomBytes(6).toString("hex")}.tmp`);
116
+
99
117
  /**
100
118
  * Atomic write for credential files (orca STA-3941 / paseo writePrivateFileAtomicSync):
101
119
  * temp file 0600 + fsync + rename, so readers only ever see the old bytes or the
102
- * complete new ones — a crash mid-write can never truncate a token. Then the
103
- * owner restriction runs on every platform. Throws only if the disk write
104
- * itself fails.
120
+ * complete new ones — a crash mid-write can never truncate a token. The temp
121
+ * file is created EXCLUSIVE ("wx"), so a planted symlink at the predictable
122
+ * `.name.*.tmp` shape cannot be truncated through, and the parent directory goes
123
+ * through ensurePrivateDir (an existing too-loose directory is tightened — or
124
+ * refused — instead of silently reused). Resolves with the owner-restriction
125
+ * outcome so callers can surface a failed pass instead of re-running it by
126
+ * hand. Throws only if the disk write itself fails.
105
127
  */
106
128
  export async function writePrivateFileAtomic(
107
129
  path: string,
108
130
  contents: string,
109
131
  deps: RestrictDeps = {},
110
- ): Promise<void> {
111
- mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
112
- const temp = join(dirname(path), `.${basename(path)}.${randomBytes(6).toString("hex")}.tmp`);
132
+ ): Promise<boolean> {
133
+ ensurePrivateDir(dirname(path));
134
+ const temp = (deps.tempName ?? tempSiblingName)(path);
113
135
  let fd: number | undefined;
114
136
  try {
115
- fd = openSync(temp, "w", 0o600);
137
+ fd = openSync(temp, "wx", 0o600);
116
138
  writeSync(fd, Buffer.from(contents, "utf8"));
117
139
  closeSync(fd);
118
140
  fd = undefined;
@@ -136,5 +158,5 @@ export async function writePrivateFileAtomic(
136
158
  /* best effort, like pairing-files' fsyncReadOnlySupported probe */
137
159
  }
138
160
  }
139
- await restrictToOwner(path, deps);
161
+ return await restrictToOwner(path, deps);
140
162
  }
@@ -93,6 +93,10 @@ export function validateToken(token: string) {
93
93
  export class NetworkRegistry {
94
94
  readonly db: DatabaseSync;
95
95
  readonly path: string;
96
+ /** run-9 u9: the owner-only restriction pass, exposed so callers can await
97
+ * it instead of the DACL landing invisibly after the secret. Still
98
+ * non-fatal (resolves false on failure) — the hub/TUI must boot either way. */
99
+ readonly restrictOwner: Promise<boolean>;
96
100
 
97
101
  constructor(path = join(dpiHome(), "network.sqlite")) {
98
102
  this.path = path;
@@ -104,8 +108,9 @@ export class NetworkRegistry {
104
108
  // The registry carries device tokens: sqlite owns the file's creation mode,
105
109
  // so tighten it here — 0600 on POSIX is ensurePrivateDir's job for the
106
110
  // directory; on Windows this installs the owner-only DACL (registry.ts is
107
- // shared by the hub, so keep it fire-and-forget and non-fatal).
108
- void restrictToOwner(path);
111
+ // shared by the hub, so it stays non-fatal; the promise is exposed as
112
+ // this.restrictOwner for callers that want to await the pass).
113
+ this.restrictOwner = restrictToOwner(path);
109
114
  this.db.exec("PRAGMA journal_mode=WAL; PRAGMA busy_timeout=3000; PRAGMA foreign_keys=ON;");
110
115
  }
111
116
 
@@ -88,6 +88,13 @@ if (values.help) {
88
88
  }
89
89
 
90
90
  const registry = new NetworkRegistry();
91
+ // R9 cold review: await the win32 owner-only DACL pass (non-fatal, logged)
92
+ // before the TUI starts talking to devices — the registry holds device tokens.
93
+ try {
94
+ await registry.restrictOwner;
95
+ } catch (error) {
96
+ console.error("tui: registry owner restriction failed:", error);
97
+ }
91
98
  const config = tryLoadNetworkConfig(process.env.INIT_CWD ?? process.cwd());
92
99
  if (config) syncConfigToRegistry(config, registry);
93
100
 
@@ -347,12 +347,12 @@ export function walkDirs(app: App, path: string): Promise<string | undefined | n
347
347
  app.setPending(null);
348
348
  if (!listing) return done(null);
349
349
  const items: SelectItem[] = [
350
- ...(listing.path ? [{ value: `use:${listing.path}`, label: `✓ Use ${sanitizeTerminal(listing.path)}` }] : []),
350
+ ...(listing.path ? [{ value: `use:${listing.path}`, label: `✓ Use ${oneLine(String(listing.path ?? ""))}` }] : []),
351
351
  ...(listing.path ? [{ value: listing.parent ?? "", label: listing.parent ? ".." : "⌂ start dirs" }] : []),
352
- ...listing.dirs.map((d) => ({ value: d.path, label: `${sanitizeTerminal(d.name)}/` })),
352
+ ...listing.dirs.map((d) => ({ value: d.path, label: `${oneLine(String(d.name ?? ""))}/` })),
353
353
  ];
354
354
  app.overlay(
355
- new Picker(`Working directory on ${sanitizeTerminal(app.device.name)}`, items, (item) => {
355
+ new Picker(`Working directory on ${oneLine(String(app.device.name ?? ""))}`, items, (item) => {
356
356
  app.closeOverlay();
357
357
  if (item.value.startsWith("use:")) done(item.value.slice(4));
358
358
  else void step(item.value);
@@ -370,7 +370,7 @@ function chooseModel(app: App, current?: string) {
370
370
  return new Promise<(typeof app.info.models)[number] | undefined>((done) => {
371
371
  const models = app.info.models;
372
372
  const picker = new Picker(
373
- `Model (${sanitizeTerminal(app.device.name)})`,
373
+ `Model (${oneLine(String(app.device.name ?? ""))})`,
374
374
  models.map((m) => ({ value: `${m.provider}/${m.id}`, label: oneLine(String(m.name ?? "")), description: `${oneLine(String(m.tier ?? ""))} │ ${oneLine(String(m.provider ?? ""))}` })),
375
375
  (item) => {
376
376
  app.closeOverlay();
@@ -440,7 +440,7 @@ export function pickAgent(app: App) {
440
440
  const icon = a.kind === "fork" ? "⑂" : a.kind === "subagent" ? "↳" : "◆";
441
441
  rows.push({
442
442
  value: String(a.id),
443
- label: `${" ".repeat(depth)}${icon} ${sanitizeTerminal(a.name)}${a.busy ? " ●" : ""}`,
443
+ label: `${" ".repeat(depth)}${icon} ${oneLine(String(a.name ?? ""))}${a.busy ? " ●" : ""}`,
444
444
  description: [a.kind === "fork" ? `fork @ #${oneLine(String(a.forkedAt ?? ""))}` : oneLine(String(a.kind ?? "")), a.background ? `${oneLine(String(a.background))} bg` : ""]
445
445
  .filter(Boolean)
446
446
  .join(" │ "),
@@ -449,7 +449,7 @@ export function pickAgent(app: App) {
449
449
  }
450
450
  };
451
451
  walk(agentTree(app.device.id, summary, false), 0);
452
- const picker = new Picker(`Agents in ${sanitizeTerminal(summary.name)}`, rows, (item) => {
452
+ const picker = new Picker(`Agents in ${oneLine(String(summary.name ?? ""))}`, rows, (item) => {
453
453
  app.closeOverlay();
454
454
  void app.attach(summary.id, Number(item.value));
455
455
  }, () => app.closeOverlay());
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "my-durable",
3
- "version": "0.0.113",
3
+ "version": "0.0.115",
4
4
  "description": "Durable Pi — the durable agent network: hub web UI, device backend daemon, TUI admin and the shared SDK, packaged as one runnable monorepo install",
5
5
  "license": "MIT",
6
6
  "repository": {