@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.
@@ -0,0 +1,160 @@
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
+ const C = fs.constants;
30
+ // Missing on Windows: 0 there.
31
+ const NOFOLLOW = C.O_NOFOLLOW ?? 0;
32
+ const NONBLOCK = C.O_NONBLOCK ?? 0;
33
+ const NOCTTY = C.O_NOCTTY ?? 0;
34
+ export class UnsafeFileError extends Error {
35
+ code = "EUNSAFEFILE";
36
+ constructor(file, why) {
37
+ super(`${path.basename(file)}: ${why}`);
38
+ }
39
+ }
40
+ /** Open a regular file for reading without following a link at its last step
41
+ * or waiting on a FIFO. The caller closes `fd`. Throws UnsafeFileError. */
42
+ export function openPlain(file, opts = {}) {
43
+ if (!NOFOLLOW) {
44
+ // No O_NOFOLLOW here: look first, as every caller did before.
45
+ if (fs.lstatSync(file).isSymbolicLink())
46
+ throw new UnsafeFileError(file, "a symbolic link (refused, never followed)");
47
+ }
48
+ let fd;
49
+ try {
50
+ fd = fs.openSync(file, C.O_RDONLY | NOFOLLOW | NONBLOCK | NOCTTY);
51
+ }
52
+ catch (err) {
53
+ const code = err.code;
54
+ if (code === "ELOOP")
55
+ throw new UnsafeFileError(file, "a symbolic link (refused, never followed)");
56
+ if (code === "ENXIO")
57
+ throw new UnsafeFileError(file, "not a regular file");
58
+ throw err;
59
+ }
60
+ try {
61
+ const st = fs.fstatSync(fd);
62
+ if (!st.isFile())
63
+ throw new UnsafeFileError(file, "not a regular file");
64
+ if (opts.ino !== undefined && (st.ino !== opts.ino || (opts.dev !== undefined && st.dev !== opts.dev))) {
65
+ throw new UnsafeFileError(file, "changed while it was being read (another file took its place)");
66
+ }
67
+ if (opts.maxBytes !== undefined && st.size > opts.maxBytes)
68
+ throw new UnsafeFileError(file, `larger than ${opts.maxBytes} bytes`);
69
+ if (opts.root !== undefined) {
70
+ const real = fs.realpathSync(file);
71
+ const root = fs.realpathSync(opts.root);
72
+ if (!(real === root || real.startsWith(root + path.sep)))
73
+ throw new UnsafeFileError(file, "leads out of its folder through a symbolic link");
74
+ const there = fs.lstatSync(real);
75
+ if (there.ino !== st.ino || there.dev !== st.dev)
76
+ throw new UnsafeFileError(file, "changed while it was being read (another file took its place)");
77
+ }
78
+ return { fd, st };
79
+ }
80
+ catch (err) {
81
+ fs.closeSync(fd);
82
+ throw err;
83
+ }
84
+ }
85
+ /** The whole file as bytes, from the checked descriptor. */
86
+ export function readPlain(file, opts = {}) {
87
+ const { fd, st } = openPlain(file, opts);
88
+ try {
89
+ // Never trust the size past the cap: a file growing under the read stops there.
90
+ if (opts.maxBytes === undefined)
91
+ return fs.readFileSync(fd);
92
+ const buf = Buffer.alloc(Math.min(st.size, opts.maxBytes) + 1);
93
+ let n = 0;
94
+ for (;;) {
95
+ const got = fs.readSync(fd, buf, n, buf.length - n, null);
96
+ if (!got)
97
+ break;
98
+ n += got;
99
+ if (n >= buf.length)
100
+ throw new UnsafeFileError(file, `larger than ${opts.maxBytes} bytes`);
101
+ }
102
+ return buf.subarray(0, n);
103
+ }
104
+ finally {
105
+ fs.closeSync(fd);
106
+ }
107
+ }
108
+ export function readPlainText(file, opts = {}) {
109
+ return readPlain(file, opts).toString("utf8");
110
+ }
111
+ /** What the file is right now (size, device, inode), without following a link. */
112
+ export function statPlain(file, opts = {}) {
113
+ const { fd, st } = openPlain(file, opts);
114
+ fs.closeSync(fd);
115
+ return st;
116
+ }
117
+ /** A read stream over the checked descriptor (a byte range is inclusive, as
118
+ * createReadStream's). The descriptor is closed with the stream. */
119
+ export function plainStream(file, opts = {}) {
120
+ const { fd } = openPlain(file, opts);
121
+ // O_NONBLOCK was for the open; a regular file reads the same either way.
122
+ return fs.createReadStream(file, { fd, start: opts.start, end: opts.end, highWaterMark: opts.highWaterMark, signal: opts.signal, autoClose: true });
123
+ }
124
+ /** The whole file as bytes, read off the event loop from the checked descriptor. */
125
+ export async function readPlainAsync(file, opts = {}) {
126
+ const { fd } = openPlain(file, opts);
127
+ try {
128
+ return await new Promise((resolve, reject) => fs.readFile(fd, (err, data) => (err ? reject(err) : resolve(data))));
129
+ }
130
+ finally {
131
+ fs.closeSync(fd);
132
+ }
133
+ }
134
+ /** copyFileSync, but from a checked descriptor: a link or a pipe swapped in
135
+ * since the caller's lstat is refused, not followed or waited on. The copy
136
+ * keeps the file's permission bits and is streamed (1 MiB at a time). */
137
+ export function copyPlain(from, to, opts = {}) {
138
+ const { fd, st } = openPlain(from, opts);
139
+ try {
140
+ const out = fs.openSync(to, C.O_WRONLY | C.O_CREAT | C.O_TRUNC, st.mode & 0o777);
141
+ try {
142
+ const buf = Buffer.allocUnsafe(1 << 20);
143
+ for (;;) {
144
+ const n = fs.readSync(fd, buf, 0, buf.length, null);
145
+ if (!n)
146
+ break;
147
+ let at = 0;
148
+ while (at < n)
149
+ at += fs.writeSync(out, buf, at, n - at);
150
+ }
151
+ fs.fchmodSync(out, st.mode & 0o777);
152
+ }
153
+ finally {
154
+ fs.closeSync(out);
155
+ }
156
+ }
157
+ finally {
158
+ fs.closeSync(fd);
159
+ }
160
+ }
@@ -1545,7 +1545,7 @@ export interface RefusedOutput {
1545
1545
  /** Relative to that agent's outputs/. */
1546
1546
  path: string;
1547
1547
  bytes: number;
1548
- reason: "file-cap" | "run-cap" | "name" | "count";
1548
+ reason: "file-cap" | "run-cap" | "name" | "count" | "unsafe";
1549
1549
  /** The cap in bytes that was exceeded (the count for "count"). */
1550
1550
  limit?: number;
1551
1551
  }
package/dist/src/store.js CHANGED
@@ -67,6 +67,7 @@ import { readTransport, KINDS } from "./kinds.js";
67
67
  import { providerPreset, looksOpenAiShaped, PROTECTED_PARAMS } from "./providers.js";
68
68
  import { starterFiles, accountFiles, blankWorkspaceFiles } from "./starter.js";
69
69
  import { trimSlashes, MAX_EDITABLE_FILE } from "./paths.js";
70
+ import { copyPlain, readPlainText, UnsafeFileError } from "./safe-open.js";
70
71
  // Where workspaces live. The hosted app keeps many under data/; the CLI runs
71
72
  // against one folder, which is what `foldrun run ./my-desk` has to mean.
72
73
  /**
@@ -424,7 +425,7 @@ meta = {}) {
424
425
  if (fs.existsSync(dir)) {
425
426
  for (const rel of listWorkspaceFiles(tenant, workspace)) {
426
427
  try {
427
- before.set(rel, fs.readFileSync(path.join(dir, rel), "utf8"));
428
+ before.set(rel, readPlainText(path.join(dir, rel)));
428
429
  }
429
430
  catch {
430
431
  // vanished mid-read; not part of the revision
@@ -451,7 +452,17 @@ meta = {}) {
451
452
  }
452
453
  const to = path.join(snapshot, rel);
453
454
  fs.mkdirSync(path.dirname(to), { recursive: true });
454
- fs.copyFileSync(from, to);
455
+ try {
456
+ // From a descriptor opened without following a link: the lstat above
457
+ // can be out of date by now (SYMRACE), and a swapped-in link would copy
458
+ // its target into the snapshot, then back into the workspace.
459
+ copyPlain(from, to);
460
+ }
461
+ catch (err) {
462
+ if (err instanceof UnsafeFileError || err.code === "ENOENT")
463
+ continue;
464
+ throw err;
465
+ }
455
466
  preserved.push(rel);
456
467
  }
457
468
  }
@@ -2480,7 +2491,18 @@ export function readWorkspaceFile(tenant, workspace, rel) {
2480
2491
  if (!fs.existsSync(p))
2481
2492
  throw new Error(`file not found: ${rel}`);
2482
2493
  assertLandsInside(dir, p, rel);
2483
- return fs.readFileSync(p, "utf8");
2494
+ // The check above is by path. A link that stays inside the workspace is
2495
+ // allowed, so the read goes to where it really lands, opened without
2496
+ // following a link and found still inside the workspace: a file or folder
2497
+ // swapped for a link out since the check is refused (SYMRACE).
2498
+ try {
2499
+ return readPlainText(realLanding(p) ?? p, { root: dir });
2500
+ }
2501
+ catch (err) {
2502
+ if (err instanceof UnsafeFileError)
2503
+ throw new Error(`illegal path: ${rel} leads out of the workspace through a symlink`);
2504
+ throw err;
2505
+ }
2484
2506
  }
2485
2507
  export function writeWorkspaceFile(tenant, workspace, rel, content, meta = {}) {
2486
2508
  // 512 KB: a folder tool's program is one file, and the gallery browser's is
@@ -48,6 +48,7 @@ import { headsOf, loadManifest, manifestsAt, manifestsOf, publish, restore, requ
48
48
  import { OpIdReused } from "./revision-store.js";
49
49
  import { pruneStateRevisions } from "./state-retention.js";
50
50
  import { setCallsBackend, dropWorkspaceCalls, settleCalls } from "./captured-calls.js";
51
+ import { plainStream, readPlain, readPlainAsync, UnsafeFileError } from "./safe-open.js";
51
52
  import { dropTenantOutputs, dropWorkspaceOutputs, moveWorkspaceOutputs, settleRunOutputs } from "./run-outputs.js";
52
53
  // ------------------------------------------------------------- the backend
53
54
  /** Everything this module is told at boot, and every queue that goes with it,
@@ -1002,15 +1003,33 @@ export async function reconcileAll(opts = {}) {
1002
1003
  /** A file this big is sent to the store from disk, never read whole. */
1003
1004
  const LARGE_FILE = 8 * 1024 * 1024;
1004
1005
  const LARGE_PIN_TTL_MS = 30 * 60_000;
1005
- async function hashOf(abs, size) {
1006
+ async function hashOf(abs, size, expect = {}) {
1006
1007
  // Read off the event loop: a dashboard process runs this too, and a desk can
1007
- // hold thousands of files.
1008
+ // hold thousands of files. From a descriptor opened without following a link,
1009
+ // on the inode the scan listed (a swap since is refused: safe-open.ts).
1008
1010
  if (size <= LARGE_FILE)
1009
- return sha256Hex(await fs.promises.readFile(abs));
1011
+ return sha256Hex(await readPlainAsync(abs, expect));
1010
1012
  const h = crypto.createHash("sha256");
1011
- await pipeline(fs.createReadStream(abs), h);
1013
+ await pipeline(plainStream(abs, expect), h);
1012
1014
  return h.digest("hex");
1013
1015
  }
1016
+ /** What a file holds now: its sha, null when there is none. A link or a pipe
1017
+ * that took its place since the caller's link check reads as something that
1018
+ * matches nothing — "changed meanwhile", so the file is left alone — instead
1019
+ * of being followed or waited on (safe-open.ts). */
1020
+ const NOT_A_FILE = "!not-a-regular-file";
1021
+ function shaOnDisk(abs) {
1022
+ try {
1023
+ return sha256Hex(readPlain(abs));
1024
+ }
1025
+ catch (err) {
1026
+ if (err.code === "ENOENT")
1027
+ return null;
1028
+ if (err instanceof UnsafeFileError)
1029
+ return NOT_A_FILE;
1030
+ throw err;
1031
+ }
1032
+ }
1014
1033
  /**
1015
1034
  * The workspace's content as the folder holds it now: every regular file on
1016
1035
  * one of the two sides (manifest.ts sideOf), whatever its bytes — the rule
@@ -1092,7 +1111,7 @@ async function scanFolder(tenant, workspace) {
1092
1111
  assertManifestPath(f.rel);
1093
1112
  if (lower.has(fold))
1094
1113
  throw new Error("differs only by case");
1095
- 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 });
1114
+ 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 });
1096
1115
  lower.add(fold);
1097
1116
  }
1098
1117
  catch {
@@ -1286,7 +1305,7 @@ async function commitEntry(deps, tenant, workspace, entry) {
1286
1305
  changes: todo,
1287
1306
  restoredFrom: done.authored ? undefined : restoredFrom,
1288
1307
  bytesOf: async (sha) => {
1289
- const b = bytes.get(sha) ?? (onDisk.has(sha) ? fs.readFileSync(onDisk.get(sha)) : null);
1308
+ const b = bytes.get(sha) ?? (onDisk.has(sha) ? readPlain(onDisk.get(sha)) : null);
1290
1309
  if (!b)
1291
1310
  throw new Error(`the journal lost the bytes for ${sha.slice(0, 12)}…`);
1292
1311
  return b;
@@ -1467,7 +1486,7 @@ async function afterPublish(deps, ws, changes, r) {
1467
1486
  // Never through a link, on any branch below (Codex review).
1468
1487
  if (throughLink(dir, p) || (fs.existsSync(abs) && fs.lstatSync(abs).isSymbolicLink()))
1469
1488
  continue;
1470
- const local = fs.existsSync(abs) ? sha256Hex(fs.readFileSync(abs)) : null;
1489
+ const local = shaOnDisk(abs);
1471
1490
  // Only while the file is still what this pod published (or gone, for a delete).
1472
1491
  if (c.op === "delete" ? local !== null : local !== c.sha)
1473
1492
  continue;
@@ -1479,7 +1498,7 @@ async function afterPublish(deps, ws, changes, r) {
1479
1498
  // through a link — the file or a folder on its way (Codex review).
1480
1499
  if (throughLink(dir, p) || (fs.existsSync(abs) && fs.lstatSync(abs).isSymbolicLink()))
1481
1500
  continue;
1482
- if ((fs.existsSync(abs) ? sha256Hex(fs.readFileSync(abs)) : null) !== local)
1501
+ if (shaOnDisk(abs) !== local)
1483
1502
  continue;
1484
1503
  fs.mkdirSync(path.dirname(abs), { recursive: true });
1485
1504
  // A new file renamed over the old one: replaces it, follows nothing.
@@ -1634,7 +1653,7 @@ async function syncNow(tenant, workspace) {
1634
1653
  next[p] = s;
1635
1654
  continue;
1636
1655
  }
1637
- if (fs.existsSync(f.abs) && (sha256Hex(fs.readFileSync(f.abs)) !== f.sha || modeOfFile(f.abs) !== f.mode)) {
1656
+ if (fs.existsSync(f.abs) && (shaOnDisk(f.abs) !== f.sha || modeOfFile(f.abs) !== f.mode)) {
1638
1657
  ownChanges = true;
1639
1658
  next[p] = s;
1640
1659
  continue;
@@ -1707,7 +1726,7 @@ async function syncNow(tenant, workspace) {
1707
1726
  // the scan saw, or it is this pod's change now and is left alone.
1708
1727
  if (busy())
1709
1728
  return "skipped";
1710
- const nowSha = fs.existsSync(abs) ? sha256Hex(fs.readFileSync(abs)) : null;
1729
+ const nowSha = shaOnDisk(abs);
1711
1730
  if (nowSha !== (f?.sha ?? null) || (f && modeOfFile(abs) !== f.mode)) {
1712
1731
  ownChanges = true;
1713
1732
  if (synced[p])
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@foldrun/core",
3
- "version": "23.4.0",
3
+ "version": "24.1.0",
4
4
  "description": "Agents are just folders. The format, the runner, the checks.",
5
5
  "license": "FSL-1.1-ALv2",
6
6
  "type": "module",
package/src/blob-types.ts CHANGED
@@ -5,6 +5,7 @@
5
5
 
6
6
  import fs from "node:fs";
7
7
  import crypto from "node:crypto";
8
+ import { plainStream, statPlain, UnsafeFileError, type PlainOpts } from "./safe-open.ts";
8
9
 
9
10
  export class BlobNotFound extends Error {
10
11
  readonly key: string;
@@ -185,15 +186,25 @@ export function bufferSource(buf: Uint8Array): BlobSource {
185
186
 
186
187
  /** A file on disk. The size is taken now; if the file is shorter (or longer)
187
188
  * when it is read, the read throws BlobSourceError rather than send a body
188
- * that no longer matches what was announced. */
189
- export function fileSource(filePath: string): BlobSource {
190
- const size = fs.statSync(filePath).size;
189
+ * that no longer matches what was announced. A link is never followed, and a
190
+ * different file (or a FIFO) swapped in since the size was taken is refused:
191
+ * each read opens the path without following links and must find the same
192
+ * inode (safe-open.ts, SYMRACE). */
193
+ export function fileSource(filePath: string, expect: PlainOpts = {}): BlobSource {
194
+ const seen = statPlain(filePath, expect);
195
+ const size = seen.size;
191
196
  return {
192
197
  size,
193
198
  async *read(start, end, signal) {
194
199
  const hi = Math.min(end, size);
195
200
  if (hi <= start) return;
196
- const stream = fs.createReadStream(filePath, { start, end: hi - 1, highWaterMark: 1 << 20, signal });
201
+ let stream: fs.ReadStream;
202
+ try {
203
+ stream = plainStream(filePath, { start, end: hi - 1, highWaterMark: 1 << 20, signal, dev: seen.dev, ino: seen.ino, root: expect.root });
204
+ } catch (err) {
205
+ if (err instanceof UnsafeFileError) throw new BlobSourceError(`${filePath} changed while it was being uploaded: ${err.message}`);
206
+ throw err;
207
+ }
197
208
  let got = 0;
198
209
  for await (const chunk of stream) {
199
210
  got += (chunk as Buffer).length;
package/src/capture.ts CHANGED
@@ -175,9 +175,19 @@ export function scrubWith(redactions: [string, string][], text: string): string
175
175
  // masked to the end of the text.
176
176
  const PRIVATE_KEY = /-----BEGIN [A-Z0-9 ]*PRIVATE KEY-----[\s\S]*?(?:-----END [A-Z0-9 ]*PRIVATE KEY-----|$(?![\s\S]))/g;
177
177
 
178
+ /** What no vault value covers: a credential-shaped string (a GitHub, Anthropic
179
+ * or AWS key, a JWT, `token=…`, a bearer) and a private key's whole block.
180
+ * Applied after the step's own value masks, to every piece of stored text that
181
+ * came out of a sandbox or a model — a tool's output, a prompt, stderr — so a
182
+ * key a tool read off disk is not kept just because it was never a secret
183
+ * of ours. Ordinary text (ids, URLs, paths, hashes) is left as it was. */
184
+ export function maskPatterns(text: string): string {
185
+ return redactText(text).replace(PRIVATE_KEY, "[redacted:private key]");
186
+ }
187
+
178
188
  /** Masked, then cut to the cap. */
179
189
  export function maskCall(text: string, redactSecrets: (text: string) => string): { text: string; cut: boolean } {
180
- const masked = redactText(redactSecrets(text)).replace(PRIVATE_KEY, "[redacted:private key]");
190
+ const masked = maskPatterns(redactSecrets(text));
181
191
  return masked.length > CAPTURE_CAP ? { text: masked.slice(0, CAPTURE_CAP), cut: true } : { text: masked, cut: false };
182
192
  }
183
193
 
@@ -68,6 +68,7 @@ import {
68
68
  } from "./manifest.ts";
69
69
  import { headsOf, manifestsAt, publish, requestDigest, type Deps } from "./publish.ts";
70
70
  import { BlobNotFound, BlobSourceError, downloadToFile, fileSource } from "./blob-store.ts";
71
+ import { plainStream, readPlain, type PlainOpts } from "./safe-open.ts";
71
72
  import type { Revision, WorkspaceRef } from "./revision-store.ts";
72
73
  import { isPlatformPath } from "./store.ts";
73
74
 
@@ -135,9 +136,11 @@ export interface ScanOptions {
135
136
  workspaces?: string[];
136
137
  }
137
138
 
138
- export async function hashFile(abs: string): Promise<string> {
139
+ export async function hashFile(abs: string, expect: PlainOpts = {}): Promise<string> {
139
140
  const h = crypto.createHash("sha256");
140
- await pipeline(fs.createReadStream(abs), h);
141
+ // Never through a link, never waiting on a pipe, and (with `st`) the file the
142
+ // scan listed: the scan's lstat said "regular file" earlier (safe-open.ts).
143
+ await pipeline(plainStream(abs, expect), h);
141
144
  return h.digest("hex");
142
145
  }
143
146
 
@@ -313,7 +316,7 @@ async function scanWorkspace(tenant: string, workspace: string, dir: string): Pr
313
316
  if (from) ws.conflicts.push({ path: from, keptAs: rel });
314
317
  let sha: string;
315
318
  try {
316
- sha = await hashFile(f.abs);
319
+ sha = await hashFile(f.abs, { dev: f.st.dev, ino: f.st.ino, root: dir });
317
320
  } catch (err) {
318
321
  ws.unmapped.push({ path: f.rel, reason: `unreadable (${(err as NodeJS.ErrnoException).code ?? "error"})`, files: 1, bytes: f.st.size });
319
322
  continue;
@@ -508,7 +511,7 @@ export async function importWorkspace(scan: WorkspaceScan, opts: ImportOptions):
508
511
  bytesOf: async (sha) => {
509
512
  const f = bySha.get(sha);
510
513
  if (!f) throw new Error(`no source file for ${sha.slice(0, 12)}…`);
511
- const b = fs.readFileSync(f.abs);
514
+ const b = readPlain(f.abs);
512
515
  if (sha256Hex(b) !== sha) throw new Error(`${f.path} changed while it was being imported`);
513
516
  return b;
514
517
  },
package/src/egress.ts CHANGED
@@ -43,7 +43,7 @@
43
43
  // platform's (it needs a long-lived process and a Service); the pod side is
44
44
  // here in core, because it is what the runner image runs.
45
45
 
46
- import { supplyProviderOfToken } from "./model-supply.ts";
46
+ import { supplyProviderOfToken, supplyViaOfToken } from "./model-supply.ts";
47
47
  import type { DelegationResult, PeerInfo } from "./operator.ts";
48
48
  import { trimSlashes } from "./paths.ts";
49
49
  import type { TestEffect } from "./test-mode.ts";
@@ -275,7 +275,7 @@ export function proxyModelEnv(
275
275
  * the call), else the value itself. */
276
276
  export function grantModelKey(grant: EgressGrant, name: string, value: string, host: string): void {
277
277
  const supply = supplyProviderOfToken(value);
278
- if (supply) addSupplyGrant(grant, name, supply, host);
278
+ if (supply) addSupplyGrant(grant, name, supply, host, supplyViaOfToken(value) ?? undefined);
279
279
  else addGrant(grant, name, value, host);
280
280
  }
281
281
 
@@ -302,19 +302,25 @@ export function unsubstitute(text: string, knownSecrets: Record<string, string>,
302
302
  * not from what the step reports. */
303
303
  export interface SupplyGrant {
304
304
  provider: string;
305
+ /** "login": the account's Claude subscription — the proxy sends the call
306
+ * on one of the platform's Claude logins (the gateway's login path),
307
+ * after checking the account still holds a plan; nothing is metered on
308
+ * an API key. Absent: the platform's API key for `provider`, metered. */
309
+ via?: "login";
305
310
  }
306
311
 
307
312
  /** Grant the platform's key for `provider` under `name`, to its host. */
308
- export function addSupplyGrant(grant: EgressGrant, name: string, provider: string, host: string): void {
313
+ export function addSupplyGrant(grant: EgressGrant, name: string, provider: string, host: string, via?: "login"): void {
309
314
  const h = host.toLowerCase();
310
315
  const existing = grant.secrets[name];
311
316
  // A name already granted as an ordinary secret is never turned into the
312
317
  // platform's key, nor the other way round: two meanings under one name
313
- // is how a value would be filled where it was not meant to be.
314
- if (existing && existing.supply?.provider !== provider) throw new Error(`egress: ${name} is already granted as another credential`);
318
+ // is how a value would be filled where it was not meant to be. Nor is a
319
+ // subscription grant the API key's, or the other way round.
320
+ if (existing && (existing.supply?.provider !== provider || existing.supply?.via !== via)) throw new Error(`egress: ${name} is already granted as another credential`);
315
321
  if (existing) {
316
322
  if (!existing.hosts.includes(h)) existing.hosts.push(h);
317
- } else grant.secrets[name] = { value: "", hosts: [h], supply: { provider } };
323
+ } else grant.secrets[name] = { value: "", hosts: [h], supply: { provider, ...(via ? { via } : {}) } };
318
324
  }
319
325
 
320
326
  export function addGrant(grant: EgressGrant, name: string, value: string, host: string): void {
package/src/model-env.ts CHANGED
@@ -59,7 +59,7 @@ export function accountModelEnv(
59
59
  const supply: SupplyAnswer = written ? { kind: "none" } : platform.modelSupply?.(tenant) ?? { kind: "none" };
60
60
  if (supply.kind === "refused") throw new ModelKeyError(`foldrun's models: ${supply.reason}`, 403);
61
61
  if (supply.kind === "foldrun") {
62
- const s = parseProvider(supplyProviderBlock(supply.provider, supply.tiers))!;
62
+ const s = parseProvider(supplyProviderBlock(supply.provider, supply.tiers, supply.via))!;
63
63
  const preset = providerPreset(s.name);
64
64
  return {
65
65
  env: providerEnvFor({ baseUrl: s.baseUrl!, token: s.token, auth: s.auth, models: s.models, headers: {} }),
@@ -240,7 +240,11 @@ export const SUPPLY_KEY_NAME = "FOLDRUN_SUPPLY_KEY";
240
240
  * What the platform says about one account's model supply, before any
241
241
  * provider: block of its own is considered (a written block always wins):
242
242
  * none — it did not choose foldrun's models: its own key, as before
243
- * foldrun — it chose them and they are on: run on the platform's key
243
+ * foldrun — it chose them and they are on: run on the platform's key;
244
+ * with `via: "login"`, on the account's Claude subscription
245
+ * instead (16 Nov 2026: an account holding a Claude Code plan
246
+ * runs its routines and sessions on Claude, counted in the
247
+ * plan's monthly and weekly windows like its Claude Code calls)
244
248
  * refused — it chose them and they cannot be had now (switched off, the
245
249
  * provider withdrawn, the account refused). The step FAILS
246
250
  * with the reason: never quietly onto the account's stored
@@ -255,6 +259,11 @@ export type SupplyAnswer =
255
259
  /** The price list's output ceiling per model id: the most one reply
256
260
  * may be on the platform's key, told to the runtime up front. */
257
261
  ceilings?: Record<string, number>;
262
+ /** "login": the calls go on the platform's Claude logins, as the
263
+ * account's subscription — the proxy sends them through the gateway's
264
+ * login path (pool, windows, extra usage), not metered on an API key.
265
+ * Anthropic only. Absent: the platform's API key, metered. */
266
+ via?: "login";
258
267
  }
259
268
  | { kind: "refused"; reason: string };
260
269
 
@@ -263,17 +272,28 @@ export type SupplyAnswer =
263
272
  * which the proxy fills with the platform's key. Sent anywhere unproxied
264
273
  * it is only a word a provider refuses. */
265
274
  const MARKER = "foldrun-supply:";
266
- export const supplyToken = (provider: SupplyProviderName) => `${MARKER}${provider}`;
275
+ /** `+login` after the provider: the subscription's marker (SupplyAnswer.via). */
276
+ const VIA_LOGIN = "+login";
277
+ export const supplyToken = (provider: SupplyProviderName, via?: "login") => `${MARKER}${provider}${via === "login" ? VIA_LOGIN : ""}`;
267
278
  export function supplyProviderOfToken(value: string | null | undefined): SupplyProviderName | null {
268
279
  if (typeof value !== "string" || !value.startsWith(MARKER)) return null;
269
- const p = value.slice(MARKER.length);
280
+ let p = value.slice(MARKER.length);
281
+ if (p.endsWith(VIA_LOGIN)) {
282
+ p = p.slice(0, -VIA_LOGIN.length);
283
+ // A subscription is Claude's alone.
284
+ if (p !== "anthropic") return null;
285
+ }
270
286
  return isSupplyProvider(p) ? p : null;
271
287
  }
288
+ /** "login" when the marker is the subscription's, else null. */
289
+ export function supplyViaOfToken(value: string | null | undefined): "login" | null {
290
+ return supplyProviderOfToken(value) !== null && String(value).endsWith(VIA_LOGIN) ? "login" : null;
291
+ }
272
292
 
273
293
  /** The provider block a step on foldrun's models runs with: the preset's
274
294
  * endpoint and format, the operator's tier map, and the key as a
275
295
  * placeholder only. */
276
- export function supplyProviderBlock(provider: SupplyProviderName, tiers: Partial<Record<"fast" | "default" | "max", string>>): Record<string, unknown> {
296
+ export function supplyProviderBlock(provider: SupplyProviderName, tiers: Partial<Record<"fast" | "default" | "max", string>>, via?: "login"): Record<string, unknown> {
277
297
  const p = SUPPLY_PROVIDERS[provider];
278
298
  const preset = p.preset ? providerPreset(p.preset) : undefined;
279
299
  const baseUrl = p.baseUrl ?? preset?.baseUrl;
@@ -285,7 +305,7 @@ export function supplyProviderBlock(provider: SupplyProviderName, tiers: Partial
285
305
  base_url: baseUrl,
286
306
  format: p.format,
287
307
  auth: p.auth,
288
- token: supplyToken(provider),
308
+ token: supplyToken(provider, via),
289
309
  ...(Object.keys(tiers).length ? { models: tiers } : {}),
290
310
  };
291
311
  }
@@ -51,6 +51,7 @@ import { putStepState, getStepState, dropStepState } from "./step-state.ts";
51
51
  import { stageRunInputs, type RunInputFile } from "./storage.ts";
52
52
  import { INPUTS_DIR, stagedLine } from "./run-inputs.ts";
53
53
  import { textBesideInputs } from "./input-text.ts";
54
+ import { readPlain, readPlainText, UnsafeFileError } from "./safe-open.ts";
54
55
 
55
56
  /** What crosses the boundary. Everything in here is values — pre-resolved
56
57
  * secrets in headers, assembled prompt, serializable MCP configs. */
@@ -555,8 +556,8 @@ export function applyContainerChanges(
555
556
  // the same rule as every file below.
556
557
  const dir = path.join(containerWs, ".foldrun");
557
558
  const file = path.join(dir, "copied-back.json");
558
- if (fs.lstatSync(dir).isDirectory() && fs.lstatSync(file).isFile()) {
559
- const m = JSON.parse(fs.readFileSync(file, "utf8"));
559
+ if (fs.lstatSync(dir).isDirectory()) {
560
+ const m = JSON.parse(readPlainText(file, { root: containerWs, maxBytes: 16 * 1024 * 1024 }));
560
561
  if (m && typeof m === "object" && !Array.isArray(m)) {
561
562
  for (const [rel, h] of Object.entries(m as Record<string, unknown>)) {
562
563
  // Every version the host handed back for the path counts: two jobs
@@ -592,7 +593,19 @@ export function applyContainerChanges(
592
593
  if (opts.drop && (posix.startsWith(opts.drop) || `${posix}/` === opts.drop)) continue;
593
594
  if (opts.keepOnly && !posix.startsWith(opts.keepOnly)) continue;
594
595
  if (!allowedBack(rel)) continue;
595
- let next: Buffer = fs.readFileSync(abs);
596
+ // Read from a descriptor opened without following a link, inside the
597
+ // sandbox's folder: the walk's readdir said "regular file" a moment ago,
598
+ // and the step may have swapped it for a link to the host's
599
+ // /proc/self/environ, or a FIFO that would block this read forever
600
+ // (SYMRACE). Such a path is skipped and said, like any other refusal.
601
+ let next: Buffer;
602
+ try {
603
+ next = readPlain(abs, { root: containerWs });
604
+ } catch (err) {
605
+ if (!(err instanceof UnsafeFileError)) throw err;
606
+ note?.(`${posix} was not copied back: ${err.message}`);
607
+ continue;
608
+ }
596
609
  // What the step was handed: its bytes (a staging dir) or its hash.
597
610
  // null when the file did not exist then; undefined when no baseline.
598
611
  let was: Buffer | string | null | undefined;
@@ -13,6 +13,8 @@ export function refusalText(r: RefusedOutput): string {
13
13
  return `${r.agent}/${r.path} (${mib(r.bytes)}) was not kept: this run's outputs may total at most ${mib(r.limit ?? 0)}`;
14
14
  case "count":
15
15
  return `${r.agent}/${r.path} was not kept: a run keeps at most ${r.limit ?? 50_000} files per agent`;
16
+ case "unsafe":
17
+ return `${r.agent}/${r.path} was not kept: it was replaced by a link or a pipe while the run ended, so it was not read`;
16
18
  default:
17
19
  return `${r.agent}/${r.path} was not kept: its name cannot be stored (control characters, over 400 bytes, or differs from another file only by case)`;
18
20
  }