@mnaimfaizy/agent-kit 1.0.0-beta.11 → 1.0.0-beta.13
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -2
- package/package.json +1 -1
- package/src/deep-scan/agent.mjs +7 -7
- package/src/deep-scan/credential.mjs +19 -2
- package/src/deep-scan/docker-driver.mjs +3 -0
- package/src/deep-scan/grounding-url.mjs +185 -0
- package/src/deep-scan/lifecycle.mjs +20 -3
- package/src/deep-scan/model-proxy.mjs +288 -52
- package/src/deep-scan/recipe.mjs +22 -1
- package/src/deep-scan/sbx-driver.mjs +3 -0
- package/src/deep-scan.mjs +3 -2
package/README.md
CHANGED
|
@@ -19,9 +19,9 @@ npx @mnaimfaizy/agent-kit deep-scan --verify findings.md --ref fix/x # Verifica
|
|
|
19
19
|
- Tags before `v1.0.0-alpha.11` have no `kit-owned-paths.txt`, and the CLI refuses them: adopt those by hand with that tag's `docs/adopt.md`.
|
|
20
20
|
- `upgrade --tag <vY>` reads the current tag from your Agent-kit `uses:` pins (they must agree), replaces each Kit-owned path vY lists (delete, then copy), deletes paths only the old tag listed, rewrites only the `@<tag>` of those pins, prints the `examples/` diff between the two tags for you to apply by hand, and then runs the `doctor --ci` checks. Every refusal is checked before anything is written. It refuses a path with uncommitted changes unless `--force`, refuses symbolic links in or above a Kit-owned path, and copies only regular and executable files from the tag. Ignored files inside a replaced path are deleted with it, and listed first. After a Dependabot pin bump, when the pins already name vY, add `--from <vX>` to also delete paths only vX listed and see the `examples/` diff. It asks before writing; pass `--yes` when there is no terminal. It writes only local files and commits nothing; where `core.fileMode` is off (Windows), it stages each copied file with the tag's mode (`git add --chmod=+x` or `-x`), so the executable bit is neither lost nor kept by mistake.
|
|
21
21
|
- `init --tag <vX>` copies the Kit-owned paths, writes `.github/workflows/agent-pipeline.yml`, `security-audit.yml` and/or `agent-review-response.yml` from the tag's `examples/` with your answers filled in (`--flows pipeline,audit,review-response`, `--actors`, `--default-branch`, `--verify`, `--preset`), writes the Threat pack skeleton to `.security/` (or `--threat-pack-dir`) and `.github/dependabot.yml` if there is none, and prints the GitHub-side steps as `gh` commands. It refuses to overwrite an existing Caller or Kit-owned path without `--force`, never overwrites an existing Threat pack file, and leaves Kit-owned paths that already match the tag alone (so `init --flows audit` later adds that flow); use `upgrade` to change tags. `--yes` asks nothing.
|
|
22
|
-
- `deep-scan` is the launcher for a Deep scan. First it reads the Scan recipe (`.security/scan-recipe.yml`, or `--recipe <path>` relative to the repository root) as committed on the default branch (origin's HEAD, else `main`, or `--default-branch <b>`), never from the working tree, and validates it. With no recipe or an invalid one it refuses, lists every problem with its field, points to [the recipe format](../docs/security-audit.md#scan-recipe), and exits 1; it never falls back to a `full` audit. Then the pre-flight refusals: it refuses, exit 1, when `GH_TOKEN` or `GITHUB_TOKEN` is set in its environment, or when the default branch has a committed `.env` (or `.env.<name>`, templates aside) that the copy-in would forward wholesale. It also refuses, exit 1, when the default branch has no security-audit `DEEP.md` or no Threat pack, or when it has no model credential: an Anthropic API key from `ANTHROPIC_API_KEY`, or with `--credential-from env:<NAME>` another variable, or `--credential-from op://<vault>/<item>/<field>` 1Password through `op read` (see [Credentials](../docs/security-audit.md#credentials)). `--credential-from` never takes the key itself (a usage error, exit 2, that never prints it), and the key never reaches any command the launcher runs. With `--credential subscription` it runs instead on a Claude subscription token (from `claude setup-token`; read from `CLAUDE_CODE_OAUTH_TOKEN` by default, or `--credential-from` as for a key), an opt-in at your own risk: it relies on undocumented behaviour and may break with any Claude Code release, has no refresh, so you rotate the token by hand, leaves the terms question to you, and the proxy's token cap is the only spend lever. On that path the sandbox holds
|
|
22
|
+
- `deep-scan` is the launcher for a Deep scan. First it reads the Scan recipe (`.security/scan-recipe.yml`, or `--recipe <path>` relative to the repository root) as committed on the default branch (origin's HEAD, else `main`, or `--default-branch <b>`), never from the working tree, and validates it. With no recipe or an invalid one it refuses, lists every problem with its field, points to [the recipe format](../docs/security-audit.md#scan-recipe), and exits 1; it never falls back to a `full` audit. Then the pre-flight refusals: it refuses, exit 1, when `GH_TOKEN` or `GITHUB_TOKEN` is set in its environment, or when the default branch has a committed `.env` (or `.env.<name>`, templates aside) that the copy-in would forward wholesale. It also refuses, exit 1, when the default branch has no security-audit `DEEP.md` or no Threat pack, or when it has no model credential: an Anthropic API key from `ANTHROPIC_API_KEY`, or with `--credential-from env:<NAME>` another variable, or `--credential-from op://<vault>/<item>/<field>` 1Password through `op read` (see [Credentials](../docs/security-audit.md#credentials)). `--credential-from` never takes the key itself (a usage error, exit 2, that never prints it), and the key never reaches any command the launcher runs. With `--credential subscription` it runs instead on a Claude subscription token (from `claude setup-token`; read from `CLAUDE_CODE_OAUTH_TOKEN` by default, or `--credential-from` as for a key), an opt-in at your own risk: it relies on undocumented behaviour and may break with any Claude Code release, has no refresh, so you rotate the token by hand, leaves the terms question to you, and the proxy's token cap is the only spend lever. On that path the sandbox holds the run's caller key as its `CLAUDE_CODE_OAUTH_TOKEN`, Claude Code runs without `--bare` (so it discovers the scanned repository's `CLAUDE.md` and skills, which the brief marks as content, not instructions) and with `--strict-mcp-config`, and the proxy swaps only the `Authorization: Bearer` value, never sending `x-api-key`. A subscription token without `--credential subscription`, or anything but one with it, is refused, exit 1, without printing it ([the subscription path](../docs/security-audit.md#the-subscription-path-opt-in)). Then it chooses a [sandbox runtime](../docs/security-audit.md#sandbox-runtimes) from the host, in this order: Docker Sandboxes (`sbx`), Kata Containers or Firecracker on Linux, gVisor (`runsc`) on Linux, the last two on Docker Engine 28.0 or later; a Mac uses Docker Sandboxes. It refuses, exit 1, plain Docker on Linux, Docker Engine older than 28.0 (naming the version found and the minimum), Docker Desktop on Windows with WSL 2, Docker Desktop on macOS (naming Docker Sandboxes), and anything else, naming the accepted runtimes and the CI path; there is no override flag. Those checks run only read-only `git` commands and read-only probes of the runtimes' CLIs (`sbx version`, `docker info`, `<cli> --version`). Then it runs [the sandbox](../docs/security-audit.md#what-goes-into-and-out-of-the-sandbox) on the chosen runtime, through `docker`: it pulls the recipe's image (or builds its Dockerfile from the default branch) and layers a pinned Claude Code with the auto-updater off; starts the sandbox with no mount; copies in a `git archive` of the default branch's tip and the recipe's grounding; runs `setup`, `start`, `ready` and `seed` with egress only to the recipe's `registries`, through a proxy it runs on the host (a failing step ends the run, exit 1, with its output); cuts setup's egress (stops its proxy and removes its relay) and checks from the host that nothing is left to reach; opens the model route, a key-injecting proxy on the host that forwards only `POST` to the Messages API's own paths, only from the caller holding the run's caller key (a random value made for each run, which the sandboxed Claude Code holds in place of a real key), with no server-side tool, `mcp_servers`, `container` or URL or file content in the body, and at most four at once, and swaps the caller key for the real one, through its own relay, and checks from the host that the sandbox reaches that relay alone; runs the real Claude Code with `--bare`, the run's caller key as its `ANTHROPIC_API_KEY`, `ANTHROPIC_BASE_URL` pinned by its own `--settings` (project settings are not loaded) and no web tools, handing it the deep procedure, the Threat pack and the recipe; copies out the one report file to a new private folder and prints its path (nothing is filed or posted); and removes the sandbox, relays, probes, networks and images on every exit path, Ctrl+C and `SIGTERM` included (exit 130 or 143). It exits 0 when the report came out. On Docker Engine the sandbox has one network, attached at `docker run` and never connected or disconnected after (a running gVisor sandbox would not see it), `--internal` and in Docker's `isolated` gateway mode, so the host has no address on it; it reaches each proxy only through a relay container on it, built on stdin from an official `node` image pinned by digest and a digest-checked Node-core script, which forwards the proxy's one port. The host checks the network's mode and that the sandbox is on it alone, and a probe container, run under the sandbox's own runtime, checks the routes before the target starts, after the cut and before the agent step. Copy-in unpacks with the sandbox's own `tar`, so a hostile setup step could alter the brief on its way in; the target already controls the sandbox. Every run is bounded by [limits](../docs/security-audit.md#limits), all enforced outside the sandbox and never set by the recipe: a setup wall clock (`--setup-minutes <n>`, default 20), a scan wall clock (`--scan-minutes <n>`, default 60), Claude Code's turn limit (`--max-turns <n>`, default 200) and the model proxy's token cap for the run (`--max-tokens <n>`, default 5000000, counting input, output and cache tokens from the model API's `usage`). A value that is not a positive number is a usage error, exit 2. A limit that fires stops the running step, copies out the report so far with a `Stopped: wall clock | turns | tokens` line added after `Finding count`, tears down and exits 3; with no report, it writes nothing and prints only `Stopped:` and the limit's name. On Docker Sandboxes it does the same through `sbx`: it first refuses, exit 1, unless your global sbx network policy is deny-all (read with `sbx policy ls --json`, never changed), builds its template with Docker on the host (Docker Desktop on Windows): it pulls the recipe's `image`, layers the pinned Claude Code and a non-root `agent` user (uid 1000, home `/home/agent`, the image's `USER`) on it, as Docker's docs require of a template, after checking it has curl, git, CA certificates and bash (sbx starts only an sbx-ready image), and loads it with `sbx template load` (a `dockerfile` is refused); then it creates the sandbox mountless from that template, opens setup egress with per-sandbox `sbx policy` rules that it removes for the cut; the model route is one more per-sandbox rule, for the model proxy alone (`host.docker.internal:<port>` from the sandbox, which sbx's policy names `localhost:<port>`), and teardown also removes the template and the layered image. Its process allowlist is `git`, `sbx`, `docker`, `runsc`, `kata-runtime`, `firecracker` and the 1Password CLI `op`; `init`, `upgrade` and `doctor` still run only `git` and `gh`. `doctor` reports whether the recipe is at its default path and valid. `--model <id>` names the model the agent runs on (a plain id; Claude Code's default without it), `--effort <level>` its effort level (`low`, `medium`, `high`, `xhigh` or `max`, passed to Claude Code as `--effort`; Claude Code's default without it, and anything else is a usage error, exit 2), the `Agent step:` line names the model and effort asked for, the `Model proxy:` line names the model id the API answered with, `--report <path>` writes the report to that new file in a folder that exists, and in GitHub Actions (`GITHUB_ACTIONS=true`) `deep-scan` keeps the Public-log rule, printing none of Claude Code's error output, the model proxy's refusals and answers (the answered model ids included), or copy-out error detail (see [Deep scan in CI](../docs/security-audit.md#deep-scan-in-ci)).
|
|
23
23
|
- `deep-scan --verify <file> --ref <ref>` is a [Verification run](../docs/security-audit.md#verification-run): it re-attempts the Reproduction of the findings in `<file>` (each a `###` section with `- **Concept id:**`, `- **Location:**` and `- **Observation:**`, as a deep report gives them) on `<ref>`, a local branch, tag or commit such as your fix branch, exported as committed, never the working tree. The recipe, the skill and the Threat pack still come from the default branch. It is confirm-only (no `full` walk, no exploration, no new findings): the agent gets the Verification-run procedure, not the full deep procedure, and the finding file goes in with its brief after the network cut. Its defaults are scan 15 min, 50 turns and the same token cap. Each flag needs the other, and `--report` is not taken with them (usage errors, exit 2). A finding file that is missing, unreadable or out of shape, or a ref that is not a local commit, is refused, exit 1, before any runtime starts. The report goes only to a new private folder; `deep-scan` prints each finding's `Reproduced: yes` (the fix does not hold) or `no` (it holds), exits 1 if the report misses one, and files or posts nothing. It is local only: refused, exit 1, in GitHub Actions (`GITHUB_ACTIONS=true`).
|
|
24
24
|
|
|
25
|
-
The package version matches the Agent-kit Release line: `@mnaimfaizy/agent-kit@1.0.0-beta.
|
|
25
|
+
The package version matches the Agent-kit Release line: `@mnaimfaizy/agent-kit@1.0.0-beta.13` is published from tag `v1.0.0-beta.13`, with npm provenance.
|
|
26
26
|
|
|
27
27
|
Full documentation: [Getting started](https://github.com/mnaimfaizy/agent-kit/blob/main/docs/getting-started.md) and [Adopt](https://github.com/mnaimfaizy/agent-kit/blob/main/docs/adopt.md#check-an-adoption-with-doctor).
|
package/package.json
CHANGED
package/src/deep-scan/agent.mjs
CHANGED
|
@@ -325,16 +325,16 @@ export function agentSettings(baseUrl, kind = "api-key") {
|
|
|
325
325
|
}
|
|
326
326
|
|
|
327
327
|
/**
|
|
328
|
-
* The agent's environment:
|
|
329
|
-
* the subscription path it is the token alone, since an
|
|
330
|
-
* outrank it in Claude Code's auth order.
|
|
328
|
+
* The agent's environment: the run's caller key (callerKeyFor), never the
|
|
329
|
+
* real credential. On the subscription path it is the token alone, since an
|
|
330
|
+
* API key would outrank it in Claude Code's auth order.
|
|
331
331
|
* @param {"api-key" | "subscription"} [kind]
|
|
332
|
+
* @param {string} [key] the run's caller key; without one, the bare placeholder
|
|
332
333
|
*/
|
|
333
|
-
export function agentEnv(kind = "api-key") {
|
|
334
|
+
export function agentEnv(kind = "api-key", key) {
|
|
335
|
+
const held = key ?? (kind === SUBSCRIPTION ? PLACEHOLDER_OAUTH_TOKEN : PLACEHOLDER_API_KEY);
|
|
334
336
|
return [
|
|
335
|
-
kind === SUBSCRIPTION
|
|
336
|
-
? `CLAUDE_CODE_OAUTH_TOKEN=${PLACEHOLDER_OAUTH_TOKEN}`
|
|
337
|
-
: `ANTHROPIC_API_KEY=${PLACEHOLDER_API_KEY}`,
|
|
337
|
+
kind === SUBSCRIPTION ? `CLAUDE_CODE_OAUTH_TOKEN=${held}` : `ANTHROPIC_API_KEY=${held}`,
|
|
338
338
|
"CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC=1",
|
|
339
339
|
];
|
|
340
340
|
}
|
|
@@ -10,22 +10,39 @@
|
|
|
10
10
|
// gets an environment with the model credential variables removed, and the
|
|
11
11
|
// sandbox gets only a placeholder.
|
|
12
12
|
|
|
13
|
+
import { randomBytes } from "node:crypto";
|
|
13
14
|
import { firstLine } from "../exec.mjs";
|
|
14
15
|
import { GITHUB_TOKEN_VARS } from "./preflight.mjs";
|
|
15
16
|
|
|
16
17
|
/** The default variable the API key is read from. */
|
|
17
18
|
export const API_KEY_VAR = "ANTHROPIC_API_KEY";
|
|
18
19
|
|
|
19
|
-
/**
|
|
20
|
+
/**
|
|
21
|
+
* The start of the key the sandboxed Claude Code holds in place of a real
|
|
22
|
+
* one; the proxy swaps it for the real key.
|
|
23
|
+
*/
|
|
20
24
|
export const PLACEHOLDER_API_KEY = "agent-kit-deep-scan-placeholder";
|
|
21
25
|
|
|
22
26
|
/**
|
|
23
|
-
* The
|
|
27
|
+
* The start of the token the sandboxed Claude Code holds on the
|
|
24
28
|
* subscription path; the proxy swaps the bearer value it sends. It is shaped
|
|
25
29
|
* like a token, in case Claude Code checks the prefix.
|
|
26
30
|
*/
|
|
27
31
|
export const PLACEHOLDER_OAUTH_TOKEN = "sk-ant-oat01-agent-kit-deep-scan-placeholder";
|
|
28
32
|
|
|
33
|
+
/**
|
|
34
|
+
* The run's caller key: a placeholder with 24 random bytes added, made once
|
|
35
|
+
* per run. The sandboxed Claude Code holds it in place of a credential, and
|
|
36
|
+
* the model proxy forwards only a request that carries it, so a process in
|
|
37
|
+
* the sandbox that never read Claude Code's environment cannot spend the
|
|
38
|
+
* real credential. It is worth nothing outside the run's proxy.
|
|
39
|
+
* @param {"api-key" | "subscription"} kind
|
|
40
|
+
*/
|
|
41
|
+
export function callerKeyFor(kind) {
|
|
42
|
+
const start = kind === SUBSCRIPTION ? PLACEHOLDER_OAUTH_TOKEN : PLACEHOLDER_API_KEY;
|
|
43
|
+
return `${start}-${randomBytes(24).toString("hex")}`;
|
|
44
|
+
}
|
|
45
|
+
|
|
29
46
|
/** The kinds `--credential` takes: an API key (the default) or the opt-in. */
|
|
30
47
|
export const API_KEY = "api-key";
|
|
31
48
|
export const SUBSCRIPTION = "subscription";
|
|
@@ -34,6 +34,7 @@
|
|
|
34
34
|
import { isIPv4 } from "node:net";
|
|
35
35
|
import { layerDockerfile } from "./claude-code.mjs";
|
|
36
36
|
import { startEgressProxy } from "./egress.mjs";
|
|
37
|
+
import { imageDigestNote } from "./recipe.mjs";
|
|
37
38
|
import {
|
|
38
39
|
OTHER_HOST_PORT,
|
|
39
40
|
probeFailure,
|
|
@@ -112,6 +113,8 @@ export function dockerDriver({ runtime, id, call }) {
|
|
|
112
113
|
} else {
|
|
113
114
|
base = steps.image;
|
|
114
115
|
out(`Image: pulling ${base}.`);
|
|
116
|
+
const note = imageDigestNote(base);
|
|
117
|
+
if (note) out(note);
|
|
115
118
|
must(await docker(["pull", base]), `pulling ${base}`, { showOutput: true });
|
|
116
119
|
}
|
|
117
120
|
out("Image: layering the pinned Claude Code, auto-updater off.");
|
|
@@ -0,0 +1,185 @@
|
|
|
1
|
+
// Grounding URLs are fetched on the host, by `deep-scan`, and the body is
|
|
2
|
+
// copied into the sandbox, which treats everything in it as untrusted. So a
|
|
3
|
+
// grounding fetch must reach only what the sandbox could reach on the public
|
|
4
|
+
// web: an `https:` page on a public host, by its DNS name, with no redirect
|
|
5
|
+
// (a redirect could name any address). Each address the name resolves to is
|
|
6
|
+
// checked, and the connection goes to the address that was checked, so a DNS
|
|
7
|
+
// answer that changes between the check and the connection cannot swap it.
|
|
8
|
+
//
|
|
9
|
+
// Node core only (ADR 0001): `node:https` with a checking `lookup`, since the
|
|
10
|
+
// global fetch takes no lookup of its own.
|
|
11
|
+
|
|
12
|
+
import { lookup as dnsLookup } from "node:dns";
|
|
13
|
+
import { Agent, request } from "node:https";
|
|
14
|
+
import { BlockList, isIP } from "node:net";
|
|
15
|
+
import { Readable } from "node:stream";
|
|
16
|
+
|
|
17
|
+
/** A grounding entry with a scheme is a URL; anything else is a repository path. */
|
|
18
|
+
const SCHEME = /^[A-Za-z][A-Za-z0-9+.-]*:\/\//;
|
|
19
|
+
|
|
20
|
+
/** True when a grounding entry is a URL to fetch, not a repository path. */
|
|
21
|
+
export function isGroundingUrl(source) {
|
|
22
|
+
return SCHEME.test(String(source));
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* What is wrong with a grounding URL as written, or null when it may be
|
|
27
|
+
* fetched: it must be `https:`, and name a fully qualified host by its DNS
|
|
28
|
+
* name (no IP literal, single-label name or localhost).
|
|
29
|
+
*/
|
|
30
|
+
export function groundingUrlProblem(source) {
|
|
31
|
+
let url;
|
|
32
|
+
try {
|
|
33
|
+
url = new URL(String(source));
|
|
34
|
+
} catch {
|
|
35
|
+
return "is not a valid URL";
|
|
36
|
+
}
|
|
37
|
+
if (url.protocol !== "https:") return "must be an https:// URL";
|
|
38
|
+
// WHATWG URL parsing has already turned 0x7f.1, 2130706433 and similar
|
|
39
|
+
// into dotted IPv4, and keeps an IPv6 literal in brackets.
|
|
40
|
+
const host = url.hostname;
|
|
41
|
+
if (host.startsWith("[") || isIP(host)) {
|
|
42
|
+
return "must name its host by a DNS name, not an IP address";
|
|
43
|
+
}
|
|
44
|
+
const name = host.replace(/\.$/, "").toLowerCase();
|
|
45
|
+
if (name === "localhost" || name.endsWith(".localhost")) {
|
|
46
|
+
return "must name a public host, not localhost";
|
|
47
|
+
}
|
|
48
|
+
if (!name.includes("."))
|
|
49
|
+
return "must name a fully qualified public host, not a single-label name";
|
|
50
|
+
return null;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
// Addresses a grounding fetch never connects to: unspecified, loopback,
|
|
54
|
+
// private, shared (CGNAT), link-local (cloud metadata among them), the
|
|
55
|
+
// documentation and benchmarking ranges, multicast and reserved; and the IPv6
|
|
56
|
+
// forms that embed an IPv4 address (mapped, NAT64, 6to4, Teredo), so none can
|
|
57
|
+
// carry a private one through. One list per family: a BlockList matches an
|
|
58
|
+
// IPv4 address against IPv6 rules by its mapped form, so `::ffff:0:0/96` in a
|
|
59
|
+
// shared list would refuse every IPv4 address.
|
|
60
|
+
const NOT_PUBLIC_V4 = new BlockList();
|
|
61
|
+
const NOT_PUBLIC_V6 = new BlockList();
|
|
62
|
+
for (const [net, prefix] of [
|
|
63
|
+
["0.0.0.0", 8],
|
|
64
|
+
["10.0.0.0", 8],
|
|
65
|
+
["100.64.0.0", 10],
|
|
66
|
+
["127.0.0.0", 8],
|
|
67
|
+
["169.254.0.0", 16],
|
|
68
|
+
["172.16.0.0", 12],
|
|
69
|
+
["192.0.0.0", 24],
|
|
70
|
+
["192.0.2.0", 24],
|
|
71
|
+
["192.88.99.0", 24],
|
|
72
|
+
["192.168.0.0", 16],
|
|
73
|
+
["198.18.0.0", 15],
|
|
74
|
+
["198.51.100.0", 24],
|
|
75
|
+
["203.0.113.0", 24],
|
|
76
|
+
["224.0.0.0", 4],
|
|
77
|
+
["240.0.0.0", 4],
|
|
78
|
+
]) {
|
|
79
|
+
NOT_PUBLIC_V4.addSubnet(net, prefix, "ipv4");
|
|
80
|
+
}
|
|
81
|
+
for (const [net, prefix] of [
|
|
82
|
+
["::", 128],
|
|
83
|
+
["::1", 128],
|
|
84
|
+
["::ffff:0:0", 96],
|
|
85
|
+
["64:ff9b::", 96],
|
|
86
|
+
["64:ff9b:1::", 48],
|
|
87
|
+
["100::", 64],
|
|
88
|
+
["2001::", 32],
|
|
89
|
+
["2001:db8::", 32],
|
|
90
|
+
["2002::", 16],
|
|
91
|
+
["fc00::", 7],
|
|
92
|
+
["fe80::", 10],
|
|
93
|
+
["fec0::", 10],
|
|
94
|
+
["ff00::", 8],
|
|
95
|
+
]) {
|
|
96
|
+
NOT_PUBLIC_V6.addSubnet(net, prefix, "ipv6");
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** True when `address` is a public unicast IP address. */
|
|
100
|
+
export function isPublicAddress(address) {
|
|
101
|
+
const family = isIP(String(address));
|
|
102
|
+
if (family === 0) return false;
|
|
103
|
+
try {
|
|
104
|
+
if (family === 4) return !NOT_PUBLIC_V4.check(String(address), "ipv4");
|
|
105
|
+
return !NOT_PUBLIC_V6.check(String(address), "ipv6");
|
|
106
|
+
} catch {
|
|
107
|
+
return false;
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/**
|
|
112
|
+
* A `lookup` for sockets that resolves as `dns.lookup` does, and fails when
|
|
113
|
+
* any address the name resolves to is not public. The socket then connects
|
|
114
|
+
* only to the addresses returned here.
|
|
115
|
+
*/
|
|
116
|
+
export function publicLookup(hostname, options, callback) {
|
|
117
|
+
const opts = typeof options === "function" ? {} : (options ?? {});
|
|
118
|
+
const done = typeof options === "function" ? options : callback;
|
|
119
|
+
dnsLookup(hostname, { ...opts, all: true }, (error, addresses) => {
|
|
120
|
+
if (error) return done(error);
|
|
121
|
+
const list = Array.isArray(addresses) ? addresses : [];
|
|
122
|
+
if (list.length === 0) {
|
|
123
|
+
return done(Object.assign(new Error(`${hostname} has no address`), { code: "ENOTFOUND" }));
|
|
124
|
+
}
|
|
125
|
+
const blocked = list.find((a) => !isPublicAddress(a.address));
|
|
126
|
+
if (blocked) {
|
|
127
|
+
return done(
|
|
128
|
+
Object.assign(
|
|
129
|
+
new Error(`${hostname} resolves to ${blocked.address}, which is not a public address`),
|
|
130
|
+
{ code: "ENOTPUBLIC" },
|
|
131
|
+
),
|
|
132
|
+
);
|
|
133
|
+
}
|
|
134
|
+
if (opts.all) return done(null, list);
|
|
135
|
+
return done(null, list[0].address, list[0].family);
|
|
136
|
+
});
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
// Its own agent: no keep-alive, and no proxy from the environment.
|
|
140
|
+
const AGENT = new Agent({ keepAlive: false });
|
|
141
|
+
const NULL_BODY = new Set([204, 205, 304]);
|
|
142
|
+
|
|
143
|
+
/**
|
|
144
|
+
* The fetch `deep-scan` uses for grounding URLs: one GET, over `https:`
|
|
145
|
+
* only, to a public address checked by `publicLookup`, with no redirect
|
|
146
|
+
* followed. It answers with a `Response`, as the global fetch does, so the
|
|
147
|
+
* caller reads it the same way. `init.signal` stops it.
|
|
148
|
+
*/
|
|
149
|
+
export function publicHttpsFetch(url, init = {}) {
|
|
150
|
+
return new Promise((resolve, reject) => {
|
|
151
|
+
const problem = groundingUrlProblem(url);
|
|
152
|
+
if (problem) {
|
|
153
|
+
reject(new Error(`the URL ${problem}`));
|
|
154
|
+
return;
|
|
155
|
+
}
|
|
156
|
+
const req = request(
|
|
157
|
+
url,
|
|
158
|
+
{
|
|
159
|
+
method: "GET",
|
|
160
|
+
agent: AGENT,
|
|
161
|
+
lookup: publicLookup,
|
|
162
|
+
signal: init.signal,
|
|
163
|
+
headers: { accept: "*/*", "user-agent": "agent-kit-deep-scan" },
|
|
164
|
+
},
|
|
165
|
+
(res) => {
|
|
166
|
+
try {
|
|
167
|
+
const headers = new Headers();
|
|
168
|
+
for (const [name, value] of Object.entries(res.headers)) {
|
|
169
|
+
for (const one of [value].flat()) if (one !== undefined) headers.append(name, one);
|
|
170
|
+
}
|
|
171
|
+
const status = res.statusCode ?? 0;
|
|
172
|
+
let body = null;
|
|
173
|
+
if (NULL_BODY.has(status)) res.resume();
|
|
174
|
+
else body = Readable.toWeb(res);
|
|
175
|
+
resolve(new Response(body, { status, headers }));
|
|
176
|
+
} catch (error) {
|
|
177
|
+
res.destroy();
|
|
178
|
+
reject(error);
|
|
179
|
+
}
|
|
180
|
+
},
|
|
181
|
+
);
|
|
182
|
+
req.on("error", reject);
|
|
183
|
+
req.end();
|
|
184
|
+
});
|
|
185
|
+
}
|
|
@@ -31,7 +31,9 @@ import { join } from "node:path";
|
|
|
31
31
|
import { firstLine } from "../exec.mjs";
|
|
32
32
|
import { agentBrief, agentEnv, agentScript, BRIEF_PATH, TURNS_MARKER } from "./agent.mjs";
|
|
33
33
|
import { CLAUDE_CODE_VERSION, layerDockerfile } from "./claude-code.mjs";
|
|
34
|
+
import { callerKeyFor } from "./credential.mjs";
|
|
34
35
|
import { dockerDriver, LABEL } from "./docker-driver.mjs";
|
|
36
|
+
import { groundingUrlProblem, isGroundingUrl } from "./grounding-url.mjs";
|
|
35
37
|
import {
|
|
36
38
|
LimitReached,
|
|
37
39
|
STOPPED_EXIT,
|
|
@@ -340,7 +342,7 @@ async function lifecycle({
|
|
|
340
342
|
const grounding = [];
|
|
341
343
|
for (const [i, source] of steps.grounding.entries()) {
|
|
342
344
|
const where = `grounding[${i}]`;
|
|
343
|
-
if (
|
|
345
|
+
if (isGroundingUrl(source)) {
|
|
344
346
|
const path = `agent-kit/grounding/urls/${i}-${basename(source)}`;
|
|
345
347
|
fetched.push({
|
|
346
348
|
path,
|
|
@@ -420,12 +422,16 @@ async function lifecycle({
|
|
|
420
422
|
|
|
421
423
|
// 6. The model route: the key-injecting model proxy on this machine, the
|
|
422
424
|
// scan's only way out, and the check from the host that nothing else is.
|
|
425
|
+
// The run's caller key: the sandboxed Claude Code holds it, and the proxy
|
|
426
|
+
// forwards only a request that carries it.
|
|
427
|
+
const callerKey = callerKeyFor(credentialKind);
|
|
423
428
|
let proxy = null;
|
|
424
429
|
const route = await driver.openModelRoute(async (bind) => {
|
|
425
430
|
proxy = await startModelProxy({
|
|
426
431
|
credential,
|
|
427
432
|
kind: credentialKind,
|
|
428
433
|
bind,
|
|
434
|
+
callerKey,
|
|
429
435
|
maxTokens: limits.tokens,
|
|
430
436
|
onCap: () => clocks.stop(TOKENS, `the run's ${limits.tokens}-token cap`),
|
|
431
437
|
...(modelApi !== undefined ? { upstream: modelApi } : {}),
|
|
@@ -500,7 +506,7 @@ async function lifecycle({
|
|
|
500
506
|
...(effort !== undefined ? { effort } : {}),
|
|
501
507
|
kind: credentialKind,
|
|
502
508
|
}),
|
|
503
|
-
{ env: agentEnv(credentialKind) },
|
|
509
|
+
{ env: agentEnv(credentialKind, callerKey) },
|
|
504
510
|
);
|
|
505
511
|
} catch (e) {
|
|
506
512
|
if (!(e instanceof LimitReached)) throw e;
|
|
@@ -651,13 +657,24 @@ async function fetchGrounding(fetch, url, where, clocks) {
|
|
|
651
657
|
const fail = (why) =>
|
|
652
658
|
new StepFailed([`FAILED ${where}: could not fetch ${url}: ${why}`, ENDS_HERE]);
|
|
653
659
|
const tooLarge = `larger than ${MAX_GROUNDING_BYTES / 1024 / 1024} MiB`;
|
|
660
|
+
// The recipe check refuses these first; this holds for any caller.
|
|
661
|
+
const problem = groundingUrlProblem(url);
|
|
662
|
+
if (problem) throw fail(`the URL ${problem}`);
|
|
654
663
|
// The request and the body read share one error path: an interrupt or a
|
|
655
664
|
// limit that fires mid-download stops the run as it would anywhere else.
|
|
656
665
|
try {
|
|
657
666
|
const res = await fetch(url, {
|
|
658
|
-
redirect
|
|
667
|
+
// A redirect could name any address, so none is followed.
|
|
668
|
+
redirect: "manual",
|
|
659
669
|
signal: AbortSignal.any([clocks.signal(), AbortSignal.timeout(GROUNDING_TIMEOUT_MS)]),
|
|
660
670
|
});
|
|
671
|
+
if (res.status >= 300 && res.status < 400) {
|
|
672
|
+
res.body?.cancel().catch(() => {});
|
|
673
|
+
const location = res.headers.get("location");
|
|
674
|
+
throw fail(
|
|
675
|
+
`it redirects (HTTP ${res.status}${location ? ` to ${location}` : ""}); name the final https:// URL in the recipe`,
|
|
676
|
+
);
|
|
677
|
+
}
|
|
661
678
|
if (!res.ok) throw fail(`HTTP ${res.status}`);
|
|
662
679
|
if (Number(res.headers.get("content-length") ?? "0") > MAX_GROUNDING_BYTES) {
|
|
663
680
|
throw fail(tooLarge);
|
|
@@ -16,7 +16,24 @@
|
|
|
16
16
|
// every further request and tells the launcher, which stops the agent step.
|
|
17
17
|
// From the same answers it reads the `model` each one names, so the launcher
|
|
18
18
|
// can say which model the API answered with, not only which was asked for.
|
|
19
|
+
//
|
|
20
|
+
// What it forwards is only what the sandboxed Claude Code needs, judged on
|
|
21
|
+
// every request, since anything in the sandbox can reach the proxy:
|
|
22
|
+
// - only `POST` to the Messages API's own two paths (FORWARDED);
|
|
23
|
+
// - with `callerKey`, only a request that carries the run's caller key, the
|
|
24
|
+
// value the launcher gave the sandboxed Claude Code in place of a real
|
|
25
|
+
// credential, so another process in the sandbox that never read it cannot
|
|
26
|
+
// spend the real one;
|
|
27
|
+
// - only a JSON body with nothing that makes the model API act outside the
|
|
28
|
+
// sandbox: no server-side tool (any `tools` entry but a client tool with an
|
|
29
|
+
// `input_schema`), no `mcp_servers` or `container`, and no content that
|
|
30
|
+
// names a file or URL for the API to fetch. Every beta feature that acts
|
|
31
|
+
// on the API's side is turned on through one of those body fields, so the
|
|
32
|
+
// beta header itself passes as Claude Code sent it;
|
|
33
|
+
// - at most MAX_IN_FLIGHT requests at once, each holding a reservation of
|
|
34
|
+
// the tokens it may spend, so the cap holds against requests sent together.
|
|
19
35
|
|
|
36
|
+
import { timingSafeEqual } from "node:crypto";
|
|
20
37
|
import { createServer, request as httpRequest } from "node:http";
|
|
21
38
|
import { request as httpsRequest } from "node:https";
|
|
22
39
|
import { createBrotliDecompress, createGunzip, createInflate } from "node:zlib";
|
|
@@ -24,9 +41,28 @@ import { createBrotliDecompress, createGunzip, createInflate } from "node:zlib";
|
|
|
24
41
|
/** The model API every forwarded request goes to. */
|
|
25
42
|
export const MODEL_API = "https://api.anthropic.com";
|
|
26
43
|
|
|
27
|
-
/**
|
|
44
|
+
/** Every path is checked against /v1/ first, then against FORWARDED. */
|
|
28
45
|
const MODEL_PATH = /^\/v1\//;
|
|
29
46
|
|
|
47
|
+
/** The only requests forwarded, by decoded path, and only as `POST`: Claude Code's Messages API calls. */
|
|
48
|
+
export const FORWARDED = Object.freeze(["/v1/messages", "/v1/messages/count_tokens"]);
|
|
49
|
+
|
|
50
|
+
/** The largest request body the proxy reads, judges and forwards. */
|
|
51
|
+
export const MAX_REQUEST = 32 * 1024 * 1024;
|
|
52
|
+
|
|
53
|
+
/** How many requests may be in flight to the model API at once. */
|
|
54
|
+
export const MAX_IN_FLIGHT = 4;
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* A request's input tokens, estimated from its body for its reservation:
|
|
58
|
+
* one token per this many bytes, which is fewer bytes than any ordinary text
|
|
59
|
+
* takes per token, so the estimate is high rather than low.
|
|
60
|
+
*/
|
|
61
|
+
const BYTES_PER_TOKEN = 2;
|
|
62
|
+
|
|
63
|
+
/** How deep the body's messages and system blocks are walked; deeper is refused. */
|
|
64
|
+
const MAX_DEPTH = 64;
|
|
65
|
+
|
|
30
66
|
/**
|
|
31
67
|
* Paths whose spend an answer's `usage` would not show (a batch is billed
|
|
32
68
|
* later, outside this run), so the token cap could not hold: refused.
|
|
@@ -82,10 +118,16 @@ const DROPPED = new Set([
|
|
|
82
118
|
* sandbox reach). `refused` collects every host or path it turned away.
|
|
83
119
|
* With `maxTokens`, the first request once the counted tokens reach it is
|
|
84
120
|
* refused, as is every one after, and `onCap` is called once. The answer
|
|
85
|
-
* that crosses the cap is delivered: a request in flight is never cut.
|
|
86
|
-
*
|
|
121
|
+
* that crosses the cap is delivered: a request in flight is never cut. A
|
|
122
|
+
* request is held back (429, retry after a second) while MAX_IN_FLIGHT are
|
|
123
|
+
* in flight, or while the counted tokens and the reservations of those in
|
|
124
|
+
* flight reach the cap, so requests sent together cannot all pass the check
|
|
125
|
+
* before any answer is counted.
|
|
126
|
+
* @param {{ credential: string, kind?: "api-key" | "subscription", bind: string, upstream?: string, maxTokens?: number, onCap?: () => void, callerKey?: string }} opts
|
|
87
127
|
* `kind` is the credential's (default an API key). `upstream` is the
|
|
88
|
-
* model API; only tests pass another.
|
|
128
|
+
* model API; only tests pass another. `callerKey`, when given, is the
|
|
129
|
+
* only value accepted as the caller's `x-api-key` or `Authorization`
|
|
130
|
+
* bearer value; the launcher always gives one.
|
|
89
131
|
* @returns {Promise<{ port: number, refused: string[], tokens: () => number, models: () => string[], credentialRefused: () => boolean, summary: () => string, close: () => Promise<void> }>}
|
|
90
132
|
* `models` is each distinct model id the answers named, in the order first
|
|
91
133
|
* seen, at most MAX_KEPT of them, and only plain ids of MAX_ENTRY or fewer.
|
|
@@ -102,10 +144,14 @@ export async function startModelProxy({
|
|
|
102
144
|
upstream = MODEL_API,
|
|
103
145
|
maxTokens,
|
|
104
146
|
onCap = () => {},
|
|
147
|
+
callerKey,
|
|
105
148
|
}) {
|
|
106
149
|
if (kind !== "api-key" && kind !== "subscription") {
|
|
107
150
|
throw new Error(`the model proxy has no credential kind ${JSON.stringify(kind)}`);
|
|
108
151
|
}
|
|
152
|
+
if (callerKey !== undefined && (typeof callerKey !== "string" || callerKey.length < 32)) {
|
|
153
|
+
throw new Error("the model proxy's caller key must be a string of at least 32 characters");
|
|
154
|
+
}
|
|
109
155
|
// The one header the proxy writes: the sandbox's x-api-key and
|
|
110
156
|
// Authorization are always dropped, so the placeholder never passes on.
|
|
111
157
|
const auth =
|
|
@@ -135,8 +181,18 @@ export async function startModelProxy({
|
|
|
135
181
|
else moreModels = true;
|
|
136
182
|
};
|
|
137
183
|
let pastCap = 0;
|
|
184
|
+
let inFlight = 0;
|
|
185
|
+
let reserved = 0;
|
|
186
|
+
let heldBack = 0;
|
|
138
187
|
const sockets = new Set();
|
|
139
188
|
const count = (key) => statuses.set(key, (statuses.get(key) ?? 0) + 1);
|
|
189
|
+
const answerError = (res, status, type, message, headers = {}) =>
|
|
190
|
+
res.writeHead(status, { "content-type": "application/json", ...headers }).end(
|
|
191
|
+
JSON.stringify({
|
|
192
|
+
type: "error",
|
|
193
|
+
error: { type, message: `deep-scan model proxy: ${message}` },
|
|
194
|
+
}),
|
|
195
|
+
);
|
|
140
196
|
|
|
141
197
|
const server = createServer((req, res) => {
|
|
142
198
|
const raw = req.url ?? "";
|
|
@@ -179,63 +235,152 @@ export async function startModelProxy({
|
|
|
179
235
|
res.writeHead(403).end("deep-scan model proxy: only the model API's /v1/ paths\n");
|
|
180
236
|
return;
|
|
181
237
|
}
|
|
238
|
+
// Only Claude Code's own Messages API calls: POST, to one of two paths.
|
|
239
|
+
if (req.method !== "POST" || !FORWARDED.includes(decoded)) {
|
|
240
|
+
refuse(`${req.method} ${path}`);
|
|
241
|
+
res.writeHead(403).end("deep-scan model proxy: only POST to the Messages API\n");
|
|
242
|
+
return;
|
|
243
|
+
}
|
|
244
|
+
if (callerKey !== undefined && !callerHolds(req.headers, callerKey)) {
|
|
245
|
+
refuse("a caller without the run's key");
|
|
246
|
+
answerError(res, 401, "authentication_error", "this caller does not hold the run's key");
|
|
247
|
+
return;
|
|
248
|
+
}
|
|
182
249
|
if (maxTokens !== undefined && tokens >= maxTokens) {
|
|
183
250
|
pastCap += 1;
|
|
184
251
|
if (pastCap === 1) onCap();
|
|
185
|
-
res
|
|
186
|
-
JSON.stringify({
|
|
187
|
-
type: "error",
|
|
188
|
-
error: {
|
|
189
|
-
type: "permission_error",
|
|
190
|
-
message: `deep-scan model proxy: this run's token cap (${maxTokens}) is reached`,
|
|
191
|
-
},
|
|
192
|
-
}),
|
|
193
|
-
);
|
|
252
|
+
answerError(res, 403, "permission_error", `this run's token cap (${maxTokens}) is reached`);
|
|
194
253
|
return;
|
|
195
254
|
}
|
|
196
|
-
const
|
|
197
|
-
|
|
198
|
-
|
|
255
|
+
const encoding = String(req.headers["content-encoding"] ?? "identity")
|
|
256
|
+
.trim()
|
|
257
|
+
.toLowerCase();
|
|
258
|
+
if (encoding !== "identity" && encoding !== "") {
|
|
259
|
+
refuse("a compressed request body");
|
|
260
|
+
answerError(res, 415, "invalid_request_error", "a request body must not be compressed");
|
|
261
|
+
return;
|
|
199
262
|
}
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
tokens += n;
|
|
224
|
-
},
|
|
225
|
-
answeredBy,
|
|
263
|
+
// The whole body, bounded, so it is judged before any of it is sent.
|
|
264
|
+
const chunks = [];
|
|
265
|
+
let size = 0;
|
|
266
|
+
let tooLarge = false;
|
|
267
|
+
req.on("data", (chunk) => {
|
|
268
|
+
if (tooLarge) return;
|
|
269
|
+
size += chunk.length;
|
|
270
|
+
if (size > MAX_REQUEST) {
|
|
271
|
+
tooLarge = true;
|
|
272
|
+
chunks.length = 0;
|
|
273
|
+
return;
|
|
274
|
+
}
|
|
275
|
+
chunks.push(chunk);
|
|
276
|
+
});
|
|
277
|
+
req.on("error", () => res.destroy());
|
|
278
|
+
req.on("end", () => {
|
|
279
|
+
if (tooLarge) {
|
|
280
|
+
refuse("a request body over the size limit");
|
|
281
|
+
answerError(
|
|
282
|
+
res,
|
|
283
|
+
413,
|
|
284
|
+
"request_too_large",
|
|
285
|
+
`a request body is at most ${MAX_REQUEST} bytes`,
|
|
226
286
|
);
|
|
227
|
-
|
|
228
|
-
}
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
287
|
+
return;
|
|
288
|
+
}
|
|
289
|
+
const body = Buffer.concat(chunks);
|
|
290
|
+
let parsed;
|
|
291
|
+
try {
|
|
292
|
+
parsed = JSON.parse(body.toString("utf8"));
|
|
293
|
+
} catch {
|
|
294
|
+
parsed = undefined;
|
|
295
|
+
}
|
|
296
|
+
const why = requestRefusal(parsed);
|
|
297
|
+
if (why) {
|
|
298
|
+
refuse(why);
|
|
299
|
+
answerError(res, 400, "invalid_request_error", `refused ${why}`);
|
|
300
|
+
return;
|
|
301
|
+
}
|
|
302
|
+
// What this request may spend, held against the cap while it is in
|
|
303
|
+
// flight: its declared output and an estimate of its input. A token
|
|
304
|
+
// count spends nothing.
|
|
305
|
+
const reservation =
|
|
306
|
+
decoded === "/v1/messages"
|
|
307
|
+
? Math.ceil(body.length / BYTES_PER_TOKEN) +
|
|
308
|
+
(Number.isSafeInteger(parsed.max_tokens) && parsed.max_tokens > 0
|
|
309
|
+
? parsed.max_tokens
|
|
310
|
+
: 0)
|
|
311
|
+
: 0;
|
|
312
|
+
if (
|
|
313
|
+
inFlight >= MAX_IN_FLIGHT ||
|
|
314
|
+
(maxTokens !== undefined && inFlight > 0 && tokens + reserved >= maxTokens)
|
|
315
|
+
) {
|
|
316
|
+
heldBack += 1;
|
|
317
|
+
answerError(
|
|
318
|
+
res,
|
|
319
|
+
429,
|
|
320
|
+
"rate_limit_error",
|
|
321
|
+
"too many requests in flight for this run's token cap; retry",
|
|
322
|
+
{ "retry-after": "1" },
|
|
323
|
+
);
|
|
324
|
+
return;
|
|
325
|
+
}
|
|
326
|
+
inFlight += 1;
|
|
327
|
+
reserved += reservation;
|
|
328
|
+
let settled = false;
|
|
329
|
+
const settle = () => {
|
|
330
|
+
if (settled) return;
|
|
331
|
+
settled = true;
|
|
332
|
+
inFlight -= 1;
|
|
333
|
+
reserved -= reservation;
|
|
334
|
+
};
|
|
335
|
+
const headers = {};
|
|
336
|
+
for (const [name, value] of Object.entries(req.headers)) {
|
|
337
|
+
if (!DROPPED.has(name.toLowerCase()) && value !== undefined) headers[name] = value;
|
|
236
338
|
}
|
|
339
|
+
headers[auth[0]] = auth[1];
|
|
340
|
+
headers["content-length"] = String(body.length);
|
|
341
|
+
// A plain body, so the meter can read its usage.
|
|
342
|
+
headers["accept-encoding"] = "identity";
|
|
343
|
+
forwarded += 1;
|
|
344
|
+
const upstreamReq = send(
|
|
345
|
+
{
|
|
346
|
+
protocol: target.protocol,
|
|
347
|
+
hostname: target.hostname,
|
|
348
|
+
port: target.port || undefined,
|
|
349
|
+
method: "POST",
|
|
350
|
+
path: raw,
|
|
351
|
+
headers,
|
|
352
|
+
},
|
|
353
|
+
(r) => {
|
|
354
|
+
count(String(r.statusCode ?? "error"));
|
|
355
|
+
// The reservation holds until the answer has been read whole, and
|
|
356
|
+
// so counted, even if the sandbox stops listening first.
|
|
357
|
+
r.on("close", settle);
|
|
358
|
+
const back = {};
|
|
359
|
+
for (const [name, value] of Object.entries(r.headers)) {
|
|
360
|
+
if (!DROPPED.has(name.toLowerCase()) && value !== undefined) back[name] = value;
|
|
361
|
+
}
|
|
362
|
+
res.writeHead(r.statusCode ?? 502, back);
|
|
363
|
+
meter(
|
|
364
|
+
r,
|
|
365
|
+
(n) => {
|
|
366
|
+
tokens += n;
|
|
367
|
+
},
|
|
368
|
+
answeredBy,
|
|
369
|
+
);
|
|
370
|
+
r.pipe(res);
|
|
371
|
+
},
|
|
372
|
+
);
|
|
373
|
+
upstreamReq.on("error", () => {
|
|
374
|
+
settle();
|
|
375
|
+
count("error");
|
|
376
|
+
if (!res.headersSent) {
|
|
377
|
+
res.writeHead(502).end("deep-scan model proxy: the model API could not be reached\n");
|
|
378
|
+
} else {
|
|
379
|
+
res.destroy();
|
|
380
|
+
}
|
|
381
|
+
});
|
|
382
|
+
upstreamReq.end(body);
|
|
237
383
|
});
|
|
238
|
-
req.pipe(upstreamReq);
|
|
239
384
|
});
|
|
240
385
|
|
|
241
386
|
// A CONNECT tunnel would reach any host: refused.
|
|
@@ -282,6 +427,9 @@ export async function startModelProxy({
|
|
|
282
427
|
const more = refusedCount > refused.length ? ", ..." : "";
|
|
283
428
|
parts.push(`refused ${refusedCount} (${refused.join(", ")}${more})`);
|
|
284
429
|
}
|
|
430
|
+
if (heldBack) {
|
|
431
|
+
parts.push(`held back ${heldBack} request(s) while others were in flight`);
|
|
432
|
+
}
|
|
285
433
|
if (maxTokens !== undefined) {
|
|
286
434
|
parts.push(
|
|
287
435
|
`counted ${tokens} of the ${maxTokens}-token cap${pastCap ? `, and refused ${pastCap} request(s) past it` : ""}`,
|
|
@@ -297,6 +445,94 @@ export async function startModelProxy({
|
|
|
297
445
|
};
|
|
298
446
|
}
|
|
299
447
|
|
|
448
|
+
/**
|
|
449
|
+
* Whether the request carries the run's caller key, as Claude Code sends
|
|
450
|
+
* its key: `x-api-key`, or the bearer value of `Authorization`. Compared in
|
|
451
|
+
* constant time.
|
|
452
|
+
* @param {import("node:http").IncomingHttpHeaders} headers
|
|
453
|
+
* @param {string} key
|
|
454
|
+
*/
|
|
455
|
+
function callerHolds(headers, key) {
|
|
456
|
+
const want = Buffer.from(key, "utf8");
|
|
457
|
+
const offered = [];
|
|
458
|
+
const apiKey = headers["x-api-key"];
|
|
459
|
+
if (typeof apiKey === "string") offered.push(apiKey);
|
|
460
|
+
const bearer = /^Bearer (\S+)$/.exec(String(headers.authorization ?? ""));
|
|
461
|
+
if (bearer) offered.push(bearer[1]);
|
|
462
|
+
return offered.some((value) => {
|
|
463
|
+
const got = Buffer.from(value, "utf8");
|
|
464
|
+
return got.length === want.length && timingSafeEqual(got, want);
|
|
465
|
+
});
|
|
466
|
+
}
|
|
467
|
+
|
|
468
|
+
/** Content sources that make the model API fetch something: a URL, or a file it holds. */
|
|
469
|
+
const FETCHED_SOURCE = new Set(["url", "file"]);
|
|
470
|
+
|
|
471
|
+
/** Content blocks that hand the model API something to act on outside the request. */
|
|
472
|
+
const ACTING_BLOCK = new Set(["container_upload", "mcp_tool_use", "server_tool_use"]);
|
|
473
|
+
|
|
474
|
+
/**
|
|
475
|
+
* Why a Messages API request body is refused, or null. The body must be a
|
|
476
|
+
* JSON object; no `mcp_servers` or `container`; every `tools` entry a
|
|
477
|
+
* client tool (no `type`, or `custom`, and an `input_schema` object), so no
|
|
478
|
+
* server-side tool; and nothing in `messages` or `system` that names a URL
|
|
479
|
+
* or a file for the API to fetch, or an upload or server-side call.
|
|
480
|
+
* @param {unknown} body
|
|
481
|
+
* @returns {string | null} a short, fixed reason, never the sandbox's text
|
|
482
|
+
*/
|
|
483
|
+
export function requestRefusal(body) {
|
|
484
|
+
if (body === null || typeof body !== "object" || Array.isArray(body)) {
|
|
485
|
+
return "a body that is not a JSON object";
|
|
486
|
+
}
|
|
487
|
+
for (const key of ["mcp_servers", "container"]) {
|
|
488
|
+
if (Object.hasOwn(body, key)) return `a request with ${key}`;
|
|
489
|
+
}
|
|
490
|
+
if (Object.hasOwn(body, "tools")) {
|
|
491
|
+
if (!Array.isArray(body.tools)) return "tools that are not a list";
|
|
492
|
+
for (const tool of body.tools) {
|
|
493
|
+
if (tool === null || typeof tool !== "object" || Array.isArray(tool)) {
|
|
494
|
+
return "a tool that is not an object";
|
|
495
|
+
}
|
|
496
|
+
if (tool.type !== undefined && tool.type !== "custom") return "a server-side tool";
|
|
497
|
+
if (tool.input_schema === null || typeof tool.input_schema !== "object") {
|
|
498
|
+
return "a tool with no input_schema";
|
|
499
|
+
}
|
|
500
|
+
}
|
|
501
|
+
}
|
|
502
|
+
for (const key of ["messages", "system"]) {
|
|
503
|
+
if (!Object.hasOwn(body, key)) continue;
|
|
504
|
+
const why = contentRefusal(body[key], 0);
|
|
505
|
+
if (why) return why;
|
|
506
|
+
}
|
|
507
|
+
return null;
|
|
508
|
+
}
|
|
509
|
+
|
|
510
|
+
/** @param {unknown} value @param {number} depth @returns {string | null} */
|
|
511
|
+
function contentRefusal(value, depth) {
|
|
512
|
+
if (value === null || typeof value !== "object") return null;
|
|
513
|
+
if (depth > MAX_DEPTH) return "content nested too deeply";
|
|
514
|
+
if (Array.isArray(value)) {
|
|
515
|
+
for (const item of value) {
|
|
516
|
+
const why = contentRefusal(item, depth + 1);
|
|
517
|
+
if (why) return why;
|
|
518
|
+
}
|
|
519
|
+
return null;
|
|
520
|
+
}
|
|
521
|
+
if (typeof value.type === "string" && ACTING_BLOCK.has(value.type)) {
|
|
522
|
+
return `a ${value.type} block`;
|
|
523
|
+
}
|
|
524
|
+
if (Object.hasOwn(value, "file_id")) return "a file reference";
|
|
525
|
+
const source = value.source;
|
|
526
|
+
if (source && typeof source === "object" && FETCHED_SOURCE.has(source.type)) {
|
|
527
|
+
return `a ${source.type} source`;
|
|
528
|
+
}
|
|
529
|
+
for (const child of Object.values(value)) {
|
|
530
|
+
const why = contentRefusal(child, depth + 1);
|
|
531
|
+
if (why) return why;
|
|
532
|
+
}
|
|
533
|
+
return null;
|
|
534
|
+
}
|
|
535
|
+
|
|
300
536
|
/**
|
|
301
537
|
* Count the tokens an answer's `usage` reports, as the answer streams past:
|
|
302
538
|
* each kind in COUNTED_USAGE, from a JSON body or from a stream's
|
package/src/deep-scan/recipe.mjs
CHANGED
|
@@ -7,6 +7,7 @@
|
|
|
7
7
|
|
|
8
8
|
import { CLI_VERSION } from "../tags.mjs";
|
|
9
9
|
import { checkSafePath } from "../safe-paths.mjs";
|
|
10
|
+
import { groundingUrlProblem, isGroundingUrl } from "./grounding-url.mjs";
|
|
10
11
|
import {
|
|
11
12
|
isMapping,
|
|
12
13
|
parseScalar,
|
|
@@ -92,6 +93,21 @@ export function readRecipeAtRef({ runner, root, ref, path }) {
|
|
|
92
93
|
return { found: true, text: blob.stdout, oid };
|
|
93
94
|
}
|
|
94
95
|
|
|
96
|
+
/**
|
|
97
|
+
* A note for a recipe `image` named by tag alone, or null when it carries a
|
|
98
|
+
* `@sha256:` digest. The image is trusted like the recipe, and is pulled and
|
|
99
|
+
* built on the host's Docker, outside the sandbox runtime, so what a tag
|
|
100
|
+
* names should not change between runs unseen. A warning, not a refusal, so
|
|
101
|
+
* existing recipes still run.
|
|
102
|
+
*
|
|
103
|
+
* @param {string} image
|
|
104
|
+
* @returns {string | null}
|
|
105
|
+
*/
|
|
106
|
+
export function imageDigestNote(image) {
|
|
107
|
+
if (/@sha256:[0-9a-f]{64}$/.test(String(image))) return null;
|
|
108
|
+
return `Note: the recipe's image ${image} has no @sha256: digest, so what it names can change between runs. Pin it as ${String(image).split("@")[0]}@sha256:<digest>; the image is pulled and built on this machine's Docker, outside the sandbox runtime, and is trusted like the recipe.`;
|
|
109
|
+
}
|
|
110
|
+
|
|
95
111
|
/**
|
|
96
112
|
* Every problem with a recipe's text, each one line naming its field. An
|
|
97
113
|
* empty list means the recipe is valid.
|
|
@@ -128,7 +144,7 @@ export function validateRecipe(text) {
|
|
|
128
144
|
say("image and dockerfile", "give one of them, not both.");
|
|
129
145
|
}
|
|
130
146
|
if (hasImage && !isWord(recipe.image)) {
|
|
131
|
-
say("image", "must be one image reference, such as node:22-bookworm
|
|
147
|
+
say("image", "must be one image reference, such as node:22-bookworm@sha256:<digest>.");
|
|
132
148
|
}
|
|
133
149
|
if (hasDockerfile) {
|
|
134
150
|
const file = recipe.dockerfile;
|
|
@@ -215,6 +231,11 @@ export function validateRecipe(text) {
|
|
|
215
231
|
if ("grounding" in recipe) {
|
|
216
232
|
asList(recipe.grounding, "grounding", say)?.forEach((g, i) => {
|
|
217
233
|
if (!isWord(g)) say(`grounding[${i}]`, "must be one URL or repository path.");
|
|
234
|
+
else if (isGroundingUrl(g)) {
|
|
235
|
+
// Fetched on the host, so only a public https:// page (see grounding-url.mjs).
|
|
236
|
+
const problem = groundingUrlProblem(g);
|
|
237
|
+
if (problem) say(`grounding[${i}]`, `${problem}.`);
|
|
238
|
+
}
|
|
218
239
|
});
|
|
219
240
|
}
|
|
220
241
|
|
|
@@ -45,6 +45,7 @@ import { firstLine } from "../exec.mjs";
|
|
|
45
45
|
import { AUTO_UPDATER_OFF, layerDockerfile } from "./claude-code.mjs";
|
|
46
46
|
import { LABEL } from "./docker-driver.mjs";
|
|
47
47
|
import { allowlistOf } from "./egress.mjs";
|
|
48
|
+
import { imageDigestNote } from "./recipe.mjs";
|
|
48
49
|
import { ENDS_HERE, must, StepFailed } from "./steps.mjs";
|
|
49
50
|
|
|
50
51
|
const UNINITIALIZED = /global network policy has not been initialized/i;
|
|
@@ -188,6 +189,8 @@ export function sbxDriver({ id, call }) {
|
|
|
188
189
|
out(
|
|
189
190
|
`Image: layering the pinned Claude Code on ${steps.image} with Docker on this machine, auto-updater off, as the sandbox's template.`,
|
|
190
191
|
);
|
|
192
|
+
const note = imageDigestNote(steps.image);
|
|
193
|
+
if (note) out(note);
|
|
191
194
|
const pulled = await docker(["pull", steps.image]);
|
|
192
195
|
if (pulled.status === null) {
|
|
193
196
|
throw new StepFailed([
|
package/src/deep-scan.mjs
CHANGED
|
@@ -37,6 +37,7 @@ import {
|
|
|
37
37
|
withoutCredentials,
|
|
38
38
|
} from "./deep-scan/credential.mjs";
|
|
39
39
|
import { DEFAULT_LIMITS, describeLimits, parseLimits, VERIFY_LIMITS } from "./deep-scan/limits.mjs";
|
|
40
|
+
import { publicHttpsFetch } from "./deep-scan/grounding-url.mjs";
|
|
40
41
|
import { runLifecycle } from "./deep-scan/lifecycle.mjs";
|
|
41
42
|
import { MODEL_ID } from "./deep-scan/model-proxy.mjs";
|
|
42
43
|
import { envFilesAtRef, envFilesCarriedFromDefault, strayTokens } from "./deep-scan/preflight.mjs";
|
|
@@ -78,7 +79,7 @@ const CREDENTIALS_DOCS_URL = `https://github.com/mnaimfaizy/agent-kit/blob/v${CL
|
|
|
78
79
|
* `verifyPath` (a finding file) and `ref` go together, for a
|
|
79
80
|
* Verification run.
|
|
80
81
|
* `platform`, `env`, `fetch`, `signals` and `timers` are the host's
|
|
81
|
-
* (`process.platform`, `process.env`, the
|
|
82
|
+
* (`process.platform`, `process.env`, the public-HTTPS grounding fetch, `process`, the
|
|
82
83
|
* real clock), and `reportDir` is a new private temporary folder, and
|
|
83
84
|
* `modelApi` is the real model API; only tests pass others, and no flag
|
|
84
85
|
* can change them.
|
|
@@ -101,7 +102,7 @@ export async function runDeepScan({
|
|
|
101
102
|
limitFlags = {},
|
|
102
103
|
platform = process.platform,
|
|
103
104
|
env = process.env,
|
|
104
|
-
fetch =
|
|
105
|
+
fetch = publicHttpsFetch,
|
|
105
106
|
signals = process,
|
|
106
107
|
reportDir,
|
|
107
108
|
modelApi,
|