my-durable 0.0.71 → 0.0.73

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 (31) hide show
  1. package/README.md +2 -2
  2. package/apps/dpi-backend/API.md +1 -0
  3. package/apps/dpi-backend/src/backup.ts +25 -1
  4. package/apps/dpi-backend/src/git.ts +34 -2
  5. package/apps/dpi-backend/src/routes.ts +10 -1
  6. package/apps/dpi-backend/src/store.ts +149 -2
  7. package/apps/dpi-backend/src/telegram.ts +141 -4
  8. package/apps/dpi-playground/apps/dpi-playground-fe/dist/assets/index-BE-fN78Y.css +1 -0
  9. package/apps/dpi-playground/apps/dpi-playground-fe/dist/assets/index-C9TcDwN6.js +82 -0
  10. package/apps/dpi-playground/apps/dpi-playground-fe/dist/index.html +2 -2
  11. package/apps/dpi-playground/apps/dpi-playground-fe/src/components/NetworkSidebar.vue +43 -4
  12. package/apps/dpi-playground/apps/dpi-playground-hub/src/audit.ts +32 -3
  13. package/apps/dpi-playground/apps/dpi-playground-hub/src/monitor.ts +18 -4
  14. package/apps/dpi-playground/apps/dpi-playground-hub/src/mux.ts +6 -2
  15. package/apps/dpi-playground/apps/dpi-playground-hub/src/proxy.ts +5 -0
  16. package/apps/dpi-playground/apps/dpi-playground-hub/src/transport.ts +59 -3
  17. package/apps/dpi-playground/apps/dpi-playground-hub/src/tunnel-transport.ts +1 -1
  18. package/apps/dpi-sdk/src/api.ts +13 -1
  19. package/apps/dpi-sdk/src/client.ts +12 -5
  20. package/apps/dpi-sdk/src/node/config.ts +34 -5
  21. package/apps/dpi-sdk/src/node/drivers.ts +15 -1
  22. package/apps/dpi-tui/src/app.ts +8 -6
  23. package/apps/dpi-tui/src/commands.ts +44 -4
  24. package/apps/dpi-tui/src/main.ts +3 -1
  25. package/apps/dpi-tui/src/pairing.ts +11 -10
  26. package/apps/dpi-tui/src/views.ts +1 -1
  27. package/apps/dpi-tui/src/welcome.ts +1 -1
  28. package/docs/host-project-checklist.md +1 -1
  29. package/package.json +1 -1
  30. package/apps/dpi-playground/apps/dpi-playground-fe/dist/assets/index-CpNu1wqa.js +0 -81
  31. package/apps/dpi-playground/apps/dpi-playground-fe/dist/assets/index-DSU1QhGO.css +0 -1
@@ -7,8 +7,8 @@
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-CpNu1wqa.js"></script>
11
- <link rel="stylesheet" crossorigin href="/assets/index-DSU1QhGO.css">
10
+ <script type="module" crossorigin src="/assets/index-C9TcDwN6.js"></script>
11
+ <link rel="stylesheet" crossorigin href="/assets/index-BE-fN78Y.css">
12
12
  </head>
13
13
  <body>
14
14
  <div id="app"></div>
@@ -46,7 +46,16 @@ const list = ref<HTMLElement>();
46
46
  * own matches (names/cwds/models) so results do not depend on how fresh the
47
47
  * hub's tree is. Transcripts are not scanned — that needs an FTS index. */
48
48
  const query = ref("");
49
- const deviceHits = ref<{ deviceId: string; name: string; cwd: string; id: string; where: string[] }[]>([]);
49
+ const deviceHits = ref<
50
+ {
51
+ deviceId: string;
52
+ name: string;
53
+ cwd: string;
54
+ id: string;
55
+ where: string[];
56
+ hits: { agent: string; entry: number; kind: string; text: string }[];
57
+ }[]
58
+ >([]);
50
59
  const searching = ref(false);
51
60
  const needle = computed(() => query.value.trim().toLowerCase());
52
61
  const filtering = computed(() => needle.value.length >= 2);
@@ -99,29 +108,42 @@ const extraHits = computed(() =>
99
108
  );
100
109
 
101
110
  let searchTimer: ReturnType<typeof setTimeout> | undefined;
111
+ let searchGeneration = 0;
102
112
  watch(query, (value) => {
103
113
  clearTimeout(searchTimer);
104
114
  const q = value.trim();
105
115
  if (q.length < 2) {
116
+ ++searchGeneration; // an in-flight scan for the cleared query must not resurrect stale hits
106
117
  deviceHits.value = [];
107
118
  searching.value = false;
108
119
  return;
109
120
  }
110
121
  searchTimer = setTimeout(async () => {
111
122
  searching.value = true;
123
+ // R18 cold-review minor 4: scope=all scans take seconds per device — a
124
+ // generation token keeps a slower OLD query from overwriting a newer one.
125
+ const generation = ++searchGeneration;
112
126
  const found: typeof deviceHits.value = [];
113
127
  for (const device of network.devices.value.filter((d) => d.status === "online")) {
114
128
  const result = await deviceClient(device.id)
115
- .searchSessions(q)
129
+ .searchSessions(q, "all")
116
130
  .catch(() => undefined);
131
+ if (generation !== searchGeneration) return; // a newer query superseded this scan
117
132
  for (const match of result?.matches ?? [])
118
- found.push({ deviceId: device.id, id: match.id, name: match.name, cwd: match.cwd, where: match.where });
133
+ found.push({
134
+ deviceId: device.id,
135
+ id: match.id,
136
+ name: match.name,
137
+ cwd: match.cwd,
138
+ where: match.where,
139
+ hits: match.hits ?? [],
140
+ });
119
141
  }
120
142
  deviceHits.value = found;
121
143
  searching.value = false;
122
144
  }, 250);
123
145
  });
124
- const clearSearch = () => ((query.value = ""), (deviceHits.value = []));
146
+ const clearSearch = () => ((query.value = ""), ++searchGeneration, (deviceHits.value = []));
125
147
 
126
148
  /** Bulk session manage (orca ManageSessionsSection): select many, then
127
149
  * archive/abort each with a per-row result. Client-side loop over the
@@ -387,6 +409,13 @@ function keydown(e: KeyboardEvent) {
387
409
  <span class="hit-name">{{ hit.name }}</span>
388
410
  <code class="hit-cwd">{{ hit.cwd }}</code>
389
411
  <em v-if="hit.where.length" class="hit-where">{{ hit.where.join(" · ") }}</em>
412
+ <em
413
+ v-if="hit.hits.length"
414
+ class="hit-line"
415
+ :title="hit.hits.map((h) => `${h.agent} #${h.entry}: ${h.text}`).join('\n')"
416
+ >
417
+ {{ hit.hits[0].agent }} #{{ hit.hits[0].entry }} · {{ hit.hits[0].text.slice(0, 90) }}
418
+ </em>
390
419
  </button>
391
420
  </template>
392
421
  <p v-if="filtering && !localRows.length && !extraHits.length" class="hint tree-empty">
@@ -446,6 +475,16 @@ function keydown(e: KeyboardEvent) {
446
475
  .search-input::-webkit-search-cancel-button { display: none; }
447
476
  .tree-search .clear { padding: 2px; }
448
477
  .searching { opacity: 0.6; font-size: 13px; }
478
+ .hit-line {
479
+ display: block;
480
+ font-style: normal;
481
+ font-size: 12px;
482
+ opacity: 0.75;
483
+ white-space: nowrap;
484
+ overflow: hidden;
485
+ text-overflow: ellipsis;
486
+ max-width: 100%;
487
+ }
449
488
  .hit-head { margin: 6px 2px 2px; }
450
489
  .hit {
451
490
  display: flex; flex-direction: column; gap: 1px; width: 100%; text-align: left;
@@ -105,9 +105,38 @@ 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 token run — not on any one
113
+ // literal prefix. Bare token-shaped values elsewhere (audit enums like
114
+ // "foreign_subscription") stay readable.
115
+ // R18 (run-4 h6): three deliberate spellings still escaped — a non-token
116
+ // separator byte wedged between segment and token ('/api/shares/.<tok>'),
117
+ // a padded run longer than 32 chars, and percent-encoded spellings the
118
+ // literal pass cannot see. Tolerate 0-2 separator bytes, drop the upper
119
+ // bound, and re-run both rules on a percent-decoded copy.
120
+ // Cold-review minor 1: a decoded `/api/shares/<word>%2F<token>` leaves the
121
+ // token behind a short extra path segment — tolerate one such segment AND
122
+ // keep the direct 0–2 non-token separator (run-4 h6) before the run.
123
+ const shareShaped =
124
+ /(\/[a-z0-9%]*shares?\/)(?:[^\s"']{0,8}\/)?[^\w\n]{0,2}[A-Za-z0-9_-]{20,}(?![A-Za-z0-9_-])/gi;
125
+ // Encoded spellings (/%73hare/) hide the literal "share" — any
126
+ // percent-bearing path segment followed by a token-shaped run is treated
127
+ // the same.
128
+ const percentBearing = /(\/[^\s"']*%[^\s"']*\/)[A-Za-z0-9_-]{20,}(?![A-Za-z0-9_-])/gi;
129
+ const scrubTokens = (s: string): string => s.replace(shareShaped, "$1<redacted>").replace(percentBearing, "$1<redacted>");
130
+ out = scrubTokens(out);
131
+ // The decoded pass sees through %XX spellings of the separator, the first
132
+ // token characters, or the segment itself; the sample is bounded (≤200
133
+ // chars) so a pathological decode cannot explode it.
134
+ try {
135
+ const decoded = decodeURIComponent(out);
136
+ if (decoded !== out) out = scrubTokens(decoded);
137
+ } catch {
138
+ // malformed percent escapes stay as the literal pass left them
139
+ }
111
140
  // Credential material without its prefix (slices, echo): 43-char base64url runs.
112
141
  out = out.replace(/(?<![A-Za-z0-9_-])[A-Za-z0-9_-]{43}(?![A-Za-z0-9_-])/g, "<redacted>");
113
142
  // Pairing codes as standalone values ("code":"AB2C7DEF" / "ABCD2345EF67") but not ordinary words.
@@ -25,8 +25,12 @@ export interface LiveState {
25
25
  const sleep = (ms: number, signal: AbortSignal) =>
26
26
  new Promise<void>((resolve) => {
27
27
  if (signal.aborted) return resolve();
28
- const timer = setTimeout(resolve, ms);
29
- signal.addEventListener("abort", () => (clearTimeout(timer), resolve()), { once: true });
28
+ // R18 (run-4 h5): remove the abort listener on the timer path too — a
29
+ // completed sleep used to leave one listener on the long-lived signal,
30
+ // and a flapping device retained closures without bound.
31
+ const onAbort = () => (clearTimeout(timer), resolve());
32
+ const timer = setTimeout(() => (signal.removeEventListener("abort", onAbort), resolve()), ms);
33
+ signal.addEventListener("abort", onAbort, { once: true });
30
34
  });
31
35
 
32
36
  export interface TunnelTransportSource {
@@ -226,10 +230,20 @@ export class DeviceMonitor {
226
230
  continue;
227
231
  }
228
232
  try {
233
+ // R17 (run-3 h8): abort the losing probe — a timed-out fetch keeps
234
+ // buffering (up to REST_TIMEOUT_MS) while the backoff loop starts the
235
+ // next one, multiplying an unbounded read. The per-probe controller
236
+ // also stops reading the moment the race is lost.
237
+ const probeCtl = new AbortController();
238
+ const onOuterAbort = () => probeCtl.abort();
239
+ signal?.addEventListener("abort", onOuterAbort, { once: true });
229
240
  const probe = await Promise.race([
230
- transport.request({ method: "GET", path: "/v1/device" }, signal),
241
+ transport.request({ method: "GET", path: "/v1/device" }, probeCtl.signal),
231
242
  sleep(6_000, signal).then(() => null),
232
- ]);
243
+ ]).finally(() => {
244
+ signal?.removeEventListener("abort", onOuterAbort);
245
+ probeCtl.abort();
246
+ });
233
247
  if (probe === null) throw new DpiError("offline", `Probe timeout for ${device.url}`);
234
248
  if (probe.status === 401)
235
249
  throw new DpiError("unauthorized", "Device rejected the token", 401);
@@ -85,8 +85,12 @@ export function parseSubKey(key: string) {
85
85
  const sleep = (ms: number, signal: AbortSignal) =>
86
86
  new Promise<void>((resolve) => {
87
87
  if (signal.aborted) return resolve();
88
- const timer = setTimeout(resolve, ms);
89
- signal.addEventListener("abort", () => (clearTimeout(timer), resolve()), { once: true });
88
+ // R18 (run-4 h5): remove the abort listener on the timer path too — a
89
+ // completed sleep used to leave one listener on the long-lived signal,
90
+ // and a flapping device retained closures without bound.
91
+ const onAbort = () => (clearTimeout(timer), resolve());
92
+ const timer = setTimeout(() => (signal.removeEventListener("abort", onAbort), resolve()), ms);
93
+ signal.addEventListener("abort", onAbort, { once: true });
90
94
  });
91
95
 
92
96
  export class StreamMux {
@@ -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
 
@@ -105,16 +108,36 @@ export class LanTransport implements DeviceTransport {
105
108
  },
106
109
  body: hasBody && input.body !== undefined ? JSON.stringify(input.body) : undefined,
107
110
  signal: effective,
111
+ // R18 (run-4 h5): the device-side connector refuses redirects (one
112
+ // exact origin); a compromised LAN peer must not aim the hub's fetches
113
+ // elsewhere. 3xx → clean 502, same as the connector.
114
+ redirect: "manual",
108
115
  });
109
116
  } catch (cause) {
110
117
  if (signal?.aborted) throw cause;
111
118
  throw new DpiError("offline", `Cannot reach ${this.client.baseUrl}`, 0, { cause });
112
119
  }
113
- const raw = Buffer.from(await response.arrayBuffer());
120
+ if (response.status >= 300 && response.status < 400) {
121
+ await response.body?.cancel().catch(() => undefined);
122
+ throw new DpiError(
123
+ "offline",
124
+ `Device API answered with a redirect (${response.status}); redirects are not followed`,
125
+ 502,
126
+ );
127
+ }
128
+ // R17 (run-3 h8): size parity with the tunnel leg — the device connector
129
+ // caps its own fetches (16 MiB textual / binary cap) and reassembly
130
+ // budgets bound the tunnel; this leg used to buffer arrayBuffer() with NO
131
+ // cap, so a hostile LAN peer (or compromised device) could OOM the whole
132
+ // hub process. Mirror the connector's capped reader.
114
133
  const ct = response.headers.get("content-type") ?? undefined;
134
+ const textual = ct === undefined || TEXTUAL_CT_RE.test(ct);
135
+ const capped = await readBodyCapped(response, textual ? LOGICAL_MESSAGE_MAX_BYTES : BINARY_RESPONSE_MAX_BYTES);
136
+ if (!capped.ok)
137
+ throw new DpiError("invalid", `device answer exceeds ${textual ? "16 MiB" : "12 MB"}`, 413);
138
+ const raw = capped.bytes;
115
139
  // Textual responses keep the legacy plain-string shape; binaries are base64-flagged
116
140
  // so the proxy can serve bytes byte-exact (R8 binary passthrough).
117
- const textual = ct === undefined || TEXTUAL_CT_RE.test(ct);
118
141
  return {
119
142
  status: response.status,
120
143
  contentType: ct,
@@ -148,3 +171,36 @@ export function transportFor(
148
171
  if (row.transport === "tunnel") return tunnel ? tunnel.dispatcherFor(row) : undefined;
149
172
  return new LanTransport(row);
150
173
  }
174
+
175
+ /**
176
+ * R17 (run-3 h8): the binary cap mirrors the device connector's own reader
177
+ * (tunnel.ts uses 12_000_000 — aligned exactly so a binary that passes one
178
+ * leg never surprises the other).
179
+ */
180
+ const BINARY_RESPONSE_MAX_BYTES = 12_000_000;
181
+
182
+ async function readBodyCapped(
183
+ res: Response,
184
+ cap: number,
185
+ ): Promise<{ ok: true; bytes: Buffer } | { ok: false }> {
186
+ const declared = Number(res.headers.get("content-length"));
187
+ if (Number.isFinite(declared) && declared > cap) {
188
+ await res.body?.cancel().catch(() => {});
189
+ return { ok: false };
190
+ }
191
+ if (!res.body) return { ok: true, bytes: Buffer.alloc(0) };
192
+ const reader = res.body.getReader();
193
+ const parts: Uint8Array[] = [];
194
+ let total = 0;
195
+ for (;;) {
196
+ const { done, value } = await reader.read();
197
+ if (done) break;
198
+ total += value.byteLength;
199
+ if (total > cap) {
200
+ await reader.cancel().catch(() => {});
201
+ return { ok: false };
202
+ }
203
+ parts.push(value);
204
+ }
205
+ return { ok: true, bytes: Buffer.concat(parts) };
206
+ }
@@ -558,7 +558,7 @@ export class TunnelDispatcher {
558
558
  // connection swap. The prefix marks hub-derived keys in device logs; 73 chars fits the
559
559
  // device's 128-char header cap and the wire schema's 256.
560
560
  const idempotencyKey =
561
- input.idempotencyKey ??
561
+ input.idempotencyKey ||
562
562
  (input.method === "GET" || input.method === "HEAD"
563
563
  ? undefined
564
564
  : "dpi-auto-" +
@@ -473,6 +473,14 @@ export interface DeviceVitals {
473
473
  counts?: { sessions: number; archived: number };
474
474
  }
475
475
 
476
+ /** One transcript hit inside a session search match (scope=all): which agent, which entry, what it says. */
477
+ export interface TranscriptSearchHit {
478
+ agent: string;
479
+ entry: number;
480
+ kind: string;
481
+ text: string;
482
+ }
483
+
476
484
  /** One session-search hit: the summary fields plus which of them matched. */
477
485
  export interface SessionSearchMatch {
478
486
  id: string;
@@ -482,12 +490,16 @@ export interface SessionSearchMatch {
482
490
  createdAt: number;
483
491
  dbPath: string;
484
492
  compaction?: CompactionSettings;
485
- where: Array<"name" | "cwd" | "model">;
493
+ where: Array<"name" | "cwd" | "model" | "transcript">;
494
+ /** Present when scope=all found transcript text (up to a few per session, newest first). */
495
+ hits?: TranscriptSearchHit[];
486
496
  }
487
497
 
488
498
  export interface SessionSearchResult {
489
499
  query: string;
490
500
  matches: SessionSearchMatch[];
501
+ /** Present on scope=all: what the transcript scan covered before its budget ran out. */
502
+ scanned?: { sessions: number; entries: number; truncated: boolean };
491
503
  }
492
504
 
493
505
  export interface DeviceTree {
@@ -342,9 +342,12 @@ export class DpiClient {
342
342
  deviceUsage() {
343
343
  return this.request<DeviceUsageReport>("GET", "/v1/device/usage");
344
344
  }
345
- /** Session search over names/cwds/models (transcripts are not scanned). */
346
- searchSessions(query: string) {
347
- return this.request<SessionSearchResult>("GET", `/v1/sessions/search?q=${enc(query)}`);
345
+ /** Session search over names/cwds/models; scope="all" adds the bounded transcript scan (R18). */
346
+ searchSessions(query: string, scope?: "meta" | "all") {
347
+ return this.request<SessionSearchResult>(
348
+ "GET",
349
+ `/v1/sessions/search?q=${enc(query)}${scope === "all" ? "&scope=all" : ""}`,
350
+ );
348
351
  }
349
352
  dirs(path = "") {
350
353
  return this.request<DirListing>("GET", `/v1/fs/dirs?path=${enc(path)}`);
@@ -614,8 +617,12 @@ export type ConnectionState = "connecting" | "live" | "offline" | "unauthorized"
614
617
  const sleep = (ms: number, signal: AbortSignal) =>
615
618
  new Promise<void>((resolve) => {
616
619
  if (signal.aborted) return resolve();
617
- const timer = setTimeout(resolve, ms);
618
- signal.addEventListener("abort", () => (clearTimeout(timer), resolve()), { once: true });
620
+ // R18 (run-4 h5): remove the abort listener on the timer path too — a
621
+ // completed sleep used to leave one listener on the long-lived signal,
622
+ // and a flapping device retained closures without bound.
623
+ const onAbort = () => (clearTimeout(timer), resolve());
624
+ const timer = setTimeout(() => (signal.removeEventListener("abort", onAbort), resolve()), ms);
625
+ signal.addEventListener("abort", onAbort, { once: true });
619
626
  });
620
627
 
621
628
  /**
@@ -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,19 @@ 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
+ // R18 (run-4 h7): ':' is the DPI_START_DIRS list separator on the device
122
+ // (config.ts splits on it) — an entry containing ':' would smuggle an
123
+ // EXTRA containment root past the operator's declared list.
124
+ startDirs:
125
+ d.start_dirs === undefined
126
+ ? [DEFAULT_START_DIR]
127
+ : strList(d.start_dirs, `${where}.start_dirs`).map((r: string) => {
128
+ if (r.includes(":")) throw Error(`${where}.start_dirs must not contain ':' (the DPI_START_DIRS separator)`);
129
+ return pathish(r, "start_dirs");
130
+ }),
131
+ host: d.host === undefined ? (kind === "local" ? "127.0.0.1" : "0.0.0.0") : pathish(str(d.host, `${where}.host`), "host"),
113
132
  envKeys: d.env_keys === undefined ? [] : strList(d.env_keys, `${where}.env_keys`),
114
133
  env: {},
115
134
  ...(typeof d.token_env === "string" ? { tokenEnv: d.token_env } : {}),
@@ -119,7 +138,17 @@ export function parseNetworkConfig(text: string, file = NETWORK_FILE): NetworkCo
119
138
  if (d.service !== "launchd" && d.service !== "systemd") throw Error(`${where}.service must be launchd or systemd`);
120
139
  device.service = d.service;
121
140
  }
122
- if (kind === "ssh") device.ssh = str(d.ssh, `${where}.ssh`);
141
+ if (kind === "ssh") {
142
+ const target = str(d.ssh, `${where}.ssh`);
143
+ // R17 (run-3 h12): the ssh scalar is a leading argv element — a leading
144
+ // dash would be parsed as an ssh OPTION (e.g. -oProxyCommand=…). Accept
145
+ // only a user@host[:port] shape.
146
+ // R18 (run-4 h7): the user part may not START with a dash either —
147
+ // `-Jjump@evil` is an attached-value ssh option (ProxyJump), not a user.
148
+ if (!/^[A-Za-z0-9._%][A-Za-z0-9._%-]*@[A-Za-z0-9.-]+(:\d+)?$/.test(target))
149
+ throw Error(`${where}.ssh must be user@host[:port] (no options, no metacharacters)`);
150
+ device.ssh = target;
151
+ }
123
152
  if (kind === "exe-dev") {
124
153
  device.vm = str(d.vm, `${where}.vm`);
125
154
  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,15 @@ 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
+ // R18 (run-4 h7): ':' in a start_dirs entry splits into an EXTRA containment
119
+ // root on the device — refuse at the sink as well.
120
+ if (device.startDirs.some((r) => r.includes(":")))
121
+ throw Error(`device ${device.id}: start_dirs must not contain ':' (the DPI_START_DIRS separator)`);
122
+ for (const [k, v] of [["DPI_HOST", device.host], ["DPI_START_DIRS", device.startDirs.join(":")]] as const)
123
+ if (/[\n\r]/.test(v))
124
+ throw Error(`device ${device.id}: ${k} value contains a newline — refusing to write backend.env`);
116
125
  const home = shPath(device.homeDir);
117
126
  const body = [
118
127
  `DPI_DEVICE_NAME=${device.id}`,
@@ -182,7 +191,12 @@ async function installService(device: NetDevice, ctx: DriverContext) {
182
191
  };
183
192
  const deployDir = join(ctx.config.root, "apps/dpi-backend/deploy");
184
193
  if (device.service === "launchd") {
185
- const plist = fill(readFileSync(join(deployDir, "dpi-backend.plist"), "utf8"), values);
194
+ // R17 (run-3 h12): plist is XML — escape & and < in the values (mirrors
195
+ // daemon.ts launchdPlist) so no new element can be forged.
196
+ const xmlValues = Object.fromEntries(
197
+ Object.entries(values).map(([k, v]) => [k, v.replaceAll("&", "&amp;").replaceAll("<", "&lt;")]),
198
+ );
199
+ const plist = fill(readFileSync(join(deployDir, "dpi-backend.plist"), "utf8"), xmlValues);
186
200
  await exec(
187
201
  device,
188
202
  `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
  }
@@ -27,6 +27,7 @@ export const COMMANDS: SlashCommand[] = [
27
27
  { name: "reset", description: "start a fresh context", argumentHint: "[handoff note]" },
28
28
  { name: "name", description: "rename this agent", argumentHint: "<name>" },
29
29
  { name: "tasks", description: "live tasks in this session" },
30
+ { name: "find", description: "search every session's transcript on this device", argumentHint: "<text>" },
30
31
  { name: "pair", description: "pair THIS device with a hub", argumentHint: "<CODE|PAIR_URL> [--hub ORIGIN] [--force]" },
31
32
  {
32
33
  name: "git",
@@ -194,7 +195,7 @@ export async function runCommand(app: App, text: string): Promise<boolean> {
194
195
  // not skip that gate (R4 finding 4: the palette entry used to wipe the
195
196
  // context unconditionally). A typed handoff note carries its own intent.
196
197
  if (!arg) {
197
- const ok = await app.prompt(`Reset ${app.sessionSummary()?.name ?? "context"}? y/n`, "");
198
+ const ok = await app.prompt(`Reset ${sanitizeTerminal(app.sessionSummary()?.name ?? "context")}? y/n`, "");
198
199
  if (ok === undefined || !ok.trim().toLowerCase().startsWith("y"))
199
200
  return app.flash("reset cancelled"), true;
200
201
  }
@@ -206,7 +207,10 @@ export async function runCommand(app: App, text: string): Promise<boolean> {
206
207
  let value = arg;
207
208
  if (!value) {
208
209
  const current = app.sessionSummary()?.agents.find((a) => a.id === app.agentId)?.name ?? "";
209
- const typed = await app.prompt("Agent name", current && current !== "main" ? current : "");
210
+ // Agent names ride the wire from device/hub (model-choosable for forks
211
+ // and subagents) and pi-tui's Input renders its value verbatim — seed
212
+ // it sanitized (run-4 h4).
213
+ const typed = await app.prompt("Agent name", current && current !== "main" ? sanitizeTerminal(current) : "");
210
214
  value = (typed ?? "").trim();
211
215
  if (!value) return app.flash("rename cancelled"), true;
212
216
  }
@@ -223,15 +227,51 @@ export async function runCommand(app: App, text: string): Promise<boolean> {
223
227
  case "pair":
224
228
  await runPairing(app, parsePairArgs(arg));
225
229
  break;
230
+ case "find": {
231
+ // R18: transcript search across every session on the device. Transcript
232
+ // text is untrusted — every interpolation below goes through
233
+ // sanitizeTerminal before it reaches chrome (run-3 h5 discipline).
234
+ if (!arg) return app.flash("usage: /find <text> — searches every session's transcript", true), true;
235
+ await app.run(async () => {
236
+ const result = await app.client.searchSessions(arg, "all");
237
+ const shown = result.matches.slice(0, 12);
238
+ app.overlay(
239
+ new Panel(() => {
240
+ const lines = [
241
+ c.bold(c.accent(`"${sanitizeTerminal(arg)}" — ${result.matches.length} session${result.matches.length === 1 ? "" : "s"}`)),
242
+ "",
243
+ ];
244
+ if (!result.matches.length) lines.push(c.muted("No matches (names, folders, models or transcripts)."));
245
+ for (const m of shown) {
246
+ lines.push(
247
+ `${c.secondary(sanitizeTerminal(m.name))} ${c.muted(sanitizeTerminal(m.cwd))}${m.where.includes("transcript") ? " " + c.warn("◍ transcript") : ""}`,
248
+ );
249
+ for (const hit of (m.hits ?? []).slice(0, 3))
250
+ lines.push(
251
+ c.muted(
252
+ ` ${sanitizeTerminal(m.name)}:${sanitizeTerminal(hit.agent)} #${hit.entry} — ${sanitizeTerminal(hit.text.slice(0, 140))}`,
253
+ ),
254
+ );
255
+ }
256
+ if (result.matches.length > shown.length) lines.push(c.muted(`… ${result.matches.length - shown.length} more`));
257
+ if (result.scanned?.truncated)
258
+ lines.push(c.muted(`scan budget reached (${result.scanned.entries} entries) — refine the query`));
259
+ lines.push("", c.muted("esc close"));
260
+ return lines;
261
+ }, () => app.closeOverlay()),
262
+ );
263
+ });
264
+ break;
265
+ }
226
266
  case "tasks":
227
267
  app.overlay(
228
268
  new Panel(() => {
229
269
  const tasks = app.session.state.tasks;
230
- const lines = [c.bold(c.accent(`Live tasks in ${app.sessionSummary()?.name ?? "session"}`)), ""];
270
+ const lines = [c.bold(c.accent(`Live tasks in ${sanitizeTerminal(app.sessionSummary()?.name ?? "session")}`)), ""];
231
271
  if (!tasks.length) lines.push(c.muted("No live tasks."));
232
272
  for (const t of tasks)
233
273
  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}` : ""}`)}`,
274
+ `${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
275
  );
236
276
  lines.push("", c.muted("esc close"));
237
277
  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