@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
@@ -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.js';
3
3
  import { type GatewayUsage } from './gateway-usage.js';
4
4
  import type { Tenant, TenantMeter, TenantStore } from './tenant-store.js';
@@ -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. */
@@ -8,11 +8,14 @@ const MAX_TICK_MS = 2 * MINUTE;
8
8
  * gateway as it sees them run, and the messages a minute they send their agents. Owners have no limits.
9
9
  */
10
10
  export class GatewayQuotas {
11
- constructor(policy, tenants, usage, ownAllowed) {
11
+ constructor(policy, tenants, usage, ownAllowed,
12
+ /** Whether the gateway gives its sandboxes models: then it counts their tokens, and holds them to the limit. */
13
+ metered = () => false) {
12
14
  this.policy = policy;
13
15
  this.tenants = tenants;
14
16
  this.usage = usage;
15
17
  this.ownAllowed = ownAllowed;
18
+ this.metered = metered;
16
19
  this.lastTick = Date.now();
17
20
  /** By tenant: the times of its messages within the last minute. */
18
21
  this.prompts = new Map();
@@ -41,20 +44,65 @@ export class GatewayQuotas {
41
44
  return freeMinutes !== undefined && meter.runMs >= (freeMinutes + meter.bonusMinutes) * MINUTE ? 'minutes' : undefined;
42
45
  }
43
46
  state(tenant, now = Date.now()) {
47
+ var _a, _b;
44
48
  const { key, next } = GatewayUsageUtil.month(now);
45
49
  const meter = this.meter(tenant, now);
46
50
  const limits = this.limits(tenant);
47
- const month = this.usage.month(tenant.id, now);
51
+ const metered = this.metered();
52
+ 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);
48
53
  return {
49
54
  month: key,
50
55
  resetsAt: next,
51
56
  minutes: { used: Math.floor(meter.runMs / MINUTE), limit: limits.freeMinutes, bonus: meter.bonusMinutes },
52
- tokens: { used: month.tokens, cost: month.cost },
57
+ tokens: { used: month.tokens, cost: month.cost, limit: metered ? limits.monthlyTokens : undefined, metered },
53
58
  promptsPerMinute: limits.promptsPerMinute,
54
59
  connections: limits.connections,
55
60
  blocked: this.blocked(tenant, now),
61
+ ...this.egressState(tenant, meter),
56
62
  };
57
63
  }
64
+ egressState(tenant, meter) {
65
+ var _a;
66
+ var _b;
67
+ const refused = (_a = this.egressOf) === null || _a === void 0 ? void 0 : _a.call(this, tenant);
68
+ return refused ? { egress: { bytes: (_b = meter.egressBytes) !== null && _b !== void 0 ? _b : 0, refused } } : {};
69
+ }
70
+ /** What its sandbox moved through the proxy of the gateway, to the month of the tenant. */
71
+ addEgress(tenantId, bytes, now = Date.now()) {
72
+ var _a;
73
+ const tenant = this.tenants.get(tenantId);
74
+ if (!tenant || bytes <= 0) {
75
+ return;
76
+ }
77
+ const meter = this.meter(tenant, now);
78
+ this.tenants.update(tenantId, { meter: { ...meter, egressBytes: ((_a = meter.egressBytes) !== null && _a !== void 0 ? _a : 0) + bytes } });
79
+ }
80
+ /** Why a call of a model of the gateway is refused now; owners have no limit. */
81
+ refuseModels(tenant, now = Date.now()) {
82
+ var _a;
83
+ if (this.role(tenant) === 'owner') {
84
+ return undefined;
85
+ }
86
+ if (tenant.suspended) {
87
+ return 'Your account is suspended by an administrator of the gateway.';
88
+ }
89
+ const limit = this.limits(tenant).monthlyTokens;
90
+ const used = (_a = this.meter(tenant, now).tokens) !== null && _a !== void 0 ? _a : 0;
91
+ // The words pi does not retry on: the month is over, not a moment of load.
92
+ return limit !== undefined && used >= limit
93
+ ? `Monthly usage limit reached: ${used} of ${limit} tokens this month; it starts again next month, or ask an administrator.`
94
+ : undefined;
95
+ }
96
+ /** What a call of a model took, to the month of the tenant. */
97
+ addTokens(tenantId, tokens, cost, now = Date.now()) {
98
+ var _a, _b;
99
+ const tenant = this.tenants.get(tenantId);
100
+ if (!tenant) {
101
+ return;
102
+ }
103
+ const meter = this.meter(tenant, now);
104
+ 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 } });
105
+ }
58
106
  /** What a message of the tenant to its agents needs: false when it sent as many this minute as it may. */
59
107
  takePrompt(tenant, now = Date.now()) {
60
108
  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.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';
11
14
  import { GatewaySocket } from './gateway-socket.js';
12
15
  import { GatewayUsage } from './gateway-usage.js';
16
+ import { type GatewayModelsConfig, ModelProxy } from './model-proxy.js';
13
17
  import { type SandboxProviderFactory, SandboxProviders } from './sandbox-provider.js';
14
18
  import { SignInLinks } from './sign-in-links.js';
15
19
  import { TenantStore } from './tenant-store.js';
@@ -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,4 +131,6 @@ 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
  }
@@ -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,17 +8,21 @@ 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';
17
+ import { GatewayExecProxy } from './gateway-exec.js';
16
18
  import { GatewayPolicy } from './gateway-policy.js';
17
19
  import { GatewayQuotas } from './gateway-quotas.js';
18
20
  import { GatewayService } from './gateway-service.js';
19
21
  import { GatewaySocket } from './gateway-socket.js';
20
22
  import { GatewayUsage } from './gateway-usage.js';
23
+ import { KubernetesSandbox } from './kubernetes-sandbox.js';
21
24
  import { LocalSandbox } from './local-sandbox.js';
25
+ import { ModelProxy, ModelProxyUtil } from './model-proxy.js';
22
26
  import { SandboxProviders } from './sandbox-provider.js';
23
27
  import { SIGN_IN_LINK_PATH, SignInLinks } from './sign-in-links.js';
24
28
  import { TaSandbox } from './ta-sandbox.js';
@@ -44,12 +48,46 @@ const TYPES = {
44
48
  /** The built-in types of providers of sandboxes. */
45
49
  export const SANDBOX_TYPES = {
46
50
  docker: (id, config) => new DockerSandbox(id, config),
51
+ kubernetes: (id, config) => new KubernetesSandbox(id, config),
47
52
  command: (id, config) => new CommandSandbox(id, config),
48
53
  local: (id, config, context) => new LocalSandbox(id, config, context),
49
54
  ta: (id, config) => new TaSandbox(id, config),
50
55
  };
51
56
  export var GatewayServerUtil;
52
57
  (function (GatewayServerUtil) {
58
+ /**
59
+ * Where a sandbox reaches the gateway, by the type of its provider: a container the host (host.docker.internal,
60
+ * mapped on Linux too), a process of this machine 127.0.0.1, another the public address.
61
+ */
62
+ function reach(type, port, publicUrl) {
63
+ if (type === 'docker') {
64
+ return `http://host.docker.internal:${port}`;
65
+ }
66
+ if (type === 'local' || !publicUrl) {
67
+ return `http://127.0.0.1:${port}`;
68
+ }
69
+ return publicUrl;
70
+ }
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;
89
+ /** Where another Ta reaches the exec server of its account's sandbox. */
90
+ GatewayServerUtil.EXEC_PATH = '/api/exec';
53
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. */
54
92
  function blockedReason(block) {
55
93
  switch (block) {
@@ -107,16 +145,20 @@ export var GatewayServerUtil;
107
145
  */
108
146
  export class GatewayServer {
109
147
  static async create(options) {
148
+ var _a, _b;
149
+ const models = ModelProxyUtil.read((_a = options.config) !== null && _a !== void 0 ? _a : options.dir);
110
150
  mkdirSync(options.dir, { recursive: true, mode: 0o700 });
111
- const config = SandboxProviders.read(options.dir);
112
- 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 };
113
153
  const providers = await SandboxProviders.create(config, context, SANDBOX_TYPES);
114
- return new GatewayServer(options, providers, config);
154
+ return new GatewayServer(options, providers, config, models);
115
155
  }
116
- constructor(options, providers, config) {
156
+ constructor(options, providers, config, models = {}) {
117
157
  var _a, _b;
118
158
  this.options = options;
119
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();
120
162
  const env = (_a = options.env) !== null && _a !== void 0 ? _a : process.env;
121
163
  const owners = AccessUtil.parseList(env.TA_GATEWAY_ADMINS);
122
164
  this.policy = new GatewayPolicy(options.dir, owners);
@@ -131,8 +173,37 @@ export class GatewayServer {
131
173
  });
132
174
  this.usage = new GatewayUsage(options.dir);
133
175
  this.audit = new GatewayAudit(options.dir);
134
- this.quotas = new GatewayQuotas(this.policy, this.tenants, this.usage, () => this.environments.settings.own);
176
+ this.quotas = new GatewayQuotas(this.policy, this.tenants, this.usage, () => this.environments.settings.own, () => this.models.enabled);
135
177
  this.environments.guard = tenant => GatewayServerUtil.blockedReason(this.quotas.blocked(tenant));
178
+ this.models = new ModelProxy(models, {
179
+ tenantOfKey: key => this.tenants.list().find(tenant => tenant.modelKey && ModelProxyUtil.sameKey(key, tenant.modelKey)),
180
+ refuse: id => {
181
+ const tenant = this.tenants.get(id);
182
+ return tenant ? this.quotas.refuseModels(tenant) : 'No such account.';
183
+ },
184
+ record: (id, usage, cost) => this.quotas.addTokens(id, ModelProxyUtil.total(usage), cost),
185
+ }, env);
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) => {
189
+ var _a, _b, _c;
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) });
199
+ }
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;
206
+ };
136
207
  this.service = new GatewayService({
137
208
  flow: this.flow,
138
209
  tenants: this.tenants,
@@ -142,14 +213,43 @@ export class GatewayServer {
142
213
  usage: this.usage,
143
214
  audit: this.audit,
144
215
  hooks: { cutOff: () => this.cutOff(), reset: id => this.reset(id) },
216
+ models: this.models,
217
+ egress: this.egress,
145
218
  meta: { links: this.links, startedAt: Date.now(), version: options.version, publicUrl: SandboxProviders.publicBase(env) },
146
219
  });
147
220
  }
148
221
  isAdmin(account) {
149
222
  return this.policy.role(account) !== 'member';
150
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
+ }
151
248
  /** The minutes of the sandboxes that ran since the last time; those out of them, or suspended, stop. */
152
249
  async tick(now = Date.now()) {
250
+ for (const [id, bytes] of this.egress.flush()) {
251
+ this.quotas.addEgress(id, bytes, now);
252
+ }
153
253
  for (const tenant of this.quotas.tick(this.environments.runningIds(), now)) {
154
254
  console.log(`ta gateway: ${tenant.account} used its free minutes of the month: its sandbox stops`);
155
255
  await this.environments.stop(tenant.id).catch(() => undefined);
@@ -160,6 +260,11 @@ export class GatewayServer {
160
260
  var _a, _b;
161
261
  const server = createServer((request, response) => void this.handle(request, response));
162
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
+ }));
163
268
  this.server = server;
164
269
  this.ticker = setInterval(() => void this.tick().catch(error => console.warn(`ta gateway: counting minutes failed: ${error.message}`)), TICK_MS);
165
270
  (_b = (_a = this.ticker).unref) === null || _b === void 0 ? void 0 : _b.call(_a);
@@ -168,6 +273,7 @@ export class GatewayServer {
168
273
  server.once('error', reject);
169
274
  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', () => {
170
275
  const { address, port } = server.address();
276
+ this.port = port;
171
277
  resolve(`http://${address.includes(':') ? `[${address}]` : address}:${port}`);
172
278
  });
173
279
  });
@@ -178,6 +284,9 @@ export class GatewayServer {
178
284
  for (const socket of this.sockets) {
179
285
  socket.close(1001, 'The gateway is stopping.');
180
286
  }
287
+ for (const exec of this.execs.keys()) {
288
+ exec.close(1001, 'The gateway is stopping.');
289
+ }
181
290
  await this.environments.dispose();
182
291
  await new Promise(resolve => (this.server ? this.server.close(() => resolve()) : resolve()));
183
292
  }
@@ -188,6 +297,11 @@ export class GatewayServer {
188
297
  socket.close(1008, 'Signed out');
189
298
  }
190
299
  }
300
+ for (const [exec, { token }] of this.execs) {
301
+ if (!this.caller(token)) {
302
+ exec.close(1008, 'Signed out');
303
+ }
304
+ }
191
305
  }
192
306
  /**
193
307
  * The connections of the tenant of now close, and connect again to its environment: in a moment, so that
@@ -195,10 +309,14 @@ export class GatewayServer {
195
309
  */
196
310
  reset(tenantId) {
197
311
  const sockets = [...this.sockets].filter(socket => socket.tenantId === tenantId);
312
+ const execs = [...this.execs].filter(([, exec]) => exec.tenantId === tenantId).map(([proxy]) => proxy);
198
313
  setTimeout(() => {
199
314
  for (const socket of sockets) {
200
315
  socket.close(1012, 'The environment changed.');
201
316
  }
317
+ for (const exec of execs) {
318
+ exec.close(1012, 'The environment changed.');
319
+ }
202
320
  }, 100);
203
321
  }
204
322
  /** Who a token signs in, while its account is let in. */
@@ -212,10 +330,16 @@ export class GatewayServer {
212
330
  return { token, account: signIn.account, tenant, role, admin: role !== 'member' };
213
331
  }
214
332
  async handle(request, response) {
215
- var _a;
333
+ var _a, _b;
216
334
  const path = ((_a = request.url) !== null && _a !== void 0 ? _a : '/').split('?')[0];
217
335
  try {
218
- 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)) {
219
343
  this.useLink(request, response, path.slice(SIGN_IN_LINK_PATH.length));
220
344
  }
221
345
  else if (SignInPages.matches(request)) {
@@ -224,6 +348,9 @@ export class GatewayServer {
224
348
  onSignedIn: (res, token, account, origin) => this.signedIn(res, token, account, origin),
225
349
  });
226
350
  }
351
+ else if (path === ModelProxyUtil.PATH || path.startsWith(`${ModelProxyUtil.PATH}/`)) {
352
+ await this.models.handle(request, response);
353
+ }
227
354
  else if (path.startsWith(`${TA_FILES_PATH}/`)) {
228
355
  await this.files(request, response);
229
356
  }
@@ -244,6 +371,30 @@ export class GatewayServer {
244
371
  }
245
372
  }
246
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
+ }
247
398
  /** A link of `ta gateway link`: lets its account in, and signs this browser in as it. */
248
399
  useLink(request, response, secret) {
249
400
  response.setHeader('Cache-Control', 'no-store');
@@ -337,7 +488,7 @@ export class GatewayServer {
337
488
  upgrade(request, socket, head) {
338
489
  var _a, _b;
339
490
  const url = new URL((_a = request.url) !== null && _a !== void 0 ? _a : '/', 'http://gateway');
340
- if (url.pathname !== TA_WEBSOCKET_PATH) {
491
+ if (url.pathname !== TA_WEBSOCKET_PATH && url.pathname !== GatewayServerUtil.EXEC_PATH) {
341
492
  socket.destroy();
342
493
  return;
343
494
  }
@@ -359,10 +510,28 @@ export class GatewayServer {
359
510
  return;
360
511
  }
361
512
  this.tenants.update(caller.tenant.id, { lastActiveAt: Date.now() });
513
+ if (url.pathname === GatewayServerUtil.EXEC_PATH) {
514
+ // Another Ta works in this account's sandbox: it counts as a page connected, and keeps the sandbox running.
515
+ const blocked = GatewayServerUtil.blockedReason(this.quotas.blocked(caller.tenant));
516
+ if (blocked) {
517
+ WebSocketConnection.refuse(socket, 403, blocked);
518
+ return;
519
+ }
520
+ const exec = WebSocketConnection.open(socket, checked.key, head, { maxPayload: 64 * 1024 * 1024, heartbeat: 30000 });
521
+ this.openExec(exec, caller);
522
+ return;
523
+ }
362
524
  const connection = WebSocketConnection.open(socket, checked.key, head, { maxPayload: 32 * 1024 * 1024, heartbeat: 30000, deflate: checked.deflate });
363
525
  const gatewaySocket = new GatewaySocket(connection, caller, this.environments, this.service, this.quotas);
364
526
  this.sockets.add(gatewaySocket);
365
527
  connection.onClose(() => this.sockets.delete(gatewaySocket));
366
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
+ }
367
536
  }
368
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 {};