ai-sdk-sandbox-gce 0.6.0 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,17 @@
1
1
  # ai-sdk-sandbox-gce
2
2
 
3
+ ## 0.7.0
4
+
5
+ ### Minor Changes
6
+
7
+ - 574c460: `gceSandboxTemplateExists({ template, setup, image })` says whether the template that sandboxes created with these options boot from is saved on the service. It is not after a new base image, a new version of the service or a new harness version, which each name another template: an application can build it ahead rather than have the next sandbox build it.
8
+ - 4b5f85a: The egress proxy can take the direct connections of programs that ignore `HTTPS_PROXY` and `HTTP_PROXY` (Node.js's own `fetch` without `NODE_USE_ENV_PROXY`, Go, Java…), once the sandboxes' DNS answers its address for every name: TLS on `SANDBOX_PROXY_TLS_PORT` (443), checked by the host its ClientHello names (SNI) and relayed without being decrypted, and plain HTTP on `SANDBOX_PROXY_HTTP_PORT` (80), sent on to its `Host`. Node.js then reaches its hosts without `NODE_USE_ENV_PROXY`, and test suites that mock `fetch` with MSW 3 pass. Nothing changes without these settings. HTTP/3, a TLS connection without SNI, and programs that pin addresses or resolve names elsewhere are not covered.
9
+
10
+ ### Patch Changes
11
+
12
+ - 1e20913: The README closes the sandboxes' DNS with a private zone for the root, which answers every type of query in the network, rather than a response policy rule on `*.`, which answered only `A` queries and let the others (`AAAA`, `TXT`, `MX`…) leave it, a channel for a few bytes at a time. A peering zone keeps `googleapis.com` resolving for the service. A network set up with the earlier steps should move to the zones, as the README shows.
13
+ - 1e20913: A sandbox's `timings` count the registration with the egress proxy once: it runs alongside the boot, and `agentMs` now holds only what it took beyond the boot, so that `insertMs`, `bootMs` and `agentMs` follow one another within `totalMs`, as documented.
14
+
3
15
  ## 0.6.0
4
16
 
5
17
  ### Minor Changes
package/README.md CHANGED
@@ -95,14 +95,28 @@ gcloud compute firewall-rules create proxy-admin-from-service --network=sandboxe
95
95
  --action=ALLOW --rules=tcp:3129 --source-ranges=10.8.17.0/26 --target-tags=ai-sdk-sandbox-proxy
96
96
  ```
97
97
 
98
- A sandbox resolves names through the metadata server, which the firewall does not filter: a DNS query for any name leaves the VPC, a channel for a few bytes at a time. Close it with a [response policy](https://cloud.google.com/dns/docs/zones/manage-response-policies) on the network that answers every name itself, so that no query leaves it:
98
+ A sandbox resolves names through the metadata server, which the firewall does not filter: a DNS query for any name leaves the VPC, a channel for a few bytes at a time. Close it with a private zone for the root of the DNS on the network, which answers every name itself, for every type of query, so that no query leaves it. The service, on the same network, still reaches Google's APIs: a peering zone resolves `googleapis.com` in a network with no zone of its own, created for that alone and free without subnetworks.
99
99
 
100
100
  ```bash
101
101
  gcloud services enable dns.googleapis.com
102
- gcloud dns response-policies create sandboxes-no-dns --networks=sandboxes \
102
+ gcloud dns managed-zones create sandboxes-root --dns-name=. --visibility=private --networks=sandboxes \
103
103
  --description="Every name answered locally: DNS is no way out of a sandbox."
104
- gcloud dns response-policies rules create every-name --response-policy=sandboxes-no-dns \
105
- --dns-name="*." --local-data=name="*.",type=A,ttl=300,rrdatas=0.0.0.0
104
+ gcloud dns record-sets create "*." --zone=sandboxes-root --type=A --ttl=300 --rrdatas=0.0.0.0
105
+
106
+ gcloud compute networks create sandboxes-dns --subnet-mode=custom
107
+ gcloud dns managed-zones create sandboxes-googleapis --dns-name=googleapis.com. --visibility=private \
108
+ --networks=sandboxes --target-network=sandboxes-dns --target-project=$PROJECT \
109
+ --description="Google's APIs for the service, through a network that answers them."
110
+ ```
111
+
112
+ An `A` query then gets `0.0.0.0`, any other type (`AAAA`, `TXT`, `MX`…) an empty answer, and none of them leaves the network. The names of Google Cloud (`metadata.google.internal`, the machines' internal names) still resolve, and `googleapis.com` too: its queries reach only Google's servers. Should the service reach another domain by name, give it a peering zone of its own the same way.
113
+
114
+ A network closed earlier with a response policy rule on `*.` (an earlier version of these steps) is not closed: such a rule answers only `A` queries, and the others leave the network. Create the zones above, then delete the policy:
115
+
116
+ ```bash
117
+ gcloud dns response-policies rules delete every-name --response-policy=sandboxes-no-dns
118
+ gcloud dns response-policies update sandboxes-no-dns --networks=""
119
+ gcloud dns response-policies delete sandboxes-no-dns
106
120
  ```
107
121
 
108
122
  Keep the `service` subnetwork for the service alone: whatever else runs in it, a Cloud Run job or a machine, reaches the agents and the proxy's administration API like the service does.
@@ -135,14 +149,14 @@ gcloud compute instances create sandbox-proxy --zone=$ZONE --machine-type=e2-sma
135
149
  #!/bin/sh
136
150
  set -e
137
151
  # The version of the proxy: the one your application depends on.
138
- VERSION=0.6.0
152
+ VERSION=0.7.0
139
153
  # Writes $2 to the file $1 when it differs, and says whether it did.
140
154
  changed() {
141
155
  mkdir -p "$(dirname "$1")"
142
156
  if printf '%b' "$2" | cmp -s - "$1"; then return 1; fi
143
157
  printf '%b' "$2" > "$1"
144
158
  }
145
- # Public resolvers, not the metadata server's, which the sandboxes' response policy answers.
159
+ # Public resolvers, not the metadata server's, which the sandboxes' root zone answers.
146
160
  # After gce-resolved.conf, which adds the metadata server: the empty DNS= resets the list.
147
161
  dns=false
148
162
  if changed /etc/systemd/resolved.conf.d/public-dns.conf '[Resolve]\nDNS=\nDNS=8.8.8.8 1.1.1.1\nDomains=~.\n'; then
@@ -283,7 +297,7 @@ echo "deb [signed-by=/etc/apt/keyrings/nodesource.asc] https://deb.nodesource.co
283
297
  > /etc/apt/sources.list.d/nodesource.list
284
298
  apt-get update
285
299
  apt-get install -y nodejs
286
- npm install --global ai-sdk-sandbox-gce@0.6.0 pnpm@10
300
+ npm install --global ai-sdk-sandbox-gce@0.7.0 pnpm@10
287
301
 
288
302
  # The sandbox's user: sudo without a password, and Docker.
289
303
  useradd --create-home --shell /bin/bash agent
@@ -311,7 +325,7 @@ The agent runs as root and starts the commands as `agent`, in its own service: `
311
325
 
312
326
  ### 4. The service
313
327
 
314
- The service's image is published on Docker Hub with each release, `docker.io/fpasquet/ai-sdk-sandbox-gce:<version>`: Node.js and the package, built by the release workflow from the version on npm. Deploy the version your application depends on. Each image carries a provenance attestation, which `gh attestation verify oci://docker.io/fpasquet/ai-sdk-sandbox-gce:0.6.0 --owner fpasquet` checks; its [`Dockerfile`](https://github.com/fpasquet/ai-sdk-harness/blob/main/packages/sandbox-gce/Dockerfile) builds the same image from your own registry.
328
+ The service's image is published on Docker Hub with each release, `docker.io/fpasquet/ai-sdk-sandbox-gce:<version>`: Node.js and the package, built by the release workflow from the version on npm. Deploy the version your application depends on. Each image carries a provenance attestation, which `gh attestation verify oci://docker.io/fpasquet/ai-sdk-sandbox-gce:0.7.0 --owner fpasquet` checks; its [`Dockerfile`](https://github.com/fpasquet/ai-sdk-harness/blob/main/packages/sandbox-gce/Dockerfile) builds the same image from your own registry.
315
329
 
316
330
  Its service account gets a role of its own, with what the service calls and nothing else, limited by a condition to the names it uses: the sandboxes' machines and disks (`sbx-`), the proxy's machine, the sandbox images and templates (`ai-sdk-`).
317
331
 
@@ -349,7 +363,7 @@ for secret in sandbox-agent-secret sandbox-proxy-token sandbox-service-token; do
349
363
  --member=serviceAccount:sandboxes@$PROJECT.iam.gserviceaccount.com --role=roles/secretmanager.secretAccessor
350
364
  done
351
365
 
352
- gcloud run deploy sandboxes --region=$REGION --image=docker.io/fpasquet/ai-sdk-sandbox-gce:0.6.0 \
366
+ gcloud run deploy sandboxes --region=$REGION --image=docker.io/fpasquet/ai-sdk-sandbox-gce:0.7.0 \
353
367
  --service-account=sandboxes@$PROJECT.iam.gserviceaccount.com \
354
368
  --network=sandboxes --subnet=service --vpc-egress=private-ranges-only \
355
369
  --no-allow-unauthenticated --min-instances=0 --timeout=3600 --concurrency=1000 \
@@ -483,6 +497,18 @@ await deleteGceSandboxTemplate({
483
497
 
484
498
  The sandboxes made from it keep their disk. The next sandbox created from the same template, setup and image builds it again. A template that does not exist is no error.
485
499
 
500
+ A template can also be gone without your deleting it: a new base image, a new version of the service or a new harness version each name another template, and old ones get cleaned up. `gceSandboxTemplateExists()` says whether the template a sandbox would boot from is saved, with the same options: build it ahead when it is not, rather than have the next user wait for it.
501
+
502
+ ```ts
503
+ import { gceSandboxTemplateExists } from 'ai-sdk-sandbox-gce';
504
+
505
+ const ready = await gceSandboxTemplateExists({
506
+ url: process.env.GCE_SANDBOX_URL!,
507
+ template: await agent.getSandboxTemplate(),
508
+ setup,
509
+ });
510
+ ```
511
+
486
512
  A template is made from a sandbox no agent ever ran in: the client's throwaway one, where only `setup` and the harness's own installation run. Never save a sandbox an agent worked in as a template, through the API or otherwise: whatever the agent left on its disk, the `agent` service of the machine included, would start in every later sandbox.
487
513
 
488
514
  Making a template takes a few minutes: the machine boots, the harness installs, Compute Engine saves the disk, and the first sandbox on a new image waits a minute more while Compute Engine spreads it. Make it when you deploy, rather than in the first user's session, with a script that creates a sandbox from the agent's template and deletes it:
@@ -630,6 +656,50 @@ Without it, code that calls an outside host with Node.js's `fetch` and has no pr
630
656
 
631
657
  The MCP servers that [`ai-sdk-harness-plugins`](https://ai-sdk-harness.pages.dev/docs/packages/harness-plugins) runs in the sandbox get it on their own. The agent sets the variables: a sandbox image built on an earlier version of this package still gives every command `NODE_USE_ENV_PROXY=1`, until it is built again.
632
658
 
659
+ To have both, Node.js's `fetch` reaching its hosts and MSW test suites passing, without `NODE_USE_ENV_PROXY`, let the sandboxes reach the proxy directly: see [Programs that ignore the proxy variables](#programs-that-ignore-the-proxy-variables).
660
+
661
+ ### Programs that ignore the proxy variables
662
+
663
+ Optional. By default, only programs that read `HTTPS_PROXY` or `HTTP_PROXY` leave a sandbox: Node.js's own `fetch` without `NODE_USE_ENV_PROXY`, Go, Java, and any binary that ignores the variables connect directly, and the firewall refuses them. The proxy can take those direct connections too, on 443 for TLS and on 80 for plain HTTP, when every name resolves to its address in the sandboxes:
664
+
665
+ - **TLS, on 443**: the proxy reads the host the connection's ClientHello names (SNI), lets it through only to an allowed host and a public address, as it does a `CONNECT` tunnel, then relays the bytes to it on 443 without decrypting them;
666
+ - **plain HTTP, on 80**: the proxy reads `Host`, and sends the request on as one through `HTTP_PROXY`;
667
+ - the same connection limits, egress counters and refusal logs as through the proxy variables.
668
+
669
+ A program then connects to `host:443` as it would anywhere, and reaches the proxy. MSW 3 sees a request it can mock, with no `CONNECT`, and `NODE_USE_ENV_PROXY` is no longer needed for Node.js to reach its hosts. The programs that read the proxy variables go on using them.
670
+
671
+ To set it up:
672
+
673
+ 1. Have the root zone answer every name with the proxy's address rather than `0.0.0.0`. No query leaves the network, as before:
674
+
675
+ ```bash
676
+ gcloud dns record-sets update "*." --zone=sandboxes-root --type=A --ttl=300 --rrdatas=10.8.16.2
677
+ ```
678
+
679
+ 2. Let the sandboxes reach the proxy on 80 and 443 as well:
680
+
681
+ ```bash
682
+ gcloud compute firewall-rules update sandboxes-to-proxy --rules=tcp:3128,tcp:80,tcp:443
683
+ gcloud compute firewall-rules update proxy-from-sandboxes --rules=tcp:3128,tcp:80,tcp:443
684
+ ```
685
+
686
+ 3. Add to the `[Service]` section of the proxy's unit, in its startup script, then restart the proxy with no sandbox running (it forgets its sandboxes as it restarts):
687
+
688
+ ```ini
689
+ Environment=SANDBOX_PROXY_TLS_PORT=443
690
+ Environment=SANDBOX_PROXY_HTTP_PORT=80
691
+ # Ports below 1024, for a user that is not root.
692
+ AmbientCapabilities=CAP_NET_BIND_SERVICE
693
+ ```
694
+
695
+ Its limits:
696
+
697
+ - **HTTP/3** (QUIC, over UDP) does not go through: clients fall back to TCP;
698
+ - **a TLS connection that names no host** (no SNI), or that is no TLS, is cut: there is no HTTP to answer it with, and it shows in the proxy's refusals;
699
+ - **credentials** stay on the base URL routes: a direct connection is never decrypted, any more than a `CONNECT` tunnel is, so no request transformation applies to it;
700
+ - **a program that pins IP addresses, or resolves names elsewhere** (its own DNS over HTTPS, `/etc/hosts`), does not reach the proxy, and stays refused by the firewall;
701
+ - **ports other than 80 and 443**: refused by the firewall, as before.
702
+
633
703
  ## Ports
634
704
 
635
705
  `ports` lists the ports inside the sandbox the harness may reach. `getPortEndpoint()` returns a WebSocket URL on the service, `wss://<service>/v1/sandboxes/<name>/ports/<port>`, with the identity token as a header, read anew at each connection. The service passes the connection on to the machine's agent, with the agent's token in place of the caller's, and the agent on to `127.0.0.1:<port>`. A port outside the list is refused with `HarnessCapabilityUnsupportedError`.
@@ -716,16 +786,18 @@ The MCP servers that [`ai-sdk-harness-plugins`](https://ai-sdk-harness.pages.dev
716
786
 
717
787
  ### The proxy (`proxy`)
718
788
 
719
- | Variable | Default | Description |
720
- | --------------------------------- | ------------------ | -------------------------------------------------------------------------------------------------------------------- |
721
- | `SANDBOX_PROXY_TOKEN` | required | The token the service proves itself with, 16 characters at least |
722
- | `SANDBOX_PROXY_PORT` | `3128` | The port the sandboxes reach |
723
- | `SANDBOX_PROXY_ADMIN_PORT` | `3129` | The port of the administration API |
724
- | `SANDBOX_ALLOW_PRIVATE_NETWORK` | `false` | For tests only: lets the sandboxes reach private addresses and plain HTTP base URLs |
725
- | `SANDBOX_PROXY_MAX_CONNECTIONS` | `128` | The most connections the commands of a sandbox hold open through the proxy at once: [Connections](#connections) |
726
- | `SANDBOX_PROXY_ROUTE_CONNECTIONS` | `32` | The connections a sandbox holds beyond those, for its base URL routes alone: [Connections](#connections) |
727
- | `SANDBOX_PROXY_TOTAL_CONNECTIONS` | from `LimitNOFILE` | The most connections the proxy holds for all its sandboxes, a tenth kept for the routes: [Connections](#connections) |
728
- | `HOST`, `LOG_FORMAT` | `0.0.0.0` | Where it listens; `text` for plain logs |
789
+ | Variable | Default | Description |
790
+ | --------------------------------- | ------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------- |
791
+ | `SANDBOX_PROXY_TOKEN` | required | The token the service proves itself with, 16 characters at least |
792
+ | `SANDBOX_PROXY_PORT` | `3128` | The port the sandboxes reach |
793
+ | `SANDBOX_PROXY_ADMIN_PORT` | `3129` | The port of the administration API |
794
+ | `SANDBOX_PROXY_TLS_PORT` | none | Where the proxy takes direct TLS connections, `443`: see [Programs that ignore the proxy variables](#programs-that-ignore-the-proxy-variables) |
795
+ | `SANDBOX_PROXY_HTTP_PORT` | none | Where it takes direct plain HTTP requests, `80`, likewise |
796
+ | `SANDBOX_ALLOW_PRIVATE_NETWORK` | `false` | For tests only: lets the sandboxes reach private addresses and plain HTTP base URLs |
797
+ | `SANDBOX_PROXY_MAX_CONNECTIONS` | `128` | The most connections the commands of a sandbox hold open through the proxy at once: [Connections](#connections) |
798
+ | `SANDBOX_PROXY_ROUTE_CONNECTIONS` | `32` | The connections a sandbox holds beyond those, for its base URL routes alone: [Connections](#connections) |
799
+ | `SANDBOX_PROXY_TOTAL_CONNECTIONS` | from `LimitNOFILE` | The most connections the proxy holds for all its sandboxes, a tenth kept for the routes: [Connections](#connections) |
800
+ | `HOST`, `LOG_FORMAT` | `0.0.0.0` | Where it listens; `text` for plain logs |
729
801
 
730
802
  ### The agent (`agent`)
731
803
 
@@ -141,6 +141,8 @@ export interface GcePrepareSettings extends GceConnectionSettings {
141
141
  abortSignal?: AbortSignal;
142
142
  }
143
143
  /** Options of `deleteGceSandboxTemplate()`: the template, as the sandboxes made from it were. */
144
+ /** What names a template to look up: the same as to delete it. */
145
+ export type GceTemplateLookupSettings = GceTemplateDeletionSettings;
144
146
  export interface GceTemplateDeletionSettings extends GceConnectionSettings {
145
147
  /** The template the sandboxes were created from, `await agent.getSandboxTemplate()`. */
146
148
  template: HarnessV1SandboxTemplate;
@@ -1,4 +1,4 @@
1
- import type { GceNetworkSandboxSessionCreateOptions, GceNetworkSandboxSessionResumeOptions, GcePrepareSettings, GceSandboxDeletionSettings, GceSandboxLookupSettings, GceSandboxMetricsSettings, GceTemplateDeletionSettings } from '../gce-settings.js';
1
+ import type { GceNetworkSandboxSessionCreateOptions, GceNetworkSandboxSessionResumeOptions, GcePrepareSettings, GceSandboxDeletionSettings, GceSandboxLookupSettings, GceSandboxMetricsSettings, GceTemplateDeletionSettings, GceTemplateLookupSettings } from '../gce-settings.js';
2
2
  import type { GceSandboxEgressUsage, GceSandboxInfo, GceSandboxMetrics } from '../gce-usage.js';
3
3
  import { GceNetworkSandboxSession } from '../session/gce-network-sandbox-session.js';
4
4
  /**
@@ -39,6 +39,14 @@ export declare function prepareGceSandboxService(options: GcePrepareSettings): P
39
39
  * template that does not exist, or no longer does, is no error.
40
40
  */
41
41
  export declare function deleteGceSandboxTemplate(options: GceTemplateDeletionSettings): Promise<void>;
42
+ /**
43
+ * Whether the template that sandboxes created with `template`, `setup` and `image` boot from is
44
+ * saved on the service, ready to boot from. It is not once the service lost it, or never had it: a
45
+ * new base image, a new version of the service, or a new `identity` of `template` (another harness
46
+ * version) each name another template. The next sandbox created from it then builds it first, which
47
+ * takes minutes: an application can build it ahead, by creating a sandbox from it and deleting it.
48
+ */
49
+ export declare function gceSandboxTemplateExists(options: GceTemplateLookupSettings): Promise<boolean>;
42
50
  /**
43
51
  * Deletes the sandbox `sandboxId`, its machine and its disk, without starting it: a stopped sandbox,
44
52
  * which `destroy()` of a session would first have to resume, a minute of a billed machine for
@@ -121,6 +121,19 @@ export async function deleteGceSandboxTemplate(options) {
121
121
  forgetTemplate(client, source);
122
122
  await client.deleteTemplate(templateId(source), image, abortSignal);
123
123
  }
124
+ /**
125
+ * Whether the template that sandboxes created with `template`, `setup` and `image` boot from is
126
+ * saved on the service, ready to boot from. It is not once the service lost it, or never had it: a
127
+ * new base image, a new version of the service, or a new `identity` of `template` (another harness
128
+ * version) each name another template. The next sandbox created from it then builds it first, which
129
+ * takes minutes: an application can build it ahead, by creating a sandbox from it and deleting it.
130
+ */
131
+ export async function gceSandboxTemplateExists(options) {
132
+ const { template, setup = [], image, abortSignal } = options;
133
+ if (abortSignal?.aborted)
134
+ throw abortReason(abortSignal);
135
+ return clientOf(options).templateExists(templateId({ template, setup }), image, abortSignal);
136
+ }
124
137
  /**
125
138
  * Deletes the sandbox `sandboxId`, its machine and its disk, without starting it: a stopped sandbox,
126
139
  * which `destroy()` of a session would first have to resume, a minute of a billed machine for
package/dist/index.d.ts CHANGED
@@ -2,9 +2,9 @@ export { GceSandboxCapacityError } from './client/errors/gce-sandbox-capacity-er
2
2
  export { GceSandboxImageError } from './client/errors/gce-sandbox-image-error.js';
3
3
  export { GceSandboxNotFoundError } from './client/errors/gce-sandbox-not-found-error.js';
4
4
  export { GceSandboxServiceError } from './client/errors/gce-sandbox-service-error.js';
5
- export type { GceAuth, GceConnectionSettings, GceCreationSettings, GceNetworkSandboxSessionCreateOptions, GceNetworkSandboxSessionResumeOptions, GcePrepareSettings, GceSandboxDeletionSettings, GceSandboxLookupSettings, GceSandboxMetricsSettings, GceTemplateDeletionSettings, } from './client/gce-settings.js';
5
+ export type { GceAuth, GceConnectionSettings, GceCreationSettings, GceNetworkSandboxSessionCreateOptions, GceNetworkSandboxSessionResumeOptions, GcePrepareSettings, GceSandboxDeletionSettings, GceSandboxLookupSettings, GceSandboxMetricsSettings, GceTemplateDeletionSettings, GceTemplateLookupSettings, } from './client/gce-settings.js';
6
6
  export type { GceSandboxEgressUsage, GceSandboxInfo, GceSandboxMetrics, GceSandboxMetricSample, GceSandboxReport, GceSandboxTimings, } from './client/gce-usage.js';
7
- export { createGceNetworkSandboxSession, deleteGceSandbox, deleteGceSandboxTemplate, describeGceSandbox, getGceSandboxMetrics, getGceSandboxUsage, prepareGceSandboxService, resumeGceNetworkSandboxSession, } from './client/lifecycle/create-session.js';
7
+ export { createGceNetworkSandboxSession, deleteGceSandbox, deleteGceSandboxTemplate, describeGceSandbox, gceSandboxTemplateExists, getGceSandboxMetrics, getGceSandboxUsage, prepareGceSandboxService, resumeGceNetworkSandboxSession, } from './client/lifecycle/create-session.js';
8
8
  export { GCE_SANDBOX_PROVIDER_ID } from './client/provider-id.js';
9
9
  export { GceNetworkSandboxSession } from './client/session/gce-network-sandbox-session.js';
10
10
  export { GceSandboxSession } from './client/session/gce-sandbox-session.js';
package/dist/index.js CHANGED
@@ -2,7 +2,7 @@ export { GceSandboxCapacityError } from './client/errors/gce-sandbox-capacity-er
2
2
  export { GceSandboxImageError } from './client/errors/gce-sandbox-image-error.js';
3
3
  export { GceSandboxNotFoundError } from './client/errors/gce-sandbox-not-found-error.js';
4
4
  export { GceSandboxServiceError } from './client/errors/gce-sandbox-service-error.js';
5
- export { createGceNetworkSandboxSession, deleteGceSandbox, deleteGceSandboxTemplate, describeGceSandbox, getGceSandboxMetrics, getGceSandboxUsage, prepareGceSandboxService, resumeGceNetworkSandboxSession, } from './client/lifecycle/create-session.js';
5
+ export { createGceNetworkSandboxSession, deleteGceSandbox, deleteGceSandboxTemplate, describeGceSandbox, gceSandboxTemplateExists, getGceSandboxMetrics, getGceSandboxUsage, prepareGceSandboxService, resumeGceNetworkSandboxSession, } from './client/lifecycle/create-session.js';
6
6
  export { GCE_SANDBOX_PROVIDER_ID } from './client/provider-id.js';
7
7
  export { GceNetworkSandboxSession } from './client/session/gce-network-sandbox-session.js';
8
8
  export { GceSandboxSession } from './client/session/gce-sandbox-session.js';
@@ -1,4 +1,5 @@
1
1
  import type { Server } from 'node:http';
2
+ import type { Server as NetServer } from 'node:net';
2
3
  import type { Logger } from '../common/logger.js';
3
4
  import type { EgressPolicy } from './egress-policy.js';
4
5
  /**
@@ -38,6 +39,13 @@ export declare const DEFAULT_TOTAL_CONNECTIONS = 32256;
38
39
  * - a plain HTTP request through `HTTP_PROXY` to an allowed host, as package mirrors still serve:
39
40
  * sent on as it is, no credential put in.
40
41
  *
42
+ * With the sandboxes' DNS answering the proxy's address for every name, the programs that ignore
43
+ * `HTTPS_PROXY` (Node.js's `fetch` without `NODE_USE_ENV_PROXY`, Go, Java…) reach it directly:
44
+ *
45
+ * - on {@link tlsServer}, a TLS connection: the host its ClientHello names (SNI) is checked as the
46
+ * host of a tunnel would be, then the connection is relayed as a tunnel's, never decrypted;
47
+ * - on {@link httpServer}, a plain HTTP request: sent on to its `Host` as through `HTTP_PROXY`.
48
+ *
41
49
  * Anything else is refused, and so is any private address however it is named: the proxy's
42
50
  * loopback, the metadata server, the VPC. A connection from a machine no sandbox holds is refused.
43
51
  * The policy is read anew for each connection: allowing a host or adding a credential applies at
@@ -47,6 +55,13 @@ export declare class EgressProxy {
47
55
  private readonly policyFor;
48
56
  private readonly logger;
49
57
  readonly server: Server;
58
+ /**
59
+ * Direct TLS connections, from programs that ignore `HTTPS_PROXY`: listened on 443 when the
60
+ * sandboxes' DNS answers the proxy's address. Not listened on otherwise.
61
+ */
62
+ readonly tlsServer: NetServer;
63
+ /** Direct plain HTTP requests, from programs that ignore `HTTP_PROXY`: listened on 80, likewise. */
64
+ readonly httpServer: Server;
50
65
  /** The connections each machine holds open, by its address. */
51
66
  private readonly machines;
52
67
  /** The connections of every machine together. */
@@ -108,6 +123,18 @@ export declare class EgressProxy {
108
123
  private busiest;
109
124
  private limits;
110
125
  private tunnel;
126
+ /**
127
+ * A TLS connection a program made directly, its host's name resolved to the proxy's address: the
128
+ * host its ClientHello names (SNI) is allowed as the host of a tunnel would be, then the
129
+ * connection is relayed to it on 443, never decrypted. One that names no host, or is no TLS, is
130
+ * cut: there is no HTTP to answer it with.
131
+ */
132
+ private direct;
133
+ /**
134
+ * A plain HTTP request a program sent directly, its host's name resolved to the proxy's
135
+ * address: sent on to its `Host` as a request through `HTTP_PROXY` would be.
136
+ */
137
+ private forwardDirect;
111
138
  /**
112
139
  * A plain request: a base URL route, its credentials put in, or, through `HTTP_PROXY`, plain HTTP
113
140
  * to an allowed host, as package mirrors still serve, with no credential at all.
@@ -1,6 +1,6 @@
1
1
  import { createServer, request as httpRequest } from 'node:http';
2
2
  import { request as httpsRequest } from 'node:https';
3
- import { connect, isIP } from 'node:net';
3
+ import { connect, createServer as createNetServer, isIP } from 'node:net';
4
4
  import { silentLogger } from '../common/logger.js';
5
5
  import { routeTarget } from '../protocol/proxy-routes.js';
6
6
  import { injectedCredentials, isListedHost, isRoutable, transformHeaders, withoutCredentials, } from './egress-policy.js';
@@ -120,6 +120,15 @@ function helloRefusal(host, hello) {
120
120
  ? `A tunnel to ${host} must name it in its TLS (SNI).`
121
121
  : `A tunnel to ${host} may not name ${named} in its TLS.`;
122
122
  }
123
+ /** The host a direct TLS connection names (SNI), or why it may not leave. */
124
+ function directHost(hello) {
125
+ if (hello?.kind !== 'hello')
126
+ return { why: 'Only TLS reaches the proxy on 443.' };
127
+ if (hello.serverName === undefined) {
128
+ return { why: 'A direct TLS connection must name its host (SNI).' };
129
+ }
130
+ return { host: canonical(hello.serverName) };
131
+ }
123
132
  const connections = (count) => `${count} connection${count === 1 ? '' : 's'}`;
124
133
  const refuse = (res, message) => {
125
134
  res.writeHead(403, { 'content-type': 'text/plain' }).end(`${message}\n`);
@@ -176,6 +185,13 @@ function targetOf(url) {
176
185
  * - a plain HTTP request through `HTTP_PROXY` to an allowed host, as package mirrors still serve:
177
186
  * sent on as it is, no credential put in.
178
187
  *
188
+ * With the sandboxes' DNS answering the proxy's address for every name, the programs that ignore
189
+ * `HTTPS_PROXY` (Node.js's `fetch` without `NODE_USE_ENV_PROXY`, Go, Java…) reach it directly:
190
+ *
191
+ * - on {@link tlsServer}, a TLS connection: the host its ClientHello names (SNI) is checked as the
192
+ * host of a tunnel would be, then the connection is relayed as a tunnel's, never decrypted;
193
+ * - on {@link httpServer}, a plain HTTP request: sent on to its `Host` as through `HTTP_PROXY`.
194
+ *
179
195
  * Anything else is refused, and so is any private address however it is named: the proxy's
180
196
  * loopback, the metadata server, the VPC. A connection from a machine no sandbox holds is refused.
181
197
  * The policy is read anew for each connection: allowing a host or adding a credential applies at
@@ -185,6 +201,13 @@ export class EgressProxy {
185
201
  policyFor;
186
202
  logger;
187
203
  server;
204
+ /**
205
+ * Direct TLS connections, from programs that ignore `HTTPS_PROXY`: listened on 443 when the
206
+ * sandboxes' DNS answers the proxy's address. Not listened on otherwise.
207
+ */
208
+ tlsServer;
209
+ /** Direct plain HTTP requests, from programs that ignore `HTTP_PROXY`: listened on 80, likewise. */
210
+ httpServer;
188
211
  /** The connections each machine holds open, by its address. */
189
212
  machines = new Map();
190
213
  /** The connections of every machine together. */
@@ -222,27 +245,41 @@ export class EgressProxy {
222
245
  this.server.headersTimeout = KEEP_ALIVE_MS + 1_000;
223
246
  this.server.on('connection', (socket) => this.count(socket));
224
247
  this.server.on('connect', (req, socket, head) => this.tunnel(req, socket, head));
248
+ this.tlsServer = createNetServer((socket) => this.direct(socket));
249
+ this.httpServer = createServer((req, res) => this.forwardDirect(req, res));
250
+ this.httpServer.keepAliveTimeout = KEEP_ALIVE_MS;
251
+ this.httpServer.headersTimeout = KEEP_ALIVE_MS + 1_000;
252
+ this.httpServer.on('connection', (socket) => this.count(socket));
225
253
  }
226
254
  close() {
227
255
  this.server.closeAllConnections();
228
256
  this.server.close();
257
+ this.httpServer.closeAllConnections();
258
+ this.httpServer.close();
259
+ // A server never listened answers its `close` with an error: nothing to close then.
260
+ this.tlsServer.close(() => undefined);
229
261
  }
230
262
  /**
231
263
  * Counts the connections of a machine, and refuses one beyond the proxy's limit, or cuts one
232
264
  * beyond both the machine's limits together: what it carries is not known yet.
233
265
  */
234
- count(socket) {
266
+ count(socket, plain = true) {
235
267
  const address = socket.remoteAddress ?? '';
236
268
  if (this.all.open >= this.totalConnections) {
237
269
  this.proxyAtLimit(`${connections(this.all.open)} are open, base URL routes included`);
238
- socket.end(`HTTP/1.1 503 Service Unavailable\r\nConnection: close\r\n\r\n${PROXY_FULL}\n`);
239
- return;
270
+ // A direct TLS connection cannot read an HTTP answer: it is cut.
271
+ if (plain) {
272
+ socket.end(`HTTP/1.1 503 Service Unavailable\r\nConnection: close\r\n\r\n${PROXY_FULL}\n`);
273
+ }
274
+ else
275
+ socket.destroy();
276
+ return false;
240
277
  }
241
278
  const machine = this.machines.get(address) ?? { open: 0, commands: 0 };
242
279
  if (machine.open >= this.maxConnections + this.routeConnections) {
243
280
  this.atLimit(address, machine, `${connections(machine.open)} are open, base URL routes included`);
244
281
  socket.destroy();
245
- return;
282
+ return false;
246
283
  }
247
284
  machine.open += 1;
248
285
  this.all.open += 1;
@@ -260,6 +297,7 @@ export class EgressProxy {
260
297
  this.underLimit(address, machine);
261
298
  this.proxyUnderLimit();
262
299
  });
300
+ return true;
263
301
  }
264
302
  /**
265
303
  * Why `socket` may not carry a command's traffic, `undefined` when it may: always once it does;
@@ -390,6 +428,70 @@ export class EgressProxy {
390
428
  upstream.on('error', () => socket.destroy());
391
429
  socket.once('close', () => upstream.destroy());
392
430
  }
431
+ /**
432
+ * A TLS connection a program made directly, its host's name resolved to the proxy's address: the
433
+ * host its ClientHello names (SNI) is allowed as the host of a tunnel would be, then the
434
+ * connection is relayed to it on 443, never decrypted. One that names no host, or is no TLS, is
435
+ * cut: there is no HTTP to answer it with.
436
+ */
437
+ direct(socket) {
438
+ socket.on('error', () => socket.destroy());
439
+ if (!this.count(socket, false))
440
+ return;
441
+ const address = socket.remoteAddress;
442
+ const policy = this.policyFor(address);
443
+ if (policy === undefined) {
444
+ this.refused({ address, why: UNKNOWN });
445
+ socket.destroy();
446
+ return;
447
+ }
448
+ void clientHello(socket, Buffer.alloc(0)).then(({ bytes, hello }) => {
449
+ if (socket.destroyed)
450
+ return;
451
+ const named = directHost(hello);
452
+ if ('why' in named) {
453
+ this.refused({ address, policy, why: named.why });
454
+ socket.destroy();
455
+ return;
456
+ }
457
+ const { host } = named;
458
+ const reach = reachability(policy, host);
459
+ const refusal = isListedHost(policy.allowedHosts, host)
460
+ ? reach.error
461
+ : `${host} is not reachable from the sandbox.`;
462
+ const full = refusal ?? this.commandRefusal(socket);
463
+ if (full !== undefined) {
464
+ this.refused({ address, policy, target: host, why: full });
465
+ socket.destroy();
466
+ return;
467
+ }
468
+ const upstream = connect({ host, port: this.tunnelPort, lookup: reach.lookup }, () => {
469
+ upstream.write(bytes);
470
+ upstream.pipe(socket);
471
+ socket.pipe(upstream);
472
+ });
473
+ upstream.on('error', () => socket.destroy());
474
+ socket.once('close', () => upstream.destroy());
475
+ });
476
+ }
477
+ /**
478
+ * A plain HTTP request a program sent directly, its host's name resolved to the proxy's
479
+ * address: sent on to its `Host` as a request through `HTTP_PROXY` would be.
480
+ */
481
+ forwardDirect(req, res) {
482
+ const address = req.socket.remoteAddress;
483
+ const policy = this.policyFor(address);
484
+ if (policy === undefined) {
485
+ this.deny(res, { address, why: UNKNOWN });
486
+ return;
487
+ }
488
+ const host = req.headers.host;
489
+ if (host === undefined || host === '' || !(req.url ?? '').startsWith('/')) {
490
+ this.deny(res, { address, policy, why: 'A direct HTTP request must name its host (Host).' });
491
+ return;
492
+ }
493
+ this.forwardPlain(req, res, { policy, url: `http://${host}${req.url ?? '/'}` });
494
+ }
393
495
  /**
394
496
  * A plain request: a base URL route, its credentials put in, or, through `HTTP_PROXY`, plain HTTP
395
497
  * to an allowed host, as package mirrors still serve, with no credential at all.
@@ -403,7 +505,7 @@ export class EgressProxy {
403
505
  }
404
506
  const route = targetOf(req.url ?? '');
405
507
  if (route === undefined) {
406
- this.forwardPlain(req, res, policy);
508
+ this.forwardPlain(req, res, { policy });
407
509
  return;
408
510
  }
409
511
  const refusal = routeRefusal(policy, route);
@@ -415,8 +517,8 @@ export class EgressProxy {
415
517
  this.send(req, res, { policy, target: route, transformations: policy.transformations });
416
518
  }
417
519
  /** A plain HTTP request through `HTTP_PROXY`: sent on to an allowed host, refused otherwise. */
418
- forwardPlain(req, res, policy) {
419
- const plain = plainTarget(req.url ?? '');
520
+ forwardPlain(req, res, { policy, url = req.url ?? '' }) {
521
+ const plain = plainTarget(url);
420
522
  if (plain !== undefined && isListedHost(policy.allowedHosts, plain.hostname)) {
421
523
  const full = this.commandRefusal(req.socket);
422
524
  if (full !== undefined) {
@@ -11,6 +11,12 @@ export declare function proxyConfig(env: Environment, limits?: string | undefine
11
11
  idleExitMs?: number;
12
12
  maxConnections: number;
13
13
  port: number;
14
+ /**
15
+ * Where the proxy takes the direct connections of programs that ignore the proxy variables: TLS
16
+ * on `tlsPort` (443), plain HTTP on `httpPort` (80). Unset, it takes none.
17
+ */
18
+ tlsPort?: number;
19
+ httpPort?: number;
14
20
  routeConnections: number;
15
21
  token: string;
16
22
  totalConnections: number;
@@ -16,6 +16,8 @@ export function proxyConfig(env, limits = readLimits()) {
16
16
  }
17
17
  return {
18
18
  port: Number.parseInt(env['SANDBOX_PROXY_PORT'] ?? String(DEFAULT_PROXY_PORT), 10),
19
+ tlsPort: directPort('SANDBOX_PROXY_TLS_PORT', env),
20
+ httpPort: directPort('SANDBOX_PROXY_HTTP_PORT', env),
19
21
  adminPort: Number.parseInt(env['SANDBOX_PROXY_ADMIN_PORT'] ?? String(DEFAULT_PROXY_ADMIN_PORT), 10),
20
22
  host: env['HOST'] ?? '0.0.0.0',
21
23
  allowPrivateNetwork: env['SANDBOX_ALLOW_PRIVATE_NETWORK'] === 'true',
@@ -35,6 +37,17 @@ export function proxyConfig(env, limits = readLimits()) {
35
37
  token,
36
38
  };
37
39
  }
40
+ /** A port of the direct connections, 1 to 65535; `undefined` when unset or empty. */
41
+ function directPort(name, env) {
42
+ const value = env[name];
43
+ if (value === undefined || value === '')
44
+ return undefined;
45
+ const port = Number(value);
46
+ if (!Number.isInteger(port) || port < 1 || port > 65_535) {
47
+ throw new Error(`${name}: \`${value}\` is not a port.`);
48
+ }
49
+ return port;
50
+ }
38
51
  /** `SANDBOX_PROXY_IDLE_EXIT_MINUTES`, a positive integer: never exits when unset. */
39
52
  function idleExitMs(value) {
40
53
  if (value === undefined || value === '')
@@ -94,6 +107,15 @@ export function main(env) {
94
107
  const admin = createAdminServer({ registry, token: config.token, logger });
95
108
  proxy.server.listen(config.port, config.host, () => logger.info(`Egress proxy listening on ${config.host}:${config.port}`));
96
109
  admin.listen(config.adminPort, config.host, () => logger.info(`Administration API listening on ${config.host}:${config.adminPort}`));
110
+ // The direct connections, once the sandboxes' DNS answers the proxy's address for every name.
111
+ if (config.tlsPort !== undefined) {
112
+ const { tlsPort } = config;
113
+ proxy.tlsServer.listen(tlsPort, config.host, () => logger.info(`Direct TLS connections taken on ${config.host}:${tlsPort}`));
114
+ }
115
+ if (config.httpPort !== undefined) {
116
+ const { httpPort } = config;
117
+ proxy.httpServer.listen(httpPort, config.host, () => logger.info(`Direct HTTP requests taken on ${config.host}:${httpPort}`));
118
+ }
97
119
  const shutDown = (code) => {
98
120
  proxy.close();
99
121
  admin.closeAllConnections();
@@ -1048,10 +1048,13 @@ export class Sandboxes {
1048
1048
  }
1049
1049
  }
1050
1050
  };
1051
+ const waiting = Date.now();
1051
1052
  const [registerMs, bootMs] = await Promise.all([
1052
1053
  registered(),
1053
1054
  timed(() => this.waitForAgent(name, agent)),
1054
1055
  ]);
1056
+ // The registration runs alongside the boot: only what it took beyond it follows the boot.
1057
+ const registerAfterBootMs = Math.min(registerMs, Date.now() - waiting - bootMs);
1055
1058
  const configuring = Date.now();
1056
1059
  const { home, workingDirectory } = await agent.configure({
1057
1060
  proxy: this.options.proxyUrl,
@@ -1061,7 +1064,7 @@ export class Sandboxes {
1061
1064
  return {
1062
1065
  description: { name, home, workingDirectory },
1063
1066
  bootMs,
1064
- agentMs: registerMs + Date.now() - configuring,
1067
+ agentMs: registerAfterBootMs + Date.now() - configuring,
1065
1068
  };
1066
1069
  }
1067
1070
  async waitForAgent(name, agent) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ai-sdk-sandbox-gce",
3
- "version": "0.6.0",
3
+ "version": "0.7.0",
4
4
  "description": "Compute Engine sandboxes for AI SDK harness agents: Claude Code, Codex and friends in a virtual machine of their own on Google Cloud, Docker included, stopped between turns.",
5
5
  "keywords": [
6
6
  "ai",
@@ -58,8 +58,8 @@
58
58
  "vitest": "^5.1.0",
59
59
  "zod": "^4.6.7",
60
60
  "@repo/build": "0.0.0",
61
- "@repo/eslint-config": "0.0.0",
62
61
  "@repo/prettier-config": "0.0.0",
62
+ "@repo/eslint-config": "0.0.0",
63
63
  "@repo/typescript-config": "0.0.0",
64
64
  "@repo/vitest-config": "0.0.0"
65
65
  },