podster 0.0.1-test.8 → 0.0.1-test.9

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.
package/README.md CHANGED
@@ -54,7 +54,7 @@ Running tasks needs plain paths: letters, digits, `.`, `_`, `-` and `/` only. If
54
54
  Runner's log is one JSON line per event, with IDs and a code, on standard error. Under each failure, refusal or stop it adds a line in plain English: what happened, what to do, the code, and where the details are. For example:
55
55
 
56
56
  ```text
57
- why: The room's policy lists network hosts, which Runner can't enforce yet. Set rooms[].network to [] in policy.json, then start Runner again. (code network_allowlist_unsupported; details: ~/.podster-runner/logs/errors.jsonl)
57
+ why: The task's container couldn't be started or prepared. Check that Docker is running and the task image is built; the details file has Docker's exit code and output. (code container_failed; details: ~/.podster-runner/logs/errors.jsonl)
58
58
  ```
59
59
 
60
60
  The details are in `logs/errors.jsonl` in Runner's home: one line per failure, with the time, the run's IDs, the code, and the raw error's message and stack. For a Docker command it also has Docker's exit code and the end of its error output. Each field is cut to 4 KiB. Before anything is written, the exact tokens Runner holds for a run (its broker token and the task's GitHub token) are written as `[redacted]`, and so is anything else that looks like a key or token. If Docker cut its own output, the last word of that output is redacted too. The folder is readable only by you (mode 700, owned by you, not a link). The file is mode 600, owned by you, with one link. The file is kept to 1 MiB and moves to `errors.jsonl.1` and `.2` as it fills, so at most three files are kept. It stays on this machine: Runner never sends it to Podster or anywhere else. `podster why <tsk_…>` prints a task's newest entry.
@@ -75,7 +75,9 @@ chmod 600 <path>
75
75
 
76
76
  Runner refuses a key file that's a link, that someone else can read, or that holds anything but one key. It reads the key once and keeps it on your machine, in its own process: never in a task's container, a log, an argument or the environment of anything it starts. Use a key with a spending limit you set at the provider.
77
77
 
78
- Runner's two container images, one for each task and one for Claude Code, are pinned by image ID in Runner's home. The first time `run --provider-key-file` finds one missing, Runner builds it with Docker from the Dockerfile in this package, says so first, and pins what it built. A build takes a few minutes, and the Claude Code image downloads Claude Code from npm's registry. If a build fails, `run` stops before running anything.
78
+ Runner's three container images, one for each task, one for Claude Code and one for the egress proxy (used only by rooms that list hosts in `rooms[].network`), are pinned by image ID in Runner's home. The first time `run --provider-key-file` finds one missing, Runner builds it with Docker from the Dockerfile in this package, says so first, and pins what it built. A build takes a few minutes, the Claude Code image downloads Claude Code from npm's registry, and the task image downloads Node.js from nodejs.org. If a build fails, `run` stops before running anything.
79
+
80
+ The task image is Debian bookworm-slim with the tools Runner's own task tools use (`cat`, `tee`, `mkdir`, `ls`, `kill` and ripgrep's `rg`), `/bin/sh` for a run policy that allows the shell, and Node.js 22.23.5 LTS with its npm and npx, so a task's shell commands can run `node`, `npm test` or `npx` on what's already in the task's folder. Each is pinned: the base by digest, Debian's packages at exact versions from one snapshot, and Node's official tarball by a SHA-256 written in the Dockerfile. npm keeps its cache and logs in the container's `/tmp` and its global prefix in `.npm-global` in the task's folder; the rest of the container is read-only. A task's container has no network unless its room lists hosts in `rooms[].network`, so without that, `npm install`, and `npx` of a package that isn't already in the task's `node_modules`, fail. With `"network": ["registry.npmjs.org"]`, npm reaches the registry through Runner's egress proxy.
79
81
 
80
82
  ## Your run policy (`policy.json`)
81
83
 
@@ -133,7 +135,7 @@ A complete, valid example, for one workroom. Replace the `org_…` and `ws_…`
133
135
  | `rooms[].mode` | `"ask"` shows each run at your terminal for you to approve. `"unattended"` runs without asking. Unattended runs are off by default: leave `mode` out or set `"ask"` until you choose otherwise. |
134
136
  | `rooms[].outputs` | `"hold"` keeps a finished run's result on your machine until you approve publishing it. `"share"` publishes it. Leaving it out means `"hold"`. |
135
137
  | `rooms[].tools` | Runner's own tools for a task. `read`, `search`, `write` and `edit` are the default. `shell` is never on unless you list it. |
136
- | `rooms[].network` | Must be `[]` (the default): no network. Runner can't allow hosts yet, since a task's container has no egress proxy, so a room listing any host is refused when Runner starts, with `network_allowlist_unsupported`. Host names will be allowed once the proxy exists. |
138
+ | `rooms[].network` | Host names the room's tasks may reach, such as `["registry.npmjs.org"]` so an agent can `npm install`; `[]`, the default, is no network. Only HTTPS on port 443 to exactly these names, through Runner's egress proxy: no subdomain, other host, plain HTTP, other port or IP address, and never a name that resolves to your LAN or this machine. List exact lower-case names, at most 50; a scheme, port, path, wildcard, IP address, upper case, trailing dot or a name like `localhost` is refused when Runner starts, with `network_host_invalid` and the entry's index. A listed host is fully reachable, so list only hosts you'd let the task send data to, and a host behind a shared CDN can be used to reach other sites on that CDN (domain fronting), which an allowlist of names can't stop. Needs Docker Engine 26 or later; an older one refuses the run with `docker_engine_too_old`. Runner logs each allowed or refused host when a run ends. |
137
139
  | `rooms[].repository` | `null` for a task that starts in an empty folder, or `{ "full_name": "owner/name", "provider_repo_id": 123456 }` for one GitHub repository. |
138
140
  | `rooms[].allowed_orgs` | Other organizations whose tasks you'll run in this room. Do not list `owner_org`: your own organization is always allowed, and Runner refuses a policy that lists it. An empty list is fine. |
139
141
  | `rooms[].acknowledged` | Both flags are required. Until `trust_statement` is `true`, Runner asks you at your terminal each time. Until `public_room_warning` is `true`, it also asks for a public room. |
@@ -14,7 +14,9 @@ const SUPPORT = `If it happens again, ${SEND}`;
14
14
  const RESTART = `Restart Runner with \`run\`; if it happens again, ${SEND}`;
15
15
  const TABLE = new Map([
16
16
  // The run policy and the network.
17
- ...group(["network_allowlist_unsupported"], "The room's policy lists network hosts, which Runner can't enforce yet.", "Set rooms[].network to [] in policy.json, then start Runner again."),
17
+ ...group(["egress_proxy_unavailable"], "The room's policy lists network hosts, but this Runner has no egress proxy to hold them, so the run didn't start.", "Start Runner with `run`, which builds and pins its egress proxy image, or set rooms[].network to [] in policy.json."),
18
+ ...group(["docker_engine_too_old"], "The room's policy lists network hosts, and this Docker Engine is older than 26, which could carry a task's DNS lookups past the egress proxy, so the run didn't start.", "Update Docker (Docker Desktop, or Docker Engine 26 or later), or set rooms[].network to [] in policy.json."),
19
+ ...group(["egress_proxy_not_ready", "egress_subnet_invalid", "egress_hosts_invalid", "egress_program_invalid"], "Runner's egress proxy for the room's listed hosts couldn't be started, so the run didn't start.", "Check that Docker is running; the details file has more. Restart Runner with `run` if it keeps happening."),
18
20
  ...group(["config_invalid", "budget_invalid"], "Runner's run policy can't be read or used.", "Fix policy.json; `run` names the field it refused when it starts."),
19
21
  ...group(["clock_invalid"], "This machine's clock went back past the day Runner last counted spend.", "Set the clock right; the task waits until then."),
20
22
  ...group(["authority_stale"], "Runner hasn't heard from Podster recently enough to trust this agent's access.", "Check the network connection; the task waits and is tried again."),
@@ -26,7 +28,7 @@ const TABLE = new Map([
26
28
  ...group(["prompt_unavailable", "provenance_invalid", "prompt_mismatch", "task_invalid"], "The task's inputs couldn't be read exactly as Podster listed them, so no prompt was built.", `Ask the room to check the task; if it happens again, ${SEND}`),
27
29
  ...group(["prompt_too_large", "prompt_invalid"], "The task's words are too large, or not text Runner can hand to the agent.", "Ask the room to shorten the task."),
28
30
  ...group(["blocked_same_inputs"], "The agent already answered blocked on these exact inputs, so Runner won't pay for the same answer again.", "Change the task, request changes, post a message on the task, or change the room's policy (such as adding shell), and it runs again."),
29
- ...group(["run_blocked"], "The agent reported it is blocked and couldn't finish.", "Read its reason on the task's thread. If it needs a shell, add \"shell\" to rooms[].tools in policy.json; network access can't be allowed yet (rooms[].network must stay [])."),
31
+ ...group(["run_blocked"], "The agent reported it is blocked and couldn't finish.", "Read its reason on the task's thread. If it needs a shell, add \"shell\" to rooms[].tools in policy.json; if it needs a host on the internet, list that exact host name in rooms[].network."),
30
32
  ...group(["note_scan_unknown", "note_scan_exhausted"], "Runner couldn't read the task's thread to check whether its note landed before a restart.", "It tries again with a growing wait; after six tries it posts its fixed note once."),
31
33
  ...group(["runner_could_not_start"], "Runner couldn't start a run for this task.", "The log line before it has the cause code, and the details file has the raw error."),
32
34
  // A run that never started.
@@ -73,7 +75,7 @@ const TABLE = new Map([
73
75
  ]);
74
76
  /** Codes with a fixed prefix and a varying part: a Docker command's step and exit code, or a Podster refusal's code. */
75
77
  const PREFIXES = [
76
- [/^docker_[a-z]+_(?:\d+|x|cut|output)$/, { what: "A Docker command failed.", todo: "Check that Docker is running; the details file has its exit code and output." }],
78
+ [/^docker_[a-z_]+_(?:\d+|x|cut|output)$/, { what: "A Docker command failed.", todo: "Check that Docker is running; the details file has its exit code and output." }],
77
79
  [/^(?:submit|accept|give_up|consume|pin|issue)_/, { what: "Podster or Runner's policy refused a step for this task.", todo: "The rest of the code says which; the task is read again or released." }],
78
80
  [/^repo_/, { what: "A step on the room's repository failed.", todo: "The details file has the cause." }],
79
81
  [/^task_[a-z_]+$/, { what: "The task's state changed, so Runner left it.", todo: "Nothing to do." }],
@@ -28,8 +28,11 @@
28
28
  * request, are required, each a positive integer under a fixed ceiling, with no "none" (condition 3; spike B rulings 3
29
29
  * and 5). A configuration lacking any of them is refused whole, as is anything else malformed.
30
30
  * - **Tools and network** are facts for step 9's adapter, which enforces them: no shell and no network unless listed by
31
- * name (condition 2). The adapter's result tool is always named. A room listing hosts is refused at load with
32
- * `network_allowlist_unsupported` until Runner's egress proxy exists: only `"network": []` works today.
31
+ * name (condition 2). The adapter's result tool is always named. A room's `network` lists exact lower-case host names
32
+ * (the owner's approval of 2026-11-20): the task's container then reaches those hosts, over HTTPS on port 443, through
33
+ * Runner's egress proxy (`egress-proxy.ts`), and nothing else. An entry that isn't such a name (a scheme, port, path,
34
+ * wildcard, IP address, upper case, a trailing dot or a special-use name such as `localhost`) is refused at load with
35
+ * `network_host_invalid`, a repeated one with `network_host_duplicate`.
33
36
  * - **Run decisions** are bound to every run fact, by a canonical form of the whole `RunFacts` (M1 on #455's review), and
34
37
  * to the task's version, input hash, repository and base. They are single-use and expire.
35
38
  * - **The repository** (M7 step 10; L4 on #455's review): a room has one only when the owner named it here, by full name
@@ -96,13 +99,18 @@ const COMMIT = /^(?:[0-9a-f]{40}|[0-9a-f]{64})$/;
96
99
  const LABEL = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/;
97
100
  const TLD = /^[a-z](?:[a-z0-9-]{0,61}[a-z0-9])?$/;
98
101
  const INPUTS = ["title", "instructions", "acceptance_criteria", "change_request"];
99
- /** A room's `network` listing hosts: refused until Runner's egress proxy exists; only `[]` works. */
100
- export const NETWORK_UNSUPPORTED = "network_allowlist_unsupported";
102
+ /** A room's `network` entry that isn't an exact lower-case host name Runner can allow. */
103
+ export const NETWORK_HOST_INVALID = "network_host_invalid";
104
+ /** A room's `network` naming one host twice. */
105
+ export const NETWORK_HOST_DUPLICATE = "network_host_duplicate";
101
106
  /** What's wrong with a policy that failed to parse, for the owner, by where it failed. */
102
107
  export function policyProblem(at) {
103
- const network = at.match(new RegExp(`^rooms\\[\\]\\.network:${NETWORK_UNSUPPORTED}:([A-Za-z0-9_-]{1,128})$`));
104
- if (network)
105
- return `the room ${network[1]} lists hosts in rooms[].network, which Runner can't allow yet (${NETWORK_UNSUPPORTED}): a task's container has no egress proxy, so only "network": [] works`;
108
+ const host = at.match(/^rooms\[\]\.network:(network_host_invalid|network_host_duplicate):([A-Za-z0-9_-]{1,128}):(\d{1,3})$/);
109
+ if (host && host[1] === NETWORK_HOST_INVALID) {
110
+ return `entry ${host[3]} of the room ${host[2]}'s rooms[].network isn't a host name Runner can allow (${NETWORK_HOST_INVALID}): list exact lower-case host names such as registry.npmjs.org, with no scheme, port, path, wildcard, IP address or trailing dot`;
111
+ }
112
+ if (host)
113
+ return `entry ${host[3]} of the room ${host[2]}'s rooms[].network repeats a host already listed (${NETWORK_HOST_DUPLICATE})`;
106
114
  return `${at} is missing or out of range`;
107
115
  }
108
116
  const fail = (at) => ({ ok: false, at });
@@ -169,11 +177,34 @@ function uniqueList(v, max, each) {
169
177
  return null;
170
178
  return new Set(v).size === v.length ? [...v] : null;
171
179
  }
172
- function isHost(v) {
180
+ /**
181
+ * Top-level names that never reach the public internet (RFC 6761, RFC 6762, RFC 8375 and Docker's own
182
+ * `*.docker.internal`): refused at load, so a listed name can't mean the machine, its LAN or Docker's host. The egress
183
+ * proxy also refuses any name that resolves to such an address, whatever its name.
184
+ */
185
+ const SPECIAL_TLDS = ["localhost", "local", "internal", "arpa", "invalid", "onion", "test", "example"];
186
+ /** An exact lower-case DNS host name with at least two labels, no IP address, wildcard, port or trailing dot. */
187
+ export function isHost(v) {
173
188
  if (typeof v !== "string" || v.length > 253)
174
189
  return false;
175
190
  const labels = v.split(".");
176
- return labels.length >= 2 && labels.every((l) => LABEL.test(l)) && TLD.test(labels[labels.length - 1]);
191
+ const tld = labels[labels.length - 1];
192
+ return labels.length >= 2 && labels.every((l) => LABEL.test(l)) && TLD.test(tld) && !SPECIAL_TLDS.includes(tld);
193
+ }
194
+ /** A room's `network`: a list of at most `MAX_HOSTS` distinct host names, each checked by `isHost`. */
195
+ function parseNetwork(v, roomId) {
196
+ if (!Array.isArray(v) || v.length > MAX_HOSTS)
197
+ return fail("rooms[].network");
198
+ const seen = new Set();
199
+ for (let i = 0; i < v.length; i++) {
200
+ const entry = v[i];
201
+ if (!isHost(entry))
202
+ return fail(`rooms[].network:${NETWORK_HOST_INVALID}:${roomId}:${i}`);
203
+ if (seen.has(entry))
204
+ return fail(`rooms[].network:${NETWORK_HOST_DUPLICATE}:${roomId}:${i}`);
205
+ seen.add(entry);
206
+ }
207
+ return { ok: true, value: [...seen] };
177
208
  }
178
209
  const isTool = (v) => typeof v === "string" && TOOLS.includes(v);
179
210
  const GH_OWNER = /^[A-Za-z0-9](?:[A-Za-z0-9-]{0,37}[A-Za-z0-9])?$/;
@@ -244,12 +275,11 @@ function parseRoom(v, ownerOrg) {
244
275
  const tools = Object.hasOwn(v, "tools") ? uniqueList(v.tools, TOOLS.length, isTool) : [...DEFAULT_TOOLS];
245
276
  if (!tools)
246
277
  return fail("rooms[].tools");
247
- const network = Object.hasOwn(v, "network") ? uniqueList(v.network, MAX_HOSTS, isHost) : [];
248
- if (!network)
249
- return fail("rooms[].network");
250
- // No sandbox can hold an allowlist until Runner's egress proxy exists: refused here, at load, not at every run's start.
251
- if (network.length > 0)
252
- return fail(`rooms[].network:${NETWORK_UNSUPPORTED}:${roomId}`);
278
+ // Each entry an exact host name, checked here, at load, so a bad one is said once, not at every run's start.
279
+ const parsedNetwork = Object.hasOwn(v, "network") ? parseNetwork(v.network, roomId) : { ok: true, value: [] };
280
+ if (!parsedNetwork.ok)
281
+ return parsedNetwork;
282
+ const network = parsedNetwork.value;
253
283
  const outputs = Object.hasOwn(v, "outputs") ? v.outputs : "hold";
254
284
  if (outputs !== "hold" && outputs !== "share")
255
285
  return fail("rooms[].outputs");
@@ -40,7 +40,9 @@ export function runFrame(facts) {
40
40
  return [
41
41
  UNTRUSTED_FRAME,
42
42
  `Your tools in this run: ${tools.length > 0 ? tools.join(", ") : "none"}, and the structured result.${shell ? "" : " There is no shell: you can't run commands, tests, builds, package managers or tools such as wrangler."}`,
43
- facts.network.length > 0 ? `Network: only these hosts: ${facts.network.join(", ")}. Nothing else is reachable.` : "Network: none. There is no network in this run: nothing outside the task's container is reachable, so don't plan to install packages (npm install, pip install), fetch anything or deploy. Work with the files that are there.",
43
+ facts.network.length > 0
44
+ ? `Network: only HTTPS, on port 443, to exactly these hosts: ${facts.network.join(", ")}. It goes through Runner's proxy, which the container's HTTPS_PROXY already names, so tools that read it, such as npm, use it without setup. Nothing else is reachable: no other host or subdomain, no plain HTTP, no other port and no IP address.`
45
+ : "Network: none. There is no network in this run: nothing outside the task's container is reachable, so don't plan to install packages (npm install, pip install), fetch anything or deploy. Work with the files that are there.",
44
46
  LIMITS_GUIDANCE,
45
47
  ].join("\n");
46
48
  }
@@ -71,6 +73,22 @@ export function markUntrusted(bytes) {
71
73
  /** The container's whole environment: fixed, nothing inherited, nothing shaped like a secret. */
72
74
  export const CONTAINER_ENV = Object.freeze({ HOME: "/work", PATH: "/usr/local/bin:/usr/bin:/bin", LANG: "C.UTF-8" });
73
75
  export const CONTAINER_WORKDIR = TASK_FOLDER_IN_CONTAINER;
76
+ /** The egress proxy's name on a run's internal network, and its port (`egress-proxy.ts`). */
77
+ export const EGRESS_ALIAS = "egress";
78
+ export const EGRESS_PORT = 3128;
79
+ /**
80
+ * What the container's environment adds when its room lists hosts: the proxy, in both spellings tools read, for HTTPS
81
+ * and plain HTTP alike (the proxy refuses plain HTTP, so it fails plainly instead of hanging), and nothing else. Fixed:
82
+ * no host, token or credential is in it.
83
+ */
84
+ export const EGRESS_ENV = Object.freeze({
85
+ HTTPS_PROXY: `http://${EGRESS_ALIAS}:${EGRESS_PORT}`,
86
+ https_proxy: `http://${EGRESS_ALIAS}:${EGRESS_PORT}`,
87
+ HTTP_PROXY: `http://${EGRESS_ALIAS}:${EGRESS_PORT}`,
88
+ http_proxy: `http://${EGRESS_ALIAS}:${EGRESS_PORT}`,
89
+ NO_PROXY: "localhost,127.0.0.1,::1",
90
+ no_proxy: "localhost,127.0.0.1,::1",
91
+ });
74
92
  /** What a container may outlive its run's time cap by, so Runner's own stop always comes first. */
75
93
  export const CONTAINER_MARGIN_S = 60;
76
94
  /** The container for a run, from its facts alone. */
@@ -79,7 +97,7 @@ export function containerSpec(run_ref, facts) {
79
97
  run_ref,
80
98
  task_folder: facts.task_folder,
81
99
  network: facts.network.length === 0 ? { kind: "none" } : { kind: "allowlist", hosts: [...facts.network] },
82
- env: { ...CONTAINER_ENV },
100
+ env: facts.network.length === 0 ? { ...CONTAINER_ENV } : { ...CONTAINER_ENV, ...EGRESS_ENV },
83
101
  mounts: [{ source: facts.task_folder, target: CONTAINER_WORKDIR }],
84
102
  read_only_root: true,
85
103
  drop_capabilities: "all",
@@ -88,13 +106,17 @@ export function containerSpec(run_ref, facts) {
88
106
  };
89
107
  }
90
108
  /**
91
- * Why a spec can't be opened, or null. The environment must be exactly the fixed one, so no key, token, keychain or
92
- * D-Bus address, agent socket or Docker host reaches a task; the only mount is the task's own folder.
109
+ * Why a spec can't be opened, or null. The environment must be exactly the fixed one (with the proxy's, `EGRESS_ENV`,
110
+ * exactly when the network is an allowlist), so no key, token, keychain or D-Bus address, agent socket or Docker host
111
+ * reaches a task; the only mount is the task's own folder.
93
112
  */
94
113
  export function checkContainerSpec(spec) {
114
+ const fixed = spec.network.kind === "allowlist" ? { ...CONTAINER_ENV, ...EGRESS_ENV } : CONTAINER_ENV;
95
115
  const names = Object.keys(spec.env);
96
- if (names.length !== Object.keys(CONTAINER_ENV).length || names.some((n) => !Object.hasOwn(CONTAINER_ENV, n) || spec.env[n] !== CONTAINER_ENV[n]))
116
+ if (names.length !== Object.keys(fixed).length || names.some((n) => !Object.hasOwn(fixed, n) || spec.env[n] !== fixed[n]))
97
117
  return "env_not_allowed";
118
+ if (spec.network.kind !== "none" && (spec.network.kind !== "allowlist" || spec.network.hosts.length === 0))
119
+ return "spec_invalid";
98
120
  if (spec.mounts.length !== 1 || spec.mounts[0].source !== spec.task_folder || spec.mounts[0].target !== CONTAINER_WORKDIR)
99
121
  return "mount_not_allowed";
100
122
  if (spec.read_only_root !== true || spec.drop_capabilities !== "all" || spec.user !== "unprivileged")
@@ -162,7 +184,7 @@ export class SupervisedAdapter {
162
184
  await live.begin();
163
185
  }
164
186
  catch (error) {
165
- // The cause is kept as a code only, such as the sandbox's `network_allowlist_unsupported`: never a message's words.
187
+ // The cause is kept as a code only, such as the sandbox's `egress_proxy_unavailable`: never a message's words.
166
188
  const cause = codeOf(error);
167
189
  await live.halt("start_failed");
168
190
  this.deps.log("adapter.run", "start_failed", { workspace: run.workspace_id, task: run.task_id, code: cause });
@@ -20,9 +20,11 @@ const ID_VALUE = /^[A-Za-z0-9_-]{1,128}$/;
20
20
  const CODE_VALUE = /^[a-z][a-z0-9_]{0,63}$/;
21
21
  const NAMES_VALUE = /^[a-z_?]{1,40}(,[a-z_?]{1,40}){0,9}$/;
22
22
  const PREFIX_VALUE = /^(yes|no)$/;
23
+ /** A lower-case DNS name of two or more labels whose last starts with a letter, so never an IP address. */
24
+ const HOST_VALUE = /^(?=.{1,253}$)(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z](?:[a-z0-9-]{0,61}[a-z0-9])?$/;
23
25
  const TYPE_VALUE = /^(null|array|object|string|number|boolean|undefined|bigint|symbol|function)$/;
24
26
  const NUMBER_FIELDS = new Set(["seq", "count", "status", "length"]);
25
- const ID_FIELDS = new Set(["agent", "plugin_agent", "workspace", "task", "attempt_id"]);
27
+ const ID_FIELDS = new Set(["agent", "plugin_agent", "workspace", "task", "attempt_id", "run"]);
26
28
  /** The line a logger writes, with everything that isn't allowed dropped. */
27
29
  export function logLine(at, outcome, fields = {}) {
28
30
  const line = { at: NAME.test(at) ? at : "runner", outcome: NAME.test(outcome) ? outcome : "unknown" };
@@ -33,6 +35,8 @@ export function logLine(at, outcome, fields = {}) {
33
35
  line[name] = value;
34
36
  else if (name === "names" && typeof value === "string" && NAMES_VALUE.test(value))
35
37
  line[name] = value;
38
+ else if (name === "host" && typeof value === "string" && HOST_VALUE.test(value))
39
+ line[name] = value;
36
40
  else if (name === "prefix" && typeof value === "string" && PREFIX_VALUE.test(value))
37
41
  line[name] = value;
38
42
  else if (name === "type" && typeof value === "string" && TYPE_VALUE.test(value))
@@ -86,6 +86,11 @@ export const RELAY_SOCKET_IN_CONTAINER = "/relay/runner.sock";
86
86
  /** The listener socket's name in the run's folder. Short, so the whole path fits a socket's limit. */
87
87
  export const SOCKET_NAME = "r.sock";
88
88
  export { LABEL_ROLE };
89
+ /**
90
+ * The driver's own network, by role: never the run's egress network, which the task sandbox opens and removes with the
91
+ * task's container, so the two never remove one network at once.
92
+ */
93
+ const OWN_NETWORK = `label=${LABEL_ROLE}=network`;
89
94
  /** How long Claude Code's containers may outlive a run's time cap, as the task container may. */
90
95
  const CONTAINER_MARGIN_S = 60;
91
96
  /** The names of a run's Claude Code container, relay and network. */
@@ -291,7 +296,7 @@ const TOOL_SHAPES = {
291
296
  search: { description: "Search the task's folder, or a folder in it given by a relative path, for a regular expression.", shape: { pattern: z.string(), path: z.string().optional() } },
292
297
  write: { description: "Write a whole file in the task's folder. Its path is relative to the folder, such as notes.txt.", shape: { path: z.string(), content: z.string() } },
293
298
  edit: { description: "Replace one exact piece of text, which must appear once, in a file in the task's folder. Its path is relative to the folder.", shape: { path: z.string(), old: z.string(), new: z.string() } },
294
- shell: { description: "Run a shell command in the task's container, in its folder, with no network.", shape: { command: z.string() } },
299
+ shell: { description: "Run a shell command in the task's container, in its folder. It reaches no network but the hosts the run's instructions name, if any.", shape: { command: z.string() } },
295
300
  };
296
301
  /** The same input, written the same way, whatever its key order. */
297
302
  function canonical(v) {
@@ -418,7 +423,7 @@ export class ClaudeDriver {
418
423
  throw new Error("run_ref_invalid");
419
424
  const run = [`label=${LABEL_RUN}=${ref}`];
420
425
  await removeContainers(this.deps.docker, await this.own(run), () => this.own(run), this.wait);
421
- await this.removeNetworks(run);
426
+ await this.removeNetworks([...run, OWN_NETWORK]);
422
427
  }
423
428
  /** Each network matching `filters`: attached containers disconnected, removed, then confirmed gone. */
424
429
  async removeNetworks(filters) {
@@ -693,7 +698,7 @@ export class ClaudeDriver {
693
698
  try {
694
699
  if ((await this.own([`label=${LABEL_RUN}=${run_ref}`])).length > 0)
695
700
  return false;
696
- if ((await this.list("network", [`label=${LABEL_RUN}=${run_ref}`])).length > 0)
701
+ if ((await this.list("network", [`label=${LABEL_RUN}=${run_ref}`, OWN_NETWORK])).length > 0)
697
702
  return false;
698
703
  }
699
704
  catch {
@@ -713,7 +718,7 @@ export class ClaudeDriver {
713
718
  async reapAll() {
714
719
  const home = [`label=${LABEL_HOME}=${this.homeLabel}`];
715
720
  await removeContainers(this.deps.docker, await this.own(home), () => this.own(home), this.wait);
716
- await this.removeNetworks(home);
721
+ await this.removeNetworks([...home, OWN_NETWORK]);
717
722
  }
718
723
  }
719
724
  /** The real exec client: from an argument array, never a shell, its errors drained. */
@@ -5,8 +5,9 @@
5
5
  * Before anything runs, it refuses unless:
6
6
  * - the installed SDK and its bundled Claude Code are exactly the pinned pair (S-48);
7
7
  * - the key file is a regular file, not a link, owned by the owner and readable by no one else, holding one key;
8
- * - Runner's two images are pinned: `task-image` and `claude-image` in Runner's home each name an image ID
9
- * (`sha256:…`), built from `apps/runner/sandbox` and `apps/runner/claude-image`. A pin that's missing, or names an
8
+ * - Runner's three images are pinned: `task-image`, `claude-image` and `proxy-image` in Runner's home each name an image
9
+ * ID (`sha256:…`), built from `apps/runner/sandbox`, `apps/runner/claude-image` and `apps/runner/proxy-image` (the
10
+ * egress proxy's, for rooms that list hosts). A pin that's missing, or names an
10
11
  * image Docker no longer has, is built from the Dockerfile in Runner's own package and pinned (`ensureImage`, the
11
12
  * ruling on #470); a build that fails stops `run` before anything runs;
12
13
  * - `docker` is installed in a fixed place;
@@ -32,6 +33,7 @@ import { CLAUDE_PROFILE } from "../core/claude-profile.js";
32
33
  import { ClaudeDriver } from "./claude-driver.js";
33
34
  import { DockerSandbox, dockerCli, dockerHost, findDocker, IMAGE_ID } from "./docker-sandbox.js";
34
35
  import { dockerReachable, homeLengthRefusal, homeRefusal, isWsl, linuxCheckFailure, readMounts, readProcVersion, relayModeFor, resolvedPath } from "./platform.js";
36
+ import { loadProxyProgram } from "./egress-network.js";
35
37
  import { ProviderKeyTransport } from "./provider-transport.js";
36
38
  import { ensureFolder, readNoFollow, writeNew } from "./safe-fs.js";
37
39
  /** The installed SDK's version and its bundled Claude Code's, from its own manifest. */
@@ -84,25 +86,37 @@ export async function claudeImage(home) {
84
86
  throw new Error("Runner's Claude Code image isn't pinned. Build apps/runner/claude-image and write its image ID (sha256:…) to claude-image in Runner's home.");
85
87
  return text;
86
88
  }
89
+ /** Runner's pinned egress proxy image, from `proxy-image` in its home. */
90
+ export async function proxyImage(home) {
91
+ const text = (await readNoFollow(join(home, "proxy-image"), 256))?.trim();
92
+ if (!text || !IMAGE_ID.test(text))
93
+ throw new Error("Runner's egress proxy image isn't pinned. Build apps/runner/proxy-image and write its image ID (sha256:…) to proxy-image in Runner's home.");
94
+ return text;
95
+ }
96
+ const PINNED = { "task-image": taskImage, "claude-image": claudeImage, "proxy-image": proxyImage };
87
97
  /** Each image's build folder, in Runner's own package: its Dockerfile, which copies nothing from the folder. */
88
98
  export const IMAGE_SOURCES = {
89
99
  "task-image": fileURLToPath(new URL("../../sandbox", import.meta.url)),
90
100
  "claude-image": fileURLToPath(new URL("../../claude-image", import.meta.url)),
101
+ "proxy-image": fileURLToPath(new URL("../../proxy-image", import.meta.url)),
91
102
  };
92
103
  /** The fixed line said before a build. */
93
104
  export const BUILDING = {
94
105
  "task-image": "Building Runner's task image from its packaged Dockerfile. This happens once and takes a few minutes.",
95
106
  "claude-image": "Building Runner's Claude Code image from its packaged Dockerfile. This happens once and takes a few minutes.",
107
+ "proxy-image": "Building Runner's egress proxy image from its packaged Dockerfile. This happens once and takes a few minutes.",
96
108
  };
97
109
  /** The fixed message a failed build stops `run` with. Docker's own output never reaches it. */
98
110
  export const BUILD_FAILED = {
99
111
  "task-image": "Runner couldn't build its task image, so nothing ran. Check that Docker Desktop is running, then start `run` again.",
100
112
  "claude-image": "Runner couldn't build its Claude Code image, so nothing ran. Check that Docker Desktop is running, then start `run` again.",
113
+ "proxy-image": "Runner couldn't build its egress proxy image, so nothing ran. Check that Docker Desktop is running, then start `run` again.",
101
114
  };
102
115
  /** The fixed message when Docker can't say whether a pinned image exists. Nothing is built or re-pinned. */
103
116
  export const INSPECT_FAILED = {
104
117
  "task-image": "Runner couldn't check its task image with Docker, so nothing ran. Check that Docker Desktop is running, then start `run` again.",
105
118
  "claude-image": "Runner couldn't check its Claude Code image with Docker, so nothing ran. Check that Docker Desktop is running, then start `run` again.",
119
+ "proxy-image": "Runner couldn't check its egress proxy image with Docker, so nothing ran. Check that Docker Desktop is running, then start `run` again.",
106
120
  };
107
121
  /** Docker's own answer for an image it doesn't have, from `docker image inspect`. */
108
122
  const NO_SUCH_IMAGE = /^(Error: |Error response from daemon: )?No such image: /m;
@@ -145,7 +159,7 @@ export async function ensureImage(name, opts) {
145
159
  const path = join(opts.home, name);
146
160
  const pinned = (await readNoFollow(path, 256))?.trim();
147
161
  if (pinned) {
148
- const pinnedId = name === "task-image" ? await taskImage(opts.home) : await claudeImage(opts.home);
162
+ const pinnedId = await PINNED[name](opts.home);
149
163
  const present = await opts.docker(["image", "inspect", "--format", "{{.Id}}", pinnedId], { timeoutMs: 60_000, maxOutputBytes: 4096 });
150
164
  if (present.code === 0)
151
165
  return pinnedId;
@@ -192,6 +206,8 @@ export async function claudeEngine(opts) {
192
206
  const notify = opts.notify ?? (() => undefined);
193
207
  const image = await ensureImage("task-image", { home: opts.home, docker, notify });
194
208
  const ccImage = await ensureImage("claude-image", { home: opts.home, docker, notify });
209
+ // The egress proxy's, for rooms whose run policy lists hosts; its program is Runner's own built file, read when needed.
210
+ const pxImage = await ensureImage("proxy-image", { home: opts.home, docker, notify });
195
211
  const uid = typeof process.getuid === "function" ? process.getuid() : 0;
196
212
  const gid = typeof process.getgid === "function" ? process.getgid() : 0;
197
213
  // Never bare: under bare mode the SDK's PreToolUse callback, Runner's decision point, never fires (the fifth real run
@@ -208,7 +224,7 @@ export async function claudeEngine(opts) {
208
224
  }
209
225
  opts.log("adapter.platform", "linux_checked", {});
210
226
  }
211
- const sandbox = new DockerSandbox({ docker, image, uid, gid, home: opts.home, wait: opts.wait, ...(relay === "unix" ? { mounts: () => (opts.mounts !== undefined ? opts.mounts : readMounts()) } : {}) });
227
+ const sandbox = new DockerSandbox({ docker, image, uid, gid, home: opts.home, wait: opts.wait, log: opts.log, proxy: { image: pxImage, program: () => loadProxyProgram() }, ...(relay === "unix" ? { mounts: () => (opts.mounts !== undefined ? opts.mounts : readMounts()) } : {}) });
212
228
  return {
213
229
  drivers: { claude_agent_sdk: driver },
214
230
  sandbox,
@@ -6,9 +6,16 @@
6
6
  * non-root UID (the owner's, so the task folder Runner made 0700 stays theirs); `--cap-drop ALL`;
7
7
  * `no-new-privileges`; a read-only root; `/tmp` a bounded tmpfs; PID, memory, swap and CPU limits; a disk bound (a
8
8
  * per-file size limit, a bounded tmpfs and a host-side size check of the task folder after every tool that writes);
9
- * `--network none`; no Docker socket, no device and no other mount than the task's folder; a fixed environment; and
10
- * labels naming the run and this Runner's home, so a stop or a restart finds it.
11
- * - **Network:** none. A policy that lists hosts is refused until an egress proxy exists.
9
+ * `--network none` unless the room lists hosts; no Docker socket, no device and no other mount than the task's folder;
10
+ * a fixed environment; and labels naming the run and this Runner's home, so a stop or a restart finds it.
11
+ * - **Network:** none, unless the room's run policy lists hosts (the owner's approval of 2026-11-20). Then the container
12
+ * joins only the run's internal network, whose one other peer is the run's egress proxy (`egress-network.ts`,
13
+ * `egress-proxy.ts`), gets the proxy's address in its fixed environment, and a resolver that answers nothing outside
14
+ * that network: Docker 26 and later answer no outside name on an internal network, older Engines are refused
15
+ * (`docker_engine_too_old`), and its upstream resolver is an address that is never routed (`BLACKHOLE_DNS`). The
16
+ * internal network has no host address (`inhibit_ipv4`), so nothing on the machine is reachable from it. The proxy allows HTTPS `CONNECT`
17
+ * to port 443 of exactly the listed hosts, at public addresses only. Without a pinned proxy image, such a run is
18
+ * refused (`egress_proxy_unavailable`), never widened.
12
19
  * - **The disk bound for the whole run** (M2 on #460): the folder's size is checked on a timer, every
13
20
  * `LIMITS.watch_ms`, independent of tool calls, so a process left running can't fill the disk between them, and a
14
21
  * breach the timer finds halts the run too (re-review item 5); and after each shell call every process in the
@@ -25,8 +32,9 @@
25
32
  * reads, replaces one exact match in Runner, and writes the same way. Only the `shell` tool, when the policy names it,
26
33
  * runs `/bin/sh -c`, which is what that tool is.
27
34
  * - **Stop:** `kill` removes every container carrying the run's label (killing a `docker exec` client leaves its process
28
- * running, so the container goes). At startup `reapAll` removes every container of this Runner's home, since one
29
- * Runner holds the home at a time and anything left is a previous process's.
35
+ * running, so the container goes), then the run's egress proxy and network, after logging the proxy's decisions. At
36
+ * startup `reapAll` removes every container and egress network of this Runner's home, since one Runner holds the home
37
+ * at a time and anything left is a previous process's.
30
38
  *
31
39
  * The `docker` program is a seam (`DockerCli`), so tests run no Docker. It gets the allow-listed environment plus its
32
40
  * own settings: a throwaway `DOCKER_CONFIG`, and the daemon's address. Logs carry IDs and codes only.
@@ -37,7 +45,9 @@ import { createHash } from "node:crypto";
37
45
  import { existsSync } from "node:fs";
38
46
  import { homedir } from "node:os";
39
47
  import { dirname, join } from "node:path";
40
- import { checkContainerSpec, CONTAINER_ENV, CONTAINER_WORKDIR, MAX_TOOL_OUTPUT_BYTES } from "../core/run-interface.js";
48
+ import { checkContainerSpec, CONTAINER_ENV, CONTAINER_WORKDIR, EGRESS_ENV, MAX_TOOL_OUTPUT_BYTES } from "../core/run-interface.js";
49
+ import { silentLogger } from "../core/runtime.js";
50
+ import { egressNames, logProxyDecisions, openEgress, removeNetworks, ROLE_NETWORK, ROLE_PROXY } from "./egress-network.js";
41
51
  import { onWindowsDrive } from "../core/policy.js";
42
52
  import { onWindowsFilesystem } from "./platform.js";
43
53
  import { childEnv } from "./child-env.js";
@@ -123,7 +133,10 @@ const containerName = (ref) => `podster-run-${ref.toLowerCase()}`;
123
133
  export const homeLabel = (home) => createHash("sha256").update(home).digest("hex").slice(0, 32);
124
134
  /** `docker run`'s arguments for a spec: the whole hardening list, and nothing from the task. */
125
135
  export function runArgs(spec, opts) {
126
- const env = Object.entries(CONTAINER_ENV).flatMap(([name, value]) => ["--env", `${name}=${value}`]);
136
+ const allowlist = spec.network.kind === "allowlist";
137
+ const env = Object.entries(allowlist ? { ...CONTAINER_ENV, ...EGRESS_ENV } : CONTAINER_ENV).flatMap(([name, value]) => ["--env", `${name}=${value}`]);
138
+ // Only the run's internal network, never a route out; its resolver answers only that network's names.
139
+ const network = allowlist ? ["--network", egressNames(spec.run_ref).network, "--dns", BLACKHOLE_DNS] : ["--network", "none"];
127
140
  return [
128
141
  "run",
129
142
  "--detach",
@@ -160,8 +173,7 @@ export function runArgs(spec, opts) {
160
173
  "nofile=1024:1024",
161
174
  "--ulimit",
162
175
  "core=0",
163
- "--network",
164
- "none",
176
+ ...network,
165
177
  "--ipc",
166
178
  "none",
167
179
  ...env,
@@ -188,7 +200,26 @@ export function toolArgv(call) {
188
200
  return null;
189
201
  }
190
202
  }
191
- const REFUSED_NETWORK = "network_allowlist_unsupported";
203
+ /** A run whose room lists hosts, on a Runner with no pinned egress proxy: refused, never widened to the internet. */
204
+ export const EGRESS_UNAVAILABLE = "egress_proxy_unavailable";
205
+ /** A run whose room lists hosts, on a Docker Engine older than `MIN_EGRESS_ENGINE`: refused. */
206
+ export const ENGINE_TOO_OLD = "docker_engine_too_old";
207
+ /**
208
+ * The oldest Docker Engine an allowlist runs on: 26.0, whose resolver no longer forwards a container's lookups outside
209
+ * an internal network. An older one could carry a task's DNS queries out, a channel past the proxy.
210
+ */
211
+ export const MIN_EGRESS_ENGINE = 26;
212
+ /**
213
+ * The task container's upstream resolver when its room lists hosts: an address of TEST-NET-1 (RFC 5737), which is never
214
+ * routed, isn't loopback (Docker forwards to a loopback resolver from the host's own namespace), and is outside every
215
+ * network the container is on. So even an engine that forwarded outside names would send them nowhere.
216
+ */
217
+ export const BLACKHOLE_DNS = "192.0.2.1";
218
+ /** The Engine's major version from `docker version --format {{.Server.Version}}`, or null. */
219
+ export function engineMajor(stdout) {
220
+ const m = stdout.trim().match(/^(\d{1,4})\.\d{1,4}/);
221
+ return m ? Number(m[1]) : null;
222
+ }
192
223
  /** The most `/proc` listings one stray-reap may take before it ends the container instead. **Proposed** figure. */
193
224
  export const STRAY_LISTINGS = 6;
194
225
  /** The PIDs an `ls -l -- /proc` shows, leaving out the listing's own (the target of `/proc/self`). */
@@ -210,9 +241,14 @@ export class DockerSandbox {
210
241
  limits;
211
242
  wait;
212
243
  mounts;
244
+ egress;
245
+ engineChecked = false;
246
+ log;
213
247
  constructor(opts) {
214
248
  if (!IMAGE_ID.test(opts.image))
215
249
  throw new Error("Runner's task image must be pinned by its sha256 image ID");
250
+ if (opts.proxy && !IMAGE_ID.test(opts.proxy.image))
251
+ throw new Error("Runner's egress proxy image must be pinned by its sha256 image ID");
216
252
  if (!Number.isSafeInteger(opts.uid) || !Number.isSafeInteger(opts.gid) || opts.uid <= 0 || opts.gid < 0)
217
253
  throw new Error("Runner won't run a task container as root");
218
254
  this.docker = opts.docker;
@@ -226,6 +262,8 @@ export class DockerSandbox {
226
262
  // The system's mounts, read at each open; none (no check by type) where there's no /proc, as on a Mac.
227
263
  this.mounts = opts.mounts ?? (() => null);
228
264
  this.limits = { folder_bytes: opts.limits?.folder_bytes ?? LIMITS.folder_bytes, folder_entries: opts.limits?.folder_entries ?? LIMITS.folder_entries };
265
+ this.log = opts.log ?? silentLogger;
266
+ this.egress = opts.proxy ? { docker: opts.docker, image: opts.proxy.image, program: opts.proxy.program, uid: opts.uid, gid: opts.gid, home_label: this.homeLabel, wait: this.wait } : null;
229
267
  }
230
268
  async overBound(opened) {
231
269
  return (await folderBytes(opened.spec.task_folder, this.limits.folder_bytes, this.limits.folder_entries).catch(() => this.limits.folder_bytes + 1)) > this.limits.folder_bytes;
@@ -238,9 +276,9 @@ export class DockerSandbox {
238
276
  // Never the Windows file system under WSL2, where modes aren't enforced (S-47); the run policy refuses it first.
239
277
  if (onWindowsDrive(spec.task_folder))
240
278
  throw new Error("workspace_on_windows_drive");
241
- // No allowlist without an egress proxy to hold it (step 9(b)'s ruling): refused, never widened to the internet.
242
- if (spec.network.kind !== "none")
243
- throw new Error(REFUSED_NETWORK);
279
+ // No allowlist without an egress proxy to hold it: refused, never widened to the internet.
280
+ if (spec.network.kind !== "none" && !this.egress)
281
+ throw new Error(EGRESS_UNAVAILABLE);
244
282
  // Runner makes the task's folder itself, mode 0700, checking every segment for links (L3).
245
283
  await ensureFolder(this.workspaceRoot(spec), spec.task_folder, { makeRoot: true });
246
284
  // By its real path and its mount's type too (L1 on #471's review): a link, or a drive mounted somewhere other than
@@ -250,6 +288,27 @@ export class DockerSandbox {
250
288
  throw new Error("workspace_on_windows_drive");
251
289
  if (signal.aborted)
252
290
  throw new Error("halted");
291
+ if (spec.network.kind === "allowlist" && this.egress) {
292
+ // Once per process: an Engine too old to keep DNS inside an internal network refuses every allowlist run.
293
+ if (!this.engineChecked) {
294
+ const v = await this.docker(["version", "--format", "{{.Server.Version}}"], { signal, timeoutMs: LIMITS.docker_ms, maxOutputBytes: 4096 });
295
+ const major = v.code === 0 && !v.cut ? engineMajor(v.stdout) : null;
296
+ if (major === null)
297
+ throw dockerFailure("version", v.code);
298
+ if (major < MIN_EGRESS_ENGINE)
299
+ throw new Error(ENGINE_TOO_OLD);
300
+ this.engineChecked = true;
301
+ }
302
+ // Recorded first, so a kill reaches a network or proxy a failed step still made.
303
+ this.opened.set(spec.run_ref, { name: containerName(spec.run_ref), spec, sleep_pid: null, unwatch: () => undefined, events: events ?? null });
304
+ try {
305
+ await openEgress(this.egress, spec.run_ref, spec.network.hosts, spec.max_seconds, signal);
306
+ }
307
+ catch (error) {
308
+ await this.kill(spec.run_ref).catch(() => undefined);
309
+ throw error;
310
+ }
311
+ }
253
312
  const run = await this.docker(runArgs(spec, { image: this.image, uid: this.uid, gid: this.gid, home_label: this.homeLabel }), { signal, timeoutMs: LIMITS.docker_ms, maxOutputBytes: 4096 });
254
313
  // Recorded either way, so a kill reaches a container a failed or aborted `docker run` still made.
255
314
  const opened = { name: containerName(spec.run_ref), spec, sleep_pid: null, unwatch: () => undefined, events: events ?? null };
@@ -375,27 +434,64 @@ export class DockerSandbox {
375
434
  this.opened.get(run_ref)?.unwatch();
376
435
  // By labels and by name, resolved to IDs and each named once, then confirmed gone.
377
436
  const left = async () => [...new Set([...(await this.list([`label=${LABEL_RUN}=${run_ref}`, `label=${LABEL_ROLE}=task`])), ...(await this.list([`name=^/${containerName(run_ref)}$`]))])];
378
- await removeContainers(this.docker, await left(), left, this.wait);
437
+ // Each step is tried even if one before it threw, so a task container Docker won't remove never leaves the proxy
438
+ // and networks behind; the first failure is thrown at the end, so the stop is never taken as done.
439
+ const failures = [];
440
+ const attempt = async (step) => {
441
+ try {
442
+ await step();
443
+ }
444
+ catch (error) {
445
+ failures.push(error);
446
+ }
447
+ };
448
+ await attempt(async () => removeContainers(this.docker, await left(), left, this.wait));
449
+ // Then the run's egress proxy, its decisions logged first, and its two networks.
450
+ const proxies = async () => [...new Set([...(await this.list([`label=${LABEL_RUN}=${run_ref}`, `label=${LABEL_ROLE}=${ROLE_PROXY}`])), ...(await this.list([`name=^/${egressNames(run_ref).proxy}$`]))])];
451
+ await attempt(async () => {
452
+ const found = await proxies();
453
+ if (found.length > 0)
454
+ await logProxyDecisions(this.docker, run_ref, this.log).catch(() => undefined);
455
+ await removeContainers(this.docker, found, proxies, this.wait);
456
+ });
457
+ await attempt(() => removeNetworks(this.docker, [`label=${LABEL_RUN}=${run_ref}`, `label=${LABEL_ROLE}=${ROLE_NETWORK}`], this.wait));
458
+ if (failures.length > 0)
459
+ throw failures[0];
379
460
  }
380
- /** Nothing of the run's task container is listed, by its labels or by its name (Docker names carry a leading slash). */
461
+ /** Nothing of the run's task container or egress is listed, by labels or by name (Docker names carry a leading slash). */
381
462
  async gone(run_ref) {
382
463
  if (!REF.test(run_ref))
383
464
  throw new Error("run_ref_invalid");
384
- const left = (await this.list([`label=${LABEL_RUN}=${run_ref}`, `label=${LABEL_ROLE}=task`])).length === 0 && (await this.list([`name=^/${containerName(run_ref)}$`])).length === 0;
465
+ const left = (await this.list([`label=${LABEL_RUN}=${run_ref}`, `label=${LABEL_ROLE}=task`])).length === 0 &&
466
+ (await this.list([`name=^/${containerName(run_ref)}$`])).length === 0 &&
467
+ (await this.list([`label=${LABEL_RUN}=${run_ref}`, `label=${LABEL_ROLE}=${ROLE_PROXY}`])).length === 0 &&
468
+ (await this.list([`name=^/${egressNames(run_ref).proxy}$`])).length === 0 &&
469
+ (await this.listNetworks([`label=${LABEL_RUN}=${run_ref}`, `label=${LABEL_ROLE}=${ROLE_NETWORK}`])).length === 0;
385
470
  if (left) {
386
471
  this.opened.get(run_ref)?.unwatch();
387
472
  this.opened.delete(run_ref);
388
473
  }
389
474
  return left;
390
475
  }
391
- /** At startup, before any stop is confirmed (M4 on #459): every container of this home goes. */
476
+ /** At startup, before any stop is confirmed (M4 on #459): every container of this home goes, then its egress networks. */
392
477
  async reapAll() {
393
478
  const ids = await this.list([`label=${LABEL_HOME}=${this.homeLabel}`]);
394
- if (ids.length === 0)
395
- return 0;
396
- await removeContainers(this.docker, ids, () => this.list([`label=${LABEL_HOME}=${this.homeLabel}`]), this.wait);
479
+ if (ids.length > 0)
480
+ await removeContainers(this.docker, ids, () => this.list([`label=${LABEL_HOME}=${this.homeLabel}`]), this.wait);
481
+ await removeNetworks(this.docker, [`label=${LABEL_HOME}=${this.homeLabel}`, `label=${LABEL_ROLE}=${ROLE_NETWORK}`], this.wait);
397
482
  return ids.length;
398
483
  }
484
+ async listNetworks(filters) {
485
+ const r = await this.docker(["network", "ls", "--quiet", "--no-trunc", ...filters.flatMap((f) => ["--filter", f])], { timeoutMs: LIMITS.docker_ms, maxOutputBytes: 64 * 1024 });
486
+ if (r.code !== 0)
487
+ throw dockerFailure("network_ls", r.code);
488
+ if (r.cut)
489
+ throw new Error("docker_network_ls_cut");
490
+ const ids = r.stdout.split("\n").map((l) => l.trim()).filter((l) => l !== "");
491
+ if (!ids.every((id) => /^[A-Za-z0-9_.-]{1,128}$/.test(id)))
492
+ throw new Error("docker_network_ls_output");
493
+ return ids;
494
+ }
399
495
  async list(filters) {
400
496
  const r = await this.docker(["ps", "--all", "--quiet", "--no-trunc", ...filters.flatMap((f) => ["--filter", f])], { timeoutMs: LIMITS.docker_ms, maxOutputBytes: 64 * 1024 });
401
497
  if (r.code !== 0)
@@ -0,0 +1,217 @@
1
+ /**
2
+ * A run's egress: the internal network and proxy container that let a task's container reach exactly the hosts its
3
+ * room's run policy lists (the owner's approval of 2026-11-20). `DockerSandbox` opens them before the task's container
4
+ * when the run's network is an allowlist, and removes them with it.
5
+ *
6
+ * - **Two networks, per run.** The internal one is `--internal`, so Docker gives it no route out, and its bridge has no
7
+ * address on the host (`inhibit_ipv4`), so no gateway either; its only containers are the task's and the proxy. The outbound one is an ordinary bridge network of the run's own, whose only container
8
+ * is the proxy, so no other container on the machine shares the proxy's route out (not Docker's default bridge), and
9
+ * Docker's resolver forwards the proxy's lookups. Both carry the run's and home's labels and the role
10
+ * `egress-network`, so the stray sweep at startup finds them, and Claude Code's driver, which removes its own role
11
+ * `network`, never touches them.
12
+ * - **The proxy** (`egress-proxy.ts`) starts on the internal network with the alias `egress`, listening only on its own
13
+ * address there, and only then joins the outbound network. Its image is pinned by its image ID and
14
+ * holds Node only; the program is Runner's own built `egress-proxy.js`, given as an argument with the subnet and the
15
+ * room's hosts (no secret). It has the task container's hardening with tighter limits, no mount and a lifetime of the
16
+ * run's.
17
+ * - **The task's container** joins only the internal network and gets the proxy's address through Runner's fixed
18
+ * environment (`EGRESS_ENV`). Docker's resolver on an internal network answers only the names of its containers.
19
+ *
20
+ * Every Docker failure is a fixed code with its step and exit code. Logs carry the run's ID, hosts and codes only.
21
+ */
22
+ import { readFile } from "node:fs/promises";
23
+ import { EGRESS_ALIAS } from "../core/run-interface.js";
24
+ import { dockerFailure, LABEL_HOME, LABEL_ROLE, LABEL_RUN, LIMITS, REMOVAL_CHECK_MS, REMOVAL_CHECKS } from "./docker-sandbox.js";
25
+ import { isHostName, PROXY_REFUSALS } from "./egress-proxy.js";
26
+ export const ROLE_PROXY = "egress";
27
+ export const ROLE_NETWORK = "egress-network";
28
+ /** The names of a run's egress network and proxy container. */
29
+ export function egressNames(ref) {
30
+ const r = ref.toLowerCase();
31
+ return { network: `podster-egress-net-${r}`, out: `podster-egress-out-${r}`, proxy: `podster-egress-${r}` };
32
+ }
33
+ /** The proxy's own limits: smaller than the task container's. **Proposed** figures. */
34
+ export const PROXY_CONTAINER = Object.freeze({ pids: 64, memory: "256m", cpus: "1", ready_checks: 40, ready_check_ms: 250, log_bytes: 256 * 1024, log_entries: 100, log_max_size: "1m", log_max_files: "2" });
35
+ const labels = (ref, home_label, role) => ["--label", `${LABEL_RUN}=${ref}`, "--label", `${LABEL_HOME}=${home_label}`, "--label", `${LABEL_ROLE}=${role}`];
36
+ /** `docker network create` for the run's internal network, or its outbound one (the proxy's alone). */
37
+ export function egressNetworkArgs(ref, home_label, which) {
38
+ const names = egressNames(ref);
39
+ // The internal network's bridge gets no address on the host (`inhibit_ipv4`), so it has no gateway: a task can reach
40
+ // the proxy and nothing on the machine, not even a service listening on all of the host's addresses.
41
+ return which === "internal"
42
+ ? ["network", "create", "--internal", "--opt", "com.docker.network.bridge.inhibit_ipv4=true", ...labels(ref, home_label, ROLE_NETWORK), names.network]
43
+ : ["network", "create", ...labels(ref, home_label, ROLE_NETWORK), names.out];
44
+ }
45
+ /** The one IPv4 subnet `docker network inspect` printed for the run's network, or null. */
46
+ export function subnetOf(stdout) {
47
+ const found = stdout.split(/\s+/).filter((s) => /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\/\d{1,2}$/.test(s));
48
+ return found.length === 1 ? found[0] : null;
49
+ }
50
+ /**
51
+ * `docker run` for the proxy: on the run's internal network as `egress`, hardened, with no mount and no environment of
52
+ * Runner's, running Runner's program over the room's hosts. Every host is checked again here, so nothing but a host name
53
+ * is ever an argument.
54
+ */
55
+ export function proxyRunArgs(o) {
56
+ if (o.hosts.length === 0 || !o.hosts.every(isHostName))
57
+ throw new Error("egress_hosts_invalid");
58
+ if (subnetOf(o.subnet) !== o.subnet)
59
+ throw new Error("egress_subnet_invalid");
60
+ const names = egressNames(o.ref);
61
+ return [
62
+ "run", "--detach", "--pull", "never",
63
+ "--name", names.proxy,
64
+ ...labels(o.ref, o.home_label, ROLE_PROXY),
65
+ "--user", `${o.uid}:${o.gid}`,
66
+ "--cap-drop", "ALL",
67
+ "--security-opt", "no-new-privileges",
68
+ "--read-only",
69
+ "--pids-limit", String(PROXY_CONTAINER.pids),
70
+ "--memory", PROXY_CONTAINER.memory,
71
+ "--memory-swap", PROXY_CONTAINER.memory,
72
+ "--cpus", PROXY_CONTAINER.cpus,
73
+ "--ulimit", "nofile=1024:1024",
74
+ "--ulimit", "core=0",
75
+ "--ipc", "none",
76
+ // Its decision log is bounded on the host's disk, whatever a flood of refused connections writes.
77
+ "--log-driver", "json-file",
78
+ "--log-opt", `max-size=${PROXY_CONTAINER.log_max_size}`,
79
+ "--log-opt", `max-file=${PROXY_CONTAINER.log_max_files}`,
80
+ "--network", names.network,
81
+ "--network-alias", EGRESS_ALIAS,
82
+ "--init",
83
+ o.image,
84
+ "timeout", String(o.max_seconds),
85
+ "node", "--input-type=module", "-e", o.program,
86
+ o.subnet, ...o.hosts,
87
+ ];
88
+ }
89
+ /** Runner's built proxy program, with the call that starts it. Read when a run first needs it. */
90
+ export async function loadProxyProgram(path = new URL("./egress-proxy.js", import.meta.url)) {
91
+ const text = await readFile(path, "utf8");
92
+ if (!/export function main\(/.test(text))
93
+ throw new Error("egress_program_invalid");
94
+ return `${text}\nmain(process.argv.slice(1));\n`;
95
+ }
96
+ const run = (docker, args, signal, maxOutputBytes = 64 * 1024) => docker(args, { signal, timeoutMs: LIMITS.docker_ms, maxOutputBytes });
97
+ /**
98
+ * Opens the run's network and proxy, and waits until the proxy says it's listening. On any failure what it made is
99
+ * left for `closeEgress`, which the sandbox's `kill` runs, and a fixed code is thrown.
100
+ */
101
+ export async function openEgress(o, ref, hosts, max_seconds, signal) {
102
+ const names = egressNames(ref);
103
+ const program = await o.program();
104
+ const step = async (name, args, max) => {
105
+ if (signal.aborted)
106
+ throw new Error("halted");
107
+ const r = await run(o.docker, args, signal, max);
108
+ if (r.code !== 0)
109
+ throw dockerFailure(name, r.code);
110
+ return r;
111
+ };
112
+ await step("egress_network_create", egressNetworkArgs(ref, o.home_label, "internal"));
113
+ await step("egress_out_create", egressNetworkArgs(ref, o.home_label, "out"));
114
+ const inspected = await step("egress_network_inspect", ["network", "inspect", "--format", "{{range .IPAM.Config}}{{.Subnet}} {{end}}", names.network], 4096);
115
+ const subnet = subnetOf(inspected.stdout);
116
+ if (!subnet)
117
+ throw new Error("egress_subnet_invalid");
118
+ await step("egress_run", proxyRunArgs({ ref, image: o.image, uid: o.uid, gid: o.gid, home_label: o.home_label, max_seconds, program, subnet, hosts }), 4096);
119
+ // Listening on the internal network first, at an address it found alone there; only then a route out.
120
+ await waitReady(o, names.proxy, signal);
121
+ await step("egress_connect", ["network", "connect", names.out, names.proxy]);
122
+ }
123
+ async function waitReady(o, proxy, signal) {
124
+ for (let check = 0; check < PROXY_CONTAINER.ready_checks; check++) {
125
+ if (signal.aborted)
126
+ throw new Error("halted");
127
+ const r = await run(o.docker, ["logs", proxy], signal, 4096);
128
+ if (r.code === 0 && r.stdout.split("\n").some((l) => l.trim() === '{"e":"ready"}'))
129
+ return;
130
+ await o.wait(PROXY_CONTAINER.ready_check_ms);
131
+ }
132
+ throw new Error("egress_proxy_not_ready");
133
+ }
134
+ /**
135
+ * The proxy's decisions from its log lines, checked again and counted: each line exactly one of the proxy's own shapes,
136
+ * with a host that is a host name and a code from its fixed list. Anything else is dropped. At most
137
+ * `PROXY_CONTAINER.log_entries` kinds.
138
+ */
139
+ export function tallyProxyLog(stdout) {
140
+ const tally = new Map();
141
+ for (const line of stdout.split("\n")) {
142
+ let event;
143
+ try {
144
+ event = JSON.parse(line);
145
+ }
146
+ catch {
147
+ continue;
148
+ }
149
+ if (typeof event !== "object" || event === null || Array.isArray(event))
150
+ continue;
151
+ const e = event;
152
+ const keys = Object.keys(e).sort().join(",");
153
+ let entry = null;
154
+ if (e.e === "allowed" && keys === "e,host" && isHostName(e.host))
155
+ entry = { outcome: "host_allowed", host: e.host, code: null };
156
+ else if (e.e === "refused" && (keys === "code,e" || keys === "code,e,host") && PROXY_REFUSALS.includes(e.code) && (keys === "code,e" || isHostName(e.host))) {
157
+ entry = { outcome: "host_refused", host: keys === "code,e" ? null : e.host, code: e.code };
158
+ }
159
+ if (!entry)
160
+ continue;
161
+ const key = `${entry.outcome} ${entry.host ?? ""} ${entry.code ?? ""}`;
162
+ const seen = tally.get(key);
163
+ if (seen)
164
+ seen.count += 1;
165
+ else if (tally.size < PROXY_CONTAINER.log_entries)
166
+ tally.set(key, { ...entry, count: 1 });
167
+ }
168
+ return [...tally.values()];
169
+ }
170
+ /** The proxy's decisions, logged by the run's ID. Best effort: a proxy already gone has nothing to say. */
171
+ export async function logProxyDecisions(docker, ref, log) {
172
+ const r = await run(docker, ["logs", egressNames(ref).proxy], undefined, PROXY_CONTAINER.log_bytes);
173
+ if (r.code !== 0)
174
+ return;
175
+ for (const t of tallyProxyLog(r.stdout))
176
+ log("adapter.egress", t.outcome, { run: ref, count: t.count, ...(t.host ? { host: t.host } : {}), ...(t.code ? { code: t.code } : {}) });
177
+ }
178
+ /**
179
+ * Removes each network matching `filters`: attached containers disconnected first if `rm` refuses, then confirmed gone
180
+ * (the ninth real run of #460: `network rm` while a container is attached answers "has active endpoints").
181
+ */
182
+ export async function removeNetworks(docker, filters, wait) {
183
+ const d = (args) => run(docker, args);
184
+ const list = async () => {
185
+ const r = await d(["network", "ls", "--quiet", "--no-trunc", ...filters.flatMap((f) => ["--filter", f])]);
186
+ if (r.code !== 0)
187
+ throw dockerFailure("network_ls", r.code);
188
+ if (r.cut)
189
+ throw new Error("docker_network_ls_cut");
190
+ const ids = r.stdout.split("\n").map((l) => l.trim()).filter((l) => l !== "");
191
+ if (!ids.every((id) => /^[A-Za-z0-9_.-]{1,128}$/.test(id)))
192
+ throw new Error("docker_network_ls_output");
193
+ return ids;
194
+ };
195
+ for (const network of await list()) {
196
+ let r = await d(["network", "rm", "--force", network]);
197
+ if (r.code !== 0) {
198
+ const attached = await d(["network", "inspect", "--format", "{{range .Containers}}{{.Name}} {{end}}", network]);
199
+ if (attached.code !== 0)
200
+ throw dockerFailure("network_inspect", attached.code);
201
+ for (const name of attached.stdout.split(/\s+/).filter((n) => /^[A-Za-z0-9_.-]{1,128}$/.test(n))) {
202
+ const x = await d(["network", "disconnect", "--force", network, name]);
203
+ if (x.code !== 0)
204
+ throw dockerFailure("network_disconnect", x.code);
205
+ }
206
+ r = await d(["network", "rm", "--force", network]);
207
+ if (r.code !== 0)
208
+ throw dockerFailure("network_rm", r.code);
209
+ }
210
+ }
211
+ for (let check = 0; check < REMOVAL_CHECKS; check++) {
212
+ if ((await list()).length === 0)
213
+ return;
214
+ await wait(REMOVAL_CHECK_MS);
215
+ }
216
+ throw new Error("docker_network_lingers");
217
+ }
@@ -0,0 +1,288 @@
1
+ /**
2
+ * Runner's egress proxy (the owner's approval of 2026-11-20): the one way out of a task's container when its room's run
3
+ * policy lists hosts in `rooms[].network`. It runs in its own container per run (`egress-network.ts`), on the run's
4
+ * internal Docker network, whose only other peer is the task's container, and on a second network of the run's own, with
5
+ * a route out, that nothing else joins. This file is the whole program: Runner hands its built text to `node` in the proxy's image as an argument,
6
+ * so the code that decides is exactly the code these tests run, and the image holds only Node, no program and no secret.
7
+ * It imports nothing but Node's own modules, so it runs alone.
8
+ *
9
+ * What it allows, and nothing else:
10
+ * - **HTTPS `CONNECT` only**, to port **443** only: `CONNECT host:443 HTTP/1.1`. Any other method, plain HTTP among
11
+ * them (an absolute-form `GET http://…`), and any other port is refused. The tunnel carries TLS end to end: the proxy
12
+ * never sees inside it and holds no certificate.
13
+ * - **Exact host names** from the room's list, compared in lower case. No wildcard, no suffix match, no IP literal
14
+ * (IPv4, IPv6 or bracketed), no trailing dot.
15
+ * - **Public addresses only.** The proxy resolves the name itself and refuses it if ANY address it resolves to is
16
+ * private, loopback, link-local (cloud metadata among them), shared, multicast, reserved, documentation, or an IPv6
17
+ * form that embeds or translates IPv4 (mapped, NAT64, 6to4, Teredo). It then connects to an address it checked, never
18
+ * to the name again, so a second answer can't swap in a LAN address (DNS rebinding).
19
+ * - **Bounded:** a request head of at most `PROXY_LIMITS.head_bytes`, read within `head_ms`; a connect within
20
+ * `connect_ms`; a tunnel idle for `idle_ms` is closed; at most `tunnels` at once. Its container's own lifetime is the
21
+ * run's.
22
+ * - **Bound to the internal network only:** it listens on its own address in the subnet Runner names, which it has
23
+ * from its start, before Runner attaches its route out. So nothing on that other network can reach it.
24
+ *
25
+ * Its log is one JSON line per decision on standard output: `ready`, `allowed` with the host, or `refused` with a fixed
26
+ * code and the host only when the host is a valid name. Never a path, URL, header, body or address. Runner reads these
27
+ * lines back by the run's ID when it removes the proxy, and checks each again before logging it.
28
+ */
29
+ import { BlockList, connect as netConnect, createServer, isIP } from "node:net";
30
+ import { lookup } from "node:dns/promises";
31
+ import { networkInterfaces } from "node:os";
32
+ /** The proxy's port, inside the run's internal network. */
33
+ export const PROXY_PORT = 3128;
34
+ /** **Proposed** figures. */
35
+ export const PROXY_LIMITS = Object.freeze({ head_bytes: 8 * 1024, head_ms: 10_000, connect_ms: 10_000, resolve_ms: 10_000, idle_ms: 120_000, tunnels: 64, addresses: 64, hosts: 50 });
36
+ export const PROXY_REFUSALS = Object.freeze(["method_not_allowed", "request_invalid", "port_not_allowed", "ip_literal", "host_invalid", "host_not_listed", "address_not_public", "resolve_failed", "connect_failed", "too_many_tunnels", "head_too_large", "head_timeout"]);
37
+ const STATUS = {
38
+ method_not_allowed: "405 Method Not Allowed",
39
+ request_invalid: "400 Bad Request",
40
+ port_not_allowed: "403 Forbidden",
41
+ ip_literal: "403 Forbidden",
42
+ host_invalid: "403 Forbidden",
43
+ host_not_listed: "403 Forbidden",
44
+ address_not_public: "403 Forbidden",
45
+ resolve_failed: "502 Bad Gateway",
46
+ connect_failed: "502 Bad Gateway",
47
+ too_many_tunnels: "503 Service Unavailable",
48
+ head_too_large: "431 Request Header Fields Too Large",
49
+ head_timeout: "408 Request Timeout",
50
+ };
51
+ const LABEL = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/;
52
+ const TLD = /^[a-z](?:[a-z0-9-]{0,61}[a-z0-9])?$/;
53
+ /** A lower-case DNS host name with at least two labels: the same shape the run policy accepts. */
54
+ export function isHostName(v) {
55
+ if (typeof v !== "string" || v.length > 253)
56
+ return false;
57
+ const labels = v.split(".");
58
+ return labels.length >= 2 && labels.every((l) => LABEL.test(l)) && TLD.test(labels[labels.length - 1]);
59
+ }
60
+ /**
61
+ * The request head's target, or why it's refused. Only `CONNECT host:443 HTTP/1.1` (or `HTTP/1.0`) passes; the host
62
+ * is lower-cased and must be a host name, never an IP literal. Headers after the request line are ignored.
63
+ */
64
+ export function parseConnect(head) {
65
+ const line = head.split("\r\n", 1)[0];
66
+ const parts = line.split(" ");
67
+ if (parts.length !== 3 || !/^HTTP\/1\.[01]$/.test(parts[2]))
68
+ return { ok: false, code: "request_invalid", host: null };
69
+ if (parts[0] !== "CONNECT")
70
+ return { ok: false, code: "method_not_allowed", host: null };
71
+ const target = parts[1];
72
+ if (target.startsWith("["))
73
+ return { ok: false, code: "ip_literal", host: null };
74
+ const colon = target.lastIndexOf(":");
75
+ if (colon <= 0)
76
+ return { ok: false, code: "request_invalid", host: null };
77
+ const host = target.slice(0, colon).toLowerCase();
78
+ const port = target.slice(colon + 1);
79
+ if (isIP(host) !== 0 || host.includes(":"))
80
+ return { ok: false, code: "ip_literal", host: null };
81
+ const named = isHostName(host) ? host : null;
82
+ if (!/^\d{1,5}$/.test(port))
83
+ return { ok: false, code: "request_invalid", host: named };
84
+ if (port !== "443")
85
+ return { ok: false, code: "port_not_allowed", host: named };
86
+ if (!named)
87
+ return { ok: false, code: "host_invalid", host: null };
88
+ return { ok: true, host: named };
89
+ }
90
+ /** Whether the room's list names this host exactly. */
91
+ export const isListed = (host, hosts) => hosts.includes(host);
92
+ const NOT_PUBLIC_V4 = [
93
+ ["0.0.0.0", 8], // this network
94
+ ["10.0.0.0", 8], // private
95
+ ["100.64.0.0", 10], // shared address space (carrier-grade NAT; some clouds' metadata)
96
+ ["127.0.0.0", 8], // loopback
97
+ ["169.254.0.0", 16], // link-local, cloud metadata (169.254.169.254)
98
+ ["172.16.0.0", 12], // private
99
+ ["192.0.0.0", 24], // IETF protocol assignments
100
+ ["192.0.2.0", 24], // documentation
101
+ ["192.88.99.0", 24], // 6to4 relay anycast
102
+ ["192.168.0.0", 16], // private
103
+ ["198.18.0.0", 15], // benchmarking
104
+ ["198.51.100.0", 24], // documentation
105
+ ["203.0.113.0", 24], // documentation
106
+ ["224.0.0.0", 4], // multicast
107
+ ["240.0.0.0", 4], // reserved, and the broadcast address
108
+ ];
109
+ /** IPv6 is allowed only in global unicast, 2000::/3, and not in these parts of it. */
110
+ const NOT_PUBLIC_V6 = [
111
+ ["2001::", 23], // IETF protocol assignments, Teredo (2001::/32) and ORCHID among them
112
+ ["2001:db8::", 32], // documentation
113
+ ["2002::", 16], // 6to4, which embeds an IPv4 address
114
+ ["3fff::", 20], // documentation
115
+ ];
116
+ const v4Blocked = new BlockList();
117
+ for (const [net, prefix] of NOT_PUBLIC_V4)
118
+ v4Blocked.addSubnet(net, prefix, "ipv4");
119
+ const v6Global = new BlockList();
120
+ v6Global.addSubnet("2000::", 3, "ipv6");
121
+ const v6Blocked = new BlockList();
122
+ for (const [net, prefix] of NOT_PUBLIC_V6)
123
+ v6Blocked.addSubnet(net, prefix, "ipv6");
124
+ /**
125
+ * Whether an address is one the proxy may connect to: public IPv4 outside every range in `NOT_PUBLIC_V4`, or IPv6 in
126
+ * global unicast outside `NOT_PUBLIC_V6`. Loopback, private, link-local, unique-local, multicast, IPv4-mapped (::ffff:),
127
+ * NAT64 (64:ff9b::) and anything that isn't an address are refused.
128
+ */
129
+ export function isPublicAddress(address) {
130
+ const family = isIP(address);
131
+ if (family === 4)
132
+ return !v4Blocked.check(address, "ipv4");
133
+ if (family === 6)
134
+ return v6Global.check(address, "ipv6") && !v6Blocked.check(address, "ipv6");
135
+ return false;
136
+ }
137
+ /**
138
+ * The addresses to try for a host, IPv4 first, or why none may be used. Refused if the name resolves to nothing, to too
139
+ * many, or to ANY address that isn't public: a name that points even partly at the LAN or the machine is refused whole.
140
+ */
141
+ export function checkAddresses(addresses) {
142
+ if (addresses.length === 0 || addresses.length > PROXY_LIMITS.addresses)
143
+ return { ok: false, code: "resolve_failed" };
144
+ if (!addresses.every(isPublicAddress))
145
+ return { ok: false, code: "address_not_public" };
146
+ return { ok: true, addresses: [...addresses].sort((a, b) => isIP(a) - isIP(b)) };
147
+ }
148
+ /** The proxy's own address in an IPv4 subnet `a.b.c.d/n`, from its interfaces; null if none or more than one. */
149
+ export function addressIn(subnet, interfaces) {
150
+ const m = subnet.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\/(\d{1,2})$/);
151
+ if (!m)
152
+ return null;
153
+ const prefix = Number(m[5]);
154
+ if (prefix < 8 || prefix > 30 || m.slice(1, 5).some((o) => Number(o) > 255))
155
+ return null;
156
+ const net = new BlockList();
157
+ net.addSubnet(m.slice(1, 5).join("."), prefix, "ipv4");
158
+ const found = Object.values(interfaces)
159
+ .flatMap((list) => list ?? [])
160
+ .filter((i) => i.family === "IPv4" && !i.internal && net.check(i.address, "ipv4"))
161
+ .map((i) => i.address);
162
+ return found.length === 1 ? found[0] : null;
163
+ }
164
+ const systemResolve = async (host) => (await lookup(host, { all: true, verbatim: true })).map((a) => a.address);
165
+ const systemDial = (address, port) => netConnect({ host: address, port });
166
+ /** What `promise` resolves to within `ms`, or null if it rejects or takes longer. */
167
+ function within(ms, promise) {
168
+ return new Promise((resolve) => {
169
+ const timer = setTimeout(() => resolve(null), ms);
170
+ promise.then((v) => (clearTimeout(timer), resolve(v)), () => (clearTimeout(timer), resolve(null)));
171
+ });
172
+ }
173
+ /** The proxy's server, not yet listening. Every name in `hosts` must be a host name, or it throws. */
174
+ export function createEgressProxy(deps) {
175
+ const hosts = [...deps.hosts];
176
+ if (hosts.length === 0 || hosts.length > PROXY_LIMITS.hosts || !hosts.every(isHostName))
177
+ throw new Error("egress_hosts_invalid");
178
+ const limits = { ...PROXY_LIMITS, ...deps.limits };
179
+ const resolve = deps.resolve ?? systemResolve;
180
+ const dial = deps.dial ?? systemDial;
181
+ const log = deps.log ?? (() => undefined);
182
+ let open = 0;
183
+ const refuse = (client, code, host) => {
184
+ log(host ? { e: "refused", code, host } : { e: "refused", code });
185
+ client.end(`HTTP/1.1 ${STATUS[code]}\r\nContent-Length: 0\r\nConnection: close\r\n\r\n`);
186
+ // Whatever else the client sends is read and dropped, so its side ends and the socket closes; a socket never read
187
+ // from would wait unread. It goes after a second even if the client never closes its side.
188
+ client.removeAllListeners("data");
189
+ client.on("data", () => undefined);
190
+ client.resume();
191
+ setTimeout(() => client.destroy(), 1_000).unref();
192
+ };
193
+ async function tunnel(client, head, rest) {
194
+ const target = parseConnect(head);
195
+ if (!target.ok)
196
+ return refuse(client, target.code, target.host);
197
+ if (!isListed(target.host, hosts))
198
+ return refuse(client, "host_not_listed", target.host);
199
+ const resolved = await within(limits.resolve_ms, resolve(target.host));
200
+ if (resolved === null)
201
+ return refuse(client, "resolve_failed", target.host);
202
+ const checked = checkAddresses(resolved);
203
+ if (!checked.ok)
204
+ return refuse(client, checked.code, target.host);
205
+ if (client.destroyed)
206
+ return;
207
+ for (const address of checked.addresses) {
208
+ const upstream = await new Promise((done) => {
209
+ const s = dial(address, 443);
210
+ const timer = setTimeout(() => (s.destroy(), done(null)), limits.connect_ms);
211
+ s.once("connect", () => (clearTimeout(timer), done(s)));
212
+ s.once("error", () => (clearTimeout(timer), s.destroy(), done(null)));
213
+ });
214
+ if (!upstream)
215
+ continue;
216
+ if (client.destroyed)
217
+ return void upstream.destroy();
218
+ log({ e: "allowed", host: target.host });
219
+ client.write("HTTP/1.1 200 Connection Established\r\n\r\n");
220
+ if (rest.length > 0)
221
+ upstream.write(rest);
222
+ const close = () => (client.destroy(), upstream.destroy());
223
+ for (const s of [client, upstream]) {
224
+ s.setTimeout(limits.idle_ms, close);
225
+ s.on("error", close);
226
+ s.on("close", close);
227
+ }
228
+ client.pipe(upstream);
229
+ upstream.pipe(client);
230
+ client.resume();
231
+ return;
232
+ }
233
+ refuse(client, "connect_failed", target.host);
234
+ }
235
+ return createServer((client) => {
236
+ client.on("error", () => client.destroy());
237
+ if (open >= limits.tunnels)
238
+ return refuse(client, "too_many_tunnels", null);
239
+ open += 1;
240
+ client.once("close", () => (open -= 1));
241
+ let buffered = Buffer.alloc(0);
242
+ let done = false;
243
+ const timer = setTimeout(() => {
244
+ if (!done) {
245
+ done = true;
246
+ refuse(client, "head_timeout", null);
247
+ }
248
+ }, limits.head_ms);
249
+ const onData = (chunk) => {
250
+ if (done)
251
+ return;
252
+ buffered = Buffer.concat([buffered, chunk]);
253
+ const end = buffered.indexOf("\r\n\r\n");
254
+ if (end < 0 && buffered.length > limits.head_bytes) {
255
+ done = true;
256
+ clearTimeout(timer);
257
+ client.off("data", onData);
258
+ return refuse(client, "head_too_large", null);
259
+ }
260
+ if (end < 0)
261
+ return;
262
+ done = true;
263
+ clearTimeout(timer);
264
+ client.off("data", onData);
265
+ client.pause();
266
+ if (end > limits.head_bytes)
267
+ return refuse(client, "head_too_large", null);
268
+ void tunnel(client, buffered.subarray(0, end).toString("latin1"), buffered.subarray(end + 4)).catch(() => client.destroy());
269
+ };
270
+ client.on("data", onData);
271
+ });
272
+ }
273
+ /**
274
+ * The program's entry, run in the proxy's container as `node --input-type=module -e <this file> <subnet> <host>…`: it
275
+ * listens on its own address in `subnet` only, and logs one JSON line per decision. It exits if it can't.
276
+ */
277
+ export function main(argv) {
278
+ const [subnet, ...hosts] = argv;
279
+ const write = (event) => process.stdout.write(`${JSON.stringify(event)}\n`);
280
+ const address = addressIn(subnet ?? "", networkInterfaces());
281
+ if (!address) {
282
+ process.stderr.write("egress_address_unknown\n");
283
+ process.exit(2);
284
+ }
285
+ const server = createEgressProxy({ hosts, log: write });
286
+ server.on("error", () => process.exit(1));
287
+ server.listen(PROXY_PORT, address, () => write({ e: "ready" }));
288
+ }
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "podster",
3
- "version": "0.0.1-test.8",
3
+ "version": "0.0.1-test.9",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "podster",
9
- "version": "0.0.1-test.8",
9
+ "version": "0.0.1-test.9",
10
10
  "license": "MIT",
11
11
  "dependencies": {
12
12
  "@anthropic-ai/claude-agent-sdk": "0.3.327",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "podster",
3
- "version": "0.0.1-test.8",
3
+ "version": "0.0.1-test.9",
4
4
  "description": "Podster Runner, test pre-release for Podster staging only. Not supported. Not security-reviewed.",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -17,6 +17,7 @@
17
17
  "git/credential-helper",
18
18
  "sandbox/Dockerfile",
19
19
  "claude-image/Dockerfile",
20
+ "proxy-image/Dockerfile",
20
21
  "npm-shrinkwrap.json",
21
22
  "README.md"
22
23
  ],
@@ -0,0 +1,28 @@
1
+ # Runner's egress proxy image (the owner's approval of 2026-11-20). It holds Node and nothing else: no program, no key
2
+ # and no secret. Runner runs `node` in it with its own built `egress-proxy.js` as an argument, one container per run
3
+ # whose room lists hosts in the run policy's rooms[].network, on the run's internal network and on an outbound network
4
+ # of the run's own that nothing else joins. Runner runs it only by its image ID, written to `proxy-image` in Runner's
5
+ # home, and builds and pins it itself when the pin is missing:
6
+ #
7
+ # docker build -q apps/runner/proxy-image > ~/.podster-runner/proxy-image
8
+ #
9
+ # Reproducible like the task image: the same debian base pinned by digest, and the same official Node.js 22.23.5 LTS
10
+ # tarball as apps/runner/sandbox, for the build's architecture, checked against the SHA-256 written here (read
11
+ # 2026-11-20 from the release's SHASUMS256.txt, whose signature by a Node release key was checked first). The build never
12
+ # trusts a checksum file it fetches, and installs no Debian package. Only the `node` binary is kept: no npm, no npx.
13
+ # Keeping it patched means moving this pin, and the task image's, to a newer Node release.
14
+ FROM debian:bookworm-slim@sha256:734a72b3d6142a71993b4bc580ca01d8ca687f77a2c422d96a961d3376b179bc AS fetch
15
+ ADD https://nodejs.org/dist/v22.23.5/node-v22.23.5-linux-arm64.tar.gz /fetch/linux-arm64.tar.gz
16
+ ADD https://nodejs.org/dist/v22.23.5/node-v22.23.5-linux-x64.tar.gz /fetch/linux-x64.tar.gz
17
+ RUN cd /fetch \
18
+ && echo "8bd3dc69eee8f3f226315a80d7d1d4faccf217a4c8fae500168ac2e38f3bdba3 linux-arm64.tar.gz" > sums \
19
+ && echo "c54118104acc524633b5abe106bbf44a53126ec8b4e5fa105cb92b5d7de8a1a1 linux-x64.tar.gz" >> sums \
20
+ && sha256sum -c sums \
21
+ && case "$(dpkg --print-architecture)" in arm64) arch=arm64 ;; amd64) arch=x64 ;; *) exit 1 ;; esac \
22
+ && mkdir /node \
23
+ && tar -xzf "linux-$arch.tar.gz" -C /node --strip-components=1 --no-same-owner \
24
+ && install -D -m 0755 /node/bin/node /out/node
25
+
26
+ FROM debian:bookworm-slim@sha256:734a72b3d6142a71993b4bc580ca01d8ca687f77a2c422d96a961d3376b179bc
27
+ COPY --from=fetch /out/node /usr/local/bin/node
28
+ CMD ["sleep", "60"]
@@ -1,17 +1,43 @@
1
1
  # Runner's task image (M7 step 9(b)). Every task command runs in a container of it, through Runner's own tools: cat,
2
2
  # tee, mkdir, rg, ls and kill (to end what a shell command leaves running) and, when the run policy names the shell,
3
- # /bin/sh. Reproducible (item 12 of the deep review of #460): the base is pinned by digest (debian:bookworm-slim's
4
- # index, read 2026-11-18), and the packages come from one fixed snapshot.debian.org timestamp at exact versions.
5
- # Runner runs the built image only by its image ID, written to `task-image` in Runner's home:
3
+ # /bin/sh, under which a task's commands can also run node, npm and npx (Node.js 22.23.5 LTS, in /usr/local).
4
+ # Reproducible (item 12 of the deep review of #460): the base is pinned by digest (debian:bookworm-slim's index, read
5
+ # 2026-11-18), the packages come from one fixed snapshot.debian.org timestamp at exact versions, and Node is the
6
+ # official nodejs.org linux tarball for the build's architecture, checked against a SHA-256 written here (read
7
+ # 2026-11-20 from the release's SHASUMS256.txt, whose signature by a Node release key was checked first). The build
8
+ # never trusts a checksum file it fetches. Runner runs the built image only by its image ID, written to `task-image`
9
+ # in Runner's home:
6
10
  #
7
11
  # docker build -q apps/runner/sandbox > ~/.podster-runner/task-image
8
12
  #
9
- # Building it fetches Debian's packages, so it is the owner's to run. Nothing here holds a key or a secret. apt checks
10
- # the snapshot's signed Release file; plain HTTP is what the slim image can reach before ca-certificates exists.
13
+ # Building it fetches Debian's packages and Node, so it is the owner's to run. Nothing here holds a key or a secret.
14
+ # apt checks the snapshot's signed Release file; plain HTTP is what the slim image can reach before ca-certificates
15
+ # exists, and Docker's own ADD fetches Node over HTTPS.
16
+ #
17
+ # npm and npx run as Runner's non-root task user, with HOME at /work (the task's folder) and the rest of the file
18
+ # system read-only. The global npmrc below sends npm's cache and logs to /tmp (a tmpfs, noexec, which suits a cache)
19
+ # and its global prefix to /work/.npm-global, so nothing npm writes needs a writable /usr/local. The container has no
20
+ # network yet, so `npm install` and an npx of a package not already in the task's node_modules fail.
21
+ FROM debian:bookworm-slim@sha256:734a72b3d6142a71993b4bc580ca01d8ca687f77a2c422d96a961d3376b179bc AS fetch
22
+ ADD https://nodejs.org/dist/v22.23.5/node-v22.23.5-linux-arm64.tar.gz /fetch/linux-arm64.tar.gz
23
+ ADD https://nodejs.org/dist/v22.23.5/node-v22.23.5-linux-x64.tar.gz /fetch/linux-x64.tar.gz
24
+ RUN cd /fetch \
25
+ && echo "8bd3dc69eee8f3f226315a80d7d1d4faccf217a4c8fae500168ac2e38f3bdba3 linux-arm64.tar.gz" > sums \
26
+ && echo "c54118104acc524633b5abe106bbf44a53126ec8b4e5fa105cb92b5d7de8a1a1 linux-x64.tar.gz" >> sums \
27
+ && sha256sum -c sums \
28
+ && case "$(dpkg --print-architecture)" in arm64) arch=arm64 ;; amd64) arch=x64 ;; *) exit 1 ;; esac \
29
+ && mkdir /node \
30
+ && tar -xzf "linux-$arch.tar.gz" -C /node --strip-components=1 --no-same-owner \
31
+ && rm -rf /node/include /node/share /node/CHANGELOG.md /node/README.md \
32
+ && printf 'cache=/tmp/.npm\nprefix=/work/.npm-global\nupdate-notifier=false\nfund=false\naudit=false\n' > /node/etc-npmrc
33
+
11
34
  FROM debian:bookworm-slim@sha256:734a72b3d6142a71993b4bc580ca01d8ca687f77a2c422d96a961d3376b179bc
12
35
  RUN rm -f /etc/apt/sources.list.d/debian.sources \
13
36
  && echo "deb [check-valid-until=no] http://snapshot.debian.org/archive/debian/20261101T000000Z bookworm main" > /etc/apt/sources.list \
14
37
  && apt-get -o Acquire::Check-Valid-Until=false update \
15
38
  && apt-get install -y --no-install-recommends ripgrep=13.0.0-4+b2 procps=2:4.0.2-3 libproc2-0=2:4.0.2-3 \
16
39
  && rm -rf /var/lib/apt/lists/*
40
+ COPY --from=fetch /node/bin /usr/local/bin
41
+ COPY --from=fetch /node/lib /usr/local/lib
42
+ COPY --from=fetch /node/etc-npmrc /usr/local/etc/npmrc
17
43
  CMD ["sleep", "60"]