ai-sdk-sandbox-gce 0.2.2 → 0.3.1

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.
@@ -1,5 +1,6 @@
1
1
  import type { HarnessV1RequestTransformation } from '@ai-sdk/harness';
2
2
  import type { IncomingHttpHeaders } from 'node:http';
3
+ import type { Traffic } from './traffic.js';
3
4
  /** What one sandbox may reach, and the credentials its requests leave with. */
4
5
  export interface EgressPolicy {
5
6
  /** The sandbox's name, which the proxy's log lines name it by. */
@@ -12,6 +13,8 @@ export interface EgressPolicy {
12
13
  readonly transformations: readonly HarnessV1RequestTransformation[];
13
14
  /** Let it reach private addresses and plain HTTP base URLs: tests and local runs only. */
14
15
  readonly allowPrivateNetwork: boolean;
16
+ /** Where the bytes its connections move are counted. */
17
+ readonly traffic?: Traffic;
15
18
  }
16
19
  /** What the egress proxy knows of one request on its way out. */
17
20
  export interface OutgoingRequest {
@@ -1,13 +1,17 @@
1
1
  import type { Server } from 'node:http';
2
2
  import type { Logger } from '../common/logger.js';
3
3
  import type { EgressPolicy } from './egress-policy.js';
4
+ /** The most connections a sandbox's machine holds open through the proxy at once, by default. */
5
+ export declare const DEFAULT_MAX_CONNECTIONS = 128;
4
6
  /**
5
7
  * The way out of the sandboxes, on a machine of its own, outside their security boundary: the VPC
6
8
  * firewall lets their machines reach nothing else. Every connection is the sandbox's whose machine
7
9
  * it comes from, and is one of two things:
8
10
  *
9
11
  * - a `CONNECT host:443`, through the sandbox's `HTTPS_PROXY`: tunnelled when `host` is allowed,
10
- * refused otherwise. The tunnel is TLS end to end: nothing in it is read or changed;
12
+ * refused otherwise. The tunnel is TLS end to end: its ClientHello is read, and the tunnel cut
13
+ * unless it names `host` (SNI), so that no other site behind the same CDN is reached; nothing
14
+ * else in it is read or changed;
11
15
  * - a plain request to a base URL route (`/https/<host>/…`, see `proxy-routes.ts`): sent on to
12
16
  * its host, the sandbox's request transformations applied to it on the way. The real credential
13
17
  * never enters the sandbox;
@@ -23,8 +27,28 @@ export declare class EgressProxy {
23
27
  private readonly policyFor;
24
28
  private readonly logger;
25
29
  readonly server: Server;
26
- constructor(policyFor: (address: string | undefined) => EgressPolicy | undefined, logger?: Logger);
30
+ /** The connections each machine holds open, by its address. */
31
+ private readonly open;
32
+ /** The machines cut at their limit since they last went under it: logged once. */
33
+ private readonly capped;
34
+ private readonly maxConnections;
35
+ private readonly tunnelPort;
36
+ /**
37
+ * @param options.maxConnections The most connections a sandbox's machine holds open at once:
38
+ * one more is cut at once, so that no sandbox takes the sockets of the others.
39
+ * @param options.tunnelPort The port a tunnel reaches on its host, whatever port its `CONNECT`
40
+ * names (443, the only one allowed). Tests only.
41
+ */
42
+ constructor(policyFor: (address: string | undefined) => EgressPolicy | undefined, logger?: Logger, { maxConnections, tunnelPort, }?: {
43
+ maxConnections?: number;
44
+ tunnelPort?: number;
45
+ });
27
46
  close(): void;
47
+ /**
48
+ * Counts the connections of a machine, and cuts the one beyond {@link maxConnections}: logged the
49
+ * first time only, until the machine goes under its limit again.
50
+ */
51
+ private count;
28
52
  private tunnel;
29
53
  /**
30
54
  * A plain request: a base URL route, its credentials put in, or, through `HTTP_PROXY`, plain HTTP
@@ -5,6 +5,7 @@ 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';
7
7
  import { isPrivateAddress, publicOnlyLookup } from './network-guard.js';
8
+ import { readClientHello } from './tls-hello.js';
8
9
  /** Headers of one hop only: never forwarded. */
9
10
  const HOP_BY_HOP = new Set([
10
11
  'connection',
@@ -31,6 +32,67 @@ function reachability(policy, host) {
31
32
  return { lookup: publicOnlyLookup };
32
33
  }
33
34
  const UNKNOWN = 'This machine is no sandbox the proxy serves.';
35
+ /** The most connections a sandbox's machine holds open through the proxy at once, by default. */
36
+ export const DEFAULT_MAX_CONNECTIONS = 128;
37
+ /** The most bytes a ClientHello is read from: well over any real one. */
38
+ const MAX_HELLO_BYTES = 64 * 1024;
39
+ /** How long a client has to send its ClientHello once its tunnel is open. */
40
+ const HELLO_TIMEOUT_MS = 10_000;
41
+ /** A name as TLS and DNS compare it: whatever its case, without its trailing dot. */
42
+ const canonical = (name) => name.toLowerCase().replace(/\.$/, '');
43
+ /**
44
+ * Reads the ClientHello a client opens its tunnel with, `head` the bytes that came with the
45
+ * `CONNECT`: the bytes read, and the hello, unless they are no TLS or the client went quiet.
46
+ */
47
+ function clientHello(socket, head) {
48
+ return new Promise((resolve) => {
49
+ let bytes = head;
50
+ const done = (hello) => {
51
+ clearTimeout(timer);
52
+ socket.off('data', received);
53
+ socket.off('close', closed);
54
+ socket.pause();
55
+ resolve({ bytes, hello });
56
+ };
57
+ const check = () => {
58
+ const hello = readClientHello(bytes);
59
+ if (hello.kind === 'hello')
60
+ done(hello);
61
+ else if (hello.kind === 'invalid' || bytes.length > MAX_HELLO_BYTES)
62
+ done();
63
+ };
64
+ const received = (chunk) => {
65
+ bytes = Buffer.concat([bytes, chunk]);
66
+ check();
67
+ };
68
+ const closed = () => done();
69
+ const timer = setTimeout(done, HELLO_TIMEOUT_MS);
70
+ socket.on('data', received);
71
+ socket.once('close', closed);
72
+ if (bytes.length > 0)
73
+ check();
74
+ });
75
+ }
76
+ /**
77
+ * Why a tunnel to `host` may not carry the TLS connection `hello` opens: `undefined` when it may.
78
+ * The server a ClientHello names is the one a shared front end, a CDN, serves: a tunnel opened to
79
+ * an allowed host must not reach another site of the same CDN.
80
+ */
81
+ function helloRefusal(host, hello) {
82
+ if (hello?.kind !== 'hello')
83
+ return `Only TLS goes through a tunnel to ${host}.`;
84
+ const named = hello.serverName === undefined ? undefined : canonical(hello.serverName);
85
+ if (isIP(host) !== 0) {
86
+ return named === undefined
87
+ ? undefined
88
+ : `A tunnel to ${host} may not name ${named} in its TLS.`;
89
+ }
90
+ if (named === canonical(host))
91
+ return undefined;
92
+ return named === undefined
93
+ ? `A tunnel to ${host} must name it in its TLS (SNI).`
94
+ : `A tunnel to ${host} may not name ${named} in its TLS.`;
95
+ }
34
96
  const refuse = (res, message) => {
35
97
  res.writeHead(403, { 'content-type': 'text/plain' }).end(`${message}\n`);
36
98
  };
@@ -77,7 +139,9 @@ function targetOf(url) {
77
139
  * it comes from, and is one of two things:
78
140
  *
79
141
  * - a `CONNECT host:443`, through the sandbox's `HTTPS_PROXY`: tunnelled when `host` is allowed,
80
- * refused otherwise. The tunnel is TLS end to end: nothing in it is read or changed;
142
+ * refused otherwise. The tunnel is TLS end to end: its ClientHello is read, and the tunnel cut
143
+ * unless it names `host` (SNI), so that no other site behind the same CDN is reached; nothing
144
+ * else in it is read or changed;
81
145
  * - a plain request to a base URL route (`/https/<host>/…`, see `proxy-routes.ts`): sent on to
82
146
  * its host, the sandbox's request transformations applied to it on the way. The real credential
83
147
  * never enters the sandbox;
@@ -93,22 +157,65 @@ export class EgressProxy {
93
157
  policyFor;
94
158
  logger;
95
159
  server;
96
- constructor(policyFor, logger = silentLogger) {
160
+ /** The connections each machine holds open, by its address. */
161
+ open = new Map();
162
+ /** The machines cut at their limit since they last went under it: logged once. */
163
+ capped = new Set();
164
+ maxConnections;
165
+ tunnelPort;
166
+ /**
167
+ * @param options.maxConnections The most connections a sandbox's machine holds open at once:
168
+ * one more is cut at once, so that no sandbox takes the sockets of the others.
169
+ * @param options.tunnelPort The port a tunnel reaches on its host, whatever port its `CONNECT`
170
+ * names (443, the only one allowed). Tests only.
171
+ */
172
+ constructor(policyFor, logger = silentLogger, { maxConnections = DEFAULT_MAX_CONNECTIONS, tunnelPort = 443, } = {}) {
97
173
  this.policyFor = policyFor;
98
174
  this.logger = logger;
175
+ this.maxConnections = maxConnections;
176
+ this.tunnelPort = tunnelPort;
99
177
  this.server = createServer((req, res) => this.forward(req, res));
178
+ this.server.on('connection', (socket) => this.count(socket));
100
179
  this.server.on('connect', (req, socket, head) => this.tunnel(req, socket, head));
101
180
  }
102
181
  close() {
103
182
  this.server.closeAllConnections();
104
183
  this.server.close();
105
184
  }
185
+ /**
186
+ * Counts the connections of a machine, and cuts the one beyond {@link maxConnections}: logged the
187
+ * first time only, until the machine goes under its limit again.
188
+ */
189
+ count(socket) {
190
+ const address = socket.remoteAddress ?? '';
191
+ const open = this.open.get(address) ?? 0;
192
+ if (open >= this.maxConnections) {
193
+ if (!this.capped.has(address)) {
194
+ this.capped.add(address);
195
+ const why = `${open} connections are open already, the most a sandbox holds at once.`;
196
+ this.refused({ address, policy: this.policyFor(address), why });
197
+ }
198
+ socket.destroy();
199
+ return;
200
+ }
201
+ this.open.set(address, open + 1);
202
+ this.policyFor(address)?.traffic?.track(socket);
203
+ socket.once('close', () => {
204
+ const left = (this.open.get(address) ?? 1) - 1;
205
+ if (left === 0)
206
+ this.open.delete(address);
207
+ else
208
+ this.open.set(address, left);
209
+ this.capped.delete(address);
210
+ });
211
+ }
106
212
  tunnel(req, socket, head) {
107
213
  socket.on('error', () => socket.destroy());
108
214
  const { hostname, port } = new URL(`http://${req.url ?? ''}`);
109
- const policy = this.policyFor(socket.remoteAddress);
215
+ const address = socket.remoteAddress;
216
+ const policy = this.policyFor(address);
110
217
  if (policy === undefined) {
111
- this.refused({ address: socket.remoteAddress, target: req.url, why: UNKNOWN });
218
+ this.refused({ address, target: req.url, why: UNKNOWN });
112
219
  socket.end(`HTTP/1.1 403 Forbidden\r\n\r\n${UNKNOWN}\n`);
113
220
  return;
114
221
  }
@@ -116,15 +223,26 @@ export class EgressProxy {
116
223
  const listed = port === '443' && isListedHost(policy.allowedHosts, hostname);
117
224
  const refusal = listed ? reach.error : `${hostname} is not reachable from the sandbox.`;
118
225
  if (refusal !== undefined) {
119
- this.refused({ address: socket.remoteAddress, policy, target: req.url, why: refusal });
226
+ this.refused({ address, policy, target: req.url, why: refusal });
120
227
  socket.end(`HTTP/1.1 403 Forbidden\r\n\r\n${refusal}\n`);
121
228
  return;
122
229
  }
123
- const upstream = connect({ host: hostname, port: 443, lookup: reach.lookup }, () => {
230
+ const upstream = connect({ host: hostname, port: this.tunnelPort, lookup: reach.lookup }, () => {
124
231
  socket.write('HTTP/1.1 200 Connection Established\r\n\r\n');
125
- upstream.write(head);
126
- upstream.pipe(socket);
127
- socket.pipe(upstream);
232
+ void clientHello(socket, head).then(({ bytes, hello }) => {
233
+ if (socket.destroyed)
234
+ return;
235
+ const why = helloRefusal(hostname, hello);
236
+ if (why !== undefined) {
237
+ this.refused({ address, policy, target: req.url, why });
238
+ socket.destroy();
239
+ upstream.destroy();
240
+ return;
241
+ }
242
+ upstream.write(bytes);
243
+ upstream.pipe(socket);
244
+ socket.pipe(upstream);
245
+ });
128
246
  });
129
247
  upstream.on('error', () => socket.destroy());
130
248
  socket.once('close', () => upstream.destroy());
@@ -4,6 +4,7 @@ export declare function proxyConfig(env: Environment): {
4
4
  adminPort: number;
5
5
  allowPrivateNetwork: boolean;
6
6
  host: string;
7
+ maxConnections: number;
7
8
  port: number;
8
9
  token: string;
9
10
  };
@@ -1,7 +1,7 @@
1
1
  import { createLogger } from '../common/logger.js';
2
2
  import { DEFAULT_PROXY_ADMIN_PORT, DEFAULT_PROXY_PORT } from '../protocol/proxy.js';
3
3
  import { createAdminServer } from './admin-server.js';
4
- import { EgressProxy } from './egress-proxy.js';
4
+ import { DEFAULT_MAX_CONNECTIONS, EgressProxy } from './egress-proxy.js';
5
5
  import { SandboxRegistry } from './registry.js';
6
6
  /** The proxy's settings, from its environment, which the systemd unit of its machine sets. */
7
7
  export function proxyConfig(env) {
@@ -14,9 +14,20 @@ export function proxyConfig(env) {
14
14
  adminPort: Number.parseInt(env['SANDBOX_PROXY_ADMIN_PORT'] ?? String(DEFAULT_PROXY_ADMIN_PORT), 10),
15
15
  host: env['HOST'] ?? '0.0.0.0',
16
16
  allowPrivateNetwork: env['SANDBOX_ALLOW_PRIVATE_NETWORK'] === 'true',
17
+ maxConnections: maxConnections(env['SANDBOX_PROXY_MAX_CONNECTIONS']),
17
18
  token,
18
19
  };
19
20
  }
21
+ /** `SANDBOX_PROXY_MAX_CONNECTIONS`, a positive integer: {@link DEFAULT_MAX_CONNECTIONS} when unset. */
22
+ function maxConnections(value) {
23
+ if (value === undefined || value === '')
24
+ return DEFAULT_MAX_CONNECTIONS;
25
+ const parsed = Number(value);
26
+ if (!Number.isInteger(parsed) || parsed < 1) {
27
+ throw new Error(`SANDBOX_PROXY_MAX_CONNECTIONS: \`${value}\` is not a positive integer.`);
28
+ }
29
+ return parsed;
30
+ }
20
31
  /** `ai-sdk-sandbox-gce proxy`: serves the sandboxes and the administration API until stopped. */
21
32
  export function main(env) {
22
33
  const logger = createLogger({ json: env['LOG_FORMAT'] !== 'text' });
@@ -24,8 +35,10 @@ export function main(env) {
24
35
  if (config.allowPrivateNetwork) {
25
36
  logger.warn('SANDBOX_ALLOW_PRIVATE_NETWORK=true: the sandboxes may reach the VPC and the metadata server. For tests only.');
26
37
  }
27
- const registry = new SandboxRegistry(config.allowPrivateNetwork);
28
- const proxy = new EgressProxy((address) => registry.policyFor(address), logger);
38
+ const registry = new SandboxRegistry(config.allowPrivateNetwork, logger);
39
+ const proxy = new EgressProxy((address) => registry.policyFor(address), logger, {
40
+ maxConnections: config.maxConnections,
41
+ });
29
42
  const admin = createAdminServer({ registry, token: config.token, logger });
30
43
  proxy.server.listen(config.port, config.host, () => logger.info(`Egress proxy listening on ${config.host}:${config.port}`));
31
44
  admin.listen(config.adminPort, config.host, () => logger.info(`Administration API listening on ${config.host}:${config.adminPort}`));
@@ -1,9 +1,9 @@
1
1
  import { lookup } from 'node:dns';
2
2
  import { BlockList, isIP } from 'node:net';
3
3
  /**
4
- * Addresses a sandbox must never reach through the proxy: the proxy's own loopback, the metadata
5
- * server (169.254.169.254, the proxy's service account token), the VPC and every other range
6
- * that is not the public internet.
4
+ * IPv4 addresses a sandbox must never reach through the proxy: the proxy's own loopback, the
5
+ * metadata server (169.254.169.254, the proxy's service account token), the VPC and every other
6
+ * range that is not the public internet.
7
7
  */
8
8
  const PRIVATE = new BlockList();
9
9
  for (const [network, prefix] of [
@@ -20,14 +20,25 @@ for (const [network, prefix] of [
20
20
  ]) {
21
21
  PRIVATE.addSubnet(network, prefix, 'ipv4');
22
22
  }
23
+ /**
24
+ * The IPv6 addresses of the public internet: global unicast (`2000::/3`), and nothing else, so
25
+ * that no range left out of a list of private ones (site-local, IPv4-compatible `::a.b.c.d`,
26
+ * local-use NAT64) slips through.
27
+ */
28
+ const GLOBAL_IPV6 = new BlockList();
29
+ GLOBAL_IPV6.addSubnet('2000::', 3, 'ipv6');
30
+ /**
31
+ * The ranges of `2000::/3` that are no public host all the same: Teredo (`2001::/32`), whose
32
+ * addresses carry an IPv4 one the network may route them to, benchmarking and documentation.
33
+ */
34
+ const NOT_GLOBAL_IPV6 = new BlockList();
23
35
  for (const [network, prefix] of [
24
- ['::', 128],
25
- ['::1', 128],
26
- ['fc00::', 7],
27
- ['fe80::', 10],
28
- ['ff00::', 8],
36
+ ['2001::', 32],
37
+ ['2001:2::', 48],
38
+ ['2001:db8::', 32],
39
+ ['3fff::', 20],
29
40
  ]) {
30
- PRIVATE.addSubnet(network, prefix, 'ipv6');
41
+ NOT_GLOBAL_IPV6.addSubnet(network, prefix, 'ipv6');
31
42
  }
32
43
  /** The two 16-bit groups of the IPv4 address of `bytes`. */
33
44
  const ipv4Groups = ([a = 0, b = 0, c = 0, d = 0]) => [
@@ -52,11 +63,14 @@ function groupsOf(address) {
52
63
  /** The IPv4 address made of two 16-bit groups. */
53
64
  const ipv4Of = (high = 0, low = 0) => [high >> 8, high & 0xff, low >> 8, low & 0xff].join('.');
54
65
  /**
55
- * The IPv4 address an IPv6 one carries, which the network may route it to: NAT64
56
- * (`64:ff9b::/96`) and 6to4 (`2002::/16`).
66
+ * The IPv4 address an IPv6 one carries, which the network may route it to: IPv4-mapped
67
+ * (`::ffff:0:0/96`), NAT64 (`64:ff9b::/96`) and 6to4 (`2002::/16`).
57
68
  */
58
69
  function embeddedIpv4(address) {
59
70
  const groups = groupsOf(address);
71
+ if (groups.slice(0, 5).every((g) => g === 0) && groups[5] === 0xffff) {
72
+ return ipv4Of(groups[6], groups[7]);
73
+ }
60
74
  if (groups[0] === 0x64 && groups[1] === 0xff9b && groups.slice(2, 6).every((g) => g === 0)) {
61
75
  return ipv4Of(groups[6], groups[7]);
62
76
  }
@@ -75,9 +89,9 @@ export function isPrivateAddress(address) {
75
89
  if (family === 4)
76
90
  return PRIVATE.check(address, 'ipv4');
77
91
  const embedded = embeddedIpv4(address);
78
- if (embedded !== undefined && PRIVATE.check(embedded, 'ipv4'))
79
- return true;
80
- return PRIVATE.check(address, 'ipv6');
92
+ if (embedded !== undefined)
93
+ return PRIVATE.check(embedded, 'ipv4');
94
+ return !GLOBAL_IPV6.check(address, 'ipv6') || NOT_GLOBAL_IPV6.check(address, 'ipv6');
81
95
  }
82
96
  /**
83
97
  * A DNS lookup for `net.connect` and `https.request` that refuses names resolving to a private
@@ -1,6 +1,7 @@
1
1
  import type { HarnessV1RequestTransformation } from '@ai-sdk/harness';
2
2
  import type { ProxyRegistration } from '../protocol/proxy.js';
3
3
  import type { EgressPolicy } from './egress-policy.js';
4
+ import { Traffic } from './traffic.js';
4
5
  /** An IPv4 address as Node.js reports a connection's on a dual-stack socket: `::ffff:10.0.0.3`. */
5
6
  export declare const normalizeAddress: (address: string) => string;
6
7
  /** One sandbox, as the proxy knows it: its machine's address, what it may reach, its credentials. */
@@ -11,6 +12,10 @@ export declare class RegisteredSandbox implements EgressPolicy {
11
12
  allowedHosts: readonly string[];
12
13
  upstreamHosts: readonly string[];
13
14
  transformations: HarnessV1RequestTransformation[];
15
+ /** What tells this registration from the next one of the same sandbox: the registry's to set. */
16
+ serial: number;
17
+ /** The bytes it moved, kept when it is registered again. */
18
+ traffic: Traffic;
14
19
  constructor(name: string, registration: ProxyRegistration, allowPrivateNetwork: boolean);
15
20
  /** The secrets the proxy holds for the sandbox: what its transformations put in requests. */
16
21
  get secrets(): string[];
@@ -1,4 +1,5 @@
1
1
  import { hostsOf } from '../protocol/proxy-routes.js';
2
+ import { Traffic } from './traffic.js';
2
3
  /** The scheme a credential header value may start with, before the secret itself. */
3
4
  const SCHEME = /^(Bearer|Basic|Token)\s+/i;
4
5
  /** Shorter values are no secret worth guarding, and would match by chance. */
@@ -13,6 +14,10 @@ export class RegisteredSandbox {
13
14
  allowedHosts;
14
15
  upstreamHosts;
15
16
  transformations = [];
17
+ /** What tells this registration from the next one of the same sandbox: the registry's to set. */
18
+ serial = 0;
19
+ /** The bytes it moved, kept when it is registered again. */
20
+ traffic = new Traffic();
16
21
  constructor(name, registration, allowPrivateNetwork) {
17
22
  this.name = name;
18
23
  this.allowPrivateNetwork = allowPrivateNetwork;
@@ -1,5 +1,6 @@
1
1
  import type { HarnessV1RequestTransformation } from '@ai-sdk/harness';
2
- import type { ProxyRegistration } from '../protocol/proxy.js';
2
+ import type { Logger } from '../common/logger.js';
3
+ import type { ProxyRegistration, ProxySandbox } from '../protocol/proxy.js';
3
4
  import type { EgressPolicy } from './egress-policy.js';
4
5
  /**
5
6
  * The sandboxes the proxy serves, by name and by the address of their machine. Kept in memory
@@ -8,13 +9,16 @@ import type { EgressPolicy } from './egress-policy.js';
8
9
  */
9
10
  export declare class SandboxRegistry {
10
11
  private readonly allowPrivateNetwork;
12
+ private readonly logger;
11
13
  private readonly byName;
12
14
  private readonly byAddress;
15
+ private registrations;
13
16
  /**
14
17
  * @param allowPrivateNetwork Let the sandboxes reach private addresses and plain HTTP base URLs:
15
18
  * tests and local runs only.
19
+ * @param logger Where the bytes a sandbox moved are told, once it is forgotten.
16
20
  */
17
- constructor(allowPrivateNetwork?: boolean);
21
+ constructor(allowPrivateNetwork?: boolean, logger?: Logger);
18
22
  /**
19
23
  * Registers the sandbox `name`, or registers it again after its machine started anew, perhaps
20
24
  * on another address: what it may reach is replaced, its credentials kept.
@@ -26,8 +30,13 @@ export declare class SandboxRegistry {
26
30
  setTransformations(name: string, transformations: HarnessV1RequestTransformation[]): void;
27
31
  /** Whether one of `texts` holds a credential the proxy keeps for the sandbox `name`. */
28
32
  holdsSecret(name: string, texts: readonly string[]): boolean;
29
- /** Forgets the sandbox `name` and its credentials. Idempotent. */
30
- remove(name: string): void;
33
+ /** The sandboxes the proxy holds. */
34
+ list(): ProxySandbox[];
35
+ /**
36
+ * Forgets the sandbox `name` and its credentials. With `serial`, only the registration that
37
+ * {@link list} gave it: one made since, its machine started again meanwhile, is kept. Idempotent.
38
+ */
39
+ remove(name: string, serial?: number): void;
31
40
  /** The policy of the sandbox whose machine has `address`, if one has. */
32
41
  policyFor(address: string | undefined): EgressPolicy | undefined;
33
42
  private get;
@@ -1,5 +1,7 @@
1
1
  import { HttpError } from '../common/http-error.js';
2
+ import { silentLogger } from '../common/logger.js';
2
3
  import { normalizeAddress, RegisteredSandbox } from './registered-sandbox.js';
4
+ import { formatBytes } from './traffic.js';
3
5
  /**
4
6
  * The sandboxes the proxy serves, by name and by the address of their machine. Kept in memory
5
7
  * alone: the credentials never touch a disk. A connection from an address no sandbox holds is
@@ -7,14 +9,18 @@ import { normalizeAddress, RegisteredSandbox } from './registered-sandbox.js';
7
9
  */
8
10
  export class SandboxRegistry {
9
11
  allowPrivateNetwork;
12
+ logger;
10
13
  byName = new Map();
11
14
  byAddress = new Map();
15
+ registrations = 0;
12
16
  /**
13
17
  * @param allowPrivateNetwork Let the sandboxes reach private addresses and plain HTTP base URLs:
14
18
  * tests and local runs only.
19
+ * @param logger Where the bytes a sandbox moved are told, once it is forgotten.
15
20
  */
16
- constructor(allowPrivateNetwork = false) {
21
+ constructor(allowPrivateNetwork = false, logger = silentLogger) {
17
22
  this.allowPrivateNetwork = allowPrivateNetwork;
23
+ this.logger = logger;
18
24
  }
19
25
  /**
20
26
  * Registers the sandbox `name`, or registers it again after its machine started anew, perhaps
@@ -22,9 +28,11 @@ export class SandboxRegistry {
22
28
  */
23
29
  register(name, registration) {
24
30
  const next = new RegisteredSandbox(name, registration, this.allowPrivateNetwork);
31
+ next.serial = ++this.registrations;
25
32
  const previous = this.byName.get(name);
26
33
  if (previous !== undefined) {
27
34
  next.transformations = previous.transformations;
35
+ next.traffic = previous.traffic;
28
36
  this.forgetAddress(name, previous.address);
29
37
  }
30
38
  this.byName.set(name, next);
@@ -45,13 +53,27 @@ export class SandboxRegistry {
45
53
  const secrets = this.byName.get(name)?.secrets ?? [];
46
54
  return secrets.some((secret) => texts.some((text) => text.includes(secret)));
47
55
  }
48
- /** Forgets the sandbox `name` and its credentials. Idempotent. */
49
- remove(name) {
56
+ /** The sandboxes the proxy holds. */
57
+ list() {
58
+ return [...this.byName.values()].map(({ name, address, serial, traffic }) => ({
59
+ name,
60
+ address,
61
+ serial,
62
+ ...traffic.totals,
63
+ }));
64
+ }
65
+ /**
66
+ * Forgets the sandbox `name` and its credentials. With `serial`, only the registration that
67
+ * {@link list} gave it: one made since, its machine started again meanwhile, is kept. Idempotent.
68
+ */
69
+ remove(name, serial) {
50
70
  const sandbox = this.byName.get(name);
51
- if (sandbox === undefined)
71
+ if (sandbox === undefined || (serial !== undefined && sandbox.serial !== serial))
52
72
  return;
53
73
  this.byName.delete(name);
54
74
  this.forgetAddress(name, sandbox.address);
75
+ const { sent, received } = sandbox.traffic.totals;
76
+ this.logger.info(`${name} forgotten, having sent ${formatBytes(sent)} out and received ${formatBytes(received)}`);
55
77
  }
56
78
  /** The policy of the sandbox whose machine has `address`, if one has. */
57
79
  policyFor(address) {
@@ -0,0 +1,20 @@
1
+ /** What the first bytes of a tunnel say of the TLS connection they open. */
2
+ export type ClientHello =
3
+ /** A ClientHello, read whole: the server it names, if it names one. */
4
+ {
5
+ kind: 'hello';
6
+ serverName?: string;
7
+ }
8
+ /** More bytes are needed to read it whole. */
9
+ | {
10
+ kind: 'incomplete';
11
+ }
12
+ /** Not a TLS ClientHello: another protocol, or a malformed one. */
13
+ | {
14
+ kind: 'invalid';
15
+ };
16
+ /**
17
+ * Reads the ClientHello a client opens a TLS connection with, from the first bytes it sent: what
18
+ * the egress proxy checks before it lets a tunnel's bytes through.
19
+ */
20
+ export declare function readClientHello(data: Buffer): ClientHello;
@@ -0,0 +1,109 @@
1
+ const HANDSHAKE_RECORD = 22;
2
+ const CLIENT_HELLO = 1;
3
+ const SERVER_NAME_EXTENSION = 0;
4
+ const HOST_NAME = 0;
5
+ const INCOMPLETE = { kind: 'incomplete' };
6
+ const INVALID = { kind: 'invalid' };
7
+ /**
8
+ * The handshake bytes the TLS records at the start of `data` carry, put back together: a
9
+ * ClientHello may span several records. `undefined` when a record is no handshake one.
10
+ */
11
+ function handshakeBytes(data) {
12
+ const fragments = [];
13
+ let offset = 0;
14
+ while (offset + 5 <= data.length) {
15
+ if (data[offset] !== HANDSHAKE_RECORD || data[offset + 1] !== 3)
16
+ return undefined;
17
+ const length = data.readUInt16BE(offset + 3);
18
+ if (offset + 5 + length > data.length)
19
+ break;
20
+ fragments.push(data.subarray(offset + 5, offset + 5 + length));
21
+ offset += 5 + length;
22
+ }
23
+ return Buffer.concat(fragments);
24
+ }
25
+ /** A reader of the fields of a ClientHello, which fails on any length past its end. */
26
+ class Fields {
27
+ bytes;
28
+ offset = 0;
29
+ constructor(bytes) {
30
+ this.bytes = bytes;
31
+ }
32
+ skip(length) {
33
+ if (this.offset + length > this.bytes.length)
34
+ throw new RangeError('Past the end');
35
+ this.offset += length;
36
+ }
37
+ uint(size) {
38
+ const value = size === 1 ? this.bytes[this.offset] : this.bytes.readUInt16BE(this.offset);
39
+ this.skip(size);
40
+ return value ?? 0;
41
+ }
42
+ /** The `length` bytes that follow, as a reader of their own. */
43
+ take(length) {
44
+ const start = this.offset;
45
+ this.skip(length);
46
+ return new Fields(this.bytes.subarray(start, start + length));
47
+ }
48
+ get done() {
49
+ return this.offset === this.bytes.length;
50
+ }
51
+ text() {
52
+ return this.bytes.toString('latin1');
53
+ }
54
+ }
55
+ /** The host name of a `server_name` extension (RFC 6066), if it carries one. */
56
+ function hostNameOf(extension) {
57
+ const names = extension.take(extension.uint(2));
58
+ while (!names.done) {
59
+ const type = names.uint(1);
60
+ const name = names.take(names.uint(2));
61
+ if (type === HOST_NAME)
62
+ return name.text();
63
+ }
64
+ return undefined;
65
+ }
66
+ /** The server a whole ClientHello handshake message names (RFC 8446, section 4.1.2). */
67
+ function serverNameOf(hello) {
68
+ hello.skip(2 + 32); // legacy_version, random
69
+ hello.skip(hello.uint(1)); // legacy_session_id
70
+ hello.skip(hello.uint(2)); // cipher_suites
71
+ hello.skip(hello.uint(1)); // legacy_compression_methods
72
+ if (hello.done)
73
+ return undefined;
74
+ const extensions = hello.take(hello.uint(2));
75
+ while (!extensions.done) {
76
+ const type = extensions.uint(2);
77
+ const data = extensions.take(extensions.uint(2));
78
+ if (type === SERVER_NAME_EXTENSION)
79
+ return hostNameOf(data);
80
+ }
81
+ return undefined;
82
+ }
83
+ /**
84
+ * Reads the ClientHello a client opens a TLS connection with, from the first bytes it sent: what
85
+ * the egress proxy checks before it lets a tunnel's bytes through.
86
+ */
87
+ export function readClientHello(data) {
88
+ if (data.length === 0)
89
+ return INCOMPLETE;
90
+ if (data[0] !== HANDSHAKE_RECORD)
91
+ return INVALID;
92
+ const bytes = handshakeBytes(data);
93
+ if (bytes === undefined)
94
+ return INVALID;
95
+ if (bytes.length < 4)
96
+ return INCOMPLETE;
97
+ if (bytes[0] !== CLIENT_HELLO)
98
+ return INVALID;
99
+ const length = bytes.readUIntBE(1, 3);
100
+ if (bytes.length < 4 + length)
101
+ return INCOMPLETE;
102
+ try {
103
+ const serverName = serverNameOf(new Fields(bytes.subarray(4, 4 + length)));
104
+ return serverName === undefined ? { kind: 'hello' } : { kind: 'hello', serverName };
105
+ }
106
+ catch {
107
+ return INVALID;
108
+ }
109
+ }