@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
@@ -10,7 +10,7 @@ class PolicyError extends Error {
10
10
  exports.PolicyError = PolicyError;
11
11
  var GatewayPolicyUtil;
12
12
  (function (GatewayPolicyUtil) {
13
- const NUMBERS = ['freeMinutes', 'promptsPerMinute', 'connections'];
13
+ const NUMBERS = ['freeMinutes', 'monthlyTokens', 'promptsPerMinute', 'connections'];
14
14
  const RANK = { member: 0, admin: 1, owner: 2 };
15
15
  function rank(role) {
16
16
  return RANK[role];
@@ -87,6 +87,7 @@ var GatewayPolicyUtil;
87
87
  const own_ = pick('own');
88
88
  return {
89
89
  freeMinutes: number('freeMinutes'),
90
+ monthlyTokens: number('monthlyTokens'),
90
91
  promptsPerMinute: number('promptsPerMinute'),
91
92
  connections: number('connections'),
92
93
  providers: Array.isArray(providers) ? providers : undefined,
@@ -125,13 +126,21 @@ class GatewayPolicy {
125
126
  this.stored = { ...this.stored, defaults: limits };
126
127
  (0, tenant_store_1.writePrivate)(this.file, this.stored);
127
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
+ }
128
137
  setRole(account, role) {
129
138
  var _a;
130
139
  const admins = ((_a = this.stored.admins) !== null && _a !== void 0 ? _a : []).filter(other => other !== account);
131
140
  this.stored = { ...this.stored, admins: role === 'admin' ? [...admins, account] : admins };
132
141
  (0, tenant_store_1.writePrivate)(this.file, this.stored);
133
142
  }
134
- view(idleMinutes) {
143
+ view(idleMinutes, egress = { enabled: false, networks: [] }) {
135
144
  var _a;
136
145
  return {
137
146
  defaults: this.defaults,
@@ -140,6 +149,7 @@ class GatewayPolicy {
140
149
  ...((_a = this.stored.admins) !== null && _a !== void 0 ? _a : []).filter(account => this.role(account) === 'admin').map(account => ({ account, role: 'admin' })),
141
150
  ],
142
151
  idleMinutes,
152
+ egress: { enabled: egress.enabled, hosts: this.egressHosts, networks: egress.networks },
143
153
  };
144
154
  }
145
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';
@@ -11,16 +11,29 @@ export declare class GatewayQuotas {
11
11
  protected readonly tenants: TenantStore;
12
12
  protected readonly usage: GatewayUsage;
13
13
  protected readonly ownAllowed: () => boolean;
14
+ /** Whether the gateway gives its sandboxes models: then it counts their tokens, and holds them to the limit. */
15
+ protected readonly metered: () => boolean;
14
16
  protected lastTick: number;
15
17
  /** By tenant: the times of its messages within the last minute. */
16
18
  protected readonly prompts: Map<string, number[]>;
17
- constructor(policy: GatewayPolicy, tenants: TenantStore, usage: GatewayUsage, ownAllowed: () => boolean);
19
+ /** When the sandboxes go out through the gateway: the latest connections of a tenant it refused. */
20
+ egressOf?: (tenant: Tenant) => TaEgressRefusal[] | undefined;
21
+ constructor(policy: GatewayPolicy, tenants: TenantStore, usage: GatewayUsage, ownAllowed: () => boolean,
22
+ /** Whether the gateway gives its sandboxes models: then it counts their tokens, and holds them to the limit. */
23
+ metered?: () => boolean);
18
24
  role(tenant: Tenant): TaGatewayRole;
19
25
  limits(tenant: Tenant): ResolvedLimits;
20
26
  /** That of this month: a meter of a month before starts again. */
21
27
  meter(tenant: Tenant, now?: number): TenantMeter;
22
28
  blocked(tenant: Tenant, now?: number): TaQuotaBlock | undefined;
23
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;
33
+ /** Why a call of a model of the gateway is refused now; owners have no limit. */
34
+ refuseModels(tenant: Tenant, now?: number): string | undefined;
35
+ /** What a call of a model took, to the month of the tenant. */
36
+ addTokens(tenantId: string, tokens: number, cost: number, now?: number): void;
24
37
  /** What a message of the tenant to its agents needs: false when it sent as many this minute as it may. */
25
38
  takePrompt(tenant: Tenant, now?: number): boolean;
26
39
  /** When the next message may go: the oldest of the minute leaves it. */
@@ -11,11 +11,14 @@ const MAX_TICK_MS = 2 * MINUTE;
11
11
  * gateway as it sees them run, and the messages a minute they send their agents. Owners have no limits.
12
12
  */
13
13
  class GatewayQuotas {
14
- constructor(policy, tenants, usage, ownAllowed) {
14
+ constructor(policy, tenants, usage, ownAllowed,
15
+ /** Whether the gateway gives its sandboxes models: then it counts their tokens, and holds them to the limit. */
16
+ metered = () => false) {
15
17
  this.policy = policy;
16
18
  this.tenants = tenants;
17
19
  this.usage = usage;
18
20
  this.ownAllowed = ownAllowed;
21
+ this.metered = metered;
19
22
  this.lastTick = Date.now();
20
23
  /** By tenant: the times of its messages within the last minute. */
21
24
  this.prompts = new Map();
@@ -44,20 +47,65 @@ class GatewayQuotas {
44
47
  return freeMinutes !== undefined && meter.runMs >= (freeMinutes + meter.bonusMinutes) * MINUTE ? 'minutes' : undefined;
45
48
  }
46
49
  state(tenant, now = Date.now()) {
50
+ var _a, _b;
47
51
  const { key, next } = gateway_usage_1.GatewayUsageUtil.month(now);
48
52
  const meter = this.meter(tenant, now);
49
53
  const limits = this.limits(tenant);
50
- const month = this.usage.month(tenant.id, now);
54
+ const metered = this.metered();
55
+ const month = metered ? { tokens: (_a = meter.tokens) !== null && _a !== void 0 ? _a : 0, cost: (_b = meter.cost) !== null && _b !== void 0 ? _b : 0 } : this.usage.month(tenant.id, now);
51
56
  return {
52
57
  month: key,
53
58
  resetsAt: next,
54
59
  minutes: { used: Math.floor(meter.runMs / MINUTE), limit: limits.freeMinutes, bonus: meter.bonusMinutes },
55
- tokens: { used: month.tokens, cost: month.cost },
60
+ tokens: { used: month.tokens, cost: month.cost, limit: metered ? limits.monthlyTokens : undefined, metered },
56
61
  promptsPerMinute: limits.promptsPerMinute,
57
62
  connections: limits.connections,
58
63
  blocked: this.blocked(tenant, now),
64
+ ...this.egressState(tenant, meter),
59
65
  };
60
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
+ }
83
+ /** Why a call of a model of the gateway is refused now; owners have no limit. */
84
+ refuseModels(tenant, now = Date.now()) {
85
+ var _a;
86
+ if (this.role(tenant) === 'owner') {
87
+ return undefined;
88
+ }
89
+ if (tenant.suspended) {
90
+ return 'Your account is suspended by an administrator of the gateway.';
91
+ }
92
+ const limit = this.limits(tenant).monthlyTokens;
93
+ const used = (_a = this.meter(tenant, now).tokens) !== null && _a !== void 0 ? _a : 0;
94
+ // The words pi does not retry on: the month is over, not a moment of load.
95
+ return limit !== undefined && used >= limit
96
+ ? `Monthly usage limit reached: ${used} of ${limit} tokens this month; it starts again next month, or ask an administrator.`
97
+ : undefined;
98
+ }
99
+ /** What a call of a model took, to the month of the tenant. */
100
+ addTokens(tenantId, tokens, cost, now = Date.now()) {
101
+ var _a, _b;
102
+ const tenant = this.tenants.get(tenantId);
103
+ if (!tenant) {
104
+ return;
105
+ }
106
+ const meter = this.meter(tenant, now);
107
+ this.tenants.update(tenantId, { meter: { ...meter, tokens: ((_a = meter.tokens) !== null && _a !== void 0 ? _a : 0) + tokens, cost: ((_b = meter.cost) !== null && _b !== void 0 ? _b : 0) + cost } });
108
+ }
61
109
  /** What a message of the tenant to its agents needs: false when it sent as many this minute as it may. */
62
110
  takePrompt(tenant, now = Date.now()) {
63
111
  var _a;
@@ -1,15 +1,19 @@
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';
11
14
  import { GatewaySocket } from './gateway-socket';
12
15
  import { GatewayUsage } from './gateway-usage';
16
+ import { type GatewayModelsConfig, ModelProxy } from './model-proxy';
13
17
  import { type SandboxProviderFactory, SandboxProviders } from './sandbox-provider';
14
18
  import { SignInLinks } from './sign-in-links';
15
19
  import { TenantStore } from './tenant-store';
@@ -18,6 +22,11 @@ export declare const SANDBOX_TYPES: Record<string, SandboxProviderFactory>;
18
22
  export interface GatewayServerOptions {
19
23
  /** Its configuration and data: sandboxes.json, access.json, tenants/, links.json. */
20
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;
21
30
  host?: string;
22
31
  port?: number;
23
32
  /** The web client: dist/public of @celljs/ta. */
@@ -28,6 +37,18 @@ export interface GatewayServerOptions {
28
37
  version?: string;
29
38
  }
30
39
  export declare namespace GatewayServerUtil {
40
+ /**
41
+ * Where a sandbox reaches the gateway, by the type of its provider: a container the host (host.docker.internal,
42
+ * mapped on Linux too), a process of this machine 127.0.0.1, another the public address.
43
+ */
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>;
50
+ /** Where another Ta reaches the exec server of its account's sandbox. */
51
+ const EXEC_PATH = "/api/exec";
31
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. */
32
53
  function blockedReason(block: TaQuotaBlock | undefined): string | undefined;
33
54
  /** A file of `root` for a path of the page, never outside it; the page for what is not a file. */
@@ -59,15 +80,29 @@ export declare class GatewayServer {
59
80
  readonly links: SignInLinks;
60
81
  protected readonly service: GatewayService;
61
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
+ }>;
62
88
  readonly policy: GatewayPolicy;
63
89
  readonly quotas: GatewayQuotas;
64
90
  readonly usage: GatewayUsage;
65
91
  readonly audit: GatewayAudit;
92
+ readonly models: ModelProxy;
93
+ readonly egress: EgressProxy;
94
+ /** The port it listens on, once it does. */
95
+ protected port?: number;
66
96
  protected server?: Server;
67
97
  protected ticker?: ReturnType<typeof setInterval>;
68
98
  static create(options: GatewayServerOptions): Promise<GatewayServer>;
69
- protected constructor(options: GatewayServerOptions, providers: Awaited<ReturnType<typeof SandboxProviders.create>>, config: ReturnType<typeof SandboxProviders.read>);
99
+ protected constructor(options: GatewayServerOptions, providers: Awaited<ReturnType<typeof SandboxProviders.create>>, config: ReturnType<typeof SandboxProviders.read>, models?: GatewayModelsConfig);
70
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;
71
106
  /** The minutes of the sandboxes that ran since the last time; those out of them, or suspended, stop. */
72
107
  tick(now?: number): Promise<void>;
73
108
  listen(): Promise<string>;
@@ -82,6 +117,11 @@ export declare class GatewayServer {
82
117
  /** Who a token signs in, while its account is let in. */
83
118
  caller(token: string): GatewayCaller | undefined;
84
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;
85
125
  /** A link of `ta gateway link`: lets its account in, and signs this browser in as it. */
86
126
  protected useLink(request: IncomingMessage, response: ServerResponse, secret: string): void;
87
127
  protected signedIn(response: ServerResponse, token: string, account: SignInAccount, origin: string): void;
@@ -91,5 +131,7 @@ export declare class GatewayServer {
91
131
  protected files(request: IncomingMessage, response: ServerResponse): Promise<void>;
92
132
  protected page(request: IncomingMessage, response: ServerResponse, path: string): void;
93
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;
94
136
  }
95
137
  //# sourceMappingURL=gateway-server.d.ts.map
@@ -14,14 +14,18 @@ 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");
20
+ const gateway_exec_1 = require("./gateway-exec");
19
21
  const gateway_policy_1 = require("./gateway-policy");
20
22
  const gateway_quotas_1 = require("./gateway-quotas");
21
23
  const gateway_service_1 = require("./gateway-service");
22
24
  const gateway_socket_1 = require("./gateway-socket");
23
25
  const gateway_usage_1 = require("./gateway-usage");
26
+ const kubernetes_sandbox_1 = require("./kubernetes-sandbox");
24
27
  const local_sandbox_1 = require("./local-sandbox");
28
+ const model_proxy_1 = require("./model-proxy");
25
29
  const sandbox_provider_1 = require("./sandbox-provider");
26
30
  const sign_in_links_1 = require("./sign-in-links");
27
31
  const ta_sandbox_1 = require("./ta-sandbox");
@@ -47,12 +51,46 @@ const TYPES = {
47
51
  /** The built-in types of providers of sandboxes. */
48
52
  exports.SANDBOX_TYPES = {
49
53
  docker: (id, config) => new docker_sandbox_1.DockerSandbox(id, config),
54
+ kubernetes: (id, config) => new kubernetes_sandbox_1.KubernetesSandbox(id, config),
50
55
  command: (id, config) => new command_sandbox_1.CommandSandbox(id, config),
51
56
  local: (id, config, context) => new local_sandbox_1.LocalSandbox(id, config, context),
52
57
  ta: (id, config) => new ta_sandbox_1.TaSandbox(id, config),
53
58
  };
54
59
  var GatewayServerUtil;
55
60
  (function (GatewayServerUtil) {
61
+ /**
62
+ * Where a sandbox reaches the gateway, by the type of its provider: a container the host (host.docker.internal,
63
+ * mapped on Linux too), a process of this machine 127.0.0.1, another the public address.
64
+ */
65
+ function reach(type, port, publicUrl) {
66
+ if (type === 'docker') {
67
+ return `http://host.docker.internal:${port}`;
68
+ }
69
+ if (type === 'local' || !publicUrl) {
70
+ return `http://127.0.0.1:${port}`;
71
+ }
72
+ return publicUrl;
73
+ }
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;
92
+ /** Where another Ta reaches the exec server of its account's sandbox. */
93
+ GatewayServerUtil.EXEC_PATH = '/api/exec';
56
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. */
57
95
  function blockedReason(block) {
58
96
  switch (block) {
@@ -110,16 +148,20 @@ var GatewayServerUtil;
110
148
  */
111
149
  class GatewayServer {
112
150
  static async create(options) {
151
+ var _a, _b;
152
+ const models = model_proxy_1.ModelProxyUtil.read((_a = options.config) !== null && _a !== void 0 ? _a : options.dir);
113
153
  (0, node_fs_1.mkdirSync)(options.dir, { recursive: true, mode: 0o700 });
114
- const config = sandbox_provider_1.SandboxProviders.read(options.dir);
115
- 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 };
116
156
  const providers = await sandbox_provider_1.SandboxProviders.create(config, context, exports.SANDBOX_TYPES);
117
- return new GatewayServer(options, providers, config);
157
+ return new GatewayServer(options, providers, config, models);
118
158
  }
119
- constructor(options, providers, config) {
159
+ constructor(options, providers, config, models = {}) {
120
160
  var _a, _b;
121
161
  this.options = options;
122
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();
123
165
  const env = (_a = options.env) !== null && _a !== void 0 ? _a : process.env;
124
166
  const owners = access_store_1.AccessUtil.parseList(env.TA_GATEWAY_ADMINS);
125
167
  this.policy = new gateway_policy_1.GatewayPolicy(options.dir, owners);
@@ -134,8 +176,37 @@ class GatewayServer {
134
176
  });
135
177
  this.usage = new gateway_usage_1.GatewayUsage(options.dir);
136
178
  this.audit = new gateway_audit_1.GatewayAudit(options.dir);
137
- this.quotas = new gateway_quotas_1.GatewayQuotas(this.policy, this.tenants, this.usage, () => this.environments.settings.own);
179
+ this.quotas = new gateway_quotas_1.GatewayQuotas(this.policy, this.tenants, this.usage, () => this.environments.settings.own, () => this.models.enabled);
138
180
  this.environments.guard = tenant => GatewayServerUtil.blockedReason(this.quotas.blocked(tenant));
181
+ this.models = new model_proxy_1.ModelProxy(models, {
182
+ tenantOfKey: key => this.tenants.list().find(tenant => tenant.modelKey && model_proxy_1.ModelProxyUtil.sameKey(key, tenant.modelKey)),
183
+ refuse: id => {
184
+ const tenant = this.tenants.get(id);
185
+ return tenant ? this.quotas.refuseModels(tenant) : 'No such account.';
186
+ },
187
+ record: (id, usage, cost) => this.quotas.addTokens(id, model_proxy_1.ModelProxyUtil.total(usage), cost),
188
+ }, env);
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) => {
192
+ var _a, _b, _c;
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}`));
207
+ }
208
+ return given;
209
+ };
139
210
  this.service = new gateway_service_1.GatewayService({
140
211
  flow: this.flow,
141
212
  tenants: this.tenants,
@@ -145,14 +216,43 @@ class GatewayServer {
145
216
  usage: this.usage,
146
217
  audit: this.audit,
147
218
  hooks: { cutOff: () => this.cutOff(), reset: id => this.reset(id) },
219
+ models: this.models,
220
+ egress: this.egress,
148
221
  meta: { links: this.links, startedAt: Date.now(), version: options.version, publicUrl: sandbox_provider_1.SandboxProviders.publicBase(env) },
149
222
  });
150
223
  }
151
224
  isAdmin(account) {
152
225
  return this.policy.role(account) !== 'member';
153
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
+ }
154
251
  /** The minutes of the sandboxes that ran since the last time; those out of them, or suspended, stop. */
155
252
  async tick(now = Date.now()) {
253
+ for (const [id, bytes] of this.egress.flush()) {
254
+ this.quotas.addEgress(id, bytes, now);
255
+ }
156
256
  for (const tenant of this.quotas.tick(this.environments.runningIds(), now)) {
157
257
  console.log(`ta gateway: ${tenant.account} used its free minutes of the month: its sandbox stops`);
158
258
  await this.environments.stop(tenant.id).catch(() => undefined);
@@ -163,6 +263,11 @@ class GatewayServer {
163
263
  var _a, _b;
164
264
  const server = (0, node_http_1.createServer)((request, response) => void this.handle(request, response));
165
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
+ }));
166
271
  this.server = server;
167
272
  this.ticker = setInterval(() => void this.tick().catch(error => console.warn(`ta gateway: counting minutes failed: ${error.message}`)), TICK_MS);
168
273
  (_b = (_a = this.ticker).unref) === null || _b === void 0 ? void 0 : _b.call(_a);
@@ -171,6 +276,7 @@ class GatewayServer {
171
276
  server.once('error', reject);
172
277
  server.listen((_a = this.options.port) !== null && _a !== void 0 ? _a : 4100, (_b = this.options.host) !== null && _b !== void 0 ? _b : '127.0.0.1', () => {
173
278
  const { address, port } = server.address();
279
+ this.port = port;
174
280
  resolve(`http://${address.includes(':') ? `[${address}]` : address}:${port}`);
175
281
  });
176
282
  });
@@ -181,6 +287,9 @@ class GatewayServer {
181
287
  for (const socket of this.sockets) {
182
288
  socket.close(1001, 'The gateway is stopping.');
183
289
  }
290
+ for (const exec of this.execs.keys()) {
291
+ exec.close(1001, 'The gateway is stopping.');
292
+ }
184
293
  await this.environments.dispose();
185
294
  await new Promise(resolve => (this.server ? this.server.close(() => resolve()) : resolve()));
186
295
  }
@@ -191,6 +300,11 @@ class GatewayServer {
191
300
  socket.close(1008, 'Signed out');
192
301
  }
193
302
  }
303
+ for (const [exec, { token }] of this.execs) {
304
+ if (!this.caller(token)) {
305
+ exec.close(1008, 'Signed out');
306
+ }
307
+ }
194
308
  }
195
309
  /**
196
310
  * The connections of the tenant of now close, and connect again to its environment: in a moment, so that
@@ -198,10 +312,14 @@ class GatewayServer {
198
312
  */
199
313
  reset(tenantId) {
200
314
  const sockets = [...this.sockets].filter(socket => socket.tenantId === tenantId);
315
+ const execs = [...this.execs].filter(([, exec]) => exec.tenantId === tenantId).map(([proxy]) => proxy);
201
316
  setTimeout(() => {
202
317
  for (const socket of sockets) {
203
318
  socket.close(1012, 'The environment changed.');
204
319
  }
320
+ for (const exec of execs) {
321
+ exec.close(1012, 'The environment changed.');
322
+ }
205
323
  }, 100);
206
324
  }
207
325
  /** Who a token signs in, while its account is let in. */
@@ -215,10 +333,16 @@ class GatewayServer {
215
333
  return { token, account: signIn.account, tenant, role, admin: role !== 'member' };
216
334
  }
217
335
  async handle(request, response) {
218
- var _a;
336
+ var _a, _b;
219
337
  const path = ((_a = request.url) !== null && _a !== void 0 ? _a : '/').split('?')[0];
220
338
  try {
221
- if (path.startsWith(sign_in_links_1.SIGN_IN_LINK_PATH)) {
339
+ if (/^[a-z][a-z0-9+.-]*:\/\//i.test((_b = request.url) !== null && _b !== void 0 ? _b : '')) {
340
+ await this.egress.request(request, response);
341
+ }
342
+ else if (path === ta_protocol_1.TA_WELL_KNOWN_PATH || path === '/healthz' || path === '/readyz') {
343
+ this.describe(path, request, response);
344
+ }
345
+ else if (path.startsWith(sign_in_links_1.SIGN_IN_LINK_PATH)) {
222
346
  this.useLink(request, response, path.slice(sign_in_links_1.SIGN_IN_LINK_PATH.length));
223
347
  }
224
348
  else if (sign_in_pages_1.SignInPages.matches(request)) {
@@ -227,6 +351,9 @@ class GatewayServer {
227
351
  onSignedIn: (res, token, account, origin) => this.signedIn(res, token, account, origin),
228
352
  });
229
353
  }
354
+ else if (path === model_proxy_1.ModelProxyUtil.PATH || path.startsWith(`${model_proxy_1.ModelProxyUtil.PATH}/`)) {
355
+ await this.models.handle(request, response);
356
+ }
230
357
  else if (path.startsWith(`${ta_protocol_1.TA_FILES_PATH}/`)) {
231
358
  await this.files(request, response);
232
359
  }
@@ -247,6 +374,30 @@ class GatewayServer {
247
374
  }
248
375
  }
249
376
  }
377
+ /**
378
+ * What it is part of (TA_WELL_KNOWN_PATH: its address, the relay of the deployment), and whether it runs and can
379
+ * keep what it holds (the probes of a platform). For anyone: nothing of it is secret.
380
+ */
381
+ describe(path, request, response) {
382
+ var _a;
383
+ const version = this.options.version;
384
+ let body = { ok: true, ...(version ? { version } : {}) };
385
+ let status = 200;
386
+ if (path === ta_protocol_1.TA_WELL_KNOWN_PATH) {
387
+ body = ta_protocol_1.TaDeploymentUtil.describe((_a = this.options.env) !== null && _a !== void 0 ? _a : process.env, { gateway: this.origin(request) }, version);
388
+ }
389
+ else if (path === '/readyz') {
390
+ try {
391
+ (0, node_fs_1.accessSync)(this.options.dir, node_fs_1.constants.W_OK);
392
+ }
393
+ catch (error) {
394
+ status = 503;
395
+ body = { ok: false, error: `${this.options.dir} cannot be written: ${error.message}` };
396
+ }
397
+ }
398
+ response.writeHead(status, ta_protocol_1.TaDeploymentUtil.HEADERS);
399
+ response.end(JSON.stringify(body));
400
+ }
250
401
  /** A link of `ta gateway link`: lets its account in, and signs this browser in as it. */
251
402
  useLink(request, response, secret) {
252
403
  response.setHeader('Cache-Control', 'no-store');
@@ -340,7 +491,7 @@ class GatewayServer {
340
491
  upgrade(request, socket, head) {
341
492
  var _a, _b;
342
493
  const url = new URL((_a = request.url) !== null && _a !== void 0 ? _a : '/', 'http://gateway');
343
- if (url.pathname !== ta_protocol_1.TA_WEBSOCKET_PATH) {
494
+ if (url.pathname !== ta_protocol_1.TA_WEBSOCKET_PATH && url.pathname !== GatewayServerUtil.EXEC_PATH) {
344
495
  socket.destroy();
345
496
  return;
346
497
  }
@@ -362,11 +513,29 @@ class GatewayServer {
362
513
  return;
363
514
  }
364
515
  this.tenants.update(caller.tenant.id, { lastActiveAt: Date.now() });
516
+ if (url.pathname === GatewayServerUtil.EXEC_PATH) {
517
+ // Another Ta works in this account's sandbox: it counts as a page connected, and keeps the sandbox running.
518
+ const blocked = GatewayServerUtil.blockedReason(this.quotas.blocked(caller.tenant));
519
+ if (blocked) {
520
+ websocket_connection_1.WebSocketConnection.refuse(socket, 403, blocked);
521
+ return;
522
+ }
523
+ const exec = websocket_connection_1.WebSocketConnection.open(socket, checked.key, head, { maxPayload: 64 * 1024 * 1024, heartbeat: 30000 });
524
+ this.openExec(exec, caller);
525
+ return;
526
+ }
365
527
  const connection = websocket_connection_1.WebSocketConnection.open(socket, checked.key, head, { maxPayload: 32 * 1024 * 1024, heartbeat: 30000, deflate: checked.deflate });
366
528
  const gatewaySocket = new gateway_socket_1.GatewaySocket(connection, caller, this.environments, this.service, this.quotas);
367
529
  this.sockets.add(gatewaySocket);
368
530
  connection.onClose(() => this.sockets.delete(gatewaySocket));
369
531
  }
532
+ /** Another Ta works in the sandbox of the caller's account: cut off as the pages of its sign-in are. */
533
+ openExec(exec, caller) {
534
+ const proxy = new gateway_exec_1.GatewayExecProxy(exec, this.environments.ensure(caller.tenant), this.environments.connect(caller.tenant.id));
535
+ this.execs.set(proxy, { token: caller.token, tenantId: caller.tenant.id });
536
+ exec.onClose(() => this.execs.delete(proxy));
537
+ return proxy;
538
+ }
370
539
  }
371
540
  exports.GatewayServer = GatewayServer;
372
541
  //# 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