@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
@@ -1,5 +1,8 @@
1
1
  import { AccessUtil } from '@celljs/ta-host/lib/node/sign-in/access-store';
2
- import { TA_RPC_ERROR_CODE, TaErrorCode } from '@celljs/ta-protocol';
2
+ import { TA_RPC_ERROR_CODE, TaErrorCode, } from '@celljs/ta-protocol';
3
+ import { Redactor } from '@celljs/ta-protocol/lib/common/redactor';
4
+ import { GatewayPolicyUtil, PolicyError } from './gateway-policy.js';
5
+ import { GatewayUsageUtil } from './gateway-usage.js';
3
6
  import { TaSandboxUtil } from './ta-sandbox.js';
4
7
  export class GatewayCallError extends Error {
5
8
  constructor(message, code, hint) {
@@ -8,10 +11,90 @@ export class GatewayCallError extends Error {
8
11
  this.hint = hint;
9
12
  }
10
13
  }
14
+ const DAY = 24 * 3600000;
11
15
  export var GatewayServiceUtil;
12
16
  (function (GatewayServiceUtil) {
17
+ GatewayServiceUtil.DEFAULT_LOG_LINES = 200;
18
+ GatewayServiceUtil.MAX_LOG_LINES = 2000;
19
+ /**
20
+ * Who may call each method: `anyone` signed in (about their own Ta, their own sign-ins), `admin` (owners too),
21
+ * `owner`. A method not here is no method. What an admin may do to another account is checked again by its role
22
+ * (GatewayService.manage).
23
+ */
24
+ GatewayServiceUtil.RULES = {
25
+ TaGatewayServer: {
26
+ getGateway: 'anyone',
27
+ setEnvironment: 'anyone',
28
+ restartEnvironment: 'anyone',
29
+ listTenants: 'admin',
30
+ getConsole: 'admin',
31
+ getTenantAgents: 'admin',
32
+ getAgentActivity: 'admin',
33
+ getTenantLogs: 'admin',
34
+ getUsageTrend: 'admin',
35
+ getPolicy: 'admin',
36
+ getAudit: 'admin',
37
+ startTenant: 'admin',
38
+ stopTenant: 'admin',
39
+ restartTenant: 'admin',
40
+ createSignInLink: 'admin',
41
+ setTenantLimits: 'admin',
42
+ grantMinutes: 'admin',
43
+ setSuspended: 'admin',
44
+ setDefaultLimits: 'owner',
45
+ setRole: 'owner',
46
+ },
47
+ TaAccessServer: {
48
+ getAccess: 'anyone',
49
+ signOut: 'anyone',
50
+ bindUrl: 'admin',
51
+ allow: 'admin',
52
+ dismiss: 'admin',
53
+ disallow: 'admin',
54
+ },
55
+ };
56
+ /** What an administrator did or looked at of others: kept in the audit. */
57
+ GatewayServiceUtil.AUDITED = new Set([
58
+ 'startTenant',
59
+ 'stopTenant',
60
+ 'restartTenant',
61
+ 'getTenantLogs',
62
+ 'getAgentActivity',
63
+ 'createSignInLink',
64
+ 'setTenantLimits',
65
+ 'grantMinutes',
66
+ 'setSuspended',
67
+ 'setDefaultLimits',
68
+ 'setRole',
69
+ 'allow',
70
+ 'dismiss',
71
+ 'disallow',
72
+ ]);
73
+ /** By name, own keys only: a method such as `toString` is no rule. */
74
+ const BY_SERVICE = new Map(Object.entries(GatewayServiceUtil.RULES).map(([service, rules]) => [service, new Map(Object.entries(rules))]));
75
+ function need(service, name) {
76
+ var _a;
77
+ return (_a = BY_SERVICE.get(service)) === null || _a === void 0 ? void 0 : _a.get(name);
78
+ }
79
+ GatewayServiceUtil.need = need;
80
+ function allowed(role, need) {
81
+ return need === 'anyone' || GatewayPolicyUtil.rank(role) >= GatewayPolicyUtil.rank(need);
82
+ }
83
+ GatewayServiceUtil.allowed = allowed;
84
+ /** As many lines as asked, within bounds. */
85
+ function lines(value) {
86
+ const count = Math.floor(Number(value !== null && value !== void 0 ? value : GatewayServiceUtil.DEFAULT_LOG_LINES));
87
+ return Number.isFinite(count) && count > 0 ? Math.min(count, GatewayServiceUtil.MAX_LOG_LINES) : GatewayServiceUtil.DEFAULT_LOG_LINES;
88
+ }
89
+ GatewayServiceUtil.lines = lines;
90
+ /** Days of a trend, 1 to 31. */
91
+ function days(value) {
92
+ const count = Math.floor(Number(value !== null && value !== void 0 ? value : 7));
93
+ return Number.isFinite(count) ? Math.min(31, Math.max(1, count)) : 7;
94
+ }
95
+ GatewayServiceUtil.days = days;
13
96
  /** The services the gateway answers itself, not the Ta of the tenant. */
14
- GatewayServiceUtil.SERVICES = ['TaGatewayServer', 'TaAccessServer'];
97
+ GatewayServiceUtil.SERVICES = Object.keys(GatewayServiceUtil.RULES);
15
98
  function owns(method) {
16
99
  return typeof method === 'string' && GatewayServiceUtil.SERVICES.includes(method.split('/')[0]);
17
100
  }
@@ -21,6 +104,12 @@ export var GatewayServiceUtil;
21
104
  return GatewayServiceUtil.SERVICES.some(service => text.includes(`"${service}/`));
22
105
  }
23
106
  GatewayServiceUtil.mayOwn = mayOwn;
107
+ /** The calls that send the agents a message, which the limit of messages a minute counts. */
108
+ GatewayServiceUtil.PROMPTS = ['TaServer/prompt', 'TaServer/steer', 'TaServer/followUp'];
109
+ function mayPrompt(text) {
110
+ return GatewayServiceUtil.PROMPTS.some(method => text.includes(`"${method}"`));
111
+ }
112
+ GatewayServiceUtil.mayPrompt = mayPrompt;
24
113
  /** The error of a JSON-RPC answer, as ta serve sends an ApplicationError: the client reads its code and hint. */
25
114
  function error(id, message, code, hint) {
26
115
  return JSON.stringify({ jsonrpc: '2.0', id, error: { code: TA_RPC_ERROR_CODE, message, data: { kind: 'application', data: { code, hint } } } });
@@ -33,18 +122,22 @@ export var GatewayServiceUtil;
33
122
  function invalid(message, hint) {
34
123
  return new GatewayCallError(message, TaErrorCode.INVALID_ARGUMENT, hint);
35
124
  }
125
+ function forbidden(message, hint) {
126
+ return new GatewayCallError(message, TaErrorCode.FORBIDDEN, hint);
127
+ }
128
+ GatewayServiceUtil.forbidden = forbidden;
36
129
  function choice(value, own, providers) {
37
130
  var _a;
38
131
  const given = (value !== null && value !== void 0 ? value : {});
39
132
  if (typeof given.provider === 'string') {
40
133
  if (!providers.includes(given.provider)) {
41
- throw invalid(`The gateway has no provider ${given.provider}.`, 'Pick one of the options of getGateway.');
134
+ throw invalid(`The gateway has no provider ${given.provider} for you.`, 'Pick one of the options of getGateway.');
42
135
  }
43
136
  return { provider: given.provider };
44
137
  }
45
138
  if (given.type === 'ta') {
46
139
  if (!own) {
47
- throw invalid('This gateway runs Ta in its own sandboxes only.', 'Pick one of the options of getGateway.');
140
+ throw invalid('This gateway runs your Ta in its own sandboxes only.', 'Pick one of the options of getGateway.');
48
141
  }
49
142
  let url;
50
143
  try {
@@ -61,62 +154,129 @@ export var GatewayServiceUtil;
61
154
  throw invalid('No environment was named.', 'Pass { provider } or { type: "ta", url, token }.');
62
155
  }
63
156
  GatewayServiceUtil.choice = choice;
157
+ /** What the audit says of the arguments of a call: its numbers, flags and roles, never more. */
158
+ function detail(method, params) {
159
+ const [, second] = params;
160
+ switch (method) {
161
+ case 'setTenantLimits':
162
+ case 'setDefaultLimits':
163
+ return JSON.stringify(method === 'setDefaultLimits' ? params[0] : second);
164
+ case 'grantMinutes':
165
+ case 'getTenantLogs':
166
+ return String(second !== null && second !== void 0 ? second : '');
167
+ case 'setSuspended':
168
+ return second ? 'suspended' : 'let go';
169
+ case 'setRole':
170
+ return String(second);
171
+ default:
172
+ return undefined;
173
+ }
174
+ }
175
+ GatewayServiceUtil.detail = detail;
64
176
  })(GatewayServiceUtil || (GatewayServiceUtil = {}));
65
177
  /**
66
178
  * The calls the gateway answers on the WebSocket of a browser: TaGatewayServer, and TaAccessServer, whose
67
- * accounts are those that may have a tenant here; administrators manage them, everyone else sees their own
68
- * sign-ins.
179
+ * accounts are those that may have a tenant here. Each method needs a role (GatewayServiceUtil.RULES); what an
180
+ * admin does to another account needs a role above it; what administrators do is kept in the audit.
69
181
  */
70
182
  export class GatewayService {
71
- constructor(flow, tenants, environments, hooks) {
72
- this.flow = flow;
73
- this.tenants = tenants;
74
- this.environments = environments;
75
- this.hooks = hooks;
183
+ constructor(parts) {
184
+ this.flow = parts.flow;
185
+ this.tenants = parts.tenants;
186
+ this.environments = parts.environments;
187
+ this.policy = parts.policy;
188
+ this.quotas = parts.quotas;
189
+ this.usage = parts.usage;
190
+ this.audit = parts.audit;
191
+ this.hooks = parts.hooks;
192
+ this.meta = parts.meta;
76
193
  }
77
194
  async call(caller, method, params) {
78
195
  const [service, name] = method.split('/');
196
+ const need = GatewayServiceUtil.need(service, name);
197
+ if (!need) {
198
+ throw new GatewayCallError(`${method} is not a method of the gateway.`, TaErrorCode.INVALID_ARGUMENT, 'Call a method of TaGatewayServer or TaAccessServer.');
199
+ }
200
+ if (!GatewayServiceUtil.allowed(caller.role, need)) {
201
+ throw need === 'owner'
202
+ ? GatewayServiceUtil.forbidden('Only owners of the gateway may do that.', 'Ask one of those of TA_GATEWAY_ADMINS.')
203
+ : GatewayServiceUtil.forbidden('Only administrators of the gateway may do that.', 'Ask one of its administrators.');
204
+ }
205
+ const result = await this.handle(caller, service, name, params);
206
+ if (GatewayServiceUtil.AUDITED.has(name)) {
207
+ this.record(caller, name, params);
208
+ }
209
+ return result;
210
+ }
211
+ handle(caller, service, name, params) {
212
+ const [first, second] = params;
79
213
  const handlers = service === 'TaGatewayServer'
80
214
  ? {
81
- getGateway: async () => this.info(caller),
82
- setEnvironment: async (choice) => this.setEnvironment(caller, choice),
83
- restartEnvironment: async () => this.restart(caller),
84
- listTenants: async () => this.listTenants(caller),
85
- stopTenant: async (id) => this.stopTenant(caller, id),
215
+ getGateway: () => this.info(caller),
216
+ setEnvironment: () => this.setEnvironment(caller, first),
217
+ restartEnvironment: () => this.restart(caller),
218
+ listTenants: () => this.tenants.list().map(tenant => this.tenantInfo(tenant)),
219
+ getConsole: () => this.console(caller),
220
+ getTenantAgents: () => this.environments.agents(this.tenant(first)),
221
+ getAgentActivity: () => this.activity(first, second),
222
+ getTenantLogs: () => this.logs(first, second),
223
+ getUsageTrend: () => this.trend(first, second),
224
+ getPolicy: () => this.policyView(),
225
+ getAudit: () => this.audit.list(Math.min(500, Math.max(1, Math.floor(Number(first !== null && first !== void 0 ? first : 100)) || 100))),
226
+ startTenant: () => this.startTenant(caller, first),
227
+ stopTenant: () => this.stopTenant(caller, first),
228
+ restartTenant: () => this.restartTenant(caller, first),
229
+ createSignInLink: () => this.signInLink(first, second),
230
+ setTenantLimits: () => this.setTenantLimits(caller, first, second),
231
+ grantMinutes: () => this.grantMinutes(caller, first, second),
232
+ setSuspended: () => this.setSuspended(caller, first, second),
233
+ setDefaultLimits: () => this.setDefaultLimits(first),
234
+ setRole: () => this.setRole(caller, first, second),
86
235
  }
87
236
  : {
88
- getAccess: async () => this.access(caller),
89
- bindUrl: async (provider) => this.admin(caller, () => this.flow.bindUrl(String(provider))),
90
- allow: async (account, name) => this.admin(caller, () => this.allow(account, name)),
91
- dismiss: async (account) => this.admin(caller, () => this.flow.store.dismiss(String(account))),
92
- disallow: async (account) => this.admin(caller, () => this.disallow(String(account))),
93
- signOut: async (id) => this.signOut(caller, String(id)),
237
+ getAccess: () => this.access(caller),
238
+ bindUrl: () => this.flow.bindUrl(String(first)),
239
+ allow: () => this.allow(first, second),
240
+ dismiss: () => this.flow.store.dismiss(String(first)),
241
+ disallow: () => this.disallow(caller, String(first)),
242
+ signOut: () => this.signOut(caller, String(first)),
94
243
  };
95
- const handler = new Map(Object.entries(handlers)).get(name);
96
- if (!handler) {
97
- throw new GatewayCallError(`${method} is not a method of the gateway.`, TaErrorCode.INVALID_ARGUMENT, 'Call a method of TaGatewayServer or TaAccessServer.');
244
+ return Promise.resolve().then(handlers[name]);
245
+ }
246
+ record(caller, action, params) {
247
+ var _a;
248
+ var _b;
249
+ const [first] = params;
250
+ const target = typeof first === 'string' ? ((_b = (_a = this.tenants.get(first)) === null || _a === void 0 ? void 0 : _a.account) !== null && _b !== void 0 ? _b : (/^[a-z][a-z0-9-]*:\S+$/.test(first) ? first : undefined)) : undefined;
251
+ try {
252
+ this.audit.add({ actor: caller.account, action, target, detail: GatewayServiceUtil.detail(action, params) });
253
+ }
254
+ catch (error) {
255
+ console.warn(`ta gateway: the audit could not be written: ${error.message}`);
98
256
  }
99
- return handler(...params);
100
257
  }
101
258
  info(caller) {
102
259
  var _a;
103
260
  const tenant = (_a = this.tenants.get(caller.tenant.id)) !== null && _a !== void 0 ? _a : caller.tenant;
261
+ // What its agents took is asked in the background: the page reads it the next time.
262
+ void this.usage.refresh(tenant.id, this.environments.usageReader(tenant)).catch(() => undefined);
263
+ const limits = this.quotas.limits(tenant);
104
264
  return {
105
265
  account: { id: tenant.account, name: tenant.name, avatar: tenant.avatar },
106
266
  tenant: tenant.id,
107
267
  environment: this.environments.info(tenant),
108
- options: this.environments.choices(),
109
- own: this.ownAllowed(),
268
+ options: this.environments.choices().filter(option => !limits.providers || limits.providers.includes(option.id)),
269
+ own: this.environments.settings.own && limits.own,
110
270
  admin: caller.admin,
271
+ role: caller.role,
272
+ quota: this.quotas.state(tenant),
111
273
  };
112
274
  }
113
- ownAllowed() {
114
- return this.environments.settings.own;
115
- }
116
275
  async setEnvironment(caller, value) {
117
276
  var _a;
118
- const choice = GatewayServiceUtil.choice(value, this.ownAllowed(), this.environments.providers.map(provider => provider.id));
119
277
  const tenant = (_a = this.tenants.get(caller.tenant.id)) !== null && _a !== void 0 ? _a : caller.tenant;
278
+ const limits = this.quotas.limits(tenant);
279
+ const choice = GatewayServiceUtil.choice(value, this.environments.settings.own && limits.own, this.environments.providers.map(provider => provider.id).filter(id => !limits.providers || limits.providers.includes(id)));
120
280
  const next = await this.environments.change(tenant, choice);
121
281
  caller.tenant = next;
122
282
  // Everyone of the tenant connects again, once the browser that asked has its answer.
@@ -128,20 +288,165 @@ export class GatewayService {
128
288
  this.hooks.reset(caller.tenant.id);
129
289
  return this.info(caller);
130
290
  }
131
- async listTenants(caller) {
132
- return this.admin(caller, () => this.tenants.list().map(tenant => ({
291
+ tenantInfo(tenant) {
292
+ return {
133
293
  id: tenant.id,
134
294
  account: tenant.account,
135
295
  name: tenant.name,
296
+ avatar: tenant.avatar,
136
297
  environment: this.environments.info(tenant),
137
298
  connections: this.environments.connections(tenant.id),
138
299
  createdAt: tenant.createdAt,
139
300
  lastActiveAt: tenant.lastActiveAt,
140
- })));
301
+ role: this.quotas.role(tenant),
302
+ quota: this.quotas.state(tenant),
303
+ limits: tenant.limits,
304
+ suspended: tenant.suspended || undefined,
305
+ };
306
+ }
307
+ /** 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. */
308
+ async console(caller) {
309
+ var _a;
310
+ var _b, _c;
311
+ const tenants = this.tenants.list();
312
+ const [usages, agents] = await Promise.all([
313
+ Promise.all(tenants.map(tenant => this.environments.usage(tenant).catch(() => undefined))),
314
+ Promise.all(tenants.map(tenant => this.environments.agentSummary(tenant).catch(() => undefined))),
315
+ ]);
316
+ const counts = new Map();
317
+ for (const tenant of tenants) {
318
+ const { provider } = this.environments.info(tenant);
319
+ counts.set(provider, ((_b = counts.get(provider)) !== null && _b !== void 0 ? _b : 0) + 1);
320
+ }
321
+ const fallback = (_c = this.environments.settings.default) !== null && _c !== void 0 ? _c : (_a = this.environments.providers[0]) === null || _a === void 0 ? void 0 : _a.id;
322
+ return {
323
+ version: this.meta.version,
324
+ startedAt: this.meta.startedAt,
325
+ publicUrl: this.meta.publicUrl,
326
+ providers: this.environments.providers.map(provider => { var _a; return ({
327
+ id: provider.id,
328
+ name: provider.name,
329
+ type: provider.type,
330
+ default: provider.id === fallback,
331
+ tenants: (_a = counts.get(provider.id)) !== null && _a !== void 0 ? _a : 0,
332
+ logs: typeof provider.logs === 'function',
333
+ }); }),
334
+ own: this.environments.settings.own,
335
+ idleMinutes: this.environments.settings.idleMinutes,
336
+ tenants: tenants
337
+ .map((tenant, index) => ({ ...this.tenantInfo(tenant), usage: usages[index], agents: agents[index] }))
338
+ .sort((a, b) => { var _a, _b; return ((_a = b.lastActiveAt) !== null && _a !== void 0 ? _a : b.createdAt) - ((_b = a.lastActiveAt) !== null && _b !== void 0 ? _b : a.createdAt); }),
339
+ requests: this.flow.store.info(caller.token).requests.length,
340
+ role: caller.role,
341
+ policy: this.policyView(),
342
+ };
343
+ }
344
+ policyView() {
345
+ return this.policy.view(this.environments.settings.idleMinutes);
346
+ }
347
+ tenant(id) {
348
+ const tenant = typeof id === 'string' ? this.tenants.get(id) : undefined;
349
+ if (!tenant) {
350
+ throw new GatewayCallError(`The gateway has no tenant ${id}.`, TaErrorCode.INVALID_ARGUMENT, 'Pick one of the tenants of getConsole.');
351
+ }
352
+ return tenant;
353
+ }
354
+ /** 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. */
355
+ manage(caller, id) {
356
+ const tenant = this.tenant(id);
357
+ if (caller.role !== 'owner' && (this.quotas.role(tenant) !== 'member' || tenant.account === caller.account)) {
358
+ throw GatewayServiceUtil.forbidden('Admins manage members only, not themselves, other admins or owners.', 'Ask an owner of the gateway (TA_GATEWAY_ADMINS).');
359
+ }
360
+ return tenant;
361
+ }
362
+ async startTenant(caller, id) {
363
+ await this.environments.ensure(this.manage(caller, id));
141
364
  }
142
365
  async stopTenant(caller, id) {
143
- await this.admin(caller, () => this.environments.stop(String(id)));
144
- this.hooks.reset(String(id));
366
+ const tenant = this.manage(caller, id);
367
+ await this.environments.stop(tenant.id);
368
+ this.hooks.reset(tenant.id);
369
+ }
370
+ async restartTenant(caller, id) {
371
+ const tenant = this.manage(caller, id);
372
+ await this.environments.stop(tenant.id).catch(() => undefined);
373
+ this.hooks.reset(tenant.id);
374
+ await this.environments.ensure(tenant);
375
+ }
376
+ /** What its sandbox wrote, its secrets hidden: tokens and keys printed by what ran there do not reach the page. */
377
+ async logs(id, lines) {
378
+ return new Redactor().text(await this.environments.logs(this.tenant(id), GatewayServiceUtil.lines(lines)));
379
+ }
380
+ activity(id, sessionId) {
381
+ return this.environments.activity(this.tenant(id), String(sessionId));
382
+ }
383
+ async trend(daysValue, id) {
384
+ const now = Date.now();
385
+ const days = GatewayServiceUtil.days(daysValue);
386
+ const tenants = id === undefined || id === null ? this.tenants.list() : [this.tenant(id)];
387
+ const fresh = await Promise.all(tenants.map(tenant => this.usage.refresh(tenant.id, this.environments.usageReader(tenant), now, 0).catch(() => false)));
388
+ const byTenant = new Map();
389
+ const stale = [];
390
+ tenants.forEach((tenant, index) => {
391
+ const kept = this.usage.get(tenant.id);
392
+ if (kept) {
393
+ byTenant.set(tenant.id, kept.buckets);
394
+ if (!fresh[index]) {
395
+ stale.push(tenant.id);
396
+ }
397
+ }
398
+ });
399
+ // Whole hours: the first is the one `days` ago.
400
+ const since = Math.floor((now - days * DAY) / 3600000) * 3600000;
401
+ return GatewayUsageUtil.trend(byTenant, since, stale, now);
402
+ }
403
+ limits(value, nullable) {
404
+ try {
405
+ return GatewayPolicyUtil.limits(value, this.environments.providers.map(provider => provider.id), nullable);
406
+ }
407
+ catch (error) {
408
+ if (error instanceof PolicyError) {
409
+ throw new GatewayCallError(error.message, TaErrorCode.INVALID_ARGUMENT, 'Send the limits again, written well.');
410
+ }
411
+ throw error;
412
+ }
413
+ }
414
+ setTenantLimits(caller, id, value) {
415
+ const tenant = this.manage(caller, id);
416
+ this.tenants.update(tenant.id, { limits: value === null ? undefined : this.limits(value, true) });
417
+ }
418
+ grantMinutes(caller, id, minutes) {
419
+ const tenant = this.manage(caller, id);
420
+ if (typeof minutes !== 'number' || !Number.isInteger(minutes) || Math.abs(minutes) > 1000000) {
421
+ throw new GatewayCallError('Minutes are a whole number.', TaErrorCode.INVALID_ARGUMENT, 'Give, say, 60; a negative number takes some back.');
422
+ }
423
+ this.quotas.grant(tenant, minutes);
424
+ }
425
+ async setSuspended(caller, id, suspended) {
426
+ const tenant = this.manage(caller, id);
427
+ this.tenants.update(tenant.id, { suspended: suspended === true || undefined });
428
+ if (suspended === true) {
429
+ await this.environments.stop(tenant.id).catch(() => undefined);
430
+ this.hooks.reset(tenant.id);
431
+ }
432
+ }
433
+ setDefaultLimits(value) {
434
+ this.policy.setDefaults(this.limits(value, false));
435
+ return this.policyView();
436
+ }
437
+ setRole(caller, account, role) {
438
+ const id = typeof account === 'string' ? account.trim() : '';
439
+ if (role !== 'admin' && role !== 'member') {
440
+ throw new GatewayCallError('A role is admin or member.', TaErrorCode.INVALID_ARGUMENT, 'Owners are those of TA_GATEWAY_ADMINS.');
441
+ }
442
+ if (this.policy.role(id) === 'owner') {
443
+ throw GatewayServiceUtil.forbidden('An owner stays one: they are of TA_GATEWAY_ADMINS.', 'Change TA_GATEWAY_ADMINS where the gateway runs.');
444
+ }
445
+ if (id === caller.account || !this.tenants.list().some(tenant => tenant.account === id)) {
446
+ throw new GatewayCallError(`${id} has not signed in to the gateway.`, TaErrorCode.INVALID_ARGUMENT, 'Make an account that signed in an admin.');
447
+ }
448
+ this.policy.setRole(id, role);
449
+ return this.policyView();
145
450
  }
146
451
  access(caller) {
147
452
  const providers = this.flow.providers.map(({ id, name }) => ({ id, name }));
@@ -158,10 +463,18 @@ export class GatewayService {
158
463
  this.flow.store.allow(account.trim(), typeof name === 'string' ? name : undefined);
159
464
  }
160
465
  /** The browsers of the account are cut off, and what reaches its Ta otherwise (paired phones) goes with its sandbox. */
161
- async disallow(account) {
162
- this.flow.store.disallow(AccessUtil.normalize(account));
466
+ async disallow(caller, account) {
467
+ const normalized = AccessUtil.normalize(account);
468
+ const role = this.policy.role(normalized);
469
+ if (role === 'owner' || (role === 'admin' && caller.role !== 'owner')) {
470
+ throw GatewayServiceUtil.forbidden(role === 'owner' ? 'Owners are let in where the gateway runs (TA_GATEWAY_ADMINS).' : 'Only owners remove an admin.', 'Ask an owner of the gateway.');
471
+ }
472
+ if (role === 'admin') {
473
+ this.policy.setRole(normalized, 'member');
474
+ }
475
+ this.flow.store.disallow(normalized);
163
476
  this.hooks.cutOff();
164
- for (const tenant of this.tenants.list().filter(one => !this.flow.store.allows(one.account))) {
477
+ for (const tenant of this.tenants.list().filter(one => !this.flow.store.allows(one.account) && !this.policy.lets(one.account))) {
165
478
  const unpaired = await this.environments.revoke(tenant).catch((error) => {
166
479
  console.warn(`ta gateway: revoking ${tenant.account} failed: ${error.message}`);
167
480
  return 0;
@@ -172,16 +485,24 @@ export class GatewayService {
172
485
  async signOut(caller, id) {
173
486
  const own = this.flow.store.info(caller.token).signIns.find(signIn => signIn.id === id);
174
487
  if (!caller.admin && (own === null || own === void 0 ? void 0 : own.account) !== caller.account) {
175
- throw new GatewayCallError('That sign-in is not yours.', TaErrorCode.INVALID_ARGUMENT, 'Sign out of the browsers of your own account.');
488
+ throw GatewayServiceUtil.forbidden('That sign-in is not yours.', 'Sign out of the browsers of your own account.');
176
489
  }
177
490
  this.flow.store.signOut(id);
178
491
  this.hooks.cutOff();
179
492
  }
180
- async admin(caller, action) {
181
- if (!caller.admin) {
182
- throw new GatewayCallError('Only administrators of the gateway may do that.', TaErrorCode.INVALID_ARGUMENT, 'Ask one of those of TA_GATEWAY_ADMINS.');
493
+ /**
494
+ * 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
495
+ * admin's, would let whoever makes the link into another's Ta. `ta gateway link`, where the gateway runs, may.
496
+ */
497
+ signInLink(account, name) {
498
+ const id = typeof account === 'string' ? account.trim() : '';
499
+ if (!/^[a-z][a-z0-9-]*:\S+$/.test(id)) {
500
+ throw new GatewayCallError(`${account} is not an account.`, TaErrorCode.INVALID_ARGUMENT, 'Write it <kind>:<name>, such as github:octocat or user:alice.');
501
+ }
502
+ if (this.tenants.list().some(tenant => tenant.account === id) || this.policy.role(id) !== 'member') {
503
+ throw GatewayServiceUtil.forbidden(`${id} has been here already: a link would sign whoever opens it in as them.`, 'Invite accounts that are new; one that has been here signs in its own way.');
183
504
  }
184
- return action();
505
+ return this.meta.links.create(id, typeof name === 'string' && name.trim() ? name.trim() : undefined);
185
506
  }
186
507
  }
187
508
  //# sourceMappingURL=gateway-service.js.map
@@ -1,5 +1,6 @@
1
1
  import type { WebSocketConnection } from '@celljs/rpc/lib/node/websocket/websocket-connection';
2
2
  import type { Environments } from './environments.js';
3
+ import type { GatewayQuotas } from './gateway-quotas.js';
3
4
  import { type GatewayCaller, type GatewayService } from './gateway-service.js';
4
5
  /**
5
6
  * One browser's WebSocket: the calls of the gateway's services answered here, everything else forwarded to
@@ -12,6 +13,7 @@ export declare class GatewaySocket {
12
13
  readonly caller: GatewayCaller;
13
14
  protected readonly environments: Environments;
14
15
  protected readonly service: GatewayService;
16
+ protected readonly quotas?: GatewayQuotas | undefined;
15
17
  protected inner?: WebSocket;
16
18
  protected readonly queued: string[];
17
19
  protected queuedBytes: number;
@@ -21,11 +23,15 @@ export declare class GatewaySocket {
21
23
  protected answering: number;
22
24
  protected closeAfterAnswers?: string;
23
25
  protected readonly release: () => void;
24
- constructor(browser: WebSocketConnection, caller: GatewayCaller, environments: Environments, service: GatewayService);
26
+ protected windowStart: number;
27
+ protected windowCount: number;
28
+ constructor(browser: WebSocketConnection, caller: GatewayCaller, environments: Environments, service: GatewayService, quotas?: GatewayQuotas | undefined);
25
29
  get tenantId(): string;
26
30
  close(code: number, reason: string): void;
27
31
  protected open(): Promise<void>;
28
32
  protected fromBrowser(text: string): void;
33
+ /** A message to the agents within the limit of the account goes on; one past it is answered here, not forwarded. */
34
+ protected admitPrompt(text: string): boolean;
29
35
  protected forward(text: string): void;
30
36
  protected answer(id: unknown, method: string, params: unknown[]): Promise<void>;
31
37
  /** The calls that wait, and those to come, fail; those of the gateway still work. */
@@ -4,6 +4,9 @@ import { GatewayCallError, GatewayServiceUtil } from './gateway-service.js';
4
4
  const MAX_QUEUED = 256;
5
5
  /** And as many bytes at most: a message may be 32 MB, and 256 of them would hold the gateway's memory for one browser. */
6
6
  const MAX_QUEUED_BYTES = 16 * 1024 * 1024;
7
+ /** Messages of one browser within {@link FLOOD_WINDOW_MS}, at most: a page sends far fewer; more is cut off. */
8
+ const FLOOD_MESSAGES = 2000;
9
+ const FLOOD_WINDOW_MS = 10000;
7
10
  /**
8
11
  * One browser's WebSocket: the calls of the gateway's services answered here, everything else forwarded to
9
12
  * the Ta of its tenant, whose token only the gateway has, and back. Until that Ta answers, what the browser
@@ -11,16 +14,19 @@ const MAX_QUEUED_BYTES = 16 * 1024 * 1024;
11
14
  * still work, so that the page can change or restart the environment.
12
15
  */
13
16
  export class GatewaySocket {
14
- constructor(browser, caller, environments, service) {
17
+ constructor(browser, caller, environments, service, quotas) {
15
18
  this.browser = browser;
16
19
  this.caller = caller;
17
20
  this.environments = environments;
18
21
  this.service = service;
22
+ this.quotas = quotas;
19
23
  this.queued = [];
20
24
  this.queuedBytes = 0;
21
25
  this.closed = false;
22
26
  /** Calls of the gateway being answered: a change of environment stops the one this socket is on meanwhile. */
23
27
  this.answering = 0;
28
+ this.windowStart = Date.now();
29
+ this.windowCount = 0;
24
30
  this.release = environments.connect(caller.tenant.id);
25
31
  browser.onMessage(text => this.fromBrowser(text));
26
32
  browser.onClose(() => this.dispose());
@@ -72,6 +78,18 @@ export class GatewaySocket {
72
78
  };
73
79
  }
74
80
  fromBrowser(text) {
81
+ const now = Date.now();
82
+ if (now - this.windowStart > FLOOD_WINDOW_MS) {
83
+ this.windowStart = now;
84
+ this.windowCount = 0;
85
+ }
86
+ if (++this.windowCount > FLOOD_MESSAGES) {
87
+ this.close(1008, 'Too many messages.');
88
+ return;
89
+ }
90
+ if (this.failure === undefined && GatewayServiceUtil.mayPrompt(text) && !this.admitPrompt(text)) {
91
+ return;
92
+ }
75
93
  // Most messages are the Ta's, some large (pictures): forwarded without being read.
76
94
  if (this.failure === undefined && !GatewayServiceUtil.mayOwn(text)) {
77
95
  this.forward(text);
@@ -97,6 +115,27 @@ export class GatewaySocket {
97
115
  }
98
116
  this.forward(text);
99
117
  }
118
+ /** A message to the agents within the limit of the account goes on; one past it is answered here, not forwarded. */
119
+ admitPrompt(text) {
120
+ let message;
121
+ try {
122
+ message = JSON.parse(text);
123
+ }
124
+ catch (_a) {
125
+ return true;
126
+ }
127
+ if (typeof message.method !== 'string' || !GatewayServiceUtil.PROMPTS.includes(message.method) || !this.quotas) {
128
+ return true;
129
+ }
130
+ if (this.quotas.takePrompt(this.caller.tenant)) {
131
+ return true;
132
+ }
133
+ const seconds = Math.ceil(this.quotas.retryAfter(this.caller.tenant) / 1000);
134
+ if (message.id !== undefined) {
135
+ this.browser.send(GatewayServiceUtil.error(message.id, `You sent as many messages this minute as your account may (${this.quotas.limits(this.caller.tenant).promptsPerMinute}).`, TaErrorCode.RATE_LIMITED, `Send it again in ${seconds} s.`));
136
+ }
137
+ return false;
138
+ }
100
139
  forward(text) {
101
140
  var _a;
102
141
  if (((_a = this.inner) === null || _a === void 0 ? void 0 : _a.readyState) === WebSocket.OPEN) {
@@ -0,0 +1,37 @@
1
+ import type { TaUsageBucket, TaUsageTrend } from '@celljs/ta-protocol';
2
+ interface Kept {
3
+ readAt: number;
4
+ buckets: TaUsageBucket[];
5
+ }
6
+ export declare namespace GatewayUsageUtil {
7
+ const KEEP_MS: number;
8
+ /** The start of the month of UTC of `now`, and of the next. */
9
+ function month(now: number): {
10
+ key: string;
11
+ start: number;
12
+ next: number;
13
+ };
14
+ function tokens(bucket: TaUsageBucket): number;
15
+ /** The buckets of tenants since `since`: by hour, by model and by tenant. */
16
+ function trend(byTenant: Map<string, TaUsageBucket[]>, since: number, stale: string[], now: number): TaUsageTrend;
17
+ }
18
+ /**
19
+ * What the agents of each tenant took, by hour, as its Ta said last (TaUsageServer): asked of a running sandbox
20
+ * at most once a minute, kept in `usage/<tenant>.json` so that one stopped still counts.
21
+ */
22
+ export declare class GatewayUsage {
23
+ protected readonly dir: string;
24
+ protected readonly kept: Map<string, Kept>;
25
+ protected readonly reading: Map<string, Promise<void>>;
26
+ constructor(root: string);
27
+ /** What is kept of the tenant. */
28
+ get(tenantId: string): Kept | undefined;
29
+ /** Asks the tenant's Ta again, unless it was asked within `maxAge` (a minute); `read` undefined: it does not run. */
30
+ refresh(tenantId: string, read: ((since: number) => Promise<TaUsageBucket[]>) | undefined, now?: number, maxAge?: number): Promise<boolean>;
31
+ /** Tokens and dollars of the month of `now`. */
32
+ month(tenantId: string, now?: number): {
33
+ tokens: number;
34
+ cost: number;
35
+ };
36
+ }
37
+ export {};