@celljs/ta-gateway 4.16.0 → 4.18.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 +13 -6
  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 +35 -1
  17. package/esm/node/gateway-server.js +150 -16
  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 +13 -6
  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 +35 -1
  48. package/lib/node/gateway-server.js +148 -14
  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
@@ -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,
@@ -75,7 +82,7 @@ var GatewayCli;
75
82
  return;
76
83
  }
77
84
  const url = await gateway.listen();
78
- const ways = gateway.flow.providers.map(provider => provider.name);
85
+ const ways = [...gateway.flow.providers, ...gateway.flow.polled].map(provider => provider.name);
79
86
  console.log(`ta gateway: ${url} (${dir})`);
80
87
  console.log(`ta gateway: sandboxes of ${gateway.environments.providers.map(provider => `${provider.id} (${provider.type})`).join(', ') || 'none'}${ways.length ? `; sign-in with ${ways.join(', ')}` : '; no provider of accounts: sign people in with ta gateway link <account>'}`);
81
88
  const stop = () => void gateway.close().then(() => process.exit(0));
@@ -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;
@@ -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';
6
8
  import { Environments } from './environments';
7
9
  import { GatewayAudit } from './gateway-audit';
10
+ import { GatewayExecProxy } from './gateway-exec';
8
11
  import { GatewayPolicy } from './gateway-policy';
9
12
  import { GatewayQuotas } from './gateway-quotas';
10
13
  import { type GatewayCaller, GatewayService } from './gateway-service';
@@ -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,14 +117,24 @@ 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;
99
128
  /** As the pages of signing in read it: behind a proxy of TLS, its X-Forwarded-Proto makes the cookie Secure. */
100
129
  protected origin(request: IncomingMessage): string;
101
- /** `/api/files` of the Ta of the tenant whose cookie came along. */
130
+ /**
131
+ * `/api/files` of the Ta of the tenant whose cookie came along, or whose token: the app on a phone and Ta Desktop, of
132
+ * another origin, read them with it (TaFiles), and are answered as any origin is, the token being what lets them in.
133
+ */
102
134
  protected files(request: IncomingMessage, response: ServerResponse): Promise<void>;
103
135
  protected page(request: IncomingMessage, response: ServerResponse, path: string): void;
104
136
  protected upgrade(request: IncomingMessage, socket: Duplex, head: Buffer): void;
137
+ /** Another Ta works in the sandbox of the caller's account: cut off as the pages of its sign-in are. */
138
+ protected openExec(exec: WebSocketConnection, caller: GatewayCaller): GatewayExecProxy;
105
139
  }
106
140
  //# sourceMappingURL=gateway-server.d.ts.map
@@ -14,6 +14,7 @@ const sign_in_provider_1 = require("@celljs/ta-host/lib/node/sign-in/sign-in-pro
14
14
  const ta_protocol_1 = require("@celljs/ta-protocol");
15
15
  const command_sandbox_1 = require("./command-sandbox");
16
16
  const docker_sandbox_1 = require("./docker-sandbox");
17
+ const egress_proxy_1 = require("./egress-proxy");
17
18
  const environments_1 = require("./environments");
18
19
  const gateway_audit_1 = require("./gateway-audit");
19
20
  const gateway_exec_1 = require("./gateway-exec");
@@ -22,6 +23,7 @@ const gateway_quotas_1 = require("./gateway-quotas");
22
23
  const gateway_service_1 = require("./gateway-service");
23
24
  const gateway_socket_1 = require("./gateway-socket");
24
25
  const gateway_usage_1 = require("./gateway-usage");
26
+ const kubernetes_sandbox_1 = require("./kubernetes-sandbox");
25
27
  const local_sandbox_1 = require("./local-sandbox");
26
28
  const model_proxy_1 = require("./model-proxy");
27
29
  const sandbox_provider_1 = require("./sandbox-provider");
@@ -49,6 +51,7 @@ const TYPES = {
49
51
  /** The built-in types of providers of sandboxes. */
50
52
  exports.SANDBOX_TYPES = {
51
53
  docker: (id, config) => new docker_sandbox_1.DockerSandbox(id, config),
54
+ kubernetes: (id, config) => new kubernetes_sandbox_1.KubernetesSandbox(id, config),
52
55
  command: (id, config) => new command_sandbox_1.CommandSandbox(id, config),
53
56
  local: (id, config, context) => new local_sandbox_1.LocalSandbox(id, config, context),
54
57
  ta: (id, config) => new ta_sandbox_1.TaSandbox(id, config),
@@ -69,6 +72,23 @@ var GatewayServerUtil;
69
72
  return publicUrl;
70
73
  }
71
74
  GatewayServerUtil.reach = reach;
75
+ /**
76
+ * What every sandbox is told of the deployment (docs/design/ta-deploy.md 3): its relay, so that a Ta in the cloud
77
+ * pairs, shares and opens rooms on the relay of its people, and its name.
78
+ */
79
+ function deploymentEnv(env) {
80
+ var _a;
81
+ const given = {};
82
+ const relay = ta_protocol_1.TaDeploymentUtil.url(env.TA_RELAY_URL);
83
+ if (relay) {
84
+ given.TA_RELAY_URL = relay;
85
+ }
86
+ if ((_a = env.TA_DEPLOYMENT_NAME) === null || _a === void 0 ? void 0 : _a.trim()) {
87
+ given.TA_DEPLOYMENT_NAME = env.TA_DEPLOYMENT_NAME.trim();
88
+ }
89
+ return given;
90
+ }
91
+ GatewayServerUtil.deploymentEnv = deploymentEnv;
72
92
  /** Where another Ta reaches the exec server of its account's sandbox. */
73
93
  GatewayServerUtil.EXEC_PATH = '/api/exec';
74
94
  /** 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. */
@@ -128,10 +148,11 @@ var GatewayServerUtil;
128
148
  */
129
149
  class GatewayServer {
130
150
  static async create(options) {
131
- const models = model_proxy_1.ModelProxyUtil.read(options.dir);
151
+ var _a, _b;
152
+ const models = model_proxy_1.ModelProxyUtil.read((_a = options.config) !== null && _a !== void 0 ? _a : options.dir);
132
153
  (0, node_fs_1.mkdirSync)(options.dir, { recursive: true, mode: 0o700 });
133
- const config = sandbox_provider_1.SandboxProviders.read(options.dir);
134
- const context = { dir: options.dir, taCommand: options.taCommand };
154
+ const config = sandbox_provider_1.SandboxProviders.read((_b = options.config) !== null && _b !== void 0 ? _b : options.dir);
155
+ const context = { dir: options.dir, config: options.config, taCommand: options.taCommand };
135
156
  const providers = await sandbox_provider_1.SandboxProviders.create(config, context, exports.SANDBOX_TYPES);
136
157
  return new GatewayServer(options, providers, config, models);
137
158
  }
@@ -139,11 +160,13 @@ class GatewayServer {
139
160
  var _a, _b;
140
161
  this.options = options;
141
162
  this.sockets = new Set();
163
+ /** The connections of other Ta to the exec servers of sandboxes (`/api/exec`), by the token they signed in with. */
164
+ this.execs = new Map();
142
165
  const env = (_a = options.env) !== null && _a !== void 0 ? _a : process.env;
143
166
  const owners = access_store_1.AccessUtil.parseList(env.TA_GATEWAY_ADMINS);
144
167
  this.policy = new gateway_policy_1.GatewayPolicy(options.dir, owners);
145
168
  const allowed = [...access_store_1.AccessUtil.parseList(env.TA_ALLOWED_USERS), ...owners];
146
- this.flow = new sign_in_flow_1.SignInFlow(sign_in_provider_1.SignInProviders.fromEnv(env), new access_store_1.AccessStore((0, node_path_1.join)(options.dir, 'access.json'), allowed), sign_in_provider_1.SignInProviders.publicUrl(env));
169
+ this.flow = new sign_in_flow_1.SignInFlow(sign_in_provider_1.SignInProviders.fromEnv(env), new access_store_1.AccessStore((0, node_path_1.join)(options.dir, 'access.json'), allowed), sign_in_provider_1.SignInProviders.publicUrl(env), sign_in_provider_1.SignInProviders.polled(env));
147
170
  this.tenants = new tenant_store_1.TenantStore(options.dir);
148
171
  this.links = new sign_in_links_1.SignInLinks(options.dir);
149
172
  this.environments = new environments_1.Environments(providers, this.tenants, {
@@ -163,13 +186,26 @@ class GatewayServer {
163
186
  },
164
187
  record: (id, usage, cost) => this.quotas.addTokens(id, model_proxy_1.ModelProxyUtil.total(usage), cost),
165
188
  }, env);
166
- this.environments.envOf = (tenant, provider) => {
189
+ this.egress = new egress_proxy_1.EgressProxy(egress_proxy_1.EgressProxyUtil.settings(config.egress), { authorize: (user, password) => this.authorizeEgress(user, password) });
190
+ this.quotas.egressOf = tenant => (this.egress.enabled ? this.egress.refused(tenant.id) : undefined);
191
+ this.environments.envOf = (tenant, provider, fresh) => {
167
192
  var _a, _b, _c;
168
- if (!this.models.enabled) {
169
- return undefined;
193
+ const deployment = GatewayServerUtil.deploymentEnv(env);
194
+ if (!this.models.enabled && !this.egress.enabled) {
195
+ return Object.keys(deployment).length ? deployment : undefined;
196
+ }
197
+ 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, sandbox_provider_1.SandboxProviders.publicBase(env));
198
+ const url = base.replace(/\/+$/, '');
199
+ const given = { ...deployment };
200
+ if (this.models.enabled) {
201
+ Object.assign(given, { TA_MODEL_PROXY_URL: url, TA_MODEL_PROXY_KEY: this.tenants.modelKey(tenant.id) });
202
+ }
203
+ if (this.egress.enabled) {
204
+ // A sandbox made anew is of a new epoch: what the one before it went out with stops working.
205
+ const key = this.tenants.egressKey(tenant.id, fresh);
206
+ Object.assign(given, egress_proxy_1.EgressProxyUtil.env(url, tenant.id, `${key.epoch}.${key.secret}`));
170
207
  }
171
- 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, sandbox_provider_1.SandboxProviders.publicBase(env));
172
- return { TA_MODEL_PROXY_URL: url.replace(/\/+$/, ''), TA_MODEL_PROXY_KEY: this.tenants.modelKey(tenant.id) };
208
+ return given;
173
209
  };
174
210
  this.service = new gateway_service_1.GatewayService({
175
211
  flow: this.flow,
@@ -181,14 +217,42 @@ class GatewayServer {
181
217
  audit: this.audit,
182
218
  hooks: { cutOff: () => this.cutOff(), reset: id => this.reset(id) },
183
219
  models: this.models,
220
+ egress: this.egress,
184
221
  meta: { links: this.links, startedAt: Date.now(), version: options.version, publicUrl: sandbox_provider_1.SandboxProviders.publicBase(env) },
185
222
  });
186
223
  }
187
224
  isAdmin(account) {
188
225
  return this.policy.role(account) !== 'member';
189
226
  }
227
+ /**
228
+ * Who goes out through the proxy: the tenant of the user, with the secret of its sandbox's epoch (that of a
229
+ * sandbox made again since is refused); members to the hosts of the policy, owners anywhere public.
230
+ */
231
+ authorizeEgress(user, password) {
232
+ const tenant = this.tenants.get(user);
233
+ const dot = password.indexOf('.');
234
+ const epoch = Number(password.slice(0, dot));
235
+ const known = tenant === null || tenant === void 0 ? void 0 : tenant.egress;
236
+ if (!tenant || !known || dot < 1 || !egress_proxy_1.EgressProxyUtil.sameSecret(password.slice(dot + 1), epoch === known.epoch ? known.secret : '')) {
237
+ const stale = known !== undefined && Number.isInteger(epoch) && epoch < known.epoch;
238
+ return {
239
+ status: 407,
240
+ message: stale
241
+ ? `ta gateway: a sandbox of epoch ${known.epoch} took over from this one (epoch ${epoch}); it goes out no more.`
242
+ : 'ta gateway: these credentials are of no sandbox of the gateway.',
243
+ };
244
+ }
245
+ if (this.quotas.blocked(tenant) === 'suspended') {
246
+ return { status: 403, message: 'ta gateway: your account is suspended by an administrator of the gateway.' };
247
+ }
248
+ const hosts = this.policy.egressHosts;
249
+ return { tenantId: tenant.id, hosts: this.quotas.role(tenant) === 'owner' || hosts.length === 0 ? undefined : hosts };
250
+ }
190
251
  /** The minutes of the sandboxes that ran since the last time; those out of them, or suspended, stop. */
191
252
  async tick(now = Date.now()) {
253
+ for (const [id, bytes] of this.egress.flush()) {
254
+ this.quotas.addEgress(id, bytes, now);
255
+ }
192
256
  for (const tenant of this.quotas.tick(this.environments.runningIds(), now)) {
193
257
  console.log(`ta gateway: ${tenant.account} used its free minutes of the month: its sandbox stops`);
194
258
  await this.environments.stop(tenant.id).catch(() => undefined);
@@ -199,6 +263,11 @@ class GatewayServer {
199
263
  var _a, _b;
200
264
  const server = (0, node_http_1.createServer)((request, response) => void this.handle(request, response));
201
265
  server.on('upgrade', (request, socket, head) => this.upgrade(request, socket, head));
266
+ // The way out of the sandboxes: CONNECT for https, absolute URLs for http (handle).
267
+ server.on('connect', (request, socket, head) => this.egress.connect(request, socket, head).catch(error => {
268
+ console.warn(`ta gateway: CONNECT ${request.url} failed: ${error.message}`);
269
+ socket.destroy();
270
+ }));
202
271
  this.server = server;
203
272
  this.ticker = setInterval(() => void this.tick().catch(error => console.warn(`ta gateway: counting minutes failed: ${error.message}`)), TICK_MS);
204
273
  (_b = (_a = this.ticker).unref) === null || _b === void 0 ? void 0 : _b.call(_a);
@@ -214,10 +283,14 @@ class GatewayServer {
214
283
  }
215
284
  async close() {
216
285
  clearInterval(this.ticker);
286
+ this.flow.stopPolling();
217
287
  await this.tick().catch(() => undefined);
218
288
  for (const socket of this.sockets) {
219
289
  socket.close(1001, 'The gateway is stopping.');
220
290
  }
291
+ for (const exec of this.execs.keys()) {
292
+ exec.close(1001, 'The gateway is stopping.');
293
+ }
221
294
  await this.environments.dispose();
222
295
  await new Promise(resolve => (this.server ? this.server.close(() => resolve()) : resolve()));
223
296
  }
@@ -228,6 +301,11 @@ class GatewayServer {
228
301
  socket.close(1008, 'Signed out');
229
302
  }
230
303
  }
304
+ for (const [exec, { token }] of this.execs) {
305
+ if (!this.caller(token)) {
306
+ exec.close(1008, 'Signed out');
307
+ }
308
+ }
231
309
  }
232
310
  /**
233
311
  * The connections of the tenant of now close, and connect again to its environment: in a moment, so that
@@ -235,10 +313,14 @@ class GatewayServer {
235
313
  */
236
314
  reset(tenantId) {
237
315
  const sockets = [...this.sockets].filter(socket => socket.tenantId === tenantId);
316
+ const execs = [...this.execs].filter(([, exec]) => exec.tenantId === tenantId).map(([proxy]) => proxy);
238
317
  setTimeout(() => {
239
318
  for (const socket of sockets) {
240
319
  socket.close(1012, 'The environment changed.');
241
320
  }
321
+ for (const exec of execs) {
322
+ exec.close(1012, 'The environment changed.');
323
+ }
242
324
  }, 100);
243
325
  }
244
326
  /** Who a token signs in, while its account is let in. */
@@ -252,10 +334,16 @@ class GatewayServer {
252
334
  return { token, account: signIn.account, tenant, role, admin: role !== 'member' };
253
335
  }
254
336
  async handle(request, response) {
255
- var _a;
337
+ var _a, _b;
256
338
  const path = ((_a = request.url) !== null && _a !== void 0 ? _a : '/').split('?')[0];
257
339
  try {
258
- if (path.startsWith(sign_in_links_1.SIGN_IN_LINK_PATH)) {
340
+ if (/^[a-z][a-z0-9+.-]*:\/\//i.test((_b = request.url) !== null && _b !== void 0 ? _b : '')) {
341
+ await this.egress.request(request, response);
342
+ }
343
+ else if (path === ta_protocol_1.TA_WELL_KNOWN_PATH || path === '/healthz' || path === '/readyz') {
344
+ this.describe(path, request, response);
345
+ }
346
+ else if (path.startsWith(sign_in_links_1.SIGN_IN_LINK_PATH)) {
259
347
  this.useLink(request, response, path.slice(sign_in_links_1.SIGN_IN_LINK_PATH.length));
260
348
  }
261
349
  else if (sign_in_pages_1.SignInPages.matches(request)) {
@@ -287,6 +375,30 @@ class GatewayServer {
287
375
  }
288
376
  }
289
377
  }
378
+ /**
379
+ * What it is part of (TA_WELL_KNOWN_PATH: its address, the relay of the deployment), and whether it runs and can
380
+ * keep what it holds (the probes of a platform). For anyone: nothing of it is secret.
381
+ */
382
+ describe(path, request, response) {
383
+ var _a;
384
+ const version = this.options.version;
385
+ let body = { ok: true, ...(version ? { version } : {}) };
386
+ let status = 200;
387
+ if (path === ta_protocol_1.TA_WELL_KNOWN_PATH) {
388
+ body = ta_protocol_1.TaDeploymentUtil.describe((_a = this.options.env) !== null && _a !== void 0 ? _a : process.env, { gateway: this.origin(request) }, version);
389
+ }
390
+ else if (path === '/readyz') {
391
+ try {
392
+ (0, node_fs_1.accessSync)(this.options.dir, node_fs_1.constants.W_OK);
393
+ }
394
+ catch (error) {
395
+ status = 503;
396
+ body = { ok: false, error: `${this.options.dir} cannot be written: ${error.message}` };
397
+ }
398
+ }
399
+ response.writeHead(status, ta_protocol_1.TaDeploymentUtil.HEADERS);
400
+ response.end(JSON.stringify(body));
401
+ }
290
402
  /** A link of `ta gateway link`: lets its account in, and signs this browser in as it. */
291
403
  useLink(request, response, secret) {
292
404
  response.setHeader('Cache-Control', 'no-store');
@@ -316,15 +428,30 @@ class GatewayServer {
316
428
  origin(request) {
317
429
  return sign_in_flow_1.SignInUtil.origin(request, this.flow.publicUrl);
318
430
  }
319
- /** `/api/files` of the Ta of the tenant whose cookie came along. */
431
+ /**
432
+ * `/api/files` of the Ta of the tenant whose cookie came along, or whose token: the app on a phone and Ta Desktop, of
433
+ * another origin, read them with it (TaFiles), and are answered as any origin is, the token being what lets them in.
434
+ */
320
435
  async files(request, response) {
321
436
  var _a, _b;
437
+ const header = request.headers.authorization;
438
+ const bearer = (header === null || header === void 0 ? void 0 : header.startsWith('Bearer ')) ? header.slice('Bearer '.length) : undefined;
439
+ if (bearer !== undefined || request.method === 'OPTIONS') {
440
+ response.setHeader('Access-Control-Allow-Origin', '*');
441
+ response.setHeader('Access-Control-Allow-Headers', 'Authorization, Range');
442
+ response.setHeader('Access-Control-Expose-Headers', 'Content-Type, Content-Length, Content-Range');
443
+ response.setHeader('Access-Control-Max-Age', '600');
444
+ }
445
+ if (request.method === 'OPTIONS') {
446
+ sign_in_pages_1.SignInPageUtil.end(response, 204);
447
+ return;
448
+ }
322
449
  if (request.method !== 'GET' && request.method !== 'HEAD') {
323
450
  response.setHeader('Allow', 'GET, HEAD');
324
451
  sign_in_pages_1.SignInPageUtil.end(response, 405);
325
452
  return;
326
453
  }
327
- const caller = this.caller((_a = sign_in_pages_1.SignInPageUtil.cookie(request.headers.cookie, FILES_COOKIE)) !== null && _a !== void 0 ? _a : '');
454
+ const caller = this.caller((_a = bearer !== null && bearer !== void 0 ? bearer : sign_in_pages_1.SignInPageUtil.cookie(request.headers.cookie, FILES_COOKIE)) !== null && _a !== void 0 ? _a : '');
328
455
  if (!caller) {
329
456
  sign_in_pages_1.SignInPageUtil.end(response, 404);
330
457
  return;
@@ -410,7 +537,7 @@ class GatewayServer {
410
537
  return;
411
538
  }
412
539
  const exec = websocket_connection_1.WebSocketConnection.open(socket, checked.key, head, { maxPayload: 64 * 1024 * 1024, heartbeat: 30000 });
413
- new gateway_exec_1.GatewayExecProxy(exec, this.environments.ensure(caller.tenant), this.environments.connect(caller.tenant.id));
540
+ this.openExec(exec, caller);
414
541
  return;
415
542
  }
416
543
  const connection = websocket_connection_1.WebSocketConnection.open(socket, checked.key, head, { maxPayload: 32 * 1024 * 1024, heartbeat: 30000, deflate: checked.deflate });
@@ -418,6 +545,13 @@ class GatewayServer {
418
545
  this.sockets.add(gatewaySocket);
419
546
  connection.onClose(() => this.sockets.delete(gatewaySocket));
420
547
  }
548
+ /** Another Ta works in the sandbox of the caller's account: cut off as the pages of its sign-in are. */
549
+ openExec(exec, caller) {
550
+ const proxy = new gateway_exec_1.GatewayExecProxy(exec, this.environments.ensure(caller.tenant), this.environments.connect(caller.tenant.id));
551
+ this.execs.set(proxy, { token: caller.token, tenantId: caller.tenant.id });
552
+ exec.onClose(() => this.execs.delete(proxy));
553
+ return proxy;
554
+ }
421
555
  }
422
556
  exports.GatewayServer = GatewayServer;
423
557
  //# sourceMappingURL=gateway-server.js.map
@@ -0,0 +1,42 @@
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 {};
42
+ //# sourceMappingURL=gateway-service-util.d.ts.map