my-durable 0.0.70 → 0.0.71

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.
@@ -24,7 +24,7 @@
24
24
  *
25
25
  * No express, no Store import: the leader wires routes and store calls.
26
26
  */
27
- import { chmodSync, readFileSync, readdirSync, statSync, writeFileSync } from "node:fs";
27
+ import { chmodSync, lstatSync, readFileSync, readdirSync, statSync, writeFileSync, type Dirent } from "node:fs";
28
28
  import { mkdir, rename, stat } from "node:fs/promises";
29
29
  import { basename, join } from "node:path";
30
30
  import { DatabaseSync } from "node:sqlite";
@@ -179,19 +179,23 @@ function bundleStats(bundleDir: string): { turns: number; lastMessageAt: number
179
179
  }
180
180
 
181
181
  /** Recursive size of a bundle dir; 0 when unreadable. Symlinks are not followed (lstat-free stat on entries we can read). */
182
- function dirBytes(dir: string): number {
182
+ function dirBytes(dir: string, depth = 0): number {
183
+ // R16 (run-2 h8): listArchived must never throw — statSync FOLLOWS symlinks,
184
+ // so a planted symlink loop (a->b, b->a) blew the stack. Lstat never
185
+ // follows; the depth cap bounds hostile deep trees. Symlinked entries are
186
+ // skipped (not sizeable), matching gc.ts.
183
187
  let total = 0;
184
- let names: string[];
188
+ let entries: Dirent[];
185
189
  try {
186
- names = readdirSync(dir);
190
+ entries = readdirSync(dir, { withFileTypes: true });
187
191
  } catch {
188
192
  return 0;
189
193
  }
190
- for (const name of names) {
194
+ if (depth >= 64) return total;
195
+ for (const e of entries) {
191
196
  try {
192
- const s = statSync(join(dir, name));
193
- if (s.isDirectory()) total += dirBytes(join(dir, name));
194
- else if (s.isFile()) total += s.size;
197
+ if (e.isDirectory()) total += dirBytes(join(dir, e.name), depth + 1);
198
+ else if (e.isFile()) total += lstatSync(join(dir, e.name)).size;
195
199
  } catch {
196
200
  // broken symlink / vanished entry: not sizeable, not fatal
197
201
  }
@@ -94,8 +94,11 @@ export function cleanChildEnv(env: Record<string, string | undefined>): NodeJS.P
94
94
  const q = (s: string) => `"${s.replaceAll('"', "")}"`;
95
95
 
96
96
  export function systemdUnit(o: { node: string; dpi: string; env: Record<string, string> }): string {
97
+ // R16 (run-2 h12): a CR/LF inside a value would start a new unit directive;
98
+ // collapse to spaces (the daemon writes its own managed values, but the unit
99
+ // file is the trust boundary — sanitize at the sink).
97
100
  const envLines = Object.entries(o.env)
98
- .map(([k, v]) => `Environment="${k}=${v.replaceAll('"', "")}"`)
101
+ .map(([k, v]) => `Environment="${k}=${v.replaceAll('"', "").replace(/[\r\n]+/g, " ")}"`)
99
102
  .join("\n");
100
103
  return `[Unit]
101
104
  Description=Durable Pi device daemon
@@ -428,7 +428,9 @@ export type GitOp =
428
428
  | "pr-comment";
429
429
 
430
430
  /** Plain string an arg may never contain — we build argv ourselves anyway. */
431
- const safeRef = (s: string) => /^[\w./@+-]+$/.test(s) && !s.includes("..");
431
+ // R16 (run-2 h6): a leading dash would turn the ref into a git OPTION
432
+ // (`push -u origin --mirror`); refuse the whole ref instead.
433
+ const safeRef = (s: string) => /^[\w./@+-]+$/.test(s) && !s.startsWith("-") && !s.includes("..");
432
434
 
433
435
  /** Run one whitelisted git operation. Every arg is ours; callers only pick names. */
434
436
  export async function gitOp(
@@ -0,0 +1,56 @@
1
+ import type { RequestHandler } from "express";
2
+ import { hostname, networkInterfaces } from "node:os";
3
+
4
+ /**
5
+ * Operator-supplied extra Host spellings (comma-separated, name or name:port;
6
+ * a bare name inherits our port). Rebind-safe by construction: the operator
7
+ * typed these names for THIS device.
8
+ */
9
+ export function extraHosts(port: number, env: NodeJS.ProcessEnv = process.env): string[] {
10
+ const raw = env.DPI_EXTRA_HOSTS ?? "";
11
+ return raw
12
+ .split(",")
13
+ .map((h) => h.trim().toLowerCase())
14
+ .filter(Boolean)
15
+ .map((h) => (h.includes(":") || h.startsWith("[") ? h : `${h}:${port}`));
16
+ }
17
+
18
+ /**
19
+ * R16 (run-2 h1 NV close): the enrollment surface is unauthenticated, and its
20
+ * x-dpi-pair custom header only forces a CORS preflight on FOREIGN origins —
21
+ * a DNS-rebind page (evil.com re-resolving to this device's LAN IP:port) makes
22
+ * every fetch same-origin from the browser's point of view, so the preflight
23
+ * guard does not see it. The Host header survives rebinding untouched: it
24
+ * still says evil.com. Mirror the hub's 421 guard (guard.ts): only hosts this
25
+ * device actually serves may talk to the unauthenticated routes.
26
+ */
27
+ export function hostAllowlist(port: number, env: NodeJS.ProcessEnv = process.env): Set<string> {
28
+ const short = hostname().toLowerCase().replace(/\.local$/, "");
29
+ const hosts = new Set([
30
+ `localhost:${port}`,
31
+ `127.0.0.1:${port}`,
32
+ `[::1]:${port}`,
33
+ `${short}:${port}`,
34
+ // mDNS spelling resolves to this machine itself — rebind-safe (the Pi
35
+ // access style: pi.local:4780/pair must not 421).
36
+ `${short}.local:${port}`,
37
+ ...extraHosts(port, env),
38
+ ]);
39
+ for (const addresses of Object.values(networkInterfaces()))
40
+ for (const a of addresses ?? []) {
41
+ if (a.family === "IPv4") hosts.add(`${a.address}:${port}`);
42
+ else if (a.family === "IPv6") hosts.add(`[${a.address}]:${port}`);
43
+ }
44
+ return hosts;
45
+ }
46
+
47
+ export function hostGuard(allowed: Set<string>): RequestHandler {
48
+ return (req, res, next) => {
49
+ const host = (req.headers.host ?? "").toLowerCase();
50
+ if (!allowed.has(host))
51
+ return void res
52
+ .status(421)
53
+ .json({ error: { code: "invalid", message: `Unknown Host header: ${host}` } });
54
+ next();
55
+ };
56
+ }
@@ -9,6 +9,7 @@ import { loadConfig, deviceHome } from "./config.js";
9
9
  import { Store, PACKAGE_VERSION } from "./store.js";
10
10
  import { installCrashHandlers } from "./crash.js";
11
11
  import { bearerAuth } from "./auth.js";
12
+ import { hostAllowlist, hostGuard } from "./host-guard.js";
12
13
  import { errorMiddleware } from "./errors.js";
13
14
  import { v1 } from "./routes.js";
14
15
  import { DevicePairing } from "./pairing.js";
@@ -73,10 +74,15 @@ crashStore = store;
73
74
 
74
75
  const app = express();
75
76
  app.disable("x-powered-by");
76
- app.get("/healthz", (_req, res) => res.json({ ok: true }));
77
+ // R16 (run-2 h1): DNS rebinding makes the enrollment surface same-origin from
78
+ // the browser's view, defeating the x-dpi-pair preflight guard. Only hosts
79
+ // this device serves (loopback + own interfaces, all with our port) may talk
80
+ // to anything unauthenticated; everything else is misdirected.
81
+ const unauthHostGuard = hostGuard(hostAllowlist(config.port));
82
+ app.get("/healthz", unauthHostGuard, (_req, res) => res.json({ ok: true }));
77
83
  // The base URL is what people type first; a JSON 404 reads like a broken
78
84
  // daemon. Land them on the one real page (unpaired: enroll; paired: status).
79
- app.get("/", (_req, res) => res.redirect("/pair"));
85
+ app.get("/", unauthHostGuard, (_req, res) => res.redirect("/pair"));
80
86
  const pairing = new DevicePairing(store, config.home, config.name, process.env.DPI_HUB_URL, {
81
87
  // Forced hub change (P-5): once the new pairing is persisted the OLD
82
88
  // connector is stopped — never two live tunnels for one device, and the old
@@ -115,8 +121,8 @@ const pairEnrollGuard = (req: Request, res: Response, next: NextFunction) => {
115
121
  .json({ error: { code: "forbidden", message: "missing x-dpi-pair header" } });
116
122
  next();
117
123
  };
118
- app.get("/pair", (_req, res) => res.type("html").send(PAIR_PAGE_HTML));
119
- app.get("/v1/pair-enroll", pairEnrollGuard, (_req, res) => {
124
+ app.get("/pair", unauthHostGuard, (_req, res) => res.type("html").send(PAIR_PAGE_HTML));
125
+ app.get("/v1/pair-enroll", unauthHostGuard, pairEnrollGuard, (_req, res) => {
120
126
  const s = pairing.status();
121
127
  res.json({
122
128
  state: s.state,
@@ -126,7 +132,7 @@ app.get("/v1/pair-enroll", pairEnrollGuard, (_req, res) => {
126
132
  lastError: s.lastError,
127
133
  });
128
134
  });
129
- app.post("/v1/pair-enroll", pairEnrollGuard, express.json({ limit: "8kb" }), (req, res) => {
135
+ app.post("/v1/pair-enroll", unauthHostGuard, pairEnrollGuard, express.json({ limit: "8kb" }), (req, res) => {
130
136
  void (async () => {
131
137
  const s = pairing.status();
132
138
  if (s.state === "paired")
@@ -1279,12 +1279,18 @@ export class Store {
1279
1279
  }
1280
1280
 
1281
1281
  async createGraph(body: Record<string, unknown>): Promise<GraphRecord> {
1282
+ // R16 (run-2 h6 parity): sessions refuse a bad cwd up-front; graphs ran
1283
+ // confined only at run time. Same rule at mutation time.
1284
+ if (typeof body?.cwd === "string" && body.cwd.trim())
1285
+ await this.assertSessionCwdAllowed(normaliseCwd(body.cwd));
1282
1286
  const created = await this.graphs.create(body as never);
1283
1287
  this.notify();
1284
1288
  return created;
1285
1289
  }
1286
1290
 
1287
1291
  async updateGraph(id: string, body: Record<string, unknown>): Promise<GraphRecord> {
1292
+ if (typeof body?.cwd === "string" && body.cwd.trim())
1293
+ await this.assertSessionCwdAllowed(normaliseCwd(body.cwd));
1288
1294
  const updated = await this.graphs.update(id, body as never);
1289
1295
  this.notify();
1290
1296
  return updated;
@@ -22,8 +22,14 @@ export type BundleTarget = Ref<{
22
22
  export function downloadBundle(r: BundleFile) {
23
23
  const a = document.createElement("a");
24
24
  // slice() normalizes the buffer to a plain ArrayBuffer (BlobPart typing, TS 5.7).
25
- a.href = URL.createObjectURL(new Blob([r.bytes.slice()], { type: r.mime || "application/zip" }));
26
- a.download = r.filename;
25
+ // R16 (run-2 h13): the device is untrusted at the operator origin — the FE
26
+ // authors the label itself (mirrors hub delta-6): zip MIME is a literal and
27
+ // the filename is charset-folded, extension-stripped is unnecessary (the
28
+ // honest device contract is *.bundle.zip) but the cap keeps it sane.
29
+ let stem = (r.filename || "device-response").replace(/[^A-Za-z0-9._-]/g, "_").slice(0, 80) || "device-response";
30
+ if (/\.zip$/i.test(r.filename) && !/\.zip$/i.test(stem)) stem = `${stem.slice(0, 76)}.zip`;
31
+ a.href = URL.createObjectURL(new Blob([r.bytes.slice()], { type: "application/zip" }));
32
+ a.download = stem;
27
33
  a.click();
28
34
  URL.revokeObjectURL(a.href);
29
35
  }
@@ -105,6 +105,9 @@ 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
111
  // Credential material without its prefix (slices, echo): 43-char base64url runs.
109
112
  out = out.replace(/(?<![A-Za-z0-9_-])[A-Za-z0-9_-]{43}(?![A-Za-z0-9_-])/g, "<redacted>");
110
113
  // Pairing codes as standalone values ("code":"AB2C7DEF" / "ABCD2345EF67") but not ordinary words.
@@ -527,6 +527,21 @@ export class PairingService {
527
527
  return this.fail(409, "code_in_use", "This code is reserved for another enrollment");
528
528
  if (existing.cancelled) return this.fail(410, "enrollment_cancelled", "Enrollment cancelled");
529
529
  if (now >= live.expiresAt) return this.fail(410, "code_expired", "Pairing code expired");
530
+ // R16 (run-2 h2 hardening): the dead window. A proof that arrives after
531
+ // NONCE_TTL is refused forever (verify() re-checks the TTL against the
532
+ // ORIGINAL nonceIssuedAt) while the code stays live for minutes — an
533
+ // unverified enrollment could never complete. Same-identity re-entry is
534
+ // exactly the retry signal: mint a fresh nonce for an unverified,
535
+ // unconsumed, stale ceremony. Verified/consumed enrollments keep their
536
+ // nonce (idempotent answer; a consumed nonce is terminal by design).
537
+ if (
538
+ existing.verifiedAt === undefined &&
539
+ !existing.nonceConsumed &&
540
+ now - existing.nonceIssuedAt > NONCE_TTL_MS
541
+ ) {
542
+ existing.nonce = randomBytes(32).toString("base64url");
543
+ existing.nonceIssuedAt = now;
544
+ }
530
545
  return this.ok({
531
546
  type: "pair.challenge",
532
547
  v: 1,
@@ -66,7 +66,16 @@ export function proxy(
66
66
  {
67
67
  method: req.method,
68
68
  path,
69
- idempotencyKey: req.get("idempotency-key") ?? undefined,
69
+ // R16 (run-2 h4): bound the forwarded key to the device schema cap —
70
+ // an over-long key would be schema-rejected on the device and drop
71
+ // the tunnel into reconnect churn. Refuse it cleanly at the edge.
72
+ idempotencyKey: (() => {
73
+ const k = req.get("idempotency-key");
74
+ if (k === undefined) return undefined;
75
+ if (k.length > 256)
76
+ throw new DpiError("invalid", "idempotency-key longer than 256 chars", 400);
77
+ return k;
78
+ })(),
70
79
  body: req.body ?? {},
71
80
  },
72
81
  closed.signal,
@@ -124,7 +133,9 @@ export function proxy(
124
133
  const disposition = isZip
125
134
  ? `attachment; filename="${stem}.zip"`
126
135
  : 'attachment; filename="device-response.bin"';
127
- res.type(isZip ? contentType : "application/octet-stream")
136
+ // R16 (run-2 h4): the zip LABEL is hub-authored — a chunk-sourced
137
+ // contentType has no length bound, so never reflect it verbatim.
138
+ res.type(isZip ? "application/zip" : "application/octet-stream")
128
139
  .set("Content-Disposition", disposition)
129
140
  .send(payload);
130
141
  }
@@ -8,6 +8,8 @@
8
8
  */
9
9
  import { DpiClient } from "../../../../dpi-sdk/src/client.js";
10
10
  import { DpiError } from "../../../../dpi-sdk/src/errors.js";
11
+ import { validateRestRequest } from "../../../../dpi-sdk/src/protocol/tunnel.js";
12
+ import { REST_PATH_PREFIX } from "../../../../dpi-sdk/src/protocol/limits.js";
11
13
  import type { Frame } from "../../../../dpi-sdk/src/api.js";
12
14
  import type { DeviceRow } from "../../../../dpi-sdk/src/node/registry.js";
13
15
 
@@ -77,6 +79,18 @@ export class LanTransport implements DeviceTransport {
77
79
 
78
80
  async request(input: TransportRequest, signal: AbortSignal): Promise<TransportResponse> {
79
81
  if (!this.available) throw new DpiError("unauthorized", "LAN device has no URL/token", 0);
82
+ // R16 (run-2 h4 parity): the tunnel dispatcher runs the REST allowlist on
83
+ // every request; the LAN leg must not be the weaker twin — same principal
84
+ // today, but drift here would surface as a hub-frontend-only capability.
85
+ // The tunnel contract carries the /v1 prefix; this leg's paths are already
86
+ // prefix-stripped, so re-attach it for the shared validator.
87
+ const allow = validateRestRequest({
88
+ method: input.method,
89
+ path: input.path.startsWith(REST_PATH_PREFIX)
90
+ ? input.path
91
+ : `${REST_PATH_PREFIX}${input.path}`,
92
+ });
93
+ if (!allow.ok) throw new DpiError("invalid", allow.error ?? "path not allowed", 400);
80
94
  const timeout = AbortSignal.timeout(REST_TIMEOUT_MS);
81
95
  const effective = signal ? AbortSignal.any([signal, timeout]) : timeout;
82
96
  const hasBody = !["GET", "HEAD", "DELETE"].includes(input.method);
@@ -339,7 +339,17 @@ export class TunnelDispatcher {
339
339
  idempotentReplay?: unknown;
340
340
  }
341
341
  | undefined;
342
- if (typeof env?.status !== "number" || !Number.isFinite(env.status)) {
342
+ // R16 (run-2 h3): mirror the inline plain-frame schema caps here — the
343
+ // chunked envelope carries no TypeBox schema, so without this a
344
+ // device could deliver a 1xx/300-599-fractional status or an
345
+ // unbounded contentType string (proxy would reflect it verbatim into
346
+ // a response header).
347
+ if (
348
+ typeof env?.status !== "number" ||
349
+ !Number.isInteger(env.status) ||
350
+ env.status < 200 ||
351
+ env.status > 599
352
+ ) {
343
353
  p?.resolve({
344
354
  status: 502,
345
355
  body: {
@@ -350,7 +360,10 @@ export class TunnelDispatcher {
350
360
  }
351
361
  p?.resolve({
352
362
  status: env.status,
353
- contentType: typeof env.contentType === "string" ? env.contentType : undefined,
363
+ contentType:
364
+ typeof env.contentType === "string" && env.contentType.length <= 256
365
+ ? env.contentType
366
+ : undefined,
354
367
  body: env.body,
355
368
  ...(env.bodyEncoding === "base64" ? { bodyEncoding: "base64" as const } : {}),
356
369
  ...(env.bodyEncoding === "base64"
@@ -31,7 +31,9 @@ const ENVELOPE_OVERHEAD_BYTES = 256;
31
31
 
32
32
  export type ChunkCorrelation =
33
33
  | { kind: "tunnel-data"; subscriptionId: string; sub: string }
34
- | { kind: "rest-request" | "rest-response"; reqId: string };
34
+ // R16: chunked rest-REQUESTS are a dead direction (removed from DEVICE_TO_HUB
35
+ // and never hub->device) — the correlation surface is rest-response only.
36
+ | { kind: "rest-response"; reqId: string };
35
37
 
36
38
  const correlationKey = (c: ChunkCorrelation) =>
37
39
  c.kind === "tunnel-data" ? `data:${c.subscriptionId}` : `${c.kind}:${c.reqId}`;
@@ -232,10 +234,15 @@ export class ChunkReassembler {
232
234
  */
233
235
  feed(chunk: TunnelChunk, owns: (correlation: ChunkCorrelation) => boolean): AssemblyOutcome {
234
236
  if (chunk.type !== "tunnel-chunk") return { ok: false, error: "chunk: not a chunk frame" };
235
- const correlation: ChunkCorrelation =
237
+ // R16: chunk.kind "rest-request" is a dead direction (direction assert
238
+ // rejects it upstream) — narrow here so the type stays honest.
239
+ const correlation: ChunkCorrelation | null =
236
240
  chunk.kind === "tunnel-data"
237
241
  ? { kind: "tunnel-data", subscriptionId: chunk.subscriptionId, sub: chunk.sub }
238
- : { kind: chunk.kind, reqId: chunk.reqId };
242
+ : chunk.kind === "rest-response"
243
+ ? { kind: "rest-response", reqId: chunk.reqId }
244
+ : null;
245
+ if (!correlation) return { ok: false, error: "chunk: unsupported chunk kind" };
239
246
  const key = correlationKey(correlation);
240
247
  const envelope = validateChunkEnvelope(chunk);
241
248
  if (!envelope.ok) return { ok: false, error: envelope.error };
@@ -110,6 +110,9 @@ async function writeEnv(device: NetDevice, ctx: DriverContext, rotate = false) {
110
110
  const local = localEnv(ctx.config);
111
111
  const missing = device.envKeys.filter((k) => !(local[k] ?? process.env[k]));
112
112
  if (missing.length) ctx.log(`warning: ${missing.join(", ")} not found in ${join(ctx.config.root, ".env")} or the environment`);
113
+ for (const [k, v] of Object.entries(device.env))
114
+ if (typeof v !== "string" || !v || /[\n\r]/.test(v))
115
+ ctx.log(`warning: device ${device.id} env ${k} has no value or contains a newline — skipped`);
113
116
  const home = shPath(device.homeDir);
114
117
  const body = [
115
118
  `DPI_DEVICE_NAME=${device.id}`,
@@ -120,7 +123,13 @@ async function writeEnv(device: NetDevice, ctx: DriverContext, rotate = false) {
120
123
  const v = local[k] ?? process.env[k];
121
124
  return v && !/[\n\r]/.test(v) ? [`${k}=${v}`] : [];
122
125
  }),
123
- ...Object.entries(device.env).map(([k, v]) => `${k}=${v}`),
126
+ // R16 (run-2 h12): env_keys secrets already refuse [\n\r]; plain env:
127
+ // entries get the same guard — a multiline YAML value would inject extra
128
+ // KEY=VALUE lines into backend.env (incl. a duplicate DPI_TOKEN, last
129
+ // wins). Misconfigured values are skipped, mirroring the env_keys branch.
130
+ ...Object.entries(device.env).flatMap(([k, v]) =>
131
+ typeof v === "string" && v && !/[\n\r]/.test(v) ? [`${k}=${v}`] : [],
132
+ ),
124
133
  ].join("\n");
125
134
  const mkStartDirs = device.startDirs.map((r) => `mkdir -p "${shPath(r)}"`).join("\n");
126
135
  await exec(
@@ -145,6 +154,10 @@ echo "env ok"`,
145
154
  function fill(template: string, values: Record<string, string>) {
146
155
  return template.replace(/__([A-Z_]+)__/g, (m, key: string) => {
147
156
  if (!(key in values)) throw Error(`Template placeholder ${m} has no value`);
157
+ // R16 (run-2 h12): these values land in a root-owned systemd unit / a
158
+ // LaunchAgent plist — a newline would inject whole new directives.
159
+ if (/[\n\r]/.test(values[key]))
160
+ throw Error(`Template value for ${key} contains a newline`);
148
161
  return values[key];
149
162
  });
150
163
  }
@@ -306,7 +306,9 @@ const DEVICE_TO_HUB = new Set([
306
306
  "tunnel-chunk:tunnel-data",
307
307
  "rest-response",
308
308
  "tunnel-chunk:rest-response",
309
- "tunnel-chunk:rest-request",
309
+ // R16 (run-2 h3): no producer exists for a chunked rest-request device->hub
310
+ // (route() ignored it silently). Removed instead of dead-allowed: a future
311
+ // device sending one is now an audited direction violation, not drift.
310
312
  ]);
311
313
 
312
314
  function messageKey(msg: { type: string; action?: string; kind?: string }): string {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "my-durable",
3
- "version": "0.0.70",
3
+ "version": "0.0.71",
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": {