my-durable 0.0.115 → 0.0.116

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.
@@ -34,6 +34,7 @@ import {
34
34
  } from "lucide-vue-next";
35
35
  import { deviceId, network, sessionSummary, notify, select } from "../client/store";
36
36
  import { deviceClient } from "../client/hub";
37
+ import { externalHref } from "../client/link-policy"; // r10 h4-1: device-authored URLs never bind raw
37
38
  import { ensureGit, gitAllowedFor, gitEntry, wireGitAutoRefresh } from "../client/git-store";
38
39
  import { addWorktree as gitAddWorktree, createSessionOn } from "../client/worktree";
39
40
  import type { GitStatus } from "@sdk/client";
@@ -136,7 +137,7 @@ const prBusy = ref(false);
136
137
  * actions built from the origin URL — no CLI, no login, no assumption. */
137
138
  const forge = computed<"github" | "gitlab" | "bitbucket" | "other" | undefined>(() => status.value?.forge);
138
139
  const isGitHub = computed(() => forge.value === "github");
139
- const webUrl = computed(() => status.value?.webUrl ?? "");
140
+ const webUrl = computed(() => externalHref(status.value?.webUrl ?? "", globalThis.location?.origin ?? "") ?? "");
140
141
  const changeLabel = computed(() =>
141
142
  forge.value === "gitlab" ? "merge request" : forge.value === "bitbucket" ? "pull request" : forge.value === "github" ? "pull request" : "change request",
142
143
  );
@@ -153,9 +154,11 @@ const newChangeHref = computed(() => {
153
154
  if (forge.value === "github") return `${webUrl.value}/compare/${b || "main"}...${e}?expand=1`;
154
155
  return "";
155
156
  });
156
- const changesHref = computed(() =>
157
- forge.value === "gitlab" ? `${webUrl.value}/-/merge_requests` : forge.value === "bitbucket" ? `${webUrl.value}/pull-requests` : `${webUrl.value}/pulls`,
158
- );
157
+ const changesHref = computed(() => {
158
+ if (!webUrl.value) return "";
159
+ return forge.value === "gitlab" ? `${webUrl.value}/-/merge_requests` : forge.value === "bitbucket" ? `${webUrl.value}/pull-requests` : `${webUrl.value}/pulls`;
160
+ });
161
+ const prSafeUrl = (u: string) => externalHref(u, globalThis.location?.origin ?? "");
159
162
  const loadPRs = async () => {
160
163
  if (!devId.value || !cwd.value) return;
161
164
  const allowed = gitAllowedFor(devId.value, cwd.value);
@@ -346,7 +349,7 @@ const dirty = computed(() => (status.value?.staged ?? 0) + (status.value?.unstag
346
349
  const noIdentity = computed(() => status.value?.repo === true && status.value?.identityComplete === false);
347
350
  /** The device parses the origin once (ssh/https/self-hosted/nested GitLab
348
351
  * namespaces) and reports the browser URL; a second FE parser drifted from it. */
349
- const remoteWeb = computed(() => status.value?.webUrl ?? "");
352
+ const remoteWeb = computed(() => externalHref(status.value?.webUrl ?? "", globalThis.location?.origin ?? "") ?? "");
350
353
  const toggle = (p: string) => {
351
354
  const next = new Set(checked.value);
352
355
  if (next.has(p)) next.delete(p);
@@ -1237,8 +1240,8 @@ const laneX = (lane: number) => lane * 12 + 7;
1237
1240
  <h4><GitMerge :size="16" /> {{ isGitHub ? "Pull requests" : changeLabel + "s" }}</h4>
1238
1241
  <span class="grow" />
1239
1242
  <a v-if="!isGitHub && newChangeHref" class="small btn-like" :href="newChangeHref" target="_blank" rel="noopener">new {{ changeLabel }}</a>
1240
- <a v-if="!isGitHub" class="small btn-like" :href="changesHref" target="_blank" rel="noopener">open {{ changeLabel }}s</a>
1241
- <a v-if="!isGitHub" class="small btn-like" :href="webUrl" target="_blank" rel="noopener">repo</a>
1243
+ <a v-if="!isGitHub && changesHref" class="small btn-like" :href="changesHref" target="_blank" rel="noopener">open {{ changeLabel }}s</a>
1244
+ <a v-if="!isGitHub && webUrl" class="small btn-like" :href="webUrl" target="_blank" rel="noopener">repo</a>
1242
1245
  </div>
1243
1246
  <template v-if="!isGitHub">
1244
1247
  <p class="hint">
@@ -1263,7 +1266,7 @@ const laneX = (lane: number) => lane * 12 + 7;
1263
1266
  <button class="icon-button" title="run checks" :disabled="prBusy" @click="prChecksOf(pr.n)"><RefreshCw :size="13" /></button>
1264
1267
  <button class="icon-button" title="comment" :disabled="prBusy" @click="prCommentAsk(pr.n)"><Copy :size="13" /></button>
1265
1268
  <button v-if="pr.state === 'OPEN'" class="small" :disabled="prBusy || !!busy" @click="prMergeAsk(pr.n)">squash &amp; merge</button>
1266
- <a class="icon-button" :href="pr.url" target="_blank" rel="noopener" title="open on the forge"><ArrowUpFromLine :size="13" style="transform: rotate(45deg)" /></a>
1269
+ <a v-if="prSafeUrl(pr.url)" class="icon-button" :href="prSafeUrl(pr.url)!" target="_blank" rel="noopener" title="open on the forge"><ArrowUpFromLine :size="13" style="transform: rotate(45deg)" /></a>
1267
1270
  </div>
1268
1271
  <pre v-for="[n, text] in prChecks" :key="n" class="pr-checks">#{{ n }} checks:{{ "\n" }}{{ text }}</pre>
1269
1272
  </div>
@@ -12,8 +12,12 @@
12
12
  import { computed } from "vue";
13
13
  import { Cable, Wifi, WifiOff } from "lucide-vue-next";
14
14
  import type { NetworkDevice } from "@sdk/api";
15
+ import { externalHref } from "../client/link-policy"; // r10 h4-1: device.url is device-authored
15
16
  import { ago } from "../client/store";
16
17
 
18
+ /** Template helper: device-authored URL → http(s)-only, non-hub href (r10 h4-1). */
19
+ const safeUrl = (u: string) => externalHref(u, globalThis.location?.origin ?? "") || undefined;
20
+
17
21
  const props = defineProps<{ device: NetworkDevice }>();
18
22
 
19
23
  const online = computed(() => props.device.status === "online");
@@ -51,7 +55,7 @@ const tunnelLive = computed(() => props.device.tunnel?.state === "connected");
51
55
  >
52
56
  {{ device.tunnel.readerCount }} reader{{ device.tunnel.readerCount === 1 ? "" : "s" }}
53
57
  </span>
54
- <a v-if="device.url" class="axis url" :href="device.url" target="_blank" rel="noreferrer">{{
58
+ <a v-if="device.url" class="axis url" :href="safeUrl(device.url)" target="_blank" rel="noreferrer">{{
55
59
  device.url
56
60
  }}</a>
57
61
  <span
@@ -96,7 +96,15 @@ registry.clearTunnelState(); // live tunnel state is RAM-only; never resurrect f
96
96
  // promise inside the registry — await it (non-fatal, logged) so network.sqlite
97
97
  // is locked down before the listener starts serving.
98
98
  try {
99
- await registry.restrictOwner;
99
+ // r10 h1-3: the DACL pass runs execFile (whoami+icacls) whose callback can
100
+ // outlive its timeout if a grandchild inherits the stdout pipe — boot never
101
+ // depends on the outcome, so race it with a deadline and log lateness.
102
+ const late = Symbol("late");
103
+ const raced = await Promise.race([
104
+ registry.restrictOwner.then(() => true, () => false),
105
+ new Promise<typeof late>((resolve) => setTimeout(() => resolve(late), 10_000)),
106
+ ]);
107
+ if (raced === late) console.warn("[hub] registry owner restriction still running after 10s — continuing boot");
100
108
  } catch (error) {
101
109
  console.warn("[hub] registry owner restriction failed:", error);
102
110
  }
@@ -505,7 +513,9 @@ app.post(
505
513
  },
506
514
  );
507
515
 
508
- app.get("/api/network", (_req, res) => res.json({ configFile, devices: monitor.network() }));
516
+ app.get("/api/network", (_req, res) =>
517
+ res.json({ configFile, devices: monitor.network(), relay: mux.relayStats() }), // r10 h1-4: relay drop counters surfaced to the operator
518
+ );
509
519
  // Devices are configured in dpi-network.yaml and `just net register`; the hub only reads them.
510
520
  app.post(
511
521
  "/api/devices/:id/check",
@@ -127,7 +127,19 @@ export class StreamMux {
127
127
  private readonly registry: NetworkRegistry,
128
128
  private readonly monitor: DeviceMonitor,
129
129
  private readonly options: { budget?: ByteBudget } = {},
130
- ) {}
130
+ ) {
131
+ // r10 h1-5: ONE network snapshot + ONE serialization per monitor change,
132
+ // shared by every open tab — the old per-tab listener rebuilt and
133
+ // re-stringified the whole network view (≤32×256KiB trees) once per tab
134
+ // per change. The invalidator fires once; the first tab's send lazily
135
+ // rebuilds the cached text.
136
+ this.monitor.onChange(() => {
137
+ this.networkText = undefined;
138
+ });
139
+ }
140
+
141
+ /** Cached `data:` payload for the network fan-out (r10 h1-5). */
142
+ private networkText?: string;
131
143
 
132
144
  private readerCount(deviceId: string): number {
133
145
  const mux = this.readersByDevice.get(deviceId) ?? 0;
@@ -203,8 +215,13 @@ export class StreamMux {
203
215
  this.streams.set(streamId, stream);
204
216
  stream.send({ sub: "hello", frame: { type: "stream", streamId } });
205
217
  if (closed) return;
206
- const pushNetwork = () =>
207
- stream.send({ sub: "network", frame: { type: "network", devices: this.monitor.network() } });
218
+ const pushNetwork = () => {
219
+ const text = (this.networkText ??= JSON.stringify({
220
+ sub: "network",
221
+ frame: { type: "network", devices: this.monitor.network() },
222
+ }));
223
+ stream.send({ sub: "network", frame: { type: "network", devices: [] } }, text);
224
+ };
208
225
  pushNetwork();
209
226
  if (closed) return;
210
227
  off = this.monitor.onChange(pushNetwork);
@@ -154,6 +154,55 @@ export interface GitOpResult {
154
154
  prs?: { n: number; title: string; state: string; draft: boolean; branch: string; url: string }[];
155
155
  }
156
156
 
157
+
158
+ /** r10 h3-1: the SDK client is the trust-boundary reader — every hub leg is
159
+ * capped (transport.ts readBodyCapped 16MiB textual / 12MB binary), but this
160
+ * client buffered `response.text()` / `arrayBuffer()` whole. A compromised
161
+ * device answering a multi-GB body OOMs the operator's TUI / net scripts /
162
+ * browser export. Cap with hub parity: content-length precheck, then a
163
+ * byte-counting stream read that aborts at the ceiling. Isomorphic: no Buffer. */
164
+ const TEXT_BODY_MAX = 16 * 1024 * 1024;
165
+ const BINARY_BODY_MAX = 12 * 1024 * 1024;
166
+
167
+ async function readBodyCapped(response: Response, cap: number, what: string): Promise<Uint8Array> {
168
+ const declared = Number(response.headers.get("content-length") ?? "");
169
+ if (Number.isFinite(declared) && declared > cap)
170
+ throw new DpiError("invalid", `${what} over ${cap} bytes (content-length ${declared})`, 413);
171
+ const body = (response as { body?: ReadableStream<Uint8Array> | null }).body;
172
+ if (body && typeof body.getReader === "function") {
173
+ const reader = body.getReader();
174
+ const chunks: Uint8Array[] = [];
175
+ let total = 0;
176
+ for (;;) {
177
+ const { done, value } = await reader.read();
178
+ if (done) break;
179
+ total += value.byteLength;
180
+ if (total > cap) {
181
+ try {
182
+ await reader.cancel();
183
+ } catch {
184
+ /* already closed */
185
+ }
186
+ throw new DpiError("invalid", `${what} over ${cap} bytes`, 413);
187
+ }
188
+ chunks.push(value);
189
+ }
190
+ const merged = new Uint8Array(total);
191
+ let off = 0;
192
+ for (const c of chunks) {
193
+ merged.set(c, off);
194
+ off += c.byteLength;
195
+ }
196
+ return merged;
197
+ }
198
+ // No stream (mocks / very old runtimes): read once, then enforce the cap.
199
+ const fallback = what === "response body"
200
+ ? new TextEncoder().encode(await response.text())
201
+ : new Uint8Array(await response.arrayBuffer());
202
+ if (fallback.byteLength > cap) throw new DpiError("invalid", `${what} over ${cap} bytes`, 413);
203
+ return fallback;
204
+ }
205
+
157
206
  export class DpiClient {
158
207
  readonly baseUrl: string;
159
208
  constructor(
@@ -199,7 +248,8 @@ export class DpiClient {
199
248
  if (options.signal?.aborted) throw cause;
200
249
  throw new DpiError("offline", `Cannot reach ${this.baseUrl}`, 0, { cause });
201
250
  }
202
- const text = await response.text();
251
+ // r10 h3-1: capped read — the hub legs cap at 16MiB textual; mirror here.
252
+ const text = new TextDecoder().decode(await readBodyCapped(response, TEXT_BODY_MAX, "response body"));
203
253
  let data: unknown;
204
254
  try {
205
255
  data = text ? JSON.parse(text) : undefined;
@@ -436,7 +486,8 @@ export class DpiClient {
436
486
  response.status,
437
487
  );
438
488
  }
439
- const bytes = new Uint8Array(await response.arrayBuffer());
489
+ // r10 h3-1: binary leg — 12MB parity with the hub's readBodyCapped.
490
+ const bytes = await readBodyCapped(response, BINARY_BODY_MAX, "export body");
440
491
  // `filename="quoted"` (the device's form) or a bare token, per RFC 6266.
441
492
  const disposition = response.headers.get("content-disposition") ?? "";
442
493
  const quoted = /filename="((?:[^"\\]|\\.)*)"/i.exec(disposition)?.[1];
@@ -195,8 +195,12 @@ export function rsync(device: NetDevice, sources: string[], dest: string, cwd: s
195
195
  /** The full exe.dev argv, built explicitly from guarded args (pure, testable). */
196
196
  export function exeDevArgv(args: string[]): string[] {
197
197
  for (const a of args)
198
- if (!a || !EXE_ARG_RE.test(a))
199
- throw Error(`exe.dev argument rejected (allowed charset [A-Za-z0-9._=-], no whitespace/metacharacters): ${JSON.stringify(a)}`);
198
+ if (!a || !EXE_ARG_RE.test(a) || /^-[^-]/.test(a) || a === "-" || a === "--")
199
+ // r10 h3-4: ssh re-parses single-dash words as ITS options (-o, -L…) —
200
+ // those die at the sink. Double-dash `--name=x` flags are exe.dev's own
201
+ // grammar (call sites pass them as constants) and stay legal; the
202
+ // charset gate already blocks everything else.
203
+ throw Error(`exe.dev argument rejected (allowed charset [A-Za-z0-9._=-], no whitespace/metacharacters, no single-dash options): ${JSON.stringify(a)}`);
200
204
  return ["-o", "BatchMode=yes", "-o", "ConnectTimeout=15", "exe.dev", ...args, "--json"];
201
205
  }
202
206
 
@@ -10,7 +10,7 @@
10
10
  * crashes the caller: it reports and returns false so the boot can continue and
11
11
  * a later pass can retry.
12
12
  */
13
- import { chmodSync, closeSync, fsyncSync, openSync, renameSync, rmSync, writeSync } from "node:fs";
13
+ import { chmodSync, closeSync, fsyncSync, openSync, readdirSync, renameSync, rmSync, statSync, writeSync } from "node:fs";
14
14
  import { execFile } from "node:child_process";
15
15
  import { basename, dirname, join } from "node:path";
16
16
  import { randomBytes } from "node:crypto";
@@ -114,6 +114,38 @@ export async function restrictDirToOwner(path: string, deps: RestrictDeps = {}):
114
114
  const tempSiblingName = (path: string) =>
115
115
  join(dirname(path), `.${basename(path)}.${randomBytes(6).toString("hex")}.tmp`);
116
116
 
117
+ /** r10 h3-2: a SIGKILL between writeSync and renameSync strands a
118
+ * secret-bearing temp sibling that nothing ever cleaned — random names never
119
+ * collide, so one stale copy of EVERY rotated-away credential could
120
+ * accumulate. Prune the target's stale temps (grace window keeps a concurrent
121
+ * writer's live temp safe) at the top of every atomic write. */
122
+ const TEMP_GRACE_MS = 60 * 60 * 1000;
123
+ function pruneStaleTemps(path: string, deps: RestrictDeps = {}): void {
124
+ if ((deps.platform ?? process.platform) === "win32") {
125
+ // win32 rename-refusal races make pruning riskier than the residue; the
126
+ // 0700 dir already bounds exposure there.
127
+ return;
128
+ }
129
+ const dir = dirname(path);
130
+ const prefix = `.${basename(path)}.`;
131
+ let names: string[];
132
+ try {
133
+ names = readdirSync(dir);
134
+ } catch {
135
+ return;
136
+ }
137
+ const now = Date.now();
138
+ for (const name of names) {
139
+ if (!name.startsWith(prefix) || !name.endsWith(".tmp")) continue;
140
+ try {
141
+ const full = join(dir, name);
142
+ if (now - statSync(full).mtimeMs > TEMP_GRACE_MS) rmSync(full, { force: true });
143
+ } catch {
144
+ /* someone else's temp racing us — leave it */
145
+ }
146
+ }
147
+ }
148
+
117
149
  /**
118
150
  * Atomic write for credential files (orca STA-3941 / paseo writePrivateFileAtomicSync):
119
151
  * temp file 0600 + fsync + rename, so readers only ever see the old bytes or the
@@ -131,6 +163,7 @@ export async function writePrivateFileAtomic(
131
163
  deps: RestrictDeps = {},
132
164
  ): Promise<boolean> {
133
165
  ensurePrivateDir(dirname(path));
166
+ pruneStaleTemps(path, deps);
134
167
  const temp = (deps.tempName ?? tempSiblingName)(path);
135
168
  let fd: number | undefined;
136
169
  try {
@@ -297,7 +297,11 @@ export class NetworkRegistry {
297
297
  },
298
298
  ) {
299
299
  const sets = ["last_status=?", "last_error=?"];
300
- const values: (string | number | null)[] = [patch.status, patch.error ?? null];
300
+ // r10 h3-3: last_error is device-authored too (error.message from the LAN
301
+ // leg is bounded only by the 16MiB transport cap) — the info/tree caps
302
+ // above must not leave this column as the one uncapped rewrite target.
303
+ const errCap = (e: string | null | undefined) => (e == null ? null : e.slice(0, 2048));
304
+ const values: (string | number | null)[] = [patch.status, errCap(patch.error)];
301
305
  if (patch.seenAt !== undefined) sets.push("last_seen_at=?"), values.push(patch.seenAt);
302
306
  // run-7 B4: device-authored JSON is untrusted — cap what a hostile device
303
307
  // can rewrite into the registry row every 10s (the uiSet sibling caps UI
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "my-durable",
3
- "version": "0.0.115",
3
+ "version": "0.0.116",
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": {