benignswarm 0.12.95 → 0.12.97
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/dist/admin-index.js +0 -0
- package/dist/args.js +39 -3
- package/dist/brief.js +5 -1
- package/dist/client.js +207 -1
- package/dist/commands/admin.js +84 -22
- package/dist/commands/agent.js +15 -2
- package/dist/commands/cloud-admin.js +56 -3
- package/dist/commands/codex-start.js +333 -239
- package/dist/commands/environment-admin.js +130 -0
- package/dist/commands/environment.js +53 -0
- package/dist/commands/evidence.js +6 -3
- package/dist/commands/feedback.js +12 -1
- package/dist/commands/flow.js +153 -0
- package/dist/commands/hook.js +29 -9
- package/dist/commands/image-admin.js +77 -0
- package/dist/commands/install.js +81 -3
- package/dist/commands/lists.js +4 -0
- package/dist/commands/machine-admin.js +444 -111
- package/dist/commands/machine-resize.js +234 -0
- package/dist/commands/machine.js +957 -39
- package/dist/commands/operator.js +5 -8
- package/dist/commands/retire.js +4 -0
- package/dist/commands/templates.js +27 -0
- package/dist/commands/watch.js +43 -10
- package/dist/commands/wu.js +131 -81
- package/dist/container.js +480 -0
- package/dist/environment-checks.js +79 -0
- package/dist/git.js +29 -1
- package/dist/help.js +88 -34
- package/dist/index.js +5 -1
- package/dist/install.js +43 -1
- package/dist/macos-readiness.js +173 -0
- package/dist/output.js +15 -4
- package/dist/templates.js +218 -0
- package/dist/test-workers.js +17 -0
- package/dist/turn.js +6 -0
- package/dist/usage.js +117 -0
- package/dist/version.js +1 -1
- package/package.json +1 -1
|
@@ -0,0 +1,480 @@
|
|
|
1
|
+
import { spawnSync } from "node:child_process";
|
|
2
|
+
import { createHash } from "node:crypto";
|
|
3
|
+
import { chmodSync, existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
|
4
|
+
import { homedir } from "node:os";
|
|
5
|
+
import { join, resolve } from "node:path";
|
|
6
|
+
const defaultRunner = (cmd, args, opts) => spawnSync(cmd, args, {
|
|
7
|
+
encoding: "utf8",
|
|
8
|
+
timeout: opts?.timeout ?? 15_000,
|
|
9
|
+
cwd: opts?.cwd,
|
|
10
|
+
env: opts?.env,
|
|
11
|
+
...(opts?.uid !== undefined ? { uid: opts.uid } : {}),
|
|
12
|
+
});
|
|
13
|
+
const SHA256_IMAGE_RE = /^[a-z0-9][a-z0-9._/-]*@sha256:[a-f0-9]{64}$/i;
|
|
14
|
+
const FORBIDDEN_MOUNT_RE = /(\/var\/run\/docker\.sock|\/\.ssh(?:\/|$)|\/\.aws(?:\/|$)|\.b9s\/machine\.json|169\.254\.169\.254|fd00:ec2::254)/i;
|
|
15
|
+
const FORBIDDEN_FLAG_RE = /(--privileged|--cap-add(?:=|\s+)(?:SYS_ADMIN|ALL)|--net(?:work)?(?:=|\s+)host|--pid(?:=|\s+)host|--userns(?:=|\s+)host)/i;
|
|
16
|
+
const SECRET_KEY_RE = /(AWS_ACCESS_KEY_ID|AWS_SECRET_ACCESS_KEY|AWS_SESSION_TOKEN|OPENAI_API_KEY|ANTHROPIC_API_KEY|DEEPSEEK_API_KEY|GITHUB_TOKEN|GH_TOKEN|BSCHAT_KEY|B9S_KEY|BOT_TOKEN|PRIVATE_KEY)/i;
|
|
17
|
+
const SECRET_VALUE_RE = /(bs_(?:admin|agent|machine|enroll|boot)_[A-Za-z0-9]+|gh[pousr]_[A-Za-z0-9_]+|sk-[A-Za-z0-9_-]{12,}|AKIA[0-9A-Z]{16})/;
|
|
18
|
+
function canonicalSort(v) {
|
|
19
|
+
if (Array.isArray(v))
|
|
20
|
+
return v.map(canonicalSort);
|
|
21
|
+
if (v && typeof v === "object") {
|
|
22
|
+
const o = v;
|
|
23
|
+
return Object.fromEntries(Object.keys(o).sort().map((k) => [k, canonicalSort(o[k])]));
|
|
24
|
+
}
|
|
25
|
+
return v;
|
|
26
|
+
}
|
|
27
|
+
function scanUnsafe(value, where) {
|
|
28
|
+
if (typeof value === "string") {
|
|
29
|
+
if (SECRET_VALUE_RE.test(value))
|
|
30
|
+
return `${where} contains secret-like material`;
|
|
31
|
+
if (FORBIDDEN_MOUNT_RE.test(value))
|
|
32
|
+
return `${where} mounts forbidden host, socket, or metadata path`;
|
|
33
|
+
if (FORBIDDEN_FLAG_RE.test(value))
|
|
34
|
+
return `${where} specifies forbidden container privilege or host-namespace flag`;
|
|
35
|
+
return null;
|
|
36
|
+
}
|
|
37
|
+
if (Array.isArray(value)) {
|
|
38
|
+
for (let i = 0; i < value.length; i++) {
|
|
39
|
+
const err = scanUnsafe(value[i], `${where}[${i}]`);
|
|
40
|
+
if (err)
|
|
41
|
+
return err;
|
|
42
|
+
}
|
|
43
|
+
return null;
|
|
44
|
+
}
|
|
45
|
+
if (value && typeof value === "object") {
|
|
46
|
+
for (const [k, v] of Object.entries(value)) {
|
|
47
|
+
if (SECRET_KEY_RE.test(k))
|
|
48
|
+
return `${where}.${k} references a secret key; build secrets are forbidden`;
|
|
49
|
+
const err = scanUnsafe(v, `${where}.${k}`);
|
|
50
|
+
if (err)
|
|
51
|
+
return err;
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
return null;
|
|
55
|
+
}
|
|
56
|
+
export function validateDevcontainerSpec(devcontainerRaw, opts = {}) {
|
|
57
|
+
let dc;
|
|
58
|
+
if (typeof devcontainerRaw === "string") {
|
|
59
|
+
try {
|
|
60
|
+
dc = JSON.parse(devcontainerRaw);
|
|
61
|
+
}
|
|
62
|
+
catch (e) {
|
|
63
|
+
return { ok: false, error: `invalid devcontainer JSON: ${e.message}` };
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
else if (devcontainerRaw && typeof devcontainerRaw === "object" && !Array.isArray(devcontainerRaw)) {
|
|
67
|
+
dc = devcontainerRaw;
|
|
68
|
+
}
|
|
69
|
+
else {
|
|
70
|
+
return { ok: false, error: "devcontainer must be a JSON object" };
|
|
71
|
+
}
|
|
72
|
+
if ("secrets" in dc)
|
|
73
|
+
return { ok: false, error: "build secrets are out of scope and refused" };
|
|
74
|
+
if (dc.privileged === true)
|
|
75
|
+
return { ok: false, error: "devcontainer privileged=true is forbidden" };
|
|
76
|
+
for (const field of ["build", "containerEnv", "remoteEnv", "mounts", "runArgs"]) {
|
|
77
|
+
const err = scanUnsafe(dc[field], `devcontainer.${field}`);
|
|
78
|
+
if (err)
|
|
79
|
+
return { ok: false, error: err };
|
|
80
|
+
}
|
|
81
|
+
let baseDigest = "";
|
|
82
|
+
if (typeof dc.image === "string") {
|
|
83
|
+
const ref = dc.image.trim();
|
|
84
|
+
if (/:latest\b/i.test(ref) || !SHA256_IMAGE_RE.test(ref)) {
|
|
85
|
+
return { ok: false, error: `devcontainer.image ${JSON.stringify(ref)} must pin @sha256:<64-hex>` };
|
|
86
|
+
}
|
|
87
|
+
baseDigest = ref.slice(ref.indexOf("@sha256:") + 1).toLowerCase();
|
|
88
|
+
}
|
|
89
|
+
else if (dc.build && typeof dc.build === "object") {
|
|
90
|
+
const df = opts.dockerfileContent ?? "";
|
|
91
|
+
if (!df.trim())
|
|
92
|
+
return { ok: false, error: "dockerfileContent required to verify pinned FROM digests" };
|
|
93
|
+
const fromMatches = [...df.matchAll(/^\s*FROM\s+(?:--platform=\S+\s+)?(\S+)/gim)];
|
|
94
|
+
if (!fromMatches.length)
|
|
95
|
+
return { ok: false, error: "Dockerfile must contain a pinned FROM instruction" };
|
|
96
|
+
for (const m of fromMatches) {
|
|
97
|
+
const ref = m[1];
|
|
98
|
+
if (ref.toLowerCase() === "scratch")
|
|
99
|
+
continue;
|
|
100
|
+
if (/:latest\b/i.test(ref) || !SHA256_IMAGE_RE.test(ref)) {
|
|
101
|
+
return { ok: false, error: `Dockerfile FROM ${JSON.stringify(ref)} must pin @sha256:<64-hex>` };
|
|
102
|
+
}
|
|
103
|
+
if (!baseDigest)
|
|
104
|
+
baseDigest = ref.slice(ref.indexOf("@sha256:") + 1).toLowerCase();
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
else {
|
|
108
|
+
return { ok: false, error: "devcontainer must specify digest-pinned image or build.dockerfile" };
|
|
109
|
+
}
|
|
110
|
+
const featureKeys = [];
|
|
111
|
+
if (dc.features !== undefined) {
|
|
112
|
+
if (!dc.features || typeof dc.features !== "object" || Array.isArray(dc.features)) {
|
|
113
|
+
return { ok: false, error: "devcontainer.features must be an object" };
|
|
114
|
+
}
|
|
115
|
+
for (const [ref, cfg] of Object.entries(dc.features)) {
|
|
116
|
+
if (/:latest\b/i.test(ref) || !/(@sha256:[a-f0-9]{64}|:\d+\.\d+(?:\.\d+)?)$/.test(ref)) {
|
|
117
|
+
return { ok: false, error: `devcontainer feature ${JSON.stringify(ref)} must be pinned by version or @sha256 digest` };
|
|
118
|
+
}
|
|
119
|
+
const err = scanUnsafe(cfg, `devcontainer.features[${ref}]`);
|
|
120
|
+
if (err)
|
|
121
|
+
return { ok: false, error: err };
|
|
122
|
+
featureKeys.push(ref);
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
const recipeHash = createHash("sha256")
|
|
126
|
+
.update(JSON.stringify(canonicalSort({
|
|
127
|
+
devcontainer: dc,
|
|
128
|
+
dockerfile: opts.dockerfileContent ?? null,
|
|
129
|
+
lockfile: opts.lockfileContent ?? null,
|
|
130
|
+
target_arch: opts.targetArch ?? "linux/amd64",
|
|
131
|
+
})))
|
|
132
|
+
.digest("hex");
|
|
133
|
+
return { ok: true, base_image_digest: baseDigest, features: featureKeys, recipe_hash: recipeHash };
|
|
134
|
+
}
|
|
135
|
+
export function readGitIdentity(cwd, runner = defaultRunner) {
|
|
136
|
+
const nameRes = runner("git", ["config", "--get", "user.name"], { cwd });
|
|
137
|
+
const emailRes = runner("git", ["config", "--get", "user.email"], { cwd });
|
|
138
|
+
const userName = nameRes.status === 0 && nameRes.stdout.trim() ? nameRes.stdout.trim() : null;
|
|
139
|
+
const userEmail = emailRes.status === 0 && emailRes.stdout.trim() ? emailRes.stdout.trim() : null;
|
|
140
|
+
return { ok: Boolean(userName && userEmail), user_name: userName, user_email: userEmail };
|
|
141
|
+
}
|
|
142
|
+
export function probeNestedSandbox(opts = {}) {
|
|
143
|
+
const runner = opts.runner ?? defaultRunner;
|
|
144
|
+
const platform = opts.platform ?? process.platform;
|
|
145
|
+
const readSysctl = opts.readSysctl ?? ((p) => (existsSync(p) ? readFileSync(p, "utf8").trim() : null));
|
|
146
|
+
let runtime = opts.runtime ?? null;
|
|
147
|
+
if (!runtime) {
|
|
148
|
+
for (const candidate of ["podman", "docker"]) {
|
|
149
|
+
const r = runner(candidate, ["--version"]);
|
|
150
|
+
if (r.status === 0) {
|
|
151
|
+
runtime = candidate;
|
|
152
|
+
break;
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
if (!runtime) {
|
|
157
|
+
return { runtime: null, ok: false, nested_sandbox_ok: false, missing: ["container_runtime"], detail: "neither podman nor docker is available" };
|
|
158
|
+
}
|
|
159
|
+
const missing = [];
|
|
160
|
+
if (platform === "linux") {
|
|
161
|
+
const unprivUserns = readSysctl("/proc/sys/kernel/unprivileged_userns_clone");
|
|
162
|
+
if (unprivUserns === "0")
|
|
163
|
+
missing.push("unprivileged_userns");
|
|
164
|
+
const maxUserns = readSysctl("/proc/sys/user/max_user_namespaces");
|
|
165
|
+
if (maxUserns !== null && Number(maxUserns) === 0)
|
|
166
|
+
missing.push("max_user_namespaces");
|
|
167
|
+
const unshare = runner("unshare", ["--user", "--net", "--pid", "--fork", "true"]);
|
|
168
|
+
if (unshare.status !== 0 && !missing.includes("unprivileged_userns")) {
|
|
169
|
+
const stderr = `${unshare.stderr}${unshare.stdout}`.trim();
|
|
170
|
+
if (/EPERM|Operation not permitted|user namespace/i.test(stderr))
|
|
171
|
+
missing.push("user_namespaces");
|
|
172
|
+
}
|
|
173
|
+
const selfStatus = readSysctl("/proc/self/status");
|
|
174
|
+
if (selfStatus && /Seccomp:\s*0\b/.test(selfStatus)) {
|
|
175
|
+
// Seccomp=0 on host process just means current shell isn't filtered; check kernel config or container probe below
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
const info = runner(runtime, ["info", "--format", "{{json .}}"]);
|
|
179
|
+
if (info.status !== 0) {
|
|
180
|
+
missing.push("runtime_daemon");
|
|
181
|
+
}
|
|
182
|
+
else if (platform === "linux") {
|
|
183
|
+
try {
|
|
184
|
+
const parsed = JSON.parse(info.stdout);
|
|
185
|
+
const secOpts = parsed.SecurityOptions ?? [];
|
|
186
|
+
const hasSeccomp = Boolean(parsed.host?.security?.seccompProfile) || secOpts.some((s) => /seccomp/i.test(s));
|
|
187
|
+
if (secOpts.length > 0 && !hasSeccomp)
|
|
188
|
+
missing.push("seccomp");
|
|
189
|
+
}
|
|
190
|
+
catch {
|
|
191
|
+
// Ignore parse failures on varied podman/docker templates; unshare check already validates namespaces.
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
const ok = missing.length === 0;
|
|
195
|
+
return {
|
|
196
|
+
runtime,
|
|
197
|
+
ok,
|
|
198
|
+
nested_sandbox_ok: ok,
|
|
199
|
+
missing,
|
|
200
|
+
detail: ok ? `${runtime} nested namespace/sandbox prerequisites verified` : `missing host sandbox capability: ${missing.join(", ")}`,
|
|
201
|
+
};
|
|
202
|
+
}
|
|
203
|
+
const IMDS_V4_URL = "http://169.254.169.254/latest/meta-data/";
|
|
204
|
+
const IMDS_V6_URL = "http://[fd00:ec2::254]/latest/meta-data/";
|
|
205
|
+
function defaultProbeImdsEndpoint(url, runner, uid) {
|
|
206
|
+
const res = runner("curl", ["-sS", "--max-time", "0.4", "-o", "/dev/null", url], { timeout: 1_500, ...(uid === 0 ? { uid: 1000 } : {}) });
|
|
207
|
+
if (res.error || res.status === null || res.status === 127)
|
|
208
|
+
return null;
|
|
209
|
+
if (res.status === 0)
|
|
210
|
+
return true;
|
|
211
|
+
if (res.status === 7 || res.status === 28)
|
|
212
|
+
return false;
|
|
213
|
+
return null;
|
|
214
|
+
}
|
|
215
|
+
export function probeImdsIsolation(opts = {}) {
|
|
216
|
+
const platformName = opts.platformName ?? process.platform;
|
|
217
|
+
const currentUid = opts.uid !== undefined ? opts.uid : (typeof process.getuid === "function" ? process.getuid() : null);
|
|
218
|
+
if (platformName !== "linux" && !opts.runner && !opts.probeEndpoint) {
|
|
219
|
+
return {
|
|
220
|
+
ok: false,
|
|
221
|
+
ipv4_firewall_blocked: false,
|
|
222
|
+
ipv6_firewall_blocked: false,
|
|
223
|
+
ipv4_reachable: null,
|
|
224
|
+
ipv6_reachable: null,
|
|
225
|
+
missing: ["linux_netfilter_iptables", "linux_netfilter_ip6tables"],
|
|
226
|
+
detail: `IMDS firewall isolation requires Linux netfilter rules (current platform: ${platformName})`,
|
|
227
|
+
};
|
|
228
|
+
}
|
|
229
|
+
const runner = opts.runner ?? defaultRunner;
|
|
230
|
+
const checkRule = (cmd, args) => {
|
|
231
|
+
const direct = runner(cmd, args, { timeout: 3_000 });
|
|
232
|
+
if (direct.status === 0)
|
|
233
|
+
return true;
|
|
234
|
+
if (!opts.runner && currentUid !== null && currentUid !== 0 && /permission|operation not permitted|root/i.test(direct.stderr ?? "")) {
|
|
235
|
+
const sudoRes = runner("sudo", ["-n", cmd, ...args], { timeout: 3_000 });
|
|
236
|
+
return sudoRes.status === 0;
|
|
237
|
+
}
|
|
238
|
+
return false;
|
|
239
|
+
};
|
|
240
|
+
const missing = [];
|
|
241
|
+
const ipv4FirewallBlocked = checkRule("iptables", ["-C", "OUTPUT", "-m", "owner", "--uid-owner", "1000", "-d", "169.254.169.254/32", "-j", "REJECT"]) &&
|
|
242
|
+
checkRule("iptables", ["-C", "FORWARD", "-d", "169.254.169.254/32", "-j", "DROP"]);
|
|
243
|
+
if (!ipv4FirewallBlocked)
|
|
244
|
+
missing.push("ipv4_imds_firewall");
|
|
245
|
+
const ipv6FirewallBlocked = checkRule("ip6tables", ["-C", "OUTPUT", "-m", "owner", "--uid-owner", "1000", "-d", "fd00:ec2::254/128", "-j", "REJECT"]) &&
|
|
246
|
+
checkRule("ip6tables", ["-C", "FORWARD", "-d", "fd00:ec2::254/128", "-j", "DROP"]);
|
|
247
|
+
if (!ipv6FirewallBlocked)
|
|
248
|
+
missing.push("ipv6_imds_firewall");
|
|
249
|
+
const probe = opts.probeEndpoint
|
|
250
|
+
?? ((t) => platformName === "linux" ? defaultProbeImdsEndpoint(t.url, runner, currentUid) : null);
|
|
251
|
+
const ipv4Reachable = probe({ family: "ipv4", url: IMDS_V4_URL });
|
|
252
|
+
const ipv6Reachable = probe({ family: "ipv6", url: IMDS_V6_URL });
|
|
253
|
+
if (ipv4Reachable !== false)
|
|
254
|
+
missing.push(ipv4Reachable === true ? "ipv4_imds_reachable" : "ipv4_imds_unverified");
|
|
255
|
+
if (ipv6Reachable !== false)
|
|
256
|
+
missing.push(ipv6Reachable === true ? "ipv6_imds_reachable" : "ipv6_imds_unverified");
|
|
257
|
+
const ok = missing.length === 0 && ipv4FirewallBlocked && ipv6FirewallBlocked && ipv4Reachable === false && ipv6Reachable === false;
|
|
258
|
+
return {
|
|
259
|
+
ok,
|
|
260
|
+
ipv4_firewall_blocked: ipv4FirewallBlocked,
|
|
261
|
+
ipv6_firewall_blocked: ipv6FirewallBlocked,
|
|
262
|
+
ipv4_reachable: ipv4Reachable,
|
|
263
|
+
ipv6_reachable: ipv6Reachable,
|
|
264
|
+
missing,
|
|
265
|
+
detail: ok
|
|
266
|
+
? "IPv4 (169.254.169.254/32) and IPv6 (fd00:ec2::254/128) IMDS endpoints verified blocked"
|
|
267
|
+
: `IMDS isolation check failed (fail-closed): ${missing.join(", ")}`,
|
|
268
|
+
};
|
|
269
|
+
}
|
|
270
|
+
export function isolatedImageMetadata(opts) {
|
|
271
|
+
const cacheKey = `acct-${opts.accountId}-proj-${opts.projectId}-${opts.arch.replace(/[^a-z0-9-]/gi, "-")}`;
|
|
272
|
+
const imageRef = `${opts.registryNamespace}:${opts.sourceCommit.slice(0, 12)}-${opts.arch.replace(/\//g, "-")}`;
|
|
273
|
+
return { imageRef, cacheKey };
|
|
274
|
+
}
|
|
275
|
+
export function isolatedBuildCommand(opts) {
|
|
276
|
+
const { imageRef, cacheKey } = isolatedImageMetadata(opts);
|
|
277
|
+
const args = [
|
|
278
|
+
"build",
|
|
279
|
+
"--platform",
|
|
280
|
+
opts.arch,
|
|
281
|
+
"--no-cache=false",
|
|
282
|
+
"--label",
|
|
283
|
+
`benignswarm.account=${opts.accountId}`,
|
|
284
|
+
"--label",
|
|
285
|
+
`benignswarm.project=${opts.projectId}`,
|
|
286
|
+
"--label",
|
|
287
|
+
`benignswarm.cache=${cacheKey}`,
|
|
288
|
+
"-f",
|
|
289
|
+
opts.dockerfilePath,
|
|
290
|
+
"-t",
|
|
291
|
+
imageRef,
|
|
292
|
+
opts.contextDir,
|
|
293
|
+
];
|
|
294
|
+
return { cmd: opts.runtime, args, imageRef, cacheKey };
|
|
295
|
+
}
|
|
296
|
+
/**
|
|
297
|
+
* Constructs isolated runtime pull + tag commands for digest-pinned `image`-only devcontainers
|
|
298
|
+
* that omit `build` and `features`.
|
|
299
|
+
*/
|
|
300
|
+
export function isolatedImagePullCommands(opts) {
|
|
301
|
+
const sourceImage = opts.sourceImage.trim();
|
|
302
|
+
if (/:latest\b/i.test(sourceImage) || !SHA256_IMAGE_RE.test(sourceImage)) {
|
|
303
|
+
throw new Error(`refusing image pull without immutable @sha256 digest: ${JSON.stringify(opts.sourceImage)}`);
|
|
304
|
+
}
|
|
305
|
+
const { imageRef, cacheKey } = isolatedImageMetadata(opts);
|
|
306
|
+
return {
|
|
307
|
+
cmd: opts.runtime,
|
|
308
|
+
pullArgs: ["pull", "--platform", opts.arch, sourceImage],
|
|
309
|
+
tagArgs: ["tag", sourceImage, imageRef],
|
|
310
|
+
imageRef,
|
|
311
|
+
cacheKey,
|
|
312
|
+
};
|
|
313
|
+
}
|
|
314
|
+
/**
|
|
315
|
+
* Constructs an isolated `@devcontainers/cli` (`devcontainer build`) command when
|
|
316
|
+
* `devcontainer.json` declares pinned `features` so features are actually applied.
|
|
317
|
+
*/
|
|
318
|
+
export function isolatedDevcontainerBuildCommand(opts) {
|
|
319
|
+
const { imageRef, cacheKey } = isolatedImageMetadata(opts);
|
|
320
|
+
return {
|
|
321
|
+
cmd: "devcontainer",
|
|
322
|
+
args: [
|
|
323
|
+
"build",
|
|
324
|
+
"--workspace-folder",
|
|
325
|
+
opts.workspaceFolder,
|
|
326
|
+
"--config",
|
|
327
|
+
opts.configPath,
|
|
328
|
+
"--docker-path",
|
|
329
|
+
opts.runtime,
|
|
330
|
+
"--platform",
|
|
331
|
+
opts.arch,
|
|
332
|
+
"--image-name",
|
|
333
|
+
imageRef,
|
|
334
|
+
],
|
|
335
|
+
imageRef,
|
|
336
|
+
cacheKey,
|
|
337
|
+
};
|
|
338
|
+
}
|
|
339
|
+
export function agentContainerName(accountSlug, project, agent) {
|
|
340
|
+
return `b9s-${accountSlug}-${project}-${agent}`.toLowerCase().replace(/[^a-z0-9_.-]/g, "-").slice(0, 60);
|
|
341
|
+
}
|
|
342
|
+
export function agentContainerRunArgs(opts) {
|
|
343
|
+
if (!SHA256_IMAGE_RE.test(opts.imageDigest) || /:latest\b/i.test(opts.imageDigest)) {
|
|
344
|
+
throw new Error(`refusing container launch with unpinned image ${JSON.stringify(opts.imageDigest)}; @sha256 digest required`);
|
|
345
|
+
}
|
|
346
|
+
const wt = resolve(opts.worktreeDir);
|
|
347
|
+
const home = resolve(opts.agentHomeDir);
|
|
348
|
+
const hostHome = resolve(homedir());
|
|
349
|
+
for (const candidate of [wt, home]) {
|
|
350
|
+
if (candidate === "/" || candidate === hostHome || FORBIDDEN_MOUNT_RE.test(candidate)) {
|
|
351
|
+
throw new Error(`refusing unsafe container mount path ${candidate}`);
|
|
352
|
+
}
|
|
353
|
+
}
|
|
354
|
+
if (wt === home) {
|
|
355
|
+
throw new Error(`refusing shared container worktree and home path ${wt}`);
|
|
356
|
+
}
|
|
357
|
+
const safeName = agentContainerName(opts.accountSlug, opts.project, opts.agent);
|
|
358
|
+
const args = [
|
|
359
|
+
"run",
|
|
360
|
+
...(opts.detach ? ["-d", "--init"] : []),
|
|
361
|
+
"--rm",
|
|
362
|
+
"--name",
|
|
363
|
+
safeName,
|
|
364
|
+
"--security-opt",
|
|
365
|
+
"no-new-privileges",
|
|
366
|
+
"--add-host",
|
|
367
|
+
"169.254.169.254:127.0.0.1",
|
|
368
|
+
"--add-host",
|
|
369
|
+
"metadata.google.internal:127.0.0.1",
|
|
370
|
+
"-v",
|
|
371
|
+
`${wt}:/workspace:rw`,
|
|
372
|
+
"-v",
|
|
373
|
+
`${home}:/home/agent:rw`,
|
|
374
|
+
"-w",
|
|
375
|
+
"/workspace",
|
|
376
|
+
"-e",
|
|
377
|
+
"HOME=/home/agent",
|
|
378
|
+
];
|
|
379
|
+
for (const cacheName of opts.allowedCaches ?? []) {
|
|
380
|
+
if (!/^[a-z0-9][a-z0-9._-]{0,63}$/.test(cacheName)) {
|
|
381
|
+
throw new Error(`invalid allowed cache name ${JSON.stringify(cacheName)}`);
|
|
382
|
+
}
|
|
383
|
+
if (!opts.cacheRootDir)
|
|
384
|
+
continue;
|
|
385
|
+
const hostCache = resolve(join(opts.cacheRootDir, cacheName));
|
|
386
|
+
if (FORBIDDEN_MOUNT_RE.test(hostCache))
|
|
387
|
+
throw new Error(`refusing unsafe cache path ${hostCache}`);
|
|
388
|
+
args.push("-v", `${hostCache}:/caches/${cacheName}:rw`);
|
|
389
|
+
}
|
|
390
|
+
for (const [k, v] of Object.entries(opts.extraEnv ?? {})) {
|
|
391
|
+
if (SECRET_KEY_RE.test(k) && v.includes("machine.json"))
|
|
392
|
+
continue;
|
|
393
|
+
args.push("-e", `${k}=${v}`);
|
|
394
|
+
}
|
|
395
|
+
args.push(opts.imageDigest, ...opts.command);
|
|
396
|
+
return args;
|
|
397
|
+
}
|
|
398
|
+
/**
|
|
399
|
+
* Constructs a secret-free host subprocess environment for disposable image builds and
|
|
400
|
+
* container-runtime client invocations, stripping AWS, harness, GitHub, and machine credentials.
|
|
401
|
+
*/
|
|
402
|
+
export function isolatedSubprocessEnv(baseEnv = process.env, extraEnv = {}) {
|
|
403
|
+
const out = {};
|
|
404
|
+
const allowKeys = ["PATH", "LANG", "LC_ALL", "TERM", "TMPDIR", "XDG_RUNTIME_DIR", "CONTAINER_HOST", "DOCKER_HOST"];
|
|
405
|
+
for (const key of allowKeys) {
|
|
406
|
+
const v = baseEnv[key];
|
|
407
|
+
if (v)
|
|
408
|
+
out[key] = v;
|
|
409
|
+
}
|
|
410
|
+
for (const [k, v] of Object.entries(extraEnv)) {
|
|
411
|
+
if (!SECRET_KEY_RE.test(k))
|
|
412
|
+
out[k] = v;
|
|
413
|
+
}
|
|
414
|
+
return out;
|
|
415
|
+
}
|
|
416
|
+
export function fetchAwsSecretToEphemeralFile(opts) {
|
|
417
|
+
const runner = opts.runner ?? defaultRunner;
|
|
418
|
+
if (!/^arn:aws(?:-[a-z]+)*:secretsmanager:[a-z0-9-]+:\d{12}:secret:[A-Za-z0-9/_+=.@*-]+$/.test(opts.secretArn)) {
|
|
419
|
+
throw new Error("invalid AWS Secrets Manager ARN");
|
|
420
|
+
}
|
|
421
|
+
const r = runner("aws", [
|
|
422
|
+
"secretsmanager",
|
|
423
|
+
"get-secret-value",
|
|
424
|
+
"--secret-id",
|
|
425
|
+
opts.secretArn,
|
|
426
|
+
"--region",
|
|
427
|
+
opts.region,
|
|
428
|
+
"--query",
|
|
429
|
+
"SecretString",
|
|
430
|
+
"--output",
|
|
431
|
+
"text",
|
|
432
|
+
]);
|
|
433
|
+
if (r.status !== 0 || !r.stdout) {
|
|
434
|
+
throw new Error(`failed to fetch AWS secret reference ${opts.secretArn.split(":").pop() ?? "secret"}`);
|
|
435
|
+
}
|
|
436
|
+
mkdirSync(opts.targetDir, { recursive: true, mode: 0o700 });
|
|
437
|
+
const filePath = join(opts.targetDir, opts.filename);
|
|
438
|
+
writeFileSync(filePath, r.stdout.replace(/\r?\n$/, "") + "\n", { mode: 0o600 });
|
|
439
|
+
chmodSync(filePath, 0o600);
|
|
440
|
+
return {
|
|
441
|
+
path: filePath,
|
|
442
|
+
cleanup: () => {
|
|
443
|
+
try {
|
|
444
|
+
rmSync(filePath, { force: true });
|
|
445
|
+
}
|
|
446
|
+
catch { /* best-effort cleanup */ }
|
|
447
|
+
},
|
|
448
|
+
};
|
|
449
|
+
}
|
|
450
|
+
/**
|
|
451
|
+
* Resolves the most specific Secrets Manager reference (project-scoped before account-wide,
|
|
452
|
+
* matching provider before 'default') and materializes it into an ephemeral 0600 key file
|
|
453
|
+
* only for the duration of process startup, returning cleanup + env bindings without logging values.
|
|
454
|
+
*/
|
|
455
|
+
export function resolveSessionSecretDelivery(opts) {
|
|
456
|
+
const provider = opts.session.provider ?? "anthropic";
|
|
457
|
+
const match = opts.secrets
|
|
458
|
+
.filter((x) => x.harness === opts.session.harness && (x.provider === provider || x.provider === "default") && (!x.project_id || x.project_id === opts.session.project_id))
|
|
459
|
+
.sort((a, b) => (b.project_id ? 1 : 0) - (a.project_id ? 1 : 0) || (b.provider === provider ? 1 : 0) - (a.provider === provider ? 1 : 0))[0];
|
|
460
|
+
if (!match)
|
|
461
|
+
return { env: {}, cleanup: () => { } };
|
|
462
|
+
const fetched = fetchAwsSecretToEphemeralFile({
|
|
463
|
+
secretArn: match.secret_arn,
|
|
464
|
+
region: match.region,
|
|
465
|
+
targetDir: opts.targetDir,
|
|
466
|
+
filename: `ephemeral-${opts.session.id}.key`,
|
|
467
|
+
runner: opts.runner,
|
|
468
|
+
});
|
|
469
|
+
const value = readFileSync(fetched.path, "utf8").trim();
|
|
470
|
+
const env = {};
|
|
471
|
+
if (opts.session.harness === "codex")
|
|
472
|
+
env.OPENAI_API_KEY = value;
|
|
473
|
+
else if (opts.session.harness === "claude-code" && provider === "deepseek")
|
|
474
|
+
env.DEEPSEEK_API_KEY_FILE = fetched.path;
|
|
475
|
+
else if (opts.session.harness === "claude-code")
|
|
476
|
+
env.ANTHROPIC_API_KEY = value;
|
|
477
|
+
else
|
|
478
|
+
env.B9S_HARNESS_CREDENTIAL_FILE = fetched.path;
|
|
479
|
+
return { env, cleanup: fetched.cleanup };
|
|
480
|
+
}
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
import { accessSync, constants, existsSync } from "node:fs";
|
|
2
|
+
import { platform } from "node:os";
|
|
3
|
+
function sandboxCheck(name, probe) {
|
|
4
|
+
if (!probe || typeof probe !== "object")
|
|
5
|
+
return {
|
|
6
|
+
check: `${name}_sandbox`, category: "sandbox", component: name, status: "unknown",
|
|
7
|
+
observation: `${name} sandbox check was unavailable`, remedy: null, recovery_verified: false,
|
|
8
|
+
};
|
|
9
|
+
const result = probe;
|
|
10
|
+
if (result.ok === true)
|
|
11
|
+
return {
|
|
12
|
+
check: `${name}_sandbox`, category: "sandbox", component: name, status: "healthy",
|
|
13
|
+
observation: `${name} sandbox no-op completed`, remedy: null, recovery_verified: true,
|
|
14
|
+
};
|
|
15
|
+
const detail = typeof result.error === "string" ? result.error : "sandbox no-op failed";
|
|
16
|
+
const namespace = /userns|user namespace|uid map|unshare/i.test(detail);
|
|
17
|
+
return {
|
|
18
|
+
check: `${name}_sandbox`, category: "sandbox", component: name, status: "failed",
|
|
19
|
+
observation: namespace ? `${name} sandbox could not create its required user namespace` : `${name} sandbox no-op failed`,
|
|
20
|
+
remedy: namespace
|
|
21
|
+
? "Check host policy with b9s machine prepare --print-apparmor; apply the exact profile only with host-owner authorization, or select a supported sandbox mode."
|
|
22
|
+
: `Read the ${name} sandbox startup error, distinguish a policy denial from a service outage, and use the named supported remedy; do not retry turns automatically.`,
|
|
23
|
+
recovery_verified: false,
|
|
24
|
+
};
|
|
25
|
+
}
|
|
26
|
+
/** Convert existing daemon facts into bounded, privacy-safe diagnostic records. */
|
|
27
|
+
export function machineEnvironmentChecks(facts, writableRoots, options = {}) {
|
|
28
|
+
const os = options.os ?? platform();
|
|
29
|
+
const exists = options.exists ?? existsSync;
|
|
30
|
+
const writable = options.writable ?? ((path) => { try {
|
|
31
|
+
accessSync(path, constants.W_OK);
|
|
32
|
+
return true;
|
|
33
|
+
}
|
|
34
|
+
catch {
|
|
35
|
+
return false;
|
|
36
|
+
} });
|
|
37
|
+
const checks = [];
|
|
38
|
+
const path = typeof facts.daemon_path === "string" ? facts.daemon_path : "";
|
|
39
|
+
checks.push({
|
|
40
|
+
check: "daemon_path", category: "path", component: "machine daemon", status: path ? "healthy" : "unknown",
|
|
41
|
+
observation: path ? "daemon PATH was recorded" : "daemon PATH was unavailable",
|
|
42
|
+
remedy: path ? null : "Run b9s doctor from the service environment and compare its PATH with the recorded daemon PATH.",
|
|
43
|
+
recovery_verified: !!path,
|
|
44
|
+
});
|
|
45
|
+
const codex = facts.codex && typeof facts.codex === "object" ? facts.codex : null;
|
|
46
|
+
const claude = facts["claude-code"] && typeof facts["claude-code"] === "object" ? facts["claude-code"] : facts.claude_code;
|
|
47
|
+
checks.push(sandboxCheck("codex", codex?.sandbox));
|
|
48
|
+
checks.push(sandboxCheck("claude_code", claude && typeof claude === "object" ? claude.sandbox : undefined));
|
|
49
|
+
const namespaceFailure = checks.some((check) => check.category === "sandbox" && check.status === "failed" && /user namespace/i.test(check.observation));
|
|
50
|
+
checks.push({
|
|
51
|
+
check: "linux_user_namespaces", category: "user_namespace", component: "sandbox runtime",
|
|
52
|
+
status: os !== "linux" ? "unknown" : namespaceFailure ? "failed" : checks.some((check) => check.category === "sandbox" && check.status === "healthy") ? "healthy" : "unknown",
|
|
53
|
+
observation: os !== "linux" ? "Linux user namespace support is not applicable to this platform" : namespaceFailure ? "sandbox probe reports that required user namespaces are unavailable" : "no failed user namespace probe was observed",
|
|
54
|
+
remedy: os !== "linux" || !namespaceFailure ? null : "Check b9s machine prepare --print-apparmor and the exact harness profile; changing host policy requires explicit host-owner authorization.",
|
|
55
|
+
recovery_verified: os === "linux" && !namespaceFailure && checks.some((check) => check.category === "sandbox" && check.status === "healthy"),
|
|
56
|
+
});
|
|
57
|
+
const rootResults = writableRoots.map((root) => ({ root, exists: exists(root), writable: exists(root) && writable(root) }));
|
|
58
|
+
const badRoots = rootResults.filter((result) => !result.exists || !result.writable);
|
|
59
|
+
checks.push({
|
|
60
|
+
check: "workspace_writable_roots", category: "writable_root", component: "machine configuration",
|
|
61
|
+
status: badRoots.length ? "failed" : "healthy",
|
|
62
|
+
observation: badRoots.length ? `${badRoots.length} configured writable root(s) are missing or not writable` : `${rootResults.length} configured writable root(s) are present and writable`,
|
|
63
|
+
remedy: badRoots.length ? "Inspect the current list with b9s-admin machine show <machine>; create the specific missing directory or use b9s-admin machine writable while retaining every currently allowed path." : null,
|
|
64
|
+
recovery_verified: badRoots.length === 0,
|
|
65
|
+
});
|
|
66
|
+
for (const [label, free, total] of [["home", facts.disk_free_bytes, facts.disk_total_bytes], ["workdir", facts.workdir_free_bytes, facts.workdir_total_bytes]]) {
|
|
67
|
+
const known = typeof free === "number" && typeof total === "number" && total > 0 && free >= 0 && free <= total;
|
|
68
|
+
const pct = known ? (free / total) * 100 : null;
|
|
69
|
+
const low = pct !== null && pct < 10;
|
|
70
|
+
checks.push({
|
|
71
|
+
check: `${label}_disk_space`, category: "storage", component: `${label} volume`,
|
|
72
|
+
status: !known ? "unknown" : low ? "failed" : "healthy",
|
|
73
|
+
observation: !known ? `${label} volume free-space reading is unavailable` : `${label} volume has ${Math.floor(pct)}% free`,
|
|
74
|
+
remedy: low ? `Move or clean only known disposable cache data on the ${label} volume, or relocate that cache; preserve worktrees, evidence, and agent state.` : null,
|
|
75
|
+
recovery_verified: known && !low,
|
|
76
|
+
});
|
|
77
|
+
}
|
|
78
|
+
return checks;
|
|
79
|
+
}
|
package/dist/git.js
CHANGED
|
@@ -40,7 +40,7 @@ export function collectAuto(opts) {
|
|
|
40
40
|
dirty = status === null ? null : status.length > 0;
|
|
41
41
|
({ repo, base, merged, ahead } = mergeFacts(cwd, worktree));
|
|
42
42
|
}
|
|
43
|
-
return { model: opts.model && opts.model.length > 0 ? opts.model : "unknown", effort: opts.effort && opts.effort.length > 0 ? opts.effort : "unknown", machine: opts.machine, cwd, worktree, branch, head, dirty, repo, base, merged, ahead };
|
|
43
|
+
return { provider: opts.provider && opts.provider.length > 0 ? opts.provider : "unknown", model: opts.model && opts.model.length > 0 ? opts.model : "unknown", effort: opts.effort && opts.effort.length > 0 ? opts.effort : "unknown", machine: opts.machine, cwd, worktree, branch, head, dirty, repo, base, merged, ahead };
|
|
44
44
|
}
|
|
45
45
|
/** Where this worktree belongs and how it relates to the base branch. Local facts only; nothing is fetched. */
|
|
46
46
|
export function mergeFacts(cwd, worktree) {
|
|
@@ -116,6 +116,16 @@ export function branchAndHead(cwd = process.cwd()) {
|
|
|
116
116
|
const a = collectAuto({ model: undefined, machine: "", cwd });
|
|
117
117
|
return { branch: a.branch, head: a.head };
|
|
118
118
|
}
|
|
119
|
+
const SHA_BRANCH_NAME = /^[0-9a-f]{7,64}$/i;
|
|
120
|
+
/** True when `branch` looks like a bare Git commit SHA rather than a named branch. */
|
|
121
|
+
export function isShaBranchName(branch) {
|
|
122
|
+
return SHA_BRANCH_NAME.test(branch.trim());
|
|
123
|
+
}
|
|
124
|
+
/** Symbolic branch name checked out at `cwd`, or null when detached, outside a repo, or SHA-named. */
|
|
125
|
+
export function symbolicBranch(cwd = process.cwd()) {
|
|
126
|
+
const branch = git(["symbolic-ref", "--short", "-q", "HEAD"], cwd);
|
|
127
|
+
return branch && !isShaBranchName(branch) ? branch : null;
|
|
128
|
+
}
|
|
119
129
|
/** Repository name from its main worktree path, for naming sibling worktrees. */
|
|
120
130
|
export function repoName(cwd = process.cwd()) {
|
|
121
131
|
const common = git(["rev-parse", "--path-format=absolute", "--git-common-dir"], cwd);
|
|
@@ -156,6 +166,8 @@ export function commitAtTime(ref, iso, cwd = process.cwd()) {
|
|
|
156
166
|
* worse than none.
|
|
157
167
|
*/
|
|
158
168
|
export function createWorktree(path, branch, base, cwd = process.cwd(), exclude = [], inheritUrlRewrites = false) {
|
|
169
|
+
if (isShaBranchName(branch))
|
|
170
|
+
throw new Error(`refusing to create branch ${branch}: never name a branch after a commit SHA`);
|
|
159
171
|
const exists = git(["rev-parse", "--verify", "-q", `refs/heads/${branch}`], cwd) !== null;
|
|
160
172
|
const sparse = exclude.length > 0;
|
|
161
173
|
// Always defer checkout until we have explicitly applied this project's policy. Otherwise Git
|
|
@@ -489,6 +501,22 @@ export function fullSha(ref, cwd = process.cwd()) {
|
|
|
489
501
|
export function fetchRef(ref, remote = "origin", cwd = process.cwd()) {
|
|
490
502
|
return spawnSync("git", ["fetch", "--quiet", remote, ref], { cwd, encoding: "utf8", timeout: 120_000 }).status === 0;
|
|
491
503
|
}
|
|
504
|
+
/**
|
|
505
|
+
* Fetch `branch` from `remote` explicitly into `refs/remotes/<remote>/<branch>`, returning either
|
|
506
|
+
* the updated tracking ref or the git failure reason.
|
|
507
|
+
*/
|
|
508
|
+
export function fetchRemoteBranch(branch, remote = "origin", cwd = process.cwd()) {
|
|
509
|
+
const r = spawnSync("git", ["fetch", "--quiet", remote, `+refs/heads/${branch}:refs/remotes/${remote}/${branch}`], { cwd, encoding: "utf8", timeout: 120_000 });
|
|
510
|
+
const trackingRef = `${remote}/${branch}`;
|
|
511
|
+
if (r.status !== 0) {
|
|
512
|
+
const reason = (r.error ? r.error.message : (r.stderr || r.stdout).trim()) || `git fetch ${remote} ${branch} failed (exit ${r.status ?? "unknown"})`;
|
|
513
|
+
return { ok: false, reason };
|
|
514
|
+
}
|
|
515
|
+
if (fullSha(trackingRef, cwd) === null) {
|
|
516
|
+
return { ok: false, reason: `${trackingRef} is unavailable after fetching ${branch} from ${remote}` };
|
|
517
|
+
}
|
|
518
|
+
return { ok: true, ref: trackingRef };
|
|
519
|
+
}
|
|
492
520
|
/** Check a merge against the local target, then the freshly fetched origin target when needed. */
|
|
493
521
|
export function verifyMergedCommit(merged, target, cwd = process.cwd()) {
|
|
494
522
|
const local = isAncestor(merged, target, cwd);
|