@celljs/ta-gateway 4.15.2 → 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 (81) hide show
  1. package/README.en.md +5 -2
  2. package/README.md +5 -2
  3. package/esm/node/command-sandbox.d.ts +1 -0
  4. package/esm/node/command-sandbox.js +10 -1
  5. package/esm/node/docker-engine.d.ts +10 -1
  6. package/esm/node/docker-engine.js +18 -1
  7. package/esm/node/docker-sandbox.d.ts +13 -1
  8. package/esm/node/docker-sandbox.js +35 -2
  9. package/esm/node/egress-proxy.d.ts +98 -0
  10. package/esm/node/egress-proxy.js +428 -0
  11. package/esm/node/environments.d.ts +5 -0
  12. package/esm/node/environments.js +7 -3
  13. package/esm/node/gateway-cli.js +12 -5
  14. package/esm/node/gateway-exec.d.ts +19 -0
  15. package/esm/node/gateway-exec.js +65 -0
  16. package/esm/node/gateway-policy.d.ts +7 -1
  17. package/esm/node/gateway-policy.js +12 -2
  18. package/esm/node/gateway-quotas.d.ts +15 -2
  19. package/esm/node/gateway-quotas.js +51 -3
  20. package/esm/node/gateway-server.d.ts +43 -1
  21. package/esm/node/gateway-server.js +179 -10
  22. package/esm/node/gateway-service-util.d.ts +41 -0
  23. package/esm/node/gateway-service-util.js +178 -0
  24. package/esm/node/gateway-service.d.ts +13 -41
  25. package/esm/node/gateway-service.js +41 -176
  26. package/esm/node/gateway-socket.d.ts +1 -1
  27. package/esm/node/gateway-socket.js +1 -1
  28. package/esm/node/index.d.ts +4 -0
  29. package/esm/node/index.js +4 -0
  30. package/esm/node/kubernetes-api.d.ts +35 -0
  31. package/esm/node/kubernetes-api.js +115 -0
  32. package/esm/node/kubernetes-sandbox.d.ts +198 -0
  33. package/esm/node/kubernetes-sandbox.js +279 -0
  34. package/esm/node/local-sandbox.d.ts +1 -0
  35. package/esm/node/local-sandbox.js +2 -1
  36. package/esm/node/model-proxy.d.ts +105 -0
  37. package/esm/node/model-proxy.js +435 -0
  38. package/esm/node/sandbox-provider.d.ts +17 -0
  39. package/esm/node/sandbox-provider.js +2 -1
  40. package/esm/node/tenant-store.d.ts +22 -0
  41. package/esm/node/tenant-store.js +25 -0
  42. package/lib/node/command-sandbox.d.ts +1 -0
  43. package/lib/node/command-sandbox.js +10 -1
  44. package/lib/node/docker-engine.d.ts +10 -1
  45. package/lib/node/docker-engine.js +18 -1
  46. package/lib/node/docker-sandbox.d.ts +13 -1
  47. package/lib/node/docker-sandbox.js +35 -2
  48. package/lib/node/egress-proxy.d.ts +99 -0
  49. package/lib/node/egress-proxy.js +433 -0
  50. package/lib/node/environments.d.ts +5 -0
  51. package/lib/node/environments.js +7 -3
  52. package/lib/node/gateway-cli.js +12 -5
  53. package/lib/node/gateway-exec.d.ts +20 -0
  54. package/lib/node/gateway-exec.js +69 -0
  55. package/lib/node/gateway-policy.d.ts +7 -1
  56. package/lib/node/gateway-policy.js +12 -2
  57. package/lib/node/gateway-quotas.d.ts +15 -2
  58. package/lib/node/gateway-quotas.js +51 -3
  59. package/lib/node/gateway-server.d.ts +43 -1
  60. package/lib/node/gateway-server.js +177 -8
  61. package/lib/node/gateway-service-util.d.ts +42 -0
  62. package/lib/node/gateway-service-util.js +182 -0
  63. package/lib/node/gateway-service.d.ts +13 -41
  64. package/lib/node/gateway-service.js +63 -199
  65. package/lib/node/gateway-socket.d.ts +1 -1
  66. package/lib/node/gateway-socket.js +10 -10
  67. package/lib/node/index.d.ts +4 -0
  68. package/lib/node/index.js +4 -0
  69. package/lib/node/kubernetes-api.d.ts +36 -0
  70. package/lib/node/kubernetes-api.js +120 -0
  71. package/lib/node/kubernetes-sandbox.d.ts +199 -0
  72. package/lib/node/kubernetes-sandbox.js +283 -0
  73. package/lib/node/local-sandbox.d.ts +1 -0
  74. package/lib/node/local-sandbox.js +2 -1
  75. package/lib/node/model-proxy.d.ts +106 -0
  76. package/lib/node/model-proxy.js +440 -0
  77. package/lib/node/sandbox-provider.d.ts +17 -0
  78. package/lib/node/sandbox-provider.js +2 -1
  79. package/lib/node/tenant-store.d.ts +22 -0
  80. package/lib/node/tenant-store.js +25 -0
  81. 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,6 +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
+ /**
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;
51
56
  constructor(providers: SandboxProvider[], tenants: TenantStore, settings: {
52
57
  default?: string;
53
58
  own: boolean;
@@ -312,9 +312,13 @@ class Environments {
312
312
  running.error = undefined;
313
313
  const starting = (async () => {
314
314
  var _a;
315
- const { provider } = this.provider(tenant);
316
- const endpoint = await provider.start(EnvironmentsUtil.sandboxTenant(tenant));
317
- await EnvironmentsUtil.waitReady(endpoint.url, (_a = this.settings.readyTimeoutMs) !== null && _a !== void 0 ? _a : provider.readyTimeoutMs);
315
+ var _b;
316
+ const { provider, own } = this.provider(tenant);
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 } : {}) });
321
+ await EnvironmentsUtil.waitReady(endpoint.url, (_b = this.settings.readyTimeoutMs) !== null && _b !== void 0 ? _b : provider.readyTimeoutMs);
318
322
  return endpoint;
319
323
  })();
320
324
  running.starting = starting;
@@ -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,
@@ -0,0 +1,20 @@
1
+ import type { WebSocketConnection } from '@celljs/rpc/lib/node/websocket/websocket-connection';
2
+ import type { SandboxEndpoint } from './sandbox-provider';
3
+ /**
4
+ * A connection of another Ta to the exec server of its account's sandbox (`/api/exec`): what it sends goes to the
5
+ * sandbox once it answers, and back, unread. The account's own token is checked by the gateway; the sandbox's by it.
6
+ */
7
+ export declare class GatewayExecProxy {
8
+ protected readonly outer: WebSocketConnection;
9
+ protected readonly release: () => void;
10
+ protected inner?: WebSocket;
11
+ protected readonly queued: string[];
12
+ protected queuedBytes: number;
13
+ protected closed: boolean;
14
+ constructor(outer: WebSocketConnection, endpoint: Promise<SandboxEndpoint>, release: () => void);
15
+ protected open(endpoint: SandboxEndpoint): void;
16
+ protected send(text: string): void;
17
+ close(code: number, reason: string): void;
18
+ protected dispose(): void;
19
+ }
20
+ //# sourceMappingURL=gateway-exec.d.ts.map
@@ -0,0 +1,69 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.GatewayExecProxy = void 0;
4
+ /** What waits for the sandbox at most, as GatewaySocket. */
5
+ const MAX_QUEUED_BYTES = 16 * 1024 * 1024;
6
+ /**
7
+ * A connection of another Ta to the exec server of its account's sandbox (`/api/exec`): what it sends goes to the
8
+ * sandbox once it answers, and back, unread. The account's own token is checked by the gateway; the sandbox's by it.
9
+ */
10
+ class GatewayExecProxy {
11
+ constructor(outer, endpoint, release) {
12
+ this.outer = outer;
13
+ this.release = release;
14
+ this.queued = [];
15
+ this.queuedBytes = 0;
16
+ this.closed = false;
17
+ outer.onMessage(text => this.send(text));
18
+ outer.onClose(() => this.dispose());
19
+ endpoint.then(found => this.open(found), (error) => this.close(1011, `Your environment did not start: ${error.message}`.slice(0, 120)));
20
+ }
21
+ open(endpoint) {
22
+ if (this.closed) {
23
+ return;
24
+ }
25
+ const url = new URL(`${endpoint.url.replace(/^http/, 'ws')}/api/exec`);
26
+ url.searchParams.set('token', endpoint.token);
27
+ const inner = new WebSocket(url);
28
+ this.inner = inner;
29
+ inner.onopen = () => {
30
+ for (const text of this.queued.splice(0)) {
31
+ inner.send(text);
32
+ }
33
+ this.queuedBytes = 0;
34
+ };
35
+ inner.onmessage = message => this.outer.open && this.outer.send(String(message.data));
36
+ inner.onclose = event => this.close(event.code === 1000 || event.code === 1001 ? 1001 : 1011, 'The sandbox closed the connection.');
37
+ inner.onerror = () => undefined;
38
+ }
39
+ send(text) {
40
+ var _a;
41
+ if (((_a = this.inner) === null || _a === void 0 ? void 0 : _a.readyState) === WebSocket.OPEN) {
42
+ this.inner.send(text);
43
+ }
44
+ else if (this.queuedBytes + text.length <= MAX_QUEUED_BYTES) {
45
+ this.queued.push(text);
46
+ this.queuedBytes += text.length;
47
+ }
48
+ else {
49
+ this.close(1013, 'The environment is still starting.');
50
+ }
51
+ }
52
+ close(code, reason) {
53
+ if (this.outer.open) {
54
+ this.outer.close(code, reason);
55
+ }
56
+ this.dispose();
57
+ }
58
+ dispose() {
59
+ var _a;
60
+ if (this.closed) {
61
+ return;
62
+ }
63
+ this.closed = true;
64
+ this.release();
65
+ (_a = this.inner) === null || _a === void 0 ? void 0 : _a.close();
66
+ }
67
+ }
68
+ exports.GatewayExecProxy = GatewayExecProxy;
69
+ //# sourceMappingURL=gateway-exec.js.map
@@ -1,12 +1,16 @@
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 {
9
12
  freeMinutes?: number;
13
+ monthlyTokens?: number;
10
14
  promptsPerMinute?: number;
11
15
  connections?: number;
12
16
  providers?: string[];
@@ -39,8 +43,10 @@ export declare class GatewayPolicy {
39
43
  lets(account: string): boolean;
40
44
  get defaults(): TaGatewayLimits;
41
45
  setDefaults(limits: TaGatewayLimits): void;
46
+ get egressHosts(): string[];
47
+ setEgressHosts(hosts: string[]): void;
42
48
  setRole(account: string, role: 'admin' | 'member'): void;
43
- view(idleMinutes: number): TaGatewayPolicy;
49
+ view(idleMinutes: number, egress?: EgressSettings): TaGatewayPolicy;
44
50
  protected read(): StoredPolicy;
45
51
  }
46
52
  export {};