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