my-durable 0.0.71 → 0.0.72

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.
@@ -53,6 +53,8 @@ const describeError = (error: unknown) => (error instanceof Error ? error.messag
53
53
 
54
54
  /** The in-memory zip build is capped so `createBackup` cannot balloon the device's RAM. */
55
55
  export const MAX_BACKUP_BYTES = 256 * 1024 * 1024;
56
+ /** R17: how much of an entry-0 manifest may ride free of the total cap (real manifests are ~150 bytes). */
57
+ const MANIFEST_ALLOWANCE_BYTES = 64 * 1024;
56
58
  /** `ensurePrivateDir` (dpi-sdk) is synchronous and not injectable; the io carries the same 0700/0600 rule instead. */
57
59
  const DIR_MODE = 0o700;
58
60
  const FILE_MODE = 0o600;
@@ -383,8 +385,12 @@ export function readZipEntries(data: Uint8Array): ZipArchiveEntry[] {
383
385
  // backup ceiling — a pile of individually-legal entries must not add up
384
386
  // to an unbounded restore either. Entry 0 is the writer's own manifest,
385
387
  // which the write-side budget (walkHome) never counts, so a ceiling-sized
386
- // home must stay restorable (R15 cold review P2-1).
388
+ // home must stay restorable (R15 cold review P2-1). R17 (run-3 h2): the
389
+ // exemption is now BOUNDED to a manifest-plausible allowance (the real
390
+ // manifest is a fixed ~150-byte shape) — a hostile entry-0 declaring the
391
+ // full 256 MiB used to ride free and double the retained ceiling.
387
392
  if (i > 0 || name !== "manifest.json") totalDeclared += uncompressedSize;
393
+ else totalDeclared += Math.max(0, uncompressedSize - MANIFEST_ALLOWANCE_BYTES);
388
394
  if (totalDeclared > MAX_BACKUP_BYTES) {
389
395
  throw bad(`archive declares more than ${MAX_BACKUP_BYTES} bytes of entries`);
390
396
  }
@@ -59,8 +59,40 @@ const gitPaths = (paths: string[]): string[] => paths.map(gitPath);
59
59
 
60
60
  /** Child-process options, exported so a test can assert the Windows console
61
61
  * window stays hidden: a daemon that polls git must never flash a terminal. */
62
- export const GIT_EXEC_OPTS = (timeout: number) => ({ timeout, maxBuffer: 8 * 1024 * 1024, windowsHide: true });
63
- export const GH_EXEC_OPTS = (cwd: string, timeout: number) => ({ cwd, timeout, maxBuffer: 4 * 1024 * 1024, windowsHide: true });
62
+ /**
63
+ * R17 (run-3 h1 hardening): git/gh children run -C agent-writable repos where
64
+ * hooks/config are plantable. The daemon's process.env carries DPI_TOKEN
65
+ * (loadEnvFile) which shellEnv deliberately strips from agent processes —
66
+ * mirror that allowlist here so the token (and any future backend.env secret)
67
+ * never rides into repo-controlled hook environments.
68
+ */
69
+ const CHILD_ENV_ALLOWLIST = ["PATH", "HOME", "USER", "SHELL", "TMPDIR", "LANG", "TERM", "GIT_SSH_COMMAND", "SSH_AUTH_SOCK"];
70
+ // execFile `env` REPLACES the whole environment, and on win32 git/gh resolve
71
+ // home (USERPROFILE chain), config (APPDATA), temp (TEMP/TMP) and TLS
72
+ // (SystemRoot) from these — without them commit identity and gh auth break.
73
+ const WIN32_CHILD_ENV_ALLOWLIST = [
74
+ ...CHILD_ENV_ALLOWLIST,
75
+ "SYSTEMROOT", "SYSTEMDRIVE", "COMSPEC", "PATHEXT",
76
+ "TEMP", "TMP", "USERPROFILE", "HOMEDRIVE", "HOMEPATH",
77
+ "APPDATA", "LOCALAPPDATA", "PROGRAMFILES", "PROGRAMDATA",
78
+ ];
79
+ const childEnv = (): NodeJS.ProcessEnv => {
80
+ const allow = process.platform === "win32" ? WIN32_CHILD_ENV_ALLOWLIST : CHILD_ENV_ALLOWLIST;
81
+ return Object.fromEntries(allow.flatMap((k) => (process.env[k] ? [[k, process.env[k]]] : [])));
82
+ }
83
+ export const GIT_EXEC_OPTS = (timeout: number) => ({
84
+ timeout,
85
+ maxBuffer: 8 * 1024 * 1024,
86
+ windowsHide: true,
87
+ env: childEnv(),
88
+ });
89
+ export const GH_EXEC_OPTS = (cwd: string, timeout: number) => ({
90
+ cwd,
91
+ timeout,
92
+ maxBuffer: 4 * 1024 * 1024,
93
+ windowsHide: true,
94
+ env: childEnv(),
95
+ });
64
96
 
65
97
  /** Test seam for counting/driving spawns: `node:child_process`'s ESM namespace
66
98
  * is not redefinable, so `mock.method` cannot reach `execFile`. Pass nothing
@@ -80,6 +80,7 @@ import { NotifySinks, type DeliveryResult, type SinkInput, type SinkRecord } fro
80
80
  import { zipSync, EXPORT_RAW_LIMIT_BYTES, type ZipEntry } from "./zip.js";
81
81
  import { salvageFailureNote, salvageSessionDb } from "./salvage.js";
82
82
  import { mkdirSync, writeFileSync, readFileSync, unlinkSync, readdirSync, renameSync, statSync } from "node:fs";
83
+ import { lstat } from "node:fs/promises";
83
84
  import { ensurePrivateDir } from "../../dpi-sdk/src/node/private-dir.js";
84
85
  import { join, dirname, relative, resolve, sep } from "node:path";
85
86
  import { homedir, hostname, platform } from "node:os";
@@ -1016,7 +1017,29 @@ export class Store {
1016
1017
  // ancestor was found at all, judging the raw spelling lexically would
1017
1018
  // resurrect the exact symlink escape this walk exists to close.
1018
1019
  if (resolvedAncestor === undefined) throw invalid("path must live under a start dir");
1019
- candidate = join(resolvedAncestor, ...tail);
1020
+ // R17 (run-3 h1): lstat every re-appended tail component. The walk only
1021
+ // calls realpath, which cannot see a DANGLING symlink — a link component
1022
+ // pointing at a nonexistent path would ride the tail verbatim and be
1023
+ // judged lexically. Any symlink in the tail is resolved-and-rejudged;
1024
+ // a dangling one is refused (fail closed on what the walk cannot see).
1025
+ let walked = resolvedAncestor;
1026
+ for (const part of tail) {
1027
+ const next = join(walked, part);
1028
+ let isLink = false;
1029
+ try {
1030
+ isLink = (await lstat(next)).isSymbolicLink();
1031
+ } catch {
1032
+ isLink = false; // plain missing component: fine, the path is new
1033
+ }
1034
+ if (isLink) {
1035
+ const linked = await realpath(next).catch(() => undefined);
1036
+ if (linked === undefined) throw invalid("path must live under a start dir"); // dangling link: refuse
1037
+ walked = linked; // existing link target: continue the walk from truth
1038
+ } else {
1039
+ walked = next;
1040
+ }
1041
+ }
1042
+ candidate = walked;
1020
1043
  }
1021
1044
  if (!this.underRoots(candidate, await this.startDirRoots())) throw invalid("path must live under a start dir");
1022
1045
  return candidate;
@@ -182,7 +182,7 @@ export interface TelegramRegistryFile {
182
182
  codes: TelegramBindCode[];
183
183
  }
184
184
 
185
- export type TelegramBridgeErrorCode = "invalid";
185
+ export type TelegramBridgeErrorCode = "invalid" | "registry_changed";
186
186
 
187
187
  /** Typed failure for the mutation paths (`bind`) so a UI can answer without string matching. */
188
188
  export class TelegramBridgeError extends Error {
@@ -465,6 +465,11 @@ export class TelegramBridge {
465
465
  targetId = sessionId;
466
466
  }
467
467
  return this.run(async () => {
468
+ // R17 (run-3 h4): the CLI is the SECOND writer — re-read the registry
469
+ // (adopt foreign state) before snapshotting, so a daemon commit that
470
+ // landed since open() is not clobbered by our persist CAS.
471
+ if (!(await this.syncForeign()))
472
+ throw new TelegramBridgeError("registry_changed", `registry ${this.filePath} is missing/unreadable; refusing to bind`);
468
473
  const now = this.now();
469
474
  const draft = this.snapshot();
470
475
  draft.codes = draft.codes.filter((code) => Date.parse(code.expiresAt) > now); // prune the dead ones
@@ -486,6 +491,8 @@ export class TelegramBridge {
486
491
  /** Remove the first binding whose chat id starts with `chatPrefix`; returns the chat id, or undefined when none matched. */
487
492
  async unbind(chatPrefix: string): Promise<number | undefined> {
488
493
  return this.run(async () => {
494
+ // R17 (run-3 h4): same second-writer discipline as bind().
495
+ if (!(await this.syncForeign())) return undefined;
489
496
  const draft = this.snapshot();
490
497
  const hit = draft.chats.find((binding) => String(binding.chatId).startsWith(chatPrefix));
491
498
  if (hit === undefined) return undefined;
@@ -598,7 +605,23 @@ export class TelegramBridge {
598
605
  */
599
606
  private async syncForeign(): Promise<boolean> {
600
607
  try {
601
- if (!(await this.io.exists(this.filePath))) return true;
608
+ // R17 (run-3 h4): an ABSENT registry is either a FRESH device (we have
609
+ // never known a registry: registryText null — load()'s "fresh device"
610
+ // semantics) or the operator revoking by removal while the daemon runs
611
+ // (or an unreadable file: exists() maps every stat failure to absent).
612
+ // Fresh → adopt the empty state and continue (bind works, no bindings
613
+ // exist to authorize anything). Known-then-gone → fail CLOSED: no
614
+ // dispatch on stale memory, and no persist either — a commit would
615
+ // resurrect the deleted file with the revoked bindings.
616
+ if (!(await this.io.exists(this.filePath))) {
617
+ if (this.registryText === null) {
618
+ this.adopt({ version: TELEGRAM_REGISTRY_VERSION, offset: this.offset, chats: [], codes: [] });
619
+ return true; // fresh: nothing to adopt, nothing to clobber
620
+ }
621
+ this.mainIsGood = false; // an absent main must not be "refreshed" into .bak
622
+ this.warn(`registry ${this.filePath} vanished; skipping the update (no dispatch, no persist)`);
623
+ return false;
624
+ }
602
625
  const text = await this.io.readFile(this.filePath);
603
626
  if (text === this.registryText) return true; // still our own last write
604
627
  const file = coerceRegistry(JSON.parse(text), this.now());
@@ -609,6 +632,7 @@ export class TelegramBridge {
609
632
  // Fail CLOSED (R15 cold review P3-1): with an unreadable/unparseable
610
633
  // registry the in-memory bindings cannot be trusted to reflect the
611
634
  // operator's intent — authorize nothing until the file is healthy.
635
+ this.mainIsGood = false; // the next persist must NOT bake these bytes into .bak
612
636
  this.warn(`could not re-read ${this.filePath} before dispatch; skipping the update`, error);
613
637
  return false;
614
638
  }
@@ -639,6 +663,22 @@ export class TelegramBridge {
639
663
  * new bytes through the io's atomic write, then 0600.
640
664
  */
641
665
  private async persist(draft: TelegramRegistryFile): Promise<void> {
666
+ // R17 (run-3 h4): the registry has TWO writers (daemon + dpi telegram
667
+ // CLI). Write-after-read validation: if the file's bytes changed since we
668
+ // last saw them, our snapshot is stale — writing it would clobber the
669
+ // foreign commit (un-spend a code, revert a /stop). Fail loudly instead.
670
+ if (this.registryText !== null && (await this.io.exists(this.filePath))) {
671
+ const current = await this.io.readFile(this.filePath);
672
+ if (current !== this.registryText) {
673
+ this.mainIsGood = false;
674
+ throw new TelegramBridgeError(
675
+ "registry_changed",
676
+ `registry changed under us (foreign write); re-open or retry — refusing to clobber ${this.filePath}`,
677
+ );
678
+ }
679
+ }
680
+ // registryText === null means no known baseline (fresh device or the
681
+ // load()-time recovery rewrite) — those writes are legitimate.
642
682
  if (this.mainIsGood && (await this.io.exists(this.filePath))) {
643
683
  try {
644
684
  const previous = await this.io.readFile(this.filePath);
@@ -724,10 +764,10 @@ export class TelegramBridge {
724
764
  /** Acknowledge first (persist the new offset), then handle. Never both-half-heartedly. */
725
765
  private async handle(update: TelegramUpdate): Promise<void> {
726
766
  const synced = await this.syncForeign();
767
+ if (!synced) return; // acknowledged (Telegram will redeliver), NOT authorized and NOT persisted — a stale snapshot must never become file truth again
727
768
  await this.commit((draft) => {
728
769
  draft.offset = Math.max(draft.offset, update.updateId + 1);
729
770
  });
730
- if (!synced) return; // acknowledged, but NOT authorized on stale state
731
771
  if (!update.message) return; // non-message or non-text: acknowledged, ignored
732
772
  await this.dispatch(
733
773
  update.message.chatId,
@@ -105,9 +105,24 @@ export function scrubSecrets(value: string): string {
105
105
  out = out.replace(/([?&]code=)[A-Za-z0-9_-]+/g, "$1<redacted>");
106
106
  // v2 offer links: the secret IS the #offer= fragment payload — redact it wherever a URL shows up.
107
107
  out = out.replace(/(#offer=)[A-Za-z0-9_-]+/g, "$1<redacted>");
108
- // R16 (run-2 h7): a requireTls-denied GET /share/<token> lands the FULL
109
- // capability token in audit path samples — the token IS the share secret.
110
- out = out.replace(/(\/share\/)[A-Za-z0-9_-]{20,32}(?![A-Za-z0-9_-])/g, "$1<redacted>");
108
+ // R16 (run-2 h7) + R17 (run-3 h10): a denied request lands the FULL share
109
+ // capability token in audit path samples — the token IS the secret. The
110
+ // prefix spelling is ATTACKER-CONTROLLED (/share/, /api/shares/, /Share/,
111
+ // /%73hare/...), so anchor on a *share-shaped* path segment (case-blind,
112
+ // percent-encoding tolerated) followed by the 20-32-char token run — not on
113
+ // any one literal prefix. Bare 20-32-char values elsewhere (audit enums
114
+ // like "foreign_subscription") stay readable.
115
+ out = out.replace(
116
+ /(\/[a-z0-9%]*shares?\/)[A-Za-z0-9_-]{20,32}(?![A-Za-z0-9_-])/gi,
117
+ "$1<redacted>",
118
+ );
119
+ // Encoded spellings (/%73hare/) hide the literal "share" — any
120
+ // percent-bearing path segment followed by a token-shaped run is treated
121
+ // the same.
122
+ out = out.replace(
123
+ /(\/[^\s"']*%[^\s"']*\/)[A-Za-z0-9_-]{20,32}(?![A-Za-z0-9_-])/gi,
124
+ "$1<redacted>",
125
+ );
111
126
  // Credential material without its prefix (slices, echo): 43-char base64url runs.
112
127
  out = out.replace(/(?<![A-Za-z0-9_-])[A-Za-z0-9_-]{43}(?![A-Za-z0-9_-])/g, "<redacted>");
113
128
  // Pairing codes as standalone values ("code":"AB2C7DEF" / "ABCD2345EF67") but not ordinary words.
@@ -226,10 +226,20 @@ export class DeviceMonitor {
226
226
  continue;
227
227
  }
228
228
  try {
229
+ // R17 (run-3 h8): abort the losing probe — a timed-out fetch keeps
230
+ // buffering (up to REST_TIMEOUT_MS) while the backoff loop starts the
231
+ // next one, multiplying an unbounded read. The per-probe controller
232
+ // also stops reading the moment the race is lost.
233
+ const probeCtl = new AbortController();
234
+ const onOuterAbort = () => probeCtl.abort();
235
+ signal?.addEventListener("abort", onOuterAbort, { once: true });
229
236
  const probe = await Promise.race([
230
- transport.request({ method: "GET", path: "/v1/device" }, signal),
237
+ transport.request({ method: "GET", path: "/v1/device" }, probeCtl.signal),
231
238
  sleep(6_000, signal).then(() => null),
232
- ]);
239
+ ]).finally(() => {
240
+ signal?.removeEventListener("abort", onOuterAbort);
241
+ probeCtl.abort();
242
+ });
233
243
  if (probe === null) throw new DpiError("offline", `Probe timeout for ${device.url}`);
234
244
  if (probe.status === 401)
235
245
  throw new DpiError("unauthorized", "Device rejected the token", 401);
@@ -72,6 +72,11 @@ export function proxy(
72
72
  idempotencyKey: (() => {
73
73
  const k = req.get("idempotency-key");
74
74
  if (k === undefined) return undefined;
75
+ // R17 (run-3 h8): an EMPTY key would suppress the R9 auto-key
76
+ // derivation and then drop as falsy at frame build — the mutation
77
+ // goes out with NO dedup key at all. Refuse it like the over-long.
78
+ if (k.trim() === "")
79
+ throw new DpiError("invalid", "idempotency-key must not be empty", 400);
75
80
  if (k.length > 256)
76
81
  throw new DpiError("invalid", "idempotency-key longer than 256 chars", 400);
77
82
  return k;
@@ -9,7 +9,10 @@
9
9
  import { DpiClient } from "../../../../dpi-sdk/src/client.js";
10
10
  import { DpiError } from "../../../../dpi-sdk/src/errors.js";
11
11
  import { validateRestRequest } from "../../../../dpi-sdk/src/protocol/tunnel.js";
12
- import { REST_PATH_PREFIX } from "../../../../dpi-sdk/src/protocol/limits.js";
12
+ import {
13
+ LOGICAL_MESSAGE_MAX_BYTES,
14
+ REST_PATH_PREFIX,
15
+ } from "../../../../dpi-sdk/src/protocol/limits.js";
13
16
  import type { Frame } from "../../../../dpi-sdk/src/api.js";
14
17
  import type { DeviceRow } from "../../../../dpi-sdk/src/node/registry.js";
15
18
 
@@ -110,11 +113,19 @@ export class LanTransport implements DeviceTransport {
110
113
  if (signal?.aborted) throw cause;
111
114
  throw new DpiError("offline", `Cannot reach ${this.client.baseUrl}`, 0, { cause });
112
115
  }
113
- const raw = Buffer.from(await response.arrayBuffer());
116
+ // R17 (run-3 h8): size parity with the tunnel leg — the device connector
117
+ // caps its own fetches (16 MiB textual / binary cap) and reassembly
118
+ // budgets bound the tunnel; this leg used to buffer arrayBuffer() with NO
119
+ // cap, so a hostile LAN peer (or compromised device) could OOM the whole
120
+ // hub process. Mirror the connector's capped reader.
114
121
  const ct = response.headers.get("content-type") ?? undefined;
122
+ const textual = ct === undefined || TEXTUAL_CT_RE.test(ct);
123
+ const capped = await readBodyCapped(response, textual ? LOGICAL_MESSAGE_MAX_BYTES : BINARY_RESPONSE_MAX_BYTES);
124
+ if (!capped.ok)
125
+ throw new DpiError("invalid", `device answer exceeds ${textual ? "16 MiB" : "12 MB"}`, 413);
126
+ const raw = capped.bytes;
115
127
  // Textual responses keep the legacy plain-string shape; binaries are base64-flagged
116
128
  // so the proxy can serve bytes byte-exact (R8 binary passthrough).
117
- const textual = ct === undefined || TEXTUAL_CT_RE.test(ct);
118
129
  return {
119
130
  status: response.status,
120
131
  contentType: ct,
@@ -148,3 +159,36 @@ export function transportFor(
148
159
  if (row.transport === "tunnel") return tunnel ? tunnel.dispatcherFor(row) : undefined;
149
160
  return new LanTransport(row);
150
161
  }
162
+
163
+ /**
164
+ * R17 (run-3 h8): the binary cap mirrors the device connector's own reader
165
+ * (tunnel.ts uses 12_000_000 — aligned exactly so a binary that passes one
166
+ * leg never surprises the other).
167
+ */
168
+ const BINARY_RESPONSE_MAX_BYTES = 12_000_000;
169
+
170
+ async function readBodyCapped(
171
+ res: Response,
172
+ cap: number,
173
+ ): Promise<{ ok: true; bytes: Buffer } | { ok: false }> {
174
+ const declared = Number(res.headers.get("content-length"));
175
+ if (Number.isFinite(declared) && declared > cap) {
176
+ await res.body?.cancel().catch(() => {});
177
+ return { ok: false };
178
+ }
179
+ if (!res.body) return { ok: true, bytes: Buffer.alloc(0) };
180
+ const reader = res.body.getReader();
181
+ const parts: Uint8Array[] = [];
182
+ let total = 0;
183
+ for (;;) {
184
+ const { done, value } = await reader.read();
185
+ if (done) break;
186
+ total += value.byteLength;
187
+ if (total > cap) {
188
+ await reader.cancel().catch(() => {});
189
+ return { ok: false };
190
+ }
191
+ parts.push(value);
192
+ }
193
+ return { ok: true, bytes: Buffer.concat(parts) };
194
+ }
@@ -99,6 +99,16 @@ 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
+ // R17 (run-3 h12): these scalars reach generated shell scripts, backend.env
103
+ // lines and unit/plist content — a newline injected env lines (duplicate
104
+ // DPI_TOKEN/DPI_START_DIRS, last-wins at daemon boot) and quote/$/backtick
105
+ // executed command substitution inside the double-quoted script segments.
106
+ // Refuse control characters and shell metacharacters at parse time.
107
+ const pathish = (v: string, field: string) => {
108
+ if (/[\n\r\0]/.test(v)) throw Error(`${where}.${field} must be a single line`);
109
+ if (/["'`$\\]/.test(v)) throw Error(`${where}.${field} must not contain quotes, $ or backslash`);
110
+ return v;
111
+ };
102
112
  const device: NetDevice = {
103
113
  id,
104
114
  name: typeof d.name === "string" ? d.name : id,
@@ -106,10 +116,10 @@ export function parseNetworkConfig(text: string, file = NETWORK_FILE): NetworkCo
106
116
  url: "",
107
117
  port,
108
118
  node: Number(d.node ?? 24),
109
- codeDir: typeof d.code_dir === "string" ? d.code_dir : "~/dpi",
110
- homeDir: typeof d.home_dir === "string" ? d.home_dir : "~/.dpi",
111
- startDirs: d.start_dirs === undefined ? [DEFAULT_START_DIR] : strList(d.start_dirs, `${where}.start_dirs`),
112
- host: d.host === undefined ? (kind === "local" ? "127.0.0.1" : "0.0.0.0") : str(d.host, `${where}.host`),
119
+ codeDir: pathish(typeof d.code_dir === "string" ? d.code_dir : "~/dpi", "code_dir"),
120
+ homeDir: pathish(typeof d.home_dir === "string" ? d.home_dir : "~/.dpi", "home_dir"),
121
+ startDirs: d.start_dirs === undefined ? [DEFAULT_START_DIR] : strList(d.start_dirs, `${where}.start_dirs`).map((r: string) => pathish(r, "start_dirs")),
122
+ host: d.host === undefined ? (kind === "local" ? "127.0.0.1" : "0.0.0.0") : pathish(str(d.host, `${where}.host`), "host"),
113
123
  envKeys: d.env_keys === undefined ? [] : strList(d.env_keys, `${where}.env_keys`),
114
124
  env: {},
115
125
  ...(typeof d.token_env === "string" ? { tokenEnv: d.token_env } : {}),
@@ -119,7 +129,15 @@ export function parseNetworkConfig(text: string, file = NETWORK_FILE): NetworkCo
119
129
  if (d.service !== "launchd" && d.service !== "systemd") throw Error(`${where}.service must be launchd or systemd`);
120
130
  device.service = d.service;
121
131
  }
122
- if (kind === "ssh") device.ssh = str(d.ssh, `${where}.ssh`);
132
+ if (kind === "ssh") {
133
+ const target = str(d.ssh, `${where}.ssh`);
134
+ // R17 (run-3 h12): the ssh scalar is a leading argv element — a leading
135
+ // dash would be parsed as an ssh OPTION (e.g. -oProxyCommand=…). Accept
136
+ // only a user@host[:port] shape.
137
+ if (!/^[A-Za-z0-9._%-]+@[A-Za-z0-9.-]+(:\d+)?$/.test(target))
138
+ throw Error(`${where}.ssh must be user@host[:port] (no options, no metacharacters)`);
139
+ device.ssh = target;
140
+ }
123
141
  if (kind === "exe-dev") {
124
142
  device.vm = str(d.vm, `${where}.vm`);
125
143
  if (!/^[a-z0-9][a-z0-9-]{1,62}$/.test(device.vm)) throw Error(`${where}.vm is not a valid exe.dev name`);
@@ -113,6 +113,11 @@ async function writeEnv(device: NetDevice, ctx: DriverContext, rotate = false) {
113
113
  for (const [k, v] of Object.entries(device.env))
114
114
  if (typeof v !== "string" || !v || /[\n\r]/.test(v))
115
115
  ctx.log(`warning: device ${device.id} env ${k} has no value or contains a newline — skipped`);
116
+ // R17 (run-3 h12): config.ts rejects CR/LF in these at parse; the sink
117
+ // guards too so a future field can never reintroduce the line-injection.
118
+ for (const [k, v] of [["DPI_HOST", device.host], ["DPI_START_DIRS", device.startDirs.join(":")]] as const)
119
+ if (/[\n\r]/.test(v))
120
+ throw Error(`device ${device.id}: ${k} value contains a newline — refusing to write backend.env`);
116
121
  const home = shPath(device.homeDir);
117
122
  const body = [
118
123
  `DPI_DEVICE_NAME=${device.id}`,
@@ -182,7 +187,12 @@ async function installService(device: NetDevice, ctx: DriverContext) {
182
187
  };
183
188
  const deployDir = join(ctx.config.root, "apps/dpi-backend/deploy");
184
189
  if (device.service === "launchd") {
185
- const plist = fill(readFileSync(join(deployDir, "dpi-backend.plist"), "utf8"), values);
190
+ // R17 (run-3 h12): plist is XML — escape & and < in the values (mirrors
191
+ // daemon.ts launchdPlist) so no new element can be forged.
192
+ const xmlValues = Object.fromEntries(
193
+ Object.entries(values).map(([k, v]) => [k, v.replaceAll("&", "&amp;").replaceAll("<", "&lt;")]),
194
+ );
195
+ const plist = fill(readFileSync(join(deployDir, "dpi-backend.plist"), "utf8"), xmlValues);
186
196
  await exec(
187
197
  device,
188
198
  `P="$HOME/Library/LaunchAgents/${SERVICE_LABEL}.plist"
@@ -653,7 +653,9 @@ export class App {
653
653
 
654
654
  /** A long fetch (dirs on a cold tunnel) holds the message line with a ◌ note. */
655
655
  setPending(text: string | null) {
656
- this.pendingNote = text;
656
+ // R17 (run-3 h5): pending notes interpolate device-sourced paths/names
657
+ // (walkDirs/newSession feed them) — sanitize at the chokepoint.
658
+ this.pendingNote = text === null ? null : sanitizeTerminal(text);
657
659
  this.requestRender();
658
660
  }
659
661
 
@@ -1231,7 +1233,7 @@ export class App {
1231
1233
  lines.push(
1232
1234
  AGENT_TABS.map((t) => (t.id === this.tab ? c.inverse(c.bold(` ${t.label} `)) : c.muted(` ${t.label} `))).join(
1233
1235
  c.muted("│"),
1234
- ) + c.muted(rep(" ", Math.max(0, w - 62))) + c.muted(this.model.state.agent.model?.modelId?.split("/").pop() ?? ""),
1236
+ ) + c.muted(rep(" ", Math.max(0, w - 62))) + c.muted(sanitizeTerminal(this.model.state.agent.model?.modelId?.split("/").pop() ?? "")),
1235
1237
  );
1236
1238
  lines.push(c.muted(rep(box.h, w)));
1237
1239
  const inner = h - 3;
@@ -1355,12 +1357,12 @@ export class App {
1355
1357
  // config tab
1356
1358
  const model = this.model.state.agent.model;
1357
1359
  const lines = [
1358
- ` ${c.muted("model")} ${c.text(model?.modelId ?? "—")}`,
1359
- ` ${c.muted("provider")} ${c.muted(model?.provider ?? "—")}`,
1360
+ ` ${c.muted("model")} ${c.text(sanitizeTerminal(model?.modelId ?? "—"))}`,
1361
+ ` ${c.muted("provider")} ${c.muted(sanitizeTerminal(model?.provider ?? "—"))}`,
1360
1362
  ` ${c.muted("thinking")} ${c.text(String(this.model.state.agent.thinkingLevel ?? "low"))} ${c.muted("(y cycles)")}`,
1361
1363
  "",
1362
- ` ${c.muted("device")} ${c.text(this.device.id)} ${c.muted(this.device.url)}`,
1363
- ` ${c.muted("start dirs")} ${c.muted(this.info.startDirs.join(", ").slice(0, w - 18) || "—")}`,
1364
+ ` ${c.muted("device")} ${c.text(sanitizeTerminal(this.device.id))} ${c.muted(sanitizeTerminal(this.device.url))}`,
1365
+ ` ${c.muted("start dirs")} ${c.muted(sanitizeTerminal(this.info.startDirs.join(", ")).slice(0, w - 18) || "—")}`,
1364
1366
  ];
1365
1367
  return lines;
1366
1368
  }
@@ -194,7 +194,7 @@ export async function runCommand(app: App, text: string): Promise<boolean> {
194
194
  // not skip that gate (R4 finding 4: the palette entry used to wipe the
195
195
  // context unconditionally). A typed handoff note carries its own intent.
196
196
  if (!arg) {
197
- const ok = await app.prompt(`Reset ${app.sessionSummary()?.name ?? "context"}? y/n`, "");
197
+ const ok = await app.prompt(`Reset ${sanitizeTerminal(app.sessionSummary()?.name ?? "context")}? y/n`, "");
198
198
  if (ok === undefined || !ok.trim().toLowerCase().startsWith("y"))
199
199
  return app.flash("reset cancelled"), true;
200
200
  }
@@ -227,11 +227,11 @@ export async function runCommand(app: App, text: string): Promise<boolean> {
227
227
  app.overlay(
228
228
  new Panel(() => {
229
229
  const tasks = app.session.state.tasks;
230
- const lines = [c.bold(c.accent(`Live tasks in ${app.sessionSummary()?.name ?? "session"}`)), ""];
230
+ const lines = [c.bold(c.accent(`Live tasks in ${sanitizeTerminal(app.sessionSummary()?.name ?? "session")}`)), ""];
231
231
  if (!tasks.length) lines.push(c.muted("No live tasks."));
232
232
  for (const t of tasks)
233
233
  lines.push(
234
- `${t.background ? c.secondary("◌ bg") : c.warn("● fg")} #${t.id} ${t.kind} ${c.muted(`agent #${t.conversationId} │ ${t.state.status}${t.state.phase ? `/${t.state.phase}` : ""}`)}`,
234
+ `${t.background ? c.secondary("◌ bg") : c.warn("● fg")} #${t.id} ${sanitizeTerminal(t.kind)} ${c.muted(sanitizeTerminal(`agent #${t.conversationId} │ ${t.state.status}${t.state.phase ? `/${t.state.phase}` : ""}`))}`,
235
235
  );
236
236
  lines.push("", c.muted("esc close"));
237
237
  return lines;
@@ -55,7 +55,9 @@ export function isValidConnectUrl(candidate: string): boolean {
55
55
  }
56
56
 
57
57
  function fail(message: string): never {
58
- process.stderr.write(`${message}\n`);
58
+ // R17 (run-3 h5): device-supplied strings (catalog lists, DpiError text)
59
+ // reach stderr here — sanitize for consistency with the frame boundaries.
60
+ process.stderr.write(`${sanitizeTerminal(message)}\n`);
59
61
  process.exit(1);
60
62
  }
61
63
 
@@ -16,6 +16,7 @@ import type { App } from "./app.ts";
16
16
  import { wrapTextWithAnsi } from "@earendil-works/pi-tui";
17
17
  import { Panel } from "./pickers.ts";
18
18
  import { c } from "./theme.ts";
19
+ import { sanitizeTerminal } from "./sanitize.ts";
19
20
 
20
21
  export interface PairArgs {
21
22
  code?: string;
@@ -151,25 +152,25 @@ export function pairingViewLines(
151
152
  hubOrigin?: string,
152
153
  ): string[] {
153
154
  const lines: string[] = [c.bold(c.accent("Pair this device"))];
154
- if (hubOrigin) lines.push(c.muted(`hub: ${hubOrigin}`));
155
+ if (hubOrigin) lines.push(c.muted(`hub: ${sanitizeTerminal(hubOrigin)}`));
155
156
  if (!status) {
156
- lines.push(c.muted(note));
157
+ lines.push(c.muted(sanitizeTerminal(note)));
157
158
  return lines.flatMap((line) => wrapTextWithAnsi(line, Math.max(1, width)));
158
159
  }
159
- lines.push(c.muted(`device: ${status.deviceName ?? status.deviceUid ?? "?"} · uid ${status.deviceUid ?? "?"}`));
160
+ lines.push(c.muted(sanitizeTerminal(`device: ${status.deviceName ?? status.deviceUid ?? "?"} · uid ${status.deviceUid ?? "?"}`)));
160
161
  lines.push("");
161
162
  lines.push(c.bold("key fingerprint (compare with the hub wizard):"));
162
- for (const line of wrapFingerprint(status.fingerprint, width)) lines.push(` ${c.secondary(line)}`);
163
+ for (const line of wrapFingerprint(status.fingerprint, width)) lines.push(` ${c.secondary(sanitizeTerminal(line))}`);
163
164
  lines.push("");
164
165
  if (status.pending) {
165
166
  lines.push(c.warn("Awaiting approval on the hub…"));
166
- if (status.pending.note) lines.push(c.muted(` ${status.pending.note}`));
167
+ if (status.pending.note) lines.push(c.muted(` ${sanitizeTerminal(status.pending.note)}`));
167
168
  } else if (status.lastError) {
168
- lines.push(c.err(describePairingError(status.lastError)));
169
+ lines.push(c.err(sanitizeTerminal(describePairingError(status.lastError))));
169
170
  if (status.state === "paired")
170
- lines.push(c.muted(`Existing pairing to ${status.hubOrigin} is unchanged.`));
171
+ lines.push(c.muted(sanitizeTerminal(`Existing pairing to ${status.hubOrigin} is unchanged.`)));
171
172
  } else if (status.state === "paired") {
172
- lines.push(c.ok(`Paired to ${status.hubOrigin} (generation ${status.generation}).`));
173
+ lines.push(c.ok(sanitizeTerminal(`Paired to ${status.hubOrigin} (generation ${status.generation}).`)));
173
174
  lines.push(c.muted("The connector keeps the tunnel up; /pair again to re-pair."));
174
175
  } else if (status.state === "revoked") {
175
176
  lines.push(c.warn("Revoked on the hub. /pair CODE to pair again."));
@@ -426,7 +426,7 @@ async function welcomeLocal(app: App) {
426
426
  const id = suggestDeviceId(probe.info.hostname, probe.info.name);
427
427
  stepPicker(
428
428
  app,
429
- `Local backend: ${probe.info.name || probe.info.hostname || url}`,
429
+ `Local backend: ${sanitizeTerminal(probe.info.name || probe.info.hostname || url)}`,
430
430
  [{ value: "open", label: `Save as "${id}" and open`, description: `${url} │ token from DPI_TOKEN / backend.env` }],
431
431
  // local.token was read BEFORE a first boot may have written backend.env —
432
432
  // re-resolve, the file exists now.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "my-durable",
3
- "version": "0.0.71",
3
+ "version": "0.0.72",
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": {