@celljs/ta-gateway 4.15.1 → 4.15.2

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 (57) hide show
  1. package/esm/node/command-sandbox.d.ts +5 -2
  2. package/esm/node/command-sandbox.js +17 -4
  3. package/esm/node/docker-engine.d.ts +45 -0
  4. package/esm/node/docker-engine.js +87 -11
  5. package/esm/node/docker-sandbox.d.ts +3 -1
  6. package/esm/node/docker-sandbox.js +6 -0
  7. package/esm/node/environments.d.ts +34 -2
  8. package/esm/node/environments.js +187 -11
  9. package/esm/node/gateway-audit.d.ts +12 -0
  10. package/esm/node/gateway-audit.js +47 -0
  11. package/esm/node/gateway-cli.d.ts +2 -0
  12. package/esm/node/gateway-cli.js +1 -0
  13. package/esm/node/gateway-policy.d.ts +46 -0
  14. package/esm/node/gateway-policy.js +151 -0
  15. package/esm/node/gateway-quotas.d.ts +32 -0
  16. package/esm/node/gateway-quotas.js +104 -0
  17. package/esm/node/gateway-server.d.ts +16 -1
  18. package/esm/node/gateway-server.js +58 -6
  19. package/esm/node/gateway-service.d.ts +91 -16
  20. package/esm/node/gateway-service.js +366 -45
  21. package/esm/node/gateway-socket.d.ts +7 -1
  22. package/esm/node/gateway-socket.js +40 -1
  23. package/esm/node/gateway-usage.d.ts +37 -0
  24. package/esm/node/gateway-usage.js +137 -0
  25. package/esm/node/local-sandbox.d.ts +12 -0
  26. package/esm/node/local-sandbox.js +36 -1
  27. package/esm/node/sandbox-provider.d.ts +10 -0
  28. package/esm/node/tenant-store.d.ts +12 -1
  29. package/lib/node/command-sandbox.d.ts +5 -2
  30. package/lib/node/command-sandbox.js +17 -4
  31. package/lib/node/docker-engine.d.ts +45 -0
  32. package/lib/node/docker-engine.js +87 -11
  33. package/lib/node/docker-sandbox.d.ts +3 -1
  34. package/lib/node/docker-sandbox.js +6 -0
  35. package/lib/node/environments.d.ts +34 -2
  36. package/lib/node/environments.js +186 -10
  37. package/lib/node/gateway-audit.d.ts +13 -0
  38. package/lib/node/gateway-audit.js +51 -0
  39. package/lib/node/gateway-cli.d.ts +2 -0
  40. package/lib/node/gateway-cli.js +1 -0
  41. package/lib/node/gateway-policy.d.ts +47 -0
  42. package/lib/node/gateway-policy.js +156 -0
  43. package/lib/node/gateway-quotas.d.ts +33 -0
  44. package/lib/node/gateway-quotas.js +108 -0
  45. package/lib/node/gateway-server.d.ts +16 -1
  46. package/lib/node/gateway-server.js +58 -6
  47. package/lib/node/gateway-service.d.ts +91 -16
  48. package/lib/node/gateway-service.js +365 -44
  49. package/lib/node/gateway-socket.d.ts +7 -1
  50. package/lib/node/gateway-socket.js +40 -1
  51. package/lib/node/gateway-usage.d.ts +38 -0
  52. package/lib/node/gateway-usage.js +141 -0
  53. package/lib/node/local-sandbox.d.ts +12 -0
  54. package/lib/node/local-sandbox.js +38 -2
  55. package/lib/node/sandbox-provider.d.ts +10 -0
  56. package/lib/node/tenant-store.d.ts +12 -1
  57. package/package.json +4 -4
@@ -2,9 +2,14 @@ import { type IncomingMessage, type Server, type ServerResponse } from 'node:htt
2
2
  import { type Duplex } from 'node:stream';
3
3
  import { SignInFlow } from '@celljs/ta-host/lib/node/sign-in/sign-in-flow';
4
4
  import { type SignInAccount } from '@celljs/ta-host/lib/node/sign-in/sign-in-provider';
5
+ import { type TaQuotaBlock } from '@celljs/ta-protocol';
5
6
  import { Environments } from './environments';
7
+ import { GatewayAudit } from './gateway-audit';
8
+ import { GatewayPolicy } from './gateway-policy';
9
+ import { GatewayQuotas } from './gateway-quotas';
6
10
  import { type GatewayCaller, GatewayService } from './gateway-service';
7
11
  import { GatewaySocket } from './gateway-socket';
12
+ import { GatewayUsage } from './gateway-usage';
8
13
  import { type SandboxProviderFactory, SandboxProviders } from './sandbox-provider';
9
14
  import { SignInLinks } from './sign-in-links';
10
15
  import { TenantStore } from './tenant-store';
@@ -19,8 +24,12 @@ export interface GatewayServerOptions {
19
24
  publicDir: string;
20
25
  taCommand: string[];
21
26
  env?: Record<string, string | undefined>;
27
+ /** Of Ta, for the console. */
28
+ version?: string;
22
29
  }
23
30
  export declare namespace GatewayServerUtil {
31
+ /** 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
+ function blockedReason(block: TaQuotaBlock | undefined): string | undefined;
24
33
  /** A file of `root` for a path of the page, never outside it; the page for what is not a file. */
25
34
  function file(root: string, urlPath: string): string;
26
35
  /**
@@ -50,11 +59,17 @@ export declare class GatewayServer {
50
59
  readonly links: SignInLinks;
51
60
  protected readonly service: GatewayService;
52
61
  protected readonly sockets: Set<GatewaySocket>;
53
- protected readonly admins: string[];
62
+ readonly policy: GatewayPolicy;
63
+ readonly quotas: GatewayQuotas;
64
+ readonly usage: GatewayUsage;
65
+ readonly audit: GatewayAudit;
54
66
  protected server?: Server;
67
+ protected ticker?: ReturnType<typeof setInterval>;
55
68
  static create(options: GatewayServerOptions): Promise<GatewayServer>;
56
69
  protected constructor(options: GatewayServerOptions, providers: Awaited<ReturnType<typeof SandboxProviders.create>>, config: ReturnType<typeof SandboxProviders.read>);
57
70
  isAdmin(account: string): boolean;
71
+ /** The minutes of the sandboxes that ran since the last time; those out of them, or suspended, stop. */
72
+ tick(now?: number): Promise<void>;
58
73
  listen(): Promise<string>;
59
74
  close(): Promise<void>;
60
75
  /** The browsers whose sign-in no longer works are cut off. */
@@ -15,13 +15,19 @@ 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
17
  const environments_1 = require("./environments");
18
+ const gateway_audit_1 = require("./gateway-audit");
19
+ const gateway_policy_1 = require("./gateway-policy");
20
+ const gateway_quotas_1 = require("./gateway-quotas");
18
21
  const gateway_service_1 = require("./gateway-service");
19
22
  const gateway_socket_1 = require("./gateway-socket");
23
+ const gateway_usage_1 = require("./gateway-usage");
20
24
  const local_sandbox_1 = require("./local-sandbox");
21
25
  const sandbox_provider_1 = require("./sandbox-provider");
22
26
  const sign_in_links_1 = require("./sign-in-links");
23
27
  const ta_sandbox_1 = require("./ta-sandbox");
24
28
  const tenant_store_1 = require("./tenant-store");
29
+ /** How often the minutes of running sandboxes are counted, and those out of them stopped. */
30
+ const TICK_MS = 30000;
25
31
  /** The browser's token for `/api/files`, which pages load by URL, without the token of the WebSocket. */
26
32
  const FILES_COOKIE = 'ta_gateway';
27
33
  const TYPES = {
@@ -47,6 +53,18 @@ exports.SANDBOX_TYPES = {
47
53
  };
48
54
  var GatewayServerUtil;
49
55
  (function (GatewayServerUtil) {
56
+ /** 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
+ function blockedReason(block) {
58
+ switch (block) {
59
+ case 'suspended':
60
+ return 'Your account is suspended by an administrator of the gateway.';
61
+ case 'minutes':
62
+ return 'Your free minutes of this month are used up.';
63
+ default:
64
+ return undefined;
65
+ }
66
+ }
67
+ GatewayServerUtil.blockedReason = blockedReason;
50
68
  /** A file of `root` for a path of the page, never outside it; the page for what is not a file. */
51
69
  function file(root, urlPath) {
52
70
  let path;
@@ -103,8 +121,9 @@ class GatewayServer {
103
121
  this.options = options;
104
122
  this.sockets = new Set();
105
123
  const env = (_a = options.env) !== null && _a !== void 0 ? _a : process.env;
106
- this.admins = access_store_1.AccessUtil.parseList(env.TA_GATEWAY_ADMINS);
107
- const allowed = [...access_store_1.AccessUtil.parseList(env.TA_ALLOWED_USERS), ...this.admins];
124
+ const owners = access_store_1.AccessUtil.parseList(env.TA_GATEWAY_ADMINS);
125
+ this.policy = new gateway_policy_1.GatewayPolicy(options.dir, owners);
126
+ const allowed = [...access_store_1.AccessUtil.parseList(env.TA_ALLOWED_USERS), ...owners];
108
127
  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));
109
128
  this.tenants = new tenant_store_1.TenantStore(options.dir);
110
129
  this.links = new sign_in_links_1.SignInLinks(options.dir);
@@ -113,15 +132,40 @@ class GatewayServer {
113
132
  own: config.ownEnvironments !== false,
114
133
  idleMinutes: (_b = config.idleMinutes) !== null && _b !== void 0 ? _b : 0,
115
134
  });
116
- this.service = new gateway_service_1.GatewayService(this.flow, this.tenants, this.environments, { cutOff: () => this.cutOff(), reset: id => this.reset(id) });
135
+ this.usage = new gateway_usage_1.GatewayUsage(options.dir);
136
+ 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);
138
+ this.environments.guard = tenant => GatewayServerUtil.blockedReason(this.quotas.blocked(tenant));
139
+ this.service = new gateway_service_1.GatewayService({
140
+ flow: this.flow,
141
+ tenants: this.tenants,
142
+ environments: this.environments,
143
+ policy: this.policy,
144
+ quotas: this.quotas,
145
+ usage: this.usage,
146
+ audit: this.audit,
147
+ hooks: { cutOff: () => this.cutOff(), reset: id => this.reset(id) },
148
+ meta: { links: this.links, startedAt: Date.now(), version: options.version, publicUrl: sandbox_provider_1.SandboxProviders.publicBase(env) },
149
+ });
117
150
  }
118
151
  isAdmin(account) {
119
- return this.admins.some(pattern => access_store_1.AccessUtil.matches(pattern, account));
152
+ return this.policy.role(account) !== 'member';
153
+ }
154
+ /** The minutes of the sandboxes that ran since the last time; those out of them, or suspended, stop. */
155
+ async tick(now = Date.now()) {
156
+ for (const tenant of this.quotas.tick(this.environments.runningIds(), now)) {
157
+ console.log(`ta gateway: ${tenant.account} used its free minutes of the month: its sandbox stops`);
158
+ await this.environments.stop(tenant.id).catch(() => undefined);
159
+ this.reset(tenant.id);
160
+ }
120
161
  }
121
162
  listen() {
163
+ var _a, _b;
122
164
  const server = (0, node_http_1.createServer)((request, response) => void this.handle(request, response));
123
165
  server.on('upgrade', (request, socket, head) => this.upgrade(request, socket, head));
124
166
  this.server = server;
167
+ this.ticker = setInterval(() => void this.tick().catch(error => console.warn(`ta gateway: counting minutes failed: ${error.message}`)), TICK_MS);
168
+ (_b = (_a = this.ticker).unref) === null || _b === void 0 ? void 0 : _b.call(_a);
125
169
  return new Promise((resolve, reject) => {
126
170
  var _a, _b;
127
171
  server.once('error', reject);
@@ -132,6 +176,8 @@ class GatewayServer {
132
176
  });
133
177
  }
134
178
  async close() {
179
+ clearInterval(this.ticker);
180
+ await this.tick().catch(() => undefined);
135
181
  for (const socket of this.sockets) {
136
182
  socket.close(1001, 'The gateway is stopping.');
137
183
  }
@@ -165,7 +211,8 @@ class GatewayServer {
165
211
  return undefined;
166
212
  }
167
213
  const tenant = this.tenants.ensure({ id: signIn.account, name: signIn.name, avatar: signIn.avatar });
168
- return { token, account: signIn.account, tenant, admin: this.isAdmin(signIn.account) };
214
+ const role = this.policy.role(signIn.account);
215
+ return { token, account: signIn.account, tenant, role, admin: role !== 'member' };
169
216
  }
170
217
  async handle(request, response) {
171
218
  var _a;
@@ -309,9 +356,14 @@ class GatewayServer {
309
356
  websocket_connection_1.WebSocketConnection.refuse(socket, 401, 'Not authorized.');
310
357
  return;
311
358
  }
359
+ const most = this.quotas.limits(caller.tenant).connections;
360
+ if (most !== undefined && this.environments.connections(caller.tenant.id) >= most) {
361
+ websocket_connection_1.WebSocketConnection.refuse(socket, 429, `At most ${most} pages of your account connect at once.`);
362
+ return;
363
+ }
312
364
  this.tenants.update(caller.tenant.id, { lastActiveAt: Date.now() });
313
365
  const connection = websocket_connection_1.WebSocketConnection.open(socket, checked.key, head, { maxPayload: 32 * 1024 * 1024, heartbeat: 30000, deflate: checked.deflate });
314
- const gatewaySocket = new gateway_socket_1.GatewaySocket(connection, caller, this.environments, this.service);
366
+ const gatewaySocket = new gateway_socket_1.GatewaySocket(connection, caller, this.environments, this.service, this.quotas);
315
367
  this.sockets.add(gatewaySocket);
316
368
  connection.onClose(() => this.sockets.delete(gatewaySocket));
317
369
  }
@@ -1,12 +1,19 @@
1
1
  import type { SignInFlow } from '@celljs/ta-host/lib/node/sign-in/sign-in-flow';
2
- import { type TaAccessInfo, type TaEnvironmentChoice, TaErrorCode, type TaGatewayInfo, type TaGatewayTenant } from '@celljs/ta-protocol';
2
+ import { type TaAccessInfo, type TaAgentActivity, type TaEnvironmentChoice, TaErrorCode, type TaGatewayConsole, type TaGatewayInfo, type TaGatewayLimits, type TaGatewayPolicy, type TaGatewayRole, type TaGatewayTenant, type TaUsageTrend } from '@celljs/ta-protocol';
3
3
  import type { Environments } from './environments';
4
+ import type { GatewayAudit } from './gateway-audit';
5
+ import { type GatewayPolicy } from './gateway-policy';
6
+ import type { GatewayQuotas } from './gateway-quotas';
7
+ import { type GatewayUsage } from './gateway-usage';
8
+ import type { SignInLinks } from './sign-in-links';
4
9
  import type { Tenant, TenantStore } from './tenant-store';
5
- /** Who calls: the browser signed in as `account`, with the token `token`. */
10
+ /** Who calls: the browser signed in as `account`, with the token `token`, and what that account is on the gateway. */
6
11
  export interface GatewayCaller {
7
12
  token: string;
8
13
  account: string;
9
14
  tenant: Tenant;
15
+ role: TaGatewayRole;
16
+ /** An owner or an admin. */
10
17
  admin: boolean;
11
18
  }
12
19
  export declare class GatewayCallError extends Error {
@@ -14,46 +21,114 @@ export declare class GatewayCallError extends Error {
14
21
  readonly hint: string;
15
22
  constructor(message: string, code: TaErrorCode, hint: string);
16
23
  }
24
+ /** What the console says of the gateway itself. */
25
+ export interface GatewayMeta {
26
+ links: SignInLinks;
27
+ startedAt: number;
28
+ version?: string;
29
+ publicUrl?: string;
30
+ }
31
+ /** The parts of the gateway its calls use. */
32
+ export interface GatewayParts {
33
+ flow: SignInFlow;
34
+ tenants: TenantStore;
35
+ environments: Environments;
36
+ policy: GatewayPolicy;
37
+ quotas: GatewayQuotas;
38
+ usage: GatewayUsage;
39
+ audit: GatewayAudit;
40
+ hooks: {
41
+ cutOff(): void;
42
+ reset(tenantId: string): void;
43
+ };
44
+ meta: GatewayMeta;
45
+ }
46
+ type Need = TaGatewayRole | 'anyone';
17
47
  export declare namespace GatewayServiceUtil {
48
+ const DEFAULT_LOG_LINES = 200;
49
+ const MAX_LOG_LINES = 2000;
50
+ /**
51
+ * Who may call each method: `anyone` signed in (about their own Ta, their own sign-ins), `admin` (owners too),
52
+ * `owner`. A method not here is no method. What an admin may do to another account is checked again by its role
53
+ * (GatewayService.manage).
54
+ */
55
+ const RULES: Record<string, Record<string, Need>>;
56
+ /** What an administrator did or looked at of others: kept in the audit. */
57
+ const AUDITED: Set<string>;
58
+ function need(service: string, name: string): Need | undefined;
59
+ function allowed(role: TaGatewayRole, need: Need): boolean;
60
+ /** As many lines as asked, within bounds. */
61
+ function lines(value: unknown): number;
62
+ /** Days of a trend, 1 to 31. */
63
+ function days(value: unknown): number;
18
64
  /** The services the gateway answers itself, not the Ta of the tenant. */
19
65
  const SERVICES: string[];
20
66
  function owns(method: unknown): method is string;
21
67
  /** Whether the text of a message may be a call of {@link SERVICES}: those that are not are not parsed. */
22
68
  function mayOwn(text: string): boolean;
69
+ /** The calls that send the agents a message, which the limit of messages a minute counts. */
70
+ const PROMPTS: string[];
71
+ function mayPrompt(text: string): boolean;
23
72
  /** The error of a JSON-RPC answer, as ta serve sends an ApplicationError: the client reads its code and hint. */
24
73
  function error(id: unknown, message: string, code: TaErrorCode, hint: string): string;
25
74
  function result(id: unknown, result: unknown): string;
75
+ function forbidden(message: string, hint: string): GatewayCallError;
26
76
  function choice(value: unknown, own: boolean, providers: string[]): TaEnvironmentChoice | undefined;
77
+ /** What the audit says of the arguments of a call: its numbers, flags and roles, never more. */
78
+ function detail(method: string, params: unknown[]): string | undefined;
27
79
  }
28
80
  /**
29
81
  * The calls the gateway answers on the WebSocket of a browser: TaGatewayServer, and TaAccessServer, whose
30
- * accounts are those that may have a tenant here; administrators manage them, everyone else sees their own
31
- * sign-ins.
82
+ * accounts are those that may have a tenant here. Each method needs a role (GatewayServiceUtil.RULES); what an
83
+ * admin does to another account needs a role above it; what administrators do is kept in the audit.
32
84
  */
33
85
  export declare class GatewayService {
34
86
  protected readonly flow: SignInFlow;
35
87
  protected readonly tenants: TenantStore;
36
88
  protected readonly environments: Environments;
37
- protected readonly hooks: {
38
- cutOff(): void;
39
- reset(tenantId: string): void;
40
- };
41
- constructor(flow: SignInFlow, tenants: TenantStore, environments: Environments, hooks: {
42
- cutOff(): void;
43
- reset(tenantId: string): void;
44
- });
89
+ protected readonly policy: GatewayPolicy;
90
+ protected readonly quotas: GatewayQuotas;
91
+ protected readonly usage: GatewayUsage;
92
+ protected readonly audit: GatewayAudit;
93
+ protected readonly hooks: GatewayParts['hooks'];
94
+ protected readonly meta: GatewayMeta;
95
+ constructor(parts: GatewayParts);
45
96
  call(caller: GatewayCaller, method: string, params: unknown[]): Promise<unknown>;
97
+ protected handle(caller: GatewayCaller, service: string, name: string, params: unknown[]): Promise<unknown>;
98
+ protected record(caller: GatewayCaller, action: string, params: unknown[]): void;
46
99
  info(caller: GatewayCaller): TaGatewayInfo;
47
- protected ownAllowed(): boolean;
48
100
  protected setEnvironment(caller: GatewayCaller, value: unknown): Promise<TaGatewayInfo>;
49
101
  protected restart(caller: GatewayCaller): Promise<TaGatewayInfo>;
50
- protected listTenants(caller: GatewayCaller): Promise<TaGatewayTenant[]>;
102
+ protected tenantInfo(tenant: Tenant): TaGatewayTenant;
103
+ /** The tenants with what their sandboxes take and their agents do, read together: a slow one holds the console a second, not a second each. */
104
+ protected console(caller: GatewayCaller): Promise<TaGatewayConsole>;
105
+ protected policyView(): TaGatewayPolicy;
106
+ protected tenant(id: unknown): Tenant;
107
+ /** A tenant the caller may change: an owner any; an admin a member's only, not their own, nor another admin's or an owner's. */
108
+ protected manage(caller: GatewayCaller, id: unknown): Tenant;
109
+ protected startTenant(caller: GatewayCaller, id: unknown): Promise<void>;
51
110
  protected stopTenant(caller: GatewayCaller, id: unknown): Promise<void>;
111
+ protected restartTenant(caller: GatewayCaller, id: unknown): Promise<void>;
112
+ /** What its sandbox wrote, its secrets hidden: tokens and keys printed by what ran there do not reach the page. */
113
+ protected logs(id: unknown, lines: unknown): Promise<string>;
114
+ protected activity(id: unknown, sessionId: unknown): Promise<TaAgentActivity[]>;
115
+ protected trend(daysValue: unknown, id: unknown): Promise<TaUsageTrend>;
116
+ protected limits(value: unknown, nullable: boolean): TaGatewayLimits;
117
+ protected setTenantLimits(caller: GatewayCaller, id: unknown, value: unknown): void;
118
+ protected grantMinutes(caller: GatewayCaller, id: unknown, minutes: unknown): void;
119
+ protected setSuspended(caller: GatewayCaller, id: unknown, suspended: unknown): Promise<void>;
120
+ protected setDefaultLimits(value: unknown): TaGatewayPolicy;
121
+ protected setRole(caller: GatewayCaller, account: unknown, role: unknown): TaGatewayPolicy;
52
122
  protected access(caller: GatewayCaller): TaAccessInfo;
53
123
  protected allow(account: unknown, name: unknown): void;
54
124
  /** The browsers of the account are cut off, and what reaches its Ta otherwise (paired phones) goes with its sandbox. */
55
- protected disallow(account: string): Promise<void>;
125
+ protected disallow(caller: GatewayCaller, account: string): Promise<void>;
56
126
  protected signOut(caller: GatewayCaller, id: string): Promise<void>;
57
- protected admin<T>(caller: GatewayCaller, action: () => T | Promise<T>): Promise<T>;
127
+ /**
128
+ * A link that signs in once as an account that has never been here: one that has a tenant, or is an owner's or an
129
+ * admin's, would let whoever makes the link into another's Ta. `ta gateway link`, where the gateway runs, may.
130
+ */
131
+ protected signInLink(account: unknown, name: unknown): string;
58
132
  }
133
+ export {};
59
134
  //# sourceMappingURL=gateway-service.d.ts.map