@celljs/ta-gateway 4.16.0 → 4.17.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 (65) hide show
  1. package/README.en.md +5 -2
  2. package/README.md +5 -2
  3. package/esm/node/docker-engine.d.ts +5 -1
  4. package/esm/node/docker-engine.js +7 -1
  5. package/esm/node/docker-sandbox.d.ts +10 -1
  6. package/esm/node/docker-sandbox.js +24 -5
  7. package/esm/node/egress-proxy.d.ts +98 -0
  8. package/esm/node/egress-proxy.js +428 -0
  9. package/esm/node/environments.d.ts +5 -2
  10. package/esm/node/environments.js +4 -2
  11. package/esm/node/gateway-cli.js +12 -5
  12. package/esm/node/gateway-policy.d.ts +6 -1
  13. package/esm/node/gateway-policy.js +10 -1
  14. package/esm/node/gateway-quotas.d.ts +6 -1
  15. package/esm/node/gateway-quotas.js +17 -0
  16. package/esm/node/gateway-server.d.ts +31 -0
  17. package/esm/node/gateway-server.js +131 -13
  18. package/esm/node/gateway-service-util.d.ts +41 -0
  19. package/esm/node/gateway-service-util.js +178 -0
  20. package/esm/node/gateway-service.d.ts +5 -41
  21. package/esm/node/gateway-service.js +19 -173
  22. package/esm/node/gateway-socket.d.ts +1 -1
  23. package/esm/node/gateway-socket.js +1 -1
  24. package/esm/node/index.d.ts +4 -0
  25. package/esm/node/index.js +4 -0
  26. package/esm/node/kubernetes-api.d.ts +35 -0
  27. package/esm/node/kubernetes-api.js +115 -0
  28. package/esm/node/kubernetes-sandbox.d.ts +198 -0
  29. package/esm/node/kubernetes-sandbox.js +279 -0
  30. package/esm/node/sandbox-provider.d.ts +11 -1
  31. package/esm/node/sandbox-provider.js +2 -1
  32. package/esm/node/tenant-store.d.ts +15 -0
  33. package/esm/node/tenant-store.js +15 -0
  34. package/lib/node/docker-engine.d.ts +5 -1
  35. package/lib/node/docker-engine.js +7 -1
  36. package/lib/node/docker-sandbox.d.ts +10 -1
  37. package/lib/node/docker-sandbox.js +24 -5
  38. package/lib/node/egress-proxy.d.ts +99 -0
  39. package/lib/node/egress-proxy.js +433 -0
  40. package/lib/node/environments.d.ts +5 -2
  41. package/lib/node/environments.js +4 -2
  42. package/lib/node/gateway-cli.js +12 -5
  43. package/lib/node/gateway-policy.d.ts +6 -1
  44. package/lib/node/gateway-policy.js +10 -1
  45. package/lib/node/gateway-quotas.d.ts +6 -1
  46. package/lib/node/gateway-quotas.js +17 -0
  47. package/lib/node/gateway-server.d.ts +31 -0
  48. package/lib/node/gateway-server.js +129 -11
  49. package/lib/node/gateway-service-util.d.ts +42 -0
  50. package/lib/node/gateway-service-util.js +182 -0
  51. package/lib/node/gateway-service.d.ts +5 -41
  52. package/lib/node/gateway-service.js +41 -196
  53. package/lib/node/gateway-socket.d.ts +1 -1
  54. package/lib/node/gateway-socket.js +10 -10
  55. package/lib/node/index.d.ts +4 -0
  56. package/lib/node/index.js +4 -0
  57. package/lib/node/kubernetes-api.d.ts +36 -0
  58. package/lib/node/kubernetes-api.js +120 -0
  59. package/lib/node/kubernetes-sandbox.d.ts +199 -0
  60. package/lib/node/kubernetes-sandbox.js +283 -0
  61. package/lib/node/sandbox-provider.d.ts +11 -1
  62. package/lib/node/sandbox-provider.js +2 -1
  63. package/lib/node/tenant-store.d.ts +15 -0
  64. package/lib/node/tenant-store.js +15 -0
  65. package/package.json +4 -4
@@ -0,0 +1,428 @@
1
+ import { timingSafeEqual } from 'node:crypto';
2
+ import { lookup } from 'node:dns/promises';
3
+ import { request as httpRequest, STATUS_CODES } from 'node:http';
4
+ import { BlockList, connect, isIP } from 'node:net';
5
+ import { networkInterfaces } from 'node:os';
6
+ import { pipeline } from 'node:stream';
7
+ export class EgressConfigError extends Error {
8
+ }
9
+ const PORTS = new Set([80, 443]);
10
+ /** Of a tenant, the refusals kept to show. */
11
+ const REFUSALS = 10;
12
+ const CONNECT_TIMEOUT_MS = 15000;
13
+ const HOP_BY_HOP = new Set([
14
+ 'connection',
15
+ 'keep-alive',
16
+ 'proxy-authenticate',
17
+ 'proxy-authorization',
18
+ 'proxy-connection',
19
+ 'te',
20
+ 'trailer',
21
+ 'transfer-encoding',
22
+ 'upgrade',
23
+ ]);
24
+ const PATTERN = /^(\*|(\*\.)?[a-z0-9_]([a-z0-9_-]*[a-z0-9_])?(\.[a-z0-9_]([a-z0-9_-]*[a-z0-9_])?)*)(:(\d{1,5}|\*))?$/;
25
+ /** Never reached through the gateway: this machine, link-local (the metadata service), multicast, reserved. */
26
+ const NEVER = new BlockList();
27
+ for (const [network, prefix] of [
28
+ ['0.0.0.0', 8],
29
+ ['127.0.0.0', 8],
30
+ ['169.254.0.0', 16],
31
+ ['224.0.0.0', 4],
32
+ ['240.0.0.0', 4],
33
+ ]) {
34
+ NEVER.addSubnet(network, prefix, 'ipv4');
35
+ }
36
+ for (const [network, prefix] of [
37
+ ['::', 128],
38
+ ['::1', 128],
39
+ ['fe80::', 10],
40
+ ['ff00::', 8],
41
+ ]) {
42
+ NEVER.addSubnet(network, prefix, 'ipv6');
43
+ }
44
+ /** Private networks, where the machine's neighbours and the other sandboxes are: only those of the configuration. */
45
+ const PRIVATE = new BlockList();
46
+ for (const [network, prefix] of [
47
+ ['10.0.0.0', 8],
48
+ ['172.16.0.0', 12],
49
+ ['192.168.0.0', 16],
50
+ ['100.64.0.0', 10],
51
+ ['198.18.0.0', 15],
52
+ ]) {
53
+ PRIVATE.addSubnet(network, prefix, 'ipv4');
54
+ }
55
+ for (const [network, prefix] of [
56
+ ['fc00::', 7],
57
+ ['64:ff9b::', 96],
58
+ ]) {
59
+ PRIVATE.addSubnet(network, prefix, 'ipv6');
60
+ }
61
+ export var EgressProxyUtil;
62
+ (function (EgressProxyUtil) {
63
+ function settings(config) {
64
+ var _a;
65
+ if (config === undefined || config === false) {
66
+ return { enabled: false, networks: [] };
67
+ }
68
+ if (config === true) {
69
+ return { enabled: true, networks: [] };
70
+ }
71
+ if (typeof config !== 'object' || config === null || (config.networks !== undefined && !Array.isArray(config.networks))) {
72
+ throw new EgressConfigError('"egress" of sandboxes.json is true, false or { "networks": ["10.0.0.0/8"] }.');
73
+ }
74
+ const networks = (_a = config.networks) !== null && _a !== void 0 ? _a : [];
75
+ networksOf(networks);
76
+ return { enabled: true, networks };
77
+ }
78
+ EgressProxyUtil.settings = settings;
79
+ /** `10.0.0.0/8`, `fd00::/8` or one address, as a list to check addresses against. */
80
+ function networksOf(networks) {
81
+ const list = new BlockList();
82
+ for (const network of networks) {
83
+ const [address, bits, ...rest] = String(network).trim().split('/');
84
+ const family = isIP(address);
85
+ const max = family === 6 ? 128 : 32;
86
+ const prefix = bits === undefined ? max : Number(bits);
87
+ if (!family || rest.length > 0 || !Number.isInteger(prefix) || prefix < 0 || prefix > max || (bits !== undefined && !/^\d+$/.test(bits))) {
88
+ throw new EgressConfigError(`"${network}" of egress.networks is no network: write it as 10.0.0.0/8, or one address.`);
89
+ }
90
+ list.addSubnet(address, prefix, family === 6 ? 'ipv6' : 'ipv4');
91
+ }
92
+ return list;
93
+ }
94
+ EgressProxyUtil.networksOf = networksOf;
95
+ /** The hosts an owner lets members reach, cleaned: lower-case, one each, at most 200. */
96
+ function hosts(value) {
97
+ var _a;
98
+ if (!Array.isArray(value) || value.length > 200) {
99
+ throw new EgressConfigError('The hosts are a list of at most 200.');
100
+ }
101
+ const hosts = new Set();
102
+ for (const item of value) {
103
+ const host = typeof item === 'string' ? item.trim().toLowerCase().replace(/\.$/, '') : '';
104
+ if (!host) {
105
+ continue;
106
+ }
107
+ const port = (_a = /:(\d+)$/.exec(host)) === null || _a === void 0 ? void 0 : _a[1];
108
+ if (!PATTERN.test(host) || (port !== undefined && (Number(port) < 1 || Number(port) > 65535))) {
109
+ throw new EgressConfigError(`"${item}" is no host: write example.com, *.example.com or example.com:8443.`);
110
+ }
111
+ hosts.add(host);
112
+ }
113
+ return [...hosts];
114
+ }
115
+ EgressProxyUtil.hosts = hosts;
116
+ /** The user and password of `Proxy-Authorization: Basic …`. */
117
+ function credentials(header) {
118
+ var _a;
119
+ const match = /^Basic\s+(\S+)$/i.exec((_a = header === null || header === void 0 ? void 0 : header.trim()) !== null && _a !== void 0 ? _a : '');
120
+ if (!match) {
121
+ return undefined;
122
+ }
123
+ const text = Buffer.from(match[1], 'base64').toString('utf8');
124
+ const colon = text.indexOf(':');
125
+ return colon < 0 ? undefined : { user: decodeURIComponent(text.slice(0, colon)), password: decodeURIComponent(text.slice(colon + 1)) };
126
+ }
127
+ EgressProxyUtil.credentials = credentials;
128
+ /** `host:port` of CONNECT, `[::1]:443` too. */
129
+ function target(authority, fallbackPort) {
130
+ var _a;
131
+ const match = /^(?:\[([0-9a-f:.]+)\]|([^\s:/[\]]+))(?::(\d{1,5}))?$/i.exec(authority.trim());
132
+ if (!match) {
133
+ return undefined;
134
+ }
135
+ const port = match[3] === undefined ? fallbackPort : Number(match[3]);
136
+ if (port < 1 || port > 65535) {
137
+ return undefined;
138
+ }
139
+ return { host: ((_a = match[1]) !== null && _a !== void 0 ? _a : match[2]).toLowerCase().replace(/\.$/, ''), port };
140
+ }
141
+ EgressProxyUtil.target = target;
142
+ /** Why the policy refuses the target: not among its hosts, or a port of none of them; none: any public host, on 80 and 443. */
143
+ function refusal(hosts, target) {
144
+ if (!hosts || hosts.length === 0) {
145
+ return PORTS.has(target.port) ? undefined : 'port';
146
+ }
147
+ let named = false;
148
+ for (const pattern of hosts) {
149
+ const colon = pattern.lastIndexOf(':');
150
+ const name = colon < 0 ? pattern : pattern.slice(0, colon);
151
+ const port = colon < 0 ? undefined : pattern.slice(colon + 1);
152
+ const matches = name === '*' || name === target.host || (name.startsWith('*.') && target.host.endsWith(name.slice(1)));
153
+ if (!matches) {
154
+ continue;
155
+ }
156
+ named = true;
157
+ if (port === '*' || (port === undefined ? PORTS.has(target.port) : Number(port) === target.port)) {
158
+ return undefined;
159
+ }
160
+ }
161
+ return named ? 'port' : 'host';
162
+ }
163
+ EgressProxyUtil.refusal = refusal;
164
+ /** `::ffff:10.0.0.1` is 10.0.0.1. */
165
+ function plain(address) {
166
+ const mapped = /^::ffff:(\d+\.\d+\.\d+\.\d+)$/i.exec(address);
167
+ return mapped ? mapped[1] : address;
168
+ }
169
+ EgressProxyUtil.plain = plain;
170
+ /** Whether a sandbox may reach the address: a public one, or one of `networks`; never this machine. */
171
+ function reachable(address, networks, own = ownAddresses()) {
172
+ const ip = plain(address);
173
+ const family = isIP(ip);
174
+ if (!family) {
175
+ return false;
176
+ }
177
+ const type = family === 6 ? 'ipv6' : 'ipv4';
178
+ if (own.has(ip) || NEVER.check(ip, type)) {
179
+ return false;
180
+ }
181
+ return !PRIVATE.check(ip, type) || networks.check(ip, type);
182
+ }
183
+ EgressProxyUtil.reachable = reachable;
184
+ function ownAddresses() {
185
+ return new Set(Object.values(networkInterfaces())
186
+ .flat()
187
+ .map(each => { var _a; return plain((_a = each === null || each === void 0 ? void 0 : each.address) !== null && _a !== void 0 ? _a : '').toLowerCase(); })
188
+ .filter(Boolean));
189
+ }
190
+ EgressProxyUtil.ownAddresses = ownAddresses;
191
+ /**
192
+ * What a sandbox goes out with: the proxy of the gateway at `url`, by the credentials of its epoch, for the
193
+ * commands that read the variables of a proxy (curl, git, npm, pip, apt, and Node.js with NODE_USE_ENV_PROXY);
194
+ * the gateway itself, for its models, directly.
195
+ */
196
+ function env(url, user, password) {
197
+ const base = new URL(url);
198
+ // The port always written: curl takes 1080 for a proxy without one, where URL leaves out the default 80.
199
+ const port = base.port || (base.protocol === 'https:' ? '443' : '80');
200
+ const proxy = `${base.protocol}//${encodeURIComponent(user)}:${encodeURIComponent(password)}@${base.hostname}:${port}`;
201
+ const direct = ['localhost', '127.0.0.1', '::1', new URL(url).hostname].filter((each, index, all) => all.indexOf(each) === index).join(',');
202
+ return {
203
+ HTTP_PROXY: proxy,
204
+ HTTPS_PROXY: proxy,
205
+ http_proxy: proxy,
206
+ https_proxy: proxy,
207
+ NO_PROXY: direct,
208
+ no_proxy: direct,
209
+ NODE_USE_ENV_PROXY: '1',
210
+ };
211
+ }
212
+ EgressProxyUtil.env = env;
213
+ function sameSecret(given, known) {
214
+ const a = Buffer.from(given);
215
+ const b = Buffer.from(known);
216
+ return a.length === b.length && timingSafeEqual(a, b);
217
+ }
218
+ EgressProxyUtil.sameSecret = sameSecret;
219
+ function headers(given) {
220
+ const kept = {};
221
+ for (const [name, value] of Object.entries(given)) {
222
+ if (value !== undefined && !HOP_BY_HOP.has(name.toLowerCase())) {
223
+ kept[name] = value;
224
+ }
225
+ }
226
+ return kept;
227
+ }
228
+ EgressProxyUtil.headers = headers;
229
+ })(EgressProxyUtil || (EgressProxyUtil = {}));
230
+ /**
231
+ * The way out of the sandboxes (docs/design/ta-cloud.md 3.5): an HTTP proxy on the port of the gateway, CONNECT
232
+ * for https and absolute URLs for http. A sandbox comes with the credentials of its tenant and epoch (those of
233
+ * a sandbox replaced since are refused); the gateway reaches only public addresses (and the private networks of
234
+ * the configuration), resolved once and checked, never this machine nor the metadata service; members only the
235
+ * hosts of the policy. It counts the bytes each tenant moved, and keeps the latest refusals for the console.
236
+ */
237
+ export class EgressProxy {
238
+ constructor(settings, hooks) {
239
+ this.settings = settings;
240
+ this.hooks = hooks;
241
+ this.pending = new Map();
242
+ this.refusals = new Map();
243
+ this.networks = EgressProxyUtil.networksOf(settings.networks);
244
+ }
245
+ get enabled() {
246
+ return this.settings.enabled;
247
+ }
248
+ /** The bytes moved since the last time, by tenant. */
249
+ flush() {
250
+ const moved = new Map(this.pending);
251
+ this.pending.clear();
252
+ return moved;
253
+ }
254
+ /** The latest refusals of a tenant, newest first. */
255
+ refused(tenantId) {
256
+ var _a;
257
+ return (_a = this.refusals.get(tenantId)) !== null && _a !== void 0 ? _a : [];
258
+ }
259
+ /** CONNECT: a tunnel to the target, once its tenant may reach it. */
260
+ async connect(request, socket, head) {
261
+ var _a;
262
+ socket.on('error', () => socket.destroy());
263
+ const who = this.authorize(request);
264
+ if ('status' in who) {
265
+ this.reply(socket, who.status, who.message);
266
+ return;
267
+ }
268
+ const target = EgressProxyUtil.target((_a = request.url) !== null && _a !== void 0 ? _a : '', 443);
269
+ if (!target) {
270
+ this.reply(socket, 400, 'ta gateway: CONNECT takes host:port.');
271
+ return;
272
+ }
273
+ const address = await this.resolve(who, target);
274
+ if (typeof address !== 'string') {
275
+ this.reply(socket, address.status, address.message);
276
+ return;
277
+ }
278
+ const upstream = connect({ host: address, port: target.port });
279
+ let open = false;
280
+ let moved = head.length;
281
+ upstream.setTimeout(CONNECT_TIMEOUT_MS, () => upstream.destroy(new Error('timed out')));
282
+ upstream.once('connect', () => {
283
+ open = true;
284
+ upstream.setTimeout(0);
285
+ socket.write('HTTP/1.1 200 Connection Established\r\n\r\n');
286
+ if (head.length > 0) {
287
+ upstream.write(head);
288
+ }
289
+ upstream.on('data', chunk => (moved += chunk.length));
290
+ socket.on('data', chunk => (moved += chunk.length));
291
+ upstream.pipe(socket);
292
+ socket.pipe(upstream);
293
+ });
294
+ upstream.once('error', error => {
295
+ if (!open) {
296
+ this.reply(socket, 502, `ta gateway: ${target.host}:${target.port} did not answer: ${error.message}`);
297
+ }
298
+ socket.destroy();
299
+ });
300
+ upstream.once('close', () => socket.destroy());
301
+ socket.once('close', () => {
302
+ upstream.destroy();
303
+ this.count(who.tenantId, moved);
304
+ });
305
+ }
306
+ /** An absolute `http://` URL: the request forwarded, once its tenant may reach the host. */
307
+ async request(request, response) {
308
+ var _a;
309
+ const who = this.authorize(request);
310
+ if ('status' in who) {
311
+ this.end(response, who.status, who.message);
312
+ return;
313
+ }
314
+ let url;
315
+ try {
316
+ url = new URL((_a = request.url) !== null && _a !== void 0 ? _a : '');
317
+ }
318
+ catch (_b) {
319
+ this.end(response, 400, 'ta gateway: not a URL.');
320
+ return;
321
+ }
322
+ const target = url.protocol === 'http:' ? EgressProxyUtil.target(url.host, 80) : undefined;
323
+ if (!target) {
324
+ this.end(response, 400, 'ta gateway: only http:// is forwarded this way; https goes by CONNECT.');
325
+ return;
326
+ }
327
+ const address = await this.resolve(who, target);
328
+ if (typeof address !== 'string') {
329
+ this.end(response, address.status, address.message);
330
+ return;
331
+ }
332
+ let moved = 0;
333
+ await new Promise(resolve => {
334
+ const outgoing = httpRequest({
335
+ host: address,
336
+ port: target.port,
337
+ method: request.method,
338
+ path: `${url.pathname}${url.search}`,
339
+ headers: { ...EgressProxyUtil.headers(request.headers), host: url.host },
340
+ setHost: false,
341
+ }, incoming => {
342
+ var _a;
343
+ response.writeHead((_a = incoming.statusCode) !== null && _a !== void 0 ? _a : 502, EgressProxyUtil.headers(incoming.headers));
344
+ incoming.on('data', chunk => (moved += chunk.length));
345
+ pipeline(incoming, response, () => resolve());
346
+ });
347
+ outgoing.setTimeout(CONNECT_TIMEOUT_MS * 4, () => outgoing.destroy(new Error('timed out')));
348
+ outgoing.once('error', error => {
349
+ if (!response.headersSent) {
350
+ this.end(response, 502, `ta gateway: ${target.host} did not answer: ${error.message}`);
351
+ }
352
+ else {
353
+ response.destroy();
354
+ }
355
+ resolve();
356
+ });
357
+ request.on('data', chunk => (moved += chunk.length));
358
+ request.pipe(outgoing);
359
+ });
360
+ this.count(who.tenantId, moved);
361
+ }
362
+ authorize(request) {
363
+ if (!this.enabled) {
364
+ return { status: 403, message: 'ta gateway: this gateway is no proxy ("egress" of sandboxes.json is off).' };
365
+ }
366
+ const credentials = EgressProxyUtil.credentials(request.headers['proxy-authorization']);
367
+ return credentials
368
+ ? this.hooks.authorize(credentials.user, credentials.password)
369
+ : { status: 407, message: 'ta gateway: a sandbox of the gateway goes out with the credentials of HTTPS_PROXY.' };
370
+ }
371
+ /** The address to connect to, resolved once and checked (no rebinding between the check and the connection), or why not. */
372
+ async resolve(who, target) {
373
+ const refusal = EgressProxyUtil.refusal(who.hosts, target);
374
+ if (refusal) {
375
+ this.refuse(who.tenantId, target, refusal);
376
+ return {
377
+ status: 403,
378
+ message: refusal === 'host'
379
+ ? `ta gateway: ${target.host} is not among the hosts the gateway lets sandboxes reach; an administrator adds it in the console (Policy).`
380
+ : `ta gateway: port ${target.port} of ${target.host} is not let out: 80 and 443 only, unless the policy names it (${target.host}:${target.port}).`,
381
+ };
382
+ }
383
+ let addresses;
384
+ try {
385
+ addresses = isIP(target.host) ? [target.host] : (await lookup(target.host, { all: true, verbatim: true })).map(each => each.address);
386
+ }
387
+ catch (error) {
388
+ return { status: 502, message: `ta gateway: cannot resolve ${target.host}: ${error.message}` };
389
+ }
390
+ const own = EgressProxyUtil.ownAddresses();
391
+ const address = addresses.find(each => this.reachable(each, own));
392
+ if (!address) {
393
+ this.refuse(who.tenantId, target, 'network');
394
+ return { status: 403, message: `ta gateway: ${target.host} is in a private network or on this machine, which sandboxes do not reach.` };
395
+ }
396
+ return EgressProxyUtil.plain(address);
397
+ }
398
+ reachable(address, own) {
399
+ return EgressProxyUtil.reachable(address, this.networks, own);
400
+ }
401
+ refuse(tenantId, target, reason) {
402
+ var _a, _b;
403
+ const host = PORTS.has(target.port) ? target.host : `${target.host}:${target.port}`;
404
+ const list = (_a = this.refusals.get(tenantId)) !== null && _a !== void 0 ? _a : [];
405
+ const known = list.find(each => each.host === host && each.reason === reason);
406
+ const entry = { host, reason, at: Date.now(), count: ((_b = known === null || known === void 0 ? void 0 : known.count) !== null && _b !== void 0 ? _b : 0) + 1 };
407
+ this.refusals.set(tenantId, [entry, ...list.filter(each => each !== known)].slice(0, REFUSALS));
408
+ }
409
+ count(tenantId, bytes) {
410
+ var _a;
411
+ if (bytes > 0) {
412
+ this.pending.set(tenantId, ((_a = this.pending.get(tenantId)) !== null && _a !== void 0 ? _a : 0) + bytes);
413
+ }
414
+ }
415
+ reply(socket, status, message) {
416
+ const body = Buffer.from(`${message}\n`);
417
+ const challenge = status === 407 ? 'Proxy-Authenticate: Basic realm="ta gateway"\r\n' : '';
418
+ socket.end(`HTTP/1.1 ${status} ${STATUS_CODES[status]}\r\nContent-Type: text/plain; charset=utf-8\r\nContent-Length: ${body.length}\r\nConnection: close\r\n${challenge}\r\n${body}`);
419
+ }
420
+ end(response, status, message) {
421
+ response.writeHead(status, {
422
+ 'Content-Type': 'text/plain; charset=utf-8',
423
+ ...(status === 407 ? { 'Proxy-Authenticate': 'Basic realm="ta gateway"' } : {}),
424
+ });
425
+ response.end(`${message}\n`);
426
+ }
427
+ }
428
+ //# sourceMappingURL=egress-proxy.js.map
@@ -48,8 +48,11 @@ export declare class Environments {
48
48
  protected readonly running: Map<string, Running>;
49
49
  /** Why the tenant's Ta may not start now (suspended, its free minutes used), checked before each start. */
50
50
  guard?: (tenant: Tenant) => string | undefined;
51
- /** More of the environment of a sandbox the gateway starts: what reaches the models of the gateway. */
52
- envOf?: (tenant: Tenant, provider: SandboxProvider) => Record<string, string> | undefined;
51
+ /**
52
+ * More of the environment of a sandbox the gateway starts: what reaches the models of the gateway and its way
53
+ * out. `fresh`: the provider has no sandbox of the tenant, and makes one now.
54
+ */
55
+ envOf?: (tenant: Tenant, provider: SandboxProvider, fresh: boolean) => Record<string, string> | undefined;
53
56
  constructor(providers: SandboxProvider[], tenants: TenantStore, settings: {
54
57
  default?: string;
55
58
  own: boolean;
@@ -310,8 +310,10 @@ export class Environments {
310
310
  var _a;
311
311
  var _b;
312
312
  const { provider, own } = this.provider(tenant);
313
- const env = own ? undefined : (_a = this.envOf) === null || _a === void 0 ? void 0 : _a.call(this, tenant, provider);
314
- const endpoint = await provider.start({ ...EnvironmentsUtil.sandboxTenant(tenant), ...(env ? { env } : {}) });
313
+ const sandbox = EnvironmentsUtil.sandboxTenant(tenant);
314
+ const fresh = !own && this.envOf ? (await provider.state(sandbox).catch(() => 'missing')) === 'missing' : false;
315
+ const env = own ? undefined : (_a = this.envOf) === null || _a === void 0 ? void 0 : _a.call(this, tenant, provider, fresh);
316
+ const endpoint = await provider.start({ ...sandbox, ...(env ? { env } : {}) });
315
317
  await EnvironmentsUtil.waitReady(endpoint.url, (_b = this.settings.readyTimeoutMs) !== null && _b !== void 0 ? _b : provider.readyTimeoutMs);
316
318
  return endpoint;
317
319
  })();
@@ -12,9 +12,11 @@ Ta runs in a sandbox of its own (a container per tenant by default), or in a Ta
12
12
  The web client is served here; each browser's connection goes to the Ta of its tenant. Stops on SIGINT
13
13
  or SIGTERM.
14
14
 
15
- --host Address to listen on. Default: 127.0.0.1
16
- --port Port to listen on. Default: 4100, or PORT
17
- --dir Its configuration and data. Default: TA_GATEWAY_DIR, else ~/.ta/gateway
15
+ --host Address to listen on. Default: 127.0.0.1
16
+ --port Port to listen on. Default: 4100, or PORT
17
+ --dir Its configuration and data. Default: TA_GATEWAY_DIR, else ~/.ta/gateway
18
+ --config Where sandboxes.json and models.json are, when not in --dir (a directory mounted read-only).
19
+ Default: TA_GATEWAY_CONFIG
18
20
 
19
21
  Accounts sign in with the providers of the environment (TA_GITHUB_*, TA_GOOGLE_*, TA_WECHAT_*,
20
22
  TA_OIDC_*, as for ta serve) when TA_ALLOWED_USERS lets them in; TA_GATEWAY_ADMINS are let in too and
@@ -25,11 +27,14 @@ The sandboxes are those of sandboxes.json in the directory, as pi's models.json
25
27
  { "default": "docker", "providers": { "docker": { "type": "docker", "image": "ta:latest", "memory": "4g" } } }
26
28
  Types: docker, command (shell commands for any platform), local (no isolation: tests), ta (a Ta service
27
29
  that runs), module (a file whose default export makes a provider). See the README of @celljs/ta-gateway.
30
+
31
+ At /.well-known/ta it tells the deployment it is part of: TA_DEPLOYMENT_NAME, its own address and the
32
+ relay (TA_RELAY_URL), which every sandbox is given too; /healthz and /readyz are for probes.
28
33
  `;
29
34
  export var GatewayCli;
30
35
  (function (GatewayCli) {
31
36
  async function run(argv, options) {
32
- var _a, _b, _c, _d;
37
+ var _a, _b, _c, _d, _e;
33
38
  const { values, positionals } = parseArgs({
34
39
  args: argv,
35
40
  allowPositionals: true,
@@ -37,6 +42,7 @@ export var GatewayCli;
37
42
  host: { type: 'string' },
38
43
  port: { type: 'string' },
39
44
  dir: { type: 'string' },
45
+ config: { type: 'string' },
40
46
  name: { type: 'string' },
41
47
  help: { type: 'boolean', short: 'h' },
42
48
  },
@@ -59,8 +65,9 @@ export var GatewayCli;
59
65
  try {
60
66
  gateway = await GatewayServer.create({
61
67
  dir,
68
+ config: (_c = values.config) !== null && _c !== void 0 ? _c : (process.env.TA_GATEWAY_CONFIG || undefined),
62
69
  host: values.host,
63
- port: Number((_d = (_c = values.port) !== null && _c !== void 0 ? _c : process.env.PORT) !== null && _d !== void 0 ? _d : 4100),
70
+ port: Number((_e = (_d = values.port) !== null && _d !== void 0 ? _d : process.env.PORT) !== null && _e !== void 0 ? _e : 4100),
64
71
  publicDir: options.publicDir,
65
72
  taCommand: options.taCommand,
66
73
  version: options.version,
@@ -1,8 +1,11 @@
1
1
  import type { TaGatewayLimits, TaGatewayPolicy, TaGatewayRole } from '@celljs/ta-protocol';
2
+ import type { EgressSettings } from './egress-proxy.js';
2
3
  interface StoredPolicy {
3
4
  defaults?: TaGatewayLimits;
4
5
  /** Accounts made admins in the console. */
5
6
  admins?: string[];
7
+ /** The hosts members' sandboxes may reach through the proxy of the gateway; none: any public host. */
8
+ egressHosts?: string[];
6
9
  }
7
10
  /** The limits of a member once the defaults and their own are taken together: none where a value is missing. */
8
11
  export interface ResolvedLimits {
@@ -40,8 +43,10 @@ export declare class GatewayPolicy {
40
43
  lets(account: string): boolean;
41
44
  get defaults(): TaGatewayLimits;
42
45
  setDefaults(limits: TaGatewayLimits): void;
46
+ get egressHosts(): string[];
47
+ setEgressHosts(hosts: string[]): void;
43
48
  setRole(account: string, role: 'admin' | 'member'): void;
44
- view(idleMinutes: number): TaGatewayPolicy;
49
+ view(idleMinutes: number, egress?: EgressSettings): TaGatewayPolicy;
45
50
  protected read(): StoredPolicy;
46
51
  }
47
52
  export {};
@@ -122,13 +122,21 @@ export class GatewayPolicy {
122
122
  this.stored = { ...this.stored, defaults: limits };
123
123
  writePrivate(this.file, this.stored);
124
124
  }
125
+ get egressHosts() {
126
+ var _a;
127
+ return (_a = this.stored.egressHosts) !== null && _a !== void 0 ? _a : [];
128
+ }
129
+ setEgressHosts(hosts) {
130
+ this.stored = { ...this.stored, egressHosts: hosts.length > 0 ? hosts : undefined };
131
+ writePrivate(this.file, this.stored);
132
+ }
125
133
  setRole(account, role) {
126
134
  var _a;
127
135
  const admins = ((_a = this.stored.admins) !== null && _a !== void 0 ? _a : []).filter(other => other !== account);
128
136
  this.stored = { ...this.stored, admins: role === 'admin' ? [...admins, account] : admins };
129
137
  writePrivate(this.file, this.stored);
130
138
  }
131
- view(idleMinutes) {
139
+ view(idleMinutes, egress = { enabled: false, networks: [] }) {
132
140
  var _a;
133
141
  return {
134
142
  defaults: this.defaults,
@@ -137,6 +145,7 @@ export class GatewayPolicy {
137
145
  ...((_a = this.stored.admins) !== null && _a !== void 0 ? _a : []).filter(account => this.role(account) === 'admin').map(account => ({ account, role: 'admin' })),
138
146
  ],
139
147
  idleMinutes,
148
+ egress: { enabled: egress.enabled, hosts: this.egressHosts, networks: egress.networks },
140
149
  };
141
150
  }
142
151
  read() {
@@ -1,4 +1,4 @@
1
- import type { TaGatewayRole, TaQuotaBlock, TaQuotaState } from '@celljs/ta-protocol';
1
+ import type { TaEgressRefusal, TaGatewayRole, TaQuotaBlock, TaQuotaState } from '@celljs/ta-protocol';
2
2
  import { type GatewayPolicy, type ResolvedLimits } from './gateway-policy.js';
3
3
  import { type GatewayUsage } from './gateway-usage.js';
4
4
  import type { Tenant, TenantMeter, TenantStore } from './tenant-store.js';
@@ -16,6 +16,8 @@ export declare class GatewayQuotas {
16
16
  protected lastTick: number;
17
17
  /** By tenant: the times of its messages within the last minute. */
18
18
  protected readonly prompts: Map<string, number[]>;
19
+ /** When the sandboxes go out through the gateway: the latest connections of a tenant it refused. */
20
+ egressOf?: (tenant: Tenant) => TaEgressRefusal[] | undefined;
19
21
  constructor(policy: GatewayPolicy, tenants: TenantStore, usage: GatewayUsage, ownAllowed: () => boolean,
20
22
  /** Whether the gateway gives its sandboxes models: then it counts their tokens, and holds them to the limit. */
21
23
  metered?: () => boolean);
@@ -25,6 +27,9 @@ export declare class GatewayQuotas {
25
27
  meter(tenant: Tenant, now?: number): TenantMeter;
26
28
  blocked(tenant: Tenant, now?: number): TaQuotaBlock | undefined;
27
29
  state(tenant: Tenant, now?: number): TaQuotaState;
30
+ protected egressState(tenant: Tenant, meter: TenantMeter): Pick<TaQuotaState, 'egress'>;
31
+ /** What its sandbox moved through the proxy of the gateway, to the month of the tenant. */
32
+ addEgress(tenantId: string, bytes: number, now?: number): void;
28
33
  /** Why a call of a model of the gateway is refused now; owners have no limit. */
29
34
  refuseModels(tenant: Tenant, now?: number): string | undefined;
30
35
  /** What a call of a model took, to the month of the tenant. */
@@ -58,8 +58,25 @@ export class GatewayQuotas {
58
58
  promptsPerMinute: limits.promptsPerMinute,
59
59
  connections: limits.connections,
60
60
  blocked: this.blocked(tenant, now),
61
+ ...this.egressState(tenant, meter),
61
62
  };
62
63
  }
64
+ egressState(tenant, meter) {
65
+ var _a;
66
+ var _b;
67
+ const refused = (_a = this.egressOf) === null || _a === void 0 ? void 0 : _a.call(this, tenant);
68
+ return refused ? { egress: { bytes: (_b = meter.egressBytes) !== null && _b !== void 0 ? _b : 0, refused } } : {};
69
+ }
70
+ /** What its sandbox moved through the proxy of the gateway, to the month of the tenant. */
71
+ addEgress(tenantId, bytes, now = Date.now()) {
72
+ var _a;
73
+ const tenant = this.tenants.get(tenantId);
74
+ if (!tenant || bytes <= 0) {
75
+ return;
76
+ }
77
+ const meter = this.meter(tenant, now);
78
+ this.tenants.update(tenantId, { meter: { ...meter, egressBytes: ((_a = meter.egressBytes) !== null && _a !== void 0 ? _a : 0) + bytes } });
79
+ }
63
80
  /** Why a call of a model of the gateway is refused now; owners have no limit. */
64
81
  refuseModels(tenant, now = Date.now()) {
65
82
  var _a;