@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
@@ -1,10 +1,13 @@
1
1
  import { type IncomingMessage, type Server, type ServerResponse } from 'node:http';
2
2
  import { type Duplex } from 'node:stream';
3
+ import { WebSocketConnection } from '@celljs/rpc/lib/node/websocket/websocket-connection';
3
4
  import { SignInFlow } from '@celljs/ta-host/lib/node/sign-in/sign-in-flow';
4
5
  import { type SignInAccount } from '@celljs/ta-host/lib/node/sign-in/sign-in-provider';
5
6
  import { type TaQuotaBlock } from '@celljs/ta-protocol';
7
+ import { type EgressAuthorization, EgressProxy } from './egress-proxy.js';
6
8
  import { Environments } from './environments.js';
7
9
  import { GatewayAudit } from './gateway-audit.js';
10
+ import { GatewayExecProxy } from './gateway-exec.js';
8
11
  import { GatewayPolicy } from './gateway-policy.js';
9
12
  import { GatewayQuotas } from './gateway-quotas.js';
10
13
  import { type GatewayCaller, GatewayService } from './gateway-service.js';
@@ -19,6 +22,11 @@ export declare const SANDBOX_TYPES: Record<string, SandboxProviderFactory>;
19
22
  export interface GatewayServerOptions {
20
23
  /** Its configuration and data: sandboxes.json, access.json, tenants/, links.json. */
21
24
  dir: string;
25
+ /**
26
+ * Where sandboxes.json and models.json are, when not in `dir`: a directory a platform mounts read-only (a ConfigMap,
27
+ * the files of a compose project), apart from the data the gateway writes.
28
+ */
29
+ config?: string;
22
30
  host?: string;
23
31
  port?: number;
24
32
  /** The web client: dist/public of @celljs/ta. */
@@ -34,6 +42,11 @@ export declare namespace GatewayServerUtil {
34
42
  * mapped on Linux too), a process of this machine 127.0.0.1, another the public address.
35
43
  */
36
44
  function reach(type: string, port: number, publicUrl: string | undefined): string;
45
+ /**
46
+ * What every sandbox is told of the deployment (docs/design/ta-deploy.md 3): its relay, so that a Ta in the cloud
47
+ * pairs, shares and opens rooms on the relay of its people, and its name.
48
+ */
49
+ function deploymentEnv(env: Record<string, string | undefined>): Record<string, string>;
37
50
  /** Where another Ta reaches the exec server of its account's sandbox. */
38
51
  const EXEC_PATH = "/api/exec";
39
52
  /** What a page is told when its Ta does not start for its account's limits; TaGatewayInfo.quota says it in the page's words. */
@@ -67,11 +80,17 @@ export declare class GatewayServer {
67
80
  readonly links: SignInLinks;
68
81
  protected readonly service: GatewayService;
69
82
  protected readonly sockets: Set<GatewaySocket>;
83
+ /** The connections of other Ta to the exec servers of sandboxes (`/api/exec`), by the token they signed in with. */
84
+ protected readonly execs: Map<GatewayExecProxy, {
85
+ token: string;
86
+ tenantId: string;
87
+ }>;
70
88
  readonly policy: GatewayPolicy;
71
89
  readonly quotas: GatewayQuotas;
72
90
  readonly usage: GatewayUsage;
73
91
  readonly audit: GatewayAudit;
74
92
  readonly models: ModelProxy;
93
+ readonly egress: EgressProxy;
75
94
  /** The port it listens on, once it does. */
76
95
  protected port?: number;
77
96
  protected server?: Server;
@@ -79,6 +98,11 @@ export declare class GatewayServer {
79
98
  static create(options: GatewayServerOptions): Promise<GatewayServer>;
80
99
  protected constructor(options: GatewayServerOptions, providers: Awaited<ReturnType<typeof SandboxProviders.create>>, config: ReturnType<typeof SandboxProviders.read>, models?: GatewayModelsConfig);
81
100
  isAdmin(account: string): boolean;
101
+ /**
102
+ * Who goes out through the proxy: the tenant of the user, with the secret of its sandbox's epoch (that of a
103
+ * sandbox made again since is refused); members to the hosts of the policy, owners anywhere public.
104
+ */
105
+ authorizeEgress(user: string, password: string): EgressAuthorization;
82
106
  /** The minutes of the sandboxes that ran since the last time; those out of them, or suspended, stop. */
83
107
  tick(now?: number): Promise<void>;
84
108
  listen(): Promise<string>;
@@ -93,6 +117,11 @@ export declare class GatewayServer {
93
117
  /** Who a token signs in, while its account is let in. */
94
118
  caller(token: string): GatewayCaller | undefined;
95
119
  protected handle(request: IncomingMessage, response: ServerResponse): Promise<void>;
120
+ /**
121
+ * What it is part of (TA_WELL_KNOWN_PATH: its address, the relay of the deployment), and whether it runs and can
122
+ * keep what it holds (the probes of a platform). For anyone: nothing of it is secret.
123
+ */
124
+ protected describe(path: string, request: IncomingMessage, response: ServerResponse): void;
96
125
  /** A link of `ta gateway link`: lets its account in, and signs this browser in as it. */
97
126
  protected useLink(request: IncomingMessage, response: ServerResponse, secret: string): void;
98
127
  protected signedIn(response: ServerResponse, token: string, account: SignInAccount, origin: string): void;
@@ -102,4 +131,6 @@ export declare class GatewayServer {
102
131
  protected files(request: IncomingMessage, response: ServerResponse): Promise<void>;
103
132
  protected page(request: IncomingMessage, response: ServerResponse, path: string): void;
104
133
  protected upgrade(request: IncomingMessage, socket: Duplex, head: Buffer): void;
134
+ /** Another Ta works in the sandbox of the caller's account: cut off as the pages of its sign-in are. */
135
+ protected openExec(exec: WebSocketConnection, caller: GatewayCaller): GatewayExecProxy;
105
136
  }
@@ -1,4 +1,4 @@
1
- import { createReadStream, existsSync, mkdirSync, statSync } from 'node:fs';
1
+ import { accessSync, constants, createReadStream, existsSync, mkdirSync, statSync } from 'node:fs';
2
2
  import { createServer, request as httpRequest } from 'node:http';
3
3
  import { request as httpsRequest } from 'node:https';
4
4
  import { extname, join, normalize, sep } from 'node:path';
@@ -8,9 +8,10 @@ import { AccessStore, AccessUtil } from '@celljs/ta-host/lib/node/sign-in/access
8
8
  import { SignInFlow, SignInUtil } from '@celljs/ta-host/lib/node/sign-in/sign-in-flow';
9
9
  import { SignInPages, SignInPageUtil } from '@celljs/ta-host/lib/node/sign-in/sign-in-pages';
10
10
  import { SignInProviders } from '@celljs/ta-host/lib/node/sign-in/sign-in-provider';
11
- import { TA_FILES_PATH, TA_WEBSOCKET_PATH } from '@celljs/ta-protocol';
11
+ import { TA_FILES_PATH, TA_WEBSOCKET_PATH, TA_WELL_KNOWN_PATH, TaDeploymentUtil } from '@celljs/ta-protocol';
12
12
  import { CommandSandbox } from './command-sandbox.js';
13
13
  import { DockerSandbox } from './docker-sandbox.js';
14
+ import { EgressProxy, EgressProxyUtil } from './egress-proxy.js';
14
15
  import { Environments } from './environments.js';
15
16
  import { GatewayAudit } from './gateway-audit.js';
16
17
  import { GatewayExecProxy } from './gateway-exec.js';
@@ -19,6 +20,7 @@ import { GatewayQuotas } from './gateway-quotas.js';
19
20
  import { GatewayService } from './gateway-service.js';
20
21
  import { GatewaySocket } from './gateway-socket.js';
21
22
  import { GatewayUsage } from './gateway-usage.js';
23
+ import { KubernetesSandbox } from './kubernetes-sandbox.js';
22
24
  import { LocalSandbox } from './local-sandbox.js';
23
25
  import { ModelProxy, ModelProxyUtil } from './model-proxy.js';
24
26
  import { SandboxProviders } from './sandbox-provider.js';
@@ -46,6 +48,7 @@ const TYPES = {
46
48
  /** The built-in types of providers of sandboxes. */
47
49
  export const SANDBOX_TYPES = {
48
50
  docker: (id, config) => new DockerSandbox(id, config),
51
+ kubernetes: (id, config) => new KubernetesSandbox(id, config),
49
52
  command: (id, config) => new CommandSandbox(id, config),
50
53
  local: (id, config, context) => new LocalSandbox(id, config, context),
51
54
  ta: (id, config) => new TaSandbox(id, config),
@@ -66,6 +69,23 @@ export var GatewayServerUtil;
66
69
  return publicUrl;
67
70
  }
68
71
  GatewayServerUtil.reach = reach;
72
+ /**
73
+ * What every sandbox is told of the deployment (docs/design/ta-deploy.md 3): its relay, so that a Ta in the cloud
74
+ * pairs, shares and opens rooms on the relay of its people, and its name.
75
+ */
76
+ function deploymentEnv(env) {
77
+ var _a;
78
+ const given = {};
79
+ const relay = TaDeploymentUtil.url(env.TA_RELAY_URL);
80
+ if (relay) {
81
+ given.TA_RELAY_URL = relay;
82
+ }
83
+ if ((_a = env.TA_DEPLOYMENT_NAME) === null || _a === void 0 ? void 0 : _a.trim()) {
84
+ given.TA_DEPLOYMENT_NAME = env.TA_DEPLOYMENT_NAME.trim();
85
+ }
86
+ return given;
87
+ }
88
+ GatewayServerUtil.deploymentEnv = deploymentEnv;
69
89
  /** Where another Ta reaches the exec server of its account's sandbox. */
70
90
  GatewayServerUtil.EXEC_PATH = '/api/exec';
71
91
  /** What a page is told when its Ta does not start for its account's limits; TaGatewayInfo.quota says it in the page's words. */
@@ -125,10 +145,11 @@ export var GatewayServerUtil;
125
145
  */
126
146
  export class GatewayServer {
127
147
  static async create(options) {
128
- const models = ModelProxyUtil.read(options.dir);
148
+ var _a, _b;
149
+ const models = ModelProxyUtil.read((_a = options.config) !== null && _a !== void 0 ? _a : options.dir);
129
150
  mkdirSync(options.dir, { recursive: true, mode: 0o700 });
130
- const config = SandboxProviders.read(options.dir);
131
- const context = { dir: options.dir, taCommand: options.taCommand };
151
+ const config = SandboxProviders.read((_b = options.config) !== null && _b !== void 0 ? _b : options.dir);
152
+ const context = { dir: options.dir, config: options.config, taCommand: options.taCommand };
132
153
  const providers = await SandboxProviders.create(config, context, SANDBOX_TYPES);
133
154
  return new GatewayServer(options, providers, config, models);
134
155
  }
@@ -136,6 +157,8 @@ export class GatewayServer {
136
157
  var _a, _b;
137
158
  this.options = options;
138
159
  this.sockets = new Set();
160
+ /** The connections of other Ta to the exec servers of sandboxes (`/api/exec`), by the token they signed in with. */
161
+ this.execs = new Map();
139
162
  const env = (_a = options.env) !== null && _a !== void 0 ? _a : process.env;
140
163
  const owners = AccessUtil.parseList(env.TA_GATEWAY_ADMINS);
141
164
  this.policy = new GatewayPolicy(options.dir, owners);
@@ -160,13 +183,26 @@ export class GatewayServer {
160
183
  },
161
184
  record: (id, usage, cost) => this.quotas.addTokens(id, ModelProxyUtil.total(usage), cost),
162
185
  }, env);
163
- this.environments.envOf = (tenant, provider) => {
186
+ this.egress = new EgressProxy(EgressProxyUtil.settings(config.egress), { authorize: (user, password) => this.authorizeEgress(user, password) });
187
+ this.quotas.egressOf = tenant => (this.egress.enabled ? this.egress.refused(tenant.id) : undefined);
188
+ this.environments.envOf = (tenant, provider, fresh) => {
164
189
  var _a, _b, _c;
165
- if (!this.models.enabled) {
166
- return undefined;
190
+ const deployment = GatewayServerUtil.deploymentEnv(env);
191
+ if (!this.models.enabled && !this.egress.enabled) {
192
+ return Object.keys(deployment).length ? deployment : undefined;
193
+ }
194
+ const base = (_a = provider.gatewayUrl) !== null && _a !== void 0 ? _a : GatewayServerUtil.reach(provider.type, (_c = (_b = this.port) !== null && _b !== void 0 ? _b : options.port) !== null && _c !== void 0 ? _c : 4100, SandboxProviders.publicBase(env));
195
+ const url = base.replace(/\/+$/, '');
196
+ const given = { ...deployment };
197
+ if (this.models.enabled) {
198
+ Object.assign(given, { TA_MODEL_PROXY_URL: url, TA_MODEL_PROXY_KEY: this.tenants.modelKey(tenant.id) });
167
199
  }
168
- const url = (_a = provider.gatewayUrl) !== null && _a !== void 0 ? _a : GatewayServerUtil.reach(provider.type, (_c = (_b = this.port) !== null && _b !== void 0 ? _b : options.port) !== null && _c !== void 0 ? _c : 4100, SandboxProviders.publicBase(env));
169
- return { TA_MODEL_PROXY_URL: url.replace(/\/+$/, ''), TA_MODEL_PROXY_KEY: this.tenants.modelKey(tenant.id) };
200
+ if (this.egress.enabled) {
201
+ // A sandbox made anew is of a new epoch: what the one before it went out with stops working.
202
+ const key = this.tenants.egressKey(tenant.id, fresh);
203
+ Object.assign(given, EgressProxyUtil.env(url, tenant.id, `${key.epoch}.${key.secret}`));
204
+ }
205
+ return given;
170
206
  };
171
207
  this.service = new GatewayService({
172
208
  flow: this.flow,
@@ -178,14 +214,42 @@ export class GatewayServer {
178
214
  audit: this.audit,
179
215
  hooks: { cutOff: () => this.cutOff(), reset: id => this.reset(id) },
180
216
  models: this.models,
217
+ egress: this.egress,
181
218
  meta: { links: this.links, startedAt: Date.now(), version: options.version, publicUrl: SandboxProviders.publicBase(env) },
182
219
  });
183
220
  }
184
221
  isAdmin(account) {
185
222
  return this.policy.role(account) !== 'member';
186
223
  }
224
+ /**
225
+ * Who goes out through the proxy: the tenant of the user, with the secret of its sandbox's epoch (that of a
226
+ * sandbox made again since is refused); members to the hosts of the policy, owners anywhere public.
227
+ */
228
+ authorizeEgress(user, password) {
229
+ const tenant = this.tenants.get(user);
230
+ const dot = password.indexOf('.');
231
+ const epoch = Number(password.slice(0, dot));
232
+ const known = tenant === null || tenant === void 0 ? void 0 : tenant.egress;
233
+ if (!tenant || !known || dot < 1 || !EgressProxyUtil.sameSecret(password.slice(dot + 1), epoch === known.epoch ? known.secret : '')) {
234
+ const stale = known !== undefined && Number.isInteger(epoch) && epoch < known.epoch;
235
+ return {
236
+ status: 407,
237
+ message: stale
238
+ ? `ta gateway: a sandbox of epoch ${known.epoch} took over from this one (epoch ${epoch}); it goes out no more.`
239
+ : 'ta gateway: these credentials are of no sandbox of the gateway.',
240
+ };
241
+ }
242
+ if (this.quotas.blocked(tenant) === 'suspended') {
243
+ return { status: 403, message: 'ta gateway: your account is suspended by an administrator of the gateway.' };
244
+ }
245
+ const hosts = this.policy.egressHosts;
246
+ return { tenantId: tenant.id, hosts: this.quotas.role(tenant) === 'owner' || hosts.length === 0 ? undefined : hosts };
247
+ }
187
248
  /** The minutes of the sandboxes that ran since the last time; those out of them, or suspended, stop. */
188
249
  async tick(now = Date.now()) {
250
+ for (const [id, bytes] of this.egress.flush()) {
251
+ this.quotas.addEgress(id, bytes, now);
252
+ }
189
253
  for (const tenant of this.quotas.tick(this.environments.runningIds(), now)) {
190
254
  console.log(`ta gateway: ${tenant.account} used its free minutes of the month: its sandbox stops`);
191
255
  await this.environments.stop(tenant.id).catch(() => undefined);
@@ -196,6 +260,11 @@ export class GatewayServer {
196
260
  var _a, _b;
197
261
  const server = createServer((request, response) => void this.handle(request, response));
198
262
  server.on('upgrade', (request, socket, head) => this.upgrade(request, socket, head));
263
+ // The way out of the sandboxes: CONNECT for https, absolute URLs for http (handle).
264
+ server.on('connect', (request, socket, head) => this.egress.connect(request, socket, head).catch(error => {
265
+ console.warn(`ta gateway: CONNECT ${request.url} failed: ${error.message}`);
266
+ socket.destroy();
267
+ }));
199
268
  this.server = server;
200
269
  this.ticker = setInterval(() => void this.tick().catch(error => console.warn(`ta gateway: counting minutes failed: ${error.message}`)), TICK_MS);
201
270
  (_b = (_a = this.ticker).unref) === null || _b === void 0 ? void 0 : _b.call(_a);
@@ -215,6 +284,9 @@ export class GatewayServer {
215
284
  for (const socket of this.sockets) {
216
285
  socket.close(1001, 'The gateway is stopping.');
217
286
  }
287
+ for (const exec of this.execs.keys()) {
288
+ exec.close(1001, 'The gateway is stopping.');
289
+ }
218
290
  await this.environments.dispose();
219
291
  await new Promise(resolve => (this.server ? this.server.close(() => resolve()) : resolve()));
220
292
  }
@@ -225,6 +297,11 @@ export class GatewayServer {
225
297
  socket.close(1008, 'Signed out');
226
298
  }
227
299
  }
300
+ for (const [exec, { token }] of this.execs) {
301
+ if (!this.caller(token)) {
302
+ exec.close(1008, 'Signed out');
303
+ }
304
+ }
228
305
  }
229
306
  /**
230
307
  * The connections of the tenant of now close, and connect again to its environment: in a moment, so that
@@ -232,10 +309,14 @@ export class GatewayServer {
232
309
  */
233
310
  reset(tenantId) {
234
311
  const sockets = [...this.sockets].filter(socket => socket.tenantId === tenantId);
312
+ const execs = [...this.execs].filter(([, exec]) => exec.tenantId === tenantId).map(([proxy]) => proxy);
235
313
  setTimeout(() => {
236
314
  for (const socket of sockets) {
237
315
  socket.close(1012, 'The environment changed.');
238
316
  }
317
+ for (const exec of execs) {
318
+ exec.close(1012, 'The environment changed.');
319
+ }
239
320
  }, 100);
240
321
  }
241
322
  /** Who a token signs in, while its account is let in. */
@@ -249,10 +330,16 @@ export class GatewayServer {
249
330
  return { token, account: signIn.account, tenant, role, admin: role !== 'member' };
250
331
  }
251
332
  async handle(request, response) {
252
- var _a;
333
+ var _a, _b;
253
334
  const path = ((_a = request.url) !== null && _a !== void 0 ? _a : '/').split('?')[0];
254
335
  try {
255
- if (path.startsWith(SIGN_IN_LINK_PATH)) {
336
+ if (/^[a-z][a-z0-9+.-]*:\/\//i.test((_b = request.url) !== null && _b !== void 0 ? _b : '')) {
337
+ await this.egress.request(request, response);
338
+ }
339
+ else if (path === TA_WELL_KNOWN_PATH || path === '/healthz' || path === '/readyz') {
340
+ this.describe(path, request, response);
341
+ }
342
+ else if (path.startsWith(SIGN_IN_LINK_PATH)) {
256
343
  this.useLink(request, response, path.slice(SIGN_IN_LINK_PATH.length));
257
344
  }
258
345
  else if (SignInPages.matches(request)) {
@@ -284,6 +371,30 @@ export class GatewayServer {
284
371
  }
285
372
  }
286
373
  }
374
+ /**
375
+ * What it is part of (TA_WELL_KNOWN_PATH: its address, the relay of the deployment), and whether it runs and can
376
+ * keep what it holds (the probes of a platform). For anyone: nothing of it is secret.
377
+ */
378
+ describe(path, request, response) {
379
+ var _a;
380
+ const version = this.options.version;
381
+ let body = { ok: true, ...(version ? { version } : {}) };
382
+ let status = 200;
383
+ if (path === TA_WELL_KNOWN_PATH) {
384
+ body = TaDeploymentUtil.describe((_a = this.options.env) !== null && _a !== void 0 ? _a : process.env, { gateway: this.origin(request) }, version);
385
+ }
386
+ else if (path === '/readyz') {
387
+ try {
388
+ accessSync(this.options.dir, constants.W_OK);
389
+ }
390
+ catch (error) {
391
+ status = 503;
392
+ body = { ok: false, error: `${this.options.dir} cannot be written: ${error.message}` };
393
+ }
394
+ }
395
+ response.writeHead(status, TaDeploymentUtil.HEADERS);
396
+ response.end(JSON.stringify(body));
397
+ }
287
398
  /** A link of `ta gateway link`: lets its account in, and signs this browser in as it. */
288
399
  useLink(request, response, secret) {
289
400
  response.setHeader('Cache-Control', 'no-store');
@@ -407,7 +518,7 @@ export class GatewayServer {
407
518
  return;
408
519
  }
409
520
  const exec = WebSocketConnection.open(socket, checked.key, head, { maxPayload: 64 * 1024 * 1024, heartbeat: 30000 });
410
- new GatewayExecProxy(exec, this.environments.ensure(caller.tenant), this.environments.connect(caller.tenant.id));
521
+ this.openExec(exec, caller);
411
522
  return;
412
523
  }
413
524
  const connection = WebSocketConnection.open(socket, checked.key, head, { maxPayload: 32 * 1024 * 1024, heartbeat: 30000, deflate: checked.deflate });
@@ -415,5 +526,12 @@ export class GatewayServer {
415
526
  this.sockets.add(gatewaySocket);
416
527
  connection.onClose(() => this.sockets.delete(gatewaySocket));
417
528
  }
529
+ /** Another Ta works in the sandbox of the caller's account: cut off as the pages of its sign-in are. */
530
+ openExec(exec, caller) {
531
+ const proxy = new GatewayExecProxy(exec, this.environments.ensure(caller.tenant), this.environments.connect(caller.tenant.id));
532
+ this.execs.set(proxy, { token: caller.token, tenantId: caller.tenant.id });
533
+ exec.onClose(() => this.execs.delete(proxy));
534
+ return proxy;
535
+ }
418
536
  }
419
537
  //# sourceMappingURL=gateway-server.js.map
@@ -0,0 +1,41 @@
1
+ import { type TaEnvironmentChoice, TaErrorCode, type TaGatewayRole } from '@celljs/ta-protocol';
2
+ export declare class GatewayCallError extends Error {
3
+ readonly code: TaErrorCode;
4
+ readonly hint: string;
5
+ constructor(message: string, code: TaErrorCode, hint: string);
6
+ }
7
+ type Need = TaGatewayRole | 'anyone';
8
+ export declare namespace GatewayServiceUtil {
9
+ const DEFAULT_LOG_LINES = 200;
10
+ const MAX_LOG_LINES = 2000;
11
+ /**
12
+ * Who may call each method: `anyone` signed in (about their own Ta, their own sign-ins), `admin` (owners too),
13
+ * `owner`. A method not here is no method. What an admin may do to another account is checked again by its role
14
+ * (GatewayService.manage).
15
+ */
16
+ const RULES: Record<string, Record<string, Need>>;
17
+ /** What an administrator did or looked at of others: kept in the audit. */
18
+ const AUDITED: Set<string>;
19
+ function need(service: string, name: string): Need | undefined;
20
+ function allowed(role: TaGatewayRole, need: Need): boolean;
21
+ /** As many lines as asked, within bounds. */
22
+ function lines(value: unknown): number;
23
+ /** Days of a trend, 1 to 31. */
24
+ function days(value: unknown): number;
25
+ /** The services the gateway answers itself, not the Ta of the tenant. */
26
+ const SERVICES: string[];
27
+ function owns(method: unknown): method is string;
28
+ /** Whether the text of a message may be a call of {@link SERVICES}: those that are not are not parsed. */
29
+ function mayOwn(text: string): boolean;
30
+ /** The calls that send the agents a message, which the limit of messages a minute counts. */
31
+ const PROMPTS: string[];
32
+ function mayPrompt(text: string): boolean;
33
+ /** The error of a JSON-RPC answer, as ta serve sends an ApplicationError: the client reads its code and hint. */
34
+ function error(id: unknown, message: string, code: TaErrorCode, hint: string): string;
35
+ function result(id: unknown, result: unknown): string;
36
+ function forbidden(message: string, hint: string): GatewayCallError;
37
+ function choice(value: unknown, own: boolean, providers: string[]): TaEnvironmentChoice | undefined;
38
+ /** What the audit says of the arguments of a call: its numbers, flags and roles, never more. */
39
+ function detail(method: string, params: unknown[]): string | undefined;
40
+ }
41
+ export {};
@@ -0,0 +1,178 @@
1
+ import { TA_RPC_ERROR_CODE, TaErrorCode } from '@celljs/ta-protocol';
2
+ import { GatewayPolicyUtil } from './gateway-policy.js';
3
+ import { TaSandboxUtil } from './ta-sandbox.js';
4
+ export class GatewayCallError extends Error {
5
+ constructor(message, code, hint) {
6
+ super(message);
7
+ this.code = code;
8
+ this.hint = hint;
9
+ }
10
+ }
11
+ export var GatewayServiceUtil;
12
+ (function (GatewayServiceUtil) {
13
+ GatewayServiceUtil.DEFAULT_LOG_LINES = 200;
14
+ GatewayServiceUtil.MAX_LOG_LINES = 2000;
15
+ /**
16
+ * Who may call each method: `anyone` signed in (about their own Ta, their own sign-ins), `admin` (owners too),
17
+ * `owner`. A method not here is no method. What an admin may do to another account is checked again by its role
18
+ * (GatewayService.manage).
19
+ */
20
+ GatewayServiceUtil.RULES = {
21
+ TaGatewayServer: {
22
+ getGateway: 'anyone',
23
+ setEnvironment: 'anyone',
24
+ restartEnvironment: 'anyone',
25
+ listTenants: 'admin',
26
+ getConsole: 'admin',
27
+ getTenantAgents: 'admin',
28
+ getAgentActivity: 'admin',
29
+ getTenantLogs: 'admin',
30
+ getUsageTrend: 'admin',
31
+ getPolicy: 'admin',
32
+ getAudit: 'admin',
33
+ startTenant: 'admin',
34
+ stopTenant: 'admin',
35
+ restartTenant: 'admin',
36
+ createSignInLink: 'admin',
37
+ setTenantLimits: 'admin',
38
+ grantMinutes: 'admin',
39
+ setSuspended: 'admin',
40
+ setDefaultLimits: 'owner',
41
+ setRole: 'owner',
42
+ setEgressHosts: 'owner',
43
+ createAccessToken: 'anyone',
44
+ },
45
+ TaAccessServer: {
46
+ getAccess: 'anyone',
47
+ signOut: 'anyone',
48
+ bindUrl: 'admin',
49
+ allow: 'admin',
50
+ dismiss: 'admin',
51
+ disallow: 'admin',
52
+ },
53
+ };
54
+ /** What an administrator did or looked at of others: kept in the audit. */
55
+ GatewayServiceUtil.AUDITED = new Set([
56
+ 'startTenant',
57
+ 'stopTenant',
58
+ 'restartTenant',
59
+ 'getTenantLogs',
60
+ 'getAgentActivity',
61
+ 'createSignInLink',
62
+ 'setTenantLimits',
63
+ 'grantMinutes',
64
+ 'setSuspended',
65
+ 'setDefaultLimits',
66
+ 'setRole',
67
+ 'setEgressHosts',
68
+ 'allow',
69
+ 'dismiss',
70
+ 'disallow',
71
+ ]);
72
+ /** By name, own keys only: a method such as `toString` is no rule. */
73
+ const BY_SERVICE = new Map(Object.entries(GatewayServiceUtil.RULES).map(([service, rules]) => [service, new Map(Object.entries(rules))]));
74
+ function need(service, name) {
75
+ var _a;
76
+ return (_a = BY_SERVICE.get(service)) === null || _a === void 0 ? void 0 : _a.get(name);
77
+ }
78
+ GatewayServiceUtil.need = need;
79
+ function allowed(role, need) {
80
+ return need === 'anyone' || GatewayPolicyUtil.rank(role) >= GatewayPolicyUtil.rank(need);
81
+ }
82
+ GatewayServiceUtil.allowed = allowed;
83
+ /** As many lines as asked, within bounds. */
84
+ function lines(value) {
85
+ const count = Math.floor(Number(value !== null && value !== void 0 ? value : GatewayServiceUtil.DEFAULT_LOG_LINES));
86
+ return Number.isFinite(count) && count > 0 ? Math.min(count, GatewayServiceUtil.MAX_LOG_LINES) : GatewayServiceUtil.DEFAULT_LOG_LINES;
87
+ }
88
+ GatewayServiceUtil.lines = lines;
89
+ /** Days of a trend, 1 to 31. */
90
+ function days(value) {
91
+ const count = Math.floor(Number(value !== null && value !== void 0 ? value : 7));
92
+ return Number.isFinite(count) ? Math.min(31, Math.max(1, count)) : 7;
93
+ }
94
+ GatewayServiceUtil.days = days;
95
+ /** The services the gateway answers itself, not the Ta of the tenant. */
96
+ GatewayServiceUtil.SERVICES = Object.keys(GatewayServiceUtil.RULES);
97
+ function owns(method) {
98
+ return typeof method === 'string' && GatewayServiceUtil.SERVICES.includes(method.split('/')[0]);
99
+ }
100
+ GatewayServiceUtil.owns = owns;
101
+ /** Whether the text of a message may be a call of {@link SERVICES}: those that are not are not parsed. */
102
+ function mayOwn(text) {
103
+ return GatewayServiceUtil.SERVICES.some(service => text.includes(`"${service}/`));
104
+ }
105
+ GatewayServiceUtil.mayOwn = mayOwn;
106
+ /** The calls that send the agents a message, which the limit of messages a minute counts. */
107
+ GatewayServiceUtil.PROMPTS = ['TaServer/prompt', 'TaServer/steer', 'TaServer/followUp'];
108
+ function mayPrompt(text) {
109
+ return GatewayServiceUtil.PROMPTS.some(method => text.includes(`"${method}"`));
110
+ }
111
+ GatewayServiceUtil.mayPrompt = mayPrompt;
112
+ /** The error of a JSON-RPC answer, as ta serve sends an ApplicationError: the client reads its code and hint. */
113
+ function error(id, message, code, hint) {
114
+ return JSON.stringify({ jsonrpc: '2.0', id, error: { code: TA_RPC_ERROR_CODE, message, data: { kind: 'application', data: { code, hint } } } });
115
+ }
116
+ GatewayServiceUtil.error = error;
117
+ function result(id, result) {
118
+ return JSON.stringify({ jsonrpc: '2.0', id, result: result !== null && result !== void 0 ? result : null });
119
+ }
120
+ GatewayServiceUtil.result = result;
121
+ function invalid(message, hint) {
122
+ return new GatewayCallError(message, TaErrorCode.INVALID_ARGUMENT, hint);
123
+ }
124
+ function forbidden(message, hint) {
125
+ return new GatewayCallError(message, TaErrorCode.FORBIDDEN, hint);
126
+ }
127
+ GatewayServiceUtil.forbidden = forbidden;
128
+ function choice(value, own, providers) {
129
+ var _a;
130
+ const given = (value !== null && value !== void 0 ? value : {});
131
+ if (typeof given.provider === 'string') {
132
+ if (!providers.includes(given.provider)) {
133
+ throw invalid(`The gateway has no provider ${given.provider} for you.`, 'Pick one of the options of getGateway.');
134
+ }
135
+ return { provider: given.provider };
136
+ }
137
+ if (given.type === 'ta') {
138
+ if (!own) {
139
+ throw invalid('This gateway runs your Ta in its own sandboxes only.', 'Pick one of the options of getGateway.');
140
+ }
141
+ let url;
142
+ try {
143
+ url = TaSandboxUtil.url(String((_a = given.url) !== null && _a !== void 0 ? _a : ''));
144
+ }
145
+ catch (error) {
146
+ throw invalid(error.message, 'Write the address its Ta service is reached at, such as https://ta.example.com.');
147
+ }
148
+ if (typeof given.token !== 'string' || !given.token.trim()) {
149
+ throw invalid('A Ta service of your own is reached with its access token.', 'Copy it from ~/.ta/agent/serve.json there, or the link ta serve printed.');
150
+ }
151
+ return { type: 'ta', url, token: given.token.trim(), name: typeof given.name === 'string' && given.name.trim() ? given.name.trim() : undefined };
152
+ }
153
+ throw invalid('No environment was named.', 'Pass { provider } or { type: "ta", url, token }.');
154
+ }
155
+ GatewayServiceUtil.choice = choice;
156
+ /** What the audit says of the arguments of a call: its numbers, flags and roles, never more. */
157
+ function detail(method, params) {
158
+ const [, second] = params;
159
+ switch (method) {
160
+ case 'setTenantLimits':
161
+ case 'setDefaultLimits':
162
+ return JSON.stringify(method === 'setDefaultLimits' ? params[0] : second);
163
+ case 'grantMinutes':
164
+ case 'getTenantLogs':
165
+ return String(second !== null && second !== void 0 ? second : '');
166
+ case 'setSuspended':
167
+ return second ? 'suspended' : 'let go';
168
+ case 'setRole':
169
+ return String(second);
170
+ case 'setEgressHosts':
171
+ return Array.isArray(params[0]) ? params[0].join(', ') || 'any public host' : undefined;
172
+ default:
173
+ return undefined;
174
+ }
175
+ }
176
+ GatewayServiceUtil.detail = detail;
177
+ })(GatewayServiceUtil || (GatewayServiceUtil = {}));
178
+ //# sourceMappingURL=gateway-service-util.js.map
@@ -1,5 +1,6 @@
1
1
  import type { SignInFlow } from '@celljs/ta-host/lib/node/sign-in/sign-in-flow';
2
- import { type TaAccessInfo, type TaAgentActivity, type TaEnvironmentChoice, TaErrorCode, type TaGatewayConsole, type TaGatewayInfo, type TaGatewayLimits, type TaGatewayPolicy, type TaGatewayRole, type TaGatewayTenant, type TaUsageTrend } from '@celljs/ta-protocol';
2
+ import { type TaAccessInfo, type TaAgentActivity, type TaGatewayConsole, type TaGatewayInfo, type TaGatewayLimits, type TaGatewayPolicy, type TaGatewayRole, type TaGatewayTenant, type TaUsageTrend } from '@celljs/ta-protocol';
3
+ import { type EgressProxy } from './egress-proxy.js';
3
4
  import type { Environments } from './environments.js';
4
5
  import type { GatewayAudit } from './gateway-audit.js';
5
6
  import { type GatewayPolicy } from './gateway-policy.js';
@@ -17,11 +18,6 @@ export interface GatewayCaller {
17
18
  /** An owner or an admin. */
18
19
  admin: boolean;
19
20
  }
20
- export declare class GatewayCallError extends Error {
21
- readonly code: TaErrorCode;
22
- readonly hint: string;
23
- constructor(message: string, code: TaErrorCode, hint: string);
24
- }
25
21
  /** What the console says of the gateway itself. */
26
22
  export interface GatewayMeta {
27
23
  links: SignInLinks;
@@ -44,40 +40,7 @@ export interface GatewayParts {
44
40
  };
45
41
  meta: GatewayMeta;
46
42
  models?: ModelProxy;
47
- }
48
- type Need = TaGatewayRole | 'anyone';
49
- export declare namespace GatewayServiceUtil {
50
- const DEFAULT_LOG_LINES = 200;
51
- const MAX_LOG_LINES = 2000;
52
- /**
53
- * Who may call each method: `anyone` signed in (about their own Ta, their own sign-ins), `admin` (owners too),
54
- * `owner`. A method not here is no method. What an admin may do to another account is checked again by its role
55
- * (GatewayService.manage).
56
- */
57
- const RULES: Record<string, Record<string, Need>>;
58
- /** What an administrator did or looked at of others: kept in the audit. */
59
- const AUDITED: Set<string>;
60
- function need(service: string, name: string): Need | undefined;
61
- function allowed(role: TaGatewayRole, need: Need): boolean;
62
- /** As many lines as asked, within bounds. */
63
- function lines(value: unknown): number;
64
- /** Days of a trend, 1 to 31. */
65
- function days(value: unknown): number;
66
- /** The services the gateway answers itself, not the Ta of the tenant. */
67
- const SERVICES: string[];
68
- function owns(method: unknown): method is string;
69
- /** Whether the text of a message may be a call of {@link SERVICES}: those that are not are not parsed. */
70
- function mayOwn(text: string): boolean;
71
- /** The calls that send the agents a message, which the limit of messages a minute counts. */
72
- const PROMPTS: string[];
73
- function mayPrompt(text: string): boolean;
74
- /** The error of a JSON-RPC answer, as ta serve sends an ApplicationError: the client reads its code and hint. */
75
- function error(id: unknown, message: string, code: TaErrorCode, hint: string): string;
76
- function result(id: unknown, result: unknown): string;
77
- function forbidden(message: string, hint: string): GatewayCallError;
78
- function choice(value: unknown, own: boolean, providers: string[]): TaEnvironmentChoice | undefined;
79
- /** What the audit says of the arguments of a call: its numbers, flags and roles, never more. */
80
- function detail(method: string, params: unknown[]): string | undefined;
43
+ egress?: EgressProxy;
81
44
  }
82
45
  /**
83
46
  * The calls the gateway answers on the WebSocket of a browser: TaGatewayServer, and TaAccessServer, whose
@@ -95,6 +58,7 @@ export declare class GatewayService {
95
58
  protected readonly hooks: GatewayParts['hooks'];
96
59
  protected readonly meta: GatewayMeta;
97
60
  protected readonly models?: ModelProxy;
61
+ protected readonly egress?: EgressProxy;
98
62
  constructor(parts: GatewayParts);
99
63
  call(caller: GatewayCaller, method: string, params: unknown[]): Promise<unknown>;
100
64
  protected handle(caller: GatewayCaller, service: string, name: string, params: unknown[]): Promise<unknown>;
@@ -106,6 +70,7 @@ export declare class GatewayService {
106
70
  /** The tenants with what their sandboxes take and their agents do, read together: a slow one holds the console a second, not a second each. */
107
71
  protected console(caller: GatewayCaller): Promise<TaGatewayConsole>;
108
72
  protected policyView(): TaGatewayPolicy;
73
+ protected setEgressHosts(value: unknown): TaGatewayPolicy;
109
74
  protected tenant(id: unknown): Tenant;
110
75
  /** A tenant the caller may change: an owner any; an admin a member's only, not their own, nor another admin's or an owner's. */
111
76
  protected manage(caller: GatewayCaller, id: unknown): Tenant;
@@ -138,4 +103,3 @@ export declare class GatewayService {
138
103
  */
139
104
  protected signInLink(account: unknown, name: unknown): string;
140
105
  }
141
- export {};