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