@celljs/ta-gateway 4.15.1 → 4.16.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (67) hide show
  1. package/esm/node/command-sandbox.d.ts +6 -2
  2. package/esm/node/command-sandbox.js +26 -4
  3. package/esm/node/docker-engine.d.ts +50 -0
  4. package/esm/node/docker-engine.js +98 -11
  5. package/esm/node/docker-sandbox.d.ts +6 -1
  6. package/esm/node/docker-sandbox.js +23 -3
  7. package/esm/node/environments.d.ts +36 -2
  8. package/esm/node/environments.js +192 -14
  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-exec.d.ts +19 -0
  14. package/esm/node/gateway-exec.js +65 -0
  15. package/esm/node/gateway-policy.d.ts +47 -0
  16. package/esm/node/gateway-policy.js +152 -0
  17. package/esm/node/gateway-quotas.d.ts +40 -0
  18. package/esm/node/gateway-quotas.js +135 -0
  19. package/esm/node/gateway-server.d.ts +28 -2
  20. package/esm/node/gateway-server.js +112 -9
  21. package/esm/node/gateway-service.d.ts +99 -16
  22. package/esm/node/gateway-service.js +385 -45
  23. package/esm/node/gateway-socket.d.ts +7 -1
  24. package/esm/node/gateway-socket.js +40 -1
  25. package/esm/node/gateway-usage.d.ts +37 -0
  26. package/esm/node/gateway-usage.js +137 -0
  27. package/esm/node/local-sandbox.d.ts +13 -0
  28. package/esm/node/local-sandbox.js +38 -2
  29. package/esm/node/model-proxy.d.ts +105 -0
  30. package/esm/node/model-proxy.js +435 -0
  31. package/esm/node/sandbox-provider.d.ts +17 -0
  32. package/esm/node/tenant-store.d.ts +19 -1
  33. package/esm/node/tenant-store.js +10 -0
  34. package/lib/node/command-sandbox.d.ts +6 -2
  35. package/lib/node/command-sandbox.js +26 -4
  36. package/lib/node/docker-engine.d.ts +50 -0
  37. package/lib/node/docker-engine.js +98 -11
  38. package/lib/node/docker-sandbox.d.ts +6 -1
  39. package/lib/node/docker-sandbox.js +23 -3
  40. package/lib/node/environments.d.ts +36 -2
  41. package/lib/node/environments.js +191 -13
  42. package/lib/node/gateway-audit.d.ts +13 -0
  43. package/lib/node/gateway-audit.js +51 -0
  44. package/lib/node/gateway-cli.d.ts +2 -0
  45. package/lib/node/gateway-cli.js +1 -0
  46. package/lib/node/gateway-exec.d.ts +20 -0
  47. package/lib/node/gateway-exec.js +69 -0
  48. package/lib/node/gateway-policy.d.ts +48 -0
  49. package/lib/node/gateway-policy.js +157 -0
  50. package/lib/node/gateway-quotas.d.ts +41 -0
  51. package/lib/node/gateway-quotas.js +139 -0
  52. package/lib/node/gateway-server.d.ts +28 -2
  53. package/lib/node/gateway-server.js +112 -9
  54. package/lib/node/gateway-service.d.ts +99 -16
  55. package/lib/node/gateway-service.js +384 -44
  56. package/lib/node/gateway-socket.d.ts +7 -1
  57. package/lib/node/gateway-socket.js +40 -1
  58. package/lib/node/gateway-usage.d.ts +38 -0
  59. package/lib/node/gateway-usage.js +141 -0
  60. package/lib/node/local-sandbox.d.ts +13 -0
  61. package/lib/node/local-sandbox.js +40 -3
  62. package/lib/node/model-proxy.d.ts +106 -0
  63. package/lib/node/model-proxy.js +440 -0
  64. package/lib/node/sandbox-provider.d.ts +17 -0
  65. package/lib/node/tenant-store.d.ts +19 -1
  66. package/lib/node/tenant-store.js +10 -0
  67. package/package.json +4 -4
@@ -1,5 +1,9 @@
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';
6
+ import { ModelProxyUtil } from './model-proxy.js';
3
7
  import { TaSandboxUtil } from './ta-sandbox.js';
4
8
  export class GatewayCallError extends Error {
5
9
  constructor(message, code, hint) {
@@ -8,10 +12,91 @@ export class GatewayCallError extends Error {
8
12
  this.hint = hint;
9
13
  }
10
14
  }
15
+ const DAY = 24 * 3600000;
11
16
  export var GatewayServiceUtil;
12
17
  (function (GatewayServiceUtil) {
18
+ GatewayServiceUtil.DEFAULT_LOG_LINES = 200;
19
+ GatewayServiceUtil.MAX_LOG_LINES = 2000;
20
+ /**
21
+ * Who may call each method: `anyone` signed in (about their own Ta, their own sign-ins), `admin` (owners too),
22
+ * `owner`. A method not here is no method. What an admin may do to another account is checked again by its role
23
+ * (GatewayService.manage).
24
+ */
25
+ GatewayServiceUtil.RULES = {
26
+ TaGatewayServer: {
27
+ getGateway: 'anyone',
28
+ setEnvironment: 'anyone',
29
+ restartEnvironment: 'anyone',
30
+ listTenants: 'admin',
31
+ getConsole: 'admin',
32
+ getTenantAgents: 'admin',
33
+ getAgentActivity: 'admin',
34
+ getTenantLogs: 'admin',
35
+ getUsageTrend: 'admin',
36
+ getPolicy: 'admin',
37
+ getAudit: 'admin',
38
+ startTenant: 'admin',
39
+ stopTenant: 'admin',
40
+ restartTenant: 'admin',
41
+ createSignInLink: 'admin',
42
+ setTenantLimits: 'admin',
43
+ grantMinutes: 'admin',
44
+ setSuspended: 'admin',
45
+ setDefaultLimits: 'owner',
46
+ setRole: 'owner',
47
+ createAccessToken: 'anyone',
48
+ },
49
+ TaAccessServer: {
50
+ getAccess: 'anyone',
51
+ signOut: 'anyone',
52
+ bindUrl: 'admin',
53
+ allow: 'admin',
54
+ dismiss: 'admin',
55
+ disallow: 'admin',
56
+ },
57
+ };
58
+ /** What an administrator did or looked at of others: kept in the audit. */
59
+ GatewayServiceUtil.AUDITED = new Set([
60
+ 'startTenant',
61
+ 'stopTenant',
62
+ 'restartTenant',
63
+ 'getTenantLogs',
64
+ 'getAgentActivity',
65
+ 'createSignInLink',
66
+ 'setTenantLimits',
67
+ 'grantMinutes',
68
+ 'setSuspended',
69
+ 'setDefaultLimits',
70
+ 'setRole',
71
+ 'allow',
72
+ 'dismiss',
73
+ 'disallow',
74
+ ]);
75
+ /** By name, own keys only: a method such as `toString` is no rule. */
76
+ const BY_SERVICE = new Map(Object.entries(GatewayServiceUtil.RULES).map(([service, rules]) => [service, new Map(Object.entries(rules))]));
77
+ function need(service, name) {
78
+ var _a;
79
+ return (_a = BY_SERVICE.get(service)) === null || _a === void 0 ? void 0 : _a.get(name);
80
+ }
81
+ GatewayServiceUtil.need = need;
82
+ function allowed(role, need) {
83
+ return need === 'anyone' || GatewayPolicyUtil.rank(role) >= GatewayPolicyUtil.rank(need);
84
+ }
85
+ GatewayServiceUtil.allowed = allowed;
86
+ /** As many lines as asked, within bounds. */
87
+ function lines(value) {
88
+ const count = Math.floor(Number(value !== null && value !== void 0 ? value : GatewayServiceUtil.DEFAULT_LOG_LINES));
89
+ return Number.isFinite(count) && count > 0 ? Math.min(count, GatewayServiceUtil.MAX_LOG_LINES) : GatewayServiceUtil.DEFAULT_LOG_LINES;
90
+ }
91
+ GatewayServiceUtil.lines = lines;
92
+ /** Days of a trend, 1 to 31. */
93
+ function days(value) {
94
+ const count = Math.floor(Number(value !== null && value !== void 0 ? value : 7));
95
+ return Number.isFinite(count) ? Math.min(31, Math.max(1, count)) : 7;
96
+ }
97
+ GatewayServiceUtil.days = days;
13
98
  /** The services the gateway answers itself, not the Ta of the tenant. */
14
- GatewayServiceUtil.SERVICES = ['TaGatewayServer', 'TaAccessServer'];
99
+ GatewayServiceUtil.SERVICES = Object.keys(GatewayServiceUtil.RULES);
15
100
  function owns(method) {
16
101
  return typeof method === 'string' && GatewayServiceUtil.SERVICES.includes(method.split('/')[0]);
17
102
  }
@@ -21,6 +106,12 @@ export var GatewayServiceUtil;
21
106
  return GatewayServiceUtil.SERVICES.some(service => text.includes(`"${service}/`));
22
107
  }
23
108
  GatewayServiceUtil.mayOwn = mayOwn;
109
+ /** The calls that send the agents a message, which the limit of messages a minute counts. */
110
+ GatewayServiceUtil.PROMPTS = ['TaServer/prompt', 'TaServer/steer', 'TaServer/followUp'];
111
+ function mayPrompt(text) {
112
+ return GatewayServiceUtil.PROMPTS.some(method => text.includes(`"${method}"`));
113
+ }
114
+ GatewayServiceUtil.mayPrompt = mayPrompt;
24
115
  /** The error of a JSON-RPC answer, as ta serve sends an ApplicationError: the client reads its code and hint. */
25
116
  function error(id, message, code, hint) {
26
117
  return JSON.stringify({ jsonrpc: '2.0', id, error: { code: TA_RPC_ERROR_CODE, message, data: { kind: 'application', data: { code, hint } } } });
@@ -33,18 +124,22 @@ export var GatewayServiceUtil;
33
124
  function invalid(message, hint) {
34
125
  return new GatewayCallError(message, TaErrorCode.INVALID_ARGUMENT, hint);
35
126
  }
127
+ function forbidden(message, hint) {
128
+ return new GatewayCallError(message, TaErrorCode.FORBIDDEN, hint);
129
+ }
130
+ GatewayServiceUtil.forbidden = forbidden;
36
131
  function choice(value, own, providers) {
37
132
  var _a;
38
133
  const given = (value !== null && value !== void 0 ? value : {});
39
134
  if (typeof given.provider === 'string') {
40
135
  if (!providers.includes(given.provider)) {
41
- throw invalid(`The gateway has no provider ${given.provider}.`, 'Pick one of the options of getGateway.');
136
+ throw invalid(`The gateway has no provider ${given.provider} for you.`, 'Pick one of the options of getGateway.');
42
137
  }
43
138
  return { provider: given.provider };
44
139
  }
45
140
  if (given.type === 'ta') {
46
141
  if (!own) {
47
- throw invalid('This gateway runs Ta in its own sandboxes only.', 'Pick one of the options of getGateway.');
142
+ throw invalid('This gateway runs your Ta in its own sandboxes only.', 'Pick one of the options of getGateway.');
48
143
  }
49
144
  let url;
50
145
  try {
@@ -61,62 +156,131 @@ export var GatewayServiceUtil;
61
156
  throw invalid('No environment was named.', 'Pass { provider } or { type: "ta", url, token }.');
62
157
  }
63
158
  GatewayServiceUtil.choice = choice;
159
+ /** What the audit says of the arguments of a call: its numbers, flags and roles, never more. */
160
+ function detail(method, params) {
161
+ const [, second] = params;
162
+ switch (method) {
163
+ case 'setTenantLimits':
164
+ case 'setDefaultLimits':
165
+ return JSON.stringify(method === 'setDefaultLimits' ? params[0] : second);
166
+ case 'grantMinutes':
167
+ case 'getTenantLogs':
168
+ return String(second !== null && second !== void 0 ? second : '');
169
+ case 'setSuspended':
170
+ return second ? 'suspended' : 'let go';
171
+ case 'setRole':
172
+ return String(second);
173
+ default:
174
+ return undefined;
175
+ }
176
+ }
177
+ GatewayServiceUtil.detail = detail;
64
178
  })(GatewayServiceUtil || (GatewayServiceUtil = {}));
65
179
  /**
66
180
  * 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.
181
+ * accounts are those that may have a tenant here. Each method needs a role (GatewayServiceUtil.RULES); what an
182
+ * admin does to another account needs a role above it; what administrators do is kept in the audit.
69
183
  */
70
184
  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;
185
+ constructor(parts) {
186
+ this.models = parts.models;
187
+ this.flow = parts.flow;
188
+ this.tenants = parts.tenants;
189
+ this.environments = parts.environments;
190
+ this.policy = parts.policy;
191
+ this.quotas = parts.quotas;
192
+ this.usage = parts.usage;
193
+ this.audit = parts.audit;
194
+ this.hooks = parts.hooks;
195
+ this.meta = parts.meta;
76
196
  }
77
197
  async call(caller, method, params) {
78
198
  const [service, name] = method.split('/');
199
+ const need = GatewayServiceUtil.need(service, name);
200
+ if (!need) {
201
+ throw new GatewayCallError(`${method} is not a method of the gateway.`, TaErrorCode.INVALID_ARGUMENT, 'Call a method of TaGatewayServer or TaAccessServer.');
202
+ }
203
+ if (!GatewayServiceUtil.allowed(caller.role, need)) {
204
+ throw need === 'owner'
205
+ ? GatewayServiceUtil.forbidden('Only owners of the gateway may do that.', 'Ask one of those of TA_GATEWAY_ADMINS.')
206
+ : GatewayServiceUtil.forbidden('Only administrators of the gateway may do that.', 'Ask one of its administrators.');
207
+ }
208
+ const result = await this.handle(caller, service, name, params);
209
+ if (GatewayServiceUtil.AUDITED.has(name)) {
210
+ this.record(caller, name, params);
211
+ }
212
+ return result;
213
+ }
214
+ handle(caller, service, name, params) {
215
+ const [first, second] = params;
79
216
  const handlers = service === 'TaGatewayServer'
80
217
  ? {
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),
218
+ getGateway: () => this.info(caller),
219
+ setEnvironment: () => this.setEnvironment(caller, first),
220
+ restartEnvironment: () => this.restart(caller),
221
+ listTenants: () => this.tenants.list().map(tenant => this.tenantInfo(tenant)),
222
+ getConsole: () => this.console(caller),
223
+ getTenantAgents: () => this.environments.agents(this.tenant(first)),
224
+ getAgentActivity: () => this.activity(first, second),
225
+ getTenantLogs: () => this.logs(first, second),
226
+ getUsageTrend: () => this.trend(first, second),
227
+ getPolicy: () => this.policyView(),
228
+ getAudit: () => this.audit.list(Math.min(500, Math.max(1, Math.floor(Number(first !== null && first !== void 0 ? first : 100)) || 100))),
229
+ startTenant: () => this.startTenant(caller, first),
230
+ stopTenant: () => this.stopTenant(caller, first),
231
+ restartTenant: () => this.restartTenant(caller, first),
232
+ createSignInLink: () => this.signInLink(first, second),
233
+ setTenantLimits: () => this.setTenantLimits(caller, first, second),
234
+ grantMinutes: () => this.grantMinutes(caller, first, second),
235
+ setSuspended: () => this.setSuspended(caller, first, second),
236
+ setDefaultLimits: () => this.setDefaultLimits(first),
237
+ setRole: () => this.setRole(caller, first, second),
238
+ createAccessToken: () => this.accessToken(caller, first),
86
239
  }
87
240
  : {
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)),
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)),
94
247
  };
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.');
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}`);
98
260
  }
99
- return handler(...params);
100
261
  }
101
262
  info(caller) {
102
263
  var _a;
103
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);
104
268
  return {
105
269
  account: { id: tenant.account, name: tenant.name, avatar: tenant.avatar },
106
270
  tenant: tenant.id,
107
271
  environment: this.environments.info(tenant),
108
- options: this.environments.choices(),
109
- 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,
110
274
  admin: caller.admin,
275
+ role: caller.role,
276
+ quota: this.quotas.state(tenant),
111
277
  };
112
278
  }
113
- ownAllowed() {
114
- return this.environments.settings.own;
115
- }
116
279
  async setEnvironment(caller, value) {
117
280
  var _a;
118
- const choice = GatewayServiceUtil.choice(value, this.ownAllowed(), this.environments.providers.map(provider => provider.id));
119
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)));
120
284
  const next = await this.environments.change(tenant, choice);
121
285
  caller.tenant = next;
122
286
  // Everyone of the tenant connects again, once the browser that asked has its answer.
@@ -128,20 +292,180 @@ export class GatewayService {
128
292
  this.hooks.reset(caller.tenant.id);
129
293
  return this.info(caller);
130
294
  }
131
- async listTenants(caller) {
132
- return this.admin(caller, () => this.tenants.list().map(tenant => ({
295
+ tenantInfo(tenant) {
296
+ return {
133
297
  id: tenant.id,
134
298
  account: tenant.account,
135
299
  name: tenant.name,
300
+ avatar: tenant.avatar,
136
301
  environment: this.environments.info(tenant),
137
302
  connections: this.environments.connections(tenant.id),
138
303
  createdAt: tenant.createdAt,
139
304
  lastActiveAt: tenant.lastActiveAt,
140
- })));
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, _b;
314
+ var _c, _d, _e;
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, ((_c = counts.get(provider)) !== null && _c !== void 0 ? _c : 0) + 1);
324
+ }
325
+ const fallback = (_d = this.environments.settings.default) !== null && _d !== void 0 ? _d : (_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
+ models: ModelProxyUtil.catalog((_e = (_b = this.models) === null || _b === void 0 ? void 0 : _b.config) !== null && _e !== void 0 ? _e : {}).providers.map(provider => ({
347
+ id: provider.id,
348
+ name: provider.name,
349
+ api: provider.api,
350
+ models: provider.models.length,
351
+ })),
352
+ };
353
+ }
354
+ policyView() {
355
+ return this.policy.view(this.environments.settings.idleMinutes);
356
+ }
357
+ tenant(id) {
358
+ const tenant = typeof id === 'string' ? this.tenants.get(id) : undefined;
359
+ if (!tenant) {
360
+ throw new GatewayCallError(`The gateway has no tenant ${id}.`, TaErrorCode.INVALID_ARGUMENT, 'Pick one of the tenants of getConsole.');
361
+ }
362
+ return tenant;
363
+ }
364
+ /** 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. */
365
+ manage(caller, id) {
366
+ const tenant = this.tenant(id);
367
+ if (caller.role !== 'owner' && (this.quotas.role(tenant) !== 'member' || tenant.account === caller.account)) {
368
+ throw GatewayServiceUtil.forbidden('Admins manage members only, not themselves, other admins or owners.', 'Ask an owner of the gateway (TA_GATEWAY_ADMINS).');
369
+ }
370
+ return tenant;
371
+ }
372
+ async startTenant(caller, id) {
373
+ await this.environments.ensure(this.manage(caller, id));
141
374
  }
142
375
  async stopTenant(caller, id) {
143
- await this.admin(caller, () => this.environments.stop(String(id)));
144
- this.hooks.reset(String(id));
376
+ const tenant = this.manage(caller, id);
377
+ await this.environments.stop(tenant.id);
378
+ this.hooks.reset(tenant.id);
379
+ }
380
+ async restartTenant(caller, id) {
381
+ const tenant = this.manage(caller, id);
382
+ await this.environments.stop(tenant.id).catch(() => undefined);
383
+ this.hooks.reset(tenant.id);
384
+ await this.environments.ensure(tenant);
385
+ }
386
+ /** What its sandbox wrote, its secrets hidden: tokens and keys printed by what ran there do not reach the page. */
387
+ async logs(id, lines) {
388
+ return new Redactor().text(await this.environments.logs(this.tenant(id), GatewayServiceUtil.lines(lines)));
389
+ }
390
+ activity(id, sessionId) {
391
+ return this.environments.activity(this.tenant(id), String(sessionId));
392
+ }
393
+ async trend(daysValue, id) {
394
+ const now = Date.now();
395
+ const days = GatewayServiceUtil.days(daysValue);
396
+ const tenants = id === undefined || id === null ? this.tenants.list() : [this.tenant(id)];
397
+ const fresh = await Promise.all(tenants.map(tenant => this.usage.refresh(tenant.id, this.environments.usageReader(tenant), now, 0).catch(() => false)));
398
+ const byTenant = new Map();
399
+ const stale = [];
400
+ tenants.forEach((tenant, index) => {
401
+ const kept = this.usage.get(tenant.id);
402
+ if (kept) {
403
+ byTenant.set(tenant.id, kept.buckets);
404
+ if (!fresh[index]) {
405
+ stale.push(tenant.id);
406
+ }
407
+ }
408
+ });
409
+ // Whole hours: the first is the one `days` ago.
410
+ const since = Math.floor((now - days * DAY) / 3600000) * 3600000;
411
+ return GatewayUsageUtil.trend(byTenant, since, stale, now);
412
+ }
413
+ limits(value, nullable) {
414
+ try {
415
+ return GatewayPolicyUtil.limits(value, this.environments.providers.map(provider => provider.id), nullable);
416
+ }
417
+ catch (error) {
418
+ if (error instanceof PolicyError) {
419
+ throw new GatewayCallError(error.message, TaErrorCode.INVALID_ARGUMENT, 'Send the limits again, written well.');
420
+ }
421
+ throw error;
422
+ }
423
+ }
424
+ setTenantLimits(caller, id, value) {
425
+ const tenant = this.manage(caller, id);
426
+ this.tenants.update(tenant.id, { limits: value === null ? undefined : this.limits(value, true) });
427
+ }
428
+ grantMinutes(caller, id, minutes) {
429
+ const tenant = this.manage(caller, id);
430
+ if (typeof minutes !== 'number' || !Number.isInteger(minutes) || Math.abs(minutes) > 1000000) {
431
+ throw new GatewayCallError('Minutes are a whole number.', TaErrorCode.INVALID_ARGUMENT, 'Give, say, 60; a negative number takes some back.');
432
+ }
433
+ this.quotas.grant(tenant, minutes);
434
+ }
435
+ async setSuspended(caller, id, suspended) {
436
+ const tenant = this.manage(caller, id);
437
+ this.tenants.update(tenant.id, { suspended: suspended === true || undefined });
438
+ if (suspended === true) {
439
+ await this.environments.stop(tenant.id).catch(() => undefined);
440
+ this.hooks.reset(tenant.id);
441
+ }
442
+ }
443
+ setDefaultLimits(value) {
444
+ this.policy.setDefaults(this.limits(value, false));
445
+ return this.policyView();
446
+ }
447
+ setRole(caller, account, role) {
448
+ const id = typeof account === 'string' ? account.trim() : '';
449
+ if (role !== 'admin' && role !== 'member') {
450
+ throw new GatewayCallError('A role is admin or member.', TaErrorCode.INVALID_ARGUMENT, 'Owners are those of TA_GATEWAY_ADMINS.');
451
+ }
452
+ if (this.policy.role(id) === 'owner') {
453
+ throw GatewayServiceUtil.forbidden('An owner stays one: they are of TA_GATEWAY_ADMINS.', 'Change TA_GATEWAY_ADMINS where the gateway runs.');
454
+ }
455
+ if (id === caller.account || !this.tenants.list().some(tenant => tenant.account === id)) {
456
+ throw new GatewayCallError(`${id} has not signed in to the gateway.`, TaErrorCode.INVALID_ARGUMENT, 'Make an account that signed in an admin.');
457
+ }
458
+ this.policy.setRole(id, role);
459
+ return this.policyView();
460
+ }
461
+ /** A sign-in of the caller's own account, named for where it is used. */
462
+ accessToken(caller, label) {
463
+ var _a;
464
+ const tenant = (_a = this.tenants.get(caller.tenant.id)) !== null && _a !== void 0 ? _a : caller.tenant;
465
+ const device = typeof label === 'string' && label.trim() ? label.trim().slice(0, 60) : 'Another Ta';
466
+ const token = this.flow.store.signIn({ id: caller.account, name: tenant.name, avatar: tenant.avatar }, device);
467
+ console.log(`ta gateway: ${caller.account} made a token for ${device}`);
468
+ return { token, url: this.meta.publicUrl };
145
469
  }
146
470
  access(caller) {
147
471
  const providers = this.flow.providers.map(({ id, name }) => ({ id, name }));
@@ -158,10 +482,18 @@ export class GatewayService {
158
482
  this.flow.store.allow(account.trim(), typeof name === 'string' ? name : undefined);
159
483
  }
160
484
  /** 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));
485
+ async disallow(caller, account) {
486
+ const normalized = AccessUtil.normalize(account);
487
+ const role = this.policy.role(normalized);
488
+ if (role === 'owner' || (role === 'admin' && caller.role !== 'owner')) {
489
+ 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.');
490
+ }
491
+ if (role === 'admin') {
492
+ this.policy.setRole(normalized, 'member');
493
+ }
494
+ this.flow.store.disallow(normalized);
163
495
  this.hooks.cutOff();
164
- for (const tenant of this.tenants.list().filter(one => !this.flow.store.allows(one.account))) {
496
+ for (const tenant of this.tenants.list().filter(one => !this.flow.store.allows(one.account) && !this.policy.lets(one.account))) {
165
497
  const unpaired = await this.environments.revoke(tenant).catch((error) => {
166
498
  console.warn(`ta gateway: revoking ${tenant.account} failed: ${error.message}`);
167
499
  return 0;
@@ -172,16 +504,24 @@ export class GatewayService {
172
504
  async signOut(caller, id) {
173
505
  const own = this.flow.store.info(caller.token).signIns.find(signIn => signIn.id === id);
174
506
  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.');
507
+ throw GatewayServiceUtil.forbidden('That sign-in is not yours.', 'Sign out of the browsers of your own account.');
176
508
  }
177
509
  this.flow.store.signOut(id);
178
510
  this.hooks.cutOff();
179
511
  }
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.');
512
+ /**
513
+ * 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
514
+ * admin's, would let whoever makes the link into another's Ta. `ta gateway link`, where the gateway runs, may.
515
+ */
516
+ signInLink(account, name) {
517
+ const id = typeof account === 'string' ? account.trim() : '';
518
+ if (!/^[a-z][a-z0-9-]*:\S+$/.test(id)) {
519
+ throw new GatewayCallError(`${account} is not an account.`, TaErrorCode.INVALID_ARGUMENT, 'Write it <kind>:<name>, such as github:octocat or user:alice.');
520
+ }
521
+ if (this.tenants.list().some(tenant => tenant.account === id) || this.policy.role(id) !== 'member') {
522
+ 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
523
  }
184
- return action();
524
+ return this.meta.links.create(id, typeof name === 'string' && name.trim() ? name.trim() : undefined);
185
525
  }
186
526
  }
187
527
  //# 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) {