@buildanagent/harness 0.1.0-alpha.28 → 0.1.0-alpha.29

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.
Files changed (90) hide show
  1. package/README.md +111 -5
  2. package/dist/context/file-spill.d.ts +11 -1
  3. package/dist/context/file-spill.js +23 -8
  4. package/dist/context/file-spill.js.map +1 -1
  5. package/dist/context/spill.d.ts +5 -1
  6. package/dist/context/spill.js +6 -2
  7. package/dist/context/spill.js.map +1 -1
  8. package/dist/credentials/allowlist.d.ts +22 -2
  9. package/dist/credentials/allowlist.js +74 -17
  10. package/dist/credentials/allowlist.js.map +1 -1
  11. package/dist/credentials/egress-policy.d.ts +69 -0
  12. package/dist/credentials/egress-policy.js +170 -0
  13. package/dist/credentials/egress-policy.js.map +1 -0
  14. package/dist/credentials/egress-proxy.d.ts +13 -1
  15. package/dist/credentials/egress-proxy.js +179 -11
  16. package/dist/credentials/egress-proxy.js.map +1 -1
  17. package/dist/credentials/git-route.d.ts +68 -0
  18. package/dist/credentials/git-route.js +288 -0
  19. package/dist/credentials/git-route.js.map +1 -0
  20. package/dist/credentials/index.d.ts +5 -1
  21. package/dist/credentials/index.js +5 -1
  22. package/dist/credentials/index.js.map +1 -1
  23. package/dist/credentials/scrub.d.ts +7 -0
  24. package/dist/credentials/scrub.js +22 -0
  25. package/dist/credentials/scrub.js.map +1 -1
  26. package/dist/errors.d.ts +9 -5
  27. package/dist/errors.js +8 -4
  28. package/dist/errors.js.map +1 -1
  29. package/dist/sandbox/base.d.ts +11 -1
  30. package/dist/sandbox/base.js +14 -0
  31. package/dist/sandbox/base.js.map +1 -1
  32. package/dist/sandbox/docker/index.d.ts +8 -2
  33. package/dist/sandbox/docker/index.js +63 -14
  34. package/dist/sandbox/docker/index.js.map +1 -1
  35. package/dist/sandbox/errors.d.ts +30 -2
  36. package/dist/sandbox/errors.js +36 -1
  37. package/dist/sandbox/errors.js.map +1 -1
  38. package/dist/sandbox/host-files.d.ts +2 -0
  39. package/dist/sandbox/host-files.js +10 -0
  40. package/dist/sandbox/host-files.js.map +1 -1
  41. package/dist/sandbox/index.d.ts +6 -4
  42. package/dist/sandbox/index.js +5 -3
  43. package/dist/sandbox/index.js.map +1 -1
  44. package/dist/sandbox/policy.d.ts +49 -0
  45. package/dist/sandbox/policy.js +149 -0
  46. package/dist/sandbox/policy.js.map +1 -0
  47. package/dist/sandbox/process.js +1 -1
  48. package/dist/sandbox/process.js.map +1 -1
  49. package/dist/sandbox/srt/index.d.ts +5 -2
  50. package/dist/sandbox/srt/index.js +27 -8
  51. package/dist/sandbox/srt/index.js.map +1 -1
  52. package/dist/sandbox/srt/settings.d.ts +17 -5
  53. package/dist/sandbox/srt/settings.js +53 -0
  54. package/dist/sandbox/srt/settings.js.map +1 -1
  55. package/dist/sandbox/types.d.ts +41 -4
  56. package/dist/sandbox/types.js.map +1 -1
  57. package/dist/testing/fake-sandbox.d.ts +21 -3
  58. package/dist/testing/fake-sandbox.js +157 -8
  59. package/dist/testing/fake-sandbox.js.map +1 -1
  60. package/dist/testing/sandbox-conformance.js +108 -1
  61. package/dist/testing/sandbox-conformance.js.map +1 -1
  62. package/dist/tools/builtins/bash.d.ts +9 -0
  63. package/dist/tools/builtins/bash.js +75 -0
  64. package/dist/tools/builtins/bash.js.map +1 -0
  65. package/dist/tools/builtins/builtins.d.ts +38 -0
  66. package/dist/tools/builtins/builtins.js +48 -0
  67. package/dist/tools/builtins/builtins.js.map +1 -0
  68. package/dist/tools/builtins/descriptions.d.ts +69 -0
  69. package/dist/tools/builtins/descriptions.js +94 -0
  70. package/dist/tools/builtins/descriptions.js.map +1 -0
  71. package/dist/tools/builtins/fetch.d.ts +12 -0
  72. package/dist/tools/builtins/fetch.js +157 -0
  73. package/dist/tools/builtins/fetch.js.map +1 -0
  74. package/dist/tools/builtins/files.d.ts +27 -0
  75. package/dist/tools/builtins/files.js +274 -0
  76. package/dist/tools/builtins/files.js.map +1 -0
  77. package/dist/tools/builtins/paths.d.ts +30 -0
  78. package/dist/tools/builtins/paths.js +62 -0
  79. package/dist/tools/builtins/paths.js.map +1 -0
  80. package/dist/tools/builtins/results.d.ts +15 -0
  81. package/dist/tools/builtins/results.js +31 -0
  82. package/dist/tools/builtins/results.js.map +1 -0
  83. package/dist/tools/builtins/search.d.ts +18 -0
  84. package/dist/tools/builtins/search.js +217 -0
  85. package/dist/tools/builtins/search.js.map +1 -0
  86. package/dist/tools/index.d.ts +6 -2
  87. package/dist/tools/index.js +5 -2
  88. package/dist/tools/index.js.map +1 -1
  89. package/llms.txt +34 -0
  90. package/package.json +5 -5
package/README.md CHANGED
@@ -60,7 +60,7 @@ const result = await sandbox.exec(["pnpm", "test"], { env: spawnEnv([]), signal:
60
60
  console.log("denied" in result ? result.denied.reason : result.exitCode);
61
61
  ```
62
62
 
63
- `exec` takes an executable and its arguments, with no shell, and resolves with the exit code and output. A failing command is a result, not an error, and a command the policy refuses resolves with `{ denied }`. A command that runs past `timeoutMs` stops with exit code 124, and one the system can't find gives 127. A command that a signal killed gives 128 plus the signal's number, with `signal` naming it. Output past `maxOutputBytes` (8 MiB for each stream by default) is dropped, and the result says `truncated: true`.
63
+ `exec` takes an executable and its arguments, with no shell, and resolves with the exit code and output. A failing command is a result, not an error, and a command the policy refuses resolves with `{ denied }`. A command that runs past `timeoutMs` stops with exit code 124 and `timedOut: true`, so a command that exits with 124 itself is told apart, and one the system can't find gives 127. A command that a signal killed gives 128 plus the signal's number, with `signal` naming it. Output past `maxOutputBytes` (8 MiB for each stream by default) is dropped, and the result says `truncated: true`.
64
64
 
65
65
  The `none` backend starts each command in its own process group. A timeout, an abort or `dispose()` therefore kills the command and everything it started, and `exec` settles even when a background process still holds the output pipes.
66
66
 
@@ -101,7 +101,7 @@ The policy decides what is mounted, at the same path inside as outside. A write
101
101
 
102
102
  The workspace must lie inside a root. The backend never mounts the Docker socket: a root that resolves to `/`, or that holds the daemon's socket (`/var/run/docker.sock`, `/run/docker.sock` or the one `dockerHost` names), is refused.
103
103
 
104
- The container has no network, so a command reaches a host only through `proxySocket`: a Unix socket on the host, mounted at `DOCKER_PROXY_SOCKET_PATH` (`/run/harness/proxy.sock`), that the credential proxy listens on. The program in the image has to speak to that socket itself. Without `proxySocket`, no host is reachable, including the ones the policy allows.
104
+ The container has no network, so a command reaches a host only through `proxySocket`: a Unix socket on the host, mounted at `DOCKER_PROXY_SOCKET_PATH` (`/run/harness/proxy.sock`), that the credential proxy listens on. The program in the image has to speak to that socket itself. Without `proxySocket`, no host is reachable, including the ones the policy allows, so `provision()` refuses a policy whose `network.allow` names one.
105
105
 
106
106
  `provision()` starts the `docker` client with a clean environment: a `PATH`, a private empty `HOME`, and `DOCKER_HOST` when the option or the host sets one. It never copies the host's environment. A missing client, a daemon that doesn't answer or an image that isn't on the host throws `SandboxUnavailableError` and runs nothing.
107
107
 
@@ -119,6 +119,30 @@ Five limits are worth knowing:
119
119
 
120
120
  The same opt-in tests run the conformance suite and the lock-down cases against a real daemon, with a pinned Node image, and fail on a skipped case. Without Docker, the other tests check the flags and the unavailable paths with a fake client.
121
121
 
122
+ ## A backend that claims a stop reads its policy back, and one that can't resume says so
123
+
124
+ A backend that claims a stop reads back the policy it applied, and `provision()` compares it with the request before it returns. `srtSandbox()` rereads its settings file from disk, and `dockerSandbox()` reports the mounts and flags it creates each container with. If any field differs, `provision()` disposes the sandbox and throws `SandboxPolicyMismatchError`, so nothing runs under a policy you didn't ask for. The check treats `readRoots`, `writeRoots`, `network.allow` and `network.deny` as sets, and a narrower policy throws too.
125
+
126
+ One gap remains: a `denyWrite` that names a write root exactly. Docker mounts such a root read-only, but the read-back counts the caller's `denyWrite` as part of the request, so it still reads back as a write root and `provision()` accepts it. Nothing in that root is writable inside the container.
127
+
128
+ The error's code is `sandbox_policy_mismatch`, and its `field` names the first field that differs, such as `network.allow`. The message never holds a path or a host. The code below catches the error and prints that field:
129
+
130
+ ```ts
131
+ import { SandboxPolicyMismatchError } from "@buildanagent/harness/sandbox";
132
+ import { srtSandbox } from "@buildanagent/harness/sandbox/srt";
133
+
134
+ const attempt = srtSandbox().provision({ root: "/work/repo" }, policy);
135
+ await attempt.catch((error) => console.log(error instanceof SandboxPolicyMismatchError ? error.field : error));
136
+ ```
137
+
138
+ A client that claims a stop but gives its sandbox no read-back, or one whose read-back fails, makes `provision()` throw the same error, with the field `readBack`. `noneSandbox()` claims no stop, so it needs none.
139
+
140
+ `stopsFor(tier, policy)` computes the stops that an applied policy delivers. Only a `microvm` stops a `hostile_process`. A policy that allows `*`, `0.0.0.0/0` or `::/0` loses `exfiltration`, and a root of `/` loses `mistakes`. A client that claims a stop its applied policy doesn't deliver is refused with the field `stops`, and the message names the cause, such as that the policy allows all hosts, so the sandbox cannot stop exfiltration. `srtSandbox()` and `dockerSandbox()` both claim `mistakes` and `exfiltration`, so `provision()` refuses a policy that allows every host on either.
141
+
142
+ A hosted backend can also list `capabilities`: `resume`, `snapshot` and `pause`. Call them through `resumeSandbox(client, id, policy)`, `snapshotSandbox(client, sandbox)` and `pauseSandbox(client, sandbox)`. A resume reads the policy back as `provision()` does and sets the handle's `stops` from it. Unlike `provision()`, a resume that finds a mismatch throws and leaves the sandbox alone, because disposing it would destroy a paused sandbox and its work: the caller decides whether to dispose. A capability the client doesn't list rejects with `SandboxUnsupportedError`, code `sandbox_unsupported`. The `none`, `srt` and Docker backends list none, so a resume, a snapshot or a pause on them is always refused.
143
+
144
+ None of this authenticates a caller. The read-back shows that the sandbox applies the policy you asked for, and the host still decides who may ask.
145
+
122
146
  ## The egress proxy keeps every credential outside the sandbox
123
147
 
124
148
  `startEgressProxy({ allow, routes, log })` from `./credentials` starts a proxy on `127.0.0.1`, or on a Unix socket you give it (`socketPath`, which is what `dockerSandbox`'s `proxySocket` mounts). Nothing leaves the sandbox except through it. It refuses everything that isn't on its allowlist with a 403, and it writes one log record for each request: the host, the method, the status and the bytes, never a header or a body. Give the sandbox `proxy.url` as `HTTPS_PROXY`. On a Unix socket, `proxy.url` is `unix:<path>`, which is not a proxy URL, and the program inside the container connects to the socket itself.
@@ -144,6 +168,48 @@ Four limits are worth knowing:
144
168
 
145
169
  The package's tests run the proxy against a real HTTPS server on loopback, with a self-signed certificate that only the test trusts and a table in place of DNS.
146
170
 
171
+ ## An egress policy names a credential and never holds one
172
+
173
+ `EgressPolicy` is plain data: an `allow` list of exact host names, and `routes` that each name the credential they inject. `compileEgressPolicy(policy, { secret })` checks it and returns the `allow` and `routes` that `startEgressProxy()` takes. The compiled routes call `secret(name)` for each request, on the host, so a rotated credential is used at once. The code below compiles one git route and starts a proxy with it:
174
+
175
+ ```ts
176
+ import { compileEgressPolicy, startEgressProxy } from "@buildanagent/harness/credentials";
177
+
178
+ const route = { kind: "git", route: "git", host: "github.com", repositories: ["acme/app"], pushRefs: ["refs/heads/agent/*"], credential: "GITHUB_TOKEN" } as const;
179
+ const compiled = compileEgressPolicy({ allow: [], routes: [route] }, { secret: async (name) => process.env[name] ?? "" });
180
+ const proxy = await startEgressProxy({ ...compiled, log: audit });
181
+ ```
182
+
183
+ The compiler refuses anything that isn't plainly allowed, with the code `invalid_egress_options`, and its message names the place of the entry and never its value:
184
+
185
+ - a field that a route kind doesn't have, such as `secret` or `token`;
186
+ - a string that looks like a credential: a value, or a whitespace-separated token, that starts with `ghp_` or `sk-` and has a long enough body, or a whole 20-character AWS key id. A name that merely contains a prefix, like the repository `sk-labs/app`, is allowed;
187
+ - a credential name that isn't upper case;
188
+ - a wildcard or an address literal in `allow` or in a route's `host`;
189
+ - a git route whose `host` is also in `allow`, or is the host of any other route, because a tunnel or a header route to that host would go around the ref filter. `startEgressProxy()` enforces the same rule on routes it is given directly.
190
+
191
+ The scan for credential-shaped strings is defence in depth. The field allowlist and the upper-case credential name are the real guards, and a token that starts mid-word, like `acme/ghp_…`, or is base64-encoded passes the scan.
192
+
193
+ The policy holds names, the proxy reads each value on the host, and the sandbox sees only a random placeholder, so no credential value enters a sandbox. The policy does not authenticate a caller: any process that knows the placeholder can use the route. `EgressPolicy` is not yet part of `SandboxPolicy`, and `srtSandbox()` keeps its own proxy.
194
+
195
+ ## A git route lets a push reach listed branches and nothing else
196
+
197
+ A route of kind `git` carries git over HTTPS for the repositories it lists, and nothing else. The sandbox's remote is `http://x-access-token:<placeholder>@127.0.0.1:<port>/git/acme/app.git`, where `git` is the route's name and the placeholder is `proxy.sentinels.git`. The proxy swaps the placeholder for the credential and sends it to the host in HTTP Basic, with the route's `username`, which is `x-access-token` unless you set one. A request with no credential gets a 401 challenge, so git asks for one.
198
+
199
+ A push is checked before anything is forwarded. The proxy reads the command list at the start of the body and refuses the whole push when one command breaks a rule:
200
+
201
+ - a deletion, a tag, or a ref that no `pushRefs` pattern matches;
202
+ - a push certificate, a body with a `content-encoding` other than `identity`, or a pkt-line that is malformed or not UTF-8;
203
+ - a command list over 64 KiB (`GIT_MAX_COMMAND_BYTES`) or over 64 commands (`GIT_MAX_COMMANDS`).
204
+
205
+ When a push is bigger than git's `http.postBuffer` (1 MiB by default), git first sends a probe whose body is a single flush packet. The proxy treats that body as an empty command list and forwards it, and it refuses any byte after the flush.
206
+
207
+ The command list has two timeouts. `idleTimeoutMs` restarts on each chunk, so a stalled client is cut off and a slow one is not. It takes a whole number from 0 to 2,147,483,647, and 0 turns the idle timeout off, as for a socket's timeout; any other value makes `startEgressProxy()` throw `invalid_egress_options`. `pushCheckTimeoutMs` never restarts, and it covers the command list only, not the pack, so a client that sends one byte at a time is cut off too. Its default is 60,000 ms, and it takes a whole number from 1 to 2,147,483,647. The 64 KiB limit applies however the list is split across chunks. A refused push gets a 403 with `Connection: close`, and the proxy stops reading the rest of the body: it discards what is already in flight, up to 1 MiB or for 1 second, then ends the response, so a large pack cannot keep the connection open.
208
+
209
+ A pattern is a branch such as `refs/heads/main`, or a prefix such as `refs/heads/agent/*`, which matches the branches under `agent/` and not `agent` itself. A route with no `pushRefs` refuses every push, and one with `fetch` left out refuses every fetch.
210
+
211
+ A route has two limits. With `fetch` on, the sandbox can read every ref of a listed repository, because a fetch is allowed or refused for the whole route. And a route filters git's HTTP requests only, so it says nothing about what a pushed commit contains. The package's tests run a real `git push` over loopback to a fake GitHub on HTTPS: a push to an agent branch arrives with the token, and a push to `main`, a tag and a deletion never reach it.
212
+
147
213
  ## Every spawned process gets a cleared environment
148
214
 
149
215
  `spawnEnv(allow, extra)` builds the whole environment for a spawned process. It returns `PATH`, a fresh temp `HOME`, `TMPDIR` and `LANG`, the parent variables that `allow` names and the parent has, and `extra`. Nothing else is copied, so a key set in the parent never reaches a child. The caller removes the temp `HOME` when the process is done; an `extra.HOME` replaces it and no folder is made. `PATH` is the parent's with every entry that isn't absolute removed, so a `.` can't run a program from the working directory, and `TMPDIR` is the shared system temp directory, not a private one.
@@ -158,9 +224,9 @@ The check goes by name and can't catch a credential under an unremarkable one, s
158
224
 
159
225
  ## Test a sandbox with the fake and the conformance suite
160
226
 
161
- `./testing` has `fakeSandbox()`, a sandbox in memory that enforces the policy it is given and records every `exec`, but runs no program: it understands `echo`, `env`, `cat`, `write`, `true`, `false`, `sleep` and `net-probe`. It claims tier `os`, because it enforces file roots and the network allowlist, but it confines no real process.
227
+ `./testing` has `fakeSandbox()`, a sandbox in memory that enforces the policy it is given and records every `exec`, but runs no program: it understands `echo`, `env`, `cat`, `write`, `true`, `false`, `sleep` and `net-probe`, plus `find`, `grep` and `bash -c` or `sh -c` with one of those commands as the script, which is what the built-in tools run. It claims tier `os`, because it enforces file roots and the network allowlist, but it confines no real process.
162
228
 
163
- `runSandboxConformance(factory)` pins the interface for every backend. Its cases check that a file reads back as written, that `exec` reports exit codes and output, that the environment holds only the variables given, that an aborted signal rejects and a timeout stops with 124, and that `dispose` ends the sandbox and any command still running. When the caller passes `processTree`, a case also checks that an abort or timeout ends the command's whole process tree. A backend that adds variables of its own, such as proxy settings, lists them in `addedEnvironment`, and the environment case accepts those and no others.
229
+ `runSandboxConformance(factory)` pins the interface for every backend. Its cases check that a file reads back as written, that `exec` reports exit codes and output, that the environment holds only the variables given, that an aborted signal rejects and a timeout stops with 124 and `timedOut: true`, and that `dispose` ends the sandbox and any command still running. When the caller passes `processTree`, a case also checks that an abort or timeout ends the command's whole process tree. A backend that adds variables of its own, such as proxy settings, lists them in `addedEnvironment`, and the environment case accepts those and no others.
164
230
 
165
231
  A case that needs enforcement runs only when the backend's `stops` claim it:
166
232
 
@@ -169,6 +235,8 @@ A case that needs enforcement runs only when the backend's `stops` claim it:
169
235
  - a working directory outside the workspace;
170
236
  - the network, where the caller passes two hosts it controls, such as two loopback listeners: the allowed one must be reached and the blocked one must not.
171
237
 
238
+ Three more cases check the read-back and the capabilities: a backend that claims a stop reads its policy back equal to the request, a read-back that differs throws `sandbox_policy_mismatch` and disposes the sandbox, and a capability the backend doesn't list is refused with `sandbox_unsupported`. `fakeSandbox({ applied })` applies a policy in place of the request, as a provider that widens it would.
239
+
172
240
  `none` passes the rest and skips those with a reason, and a backend that can't start skips every case with its reason and fails none. The suite tells errors apart by `isHarnessError()` and the error's `code`, so a backend bundled separately from the suite still passes. `sandboxConformanceCases(factory)` returns the same cases one by one, for a runner that wants a test for each.
173
241
 
174
242
  ## One registry names, defers and wraps every tool
@@ -185,6 +253,44 @@ A case that needs enforcement runs only when the backend's `stops` claim it:
185
253
  - **Output trust.** A tool's `outputTrust` is `untrusted` for an MCP tool and for a tool registered with `remoteAgent: true`, `trusted` otherwise, and the value a registration declares wins. `approvalReuse` defaults to `both`, and `pattern` records whether the tool runs `in_process` or by a `client_request`.
186
254
  - **Preamble size.** `preambleTokens({ system })` estimates the tokens a request carries before any message: the system prompt and every `direct` tool. A `deferred` tool adds nothing, which is why the default for MCP is `deferred`. A `RegisteredTool` that `register()` returns is a snapshot, so call `get()` after `setExposure()` to read the current exposure.
187
255
 
256
+ ## The built-in tools reach files, commands and the web only through the sandbox and the egress proxy
257
+
258
+ `builtinTools(sandbox, proxy, { root, policy })` returns up to seven tools for one provisioned sandbox: `read`, `write`, `edit`, `bash`, `grep`, `glob` and `fetch`, which needs a proxy, so six without one. No tool touches the host. Files go through the sandbox's `readFile()` and `writeFile()`, commands through its `exec()`, and the web through the proxy's `fetch()`, so the backend and the allowlist decide what each call can reach. This coding agent binds them to a workspace and lets `read` open the write cap's spill files:
259
+
260
+ ```ts
261
+ const sandbox = await client.provision({ root: workspace }, policy);
262
+ const spill = fileSpillStore({ dir: spillDir });
263
+ const registry = createToolRegistry();
264
+ const spills = (path: string) => spill.read(key, path);
265
+ for (const tool of builtinTools(sandbox, proxy, { root: workspace, policy, spills })) registry.register(tool);
266
+ const harness = createHarness({ registry, model, system: SYSTEM, context: createContextPolicy({ spill }) });
267
+ ```
268
+
269
+ Pass the `root` and `policy` the sandbox was provisioned with, because the sandbox interface reports neither. Leave `proxy` out, as `undefined`, and the set has no `fetch`. `env` is the whole environment of every command the tools run; it defaults to a `PATH` and a `LANG` alone, and on Node you pass `spawnEnv()`.
270
+
271
+ Each tool's contract:
272
+
273
+ - **`read`** takes `path` or `file_path`, relative to `root` or absolute, `offset` (the first line, from 1), `limit` (a line count) and `column` (where to start in the first line, from 1, to read on in a line too long for a page). With none of the three, it returns the whole file up to 2,000 lines and 32 KiB, and a longer file or a page ends with a line that names the next `offset`. The write cap counts bytes after JSON escaping, so `read` counts 32 KiB the same way (a quote, a backslash or a newline costs two bytes). A page therefore always passes the default 64 KiB cap whole. A line longer than a page is shown in parts, and each part's last line names the `offset` and `column` where the next starts, so a cut result that is one long line can still be read in full. Only an absolute path is offered to the `spills` reader, and a path it knows is served from the spill; a relative path always reads the workspace. A binary file is an error result.
274
+ - **`write`** takes a path and `content`, makes the folders and replaces the whole file.
275
+ - **`edit`** takes a path, `old_string` and `new_string`. `old_string` must occur exactly once: no match, or two matches without `replace_all: true`, returns an error result and leaves the file unchanged. `new_string` is inserted as written, so `$&` stays `$&`. A byte order mark is kept, and a binary file or one that is not UTF-8 is an error result, left unchanged, because writing it back as text would corrupt it.
276
+ - **`bash`** runs `command` as `bash -c` inside the sandbox, from `root`, with a timeout of `timeout_ms` (default 120,000, at most 600,000). The model reads the output, standard error and exit code. A timeout or a denial is an error result, and each stream keeps at most 1 MiB. Only the sandbox's `timedOut` flag marks a timeout, so a command that exits with 124 itself reads as that exit code.
277
+ - **`grep`** searches files for `pattern`, an extended regular expression, below `path` (default `root`), and prints `path:line:text`. `glob` narrows the files: a glob with no `/`, such as `*.ts`, matches the file name, and any other matches the path below `path`. `ignore_case` ignores case. Binary files are skipped (`grep -I`).
278
+
279
+ The matching lines stop at 1 MiB, across every `grep` command the call runs, and a result cut there says so, so the model can narrow the search. If the first matching line alone passes 1 MiB, the result still says that lines match, names the file and line, and suggests a narrower search or `read`; it never reports "no match". A file `grep` can't read, or a folder `find` can't list, keeps the matches found elsewhere and adds a line quoting the error; the call fails only when nothing matched.
280
+ - **`glob`** lists the files below `path` whose path matches `pattern`, sorted. `*` matches inside one name, `**` across folders and `?` one character.
281
+ - **`fetch`** sends a GET for an `https` `url` through `proxy.fetch()`. It returns the status line, the final URL, any `location`, the content type and, for a text body, up to 1 MiB of it. A body of another type is left out and reported by its size. Every secret the proxy knows is replaced by `[REDACTED]`, and a body cut at 1 MiB also loses any start of a secret left at its end.
282
+ - A text body is read in the charset its content type names, when `TextDecoder` knows that label, and as UTF-8 otherwise.
283
+ - A body with no content type, or with a charset label `TextDecoder` does not know, is shown only when it reads as UTF-8 text with no NUL byte.
284
+ - A request that takes over 30 seconds returns an error, as do a host off the allowlist and a URL that is not `https`. Plain HTTP is refused, which keeps the model off the proxy's credential routes.
285
+
286
+ **Paths are checked before the sandbox sees them.** `read`, `grep` and `glob` accept a path inside a read or write root, and `write` and `edit` only inside a write root. A path with a backslash is refused, because the workspace is POSIX, where `\` is part of a name, while the permission rules read it as a separator. The check joins a relative path to `root` and removes `.` and `..`, so `../etc/passwd` and `/etc/passwd` are refused without a sandbox call, and the sandbox gets the checked path. A symlink is invisible to a check on text, so the sandbox's own check of the real path is the second line: its denial reaches the model as an error result. `grep` and `glob` list files with `find`, which never follows a symlink, and skip folders named `.git` and `node_modules` below the folder searched, so a search of `node_modules` itself still works.
287
+
288
+ **Big results pass the write cap like any other.** The tools cap nothing themselves: the context policy's write cap cuts a long result and spills its full text, and `read` with `spills` opens that spill. Bind `spills` to one session, as `fileSpillStore().read(key, path)` already does, so one session cannot read another's spills.
289
+
290
+ **Scheduling follows what each tool changes.** `read`, `grep`, `glob` and `fetch` are first-party and read-only, so their calls in one step run together. `write` and `edit` declare a write, so they wait for the file calls before them, and `bash` runs its step one call at a time. A crash during a write makes the next turn report its outcome as unknown. Only `fetch`'s output is `untrusted`, because a web page can carry instructions; the rest is `trusted`, though a workspace file or a command's output can carry instructions too.
291
+
292
+ **The descriptions are versioned.** Every description, limit and default the tools use is in `BUILTIN_TOOL_DEFAULTS`, and `BUILTIN_TOOLS_HASH` changes whenever any of them does, so two runs with different hashes ran with different tools.
293
+
188
294
  ## One pipeline decides every tool call, and a call no rule settles is denied when nobody can answer
189
295
 
190
296
  `@buildanagent/harness/permissions` decides each tool call in one order: hooks, deny rules, ask rules, the mode, allow rules, the host callback, then the no-match default. A deny at any step ends the decision, so a deny rule beats every mode, `bypass` included, and a hook's deny beats everything. `createPermissionPipeline(config, registry)` returns a pipeline, and `pipeline.gate(context)` is the SDK's `beforeToolCall` gate, where `context` gives each call its session, host context and entries.
@@ -406,7 +512,7 @@ const context = createContextPolicy({ spill: fileSpillStore({ dir: ".sessions/sp
406
512
 
407
513
  **Layer 1, the write cap.** A tool result whose text is over the cap is cut before the model reads it, and the full text goes to the `spill` store. The model reads the first part and a line that names the file, and the `tool_result` entry stores the same cut text with `spill: { path, bytes }`. If the store cannot write, the text is still cut, and the notice says the rest was not kept.
408
514
 
409
- The cap counts the bytes the entry takes in the log: JSON escaping, the result's details and other blocks, and 1 KiB for the entry's own fields. A capped entry therefore always fits the stores' 64 KiB entry bound. The default `writeCapBytes` of 65,536 leaves the model a little under 64 KiB of plain text, and less of a text full of newlines or quotes. `fileSpillStore({ dir })` from `@buildanagent/harness/context/file` writes one file per capped result, and `memorySpillStore()` serves tests. A file is named by the run id, a count within the run and the call id, because a provider may reuse a call id. A policy with the layer on and no `spill` throws `invalid_context_options`.
515
+ The cap counts the bytes the entry takes in the log: JSON escaping, the result's details and other blocks, and 1 KiB for the entry's own fields. A capped entry therefore always fits the stores' 64 KiB entry bound. The default `writeCapBytes` of 65,536 leaves the model a little under 64 KiB of plain text, and less of a text full of newlines or quotes. `fileSpillStore({ dir })` from `@buildanagent/harness/context/file` writes one file per capped result, and `memorySpillStore()` serves tests, with absolute paths under `/spill/`. `fileSpillStore().read()` reads only an absolute path inside the session's folder. A file is named by the run id, a count within the run and the call id, because a provider may reuse a call id. A policy with the layer on and no `spill` throws `invalid_context_options`.
410
516
 
411
517
  **Layer 2, stepped masking.** Before each model call, every tool result before a cutoff shrinks to its first 500 characters and a pointer line. The line names the spill file, or the log entry when the result was never spilled. A cut never leaves half of a surrogate pair. The cutoff is `floor((messages − 8) / 8) × 8`, so it moves once every eight messages. Between moves the view's prefix stays byte-identical, which keeps a provider's prompt cache hitting.
412
518
 
@@ -1,5 +1,15 @@
1
+ import { type SessionKey } from "../session/store.js";
1
2
  import type { SpillStore } from "./types.js";
3
+ /** A spill store in files, which can also read back the spills of one session. */
4
+ export interface FileSpillStore extends SpillStore {
5
+ /**
6
+ * The text spilled to `path` for the session `key`, or `undefined` when `path` is not a spill file of that session.
7
+ * `path` must be absolute, as `write()` returns it. A relative path, a path outside the session's folder, and one
8
+ * that leads out through a symlink are never read.
9
+ */
10
+ read(key: SessionKey, path: string): Promise<string | undefined>;
11
+ }
2
12
  /** A spill store that writes `<dir>/<user>/<session>/<callId>.txt` and returns that path. */
3
13
  export declare function fileSpillStore(options: {
4
14
  readonly dir: string;
5
- }): SpillStore;
15
+ }): FileSpillStore;
@@ -1,25 +1,40 @@
1
1
  /**
2
2
  * The spill store that keeps each capped tool result in a file, one per call, in a folder per session. It uses Node's
3
- * file system, loaded with `process.getBuiltinModule()` when a result is written, so importing it costs a portable
4
- * bundle nothing. It has its own entry, `@buildanagent/harness/context/file`.
3
+ * file system, loaded with `process.getBuiltinModule()` when a result is written or read, so importing it costs a
4
+ * portable bundle nothing. It has its own entry, `@buildanagent/harness/context/file`.
5
5
  */
6
6
  import { HarnessError } from "../errors.js";
7
7
  import { encodeName } from "../session/store.js";
8
+ function nodeModules() {
9
+ if (typeof process === "undefined" || typeof process.getBuiltinModule !== "function") {
10
+ throw new HarnessError("spill_unavailable", "fileSpillStore needs Node's file system, which this runtime lacks");
11
+ }
12
+ return { fs: process.getBuiltinModule("node:fs/promises"), path: process.getBuiltinModule("node:path") };
13
+ }
8
14
  /** A spill store that writes `<dir>/<user>/<session>/<callId>.txt` and returns that path. */
9
15
  export function fileSpillStore(options) {
16
+ const folderOf = (key) => nodeModules().path.resolve(options.dir, encodeName(key.userId), encodeName(key.sessionId));
10
17
  return {
11
18
  async write(key, callId, text) {
12
- if (typeof process === "undefined" || typeof process.getBuiltinModule !== "function") {
13
- throw new HarnessError("spill_unavailable", "fileSpillStore needs Node's file system, which this runtime lacks");
14
- }
15
- const fs = process.getBuiltinModule("node:fs/promises");
16
- const path = process.getBuiltinModule("node:path");
17
- const folder = path.resolve(options.dir, encodeName(key.userId), encodeName(key.sessionId));
19
+ const { fs, path } = nodeModules();
20
+ const folder = folderOf(key);
18
21
  await fs.mkdir(folder, { recursive: true });
19
22
  const file = path.join(folder, `${encodeName(callId)}.txt`);
20
23
  await fs.writeFile(file, text, "utf8");
21
24
  return file;
22
25
  },
26
+ async read(key, file) {
27
+ const { fs, path } = nodeModules();
28
+ // A relative path would resolve against the spill folder, so a workspace file's name could open a spill.
29
+ if (!path.isAbsolute(file))
30
+ return undefined;
31
+ // Both sides are real paths, so a link inside the folder that points out of it is caught.
32
+ const folder = await fs.realpath(folderOf(key)).catch(() => undefined);
33
+ const real = await fs.realpath(path.resolve(folderOf(key), file)).catch(() => undefined);
34
+ if (folder === undefined || real === undefined || path.dirname(real) !== folder)
35
+ return undefined;
36
+ return fs.readFile(real, "utf8").catch(() => undefined);
37
+ },
23
38
  };
24
39
  }
25
40
  //# sourceMappingURL=file-spill.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"file-spill.js","sourceRoot":"","sources":["../../src/context/file-spill.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,OAAO,EAAE,YAAY,EAAE,MAAM,cAAc,CAAC;AAC5C,OAAO,EAAE,UAAU,EAAmB,MAAM,qBAAqB,CAAC;AAGlE,6FAA6F;AAC7F,MAAM,UAAU,cAAc,CAAC,OAAiC;IAC9D,OAAO;QACL,KAAK,CAAC,KAAK,CAAC,GAAe,EAAE,MAAc,EAAE,IAAY;YACvD,IAAI,OAAO,OAAO,KAAK,WAAW,IAAI,OAAO,OAAO,CAAC,gBAAgB,KAAK,UAAU,EAAE,CAAC;gBACrF,MAAM,IAAI,YAAY,CACpB,mBAAmB,EACnB,mEAAmE,CACpE,CAAC;YACJ,CAAC;YACD,MAAM,EAAE,GAAG,OAAO,CAAC,gBAAgB,CAAC,kBAAkB,CAAC,CAAC;YACxD,MAAM,IAAI,GAAG,OAAO,CAAC,gBAAgB,CAAC,WAAW,CAAC,CAAC;YACnD,MAAM,MAAM,GAAG,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,GAAG,EAAE,UAAU,CAAC,GAAG,CAAC,MAAM,CAAC,EAAE,UAAU,CAAC,GAAG,CAAC,SAAS,CAAC,CAAC,CAAC;YAC5F,MAAM,EAAE,CAAC,KAAK,CAAC,MAAM,EAAE,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC,CAAC;YAC5C,MAAM,IAAI,GAAG,IAAI,CAAC,IAAI,CAAC,MAAM,EAAE,GAAG,UAAU,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC;YAC5D,MAAM,EAAE,CAAC,SAAS,CAAC,IAAI,EAAE,IAAI,EAAE,MAAM,CAAC,CAAC;YACvC,OAAO,IAAI,CAAC;QACd,CAAC;KACF,CAAC;AACJ,CAAC","sourcesContent":["/**\n * The spill store that keeps each capped tool result in a file, one per call, in a folder per session. It uses Node's\n * file system, loaded with `process.getBuiltinModule()` when a result is written, so importing it costs a portable\n * bundle nothing. It has its own entry, `@buildanagent/harness/context/file`.\n */\nimport { HarnessError } from \"../errors.js\";\nimport { encodeName, type SessionKey } from \"../session/store.js\";\nimport type { SpillStore } from \"./types.js\";\n\n/** A spill store that writes `<dir>/<user>/<session>/<callId>.txt` and returns that path. */\nexport function fileSpillStore(options: { readonly dir: string }): SpillStore {\n return {\n async write(key: SessionKey, callId: string, text: string): Promise<string> {\n if (typeof process === \"undefined\" || typeof process.getBuiltinModule !== \"function\") {\n throw new HarnessError(\n \"spill_unavailable\",\n \"fileSpillStore needs Node's file system, which this runtime lacks\",\n );\n }\n const fs = process.getBuiltinModule(\"node:fs/promises\");\n const path = process.getBuiltinModule(\"node:path\");\n const folder = path.resolve(options.dir, encodeName(key.userId), encodeName(key.sessionId));\n await fs.mkdir(folder, { recursive: true });\n const file = path.join(folder, `${encodeName(callId)}.txt`);\n await fs.writeFile(file, text, \"utf8\");\n return file;\n },\n };\n}\n"]}
1
+ {"version":3,"file":"file-spill.js","sourceRoot":"","sources":["../../src/context/file-spill.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,OAAO,EAAE,YAAY,EAAE,MAAM,cAAc,CAAC;AAC5C,OAAO,EAAE,UAAU,EAAmB,MAAM,qBAAqB,CAAC;AAalE,SAAS,WAAW;IAClB,IAAI,OAAO,OAAO,KAAK,WAAW,IAAI,OAAO,OAAO,CAAC,gBAAgB,KAAK,UAAU,EAAE,CAAC;QACrF,MAAM,IAAI,YAAY,CAAC,mBAAmB,EAAE,mEAAmE,CAAC,CAAC;IACnH,CAAC;IACD,OAAO,EAAE,EAAE,EAAE,OAAO,CAAC,gBAAgB,CAAC,kBAAkB,CAAC,EAAE,IAAI,EAAE,OAAO,CAAC,gBAAgB,CAAC,WAAW,CAAC,EAAE,CAAC;AAC3G,CAAC;AAED,6FAA6F;AAC7F,MAAM,UAAU,cAAc,CAAC,OAAiC;IAC9D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,EAAE,CAAC,SAAS,CAAC,CAAC;YACzF,IAAI,MAAM,KAAK,SAAS,IAAI,IAAI,KAAK,SAAS,IAAI,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,KAAK,MAAM;gBAAE,OAAO,SAAS,CAAC;YAClG,OAAO,EAAE,CAAC,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC,CAAC,KAAK,CAAC,GAAG,EAAE,CAAC,SAAS,CAAC,CAAC;QAC1D,CAAC;KACF,CAAC;AACJ,CAAC","sourcesContent":["/**\n * The spill store that keeps each capped tool result in a file, one per call, in a folder per session. It uses Node's\n * file system, loaded with `process.getBuiltinModule()` when a result is written or read, so importing it costs a\n * portable bundle nothing. It has its own entry, `@buildanagent/harness/context/file`.\n */\nimport { HarnessError } from \"../errors.js\";\nimport { encodeName, type SessionKey } from \"../session/store.js\";\nimport type { SpillStore } from \"./types.js\";\n\n/** A spill store in files, which can also read back the spills of one session. */\nexport interface FileSpillStore extends SpillStore {\n /**\n * The text spilled to `path` for the session `key`, or `undefined` when `path` is not a spill file of that session.\n * `path` must be absolute, as `write()` returns it. A relative path, a path outside the session's folder, and one\n * that leads out through a symlink are never read.\n */\n read(key: SessionKey, path: string): Promise<string | undefined>;\n}\n\nfunction nodeModules() {\n if (typeof process === \"undefined\" || typeof process.getBuiltinModule !== \"function\") {\n throw new HarnessError(\"spill_unavailable\", \"fileSpillStore needs Node's file system, which this runtime lacks\");\n }\n return { fs: process.getBuiltinModule(\"node:fs/promises\"), path: process.getBuiltinModule(\"node:path\") };\n}\n\n/** A spill store that writes `<dir>/<user>/<session>/<callId>.txt` and returns that path. */\nexport function fileSpillStore(options: { readonly dir: string }): FileSpillStore {\n const folderOf = (key: SessionKey) =>\n nodeModules().path.resolve(options.dir, encodeName(key.userId), encodeName(key.sessionId));\n return {\n async write(key: SessionKey, callId: string, text: string): Promise<string> {\n const { fs, path } = nodeModules();\n const folder = folderOf(key);\n await fs.mkdir(folder, { recursive: true });\n const file = path.join(folder, `${encodeName(callId)}.txt`);\n await fs.writeFile(file, text, \"utf8\");\n return file;\n },\n async read(key: SessionKey, file: string): Promise<string | undefined> {\n const { fs, path } = nodeModules();\n // A relative path would resolve against the spill folder, so a workspace file's name could open a spill.\n if (!path.isAbsolute(file)) return undefined;\n // Both sides are real paths, so a link inside the folder that points out of it is caught.\n const folder = await fs.realpath(folderOf(key)).catch(() => undefined);\n const real = await fs.realpath(path.resolve(folderOf(key), file)).catch(() => undefined);\n if (folder === undefined || real === undefined || path.dirname(real) !== folder) return undefined;\n return fs.readFile(real, \"utf8\").catch(() => undefined);\n },\n };\n}\n"]}
@@ -1,5 +1,9 @@
1
1
  import type { SpillStore } from "./types.js";
2
- /** A spill store in memory, for tests and for a process that keeps its sessions in `memoryStore()`. */
2
+ /**
3
+ * A spill store in memory, for tests and for a process that keeps its sessions in `memoryStore()`. Its paths are
4
+ * absolute, `/spill/<user>/<session>/<call>.txt`, so the built-in `read` tool, which asks its spill reader only about an
5
+ * absolute path, can open them.
6
+ */
3
7
  export declare function memorySpillStore(): SpillStore & {
4
8
  /** The full text spilled to `path`, or `undefined` when nothing was. */
5
9
  read(path: string): string | undefined;
@@ -1,10 +1,14 @@
1
1
  import { encodeName } from "../session/store.js";
2
- /** A spill store in memory, for tests and for a process that keeps its sessions in `memoryStore()`. */
2
+ /**
3
+ * A spill store in memory, for tests and for a process that keeps its sessions in `memoryStore()`. Its paths are
4
+ * absolute, `/spill/<user>/<session>/<call>.txt`, so the built-in `read` tool, which asks its spill reader only about an
5
+ * absolute path, can open them.
6
+ */
3
7
  export function memorySpillStore() {
4
8
  const files = new Map();
5
9
  return {
6
10
  async write(key, callId, text) {
7
- const path = `spill/${encodeName(key.userId)}/${encodeName(key.sessionId)}/${encodeName(callId)}.txt`;
11
+ const path = `/spill/${encodeName(key.userId)}/${encodeName(key.sessionId)}/${encodeName(callId)}.txt`;
8
12
  files.set(path, text);
9
13
  return path;
10
14
  },
@@ -1 +1 @@
1
- {"version":3,"file":"spill.js","sourceRoot":"","sources":["../../src/context/spill.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAmB,MAAM,qBAAqB,CAAC;AAGlE,uGAAuG;AACvG,MAAM,UAAU,gBAAgB;IAI9B,MAAM,KAAK,GAAG,IAAI,GAAG,EAAkB,CAAC;IACxC,OAAO;QACL,KAAK,CAAC,KAAK,CAAC,GAAe,EAAE,MAAc,EAAE,IAAY;YACvD,MAAM,IAAI,GAAG,SAAS,UAAU,CAAC,GAAG,CAAC,MAAM,CAAC,IAAI,UAAU,CAAC,GAAG,CAAC,SAAS,CAAC,IAAI,UAAU,CAAC,MAAM,CAAC,MAAM,CAAC;YACtG,KAAK,CAAC,GAAG,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC;YACtB,OAAO,IAAI,CAAC;QACd,CAAC;QACD,IAAI,EAAE,CAAC,IAAI,EAAE,EAAE,CAAC,KAAK,CAAC,GAAG,CAAC,IAAI,CAAC;KAChC,CAAC;AACJ,CAAC","sourcesContent":["import { encodeName, type SessionKey } from \"../session/store.js\";\nimport type { SpillStore } from \"./types.js\";\n\n/** A spill store in memory, for tests and for a process that keeps its sessions in `memoryStore()`. */\nexport function memorySpillStore(): SpillStore & {\n /** The full text spilled to `path`, or `undefined` when nothing was. */\n read(path: string): string | undefined;\n} {\n const files = new Map<string, string>();\n return {\n async write(key: SessionKey, callId: string, text: string): Promise<string> {\n const path = `spill/${encodeName(key.userId)}/${encodeName(key.sessionId)}/${encodeName(callId)}.txt`;\n files.set(path, text);\n return path;\n },\n read: (path) => files.get(path),\n };\n}\n"]}
1
+ {"version":3,"file":"spill.js","sourceRoot":"","sources":["../../src/context/spill.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAmB,MAAM,qBAAqB,CAAC;AAGlE;;;;GAIG;AACH,MAAM,UAAU,gBAAgB;IAI9B,MAAM,KAAK,GAAG,IAAI,GAAG,EAAkB,CAAC;IACxC,OAAO;QACL,KAAK,CAAC,KAAK,CAAC,GAAe,EAAE,MAAc,EAAE,IAAY;YACvD,MAAM,IAAI,GAAG,UAAU,UAAU,CAAC,GAAG,CAAC,MAAM,CAAC,IAAI,UAAU,CAAC,GAAG,CAAC,SAAS,CAAC,IAAI,UAAU,CAAC,MAAM,CAAC,MAAM,CAAC;YACvG,KAAK,CAAC,GAAG,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC;YACtB,OAAO,IAAI,CAAC;QACd,CAAC;QACD,IAAI,EAAE,CAAC,IAAI,EAAE,EAAE,CAAC,KAAK,CAAC,GAAG,CAAC,IAAI,CAAC;KAChC,CAAC;AACJ,CAAC","sourcesContent":["import { encodeName, type SessionKey } from \"../session/store.js\";\nimport type { SpillStore } from \"./types.js\";\n\n/**\n * A spill store in memory, for tests and for a process that keeps its sessions in `memoryStore()`. Its paths are\n * absolute, `/spill/<user>/<session>/<call>.txt`, so the built-in `read` tool, which asks its spill reader only about an\n * absolute path, can open them.\n */\nexport function memorySpillStore(): SpillStore & {\n /** The full text spilled to `path`, or `undefined` when nothing was. */\n read(path: string): string | undefined;\n} {\n const files = new Map<string, string>();\n return {\n async write(key: SessionKey, callId: string, text: string): Promise<string> {\n const path = `/spill/${encodeName(key.userId)}/${encodeName(key.sessionId)}/${encodeName(callId)}.txt`;\n files.set(path, text);\n return path;\n },\n read: (path) => files.get(path),\n };\n}\n"]}
@@ -1,3 +1,4 @@
1
+ import { type GitRouteFilter } from "./git-route.js";
1
2
  /** A host the proxy may reach on one port. A `*.` name matches every name under it, and never the name itself. */
2
3
  export interface AllowEntry {
3
4
  readonly name: string;
@@ -16,6 +17,12 @@ export interface CredentialRoute {
16
17
  readonly header: string;
17
18
  /** The real secret, read at each request so a rotated key is used at once. It never enters the sandbox. */
18
19
  readonly secret: () => Promise<string>;
20
+ /**
21
+ * Makes the route a git route: only git's smart HTTP requests for the listed repositories pass, a push only to the
22
+ * listed branches, and the secret goes in HTTP Basic as the password of `username`. Its `header` must be
23
+ * `authorization` and its `methods` `GET` and `POST`. The sandbox's git sends the route's sentinel as its password.
24
+ */
25
+ readonly git?: GitRouteFilter;
19
26
  }
20
27
  /** A route with its host and port split, its method and header names normalised, and its sentinel. */
21
28
  export interface ParsedRoute {
@@ -25,10 +32,23 @@ export interface ParsedRoute {
25
32
  readonly methods: ReadonlySet<string>;
26
33
  readonly header: string;
27
34
  readonly secret: () => Promise<string>;
35
+ readonly git?: GitRouteFilter;
28
36
  }
29
37
  /** Parses the allowlist: each entry is `name`, `*.name`, with `:port` when it isn't 443. */
30
38
  export declare function parseAllow(entries: readonly string[]): AllowEntry[];
31
39
  /** Whether `host` on `port` is on the allowlist. `host` is lower case, without a trailing dot. */
32
40
  export declare function isAllowed(allow: readonly AllowEntry[], host: string, port: number): boolean;
33
- /** Parses and checks the routes, and refuses two with one name. */
34
- export declare function parseRoutes(routes: readonly CredentialRoute[]): ParsedRoute[];
41
+ /**
42
+ * The first git route that shares its host with a way around its filter, and what that way is: an allowlist entry, on
43
+ * any port, that lets a tunnel reach the host, or another route to the same host, which would carry a credential there
44
+ * without the git route's repository and ref checks. Hosts are compared in lower case without their ports.
45
+ */
46
+ export declare function gitHostOverlap(routes: readonly Pick<CredentialRoute, "host" | "git">[], allow: readonly AllowEntry[]): {
47
+ readonly index: number;
48
+ readonly with: "allow" | "route";
49
+ } | undefined;
50
+ /**
51
+ * Parses and checks the routes against the parsed allowlist. It refuses two routes with one name, and a git route whose
52
+ * host is also on the allowlist or is another route's host, because either would go around its filter.
53
+ */
54
+ export declare function parseRoutes(routes: readonly CredentialRoute[], allow: readonly AllowEntry[]): ParsedRoute[];
@@ -4,6 +4,7 @@
4
4
  */
5
5
  import { HarnessError } from "../errors.js";
6
6
  import { isAddressLiteral } from "./addresses.js";
7
+ import { checkGitFilter } from "./git-route.js";
7
8
  const HOST_NAME = /^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$/;
8
9
  const ROUTE_NAME = /^[a-z0-9][a-z0-9_-]{0,63}$/;
9
10
  const HEADER_NAME = /^[!#$%&'*+.^_`|~0-9a-z-]+$/;
@@ -49,29 +50,85 @@ export function parseAllow(entries) {
49
50
  export function isAllowed(allow, host, port) {
50
51
  return allow.some((entry) => entry.port === port && (entry.wildcard ? host.endsWith(`.${entry.name}`) : host === entry.name));
51
52
  }
52
- /** Parses and checks the routes, and refuses two with one name. */
53
- export function parseRoutes(routes) {
53
+ /** Whether `name` is on the allowlist on any port, so a tunnel could reach it. */
54
+ const allowedOnAnyPort = (allow, name) => allow.some((entry) => (entry.wildcard ? name.endsWith(`.${entry.name}`) : name === entry.name));
55
+ /**
56
+ * The first git route that shares its host with a way around its filter, and what that way is: an allowlist entry, on
57
+ * any port, that lets a tunnel reach the host, or another route to the same host, which would carry a credential there
58
+ * without the git route's repository and ref checks. Hosts are compared in lower case without their ports.
59
+ */
60
+ export function gitHostOverlap(routes, allow) {
61
+ const names = routes.map((route) => String(route.host)
62
+ .toLowerCase()
63
+ .replace(/:[0-9]*$/, ""));
64
+ for (const [index, route] of routes.entries()) {
65
+ if (route.git === undefined)
66
+ continue;
67
+ const name = names[index] ?? "";
68
+ if (allowedOnAnyPort(allow, name))
69
+ return { index, with: "allow" };
70
+ if (names.some((other, at) => at !== index && other === name))
71
+ return { index, with: "route" };
72
+ }
73
+ return undefined;
74
+ }
75
+ /**
76
+ * Parses and checks the routes against the parsed allowlist. It refuses two routes with one name, and a git route whose
77
+ * host is also on the allowlist or is another route's host, because either would go around its filter.
78
+ */
79
+ export function parseRoutes(routes, allow) {
54
80
  const seen = new Set();
55
- return routes.map((route) => {
81
+ const parsed = routes.map((route) => {
56
82
  if (!ROUTE_NAME.test(route.route))
57
83
  throw invalid(`the route name ${JSON.stringify(route.route)} is not usable`);
58
84
  if (seen.has(route.route))
59
85
  throw invalid(`two routes are named ${route.route}`);
60
86
  seen.add(route.route);
61
- const { name, port } = splitHost(route.host, "the route host");
62
- if (!HOST_NAME.test(name) || isAddressLiteral(name))
63
- throw invalid(`the route host ${route.host} must be a host name`);
64
- const methods = route.methods.map((method) => method.toUpperCase());
65
- if (methods.length === 0 || !methods.every((method) => METHOD.test(method)) || methods.includes("CONNECT")) {
66
- throw invalid(`the route ${route.route} needs a list of methods, such as ["GET"]`);
67
- }
68
- const header = route.header.toLowerCase();
69
- if (!HEADER_NAME.test(header) || RESERVED_HEADERS.has(header)) {
70
- throw invalid(`the route ${route.route} can't carry its credential in the header ${route.header}`);
71
- }
72
- if (typeof route.secret !== "function")
73
- throw invalid(`the route ${route.route} needs a secret function`);
74
- return { route: route.route, hostname: name, port, methods: new Set(methods), header, secret: route.secret };
87
+ return parseRoute(route);
75
88
  });
89
+ const overlap = gitHostOverlap(routes, allow);
90
+ if (overlap !== undefined) {
91
+ const name = routes[overlap.index]?.route ?? "";
92
+ throw invalid(overlap.with === "allow"
93
+ ? `the host of the git route ${name} is also on the allowlist, so a tunnel could go around its filter`
94
+ : `the host of the git route ${name} is another route's host, which could go around its filter`);
95
+ }
96
+ return parsed;
97
+ }
98
+ /** Parses and checks one route's host, methods, header, secret and git filter. */
99
+ function parseRoute(route) {
100
+ const { name, port } = splitHost(route.host, "the route host");
101
+ if (!HOST_NAME.test(name) || isAddressLiteral(name))
102
+ throw invalid(`the route host ${route.host} must be a host name`);
103
+ const methods = route.methods.map((method) => method.toUpperCase());
104
+ if (methods.length === 0 || !methods.every((method) => METHOD.test(method)) || methods.includes("CONNECT")) {
105
+ throw invalid(`the route ${route.route} needs a list of methods, such as ["GET"]`);
106
+ }
107
+ const header = route.header.toLowerCase();
108
+ if (!HEADER_NAME.test(header) || RESERVED_HEADERS.has(header)) {
109
+ throw invalid(`the route ${route.route} can't carry its credential in the header ${route.header}`);
110
+ }
111
+ if (typeof route.secret !== "function")
112
+ throw invalid(`the route ${route.route} needs a secret function`);
113
+ if (route.git !== undefined)
114
+ checkGitRoute(route.git, methods, header);
115
+ return {
116
+ route: route.route,
117
+ hostname: name,
118
+ port,
119
+ methods: new Set(methods),
120
+ header,
121
+ secret: route.secret,
122
+ ...(route.git === undefined ? {} : { git: route.git }),
123
+ };
124
+ }
125
+ /** Throws unless a git route carries its credential in `authorization` and takes exactly `GET` and `POST`. */
126
+ function checkGitRoute(filter, methods, header) {
127
+ checkGitFilter(filter);
128
+ if (header !== "authorization")
129
+ throw invalid("a git route carries its credential in the authorization header");
130
+ if (new Set(methods).size !== 2 || !methods.includes("GET") || !methods.includes("POST")) {
131
+ throw invalid("a git route takes the methods GET and POST");
132
+ }
76
133
  }
77
134
  //# sourceMappingURL=allowlist.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"allowlist.js","sourceRoot":"","sources":["../../src/credentials/allowlist.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,OAAO,EAAE,YAAY,EAAE,MAAM,cAAc,CAAC;AAC5C,OAAO,EAAE,gBAAgB,EAAE,MAAM,gBAAgB,CAAC;AAiClD,MAAM,SAAS,GAAG,mEAAmE,CAAC;AACtF,MAAM,UAAU,GAAG,4BAA4B,CAAC;AAChD,MAAM,WAAW,GAAG,4BAA4B,CAAC;AACjD,MAAM,MAAM,GAAG,eAAe,CAAC;AAC/B,gGAAgG;AAChG,MAAM,gBAAgB,GAAG,IAAI,GAAG,CAAC;IAC/B,MAAM;IACN,gBAAgB;IAChB,mBAAmB;IACnB,YAAY;IACZ,YAAY;IACZ,IAAI;IACJ,SAAS;IACT,SAAS;IACT,qBAAqB;IACrB,oBAAoB;IACpB,kBAAkB;CACnB,CAAC,CAAC;AAEH,SAAS,OAAO,CAAC,OAAe;IAC9B,OAAO,IAAI,YAAY,CAAC,wBAAwB,EAAE,OAAO,CAAC,CAAC;AAC7D,CAAC;AAED,oGAAoG;AACpG,SAAS,SAAS,CAAC,IAAY,EAAE,IAAY;IAC3C,MAAM,CAAC,IAAI,GAAG,EAAE,EAAE,IAAI,EAAE,KAAK,CAAC,GAAG,IAAI,CAAC,WAAW,EAAE,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;IAC/D,MAAM,UAAU,GAA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AM,CAAC,CAAC,IAAI,OAAO,CAAC,QAAQ,CAAC,SAAS,CAAC,EAAE,CAAC;YAC3G,MAAM,OAAO,CAAC,aAAa,KAAK,CAAC,KAAK,2CAA2C,CAAC,CAAC;QACrF,CAAC;QACD,MAAM,MAAM,GAAG,KAAK,CAAC,MAAM,CAAC,WAAW,EAAE,CAAC;QAC1C,IAAI,CAAC,WAAW,CAAC,IAAI,CAAC,MAAM,CAAC,IAAI,gBAAgB,CAAC,GAAG,CAAC,MAAM,CAAC,EAAE,CAAC;YAC9D,MAAM,OAAO,CAAC,aAAa,KAAK,CAAC,KAAK,6CAA6C,KAAK,CAAC,MAAM,EAAE,CAAC,CAAC;QACrG,CAAC;QACD,IAAI,OAAO,KAAK,CAAC,MAAM,KAAK,UAAU;YAAE,MAAM,OAAO,CAAC,aAAa,KAAK,CAAC,KAAK,0BAA0B,CAAC,CAAC;QAC1G,OAAO,EAAE,KAAK,EAAE,KAAK,CAAC,KAAK,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,EAAE,OAAO,EAAE,IAAI,GAAG,CAAC,OAAO,CAAC,EAAE,MAAM,EAAE,MAAM,EAAE,KAAK,CAAC,MAAM,EAAE,CAAC;IAC/G,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["/**\n * The egress proxy's configuration, checked once when it starts: the allowlist of names and the credential routes. A\n * bad entry throws, so a typo can't widen what leaves the machine. It is pure and portable.\n */\nimport { HarnessError } from \"../errors.js\";\nimport { isAddressLiteral } from \"./addresses.js\";\n\n/** A host the proxy may reach on one port. A `*.` name matches every name under it, and never the name itself. */\nexport interface AllowEntry {\n readonly name: string;\n readonly wildcard: boolean;\n readonly port: number;\n}\n\n/** One credential route: where a request for `/<route>/…` goes, and how the proxy adds the credential. */\nexport interface CredentialRoute {\n /** The first part of the path the sandbox requests, such as `github`. Lower case letters, digits, `-` and `_`. */\n readonly route: string;\n /** The HTTPS host the request is forwarded to, such as `api.github.com`, with `:port` when it isn't 443. */\n readonly host: string;\n /** The methods the route accepts, such as `[\"GET\"]`. A request with another method is refused. */\n readonly methods: readonly string[];\n /** The request header that carries the credential, such as `authorization`. */\n readonly header: string;\n /** The real secret, read at each request so a rotated key is used at once. It never enters the sandbox. */\n readonly secret: () => Promise<string>;\n}\n\n/** A route with its host and port split, its method and header names normalised, and its sentinel. */\nexport interface ParsedRoute {\n readonly route: string;\n readonly hostname: string;\n readonly port: number;\n readonly methods: ReadonlySet<string>;\n readonly header: string;\n readonly secret: () => Promise<string>;\n}\n\nconst HOST_NAME = /^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$/;\nconst ROUTE_NAME = /^[a-z0-9][a-z0-9_-]{0,63}$/;\nconst HEADER_NAME = /^[!#$%&'*+.^_`|~0-9a-z-]+$/;\nconst METHOD = /^[A-Z]{3,10}$/;\n// Headers the proxy sets or removes itself, so a route can't name one as its credential header.\nconst RESERVED_HEADERS = new Set([\n \"host\",\n \"content-length\",\n \"transfer-encoding\",\n \"connection\",\n \"keep-alive\",\n \"te\",\n \"trailer\",\n \"upgrade\",\n \"proxy-authorization\",\n \"proxy-authenticate\",\n \"proxy-connection\",\n]);\n\nfunction invalid(message: string): HarnessError {\n return new HarnessError(\"invalid_egress_options\", message);\n}\n\n/** The lower-case host name and the port of `text`, which is `name` or `name:port`, or an error. */\nfunction splitHost(text: string, what: string): { name: string; port: number } {\n const [name = \"\", port, extra] = text.toLowerCase().split(\":\");\n const portNumber = port === undefined ? 443 : Number(port);\n if (extra !== undefined || !Number.isInteger(portNumber) || portNumber < 1 || portNumber > 65535) {\n throw invalid(`${what} ${JSON.stringify(text)} has a bad port`);\n }\n return { name, port: portNumber };\n}\n\n/** Parses the allowlist: each entry is `name`, `*.name`, with `:port` when it isn't 443. */\nexport function parseAllow(entries: readonly string[]): AllowEntry[] {\n return entries.map((entry) => {\n const wildcard = entry.startsWith(\"*.\");\n const { name, port } = splitHost(wildcard ? entry.slice(2) : entry, \"the allowlist entry\");\n if (!HOST_NAME.test(name) || isAddressLiteral(name)) {\n throw invalid(\n `the allowlist entry ${JSON.stringify(entry)} must be a host name, such as example.com or *.example.com`,\n );\n }\n return { name, wildcard, port };\n });\n}\n\n/** Whether `host` on `port` is on the allowlist. `host` is lower case, without a trailing dot. */\nexport function isAllowed(allow: readonly AllowEntry[], host: string, port: number): boolean {\n return allow.some(\n (entry) => entry.port === port && (entry.wildcard ? host.endsWith(`.${entry.name}`) : host === entry.name),\n );\n}\n\n/** Parses and checks the routes, and refuses two with one name. */\nexport function parseRoutes(routes: readonly CredentialRoute[]): ParsedRoute[] {\n const seen = new Set<string>();\n return routes.map((route) => {\n if (!ROUTE_NAME.test(route.route)) throw invalid(`the route name ${JSON.stringify(route.route)} is not usable`);\n if (seen.has(route.route)) throw invalid(`two routes are named ${route.route}`);\n seen.add(route.route);\n const { name, port } = splitHost(route.host, \"the route host\");\n if (!HOST_NAME.test(name) || isAddressLiteral(name))\n throw invalid(`the route host ${route.host} must be a host name`);\n const methods = route.methods.map((method) => method.toUpperCase());\n if (methods.length === 0 || !methods.every((method) => METHOD.test(method)) || methods.includes(\"CONNECT\")) {\n throw invalid(`the route ${route.route} needs a list of methods, such as [\"GET\"]`);\n }\n const header = route.header.toLowerCase();\n if (!HEADER_NAME.test(header) || RESERVED_HEADERS.has(header)) {\n throw invalid(`the route ${route.route} can't carry its credential in the header ${route.header}`);\n }\n if (typeof route.secret !== \"function\") throw invalid(`the route ${route.route} needs a secret function`);\n return { route: route.route, hostname: name, port, methods: new Set(methods), header, secret: route.secret };\n });\n}\n"]}
1
+ {"version":3,"file":"allowlist.js","sourceRoot":"","sources":["../../src/credentials/allowlist.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,OAAO,EAAE,YAAY,EAAE,MAAM,cAAc,CAAC;AAC5C,OAAO,EAAE,gBAAgB,EAAE,MAAM,gBAAgB,CAAC;AAClD,OAAO,EAAE,cAAc,EAAuB,MAAM,gBAAgB,CAAC;AA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AAC;QACzF,MAAM,OAAO,CAAC,4CAA4C,CAAC,CAAC;IAC9D,CAAC;AACH,CAAC","sourcesContent":["/**\n * The egress proxy's configuration, checked once when it starts: the allowlist of names and the credential routes. A\n * bad entry throws, so a typo can't widen what leaves the machine. It is pure and portable.\n */\nimport { HarnessError } from \"../errors.js\";\nimport { isAddressLiteral } from \"./addresses.js\";\nimport { checkGitFilter, type GitRouteFilter } from \"./git-route.js\";\n\n/** A host the proxy may reach on one port. A `*.` name matches every name under it, and never the name itself. */\nexport interface AllowEntry {\n readonly name: string;\n readonly wildcard: boolean;\n readonly port: number;\n}\n\n/** One credential route: where a request for `/<route>/…` goes, and how the proxy adds the credential. */\nexport interface CredentialRoute {\n /** The first part of the path the sandbox requests, such as `github`. Lower case letters, digits, `-` and `_`. */\n readonly route: string;\n /** The HTTPS host the request is forwarded to, such as `api.github.com`, with `:port` when it isn't 443. */\n readonly host: string;\n /** The methods the route accepts, such as `[\"GET\"]`. A request with another method is refused. */\n readonly methods: readonly string[];\n /** The request header that carries the credential, such as `authorization`. */\n readonly header: string;\n /** The real secret, read at each request so a rotated key is used at once. It never enters the sandbox. */\n readonly secret: () => Promise<string>;\n /**\n * Makes the route a git route: only git's smart HTTP requests for the listed repositories pass, a push only to the\n * listed branches, and the secret goes in HTTP Basic as the password of `username`. Its `header` must be\n * `authorization` and its `methods` `GET` and `POST`. The sandbox's git sends the route's sentinel as its password.\n */\n readonly git?: GitRouteFilter;\n}\n\n/** A route with its host and port split, its method and header names normalised, and its sentinel. */\nexport interface ParsedRoute {\n readonly route: string;\n readonly hostname: string;\n readonly port: number;\n readonly methods: ReadonlySet<string>;\n readonly header: string;\n readonly secret: () => Promise<string>;\n readonly git?: GitRouteFilter;\n}\n\nconst HOST_NAME = /^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$/;\nconst ROUTE_NAME = /^[a-z0-9][a-z0-9_-]{0,63}$/;\nconst HEADER_NAME = /^[!#$%&'*+.^_`|~0-9a-z-]+$/;\nconst METHOD = /^[A-Z]{3,10}$/;\n// Headers the proxy sets or removes itself, so a route can't name one as its credential header.\nconst RESERVED_HEADERS = new Set([\n \"host\",\n \"content-length\",\n \"transfer-encoding\",\n \"connection\",\n \"keep-alive\",\n \"te\",\n \"trailer\",\n \"upgrade\",\n \"proxy-authorization\",\n \"proxy-authenticate\",\n \"proxy-connection\",\n]);\n\nfunction invalid(message: string): HarnessError {\n return new HarnessError(\"invalid_egress_options\", message);\n}\n\n/** The lower-case host name and the port of `text`, which is `name` or `name:port`, or an error. */\nfunction splitHost(text: string, what: string): { name: string; port: number } {\n const [name = \"\", port, extra] = text.toLowerCase().split(\":\");\n const portNumber = port === undefined ? 443 : Number(port);\n if (extra !== undefined || !Number.isInteger(portNumber) || portNumber < 1 || portNumber > 65535) {\n throw invalid(`${what} ${JSON.stringify(text)} has a bad port`);\n }\n return { name, port: portNumber };\n}\n\n/** Parses the allowlist: each entry is `name`, `*.name`, with `:port` when it isn't 443. */\nexport function parseAllow(entries: readonly string[]): AllowEntry[] {\n return entries.map((entry) => {\n const wildcard = entry.startsWith(\"*.\");\n const { name, port } = splitHost(wildcard ? entry.slice(2) : entry, \"the allowlist entry\");\n if (!HOST_NAME.test(name) || isAddressLiteral(name)) {\n throw invalid(\n `the allowlist entry ${JSON.stringify(entry)} must be a host name, such as example.com or *.example.com`,\n );\n }\n return { name, wildcard, port };\n });\n}\n\n/** Whether `host` on `port` is on the allowlist. `host` is lower case, without a trailing dot. */\nexport function isAllowed(allow: readonly AllowEntry[], host: string, port: number): boolean {\n return allow.some(\n (entry) => entry.port === port && (entry.wildcard ? host.endsWith(`.${entry.name}`) : host === entry.name),\n );\n}\n\n/** Whether `name` is on the allowlist on any port, so a tunnel could reach it. */\nconst allowedOnAnyPort = (allow: readonly AllowEntry[], name: string): boolean =>\n allow.some((entry) => (entry.wildcard ? name.endsWith(`.${entry.name}`) : name === entry.name));\n\n/**\n * The first git route that shares its host with a way around its filter, and what that way is: an allowlist entry, on\n * any port, that lets a tunnel reach the host, or another route to the same host, which would carry a credential there\n * without the git route's repository and ref checks. Hosts are compared in lower case without their ports.\n */\nexport function gitHostOverlap(\n routes: readonly Pick<CredentialRoute, \"host\" | \"git\">[],\n allow: readonly AllowEntry[],\n): { readonly index: number; readonly with: \"allow\" | \"route\" } | undefined {\n const names = routes.map((route) =>\n String(route.host)\n .toLowerCase()\n .replace(/:[0-9]*$/, \"\"),\n );\n for (const [index, route] of routes.entries()) {\n if (route.git === undefined) continue;\n const name = names[index] ?? \"\";\n if (allowedOnAnyPort(allow, name)) return { index, with: \"allow\" };\n if (names.some((other, at) => at !== index && other === name)) return { index, with: \"route\" };\n }\n return undefined;\n}\n\n/**\n * Parses and checks the routes against the parsed allowlist. It refuses two routes with one name, and a git route whose\n * host is also on the allowlist or is another route's host, because either would go around its filter.\n */\nexport function parseRoutes(routes: readonly CredentialRoute[], allow: readonly AllowEntry[]): ParsedRoute[] {\n const seen = new Set<string>();\n const parsed = routes.map((route) => {\n if (!ROUTE_NAME.test(route.route)) throw invalid(`the route name ${JSON.stringify(route.route)} is not usable`);\n if (seen.has(route.route)) throw invalid(`two routes are named ${route.route}`);\n seen.add(route.route);\n return parseRoute(route);\n });\n const overlap = gitHostOverlap(routes, allow);\n if (overlap !== undefined) {\n const name = routes[overlap.index]?.route ?? \"\";\n throw invalid(\n overlap.with === \"allow\"\n ? `the host of the git route ${name} is also on the allowlist, so a tunnel could go around its filter`\n : `the host of the git route ${name} is another route's host, which could go around its filter`,\n );\n }\n return parsed;\n}\n\n/** Parses and checks one route's host, methods, header, secret and git filter. */\nfunction parseRoute(route: CredentialRoute): ParsedRoute {\n const { name, port } = splitHost(route.host, \"the route host\");\n if (!HOST_NAME.test(name) || isAddressLiteral(name))\n throw invalid(`the route host ${route.host} must be a host name`);\n const methods = route.methods.map((method) => method.toUpperCase());\n if (methods.length === 0 || !methods.every((method) => METHOD.test(method)) || methods.includes(\"CONNECT\")) {\n throw invalid(`the route ${route.route} needs a list of methods, such as [\"GET\"]`);\n }\n const header = route.header.toLowerCase();\n if (!HEADER_NAME.test(header) || RESERVED_HEADERS.has(header)) {\n throw invalid(`the route ${route.route} can't carry its credential in the header ${route.header}`);\n }\n if (typeof route.secret !== \"function\") throw invalid(`the route ${route.route} needs a secret function`);\n if (route.git !== undefined) checkGitRoute(route.git, methods, header);\n return {\n route: route.route,\n hostname: name,\n port,\n methods: new Set(methods),\n header,\n secret: route.secret,\n ...(route.git === undefined ? {} : { git: route.git }),\n };\n}\n\n/** Throws unless a git route carries its credential in `authorization` and takes exactly `GET` and `POST`. */\nfunction checkGitRoute(filter: GitRouteFilter, methods: readonly string[], header: string): void {\n checkGitFilter(filter);\n if (header !== \"authorization\") throw invalid(\"a git route carries its credential in the authorization header\");\n if (new Set(methods).size !== 2 || !methods.includes(\"GET\") || !methods.includes(\"POST\")) {\n throw invalid(\"a git route takes the methods GET and POST\");\n }\n}\n"]}
@@ -0,0 +1,69 @@
1
+ import { type CredentialRoute } from "./allowlist.js";
2
+ /** A route that swaps the sentinel in one request header for a credential, as `startEgressProxy()`'s routes do. */
3
+ export interface HeaderEgressRoute {
4
+ readonly kind: "header";
5
+ /** The first part of the path the sandbox requests, such as `github`. Lower case letters, digits, `-` and `_`. */
6
+ readonly route: string;
7
+ /** The HTTPS host the request is forwarded to, such as `api.github.com`, with `:port` when it isn't 443. */
8
+ readonly host: string;
9
+ /** The methods the route accepts, such as `["GET"]`. */
10
+ readonly methods: readonly string[];
11
+ /** The request header that carries the credential, such as `authorization`. */
12
+ readonly header: string;
13
+ /** The name of the credential the host injects, in upper case, such as `GITHUB_TOKEN`. Never the credential. */
14
+ readonly credential: string;
15
+ }
16
+ /**
17
+ * A route for git over HTTPS: git's smart HTTP requests for the listed repositories only, and a push only to the listed
18
+ * branches. A deletion and a tag are always refused, and so is anything the route can't parse.
19
+ */
20
+ export interface GitEgressRoute {
21
+ readonly kind: "git";
22
+ /** The first part of the path the sandbox's git remote uses, such as `git`. */
23
+ readonly route: string;
24
+ /** The git host, such as `github.com`. */
25
+ readonly host: string;
26
+ /** The repositories the route reaches, as `owner/name`. */
27
+ readonly repositories: readonly string[];
28
+ /** The branches a push may create or update, such as `refs/heads/agent/*`. Leave it out to refuse every push. */
29
+ readonly pushRefs?: readonly string[];
30
+ /** Whether a fetch or clone may read the repositories. Defaults to `false`. */
31
+ readonly fetch?: boolean;
32
+ /** The user name sent with the credential in HTTP Basic. Defaults to `x-access-token`, which GitHub App tokens use. */
33
+ readonly username?: string;
34
+ /** The name of the credential the host injects, in upper case, such as `GITHUB_TOKEN`. Never the credential. */
35
+ readonly credential: string;
36
+ }
37
+ /** One credential route of an `EgressPolicy`. */
38
+ export type EgressRoute = HeaderEgressRoute | GitEgressRoute;
39
+ /** What a sandbox may reach: the hosts it may tunnel to, and the routes that add a credential on its behalf. */
40
+ export interface EgressPolicy {
41
+ /** Exact host names, with `:port` when it isn't 443. A wildcard and an address literal are refused. */
42
+ readonly allow: readonly string[];
43
+ readonly routes: readonly EgressRoute[];
44
+ }
45
+ /** The options of `compileEgressPolicy()`. */
46
+ export interface CompileEgressOptions {
47
+ /** Reads the credential a route names, at each request, on the host. It never runs in the sandbox. */
48
+ readonly secret: (name: string) => Promise<string>;
49
+ }
50
+ /** A compiled policy: the `allow` and `routes` options of `startEgressProxy()`. */
51
+ export interface CompiledEgressPolicy {
52
+ readonly allow: readonly string[];
53
+ readonly routes: readonly CredentialRoute[];
54
+ }
55
+ /**
56
+ * Checks `policy` and compiles it for `startEgressProxy()`: pass the result's `allow` and `routes` with a `log`.
57
+ * Everything is refused that isn't plainly allowed, with `HarnessError` code `invalid_egress_options`, and the
58
+ * message names the entry's place, never its value:
59
+ *
60
+ * - a field a route kind doesn't have, such as `secret` or `token`, and a credential that is not an upper-case name;
61
+ * - any string in the policy that looks like a credential, such as one starting `ghp_` or `sk-`;
62
+ * - a wildcard or an address literal in `allow` or a route's host;
63
+ * - a git route whose host is also in `allow`, because a tunnel to it would go around the ref filter, and a git route
64
+ * whose host is another route's host, because that route would carry a credential there without the ref filter;
65
+ * - a git route with no repository, a push ref outside `refs/heads/`, or neither a push nor a fetch.
66
+ *
67
+ * The compiled routes read each credential through `options.secret` at every request, so a rotated one is used at once.
68
+ */
69
+ export declare function compileEgressPolicy(policy: EgressPolicy, options: CompileEgressOptions): CompiledEgressPolicy;