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