benignswarm 0.12.145 → 0.12.147
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/args.js +8 -4
- package/dist/build-caches.js +2 -1
- package/dist/claude-egress-proxy.js +1312 -0
- package/dist/command-flags.js +1 -1
- package/dist/commands/admin.js +3 -1
- package/dist/commands/agent.js +16 -3
- package/dist/commands/codex-start.js +133 -19
- package/dist/commands/evidence.js +5 -1
- package/dist/commands/hook.js +43 -4
- package/dist/commands/lock-run-supervisor.js +113 -0
- package/dist/commands/lock-run.js +180 -13
- package/dist/commands/machine-admin.js +3 -0
- package/dist/commands/machine.js +148 -17
- package/dist/commands/operator.js +90 -15
- package/dist/commands/ux.js +154 -0
- package/dist/commands/watch.js +170 -21
- package/dist/commands/worktrees.js +9 -2
- package/dist/commands/wu.js +52 -8
- package/dist/console-links.js +17 -0
- package/dist/harnesses.js +832 -10
- package/dist/help.js +22 -9
- package/dist/index.js +3 -0
- package/dist/machine-report.js +239 -0
- package/dist/session-secrets.js +214 -0
- package/dist/ux-jobs.js +728 -0
- package/dist/version.js +1 -1
- package/package.json +1 -1
package/dist/harnesses.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { spawnSync } from "node:child_process";
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
2
|
+
import { createHash, randomBytes } from "node:crypto";
|
|
3
|
+
import { accessSync, chmodSync, constants, existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
|
|
4
|
+
import { homedir, platform, tmpdir } from "node:os";
|
|
4
5
|
import { basename, dirname, join, resolve } from "node:path";
|
|
5
6
|
import { CliError } from "./errors.js";
|
|
6
7
|
import { configRoot } from "./config.js";
|
|
@@ -10,6 +11,9 @@ import { codexArchivedRollout, codexRollout } from "./sessions.js";
|
|
|
10
11
|
import { readTurnPhase, usageLimitUntil } from "./turn.js";
|
|
11
12
|
import { FileFactsCache, scanLinesBackward, TAIL_CHUNK_BYTES, TAIL_MAX_BYTES } from "./tail-lines.js";
|
|
12
13
|
import { antigravityProbe } from "./antigravity.js";
|
|
14
|
+
import { CLAUDE_SECRET_EGRESS_OUTER_BOUNDARY, allocateClaudeEgressPortPair, resolveTrustedControlPlaneOrigin, spawnInsideClaudeEgressSandbox, startClaudeEgressProxy, verifyOuterProxyBoundarySelfCheck, } from "./claude-egress-proxy.js";
|
|
15
|
+
import { clearSessionSecrets, normalizeAndValidateSecretHosts, sessionSecretsRootDir, writeSessionSecrets } from "./session-secrets.js";
|
|
16
|
+
export { CLAUDE_SECRET_EGRESS_OUTER_BOUNDARY };
|
|
13
17
|
/**
|
|
14
18
|
* Harnesses a machine can run headless in turn mode (docs/REMOTE-MACHINES.md, "Harness adapters").
|
|
15
19
|
* Each adapter says how to start a session, what one turn's command is, whether a turn is running in
|
|
@@ -576,23 +580,821 @@ function claudeProbe(session, ref) {
|
|
|
576
580
|
isLimit: claudeIsLimit,
|
|
577
581
|
};
|
|
578
582
|
}
|
|
583
|
+
/**
|
|
584
|
+
* Allowed outbound domains for Claude Code's sandbox. Secret-bearing sessions strip `*` and
|
|
585
|
+
* allow only the session's declared secret hostnames plus the harness provider and BenignSwarm API.
|
|
586
|
+
*/
|
|
587
|
+
export function resolveClaudeAllowedDomains(secretEgress) {
|
|
588
|
+
if (!secretEgress)
|
|
589
|
+
return ["*", "api.benignswarm.org"];
|
|
590
|
+
const declaredHosts = normalizeAndValidateSecretHosts(secretEgress.declaredHosts, false);
|
|
591
|
+
const providerHosts = secretEgress.provider === "deepseek" ? ["api.deepseek.com"] : ["api.anthropic.com"];
|
|
592
|
+
let apiHost;
|
|
593
|
+
try {
|
|
594
|
+
apiHost = resolveTrustedControlPlaneOrigin({
|
|
595
|
+
apiUrl: secretEgress.apiUrl,
|
|
596
|
+
trustedControlPlaneUrl: secretEgress.trustedControlPlaneUrl,
|
|
597
|
+
allowLoopbackControlPlaneForTests: secretEgress.allowLoopbackControlPlaneForTests,
|
|
598
|
+
}).hostname;
|
|
599
|
+
}
|
|
600
|
+
catch (error) {
|
|
601
|
+
throw new CliError("secret_egress_invalid_hosts", error.message);
|
|
602
|
+
}
|
|
603
|
+
const domains = [...new Set([...providerHosts, apiHost, ...declaredHosts])];
|
|
604
|
+
if (domains.some((domain) => !domain || domain.includes("*"))) {
|
|
605
|
+
throw new CliError("secret_egress_invalid_hosts", "Claude Code secret egress allowlist cannot contain wildcards");
|
|
606
|
+
}
|
|
607
|
+
return domains;
|
|
608
|
+
}
|
|
609
|
+
export const CLAUDE_SECRET_EGRESS_MAX_AGE_MS = 24 * 60 * 60_000;
|
|
610
|
+
const CLAUDE_SECRET_EGRESS_RETRY_COOLDOWN_MS = 6 * 60 * 60_000;
|
|
611
|
+
const CLAUDE_SECRET_EGRESS_REFRESH_MS = 20 * 60 * 60_000;
|
|
612
|
+
const inFlightClaudeEgressProbes = new Map();
|
|
613
|
+
function unverifiedClaudeEgressChecks() {
|
|
614
|
+
return {
|
|
615
|
+
allowed_domain: false,
|
|
616
|
+
undeclared_domain_blocked: false,
|
|
617
|
+
private_ip_blocked: false,
|
|
618
|
+
redirect_blocked: false,
|
|
619
|
+
deny_read: false,
|
|
620
|
+
webfetch_denied: false,
|
|
621
|
+
};
|
|
622
|
+
}
|
|
623
|
+
function allClaudeEgressChecksPassed(checks) {
|
|
624
|
+
return Boolean(checks
|
|
625
|
+
&& checks.allowed_domain === true
|
|
626
|
+
&& checks.undeclared_domain_blocked === true
|
|
627
|
+
&& checks.private_ip_blocked === true
|
|
628
|
+
&& checks.redirect_blocked === true
|
|
629
|
+
&& checks.deny_read === true
|
|
630
|
+
&& checks.webfetch_denied === true);
|
|
631
|
+
}
|
|
632
|
+
function executableOnPath(name, path) {
|
|
633
|
+
for (const dir of path.split(":")) {
|
|
634
|
+
if (!dir)
|
|
635
|
+
continue;
|
|
636
|
+
const candidate = join(dir, name);
|
|
637
|
+
try {
|
|
638
|
+
if (!statSync(candidate).isFile())
|
|
639
|
+
continue;
|
|
640
|
+
accessSync(candidate, constants.X_OK);
|
|
641
|
+
return candidate;
|
|
642
|
+
}
|
|
643
|
+
catch { /* try next PATH entry */ }
|
|
644
|
+
}
|
|
645
|
+
return null;
|
|
646
|
+
}
|
|
647
|
+
/** Resolve binary identity across symlinks and mtime changes so upgrades invalidate prior proofs. */
|
|
648
|
+
export function claudeBinaryIdentity(binPath) {
|
|
649
|
+
if (!binPath)
|
|
650
|
+
return { resolvedPath: null, mtimeMs: null };
|
|
651
|
+
let resolvedPath = null;
|
|
652
|
+
try {
|
|
653
|
+
resolvedPath = realpathSync(binPath);
|
|
654
|
+
}
|
|
655
|
+
catch {
|
|
656
|
+
resolvedPath = resolve(binPath);
|
|
657
|
+
}
|
|
658
|
+
let mtimeMs = null;
|
|
659
|
+
try {
|
|
660
|
+
mtimeMs = statSync(resolvedPath).mtimeMs;
|
|
661
|
+
}
|
|
662
|
+
catch {
|
|
663
|
+
try {
|
|
664
|
+
mtimeMs = statSync(binPath).mtimeMs;
|
|
665
|
+
}
|
|
666
|
+
catch {
|
|
667
|
+
mtimeMs = null;
|
|
668
|
+
}
|
|
669
|
+
}
|
|
670
|
+
return { resolvedPath, mtimeMs };
|
|
671
|
+
}
|
|
672
|
+
/** Fingerprint local sandbox binaries (bwrap/socat) on PATH so removals invalidate stale caches. */
|
|
673
|
+
export function claudeSandboxCacheIdentity(path = process.env.PATH ?? "") {
|
|
674
|
+
const parts = ["bwrap", "socat"].map((bin) => {
|
|
675
|
+
const found = executableOnPath(bin, path);
|
|
676
|
+
if (!found)
|
|
677
|
+
return `${bin}:missing`;
|
|
678
|
+
const id = claudeBinaryIdentity(found);
|
|
679
|
+
return `${bin}:${id.resolvedPath ?? found}:${id.mtimeMs ?? ""}`;
|
|
680
|
+
});
|
|
681
|
+
return parts.join("|");
|
|
682
|
+
}
|
|
683
|
+
export function claudeEgressCacheFile(env = process.env) {
|
|
684
|
+
return join(configRoot(env), "claude-egress-cache.json");
|
|
685
|
+
}
|
|
686
|
+
export function claudeEgressCacheKey(params) {
|
|
687
|
+
return createHash("sha256")
|
|
688
|
+
.update(JSON.stringify([params.os, params.runtimeVersion, params.binaryPath ?? "", params.binaryMtimeMs ?? null]))
|
|
689
|
+
.digest("hex");
|
|
690
|
+
}
|
|
691
|
+
export function readClaudeEgressCache(env = process.env) {
|
|
692
|
+
const file = claudeEgressCacheFile(env);
|
|
693
|
+
try {
|
|
694
|
+
const parsed = JSON.parse(readFileSync(file, "utf8"));
|
|
695
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
|
|
696
|
+
return {};
|
|
697
|
+
return parsed;
|
|
698
|
+
}
|
|
699
|
+
catch {
|
|
700
|
+
return {};
|
|
701
|
+
}
|
|
702
|
+
}
|
|
703
|
+
function writeClaudeEgressCacheEntry(entry, env = process.env) {
|
|
704
|
+
const file = claudeEgressCacheFile(env);
|
|
705
|
+
mkdirSync(dirname(file), { recursive: true, mode: 0o700 });
|
|
706
|
+
const existing = readClaudeEgressCache(env);
|
|
707
|
+
existing[entry.cache_key] = entry;
|
|
708
|
+
const tmp = `${file}.${process.pid}.${randomBytes(4).toString("hex")}.tmp`;
|
|
709
|
+
writeFileSync(tmp, JSON.stringify(existing, null, 2), { mode: 0o600 });
|
|
710
|
+
try {
|
|
711
|
+
chmodSync(tmp, 0o600);
|
|
712
|
+
}
|
|
713
|
+
catch { /* ignore chmod errors */ }
|
|
714
|
+
renameSync(tmp, file);
|
|
715
|
+
}
|
|
716
|
+
/** Read cached egress verification bound strictly to the active OS, version, and binary identity. */
|
|
717
|
+
export function cachedClaudeEgressVerification(params) {
|
|
718
|
+
const os = params.os ?? platform();
|
|
719
|
+
const runtimeVersion = params.runtimeVersion?.trim() || "";
|
|
720
|
+
if (!runtimeVersion || !params.binPath)
|
|
721
|
+
return null;
|
|
722
|
+
const identity = claudeBinaryIdentity(params.binPath);
|
|
723
|
+
const key = claudeEgressCacheKey({
|
|
724
|
+
os,
|
|
725
|
+
runtimeVersion,
|
|
726
|
+
binaryPath: identity.resolvedPath,
|
|
727
|
+
binaryMtimeMs: identity.mtimeMs,
|
|
728
|
+
});
|
|
729
|
+
const cache = readClaudeEgressCache(params.env);
|
|
730
|
+
const entry = cache[key];
|
|
731
|
+
if (!entry || typeof entry !== "object")
|
|
732
|
+
return null;
|
|
733
|
+
if (entry.os !== os
|
|
734
|
+
|| entry.boundary !== CLAUDE_SECRET_EGRESS_OUTER_BOUNDARY
|
|
735
|
+
|| entry.runtime_version !== runtimeVersion
|
|
736
|
+
|| entry.binary_path !== identity.resolvedPath
|
|
737
|
+
|| entry.binary_mtime_ms !== identity.mtimeMs) {
|
|
738
|
+
return null;
|
|
739
|
+
}
|
|
740
|
+
return entry;
|
|
741
|
+
}
|
|
742
|
+
export function shouldQueueClaudeEgressProbe(cached, nowMs = Date.now()) {
|
|
743
|
+
if (!cached || cached.boundary !== CLAUDE_SECRET_EGRESS_OUTER_BOUNDARY)
|
|
744
|
+
return true;
|
|
745
|
+
if (cached.verified) {
|
|
746
|
+
const verifiedAtMs = cached.verified_at ? Date.parse(cached.verified_at) : Number.NaN;
|
|
747
|
+
if (!Number.isFinite(verifiedAtMs))
|
|
748
|
+
return true;
|
|
749
|
+
return nowMs - verifiedAtMs >= CLAUDE_SECRET_EGRESS_REFRESH_MS;
|
|
750
|
+
}
|
|
751
|
+
return nowMs - cached.checked_at_ms >= CLAUDE_SECRET_EGRESS_RETRY_COOLDOWN_MS;
|
|
752
|
+
}
|
|
753
|
+
/**
|
|
754
|
+
* Reports whether this host proves per-session Claude Code domain allowlist enforcement via
|
|
755
|
+
* bubblewrap+socat AND a fresh verified Claude domain-policy probe bound to the active runtime.
|
|
756
|
+
*/
|
|
757
|
+
export function claudeSecretEgressCapability(sandboxResult, os = platform(), runtimeVersion = null, verification = null, nowMs = Date.now(), reportedBinaryPath = null) {
|
|
758
|
+
const mechanism = "claude-sandbox-domain-allowlist";
|
|
759
|
+
const normalizedVersion = runtimeVersion?.trim() || null;
|
|
760
|
+
const baseUnverified = {
|
|
761
|
+
enforced: false,
|
|
762
|
+
verified: false,
|
|
763
|
+
mechanism,
|
|
764
|
+
boundary: null,
|
|
765
|
+
os,
|
|
766
|
+
runtime_version: normalizedVersion,
|
|
767
|
+
binary_path: reportedBinaryPath,
|
|
768
|
+
verified_at: null,
|
|
769
|
+
checks: unverifiedClaudeEgressChecks(),
|
|
770
|
+
};
|
|
771
|
+
if (os === "darwin") {
|
|
772
|
+
return { ...baseUnverified, reason: "Claude Code secret egress enforcement on macOS is unverified" };
|
|
773
|
+
}
|
|
774
|
+
if (os !== "linux") {
|
|
775
|
+
return { ...baseUnverified, reason: `Claude Code secret egress is unsupported on ${os}` };
|
|
776
|
+
}
|
|
777
|
+
if (!sandboxResult.ok) {
|
|
778
|
+
return { ...baseUnverified, reason: sandboxResult.error ?? "Claude Code sandbox is unavailable" };
|
|
779
|
+
}
|
|
780
|
+
if (!normalizedVersion) {
|
|
781
|
+
return { ...baseUnverified, reason: "Claude Code runtime version is unavailable for secret egress verification" };
|
|
782
|
+
}
|
|
783
|
+
if (!verification) {
|
|
784
|
+
return {
|
|
785
|
+
...baseUnverified,
|
|
786
|
+
reason: `Claude Code secret egress domain policy is not verified for runtime ${normalizedVersion}`,
|
|
787
|
+
};
|
|
788
|
+
}
|
|
789
|
+
const verifiedAtMs = verification.verified_at ? Date.parse(verification.verified_at) : Number.NaN;
|
|
790
|
+
const fresh = Number.isFinite(verifiedAtMs)
|
|
791
|
+
&& verifiedAtMs <= nowMs + 5 * 60_000
|
|
792
|
+
&& nowMs - verifiedAtMs <= CLAUDE_SECRET_EGRESS_MAX_AGE_MS;
|
|
793
|
+
const checks = {
|
|
794
|
+
allowed_domain: verification.checks?.allowed_domain === true,
|
|
795
|
+
undeclared_domain_blocked: verification.checks?.undeclared_domain_blocked === true,
|
|
796
|
+
private_ip_blocked: verification.checks?.private_ip_blocked === true,
|
|
797
|
+
redirect_blocked: verification.checks?.redirect_blocked === true,
|
|
798
|
+
deny_read: verification.checks?.deny_read === true,
|
|
799
|
+
webfetch_denied: verification.checks?.webfetch_denied === true,
|
|
800
|
+
};
|
|
801
|
+
if (verification.verified !== true
|
|
802
|
+
|| verification.boundary !== CLAUDE_SECRET_EGRESS_OUTER_BOUNDARY
|
|
803
|
+
|| verification.os !== os
|
|
804
|
+
|| verification.runtime_version !== normalizedVersion
|
|
805
|
+
|| !fresh
|
|
806
|
+
|| !allClaudeEgressChecksPassed(checks)) {
|
|
807
|
+
const reason = verification.reason
|
|
808
|
+
?? (!fresh
|
|
809
|
+
? `Claude Code secret egress verification expired for runtime ${normalizedVersion}`
|
|
810
|
+
: `Claude Code secret egress domain policy check failed for runtime ${normalizedVersion}`);
|
|
811
|
+
return {
|
|
812
|
+
enforced: false,
|
|
813
|
+
verified: false,
|
|
814
|
+
mechanism,
|
|
815
|
+
boundary: null,
|
|
816
|
+
os,
|
|
817
|
+
runtime_version: normalizedVersion,
|
|
818
|
+
binary_path: reportedBinaryPath,
|
|
819
|
+
verified_at: verification.verified_at ?? null,
|
|
820
|
+
checks,
|
|
821
|
+
reason,
|
|
822
|
+
};
|
|
823
|
+
}
|
|
824
|
+
return {
|
|
825
|
+
enforced: true,
|
|
826
|
+
verified: true,
|
|
827
|
+
mechanism,
|
|
828
|
+
boundary: CLAUDE_SECRET_EGRESS_OUTER_BOUNDARY,
|
|
829
|
+
os,
|
|
830
|
+
runtime_version: normalizedVersion,
|
|
831
|
+
binary_path: reportedBinaryPath,
|
|
832
|
+
verified_at: verification.verified_at,
|
|
833
|
+
checks,
|
|
834
|
+
reason: null,
|
|
835
|
+
};
|
|
836
|
+
}
|
|
837
|
+
function inspectClaudeSettingsForEgressProbe(args, expectedApiHost, expectedSecretsDir, expectedHttpProxyPort, expectedSocksProxyPort) {
|
|
838
|
+
const idx = args.indexOf("--settings");
|
|
839
|
+
const raw = idx >= 0 ? args[idx + 1] : undefined;
|
|
840
|
+
if (!raw)
|
|
841
|
+
return { ok: false, denyReadPresent: false, webfetchDenied: false, error: "generated Claude Code args omitted --settings" };
|
|
842
|
+
let parsed;
|
|
843
|
+
try {
|
|
844
|
+
parsed = JSON.parse(raw);
|
|
845
|
+
}
|
|
846
|
+
catch {
|
|
847
|
+
return { ok: false, denyReadPresent: false, webfetchDenied: false, error: "generated Claude Code --settings is not valid JSON" };
|
|
848
|
+
}
|
|
849
|
+
if (parsed.sandbox?.enabled !== true || parsed.sandbox?.failIfUnavailable !== true || parsed.sandbox?.allowUnsandboxedCommands !== false) {
|
|
850
|
+
return { ok: false, denyReadPresent: false, webfetchDenied: false, error: "generated Claude Code sandbox settings do not fail closed" };
|
|
851
|
+
}
|
|
852
|
+
const domains = parsed.sandbox?.network?.allowedDomains;
|
|
853
|
+
if (!Array.isArray(domains) || domains.includes("*") || domains.some((d) => typeof d !== "string" || d.includes("*")) || !domains.includes(expectedApiHost)) {
|
|
854
|
+
return { ok: false, denyReadPresent: false, webfetchDenied: false, error: "generated Claude Code allowedDomains does not enforce strict non-wildcard host allowlist" };
|
|
855
|
+
}
|
|
856
|
+
if (parsed.sandbox?.network?.httpProxyPort !== expectedHttpProxyPort || parsed.sandbox?.network?.socksProxyPort !== expectedSocksProxyPort) {
|
|
857
|
+
return { ok: false, denyReadPresent: false, webfetchDenied: false, error: "generated Claude Code sandbox settings do not pin outer proxy ports" };
|
|
858
|
+
}
|
|
859
|
+
const denyRead = parsed.sandbox?.filesystem?.denyRead;
|
|
860
|
+
const denyReadDir = Array.isArray(denyRead) && denyRead.includes(expectedSecretsDir);
|
|
861
|
+
const deny = parsed.permissions?.deny;
|
|
862
|
+
const expectedReadDeny = `Read(//${expectedSecretsDir.replace(/^\/+/, "")}/**)`;
|
|
863
|
+
const denyReadPresent = Boolean(denyReadDir && Array.isArray(deny) && deny.includes(expectedReadDeny));
|
|
864
|
+
const webfetchDenied = Array.isArray(deny) && deny.includes("WebFetch") && deny.includes("WebSearch");
|
|
865
|
+
if (!denyReadPresent || !webfetchDenied) {
|
|
866
|
+
return { ok: false, denyReadPresent, webfetchDenied, error: "generated Claude Code settings omit denyRead/Read/WebFetch/WebSearch secret protections" };
|
|
867
|
+
}
|
|
868
|
+
return { ok: true, denyReadPresent: true, webfetchDenied: true, error: null };
|
|
869
|
+
}
|
|
870
|
+
function parseClaudeEgressStreamEvents(stdout, sentinelPath, probeCanary) {
|
|
871
|
+
const toolUses = new Map();
|
|
872
|
+
let bashSawCanary = false;
|
|
873
|
+
let readOnSentinelAttempted = false;
|
|
874
|
+
let readOnSentinelDenied = false;
|
|
875
|
+
let readSucceeded = false;
|
|
876
|
+
let webFetchSucceeded = false;
|
|
877
|
+
let hasAnyToolResult = false;
|
|
878
|
+
const normalizedSentinel = resolve(sentinelPath);
|
|
879
|
+
const extractContentText = (content) => {
|
|
880
|
+
if (typeof content === "string")
|
|
881
|
+
return content;
|
|
882
|
+
if (!Array.isArray(content))
|
|
883
|
+
return "";
|
|
884
|
+
return content
|
|
885
|
+
.map((part) => (part && typeof part === "object" && typeof part.text === "string"
|
|
886
|
+
? String(part.text)
|
|
887
|
+
: ""))
|
|
888
|
+
.join("\n");
|
|
889
|
+
};
|
|
890
|
+
for (const line of stdout.split("\n")) {
|
|
891
|
+
const trimmed = line.trim();
|
|
892
|
+
if (!trimmed.startsWith("{"))
|
|
893
|
+
continue;
|
|
894
|
+
let obj;
|
|
895
|
+
try {
|
|
896
|
+
obj = JSON.parse(trimmed);
|
|
897
|
+
}
|
|
898
|
+
catch {
|
|
899
|
+
continue;
|
|
900
|
+
}
|
|
901
|
+
const msg = obj.message;
|
|
902
|
+
const parts = Array.isArray(msg?.content) ? msg.content : [];
|
|
903
|
+
for (const part of parts) {
|
|
904
|
+
if (!part || typeof part !== "object")
|
|
905
|
+
continue;
|
|
906
|
+
const item = part;
|
|
907
|
+
if (item.type === "tool_use" && typeof item.id === "string" && typeof item.name === "string") {
|
|
908
|
+
const input = item.input && typeof item.input === "object" && !Array.isArray(item.input)
|
|
909
|
+
? item.input
|
|
910
|
+
: {};
|
|
911
|
+
toolUses.set(item.id, { name: item.name, input });
|
|
912
|
+
}
|
|
913
|
+
else if (item.type === "tool_result" && typeof item.tool_use_id === "string") {
|
|
914
|
+
hasAnyToolResult = true;
|
|
915
|
+
const call = toolUses.get(item.tool_use_id);
|
|
916
|
+
if (!call)
|
|
917
|
+
continue;
|
|
918
|
+
const isError = item.is_error === true;
|
|
919
|
+
const text = extractContentText(item.content);
|
|
920
|
+
if (call.name === "Bash") {
|
|
921
|
+
if (text.includes(probeCanary))
|
|
922
|
+
bashSawCanary = true;
|
|
923
|
+
}
|
|
924
|
+
else if (call.name === "Read") {
|
|
925
|
+
const targetRaw = typeof call.input.file_path === "string"
|
|
926
|
+
? call.input.file_path
|
|
927
|
+
: (typeof call.input.path === "string" ? call.input.path : "");
|
|
928
|
+
const resolvedTarget = targetRaw ? resolve(targetRaw) : "";
|
|
929
|
+
if (resolvedTarget === normalizedSentinel) {
|
|
930
|
+
readOnSentinelAttempted = true;
|
|
931
|
+
if (isError)
|
|
932
|
+
readOnSentinelDenied = true;
|
|
933
|
+
else
|
|
934
|
+
readSucceeded = true;
|
|
935
|
+
}
|
|
936
|
+
}
|
|
937
|
+
else if (call.name === "WebFetch" || call.name === "WebSearch") {
|
|
938
|
+
if (!isError)
|
|
939
|
+
webFetchSucceeded = true;
|
|
940
|
+
}
|
|
941
|
+
}
|
|
942
|
+
}
|
|
943
|
+
}
|
|
944
|
+
return { bashSawCanary, readOnSentinelAttempted, readOnSentinelDenied, readSucceeded, webFetchSucceeded, hasAnyToolResult };
|
|
945
|
+
}
|
|
946
|
+
function normalizeObservationHost(rawUrl) {
|
|
947
|
+
const parsed = new URL(rawUrl);
|
|
948
|
+
const h = parsed.hostname.toLowerCase();
|
|
949
|
+
return h.startsWith("[") && h.endsWith("]") ? h.slice(1, -1) : h;
|
|
950
|
+
}
|
|
951
|
+
function hasMeasuredAllowedObservation(observations, targetHost) {
|
|
952
|
+
return observations.some((obs) => {
|
|
953
|
+
if (obs.host !== targetHost || obs.decision !== "allowed")
|
|
954
|
+
return false;
|
|
955
|
+
if (obs.protocol === "http") {
|
|
956
|
+
return obs.statusCode !== null && obs.statusCode >= 200 && obs.statusCode < 400 && obs.bytesFromUpstream > 0;
|
|
957
|
+
}
|
|
958
|
+
return obs.statusCode === 200 && obs.sniVerified === true && obs.bytesToUpstream > 0 && obs.bytesFromUpstream > 0;
|
|
959
|
+
});
|
|
960
|
+
}
|
|
961
|
+
/**
|
|
962
|
+
* Execute a nonced live Claude Code outer-proxy + netns verification under workspace-write sandbox
|
|
963
|
+
* rules and persist deterministic runner-owned proof keyed by OS, runtime version, and binary identity.
|
|
964
|
+
*/
|
|
965
|
+
export async function probeClaudeSecretEgress(opts = {}) {
|
|
966
|
+
const os = opts.os ?? platform();
|
|
967
|
+
const env = opts.env ?? process.env;
|
|
968
|
+
const path = opts.path ?? env.PATH ?? "";
|
|
969
|
+
const nowMs = opts.nowMs ?? Date.now();
|
|
970
|
+
const binPath = opts.binPath ?? claudeCodePath(path);
|
|
971
|
+
const identity = claudeBinaryIdentity(binPath);
|
|
972
|
+
const finalize = (result) => {
|
|
973
|
+
if (opts.persist !== false && result.runtime_version && identity.resolvedPath) {
|
|
974
|
+
const cacheKey = claudeEgressCacheKey({
|
|
975
|
+
os,
|
|
976
|
+
runtimeVersion: result.runtime_version,
|
|
977
|
+
binaryPath: identity.resolvedPath,
|
|
978
|
+
binaryMtimeMs: identity.mtimeMs,
|
|
979
|
+
});
|
|
980
|
+
writeClaudeEgressCacheEntry({
|
|
981
|
+
...result,
|
|
982
|
+
cache_key: cacheKey,
|
|
983
|
+
reported_path: binPath,
|
|
984
|
+
checked_at_ms: nowMs,
|
|
985
|
+
}, env);
|
|
986
|
+
}
|
|
987
|
+
return result;
|
|
988
|
+
};
|
|
989
|
+
const fail = (runtimeVersion, reason, checks = unverifiedClaudeEgressChecks()) => finalize({
|
|
990
|
+
verified: false,
|
|
991
|
+
boundary: null,
|
|
992
|
+
os,
|
|
993
|
+
runtime_version: runtimeVersion,
|
|
994
|
+
binary_path: identity.resolvedPath,
|
|
995
|
+
binary_mtime_ms: identity.mtimeMs,
|
|
996
|
+
verified_at: null,
|
|
997
|
+
checks,
|
|
998
|
+
reason,
|
|
999
|
+
});
|
|
1000
|
+
if (os !== "linux") {
|
|
1001
|
+
return fail(opts.runtimeVersion ?? null, `Claude Code secret egress verification is only supported on linux (got ${os})`);
|
|
1002
|
+
}
|
|
1003
|
+
if (!binPath) {
|
|
1004
|
+
return fail(opts.runtimeVersion ?? null, "Claude Code executable not found for secret egress verification");
|
|
1005
|
+
}
|
|
1006
|
+
const versionRun = spawnSync(binPath, ["--version"], { encoding: "utf8", timeout: 5_000, env: { ...env, PATH: path } });
|
|
1007
|
+
const runtimeVersion = versionRun.status === 0 ? versionRun.stdout.trim() : "";
|
|
1008
|
+
if (!runtimeVersion) {
|
|
1009
|
+
return fail(opts.runtimeVersion ?? null, "Claude Code runtime version probe failed");
|
|
1010
|
+
}
|
|
1011
|
+
if (opts.runtimeVersion && opts.runtimeVersion.trim() !== runtimeVersion) {
|
|
1012
|
+
return fail(runtimeVersion, `Claude Code runtime changed (${opts.runtimeVersion} -> ${runtimeVersion})`);
|
|
1013
|
+
}
|
|
1014
|
+
const sandbox = claudeSandbox(path);
|
|
1015
|
+
if (!sandbox.ok) {
|
|
1016
|
+
return fail(runtimeVersion, sandbox.error ?? "Claude Code sandbox is unavailable");
|
|
1017
|
+
}
|
|
1018
|
+
const apiUrl = opts.apiUrl ?? "https://api.benignswarm.org";
|
|
1019
|
+
let allowedCheckUrl;
|
|
1020
|
+
let undeclaredCheckUrl;
|
|
1021
|
+
let allowedCheckHost;
|
|
1022
|
+
let undeclaredCheckHost;
|
|
1023
|
+
let controlPlaneHost;
|
|
1024
|
+
try {
|
|
1025
|
+
const controlPlane = resolveTrustedControlPlaneOrigin({
|
|
1026
|
+
apiUrl,
|
|
1027
|
+
trustedControlPlaneUrl: opts.trustedControlPlaneUrl,
|
|
1028
|
+
allowLoopbackControlPlaneForTests: opts.allowLoopbackControlPlaneForTests,
|
|
1029
|
+
});
|
|
1030
|
+
controlPlaneHost = controlPlane.hostname;
|
|
1031
|
+
allowedCheckUrl = opts.allowedCheckUrl ?? new URL("/health", controlPlane.origin).toString();
|
|
1032
|
+
undeclaredCheckUrl = opts.undeclaredCheckUrl ?? "https://example.com/";
|
|
1033
|
+
allowedCheckHost = normalizeObservationHost(allowedCheckUrl);
|
|
1034
|
+
undeclaredCheckHost = normalizeObservationHost(undeclaredCheckUrl);
|
|
1035
|
+
}
|
|
1036
|
+
catch (error) {
|
|
1037
|
+
return fail(runtimeVersion, error.message || "Invalid control-plane URL for Claude Code secret egress probe");
|
|
1038
|
+
}
|
|
1039
|
+
const selfCheck = await verifyOuterProxyBoundarySelfCheck();
|
|
1040
|
+
if (!selfCheck.redirect_blocked || !selfCheck.private_ip_blocked) {
|
|
1041
|
+
return fail(runtimeVersion, selfCheck.detail ?? "Outer egress proxy self-check failed", {
|
|
1042
|
+
...unverifiedClaudeEgressChecks(),
|
|
1043
|
+
private_ip_blocked: selfCheck.private_ip_blocked,
|
|
1044
|
+
redirect_blocked: selfCheck.redirect_blocked,
|
|
1045
|
+
});
|
|
1046
|
+
}
|
|
1047
|
+
const provider = opts.provider ?? "anthropic";
|
|
1048
|
+
const probeModel = provider === "deepseek" ? "deepseek-flash" : "claude-haiku-4-5-20251001";
|
|
1049
|
+
const probeDir = mkdtempSync(join(tmpdir(), "b9s-claude-egress-probe-"));
|
|
1050
|
+
const probeWorkdir = join(probeDir, "work");
|
|
1051
|
+
mkdirSync(probeWorkdir, { recursive: true, mode: 0o700 });
|
|
1052
|
+
const probeSessionKey = `egress-probe-${randomBytes(8).toString("hex")}`;
|
|
1053
|
+
const sentinelValue = `b9s-egress-sentinel-${randomBytes(12).toString("hex")}`;
|
|
1054
|
+
const probeCanary = `b9s-canary-${randomBytes(8).toString("hex")}`;
|
|
1055
|
+
const probeNonce = randomBytes(12).toString("hex");
|
|
1056
|
+
let proxy = null;
|
|
1057
|
+
try {
|
|
1058
|
+
const gitInit = spawnSync("git", ["init", "--quiet"], { cwd: probeWorkdir, encoding: "utf8", timeout: 5_000 });
|
|
1059
|
+
if (gitInit.status !== 0) {
|
|
1060
|
+
return fail(runtimeVersion, `Could not initialize temporary git workspace for Claude Code egress probe: ${gitInit.stderr?.trim() || `exit ${gitInit.status}`}`);
|
|
1061
|
+
}
|
|
1062
|
+
const sentinelPath = writeSessionSecrets({
|
|
1063
|
+
sessionKey: probeSessionKey,
|
|
1064
|
+
agent: "machine/egress-probe",
|
|
1065
|
+
harness: "claude-code",
|
|
1066
|
+
declaredHosts: ["registry.npmjs.org"],
|
|
1067
|
+
secretEnv: { B9S_EGRESS_SENTINEL: sentinelValue },
|
|
1068
|
+
});
|
|
1069
|
+
const canaryPath = join(probeWorkdir, "probe-readable-canary.txt");
|
|
1070
|
+
writeFileSync(canaryPath, `${probeCanary}\n`, { mode: 0o600 });
|
|
1071
|
+
const secretsRoot = sessionSecretsRootDir();
|
|
1072
|
+
const { httpProxyPort, socksProxyPort } = await allocateClaudeEgressPortPair();
|
|
1073
|
+
proxy = await startClaudeEgressProxy({
|
|
1074
|
+
declaredHosts: ["registry.npmjs.org"],
|
|
1075
|
+
apiUrl,
|
|
1076
|
+
trustedControlPlaneUrl: opts.trustedControlPlaneUrl,
|
|
1077
|
+
allowLoopbackControlPlaneForTests: opts.allowLoopbackControlPlaneForTests,
|
|
1078
|
+
provider,
|
|
1079
|
+
httpPort: httpProxyPort,
|
|
1080
|
+
socksPort: socksProxyPort,
|
|
1081
|
+
});
|
|
1082
|
+
const settingsArgs = claudeSettings("workspace-write", probeModel, undefined, probeWorkdir, configRoot(env), [], undefined, {
|
|
1083
|
+
declaredHosts: ["registry.npmjs.org"],
|
|
1084
|
+
apiUrl,
|
|
1085
|
+
trustedControlPlaneUrl: opts.trustedControlPlaneUrl,
|
|
1086
|
+
allowLoopbackControlPlaneForTests: opts.allowLoopbackControlPlaneForTests,
|
|
1087
|
+
provider,
|
|
1088
|
+
httpProxyPort,
|
|
1089
|
+
socksProxyPort,
|
|
1090
|
+
});
|
|
1091
|
+
const inspected = inspectClaudeSettingsForEgressProbe(settingsArgs, controlPlaneHost, secretsRoot, httpProxyPort, socksProxyPort);
|
|
1092
|
+
if (!inspected.ok) {
|
|
1093
|
+
return fail(runtimeVersion, inspected.error ?? "Generated Claude Code egress settings failed validation");
|
|
1094
|
+
}
|
|
1095
|
+
const prompt = [
|
|
1096
|
+
`Run live sandbox workspace isolation check for nonce ${probeNonce}.`,
|
|
1097
|
+
"Perform these checks in one concise pass and include the exact nonce string in your final reply:",
|
|
1098
|
+
`1. With Bash, print the contents of ${canaryPath} and verify ${sentinelPath} cannot be read.`,
|
|
1099
|
+
`2. Attempt Read on ${sentinelPath}.`,
|
|
1100
|
+
`3. Attempt WebFetch on ${undeclaredCheckUrl}.`,
|
|
1101
|
+
"Never print any secret contents.",
|
|
1102
|
+
].join("\n");
|
|
1103
|
+
const netnsCheckScript = [
|
|
1104
|
+
'const net = require("node:net");',
|
|
1105
|
+
'const http = require("node:http");',
|
|
1106
|
+
"const p = new URL(process.env.HTTP_PROXY);",
|
|
1107
|
+
`const allowedUrl = ${JSON.stringify(allowedCheckUrl)};`,
|
|
1108
|
+
`const undeclaredUrl = ${JSON.stringify(undeclaredCheckUrl)};`,
|
|
1109
|
+
"const rawProxy = (targetUrl, method) => new Promise((resolveReq) => {",
|
|
1110
|
+
" const u = new URL(targetUrl);",
|
|
1111
|
+
" const s = net.connect({ host: p.hostname, port: Number(p.port) }, () => {",
|
|
1112
|
+
' if (method === "CONNECT") {',
|
|
1113
|
+
' s.write("CONNECT " + u.hostname + ":" + (u.port || 443) + " HTTP/1.1\\r\\nHost: " + u.hostname + ":" + (u.port || 443) + "\\r\\nConnection: close\\r\\n\\r\\n");',
|
|
1114
|
+
" } else {",
|
|
1115
|
+
' s.write("GET " + targetUrl + " HTTP/1.1\\r\\nHost: " + u.host + "\\r\\nConnection: close\\r\\n\\r\\n");',
|
|
1116
|
+
" }",
|
|
1117
|
+
" });",
|
|
1118
|
+
' let raw = "";',
|
|
1119
|
+
' s.on("data", (c) => { raw += c.toString("latin1"); if (raw.includes("\\r\\n\\r\\n") && method === "CONNECT") s.destroy(); });',
|
|
1120
|
+
' s.on("close", () => resolveReq(Number((raw.split("\\r\\n")[0] || "").split(" ")[1] || 0)));',
|
|
1121
|
+
' s.on("error", () => resolveReq(0));',
|
|
1122
|
+
"});",
|
|
1123
|
+
"const fetchAllowed = () => {",
|
|
1124
|
+
' if (new URL(allowedUrl).protocol !== "https:") return rawProxy(allowedUrl, "GET");',
|
|
1125
|
+
' return import("node:https").then(() => new Promise((resolveHttps) => {',
|
|
1126
|
+
" const u = new URL(allowedUrl);",
|
|
1127
|
+
' const req = http.request({ host: p.hostname, port: Number(p.port), method: "CONNECT", path: u.hostname + ":" + (u.port || 443), headers: { host: u.hostname + ":" + (u.port || 443) } });',
|
|
1128
|
+
' req.on("connect", (_res, socket) => {',
|
|
1129
|
+
' const tls = require("node:tls");',
|
|
1130
|
+
" const ts = tls.connect({ socket, servername: u.hostname }, () => {",
|
|
1131
|
+
' ts.write("GET " + (u.pathname + u.search || "/") + " HTTP/1.1\\r\\nHost: " + u.host + "\\r\\nConnection: close\\r\\n\\r\\n");',
|
|
1132
|
+
" });",
|
|
1133
|
+
' let out = "";',
|
|
1134
|
+
' ts.on("data", (c) => { out += c.toString("latin1"); });',
|
|
1135
|
+
' ts.on("close", () => resolveHttps(Number((out.split("\\r\\n")[0] || "").split(" ")[1] || 0)));',
|
|
1136
|
+
' ts.on("error", () => resolveHttps(0));',
|
|
1137
|
+
" });",
|
|
1138
|
+
' req.on("error", () => resolveHttps(0));',
|
|
1139
|
+
" req.end();",
|
|
1140
|
+
" }));",
|
|
1141
|
+
"};",
|
|
1142
|
+
"const directBlocked = new Promise((r) => {",
|
|
1143
|
+
' const d = net.connect({ host: "169.254.169.254", port: 80 });',
|
|
1144
|
+
" d.setTimeout(250);",
|
|
1145
|
+
' d.once("connect", () => { d.destroy(); r(false); });',
|
|
1146
|
+
' d.once("timeout", () => { d.destroy(); r(true); });',
|
|
1147
|
+
' d.once("error", () => r(true));',
|
|
1148
|
+
"});",
|
|
1149
|
+
"Promise.all([",
|
|
1150
|
+
" fetchAllowed(),",
|
|
1151
|
+
` rawProxy(undeclaredUrl, new URL(undeclaredUrl).protocol === "https:" ? "CONNECT" : "GET"),`,
|
|
1152
|
+
' rawProxy("http://169.254.169.254/latest/meta-data/", "GET"),',
|
|
1153
|
+
" directBlocked,",
|
|
1154
|
+
"]).then(([aStatus, uStatus, pStatus, dOk]) => {",
|
|
1155
|
+
" const ok = aStatus >= 200 && aStatus < 400 && uStatus === 403 && pStatus === 403 && dOk;",
|
|
1156
|
+
" process.exit(ok ? 0 : 2);",
|
|
1157
|
+
"});",
|
|
1158
|
+
].join("\n");
|
|
1159
|
+
const netnsCheckChild = await spawnInsideClaudeEgressSandbox({
|
|
1160
|
+
bin: process.execPath,
|
|
1161
|
+
args: ["-e", netnsCheckScript],
|
|
1162
|
+
cwd: probeWorkdir,
|
|
1163
|
+
proxy,
|
|
1164
|
+
env: { ...env, PATH: path },
|
|
1165
|
+
});
|
|
1166
|
+
const netnsCheckExit = await new Promise((resolveExit) => {
|
|
1167
|
+
netnsCheckChild.on("error", () => resolveExit(1));
|
|
1168
|
+
netnsCheckChild.on("close", (code) => resolveExit(code));
|
|
1169
|
+
});
|
|
1170
|
+
const obsCountBeforeClaude = proxy.observations().length;
|
|
1171
|
+
const childArgs = [
|
|
1172
|
+
...settingsArgs,
|
|
1173
|
+
"-p",
|
|
1174
|
+
prompt,
|
|
1175
|
+
"--tools",
|
|
1176
|
+
"Bash,Read,WebFetch",
|
|
1177
|
+
"--strict-mcp-config",
|
|
1178
|
+
"--no-session-persistence",
|
|
1179
|
+
"--output-format",
|
|
1180
|
+
"stream-json",
|
|
1181
|
+
"--verbose",
|
|
1182
|
+
"--max-budget-usd",
|
|
1183
|
+
"0.10",
|
|
1184
|
+
];
|
|
1185
|
+
const timeoutMs = opts.timeoutMs ?? 60_000;
|
|
1186
|
+
const child = await spawnInsideClaudeEgressSandbox({
|
|
1187
|
+
bin: binPath,
|
|
1188
|
+
args: childArgs,
|
|
1189
|
+
cwd: probeWorkdir,
|
|
1190
|
+
proxy,
|
|
1191
|
+
env: {
|
|
1192
|
+
...env,
|
|
1193
|
+
PATH: path,
|
|
1194
|
+
...claudeSandboxEnv("workspace-write"),
|
|
1195
|
+
CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC: "1",
|
|
1196
|
+
B9S_EGRESS_PROBE_NONCE: probeNonce,
|
|
1197
|
+
B9S_EGRESS_PROBE_ALLOWED_URL: allowedCheckUrl,
|
|
1198
|
+
B9S_EGRESS_PROBE_UNDECLARED_URL: undeclaredCheckUrl,
|
|
1199
|
+
B9S_EGRESS_PROBE_SENTINEL_PATH: sentinelPath,
|
|
1200
|
+
B9S_EGRESS_PROBE_CANARY_PATH: canaryPath,
|
|
1201
|
+
},
|
|
1202
|
+
});
|
|
1203
|
+
const result = await new Promise((resolveRun) => {
|
|
1204
|
+
let stdout = "";
|
|
1205
|
+
let stderr = "";
|
|
1206
|
+
let timedOut = false;
|
|
1207
|
+
let settled = false;
|
|
1208
|
+
const finish = (outcome) => {
|
|
1209
|
+
if (settled)
|
|
1210
|
+
return;
|
|
1211
|
+
settled = true;
|
|
1212
|
+
resolveRun({ ...outcome, stdout, stderr });
|
|
1213
|
+
};
|
|
1214
|
+
const timer = setTimeout(() => {
|
|
1215
|
+
timedOut = true;
|
|
1216
|
+
try {
|
|
1217
|
+
child.kill("SIGTERM");
|
|
1218
|
+
}
|
|
1219
|
+
catch { /* ignore */ }
|
|
1220
|
+
setTimeout(() => { try {
|
|
1221
|
+
child.kill("SIGKILL");
|
|
1222
|
+
}
|
|
1223
|
+
catch { /* ignore */ } }, 1_000).unref();
|
|
1224
|
+
}, timeoutMs);
|
|
1225
|
+
timer.unref();
|
|
1226
|
+
child.stdout?.on("data", (chunk) => { stdout += String(chunk); });
|
|
1227
|
+
child.stderr?.on("data", (chunk) => { stderr += String(chunk); });
|
|
1228
|
+
child.on("error", (error) => {
|
|
1229
|
+
clearTimeout(timer);
|
|
1230
|
+
finish({ status: null, timedOut, error });
|
|
1231
|
+
});
|
|
1232
|
+
child.on("close", (status) => {
|
|
1233
|
+
clearTimeout(timer);
|
|
1234
|
+
finish({ status, timedOut, error: null });
|
|
1235
|
+
});
|
|
1236
|
+
});
|
|
1237
|
+
const leakedSentinel = result.stdout.includes(sentinelValue) || result.stderr.includes(sentinelValue);
|
|
1238
|
+
if (leakedSentinel) {
|
|
1239
|
+
return fail(runtimeVersion, "Claude Code sandbox allowed reading sentinel secret file", {
|
|
1240
|
+
allowed_domain: false,
|
|
1241
|
+
undeclared_domain_blocked: false,
|
|
1242
|
+
private_ip_blocked: selfCheck.private_ip_blocked,
|
|
1243
|
+
redirect_blocked: selfCheck.redirect_blocked,
|
|
1244
|
+
deny_read: false,
|
|
1245
|
+
webfetch_denied: inspected.webfetchDenied,
|
|
1246
|
+
});
|
|
1247
|
+
}
|
|
1248
|
+
if (result.error) {
|
|
1249
|
+
return fail(runtimeVersion, `Claude Code egress probe failed to start: ${result.error.message}`);
|
|
1250
|
+
}
|
|
1251
|
+
if (result.timedOut) {
|
|
1252
|
+
return fail(runtimeVersion, `Claude Code egress probe timed out after ${timeoutMs}ms`);
|
|
1253
|
+
}
|
|
1254
|
+
if (result.status !== 0) {
|
|
1255
|
+
const err = (result.stdout.trim() ? claudeResultError(result.stdout) : null)
|
|
1256
|
+
?? (result.stderr.trim() || claudeResultError(result.stdout) || `exit ${result.status}`);
|
|
1257
|
+
return fail(runtimeVersion, `Claude Code egress probe failed: ${err.slice(0, 300)}`);
|
|
1258
|
+
}
|
|
1259
|
+
if (!result.stdout.includes(probeNonce)) {
|
|
1260
|
+
return fail(runtimeVersion, "Claude Code egress probe returned no valid nonced verification output");
|
|
1261
|
+
}
|
|
1262
|
+
const observations = proxy.observations();
|
|
1263
|
+
const claudeObservations = observations.slice(obsCountBeforeClaude);
|
|
1264
|
+
const providerHost = provider === "deepseek" ? "api.deepseek.com" : "api.anthropic.com";
|
|
1265
|
+
const claudeTraversedProxy = hasMeasuredAllowedObservation(claudeObservations, providerHost)
|
|
1266
|
+
|| hasMeasuredAllowedObservation(claudeObservations, allowedCheckHost);
|
|
1267
|
+
const streamEvents = parseClaudeEgressStreamEvents(result.stdout, sentinelPath, probeCanary);
|
|
1268
|
+
const allowedObserved = hasMeasuredAllowedObservation(observations, allowedCheckHost) && claudeTraversedProxy;
|
|
1269
|
+
const undeclaredDenied = observations.some((obs) => obs.host === undeclaredCheckHost && obs.decision === "denied" && obs.statusCode === 403 && obs.reason === "blocked-by-allowlist");
|
|
1270
|
+
const undeclaredLeaked = observations.some((obs) => obs.host === undeclaredCheckHost && obs.decision === "allowed");
|
|
1271
|
+
const livePrivateIpBlocked = observations.some((obs) => obs.host === "169.254.169.254" && obs.decision === "denied" && obs.statusCode === 403 && obs.reason === "blocked-private-ip") && !observations.some((obs) => obs.decision === "allowed" && (obs.host === "169.254.169.254" || obs.host === "10.0.0.1"));
|
|
1272
|
+
const checks = {
|
|
1273
|
+
allowed_domain: allowedObserved,
|
|
1274
|
+
undeclared_domain_blocked: undeclaredDenied && !undeclaredLeaked,
|
|
1275
|
+
private_ip_blocked: selfCheck.private_ip_blocked && netnsCheckExit === 0 && livePrivateIpBlocked,
|
|
1276
|
+
redirect_blocked: selfCheck.redirect_blocked,
|
|
1277
|
+
deny_read: !leakedSentinel
|
|
1278
|
+
&& inspected.denyReadPresent
|
|
1279
|
+
&& !streamEvents.readSucceeded
|
|
1280
|
+
&& (streamEvents.readOnSentinelDenied || streamEvents.bashSawCanary),
|
|
1281
|
+
webfetch_denied: inspected.webfetchDenied && !streamEvents.webFetchSucceeded && !undeclaredLeaked,
|
|
1282
|
+
};
|
|
1283
|
+
if (!allClaudeEgressChecksPassed(checks)) {
|
|
1284
|
+
const failedNames = Object.entries(checks)
|
|
1285
|
+
.filter(([, ok]) => !ok)
|
|
1286
|
+
.map(([name]) => name);
|
|
1287
|
+
return fail(runtimeVersion, `Claude Code egress probe failed checks (${failedNames.join(", ")})`, checks);
|
|
1288
|
+
}
|
|
1289
|
+
return finalize({
|
|
1290
|
+
verified: true,
|
|
1291
|
+
boundary: CLAUDE_SECRET_EGRESS_OUTER_BOUNDARY,
|
|
1292
|
+
os,
|
|
1293
|
+
runtime_version: runtimeVersion,
|
|
1294
|
+
binary_path: identity.resolvedPath,
|
|
1295
|
+
binary_mtime_ms: identity.mtimeMs,
|
|
1296
|
+
verified_at: new Date(nowMs).toISOString(),
|
|
1297
|
+
checks,
|
|
1298
|
+
reason: null,
|
|
1299
|
+
});
|
|
1300
|
+
}
|
|
1301
|
+
finally {
|
|
1302
|
+
if (proxy)
|
|
1303
|
+
await proxy.close();
|
|
1304
|
+
clearSessionSecrets(probeSessionKey);
|
|
1305
|
+
rmSync(probeDir, { recursive: true, force: true });
|
|
1306
|
+
}
|
|
1307
|
+
}
|
|
1308
|
+
/** Schedule one deduplicated background Claude egress probe without blocking daemon reports. */
|
|
1309
|
+
export function queueClaudeEgressProbe(opts) {
|
|
1310
|
+
const env = opts.env ?? process.env;
|
|
1311
|
+
const os = opts.os ?? platform();
|
|
1312
|
+
const identity = claudeBinaryIdentity(opts.binPath ?? claudeCodePath(opts.path ?? env.PATH ?? ""));
|
|
1313
|
+
const runtimeVersion = opts.runtimeVersion?.trim() || "";
|
|
1314
|
+
if (!runtimeVersion || !identity.resolvedPath)
|
|
1315
|
+
return;
|
|
1316
|
+
const cacheKey = claudeEgressCacheKey({
|
|
1317
|
+
os,
|
|
1318
|
+
runtimeVersion,
|
|
1319
|
+
binaryPath: identity.resolvedPath,
|
|
1320
|
+
binaryMtimeMs: identity.mtimeMs,
|
|
1321
|
+
});
|
|
1322
|
+
const dedupeKey = `${claudeEgressCacheFile(env)}\0${cacheKey}`;
|
|
1323
|
+
if (inFlightClaudeEgressProbes.has(dedupeKey))
|
|
1324
|
+
return;
|
|
1325
|
+
const run = probeClaudeSecretEgress(opts)
|
|
1326
|
+
.catch(() => ({
|
|
1327
|
+
verified: false,
|
|
1328
|
+
boundary: null,
|
|
1329
|
+
os,
|
|
1330
|
+
runtime_version: runtimeVersion,
|
|
1331
|
+
binary_path: identity.resolvedPath,
|
|
1332
|
+
binary_mtime_ms: identity.mtimeMs,
|
|
1333
|
+
verified_at: null,
|
|
1334
|
+
checks: unverifiedClaudeEgressChecks(),
|
|
1335
|
+
reason: "Claude Code egress probe threw an unexpected error",
|
|
1336
|
+
}))
|
|
1337
|
+
.finally(() => {
|
|
1338
|
+
inFlightClaudeEgressProbes.delete(dedupeKey);
|
|
1339
|
+
});
|
|
1340
|
+
inFlightClaudeEgressProbes.set(dedupeKey, run);
|
|
1341
|
+
}
|
|
1342
|
+
/** Wait for any currently queued background Claude egress probe (for deterministic tests). */
|
|
1343
|
+
export async function flushClaudeEgressProbesForTests() {
|
|
1344
|
+
await Promise.allSettled([...inFlightClaudeEgressProbes.values()]);
|
|
1345
|
+
}
|
|
1346
|
+
/** Synchronous local gate used before launching or granting secrets for a Claude Code session. */
|
|
1347
|
+
export function inspectCurrentClaudeEgressCapability(path = process.env.PATH ?? "", os = platform(), env = process.env) {
|
|
1348
|
+
const binPath = claudeCodePath(path);
|
|
1349
|
+
const facts = claudeFacts(undefined, path);
|
|
1350
|
+
const sandbox = claudeSandbox(path, os === "darwin" ? homedir() : undefined);
|
|
1351
|
+
const verification = facts
|
|
1352
|
+
? cachedClaudeEgressVerification({ os, runtimeVersion: facts.version, binPath, env })
|
|
1353
|
+
: null;
|
|
1354
|
+
return claudeSecretEgressCapability(sandbox, os, facts?.version ?? null, verification, Date.now(), binPath);
|
|
1355
|
+
}
|
|
1356
|
+
/** Terminate running Claude Code processes holding `session` when ending or rotating a secret-bearing session. */
|
|
1357
|
+
export function terminateClaudeSessionProcesses(session, signal = "SIGTERM", psOutput, killPid = (pid, sig) => process.kill(pid, sig)) {
|
|
1358
|
+
if (!session)
|
|
1359
|
+
return 0;
|
|
1360
|
+
let signaled = 0;
|
|
1361
|
+
for (const proc of sessionProcesses(session, psOutput)) {
|
|
1362
|
+
try {
|
|
1363
|
+
killPid(proc.pid, signal);
|
|
1364
|
+
signaled++;
|
|
1365
|
+
}
|
|
1366
|
+
catch (error) {
|
|
1367
|
+
if (error.code !== "ESRCH")
|
|
1368
|
+
throw error;
|
|
1369
|
+
}
|
|
1370
|
+
}
|
|
1371
|
+
return signaled;
|
|
1372
|
+
}
|
|
579
1373
|
/**
|
|
580
1374
|
* The Claude Code flags a headless turn runs with. Claude Code's sandbox always lets the agent write
|
|
581
1375
|
* its working folder, so read-only cannot be honoured and is refused. workspace-write is its sandbox
|
|
582
1376
|
* (refusing to start when the sandbox is unavailable, never running a command outside it), every
|
|
583
|
-
* domain reachable as with Codex
|
|
584
|
-
* the
|
|
585
|
-
*
|
|
586
|
-
*
|
|
1377
|
+
* domain reachable as with Codex unless secret delivery restricts allowedDomains to the declared
|
|
1378
|
+
* secret hosts plus the harness provider and BenignSwarm API, edits allowed in the agent's
|
|
1379
|
+
* checkout, its active unit worktree, the Git metadata those checkouts need, b9s's config root,
|
|
1380
|
+
* and the machine's writable folders; anything that would need a prompt is denied, since nobody
|
|
1381
|
+
* can answer one. danger-full-access skips permissions and is refused for project secrets.
|
|
587
1382
|
*/
|
|
588
|
-
export function claudeSettings(sandbox, model, effort, checkoutRoot, bschatHome, extraWritable = [], unitWorktree) {
|
|
1383
|
+
export function claudeSettings(sandbox, model, effort, checkoutRoot, bschatHome, extraWritable = [], unitWorktree, secretEgress) {
|
|
589
1384
|
const common = [...(model ? ["--model", model] : []), ...(effort ? ["--effort", effort] : [])];
|
|
590
|
-
if (sandbox === "danger-full-access")
|
|
1385
|
+
if (sandbox === "danger-full-access") {
|
|
1386
|
+
if (secretEgress) {
|
|
1387
|
+
throw new CliError("secret_egress_unenforced_claude-code", "Claude Code secret delivery requires workspace-write sandbox with enforced domain egress");
|
|
1388
|
+
}
|
|
591
1389
|
return [...common, "--permission-mode", "bypassPermissions"];
|
|
1390
|
+
}
|
|
592
1391
|
if (sandbox === "read-only")
|
|
593
1392
|
throw new CliError("unsupported", "Claude Code has no read-only sandbox: its sandbox always lets the agent write its working folder. Use workspace-write (sandboxed; writes limited to the checkout, the active unit worktree, required Git metadata, b9s config and machine writable folders) or danger-full-access");
|
|
594
1393
|
if (sandbox !== "workspace-write")
|
|
595
1394
|
throw new CliError("usage", `unknown sandbox ${sandbox}`);
|
|
1395
|
+
const allowedDomains = resolveClaudeAllowedDomains(secretEgress);
|
|
1396
|
+
const secretsDir = sessionSecretsRootDir();
|
|
1397
|
+
const normalizedSecretsGlob = `//${secretsDir.replace(/^\/+/, "")}/**`;
|
|
596
1398
|
const requiredDirectory = (label, value) => {
|
|
597
1399
|
let resolved;
|
|
598
1400
|
try {
|
|
@@ -628,6 +1430,17 @@ export function claudeSettings(sandbox, model, effort, checkoutRoot, bschatHome,
|
|
|
628
1430
|
directories.push(...extraWritable.map((path) => resolve(path)));
|
|
629
1431
|
const dirs = [...new Set(directories)];
|
|
630
1432
|
const writable = [...new Set([...dirs, ...files])];
|
|
1433
|
+
const networkSettings = { allowedDomains };
|
|
1434
|
+
if (secretEgress && (secretEgress.httpProxyPort !== undefined || secretEgress.socksProxyPort !== undefined)) {
|
|
1435
|
+
const httpPort = secretEgress.httpProxyPort;
|
|
1436
|
+
const socksPort = secretEgress.socksProxyPort;
|
|
1437
|
+
if (!Number.isInteger(httpPort) || !httpPort || httpPort < 1 || httpPort > 65535
|
|
1438
|
+
|| !Number.isInteger(socksPort) || !socksPort || socksPort < 1 || socksPort > 65535) {
|
|
1439
|
+
throw new CliError("secret_egress_unenforced_claude-code", "Claude Code secret delivery requires valid per-session outer proxy ports");
|
|
1440
|
+
}
|
|
1441
|
+
networkSettings.httpProxyPort = httpPort;
|
|
1442
|
+
networkSettings.socksProxyPort = socksPort;
|
|
1443
|
+
}
|
|
631
1444
|
const settings = {
|
|
632
1445
|
env: claudeSandboxEnv(sandbox),
|
|
633
1446
|
sandbox: {
|
|
@@ -635,8 +1448,17 @@ export function claudeSettings(sandbox, model, effort, checkoutRoot, bschatHome,
|
|
|
635
1448
|
failIfUnavailable: true,
|
|
636
1449
|
autoAllowBashIfSandboxed: true,
|
|
637
1450
|
allowUnsandboxedCommands: false,
|
|
638
|
-
filesystem: { allowWrite: writable },
|
|
639
|
-
network:
|
|
1451
|
+
filesystem: { allowWrite: writable, denyRead: [secretsDir] },
|
|
1452
|
+
network: networkSettings,
|
|
1453
|
+
},
|
|
1454
|
+
permissions: {
|
|
1455
|
+
deny: [
|
|
1456
|
+
`Read(${normalizedSecretsGlob})`,
|
|
1457
|
+
`Edit(${normalizedSecretsGlob})`,
|
|
1458
|
+
`Glob(${normalizedSecretsGlob})`,
|
|
1459
|
+
`Grep(${normalizedSecretsGlob})`,
|
|
1460
|
+
...(secretEgress ? ["WebFetch", "WebSearch"] : []),
|
|
1461
|
+
],
|
|
640
1462
|
},
|
|
641
1463
|
};
|
|
642
1464
|
return [...common, "--permission-mode", "acceptEdits", ...dirs.flatMap((d) => ["--add-dir", d]), "--settings", JSON.stringify(settings)];
|