@ship.zone/runner 3.0.0 → 5.0.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.
Files changed (80) hide show
  1. package/.smartconfig.json +19 -1
  2. package/changelog.md +61 -0
  3. package/dist_rust/runnerworkspace_linux_amd64_musl +0 -0
  4. package/dist_rust/runnerworkspace_linux_amd64_musl.tsrust-build.json +4 -4
  5. package/dist_rust/runnerworkspace_linux_arm64_musl +0 -0
  6. package/dist_rust/runnerworkspace_linux_arm64_musl.tsrust-build.json +4 -4
  7. package/dist_ts/00_commitinfo_data.js +3 -3
  8. package/dist_ts/api-client.d.ts +2 -1
  9. package/dist_ts/api-client.js +10 -2
  10. package/dist_ts/artifact-manager.js +1 -1
  11. package/dist_ts/attempt-state.js +1 -1
  12. package/dist_ts/cache-manager.js +1 -1
  13. package/dist_ts/cli-entry.js +17 -3
  14. package/dist_ts/cli.d.ts +7 -0
  15. package/dist_ts/cli.js +155 -35
  16. package/dist_ts/config.js +75 -22
  17. package/dist_ts/egress-proxy.d.ts +99 -0
  18. package/dist_ts/egress-proxy.js +607 -0
  19. package/dist_ts/errors.js +1 -1
  20. package/dist_ts/filesystem.js +1 -1
  21. package/dist_ts/index.d.ts +5 -1
  22. package/dist_ts/index.js +6 -2
  23. package/dist_ts/interfaces.d.ts +85 -31
  24. package/dist_ts/interfaces.js +1 -1
  25. package/dist_ts/log-sender.js +1 -1
  26. package/dist_ts/microvm-executor.d.ts +90 -0
  27. package/dist_ts/microvm-executor.js +1078 -0
  28. package/dist_ts/node-version.d.ts +11 -0
  29. package/dist_ts/node-version.js +43 -0
  30. package/dist_ts/npm-grants.d.ts +9 -0
  31. package/dist_ts/npm-grants.js +44 -0
  32. package/dist_ts/oci-registry.d.ts +73 -0
  33. package/dist_ts/oci-registry.js +508 -0
  34. package/dist_ts/plugins.d.ts +6 -2
  35. package/dist_ts/plugins.js +7 -3
  36. package/dist_ts/protocol-validator.d.ts +3 -5
  37. package/dist_ts/protocol-validator.js +27 -51
  38. package/dist_ts/redactor.js +1 -1
  39. package/dist_ts/registration-state.js +1 -1
  40. package/dist_ts/runner.d.ts +5 -5
  41. package/dist_ts/runner.js +47 -22
  42. package/dist_ts/source-workspace.js +1 -1
  43. package/dist_ts/spec-version.js +1 -1
  44. package/dist_ts/staging-scavenger.js +1 -1
  45. package/dist_ts/state-owner.js +4 -2
  46. package/dist_ts/transfer-archive.js +1 -1
  47. package/dist_ts/validation.js +1 -1
  48. package/dist_ts/vsock-protocol.d.ts +130 -0
  49. package/dist_ts/vsock-protocol.js +336 -0
  50. package/dist_ts/wire-schema.js +1 -1
  51. package/package.json +19 -15
  52. package/readme.md +106 -108
  53. package/rust/Cargo.lock +1 -0
  54. package/rust/Cargo.toml +2 -1
  55. package/rust/src/cpio.rs +147 -0
  56. package/rust/src/extfs.rs +747 -0
  57. package/rust/src/guest.rs +2411 -0
  58. package/rust/src/lib.rs +41 -0
  59. package/rust/src/main.rs +6 -1
  60. package/rust/src/oci_tar.rs +842 -0
  61. package/ts/00_commitinfo_data.ts +2 -2
  62. package/ts/api-client.ts +19 -1
  63. package/ts/cli-entry.ts +15 -2
  64. package/ts/cli.ts +172 -40
  65. package/ts/config.ts +100 -25
  66. package/ts/egress-proxy.ts +649 -0
  67. package/ts/index.ts +5 -1
  68. package/ts/interfaces.ts +97 -30
  69. package/ts/microvm-executor.ts +1310 -0
  70. package/ts/node-version.ts +49 -0
  71. package/ts/npm-grants.ts +49 -0
  72. package/ts/oci-registry.ts +649 -0
  73. package/ts/plugins.ts +6 -2
  74. package/ts/protocol-validator.ts +29 -58
  75. package/ts/runner.ts +48 -21
  76. package/ts/state-owner.ts +8 -1
  77. package/ts/vsock-protocol.ts +437 -0
  78. package/dist_ts/oci-executor.d.ts +0 -155
  79. package/dist_ts/oci-executor.js +0 -2238
  80. package/ts/oci-executor.ts +0 -2989
@@ -0,0 +1,649 @@
1
+ import * as plugins from './plugins.js';
2
+ import { ProtocolError, RunnerError } from './errors.js';
3
+ import type { IEgressRule, IImageGrant } from './interfaces.js';
4
+
5
+ export const EGRESS_VSOCK_PORT = 1025;
6
+
7
+ const DNS_TYPE_A = 1;
8
+ const DNS_TYPE_AAAA = 28;
9
+ const DNS_CLASS_IN = 1;
10
+ const DEFAULT_TTL_SECONDS = 60;
11
+ const MAXIMUM_TTL_SECONDS = 300;
12
+ const MAXIMUM_INITIAL_INSPECT_BYTES = 16 * 1024;
13
+ const INITIAL_INSPECT_TIMEOUT_MS = 5_000;
14
+
15
+ const hostnameLabelPattern = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/;
16
+ const ipv4Pattern = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/;
17
+
18
+ export interface IResolvedAddress {
19
+ readonly address: string;
20
+ readonly family: 4 | 6;
21
+ readonly ttlSeconds: number;
22
+ }
23
+
24
+ export type TDnsResolveFn = (
25
+ hostname: string,
26
+ family: 4 | 6,
27
+ ) => Promise<IResolvedAddress[]>;
28
+
29
+ export interface ICidrBlock {
30
+ readonly family: 4 | 6;
31
+ readonly network: bigint;
32
+ readonly prefixLength: number;
33
+ }
34
+
35
+ export interface IEgressProxyOptions {
36
+ readonly allow: readonly IEgressRule[];
37
+ /** Extra registry origins authorized by lease grants for `oci-image` builds (runner-plane). */
38
+ readonly grantOrigins?: readonly { host: string; port: number }[];
39
+ /** Additional deployment-declared internal CIDRs to block (e.g. coordinator networks). */
40
+ readonly blockedCidrs?: readonly string[];
41
+ /** Optional custom DNS resolver (defaults to Node `dns.promises.resolve4/resolve6`). */
42
+ readonly resolveDns?: TDnsResolveFn;
43
+ /** Optional clock for TTL verification in tests. */
44
+ readonly now?: () => number;
45
+ /** Optional loopback override ONLY for local unit tests. */
46
+ readonly allowLoopbackForTest?: boolean;
47
+ }
48
+
49
+ /** Parses an IPv4 dotted quad to a 32-bit unsigned BigInt, or returns undefined if invalid. */
50
+ export const parseIpv4 = (ip: string): bigint | undefined => {
51
+ const match = ipv4Pattern.exec(ip);
52
+ if (!match) return undefined;
53
+ let value = 0n;
54
+ for (let i = 1; i <= 4; i += 1) {
55
+ const octet = Number(match[i]);
56
+ if (!Number.isInteger(octet) || octet < 0 || octet > 255) return undefined;
57
+ value = (value << 8n) | BigInt(octet);
58
+ }
59
+ return value;
60
+ };
61
+
62
+ /** Parses an IPv6 address (including compressed `::` and IPv4-mapped `::ffff:a.b.c.d`) to 128-bit BigInt. */
63
+ export const parseIpv6 = (ip: string): bigint | undefined => {
64
+ const zoneIndex = ip.indexOf('%');
65
+ const clean = (zoneIndex >= 0 ? ip.slice(0, zoneIndex) : ip).toLowerCase();
66
+ if (!clean.includes(':')) return undefined;
67
+ const halves = clean.split('::');
68
+ if (halves.length > 2) return undefined;
69
+
70
+ const parseGroups = (part: string): number[] | undefined => {
71
+ if (part.length === 0) return [];
72
+ const tokens = part.split(':');
73
+ const groups: number[] = [];
74
+ for (let i = 0; i < tokens.length; i += 1) {
75
+ const token = tokens[i];
76
+ if (token.includes('.')) {
77
+ if (i !== tokens.length - 1) return undefined;
78
+ const v4 = parseIpv4(token);
79
+ if (v4 === undefined) return undefined;
80
+ groups.push(Number((v4 >> 16n) & 0xffffn), Number(v4 & 0xffffn));
81
+ } else {
82
+ if (!/^[0-9a-f]{1,4}$/.test(token)) return undefined;
83
+ groups.push(Number.parseInt(token, 16));
84
+ }
85
+ }
86
+ return groups;
87
+ };
88
+
89
+ const left = parseGroups(halves[0]);
90
+ if (!left) return undefined;
91
+ const right = halves.length === 2 ? parseGroups(halves[1]) : [];
92
+ if (!right) return undefined;
93
+
94
+ let groups: number[];
95
+ if (halves.length === 2) {
96
+ const missing = 8 - (left.length + right.length);
97
+ if (missing < 1) return undefined;
98
+ groups = [...left, ...new Array<number>(missing).fill(0), ...right];
99
+ } else {
100
+ if (left.length !== 8) return undefined;
101
+ groups = left;
102
+ }
103
+
104
+ let value = 0n;
105
+ for (const g of groups) value = (value << 16n) | BigInt(g);
106
+ return value;
107
+ };
108
+
109
+ export const parseCidr = (cidr: string): ICidrBlock => {
110
+ const slash = cidr.indexOf('/');
111
+ if (slash <= 0) throw new ProtocolError(`Invalid CIDR block: ${cidr}`);
112
+ const ipPart = cidr.slice(0, slash);
113
+ const prefix = Number(cidr.slice(slash + 1));
114
+ const v4 = parseIpv4(ipPart);
115
+ if (v4 !== undefined) {
116
+ if (!Number.isInteger(prefix) || prefix < 0 || prefix > 32) {
117
+ throw new ProtocolError(`Invalid IPv4 prefix in CIDR: ${cidr}`);
118
+ }
119
+ const mask = prefix === 0 ? 0n : ((0xffff_ffffn << BigInt(32 - prefix)) & 0xffff_ffffn);
120
+ return { family: 4, network: v4 & mask, prefixLength: prefix };
121
+ }
122
+ const v6 = parseIpv6(ipPart);
123
+ if (v6 !== undefined) {
124
+ if (!Number.isInteger(prefix) || prefix < 0 || prefix > 128) {
125
+ throw new ProtocolError(`Invalid IPv6 prefix in CIDR: ${cidr}`);
126
+ }
127
+ const allOnes = (1n << 128n) - 1n;
128
+ const mask = prefix === 0 ? 0n : ((allOnes << BigInt(128 - prefix)) & allOnes);
129
+ return { family: 6, network: v6 & mask, prefixLength: prefix };
130
+ }
131
+ throw new ProtocolError(`Invalid IP address in CIDR: ${cidr}`);
132
+ };
133
+
134
+ const ipMatchesCidr = (family: 4 | 6, value: bigint, cidr: ICidrBlock): boolean => {
135
+ if (family !== cidr.family) return false;
136
+ const bits = family === 4 ? 32 : 128;
137
+ const shift = BigInt(bits - cidr.prefixLength);
138
+ if (cidr.prefixLength === 0) return true;
139
+ return (value >> shift) === (cidr.network >> shift);
140
+ };
141
+
142
+ /** Non-globally-reachable IPv4 ranges per IANA + `@ship.zone/ci-spec` Network section. */
143
+ const NON_GLOBAL_IPV4_CIDRS: readonly ICidrBlock[] = [
144
+ '0.0.0.0/8', // Unspecified / "this network"
145
+ '10.0.0.0/8', // RFC 1918 private
146
+ '100.64.0.0/10', // Shared address space (CGNAT)
147
+ '127.0.0.0/8', // Loopback
148
+ '169.254.0.0/16', // Link-local (including cloud metadata 169.254.169.254)
149
+ '172.16.0.0/12', // RFC 1918 private
150
+ '192.0.0.0/24', // IETF protocol assignments
151
+ '192.0.2.0/24', // TEST-NET-1
152
+ '192.168.0.0/16', // RFC 1918 private
153
+ '198.18.0.0/15', // Benchmarking
154
+ '198.51.100.0/24', // TEST-NET-2
155
+ '203.0.113.0/24', // TEST-NET-3
156
+ '224.0.0.0/4', // Multicast
157
+ '240.0.0.0/4', // Reserved / broadcast
158
+ ].map(parseCidr);
159
+
160
+ /** Non-globally-reachable IPv6 ranges per IANA + `@ship.zone/ci-spec`. */
161
+ const NON_GLOBAL_IPV6_CIDRS: readonly ICidrBlock[] = [
162
+ '::/128', // Unspecified
163
+ '::1/128', // Loopback
164
+ '::ffff:0:0/96', // IPv4-mapped (checked specially too)
165
+ '64:ff9b::/96', // NAT64 well-known prefix
166
+ '64:ff9b:1::/48', // NAT64 local-use
167
+ '100::/64', // Discard-only
168
+ '2001:db8::/32', // Documentation
169
+ 'fc00::/7', // Unique-local
170
+ 'fe80::/10', // Link-local
171
+ 'ff00::/8', // Multicast
172
+ ].map(parseCidr);
173
+
174
+ /**
175
+ * Returns true if `ip` is globally reachable (not loopback, private, link-local, CGNAT, ULA,
176
+ * multicast, unspecified, IPv4-mapped non-global, or inside `extraBlocked`).
177
+ */
178
+ export const isGloballyReachableIp = (
179
+ ip: string,
180
+ extraBlocked: readonly ICidrBlock[] = [],
181
+ ): boolean => {
182
+ const v4 = parseIpv4(ip);
183
+ if (v4 !== undefined) {
184
+ for (const cidr of NON_GLOBAL_IPV4_CIDRS) {
185
+ if (ipMatchesCidr(4, v4, cidr)) return false;
186
+ }
187
+ for (const cidr of extraBlocked) {
188
+ if (ipMatchesCidr(4, v4, cidr)) return false;
189
+ }
190
+ return true;
191
+ }
192
+ const v6 = parseIpv6(ip);
193
+ if (v6 !== undefined) {
194
+ // Check IPv4-mapped IPv6 (`::ffff:a.b.c.d`): ci-spec explicitly withholds IPv4-mapped forms
195
+ // of non-global addresses, and we withhold all IPv4-mapped forms from AAAA answers.
196
+ if ((v6 >> 32n) === 0xffffn) {
197
+ const embeddedV4 = v6 & 0xffff_ffffn;
198
+ for (const cidr of NON_GLOBAL_IPV4_CIDRS) {
199
+ if (ipMatchesCidr(4, embeddedV4, cidr)) return false;
200
+ }
201
+ for (const cidr of extraBlocked) {
202
+ if (ipMatchesCidr(4, embeddedV4, cidr)) return false;
203
+ }
204
+ return false;
205
+ }
206
+ for (const cidr of NON_GLOBAL_IPV6_CIDRS) {
207
+ if (ipMatchesCidr(6, v6, cidr)) return false;
208
+ }
209
+ for (const cidr of extraBlocked) {
210
+ if (ipMatchesCidr(6, v6, cidr)) return false;
211
+ }
212
+ return true;
213
+ }
214
+ return false;
215
+ };
216
+
217
+ /** Validates a DNS host allowlist pattern (`exact.host` or `*.suffix.tld`). */
218
+ export const validateAllowHostPattern = (pattern: string): void => {
219
+ if (pattern !== pattern.toLowerCase() || pattern.length === 0 || pattern.length > 253) {
220
+ throw new ProtocolError(`Invalid egress allowlist host: ${pattern}`);
221
+ }
222
+ if (parseIpv4(pattern) !== undefined || parseIpv6(pattern) !== undefined) {
223
+ throw new ProtocolError(`IP literals are not allowed in egress allowlist: ${pattern}`);
224
+ }
225
+ const bare = pattern.startsWith('*.') ? pattern.slice(2) : pattern;
226
+ if (bare.includes('*')) {
227
+ throw new ProtocolError(`Wildcard must only appear as leading '*.': ${pattern}`);
228
+ }
229
+ const labels = bare.split('.');
230
+ if (labels.length < 2) {
231
+ throw new ProtocolError(`Single-label hosts are not allowed in egress allowlist: ${pattern}`);
232
+ }
233
+ for (const label of labels) {
234
+ if (!hostnameLabelPattern.test(label)) {
235
+ throw new ProtocolError(`Invalid DNS label in egress allowlist: ${pattern}`);
236
+ }
237
+ }
238
+ };
239
+
240
+ /** Matches a lowercase hostname against an allowlist pattern (`exact` or `*.suffix` at any depth). */
241
+ export const hostnameMatchesPattern = (hostname: string, pattern: string): boolean => {
242
+ const normalized = hostname.endsWith('.') ? hostname.slice(0, -1).toLowerCase() : hostname.toLowerCase();
243
+ if (normalized.length === 0 || parseIpv4(normalized) !== undefined || parseIpv6(normalized) !== undefined) {
244
+ return false;
245
+ }
246
+ if (pattern.startsWith('*.')) {
247
+ const suffix = pattern.slice(1); // includes leading '.'
248
+ return normalized.length > suffix.length && normalized.endsWith(suffix);
249
+ }
250
+ return normalized === pattern;
251
+ };
252
+
253
+ /**
254
+ * Extracts the Server Name Indication (SNI) hostname from a TLS ClientHello record,
255
+ * or returns `undefined` if the bytes are not a valid TLS ClientHello with a `host_name` SNI.
256
+ */
257
+ export const extractTlsSni = (data: Uint8Array): string | undefined => {
258
+ if (data.byteLength < 5) return undefined;
259
+ // TLS Record header: type=0x16 (Handshake), version 0x03 0x00..0x04, u16 length
260
+ if (data[0] !== 0x16 || data[1] !== 0x03) return undefined;
261
+ const recordLen = (data[3] << 8) | data[4];
262
+ if (data.byteLength < 5 + recordLen || recordLen < 42) return undefined;
263
+
264
+ let pos = 5;
265
+ const end = 5 + recordLen;
266
+ // Handshake header: type=0x01 (ClientHello), u24 length
267
+ if (data[pos] !== 0x01) return undefined;
268
+ const hsLen = (data[pos + 1] << 16) | (data[pos + 2] << 8) | data[pos + 3];
269
+ pos += 4;
270
+ if (pos + hsLen > end) return undefined;
271
+ const hsEnd = pos + hsLen;
272
+
273
+ // client_version (2) + random (32)
274
+ pos += 34;
275
+ if (pos >= hsEnd) return undefined;
276
+ // session_id
277
+ const sessionIdLen = data[pos];
278
+ pos += 1 + sessionIdLen;
279
+ if (pos + 2 > hsEnd) return undefined;
280
+ // cipher_suites
281
+ const cipherSuitesLen = (data[pos] << 8) | data[pos + 1];
282
+ pos += 2 + cipherSuitesLen;
283
+ if (pos + 1 > hsEnd) return undefined;
284
+ // compression_methods
285
+ const compLen = data[pos];
286
+ pos += 1 + compLen;
287
+ if (pos + 2 > hsEnd) return undefined;
288
+ // extensions
289
+ const extTotalLen = (data[pos] << 8) | data[pos + 1];
290
+ pos += 2;
291
+ const extEnd = Math.min(pos + extTotalLen, hsEnd);
292
+
293
+ while (pos + 4 <= extEnd) {
294
+ const extType = (data[pos] << 8) | data[pos + 1];
295
+ const extLen = (data[pos + 2] << 8) | data[pos + 3];
296
+ pos += 4;
297
+ if (pos + extLen > extEnd) return undefined;
298
+ if (extType === 0x0000) {
299
+ // server_name extension
300
+ if (extLen < 5) return undefined;
301
+ const listLen = (data[pos] << 8) | data[pos + 1];
302
+ let p = pos + 2;
303
+ const listEnd = Math.min(p + listLen, pos + extLen);
304
+ while (p + 3 <= listEnd) {
305
+ const nameType = data[p];
306
+ const nameLen = (data[p + 1] << 8) | data[p + 2];
307
+ p += 3;
308
+ if (p + nameLen > listEnd) return undefined;
309
+ if (nameType === 0x00) {
310
+ return Buffer.from(data.subarray(p, p + nameLen)).toString('ascii').toLowerCase();
311
+ }
312
+ p += nameLen;
313
+ }
314
+ return undefined;
315
+ }
316
+ pos += extLen;
317
+ }
318
+ return undefined;
319
+ };
320
+
321
+ /**
322
+ * Extracts the HTTP/1.x `Host` header hostname (without optional `:port`) from initial request bytes.
323
+ */
324
+ export const extractHttpHost = (data: Uint8Array): string | undefined => {
325
+ const text = Buffer.from(data).toString('latin1');
326
+ const headerEnd = text.indexOf('\r\n\r\n');
327
+ if (headerEnd < 0) return undefined;
328
+ const lines = text.slice(0, headerEnd).split('\r\n');
329
+ if (lines.length < 2) return undefined;
330
+ let hostHeader: string | undefined;
331
+ for (let i = 1; i < lines.length; i += 1) {
332
+ const colon = lines[i].indexOf(':');
333
+ if (colon <= 0) continue;
334
+ const name = lines[i].slice(0, colon).trim().toLowerCase();
335
+ if (name === 'host') {
336
+ if (hostHeader !== undefined) return undefined; // reject duplicate Host headers
337
+ hostHeader = lines[i].slice(colon + 1).trim().toLowerCase();
338
+ }
339
+ }
340
+ if (!hostHeader || hostHeader.length === 0) return undefined;
341
+ if (hostHeader.startsWith('[')) return undefined; // reject IPv6 literal
342
+ const portColon = hostHeader.lastIndexOf(':');
343
+ const host = portColon > 0 ? hostHeader.slice(0, portColon) : hostHeader;
344
+ return host.length > 0 ? host : undefined;
345
+ };
346
+
347
+ /** Converts lease grants into allowed `{ host, port }` registry origins for `oci-image` builders. */
348
+ export const grantOriginsFromLease = (grants: readonly IImageGrant[]): Array<{ host: string; port: number }> => {
349
+ const seen = new Set<string>();
350
+ const out: Array<{ host: string; port: number }> = [];
351
+ for (const grant of grants) {
352
+ const colon = grant.registry.lastIndexOf(':');
353
+ const hasPort = colon > 0 && !grant.registry.includes(']');
354
+ const host = (hasPort ? grant.registry.slice(0, colon) : grant.registry).toLowerCase();
355
+ const port = hasPort ? Number(grant.registry.slice(colon + 1)) : 443;
356
+ const key = `${host}:${port}`;
357
+ if (!seen.has(key) && Number.isInteger(port) && port >= 1 && port <= 65535) {
358
+ seen.add(key);
359
+ out.push({ host, port });
360
+ }
361
+ }
362
+ return out;
363
+ };
364
+
365
+ interface ICachedResolution {
366
+ readonly hostname: string;
367
+ readonly expiresAtMs: number;
368
+ readonly allowedPorts: Set<number>;
369
+ }
370
+
371
+ const defaultResolveDns: TDnsResolveFn = async (hostname, family) => {
372
+ const dns = await import('node:dns/promises');
373
+ try {
374
+ if (family === 4) {
375
+ const records = await dns.resolve4(hostname, { ttl: true });
376
+ return records.map((r) => ({ address: r.address, family: 4 as const, ttlSeconds: r.ttl }));
377
+ }
378
+ const records = await dns.resolve6(hostname, { ttl: true });
379
+ return records.map((r) => ({ address: r.address, family: 6 as const, ttlSeconds: r.ttl }));
380
+ } catch {
381
+ return [];
382
+ }
383
+ };
384
+
385
+ /**
386
+ * Host-side egress allowlist policy & proxy enforcing `@ship.zone/ci-spec` Network rules:
387
+ * - Resolves only `A` and `AAAA` queries for allowlisted hosts (plus optional `oci-image` grant origins).
388
+ * - Withholds and blocks all non-globally-reachable IPs and deployment-declared internal CIDRs.
389
+ * - Permits TCP dials only to IPs returned by this attempt's resolver within TTL and on an allowed port.
390
+ * - Enforces TLS SNI on port 443 and HTTP `Host` on port 80 matching the resolved allowlisted host.
391
+ */
392
+ export class EgressAllowlistController {
393
+ private readonly allowRules: readonly IEgressRule[];
394
+ private readonly grantOrigins: readonly { host: string; port: number }[];
395
+ private readonly blockedCidrs: readonly ICidrBlock[];
396
+ private readonly resolveDnsImpl: TDnsResolveFn;
397
+ private readonly now: () => number;
398
+ private readonly allowLoopbackForTest: boolean;
399
+ private readonly ipBindings = new Map<string, ICachedResolution[]>();
400
+
401
+ constructor(options: IEgressProxyOptions) {
402
+ for (const rule of options.allow) {
403
+ validateAllowHostPattern(rule.host);
404
+ if (!Array.isArray(rule.ports) || rule.ports.length === 0) {
405
+ throw new ProtocolError(`Egress allow rule for ${rule.host} requires at least one port`);
406
+ }
407
+ for (const port of rule.ports) {
408
+ if (!Number.isInteger(port) || port < 1 || port > 65535) {
409
+ throw new ProtocolError(`Invalid egress allow port ${port} for ${rule.host}`);
410
+ }
411
+ }
412
+ }
413
+ this.allowRules = options.allow;
414
+ this.grantOrigins = options.grantOrigins ?? [];
415
+ this.blockedCidrs = (options.blockedCidrs ?? []).map(parseCidr);
416
+ this.resolveDnsImpl = options.resolveDns ?? defaultResolveDns;
417
+ this.now = options.now ?? Date.now;
418
+ this.allowLoopbackForTest = options.allowLoopbackForTest ?? false;
419
+ }
420
+
421
+ /** Returns the set of allowed TCP ports for `hostname`, or `undefined` if the host is not allowed. */
422
+ allowedPortsForHost(hostname: string): Set<number> | undefined {
423
+ const normalized = hostname.endsWith('.')
424
+ ? hostname.slice(0, -1).toLowerCase()
425
+ : hostname.toLowerCase();
426
+ const ports = new Set<number>();
427
+ for (const rule of this.allowRules) {
428
+ if (hostnameMatchesPattern(normalized, rule.host)) {
429
+ for (const port of rule.ports) ports.add(port);
430
+ }
431
+ }
432
+ for (const origin of this.grantOrigins) {
433
+ if (origin.host === normalized) ports.add(origin.port);
434
+ }
435
+ return ports.size > 0 ? ports : undefined;
436
+ }
437
+
438
+ /** Resolves `A` or `AAAA` for an allowlisted host, filtering out non-global/blocked IPs and recording TTL bindings. */
439
+ async resolveQuery(
440
+ hostname: string,
441
+ queryType: number,
442
+ queryClass = DNS_CLASS_IN,
443
+ ): Promise<{ allowed: boolean; records: IResolvedAddress[] }> {
444
+ if (queryClass !== DNS_CLASS_IN || (queryType !== DNS_TYPE_A && queryType !== DNS_TYPE_AAAA)) {
445
+ return { allowed: false, records: [] };
446
+ }
447
+ const normalized = hostname.endsWith('.')
448
+ ? hostname.slice(0, -1).toLowerCase()
449
+ : hostname.toLowerCase();
450
+ const allowedPorts = this.allowedPortsForHost(normalized);
451
+ if (!allowedPorts) {
452
+ return { allowed: false, records: [] };
453
+ }
454
+ const family: 4 | 6 = queryType === DNS_TYPE_A ? 4 : 6;
455
+ const raw = await this.resolveDnsImpl(normalized, family);
456
+ const filtered: IResolvedAddress[] = [];
457
+ const nowMs = this.now();
458
+ for (const record of raw) {
459
+ if (!this.isPermittedIp(record.address)) continue;
460
+ const ttl = Math.max(1, Math.min(MAXIMUM_TTL_SECONDS, Math.floor(record.ttlSeconds || DEFAULT_TTL_SECONDS)));
461
+ filtered.push({ address: record.address, family, ttlSeconds: ttl });
462
+ const existing = this.ipBindings.get(record.address) ?? [];
463
+ const active = existing.filter((entry) => entry.expiresAtMs > nowMs && entry.hostname !== normalized);
464
+ active.push({
465
+ hostname: normalized,
466
+ expiresAtMs: nowMs + ttl * 1000,
467
+ allowedPorts,
468
+ });
469
+ this.ipBindings.set(record.address, active);
470
+ }
471
+ return { allowed: true, records: filtered };
472
+ }
473
+
474
+ private isPermittedIp(ip: string): boolean {
475
+ if (this.allowLoopbackForTest && (ip === '127.0.0.1' || ip === '::1')) {
476
+ return true;
477
+ }
478
+ return isGloballyReachableIp(ip, this.blockedCidrs);
479
+ }
480
+
481
+ /**
482
+ * Authorizes a TCP connection to `(ip, port)` and validates initial payload (`SNI` on 443,
483
+ * `Host` on 80) against the allowlisted hostname(s) bound to `ip` within TTL.
484
+ */
485
+ authorizeConnection(
486
+ ip: string,
487
+ port: number,
488
+ initialPayload?: Uint8Array,
489
+ ): { allowed: true; hostname: string } | { allowed: false; reason: string } {
490
+ if (!this.isPermittedIp(ip)) {
491
+ return { allowed: false, reason: 'Destination IP is not globally reachable' };
492
+ }
493
+ const nowMs = this.now();
494
+ const candidates = (this.ipBindings.get(ip) ?? []).filter(
495
+ (entry) => entry.expiresAtMs > nowMs && entry.allowedPorts.has(port),
496
+ );
497
+ if (candidates.length === 0) {
498
+ return {
499
+ allowed: false,
500
+ reason: `Destination ${ip}:${port} has no active allowlisted DNS resolution`,
501
+ };
502
+ }
503
+
504
+ if (port === 443) {
505
+ if (!initialPayload || initialPayload.byteLength === 0) {
506
+ return { allowed: false, reason: 'Port 443 requires TLS ClientHello with SNI' };
507
+ }
508
+ const sni = extractTlsSni(initialPayload);
509
+ if (!sni) {
510
+ return { allowed: false, reason: 'Port 443 connection lacks a valid TLS SNI hostname' };
511
+ }
512
+ const matched = candidates.find((entry) => entry.hostname === sni);
513
+ if (!matched) {
514
+ return {
515
+ allowed: false,
516
+ reason: `TLS SNI ${sni} does not match the resolved allowlisted host for ${ip}`,
517
+ };
518
+ }
519
+ return { allowed: true, hostname: matched.hostname };
520
+ }
521
+
522
+ if (port === 80) {
523
+ if (!initialPayload || initialPayload.byteLength === 0) {
524
+ return { allowed: false, reason: 'Port 80 requires an HTTP Host header' };
525
+ }
526
+ const httpHost = extractHttpHost(initialPayload);
527
+ if (!httpHost) {
528
+ return { allowed: false, reason: 'Port 80 connection lacks a valid HTTP Host header' };
529
+ }
530
+ const matched = candidates.find((entry) => entry.hostname === httpHost);
531
+ if (!matched) {
532
+ return {
533
+ allowed: false,
534
+ reason: `HTTP Host ${httpHost} does not match the resolved allowlisted host for ${ip}`,
535
+ };
536
+ }
537
+ return { allowed: true, hostname: matched.hostname };
538
+ }
539
+
540
+ return { allowed: true, hostname: candidates[0].hostname };
541
+ }
542
+
543
+ /**
544
+ * Proxies an outbound TCP connection from an incoming guest tunnel socket after verifying
545
+ * IP/port TTL binding and (on ports 80/443) initial SNI/Host header bytes before dialing.
546
+ */
547
+ async proxyTcpStream(
548
+ clientSocket: plugins.net.Socket,
549
+ destinationIp: string,
550
+ destinationPort: number,
551
+ ): Promise<void> {
552
+ const needsInspect = destinationPort === 443 || destinationPort === 80;
553
+ let initialBytes: Uint8Array = Buffer.alloc(0);
554
+
555
+ if (needsInspect) {
556
+ initialBytes = await readInitialClientBytes(clientSocket);
557
+ }
558
+
559
+ const decision = this.authorizeConnection(destinationIp, destinationPort, initialBytes);
560
+ if (!decision.allowed) {
561
+ clientSocket.destroy();
562
+ throw new RunnerError(`Egress blocked: ${decision.reason}`);
563
+ }
564
+
565
+ await new Promise<void>((resolve, reject) => {
566
+ const upstream = plugins.net.createConnection({
567
+ host: destinationIp,
568
+ port: destinationPort,
569
+ });
570
+ let settled = false;
571
+ const done = (error?: Error): void => {
572
+ if (settled) return;
573
+ settled = true;
574
+ if (error) reject(error);
575
+ else resolve();
576
+ };
577
+ upstream.once('connect', () => {
578
+ if (initialBytes.length > 0) upstream.write(initialBytes);
579
+ clientSocket.pipe(upstream);
580
+ upstream.pipe(clientSocket);
581
+ });
582
+ upstream.once('error', (error) => {
583
+ clientSocket.destroy();
584
+ done(error);
585
+ });
586
+ clientSocket.once('error', () => {
587
+ upstream.destroy();
588
+ done();
589
+ });
590
+ upstream.once('close', () => {
591
+ clientSocket.end();
592
+ done();
593
+ });
594
+ clientSocket.once('close', () => {
595
+ upstream.destroy();
596
+ done();
597
+ });
598
+ });
599
+ }
600
+ }
601
+
602
+ const readInitialClientBytes = (socket: plugins.net.Socket): Promise<Buffer> =>
603
+ new Promise((resolve, reject) => {
604
+ const chunks: Buffer[] = [];
605
+ let total = 0;
606
+ const timer = setTimeout(() => {
607
+ cleanup();
608
+ resolve(Buffer.concat(chunks, total));
609
+ }, INITIAL_INSPECT_TIMEOUT_MS);
610
+
611
+ const cleanup = (): void => {
612
+ clearTimeout(timer);
613
+ socket.off('data', onData);
614
+ socket.off('end', onEnd);
615
+ socket.off('error', onError);
616
+ };
617
+ const onData = (chunk: Buffer): void => {
618
+ chunks.push(chunk);
619
+ total += chunk.length;
620
+ if (total >= MAXIMUM_INITIAL_INSPECT_BYTES) {
621
+ cleanup();
622
+ resolve(Buffer.concat(chunks, total));
623
+ return;
624
+ }
625
+ const combined = Buffer.concat(chunks, total);
626
+ // Complete TLS record or complete HTTP headers?
627
+ if (combined[0] === 0x16 && combined.length >= 5) {
628
+ const recordLen = (combined[3] << 8) | combined[4];
629
+ if (combined.length >= 5 + recordLen) {
630
+ cleanup();
631
+ resolve(combined);
632
+ }
633
+ } else if (combined.includes('\r\n\r\n')) {
634
+ cleanup();
635
+ resolve(combined);
636
+ }
637
+ };
638
+ const onEnd = (): void => {
639
+ cleanup();
640
+ resolve(Buffer.concat(chunks, total));
641
+ };
642
+ const onError = (error: Error): void => {
643
+ cleanup();
644
+ reject(error);
645
+ };
646
+ socket.on('data', onData);
647
+ socket.once('end', onEnd);
648
+ socket.once('error', onError);
649
+ });
package/ts/index.ts CHANGED
@@ -2,10 +2,13 @@ export * from './api-client.js';
2
2
  export * from './artifact-manager.js';
3
3
  export * from './cache-manager.js';
4
4
  export * from './config.js';
5
+ export * from './egress-proxy.js';
5
6
  export * from './errors.js';
6
7
  export * from './interfaces.js';
7
8
  export * from './log-sender.js';
8
- export * from './oci-executor.js';
9
+ export * from './microvm-executor.js';
10
+ export * from './npm-grants.js';
11
+ export * from './oci-registry.js';
9
12
  export * from './protocol-validator.js';
10
13
  export * from './redactor.js';
11
14
  export * from './runner.js';
@@ -13,4 +16,5 @@ export * from './source-workspace.js';
13
16
  export * from './spec-version.js';
14
17
  export * from './staging-scavenger.js';
15
18
  export * from './state-owner.js';
19
+ export * from './vsock-protocol.js';
16
20
  export * from './wire-schema.js';