@buildanagent/harness 0.1.0-alpha.28 → 0.1.0-alpha.30

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.
Files changed (113) hide show
  1. package/README.md +152 -5
  2. package/dist/context/file-spill.d.ts +11 -1
  3. package/dist/context/file-spill.js +23 -8
  4. package/dist/context/file-spill.js.map +1 -1
  5. package/dist/context/spill.d.ts +5 -1
  6. package/dist/context/spill.js +6 -2
  7. package/dist/context/spill.js.map +1 -1
  8. package/dist/credentials/addresses.d.ts +11 -0
  9. package/dist/credentials/addresses.js +41 -2
  10. package/dist/credentials/addresses.js.map +1 -1
  11. package/dist/credentials/allowlist.d.ts +22 -2
  12. package/dist/credentials/allowlist.js +74 -17
  13. package/dist/credentials/allowlist.js.map +1 -1
  14. package/dist/credentials/egress-policy.d.ts +69 -0
  15. package/dist/credentials/egress-policy.js +170 -0
  16. package/dist/credentials/egress-policy.js.map +1 -0
  17. package/dist/credentials/egress-proxy.d.ts +13 -1
  18. package/dist/credentials/egress-proxy.js +179 -11
  19. package/dist/credentials/egress-proxy.js.map +1 -1
  20. package/dist/credentials/git-route.d.ts +68 -0
  21. package/dist/credentials/git-route.js +288 -0
  22. package/dist/credentials/git-route.js.map +1 -0
  23. package/dist/credentials/index.d.ts +5 -1
  24. package/dist/credentials/index.js +5 -1
  25. package/dist/credentials/index.js.map +1 -1
  26. package/dist/credentials/scrub.d.ts +7 -0
  27. package/dist/credentials/scrub.js +22 -0
  28. package/dist/credentials/scrub.js.map +1 -1
  29. package/dist/errors.d.ts +14 -7
  30. package/dist/errors.js +13 -6
  31. package/dist/errors.js.map +1 -1
  32. package/dist/sandbox/base.d.ts +11 -1
  33. package/dist/sandbox/base.js +14 -0
  34. package/dist/sandbox/base.js.map +1 -1
  35. package/dist/sandbox/docker/index.d.ts +8 -2
  36. package/dist/sandbox/docker/index.js +63 -14
  37. package/dist/sandbox/docker/index.js.map +1 -1
  38. package/dist/sandbox/errors.d.ts +30 -2
  39. package/dist/sandbox/errors.js +36 -1
  40. package/dist/sandbox/errors.js.map +1 -1
  41. package/dist/sandbox/escalation-table.d.ts +38 -0
  42. package/dist/sandbox/escalation-table.js +95 -0
  43. package/dist/sandbox/escalation-table.js.map +1 -0
  44. package/dist/sandbox/escalation.d.ts +191 -0
  45. package/dist/sandbox/escalation.js +370 -0
  46. package/dist/sandbox/escalation.js.map +1 -0
  47. package/dist/sandbox/host-files.d.ts +2 -0
  48. package/dist/sandbox/host-files.js +10 -0
  49. package/dist/sandbox/host-files.js.map +1 -1
  50. package/dist/sandbox/index.d.ts +9 -4
  51. package/dist/sandbox/index.js +8 -3
  52. package/dist/sandbox/index.js.map +1 -1
  53. package/dist/sandbox/policy.d.ts +49 -0
  54. package/dist/sandbox/policy.js +149 -0
  55. package/dist/sandbox/policy.js.map +1 -0
  56. package/dist/sandbox/process.js +1 -1
  57. package/dist/sandbox/process.js.map +1 -1
  58. package/dist/sandbox/srt/index.d.ts +5 -2
  59. package/dist/sandbox/srt/index.js +27 -8
  60. package/dist/sandbox/srt/index.js.map +1 -1
  61. package/dist/sandbox/srt/settings.d.ts +17 -5
  62. package/dist/sandbox/srt/settings.js +53 -0
  63. package/dist/sandbox/srt/settings.js.map +1 -1
  64. package/dist/sandbox/types.d.ts +41 -4
  65. package/dist/sandbox/types.js.map +1 -1
  66. package/dist/sandbox/widen.d.ts +10 -0
  67. package/dist/sandbox/widen.js +150 -0
  68. package/dist/sandbox/widen.js.map +1 -0
  69. package/dist/session/approvals.d.ts +30 -1
  70. package/dist/session/approvals.js +12 -4
  71. package/dist/session/approvals.js.map +1 -1
  72. package/dist/session/code-call.d.ts +15 -1
  73. package/dist/session/code-call.js +2 -1
  74. package/dist/session/code-call.js.map +1 -1
  75. package/dist/session/escalation-log.d.ts +65 -0
  76. package/dist/session/escalation-log.js +84 -0
  77. package/dist/session/escalation-log.js.map +1 -0
  78. package/dist/session/rebuild.js +12 -3
  79. package/dist/session/rebuild.js.map +1 -1
  80. package/dist/testing/fake-sandbox.d.ts +21 -3
  81. package/dist/testing/fake-sandbox.js +157 -8
  82. package/dist/testing/fake-sandbox.js.map +1 -1
  83. package/dist/testing/sandbox-conformance.js +108 -1
  84. package/dist/testing/sandbox-conformance.js.map +1 -1
  85. package/dist/tools/builtins/bash.d.ts +9 -0
  86. package/dist/tools/builtins/bash.js +75 -0
  87. package/dist/tools/builtins/bash.js.map +1 -0
  88. package/dist/tools/builtins/builtins.d.ts +38 -0
  89. package/dist/tools/builtins/builtins.js +48 -0
  90. package/dist/tools/builtins/builtins.js.map +1 -0
  91. package/dist/tools/builtins/descriptions.d.ts +69 -0
  92. package/dist/tools/builtins/descriptions.js +94 -0
  93. package/dist/tools/builtins/descriptions.js.map +1 -0
  94. package/dist/tools/builtins/fetch.d.ts +12 -0
  95. package/dist/tools/builtins/fetch.js +157 -0
  96. package/dist/tools/builtins/fetch.js.map +1 -0
  97. package/dist/tools/builtins/files.d.ts +27 -0
  98. package/dist/tools/builtins/files.js +274 -0
  99. package/dist/tools/builtins/files.js.map +1 -0
  100. package/dist/tools/builtins/paths.d.ts +30 -0
  101. package/dist/tools/builtins/paths.js +62 -0
  102. package/dist/tools/builtins/paths.js.map +1 -0
  103. package/dist/tools/builtins/results.d.ts +15 -0
  104. package/dist/tools/builtins/results.js +31 -0
  105. package/dist/tools/builtins/results.js.map +1 -0
  106. package/dist/tools/builtins/search.d.ts +18 -0
  107. package/dist/tools/builtins/search.js +217 -0
  108. package/dist/tools/builtins/search.js.map +1 -0
  109. package/dist/tools/index.d.ts +6 -2
  110. package/dist/tools/index.js +5 -2
  111. package/dist/tools/index.js.map +1 -1
  112. package/llms.txt +52 -0
  113. package/package.json +5 -5
@@ -0,0 +1,288 @@
1
+ /**
2
+ * The checks of a git route: git's smart HTTP protocol over a credential route, limited to listed repositories and,
3
+ * for a push, to listed branches. It is pure and portable, so the proxy and any other backend can share it. Everything
4
+ * it doesn't understand is refused: an unknown path, a query, a push certificate, a pkt-line it can't read, a command
5
+ * list past its size limit, a deletion, a tag and any ref outside the patterns.
6
+ */
7
+ import { HarnessError } from "../errors.js";
8
+ /** The most bytes of a push's command list, before its flush, that the route reads. A longer list is refused. */
9
+ export const GIT_MAX_COMMAND_BYTES = 64 * 1024;
10
+ /** The most ref updates in one push. */
11
+ export const GIT_MAX_COMMANDS = 64;
12
+ const PKT_MAX = 65520;
13
+ const SEGMENT = /^[A-Za-z0-9_.-]+$/;
14
+ const REPOSITORY_PATH = /^\/([^/]+)\/([^/]+)\/(info\/refs|git-receive-pack|git-upload-pack)$/;
15
+ const OID = "([0-9a-f]{40}|[0-9a-f]{64})";
16
+ const COMMAND = new RegExp(`^${OID} ${OID} (\\S+)$`);
17
+ const SHALLOW = new RegExp(`^shallow ${OID}$`);
18
+ const ZERO = /^0+$/;
19
+ const USERNAME = /^[A-Za-z0-9._-]{1,64}$/;
20
+ const invalid = (message) => new HarnessError("invalid_egress_options", message);
21
+ /** Whether `name` is a ref name git itself would accept, by `git check-ref-format`'s rules, under `refs/`. */
22
+ export function isValidRefName(name) {
23
+ if (!name.startsWith("refs/") || name.length > 1024)
24
+ return false;
25
+ const control = [...name].some((char) => char.charCodeAt(0) <= 0x20 || char.charCodeAt(0) === 0x7f);
26
+ if (control || /[~^:?*[\\]/.test(name) || name.includes("..") || name.includes("@{") || name.includes("//")) {
27
+ return false;
28
+ }
29
+ if (name.endsWith("/") || name.endsWith("."))
30
+ return false;
31
+ return name.split("/").every((part) => part !== "" && !part.startsWith(".") && !part.endsWith(".lock"));
32
+ }
33
+ /** Throws unless `pattern` is a branch, or a branch prefix ending in `/*`, under `refs/heads/`. */
34
+ function checkPattern(pattern, index) {
35
+ const text = typeof pattern === "string" ? pattern : "";
36
+ const bare = text.endsWith("/*") ? `${text.slice(0, -2)}/x` : text;
37
+ if (!text.startsWith("refs/heads/") || !isValidRefName(bare)) {
38
+ throw invalid(`push ref ${index} must be a branch, or a branch prefix ending in /*, under refs/heads/`);
39
+ }
40
+ }
41
+ /** Throws unless every field of a git route's filter is usable. The message names the field, never its value. */
42
+ export function checkGitFilter(filter) {
43
+ const { repositories, pushRefs, fetch, username } = filter;
44
+ if (!Array.isArray(repositories) || repositories.length === 0) {
45
+ throw invalid("a git route needs at least one repository, as owner/name");
46
+ }
47
+ repositories.forEach((repository, index) => {
48
+ const parts = typeof repository === "string" ? repository.split("/") : [];
49
+ const usable = parts.length === 2 && parts.every((part) => SEGMENT.test(part) && !/^\.+$/.test(part));
50
+ if (!usable)
51
+ throw invalid(`repository ${index} must be owner/name`);
52
+ });
53
+ if (!Array.isArray(pushRefs))
54
+ throw invalid("a git route's pushRefs must be a list");
55
+ pushRefs.forEach(checkPattern);
56
+ if (typeof fetch !== "boolean")
57
+ throw invalid("a git route's fetch must be true or false");
58
+ if (pushRefs.length === 0 && !fetch)
59
+ throw invalid("a git route must allow a push, a fetch or both");
60
+ if (typeof username !== "string" || !USERNAME.test(username))
61
+ throw invalid("a git route's username is not usable");
62
+ }
63
+ /** The repository `owner/name` in lower case, without a trailing `.git`. */
64
+ const repositoryKey = (owner, name) => `${owner}/${name.replace(/\.git$/i, "")}`.toLowerCase();
65
+ /**
66
+ * The git endpoint a request is for, or the reason it is refused. `path` is the part after the route's name, and
67
+ * `query` is the search part with its `?`, or empty.
68
+ */
69
+ export function gitEndpoint(filter, method, path, query) {
70
+ const match = REPOSITORY_PATH.exec(path);
71
+ const [, owner = "", name = "", action = ""] = match ?? [];
72
+ if (match === null || ![owner, name].every((part) => SEGMENT.test(part) && !/^\.+$/.test(part))) {
73
+ return { refused: "git_path_refused" };
74
+ }
75
+ const listed = filter.repositories.map((repository) => repositoryKey(...repository.split("/")));
76
+ if (!listed.includes(repositoryKey(owner, name)))
77
+ return { refused: "git_repository_refused" };
78
+ const endpoint = endpointOf(action, method.toUpperCase(), query);
79
+ if (endpoint === undefined)
80
+ return { refused: "git_path_refused" };
81
+ if (endpoint.service === "git-receive-pack" && filter.pushRefs.length === 0)
82
+ return { refused: "git_push_refused" };
83
+ if (endpoint.service === "git-upload-pack" && !filter.fetch)
84
+ return { refused: "git_fetch_refused" };
85
+ return endpoint;
86
+ }
87
+ function endpointOf(action, method, query) {
88
+ if (action === "info/refs") {
89
+ if (method !== "GET")
90
+ return undefined;
91
+ if (query === "?service=git-receive-pack")
92
+ return { service: "git-receive-pack", phase: "advertise" };
93
+ if (query === "?service=git-upload-pack")
94
+ return { service: "git-upload-pack", phase: "advertise" };
95
+ return undefined;
96
+ }
97
+ if (method !== "POST" || query !== "")
98
+ return undefined;
99
+ return { service: action, phase: "rpc" };
100
+ }
101
+ const DECODER = new TextDecoder("utf-8", { fatal: true });
102
+ const LENGTH = /^[0-9a-fA-F]{4}$/;
103
+ const BAD = { refused: "git_bad_pkt_line" };
104
+ const FLUSH_LENGTH = 4;
105
+ /** The text of one pkt-line's payload without its line feed, or `undefined` when it isn't UTF-8. */
106
+ function payloadText(bytes) {
107
+ try {
108
+ return DECODER.decode(bytes).replace(/\n$/, "");
109
+ }
110
+ catch {
111
+ return undefined;
112
+ }
113
+ }
114
+ /** Reads one command line; the first carries the capabilities after a NUL, which are dropped. */
115
+ function readCommand(text, commands) {
116
+ if (commands.length === 0 && SHALLOW.test(text))
117
+ return undefined;
118
+ if (text.startsWith("push-cert"))
119
+ return "git_push_cert";
120
+ const line = commands.length === 0 ? (text.split("\0")[0] ?? "") : text;
121
+ if (commands.length > 0 && text.includes("\0"))
122
+ return "git_bad_pkt_line";
123
+ const match = COMMAND.exec(line);
124
+ if (match === null || match[1]?.length !== match[2]?.length)
125
+ return "git_bad_pkt_line";
126
+ commands.push({ old: match[1] ?? "", new: match[2] ?? "", ref: match[3] ?? "" });
127
+ return commands.length > GIT_MAX_COMMANDS ? "git_too_many_commands" : undefined;
128
+ }
129
+ /**
130
+ * One pkt-line at `at` in `bytes`, which starts at body offset `offset`: a flush, a payload's text, how many bytes from
131
+ * `at` it needs before it can be read, or a refusal. A line that would end past `GIT_MAX_COMMAND_BYTES` is refused from
132
+ * its header, so the reader never holds much more than the limit.
133
+ */
134
+ function readPacket(bytes, at, offset) {
135
+ if (bytes.length - at < 4)
136
+ return { needed: 4 };
137
+ const header = String.fromCharCode(...bytes.subarray(at, at + 4));
138
+ if (!LENGTH.test(header))
139
+ return BAD;
140
+ const length = Number.parseInt(header, 16);
141
+ if (length === 0)
142
+ return "flush";
143
+ if (length < 5 || length > PKT_MAX)
144
+ return BAD;
145
+ if (offset + at + length > GIT_MAX_COMMAND_BYTES)
146
+ return { refused: "git_too_large" };
147
+ if (bytes.length - at < length)
148
+ return { needed: length };
149
+ const text = payloadText(bytes.subarray(at + 4, at + length));
150
+ return text === undefined ? BAD : { text, length };
151
+ }
152
+ /** The chunks joined into one array, or the one chunk itself. */
153
+ function join(chunks) {
154
+ if (chunks.length === 1)
155
+ return chunks[0];
156
+ const joined = new Uint8Array(chunks.reduce((total, chunk) => total + chunk.length, 0));
157
+ let at = 0;
158
+ for (const chunk of chunks) {
159
+ joined.set(chunk, at);
160
+ at += chunk.length;
161
+ }
162
+ return joined;
163
+ }
164
+ /**
165
+ * Reads the command list at the start of a push body as the body arrives, in pieces of any size, and gives the route's
166
+ * verdict once it can. The work is linear in the bytes received: pieces are joined only once they hold the next
167
+ * pkt-line's header or the whole line, and a line already read is never read again. A list whose lines end past
168
+ * `GIT_MAX_COMMAND_BYTES` is refused as soon as a header says so, however the body is split.
169
+ */
170
+ export class PushReader {
171
+ #filter;
172
+ #pending = [];
173
+ #pendingBytes = 0;
174
+ /** The body offset of the first pending byte. Every byte before it belongs to a pkt-line already read. */
175
+ #offset = 0;
176
+ /** How many pending bytes the next pkt-line needs before it can be read. */
177
+ #needed = 4;
178
+ #commands = [];
179
+ /** Whether the body so far is exactly one flush, git's probe before a large push. */
180
+ #probe = false;
181
+ #verdict;
182
+ constructor(filter) {
183
+ this.#filter = filter;
184
+ }
185
+ /** Reads the next piece of the body and returns the verdict so far. Bytes after a verdict are not read. */
186
+ add(chunk) {
187
+ if (this.#verdict !== undefined)
188
+ return this.#verdict;
189
+ if (chunk.length === 0)
190
+ return "incomplete";
191
+ // The probe is a body of one flush and nothing else, so any byte after it is refused.
192
+ if (this.#probe)
193
+ return this.#settle(BAD);
194
+ this.#pending.push(chunk);
195
+ this.#pendingBytes += chunk.length;
196
+ return this.#pendingBytes < this.#needed ? "incomplete" : this.#read();
197
+ }
198
+ /** Says the body has ended and returns the final verdict: a list still incomplete is refused. */
199
+ end() {
200
+ return this.#verdict ?? this.#settle(this.#probe ? "allowed" : BAD);
201
+ }
202
+ #read() {
203
+ const bytes = join(this.#pending);
204
+ let at = 0;
205
+ for (;;) {
206
+ const packet = readPacket(bytes, at, this.#offset);
207
+ if (packet === "flush")
208
+ return this.#flush(bytes, at);
209
+ if ("refused" in packet)
210
+ return this.#settle(packet);
211
+ if ("needed" in packet) {
212
+ this.#pending = at < bytes.length ? [bytes.subarray(at)] : [];
213
+ this.#pendingBytes = bytes.length - at;
214
+ this.#offset += at;
215
+ this.#needed = packet.needed;
216
+ return "incomplete";
217
+ }
218
+ const refused = readCommand(packet.text, this.#commands);
219
+ if (refused !== undefined)
220
+ return this.#settle({ refused });
221
+ at += packet.length;
222
+ }
223
+ }
224
+ /** The verdict at a flush at `at`: the end of the command list, git's probe, or a flush with no command before it. */
225
+ #flush(bytes, at) {
226
+ if (this.#commands.length > 0)
227
+ return this.#settle(commandsVerdict(this.#commands, this.#filter));
228
+ if (this.#offset + at !== 0 || bytes.length > FLUSH_LENGTH)
229
+ return this.#settle(BAD);
230
+ this.#probe = true;
231
+ this.#pending = [];
232
+ this.#pendingBytes = 0;
233
+ return "incomplete";
234
+ }
235
+ #settle(verdict) {
236
+ this.#verdict = verdict;
237
+ this.#pending = [];
238
+ this.#pendingBytes = 0;
239
+ return verdict;
240
+ }
241
+ }
242
+ /** Whether `ref` is matched by one of the patterns: exactly, or under a prefix that ends in `/*`. */
243
+ function refAllowed(ref, patterns) {
244
+ return patterns.some((pattern) => pattern.endsWith("/*") ? ref.startsWith(pattern.slice(0, -1)) && ref.length > pattern.length - 1 : ref === pattern);
245
+ }
246
+ /** Whether every command creates or updates a ref the patterns allow, or why not. */
247
+ function commandsVerdict(commands, filter) {
248
+ for (const command of commands) {
249
+ if (ZERO.test(command.new))
250
+ return { refused: "git_delete_refused" };
251
+ if (!isValidRefName(command.ref) || !refAllowed(command.ref, filter.pushRefs))
252
+ return { refused: "git_ref_refused" };
253
+ }
254
+ return "allowed";
255
+ }
256
+ /**
257
+ * The route's verdict on the start of a push body: `incomplete` while the command list hasn't reached its flush,
258
+ * `allowed` once every command creates or updates a ref the patterns allow, or the reason it is refused. A body that is
259
+ * exactly one flush packet, the probe git sends before a large push, is `allowed` once it has ended, because it updates
260
+ * no ref; a byte after that flush is refused. `ended` says the body has no more bytes, so a list still incomplete is
261
+ * refused. A list whose lines end past `GIT_MAX_COMMAND_BYTES` is refused, whether or not its flush has arrived.
262
+ */
263
+ export function pushVerdict(bytes, filter, ended) {
264
+ const reader = new PushReader(filter);
265
+ const verdict = reader.add(bytes);
266
+ return verdict === "incomplete" && ended ? reader.end() : verdict;
267
+ }
268
+ /** Whether an `Authorization` header is HTTP Basic whose password is exactly `sentinel`. */
269
+ export function basicCarries(header, sentinel) {
270
+ const match = /^Basic ([A-Za-z0-9+/]+={0,2})$/i.exec(header ?? "");
271
+ if (match === null || sentinel === "")
272
+ return false;
273
+ let decoded;
274
+ try {
275
+ decoded = atob(match[1] ?? "");
276
+ }
277
+ catch {
278
+ return false;
279
+ }
280
+ const colon = decoded.indexOf(":");
281
+ return colon >= 0 && decoded.slice(colon + 1) === sentinel;
282
+ }
283
+ /** The `Authorization` value that carries `secret` as the password of `username`. */
284
+ export function basicHeader(username, secret) {
285
+ const bytes = new TextEncoder().encode(`${username}:${secret}`);
286
+ return `Basic ${btoa(String.fromCharCode(...bytes))}`;
287
+ }
288
+ //# sourceMappingURL=git-route.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"git-route.js","sourceRoot":"","sources":["../../src/credentials/git-route.ts"],"names":[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,CAAC,GAAG,KAAK,CAAC,CAAC,EAAE,CAAC;AACxD,CAAC","sourcesContent":["/**\n * The checks of a git route: git's smart HTTP protocol over a credential route, limited to listed repositories and,\n * for a push, to listed branches. It is pure and portable, so the proxy and any other backend can share it. Everything\n * it doesn't understand is refused: an unknown path, a query, a push certificate, a pkt-line it can't read, a command\n * list past its size limit, a deletion, a tag and any ref outside the patterns.\n */\nimport { HarnessError } from \"../errors.js\";\n\n/** What a git route lets through. */\nexport interface GitRouteFilter {\n /** The repositories the route reaches, as `owner/name`. Compared without case, as GitHub does. */\n readonly repositories: readonly string[];\n /**\n * The branches a push may create or update, as `refs/heads/<name>` or a prefix ending in `/*`, such as\n * `refs/heads/agent/*`. Leave it empty to refuse every push. A deletion and a tag are always refused.\n */\n readonly pushRefs: readonly string[];\n /** Whether a fetch or clone may read the repositories. A fetch is not limited by ref. */\n readonly fetch: boolean;\n /** The user name sent with the credential in HTTP Basic, such as `x-access-token` for a GitHub App token. */\n readonly username: string;\n}\n\n/** A git request the route accepts: which service, and whether it is the ref advertisement or the request itself. */\nexport interface GitEndpoint {\n readonly service: \"git-receive-pack\" | \"git-upload-pack\";\n readonly phase: \"advertise\" | \"rpc\";\n}\n\n/** The most bytes of a push's command list, before its flush, that the route reads. A longer list is refused. */\nexport const GIT_MAX_COMMAND_BYTES = 64 * 1024;\n/** The most ref updates in one push. */\nexport const GIT_MAX_COMMANDS = 64;\n\nconst PKT_MAX = 65520;\nconst SEGMENT = /^[A-Za-z0-9_.-]+$/;\nconst REPOSITORY_PATH = /^\\/([^/]+)\\/([^/]+)\\/(info\\/refs|git-receive-pack|git-upload-pack)$/;\nconst OID = \"([0-9a-f]{40}|[0-9a-f]{64})\";\nconst COMMAND = new RegExp(`^${OID} ${OID} (\\\\S+)$`);\nconst SHALLOW = new RegExp(`^shallow ${OID}$`);\nconst ZERO = /^0+$/;\nconst USERNAME = /^[A-Za-z0-9._-]{1,64}$/;\n\nconst invalid = (message: string) => new HarnessError(\"invalid_egress_options\", message);\n\n/** Whether `name` is a ref name git itself would accept, by `git check-ref-format`'s rules, under `refs/`. */\nexport function isValidRefName(name: string): boolean {\n if (!name.startsWith(\"refs/\") || name.length > 1024) return false;\n const control = [...name].some((char) => char.charCodeAt(0) <= 0x20 || char.charCodeAt(0) === 0x7f);\n if (control || /[~^:?*[\\\\]/.test(name) || name.includes(\"..\") || name.includes(\"@{\") || name.includes(\"//\")) {\n return false;\n }\n if (name.endsWith(\"/\") || name.endsWith(\".\")) return false;\n return name.split(\"/\").every((part) => part !== \"\" && !part.startsWith(\".\") && !part.endsWith(\".lock\"));\n}\n\n/** Throws unless `pattern` is a branch, or a branch prefix ending in `/*`, under `refs/heads/`. */\nfunction checkPattern(pattern: unknown, index: number): void {\n const text = typeof pattern === \"string\" ? pattern : \"\";\n const bare = text.endsWith(\"/*\") ? `${text.slice(0, -2)}/x` : text;\n if (!text.startsWith(\"refs/heads/\") || !isValidRefName(bare)) {\n throw invalid(`push ref ${index} must be a branch, or a branch prefix ending in /*, under refs/heads/`);\n }\n}\n\n/** Throws unless every field of a git route's filter is usable. The message names the field, never its value. */\nexport function checkGitFilter(filter: GitRouteFilter): void {\n const { repositories, pushRefs, fetch, username } = filter;\n if (!Array.isArray(repositories) || repositories.length === 0) {\n throw invalid(\"a git route needs at least one repository, as owner/name\");\n }\n repositories.forEach((repository: unknown, index) => {\n const parts = typeof repository === \"string\" ? repository.split(\"/\") : [];\n const usable = parts.length === 2 && parts.every((part) => SEGMENT.test(part) && !/^\\.+$/.test(part));\n if (!usable) throw invalid(`repository ${index} must be owner/name`);\n });\n if (!Array.isArray(pushRefs)) throw invalid(\"a git route's pushRefs must be a list\");\n pushRefs.forEach(checkPattern);\n if (typeof fetch !== \"boolean\") throw invalid(\"a git route's fetch must be true or false\");\n if (pushRefs.length === 0 && !fetch) throw invalid(\"a git route must allow a push, a fetch or both\");\n if (typeof username !== \"string\" || !USERNAME.test(username)) throw invalid(\"a git route's username is not usable\");\n}\n\n/** The repository `owner/name` in lower case, without a trailing `.git`. */\nconst repositoryKey = (owner: string, name: string): string => `${owner}/${name.replace(/\\.git$/i, \"\")}`.toLowerCase();\n\n/**\n * The git endpoint a request is for, or the reason it is refused. `path` is the part after the route's name, and\n * `query` is the search part with its `?`, or empty.\n */\nexport function gitEndpoint(\n filter: GitRouteFilter,\n method: string,\n path: string,\n query: string,\n): GitEndpoint | { readonly refused: string } {\n const match = REPOSITORY_PATH.exec(path);\n const [, owner = \"\", name = \"\", action = \"\"] = match ?? [];\n if (match === null || ![owner, name].every((part) => SEGMENT.test(part) && !/^\\.+$/.test(part))) {\n return { refused: \"git_path_refused\" };\n }\n const listed = filter.repositories.map((repository) => repositoryKey(...(repository.split(\"/\") as [string, string])));\n if (!listed.includes(repositoryKey(owner, name))) return { refused: \"git_repository_refused\" };\n const endpoint = endpointOf(action, method.toUpperCase(), query);\n if (endpoint === undefined) return { refused: \"git_path_refused\" };\n if (endpoint.service === \"git-receive-pack\" && filter.pushRefs.length === 0) return { refused: \"git_push_refused\" };\n if (endpoint.service === \"git-upload-pack\" && !filter.fetch) return { refused: \"git_fetch_refused\" };\n return endpoint;\n}\n\nfunction endpointOf(action: string, method: string, query: string): GitEndpoint | undefined {\n if (action === \"info/refs\") {\n if (method !== \"GET\") return undefined;\n if (query === \"?service=git-receive-pack\") return { service: \"git-receive-pack\", phase: \"advertise\" };\n if (query === \"?service=git-upload-pack\") return { service: \"git-upload-pack\", phase: \"advertise\" };\n return undefined;\n }\n if (method !== \"POST\" || query !== \"\") return undefined;\n return { service: action as GitEndpoint[\"service\"], phase: \"rpc\" };\n}\n\n/** One ref update in a push. */\ninterface PushCommand {\n readonly old: string;\n readonly new: string;\n readonly ref: string;\n}\n\nconst DECODER = new TextDecoder(\"utf-8\", { fatal: true });\nconst LENGTH = /^[0-9a-fA-F]{4}$/;\nconst BAD: { readonly refused: string } = { refused: \"git_bad_pkt_line\" };\nconst FLUSH_LENGTH = 4;\n\n/** The text of one pkt-line's payload without its line feed, or `undefined` when it isn't UTF-8. */\nfunction payloadText(bytes: Uint8Array): string | undefined {\n try {\n return DECODER.decode(bytes).replace(/\\n$/, \"\");\n } catch {\n return undefined;\n }\n}\n\n/** Reads one command line; the first carries the capabilities after a NUL, which are dropped. */\nfunction readCommand(text: string, commands: PushCommand[]): string | undefined {\n if (commands.length === 0 && SHALLOW.test(text)) return undefined;\n if (text.startsWith(\"push-cert\")) return \"git_push_cert\";\n const line = commands.length === 0 ? (text.split(\"\\0\")[0] ?? \"\") : text;\n if (commands.length > 0 && text.includes(\"\\0\")) return \"git_bad_pkt_line\";\n const match = COMMAND.exec(line);\n if (match === null || match[1]?.length !== match[2]?.length) return \"git_bad_pkt_line\";\n commands.push({ old: match[1] ?? \"\", new: match[2] ?? \"\", ref: match[3] ?? \"\" });\n return commands.length > GIT_MAX_COMMANDS ? \"git_too_many_commands\" : undefined;\n}\n\n/**\n * One pkt-line at `at` in `bytes`, which starts at body offset `offset`: a flush, a payload's text, how many bytes from\n * `at` it needs before it can be read, or a refusal. A line that would end past `GIT_MAX_COMMAND_BYTES` is refused from\n * its header, so the reader never holds much more than the limit.\n */\nfunction readPacket(\n bytes: Uint8Array,\n at: number,\n offset: number,\n):\n | { readonly needed: number }\n | { readonly refused: string }\n | \"flush\"\n | { readonly text: string; readonly length: number } {\n if (bytes.length - at < 4) return { needed: 4 };\n const header = String.fromCharCode(...bytes.subarray(at, at + 4));\n if (!LENGTH.test(header)) return BAD;\n const length = Number.parseInt(header, 16);\n if (length === 0) return \"flush\";\n if (length < 5 || length > PKT_MAX) return BAD;\n if (offset + at + length > GIT_MAX_COMMAND_BYTES) return { refused: \"git_too_large\" };\n if (bytes.length - at < length) return { needed: length };\n const text = payloadText(bytes.subarray(at + 4, at + length));\n return text === undefined ? BAD : { text, length };\n}\n\n/** The chunks joined into one array, or the one chunk itself. */\nfunction join(chunks: readonly Uint8Array[]): Uint8Array {\n if (chunks.length === 1) return chunks[0] as Uint8Array;\n const joined = new Uint8Array(chunks.reduce((total, chunk) => total + chunk.length, 0));\n let at = 0;\n for (const chunk of chunks) {\n joined.set(chunk, at);\n at += chunk.length;\n }\n return joined;\n}\n\n/** A push check's verdict so far: `incomplete` until the command list reaches its flush, or the route's verdict. */\nexport type PushCheckVerdict = \"incomplete\" | \"allowed\" | { readonly refused: string };\n\n/**\n * Reads the command list at the start of a push body as the body arrives, in pieces of any size, and gives the route's\n * verdict once it can. The work is linear in the bytes received: pieces are joined only once they hold the next\n * pkt-line's header or the whole line, and a line already read is never read again. A list whose lines end past\n * `GIT_MAX_COMMAND_BYTES` is refused as soon as a header says so, however the body is split.\n */\nexport class PushReader {\n readonly #filter: GitRouteFilter;\n #pending: Uint8Array[] = [];\n #pendingBytes = 0;\n /** The body offset of the first pending byte. Every byte before it belongs to a pkt-line already read. */\n #offset = 0;\n /** How many pending bytes the next pkt-line needs before it can be read. */\n #needed = 4;\n readonly #commands: PushCommand[] = [];\n /** Whether the body so far is exactly one flush, git's probe before a large push. */\n #probe = false;\n #verdict: \"allowed\" | { readonly refused: string } | undefined;\n\n constructor(filter: GitRouteFilter) {\n this.#filter = filter;\n }\n\n /** Reads the next piece of the body and returns the verdict so far. Bytes after a verdict are not read. */\n add(chunk: Uint8Array): PushCheckVerdict {\n if (this.#verdict !== undefined) return this.#verdict;\n if (chunk.length === 0) return \"incomplete\";\n // The probe is a body of one flush and nothing else, so any byte after it is refused.\n if (this.#probe) return this.#settle(BAD);\n this.#pending.push(chunk);\n this.#pendingBytes += chunk.length;\n return this.#pendingBytes < this.#needed ? \"incomplete\" : this.#read();\n }\n\n /** Says the body has ended and returns the final verdict: a list still incomplete is refused. */\n end(): \"allowed\" | { readonly refused: string } {\n return this.#verdict ?? this.#settle(this.#probe ? \"allowed\" : BAD);\n }\n\n #read(): PushCheckVerdict {\n const bytes = join(this.#pending);\n let at = 0;\n for (;;) {\n const packet = readPacket(bytes, at, this.#offset);\n if (packet === \"flush\") return this.#flush(bytes, at);\n if (\"refused\" in packet) return this.#settle(packet);\n if (\"needed\" in packet) {\n this.#pending = at < bytes.length ? [bytes.subarray(at)] : [];\n this.#pendingBytes = bytes.length - at;\n this.#offset += at;\n this.#needed = packet.needed;\n return \"incomplete\";\n }\n const refused = readCommand(packet.text, this.#commands);\n if (refused !== undefined) return this.#settle({ refused });\n at += packet.length;\n }\n }\n\n /** The verdict at a flush at `at`: the end of the command list, git's probe, or a flush with no command before it. */\n #flush(bytes: Uint8Array, at: number): PushCheckVerdict {\n if (this.#commands.length > 0) return this.#settle(commandsVerdict(this.#commands, this.#filter));\n if (this.#offset + at !== 0 || bytes.length > FLUSH_LENGTH) return this.#settle(BAD);\n this.#probe = true;\n this.#pending = [];\n this.#pendingBytes = 0;\n return \"incomplete\";\n }\n\n #settle(verdict: \"allowed\" | { readonly refused: string }): \"allowed\" | { readonly refused: string } {\n this.#verdict = verdict;\n this.#pending = [];\n this.#pendingBytes = 0;\n return verdict;\n }\n}\n\n/** Whether `ref` is matched by one of the patterns: exactly, or under a prefix that ends in `/*`. */\nfunction refAllowed(ref: string, patterns: readonly string[]): boolean {\n return patterns.some((pattern) =>\n pattern.endsWith(\"/*\") ? ref.startsWith(pattern.slice(0, -1)) && ref.length > pattern.length - 1 : ref === pattern,\n );\n}\n\n/** Whether every command creates or updates a ref the patterns allow, or why not. */\nfunction commandsVerdict(\n commands: readonly PushCommand[],\n filter: GitRouteFilter,\n): \"allowed\" | { readonly refused: string } {\n for (const command of commands) {\n if (ZERO.test(command.new)) return { refused: \"git_delete_refused\" };\n if (!isValidRefName(command.ref) || !refAllowed(command.ref, filter.pushRefs))\n return { refused: \"git_ref_refused\" };\n }\n return \"allowed\";\n}\n\n/**\n * The route's verdict on the start of a push body: `incomplete` while the command list hasn't reached its flush,\n * `allowed` once every command creates or updates a ref the patterns allow, or the reason it is refused. A body that is\n * exactly one flush packet, the probe git sends before a large push, is `allowed` once it has ended, because it updates\n * no ref; a byte after that flush is refused. `ended` says the body has no more bytes, so a list still incomplete is\n * refused. A list whose lines end past `GIT_MAX_COMMAND_BYTES` is refused, whether or not its flush has arrived.\n */\nexport function pushVerdict(\n bytes: Uint8Array,\n filter: GitRouteFilter,\n ended: boolean,\n): \"incomplete\" | \"allowed\" | { readonly refused: string } {\n const reader = new PushReader(filter);\n const verdict = reader.add(bytes);\n return verdict === \"incomplete\" && ended ? reader.end() : verdict;\n}\n\n/** Whether an `Authorization` header is HTTP Basic whose password is exactly `sentinel`. */\nexport function basicCarries(header: string | undefined, sentinel: string): boolean {\n const match = /^Basic ([A-Za-z0-9+/]+={0,2})$/i.exec(header ?? \"\");\n if (match === null || sentinel === \"\") return false;\n let decoded: string;\n try {\n decoded = atob(match[1] ?? \"\");\n } catch {\n return false;\n }\n const colon = decoded.indexOf(\":\");\n return colon >= 0 && decoded.slice(colon + 1) === sentinel;\n}\n\n/** The `Authorization` value that carries `secret` as the password of `username`. */\nexport function basicHeader(username: string, secret: string): string {\n const bytes = new TextEncoder().encode(`${username}:${secret}`);\n return `Basic ${btoa(String.fromCharCode(...bytes))}`;\n}\n"]}
@@ -2,8 +2,12 @@
2
2
  * `@buildanagent/harness/credentials`: the credential boundary. `startEgressProxy()` is a host-side, default-deny
3
3
  * egress proxy that logs each request, injects a host-scoped credential on a local route when the sentinel matches, and
4
4
  * gates an in-process fetch under the same allowlist. `scrubSecrets()` removes known secrets from an entry before it is
5
- * appended. The proxy is Node-only; the scrubber and the address check are portable.
5
+ * appended. `compileEgressPolicy()` turns an `EgressPolicy`, which names credentials but never holds them, into the
6
+ * proxy's allowlist and routes, and a `git` route limits git over HTTPS to listed repositories and branches. The proxy
7
+ * is Node-only; the policy compiler, the git checks, the scrubber and the address check are portable.
6
8
  */
7
9
  export { isAddressLiteral, isPublicAddress } from "./addresses.js";
10
+ export { type CompiledEgressPolicy, type CompileEgressOptions, compileEgressPolicy, type EgressPolicy, type EgressRoute, type GitEgressRoute, type HeaderEgressRoute, } from "./egress-policy.js";
8
11
  export { type CredentialRoute, type EgressProxy, type EgressProxyOptions, type EgressRecord, startEgressProxy, } from "./egress-proxy.js";
12
+ export { GIT_MAX_COMMAND_BYTES, GIT_MAX_COMMANDS, type GitRouteFilter, isValidRefName, pushVerdict, } from "./git-route.js";
9
13
  export { REDACTED, scrubSecrets } from "./scrub.js";
@@ -2,9 +2,13 @@
2
2
  * `@buildanagent/harness/credentials`: the credential boundary. `startEgressProxy()` is a host-side, default-deny
3
3
  * egress proxy that logs each request, injects a host-scoped credential on a local route when the sentinel matches, and
4
4
  * gates an in-process fetch under the same allowlist. `scrubSecrets()` removes known secrets from an entry before it is
5
- * appended. The proxy is Node-only; the scrubber and the address check are portable.
5
+ * appended. `compileEgressPolicy()` turns an `EgressPolicy`, which names credentials but never holds them, into the
6
+ * proxy's allowlist and routes, and a `git` route limits git over HTTPS to listed repositories and branches. The proxy
7
+ * is Node-only; the policy compiler, the git checks, the scrubber and the address check are portable.
6
8
  */
7
9
  export { isAddressLiteral, isPublicAddress } from "./addresses.js";
10
+ export { compileEgressPolicy, } from "./egress-policy.js";
8
11
  export { startEgressProxy, } from "./egress-proxy.js";
12
+ export { GIT_MAX_COMMAND_BYTES, GIT_MAX_COMMANDS, isValidRefName, pushVerdict, } from "./git-route.js";
9
13
  export { REDACTED, scrubSecrets } from "./scrub.js";
10
14
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/credentials/index.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,OAAO,EAAE,gBAAgB,EAAE,eAAe,EAAE,MAAM,gBAAgB,CAAC;AACnE,OAAO,EAKL,gBAAgB,GACjB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,QAAQ,EAAE,YAAY,EAAE,MAAM,YAAY,CAAC","sourcesContent":["/**\n * `@buildanagent/harness/credentials`: the credential boundary. `startEgressProxy()` is a host-side, default-deny\n * egress proxy that logs each request, injects a host-scoped credential on a local route when the sentinel matches, and\n * gates an in-process fetch under the same allowlist. `scrubSecrets()` removes known secrets from an entry before it is\n * appended. The proxy is Node-only; the scrubber and the address check are portable.\n */\nexport { isAddressLiteral, isPublicAddress } from \"./addresses.js\";\nexport {\n type CredentialRoute,\n type EgressProxy,\n type EgressProxyOptions,\n type EgressRecord,\n startEgressProxy,\n} from \"./egress-proxy.js\";\nexport { REDACTED, scrubSecrets } from \"./scrub.js\";\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/credentials/index.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AACH,OAAO,EAAE,gBAAgB,EAAE,eAAe,EAAE,MAAM,gBAAgB,CAAC;AACnE,OAAO,EAGL,mBAAmB,GAKpB,MAAM,oBAAoB,CAAC;AAC5B,OAAO,EAKL,gBAAgB,GACjB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EACL,qBAAqB,EACrB,gBAAgB,EAEhB,cAAc,EACd,WAAW,GACZ,MAAM,gBAAgB,CAAC;AACxB,OAAO,EAAE,QAAQ,EAAE,YAAY,EAAE,MAAM,YAAY,CAAC","sourcesContent":["/**\n * `@buildanagent/harness/credentials`: the credential boundary. `startEgressProxy()` is a host-side, default-deny\n * egress proxy that logs each request, injects a host-scoped credential on a local route when the sentinel matches, and\n * gates an in-process fetch under the same allowlist. `scrubSecrets()` removes known secrets from an entry before it is\n * appended. `compileEgressPolicy()` turns an `EgressPolicy`, which names credentials but never holds them, into the\n * proxy's allowlist and routes, and a `git` route limits git over HTTPS to listed repositories and branches. The proxy\n * is Node-only; the policy compiler, the git checks, the scrubber and the address check are portable.\n */\nexport { isAddressLiteral, isPublicAddress } from \"./addresses.js\";\nexport {\n type CompiledEgressPolicy,\n type CompileEgressOptions,\n compileEgressPolicy,\n type EgressPolicy,\n type EgressRoute,\n type GitEgressRoute,\n type HeaderEgressRoute,\n} from \"./egress-policy.js\";\nexport {\n type CredentialRoute,\n type EgressProxy,\n type EgressProxyOptions,\n type EgressRecord,\n startEgressProxy,\n} from \"./egress-proxy.js\";\nexport {\n GIT_MAX_COMMAND_BYTES,\n GIT_MAX_COMMANDS,\n type GitRouteFilter,\n isValidRefName,\n pushVerdict,\n} from \"./git-route.js\";\nexport { REDACTED, scrubSecrets } from \"./scrub.js\";\n"]}
@@ -7,6 +7,13 @@
7
7
  import type { SessionEntry } from "@buildanagent/protocol";
8
8
  /** What replaces a secret. */
9
9
  export declare const REDACTED = "[REDACTED]";
10
+ /** `text` with every form of each secret replaced, for a host-side tool that returns text it fetched. */
11
+ export declare function scrubString(text: string, secrets: readonly string[]): string;
12
+ /**
13
+ * `text`, the start of a longer text that was cut, with every form of each secret replaced and any start of one left at
14
+ * its end removed, so a secret that the cut split leaks none of its first characters.
15
+ */
16
+ export declare function scrubCutString(text: string, secrets: readonly string[]): string;
10
17
  /**
11
18
  * Returns a copy of `entry` with every secret replaced by `[REDACTED]`, in every string value and every key, at any depth.
12
19
  * A secret is also removed when it appears percent-encoded, JSON-escaped or in base64. The entry's `type`, `id`,
@@ -59,6 +59,28 @@ function scrubText(text, patterns) {
59
59
  }
60
60
  return result;
61
61
  }
62
+ /** `text` with every form of each secret replaced, for a host-side tool that returns text it fetched. */
63
+ export function scrubString(text, secrets) {
64
+ return scrubText(text, forms(secrets));
65
+ }
66
+ /**
67
+ * `text`, the start of a longer text that was cut, with every form of each secret replaced and any start of one left at
68
+ * its end removed, so a secret that the cut split leaks none of its first characters.
69
+ */
70
+ export function scrubCutString(text, secrets) {
71
+ const patterns = forms(secrets);
72
+ const scrubbed = scrubText(text, patterns);
73
+ let keep = scrubbed.length;
74
+ for (const pattern of patterns) {
75
+ for (let size = Math.min(pattern.length - 1, scrubbed.length); size > 0; size -= 1) {
76
+ if (scrubbed.endsWith(pattern.slice(0, size))) {
77
+ keep = Math.min(keep, scrubbed.length - size);
78
+ break;
79
+ }
80
+ }
81
+ }
82
+ return scrubbed.slice(0, keep);
83
+ }
62
84
  function scrubValue(value, patterns) {
63
85
  if (typeof value === "string")
64
86
  return scrubText(value, patterns);
@@ -1 +1 @@
1
- {"version":3,"file":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MAAM,CAAC,GAAG,EAAE,KAAK,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,KAAK,CAAC,EAAE,CAAC;QACjD,GAAG,CAAC,UAAU,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,SAAS,CAAC,GAAG,EAAE,QAAQ,CAAC,CAAC,GAAG,UAAU,CAAC,GAAG,CAAC,GAAG,CAAC;YAC7E,CAAC,CAAC,KAAK;YACP,CAAC,CAAC,UAAU,CAAC,KAAK,EAAE,QAAQ,CAAC,CAAC;IAClC,CAAC;IACD,OAAO,GAAQ,CAAC;AAClB,CAAC","sourcesContent":["/**\n * `scrubSecrets()`: removes known secrets from a session entry before it is appended, so a credential that reached a\n * tool result, a model message or an error never reaches the log. It is the net under the credential boundary, not the\n * boundary itself: the boundary keeps the secret out of the sandbox, and this catches what a host-side tool wrote\n * anyway. It is pure and portable.\n */\nimport type { SessionEntry } from \"@buildanagent/protocol\";\n\n/** What replaces a secret. */\nexport const REDACTED = \"[REDACTED]\";\n\n// Fields that give an entry its shape and place in the log. A secret is never one of them, and changing one would break\n// the log, so they are left alone at the top of an entry.\nconst STRUCTURAL = new Set([\"type\", \"id\", \"parentId\", \"seq\", \"timestamp\", \"origin\", \"formatVersion\"]);\n\n/** The standard and URL-safe base64 of `bytes`, without padding. */\nfunction base64Of(bytes: Uint8Array): string[] {\n let binary = \"\";\n for (const byte of bytes) binary += String.fromCharCode(byte);\n const standard = btoa(binary).replace(/=+$/, \"\");\n return [standard, standard.replaceAll(\"+\", \"-\").replaceAll(\"/\", \"_\")];\n}\n\n// The fewest base64 characters worth looking for, so a short secret's pieces don't redact ordinary text.\nconst MIN_BASE64_PIECE = 8;\n\n/**\n * The base64 forms of a secret: alone, and as part of longer text. Base64 packs three bytes into four characters, so a\n * secret that follows a prefix such as `user:` encodes differently by its offset in the group. The encodings at all three\n * offsets are kept, trimmed to the groups the secret fills, because the groups at its edges depend on its neighbours.\n */\nfunction base64Forms(text: string): string[] {\n const secret = new TextEncoder().encode(text);\n const found = new Set(base64Of(secret));\n for (let offset = 0; offset < 3; offset += 1) {\n const shifted = new Uint8Array(offset + secret.length);\n shifted.set(secret, offset);\n const groups = Math.floor(shifted.length / 3);\n for (const form of base64Of(shifted)) {\n const piece = form.slice(offset === 0 ? 0 : 4, groups * 4);\n if (piece.length >= MIN_BASE64_PIECE) found.add(piece);\n }\n }\n return [...found];\n}\n\n/**\n * The forms a secret takes when something copies it: as written, percent-encoded, escaped inside JSON, and base64 (which\n * is how a Basic authorization header carries one). Longest first, so a secret that contains another is removed whole.\n */\nfunction forms(secrets: readonly string[]): string[] {\n const found = new Set<string>();\n for (const secret of secrets) {\n if (secret === \"\") continue;\n found.add(secret);\n found.add(encodeURIComponent(secret));\n found.add(JSON.stringify(secret).slice(1, -1));\n for (const form of base64Forms(secret)) found.add(form);\n }\n found.delete(\"\");\n return [...found].sort((a, b) => b.length - a.length);\n}\n\nfunction scrubText(text: string, patterns: readonly string[]): string {\n let result = text;\n for (const pattern of patterns) {\n if (result.includes(pattern)) result = result.replaceAll(pattern, REDACTED);\n }\n return result;\n}\n\nfunction scrubValue(value: unknown, patterns: readonly string[]): unknown {\n if (typeof value === \"string\") return scrubText(value, patterns);\n if (Array.isArray(value)) return value.map((item) => scrubValue(item, patterns));\n if (value !== null && typeof value === \"object\") {\n const out: Record<string, unknown> = {};\n for (const [key, inner] of Object.entries(value)) out[scrubText(key, patterns)] = scrubValue(inner, patterns);\n return out;\n }\n return value;\n}\n\n/**\n * Returns a copy of `entry` with every secret replaced by `[REDACTED]`, in every string value and every key, at any depth.\n * A secret is also removed when it appears percent-encoded, JSON-escaped or in base64. The entry's `type`, `id`,\n * `parentId`, `seq`, `timestamp`, `origin` and `formatVersion` are kept as they are. An empty secret is ignored, and a short one redacts\n * every place it occurs, so pass real credentials. The input is not changed.\n */\nexport function scrubSecrets<T extends SessionEntry>(entry: T, secrets: readonly string[]): T {\n const patterns = forms(secrets);\n if (patterns.length === 0) return { ...entry };\n const out: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(entry)) {\n out[STRUCTURAL.has(key) ? key : scrubText(key, patterns)] = STRUCTURAL.has(key)\n ? value\n : scrubValue(value, patterns);\n }\n return out as T;\n}\n"]}
1
+ {"version":3,"file":"scrub.js","sourceRoot":"","sources":["../../src/credentials/scrub.ts"],"names":[],"mappings":"AAQA,8BAA8B;AAC9B,MAAM,CAAC,MAAM,QAAQ,GAAG,YAAY,CAAC;AAErC,wHAAwH;AACxH,0DAA0D;AAC1D,MAAM,UAAU,GAAG,IAAI,GAAG,CAAC,CAAC,MAAM,EAAE,IAAI,EAAE,UAAU,EAAE,KAAK,EAAE,WAAW,EAAE,QAAQ,EAAE,eAAe,CAAC,CAAC,CAAC;AAEtG,oEAAoE;AACpE,SAAS,QAAQ,CAAC,KAAiB;IACjC,IAAI,MAAM,GAAG,EAAE,CAAC;IAChB,KAAK,MAAM,IAAI,IAAI,KAAK;QAAE,MAAM,IAAI,MAAM,CAAC,YAAY,CAAC,IAAI,CAAC,CAAC;IAC9D,MAAM,QAAQ,GAAG,IAAI,CAAC,MAAM,CAAC,CAAC,OAAO,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC;IACjD,OAAO,CAAC,QAAQ,EAAE,QAAQ,CAAC,UAAU,CAAC,GAAG,EAAE,GAAG,CAAC,CAAC,UAAU,CAAC,GAAG,EAAE,GAAG,CAAC,CAAC,CAAC;AACxE,CAAC;AAED,yGAAyG;AACzG,MAAM,gBAAgB,GAAG,CAAC,CAAC;AAE3B;;;;GAIG;AACH,SAAS,WAAW,CAAC,IAAY;IAC/B,MAAM,MAAM,GAAG,IAAI,WAAW,EAAE,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC;IAC9C,MAAM,KAAK,GAAG,IAAI,GAAG,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC,CAAC;IACxC,KAAK,IAAI,MAAM,GAAG,CAAC,EAAE,MAAM,GAAG,CAAC,EAA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AC,UAAU,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,SAAS,CAAC,GAAG,EAAE,QAAQ,CAAC,CAAC,GAAG,UAAU,CAAC,GAAG,CAAC,GAAG,CAAC;YAC7E,CAAC,CAAC,KAAK;YACP,CAAC,CAAC,UAAU,CAAC,KAAK,EAAE,QAAQ,CAAC,CAAC;IAClC,CAAC;IACD,OAAO,GAAQ,CAAC;AAClB,CAAC","sourcesContent":["/**\n * `scrubSecrets()`: removes known secrets from a session entry before it is appended, so a credential that reached a\n * tool result, a model message or an error never reaches the log. It is the net under the credential boundary, not the\n * boundary itself: the boundary keeps the secret out of the sandbox, and this catches what a host-side tool wrote\n * anyway. It is pure and portable.\n */\nimport type { SessionEntry } from \"@buildanagent/protocol\";\n\n/** What replaces a secret. */\nexport const REDACTED = \"[REDACTED]\";\n\n// Fields that give an entry its shape and place in the log. A secret is never one of them, and changing one would break\n// the log, so they are left alone at the top of an entry.\nconst STRUCTURAL = new Set([\"type\", \"id\", \"parentId\", \"seq\", \"timestamp\", \"origin\", \"formatVersion\"]);\n\n/** The standard and URL-safe base64 of `bytes`, without padding. */\nfunction base64Of(bytes: Uint8Array): string[] {\n let binary = \"\";\n for (const byte of bytes) binary += String.fromCharCode(byte);\n const standard = btoa(binary).replace(/=+$/, \"\");\n return [standard, standard.replaceAll(\"+\", \"-\").replaceAll(\"/\", \"_\")];\n}\n\n// The fewest base64 characters worth looking for, so a short secret's pieces don't redact ordinary text.\nconst MIN_BASE64_PIECE = 8;\n\n/**\n * The base64 forms of a secret: alone, and as part of longer text. Base64 packs three bytes into four characters, so a\n * secret that follows a prefix such as `user:` encodes differently by its offset in the group. The encodings at all three\n * offsets are kept, trimmed to the groups the secret fills, because the groups at its edges depend on its neighbours.\n */\nfunction base64Forms(text: string): string[] {\n const secret = new TextEncoder().encode(text);\n const found = new Set(base64Of(secret));\n for (let offset = 0; offset < 3; offset += 1) {\n const shifted = new Uint8Array(offset + secret.length);\n shifted.set(secret, offset);\n const groups = Math.floor(shifted.length / 3);\n for (const form of base64Of(shifted)) {\n const piece = form.slice(offset === 0 ? 0 : 4, groups * 4);\n if (piece.length >= MIN_BASE64_PIECE) found.add(piece);\n }\n }\n return [...found];\n}\n\n/**\n * The forms a secret takes when something copies it: as written, percent-encoded, escaped inside JSON, and base64 (which\n * is how a Basic authorization header carries one). Longest first, so a secret that contains another is removed whole.\n */\nfunction forms(secrets: readonly string[]): string[] {\n const found = new Set<string>();\n for (const secret of secrets) {\n if (secret === \"\") continue;\n found.add(secret);\n found.add(encodeURIComponent(secret));\n found.add(JSON.stringify(secret).slice(1, -1));\n for (const form of base64Forms(secret)) found.add(form);\n }\n found.delete(\"\");\n return [...found].sort((a, b) => b.length - a.length);\n}\n\nfunction scrubText(text: string, patterns: readonly string[]): string {\n let result = text;\n for (const pattern of patterns) {\n if (result.includes(pattern)) result = result.replaceAll(pattern, REDACTED);\n }\n return result;\n}\n\n/** `text` with every form of each secret replaced, for a host-side tool that returns text it fetched. */\nexport function scrubString(text: string, secrets: readonly string[]): string {\n return scrubText(text, forms(secrets));\n}\n\n/**\n * `text`, the start of a longer text that was cut, with every form of each secret replaced and any start of one left at\n * its end removed, so a secret that the cut split leaks none of its first characters.\n */\nexport function scrubCutString(text: string, secrets: readonly string[]): string {\n const patterns = forms(secrets);\n const scrubbed = scrubText(text, patterns);\n let keep = scrubbed.length;\n for (const pattern of patterns) {\n for (let size = Math.min(pattern.length - 1, scrubbed.length); size > 0; size -= 1) {\n if (scrubbed.endsWith(pattern.slice(0, size))) {\n keep = Math.min(keep, scrubbed.length - size);\n break;\n }\n }\n }\n return scrubbed.slice(0, keep);\n}\n\nfunction scrubValue(value: unknown, patterns: readonly string[]): unknown {\n if (typeof value === \"string\") return scrubText(value, patterns);\n if (Array.isArray(value)) return value.map((item) => scrubValue(item, patterns));\n if (value !== null && typeof value === \"object\") {\n const out: Record<string, unknown> = {};\n for (const [key, inner] of Object.entries(value)) out[scrubText(key, patterns)] = scrubValue(inner, patterns);\n return out;\n }\n return value;\n}\n\n/**\n * Returns a copy of `entry` with every secret replaced by `[REDACTED]`, in every string value and every key, at any depth.\n * A secret is also removed when it appears percent-encoded, JSON-escaped or in base64. The entry's `type`, `id`,\n * `parentId`, `seq`, `timestamp`, `origin` and `formatVersion` are kept as they are. An empty secret is ignored, and a short one redacts\n * every place it occurs, so pass real credentials. The input is not changed.\n */\nexport function scrubSecrets<T extends SessionEntry>(entry: T, secrets: readonly string[]): T {\n const patterns = forms(secrets);\n if (patterns.length === 0) return { ...entry };\n const out: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(entry)) {\n out[STRUCTURAL.has(key) ? key : scrubText(key, patterns)] = STRUCTURAL.has(key)\n ? value\n : scrubValue(value, patterns);\n }\n return out as T;\n}\n"]}
package/dist/errors.d.ts CHANGED
@@ -1,20 +1,24 @@
1
1
  /**
2
- * `HarnessError`: the harness's error for programmer errors and for a sandbox that can't do what it was asked. Two
3
- * subclasses keep their own names for the cases callers catch by class: `SandboxUnavailableError` and
4
- * `SandboxDeniedError`, both in `./sandbox`.
2
+ * `HarnessError`: the harness's error for programmer errors and for a sandbox that can't do what it was asked. Four
3
+ * subclasses keep their own names for the cases callers catch by class: `SandboxUnavailableError`,
4
+ * `SandboxDeniedError`, `SandboxPolicyMismatchError` and `SandboxUnsupportedError`, all in `./sandbox`.
5
5
  */
6
6
  /** Why a `HarnessError` was thrown. */
7
- export type HarnessErrorCode = "sandbox_unavailable" | "sandbox_denied" | "sandbox_disposed" | "sandbox_not_found" | "sandbox_io_failed" | "egress_denied" | "invalid_egress_options" | "unsafe_sandbox_not_acknowledged" | "invalid_sandbox_options" | "invalid_spawn_env" | "duplicate_tool" | "invalid_tool_registration" | "invalid_permission_config" | "invalid_lock_options" | "session_locked" | "session_read_only" | "entry_not_found" | "unsupported_format" | "invalid_turn_options" | "invalid_context_options" | "invalid_dispatcher_options" | "invalid_transport_options" | "spill_unavailable" | "invalid_extension" | "extension_hash_mismatch" | "approval_not_pending" | "approval_unavailable" | "sticky_refused" | "approval_reuse_refused" | "approver_is_requester" | "approval_refused" | "invalid_code_call" | "invalid_key_store" | "key_store_read_only" | "session_conflict" | "entry_too_large" | "invalid_session_entry" | "invalid_session_key" | "invalid_retention" | "session_corrupt" | "invalid_completion_config" | "invalid_mcp_config" | "mcp_connect_failed" | "mcp_tool_list_refused" | "mcp_call_failed";
7
+ export type HarnessErrorCode = "sandbox_unavailable" | "sandbox_denied" | "sandbox_disposed" | "sandbox_not_found" | "sandbox_io_failed" | "sandbox_policy_mismatch" | "sandbox_unsupported" | "egress_denied" | "invalid_egress_options" | "unsafe_sandbox_not_acknowledged" | "invalid_sandbox_options" | "invalid_spawn_env" | "duplicate_tool" | "invalid_tool_registration" | "invalid_tool_options" | "invalid_permission_config" | "invalid_lock_options" | "session_locked" | "session_read_only" | "entry_not_found" | "unsupported_format" | "invalid_turn_options" | "invalid_context_options" | "invalid_dispatcher_options" | "invalid_transport_options" | "spill_unavailable" | "invalid_extension" | "extension_hash_mismatch" | "approval_not_pending" | "approval_unavailable" | "sticky_refused" | "approval_reuse_refused" | "approver_is_requester" | "approval_refused" | "invalid_code_call" | "invalid_escalation" | "invalid_key_store" | "key_store_read_only" | "session_conflict" | "entry_too_large" | "invalid_session_entry" | "invalid_session_key" | "invalid_retention" | "session_corrupt" | "invalid_completion_config" | "invalid_mcp_config" | "mcp_connect_failed" | "mcp_tool_list_refused" | "mcp_call_failed";
8
8
  /**
9
9
  * Thrown for a mistake in how the harness is called, and for a sandbox that is unavailable or refuses a file operation.
10
10
  * `sandbox_unavailable`: a backend can't start (`SandboxUnavailableError`). `sandbox_denied`: the policy refused a file
11
11
  * read or write (`SandboxDeniedError`). `sandbox_disposed`: the sandbox was disposed before the call.
12
12
  * `sandbox_not_found`: a file to read doesn't exist. `sandbox_io_failed`: a file call failed for a reason that is
13
- * neither a missing file nor a denial. `unsafe_sandbox_not_acknowledged`: `noneSandbox()` was called without `unsafe:
13
+ * neither a missing file nor a denial. `sandbox_policy_mismatch`: the policy a backend read back after it provisioned or
14
+ * resumed a sandbox differs from the one requested (`SandboxPolicyMismatchError`). `sandbox_unsupported`: a sandbox was
15
+ * asked to resume, snapshot or pause on a backend that lacks the capability (`SandboxUnsupportedError`).
16
+ * `unsafe_sandbox_not_acknowledged`: `noneSandbox()` was called without `unsafe:
14
17
  * true`. `invalid_sandbox_options`: a sandbox option, manifest or command is unusable. `invalid_spawn_env`:
15
18
  * `spawnEnv()` was given a name or value that can't be part of a clean environment. `duplicate_tool`: a tool registry
16
19
  * already holds a tool or alias by that name (`DuplicateToolError`). `invalid_tool_registration`: a tool registration
17
20
  * or a registry option is unusable, such as a name that breaks the canonical rule or an unknown source.
21
+ * `invalid_tool_options`: the built-in tools were given a workspace root or a policy root that is not an absolute path.
18
22
  * `invalid_permission_config`: an allow rule makes the host callback unreachable (`PermissionConfigError`).
19
23
  * `invalid_lock_options`: a file lock was given a lease, renewal interval or host name it can't use. `session_locked`:
20
24
  * another writer holds the session. `session_read_only`: a session opened without a lock was asked to write.
@@ -30,9 +34,12 @@ export type HarnessErrorCode = "sandbox_unavailable" | "sandbox_denied" | "sandb
30
34
  * `approval_unavailable`: the harness has no signer, so no approval can be checked. `sticky_refused`: a sticky
31
35
  * allowance would cover an interpreter prefix or a secret. `approval_reuse_refused`: the tool's `approvalReuse` forbids
32
36
  * a sticky or grouped answer. `approver_is_requester`: the approver is the one who asked. `approval_refused`: a code
33
- * call's signed request failed its check when it was resolved, so nothing ran and nothing was written.
37
+ * call's or a sandbox escalation's signed request failed its check when it was resolved, or a classifier tried to
38
+ * approve an escalation, so nothing ran and nothing was written.
34
39
  * `invalid_code_call`: `Harness.invokeTool()` or a code call's resolution was given something it can't run, such as a
35
- * tool the registry lacks or a compensation that names no call that ran. `invalid_key_store`: a key
40
+ * tool the registry lacks or a compensation that names no call that ran. `invalid_escalation`: `escalation()` or one
41
+ * of its calls was given something it can't use, such as a granular policy with no rules, or an edge the escalation
42
+ * table does not list. `invalid_key_store`: a key
36
43
  * file or key secret is unreadable or malformed, or a key file is readable by others. `key_store_read_only`: a key store
37
44
  * with no `rotate()` or `prune()` was asked to rotate or prune. `session_conflict`: an append found the log in a state it did
38
45
  * not expect (`ConflictError`). `entry_too_large`: an entry is over the store's size bound (`EntryTooLargeError`).
package/dist/errors.js CHANGED
@@ -1,7 +1,7 @@
1
1
  /**
2
- * `HarnessError`: the harness's error for programmer errors and for a sandbox that can't do what it was asked. Two
3
- * subclasses keep their own names for the cases callers catch by class: `SandboxUnavailableError` and
4
- * `SandboxDeniedError`, both in `./sandbox`.
2
+ * `HarnessError`: the harness's error for programmer errors and for a sandbox that can't do what it was asked. Four
3
+ * subclasses keep their own names for the cases callers catch by class: `SandboxUnavailableError`,
4
+ * `SandboxDeniedError`, `SandboxPolicyMismatchError` and `SandboxUnsupportedError`, all in `./sandbox`.
5
5
  */
6
6
  // A registered symbol, so the guard still works when two copies of the package are bundled.
7
7
  const HARNESS_ERROR = Symbol.for("buildanagent.harness.HarnessError");
@@ -10,11 +10,15 @@ const HARNESS_ERROR = Symbol.for("buildanagent.harness.HarnessError");
10
10
  * `sandbox_unavailable`: a backend can't start (`SandboxUnavailableError`). `sandbox_denied`: the policy refused a file
11
11
  * read or write (`SandboxDeniedError`). `sandbox_disposed`: the sandbox was disposed before the call.
12
12
  * `sandbox_not_found`: a file to read doesn't exist. `sandbox_io_failed`: a file call failed for a reason that is
13
- * neither a missing file nor a denial. `unsafe_sandbox_not_acknowledged`: `noneSandbox()` was called without `unsafe:
13
+ * neither a missing file nor a denial. `sandbox_policy_mismatch`: the policy a backend read back after it provisioned or
14
+ * resumed a sandbox differs from the one requested (`SandboxPolicyMismatchError`). `sandbox_unsupported`: a sandbox was
15
+ * asked to resume, snapshot or pause on a backend that lacks the capability (`SandboxUnsupportedError`).
16
+ * `unsafe_sandbox_not_acknowledged`: `noneSandbox()` was called without `unsafe:
14
17
  * true`. `invalid_sandbox_options`: a sandbox option, manifest or command is unusable. `invalid_spawn_env`:
15
18
  * `spawnEnv()` was given a name or value that can't be part of a clean environment. `duplicate_tool`: a tool registry
16
19
  * already holds a tool or alias by that name (`DuplicateToolError`). `invalid_tool_registration`: a tool registration
17
20
  * or a registry option is unusable, such as a name that breaks the canonical rule or an unknown source.
21
+ * `invalid_tool_options`: the built-in tools were given a workspace root or a policy root that is not an absolute path.
18
22
  * `invalid_permission_config`: an allow rule makes the host callback unreachable (`PermissionConfigError`).
19
23
  * `invalid_lock_options`: a file lock was given a lease, renewal interval or host name it can't use. `session_locked`:
20
24
  * another writer holds the session. `session_read_only`: a session opened without a lock was asked to write.
@@ -30,9 +34,12 @@ const HARNESS_ERROR = Symbol.for("buildanagent.harness.HarnessError");
30
34
  * `approval_unavailable`: the harness has no signer, so no approval can be checked. `sticky_refused`: a sticky
31
35
  * allowance would cover an interpreter prefix or a secret. `approval_reuse_refused`: the tool's `approvalReuse` forbids
32
36
  * a sticky or grouped answer. `approver_is_requester`: the approver is the one who asked. `approval_refused`: a code
33
- * call's signed request failed its check when it was resolved, so nothing ran and nothing was written.
37
+ * call's or a sandbox escalation's signed request failed its check when it was resolved, or a classifier tried to
38
+ * approve an escalation, so nothing ran and nothing was written.
34
39
  * `invalid_code_call`: `Harness.invokeTool()` or a code call's resolution was given something it can't run, such as a
35
- * tool the registry lacks or a compensation that names no call that ran. `invalid_key_store`: a key
40
+ * tool the registry lacks or a compensation that names no call that ran. `invalid_escalation`: `escalation()` or one
41
+ * of its calls was given something it can't use, such as a granular policy with no rules, or an edge the escalation
42
+ * table does not list. `invalid_key_store`: a key
36
43
  * file or key secret is unreadable or malformed, or a key file is readable by others. `key_store_read_only`: a key store
37
44
  * with no `rotate()` or `prune()` was asked to rotate or prune. `session_conflict`: an append found the log in a state it did
38
45
  * not expect (`ConflictError`). `entry_too_large`: an entry is over the store's size bound (`EntryTooLargeError`).