@buildanagent/harness 0.1.0-alpha.29 → 0.1.0-alpha.31

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 (84) hide show
  1. package/README.md +110 -3
  2. package/dist/credentials/addresses.d.ts +20 -0
  3. package/dist/credentials/addresses.js +93 -2
  4. package/dist/credentials/addresses.js.map +1 -1
  5. package/dist/credentials/egress-proxy.js +34 -4
  6. package/dist/credentials/egress-proxy.js.map +1 -1
  7. package/dist/errors.d.ts +6 -3
  8. package/dist/errors.js +5 -2
  9. package/dist/errors.js.map +1 -1
  10. package/dist/extensions/load.js +5 -2
  11. package/dist/extensions/load.js.map +1 -1
  12. package/dist/extensions/lock.d.ts +16 -2
  13. package/dist/extensions/lock.js +155 -21
  14. package/dist/extensions/lock.js.map +1 -1
  15. package/dist/extensions/mcp-pins-node.d.ts +16 -0
  16. package/dist/extensions/mcp-pins-node.js +18 -0
  17. package/dist/extensions/mcp-pins-node.js.map +1 -0
  18. package/dist/extensions/node.d.ts +4 -2
  19. package/dist/extensions/node.js +4 -2
  20. package/dist/extensions/node.js.map +1 -1
  21. package/dist/harness.d.ts +7 -1
  22. package/dist/harness.js.map +1 -1
  23. package/dist/mcp/connection.d.ts +9 -3
  24. package/dist/mcp/connection.js +192 -25
  25. package/dist/mcp/connection.js.map +1 -1
  26. package/dist/mcp/errors.d.ts +5 -2
  27. package/dist/mcp/errors.js.map +1 -1
  28. package/dist/mcp/guarded-fetch.d.ts +33 -0
  29. package/dist/mcp/guarded-fetch.js +391 -0
  30. package/dist/mcp/guarded-fetch.js.map +1 -0
  31. package/dist/mcp/http-node.d.ts +15 -0
  32. package/dist/mcp/http-node.js +179 -0
  33. package/dist/mcp/http-node.js.map +1 -0
  34. package/dist/mcp/index.d.ts +6 -3
  35. package/dist/mcp/index.js +5 -2
  36. package/dist/mcp/index.js.map +1 -1
  37. package/dist/mcp/manager.d.ts +4 -3
  38. package/dist/mcp/manager.js +432 -47
  39. package/dist/mcp/manager.js.map +1 -1
  40. package/dist/mcp/pins.d.ts +9 -0
  41. package/dist/mcp/pins.js +54 -0
  42. package/dist/mcp/pins.js.map +1 -0
  43. package/dist/mcp/record.js +6 -0
  44. package/dist/mcp/record.js.map +1 -1
  45. package/dist/mcp/remote-config.d.ts +20 -0
  46. package/dist/mcp/remote-config.js +208 -0
  47. package/dist/mcp/remote-config.js.map +1 -0
  48. package/dist/mcp/remote.d.ts +20 -0
  49. package/dist/mcp/remote.js +146 -0
  50. package/dist/mcp/remote.js.map +1 -0
  51. package/dist/mcp/types.d.ts +198 -8
  52. package/dist/mcp/types.js.map +1 -1
  53. package/dist/sandbox/escalation-table.d.ts +38 -0
  54. package/dist/sandbox/escalation-table.js +95 -0
  55. package/dist/sandbox/escalation-table.js.map +1 -0
  56. package/dist/sandbox/escalation.d.ts +191 -0
  57. package/dist/sandbox/escalation.js +370 -0
  58. package/dist/sandbox/escalation.js.map +1 -0
  59. package/dist/sandbox/index.d.ts +6 -3
  60. package/dist/sandbox/index.js +6 -3
  61. package/dist/sandbox/index.js.map +1 -1
  62. package/dist/sandbox/widen.d.ts +10 -0
  63. package/dist/sandbox/widen.js +150 -0
  64. package/dist/sandbox/widen.js.map +1 -0
  65. package/dist/server/protocol.schema.json +6 -3
  66. package/dist/session/approvals.d.ts +30 -1
  67. package/dist/session/approvals.js +12 -4
  68. package/dist/session/approvals.js.map +1 -1
  69. package/dist/session/code-call.d.ts +15 -1
  70. package/dist/session/code-call.js +2 -1
  71. package/dist/session/code-call.js.map +1 -1
  72. package/dist/session/escalation-log.d.ts +65 -0
  73. package/dist/session/escalation-log.js +84 -0
  74. package/dist/session/escalation-log.js.map +1 -0
  75. package/dist/session/rebuild.js +12 -3
  76. package/dist/session/rebuild.js.map +1 -1
  77. package/dist/session/runner.js +39 -6
  78. package/dist/session/runner.js.map +1 -1
  79. package/dist/tools/index.d.ts +1 -1
  80. package/dist/tools/index.js.map +1 -1
  81. package/dist/tools/types.d.ts +16 -0
  82. package/dist/tools/types.js.map +1 -1
  83. package/llms.txt +36 -2
  84. package/package.json +7 -6
@@ -1 +1 @@
1
- {"version":3,"file":"egress-proxy.js","sourceRoot":"","sources":["../../src/credentials/egress-proxy.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AACH,OAAO,EAAE,YAAY,EAAE,MAAM,cAAc,CAAC;AAC5C,OAAO,EAAE,gBAAgB,EAAE,eAAe,EAAE,MAAM,gBAAgB,CAAC;AACnE,OAAO,EAGL,SAAS,EAET,UAAU,EACV,WAAW,GACZ,MAAM,gBAAgB,CAAC;AACxB,OAAO,EAAE,YAAY,EAAE,WAAW,EAAuB,WAAW,EAAE,UAAU,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAC;AA0FtH,SAAS,WAAW;IAClB,IAAI,OAAO,OAAO,KAAK,WAAW,IAAI,OAAO,OAAO,CAAC,gBAAgB,KAAK,UAAU,EAAE,CAAC;QACrF,MAAM,IAAI,YAAY,CACpB,wBAAwB,EACxB,yEAAyE,CAC1E,CAAC;IACJ,CAAC;IACD,OAAO;QACL,IAAI,EAAE,OAAO,CAAC,gBAAgB,CAAC,WAAW,CAAC;QAC3C,KAAK,EAAE,OAAO,CAAC,gBAAgB,CAAC,YAAY,CAAC;QAC7C,GAAG,EAAE,OAAO,CAAC,gBAAgB,CAAC,UAAU,CAAC;QACzC,GAAG,EAAE,OAAO,CAAC,gBAAgB,CAAC,UAAU,CAAC;QACzC,MAAM,EAAE,OAAO,CAAC,gBAAgB,CAAC,aAAa,CAAC;QAC/C,MAAM,EAAE,OAAO,CAAC,gBAAgB,CAAC,aAAa,CAAC;KAChD,CAAC;AACJ,CAAC;AAED,8EAA8E;AAC9E,MAAM,UAAU,GAAG,IAAI,GAAG,CAAC;IACzB,YAAY;IACZ,YAAY;IACZ,oBAAoB;IACpB,qBAAqB;IACrB,kBAAkB;IAClB,IAAI;IACJ,SAAS;IACT,mBAAmB;IACnB,SAAS;IACT,MAAM;CACP,CAAC,CA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AC,KAAK,EAAE,IAAI,CAAC;QAChD,YAAY,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC,YAAY,EAAE;QACxC,KAAK,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC,KAAK,CAAC,MAAM,CAAC;KACjC,CAAC;AACJ,CAAC","sourcesContent":["/**\n * `startEgressProxy()`: the host-side proxy that keeps credentials out of the sandbox. Nothing leaves the sandbox except\n * through it, it refuses everything that isn't on its allowlist, and it logs each request without its headers. A tool\n * that needs a credential sends its request to a local route, such as `http://127.0.0.1:<port>/github/user`, with the\n * route's sentinel where the credential goes. The proxy checks the sentinel and the method, swaps in the real secret and\n * forwards the request over HTTPS. It never intercepts TLS: everything else leaves through `CONNECT` to an\n * allowlisted name, and a name is connected to only at an address the proxy checked. It is Node-only.\n */\nimport { HarnessError } from \"../errors.js\";\nimport { isAddressLiteral, isPublicAddress } from \"./addresses.js\";\nimport {\n type AllowEntry,\n type CredentialRoute,\n isAllowed,\n type ParsedRoute,\n parseAllow,\n parseRoutes,\n} from \"./allowlist.js\";\nimport { basicCarries, basicHeader, type GitRouteFilter, gitEndpoint, PushReader, pushVerdict } from \"./git-route.js\";\n\nexport type { CredentialRoute } from \"./allowlist.js\";\n\n/** One line of the egress log. It names the host and the outcome, and never holds a header, a body or a secret. */\nexport interface EgressRecord {\n /** When the request ended, as an ISO 8601 string. */\n readonly time: string;\n /** `connect` for a tunnel, `route` for a credential route and `fetch` for an in-process call. */\n readonly kind: \"connect\" | \"route\" | \"fetch\";\n /** The host the request was for. */\n readonly host: string;\n readonly port: number;\n readonly method: string;\n /** The status the sandbox saw: 200 for an established tunnel, 403 for a refusal, 502 for a failed connection. */\n readonly status: number;\n /** The bytes that went both ways, 0 for a refusal. */\n readonly bytes: number;\n /** The route's name, for a route request. */\n readonly route?: string | undefined;\n /** Why a request was refused or failed, as a short code such as `not_allowed` or `address_refused`. */\n readonly reason?: string;\n}\n\n/** The options of `startEgressProxy()`. */\nexport interface EgressProxyOptions {\n /** The names a tunnel or an in-process fetch may reach: `example.com`, `*.example.com`, or either with `:port`. */\n readonly allow: readonly string[];\n /** The credential routes. Without any, the proxy only tunnels. */\n readonly routes?: readonly CredentialRoute[];\n /** Receives one record for each request. A throw from it is ignored. */\n readonly log: (record: EgressRecord) => void;\n /** Listens on this Unix socket instead of a port on `127.0.0.1`, so a container can mount it (`dockerSandbox`'s `proxySocket`). */\n readonly socketPath?: string;\n /** Extra certificate authorities to trust for the routes' hosts and for the fetch, such as a test's own. */\n readonly ca?: string | Uint8Array | readonly (string | Uint8Array)[];\n /** Resolves a name to its addresses. Defaults to the system resolver. Every address it returns is checked. */\n readonly resolve?: (host: string) => Promise<readonly string[]>;\n /**\n * Addresses that skip the public-address check. This exists so a test can reach a server on `127.0.0.1`. Never set it\n * for a real run: the check is what keeps a name that points at the host's own network from being reached.\n */\n readonly unsafeAllowAddresses?: readonly string[];\n /**\n * Ends a tunnel, a forwarded request or a push check that is idle this long. A whole number of milliseconds from 0 to\n * 2,147,483,647, where 0 turns the idle timeout off, as it does for a socket; anything else throws\n * `invalid_egress_options` when the proxy starts. Defaults to 120000.\n */\n readonly idleTimeoutMs?: number;\n /**\n * The longest a push's command list may take to arrive, from the start of its body, however often bytes come. The\n * clock starts once and is never reset, so a client that sends a byte just inside the idle timeout is still cut off;\n * a push that takes longer is refused with `git_timeout`. Only the command list is timed, not the pack after it. A\n * whole number of milliseconds from 1 to 2,147,483,647; anything else throws `invalid_egress_options` when the proxy\n * starts. Defaults to 60000.\n */\n readonly pushCheckTimeoutMs?: number;\n}\n\n/** A running egress proxy. */\nexport interface EgressProxy {\n /**\n * Where the sandbox sends its requests: give it as `HTTPS_PROXY`, and join a route's name to it for a route. On a Unix\n * socket it is `unix:<path>`, which is not a proxy URL: the program that uses the socket connects to it itself.\n */\n readonly url: string;\n /** The Unix socket the proxy listens on, when it was started with `socketPath`. */\n readonly socketPath?: string;\n /** For each route, the placeholder the sandbox puts where the credential goes. The real secret never leaves the host. */\n readonly sentinels: Readonly<Record<string, string>>;\n /**\n * Fetches `input` for an in-process tool, under the same allowlist. A host that isn't on it rejects with `egress_denied`.\n * A route is reached at `${proxy.url}/<route>/…`, or at `http://egress.proxy/<route>/…`, which also works on a Unix socket.\n */\n fetch(input: string | URL, init?: RequestInit): Promise<Response>;\n /** The routes' secrets now, for `scrubSecrets()`. */\n knownSecrets(): Promise<readonly string[]>;\n /** Stops listening and ends every open tunnel and request. */\n close(): Promise<void>;\n}\n\ntype Modules = {\n readonly http: typeof import(\"node:http\");\n readonly https: typeof import(\"node:https\");\n readonly net: typeof import(\"node:net\");\n readonly dns: typeof import(\"node:dns\");\n readonly crypto: typeof import(\"node:crypto\");\n readonly stream: typeof import(\"node:stream\");\n};\n\nfunction nodeModules(): Modules {\n if (typeof process === \"undefined\" || typeof process.getBuiltinModule !== \"function\") {\n throw new HarnessError(\n \"invalid_egress_options\",\n \"the egress proxy needs Node's network modules, which this runtime lacks\",\n );\n }\n return {\n http: process.getBuiltinModule(\"node:http\"),\n https: process.getBuiltinModule(\"node:https\"),\n net: process.getBuiltinModule(\"node:net\"),\n dns: process.getBuiltinModule(\"node:dns\"),\n crypto: process.getBuiltinModule(\"node:crypto\"),\n stream: process.getBuiltinModule(\"node:stream\"),\n };\n}\n\n// Headers that belong to one connection, and are never passed on to the next.\nconst HOP_BY_HOP = new Set([\n \"connection\",\n \"keep-alive\",\n \"proxy-authenticate\",\n \"proxy-authorization\",\n \"proxy-connection\",\n \"te\",\n \"trailer\",\n \"transfer-encoding\",\n \"upgrade\",\n \"host\",\n]);\nconst DEFAULT_IDLE_MS = 120_000;\nconst DEFAULT_PUSH_CHECK_MS = 60_000;\n// How much of a refused request's unread body is discarded, and for how long, before its connection is closed.\nconst LINGER_BYTES = 1024 * 1024;\nconst LINGER_MS = 1000;\n// The longest delay a timer takes; past it, `setTimeout` fires at once.\nconst MAX_TIMER_MS = 2_147_483_647;\n// What Node refuses in a header value: anything but tab, printable ASCII and the Latin-1 range. A secret with a line break\n// or another control character would split or break the request, so it is refused before it is sent.\nconst INVALID_HEADER_VALUE = /[^\\t\\x20-\\x7e\\x80-\\xff]/;\n// The origin an in-process tool uses for a route, in either mode, because a Unix socket has no address of its own.\nconst ROUTE_ORIGIN = \"http://egress.proxy\";\n\n/** What a request for a route resolves to, before it is written to a socket or wrapped in a `Response`. */\ninterface RouteReply {\n readonly status: number;\n readonly headers: Record<string, string | string[]>;\n readonly body: import(\"node:stream\").Readable | undefined;\n readonly reason?: string;\n}\n\nconst refusal = (status: number, reason: string): RouteReply => ({\n status,\n headers: { \"content-type\": \"text/plain\" },\n body: undefined,\n reason,\n});\n\n/**\n * The answer to a git request whose credential is missing or wrong, or `undefined` when its HTTP Basic password is the\n * route's sentinel. A missing one gets 401 with a Basic challenge, so git asks its credential helper.\n */\nfunction gitCredentialRefusal(presented: string | string[] | undefined, sentinel: string): RouteReply | undefined {\n if (presented === undefined) {\n return { ...refusal(401, \"git_credential_missing\"), headers: { \"www-authenticate\": 'Basic realm=\"egress\"' } };\n }\n return typeof presented === \"string\" && basicCarries(presented, sentinel) ? undefined : refusal(403, \"bad_sentinel\");\n}\n\n/**\n * Checks a timeout option and returns the value to use: `fallback` when it is unset, or a whole number of milliseconds\n * from `min` to the longest delay a timer takes. The message names the option and never quotes the value.\n */\nfunction timeoutOption(name: string, ms: unknown, min: number, fallback: number): number {\n if (ms === undefined) return fallback;\n if (typeof ms === \"number\" && Number.isInteger(ms) && ms >= min && ms <= MAX_TIMER_MS) return ms;\n throw new HarnessError(\n \"invalid_egress_options\",\n `${name} must be a whole number of milliseconds from ${min} to ${MAX_TIMER_MS}`,\n );\n}\n\nclass EgressGate {\n private readonly modules: Modules;\n private readonly allow: readonly AllowEntry[];\n private readonly routes: ReadonlyMap<string, ParsedRoute>;\n private readonly sentinels: Record<string, string> = {};\n private readonly options: EgressProxyOptions;\n private readonly unsafe: ReadonlySet<string>;\n private readonly sockets = new Set<import(\"node:net\").Socket>();\n private readonly requests = new Set<import(\"node:http\").ClientRequest>();\n private readonly pushCheckMs: number;\n // 0 means no idle timeout, as it does for `socket.setTimeout`.\n private readonly idleMs: number;\n private origin = \"\";\n\n constructor(modules: Modules, options: EgressProxyOptions) {\n this.modules = modules;\n this.options = options;\n this.idleMs = timeoutOption(\"idleTimeoutMs\", options.idleTimeoutMs, 0, DEFAULT_IDLE_MS);\n this.pushCheckMs = timeoutOption(\"pushCheckTimeoutMs\", options.pushCheckTimeoutMs, 1, DEFAULT_PUSH_CHECK_MS);\n this.allow = parseAllow(options.allow);\n this.routes = new Map(parseRoutes(options.routes ?? [], this.allow).map((route) => [route.route, route]));\n this.unsafe = new Set(options.unsafeAllowAddresses ?? []);\n for (const route of this.routes.keys()) {\n this.sentinels[route] = `sentinel_${modules.crypto.randomBytes(18).toString(\"base64url\")}`;\n }\n }\n\n setOrigin(origin: string): void {\n this.origin = origin;\n }\n\n sentinelMap(): Readonly<Record<string, string>> {\n return this.sentinels;\n }\n\n private record(record: Omit<EgressRecord, \"time\">): void {\n try {\n this.options.log({ time: new Date().toISOString(), ...record });\n } catch {\n // A logger that throws must not take the proxy down.\n }\n }\n\n /** A `lookup` for `net` and `https`: it resolves in the proxy, checks every address, and connects only to those. */\n private readonly checkedLookup = (\n hostname: string,\n lookupOptions: { all?: boolean },\n callback: (error: Error | null, address?: unknown, family?: number) => void,\n ): void => {\n const resolve =\n this.options.resolve ??\n (async (host: string) =>\n (await this.modules.dns.promises.lookup(host, { all: true })).map((found) => found.address));\n resolve(hostname).then(\n (addresses) => {\n const refused = addresses.length === 0 || addresses.some((a) => !isPublicAddress(a) && !this.unsafe.has(a));\n if (refused) {\n callback(\n Object.assign(new Error(`${hostname} resolves to an address the proxy refuses`), {\n code: \"EGRESS_ADDRESS\",\n }),\n );\n return;\n }\n const family = (address: string) => (address.includes(\":\") ? 6 : 4);\n if (lookupOptions.all === true) {\n callback(\n null,\n addresses.map((address) => ({ address, family: family(address) })),\n );\n } else {\n callback(null, addresses[0], family(addresses[0] ?? \"\"));\n }\n },\n (error: unknown) => callback(error as Error),\n );\n };\n\n private reasonOf(error: unknown): string {\n const code = (error as { code?: string }).code;\n if (code === \"EGRESS_ADDRESS\") return \"address_refused\";\n return code === \"ETIMEDOUT\" ? \"timeout\" : \"connect_failed\";\n }\n\n /** The host and port of a `CONNECT` target, or `undefined` for one that isn't `host:port`. */\n private parseTarget(target: string): { host: string; port: number } | undefined {\n const match = /^(\\[[0-9a-fA-F:.]+\\]|[^:[\\]]+):([0-9]{1,5})$/.exec(target);\n if (match === null) return undefined;\n const host = (match[1] ?? \"\").toLowerCase().replace(/\\.$/, \"\");\n const port = Number(match[2]);\n return port >= 1 && port <= 65535 ? { host, port } : undefined;\n }\n\n /** Handles one `CONNECT`: allow-checks the name, then tunnels to the address the proxy checked. */\n handleConnect(request: import(\"node:http\").IncomingMessage, client: import(\"node:net\").Socket, head: Buffer): void {\n this.track(client);\n const target = this.parseTarget(request.url ?? \"\");\n const host = target?.host ?? \"(invalid)\";\n const port = target?.port ?? 0;\n const deny = (reason: string, status = 403) => {\n client.end(`HTTP/1.1 ${status} ${status === 403 ? \"Forbidden\" : \"Bad Gateway\"}\\r\\nConnection: close\\r\\n\\r\\n`);\n this.record({ kind: \"connect\", host, port, method: \"CONNECT\", status, bytes: 0, reason });\n };\n const refusedBecause =\n target === undefined\n ? \"bad_target\"\n : isAddressLiteral(host)\n ? \"address_literal\"\n : isAllowed(this.allow, host, port)\n ? undefined\n : \"not_allowed\";\n if (refusedBecause !== undefined) {\n deny(refusedBecause);\n return;\n }\n let established = false;\n const upstream = this.modules.net.connect({ host, port, lookup: this.checkedLookup as never });\n this.track(upstream);\n // A client that leaves before the tunnel is up takes the connection attempt with it.\n client.once(\"close\", () => upstream.destroy());\n upstream.setTimeout(this.idleMs, () => upstream.destroy(Object.assign(new Error(\"idle\"), { code: \"ETIMEDOUT\" })));\n upstream.once(\"error\", (error) => {\n if (established) client.destroy();\n else deny(this.reasonOf(error), 502);\n upstream.destroy();\n });\n upstream.once(\"connect\", () => {\n established = true;\n client.write(\"HTTP/1.1 200 Connection Established\\r\\n\\r\\n\");\n if (head.length > 0) upstream.write(head);\n upstream.pipe(client);\n client.pipe(upstream);\n const done = () => {\n client.destroy();\n upstream.destroy();\n };\n client.once(\"close\", done);\n upstream.once(\"close\", () => {\n this.record({\n kind: \"connect\",\n host,\n port,\n method: \"CONNECT\",\n status: 200,\n bytes: upstream.bytesRead + upstream.bytesWritten,\n });\n done();\n });\n });\n client.once(\"error\", () => upstream.destroy());\n }\n\n private track(socket: import(\"node:net\").Socket): void {\n if (this.sockets.has(socket)) return;\n this.sockets.add(socket);\n socket.once(\"close\", () => this.sockets.delete(socket));\n socket.on(\"error\", () => {});\n }\n\n /** Handles one request that isn't a `CONNECT`: a route request, or a refusal of anything else. */\n handleRequest(request: import(\"node:http\").IncomingMessage, response: import(\"node:http\").ServerResponse): void {\n this.track(request.socket);\n const url = request.url ?? \"\";\n if (!url.startsWith(\"/\")) {\n // A proxy request in absolute form: only a tunnel may leave, so the name is not even looked at.\n this.finish(response, refusal(403, \"only_connect\"), {\n kind: \"route\",\n host: \"(proxy request)\",\n port: 0,\n method: request.method ?? \"\",\n });\n return;\n }\n // A client that goes away takes the upstream request with it, so a credential isn't spent for nobody.\n const gone = new AbortController();\n response.once(\"close\", () => gone.abort());\n const base = {\n kind: \"route\" as const,\n host: \"(route)\",\n port: 0,\n method: request.method ?? \"GET\",\n route: undefined,\n };\n this.routeRequest(request.method ?? \"GET\", url, request.headers, request, gone.signal).then(\n (reply) => this.finish(response, reply.reply, reply.base, request),\n () => this.finish(response, refusal(502, \"request_failed\"), base, request),\n );\n }\n\n private finish(\n response: import(\"node:http\").ServerResponse,\n reply: RouteReply,\n base: Pick<EgressRecord, \"kind\" | \"host\" | \"port\" | \"method\" | \"route\">,\n request?: import(\"node:http\").IncomingMessage,\n ): void {\n let bytes = 0;\n const report = () =>\n this.record({\n ...base,\n status: reply.status,\n bytes,\n ...(reply.reason === undefined ? {} : { reason: reply.reason }),\n });\n if (reply.body === undefined && reply.status >= 400 && request !== undefined && !request.complete) {\n this.refuseAndClose(request, response, reply);\n report();\n return;\n }\n response.writeHead(reply.status, reply.headers);\n if (reply.body === undefined) {\n response.end(reply.status === 403 || reply.status >= 400 ? `${reply.reason ?? \"refused\"}\\n` : undefined);\n report();\n return;\n }\n reply.body.on(\"data\", (chunk: Buffer) => {\n bytes += chunk.length;\n });\n reply.body.once(\"close\", report);\n reply.body.once(\"error\", () => response.destroy());\n response.once(\"close\", () => reply.body?.destroy());\n reply.body.pipe(response);\n }\n\n /**\n * Refuses a request whose body has not been read to its end, and closes its connection. Node would otherwise read and\n * discard the rest of the body, a whole pack perhaps, to keep the connection alive. The answer is written whole, with\n * its length and `Connection: close`, and the response is ended, which closes the socket, only after the bytes already\n * on their way are discarded, up to `LINGER_BYTES` or for `LINGER_MS`. Closing a socket with unread bytes resets the\n * connection, and a client that has not yet read the answer would lose it.\n */\n private refuseAndClose(\n request: import(\"node:http\").IncomingMessage,\n response: import(\"node:http\").ServerResponse,\n reply: RouteReply,\n ): void {\n const text = `${reply.reason ?? \"refused\"}\\n`;\n response.writeHead(reply.status, { ...reply.headers, connection: \"close\", \"content-length\": String(text.length) });\n response.write(text);\n let discarded = 0;\n const done = () => {\n clearTimeout(timer);\n request.off(\"data\", onData);\n request.off(\"end\", done);\n request.off(\"close\", done);\n request.pause();\n response.end();\n };\n const onData = (chunk: Uint8Array) => {\n discarded += chunk.length;\n if (discarded >= LINGER_BYTES) done();\n };\n const timer = setTimeout(done, LINGER_MS);\n request.on(\"data\", onData);\n request.once(\"end\", done);\n request.once(\"close\", done);\n request.resume();\n }\n\n /**\n * Resolves a request for `/<route>/…`. It checks the route, the method and the sentinel, swaps in the secret, and\n * forwards the request to the route's host. A request that fails any check is answered here, and nothing is sent.\n */\n async routeRequest(\n method: string,\n rawPath: string,\n headers: Record<string, string | string[] | undefined>,\n body: import(\"node:stream\").Readable | Uint8Array | undefined,\n signal?: AbortSignal,\n ): Promise<{ reply: RouteReply; base: Pick<EgressRecord, \"kind\" | \"host\" | \"port\" | \"method\" | \"route\"> }> {\n const match = /^\\/([^/?#]+)(\\/[^?#]*)?(\\?[^#]*)?$/.exec(rawPath);\n const route = match === null ? undefined : this.routes.get(match[1] ?? \"\");\n const base = {\n kind: \"route\" as const,\n host: route?.hostname ?? \"(no route)\",\n port: route?.port ?? 0,\n method,\n route: route?.route,\n };\n if (route === undefined || match === null) return { reply: refusal(403, \"unknown_route\"), base };\n if (!route.methods.has(method.toUpperCase())) return { reply: refusal(405, \"method_not_allowed\"), base };\n const target = { path: match[2] ?? \"/\", query: match[3] ?? \"\" };\n const reply =\n route.git === undefined\n ? await this.headerRequest(route, method, target, headers, body, signal)\n : await this.gitRequest(route, route.git, method, target, headers, body, signal);\n return { reply, base };\n }\n\n /** Resolves a request on a header route: it swaps the sentinel in the route's header for the secret. */\n private async headerRequest(\n route: ParsedRoute,\n method: string,\n target: { readonly path: string; readonly query: string },\n headers: Record<string, string | string[] | undefined>,\n body: import(\"node:stream\").Readable | Uint8Array | undefined,\n signal?: AbortSignal,\n ): Promise<RouteReply> {\n const presented = headers[route.header];\n const sentinel = this.sentinels[route.route] ?? \"\";\n if (typeof presented !== \"string\" || sentinel === \"\" || !presented.includes(sentinel)) {\n return refusal(403, \"bad_sentinel\");\n }\n const secret = await route.secret().catch(() => \"\");\n if (secret === \"\" || INVALID_HEADER_VALUE.test(secret)) return refusal(502, \"secret_unavailable\");\n const outgoing = this.outgoingHeaders(\n headers,\n route,\n presented.replaceAll(sentinel, () => secret),\n );\n return this.forward(route, method, `${target.path}${target.query}`, outgoing, body, signal);\n }\n\n /**\n * Resolves a request on a git route. The endpoint and repository are checked first, then the sentinel in HTTP Basic,\n * then a push's command list, and only then is the secret read and the request forwarded with it. A missing\n * credential gets 401 with a Basic challenge, so git asks its credential helper for the sentinel.\n */\n private async gitRequest(\n route: ParsedRoute,\n filter: GitRouteFilter,\n method: string,\n target: { readonly path: string; readonly query: string },\n headers: Record<string, string | string[] | undefined>,\n body: import(\"node:stream\").Readable | Uint8Array | undefined,\n signal?: AbortSignal,\n ): Promise<RouteReply> {\n const endpoint = gitEndpoint(filter, method, target.path, target.query);\n if (\"refused\" in endpoint) return refusal(403, endpoint.refused);\n const unauthorized = gitCredentialRefusal(headers.authorization, this.sentinels[route.route] ?? \"\");\n if (unauthorized !== undefined) return unauthorized;\n let forwarded = body;\n if (endpoint.service === \"git-receive-pack\" && endpoint.phase === \"rpc\") {\n const encoding = headers[\"content-encoding\"];\n if (encoding !== undefined && encoding !== \"identity\") return refusal(403, \"git_encoded_push\");\n const checked = await this.checkPush(body, filter);\n if (\"refused\" in checked) return refusal(403, checked.refused);\n forwarded = checked.body;\n }\n const secret = await route.secret().catch(() => \"\");\n if (secret === \"\" || INVALID_HEADER_VALUE.test(secret)) return refusal(502, \"secret_unavailable\");\n const outgoing = this.outgoingHeaders(headers, route, basicHeader(filter.username, secret));\n return this.forward(route, method, `${target.path}${target.query}`, outgoing, forwarded, signal);\n }\n\n /**\n * Reads a push's command list and checks it, then hands back a body that starts with what was read. `PushReader`\n * reads each chunk once, so the check is linear in the bytes however small the chunks. The check gives up once the\n * body is idle for the idle timeout, which each chunk resets, or once `pushCheckTimeoutMs` has passed since it\n * started, which nothing resets.\n */\n private checkPush(\n body: import(\"node:stream\").Readable | Uint8Array | undefined,\n filter: GitRouteFilter,\n ): Promise<{ readonly refused: string } | { readonly body: import(\"node:stream\").Readable | Uint8Array }> {\n if (body === undefined) return Promise.resolve({ refused: \"git_bad_pkt_line\" });\n if (body instanceof Uint8Array) {\n const verdict = pushVerdict(body, filter, true);\n return Promise.resolve(verdict === \"allowed\" ? { body } : { refused: (verdict as { refused: string }).refused });\n }\n return new Promise((resolve) => {\n const reader = new PushReader(filter);\n const chunks: Uint8Array[] = [];\n const timedOut = () => settle({ refused: \"git_timeout\" });\n // An idle timeout of 0 is off, so only the deadline ends a quiet body.\n const startIdle = () => (this.idleMs === 0 ? undefined : setTimeout(timedOut, this.idleMs));\n let idle = startIdle();\n const deadline = setTimeout(timedOut, this.pushCheckMs);\n const settle = (outcome: { refused: string } | { body: import(\"node:stream\").Readable }) => {\n clearTimeout(idle);\n clearTimeout(deadline);\n body.off(\"data\", onData);\n body.off(\"end\", onEnd);\n body.off(\"error\", onError);\n body.off(\"close\", onError);\n // A refused body is not read further; the answer closes its connection.\n if (\"refused\" in outcome) body.pause();\n resolve(outcome);\n };\n const judge = (verdict: ReturnType<PushReader[\"add\"]>, ended: boolean) => {\n if (verdict === \"incomplete\") return;\n if (verdict !== \"allowed\") {\n settle(verdict);\n return;\n }\n const rest = new this.modules.stream.PassThrough();\n for (const chunk of chunks) rest.write(chunk);\n settle({ body: rest });\n if (ended) rest.end();\n else body.pipe(rest);\n };\n const onData = (chunk: Uint8Array) => {\n clearTimeout(idle);\n idle = startIdle();\n chunks.push(chunk);\n judge(reader.add(chunk), false);\n };\n const onEnd = () => judge(reader.end(), true);\n const onError = () => settle({ refused: \"request_failed\" });\n body.on(\"data\", onData);\n body.once(\"end\", onEnd);\n body.once(\"error\", onError);\n // A client that goes away before its command list ends would otherwise hold the check until a timeout.\n body.once(\"close\", onError);\n });\n }\n\n private outgoingHeaders(\n headers: Record<string, string | string[] | undefined>,\n route: ParsedRoute,\n credential: string,\n ): Record<string, string | string[]> {\n const out: Record<string, string | string[]> = {};\n for (const [name, value] of Object.entries(headers)) {\n if (value !== undefined && !HOP_BY_HOP.has(name)) out[name] = value;\n }\n out[route.header] = credential;\n out.host = route.port === 443 ? route.hostname : `${route.hostname}:${route.port}`;\n return out;\n }\n\n private forward(\n route: ParsedRoute,\n method: string,\n path: string,\n headers: Record<string, string | string[]>,\n body: import(\"node:stream\").Readable | Uint8Array | undefined,\n signal?: AbortSignal,\n ): Promise<RouteReply> {\n return new Promise((resolve) => {\n let upstream: import(\"node:http\").ClientRequest;\n try {\n upstream = this.openRoute(route, method, path, headers);\n } catch {\n resolve(refusal(502, \"request_invalid\"));\n return;\n }\n const stop = () => upstream.destroy(new Error(\"client gone\"));\n if (signal?.aborted === true) stop();\n else signal?.addEventListener(\"abort\", stop, { once: true });\n upstream.once(\"close\", () => signal?.removeEventListener(\"abort\", stop));\n this.requests.add(upstream);\n upstream.setTimeout(this.idleMs, () => upstream.destroy(new Error(\"idle\")));\n upstream.once(\"close\", () => this.requests.delete(upstream));\n upstream.once(\"response\", (reply) => {\n const passed: Record<string, string | string[]> = {};\n for (const [name, value] of Object.entries(reply.headers)) {\n if (value !== undefined && !HOP_BY_HOP.has(name)) passed[name] = value;\n }\n resolve({ status: reply.statusCode ?? 502, headers: passed, body: reply });\n });\n upstream.once(\"error\", (error) => resolve(refusal(502, this.reasonOf(error))));\n if (body === undefined) upstream.end();\n else if (body instanceof Uint8Array) upstream.end(body);\n else body.pipe(upstream);\n });\n }\n\n /** Opens the HTTPS request to a route's host, which throws for a header or path Node refuses. */\n private openRoute(\n route: ParsedRoute,\n method: string,\n path: string,\n headers: Record<string, string | string[]>,\n ): import(\"node:http\").ClientRequest {\n return this.modules.https.request({\n host: route.hostname,\n port: route.port,\n servername: route.hostname,\n method,\n path,\n headers,\n agent: false,\n lookup: this.checkedLookup as never,\n ...(this.options.ca === undefined ? {} : { ca: this.options.ca as never }),\n });\n }\n\n /** An in-process fetch under the same allowlist, with the same address checks and pinned connection. */\n async fetch(input: string | URL, init?: RequestInit): Promise<Response> {\n const request = new Request(input, init);\n request.signal.throwIfAborted();\n const url = new URL(request.url);\n const host = url.hostname.toLowerCase().replace(/\\.$/, \"\");\n const port = url.port === \"\" ? 443 : Number(url.port);\n const bodyBytes =\n request.method === \"GET\" || request.method === \"HEAD\" ? undefined : new Uint8Array(await request.arrayBuffer());\n if (url.origin === ROUTE_ORIGIN || (this.origin !== \"\" && url.origin === this.origin)) {\n return this.fetchRoute(request, url, bodyBytes);\n }\n const refuse = (reason: string): never => {\n this.record({ kind: \"fetch\", host, port, method: request.method, status: 403, bytes: 0, reason });\n throw new HarnessError(\"egress_denied\", `the egress proxy refused ${url.host}: ${reason}`);\n };\n if (url.protocol !== \"https:\") return refuse(\"only_https\");\n if (isAddressLiteral(host)) return refuse(\"address_literal\");\n if (!isAllowed(this.allow, host, port)) return refuse(\"not_allowed\");\n return this.sendFetch(request, url, host, port, bodyBytes);\n }\n\n private async fetchRoute(request: Request, url: URL, body: Uint8Array | undefined): Promise<Response> {\n const headers: Record<string, string> = {};\n request.headers.forEach((value, name) => {\n headers[name.toLowerCase()] = value;\n });\n const path = `${url.pathname}${url.search}`;\n const { reply, base } = await this.routeRequest(request.method, path, headers, body, request.signal);\n const stream = reply.body;\n let bytes = 0;\n stream?.on(\"data\", (chunk: Buffer) => {\n bytes += chunk.length;\n });\n const finished = () =>\n this.record({\n ...base,\n status: reply.status,\n bytes,\n ...(reply.reason === undefined ? {} : { reason: reply.reason }),\n });\n if (stream === undefined) finished();\n else stream.once(\"close\", finished);\n return this.toResponse(reply.status, reply.headers, stream);\n }\n\n private sendFetch(\n request: Request,\n url: URL,\n host: string,\n port: number,\n body: Uint8Array | undefined,\n ): Promise<Response> {\n return new Promise((resolve, reject) => {\n const headers: Record<string, string> = {};\n request.headers.forEach((value, name) => {\n if (!HOP_BY_HOP.has(name.toLowerCase())) headers[name] = value;\n });\n const upstream = this.modules.https.request({\n host,\n port,\n servername: host,\n method: request.method,\n path: `${url.pathname}${url.search}`,\n headers: { ...headers, host: url.host },\n agent: false,\n lookup: this.checkedLookup as never,\n ...(this.options.ca === undefined ? {} : { ca: this.options.ca as never }),\n });\n this.requests.add(upstream);\n const abort = () => upstream.destroy(request.signal.reason as Error);\n request.signal.addEventListener(\"abort\", abort, { once: true });\n upstream.once(\"close\", () => {\n this.requests.delete(upstream);\n request.signal.removeEventListener(\"abort\", abort);\n });\n upstream.setTimeout(this.idleMs, () => upstream.destroy(new Error(\"idle\")));\n upstream.once(\"response\", (reply) => {\n let bytes = 0;\n reply.on(\"data\", (chunk: Buffer) => {\n bytes += chunk.length;\n });\n // The record is written when the response is done with, which also covers one that is never read to its end.\n reply.once(\"close\", () =>\n this.record({ kind: \"fetch\", host, port, method: request.method, status: reply.statusCode ?? 0, bytes }),\n );\n resolve(this.toResponse(reply.statusCode ?? 502, reply.headers as Record<string, string | string[]>, reply));\n });\n upstream.once(\"error\", (error) => {\n if (request.signal.aborted) {\n reject(request.signal.reason);\n return;\n }\n const reason = this.reasonOf(error);\n this.record({ kind: \"fetch\", host, port, method: request.method, status: 502, bytes: 0, reason });\n reject(\n new HarnessError(\"egress_denied\", `the egress proxy could not reach ${url.host}: ${reason}`, {\n cause: error,\n }),\n );\n });\n upstream.end(body);\n });\n }\n\n private toResponse(\n status: number,\n headers: Record<string, string | string[]>,\n stream: import(\"node:stream\").Readable | undefined,\n ): Response {\n const out = new Headers();\n for (const [name, value] of Object.entries(headers)) {\n for (const one of Array.isArray(value) ? value : [value]) out.append(name, one);\n }\n const bodiless = stream === undefined || [101, 204, 205, 304].includes(status);\n // A response with no body is drained, so its socket and its log record don't wait for a reader that never comes.\n if (bodiless) stream?.resume();\n const web = bodiless ? null : (this.modules.stream.Readable.toWeb(stream) as ReadableStream);\n return new Response(web, { status, headers: out });\n }\n\n async knownSecrets(): Promise<readonly string[]> {\n const secrets = await Promise.all([...this.routes.values()].map((route) => route.secret().catch(() => \"\")));\n return [...new Set(secrets.filter((secret) => secret !== \"\"))];\n }\n\n close(server: import(\"node:http\").Server): Promise<void> {\n return new Promise((resolve) => {\n for (const socket of this.sockets) socket.destroy();\n for (const request of this.requests) request.destroy();\n server.close(() => resolve());\n server.closeAllConnections();\n });\n }\n}\n\n/**\n * Starts the egress proxy on `127.0.0.1` with a port the system picks, or on `socketPath`. The allowlist and routes are\n * checked first, and a bad entry throws `invalid_egress_options`. Give the sandbox `proxy.url` as `HTTPS_PROXY`, and\n * give a tool that needs a credential the route's URL and its sentinel.\n */\nexport async function startEgressProxy(options: EgressProxyOptions): Promise<EgressProxy> {\n const modules = nodeModules();\n const proxy = new EgressGate(modules, options);\n const server = modules.http.createServer((request, response) => proxy.handleRequest(request, response));\n server.on(\"connect\", (request, socket, head) => proxy.handleConnect(request, socket as never, head));\n server.on(\"clientError\", (_error, socket) => socket.destroy());\n await new Promise<void>((resolve, reject) => {\n server.once(\"error\", reject);\n if (options.socketPath === undefined) server.listen(0, \"127.0.0.1\", resolve);\n else server.listen(options.socketPath, resolve);\n });\n const address = server.address();\n const url =\n options.socketPath !== undefined\n ? `unix:${options.socketPath}`\n : `http://127.0.0.1:${(address as { port: number }).port}`;\n if (options.socketPath === undefined) proxy.setOrigin(url);\n return {\n url,\n ...(options.socketPath === undefined ? {} : { socketPath: options.socketPath }),\n sentinels: proxy.sentinelMap(),\n fetch: (input, init) => proxy.fetch(input, init),\n knownSecrets: () => proxy.knownSecrets(),\n close: () => proxy.close(server),\n };\n}\n"]}
1
+ {"version":3,"file":"egress-proxy.js","sourceRoot":"","sources":["../../src/credentials/egress-proxy.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AACH,OAAO,EAAE,YAAY,EAAE,MAAM,cAAc,CAAC;AAC5C,OAAO,EAAE,gBAAgB,EAAE,eAAe,EAAE,MAAM,gBAAgB,CAAC;AACnE,OAAO,EAGL,SAAS,EAET,UAAU,EACV,WAAW,GACZ,MAAM,gBAAgB,CAAC;AACxB,OAAO,EAAE,YAAY,EAAE,WAAW,EAAuB,WAAW,EAAE,UAAU,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAC;AA0FtH,SAAS,WAAW;IAClB,IAAI,OAAO,OAAO,KAAK,WAAW,IAAI,OAAO,OAAO,CAAC,gBAAgB,KAAK,UAAU,EAAE,CAAC;QACrF,MAAM,IAAI,YAAY,CACpB,wBAAwB,EACxB,yEAAyE,CAC1E,CAAC;IACJ,CAAC;IACD,OAAO;QACL,IAAI,EAAE,OAAO,CAAC,gBAAgB,CAAC,WAAW,CAAC;QAC3C,KAAK,EAAE,OAAO,CAAC,gBAAgB,CAAC,YAAY,CAAC;QAC7C,GAAG,EAAE,OAAO,CAAC,gBAAgB,CAAC,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,CAAC,KAAK,CAAC,YAAY,EAAE;QACxC,KAAK,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC,KAAK,CAAC,MAAM,CAAC;KACjC,CAAC;AACJ,CAAC","sourcesContent":["/**\n * `startEgressProxy()`: the host-side proxy that keeps credentials out of the sandbox. Nothing leaves the sandbox except\n * through it, it refuses everything that isn't on its allowlist, and it logs each request without its headers. A tool\n * that needs a credential sends its request to a local route, such as `http://127.0.0.1:<port>/github/user`, with the\n * route's sentinel where the credential goes. The proxy checks the sentinel and the method, swaps in the real secret and\n * forwards the request over HTTPS. It never intercepts TLS: everything else leaves through `CONNECT` to an\n * allowlisted name, and a name is connected to only at an address the proxy checked. It is Node-only.\n */\nimport { HarnessError } from \"../errors.js\";\nimport { isAddressLiteral, isPublicAddress } from \"./addresses.js\";\nimport {\n type AllowEntry,\n type CredentialRoute,\n isAllowed,\n type ParsedRoute,\n parseAllow,\n parseRoutes,\n} from \"./allowlist.js\";\nimport { basicCarries, basicHeader, type GitRouteFilter, gitEndpoint, PushReader, pushVerdict } from \"./git-route.js\";\n\nexport type { CredentialRoute } from \"./allowlist.js\";\n\n/** One line of the egress log. It names the host and the outcome, and never holds a header, a body or a secret. */\nexport interface EgressRecord {\n /** When the request ended, as an ISO 8601 string. */\n readonly time: string;\n /** `connect` for a tunnel, `route` for a credential route and `fetch` for an in-process call. */\n readonly kind: \"connect\" | \"route\" | \"fetch\";\n /** The host the request was for. */\n readonly host: string;\n readonly port: number;\n readonly method: string;\n /** The status the sandbox saw: 200 for an established tunnel, 403 for a refusal, 502 for a failed connection. */\n readonly status: number;\n /** The bytes that went both ways, 0 for a refusal. */\n readonly bytes: number;\n /** The route's name, for a route request. */\n readonly route?: string | undefined;\n /** Why a request was refused or failed, as a short code such as `not_allowed` or `address_refused`. */\n readonly reason?: string;\n}\n\n/** The options of `startEgressProxy()`. */\nexport interface EgressProxyOptions {\n /** The names a tunnel or an in-process fetch may reach: `example.com`, `*.example.com`, or either with `:port`. */\n readonly allow: readonly string[];\n /** The credential routes. Without any, the proxy only tunnels. */\n readonly routes?: readonly CredentialRoute[];\n /** Receives one record for each request. A throw from it is ignored. */\n readonly log: (record: EgressRecord) => void;\n /** Listens on this Unix socket instead of a port on `127.0.0.1`, so a container can mount it (`dockerSandbox`'s `proxySocket`). */\n readonly socketPath?: string;\n /** Extra certificate authorities to trust for the routes' hosts and for the fetch, such as a test's own. */\n readonly ca?: string | Uint8Array | readonly (string | Uint8Array)[];\n /** Resolves a name to its addresses. Defaults to the system resolver. Every address it returns is checked. */\n readonly resolve?: (host: string) => Promise<readonly string[]>;\n /**\n * Addresses that skip the public-address check. This exists so a test can reach a server on `127.0.0.1`. Never set it\n * for a real run: the check is what keeps a name that points at the host's own network from being reached.\n */\n readonly unsafeAllowAddresses?: readonly string[];\n /**\n * Ends a tunnel, a forwarded request or a push check that is idle this long. A whole number of milliseconds from 0 to\n * 2,147,483,647, where 0 turns the idle timeout off, as it does for a socket; anything else throws\n * `invalid_egress_options` when the proxy starts. Defaults to 120000.\n */\n readonly idleTimeoutMs?: number;\n /**\n * The longest a push's command list may take to arrive, from the start of its body, however often bytes come. The\n * clock starts once and is never reset, so a client that sends a byte just inside the idle timeout is still cut off;\n * a push that takes longer is refused with `git_timeout`. Only the command list is timed, not the pack after it. A\n * whole number of milliseconds from 1 to 2,147,483,647; anything else throws `invalid_egress_options` when the proxy\n * starts. Defaults to 60000.\n */\n readonly pushCheckTimeoutMs?: number;\n}\n\n/** A running egress proxy. */\nexport interface EgressProxy {\n /**\n * Where the sandbox sends its requests: give it as `HTTPS_PROXY`, and join a route's name to it for a route. On a Unix\n * socket it is `unix:<path>`, which is not a proxy URL: the program that uses the socket connects to it itself.\n */\n readonly url: string;\n /** The Unix socket the proxy listens on, when it was started with `socketPath`. */\n readonly socketPath?: string;\n /** For each route, the placeholder the sandbox puts where the credential goes. The real secret never leaves the host. */\n readonly sentinels: Readonly<Record<string, string>>;\n /**\n * Fetches `input` for an in-process tool, under the same allowlist. A host that isn't on it rejects with `egress_denied`.\n * A route is reached at `${proxy.url}/<route>/…`, or at `http://egress.proxy/<route>/…`, which also works on a Unix socket.\n */\n fetch(input: string | URL, init?: RequestInit): Promise<Response>;\n /** The routes' secrets now, for `scrubSecrets()`. */\n knownSecrets(): Promise<readonly string[]>;\n /** Stops listening and ends every open tunnel and request. */\n close(): Promise<void>;\n}\n\ntype Modules = {\n readonly http: typeof import(\"node:http\");\n readonly https: typeof import(\"node:https\");\n readonly net: typeof import(\"node:net\");\n readonly dns: typeof import(\"node:dns\");\n readonly crypto: typeof import(\"node:crypto\");\n readonly stream: typeof import(\"node:stream\");\n};\n\nfunction nodeModules(): Modules {\n if (typeof process === \"undefined\" || typeof process.getBuiltinModule !== \"function\") {\n throw new HarnessError(\n \"invalid_egress_options\",\n \"the egress proxy needs Node's network modules, which this runtime lacks\",\n );\n }\n return {\n http: process.getBuiltinModule(\"node:http\"),\n https: process.getBuiltinModule(\"node:https\"),\n net: process.getBuiltinModule(\"node:net\"),\n dns: process.getBuiltinModule(\"node:dns\"),\n crypto: process.getBuiltinModule(\"node:crypto\"),\n stream: process.getBuiltinModule(\"node:stream\"),\n };\n}\n\n// Headers that belong to one connection, and are never passed on to the next.\nconst HOP_BY_HOP = new Set([\n \"connection\",\n \"keep-alive\",\n \"proxy-authenticate\",\n \"proxy-authorization\",\n \"proxy-connection\",\n \"te\",\n \"trailer\",\n \"transfer-encoding\",\n \"upgrade\",\n \"host\",\n]);\nconst DEFAULT_IDLE_MS = 120_000;\nconst DEFAULT_PUSH_CHECK_MS = 60_000;\n// How much of a refused request's unread body is discarded, and for how long, before its connection is closed.\nconst LINGER_BYTES = 1024 * 1024;\nconst LINGER_MS = 1000;\n// The longest delay a timer takes; past it, `setTimeout` fires at once.\nconst MAX_TIMER_MS = 2_147_483_647;\n// What Node refuses in a header value: anything but tab, printable ASCII and the Latin-1 range. A secret with a line break\n// or another control character would split or break the request, so it is refused before it is sent.\nconst INVALID_HEADER_VALUE = /[^\\t\\x20-\\x7e\\x80-\\xff]/;\n// The origin an in-process tool uses for a route, in either mode, because a Unix socket has no address of its own.\nconst ROUTE_ORIGIN = \"http://egress.proxy\";\n\n/** What a request for a route resolves to, before it is written to a socket or wrapped in a `Response`. */\ninterface RouteReply {\n readonly status: number;\n readonly headers: Record<string, string | string[]>;\n readonly body: import(\"node:stream\").Readable | undefined;\n readonly reason?: string;\n}\n\nconst refusal = (status: number, reason: string): RouteReply => ({\n status,\n headers: { \"content-type\": \"text/plain\" },\n body: undefined,\n reason,\n});\n\n/**\n * The answer to a git request whose credential is missing or wrong, or `undefined` when its HTTP Basic password is the\n * route's sentinel. A missing one gets 401 with a Basic challenge, so git asks its credential helper.\n */\nfunction gitCredentialRefusal(presented: string | string[] | undefined, sentinel: string): RouteReply | undefined {\n if (presented === undefined) {\n return { ...refusal(401, \"git_credential_missing\"), headers: { \"www-authenticate\": 'Basic realm=\"egress\"' } };\n }\n return typeof presented === \"string\" && basicCarries(presented, sentinel) ? undefined : refusal(403, \"bad_sentinel\");\n}\n\n/**\n * Checks a timeout option and returns the value to use: `fallback` when it is unset, or a whole number of milliseconds\n * from `min` to the longest delay a timer takes. The message names the option and never quotes the value.\n */\nfunction timeoutOption(name: string, ms: unknown, min: number, fallback: number): number {\n if (ms === undefined) return fallback;\n if (typeof ms === \"number\" && Number.isInteger(ms) && ms >= min && ms <= MAX_TIMER_MS) return ms;\n throw new HarnessError(\n \"invalid_egress_options\",\n `${name} must be a whole number of milliseconds from ${min} to ${MAX_TIMER_MS}`,\n );\n}\n\nclass EgressGate {\n private readonly modules: Modules;\n private readonly allow: readonly AllowEntry[];\n private readonly routes: ReadonlyMap<string, ParsedRoute>;\n private readonly sentinels: Record<string, string> = {};\n private readonly options: EgressProxyOptions;\n private readonly unsafe: ReadonlySet<string>;\n private readonly sockets = new Set<import(\"node:net\").Socket>();\n private readonly requests = new Set<import(\"node:http\").ClientRequest>();\n private readonly pushCheckMs: number;\n // 0 means no idle timeout, as it does for `socket.setTimeout`.\n private readonly idleMs: number;\n private origin = \"\";\n\n constructor(modules: Modules, options: EgressProxyOptions) {\n this.modules = modules;\n this.options = options;\n this.idleMs = timeoutOption(\"idleTimeoutMs\", options.idleTimeoutMs, 0, DEFAULT_IDLE_MS);\n this.pushCheckMs = timeoutOption(\"pushCheckTimeoutMs\", options.pushCheckTimeoutMs, 1, DEFAULT_PUSH_CHECK_MS);\n this.allow = parseAllow(options.allow);\n this.routes = new Map(parseRoutes(options.routes ?? [], this.allow).map((route) => [route.route, route]));\n this.unsafe = new Set(options.unsafeAllowAddresses ?? []);\n for (const route of this.routes.keys()) {\n this.sentinels[route] = `sentinel_${modules.crypto.randomBytes(18).toString(\"base64url\")}`;\n }\n }\n\n setOrigin(origin: string): void {\n this.origin = origin;\n }\n\n sentinelMap(): Readonly<Record<string, string>> {\n return this.sentinels;\n }\n\n private record(record: Omit<EgressRecord, \"time\">): void {\n try {\n this.options.log({ time: new Date().toISOString(), ...record });\n } catch {\n // A logger that throws must not take the proxy down.\n }\n }\n\n /** A `lookup` for `net` and `https`: it resolves in the proxy, checks every address, and connects only to those. */\n private readonly checkedLookup = (\n hostname: string,\n lookupOptions: { all?: boolean },\n callback: (error: Error | null, address?: unknown, family?: number) => void,\n ): void => {\n const resolve =\n this.options.resolve ??\n (async (host: string) =>\n (await this.modules.dns.promises.lookup(host, { all: true })).map((found) => found.address));\n resolve(hostname).then(\n (addresses) => {\n const refused = addresses.length === 0 || addresses.some((a) => !isPublicAddress(a) && !this.unsafe.has(a));\n if (refused) {\n callback(\n Object.assign(new Error(`${hostname} resolves to an address the proxy refuses`), {\n code: \"EGRESS_ADDRESS\",\n }),\n );\n return;\n }\n const family = (address: string) => (address.includes(\":\") ? 6 : 4);\n if (lookupOptions.all === true) {\n callback(\n null,\n addresses.map((address) => ({ address, family: family(address) })),\n );\n } else {\n callback(null, addresses[0], family(addresses[0] ?? \"\"));\n }\n },\n (error: unknown) => callback(error as Error),\n );\n };\n\n private reasonOf(error: unknown): string {\n const code = (error as { code?: string }).code;\n if (code === \"EGRESS_ADDRESS\") return \"address_refused\";\n return code === \"ETIMEDOUT\" ? \"timeout\" : \"connect_failed\";\n }\n\n /** The host and port of a `CONNECT` target, or `undefined` for one that isn't `host:port`. */\n private parseTarget(target: string): { host: string; port: number } | undefined {\n const match = /^(\\[[0-9a-fA-F:.]+\\]|[^:[\\]]+):([0-9]{1,5})$/.exec(target);\n if (match === null) return undefined;\n const host = (match[1] ?? \"\").toLowerCase().replace(/\\.$/, \"\");\n const port = Number(match[2]);\n return port >= 1 && port <= 65535 ? { host, port } : undefined;\n }\n\n /** Handles one `CONNECT`: allow-checks the name, then tunnels to the address the proxy checked. */\n handleConnect(request: import(\"node:http\").IncomingMessage, client: import(\"node:net\").Socket, head: Buffer): void {\n this.track(client);\n const target = this.parseTarget(request.url ?? \"\");\n const host = target?.host ?? \"(invalid)\";\n const port = target?.port ?? 0;\n const deny = (reason: string, status = 403) => {\n client.end(`HTTP/1.1 ${status} ${status === 403 ? \"Forbidden\" : \"Bad Gateway\"}\\r\\nConnection: close\\r\\n\\r\\n`);\n this.record({ kind: \"connect\", host, port, method: \"CONNECT\", status, bytes: 0, reason });\n };\n const refusedBecause =\n target === undefined\n ? \"bad_target\"\n : isAddressLiteral(host)\n ? \"address_literal\"\n : isAllowed(this.allow, host, port)\n ? undefined\n : \"not_allowed\";\n if (refusedBecause !== undefined) {\n deny(refusedBecause);\n return;\n }\n let established = false;\n const upstream = this.modules.net.connect({ host, port, lookup: this.checkedLookup as never });\n this.track(upstream);\n // A client that leaves before the tunnel is up takes the connection attempt with it.\n client.once(\"close\", () => upstream.destroy());\n upstream.setTimeout(this.idleMs, () => upstream.destroy(Object.assign(new Error(\"idle\"), { code: \"ETIMEDOUT\" })));\n upstream.once(\"error\", (error) => {\n if (established) client.destroy();\n else deny(this.reasonOf(error), 502);\n upstream.destroy();\n });\n upstream.once(\"connect\", () => {\n established = true;\n client.write(\"HTTP/1.1 200 Connection Established\\r\\n\\r\\n\");\n if (head.length > 0) upstream.write(head);\n upstream.pipe(client);\n client.pipe(upstream);\n const done = () => {\n client.destroy();\n upstream.destroy();\n };\n client.once(\"close\", done);\n upstream.once(\"close\", () => {\n this.record({\n kind: \"connect\",\n host,\n port,\n method: \"CONNECT\",\n status: 200,\n bytes: upstream.bytesRead + upstream.bytesWritten,\n });\n done();\n });\n });\n client.once(\"error\", () => upstream.destroy());\n }\n\n private track(socket: import(\"node:net\").Socket): void {\n if (this.sockets.has(socket)) return;\n this.sockets.add(socket);\n socket.once(\"close\", () => this.sockets.delete(socket));\n socket.on(\"error\", () => {});\n }\n\n /** Handles one request that isn't a `CONNECT`: a route request, or a refusal of anything else. */\n handleRequest(request: import(\"node:http\").IncomingMessage, response: import(\"node:http\").ServerResponse): void {\n this.track(request.socket);\n const url = request.url ?? \"\";\n if (!url.startsWith(\"/\")) {\n // A proxy request in absolute form: only a tunnel may leave, so the name is not even looked at.\n this.finish(response, refusal(403, \"only_connect\"), {\n kind: \"route\",\n host: \"(proxy request)\",\n port: 0,\n method: request.method ?? \"\",\n });\n return;\n }\n // A client that goes away takes the upstream request with it, so a credential isn't spent for nobody.\n const gone = new AbortController();\n response.once(\"close\", () => gone.abort());\n const base = {\n kind: \"route\" as const,\n host: \"(route)\",\n port: 0,\n method: request.method ?? \"GET\",\n route: undefined,\n };\n this.routeRequest(request.method ?? \"GET\", url, request.headers, request, gone.signal).then(\n (reply) => this.finish(response, reply.reply, reply.base, request),\n () => this.finish(response, refusal(502, \"request_failed\"), base, request),\n );\n }\n\n private finish(\n response: import(\"node:http\").ServerResponse,\n reply: RouteReply,\n base: Pick<EgressRecord, \"kind\" | \"host\" | \"port\" | \"method\" | \"route\">,\n request?: import(\"node:http\").IncomingMessage,\n ): void {\n let bytes = 0;\n const report = () =>\n this.record({\n ...base,\n status: reply.status,\n bytes,\n ...(reply.reason === undefined ? {} : { reason: reply.reason }),\n });\n if (reply.body === undefined && reply.status >= 400 && request !== undefined && !request.complete) {\n this.refuseAndClose(request, response, reply);\n report();\n return;\n }\n response.writeHead(reply.status, reply.headers);\n if (reply.body === undefined) {\n response.end(reply.status === 403 || reply.status >= 400 ? `${reply.reason ?? \"refused\"}\\n` : undefined);\n report();\n return;\n }\n reply.body.on(\"data\", (chunk: Buffer) => {\n bytes += chunk.length;\n });\n reply.body.once(\"close\", report);\n reply.body.once(\"error\", () => response.destroy());\n response.once(\"close\", () => reply.body?.destroy());\n reply.body.pipe(response);\n }\n\n /**\n * Refuses a request whose body has not been read to its end, and closes its connection. Node would otherwise read and\n * discard the rest of the body, a whole pack perhaps, to keep the connection alive. The answer is written whole, with\n * its length and `Connection: close`, and the response is ended, which closes the socket, only after the bytes already\n * on their way are discarded, up to `LINGER_BYTES` or for `LINGER_MS`. Closing a socket with unread bytes resets the\n * connection, and a client that has not yet read the answer would lose it.\n */\n private refuseAndClose(\n request: import(\"node:http\").IncomingMessage,\n response: import(\"node:http\").ServerResponse,\n reply: RouteReply,\n ): void {\n const text = `${reply.reason ?? \"refused\"}\\n`;\n response.writeHead(reply.status, { ...reply.headers, connection: \"close\", \"content-length\": String(text.length) });\n response.write(text);\n let discarded = 0;\n const done = () => {\n clearTimeout(timer);\n request.off(\"data\", onData);\n request.off(\"end\", done);\n request.off(\"close\", done);\n request.pause();\n response.end();\n };\n const onData = (chunk: Uint8Array) => {\n discarded += chunk.length;\n if (discarded >= LINGER_BYTES) done();\n };\n const timer = setTimeout(done, LINGER_MS);\n request.on(\"data\", onData);\n request.once(\"end\", done);\n request.once(\"close\", done);\n request.resume();\n }\n\n /**\n * Resolves a request for `/<route>/…`. It checks the route, the method and the sentinel, swaps in the secret, and\n * forwards the request to the route's host. A request that fails any check is answered here, and nothing is sent.\n */\n async routeRequest(\n method: string,\n rawPath: string,\n headers: Record<string, string | string[] | undefined>,\n body: import(\"node:stream\").Readable | Uint8Array | undefined,\n signal?: AbortSignal,\n ): Promise<{ reply: RouteReply; base: Pick<EgressRecord, \"kind\" | \"host\" | \"port\" | \"method\" | \"route\"> }> {\n const match = /^\\/([^/?#]+)(\\/[^?#]*)?(\\?[^#]*)?$/.exec(rawPath);\n const route = match === null ? undefined : this.routes.get(match[1] ?? \"\");\n const base = {\n kind: \"route\" as const,\n host: route?.hostname ?? \"(no route)\",\n port: route?.port ?? 0,\n method,\n route: route?.route,\n };\n if (route === undefined || match === null) return { reply: refusal(403, \"unknown_route\"), base };\n if (!route.methods.has(method.toUpperCase())) return { reply: refusal(405, \"method_not_allowed\"), base };\n const target = { path: match[2] ?? \"/\", query: match[3] ?? \"\" };\n const reply =\n route.git === undefined\n ? await this.headerRequest(route, method, target, headers, body, signal)\n : await this.gitRequest(route, route.git, method, target, headers, body, signal);\n return { reply, base };\n }\n\n /** Resolves a request on a header route: it swaps the sentinel in the route's header for the secret. */\n private async headerRequest(\n route: ParsedRoute,\n method: string,\n target: { readonly path: string; readonly query: string },\n headers: Record<string, string | string[] | undefined>,\n body: import(\"node:stream\").Readable | Uint8Array | undefined,\n signal?: AbortSignal,\n ): Promise<RouteReply> {\n const presented = headers[route.header];\n const sentinel = this.sentinels[route.route] ?? \"\";\n if (typeof presented !== \"string\" || sentinel === \"\" || !presented.includes(sentinel)) {\n return refusal(403, \"bad_sentinel\");\n }\n const secret = await route.secret().catch(() => \"\");\n if (secret === \"\" || INVALID_HEADER_VALUE.test(secret)) return refusal(502, \"secret_unavailable\");\n const outgoing = this.outgoingHeaders(\n headers,\n route,\n presented.replaceAll(sentinel, () => secret),\n );\n return this.forward(route, method, `${target.path}${target.query}`, outgoing, body, signal);\n }\n\n /**\n * Resolves a request on a git route. The endpoint and repository are checked first, then the sentinel in HTTP Basic,\n * then a push's command list, and only then is the secret read and the request forwarded with it. A missing\n * credential gets 401 with a Basic challenge, so git asks its credential helper for the sentinel.\n */\n private async gitRequest(\n route: ParsedRoute,\n filter: GitRouteFilter,\n method: string,\n target: { readonly path: string; readonly query: string },\n headers: Record<string, string | string[] | undefined>,\n body: import(\"node:stream\").Readable | Uint8Array | undefined,\n signal?: AbortSignal,\n ): Promise<RouteReply> {\n const endpoint = gitEndpoint(filter, method, target.path, target.query);\n if (\"refused\" in endpoint) return refusal(403, endpoint.refused);\n const unauthorized = gitCredentialRefusal(headers.authorization, this.sentinels[route.route] ?? \"\");\n if (unauthorized !== undefined) return unauthorized;\n let forwarded = body;\n if (endpoint.service === \"git-receive-pack\" && endpoint.phase === \"rpc\") {\n const encoding = headers[\"content-encoding\"];\n if (encoding !== undefined && encoding !== \"identity\") return refusal(403, \"git_encoded_push\");\n const checked = await this.checkPush(body, filter);\n if (\"refused\" in checked) return refusal(403, checked.refused);\n forwarded = checked.body;\n }\n const secret = await route.secret().catch(() => \"\");\n if (secret === \"\" || INVALID_HEADER_VALUE.test(secret)) return refusal(502, \"secret_unavailable\");\n const outgoing = this.outgoingHeaders(headers, route, basicHeader(filter.username, secret));\n return this.forward(route, method, `${target.path}${target.query}`, outgoing, forwarded, signal);\n }\n\n /**\n * Reads a push's command list and checks it, then hands back a body that starts with what was read. `PushReader`\n * reads each chunk once, so the check is linear in the bytes however small the chunks. The check gives up once the\n * body is idle for the idle timeout, which each chunk resets, or once `pushCheckTimeoutMs` has passed since it\n * started, which nothing resets.\n */\n private checkPush(\n body: import(\"node:stream\").Readable | Uint8Array | undefined,\n filter: GitRouteFilter,\n ): Promise<{ readonly refused: string } | { readonly body: import(\"node:stream\").Readable | Uint8Array }> {\n if (body === undefined) return Promise.resolve({ refused: \"git_bad_pkt_line\" });\n if (body instanceof Uint8Array) {\n const verdict = pushVerdict(body, filter, true);\n return Promise.resolve(verdict === \"allowed\" ? { body } : { refused: (verdict as { refused: string }).refused });\n }\n return new Promise((resolve) => {\n const reader = new PushReader(filter);\n const chunks: Uint8Array[] = [];\n const timedOut = () => settle({ refused: \"git_timeout\" });\n // An idle timeout of 0 is off, so only the deadline ends a quiet body.\n const startIdle = () => (this.idleMs === 0 ? undefined : setTimeout(timedOut, this.idleMs));\n let idle = startIdle();\n const deadline = setTimeout(timedOut, this.pushCheckMs);\n const settle = (outcome: { refused: string } | { body: import(\"node:stream\").Readable }) => {\n clearTimeout(idle);\n clearTimeout(deadline);\n body.off(\"data\", onData);\n body.off(\"end\", onEnd);\n body.off(\"error\", onError);\n body.off(\"close\", onError);\n // A refused body is not read further; the answer closes its connection.\n if (\"refused\" in outcome) body.pause();\n resolve(outcome);\n };\n const judge = (verdict: ReturnType<PushReader[\"add\"]>, ended: boolean) => {\n if (verdict === \"incomplete\") return;\n if (verdict !== \"allowed\") {\n settle(verdict);\n return;\n }\n const rest = new this.modules.stream.PassThrough();\n for (const chunk of chunks) rest.write(chunk);\n settle({ body: rest });\n if (ended) rest.end();\n else body.pipe(rest);\n };\n const onData = (chunk: Uint8Array) => {\n clearTimeout(idle);\n idle = startIdle();\n chunks.push(chunk);\n judge(reader.add(chunk), false);\n };\n const onEnd = () => judge(reader.end(), true);\n const onError = () => settle({ refused: \"request_failed\" });\n body.on(\"data\", onData);\n body.once(\"end\", onEnd);\n body.once(\"error\", onError);\n // A client that goes away before its command list ends would otherwise hold the check until a timeout.\n body.once(\"close\", onError);\n });\n }\n\n private outgoingHeaders(\n headers: Record<string, string | string[] | undefined>,\n route: ParsedRoute,\n credential: string,\n ): Record<string, string | string[]> {\n const out: Record<string, string | string[]> = {};\n for (const [name, value] of Object.entries(headers)) {\n if (value !== undefined && !HOP_BY_HOP.has(name)) out[name] = value;\n }\n out[route.header] = credential;\n out.host = route.port === 443 ? route.hostname : `${route.hostname}:${route.port}`;\n return out;\n }\n\n private forward(\n route: ParsedRoute,\n method: string,\n path: string,\n headers: Record<string, string | string[]>,\n body: import(\"node:stream\").Readable | Uint8Array | undefined,\n signal?: AbortSignal,\n ): Promise<RouteReply> {\n return new Promise((resolve) => {\n let upstream: import(\"node:http\").ClientRequest;\n try {\n upstream = this.openRoute(route, method, path, headers);\n } catch {\n resolve(refusal(502, \"request_invalid\"));\n return;\n }\n const stop = () => upstream.destroy(new Error(\"client gone\"));\n if (signal?.aborted === true) stop();\n else signal?.addEventListener(\"abort\", stop, { once: true });\n upstream.once(\"close\", () => signal?.removeEventListener(\"abort\", stop));\n this.requests.add(upstream);\n upstream.setTimeout(this.idleMs, () => upstream.destroy(new Error(\"idle\")));\n upstream.once(\"close\", () => this.requests.delete(upstream));\n upstream.once(\"response\", (reply) => {\n const passed: Record<string, string | string[]> = {};\n for (const [name, value] of Object.entries(reply.headers)) {\n if (value !== undefined && !HOP_BY_HOP.has(name)) passed[name] = value;\n }\n resolve({ status: reply.statusCode ?? 502, headers: passed, body: reply });\n });\n upstream.once(\"error\", (error) => resolve(refusal(502, this.reasonOf(error))));\n if (body === undefined) upstream.end();\n else if (body instanceof Uint8Array) upstream.end(body);\n else body.pipe(upstream);\n });\n }\n\n /** Opens the HTTPS request to a route's host, which throws for a header or path Node refuses. */\n private openRoute(\n route: ParsedRoute,\n method: string,\n path: string,\n headers: Record<string, string | string[]>,\n ): import(\"node:http\").ClientRequest {\n return this.modules.https.request({\n host: route.hostname,\n port: route.port,\n servername: route.hostname,\n method,\n path,\n headers,\n agent: false,\n lookup: this.checkedLookup as never,\n ...(this.options.ca === undefined ? {} : { ca: this.options.ca as never }),\n });\n }\n\n /** An in-process fetch under the same allowlist, with the same address checks and pinned connection. */\n async fetch(input: string | URL, init?: RequestInit): Promise<Response> {\n const request = new Request(input, init);\n request.signal.throwIfAborted();\n const url = new URL(request.url);\n const host = url.hostname.toLowerCase().replace(/\\.$/, \"\");\n const port = url.port === \"\" ? 443 : Number(url.port);\n const bodyBytes =\n request.method === \"GET\" || request.method === \"HEAD\" ? undefined : new Uint8Array(await request.arrayBuffer());\n if (url.origin === ROUTE_ORIGIN || (this.origin !== \"\" && url.origin === this.origin)) {\n return this.fetchRoute(request, url, bodyBytes);\n }\n const refuse = (reason: string): never => {\n this.record({ kind: \"fetch\", host, port, method: request.method, status: 403, bytes: 0, reason });\n throw new HarnessError(\"egress_denied\", `the egress proxy refused ${url.host}: ${reason}`);\n };\n if (url.protocol !== \"https:\") return refuse(\"only_https\");\n if (isAddressLiteral(host)) return refuse(\"address_literal\");\n if (!isAllowed(this.allow, host, port)) return refuse(\"not_allowed\");\n return this.sendFetch(request, url, host, port, bodyBytes);\n }\n\n private async fetchRoute(request: Request, url: URL, body: Uint8Array | undefined): Promise<Response> {\n const headers: Record<string, string> = {};\n request.headers.forEach((value, name) => {\n headers[name.toLowerCase()] = value;\n });\n const path = `${url.pathname}${url.search}`;\n const { reply, base } = await this.routeRequest(request.method, path, headers, body, request.signal);\n const stream = reply.body;\n let bytes = 0;\n stream?.on(\"data\", (chunk: Buffer) => {\n bytes += chunk.length;\n });\n // A status `Response` refuses is recorded with its reason, as the fetch records one.\n const reason = reply.status < 200 || reply.status > 599 ? \"bad_status\" : reply.reason;\n const finished = () =>\n this.record({\n ...base,\n status: reply.status,\n bytes,\n ...(reason === undefined ? {} : { reason }),\n });\n if (stream === undefined) finished();\n else stream.once(\"close\", finished);\n return this.toResponse(reply.status, reply.headers, stream);\n }\n\n private sendFetch(\n request: Request,\n url: URL,\n host: string,\n port: number,\n body: Uint8Array | undefined,\n ): Promise<Response> {\n return new Promise((resolve, reject) => {\n const headers: Record<string, string> = {};\n request.headers.forEach((value, name) => {\n if (!HOP_BY_HOP.has(name.toLowerCase())) headers[name] = value;\n });\n const upstream = this.modules.https.request({\n host,\n port,\n servername: host,\n method: request.method,\n path: `${url.pathname}${url.search}`,\n headers: { ...headers, host: url.host },\n agent: false,\n lookup: this.checkedLookup as never,\n ...(this.options.ca === undefined ? {} : { ca: this.options.ca as never }),\n });\n this.requests.add(upstream);\n const abort = () => upstream.destroy(request.signal.reason as Error);\n request.signal.addEventListener(\"abort\", abort, { once: true });\n upstream.once(\"close\", () => {\n this.requests.delete(upstream);\n request.signal.removeEventListener(\"abort\", abort);\n });\n upstream.setTimeout(this.idleMs, () => upstream.destroy(new Error(\"idle\")));\n // Once an answer has begun, its record is written when the answer closes, so a socket error after it, such as a\n // 204 with bytes after it, writes no second record.\n let answered = false;\n upstream.once(\"response\", (reply) => {\n answered = true;\n let bytes = 0;\n let reason: string | undefined;\n reply.on(\"data\", (chunk: Buffer) => {\n bytes += chunk.length;\n });\n // The record is written when the response is done with, which also covers one that is never read to its end.\n reply.once(\"close\", () =>\n this.record({\n kind: \"fetch\",\n host,\n port,\n method: request.method,\n status: reply.statusCode ?? 0,\n bytes,\n ...(reason === undefined ? {} : { reason }),\n }),\n );\n // A throw here would escape the event handler and end the process, so a status `Response` refuses rejects.\n try {\n resolve(this.toResponse(reply.statusCode ?? 0, reply.headers as Record<string, string | string[]>, reply));\n } catch (error) {\n reason = \"bad_status\";\n reject(error);\n }\n });\n upstream.once(\"error\", (error) => {\n if (answered) return;\n if (request.signal.aborted) {\n reject(request.signal.reason);\n return;\n }\n const reason = this.reasonOf(error);\n this.record({ kind: \"fetch\", host, port, method: request.method, status: 502, bytes: 0, reason });\n reject(\n new HarnessError(\"egress_denied\", `the egress proxy could not reach ${url.host}: ${reason}`, {\n cause: error,\n }),\n );\n });\n upstream.end(body);\n });\n }\n\n private toResponse(\n status: number,\n headers: Record<string, string | string[]>,\n stream: import(\"node:stream\").Readable | undefined,\n ): Response {\n // Node parses any three-digit status, and `Response` takes only 200 to 599, so any other is refused here and its\n // upstream reply is destroyed, so its socket closes.\n if (status < 200 || status > 599) {\n stream?.destroy();\n throw new HarnessError(\n \"egress_denied\",\n `the upstream answered with status ${status}, which HTTP does not define`,\n );\n }\n const out = new Headers();\n for (const [name, value] of Object.entries(headers)) {\n for (const one of Array.isArray(value) ? value : [value]) out.append(name, one);\n }\n const bodiless = stream === undefined || [204, 205, 304].includes(status);\n // A response with no body is drained, so its socket and its log record don't wait for a reader that never comes.\n if (bodiless) stream?.resume();\n const web = bodiless ? null : (this.modules.stream.Readable.toWeb(stream) as ReadableStream);\n return new Response(web, { status, headers: out });\n }\n\n async knownSecrets(): Promise<readonly string[]> {\n const secrets = await Promise.all([...this.routes.values()].map((route) => route.secret().catch(() => \"\")));\n return [...new Set(secrets.filter((secret) => secret !== \"\"))];\n }\n\n close(server: import(\"node:http\").Server): Promise<void> {\n return new Promise((resolve) => {\n for (const socket of this.sockets) socket.destroy();\n for (const request of this.requests) request.destroy();\n server.close(() => resolve());\n server.closeAllConnections();\n });\n }\n}\n\n/**\n * Starts the egress proxy on `127.0.0.1` with a port the system picks, or on `socketPath`. The allowlist and routes are\n * checked first, and a bad entry throws `invalid_egress_options`. Give the sandbox `proxy.url` as `HTTPS_PROXY`, and\n * give a tool that needs a credential the route's URL and its sentinel.\n */\nexport async function startEgressProxy(options: EgressProxyOptions): Promise<EgressProxy> {\n const modules = nodeModules();\n const proxy = new EgressGate(modules, options);\n const server = modules.http.createServer((request, response) => proxy.handleRequest(request, response));\n server.on(\"connect\", (request, socket, head) => proxy.handleConnect(request, socket as never, head));\n server.on(\"clientError\", (_error, socket) => socket.destroy());\n await new Promise<void>((resolve, reject) => {\n server.once(\"error\", reject);\n if (options.socketPath === undefined) server.listen(0, \"127.0.0.1\", resolve);\n else server.listen(options.socketPath, resolve);\n });\n const address = server.address();\n const url =\n options.socketPath !== undefined\n ? `unix:${options.socketPath}`\n : `http://127.0.0.1:${(address as { port: number }).port}`;\n if (options.socketPath === undefined) proxy.setOrigin(url);\n return {\n url,\n ...(options.socketPath === undefined ? {} : { socketPath: options.socketPath }),\n sentinels: proxy.sentinelMap(),\n fetch: (input, init) => proxy.fetch(input, init),\n knownSecrets: () => proxy.knownSecrets(),\n close: () => proxy.close(server),\n };\n}\n"]}
package/dist/errors.d.ts CHANGED
@@ -4,7 +4,7 @@
4
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" | "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_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
@@ -34,9 +34,12 @@ export type HarnessErrorCode = "sandbox_unavailable" | "sandbox_denied" | "sandb
34
34
  * `approval_unavailable`: the harness has no signer, so no approval can be checked. `sticky_refused`: a sticky
35
35
  * allowance would cover an interpreter prefix or a secret. `approval_reuse_refused`: the tool's `approvalReuse` forbids
36
36
  * a sticky or grouped answer. `approver_is_requester`: the approver is the one who asked. `approval_refused`: a code
37
- * 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.
38
39
  * `invalid_code_call`: `Harness.invokeTool()` or a code call's resolution was given something it can't run, such as a
39
- * 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
40
43
  * file or key secret is unreadable or malformed, or a key file is readable by others. `key_store_read_only`: a key store
41
44
  * with no `rotate()` or `prune()` was asked to rotate or prune. `session_conflict`: an append found the log in a state it did
42
45
  * not expect (`ConflictError`). `entry_too_large`: an entry is over the store's size bound (`EntryTooLargeError`).
package/dist/errors.js CHANGED
@@ -34,9 +34,12 @@ const HARNESS_ERROR = Symbol.for("buildanagent.harness.HarnessError");
34
34
  * `approval_unavailable`: the harness has no signer, so no approval can be checked. `sticky_refused`: a sticky
35
35
  * allowance would cover an interpreter prefix or a secret. `approval_reuse_refused`: the tool's `approvalReuse` forbids
36
36
  * a sticky or grouped answer. `approver_is_requester`: the approver is the one who asked. `approval_refused`: a code
37
- * 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.
38
39
  * `invalid_code_call`: `Harness.invokeTool()` or a code call's resolution was given something it can't run, such as a
39
- * 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
40
43
  * file or key secret is unreadable or malformed, or a key file is readable by others. `key_store_read_only`: a key store
41
44
  * with no `rotate()` or `prune()` was asked to rotate or prune. `session_conflict`: an append found the log in a state it did
42
45
  * not expect (`ConflictError`). `entry_too_large`: an entry is over the store's size bound (`EntryTooLargeError`).
@@ -1 +1 @@
1
- {"version":3,"file":"errors.js","sourceRoot":"","sources":["../src/errors.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAqDH,4FAA4F;AAC5F,MAAM,aAAa,GAAG,MAAM,CAAC,GAAG,CAAC,mCAAmC,CAAC,CAAC;AAEtE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA6CG;AACH,MAAM,OAAO,YAAa,SAAQ,KAAK;IACnB,IAAI,GAAW,cAAc,CAAC;IACvC,IAAI,CAAmB;IAEhC,YAAY,IAAsB,EAAE,OAAe,EAAE,OAAsB;QACzE,KAAK,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;QACxB,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;QACjB,MAAM,CAAC,cAAc,CAAC,IAAI,EAAE,aAAa,EAAE,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC,CAAC;IAC9D,CAAC;CACF;AAED,iFAAiF;AACjF,MAAM,UAAU,cAAc,CAAC,KAAc;IAC3C,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI,IAAK,KAAiC,CAAC,aAAa,CAAC,KAAK,IAAI,CAAC;AACnH,CAAC","sourcesContent":["/**\n * `HarnessError`: the harness's error for programmer errors and for a sandbox that can't do what it was asked. Four\n * subclasses keep their own names for the cases callers catch by class: `SandboxUnavailableError`,\n * `SandboxDeniedError`, `SandboxPolicyMismatchError` and `SandboxUnsupportedError`, all in `./sandbox`.\n */\n\n/** Why a `HarnessError` was thrown. */\nexport type HarnessErrorCode =\n | \"sandbox_unavailable\"\n | \"sandbox_denied\"\n | \"sandbox_disposed\"\n | \"sandbox_not_found\"\n | \"sandbox_io_failed\"\n | \"sandbox_policy_mismatch\"\n | \"sandbox_unsupported\"\n | \"egress_denied\"\n | \"invalid_egress_options\"\n | \"unsafe_sandbox_not_acknowledged\"\n | \"invalid_sandbox_options\"\n | \"invalid_spawn_env\"\n | \"duplicate_tool\"\n | \"invalid_tool_registration\"\n | \"invalid_tool_options\"\n | \"invalid_permission_config\"\n | \"invalid_lock_options\"\n | \"session_locked\"\n | \"session_read_only\"\n | \"entry_not_found\"\n | \"unsupported_format\"\n | \"invalid_turn_options\"\n | \"invalid_context_options\"\n | \"invalid_dispatcher_options\"\n | \"invalid_transport_options\"\n | \"spill_unavailable\"\n | \"invalid_extension\"\n | \"extension_hash_mismatch\"\n | \"approval_not_pending\"\n | \"approval_unavailable\"\n | \"sticky_refused\"\n | \"approval_reuse_refused\"\n | \"approver_is_requester\"\n | \"approval_refused\"\n | \"invalid_code_call\"\n | \"invalid_key_store\"\n | \"key_store_read_only\"\n | \"session_conflict\"\n | \"entry_too_large\"\n | \"invalid_session_entry\"\n | \"invalid_session_key\"\n | \"invalid_retention\"\n | \"session_corrupt\"\n | \"invalid_completion_config\"\n | \"invalid_mcp_config\"\n | \"mcp_connect_failed\"\n | \"mcp_tool_list_refused\"\n | \"mcp_call_failed\";\n\n// A registered symbol, so the guard still works when two copies of the package are bundled.\nconst HARNESS_ERROR = Symbol.for(\"buildanagent.harness.HarnessError\");\n\n/**\n * Thrown for a mistake in how the harness is called, and for a sandbox that is unavailable or refuses a file operation.\n * `sandbox_unavailable`: a backend can't start (`SandboxUnavailableError`). `sandbox_denied`: the policy refused a file\n * read or write (`SandboxDeniedError`). `sandbox_disposed`: the sandbox was disposed before the call.\n * `sandbox_not_found`: a file to read doesn't exist. `sandbox_io_failed`: a file call failed for a reason that is\n * neither a missing file nor a denial. `sandbox_policy_mismatch`: the policy a backend read back after it provisioned or\n * resumed a sandbox differs from the one requested (`SandboxPolicyMismatchError`). `sandbox_unsupported`: a sandbox was\n * asked to resume, snapshot or pause on a backend that lacks the capability (`SandboxUnsupportedError`).\n * `unsafe_sandbox_not_acknowledged`: `noneSandbox()` was called without `unsafe:\n * true`. `invalid_sandbox_options`: a sandbox option, manifest or command is unusable. `invalid_spawn_env`:\n * `spawnEnv()` was given a name or value that can't be part of a clean environment. `duplicate_tool`: a tool registry\n * already holds a tool or alias by that name (`DuplicateToolError`). `invalid_tool_registration`: a tool registration\n * or a registry option is unusable, such as a name that breaks the canonical rule or an unknown source.\n * `invalid_tool_options`: the built-in tools were given a workspace root or a policy root that is not an absolute path.\n * `invalid_permission_config`: an allow rule makes the host callback unreachable (`PermissionConfigError`).\n * `invalid_lock_options`: a file lock was given a lease, renewal interval or host name it can't use. `session_locked`:\n * another writer holds the session. `session_read_only`: a session opened without a lock was asked to write.\n * `entry_not_found`: an entry id is in no file of the session. `unsupported_format`: a session file's format can't be\n * read or migrated, its header names none, or the store can't read it as written. `invalid_turn_options`: a turn's\n * options can't be used, such as a tool allowlist that names a tool the registry lacks, or a hook that changed the\n * model inside a turn.\n * `invalid_context_options`: a context policy's setting can't be used, such as a write cap with no spill store or a mask\n * step of zero. `invalid_dispatcher_options`: a dispatcher's setting can't be used, such as a queue size of zero.\n * `invalid_transport_options`: a transport's setting can't be used, such as a write timeout of zero.\n * `spill_unavailable`: a spill store can't write, such as the file store on a runtime without Node's file\n * system. `invalid_extension`: an extension has no name or version, two share a name, or a project extension's module does not export one. `extension_hash_mismatch`: a project extension's files hash differently from the lock file, or the lock file does not list it. `approval_not_pending`: a resolution names a request that is not waiting.\n * `approval_unavailable`: the harness has no signer, so no approval can be checked. `sticky_refused`: a sticky\n * allowance would cover an interpreter prefix or a secret. `approval_reuse_refused`: the tool's `approvalReuse` forbids\n * a sticky or grouped answer. `approver_is_requester`: the approver is the one who asked. `approval_refused`: a code\n * call's signed request failed its check when it was resolved, so nothing ran and nothing was written.\n * `invalid_code_call`: `Harness.invokeTool()` or a code call's resolution was given something it can't run, such as a\n * tool the registry lacks or a compensation that names no call that ran. `invalid_key_store`: a key\n * file or key secret is unreadable or malformed, or a key file is readable by others. `key_store_read_only`: a key store\n * with no `rotate()` or `prune()` was asked to rotate or prune. `session_conflict`: an append found the log in a state it did\n * not expect (`ConflictError`). `entry_too_large`: an entry is over the store's size bound (`EntryTooLargeError`).\n * `invalid_session_entry`: an entry is not valid or is out of place, such as a first entry that is not a header.\n * `invalid_session_key`: a user or session id the store can't use. `invalid_retention`: a retention period that is not a\n * positive number, or an action other than `archive` and `purge`. `session_corrupt`: a log file has a bad line before\n * its last line. `invalid_completion_config`: `.agents/harness.json` is not JSON, or its `completionChecks` is not a list\n * of commands. `invalid_mcp_config`: an MCP server's configuration can't be used, such as a name outside the allowed\n * characters or two servers with one name. `mcp_connect_failed`: an MCP server did not start, did not finish the\n * handshake in time, or closed before it did (`McpError`). `mcp_tool_list_refused`: an MCP server listed tools the\n * harness refuses, such as two with one name, so none of its tools was registered (`McpError`). `mcp_call_failed`: an\n * MCP tool call ended without a result, because the server closed, timed out, asked for input or answered with an\n * error (`McpError`).\n */\nexport class HarnessError extends Error {\n override readonly name: string = \"HarnessError\";\n readonly code: HarnessErrorCode;\n\n constructor(code: HarnessErrorCode, message: string, options?: ErrorOptions) {\n super(message, options);\n this.code = code;\n Object.defineProperty(this, HARNESS_ERROR, { value: true });\n }\n}\n\n/** True for a `HarnessError`, including one from another copy of the package. */\nexport function isHarnessError(error: unknown): error is HarnessError {\n return typeof error === \"object\" && error !== null && (error as Record<symbol, unknown>)[HARNESS_ERROR] === true;\n}\n"]}
1
+ {"version":3,"file":"errors.js","sourceRoot":"","sources":["../src/errors.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAsDH,4FAA4F;AAC5F,MAAM,aAAa,GAAG,MAAM,CAAC,GAAG,CAAC,mCAAmC,CAAC,CAAC;AAEtE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAgDG;AACH,MAAM,OAAO,YAAa,SAAQ,KAAK;IACnB,IAAI,GAAW,cAAc,CAAC;IACvC,IAAI,CAAmB;IAEhC,YAAY,IAAsB,EAAE,OAAe,EAAE,OAAsB;QACzE,KAAK,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;QACxB,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;QACjB,MAAM,CAAC,cAAc,CAAC,IAAI,EAAE,aAAa,EAAE,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC,CAAC;IAC9D,CAAC;CACF;AAED,iFAAiF;AACjF,MAAM,UAAU,cAAc,CAAC,KAAc;IAC3C,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI,IAAK,KAAiC,CAAC,aAAa,CAAC,KAAK,IAAI,CAAC;AACnH,CAAC","sourcesContent":["/**\n * `HarnessError`: the harness's error for programmer errors and for a sandbox that can't do what it was asked. Four\n * subclasses keep their own names for the cases callers catch by class: `SandboxUnavailableError`,\n * `SandboxDeniedError`, `SandboxPolicyMismatchError` and `SandboxUnsupportedError`, all in `./sandbox`.\n */\n\n/** Why a `HarnessError` was thrown. */\nexport type HarnessErrorCode =\n | \"sandbox_unavailable\"\n | \"sandbox_denied\"\n | \"sandbox_disposed\"\n | \"sandbox_not_found\"\n | \"sandbox_io_failed\"\n | \"sandbox_policy_mismatch\"\n | \"sandbox_unsupported\"\n | \"egress_denied\"\n | \"invalid_egress_options\"\n | \"unsafe_sandbox_not_acknowledged\"\n | \"invalid_sandbox_options\"\n | \"invalid_spawn_env\"\n | \"duplicate_tool\"\n | \"invalid_tool_registration\"\n | \"invalid_tool_options\"\n | \"invalid_permission_config\"\n | \"invalid_lock_options\"\n | \"session_locked\"\n | \"session_read_only\"\n | \"entry_not_found\"\n | \"unsupported_format\"\n | \"invalid_turn_options\"\n | \"invalid_context_options\"\n | \"invalid_dispatcher_options\"\n | \"invalid_transport_options\"\n | \"spill_unavailable\"\n | \"invalid_extension\"\n | \"extension_hash_mismatch\"\n | \"approval_not_pending\"\n | \"approval_unavailable\"\n | \"sticky_refused\"\n | \"approval_reuse_refused\"\n | \"approver_is_requester\"\n | \"approval_refused\"\n | \"invalid_code_call\"\n | \"invalid_escalation\"\n | \"invalid_key_store\"\n | \"key_store_read_only\"\n | \"session_conflict\"\n | \"entry_too_large\"\n | \"invalid_session_entry\"\n | \"invalid_session_key\"\n | \"invalid_retention\"\n | \"session_corrupt\"\n | \"invalid_completion_config\"\n | \"invalid_mcp_config\"\n | \"mcp_connect_failed\"\n | \"mcp_tool_list_refused\"\n | \"mcp_call_failed\";\n\n// A registered symbol, so the guard still works when two copies of the package are bundled.\nconst HARNESS_ERROR = Symbol.for(\"buildanagent.harness.HarnessError\");\n\n/**\n * Thrown for a mistake in how the harness is called, and for a sandbox that is unavailable or refuses a file operation.\n * `sandbox_unavailable`: a backend can't start (`SandboxUnavailableError`). `sandbox_denied`: the policy refused a file\n * read or write (`SandboxDeniedError`). `sandbox_disposed`: the sandbox was disposed before the call.\n * `sandbox_not_found`: a file to read doesn't exist. `sandbox_io_failed`: a file call failed for a reason that is\n * neither a missing file nor a denial. `sandbox_policy_mismatch`: the policy a backend read back after it provisioned or\n * resumed a sandbox differs from the one requested (`SandboxPolicyMismatchError`). `sandbox_unsupported`: a sandbox was\n * asked to resume, snapshot or pause on a backend that lacks the capability (`SandboxUnsupportedError`).\n * `unsafe_sandbox_not_acknowledged`: `noneSandbox()` was called without `unsafe:\n * true`. `invalid_sandbox_options`: a sandbox option, manifest or command is unusable. `invalid_spawn_env`:\n * `spawnEnv()` was given a name or value that can't be part of a clean environment. `duplicate_tool`: a tool registry\n * already holds a tool or alias by that name (`DuplicateToolError`). `invalid_tool_registration`: a tool registration\n * or a registry option is unusable, such as a name that breaks the canonical rule or an unknown source.\n * `invalid_tool_options`: the built-in tools were given a workspace root or a policy root that is not an absolute path.\n * `invalid_permission_config`: an allow rule makes the host callback unreachable (`PermissionConfigError`).\n * `invalid_lock_options`: a file lock was given a lease, renewal interval or host name it can't use. `session_locked`:\n * another writer holds the session. `session_read_only`: a session opened without a lock was asked to write.\n * `entry_not_found`: an entry id is in no file of the session. `unsupported_format`: a session file's format can't be\n * read or migrated, its header names none, or the store can't read it as written. `invalid_turn_options`: a turn's\n * options can't be used, such as a tool allowlist that names a tool the registry lacks, or a hook that changed the\n * model inside a turn.\n * `invalid_context_options`: a context policy's setting can't be used, such as a write cap with no spill store or a mask\n * step of zero. `invalid_dispatcher_options`: a dispatcher's setting can't be used, such as a queue size of zero.\n * `invalid_transport_options`: a transport's setting can't be used, such as a write timeout of zero.\n * `spill_unavailable`: a spill store can't write, such as the file store on a runtime without Node's file\n * system. `invalid_extension`: an extension has no name or version, two share a name, or a project extension's module does not export one. `extension_hash_mismatch`: a project extension's files hash differently from the lock file, or the lock file does not list it. `approval_not_pending`: a resolution names a request that is not waiting.\n * `approval_unavailable`: the harness has no signer, so no approval can be checked. `sticky_refused`: a sticky\n * allowance would cover an interpreter prefix or a secret. `approval_reuse_refused`: the tool's `approvalReuse` forbids\n * a sticky or grouped answer. `approver_is_requester`: the approver is the one who asked. `approval_refused`: a code\n * call's or a sandbox escalation's signed request failed its check when it was resolved, or a classifier tried to\n * approve an escalation, so nothing ran and nothing was written.\n * `invalid_code_call`: `Harness.invokeTool()` or a code call's resolution was given something it can't run, such as a\n * tool the registry lacks or a compensation that names no call that ran. `invalid_escalation`: `escalation()` or one\n * of its calls was given something it can't use, such as a granular policy with no rules, or an edge the escalation\n * table does not list. `invalid_key_store`: a key\n * file or key secret is unreadable or malformed, or a key file is readable by others. `key_store_read_only`: a key store\n * with no `rotate()` or `prune()` was asked to rotate or prune. `session_conflict`: an append found the log in a state it did\n * not expect (`ConflictError`). `entry_too_large`: an entry is over the store's size bound (`EntryTooLargeError`).\n * `invalid_session_entry`: an entry is not valid or is out of place, such as a first entry that is not a header.\n * `invalid_session_key`: a user or session id the store can't use. `invalid_retention`: a retention period that is not a\n * positive number, or an action other than `archive` and `purge`. `session_corrupt`: a log file has a bad line before\n * its last line. `invalid_completion_config`: `.agents/harness.json` is not JSON, or its `completionChecks` is not a list\n * of commands. `invalid_mcp_config`: an MCP server's configuration can't be used, such as a name outside the allowed\n * characters or two servers with one name. `mcp_connect_failed`: an MCP server did not start, did not finish the\n * handshake in time, or closed before it did (`McpError`). `mcp_tool_list_refused`: an MCP server listed tools the\n * harness refuses, such as two with one name, so none of its tools was registered (`McpError`). `mcp_call_failed`: an\n * MCP tool call ended without a result, because the server closed, timed out, asked for input or answered with an\n * error (`McpError`).\n */\nexport class HarnessError extends Error {\n override readonly name: string = \"HarnessError\";\n readonly code: HarnessErrorCode;\n\n constructor(code: HarnessErrorCode, message: string, options?: ErrorOptions) {\n super(message, options);\n this.code = code;\n Object.defineProperty(this, HARNESS_ERROR, { value: true });\n }\n}\n\n/** True for a `HarnessError`, including one from another copy of the package. */\nexport function isHarnessError(error: unknown): error is HarnessError {\n return typeof error === \"object\" && error !== null && (error as Record<symbol, unknown>)[HARNESS_ERROR] === true;\n}\n"]}
@@ -160,8 +160,11 @@ export async function loadProjectExtensions(root, options) {
160
160
  const pins = await readLock(lock);
161
161
  if (names.length === 0 && (pins === undefined || pins.size === 0))
162
162
  return result;
163
- if (pins === undefined)
164
- result.notices.push(`the extensions of ${base} are not pinned: there is no ${lock}`);
163
+ if (pins === undefined) {
164
+ // A lock file may hold MCP tool pins alone, and then it pins no extension.
165
+ const why = (await exists(lock)) ? `${lock} holds no extension pins` : `there is no ${lock}`;
166
+ result.notices.push(`the extensions of ${base} are not pinned: ${why}`);
167
+ }
165
168
  const hashes = await checkedHashes(dir, names, pins);
166
169
  const seen = new Set();
167
170
  for (const name of names) {
@@ -1 +1 @@
1
- {"version":3,"file":"load.js","sourceRoot":"","sources":["../../src/extensions/load.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,O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BAAyB,EAAE,kBAAkB,IAAI,iBAAiB,GAAG,EAAE,CAAC,CAAC;IAClG,CAAC;IACD,OAAO,MAAM,CAAC;AAChB,CAAC;AAED,mHAAmH;AACnH,MAAM,CAAC,KAAK,UAAU,oBAAoB,CACxC,IAAY,EACZ,OAAO,GAAoD,EAAE;IAE7D,MAAM,EAAE,GAAG,EAAE,IAAI,EAAE,GAAG,MAAM,MAAM,CAAC,MAAM,aAAa,CAAC,IAAI,CAAC,EAAE,OAAO,CAAC,CAAC;IACvE,MAAM,IAAI,GAAG,IAAI,GAAG,EAAkB,CAAC;IACvC,KAAK,MAAM,IAAI,IAAI,MAAM,OAAO,CAAC,GAAG,CAAC;QAAE,IAAI,CAAC,GAAG,CAAC,IAAI,EAAE,MAAM,gBAAgB,CAAC,IAAI,CAAC,GAAG,EAAE,IAAI,CAAC,CAAC,CAAC,CAAC;IAC/F,MAAM,SAAS,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC;IAC5B,OAAO,IAAI,CAAC;AACd,CAAC","sourcesContent":["/**\n * Loading the extensions a project supplies. A project's extensions live in `.agents/extensions/<folder>/`, each with an\n * `index.mjs` or `index.js` whose default export is an `Extension`, or a function returning one. They load only when the\n * project is trusted and the run is not headless, and only when every folder's hash matches the lock file. Trust gates\n * loading, not execution: an extension that loads runs with the harness's own permissions. Node-only.\n */\nimport { access, lstat, readdir, realpath } from \"node:fs/promises\";\nimport { join, resolve } from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\nimport { HarnessError } from \"../errors.js\";\nimport { hashExtensionDir, readLock, writeLock } from \"./lock.js\";\nimport type { Extension, ExtensionLoadedRecord, TrustStore } from \"./types.js\";\n\n/** What `loadProjectExtensions()` needs to decide. */\nexport interface LoadOptions {\n readonly trust: TrustStore;\n /** True for a run nobody can answer: project extensions are skipped unless `loadInHeadless` is set. */\n readonly headless: boolean;\n /** Lets a headless run load the extensions of a project the trust store already trusts. Default false. */\n readonly loadInHeadless?: boolean;\n /** The lock file. Default `<root>/.agents/extensions.lock.json`. */\n readonly lockFile?: string;\n /** The folder that holds the extensions. Default `<root>/.agents/extensions`. */\n readonly extensionsDir?: string;\n}\n\n/** The extensions a project supplied, what to record about them, and why any were skipped. */\nexport interface ProjectExtensions {\n readonly extensions: Extension[];\n readonly records: ExtensionLoadedRecord[];\n /** One line for each reason the load was skipped or left unpinned, for the caller to show. */\n readonly notices: string[];\n}\n\n/** The path with symlinks resolved, so a symlinked root and its target are one project to the trust store. */\nexport async function canonicalPath(path: string): Promise<string> {\n try {\n return await realpath(resolve(path));\n } catch {\n return resolve(path);\n }\n}\n\n/**\n * Whether the trust store trusts the project at `root`, asked about its real path only. A link that the store trusted\n * can be pointed at another folder later, so the spelling the caller wrote is never what is trusted: the folder it\n * resolves to now is. Every loader asks through this, so the extensions and the skills of a project are trusted alike.\n */\nexport async function projectTrusted(trust: TrustStore, root: string): Promise<boolean> {\n return trust.isTrusted(await canonicalPath(root));\n}\n\nconst places = async (root: string, options: Pick<LoadOptions, \"lockFile\" | \"extensionsDir\">) => ({\n // The folder is canonical, so a relative or symlinked spelling of it is one folder to the import-cache check.\n dir: await canonicalPath(options.extensionsDir ?? join(root, \".agents\", \"extensions\")),\n lock: options.lockFile ?? join(root, \".agents\", \"extensions.lock.json\"),\n});\n\n/** Whether `path` exists, without following a link or reading it. */\nasync function exists(path: string): Promise<boolean> {\n try {\n await lstat(path);\n return true;\n } catch {\n return false;\n }\n}\n\n/** The extension folders under `dir`, by name; none when the folder does not exist. */\nasync function folders(dir: string): Promise<string[]> {\n try {\n const entries = await readdir(dir, { withFileTypes: true });\n // A linked folder is not hashed as the folder it points at, so it cannot be pinned.\n const linked = entries.find((entry) => entry.isSymbolicLink());\n if (linked !== undefined) {\n throw new HarnessError(\n \"invalid_extension\",\n `${join(dir, linked.name)} is a link, which an extension folder may not be`,\n );\n }\n return entries\n .filter((entry) => entry.isDirectory())\n .map((entry) => entry.name)\n .sort();\n } catch (error) {\n const code = (error as { code?: string }).code;\n if (code === \"ENOENT\" || code === \"ENOTDIR\") return [];\n throw error;\n }\n}\n\nasync function entryFile(dir: string): Promise<string> {\n for (const name of [\"index.mjs\", \"index.js\"]) {\n try {\n await access(join(dir, name));\n return join(dir, name);\n } catch {\n // try the next name\n }\n }\n throw new HarnessError(\"invalid_extension\", `the extension folder ${dir} has no index.mjs or index.js`);\n}\n\n// The hash each folder had when this process first imported it. Node caches modules for the life of the process, so a\n// folder that changed since then would run its old code while the log recorded the new hash.\nconst importedHashes = new Map<string, string>();\n\n/** Refuses a folder this process has imported with other files, before any folder of the project is imported. */\nfunction refuseChanged(folder: string, hash: string): void {\n const before = importedHashes.get(folder);\n if (before !== undefined && before !== hash) {\n throw new HarnessError(\n \"extension_hash_mismatch\",\n `the extension in ${folder} changed after this process loaded it; restart the process to load the new files`,\n );\n }\n}\n\nconst isFunction = (value: unknown): boolean => typeof value === \"function\";\n\nconst badShape = (dir: string, why: string) => new HarnessError(\"invalid_extension\", `the extension in ${dir} ${why}`);\n\n/** Throws unless `interceptors` is an object whose hooks are functions, apart from the `onFailure` setting. */\nfunction checkInterceptors(interceptors: unknown, dir: string): void {\n if (interceptors === undefined) return;\n if (typeof interceptors !== \"object\" || interceptors === null) {\n throw badShape(dir, \"has interceptors that are not an object\");\n }\n for (const [name, hook] of Object.entries(interceptors)) {\n if (name !== \"onFailure\" && !isFunction(hook))\n throw badShape(dir, `has an interceptor \"${name}\" that is not a function`);\n }\n}\n\n/** Throws unless `observers` is a list of functions and `tools` a list of `{ name, definition }`. */\nfunction checkLists(observers: unknown, tools: unknown, dir: string): void {\n if (observers !== undefined && !(Array.isArray(observers) && observers.every(isFunction))) {\n throw badShape(dir, \"has observers that are not a list of functions\");\n }\n const wellFormed = (tool: { name?: unknown; definition?: unknown } | null) =>\n typeof tool?.name === \"string\" && typeof tool.definition === \"object\" && tool.definition !== null;\n if (tools !== undefined && !(Array.isArray(tools) && tools.every(wellFormed))) {\n throw badShape(dir, \"has tools that are not a list of { name, definition }\");\n }\n}\n\n/** Throws `invalid_extension` unless the module's export has the shape of an `Extension`. */\nfunction checkShape(extension: Partial<Extension> | undefined, dir: string): asserts extension is Extension {\n if (typeof extension?.name !== \"string\" || typeof extension.version !== \"string\") {\n throw badShape(dir, \"does not export a name and a version\");\n }\n checkInterceptors(extension.interceptors, dir);\n checkLists(extension.observers, extension.tools, dir);\n}\n\nasync function importExtension(dir: string, hash: string): Promise<Extension> {\n const loaded = (await import(/* @vite-ignore */ pathToFileURL(await entryFile(dir)).href)) as { default?: unknown };\n importedHashes.set(await canonicalPath(dir), hash);\n const made = typeof loaded.default === \"function\" ? await (loaded.default as () => unknown)() : loaded.default;\n const extension = made as Partial<Extension> | undefined;\n checkShape(extension, dir);\n return extension;\n}\n\n/** Why a project's extensions are not loaded, or `undefined` when they may be. */\nasync function skipReason(root: string, base: string, options: LoadOptions): Promise<string | undefined> {\n if (options.headless && options.loadInHeadless !== true) {\n return `the project extensions of ${base} are skipped: this run is headless`;\n }\n if (!(await projectTrusted(options.trust, root)))\n return `the project extensions of ${base} are skipped: the project is not trusted`;\n return undefined;\n}\n\n/**\n * Loads the extensions in a project, or skips them with a notice. Every folder is hashed and checked against the lock\n * file before any is imported, so a refusal runs none of the project's code. A folder whose hash differs from the lock\n * file, that the lock file does not list, or that the lock file lists and the project no longer holds is refused with\n * `extension_hash_mismatch`; with no lock file the extensions load and a notice says they are unpinned.\n *\n * The pin covers the files inside each extension folder, and nothing an extension imports from outside it, such as a\n * relative path that leaves the folder or a package from the project's `node_modules`. The lock file sits inside the\n * project it pins, so anyone who can edit the project can pin their own changes: the pin catches a change nobody\n * meant, not an attacker who holds the project.\n */\nexport async function loadProjectExtensions(root: string, options: LoadOptions): Promise<ProjectExtensions> {\n const base = await canonicalPath(root);\n const result: ProjectExtensions = { extensions: [], records: [], notices: [] };\n const { dir, lock } = await places(base, options);\n // Nothing of a project is read, other than whether it has extensions at all, until trust and headless are decided.\n if (!(await exists(dir)) && !(await exists(lock))) return result;\n const reason = await skipReason(root, base, options);\n if (reason !== undefined) {\n result.notices.push(reason);\n return result;\n }\n const names = await folders(dir);\n const pins = await readLock(lock);\n if (names.length === 0 && (pins === undefined || pins.size === 0)) return result;\n if (pins === undefined) result.notices.push(`the extensions of ${base} are not pinned: there is no ${lock}`);\n const hashes = await checkedHashes(dir, names, pins);\n const seen = new Set<string>();\n for (const name of names) {\n const hash = hashes.get(name) as string;\n const extension = await importExtension(join(dir, name), hash);\n if (seen.has(extension.name))\n throw new HarnessError(\"invalid_extension\", `two project extensions are named \"${extension.name}\"`);\n seen.add(extension.name);\n result.extensions.push(extension);\n result.records.push({ name: extension.name, tier: \"in_process\", contentHash: hash });\n }\n return result;\n}\n\n/** The hash of every folder, after checking each against the pins: none of the project's code has run yet. */\nasync function checkedHashes(\n dir: string,\n names: readonly string[],\n pins: ReadonlyMap<string, string> | undefined,\n): Promise<Map<string, string>> {\n const hashes = new Map<string, string>();\n for (const name of names) {\n const hash = await hashExtensionDir(join(dir, name));\n hashes.set(name, hash);\n refuseChanged(await canonicalPath(join(dir, name)), hash);\n }\n if (pins === undefined) return hashes;\n for (const name of pins.keys()) {\n if (!hashes.has(name)) {\n throw new HarnessError(\n \"extension_hash_mismatch\",\n `the extension \"${name}\" is pinned but the project no longer holds it`,\n );\n }\n }\n for (const [name, hash] of hashes) {\n const pinned = pins.get(name);\n if (pinned === hash) continue;\n const why = pinned === undefined ? \"the lock file does not list it\" : \"its files changed since they were pinned\";\n throw new HarnessError(\"extension_hash_mismatch\", `the extension \"${name}\" is refused: ${why}`);\n }\n return hashes;\n}\n\n/** Writes the lock file for every extension folder as it is now. A person runs it, which is what pins the code. */\nexport async function pinProjectExtensions(\n root: string,\n options: Pick<LoadOptions, \"lockFile\" | \"extensionsDir\"> = {},\n): Promise<ReadonlyMap<string, string>> {\n const { dir, lock } = await places(await canonicalPath(root), options);\n const pins = new Map<string, string>();\n for (const name of await folders(dir)) pins.set(name, await hashExtensionDir(join(dir, name)));\n await writeLock(lock, pins);\n return pins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AI,EAAE,IAAI,CAAC,IAAI,MAAM,EAAE,CAAC;QAClC,MAAM,MAAM,GAAG,IAAI,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;QAC9B,IAAI,MAAM,KAAK,IAAI;YAAE,SAAS;QAC9B,MAAM,GAAG,GAAG,MAAM,KAAK,SAAS,CAAC,CAAC,CAAC,gCAAgC,CAAC,CAAC,CAAC,0CAA0C,CAAC;QACjH,MAAM,IAAI,YAAY,CAAC,yBAAyB,EAAE,kBAAkB,IAAI,iBAAiB,GAAG,EAAE,CAAC,CAAC;IAClG,CAAC;IACD,OAAO,MAAM,CAAC;AAChB,CAAC;AAED,mHAAmH;AACnH,MAAM,CAAC,KAAK,UAAU,oBAAoB,CACxC,IAAY,EACZ,OAAO,GAAoD,EAAE;IAE7D,MAAM,EAAE,GAAG,EAAE,IAAI,EAAE,GAAG,MAAM,MAAM,CAAC,MAAM,aAAa,CAAC,IAAI,CAAC,EAAE,OAAO,CAAC,CAAC;IACvE,MAAM,IAAI,GAAG,IAAI,GAAG,EAAkB,CAAC;IACvC,KAAK,MAAM,IAAI,IAAI,MAAM,OAAO,CAAC,GAAG,CAAC;QAAE,IAAI,CAAC,GAAG,CAAC,IAAI,EAAE,MAAM,gBAAgB,CAAC,IAAI,CAAC,GAAG,EAAE,IAAI,CAAC,CAAC,CAAC,CAAC;IAC/F,MAAM,SAAS,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC;IAC5B,OAAO,IAAI,CAAC;AACd,CAAC","sourcesContent":["/**\n * Loading the extensions a project supplies. A project's extensions live in `.agents/extensions/<folder>/`, each with an\n * `index.mjs` or `index.js` whose default export is an `Extension`, or a function returning one. They load only when the\n * project is trusted and the run is not headless, and only when every folder's hash matches the lock file. Trust gates\n * loading, not execution: an extension that loads runs with the harness's own permissions. Node-only.\n */\nimport { access, lstat, readdir, realpath } from \"node:fs/promises\";\nimport { join, resolve } from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\nimport { HarnessError } from \"../errors.js\";\nimport { hashExtensionDir, readLock, writeLock } from \"./lock.js\";\nimport type { Extension, ExtensionLoadedRecord, TrustStore } from \"./types.js\";\n\n/** What `loadProjectExtensions()` needs to decide. */\nexport interface LoadOptions {\n readonly trust: TrustStore;\n /** True for a run nobody can answer: project extensions are skipped unless `loadInHeadless` is set. */\n readonly headless: boolean;\n /** Lets a headless run load the extensions of a project the trust store already trusts. Default false. */\n readonly loadInHeadless?: boolean;\n /** The lock file. Default `<root>/.agents/extensions.lock.json`. */\n readonly lockFile?: string;\n /** The folder that holds the extensions. Default `<root>/.agents/extensions`. */\n readonly extensionsDir?: string;\n}\n\n/** The extensions a project supplied, what to record about them, and why any were skipped. */\nexport interface ProjectExtensions {\n readonly extensions: Extension[];\n readonly records: ExtensionLoadedRecord[];\n /** One line for each reason the load was skipped or left unpinned, for the caller to show. */\n readonly notices: string[];\n}\n\n/** The path with symlinks resolved, so a symlinked root and its target are one project to the trust store. */\nexport async function canonicalPath(path: string): Promise<string> {\n try {\n return await realpath(resolve(path));\n } catch {\n return resolve(path);\n }\n}\n\n/**\n * Whether the trust store trusts the project at `root`, asked about its real path only. A link that the store trusted\n * can be pointed at another folder later, so the spelling the caller wrote is never what is trusted: the folder it\n * resolves to now is. Every loader asks through this, so the extensions and the skills of a project are trusted alike.\n */\nexport async function projectTrusted(trust: TrustStore, root: string): Promise<boolean> {\n return trust.isTrusted(await canonicalPath(root));\n}\n\nconst places = async (root: string, options: Pick<LoadOptions, \"lockFile\" | \"extensionsDir\">) => ({\n // The folder is canonical, so a relative or symlinked spelling of it is one folder to the import-cache check.\n dir: await canonicalPath(options.extensionsDir ?? join(root, \".agents\", \"extensions\")),\n lock: options.lockFile ?? join(root, \".agents\", \"extensions.lock.json\"),\n});\n\n/** Whether `path` exists, without following a link or reading it. */\nasync function exists(path: string): Promise<boolean> {\n try {\n await lstat(path);\n return true;\n } catch {\n return false;\n }\n}\n\n/** The extension folders under `dir`, by name; none when the folder does not exist. */\nasync function folders(dir: string): Promise<string[]> {\n try {\n const entries = await readdir(dir, { withFileTypes: true });\n // A linked folder is not hashed as the folder it points at, so it cannot be pinned.\n const linked = entries.find((entry) => entry.isSymbolicLink());\n if (linked !== undefined) {\n throw new HarnessError(\n \"invalid_extension\",\n `${join(dir, linked.name)} is a link, which an extension folder may not be`,\n );\n }\n return entries\n .filter((entry) => entry.isDirectory())\n .map((entry) => entry.name)\n .sort();\n } catch (error) {\n const code = (error as { code?: string }).code;\n if (code === \"ENOENT\" || code === \"ENOTDIR\") return [];\n throw error;\n }\n}\n\nasync function entryFile(dir: string): Promise<string> {\n for (const name of [\"index.mjs\", \"index.js\"]) {\n try {\n await access(join(dir, name));\n return join(dir, name);\n } catch {\n // try the next name\n }\n }\n throw new HarnessError(\"invalid_extension\", `the extension folder ${dir} has no index.mjs or index.js`);\n}\n\n// The hash each folder had when this process first imported it. Node caches modules for the life of the process, so a\n// folder that changed since then would run its old code while the log recorded the new hash.\nconst importedHashes = new Map<string, string>();\n\n/** Refuses a folder this process has imported with other files, before any folder of the project is imported. */\nfunction refuseChanged(folder: string, hash: string): void {\n const before = importedHashes.get(folder);\n if (before !== undefined && before !== hash) {\n throw new HarnessError(\n \"extension_hash_mismatch\",\n `the extension in ${folder} changed after this process loaded it; restart the process to load the new files`,\n );\n }\n}\n\nconst isFunction = (value: unknown): boolean => typeof value === \"function\";\n\nconst badShape = (dir: string, why: string) => new HarnessError(\"invalid_extension\", `the extension in ${dir} ${why}`);\n\n/** Throws unless `interceptors` is an object whose hooks are functions, apart from the `onFailure` setting. */\nfunction checkInterceptors(interceptors: unknown, dir: string): void {\n if (interceptors === undefined) return;\n if (typeof interceptors !== \"object\" || interceptors === null) {\n throw badShape(dir, \"has interceptors that are not an object\");\n }\n for (const [name, hook] of Object.entries(interceptors)) {\n if (name !== \"onFailure\" && !isFunction(hook))\n throw badShape(dir, `has an interceptor \"${name}\" that is not a function`);\n }\n}\n\n/** Throws unless `observers` is a list of functions and `tools` a list of `{ name, definition }`. */\nfunction checkLists(observers: unknown, tools: unknown, dir: string): void {\n if (observers !== undefined && !(Array.isArray(observers) && observers.every(isFunction))) {\n throw badShape(dir, \"has observers that are not a list of functions\");\n }\n const wellFormed = (tool: { name?: unknown; definition?: unknown } | null) =>\n typeof tool?.name === \"string\" && typeof tool.definition === \"object\" && tool.definition !== null;\n if (tools !== undefined && !(Array.isArray(tools) && tools.every(wellFormed))) {\n throw badShape(dir, \"has tools that are not a list of { name, definition }\");\n }\n}\n\n/** Throws `invalid_extension` unless the module's export has the shape of an `Extension`. */\nfunction checkShape(extension: Partial<Extension> | undefined, dir: string): asserts extension is Extension {\n if (typeof extension?.name !== \"string\" || typeof extension.version !== \"string\") {\n throw badShape(dir, \"does not export a name and a version\");\n }\n checkInterceptors(extension.interceptors, dir);\n checkLists(extension.observers, extension.tools, dir);\n}\n\nasync function importExtension(dir: string, hash: string): Promise<Extension> {\n const loaded = (await import(/* @vite-ignore */ pathToFileURL(await entryFile(dir)).href)) as { default?: unknown };\n importedHashes.set(await canonicalPath(dir), hash);\n const made = typeof loaded.default === \"function\" ? await (loaded.default as () => unknown)() : loaded.default;\n const extension = made as Partial<Extension> | undefined;\n checkShape(extension, dir);\n return extension;\n}\n\n/** Why a project's extensions are not loaded, or `undefined` when they may be. */\nasync function skipReason(root: string, base: string, options: LoadOptions): Promise<string | undefined> {\n if (options.headless && options.loadInHeadless !== true) {\n return `the project extensions of ${base} are skipped: this run is headless`;\n }\n if (!(await projectTrusted(options.trust, root)))\n return `the project extensions of ${base} are skipped: the project is not trusted`;\n return undefined;\n}\n\n/**\n * Loads the extensions in a project, or skips them with a notice. Every folder is hashed and checked against the lock\n * file before any is imported, so a refusal runs none of the project's code. A folder whose hash differs from the lock\n * file, that the lock file does not list, or that the lock file lists and the project no longer holds is refused with\n * `extension_hash_mismatch`; with no lock file the extensions load and a notice says they are unpinned.\n *\n * The pin covers the files inside each extension folder, and nothing an extension imports from outside it, such as a\n * relative path that leaves the folder or a package from the project's `node_modules`. The lock file sits inside the\n * project it pins, so anyone who can edit the project can pin their own changes: the pin catches a change nobody\n * meant, not an attacker who holds the project.\n */\nexport async function loadProjectExtensions(root: string, options: LoadOptions): Promise<ProjectExtensions> {\n const base = await canonicalPath(root);\n const result: ProjectExtensions = { extensions: [], records: [], notices: [] };\n const { dir, lock } = await places(base, options);\n // Nothing of a project is read, other than whether it has extensions at all, until trust and headless are decided.\n if (!(await exists(dir)) && !(await exists(lock))) return result;\n const reason = await skipReason(root, base, options);\n if (reason !== undefined) {\n result.notices.push(reason);\n return result;\n }\n const names = await folders(dir);\n const pins = await readLock(lock);\n if (names.length === 0 && (pins === undefined || pins.size === 0)) return result;\n if (pins === undefined) {\n // A lock file may hold MCP tool pins alone, and then it pins no extension.\n const why = (await exists(lock)) ? `${lock} holds no extension pins` : `there is no ${lock}`;\n result.notices.push(`the extensions of ${base} are not pinned: ${why}`);\n }\n const hashes = await checkedHashes(dir, names, pins);\n const seen = new Set<string>();\n for (const name of names) {\n const hash = hashes.get(name) as string;\n const extension = await importExtension(join(dir, name), hash);\n if (seen.has(extension.name))\n throw new HarnessError(\"invalid_extension\", `two project extensions are named \"${extension.name}\"`);\n seen.add(extension.name);\n result.extensions.push(extension);\n result.records.push({ name: extension.name, tier: \"in_process\", contentHash: hash });\n }\n return result;\n}\n\n/** The hash of every folder, after checking each against the pins: none of the project's code has run yet. */\nasync function checkedHashes(\n dir: string,\n names: readonly string[],\n pins: ReadonlyMap<string, string> | undefined,\n): Promise<Map<string, string>> {\n const hashes = new Map<string, string>();\n for (const name of names) {\n const hash = await hashExtensionDir(join(dir, name));\n hashes.set(name, hash);\n refuseChanged(await canonicalPath(join(dir, name)), hash);\n }\n if (pins === undefined) return hashes;\n for (const name of pins.keys()) {\n if (!hashes.has(name)) {\n throw new HarnessError(\n \"extension_hash_mismatch\",\n `the extension \"${name}\" is pinned but the project no longer holds it`,\n );\n }\n }\n for (const [name, hash] of hashes) {\n const pinned = pins.get(name);\n if (pinned === hash) continue;\n const why = pinned === undefined ? \"the lock file does not list it\" : \"its files changed since they were pinned\";\n throw new HarnessError(\"extension_hash_mismatch\", `the extension \"${name}\" is refused: ${why}`);\n }\n return hashes;\n}\n\n/** Writes the lock file for every extension folder as it is now. A person runs it, which is what pins the code. */\nexport async function pinProjectExtensions(\n root: string,\n options: Pick<LoadOptions, \"lockFile\" | \"extensionsDir\"> = {},\n): Promise<ReadonlyMap<string, string>> {\n const { dir, lock } = await places(await canonicalPath(root), options);\n const pins = new Map<string, string>();\n for (const name of await folders(dir)) pins.set(name, await hashExtensionDir(join(dir, name)));\n await writeLock(lock, pins);\n return pins;\n}\n"]}
@@ -2,7 +2,21 @@
2
2
  export declare function hashExtensionDir(dir: string): Promise<string>;
3
3
  /** Parses JSON that must be an object, or throws `invalid_extension` naming the file. */
4
4
  export declare function parseObject(text: string, file: string): Record<string, unknown>;
5
- /** The pins in a lock file, by extension folder name, or `undefined` when there is no lock file. */
5
+ /**
6
+ * The pins in a lock file, by extension folder name, or `undefined` when there is no lock file or it pins no
7
+ * extension, because it holds MCP pins alone.
8
+ */
6
9
  export declare function readLock(file: string): Promise<ReadonlyMap<string, string> | undefined>;
7
- /** Writes the lock file for these pins, replacing the old one in one step. */
10
+ /**
11
+ * Writes the lock file for these extension pins, keeping its MCP pins, and replaces the old file in one step. A lock
12
+ * file that can't be read as one, such as one left with merge-conflict markers, is replaced whole, so a person can
13
+ * repin a broken file; its MCP pins go with it, and their tools wait for approval again.
14
+ */
8
15
  export declare function writeLock(file: string, pins: ReadonlyMap<string, string>): Promise<void>;
16
+ /** The MCP pins of one server in a lock file, by tool name, or `undefined` when it holds none for the server. */
17
+ export declare function readMcpPins(file: string, server: string): Promise<Readonly<Record<string, string>> | undefined>;
18
+ /**
19
+ * Replaces the MCP pins of one server in a lock file, keeping every other member. It throws `invalid_extension` for a
20
+ * lock file it can't read, rather than replace it: a file without its extension pins would let unpinned extensions load.
21
+ */
22
+ export declare function writeMcpPins(file: string, server: string, pins: Readonly<Record<string, string>>): Promise<void>;