my-durable 0.0.77 → 0.0.78

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.
@@ -21,6 +21,7 @@ import { chmodSync, closeSync, existsSync, fstatSync, fsyncSync, openSync, rmSyn
21
21
  import { dirname } from "node:path";
22
22
  import { randomUUID } from "node:crypto";
23
23
  import { ensurePrivateDir } from "./private-dir.js";
24
+ import { normalizeUrl, validateToken } from "./registry.js";
24
25
 
25
26
  export const REGISTRY_SCHEMA_VERSION = 1;
26
27
  const UUID_CANONICAL = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
@@ -346,7 +347,19 @@ function openExclusive(path: string, busyTimeoutMs: number): DatabaseSync {
346
347
  }
347
348
 
348
349
  /** v0 preflight: no stray v1 objects, exact column set per v0 table, canonical ids/uids, no duplicates. */
349
- function preflightV0(db: DatabaseSync): void {
350
+ /** Sanitized replacement values for rows whose legacy fields the live writers
351
+ * would refuse or cap. Applied INSIDE the migration transaction (never in the
352
+ * read-only preflight): a preflight write would mutate the v0 file before the
353
+ * WAL-safe backup and before BEGIN, so an aborted migration would silently
354
+ * drop operator tokens. */
355
+ export interface V0Overrides {
356
+ url?: string;
357
+ token?: string | null;
358
+ info?: string | null;
359
+ tree?: string | null;
360
+ }
361
+
362
+ function preflightV0(db: DatabaseSync): Map<string, V0Overrides> {
350
363
  // First: anything the v1 schema owns means this is not a v0 file at all. Refused before
351
364
  // the backup is written and before any write touches the registry (the caller's
352
365
  // `reached(opts, "preflight")` hook still fires only after preflightV0 returns).
@@ -373,9 +386,21 @@ function preflightV0(db: DatabaseSync): void {
373
386
  );
374
387
  }
375
388
  }
376
- const rows = db.prepare("SELECT id, url, device_uid FROM devices").all() as {
389
+ // run-8 U9: the v0 rows predate the writer-side caps and normalisation, and
390
+ // the copy below is verbatim — a pre-run-7 registry could carry a hostile
391
+ // 16MiB last_tree_json (parsed by EVERY NetworkRegistry.list() forever) or a
392
+ // token with CRLF (breaking every client construction). Enforce the same
393
+ // per-field policy at the migration seam: cap the JSON blobs and NULL out a
394
+ // url/token that the live writers would have refused.
395
+ const rows = db.prepare(
396
+ "SELECT id, url, device_uid, token, last_info_json, last_tree_json FROM devices",
397
+ ).all() as {
377
398
  id: string; url: string | null; device_uid: string | null;
399
+ token: string | null; last_info_json: string | null; last_tree_json: string | null;
378
400
  }[];
401
+ const INFO_CAP = 64 * 1024;
402
+ const TREE_CAP = 288 * 1024;
403
+ const overrides = new Map<string, V0Overrides>();
379
404
  const seenUid = new Set<string>();
380
405
  for (const row of rows) {
381
406
  if (!DEVICE_ID_PATTERN.test(row.id)) throw new MigrationError(`non-canonical device id ${JSON.stringify(row.id)} — resolve manually (no trim)`);
@@ -385,7 +410,34 @@ function preflightV0(db: DatabaseSync): void {
385
410
  if (seenUid.has(row.device_uid)) throw new MigrationError(`duplicate device_uid ${row.device_uid} — operator must resolve before migration`);
386
411
  seenUid.add(row.device_uid);
387
412
  }
413
+ let url: string = row.url;
414
+ try {
415
+ url = normalizeUrl(row.url);
416
+ } catch {
417
+ // The live writer would have refused this url; carrying it over would put
418
+ // an arbitrary scheme in every consumer. Fail closed (url is NOT NULL).
419
+ throw new MigrationError(`device ${row.id} has a url the live writer refuses — resolve manually`);
420
+ }
421
+ let token: string | null = row.token;
422
+ if (token !== null) {
423
+ try {
424
+ validateToken(token);
425
+ } catch {
426
+ token = null;
427
+ }
428
+ }
429
+ const capJson = (text: string | null, cap: number): string | null =>
430
+ text !== null && text.length > cap ? null : text;
431
+ const info = capJson(row.last_info_json, INFO_CAP);
432
+ const tree = capJson(row.last_tree_json, TREE_CAP);
433
+ const patch: V0Overrides = {};
434
+ if (url !== row.url) patch.url = url;
435
+ if (token !== row.token) patch.token = token;
436
+ if (info !== row.last_info_json) patch.info = info;
437
+ if (tree !== row.last_tree_json) patch.tree = tree;
438
+ if (Object.keys(patch).length) overrides.set(row.id, patch);
388
439
  }
440
+ return overrides;
389
441
  }
390
442
 
391
443
  /**
@@ -462,7 +514,7 @@ function migrateV0(db: DatabaseSync, path: string, opts: MigrationOptions): Regi
462
514
  }
463
515
  assertMigratable(version);
464
516
 
465
- preflightV0(db);
517
+ const overrides = preflightV0(db);
466
518
  reached(opts, "preflight");
467
519
 
468
520
  const preCount = (db.prepare("SELECT count(*) AS n FROM devices").get() as { n: number }).n;
@@ -484,6 +536,27 @@ function migrateV0(db: DatabaseSync, path: string, opts: MigrationOptions): Regi
484
536
  created_at,updated_at,'lan'
485
537
  FROM devices`,
486
538
  );
539
+ // The sanitized legacy values land on the NEW table, inside this
540
+ // transaction: the v0 file is never modified by a migration that aborts.
541
+ if (overrides.size) {
542
+ // cold-3 L11: dropping a legacy token is a behaviour change the operator
543
+ // must be able to see (the refused URL aborts loudly; this must not be
544
+ // silent). Ids + field names only, never the values.
545
+ const fields = [...overrides].map(([id, patch]) => `${id}(${Object.keys(patch).join(",")})`);
546
+ process.emitWarning(
547
+ `registry migration: sanitised ${overrides.size} legacy row(s) — ${fields.join(" ")}; those devices may need re-pairing`,
548
+ );
549
+ const setUrl = db.prepare("UPDATE devices_v1_new SET url=? WHERE id=?");
550
+ const setToken = db.prepare("UPDATE devices_v1_new SET token=? WHERE id=?");
551
+ const setInfo = db.prepare("UPDATE devices_v1_new SET last_info_json=? WHERE id=?");
552
+ const setTree = db.prepare("UPDATE devices_v1_new SET last_tree_json=? WHERE id=?");
553
+ for (const [id, patch] of overrides) {
554
+ if (patch.url !== undefined) setUrl.run(patch.url, id);
555
+ if (patch.token !== undefined) setToken.run(patch.token, id);
556
+ if (patch.info !== undefined) setInfo.run(patch.info, id);
557
+ if (patch.tree !== undefined) setTree.run(patch.tree, id);
558
+ }
559
+ }
487
560
  reached(opts, "mid-transaction");
488
561
  db.exec("DROP TABLE devices; ALTER TABLE devices_v1_new RENAME TO devices;");
489
562
  db.exec(V1_SCHEMA_SQL);
@@ -16,7 +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
+ import { oneLine } from "./sanitize.ts";
20
20
 
21
21
  export interface PairArgs {
22
22
  code?: string;
@@ -152,32 +152,36 @@ export function pairingViewLines(
152
152
  hubOrigin?: string,
153
153
  ): string[] {
154
154
  const lines: string[] = [c.bold(c.accent("Pair this device"))];
155
- if (hubOrigin) lines.push(c.muted(`hub: ${sanitizeTerminal(hubOrigin)}`));
155
+ if (hubOrigin) lines.push(c.muted(`hub: ${oneLine(hubOrigin)}`));
156
156
  if (!status) {
157
- lines.push(c.muted(sanitizeTerminal(note)));
157
+ lines.push(c.muted(oneLine(note)));
158
158
  return lines.flatMap((line) => wrapTextWithAnsi(line, Math.max(1, width)));
159
159
  }
160
- lines.push(c.muted(sanitizeTerminal(`device: ${status.deviceName ?? status.deviceUid ?? "?"} · uid ${status.deviceUid ?? "?"}`)));
160
+ lines.push(c.muted(oneLine(`device: ${status.deviceName ?? status.deviceUid ?? "?"} · uid ${status.deviceUid ?? "?"}`)));
161
161
  lines.push("");
162
162
  lines.push(c.bold("key fingerprint (compare with the hub wizard):"));
163
- for (const line of wrapFingerprint(status.fingerprint, width)) lines.push(` ${c.secondary(sanitizeTerminal(line))}`);
163
+ for (const line of wrapFingerprint(status.fingerprint, width)) lines.push(` ${c.secondary(oneLine(line))}`);
164
164
  lines.push("");
165
165
  if (status.pending) {
166
166
  lines.push(c.warn("Awaiting approval on the hub…"));
167
- if (status.pending.note) lines.push(c.muted(` ${sanitizeTerminal(status.pending.note)}`));
167
+ if (status.pending.note) lines.push(c.muted(` ${oneLine(status.pending.note)}`));
168
168
  } else if (status.lastError) {
169
- lines.push(c.err(sanitizeTerminal(describePairingError(status.lastError))));
169
+ // run-8 U6: the hub relays its own error.message here unbounded, and
170
+ // wrapTextWithAnsi SPLITS on LF — a hostile message forged panel rows
171
+ // right below the real TOFU fingerprint block (probe: 2 rows, one read
172
+ // "Paired to https://good.example (generation 9)").
173
+ lines.push(c.err(oneLine(describePairingError(status.lastError))));
170
174
  if (status.state === "paired")
171
- lines.push(c.muted(sanitizeTerminal(`Existing pairing to ${status.hubOrigin} is unchanged.`)));
175
+ lines.push(c.muted(oneLine(`Existing pairing to ${status.hubOrigin} is unchanged.`)));
172
176
  } else if (status.state === "paired") {
173
- lines.push(c.ok(sanitizeTerminal(`Paired to ${status.hubOrigin} (generation ${status.generation}).`)));
177
+ lines.push(c.ok(oneLine(`Paired to ${status.hubOrigin} (generation ${status.generation}).`)));
174
178
  lines.push(c.muted("The connector keeps the tunnel up; /pair again to re-pair."));
175
179
  } else if (status.state === "revoked") {
176
180
  lines.push(c.warn("Revoked on the hub. /pair CODE to pair again."));
177
181
  } else {
178
- lines.push(c.muted(sanitizeTerminal(note)));
182
+ lines.push(c.muted(oneLine(note)));
179
183
  }
180
- if (note && status.state !== "pairing") lines.push(c.muted(sanitizeTerminal(note)));
184
+ if (note && status.state !== "pairing") lines.push(c.muted(oneLine(note)));
181
185
  return lines.flatMap((line) => wrapTextWithAnsi(line, Math.max(1, width)));
182
186
  }
183
187
 
@@ -239,7 +239,7 @@ export function renderNetwork(
239
239
  const seen = d.lastSeenAt ? ageOf(d.lastSeenAt) : "never";
240
240
  label =
241
241
  `${dot} ${c.bold(row.label)}${row.current ? c.accent(" ▌") : ""} ${c.muted(`[${d.kind}]`)} ` +
242
- `${c.muted(d.transport === "tunnel" ? "tunnel" : "lan")} ${c.muted(d.lastStatus === "online" ? seen : `${sanitizeTerminal(d.lastStatus)} · ${seen}`)}`;
242
+ `${c.muted(d.transport === "tunnel" ? "tunnel" : "lan")} ${c.muted(d.lastStatus === "online" ? seen : `${oneLine(d.lastStatus)} · ${seen}`)}`;
243
243
  } else {
244
244
  const selected = row.sessionId === opts.currentSessionId;
245
245
  const marker = selected ? c.accent("▌") : " ";
@@ -21,7 +21,7 @@ import type { App, DeviceRef } from "./app.ts";
21
21
  import { Picker } from "./pickers.ts";
22
22
  import { parsePairArgs, runPairing, type PairArgs } from "./pairing.ts";
23
23
  import { c } from "./theme.ts";
24
- import { sanitizeTerminal } from "./sanitize.ts";
24
+ import { oneLine, sanitizeTerminal } from "./sanitize.ts";
25
25
 
26
26
  const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
27
27
 
@@ -277,8 +277,11 @@ export class WelcomePicker extends Picker {
277
277
  /** Open the welcome screen overlay. `notice` names an unreachable auto-connect. */
278
278
  export function showWelcome(app: App, opts: { notice?: string } = {}) {
279
279
  const devices = app.registry?.list() ?? [];
280
+ // run-8 U6: oneLine, not just sanitizeTerminal — a hostile device JSON
281
+ // error.message carries LFs, and truncateToWidth passes an embedded LF
282
+ // through inside ONE logical row (probe: forged row + cursor drift).
280
283
  const subtitle = opts.notice
281
- ? c.err(sanitizeTerminal(opts.notice))
284
+ ? c.err(oneLine(opts.notice))
282
285
  : c.muted("This is the app — connect a device to get started:");
283
286
  let picked = false; // an action was chosen: closing the overlay is a step, not a quit
284
287
  app.overlay(
@@ -426,7 +429,7 @@ async function welcomeLocal(app: App) {
426
429
  const id = suggestDeviceId(probe.info.hostname, probe.info.name);
427
430
  stepPicker(
428
431
  app,
429
- `Local backend: ${sanitizeTerminal(probe.info.name || probe.info.hostname || url)}`,
432
+ `Local backend: ${oneLine(probe.info.name || probe.info.hostname || url)}`,
430
433
  [{ value: "open", label: `Save as "${id}" and open`, description: `${url} │ token from DPI_TOKEN / backend.env` }],
431
434
  // local.token was read BEFORE a first boot may have written backend.env —
432
435
  // re-resolve, the file exists now.
@@ -454,7 +457,9 @@ function welcomeSwitch(app: App) {
454
457
  async function saveAndOpen(app: App, id: string, url: string, token: string, name?: string) {
455
458
  if (!app.registry) return app.flash("No registry — start with --url/--token.", true);
456
459
  try {
457
- app.registry.upsert({ id, name: name || id, url, kind: "url", source: "ui", token });
460
+ // run-8 U6: the device-supplied name is persisted for EVERY later render —
461
+ // collapse and bound it at the write boundary, not per render site.
462
+ app.registry.upsert({ id, name: oneLine(name || id).slice(0, 128) || id, url, kind: "url", source: "ui", token });
458
463
  } catch (e) {
459
464
  app.flash((e as Error).message, true);
460
465
  return showWelcome(app);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "my-durable",
3
- "version": "0.0.77",
3
+ "version": "0.0.78",
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": {