@buildanagent/harness 0.0.0-bootstrap.0 → 0.1.0-alpha.28
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/LICENSE +54 -0
- package/LICENSE-APACHE +202 -0
- package/LICENSE-MIT +21 -0
- package/README.md +717 -0
- package/dist/ablation.d.ts +2 -0
- package/dist/ablation.js +3 -0
- package/dist/ablation.js.map +1 -0
- package/dist/completion/check.d.ts +64 -0
- package/dist/completion/check.js +152 -0
- package/dist/completion/check.js.map +1 -0
- package/dist/completion/checks.d.ts +45 -0
- package/dist/completion/checks.js +173 -0
- package/dist/completion/checks.js.map +1 -0
- package/dist/completion/flags.d.ts +25 -0
- package/dist/completion/flags.js +87 -0
- package/dist/completion/flags.js.map +1 -0
- package/dist/completion/index.d.ts +8 -0
- package/dist/completion/index.js +9 -0
- package/dist/completion/index.js.map +1 -0
- package/dist/completion/snapshot.d.ts +33 -0
- package/dist/completion/snapshot.js +83 -0
- package/dist/completion/snapshot.js.map +1 -0
- package/dist/context/cap.d.ts +32 -0
- package/dist/context/cap.js +50 -0
- package/dist/context/cap.js.map +1 -0
- package/dist/context/estimate.d.ts +18 -0
- package/dist/context/estimate.js +20 -0
- package/dist/context/estimate.js.map +1 -0
- package/dist/context/file-spill.d.ts +5 -0
- package/dist/context/file-spill.js +25 -0
- package/dist/context/file-spill.js.map +1 -0
- package/dist/context/index.d.ts +10 -0
- package/dist/context/index.js +10 -0
- package/dist/context/index.js.map +1 -0
- package/dist/context/mask.d.ts +27 -0
- package/dist/context/mask.js +71 -0
- package/dist/context/mask.js.map +1 -0
- package/dist/context/mid-turn.d.ts +40 -0
- package/dist/context/mid-turn.js +82 -0
- package/dist/context/mid-turn.js.map +1 -0
- package/dist/context/policy.d.ts +9 -0
- package/dist/context/policy.js +140 -0
- package/dist/context/policy.js.map +1 -0
- package/dist/context/spill-ledger.d.ts +25 -0
- package/dist/context/spill-ledger.js +54 -0
- package/dist/context/spill-ledger.js.map +1 -0
- package/dist/context/spill.d.ts +6 -0
- package/dist/context/spill.js +14 -0
- package/dist/context/spill.js.map +1 -0
- package/dist/context/summarize.d.ts +53 -0
- package/dist/context/summarize.js +204 -0
- package/dist/context/summarize.js.map +1 -0
- package/dist/context/summary-template.d.ts +29 -0
- package/dist/context/summary-template.js +69 -0
- package/dist/context/summary-template.js.map +1 -0
- package/dist/context/types.d.ts +150 -0
- package/dist/context/types.js +2 -0
- package/dist/context/types.js.map +1 -0
- package/dist/context/write-cap.d.ts +19 -0
- package/dist/context/write-cap.js +41 -0
- package/dist/context/write-cap.js.map +1 -0
- package/dist/create-harness.d.ts +7 -0
- package/dist/create-harness.js +21 -0
- package/dist/create-harness.js.map +1 -0
- package/dist/credentials/addresses.d.ts +14 -0
- package/dist/credentials/addresses.js +144 -0
- package/dist/credentials/addresses.js.map +1 -0
- package/dist/credentials/allowlist.d.ts +34 -0
- package/dist/credentials/allowlist.js +77 -0
- package/dist/credentials/allowlist.js.map +1 -0
- package/dist/credentials/egress-proxy.d.ts +70 -0
- package/dist/credentials/egress-proxy.js +482 -0
- package/dist/credentials/egress-proxy.js.map +1 -0
- package/dist/credentials/index.d.ts +9 -0
- package/dist/credentials/index.js +10 -0
- package/dist/credentials/index.js.map +1 -0
- package/dist/credentials/scrub.d.ts +16 -0
- package/dist/credentials/scrub.js +93 -0
- package/dist/credentials/scrub.js.map +1 -0
- package/dist/errors.d.ts +56 -0
- package/dist/errors.js +63 -0
- package/dist/errors.js.map +1 -0
- package/dist/extensions/compose.d.ts +27 -0
- package/dist/extensions/compose.js +83 -0
- package/dist/extensions/compose.js.map +1 -0
- package/dist/extensions/context-files-node.d.ts +28 -0
- package/dist/extensions/context-files-node.js +74 -0
- package/dist/extensions/context-files-node.js.map +1 -0
- package/dist/extensions/context-files.d.ts +68 -0
- package/dist/extensions/context-files.js +214 -0
- package/dist/extensions/context-files.js.map +1 -0
- package/dist/extensions/digest.d.ts +6 -0
- package/dist/extensions/digest.js +68 -0
- package/dist/extensions/digest.js.map +1 -0
- package/dist/extensions/index.d.ts +10 -0
- package/dist/extensions/index.js +10 -0
- package/dist/extensions/index.js.map +1 -0
- package/dist/extensions/load.d.ts +42 -0
- package/dist/extensions/load.js +211 -0
- package/dist/extensions/load.js.map +1 -0
- package/dist/extensions/lock.d.ts +8 -0
- package/dist/extensions/lock.js +95 -0
- package/dist/extensions/lock.js.map +1 -0
- package/dist/extensions/node.d.ts +10 -0
- package/dist/extensions/node.js +11 -0
- package/dist/extensions/node.js.map +1 -0
- package/dist/extensions/project-dirs.d.ts +24 -0
- package/dist/extensions/project-dirs.js +97 -0
- package/dist/extensions/project-dirs.js.map +1 -0
- package/dist/extensions/skills-node.d.ts +34 -0
- package/dist/extensions/skills-node.js +123 -0
- package/dist/extensions/skills-node.js.map +1 -0
- package/dist/extensions/skills.d.ts +51 -0
- package/dist/extensions/skills.js +175 -0
- package/dist/extensions/skills.js.map +1 -0
- package/dist/extensions/trust-file.d.ts +3 -0
- package/dist/extensions/trust-file.js +62 -0
- package/dist/extensions/trust-file.js.map +1 -0
- package/dist/extensions/trust-store-node.d.ts +10 -0
- package/dist/extensions/trust-store-node.js +33 -0
- package/dist/extensions/trust-store-node.js.map +1 -0
- package/dist/extensions/types.d.ts +42 -0
- package/dist/extensions/types.js +2 -0
- package/dist/extensions/types.js.map +1 -0
- package/dist/harness.d.ts +156 -0
- package/dist/harness.js +2 -0
- package/dist/harness.js.map +1 -0
- package/dist/index.d.ts +4 -0
- package/dist/index.js +5 -0
- package/dist/index.js.map +1 -0
- package/dist/mcp/connection.d.ts +22 -0
- package/dist/mcp/connection.js +267 -0
- package/dist/mcp/connection.js.map +1 -0
- package/dist/mcp/content.d.ts +27 -0
- package/dist/mcp/content.js +177 -0
- package/dist/mcp/content.js.map +1 -0
- package/dist/mcp/errors.d.ts +19 -0
- package/dist/mcp/errors.js +21 -0
- package/dist/mcp/errors.js.map +1 -0
- package/dist/mcp/index.d.ts +10 -0
- package/dist/mcp/index.js +10 -0
- package/dist/mcp/index.js.map +1 -0
- package/dist/mcp/manager.d.ts +7 -0
- package/dist/mcp/manager.js +173 -0
- package/dist/mcp/manager.js.map +1 -0
- package/dist/mcp/record.d.ts +7 -0
- package/dist/mcp/record.js +20 -0
- package/dist/mcp/record.js.map +1 -0
- package/dist/mcp/stdio.d.ts +39 -0
- package/dist/mcp/stdio.js +382 -0
- package/dist/mcp/stdio.js.map +1 -0
- package/dist/mcp/types.d.ts +172 -0
- package/dist/mcp/types.js +2 -0
- package/dist/mcp/types.js.map +1 -0
- package/dist/memory/index.d.ts +2 -0
- package/dist/memory/index.js +3 -0
- package/dist/memory/index.js.map +1 -0
- package/dist/permissions/default-rules.d.ts +7 -0
- package/dist/permissions/default-rules.js +42 -0
- package/dist/permissions/default-rules.js.map +1 -0
- package/dist/permissions/errors.d.ts +11 -0
- package/dist/permissions/errors.js +14 -0
- package/dist/permissions/errors.js.map +1 -0
- package/dist/permissions/index.d.ts +9 -0
- package/dist/permissions/index.js +9 -0
- package/dist/permissions/index.js.map +1 -0
- package/dist/permissions/match.d.ts +33 -0
- package/dist/permissions/match.js +287 -0
- package/dist/permissions/match.js.map +1 -0
- package/dist/permissions/pipeline.d.ts +9 -0
- package/dist/permissions/pipeline.js +235 -0
- package/dist/permissions/pipeline.js.map +1 -0
- package/dist/permissions/rules.d.ts +22 -0
- package/dist/permissions/rules.js +74 -0
- package/dist/permissions/rules.js.map +1 -0
- package/dist/permissions/shadow.d.ts +5 -0
- package/dist/permissions/shadow.js +22 -0
- package/dist/permissions/shadow.js.map +1 -0
- package/dist/permissions/types.d.ts +104 -0
- package/dist/permissions/types.js +2 -0
- package/dist/permissions/types.js.map +1 -0
- package/dist/sandbox/base.d.ts +35 -0
- package/dist/sandbox/base.js +60 -0
- package/dist/sandbox/base.js.map +1 -0
- package/dist/sandbox/docker/index.d.ts +35 -0
- package/dist/sandbox/docker/index.js +448 -0
- package/dist/sandbox/docker/index.js.map +1 -0
- package/dist/sandbox/errors.d.ts +16 -0
- package/dist/sandbox/errors.js +22 -0
- package/dist/sandbox/errors.js.map +1 -0
- package/dist/sandbox/host-files.d.ts +63 -0
- package/dist/sandbox/host-files.js +248 -0
- package/dist/sandbox/host-files.js.map +1 -0
- package/dist/sandbox/index.d.ts +8 -0
- package/dist/sandbox/index.js +8 -0
- package/dist/sandbox/index.js.map +1 -0
- package/dist/sandbox/none.d.ts +17 -0
- package/dist/sandbox/none.js +108 -0
- package/dist/sandbox/none.js.map +1 -0
- package/dist/sandbox/process.d.ts +61 -0
- package/dist/sandbox/process.js +253 -0
- package/dist/sandbox/process.js.map +1 -0
- package/dist/sandbox/spawn-env.d.ts +20 -0
- package/dist/sandbox/spawn-env.js +128 -0
- package/dist/sandbox/spawn-env.js.map +1 -0
- package/dist/sandbox/srt/index.d.ts +35 -0
- package/dist/sandbox/srt/index.js +264 -0
- package/dist/sandbox/srt/index.js.map +1 -0
- package/dist/sandbox/srt/settings.d.ts +48 -0
- package/dist/sandbox/srt/settings.js +31 -0
- package/dist/sandbox/srt/settings.js.map +1 -0
- package/dist/sandbox/types.d.ts +88 -0
- package/dist/sandbox/types.js +6 -0
- package/dist/sandbox/types.js.map +1 -0
- package/dist/server/answers.d.ts +16 -0
- package/dist/server/answers.js +43 -0
- package/dist/server/answers.js.map +1 -0
- package/dist/server/connection.d.ts +99 -0
- package/dist/server/connection.js +309 -0
- package/dist/server/connection.js.map +1 -0
- package/dist/server/dispatcher.d.ts +86 -0
- package/dist/server/dispatcher.js +800 -0
- package/dist/server/dispatcher.js.map +1 -0
- package/dist/server/index.d.ts +13 -0
- package/dist/server/index.js +12 -0
- package/dist/server/index.js.map +1 -0
- package/dist/server/local-transport.d.ts +44 -0
- package/dist/server/local-transport.js +103 -0
- package/dist/server/local-transport.js.map +1 -0
- package/dist/server/outbox.d.ts +31 -0
- package/dist/server/outbox.js +130 -0
- package/dist/server/outbox.js.map +1 -0
- package/dist/server/params.d.ts +25 -0
- package/dist/server/params.js +112 -0
- package/dist/server/params.js.map +1 -0
- package/dist/server/protocol.schema.json +2448 -0
- package/dist/server/rpc-session.d.ts +43 -0
- package/dist/server/rpc-session.js +167 -0
- package/dist/server/rpc-session.js.map +1 -0
- package/dist/server/stdio-streams.d.ts +67 -0
- package/dist/server/stdio-streams.js +218 -0
- package/dist/server/stdio-streams.js.map +1 -0
- package/dist/server/stdio.d.ts +59 -0
- package/dist/server/stdio.js +189 -0
- package/dist/server/stdio.js.map +1 -0
- package/dist/server/websocket.d.ts +106 -0
- package/dist/server/websocket.js +327 -0
- package/dist/server/websocket.js.map +1 -0
- package/dist/session/approvals.d.ts +81 -0
- package/dist/session/approvals.js +217 -0
- package/dist/session/approvals.js.map +1 -0
- package/dist/session/code-call-log.d.ts +42 -0
- package/dist/session/code-call-log.js +63 -0
- package/dist/session/code-call-log.js.map +1 -0
- package/dist/session/code-call-result.d.ts +19 -0
- package/dist/session/code-call-result.js +95 -0
- package/dist/session/code-call-result.js.map +1 -0
- package/dist/session/code-call.d.ts +49 -0
- package/dist/session/code-call.js +345 -0
- package/dist/session/code-call.js.map +1 -0
- package/dist/session/effect-scope.d.ts +11 -0
- package/dist/session/effect-scope.js +10 -0
- package/dist/session/effect-scope.js.map +1 -0
- package/dist/session/errors.d.ts +19 -0
- package/dist/session/errors.js +27 -0
- package/dist/session/errors.js.map +1 -0
- package/dist/session/file-index.d.ts +8 -0
- package/dist/session/file-index.js +70 -0
- package/dist/session/file-index.js.map +1 -0
- package/dist/session/file-key-store.d.ts +16 -0
- package/dist/session/file-key-store.js +169 -0
- package/dist/session/file-key-store.js.map +1 -0
- package/dist/session/file-lock.d.ts +52 -0
- package/dist/session/file-lock.js +324 -0
- package/dist/session/file-lock.js.map +1 -0
- package/dist/session/index.d.ts +22 -0
- package/dist/session/index.js +20 -0
- package/dist/session/index.js.map +1 -0
- package/dist/session/jsonl-store.d.ts +37 -0
- package/dist/session/jsonl-store.js +386 -0
- package/dist/session/jsonl-store.js.map +1 -0
- package/dist/session/jsonl.d.ts +9 -0
- package/dist/session/jsonl.js +10 -0
- package/dist/session/jsonl.js.map +1 -0
- package/dist/session/lock.d.ts +19 -0
- package/dist/session/lock.js +2 -0
- package/dist/session/lock.js.map +1 -0
- package/dist/session/memory-store.d.ts +12 -0
- package/dist/session/memory-store.js +60 -0
- package/dist/session/memory-store.js.map +1 -0
- package/dist/session/migrate.d.ts +41 -0
- package/dist/session/migrate.js +86 -0
- package/dist/session/migrate.js.map +1 -0
- package/dist/session/pointer.d.ts +15 -0
- package/dist/session/pointer.js +22 -0
- package/dist/session/pointer.js.map +1 -0
- package/dist/session/rebuild.d.ts +53 -0
- package/dist/session/rebuild.js +230 -0
- package/dist/session/rebuild.js.map +1 -0
- package/dist/session/resume.d.ts +26 -0
- package/dist/session/resume.js +128 -0
- package/dist/session/resume.js.map +1 -0
- package/dist/session/retention.d.ts +97 -0
- package/dist/session/retention.js +702 -0
- package/dist/session/retention.js.map +1 -0
- package/dist/session/runner.d.ts +156 -0
- package/dist/session/runner.js +656 -0
- package/dist/session/runner.js.map +1 -0
- package/dist/session/scheduler.d.ts +47 -0
- package/dist/session/scheduler.js +85 -0
- package/dist/session/scheduler.js.map +1 -0
- package/dist/session/secret-key-store.d.ts +47 -0
- package/dist/session/secret-key-store.js +79 -0
- package/dist/session/secret-key-store.js.map +1 -0
- package/dist/session/session.d.ts +106 -0
- package/dist/session/session.js +353 -0
- package/dist/session/session.js.map +1 -0
- package/dist/session/sticky.d.ts +48 -0
- package/dist/session/sticky.js +232 -0
- package/dist/session/sticky.js.map +1 -0
- package/dist/session/store.d.ts +108 -0
- package/dist/session/store.js +163 -0
- package/dist/session/store.js.map +1 -0
- package/dist/telemetry/index.d.ts +2 -0
- package/dist/telemetry/index.js +3 -0
- package/dist/telemetry/index.js.map +1 -0
- package/dist/testing/fake-sandbox.d.ts +34 -0
- package/dist/testing/fake-sandbox.js +221 -0
- package/dist/testing/fake-sandbox.js.map +1 -0
- package/dist/testing/index.d.ts +10 -0
- package/dist/testing/index.js +11 -0
- package/dist/testing/index.js.map +1 -0
- package/dist/testing/key-store-conformance.d.ts +22 -0
- package/dist/testing/key-store-conformance.js +97 -0
- package/dist/testing/key-store-conformance.js.map +1 -0
- package/dist/testing/run-cases.d.ts +21 -0
- package/dist/testing/run-cases.js +20 -0
- package/dist/testing/run-cases.js.map +1 -0
- package/dist/testing/sandbox-conformance.d.ts +64 -0
- package/dist/testing/sandbox-conformance.js +361 -0
- package/dist/testing/sandbox-conformance.js.map +1 -0
- package/dist/testing/scheduler-conformance.d.ts +32 -0
- package/dist/testing/scheduler-conformance.js +72 -0
- package/dist/testing/scheduler-conformance.js.map +1 -0
- package/dist/testing/store-conformance.d.ts +21 -0
- package/dist/testing/store-conformance.js +320 -0
- package/dist/testing/store-conformance.js.map +1 -0
- package/dist/tools/errors.d.ts +13 -0
- package/dist/tools/errors.js +17 -0
- package/dist/tools/errors.js.map +1 -0
- package/dist/tools/index.d.ts +8 -0
- package/dist/tools/index.js +8 -0
- package/dist/tools/index.js.map +1 -0
- package/dist/tools/registry.d.ts +3 -0
- package/dist/tools/registry.js +234 -0
- package/dist/tools/registry.js.map +1 -0
- package/dist/tools/tool-search.d.ts +30 -0
- package/dist/tools/tool-search.js +118 -0
- package/dist/tools/tool-search.js.map +1 -0
- package/dist/tools/types.d.ts +106 -0
- package/dist/tools/types.js +2 -0
- package/dist/tools/types.js.map +1 -0
- package/llms.txt +435 -0
- package/package.json +119 -5
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `noneSandbox()`: the backend that confines nothing. It runs a command as the host's own user with the environment it
|
|
3
|
+
* is given, and it stops no mistake, no exfiltration and no hostile process, so its `stops` is empty and it refuses to
|
|
4
|
+
* be built without `unsafe: true` (HD4, ADR 0020). It exists for a machine that is already disposable and for tests of
|
|
5
|
+
* the rest of the harness. It is Node-only: it loads Node's modules by `process.getBuiltinModule()` when it is used.
|
|
6
|
+
* It starts each command in its own process group, so a timeout, an abort or a dispose ends the command's whole tree.
|
|
7
|
+
*/
|
|
8
|
+
import { HarnessError } from "../errors.js";
|
|
9
|
+
import { checkCommand, checkOptions, nodeModules, ProcessRunner } from "./process.js";
|
|
10
|
+
/** The warning written when a sandbox starts. */
|
|
11
|
+
export const NONE_SANDBOX_WARNING = "WARNING: the none sandbox confines nothing. Commands run as this user with this machine's files and network.";
|
|
12
|
+
class NoneSandbox {
|
|
13
|
+
disposed = false;
|
|
14
|
+
root;
|
|
15
|
+
modules;
|
|
16
|
+
runner;
|
|
17
|
+
constructor(root, modules) {
|
|
18
|
+
this.root = root;
|
|
19
|
+
this.modules = modules;
|
|
20
|
+
this.runner = new ProcessRunner(modules);
|
|
21
|
+
}
|
|
22
|
+
live() {
|
|
23
|
+
if (this.disposed)
|
|
24
|
+
throw new HarnessError("sandbox_disposed", "the sandbox was disposed");
|
|
25
|
+
}
|
|
26
|
+
resolve(path) {
|
|
27
|
+
return this.modules.path.resolve(this.root, path);
|
|
28
|
+
}
|
|
29
|
+
/** The working directory as an absolute path, or an error when it isn't an existing folder. */
|
|
30
|
+
async workingDirectory(options) {
|
|
31
|
+
const cwd = this.resolve(options.cwd ?? ".");
|
|
32
|
+
const stats = await this.modules.fs.stat(cwd).catch(() => undefined);
|
|
33
|
+
if (!stats?.isDirectory()) {
|
|
34
|
+
throw new HarnessError("invalid_sandbox_options", `the working directory ${cwd} is not an existing folder`);
|
|
35
|
+
}
|
|
36
|
+
return cwd;
|
|
37
|
+
}
|
|
38
|
+
async exec(command, options) {
|
|
39
|
+
this.live();
|
|
40
|
+
checkCommand(command);
|
|
41
|
+
checkOptions(options);
|
|
42
|
+
options.signal.throwIfAborted();
|
|
43
|
+
const cwd = await this.workingDirectory(options);
|
|
44
|
+
// The sandbox or the signal may have changed while the folder was checked.
|
|
45
|
+
this.live();
|
|
46
|
+
options.signal.throwIfAborted();
|
|
47
|
+
const [program, ...args] = command;
|
|
48
|
+
const { stdoutBytes: _bytes, ...result } = await this.runner.run({ program, args, cwd, env: options.env, missingProgram: "result" }, options);
|
|
49
|
+
return result;
|
|
50
|
+
}
|
|
51
|
+
async readFile(path) {
|
|
52
|
+
this.live();
|
|
53
|
+
const target = this.resolve(path);
|
|
54
|
+
try {
|
|
55
|
+
return new Uint8Array(await this.modules.fs.readFile(target));
|
|
56
|
+
}
|
|
57
|
+
catch (error) {
|
|
58
|
+
if (error.code === "ENOENT") {
|
|
59
|
+
throw new HarnessError("sandbox_not_found", `no such file: ${target}`, { cause: error });
|
|
60
|
+
}
|
|
61
|
+
throw error;
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
async writeFile(path, data) {
|
|
65
|
+
this.live();
|
|
66
|
+
const target = this.resolve(path);
|
|
67
|
+
await this.modules.fs.mkdir(this.modules.path.dirname(target), { recursive: true });
|
|
68
|
+
await this.modules.fs.writeFile(target, data);
|
|
69
|
+
}
|
|
70
|
+
async dispose() {
|
|
71
|
+
this.disposed = true;
|
|
72
|
+
await this.runner.stopAll();
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
/**
|
|
76
|
+
* Builds the `none` backend. Without `unsafe: true` it is a type error, and at run time it throws a `HarnessError`,
|
|
77
|
+
* code `unsafe_sandbox_not_acknowledged`, so a JavaScript caller can't leave it out either. Provisioning writes the
|
|
78
|
+
* warning, then the manifest's files under its root, which must be an existing absolute folder. The policy is
|
|
79
|
+
* ignored: nothing here enforces it, which is what `stops: []` says.
|
|
80
|
+
*/
|
|
81
|
+
export function noneSandbox(options) {
|
|
82
|
+
if (options?.unsafe !== true) {
|
|
83
|
+
throw new HarnessError("unsafe_sandbox_not_acknowledged", "noneSandbox confines nothing, so it needs { unsafe: true } to say the caller knows");
|
|
84
|
+
}
|
|
85
|
+
const warn = options.warn ?? ((message) => process.stderr.write(`${message}\n`));
|
|
86
|
+
return {
|
|
87
|
+
tier: "none",
|
|
88
|
+
stops: [],
|
|
89
|
+
async provision(manifest) {
|
|
90
|
+
const modules = nodeModules("none");
|
|
91
|
+
if (!modules.path.isAbsolute(manifest.root)) {
|
|
92
|
+
throw new HarnessError("invalid_sandbox_options", "a workspace manifest's root must be an absolute path");
|
|
93
|
+
}
|
|
94
|
+
const stats = await modules.fs.stat(manifest.root).catch(() => undefined);
|
|
95
|
+
if (!stats?.isDirectory()) {
|
|
96
|
+
throw new HarnessError("invalid_sandbox_options", "a workspace manifest's root must be an existing folder");
|
|
97
|
+
}
|
|
98
|
+
warn(NONE_SANDBOX_WARNING);
|
|
99
|
+
const sandbox = new NoneSandbox(manifest.root, modules);
|
|
100
|
+
const encoder = new TextEncoder();
|
|
101
|
+
for (const [path, data] of Object.entries(manifest.files ?? {})) {
|
|
102
|
+
await sandbox.writeFile(path, typeof data === "string" ? encoder.encode(data) : data);
|
|
103
|
+
}
|
|
104
|
+
return sandbox;
|
|
105
|
+
},
|
|
106
|
+
};
|
|
107
|
+
}
|
|
108
|
+
//# sourceMappingURL=none.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"none.js","sourceRoot":"","sources":["../../src/sandbox/none.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AACH,OAAO,EAAE,YAAY,EAAE,MAAM,cAAc,CAAC;AAC5C,OAAO,EAAE,YAAY,EAAE,YAAY,EAAoB,WAAW,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAWxG,iDAAiD;AACjD,MAAM,CAAC,MAAM,oBAAoB,GAC/B,8GAA8G,CAAC;AAEjH,MAAM,WAAW;IACP,QAAQ,GAAG,KAAK,CAAC;IACR,IAAI,CAAS;IACb,OAAO,CAAc;IACrB,MAAM,CAAgB;IAEvC,YAAY,IAAY,EAAE,OAAoB;QAC5C,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;QACjB,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;QACvB,IAAI,CAAC,MAAM,GAAG,IAAI,aAAa,CAAC,OAAO,CAAC,CAAC;IAC3C,CAAC;IAEO,IAAI;QACV,IAAI,IAAI,CAAC,QAAQ;YAAE,MAAM,IAA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IAAI,EAAE,CAAC,EAAE,CAAC;gBAChE,MAAM,OAAO,CAAC,SAAS,CAAC,IAAI,EAAE,OAAO,IAAI,KAAK,QAAQ,CAAC,CAAC,CAAC,OAAO,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC;YACxF,CAAC;YACD,OAAO,OAAO,CAAC;QACjB,CAAC;KACF,CAAC;AACJ,CAAC","sourcesContent":["/**\n * `noneSandbox()`: the backend that confines nothing. It runs a command as the host's own user with the environment it\n * is given, and it stops no mistake, no exfiltration and no hostile process, so its `stops` is empty and it refuses to\n * be built without `unsafe: true` (HD4, ADR 0020). It exists for a machine that is already disposable and for tests of\n * the rest of the harness. It is Node-only: it loads Node's modules by `process.getBuiltinModule()` when it is used.\n * It starts each command in its own process group, so a timeout, an abort or a dispose ends the command's whole tree.\n */\nimport { HarnessError } from \"../errors.js\";\nimport { checkCommand, checkOptions, type NodeModules, nodeModules, ProcessRunner } from \"./process.js\";\nimport type { ExecOptions, ExecResult, Sandbox, SandboxClient, WorkspaceManifest } from \"./types.js\";\n\n/** The options of `noneSandbox()`. */\nexport interface NoneSandboxOptions {\n /** Must be `true`: the caller says it knows this backend confines nothing. Leaving it out is a type error. */\n readonly unsafe: true;\n /** Receives the start-up warning, once for each sandbox provisioned. Defaults to a line on standard error. */\n readonly warn?: (message: string) => void;\n}\n\n/** The warning written when a sandbox starts. */\nexport const NONE_SANDBOX_WARNING =\n \"WARNING: the none sandbox confines nothing. Commands run as this user with this machine's files and network.\";\n\nclass NoneSandbox implements Sandbox {\n private disposed = false;\n private readonly root: string;\n private readonly modules: NodeModules;\n private readonly runner: ProcessRunner;\n\n constructor(root: string, modules: NodeModules) {\n this.root = root;\n this.modules = modules;\n this.runner = new ProcessRunner(modules);\n }\n\n private live(): void {\n if (this.disposed) throw new HarnessError(\"sandbox_disposed\", \"the sandbox was disposed\");\n }\n\n private resolve(path: string): string {\n return this.modules.path.resolve(this.root, path);\n }\n\n /** The working directory as an absolute path, or an error when it isn't an existing folder. */\n private async workingDirectory(options: ExecOptions): Promise<string> {\n const cwd = this.resolve(options.cwd ?? \".\");\n const stats = await this.modules.fs.stat(cwd).catch(() => undefined);\n if (!stats?.isDirectory()) {\n throw new HarnessError(\"invalid_sandbox_options\", `the working directory ${cwd} is not an existing folder`);\n }\n return cwd;\n }\n\n async exec(command: readonly string[], options: ExecOptions): Promise<ExecResult> {\n this.live();\n checkCommand(command);\n checkOptions(options);\n options.signal.throwIfAborted();\n const cwd = await this.workingDirectory(options);\n // The sandbox or the signal may have changed while the folder was checked.\n this.live();\n options.signal.throwIfAborted();\n const [program, ...args] = command as [string, ...string[]];\n const { stdoutBytes: _bytes, ...result } = await this.runner.run(\n { program, args, cwd, env: options.env, missingProgram: \"result\" },\n options,\n );\n return result;\n }\n\n async readFile(path: string): Promise<Uint8Array> {\n this.live();\n const target = this.resolve(path);\n try {\n return new Uint8Array(await this.modules.fs.readFile(target));\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === \"ENOENT\") {\n throw new HarnessError(\"sandbox_not_found\", `no such file: ${target}`, { cause: error });\n }\n throw error;\n }\n }\n\n async writeFile(path: string, data: Uint8Array): Promise<void> {\n this.live();\n const target = this.resolve(path);\n await this.modules.fs.mkdir(this.modules.path.dirname(target), { recursive: true });\n await this.modules.fs.writeFile(target, data);\n }\n\n async dispose(): Promise<void> {\n this.disposed = true;\n await this.runner.stopAll();\n }\n}\n\n/**\n * Builds the `none` backend. Without `unsafe: true` it is a type error, and at run time it throws a `HarnessError`,\n * code `unsafe_sandbox_not_acknowledged`, so a JavaScript caller can't leave it out either. Provisioning writes the\n * warning, then the manifest's files under its root, which must be an existing absolute folder. The policy is\n * ignored: nothing here enforces it, which is what `stops: []` says.\n */\nexport function noneSandbox(options: NoneSandboxOptions): SandboxClient {\n if ((options as { unsafe?: unknown } | undefined)?.unsafe !== true) {\n throw new HarnessError(\n \"unsafe_sandbox_not_acknowledged\",\n \"noneSandbox confines nothing, so it needs { unsafe: true } to say the caller knows\",\n );\n }\n const warn = options.warn ?? ((message: string) => process.stderr.write(`${message}\\n`));\n return {\n tier: \"none\",\n stops: [],\n async provision(manifest: WorkspaceManifest) {\n const modules = nodeModules(\"none\");\n if (!modules.path.isAbsolute(manifest.root)) {\n throw new HarnessError(\"invalid_sandbox_options\", \"a workspace manifest's root must be an absolute path\");\n }\n const stats = await modules.fs.stat(manifest.root).catch(() => undefined);\n if (!stats?.isDirectory()) {\n throw new HarnessError(\"invalid_sandbox_options\", \"a workspace manifest's root must be an existing folder\");\n }\n warn(NONE_SANDBOX_WARNING);\n const sandbox = new NoneSandbox(manifest.root, modules);\n const encoder = new TextEncoder();\n for (const [path, data] of Object.entries(manifest.files ?? {})) {\n await sandbox.writeFile(path, typeof data === \"string\" ? encoder.encode(data) : data);\n }\n return sandbox;\n },\n };\n}\n"]}
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import type { ExecOptions, ExecResult } from "./types.js";
|
|
2
|
+
/** The Node modules the backends use. */
|
|
3
|
+
export type NodeModules = {
|
|
4
|
+
readonly cp: typeof import("node:child_process");
|
|
5
|
+
readonly fs: typeof import("node:fs/promises");
|
|
6
|
+
readonly os: typeof import("node:os");
|
|
7
|
+
readonly path: typeof import("node:path");
|
|
8
|
+
readonly url: typeof import("node:url");
|
|
9
|
+
};
|
|
10
|
+
/** Node's modules, or a `SandboxUnavailableError` for `backend` on a runtime that lacks them. */
|
|
11
|
+
export declare function nodeModules(backend: string): NodeModules;
|
|
12
|
+
/** Throws unless the options are usable. */
|
|
13
|
+
export declare function checkOptions(options: ExecOptions): void;
|
|
14
|
+
/** Throws unless the command is a non-empty list of strings. */
|
|
15
|
+
export declare function checkCommand(command: readonly string[]): void;
|
|
16
|
+
/** What one process is started with. */
|
|
17
|
+
export interface ProcessSpec {
|
|
18
|
+
readonly program: string;
|
|
19
|
+
readonly args: readonly string[];
|
|
20
|
+
readonly cwd: string;
|
|
21
|
+
readonly env: Readonly<Record<string, string>>;
|
|
22
|
+
/** Bytes to write to the process's standard input before closing it. Without it, standard input is closed at once. */
|
|
23
|
+
readonly input?: Uint8Array;
|
|
24
|
+
/** Whether a program that can't be started is a result with exit code 127, as a shell gives, or a rejection. */
|
|
25
|
+
readonly missingProgram: "result" | "reject";
|
|
26
|
+
/**
|
|
27
|
+
* How long a stopped process's group has to exit after a `SIGTERM`, which lets a program clean up, before a `SIGKILL`
|
|
28
|
+
* ends what is left. Without it the group is killed at once.
|
|
29
|
+
*/
|
|
30
|
+
readonly graceMs?: number;
|
|
31
|
+
/**
|
|
32
|
+
* Runs, and is awaited, when a timeout, an abort or `stopAll()` ends the process, before its group is killed. A
|
|
33
|
+
* backend whose commands run outside the process's group, such as in a container, ends them here.
|
|
34
|
+
*/
|
|
35
|
+
readonly onStop?: () => Promise<void>;
|
|
36
|
+
}
|
|
37
|
+
/** A finished process: the `ExecResult` fields, and the raw bytes of standard output. */
|
|
38
|
+
export type ProcessResult = Extract<ExecResult, {
|
|
39
|
+
exitCode: number;
|
|
40
|
+
}> & {
|
|
41
|
+
readonly stdoutBytes: Uint8Array;
|
|
42
|
+
};
|
|
43
|
+
/** Runs processes, each in its own group, and ends them all on `stopAll()`. */
|
|
44
|
+
export declare class ProcessRunner {
|
|
45
|
+
private readonly modules;
|
|
46
|
+
private readonly running;
|
|
47
|
+
constructor(modules: NodeModules);
|
|
48
|
+
/** Kills the process's whole group, or just the process where the platform has no groups. */
|
|
49
|
+
private kill;
|
|
50
|
+
/** The exit code, and the signal's name when a signal killed the process. */
|
|
51
|
+
private exit;
|
|
52
|
+
/** Ends every process still running, each one's promise rejecting with `sandbox_disposed`, and waits until they have. */
|
|
53
|
+
stopAll(): Promise<void>;
|
|
54
|
+
/** Ends the process's group: at once, or with a `SIGTERM` first and a `SIGKILL` after `graceMs` for what is left. */
|
|
55
|
+
private end;
|
|
56
|
+
/**
|
|
57
|
+
* Runs the process and resolves when it exits, its signal aborts it, its timeout passes (exit code 124) or `stopAll()`
|
|
58
|
+
* runs. An abort rejects with the signal's reason, and `stopAll()` with `sandbox_disposed`.
|
|
59
|
+
*/
|
|
60
|
+
run(spec: ProcessSpec, options: ExecOptions): Promise<ProcessResult>;
|
|
61
|
+
}
|
|
@@ -0,0 +1,253 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The process handling that the Node-only sandbox backends share: checking a command's options, running it in its own
|
|
3
|
+
* process group, capping its output, and ending the whole tree on a timeout, an abort or a dispose. It loads Node's
|
|
4
|
+
* modules by `process.getBuiltinModule()` when it is used, so importing it costs a portable bundle nothing.
|
|
5
|
+
*/
|
|
6
|
+
import { HarnessError } from "../errors.js";
|
|
7
|
+
import { SandboxUnavailableError } from "./errors.js";
|
|
8
|
+
// The exit code GNU `timeout` uses, which callers already know.
|
|
9
|
+
const TIMEOUT_EXIT_CODE = 124;
|
|
10
|
+
// The exit code a shell gives for a program it can't find.
|
|
11
|
+
const NOT_FOUND_EXIT_CODE = 127;
|
|
12
|
+
// A shell reports a command that a signal killed as 128 plus the signal's number.
|
|
13
|
+
const SIGNAL_EXIT_BASE = 128;
|
|
14
|
+
const DEFAULT_MAX_OUTPUT_BYTES = 8 * 1024 * 1024;
|
|
15
|
+
// The longest delay a timer takes: a larger one fires at once.
|
|
16
|
+
const MAX_TIMER_MS = 2 ** 31 - 1;
|
|
17
|
+
// The longest a stop waits for a backend's `onStop` hook.
|
|
18
|
+
const STOP_HOOK_MAX_MS = 15_000;
|
|
19
|
+
/** Node's modules, or a `SandboxUnavailableError` for `backend` on a runtime that lacks them. */
|
|
20
|
+
export function nodeModules(backend) {
|
|
21
|
+
if (typeof process === "undefined" || typeof process.getBuiltinModule !== "function") {
|
|
22
|
+
throw new SandboxUnavailableError(backend, "it runs commands through Node's child_process, which this runtime lacks");
|
|
23
|
+
}
|
|
24
|
+
return {
|
|
25
|
+
cp: process.getBuiltinModule("node:child_process"),
|
|
26
|
+
fs: process.getBuiltinModule("node:fs/promises"),
|
|
27
|
+
os: process.getBuiltinModule("node:os"),
|
|
28
|
+
path: process.getBuiltinModule("node:path"),
|
|
29
|
+
url: process.getBuiltinModule("node:url"),
|
|
30
|
+
};
|
|
31
|
+
}
|
|
32
|
+
/** The length to keep of cut output, backing up over a UTF-8 character that the cut split. */
|
|
33
|
+
function whole(chunks, size) {
|
|
34
|
+
const last = chunks[chunks.length - 1];
|
|
35
|
+
if (last === undefined)
|
|
36
|
+
return 0;
|
|
37
|
+
// Find the lead byte of the last character within the final three bytes, and drop it if its character is incomplete.
|
|
38
|
+
for (let back = 1; back <= Math.min(3, last.length); back += 1) {
|
|
39
|
+
const byte = last[last.length - back];
|
|
40
|
+
if ((byte & 0xc0) === 0x80)
|
|
41
|
+
continue;
|
|
42
|
+
const need = byte >= 0xf0 ? 4 : byte >= 0xe0 ? 3 : byte >= 0xc0 ? 2 : 1;
|
|
43
|
+
return need > back ? size - back : size;
|
|
44
|
+
}
|
|
45
|
+
return size;
|
|
46
|
+
}
|
|
47
|
+
/** Throws unless the options are usable. */
|
|
48
|
+
export function checkOptions(options) {
|
|
49
|
+
const { maxOutputBytes, timeoutMs } = options;
|
|
50
|
+
if (maxOutputBytes !== undefined && !(Number.isInteger(maxOutputBytes) && maxOutputBytes >= 0)) {
|
|
51
|
+
throw new HarnessError("invalid_sandbox_options", "maxOutputBytes must be a non-negative whole number");
|
|
52
|
+
}
|
|
53
|
+
if (timeoutMs !== undefined && !(Number.isFinite(timeoutMs) && timeoutMs > 0 && timeoutMs <= MAX_TIMER_MS)) {
|
|
54
|
+
throw new HarnessError("invalid_sandbox_options", `timeoutMs must be a number from 1 to ${MAX_TIMER_MS}`);
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
/** Throws unless the command is a non-empty list of strings. */
|
|
58
|
+
export function checkCommand(command) {
|
|
59
|
+
if (!Array.isArray(command) || command.length === 0 || command.some((part) => typeof part !== "string")) {
|
|
60
|
+
throw new HarnessError("invalid_sandbox_options", "a sandbox command is a non-empty list of strings");
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
/** Keeps the first `limit` bytes of a stream and drops the rest, but keeps reading so the child never blocks. */
|
|
64
|
+
function capture(stream, limit) {
|
|
65
|
+
const chunks = [];
|
|
66
|
+
let size = 0;
|
|
67
|
+
let truncated = false;
|
|
68
|
+
stream.on("data", (chunk) => {
|
|
69
|
+
const room = limit - size;
|
|
70
|
+
if (chunk.length <= room) {
|
|
71
|
+
chunks.push(chunk);
|
|
72
|
+
size += chunk.length;
|
|
73
|
+
}
|
|
74
|
+
else {
|
|
75
|
+
if (room > 0)
|
|
76
|
+
chunks.push(chunk.subarray(0, room));
|
|
77
|
+
size = limit;
|
|
78
|
+
truncated = true;
|
|
79
|
+
}
|
|
80
|
+
});
|
|
81
|
+
const joined = () => {
|
|
82
|
+
const all = new Uint8Array(size);
|
|
83
|
+
let at = 0;
|
|
84
|
+
for (const chunk of chunks) {
|
|
85
|
+
all.set(chunk, at);
|
|
86
|
+
at += chunk.length;
|
|
87
|
+
}
|
|
88
|
+
return all;
|
|
89
|
+
};
|
|
90
|
+
return {
|
|
91
|
+
get truncated() {
|
|
92
|
+
return truncated;
|
|
93
|
+
},
|
|
94
|
+
bytes: joined,
|
|
95
|
+
text() {
|
|
96
|
+
const all = joined();
|
|
97
|
+
return new TextDecoder().decode(truncated ? all.subarray(0, whole(chunks, size)) : all);
|
|
98
|
+
},
|
|
99
|
+
};
|
|
100
|
+
}
|
|
101
|
+
/** A process's captured output as the fields of a result, with `note` added to the end of standard error. */
|
|
102
|
+
function outputOf(out, err, note) {
|
|
103
|
+
return {
|
|
104
|
+
stdout: out.text(),
|
|
105
|
+
stdoutBytes: out.bytes(),
|
|
106
|
+
stderr: `${err.text()}${note}`,
|
|
107
|
+
...(out.truncated || err.truncated ? { truncated: true } : {}),
|
|
108
|
+
};
|
|
109
|
+
}
|
|
110
|
+
/** The result for a program that can't be started, as a shell reports it. */
|
|
111
|
+
function notFound(program) {
|
|
112
|
+
return {
|
|
113
|
+
exitCode: NOT_FOUND_EXIT_CODE,
|
|
114
|
+
stdout: "",
|
|
115
|
+
stdoutBytes: new Uint8Array(),
|
|
116
|
+
stderr: `command not found: ${program}\n`,
|
|
117
|
+
};
|
|
118
|
+
}
|
|
119
|
+
/** Runs processes, each in its own group, and ends them all on `stopAll()`. */
|
|
120
|
+
export class ProcessRunner {
|
|
121
|
+
modules;
|
|
122
|
+
// What stops each process still running, so `stopAll()` can end them.
|
|
123
|
+
running = new Set();
|
|
124
|
+
constructor(modules) {
|
|
125
|
+
this.modules = modules;
|
|
126
|
+
}
|
|
127
|
+
/** Kills the process's whole group, or just the process where the platform has no groups. */
|
|
128
|
+
kill(child) {
|
|
129
|
+
const pid = child.pid;
|
|
130
|
+
if (pid === undefined)
|
|
131
|
+
return;
|
|
132
|
+
try {
|
|
133
|
+
if (process.platform === "win32")
|
|
134
|
+
child.kill("SIGKILL");
|
|
135
|
+
else
|
|
136
|
+
process.kill(-pid, "SIGKILL");
|
|
137
|
+
}
|
|
138
|
+
catch {
|
|
139
|
+
// The group is already gone, so there is nothing left to kill.
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
/** The exit code, and the signal's name when a signal killed the process. */
|
|
143
|
+
exit(code, signal) {
|
|
144
|
+
if (signal === null)
|
|
145
|
+
return { exitCode: code ?? 1 };
|
|
146
|
+
return { exitCode: SIGNAL_EXIT_BASE + (this.modules.os.constants.signals[signal] ?? 0), signal };
|
|
147
|
+
}
|
|
148
|
+
/** Ends every process still running, each one's promise rejecting with `sandbox_disposed`, and waits until they have. */
|
|
149
|
+
async stopAll() {
|
|
150
|
+
await Promise.all([...this.running].map((stop) => stop()));
|
|
151
|
+
}
|
|
152
|
+
/** Ends the process's group: at once, or with a `SIGTERM` first and a `SIGKILL` after `graceMs` for what is left. */
|
|
153
|
+
async end(child, graceMs, onStop) {
|
|
154
|
+
// Runs beside the kill, and is waited for only so long, so a hook that hangs can't hold the call.
|
|
155
|
+
const hook = onStop?.().catch(() => { });
|
|
156
|
+
const running = child.exitCode === null && child.signalCode === null;
|
|
157
|
+
if (graceMs > 0 && process.platform !== "win32" && child.pid !== undefined && running) {
|
|
158
|
+
const exited = new Promise((resolve) => child.once("exit", () => resolve()));
|
|
159
|
+
let timer;
|
|
160
|
+
const expired = new Promise((resolve) => {
|
|
161
|
+
timer = setTimeout(resolve, graceMs);
|
|
162
|
+
});
|
|
163
|
+
try {
|
|
164
|
+
process.kill(-child.pid, "SIGTERM");
|
|
165
|
+
}
|
|
166
|
+
catch {
|
|
167
|
+
// The group is already gone.
|
|
168
|
+
}
|
|
169
|
+
await Promise.race([exited, expired]);
|
|
170
|
+
clearTimeout(timer);
|
|
171
|
+
}
|
|
172
|
+
this.kill(child);
|
|
173
|
+
if (hook !== undefined)
|
|
174
|
+
await Promise.race([hook, new Promise((resolve) => setTimeout(resolve, STOP_HOOK_MAX_MS).unref())]);
|
|
175
|
+
}
|
|
176
|
+
/**
|
|
177
|
+
* Runs the process and resolves when it exits, its signal aborts it, its timeout passes (exit code 124) or `stopAll()`
|
|
178
|
+
* runs. An abort rejects with the signal's reason, and `stopAll()` with `sandbox_disposed`.
|
|
179
|
+
*/
|
|
180
|
+
run(spec, options) {
|
|
181
|
+
const limit = options.maxOutputBytes ?? DEFAULT_MAX_OUTPUT_BYTES;
|
|
182
|
+
return new Promise((resolve, reject) => {
|
|
183
|
+
const child = this.modules.cp.spawn(spec.program, [...spec.args], {
|
|
184
|
+
cwd: spec.cwd,
|
|
185
|
+
env: { ...spec.env },
|
|
186
|
+
stdio: ["pipe", "pipe", "pipe"],
|
|
187
|
+
detached: true,
|
|
188
|
+
});
|
|
189
|
+
const out = capture(child.stdout, limit);
|
|
190
|
+
const err = capture(child.stderr, limit);
|
|
191
|
+
const output = (note = "") => outputOf(out, err, note);
|
|
192
|
+
let settled = false;
|
|
193
|
+
let timer;
|
|
194
|
+
const done = (settle) => {
|
|
195
|
+
if (settled)
|
|
196
|
+
return;
|
|
197
|
+
settled = true;
|
|
198
|
+
clearTimeout(timer);
|
|
199
|
+
options.signal.removeEventListener("abort", onAbort);
|
|
200
|
+
this.running.delete(onDispose);
|
|
201
|
+
settle();
|
|
202
|
+
};
|
|
203
|
+
// Ends the whole tree and stops waiting for the pipes, which a surviving grandchild would hold open.
|
|
204
|
+
let stopping;
|
|
205
|
+
const stop = (settle) => {
|
|
206
|
+
if (stopping !== undefined || settled)
|
|
207
|
+
return stopping ?? Promise.resolve();
|
|
208
|
+
stopping = this.end(child, spec.graceMs ?? 0, spec.onStop).then(() => {
|
|
209
|
+
child.stdout.destroy();
|
|
210
|
+
child.stderr.destroy();
|
|
211
|
+
done(settle);
|
|
212
|
+
});
|
|
213
|
+
return stopping;
|
|
214
|
+
};
|
|
215
|
+
const onAbort = () => void stop(() => reject(options.signal.reason));
|
|
216
|
+
const onDispose = () => stop(() => reject(new HarnessError("sandbox_disposed", "the sandbox was disposed")));
|
|
217
|
+
options.signal.addEventListener("abort", onAbort, { once: true });
|
|
218
|
+
this.running.add(onDispose);
|
|
219
|
+
if (options.timeoutMs !== undefined) {
|
|
220
|
+
const note = `timed out after ${options.timeoutMs} ms\n`;
|
|
221
|
+
timer = setTimeout(() => void stop(() => resolve({ exitCode: TIMEOUT_EXIT_CODE, ...output(note) })), options.timeoutMs);
|
|
222
|
+
}
|
|
223
|
+
child.on("error", (error) => {
|
|
224
|
+
done(() => {
|
|
225
|
+
if (error.code === "ENOENT" && spec.missingProgram === "result") {
|
|
226
|
+
resolve(notFound(spec.program));
|
|
227
|
+
}
|
|
228
|
+
else {
|
|
229
|
+
reject(error);
|
|
230
|
+
}
|
|
231
|
+
});
|
|
232
|
+
});
|
|
233
|
+
child.on("close", (code, signal) => {
|
|
234
|
+
// A stop in progress settles the call itself, with the reason that began it.
|
|
235
|
+
if (stopping !== undefined)
|
|
236
|
+
return;
|
|
237
|
+
// A failure while building the result must reject, not leave the promise pending.
|
|
238
|
+
done(() => {
|
|
239
|
+
try {
|
|
240
|
+
resolve({ ...this.exit(code, signal), ...output() });
|
|
241
|
+
}
|
|
242
|
+
catch (error) {
|
|
243
|
+
reject(error);
|
|
244
|
+
}
|
|
245
|
+
});
|
|
246
|
+
});
|
|
247
|
+
// A process that exits before it reads its input closes the pipe, which is no error of ours.
|
|
248
|
+
child.stdin.on("error", () => { });
|
|
249
|
+
child.stdin.end(spec.input);
|
|
250
|
+
});
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
//# sourceMappingURL=process.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"process.js","sourceRoot":"","sources":["../../src/sandbox/process.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,OAAO,EAAE,YAAY,EAAE,MAAM,cAAc,CAAC;AAC5C,OAAO,EAAE,uBAAuB,EAAE,MAAM,aAAa,CAAC;AAGtD,gEAAgE;AAChE,MAAM,iBAAiB,GAAG,GAAG,CAAC;AAC9B,2DAA2D;AAC3D,MAAM,mBAAmB,GAAG,GAAG,CAAC;AAChC,kFAAkF;AAClF,MAAM,gBAAgB,GAAG,GAAG,CAAC;AAC7B,MAAM,wBAAwB,GAAG,CAAC,GAAG,IAAI,GAAG,IAAI,CAAC;AACjD,+DAA+D;AAC/D,MAAM,YAAY,GAAG,CAAC,IAAI,EAAE,GAAG,CAAC,CAAC;AACjC,0DAA0D;AAC1D,MAAM,gBAAgB,GAAG,MAAM,CAAC;AAWhC,iGAAiG;AACjG,MAAM,UAAU,WAAW,CAAC,OAAe;IACzC,IAAI,OAAO,OAAO,KAAK,WAAW,IAAI,OAAO,OAAO,CAAC,gBAAgB,KAAK,UAAU,EAAE,CAAC;QACrF,MAAM,IAAI,uBAAuB,CAC/B,OAAO,EACP,yEAAyE,CAC1E,CAAC;IACJ,CAAC;IACD,OAAO;QACL,EAAE,EAAE,OAAO,CAAC,gBAAgB,CAAC,oBAAoB,CAAC;QAClD,EAAE,EAAE,OAAO,CAAC,gBAAgB,CAAC,kBAAkB,CAAC;QAChD,EAAE,EAAE,OAAO,CAAC,gBAAgB,CAAC,SAA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CACF","sourcesContent":["/**\n * The process handling that the Node-only sandbox backends share: checking a command's options, running it in its own\n * process group, capping its output, and ending the whole tree on a timeout, an abort or a dispose. It loads Node's\n * modules by `process.getBuiltinModule()` when it is used, so importing it costs a portable bundle nothing.\n */\nimport { HarnessError } from \"../errors.js\";\nimport { SandboxUnavailableError } from \"./errors.js\";\nimport type { ExecOptions, ExecResult } from \"./types.js\";\n\n// The exit code GNU `timeout` uses, which callers already know.\nconst TIMEOUT_EXIT_CODE = 124;\n// The exit code a shell gives for a program it can't find.\nconst NOT_FOUND_EXIT_CODE = 127;\n// A shell reports a command that a signal killed as 128 plus the signal's number.\nconst SIGNAL_EXIT_BASE = 128;\nconst DEFAULT_MAX_OUTPUT_BYTES = 8 * 1024 * 1024;\n// The longest delay a timer takes: a larger one fires at once.\nconst MAX_TIMER_MS = 2 ** 31 - 1;\n// The longest a stop waits for a backend's `onStop` hook.\nconst STOP_HOOK_MAX_MS = 15_000;\n\n/** The Node modules the backends use. */\nexport type NodeModules = {\n readonly cp: typeof import(\"node:child_process\");\n readonly fs: typeof import(\"node:fs/promises\");\n readonly os: typeof import(\"node:os\");\n readonly path: typeof import(\"node:path\");\n readonly url: typeof import(\"node:url\");\n};\n\n/** Node's modules, or a `SandboxUnavailableError` for `backend` on a runtime that lacks them. */\nexport function nodeModules(backend: string): NodeModules {\n if (typeof process === \"undefined\" || typeof process.getBuiltinModule !== \"function\") {\n throw new SandboxUnavailableError(\n backend,\n \"it runs commands through Node's child_process, which this runtime lacks\",\n );\n }\n return {\n cp: process.getBuiltinModule(\"node:child_process\"),\n fs: process.getBuiltinModule(\"node:fs/promises\"),\n os: process.getBuiltinModule(\"node:os\"),\n path: process.getBuiltinModule(\"node:path\"),\n url: process.getBuiltinModule(\"node:url\"),\n };\n}\n\n/** The length to keep of cut output, backing up over a UTF-8 character that the cut split. */\nfunction whole(chunks: readonly Uint8Array[], size: number): number {\n const last = chunks[chunks.length - 1];\n if (last === undefined) return 0;\n // Find the lead byte of the last character within the final three bytes, and drop it if its character is incomplete.\n for (let back = 1; back <= Math.min(3, last.length); back += 1) {\n const byte = last[last.length - back] as number;\n if ((byte & 0xc0) === 0x80) continue;\n const need = byte >= 0xf0 ? 4 : byte >= 0xe0 ? 3 : byte >= 0xc0 ? 2 : 1;\n return need > back ? size - back : size;\n }\n return size;\n}\n\n/** Throws unless the options are usable. */\nexport function checkOptions(options: ExecOptions): void {\n const { maxOutputBytes, timeoutMs } = options;\n if (maxOutputBytes !== undefined && !(Number.isInteger(maxOutputBytes) && maxOutputBytes >= 0)) {\n throw new HarnessError(\"invalid_sandbox_options\", \"maxOutputBytes must be a non-negative whole number\");\n }\n if (timeoutMs !== undefined && !(Number.isFinite(timeoutMs) && timeoutMs > 0 && timeoutMs <= MAX_TIMER_MS)) {\n throw new HarnessError(\"invalid_sandbox_options\", `timeoutMs must be a number from 1 to ${MAX_TIMER_MS}`);\n }\n}\n\n/** Throws unless the command is a non-empty list of strings. */\nexport function checkCommand(command: readonly string[]): void {\n if (!Array.isArray(command) || command.length === 0 || command.some((part) => typeof part !== \"string\")) {\n throw new HarnessError(\"invalid_sandbox_options\", \"a sandbox command is a non-empty list of strings\");\n }\n}\n\n/** Keeps the first `limit` bytes of a stream and drops the rest, but keeps reading so the child never blocks. */\nfunction capture(stream: NodeJS.ReadableStream, limit: number) {\n const chunks: Uint8Array[] = [];\n let size = 0;\n let truncated = false;\n stream.on(\"data\", (chunk: Uint8Array) => {\n const room = limit - size;\n if (chunk.length <= room) {\n chunks.push(chunk);\n size += chunk.length;\n } else {\n if (room > 0) chunks.push(chunk.subarray(0, room));\n size = limit;\n truncated = true;\n }\n });\n const joined = (): Uint8Array => {\n const all = new Uint8Array(size);\n let at = 0;\n for (const chunk of chunks) {\n all.set(chunk, at);\n at += chunk.length;\n }\n return all;\n };\n return {\n get truncated() {\n return truncated;\n },\n bytes: joined,\n text(): string {\n const all = joined();\n return new TextDecoder().decode(truncated ? all.subarray(0, whole(chunks, size)) : all);\n },\n };\n}\n\ntype Capture = ReturnType<typeof capture>;\n\n/** A process's captured output as the fields of a result, with `note` added to the end of standard error. */\nfunction outputOf(out: Capture, err: Capture, note: string) {\n return {\n stdout: out.text(),\n stdoutBytes: out.bytes(),\n stderr: `${err.text()}${note}`,\n ...(out.truncated || err.truncated ? { truncated: true } : {}),\n };\n}\n\n/** The result for a program that can't be started, as a shell reports it. */\nfunction notFound(program: string) {\n return {\n exitCode: NOT_FOUND_EXIT_CODE,\n stdout: \"\",\n stdoutBytes: new Uint8Array(),\n stderr: `command not found: ${program}\\n`,\n };\n}\n\n/** What one process is started with. */\nexport interface ProcessSpec {\n readonly program: string;\n readonly args: readonly string[];\n readonly cwd: string;\n readonly env: Readonly<Record<string, string>>;\n /** Bytes to write to the process's standard input before closing it. Without it, standard input is closed at once. */\n readonly input?: Uint8Array;\n /** Whether a program that can't be started is a result with exit code 127, as a shell gives, or a rejection. */\n readonly missingProgram: \"result\" | \"reject\";\n /**\n * How long a stopped process's group has to exit after a `SIGTERM`, which lets a program clean up, before a `SIGKILL`\n * ends what is left. Without it the group is killed at once.\n */\n readonly graceMs?: number;\n /**\n * Runs, and is awaited, when a timeout, an abort or `stopAll()` ends the process, before its group is killed. A\n * backend whose commands run outside the process's group, such as in a container, ends them here.\n */\n readonly onStop?: () => Promise<void>;\n}\n\n/** A finished process: the `ExecResult` fields, and the raw bytes of standard output. */\nexport type ProcessResult = Extract<ExecResult, { exitCode: number }> & { readonly stdoutBytes: Uint8Array };\n\n/** Runs processes, each in its own group, and ends them all on `stopAll()`. */\nexport class ProcessRunner {\n private readonly modules: NodeModules;\n // What stops each process still running, so `stopAll()` can end them.\n private readonly running = new Set<() => Promise<void>>();\n\n constructor(modules: NodeModules) {\n this.modules = modules;\n }\n\n /** Kills the process's whole group, or just the process where the platform has no groups. */\n private kill(child: import(\"node:child_process\").ChildProcess): void {\n const pid = child.pid;\n if (pid === undefined) return;\n try {\n if (process.platform === \"win32\") child.kill(\"SIGKILL\");\n else process.kill(-pid, \"SIGKILL\");\n } catch {\n // The group is already gone, so there is nothing left to kill.\n }\n }\n\n /** The exit code, and the signal's name when a signal killed the process. */\n private exit(code: number | null, signal: NodeJS.Signals | null): { exitCode: number; signal?: string } {\n if (signal === null) return { exitCode: code ?? 1 };\n return { exitCode: SIGNAL_EXIT_BASE + (this.modules.os.constants.signals[signal] ?? 0), signal };\n }\n\n /** Ends every process still running, each one's promise rejecting with `sandbox_disposed`, and waits until they have. */\n async stopAll(): Promise<void> {\n await Promise.all([...this.running].map((stop) => stop()));\n }\n\n /** Ends the process's group: at once, or with a `SIGTERM` first and a `SIGKILL` after `graceMs` for what is left. */\n private async end(\n child: import(\"node:child_process\").ChildProcess,\n graceMs: number,\n onStop?: () => Promise<void>,\n ): Promise<void> {\n // Runs beside the kill, and is waited for only so long, so a hook that hangs can't hold the call.\n const hook = onStop?.().catch(() => {});\n const running = child.exitCode === null && child.signalCode === null;\n if (graceMs > 0 && process.platform !== \"win32\" && child.pid !== undefined && running) {\n const exited = new Promise<void>((resolve) => child.once(\"exit\", () => resolve()));\n let timer: ReturnType<typeof setTimeout> | undefined;\n const expired = new Promise<void>((resolve) => {\n timer = setTimeout(resolve, graceMs);\n });\n try {\n process.kill(-child.pid, \"SIGTERM\");\n } catch {\n // The group is already gone.\n }\n await Promise.race([exited, expired]);\n clearTimeout(timer);\n }\n this.kill(child);\n if (hook !== undefined)\n await Promise.race([hook, new Promise<void>((resolve) => setTimeout(resolve, STOP_HOOK_MAX_MS).unref())]);\n }\n\n /**\n * Runs the process and resolves when it exits, its signal aborts it, its timeout passes (exit code 124) or `stopAll()`\n * runs. An abort rejects with the signal's reason, and `stopAll()` with `sandbox_disposed`.\n */\n run(spec: ProcessSpec, options: ExecOptions): Promise<ProcessResult> {\n const limit = options.maxOutputBytes ?? DEFAULT_MAX_OUTPUT_BYTES;\n return new Promise((resolve, reject) => {\n const child = this.modules.cp.spawn(spec.program, [...spec.args], {\n cwd: spec.cwd,\n env: { ...spec.env },\n stdio: [\"pipe\", \"pipe\", \"pipe\"],\n detached: true,\n });\n const out = capture(child.stdout, limit);\n const err = capture(child.stderr, limit);\n const output = (note = \"\") => outputOf(out, err, note);\n let settled = false;\n let timer: ReturnType<typeof setTimeout> | undefined;\n const done = (settle: () => void) => {\n if (settled) return;\n settled = true;\n clearTimeout(timer);\n options.signal.removeEventListener(\"abort\", onAbort);\n this.running.delete(onDispose);\n settle();\n };\n // Ends the whole tree and stops waiting for the pipes, which a surviving grandchild would hold open.\n let stopping: Promise<void> | undefined;\n const stop = (settle: () => void): Promise<void> => {\n if (stopping !== undefined || settled) return stopping ?? Promise.resolve();\n stopping = this.end(child, spec.graceMs ?? 0, spec.onStop).then(() => {\n child.stdout.destroy();\n child.stderr.destroy();\n done(settle);\n });\n return stopping;\n };\n const onAbort = () => void stop(() => reject(options.signal.reason));\n const onDispose = () => stop(() => reject(new HarnessError(\"sandbox_disposed\", \"the sandbox was disposed\")));\n options.signal.addEventListener(\"abort\", onAbort, { once: true });\n this.running.add(onDispose);\n if (options.timeoutMs !== undefined) {\n const note = `timed out after ${options.timeoutMs} ms\\n`;\n timer = setTimeout(\n () => void stop(() => resolve({ exitCode: TIMEOUT_EXIT_CODE, ...output(note) })),\n options.timeoutMs,\n );\n }\n child.on(\"error\", (error: NodeJS.ErrnoException) => {\n done(() => {\n if (error.code === \"ENOENT\" && spec.missingProgram === \"result\") {\n resolve(notFound(spec.program));\n } else {\n reject(error);\n }\n });\n });\n child.on(\"close\", (code, signal) => {\n // A stop in progress settles the call itself, with the reason that began it.\n if (stopping !== undefined) return;\n // A failure while building the result must reject, not leave the promise pending.\n done(() => {\n try {\n resolve({ ...this.exit(code, signal), ...output() });\n } catch (error) {\n reject(error);\n }\n });\n });\n // A process that exits before it reads its input closes the pipe, which is no error of ours.\n child.stdin.on(\"error\", () => {});\n child.stdin.end(spec.input);\n });\n }\n}\n"]}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The environment for a spawned process: `PATH`, a fresh temp `HOME`, `TMPDIR` and `LANG`, plus the parent variables
|
|
3
|
+
* named in `allow` that are set, plus every `extra`. Nothing else is copied. `HOME` is a new folder under the temp
|
|
4
|
+
* directory on each call, which the caller removes when the process is done, so a tool that writes dotfiles never
|
|
5
|
+
* touches the real home.
|
|
6
|
+
*
|
|
7
|
+
* `PATH` is the parent's with every entry that isn't absolute removed, and `TMPDIR` is the shared temp directory.
|
|
8
|
+
* When `extra` sets `HOME`, no temp folder is made.
|
|
9
|
+
*
|
|
10
|
+
* `allow` takes plain names, such as `DOCKER_HOST`. It refuses a reserved name (`PATH`, `HOME`, `TMPDIR`, `LANG`), which
|
|
11
|
+
* is always set already; a name that looks like a credential, because a `_`-separated part of it is `KEY`, `TOKEN`,
|
|
12
|
+
* `SECRET`, `PASSWORD`, `PAT`, `AUTH` and the like, or because it is a connection string or a proxy URL such as
|
|
13
|
+
* `DATABASE_URL`; and a name that makes a program load code, such as `NODE_OPTIONS` or `LD_PRELOAD`. A credential can
|
|
14
|
+
* reach a child only as an explicit `extra`. The check goes by name, so it can't catch a credential under an
|
|
15
|
+
* unremarkable name. `extra` overrides everything and holds the values the caller writes itself.
|
|
16
|
+
*
|
|
17
|
+
* Throws a `HarnessError`, code `invalid_spawn_env`, for a name that isn't a variable name or a value that isn't a
|
|
18
|
+
* string without a NUL character.
|
|
19
|
+
*/
|
|
20
|
+
export declare function spawnEnv(allow: readonly string[], extra?: Readonly<Record<string, string>>): Record<string, string>;
|
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `spawnEnv()`: the cleared environment every process the harness spawns gets, so an inherited credential can never
|
|
3
|
+
* reach a child (AGENTS.md, "Running third-party code"; ADR 0036). It is Node-only, because it reads the parent's
|
|
4
|
+
* environment and makes a temp folder, so it loads Node's modules by `process.getBuiltinModule()` when it is called,
|
|
5
|
+
* not by an import, and the sandbox entry still loads on a runtime without them.
|
|
6
|
+
*/
|
|
7
|
+
import { HarnessError } from "../errors.js";
|
|
8
|
+
// Where a child finds its programs when the parent has no PATH, which only a parent started without a shell lacks.
|
|
9
|
+
const DEFAULT_PATH = "/usr/local/bin:/usr/bin:/bin";
|
|
10
|
+
const DEFAULT_LANG = "C.UTF-8";
|
|
11
|
+
// The variables every child gets, by `spawnEnv()` itself. A caller names no other source for them.
|
|
12
|
+
const RESERVED = ["PATH", "HOME", "TMPDIR", "LANG"];
|
|
13
|
+
const NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;
|
|
14
|
+
// A name that says it holds a credential, matched by each `_`-separated segment so `GIT_AUTHOR_NAME` and
|
|
15
|
+
// `KEYBOARD_LAYOUT` pass and `GH_PAT` and `ANTHROPIC_API_KEY` don't. These reach a child only through `extra`, where the
|
|
16
|
+
// caller writes the value in code, such as a dummy key for a proxy, and never by being copied from the parent.
|
|
17
|
+
// A word that ends a part catches a joined one such as `GITHUBTOKEN`; a short word must be the whole part, so `PATH` and
|
|
18
|
+
// `PASSIVE` pass. `PASS` and `AUTH` refuse a name like `PASS_THROUGH`, which is the safe side: it passes as an `extra`.
|
|
19
|
+
const CREDENTIAL_ENDING = /(KEY|TOKEN|SECRET|PASSWORD|PASSWD|CREDENTIALS?)$/;
|
|
20
|
+
const CREDENTIAL_WORD = /^(PASS|PGPASS|PAT|AUTH|AUTHORIZATION|COOKIE|DSN)$/;
|
|
21
|
+
// Names that hold a credential without a word that says so: a connection string or a proxy URL can carry a password.
|
|
22
|
+
const CREDENTIAL_NAMES = new Set([
|
|
23
|
+
"DATABASE_URL",
|
|
24
|
+
"REDIS_URL",
|
|
25
|
+
"MONGODB_URI",
|
|
26
|
+
"HTTP_PROXY",
|
|
27
|
+
"HTTPS_PROXY",
|
|
28
|
+
"ALL_PROXY",
|
|
29
|
+
"NPM_CONFIG__AUTH",
|
|
30
|
+
]);
|
|
31
|
+
// Names that make a program load the caller's code or change where it looks, which a copy from the parent must not do.
|
|
32
|
+
const LOADER_NAMES = new Set([
|
|
33
|
+
"NODE_OPTIONS",
|
|
34
|
+
"LD_PRELOAD",
|
|
35
|
+
"LD_LIBRARY_PATH",
|
|
36
|
+
"DYLD_INSERT_LIBRARIES",
|
|
37
|
+
"DYLD_LIBRARY_PATH",
|
|
38
|
+
"BASH_ENV",
|
|
39
|
+
"ENV",
|
|
40
|
+
"NODE_PATH",
|
|
41
|
+
"NODE_EXTRA_CA_CERTS",
|
|
42
|
+
"PYTHONPATH",
|
|
43
|
+
"PYTHONSTARTUP",
|
|
44
|
+
"PERL5OPT",
|
|
45
|
+
"RUBYOPT",
|
|
46
|
+
"LD_AUDIT",
|
|
47
|
+
"GIT_SSH_COMMAND",
|
|
48
|
+
"GIT_ASKPASS",
|
|
49
|
+
"GIT_CONFIG_GLOBAL",
|
|
50
|
+
"GIT_CONFIG_COUNT",
|
|
51
|
+
]);
|
|
52
|
+
function looksLikeCredential(name) {
|
|
53
|
+
const upper = name.toUpperCase();
|
|
54
|
+
return (CREDENTIAL_NAMES.has(upper) ||
|
|
55
|
+
upper.split("_").some((part) => CREDENTIAL_ENDING.test(part) || CREDENTIAL_WORD.test(part)));
|
|
56
|
+
}
|
|
57
|
+
// The parent's PATH without an entry that isn't absolute, because "." or an empty entry would run a program from
|
|
58
|
+
// whatever folder a command starts in. It falls back to `DEFAULT_PATH` when nothing absolute is left.
|
|
59
|
+
function safePath(parentPath, path) {
|
|
60
|
+
const kept = (parentPath ?? "").split(path.delimiter).filter((entry) => path.isAbsolute(entry));
|
|
61
|
+
return kept.length > 0 ? kept.join(path.delimiter) : DEFAULT_PATH;
|
|
62
|
+
}
|
|
63
|
+
function refuse(message) {
|
|
64
|
+
return new HarnessError("invalid_spawn_env", `spawnEnv: ${message}`);
|
|
65
|
+
}
|
|
66
|
+
function checkName(name) {
|
|
67
|
+
if (!NAME.test(name))
|
|
68
|
+
throw refuse(`${JSON.stringify(name)} is not a valid variable name`);
|
|
69
|
+
}
|
|
70
|
+
function checkValue(name, value) {
|
|
71
|
+
if (typeof value !== "string" || value.includes("\0")) {
|
|
72
|
+
throw refuse(`the value of ${name} must be a string without a NUL character`);
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
/**
|
|
76
|
+
* The environment for a spawned process: `PATH`, a fresh temp `HOME`, `TMPDIR` and `LANG`, plus the parent variables
|
|
77
|
+
* named in `allow` that are set, plus every `extra`. Nothing else is copied. `HOME` is a new folder under the temp
|
|
78
|
+
* directory on each call, which the caller removes when the process is done, so a tool that writes dotfiles never
|
|
79
|
+
* touches the real home.
|
|
80
|
+
*
|
|
81
|
+
* `PATH` is the parent's with every entry that isn't absolute removed, and `TMPDIR` is the shared temp directory.
|
|
82
|
+
* When `extra` sets `HOME`, no temp folder is made.
|
|
83
|
+
*
|
|
84
|
+
* `allow` takes plain names, such as `DOCKER_HOST`. It refuses a reserved name (`PATH`, `HOME`, `TMPDIR`, `LANG`), which
|
|
85
|
+
* is always set already; a name that looks like a credential, because a `_`-separated part of it is `KEY`, `TOKEN`,
|
|
86
|
+
* `SECRET`, `PASSWORD`, `PAT`, `AUTH` and the like, or because it is a connection string or a proxy URL such as
|
|
87
|
+
* `DATABASE_URL`; and a name that makes a program load code, such as `NODE_OPTIONS` or `LD_PRELOAD`. A credential can
|
|
88
|
+
* reach a child only as an explicit `extra`. The check goes by name, so it can't catch a credential under an
|
|
89
|
+
* unremarkable name. `extra` overrides everything and holds the values the caller writes itself.
|
|
90
|
+
*
|
|
91
|
+
* Throws a `HarnessError`, code `invalid_spawn_env`, for a name that isn't a variable name or a value that isn't a
|
|
92
|
+
* string without a NUL character.
|
|
93
|
+
*/
|
|
94
|
+
export function spawnEnv(allow, extra = {}) {
|
|
95
|
+
const fs = process.getBuiltinModule("node:fs");
|
|
96
|
+
const os = process.getBuiltinModule("node:os");
|
|
97
|
+
const path = process.getBuiltinModule("node:path");
|
|
98
|
+
for (const name of allow) {
|
|
99
|
+
checkName(name);
|
|
100
|
+
if (RESERVED.includes(name))
|
|
101
|
+
throw refuse(`${name} is always set, so it can't be allowed`);
|
|
102
|
+
if (LOADER_NAMES.has(name.toUpperCase())) {
|
|
103
|
+
throw refuse(`${name} changes what a program loads, so it can't be copied from the parent; pass it in \`extra\``);
|
|
104
|
+
}
|
|
105
|
+
if (looksLikeCredential(name)) {
|
|
106
|
+
throw refuse(`${name} looks like a credential, so it can't be copied from the parent; pass it in \`extra\` if the child needs it`);
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
for (const [name, value] of Object.entries(extra)) {
|
|
110
|
+
checkName(name);
|
|
111
|
+
checkValue(name, value);
|
|
112
|
+
}
|
|
113
|
+
// A caller's own HOME replaces ours, so making a folder for it would leave one behind that nothing removes.
|
|
114
|
+
const home = "HOME" in extra ? extra.HOME : fs.mkdtempSync(path.join(os.tmpdir(), "buildanagent-home-"));
|
|
115
|
+
const env = {
|
|
116
|
+
PATH: safePath(process.env.PATH, path),
|
|
117
|
+
HOME: home,
|
|
118
|
+
TMPDIR: os.tmpdir(),
|
|
119
|
+
LANG: process.env.LANG ?? DEFAULT_LANG,
|
|
120
|
+
};
|
|
121
|
+
for (const name of allow) {
|
|
122
|
+
const value = process.env[name];
|
|
123
|
+
if (value !== undefined)
|
|
124
|
+
env[name] = value;
|
|
125
|
+
}
|
|
126
|
+
return { ...env, ...extra };
|
|
127
|
+
}
|
|
128
|
+
//# sourceMappingURL=spawn-env.js.map
|