@foldrun/core 23.4.0 → 24.1.0

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.
@@ -44,6 +44,7 @@ import crypto from "node:crypto";
44
44
  import { dataRoot } from "./paths.ts";
45
45
  import { processState } from "./process-state.ts";
46
46
  import { BlobNotFound, fileSource, hashRange, type BlobStore } from "./blob-store.ts";
47
+ import { plainStream, readPlain, statPlain, UnsafeFileError } from "./safe-open.ts";
47
48
  import { PUBLISH_PIN_TTL_MS, noPins, type BlobPins, type PinHolder } from "./blob-pins.ts";
48
49
  import {
49
50
  MAX_MANIFEST_FILES,
@@ -237,10 +238,17 @@ interface Candidate {
237
238
  abs: string;
238
239
  size: number;
239
240
  mode: number;
241
+ /** The inode the walk saw: the read must find the same one (safe-open.ts). */
242
+ dev: number;
243
+ ino: number;
240
244
  }
241
245
 
242
246
  function walk(root: string): Candidate[] {
243
247
  const out: Candidate[] = [];
248
+ // The folder itself a link (an agent folder pointed elsewhere): its
249
+ // contents are not this run's outputs, and the per-file root check would
250
+ // take the link's target for the root. Nothing is kept from it.
251
+ if (fs.lstatSync(root).isSymbolicLink()) return out;
244
252
  const rec = (dir: string, rel: string) => {
245
253
  for (const e of fs.readdirSync(dir, { withFileTypes: true })) {
246
254
  const abs = path.join(dir, e.name);
@@ -248,7 +256,7 @@ function walk(root: string): Candidate[] {
248
256
  if (e.isDirectory()) rec(abs, r);
249
257
  else if (e.isFile()) {
250
258
  const st = fs.lstatSync(abs);
251
- out.push({ rel: r, abs, size: st.size, mode: st.mode & 0o111 ? MODE_EXEC : MODE_FILE });
259
+ out.push({ rel: r, abs, size: st.size, mode: st.mode & 0o111 ? MODE_EXEC : MODE_FILE, dev: st.dev, ino: st.ino });
252
260
  }
253
261
  // symlinks, sockets and the like are not outputs (the volume copy skipped them too)
254
262
  }
@@ -340,33 +348,44 @@ export async function publishRunOutputs(
340
348
  const c = kept[i];
341
349
  let sha: string;
342
350
  let size: number;
343
- if (c.size <= SMALL_OUTPUT_FILE_BYTES) {
344
- const body = fs.readFileSync(c.abs);
345
- // Grew since it was measured (an agent still writing): same rule, same cap.
346
- if (body.length > fileCap) {
347
- refused.push({ agent, path: c.rel, bytes: body.length, reason: "file-cap", limit: fileCap });
348
- continue;
349
- }
350
- sha = sha256Hex(body);
351
- size = body.length;
352
- // Pin each blob before its put; a repeat extends the lease.
353
- await pins.pinBlobs(tenant, [sha], publishHolder, { ttlMs: PUBLISH_PIN_TTL_MS });
354
- await b.blobs.putIfAbsent(blobObjectKey(tenant, sha), body);
355
- } else {
356
- const source = fileSource(c.abs);
357
- if (source.size > fileCap) {
358
- refused.push({ agent, path: c.rel, bytes: source.size, reason: "file-cap", limit: fileCap });
359
- continue;
351
+ // The walk looked with lstat; the read opens the path without following
352
+ // a link and must find the inode the walk saw (a file the agent swapped
353
+ // for a link to a secret, or a FIFO, since is refused, not read). The
354
+ // outputs folder is the root: a folder swapped for a link out is too.
355
+ const want = { dev: c.dev, ino: c.ino, root: dir };
356
+ try {
357
+ if (c.size <= SMALL_OUTPUT_FILE_BYTES) {
358
+ // A file that grew past twice the small size since the walk is not read whole.
359
+ const body = readPlain(c.abs, { ...want, maxBytes: 2 * SMALL_OUTPUT_FILE_BYTES });
360
+ // Grew since it was measured (an agent still writing): same rule, same cap.
361
+ if (body.length > fileCap) {
362
+ refused.push({ agent, path: c.rel, bytes: body.length, reason: "file-cap", limit: fileCap });
363
+ continue;
364
+ }
365
+ sha = sha256Hex(body);
366
+ size = body.length;
367
+ // Pin each blob before its put; a repeat extends the lease.
368
+ await pins.pinBlobs(tenant, [sha], publishHolder, { ttlMs: PUBLISH_PIN_TTL_MS });
369
+ await b.blobs.putIfAbsent(blobObjectKey(tenant, sha), body);
370
+ } else {
371
+ const source = fileSource(c.abs, want);
372
+ if (source.size > fileCap) {
373
+ refused.push({ agent, path: c.rel, bytes: source.size, reason: "file-cap", limit: fileCap });
374
+ continue;
375
+ }
376
+ // A file that changes under the read throws BlobSourceError (and the
377
+ // store checks the hash it is given): the publish fails, never stores
378
+ // bytes under a name they do not have.
379
+ sha = (await hashRange(source, 0, source.size)).sha256;
380
+ size = source.size;
381
+ await pins.pinBlobs(tenant, [sha], publishHolder, { ttlMs: PUBLISH_PIN_TTL_MS });
382
+ await b.blobs.putSourceIfAbsent(blobObjectKey(tenant, sha), source, { sha256: sha });
360
383
  }
361
- // A file that changes under the read throws BlobSourceError (and the
362
- // store checks the hash it is given): the publish fails, never stores
363
- // bytes under a name they do not have.
364
- sha = (await hashRange(source, 0, source.size)).sha256;
365
- size = source.size;
366
- await pins.pinBlobs(tenant, [sha], publishHolder, { ttlMs: PUBLISH_PIN_TTL_MS });
367
- await b.blobs.putSourceIfAbsent(blobObjectKey(tenant, sha), source, { sha256: sha });
384
+ files[c.rel] = { sha, size, mode: c.mode };
385
+ } catch (err) {
386
+ if (!(err instanceof UnsafeFileError)) throw err;
387
+ refused.push({ agent, path: c.rel, bytes: c.size, reason: "unsafe" });
368
388
  }
369
- files[c.rel] = { sha, size, mode: c.mode };
370
389
  }
371
390
  };
372
391
  await Promise.all(Array.from({ length: Math.min(UPLOAD_CONCURRENCY, kept.length) }, lane));
@@ -560,11 +579,13 @@ export async function openRunOutput(tenant: string, workspace: string, runId: st
560
579
  }
561
580
  const file = runOutputPathOnVolume(tenant, workspace, runId, agent, rel);
562
581
  if (!file) return null;
563
- const size = fs.statSync(file).size;
582
+ // Opened without following a link: the path was checked by
583
+ // runOutputPathOnVolume, and a swap since (link, FIFO) is refused (SYMRACE).
584
+ const seen = statPlain(file);
564
585
  return {
565
- size,
586
+ size: seen.size,
566
587
  // Node's own bridge keeps the file stream paused until the reader pulls.
567
- read: (range) => Readable.toWeb(fs.createReadStream(file, range ? { start: range.start, end: range.end } : undefined)) as ReadableStream<Uint8Array>,
588
+ read: (range) => Readable.toWeb(plainStream(file, { dev: seen.dev, ino: seen.ino, ...(range ? { start: range.start, end: range.end } : {}) })) as ReadableStream<Uint8Array>,
568
589
  };
569
590
  }
570
591
 
package/src/runner.ts CHANGED
@@ -6,7 +6,7 @@
6
6
  import { opsLog, opsError } from "./ops-log.ts";
7
7
  import { globMatch } from "./bounded-match.ts";
8
8
  import { latestRevisionId } from "./history.ts";
9
- import { recordCallIo, redactionsFor, scrubWith } from "./capture.ts";
9
+ import { maskPatterns, recordCallIo, redactionsFor, scrubWith } from "./capture.ts";
10
10
  import { callSink, flushCalls } from "./captured-calls.ts";
11
11
  import { AUTH_REFUSAL, platformCause } from "./issues.ts";
12
12
  import { hookNames } from "./hooks.ts";
@@ -45,7 +45,7 @@ const isolatedRun = () => {
45
45
  import { gatherConsults, buildConsultTools } from "./agent-tools.ts";
46
46
  import { DELEGATE_TOOL, gatherSubagents, ownSandbox, subagentPrompt, subagentTools, SUBAGENT_NO_REMOTES, type DelegateSpec, type SubagentSpec } from "./subagents.ts";
47
47
  import { DELEGATE_SERVER, buildDelegateTools, delegatePromptLine, delegateToolNames, localDelegateChannel, readCopyBack } from "./delegate-tools.ts";
48
- import type { DelegationResult } from "./operator.ts";
48
+ import type { DelegationResult, OperatorEvent } from "./operator.ts";
49
49
  import type { StepDelegation } from "./store.ts";
50
50
  import { TEXT_SERVER, TEXT_TOOL, buildTextTools, textPromptLine } from "./text-tool.ts";
51
51
  import { ASK_TOOL, PEER_TOOLS, applyOperatorEvent, askPromptLine, askTimeoutSec, buildAskTool, buildPeerTools, inboxReader, localPeerBus, peersPromptLine, type PeerInfo } from "./operator.ts";
@@ -1439,7 +1439,7 @@ export function agentContext(
1439
1439
  const providerBlock =
1440
1440
  fileBlock ??
1441
1441
  (supply.kind === "foldrun"
1442
- ? supplyProviderBlock(supply.provider, supply.tiers)
1442
+ ? supplyProviderBlock(supply.provider, supply.tiers, supply.via)
1443
1443
  : supply.kind === "refused"
1444
1444
  ? undefined
1445
1445
  : accountModelBlock((name) => getSecret(tenant, name)?.value ?? null));
@@ -2293,6 +2293,27 @@ async function runStepBody(
2293
2293
  let canActOutward = false;
2294
2294
  const eventsAtStart = step.events.length;
2295
2295
  const redact = (text: string) => scrubWith(redactions, text);
2296
+ // An event line, a question, a message: text that came out of a sandbox or a
2297
+ // model, read by viewers, A2A callers, notifications and exports. The values
2298
+ // above, then what no vault value covers (a key a tool printed, a private
2299
+ // key block) — the mask a captured call already gets. One place: the retry
2300
+ // row's error, the run's failure reason and a notification's summary are all
2301
+ // read back off these events.
2302
+ const mask = (text: string) => maskPatterns(redact(text));
2303
+ const maskOperator = (ev: OperatorEvent): OperatorEvent => {
2304
+ switch (ev.kind) {
2305
+ case "asked":
2306
+ return { ...ev, question: mask(ev.question), ...(ev.options ? { options: ev.options.map(mask) } : {}) };
2307
+ case "message":
2308
+ case "peer":
2309
+ case "told":
2310
+ return { ...ev, text: mask(ev.text) };
2311
+ case "answered":
2312
+ return { ...ev, answer: mask(ev.answer) };
2313
+ default:
2314
+ return ev;
2315
+ }
2316
+ };
2296
2317
 
2297
2318
  // The reply, the conclusion and an `output: json` value land on the same
2298
2319
  // record the events do, and a model that quotes a script's stdout puts
@@ -2329,7 +2350,9 @@ async function runStepBody(
2329
2350
  let captureFull = false;
2330
2351
  const callsRoot = path.resolve(agentDir, "..", "..");
2331
2352
  const sink = runId ? callSink(step, { tenant, workspace: path.basename(callsRoot), runId, workspaceRoot: callsRoot }) : undefined;
2332
- const push = (type: StepRecord["events"][number]["type"], text: string, extra?: EventExtra) => {
2353
+ const push = (type: StepRecord["events"][number]["type"], text: string, given?: EventExtra) => {
2354
+ // A question or a message a model wrote is masked before it is stored or sent on.
2355
+ const extra: EventExtra | undefined = given?.operator ? { ...given, operator: maskOperator(given.operator) } : given;
2333
2356
  const t = new Date().toISOString();
2334
2357
  // The model has begun its first response: held only in memory, for
2335
2358
  // the fan-out gate (warmGate). Not a line in the trace.
@@ -2368,7 +2391,7 @@ async function runStepBody(
2368
2391
  rest = { ...others, captured: true };
2369
2392
  }
2370
2393
  }
2371
- step.events.push({ t, type, text: redact(text), ...rest });
2394
+ step.events.push({ t, type, text: mask(text), ...rest });
2372
2395
  // A person in the loop: the question, its answer, a message delivered —
2373
2396
  // onto the step, so the run page, the API and history show them.
2374
2397
  if (extra?.operator) {
@@ -2601,7 +2624,9 @@ async function runStepBody(
2601
2624
  const before: StepSupply = (step.credential ?? "").startsWith("provider:") ? "own" : "operator";
2602
2625
  for (const t of step.tries ?? []) t.supply ??= before;
2603
2626
  step.credential = onSupply
2604
- ? `foldrun models · ${SUPPLY_TITLES[supply.provider]}`
2627
+ ? supply.via === "login"
2628
+ ? "Claude subscription"
2629
+ : `foldrun models · ${SUPPLY_TITLES[supply.provider]}`
2605
2630
  : credential ? credential.label : noKey ? "none — this account has no model key" : `provider: ${providerLabel}`;
2606
2631
  step.supply = onSupply ? "foldrun" : primaryOnPlatform ? "operator" : "own";
2607
2632
  if (onSupply) step.supplyProvider = supply.provider;
@@ -0,0 +1,164 @@
1
+ /**
2
+ * Reading a file a sandbox, an agent or a customer's upload could have
3
+ * touched — without following a link it swapped in after we looked.
4
+ *
5
+ * The walkers (run outputs, copy-back, folder scan, import) list a tree with
6
+ * lstat, which is honest at that moment. The read comes later, by path, and a
7
+ * path is looked up again: a regular file replaced by a symlink to /proc/self/environ
8
+ * or another tenant's file in between was followed and its bytes stored or
9
+ * served; one replaced by a FIFO blocked the whole worker in a synchronous
10
+ * read. So the read opens with O_NOFOLLOW (a link at the last step is ELOOP)
11
+ * and O_NONBLOCK (a FIFO opens at once instead of waiting for a writer), asks
12
+ * the OPEN file what it is (fstat: a regular file, within the size cap, the
13
+ * same device and inode the walk saw, when it knows them) and reads from that
14
+ * descriptor, so what was checked is what is read.
15
+ *
16
+ * `root`: a directory ON THE WAY can also be swapped for a link (the open only
17
+ * refuses a link at the last step). With a root given, after the open the
18
+ * file's real path must be inside the real root and be the very inode that was
19
+ * opened. That narrows the window to an attacker who flips a directory link
20
+ * back and forth across two syscalls; it does not close it (Node has no
21
+ * openat2 / RESOLVE_NO_SYMLINKS). Callers that need no link anywhere on the way
22
+ * must keep the directory off the sandbox's reach, as the live archive does.
23
+ *
24
+ * Windows has no O_NOFOLLOW: there the check stays what it was (lstat, then
25
+ * open, then fstat) — no weaker than before, with the same small window.
26
+ */
27
+ import fs from "node:fs";
28
+ import path from "node:path";
29
+
30
+ const C = fs.constants;
31
+ // Missing on Windows: 0 there.
32
+ const NOFOLLOW = C.O_NOFOLLOW ?? 0;
33
+ const NONBLOCK = C.O_NONBLOCK ?? 0;
34
+ const NOCTTY = C.O_NOCTTY ?? 0;
35
+
36
+ export class UnsafeFileError extends Error {
37
+ readonly code = "EUNSAFEFILE";
38
+ constructor(file: string, why: string) {
39
+ super(`${path.basename(file)}: ${why}`);
40
+ }
41
+ }
42
+
43
+ export interface PlainOpts {
44
+ /** Refuse a file bigger than this (checked on the open file, not on a stat before). */
45
+ maxBytes?: number;
46
+ /** The inode the walk saw: a different one was swapped in since. */
47
+ dev?: number | bigint;
48
+ ino?: number | bigint;
49
+ /** A real (symlink-free) directory the file must really be inside. */
50
+ root?: string;
51
+ }
52
+
53
+ /** Open a regular file for reading without following a link at its last step
54
+ * or waiting on a FIFO. The caller closes `fd`. Throws UnsafeFileError. */
55
+ export function openPlain(file: string, opts: PlainOpts = {}): { fd: number; st: fs.Stats } {
56
+ if (!NOFOLLOW) {
57
+ // No O_NOFOLLOW here: look first, as every caller did before.
58
+ if (fs.lstatSync(file).isSymbolicLink()) throw new UnsafeFileError(file, "a symbolic link (refused, never followed)");
59
+ }
60
+ let fd: number;
61
+ try {
62
+ fd = fs.openSync(file, C.O_RDONLY | NOFOLLOW | NONBLOCK | NOCTTY);
63
+ } catch (err) {
64
+ const code = (err as NodeJS.ErrnoException).code;
65
+ if (code === "ELOOP") throw new UnsafeFileError(file, "a symbolic link (refused, never followed)");
66
+ if (code === "ENXIO") throw new UnsafeFileError(file, "not a regular file");
67
+ throw err;
68
+ }
69
+ try {
70
+ const st = fs.fstatSync(fd);
71
+ if (!st.isFile()) throw new UnsafeFileError(file, "not a regular file");
72
+ if (opts.ino !== undefined && (st.ino !== opts.ino || (opts.dev !== undefined && st.dev !== opts.dev))) {
73
+ throw new UnsafeFileError(file, "changed while it was being read (another file took its place)");
74
+ }
75
+ if (opts.maxBytes !== undefined && st.size > opts.maxBytes) throw new UnsafeFileError(file, `larger than ${opts.maxBytes} bytes`);
76
+ if (opts.root !== undefined) {
77
+ const real = fs.realpathSync(file);
78
+ const root = fs.realpathSync(opts.root);
79
+ if (!(real === root || real.startsWith(root + path.sep))) throw new UnsafeFileError(file, "leads out of its folder through a symbolic link");
80
+ const there = fs.lstatSync(real);
81
+ if (there.ino !== st.ino || there.dev !== st.dev) throw new UnsafeFileError(file, "changed while it was being read (another file took its place)");
82
+ }
83
+ return { fd, st };
84
+ } catch (err) {
85
+ fs.closeSync(fd);
86
+ throw err;
87
+ }
88
+ }
89
+
90
+ /** The whole file as bytes, from the checked descriptor. */
91
+ export function readPlain(file: string, opts: PlainOpts = {}): Buffer {
92
+ const { fd, st } = openPlain(file, opts);
93
+ try {
94
+ // Never trust the size past the cap: a file growing under the read stops there.
95
+ if (opts.maxBytes === undefined) return fs.readFileSync(fd);
96
+ const buf = Buffer.alloc(Math.min(st.size, opts.maxBytes) + 1);
97
+ let n = 0;
98
+ for (;;) {
99
+ const got = fs.readSync(fd, buf, n, buf.length - n, null);
100
+ if (!got) break;
101
+ n += got;
102
+ if (n >= buf.length) throw new UnsafeFileError(file, `larger than ${opts.maxBytes} bytes`);
103
+ }
104
+ return buf.subarray(0, n);
105
+ } finally {
106
+ fs.closeSync(fd);
107
+ }
108
+ }
109
+
110
+ export function readPlainText(file: string, opts: PlainOpts = {}): string {
111
+ return readPlain(file, opts).toString("utf8");
112
+ }
113
+
114
+ /** What the file is right now (size, device, inode), without following a link. */
115
+ export function statPlain(file: string, opts: PlainOpts = {}): fs.Stats {
116
+ const { fd, st } = openPlain(file, opts);
117
+ fs.closeSync(fd);
118
+ return st;
119
+ }
120
+
121
+ /** A read stream over the checked descriptor (a byte range is inclusive, as
122
+ * createReadStream's). The descriptor is closed with the stream. */
123
+ export function plainStream(
124
+ file: string,
125
+ opts: PlainOpts & { start?: number; end?: number; highWaterMark?: number; signal?: AbortSignal } = {},
126
+ ): fs.ReadStream {
127
+ const { fd } = openPlain(file, opts);
128
+ // O_NONBLOCK was for the open; a regular file reads the same either way.
129
+ return fs.createReadStream(file, { fd, start: opts.start, end: opts.end, highWaterMark: opts.highWaterMark, signal: opts.signal, autoClose: true });
130
+ }
131
+
132
+ /** The whole file as bytes, read off the event loop from the checked descriptor. */
133
+ export async function readPlainAsync(file: string, opts: PlainOpts = {}): Promise<Buffer> {
134
+ const { fd } = openPlain(file, opts);
135
+ try {
136
+ return await new Promise<Buffer>((resolve, reject) => fs.readFile(fd, (err, data) => (err ? reject(err) : resolve(data))));
137
+ } finally {
138
+ fs.closeSync(fd);
139
+ }
140
+ }
141
+
142
+ /** copyFileSync, but from a checked descriptor: a link or a pipe swapped in
143
+ * since the caller's lstat is refused, not followed or waited on. The copy
144
+ * keeps the file's permission bits and is streamed (1 MiB at a time). */
145
+ export function copyPlain(from: string, to: string, opts: PlainOpts = {}): void {
146
+ const { fd, st } = openPlain(from, opts);
147
+ try {
148
+ const out = fs.openSync(to, C.O_WRONLY | C.O_CREAT | C.O_TRUNC, st.mode & 0o777);
149
+ try {
150
+ const buf = Buffer.allocUnsafe(1 << 20);
151
+ for (;;) {
152
+ const n = fs.readSync(fd, buf, 0, buf.length, null);
153
+ if (!n) break;
154
+ let at = 0;
155
+ while (at < n) at += fs.writeSync(out, buf, at, n - at);
156
+ }
157
+ fs.fchmodSync(out, st.mode & 0o777);
158
+ } finally {
159
+ fs.closeSync(out);
160
+ }
161
+ } finally {
162
+ fs.closeSync(fd);
163
+ }
164
+ }
package/src/store.ts CHANGED
@@ -76,6 +76,7 @@ import { starterFiles, accountFiles, blankWorkspaceFiles } from "./starter.ts";
76
76
  import { trimSlashes, MAX_EDITABLE_FILE } from "./paths.ts";
77
77
  import type { RunContext, RunInput, ConversationRecord } from "./conversation.ts";
78
78
  import type { RunInputFile } from "./storage.ts";
79
+ import { copyPlain, readPlainText, UnsafeFileError } from "./safe-open.ts";
79
80
 
80
81
  // Where workspaces live. The hosted app keeps many under data/; the CLI runs
81
82
  // against one folder, which is what `foldrun run ./my-desk` has to mean.
@@ -471,7 +472,7 @@ export function saveWorkspace(
471
472
  if (fs.existsSync(dir)) {
472
473
  for (const rel of listWorkspaceFiles(tenant, workspace)) {
473
474
  try {
474
- before.set(rel, fs.readFileSync(path.join(dir, rel), "utf8"));
475
+ before.set(rel, readPlainText(path.join(dir, rel)));
475
476
  } catch {
476
477
  // vanished mid-read; not part of the revision
477
478
  }
@@ -497,7 +498,15 @@ export function saveWorkspace(
497
498
  }
498
499
  const to = path.join(snapshot, rel);
499
500
  fs.mkdirSync(path.dirname(to), { recursive: true });
500
- fs.copyFileSync(from, to);
501
+ try {
502
+ // From a descriptor opened without following a link: the lstat above
503
+ // can be out of date by now (SYMRACE), and a swapped-in link would copy
504
+ // its target into the snapshot, then back into the workspace.
505
+ copyPlain(from, to);
506
+ } catch (err) {
507
+ if (err instanceof UnsafeFileError || (err as NodeJS.ErrnoException).code === "ENOENT") continue;
508
+ throw err;
509
+ }
501
510
  preserved.push(rel);
502
511
  }
503
512
  }
@@ -2974,7 +2983,16 @@ export function readWorkspaceFile(tenant: string, workspace: string, rel: string
2974
2983
  const p = path.join(dir, assertEditablePath(rel));
2975
2984
  if (!fs.existsSync(p)) throw new Error(`file not found: ${rel}`);
2976
2985
  assertLandsInside(dir, p, rel);
2977
- return fs.readFileSync(p, "utf8");
2986
+ // The check above is by path. A link that stays inside the workspace is
2987
+ // allowed, so the read goes to where it really lands, opened without
2988
+ // following a link and found still inside the workspace: a file or folder
2989
+ // swapped for a link out since the check is refused (SYMRACE).
2990
+ try {
2991
+ return readPlainText(realLanding(p) ?? p, { root: dir });
2992
+ } catch (err) {
2993
+ if (err instanceof UnsafeFileError) throw new Error(`illegal path: ${rel} leads out of the workspace through a symlink`);
2994
+ throw err;
2995
+ }
2978
2996
  }
2979
2997
 
2980
2998
  /** Who made a change and why — recorded on its revision. */
@@ -3955,7 +3973,7 @@ export interface RefusedOutput {
3955
3973
  /** Relative to that agent's outputs/. */
3956
3974
  path: string;
3957
3975
  bytes: number;
3958
- reason: "file-cap" | "run-cap" | "name" | "count";
3976
+ reason: "file-cap" | "run-cap" | "name" | "count" | "unsafe";
3959
3977
  /** The cap in bytes that was exceeded (the count for "count"). */
3960
3978
  limit?: number;
3961
3979
  }
@@ -67,6 +67,7 @@ import { OpIdReused, type HeadIds, type Revision, type WorkspaceRef } from "./re
67
67
  import { pruneStateRevisions, type StateRetention } from "./state-retention.ts";
68
68
  import type { SweepMarks } from "./blob-sweeper.ts";
69
69
  import { setCallsBackend, dropWorkspaceCalls, settleCalls } from "./captured-calls.ts";
70
+ import { plainStream, readPlain, readPlainAsync, UnsafeFileError, type PlainOpts } from "./safe-open.ts";
70
71
  import { dropTenantOutputs, dropWorkspaceOutputs, moveWorkspaceOutputs, settleRunOutputs } from "./run-outputs.ts";
71
72
 
72
73
  // ------------------------------------------------------------- the backend
@@ -1094,15 +1095,31 @@ interface FolderFile {
1094
1095
  mode: number;
1095
1096
  }
1096
1097
 
1097
- async function hashOf(abs: string, size: number): Promise<string> {
1098
+ async function hashOf(abs: string, size: number, expect: PlainOpts = {}): Promise<string> {
1098
1099
  // Read off the event loop: a dashboard process runs this too, and a desk can
1099
- // hold thousands of files.
1100
- if (size <= LARGE_FILE) return sha256Hex(await fs.promises.readFile(abs));
1100
+ // hold thousands of files. From a descriptor opened without following a link,
1101
+ // on the inode the scan listed (a swap since is refused: safe-open.ts).
1102
+ if (size <= LARGE_FILE) return sha256Hex(await readPlainAsync(abs, expect));
1101
1103
  const h = crypto.createHash("sha256");
1102
- await pipeline(fs.createReadStream(abs), h);
1104
+ await pipeline(plainStream(abs, expect), h);
1103
1105
  return h.digest("hex");
1104
1106
  }
1105
1107
 
1108
+ /** What a file holds now: its sha, null when there is none. A link or a pipe
1109
+ * that took its place since the caller's link check reads as something that
1110
+ * matches nothing — "changed meanwhile", so the file is left alone — instead
1111
+ * of being followed or waited on (safe-open.ts). */
1112
+ const NOT_A_FILE = "!not-a-regular-file";
1113
+ function shaOnDisk(abs: string): string | null {
1114
+ try {
1115
+ return sha256Hex(readPlain(abs));
1116
+ } catch (err) {
1117
+ if ((err as NodeJS.ErrnoException).code === "ENOENT") return null;
1118
+ if (err instanceof UnsafeFileError) return NOT_A_FILE;
1119
+ throw err;
1120
+ }
1121
+ }
1122
+
1106
1123
  /**
1107
1124
  * The workspace's content as the folder holds it now: every regular file on
1108
1125
  * one of the two sides (manifest.ts sideOf), whatever its bytes — the rule
@@ -1169,7 +1186,7 @@ async function scanFolder(tenant: string, workspace: string): Promise<{ files: M
1169
1186
  try {
1170
1187
  assertManifestPath(f.rel);
1171
1188
  if (lower.has(fold)) throw new Error("differs only by case");
1172
- files.set(f.rel, { abs: f.abs, sha: await hashOf(f.abs, f.st.size), size: f.st.size, mode: f.st.mode & 0o111 ? MODE_EXEC : MODE_FILE });
1189
+ files.set(f.rel, { abs: f.abs, sha: await hashOf(f.abs, f.st.size, { dev: f.st.dev, ino: f.st.ino, root: dir }), size: f.st.size, mode: f.st.mode & 0o111 ? MODE_EXEC : MODE_FILE });
1173
1190
  lower.add(fold);
1174
1191
  } catch {
1175
1192
  left.add(f.rel);
@@ -1352,7 +1369,7 @@ async function commitEntry(deps: Deps, tenant: string, workspace: string, entry:
1352
1369
  changes: todo,
1353
1370
  restoredFrom: done.authored ? undefined : restoredFrom,
1354
1371
  bytesOf: async (sha) => {
1355
- const b = bytes.get(sha) ?? (onDisk.has(sha) ? fs.readFileSync(onDisk.get(sha)!) : null);
1372
+ const b = bytes.get(sha) ?? (onDisk.has(sha) ? readPlain(onDisk.get(sha)!) : null);
1356
1373
  if (!b) throw new Error(`the journal lost the bytes for ${sha.slice(0, 12)}…`);
1357
1374
  return b;
1358
1375
  },
@@ -1516,7 +1533,7 @@ async function afterPublish(deps: Deps, ws: WorkspaceRef, changes: Changes, r: P
1516
1533
  const abs = path.join(dir, p);
1517
1534
  // Never through a link, on any branch below (Codex review).
1518
1535
  if (throughLink(dir, p) || (fs.existsSync(abs) && fs.lstatSync(abs).isSymbolicLink())) continue;
1519
- const local = fs.existsSync(abs) ? sha256Hex(fs.readFileSync(abs)) : null;
1536
+ const local = shaOnDisk(abs);
1520
1537
  // Only while the file is still what this pod published (or gone, for a delete).
1521
1538
  if (c.op === "delete" ? local !== null : local !== c.sha) continue;
1522
1539
  if (winner) {
@@ -1525,7 +1542,7 @@ async function afterPublish(deps: Deps, ws: WorkspaceRef, changes: Changes, r: P
1525
1542
  // Again after the download: an edit made meanwhile is kept, and never
1526
1543
  // through a link — the file or a folder on its way (Codex review).
1527
1544
  if (throughLink(dir, p) || (fs.existsSync(abs) && fs.lstatSync(abs).isSymbolicLink())) continue;
1528
- if ((fs.existsSync(abs) ? sha256Hex(fs.readFileSync(abs)) : null) !== local) continue;
1545
+ if (shaOnDisk(abs) !== local) continue;
1529
1546
  fs.mkdirSync(path.dirname(abs), { recursive: true });
1530
1547
  // A new file renamed over the old one: replaces it, follows nothing.
1531
1548
  const tmp = `${abs}.${process.pid}.${crypto.randomBytes(4).toString("hex")}.mirror-tmp`;
@@ -1663,7 +1680,7 @@ async function syncNow(tenant: string, workspace: string): Promise<"unchanged" |
1663
1680
  next[p] = s;
1664
1681
  continue;
1665
1682
  }
1666
- if (fs.existsSync(f.abs) && (sha256Hex(fs.readFileSync(f.abs)) !== f.sha || modeOfFile(f.abs) !== f.mode)) {
1683
+ if (fs.existsSync(f.abs) && (shaOnDisk(f.abs) !== f.sha || modeOfFile(f.abs) !== f.mode)) {
1667
1684
  ownChanges = true;
1668
1685
  next[p] = s;
1669
1686
  continue;
@@ -1727,7 +1744,7 @@ async function syncNow(tenant: string, workspace: string): Promise<"unchanged" |
1727
1744
  // this very file while it ran (Codex review). The file must still be what
1728
1745
  // the scan saw, or it is this pod's change now and is left alone.
1729
1746
  if (busy()) return "skipped";
1730
- const nowSha = fs.existsSync(abs) ? sha256Hex(fs.readFileSync(abs)) : null;
1747
+ const nowSha = shaOnDisk(abs);
1731
1748
  if (nowSha !== (f?.sha ?? null) || (f && modeOfFile(abs) !== f.mode)) {
1732
1749
  ownChanges = true;
1733
1750
  if (synced[p]) next[p] = synced[p];