@mnaimfaizy/agent-kit 1.0.0-alpha.12 → 1.0.0-beta.10
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 +14 -6
- package/bin/agent-kit.mjs +3 -1
- package/package.json +1 -1
- package/src/callers.mjs +73 -10
- package/src/checks/kit-owned-trees.mjs +47 -4
- package/src/checks/result.mjs +8 -2
- package/src/checks/review-response.mjs +205 -0
- package/src/checks/rulesets.mjs +7 -2
- package/src/checks/scan-recipe.mjs +56 -0
- package/src/checks/secrets-and-variables.mjs +65 -15
- package/src/cli.mjs +306 -19
- package/src/deep-scan/agent.mjs +410 -0
- package/src/deep-scan/claude-code.mjs +25 -0
- package/src/deep-scan/credential.mjs +215 -0
- package/src/deep-scan/docker-driver.mjs +696 -0
- package/src/deep-scan/egress.mjs +150 -0
- package/src/deep-scan/lifecycle.mjs +703 -0
- package/src/deep-scan/limits.mjs +126 -0
- package/src/deep-scan/model-proxy.mjs +378 -0
- package/src/deep-scan/preflight.mjs +78 -0
- package/src/deep-scan/recipe.mjs +447 -0
- package/src/deep-scan/relay-script.mjs +98 -0
- package/src/deep-scan/relay.mjs +130 -0
- package/src/deep-scan/runtime.mjs +181 -0
- package/src/deep-scan/sbx-driver.mjs +501 -0
- package/src/deep-scan/steps.mjs +47 -0
- package/src/deep-scan/tar.mjs +84 -0
- package/src/deep-scan/verify.mjs +272 -0
- package/src/deep-scan.mjs +474 -0
- package/src/doctor.mjs +57 -16
- package/src/exec.mjs +225 -23
- package/src/init.mjs +653 -0
- package/src/kit-owned-paths.mjs +5 -3
- package/src/kit-tag.mjs +175 -28
- package/src/local-tree.mjs +142 -27
- package/src/local-writes.mjs +278 -0
- package/src/prompt.mjs +42 -0
- package/src/safe-paths.mjs +68 -0
- package/src/tags.mjs +15 -5
- package/src/templates.mjs +137 -0
- package/src/upgrade.mjs +288 -0
- package/src/workflow-call.mjs +3 -5
- package/src/yaml-subset.mjs +134 -24
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
// The limits that bound every Deep scan (#371), all enforced from outside
|
|
2
|
+
// the sandbox: the setup and scan wall clocks by the launcher, the turns by
|
|
3
|
+
// the launcher's own `--max-turns` on the claude command line, and the token
|
|
4
|
+
// cap by the model proxy, which counts the model API's returned `usage`.
|
|
5
|
+
// Limits come from launcher flags only (and, in CI, workflow inputs): the
|
|
6
|
+
// Scan recipe never sets them (recipe.mjs refuses a limit field), so a
|
|
7
|
+
// merged recipe change cannot raise a run's spend.
|
|
8
|
+
|
|
9
|
+
/** The starting defaults, from the spec's limits table. */
|
|
10
|
+
export const DEFAULT_LIMITS = Object.freeze({
|
|
11
|
+
setupMinutes: 20,
|
|
12
|
+
scanMinutes: 60,
|
|
13
|
+
turns: 200,
|
|
14
|
+
tokens: 5_000_000,
|
|
15
|
+
});
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* A Verification run's defaults (#372): confirm-only, so a shorter scan and
|
|
19
|
+
* fewer turns, the same setup clock and the same token cap.
|
|
20
|
+
*/
|
|
21
|
+
export const VERIFY_LIMITS = Object.freeze({
|
|
22
|
+
...DEFAULT_LIMITS,
|
|
23
|
+
scanMinutes: 15,
|
|
24
|
+
turns: 50,
|
|
25
|
+
});
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* The longest wall clock: what a timer can hold (2^31 - 1 ms, about 24
|
|
29
|
+
* days). A longer one would fire at once.
|
|
30
|
+
*/
|
|
31
|
+
export const MAX_MINUTES = Math.floor((2 ** 31 - 1) / 60_000);
|
|
32
|
+
|
|
33
|
+
/** Each limit's flag, whether it takes a whole number, and its largest value. */
|
|
34
|
+
export const LIMIT_FLAGS = Object.freeze({
|
|
35
|
+
setupMinutes: { flag: "setup-minutes", whole: false, max: MAX_MINUTES },
|
|
36
|
+
scanMinutes: { flag: "scan-minutes", whole: false, max: MAX_MINUTES },
|
|
37
|
+
turns: { flag: "max-turns", whole: true, max: Number.MAX_SAFE_INTEGER },
|
|
38
|
+
tokens: { flag: "max-tokens", whole: true, max: Number.MAX_SAFE_INTEGER },
|
|
39
|
+
});
|
|
40
|
+
|
|
41
|
+
/** The `Stopped:` values report-format.md defines. */
|
|
42
|
+
export const WALL_CLOCK = "wall clock";
|
|
43
|
+
export const TURNS = "turns";
|
|
44
|
+
export const TOKENS = "tokens";
|
|
45
|
+
|
|
46
|
+
/** The exit code of a run a limit stopped, whether or not a report came out. */
|
|
47
|
+
export const STOPPED_EXIT = 3;
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* The limits from the flags' values (strings, or undefined for the default).
|
|
51
|
+
* A value that is not a positive number (a whole one for turns and tokens)
|
|
52
|
+
* is a usage error.
|
|
53
|
+
* @param {Record<string, string | undefined>} values keyed by flag name
|
|
54
|
+
* @param {Limits} [defaults] DEFAULT_LIMITS, or VERIFY_LIMITS for a Verification run
|
|
55
|
+
* @returns {{ limits: Limits } | { error: string }}
|
|
56
|
+
*
|
|
57
|
+
* @typedef {{ setupMinutes: number, scanMinutes: number, turns: number, tokens: number }} Limits
|
|
58
|
+
*/
|
|
59
|
+
export function parseLimits(values, defaults = DEFAULT_LIMITS) {
|
|
60
|
+
const limits = { ...defaults };
|
|
61
|
+
for (const [key, { flag, whole, max }] of Object.entries(LIMIT_FLAGS)) {
|
|
62
|
+
const raw = values[flag];
|
|
63
|
+
if (raw === undefined) continue;
|
|
64
|
+
const shape = whole ? /^\d+$/ : /^\d+(\.\d+)?$/;
|
|
65
|
+
const n = Number(raw);
|
|
66
|
+
if (!shape.test(raw) || !(n > 0) || n > max) {
|
|
67
|
+
return {
|
|
68
|
+
error: `--${flag} must be a positive ${whole ? "whole number" : "number"} of at most ${max}, got: ${JSON.stringify(raw)}`,
|
|
69
|
+
};
|
|
70
|
+
}
|
|
71
|
+
limits[key] = n;
|
|
72
|
+
}
|
|
73
|
+
return { limits };
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** The limits as one line of the launcher's output. */
|
|
77
|
+
export function describeLimits(limits) {
|
|
78
|
+
const flags = Object.values(LIMIT_FLAGS)
|
|
79
|
+
.map((f) => `--${f.flag}`)
|
|
80
|
+
.join(", ");
|
|
81
|
+
return `Limits: setup ${limits.setupMinutes} min, scan ${limits.scanMinutes} min, ${limits.turns} turns, ${limits.tokens} tokens (raise them with ${flags}).`;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/** A run stopped by a limit: what fired, said for a person. */
|
|
85
|
+
export class LimitReached extends Error {
|
|
86
|
+
/** @param {{ limit: string, detail: string }} stop */
|
|
87
|
+
constructor(stop) {
|
|
88
|
+
super(`stopped: ${stop.limit} (${stop.detail})`);
|
|
89
|
+
this.stop = stop;
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/** The status line for a run a limit stopped. */
|
|
94
|
+
export const stoppedStatus = (stop) => `Stopped: ${stop.limit} (${stop.detail}).`;
|
|
95
|
+
|
|
96
|
+
const STOPPED_LINE = /^[ \t]*[-*][ \t]+\*\*Stopped:\*\*.*$/;
|
|
97
|
+
const FINDING_COUNT = /^[ \t]*[-*][ \t]+\*\*Finding count:\*\*/;
|
|
98
|
+
const REPORT_HEADING = /^## Security audit report[ \t]*$/;
|
|
99
|
+
|
|
100
|
+
/**
|
|
101
|
+
* The report's bytes with the launcher's `Stopped:` line, when a limit ended
|
|
102
|
+
* the run: after the `Finding count` header line, as report-format.md places
|
|
103
|
+
* it (else after the report's heading, else first). Any `Stopped:` line the
|
|
104
|
+
* agent wrote is removed, since only the launcher writes one. A report with
|
|
105
|
+
* neither is returned byte for byte. Bytes are read as latin1, so a report
|
|
106
|
+
* that is not valid UTF-8 keeps every other byte unchanged.
|
|
107
|
+
* @param {Buffer} data
|
|
108
|
+
* @param {string | null} limit the `Stopped:` value, or null
|
|
109
|
+
* @returns {Buffer}
|
|
110
|
+
*/
|
|
111
|
+
export function withStopped(data, limit) {
|
|
112
|
+
const text = data.toString("latin1");
|
|
113
|
+
const eol = text.includes("\r\n") ? "\r\n" : "\n";
|
|
114
|
+
const lines = text.split(/\r?\n/);
|
|
115
|
+
const kept = lines.filter((l) => !STOPPED_LINE.test(l));
|
|
116
|
+
if (limit === null && kept.length === lines.length) return data;
|
|
117
|
+
if (limit !== null) {
|
|
118
|
+
const line = `- **Stopped:** ${limit}`;
|
|
119
|
+
const count = kept.findIndex((l) => FINDING_COUNT.test(l));
|
|
120
|
+
const heading = kept.findIndex((l) => REPORT_HEADING.test(l));
|
|
121
|
+
if (count >= 0) kept.splice(count + 1, 0, line);
|
|
122
|
+
else if (heading >= 0) kept.splice(heading + 1, 0, "", line);
|
|
123
|
+
else kept.unshift(line, "");
|
|
124
|
+
}
|
|
125
|
+
return Buffer.from(kept.join(eol), "latin1");
|
|
126
|
+
}
|
|
@@ -0,0 +1,378 @@
|
|
|
1
|
+
// The scan phase's only route out (#370): a key-injecting reverse proxy that
|
|
2
|
+
// runs in the launcher, on the host, outside the sandbox. The sandboxed
|
|
3
|
+
// Claude Code holds only a placeholder key and reaches the model API through
|
|
4
|
+
// this proxy, which forwards only to the model API, strips the placeholder
|
|
5
|
+
// (`x-api-key`, `Authorization`) and inserts the real credential: as
|
|
6
|
+
// `x-api-key` for an API key, or, on the subscription path (#375), as the
|
|
7
|
+
// bearer value of `Authorization` and nothing else, so every other header
|
|
8
|
+
// Claude Code sends (its OAuth beta header among them) passes on as it is
|
|
9
|
+
// and need not be known here. The
|
|
10
|
+
// credential lives only in this process's memory: it is never an argument,
|
|
11
|
+
// an environment variable or a file of any command the launcher runs.
|
|
12
|
+
// Node core only (ADR 0001).
|
|
13
|
+
//
|
|
14
|
+
// It also holds the run's token cap (#371): it counts the `usage` each
|
|
15
|
+
// model API answer returns, and once the count reaches the cap it refuses
|
|
16
|
+
// every further request and tells the launcher, which stops the agent step.
|
|
17
|
+
// From the same answers it reads the `model` each one names, so the launcher
|
|
18
|
+
// can say which model the API answered with, not only which was asked for.
|
|
19
|
+
|
|
20
|
+
import { createServer, request as httpRequest } from "node:http";
|
|
21
|
+
import { request as httpsRequest } from "node:https";
|
|
22
|
+
import { createBrotliDecompress, createGunzip, createInflate } from "node:zlib";
|
|
23
|
+
|
|
24
|
+
/** The model API every forwarded request goes to. */
|
|
25
|
+
export const MODEL_API = "https://api.anthropic.com";
|
|
26
|
+
|
|
27
|
+
/** Only the Messages API's paths are forwarded. */
|
|
28
|
+
const MODEL_PATH = /^\/v1\//;
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* Paths whose spend an answer's `usage` would not show (a batch is billed
|
|
32
|
+
* later, outside this run), so the token cap could not hold: refused.
|
|
33
|
+
*/
|
|
34
|
+
const UNCOUNTED_PATH = /^\/v1\/(messages\/batches|complete)(\/|$)/i;
|
|
35
|
+
|
|
36
|
+
/** The `usage` fields the cap counts: every kind of token billed. */
|
|
37
|
+
export const COUNTED_USAGE = Object.freeze([
|
|
38
|
+
"input_tokens",
|
|
39
|
+
"cache_creation_input_tokens",
|
|
40
|
+
"cache_read_input_tokens",
|
|
41
|
+
"output_tokens",
|
|
42
|
+
]);
|
|
43
|
+
|
|
44
|
+
/** How much of an answer the meter reads: a line of a stream, or a whole JSON body. */
|
|
45
|
+
const MAX_LINE = 1024 * 1024;
|
|
46
|
+
const MAX_BODY = 16 * 1024 * 1024;
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* A model id as Claude Code's --model takes it, and nothing more: the
|
|
50
|
+
* launcher's check of --model, which goes into the agent step's command
|
|
51
|
+
* line (so no space, quote or leading dash; the same pattern as the static
|
|
52
|
+
* workflow's model input), and the only form of an answer's `model` the
|
|
53
|
+
* summary names, so an answer cannot write a line of its own.
|
|
54
|
+
*/
|
|
55
|
+
export const MODEL_ID = /^[A-Za-z0-9][A-Za-z0-9._:@/[\]-]*$/;
|
|
56
|
+
|
|
57
|
+
/** How many distinct refused hosts, paths or answered models the summary keeps, and how long each. */
|
|
58
|
+
const MAX_KEPT = 5;
|
|
59
|
+
const MAX_ENTRY = 80;
|
|
60
|
+
|
|
61
|
+
// Hop-by-hop headers (RFC 9110 7.6.1), the client's credentials, and the
|
|
62
|
+
// Host, which is the model API's own.
|
|
63
|
+
const DROPPED = new Set([
|
|
64
|
+
"x-api-key",
|
|
65
|
+
"authorization",
|
|
66
|
+
"proxy-authorization",
|
|
67
|
+
"proxy-authenticate",
|
|
68
|
+
"proxy-connection",
|
|
69
|
+
"connection",
|
|
70
|
+
"keep-alive",
|
|
71
|
+
"te",
|
|
72
|
+
"trailer",
|
|
73
|
+
"transfer-encoding",
|
|
74
|
+
"upgrade",
|
|
75
|
+
"host",
|
|
76
|
+
"cookie",
|
|
77
|
+
]);
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* Start the proxy on `bind` (an address the relay reaches, never all
|
|
81
|
+
* interfaces; on Docker Sandboxes, 127.0.0.1, which its policy lets the
|
|
82
|
+
* sandbox reach). `refused` collects every host or path it turned away.
|
|
83
|
+
* With `maxTokens`, the first request once the counted tokens reach it is
|
|
84
|
+
* 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
|
+
* @param {{ credential: string, kind?: "api-key" | "subscription", bind: string, upstream?: string, maxTokens?: number, onCap?: () => void }} opts
|
|
87
|
+
* `kind` is the credential's (default an API key). `upstream` is the
|
|
88
|
+
* model API; only tests pass another.
|
|
89
|
+
* @returns {Promise<{ port: number, refused: string[], tokens: () => number, models: () => string[], credentialRefused: () => boolean, summary: () => string, close: () => Promise<void> }>}
|
|
90
|
+
* `models` is each distinct model id the answers named, in the order first
|
|
91
|
+
* seen, at most MAX_KEPT of them, and only plain ids of MAX_ENTRY or fewer.
|
|
92
|
+
* `credentialRefused` is true when at least one request was forwarded and
|
|
93
|
+
* the model API answered every one with 401 or 403: it refused the
|
|
94
|
+
* credential (a request that got no answer, or still waits for one, is not
|
|
95
|
+
* a refusal). The proxy's own refusals (a path, a host, the cap) are not
|
|
96
|
+
* answers of the model API, so they never count.
|
|
97
|
+
*/
|
|
98
|
+
export async function startModelProxy({
|
|
99
|
+
credential,
|
|
100
|
+
kind = "api-key",
|
|
101
|
+
bind,
|
|
102
|
+
upstream = MODEL_API,
|
|
103
|
+
maxTokens,
|
|
104
|
+
onCap = () => {},
|
|
105
|
+
}) {
|
|
106
|
+
if (kind !== "api-key" && kind !== "subscription") {
|
|
107
|
+
throw new Error(`the model proxy has no credential kind ${JSON.stringify(kind)}`);
|
|
108
|
+
}
|
|
109
|
+
// The one header the proxy writes: the sandbox's x-api-key and
|
|
110
|
+
// Authorization are always dropped, so the placeholder never passes on.
|
|
111
|
+
const auth =
|
|
112
|
+
kind === "subscription" ? ["authorization", `Bearer ${credential}`] : ["x-api-key", credential];
|
|
113
|
+
const target = new URL(upstream);
|
|
114
|
+
const send = target.protocol === "https:" ? httpsRequest : httpRequest;
|
|
115
|
+
const refused = [];
|
|
116
|
+
let refusedCount = 0;
|
|
117
|
+
// What the sandbox sends is untrusted: keep a few short entries, and a count.
|
|
118
|
+
const refuse = (what) => {
|
|
119
|
+
refusedCount += 1;
|
|
120
|
+
const entry = what.slice(0, MAX_ENTRY);
|
|
121
|
+
if (refused.length < MAX_KEPT && !refused.includes(entry)) refused.push(entry);
|
|
122
|
+
};
|
|
123
|
+
/** @type {Map<string, number>} upstream status (or "error") to count */
|
|
124
|
+
const statuses = new Map();
|
|
125
|
+
let forwarded = 0;
|
|
126
|
+
let tokens = 0;
|
|
127
|
+
/** @type {string[]} */
|
|
128
|
+
const models = [];
|
|
129
|
+
let moreModels = false;
|
|
130
|
+
// What an answer names is kept only as a plain, short id.
|
|
131
|
+
const answeredBy = (model) => {
|
|
132
|
+
if (typeof model !== "string" || model.length > MAX_ENTRY || !MODEL_ID.test(model)) return;
|
|
133
|
+
if (models.includes(model)) return;
|
|
134
|
+
if (models.length < MAX_KEPT) models.push(model);
|
|
135
|
+
else moreModels = true;
|
|
136
|
+
};
|
|
137
|
+
let pastCap = 0;
|
|
138
|
+
const sockets = new Set();
|
|
139
|
+
const count = (key) => statuses.set(key, (statuses.get(key) ?? 0) + 1);
|
|
140
|
+
|
|
141
|
+
const server = createServer((req, res) => {
|
|
142
|
+
const raw = req.url ?? "";
|
|
143
|
+
if (!raw.startsWith("/")) {
|
|
144
|
+
// An absolute URL: someone is using the proxy as a forward proxy.
|
|
145
|
+
let host = raw;
|
|
146
|
+
try {
|
|
147
|
+
host = new URL(raw).host;
|
|
148
|
+
} catch {
|
|
149
|
+
host = raw;
|
|
150
|
+
}
|
|
151
|
+
refuse(host);
|
|
152
|
+
res.writeHead(403).end("deep-scan model proxy: only the model API is reachable\n");
|
|
153
|
+
return;
|
|
154
|
+
}
|
|
155
|
+
const path = raw.split("?")[0];
|
|
156
|
+
// The checks run on the path as the API would route it, percent-decoded,
|
|
157
|
+
// so `/v1/%6dessages/batches` is the batch path it names. A path that
|
|
158
|
+
// does not decode, or still holds a `%` once decoded (encoded twice), is
|
|
159
|
+
// refused. No dot segment, plain or encoded, may walk it out of /v1/.
|
|
160
|
+
let decoded = null;
|
|
161
|
+
try {
|
|
162
|
+
decoded = decodeURIComponent(path);
|
|
163
|
+
} catch {
|
|
164
|
+
decoded = null;
|
|
165
|
+
}
|
|
166
|
+
if (
|
|
167
|
+
decoded === null ||
|
|
168
|
+
decoded.includes("%") ||
|
|
169
|
+
!MODEL_PATH.test(path) ||
|
|
170
|
+
!MODEL_PATH.test(decoded) ||
|
|
171
|
+
UNCOUNTED_PATH.test(decoded) ||
|
|
172
|
+
// An empty segment (`/v1//messages/batches`): a front end that merges
|
|
173
|
+
// slashes would route it past the uncounted-path check.
|
|
174
|
+
/\/\/|\/$/.test(decoded) ||
|
|
175
|
+
/(^|\/)\.{1,2}(\/|$)|\\/.test(decoded) ||
|
|
176
|
+
/(^|\/)(\.|%2e){1,2}(\/|$)|%2f|\\/i.test(path)
|
|
177
|
+
) {
|
|
178
|
+
refuse(path);
|
|
179
|
+
res.writeHead(403).end("deep-scan model proxy: only the model API's /v1/ paths\n");
|
|
180
|
+
return;
|
|
181
|
+
}
|
|
182
|
+
if (maxTokens !== undefined && tokens >= maxTokens) {
|
|
183
|
+
pastCap += 1;
|
|
184
|
+
if (pastCap === 1) onCap();
|
|
185
|
+
res.writeHead(403, { "content-type": "application/json" }).end(
|
|
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
|
+
);
|
|
194
|
+
return;
|
|
195
|
+
}
|
|
196
|
+
const headers = {};
|
|
197
|
+
for (const [name, value] of Object.entries(req.headers)) {
|
|
198
|
+
if (!DROPPED.has(name.toLowerCase()) && value !== undefined) headers[name] = value;
|
|
199
|
+
}
|
|
200
|
+
headers[auth[0]] = auth[1];
|
|
201
|
+
// A plain body, so the meter can read its usage.
|
|
202
|
+
headers["accept-encoding"] = "identity";
|
|
203
|
+
forwarded += 1;
|
|
204
|
+
const upstreamReq = send(
|
|
205
|
+
{
|
|
206
|
+
protocol: target.protocol,
|
|
207
|
+
hostname: target.hostname,
|
|
208
|
+
port: target.port || undefined,
|
|
209
|
+
method: req.method,
|
|
210
|
+
path: raw,
|
|
211
|
+
headers,
|
|
212
|
+
},
|
|
213
|
+
(r) => {
|
|
214
|
+
count(String(r.statusCode ?? "error"));
|
|
215
|
+
const back = {};
|
|
216
|
+
for (const [name, value] of Object.entries(r.headers)) {
|
|
217
|
+
if (!DROPPED.has(name.toLowerCase()) && value !== undefined) back[name] = value;
|
|
218
|
+
}
|
|
219
|
+
res.writeHead(r.statusCode ?? 502, back);
|
|
220
|
+
meter(
|
|
221
|
+
r,
|
|
222
|
+
(n) => {
|
|
223
|
+
tokens += n;
|
|
224
|
+
},
|
|
225
|
+
answeredBy,
|
|
226
|
+
);
|
|
227
|
+
r.pipe(res);
|
|
228
|
+
},
|
|
229
|
+
);
|
|
230
|
+
upstreamReq.on("error", () => {
|
|
231
|
+
count("error");
|
|
232
|
+
if (!res.headersSent) {
|
|
233
|
+
res.writeHead(502).end("deep-scan model proxy: the model API could not be reached\n");
|
|
234
|
+
} else {
|
|
235
|
+
res.destroy();
|
|
236
|
+
}
|
|
237
|
+
});
|
|
238
|
+
req.pipe(upstreamReq);
|
|
239
|
+
});
|
|
240
|
+
|
|
241
|
+
// A CONNECT tunnel would reach any host: refused.
|
|
242
|
+
server.on("connect", (req, socket) => {
|
|
243
|
+
socket.on("error", () => {});
|
|
244
|
+
refuse(req.url ?? "");
|
|
245
|
+
socket.end("HTTP/1.1 403 Forbidden\r\n\r\n");
|
|
246
|
+
});
|
|
247
|
+
server.on("connection", (socket) => {
|
|
248
|
+
sockets.add(socket);
|
|
249
|
+
socket.on("close", () => sockets.delete(socket));
|
|
250
|
+
});
|
|
251
|
+
|
|
252
|
+
await new Promise((resolve, reject) => {
|
|
253
|
+
server.once("error", reject);
|
|
254
|
+
server.listen(0, bind, () => resolve(undefined));
|
|
255
|
+
});
|
|
256
|
+
const address = server.address();
|
|
257
|
+
return {
|
|
258
|
+
port: typeof address === "object" && address ? address.port : 0,
|
|
259
|
+
refused,
|
|
260
|
+
tokens: () => tokens,
|
|
261
|
+
models: () => [...models],
|
|
262
|
+
// Every forwarded request answered, and each answer a 401 or 403.
|
|
263
|
+
credentialRefused: () =>
|
|
264
|
+
forwarded > 0 &&
|
|
265
|
+
[...statuses].reduce(
|
|
266
|
+
(sum, [status, n]) => (status === "401" || status === "403" ? sum + n : sum),
|
|
267
|
+
0,
|
|
268
|
+
) === forwarded,
|
|
269
|
+
summary() {
|
|
270
|
+
const byStatus = [...statuses].map(([s, n]) => `${s} x${n}`).join(", ");
|
|
271
|
+
const parts = [
|
|
272
|
+
`forwarded ${forwarded} request(s) to ${target.host}${byStatus ? ` (answers: ${byStatus})` : ""}`,
|
|
273
|
+
];
|
|
274
|
+
if (forwarded) {
|
|
275
|
+
parts.push(
|
|
276
|
+
models.length
|
|
277
|
+
? `the model API answered with ${models.join(", ")}${moreModels ? ", ..." : ""}`
|
|
278
|
+
: "no answer named a model",
|
|
279
|
+
);
|
|
280
|
+
}
|
|
281
|
+
if (refusedCount) {
|
|
282
|
+
const more = refusedCount > refused.length ? ", ..." : "";
|
|
283
|
+
parts.push(`refused ${refusedCount} (${refused.join(", ")}${more})`);
|
|
284
|
+
}
|
|
285
|
+
if (maxTokens !== undefined) {
|
|
286
|
+
parts.push(
|
|
287
|
+
`counted ${tokens} of the ${maxTokens}-token cap${pastCap ? `, and refused ${pastCap} request(s) past it` : ""}`,
|
|
288
|
+
);
|
|
289
|
+
}
|
|
290
|
+
return parts.join("; ");
|
|
291
|
+
},
|
|
292
|
+
close: () =>
|
|
293
|
+
new Promise((resolve) => {
|
|
294
|
+
for (const s of sockets) s.destroy();
|
|
295
|
+
server.close(() => resolve(undefined));
|
|
296
|
+
}),
|
|
297
|
+
};
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
/**
|
|
301
|
+
* Count the tokens an answer's `usage` reports, as the answer streams past:
|
|
302
|
+
* each kind in COUNTED_USAGE, from a JSON body or from a stream's
|
|
303
|
+
* `message_start` and `message_delta` events. A stream's usage is
|
|
304
|
+
* cumulative, so each kind counts its highest value once. A compressed body
|
|
305
|
+
* (sent although the proxy asked for none) is decoded for counting only.
|
|
306
|
+
* The `model` the answer names (a JSON body's, or a stream's
|
|
307
|
+
* `message_start`'s) goes to `named`, unchecked.
|
|
308
|
+
* @param {import("node:http").IncomingMessage} r
|
|
309
|
+
* @param {(n: number) => void} add called with each newly counted amount
|
|
310
|
+
* @param {(model: unknown) => void} named called with each `model` an answer names
|
|
311
|
+
*/
|
|
312
|
+
function meter(r, add, named) {
|
|
313
|
+
const seen = Object.fromEntries(COUNTED_USAGE.map((k) => [k, 0]));
|
|
314
|
+
const take = (obj) => {
|
|
315
|
+
const model = obj?.model ?? obj?.message?.model;
|
|
316
|
+
if (model !== undefined) named(model);
|
|
317
|
+
const usage = obj?.usage ?? obj?.message?.usage;
|
|
318
|
+
if (!usage || typeof usage !== "object") return;
|
|
319
|
+
for (const key of COUNTED_USAGE) {
|
|
320
|
+
const n = usage[key];
|
|
321
|
+
if (typeof n === "number" && Number.isFinite(n) && n > seen[key]) {
|
|
322
|
+
add(n - seen[key]);
|
|
323
|
+
seen[key] = n;
|
|
324
|
+
}
|
|
325
|
+
}
|
|
326
|
+
};
|
|
327
|
+
const parse = (text) => {
|
|
328
|
+
try {
|
|
329
|
+
take(JSON.parse(text));
|
|
330
|
+
} catch {
|
|
331
|
+
// Not JSON: nothing to count.
|
|
332
|
+
}
|
|
333
|
+
};
|
|
334
|
+
const stream = /text\/event-stream/i.test(String(r.headers["content-type"] ?? ""));
|
|
335
|
+
const decoders = {
|
|
336
|
+
gzip: createGunzip,
|
|
337
|
+
"x-gzip": createGunzip,
|
|
338
|
+
deflate: createInflate,
|
|
339
|
+
br: createBrotliDecompress,
|
|
340
|
+
};
|
|
341
|
+
const encoding = String(r.headers["content-encoding"] ?? "identity")
|
|
342
|
+
.trim()
|
|
343
|
+
.toLowerCase();
|
|
344
|
+
/** @type {import("node:stream").Readable} */
|
|
345
|
+
let body = r;
|
|
346
|
+
if (encoding !== "identity" && encoding !== "") {
|
|
347
|
+
const make = decoders[encoding];
|
|
348
|
+
if (!make) return;
|
|
349
|
+
const decoder = make();
|
|
350
|
+
decoder.on("error", () => {});
|
|
351
|
+
r.on("data", (chunk) => decoder.write(chunk));
|
|
352
|
+
r.on("end", () => decoder.end());
|
|
353
|
+
body = decoder;
|
|
354
|
+
}
|
|
355
|
+
let pending = "";
|
|
356
|
+
let size = 0;
|
|
357
|
+
let overflow = false;
|
|
358
|
+
body.on("data", (chunk) => {
|
|
359
|
+
const text = chunk.toString("utf8");
|
|
360
|
+
if (!stream) {
|
|
361
|
+
size += text.length;
|
|
362
|
+
if (size > MAX_BODY) overflow = true;
|
|
363
|
+
if (!overflow) pending += text;
|
|
364
|
+
return;
|
|
365
|
+
}
|
|
366
|
+
pending += text;
|
|
367
|
+
const lines = pending.split(/\r?\n/);
|
|
368
|
+
pending = lines.pop() ?? "";
|
|
369
|
+
if (pending.length > MAX_LINE) pending = "";
|
|
370
|
+
for (const line of lines) {
|
|
371
|
+
if (line.startsWith("data:") && /"(usage|model)"/.test(line)) parse(line.slice(5).trim());
|
|
372
|
+
}
|
|
373
|
+
});
|
|
374
|
+
body.on("end", () => {
|
|
375
|
+
if (!stream && !overflow) parse(pending);
|
|
376
|
+
else if (stream && pending.startsWith("data:")) parse(pending.slice(5).trim());
|
|
377
|
+
});
|
|
378
|
+
}
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
// The Deep scan launcher's pre-flight refusals (#368): before any sandbox
|
|
2
|
+
// runtime is touched, refuse a GitHub token that would reach the sandbox and
|
|
3
|
+
// a .env that would be forwarded into it wholesale. Both checks read only the
|
|
4
|
+
// launcher's own environment and the trusted ref's file list.
|
|
5
|
+
|
|
6
|
+
import { firstLine } from "../exec.mjs";
|
|
7
|
+
|
|
8
|
+
/** The GitHub token variables that must never reach the sandbox. */
|
|
9
|
+
export const GITHUB_TOKEN_VARS = Object.freeze(["GH_TOKEN", "GITHUB_TOKEN"]);
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* The GitHub token variables set to a value in `env`, by the names `env`
|
|
13
|
+
* gives them. Names are matched in any letter case, as Windows does.
|
|
14
|
+
* @param {Record<string, string | undefined>} env
|
|
15
|
+
* @returns {string[]}
|
|
16
|
+
*/
|
|
17
|
+
export function strayTokens(env) {
|
|
18
|
+
return Object.keys(env).filter(
|
|
19
|
+
(name) => GITHUB_TOKEN_VARS.includes(name.toUpperCase()) && Boolean(env[name]),
|
|
20
|
+
);
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
// `.env` and `.env.<anything>`, except the templates that hold no values.
|
|
24
|
+
const ENV_FILE = /^\.env(\..+)?$/;
|
|
25
|
+
/** The suffixes of the `.env` templates that hold no values; docs/security-audit.md lists them. */
|
|
26
|
+
export const ENV_TEMPLATES = Object.freeze([
|
|
27
|
+
"example",
|
|
28
|
+
"sample",
|
|
29
|
+
"template",
|
|
30
|
+
"dist",
|
|
31
|
+
"default",
|
|
32
|
+
"defaults",
|
|
33
|
+
]);
|
|
34
|
+
const TEMPLATE = new RegExp(`\\.(${ENV_TEMPLATES.join("|")})$`, "i");
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* Of the environment files on the default branch, those a Verification run
|
|
38
|
+
* would still carry in from it: every one when the recipe builds a
|
|
39
|
+
* Dockerfile (the build context is the default branch's whole tree), and
|
|
40
|
+
* else those under a repository grounding path. A grounding entry with
|
|
41
|
+
* pathspec characters is taken to reach them all.
|
|
42
|
+
* @param {string[]} files
|
|
43
|
+
* @param {{ dockerfile?: string, grounding: string[] }} steps
|
|
44
|
+
* @returns {{ files: string[], why: string }}
|
|
45
|
+
*/
|
|
46
|
+
export function envFilesCarriedFromDefault(files, steps) {
|
|
47
|
+
if (steps.dockerfile !== undefined) {
|
|
48
|
+
return { files, why: `the Dockerfile's build context (${steps.dockerfile})` };
|
|
49
|
+
}
|
|
50
|
+
const paths = steps.grounding.filter((g) => !/^https?:\/\//i.test(g));
|
|
51
|
+
const reaches = (source, file) => {
|
|
52
|
+
if (/[*?[\]:\\]/.test(source)) return true;
|
|
53
|
+
const dir = source.replace(/^(\.\/)+/, "").replace(/\/+$/, "");
|
|
54
|
+
return dir === "" || dir === "." || file === dir || file.startsWith(`${dir}/`);
|
|
55
|
+
};
|
|
56
|
+
return {
|
|
57
|
+
files: files.filter((f) => paths.some((g) => reaches(g, f))),
|
|
58
|
+
why: "the recipe's grounding paths",
|
|
59
|
+
};
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** Whether a repository path names an environment file. */
|
|
63
|
+
export function isEnvFile(path) {
|
|
64
|
+
const base = path.slice(path.lastIndexOf("/") + 1);
|
|
65
|
+
return ENV_FILE.test(base) && !TEMPLATE.test(base);
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* The environment files committed at `ref`. The copy-in exports the trusted
|
|
70
|
+
* ref's whole tree into the sandbox, so each would be forwarded wholesale.
|
|
71
|
+
* @param {{ runner: import("../exec.mjs").Runner, root: string, ref: string }} opts
|
|
72
|
+
* @returns {{ files: string[] } | { error: string }}
|
|
73
|
+
*/
|
|
74
|
+
export function envFilesAtRef({ runner, root, ref }) {
|
|
75
|
+
const r = runner("git", ["-C", root, "ls-tree", "-r", "-z", "--name-only", ref]);
|
|
76
|
+
if (r.status !== 0) return { error: firstLine(r.stderr) || "git ls-tree failed" };
|
|
77
|
+
return { files: r.stdout.split("\0").filter((p) => p && isEnvFile(p)) };
|
|
78
|
+
}
|