@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
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
import { GatewayPolicyUtil } from './gateway-policy.js';
|
|
2
|
+
import { GatewayUsageUtil } from './gateway-usage.js';
|
|
3
|
+
const MINUTE = 60000;
|
|
4
|
+
/** Of the time between two ticks, at most this counts: a gateway asleep or stopped did not see its sandboxes run. */
|
|
5
|
+
const MAX_TICK_MS = 2 * MINUTE;
|
|
6
|
+
/**
|
|
7
|
+
* What members may use and what they used: the minutes their sandboxes ran this month (of UTC), counted by the
|
|
8
|
+
* gateway as it sees them run, and the messages a minute they send their agents. Owners have no limits.
|
|
9
|
+
*/
|
|
10
|
+
export class GatewayQuotas {
|
|
11
|
+
constructor(policy, tenants, usage, ownAllowed,
|
|
12
|
+
/** Whether the gateway gives its sandboxes models: then it counts their tokens, and holds them to the limit. */
|
|
13
|
+
metered = () => false) {
|
|
14
|
+
this.policy = policy;
|
|
15
|
+
this.tenants = tenants;
|
|
16
|
+
this.usage = usage;
|
|
17
|
+
this.ownAllowed = ownAllowed;
|
|
18
|
+
this.metered = metered;
|
|
19
|
+
this.lastTick = Date.now();
|
|
20
|
+
/** By tenant: the times of its messages within the last minute. */
|
|
21
|
+
this.prompts = new Map();
|
|
22
|
+
}
|
|
23
|
+
role(tenant) {
|
|
24
|
+
return this.policy.role(tenant.account);
|
|
25
|
+
}
|
|
26
|
+
limits(tenant) {
|
|
27
|
+
if (this.role(tenant) === 'owner') {
|
|
28
|
+
return { own: this.ownAllowed() };
|
|
29
|
+
}
|
|
30
|
+
return GatewayPolicyUtil.resolve(this.policy.defaults, tenant.limits, this.ownAllowed());
|
|
31
|
+
}
|
|
32
|
+
/** That of this month: a meter of a month before starts again. */
|
|
33
|
+
meter(tenant, now = Date.now()) {
|
|
34
|
+
var _a;
|
|
35
|
+
const { key } = GatewayUsageUtil.month(now);
|
|
36
|
+
return ((_a = tenant.meter) === null || _a === void 0 ? void 0 : _a.month) === key ? tenant.meter : { month: key, runMs: 0, bonusMinutes: 0 };
|
|
37
|
+
}
|
|
38
|
+
blocked(tenant, now = Date.now()) {
|
|
39
|
+
if (tenant.suspended && this.role(tenant) !== 'owner') {
|
|
40
|
+
return 'suspended';
|
|
41
|
+
}
|
|
42
|
+
const { freeMinutes } = this.limits(tenant);
|
|
43
|
+
const meter = this.meter(tenant, now);
|
|
44
|
+
return freeMinutes !== undefined && meter.runMs >= (freeMinutes + meter.bonusMinutes) * MINUTE ? 'minutes' : undefined;
|
|
45
|
+
}
|
|
46
|
+
state(tenant, now = Date.now()) {
|
|
47
|
+
var _a, _b;
|
|
48
|
+
const { key, next } = GatewayUsageUtil.month(now);
|
|
49
|
+
const meter = this.meter(tenant, now);
|
|
50
|
+
const limits = this.limits(tenant);
|
|
51
|
+
const metered = this.metered();
|
|
52
|
+
const month = metered ? { tokens: (_a = meter.tokens) !== null && _a !== void 0 ? _a : 0, cost: (_b = meter.cost) !== null && _b !== void 0 ? _b : 0 } : this.usage.month(tenant.id, now);
|
|
53
|
+
return {
|
|
54
|
+
month: key,
|
|
55
|
+
resetsAt: next,
|
|
56
|
+
minutes: { used: Math.floor(meter.runMs / MINUTE), limit: limits.freeMinutes, bonus: meter.bonusMinutes },
|
|
57
|
+
tokens: { used: month.tokens, cost: month.cost, limit: metered ? limits.monthlyTokens : undefined, metered },
|
|
58
|
+
promptsPerMinute: limits.promptsPerMinute,
|
|
59
|
+
connections: limits.connections,
|
|
60
|
+
blocked: this.blocked(tenant, now),
|
|
61
|
+
};
|
|
62
|
+
}
|
|
63
|
+
/** Why a call of a model of the gateway is refused now; owners have no limit. */
|
|
64
|
+
refuseModels(tenant, now = Date.now()) {
|
|
65
|
+
var _a;
|
|
66
|
+
if (this.role(tenant) === 'owner') {
|
|
67
|
+
return undefined;
|
|
68
|
+
}
|
|
69
|
+
if (tenant.suspended) {
|
|
70
|
+
return 'Your account is suspended by an administrator of the gateway.';
|
|
71
|
+
}
|
|
72
|
+
const limit = this.limits(tenant).monthlyTokens;
|
|
73
|
+
const used = (_a = this.meter(tenant, now).tokens) !== null && _a !== void 0 ? _a : 0;
|
|
74
|
+
// The words pi does not retry on: the month is over, not a moment of load.
|
|
75
|
+
return limit !== undefined && used >= limit
|
|
76
|
+
? `Monthly usage limit reached: ${used} of ${limit} tokens this month; it starts again next month, or ask an administrator.`
|
|
77
|
+
: undefined;
|
|
78
|
+
}
|
|
79
|
+
/** What a call of a model took, to the month of the tenant. */
|
|
80
|
+
addTokens(tenantId, tokens, cost, now = Date.now()) {
|
|
81
|
+
var _a, _b;
|
|
82
|
+
const tenant = this.tenants.get(tenantId);
|
|
83
|
+
if (!tenant) {
|
|
84
|
+
return;
|
|
85
|
+
}
|
|
86
|
+
const meter = this.meter(tenant, now);
|
|
87
|
+
this.tenants.update(tenantId, { meter: { ...meter, tokens: ((_a = meter.tokens) !== null && _a !== void 0 ? _a : 0) + tokens, cost: ((_b = meter.cost) !== null && _b !== void 0 ? _b : 0) + cost } });
|
|
88
|
+
}
|
|
89
|
+
/** What a message of the tenant to its agents needs: false when it sent as many this minute as it may. */
|
|
90
|
+
takePrompt(tenant, now = Date.now()) {
|
|
91
|
+
var _a;
|
|
92
|
+
const limit = this.limits(tenant).promptsPerMinute;
|
|
93
|
+
if (limit === undefined) {
|
|
94
|
+
return true;
|
|
95
|
+
}
|
|
96
|
+
const times = ((_a = this.prompts.get(tenant.id)) !== null && _a !== void 0 ? _a : []).filter(time => now - time < MINUTE);
|
|
97
|
+
if (times.length >= limit) {
|
|
98
|
+
this.prompts.set(tenant.id, times);
|
|
99
|
+
return false;
|
|
100
|
+
}
|
|
101
|
+
times.push(now);
|
|
102
|
+
this.prompts.set(tenant.id, times);
|
|
103
|
+
return true;
|
|
104
|
+
}
|
|
105
|
+
/** When the next message may go: the oldest of the minute leaves it. */
|
|
106
|
+
retryAfter(tenant, now = Date.now()) {
|
|
107
|
+
var _a;
|
|
108
|
+
const oldest = (_a = this.prompts.get(tenant.id)) === null || _a === void 0 ? void 0 : _a[0];
|
|
109
|
+
return oldest === undefined ? 0 : Math.max(0, MINUTE - (now - oldest));
|
|
110
|
+
}
|
|
111
|
+
/** The time since the last tick, to each tenant whose sandbox ran meanwhile; those now blocked. */
|
|
112
|
+
tick(running, now = Date.now()) {
|
|
113
|
+
const elapsed = Math.min(Math.max(0, now - this.lastTick), MAX_TICK_MS);
|
|
114
|
+
this.lastTick = now;
|
|
115
|
+
const blocked = [];
|
|
116
|
+
for (const id of running) {
|
|
117
|
+
const tenant = this.tenants.get(id);
|
|
118
|
+
if (!tenant) {
|
|
119
|
+
continue;
|
|
120
|
+
}
|
|
121
|
+
const meter = this.meter(tenant, now);
|
|
122
|
+
const next = this.tenants.update(id, { meter: { ...meter, runMs: meter.runMs + elapsed } });
|
|
123
|
+
if (this.blocked(next, now)) {
|
|
124
|
+
blocked.push(next);
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
return blocked;
|
|
128
|
+
}
|
|
129
|
+
/** Free minutes on top of the limit, this month; never fewer than none. */
|
|
130
|
+
grant(tenant, minutes, now = Date.now()) {
|
|
131
|
+
const meter = this.meter(tenant, now);
|
|
132
|
+
return this.tenants.update(tenant.id, { meter: { ...meter, bonusMinutes: Math.max(0, meter.bonusMinutes + minutes) } });
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
//# sourceMappingURL=gateway-quotas.js.map
|
|
@@ -2,9 +2,15 @@ import { type IncomingMessage, type Server, type ServerResponse } from 'node:htt
|
|
|
2
2
|
import { type Duplex } from 'node:stream';
|
|
3
3
|
import { SignInFlow } from '@celljs/ta-host/lib/node/sign-in/sign-in-flow';
|
|
4
4
|
import { type SignInAccount } from '@celljs/ta-host/lib/node/sign-in/sign-in-provider';
|
|
5
|
+
import { type TaQuotaBlock } from '@celljs/ta-protocol';
|
|
5
6
|
import { Environments } from './environments.js';
|
|
7
|
+
import { GatewayAudit } from './gateway-audit.js';
|
|
8
|
+
import { GatewayPolicy } from './gateway-policy.js';
|
|
9
|
+
import { GatewayQuotas } from './gateway-quotas.js';
|
|
6
10
|
import { type GatewayCaller, GatewayService } from './gateway-service.js';
|
|
7
11
|
import { GatewaySocket } from './gateway-socket.js';
|
|
12
|
+
import { GatewayUsage } from './gateway-usage.js';
|
|
13
|
+
import { type GatewayModelsConfig, ModelProxy } from './model-proxy.js';
|
|
8
14
|
import { type SandboxProviderFactory, SandboxProviders } from './sandbox-provider.js';
|
|
9
15
|
import { SignInLinks } from './sign-in-links.js';
|
|
10
16
|
import { TenantStore } from './tenant-store.js';
|
|
@@ -19,8 +25,19 @@ export interface GatewayServerOptions {
|
|
|
19
25
|
publicDir: string;
|
|
20
26
|
taCommand: string[];
|
|
21
27
|
env?: Record<string, string | undefined>;
|
|
28
|
+
/** Of Ta, for the console. */
|
|
29
|
+
version?: string;
|
|
22
30
|
}
|
|
23
31
|
export declare namespace GatewayServerUtil {
|
|
32
|
+
/**
|
|
33
|
+
* Where a sandbox reaches the gateway, by the type of its provider: a container the host (host.docker.internal,
|
|
34
|
+
* mapped on Linux too), a process of this machine 127.0.0.1, another the public address.
|
|
35
|
+
*/
|
|
36
|
+
function reach(type: string, port: number, publicUrl: string | undefined): string;
|
|
37
|
+
/** Where another Ta reaches the exec server of its account's sandbox. */
|
|
38
|
+
const EXEC_PATH = "/api/exec";
|
|
39
|
+
/** What a page is told when its Ta does not start for its account's limits; TaGatewayInfo.quota says it in the page's words. */
|
|
40
|
+
function blockedReason(block: TaQuotaBlock | undefined): string | undefined;
|
|
24
41
|
/** A file of `root` for a path of the page, never outside it; the page for what is not a file. */
|
|
25
42
|
function file(root: string, urlPath: string): string;
|
|
26
43
|
/**
|
|
@@ -50,11 +67,20 @@ export declare class GatewayServer {
|
|
|
50
67
|
readonly links: SignInLinks;
|
|
51
68
|
protected readonly service: GatewayService;
|
|
52
69
|
protected readonly sockets: Set<GatewaySocket>;
|
|
53
|
-
|
|
70
|
+
readonly policy: GatewayPolicy;
|
|
71
|
+
readonly quotas: GatewayQuotas;
|
|
72
|
+
readonly usage: GatewayUsage;
|
|
73
|
+
readonly audit: GatewayAudit;
|
|
74
|
+
readonly models: ModelProxy;
|
|
75
|
+
/** The port it listens on, once it does. */
|
|
76
|
+
protected port?: number;
|
|
54
77
|
protected server?: Server;
|
|
78
|
+
protected ticker?: ReturnType<typeof setInterval>;
|
|
55
79
|
static create(options: GatewayServerOptions): Promise<GatewayServer>;
|
|
56
|
-
protected constructor(options: GatewayServerOptions, providers: Awaited<ReturnType<typeof SandboxProviders.create>>, config: ReturnType<typeof SandboxProviders.read
|
|
80
|
+
protected constructor(options: GatewayServerOptions, providers: Awaited<ReturnType<typeof SandboxProviders.create>>, config: ReturnType<typeof SandboxProviders.read>, models?: GatewayModelsConfig);
|
|
57
81
|
isAdmin(account: string): boolean;
|
|
82
|
+
/** The minutes of the sandboxes that ran since the last time; those out of them, or suspended, stop. */
|
|
83
|
+
tick(now?: number): Promise<void>;
|
|
58
84
|
listen(): Promise<string>;
|
|
59
85
|
close(): Promise<void>;
|
|
60
86
|
/** The browsers whose sign-in no longer works are cut off. */
|
|
@@ -12,13 +12,21 @@ import { TA_FILES_PATH, TA_WEBSOCKET_PATH } from '@celljs/ta-protocol';
|
|
|
12
12
|
import { CommandSandbox } from './command-sandbox.js';
|
|
13
13
|
import { DockerSandbox } from './docker-sandbox.js';
|
|
14
14
|
import { Environments } from './environments.js';
|
|
15
|
+
import { GatewayAudit } from './gateway-audit.js';
|
|
16
|
+
import { GatewayExecProxy } from './gateway-exec.js';
|
|
17
|
+
import { GatewayPolicy } from './gateway-policy.js';
|
|
18
|
+
import { GatewayQuotas } from './gateway-quotas.js';
|
|
15
19
|
import { GatewayService } from './gateway-service.js';
|
|
16
20
|
import { GatewaySocket } from './gateway-socket.js';
|
|
21
|
+
import { GatewayUsage } from './gateway-usage.js';
|
|
17
22
|
import { LocalSandbox } from './local-sandbox.js';
|
|
23
|
+
import { ModelProxy, ModelProxyUtil } from './model-proxy.js';
|
|
18
24
|
import { SandboxProviders } from './sandbox-provider.js';
|
|
19
25
|
import { SIGN_IN_LINK_PATH, SignInLinks } from './sign-in-links.js';
|
|
20
26
|
import { TaSandbox } from './ta-sandbox.js';
|
|
21
27
|
import { TenantStore } from './tenant-store.js';
|
|
28
|
+
/** How often the minutes of running sandboxes are counted, and those out of them stopped. */
|
|
29
|
+
const TICK_MS = 30000;
|
|
22
30
|
/** The browser's token for `/api/files`, which pages load by URL, without the token of the WebSocket. */
|
|
23
31
|
const FILES_COOKIE = 'ta_gateway';
|
|
24
32
|
const TYPES = {
|
|
@@ -44,6 +52,34 @@ export const SANDBOX_TYPES = {
|
|
|
44
52
|
};
|
|
45
53
|
export var GatewayServerUtil;
|
|
46
54
|
(function (GatewayServerUtil) {
|
|
55
|
+
/**
|
|
56
|
+
* Where a sandbox reaches the gateway, by the type of its provider: a container the host (host.docker.internal,
|
|
57
|
+
* mapped on Linux too), a process of this machine 127.0.0.1, another the public address.
|
|
58
|
+
*/
|
|
59
|
+
function reach(type, port, publicUrl) {
|
|
60
|
+
if (type === 'docker') {
|
|
61
|
+
return `http://host.docker.internal:${port}`;
|
|
62
|
+
}
|
|
63
|
+
if (type === 'local' || !publicUrl) {
|
|
64
|
+
return `http://127.0.0.1:${port}`;
|
|
65
|
+
}
|
|
66
|
+
return publicUrl;
|
|
67
|
+
}
|
|
68
|
+
GatewayServerUtil.reach = reach;
|
|
69
|
+
/** Where another Ta reaches the exec server of its account's sandbox. */
|
|
70
|
+
GatewayServerUtil.EXEC_PATH = '/api/exec';
|
|
71
|
+
/** What a page is told when its Ta does not start for its account's limits; TaGatewayInfo.quota says it in the page's words. */
|
|
72
|
+
function blockedReason(block) {
|
|
73
|
+
switch (block) {
|
|
74
|
+
case 'suspended':
|
|
75
|
+
return 'Your account is suspended by an administrator of the gateway.';
|
|
76
|
+
case 'minutes':
|
|
77
|
+
return 'Your free minutes of this month are used up.';
|
|
78
|
+
default:
|
|
79
|
+
return undefined;
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
GatewayServerUtil.blockedReason = blockedReason;
|
|
47
83
|
/** A file of `root` for a path of the page, never outside it; the page for what is not a file. */
|
|
48
84
|
function file(root, urlPath) {
|
|
49
85
|
let path;
|
|
@@ -89,19 +125,21 @@ export var GatewayServerUtil;
|
|
|
89
125
|
*/
|
|
90
126
|
export class GatewayServer {
|
|
91
127
|
static async create(options) {
|
|
128
|
+
const models = ModelProxyUtil.read(options.dir);
|
|
92
129
|
mkdirSync(options.dir, { recursive: true, mode: 0o700 });
|
|
93
130
|
const config = SandboxProviders.read(options.dir);
|
|
94
131
|
const context = { dir: options.dir, taCommand: options.taCommand };
|
|
95
132
|
const providers = await SandboxProviders.create(config, context, SANDBOX_TYPES);
|
|
96
|
-
return new GatewayServer(options, providers, config);
|
|
133
|
+
return new GatewayServer(options, providers, config, models);
|
|
97
134
|
}
|
|
98
|
-
constructor(options, providers, config) {
|
|
135
|
+
constructor(options, providers, config, models = {}) {
|
|
99
136
|
var _a, _b;
|
|
100
137
|
this.options = options;
|
|
101
138
|
this.sockets = new Set();
|
|
102
139
|
const env = (_a = options.env) !== null && _a !== void 0 ? _a : process.env;
|
|
103
|
-
|
|
104
|
-
|
|
140
|
+
const owners = AccessUtil.parseList(env.TA_GATEWAY_ADMINS);
|
|
141
|
+
this.policy = new GatewayPolicy(options.dir, owners);
|
|
142
|
+
const allowed = [...AccessUtil.parseList(env.TA_ALLOWED_USERS), ...owners];
|
|
105
143
|
this.flow = new SignInFlow(SignInProviders.fromEnv(env), new AccessStore(join(options.dir, 'access.json'), allowed), SignInProviders.publicUrl(env));
|
|
106
144
|
this.tenants = new TenantStore(options.dir);
|
|
107
145
|
this.links = new SignInLinks(options.dir);
|
|
@@ -110,25 +148,70 @@ export class GatewayServer {
|
|
|
110
148
|
own: config.ownEnvironments !== false,
|
|
111
149
|
idleMinutes: (_b = config.idleMinutes) !== null && _b !== void 0 ? _b : 0,
|
|
112
150
|
});
|
|
113
|
-
this.
|
|
151
|
+
this.usage = new GatewayUsage(options.dir);
|
|
152
|
+
this.audit = new GatewayAudit(options.dir);
|
|
153
|
+
this.quotas = new GatewayQuotas(this.policy, this.tenants, this.usage, () => this.environments.settings.own, () => this.models.enabled);
|
|
154
|
+
this.environments.guard = tenant => GatewayServerUtil.blockedReason(this.quotas.blocked(tenant));
|
|
155
|
+
this.models = new ModelProxy(models, {
|
|
156
|
+
tenantOfKey: key => this.tenants.list().find(tenant => tenant.modelKey && ModelProxyUtil.sameKey(key, tenant.modelKey)),
|
|
157
|
+
refuse: id => {
|
|
158
|
+
const tenant = this.tenants.get(id);
|
|
159
|
+
return tenant ? this.quotas.refuseModels(tenant) : 'No such account.';
|
|
160
|
+
},
|
|
161
|
+
record: (id, usage, cost) => this.quotas.addTokens(id, ModelProxyUtil.total(usage), cost),
|
|
162
|
+
}, env);
|
|
163
|
+
this.environments.envOf = (tenant, provider) => {
|
|
164
|
+
var _a, _b, _c;
|
|
165
|
+
if (!this.models.enabled) {
|
|
166
|
+
return undefined;
|
|
167
|
+
}
|
|
168
|
+
const url = (_a = provider.gatewayUrl) !== null && _a !== void 0 ? _a : GatewayServerUtil.reach(provider.type, (_c = (_b = this.port) !== null && _b !== void 0 ? _b : options.port) !== null && _c !== void 0 ? _c : 4100, SandboxProviders.publicBase(env));
|
|
169
|
+
return { TA_MODEL_PROXY_URL: url.replace(/\/+$/, ''), TA_MODEL_PROXY_KEY: this.tenants.modelKey(tenant.id) };
|
|
170
|
+
};
|
|
171
|
+
this.service = new GatewayService({
|
|
172
|
+
flow: this.flow,
|
|
173
|
+
tenants: this.tenants,
|
|
174
|
+
environments: this.environments,
|
|
175
|
+
policy: this.policy,
|
|
176
|
+
quotas: this.quotas,
|
|
177
|
+
usage: this.usage,
|
|
178
|
+
audit: this.audit,
|
|
179
|
+
hooks: { cutOff: () => this.cutOff(), reset: id => this.reset(id) },
|
|
180
|
+
models: this.models,
|
|
181
|
+
meta: { links: this.links, startedAt: Date.now(), version: options.version, publicUrl: SandboxProviders.publicBase(env) },
|
|
182
|
+
});
|
|
114
183
|
}
|
|
115
184
|
isAdmin(account) {
|
|
116
|
-
return this.
|
|
185
|
+
return this.policy.role(account) !== 'member';
|
|
186
|
+
}
|
|
187
|
+
/** The minutes of the sandboxes that ran since the last time; those out of them, or suspended, stop. */
|
|
188
|
+
async tick(now = Date.now()) {
|
|
189
|
+
for (const tenant of this.quotas.tick(this.environments.runningIds(), now)) {
|
|
190
|
+
console.log(`ta gateway: ${tenant.account} used its free minutes of the month: its sandbox stops`);
|
|
191
|
+
await this.environments.stop(tenant.id).catch(() => undefined);
|
|
192
|
+
this.reset(tenant.id);
|
|
193
|
+
}
|
|
117
194
|
}
|
|
118
195
|
listen() {
|
|
196
|
+
var _a, _b;
|
|
119
197
|
const server = createServer((request, response) => void this.handle(request, response));
|
|
120
198
|
server.on('upgrade', (request, socket, head) => this.upgrade(request, socket, head));
|
|
121
199
|
this.server = server;
|
|
200
|
+
this.ticker = setInterval(() => void this.tick().catch(error => console.warn(`ta gateway: counting minutes failed: ${error.message}`)), TICK_MS);
|
|
201
|
+
(_b = (_a = this.ticker).unref) === null || _b === void 0 ? void 0 : _b.call(_a);
|
|
122
202
|
return new Promise((resolve, reject) => {
|
|
123
203
|
var _a, _b;
|
|
124
204
|
server.once('error', reject);
|
|
125
205
|
server.listen((_a = this.options.port) !== null && _a !== void 0 ? _a : 4100, (_b = this.options.host) !== null && _b !== void 0 ? _b : '127.0.0.1', () => {
|
|
126
206
|
const { address, port } = server.address();
|
|
207
|
+
this.port = port;
|
|
127
208
|
resolve(`http://${address.includes(':') ? `[${address}]` : address}:${port}`);
|
|
128
209
|
});
|
|
129
210
|
});
|
|
130
211
|
}
|
|
131
212
|
async close() {
|
|
213
|
+
clearInterval(this.ticker);
|
|
214
|
+
await this.tick().catch(() => undefined);
|
|
132
215
|
for (const socket of this.sockets) {
|
|
133
216
|
socket.close(1001, 'The gateway is stopping.');
|
|
134
217
|
}
|
|
@@ -162,7 +245,8 @@ export class GatewayServer {
|
|
|
162
245
|
return undefined;
|
|
163
246
|
}
|
|
164
247
|
const tenant = this.tenants.ensure({ id: signIn.account, name: signIn.name, avatar: signIn.avatar });
|
|
165
|
-
|
|
248
|
+
const role = this.policy.role(signIn.account);
|
|
249
|
+
return { token, account: signIn.account, tenant, role, admin: role !== 'member' };
|
|
166
250
|
}
|
|
167
251
|
async handle(request, response) {
|
|
168
252
|
var _a;
|
|
@@ -177,6 +261,9 @@ export class GatewayServer {
|
|
|
177
261
|
onSignedIn: (res, token, account, origin) => this.signedIn(res, token, account, origin),
|
|
178
262
|
});
|
|
179
263
|
}
|
|
264
|
+
else if (path === ModelProxyUtil.PATH || path.startsWith(`${ModelProxyUtil.PATH}/`)) {
|
|
265
|
+
await this.models.handle(request, response);
|
|
266
|
+
}
|
|
180
267
|
else if (path.startsWith(`${TA_FILES_PATH}/`)) {
|
|
181
268
|
await this.files(request, response);
|
|
182
269
|
}
|
|
@@ -290,7 +377,7 @@ export class GatewayServer {
|
|
|
290
377
|
upgrade(request, socket, head) {
|
|
291
378
|
var _a, _b;
|
|
292
379
|
const url = new URL((_a = request.url) !== null && _a !== void 0 ? _a : '/', 'http://gateway');
|
|
293
|
-
if (url.pathname !== TA_WEBSOCKET_PATH) {
|
|
380
|
+
if (url.pathname !== TA_WEBSOCKET_PATH && url.pathname !== GatewayServerUtil.EXEC_PATH) {
|
|
294
381
|
socket.destroy();
|
|
295
382
|
return;
|
|
296
383
|
}
|
|
@@ -306,9 +393,25 @@ export class GatewayServer {
|
|
|
306
393
|
WebSocketConnection.refuse(socket, 401, 'Not authorized.');
|
|
307
394
|
return;
|
|
308
395
|
}
|
|
396
|
+
const most = this.quotas.limits(caller.tenant).connections;
|
|
397
|
+
if (most !== undefined && this.environments.connections(caller.tenant.id) >= most) {
|
|
398
|
+
WebSocketConnection.refuse(socket, 429, `At most ${most} pages of your account connect at once.`);
|
|
399
|
+
return;
|
|
400
|
+
}
|
|
309
401
|
this.tenants.update(caller.tenant.id, { lastActiveAt: Date.now() });
|
|
402
|
+
if (url.pathname === GatewayServerUtil.EXEC_PATH) {
|
|
403
|
+
// Another Ta works in this account's sandbox: it counts as a page connected, and keeps the sandbox running.
|
|
404
|
+
const blocked = GatewayServerUtil.blockedReason(this.quotas.blocked(caller.tenant));
|
|
405
|
+
if (blocked) {
|
|
406
|
+
WebSocketConnection.refuse(socket, 403, blocked);
|
|
407
|
+
return;
|
|
408
|
+
}
|
|
409
|
+
const exec = WebSocketConnection.open(socket, checked.key, head, { maxPayload: 64 * 1024 * 1024, heartbeat: 30000 });
|
|
410
|
+
new GatewayExecProxy(exec, this.environments.ensure(caller.tenant), this.environments.connect(caller.tenant.id));
|
|
411
|
+
return;
|
|
412
|
+
}
|
|
310
413
|
const connection = WebSocketConnection.open(socket, checked.key, head, { maxPayload: 32 * 1024 * 1024, heartbeat: 30000, deflate: checked.deflate });
|
|
311
|
-
const gatewaySocket = new GatewaySocket(connection, caller, this.environments, this.service);
|
|
414
|
+
const gatewaySocket = new GatewaySocket(connection, caller, this.environments, this.service, this.quotas);
|
|
312
415
|
this.sockets.add(gatewaySocket);
|
|
313
416
|
connection.onClose(() => this.sockets.delete(gatewaySocket));
|
|
314
417
|
}
|
|
@@ -1,12 +1,20 @@
|
|
|
1
1
|
import type { SignInFlow } from '@celljs/ta-host/lib/node/sign-in/sign-in-flow';
|
|
2
|
-
import { type TaAccessInfo, type TaEnvironmentChoice, TaErrorCode, type TaGatewayInfo, type TaGatewayTenant } from '@celljs/ta-protocol';
|
|
2
|
+
import { type TaAccessInfo, type TaAgentActivity, type TaEnvironmentChoice, TaErrorCode, type TaGatewayConsole, type TaGatewayInfo, type TaGatewayLimits, type TaGatewayPolicy, type TaGatewayRole, type TaGatewayTenant, type TaUsageTrend } from '@celljs/ta-protocol';
|
|
3
3
|
import type { Environments } from './environments.js';
|
|
4
|
+
import type { GatewayAudit } from './gateway-audit.js';
|
|
5
|
+
import { type GatewayPolicy } from './gateway-policy.js';
|
|
6
|
+
import type { GatewayQuotas } from './gateway-quotas.js';
|
|
7
|
+
import { type GatewayUsage } from './gateway-usage.js';
|
|
8
|
+
import { type ModelProxy } from './model-proxy.js';
|
|
9
|
+
import type { SignInLinks } from './sign-in-links.js';
|
|
4
10
|
import type { Tenant, TenantStore } from './tenant-store.js';
|
|
5
|
-
/** Who calls: the browser signed in as `account`, with the token `token
|
|
11
|
+
/** Who calls: the browser signed in as `account`, with the token `token`, and what that account is on the gateway. */
|
|
6
12
|
export interface GatewayCaller {
|
|
7
13
|
token: string;
|
|
8
14
|
account: string;
|
|
9
15
|
tenant: Tenant;
|
|
16
|
+
role: TaGatewayRole;
|
|
17
|
+
/** An owner or an admin. */
|
|
10
18
|
admin: boolean;
|
|
11
19
|
}
|
|
12
20
|
export declare class GatewayCallError extends Error {
|
|
@@ -14,45 +22,120 @@ export declare class GatewayCallError extends Error {
|
|
|
14
22
|
readonly hint: string;
|
|
15
23
|
constructor(message: string, code: TaErrorCode, hint: string);
|
|
16
24
|
}
|
|
25
|
+
/** What the console says of the gateway itself. */
|
|
26
|
+
export interface GatewayMeta {
|
|
27
|
+
links: SignInLinks;
|
|
28
|
+
startedAt: number;
|
|
29
|
+
version?: string;
|
|
30
|
+
publicUrl?: string;
|
|
31
|
+
}
|
|
32
|
+
/** The parts of the gateway its calls use. */
|
|
33
|
+
export interface GatewayParts {
|
|
34
|
+
flow: SignInFlow;
|
|
35
|
+
tenants: TenantStore;
|
|
36
|
+
environments: Environments;
|
|
37
|
+
policy: GatewayPolicy;
|
|
38
|
+
quotas: GatewayQuotas;
|
|
39
|
+
usage: GatewayUsage;
|
|
40
|
+
audit: GatewayAudit;
|
|
41
|
+
hooks: {
|
|
42
|
+
cutOff(): void;
|
|
43
|
+
reset(tenantId: string): void;
|
|
44
|
+
};
|
|
45
|
+
meta: GatewayMeta;
|
|
46
|
+
models?: ModelProxy;
|
|
47
|
+
}
|
|
48
|
+
type Need = TaGatewayRole | 'anyone';
|
|
17
49
|
export declare namespace GatewayServiceUtil {
|
|
50
|
+
const DEFAULT_LOG_LINES = 200;
|
|
51
|
+
const MAX_LOG_LINES = 2000;
|
|
52
|
+
/**
|
|
53
|
+
* Who may call each method: `anyone` signed in (about their own Ta, their own sign-ins), `admin` (owners too),
|
|
54
|
+
* `owner`. A method not here is no method. What an admin may do to another account is checked again by its role
|
|
55
|
+
* (GatewayService.manage).
|
|
56
|
+
*/
|
|
57
|
+
const RULES: Record<string, Record<string, Need>>;
|
|
58
|
+
/** What an administrator did or looked at of others: kept in the audit. */
|
|
59
|
+
const AUDITED: Set<string>;
|
|
60
|
+
function need(service: string, name: string): Need | undefined;
|
|
61
|
+
function allowed(role: TaGatewayRole, need: Need): boolean;
|
|
62
|
+
/** As many lines as asked, within bounds. */
|
|
63
|
+
function lines(value: unknown): number;
|
|
64
|
+
/** Days of a trend, 1 to 31. */
|
|
65
|
+
function days(value: unknown): number;
|
|
18
66
|
/** The services the gateway answers itself, not the Ta of the tenant. */
|
|
19
67
|
const SERVICES: string[];
|
|
20
68
|
function owns(method: unknown): method is string;
|
|
21
69
|
/** Whether the text of a message may be a call of {@link SERVICES}: those that are not are not parsed. */
|
|
22
70
|
function mayOwn(text: string): boolean;
|
|
71
|
+
/** The calls that send the agents a message, which the limit of messages a minute counts. */
|
|
72
|
+
const PROMPTS: string[];
|
|
73
|
+
function mayPrompt(text: string): boolean;
|
|
23
74
|
/** The error of a JSON-RPC answer, as ta serve sends an ApplicationError: the client reads its code and hint. */
|
|
24
75
|
function error(id: unknown, message: string, code: TaErrorCode, hint: string): string;
|
|
25
76
|
function result(id: unknown, result: unknown): string;
|
|
77
|
+
function forbidden(message: string, hint: string): GatewayCallError;
|
|
26
78
|
function choice(value: unknown, own: boolean, providers: string[]): TaEnvironmentChoice | undefined;
|
|
79
|
+
/** What the audit says of the arguments of a call: its numbers, flags and roles, never more. */
|
|
80
|
+
function detail(method: string, params: unknown[]): string | undefined;
|
|
27
81
|
}
|
|
28
82
|
/**
|
|
29
83
|
* The calls the gateway answers on the WebSocket of a browser: TaGatewayServer, and TaAccessServer, whose
|
|
30
|
-
* accounts are those that may have a tenant here
|
|
31
|
-
*
|
|
84
|
+
* accounts are those that may have a tenant here. Each method needs a role (GatewayServiceUtil.RULES); what an
|
|
85
|
+
* admin does to another account needs a role above it; what administrators do is kept in the audit.
|
|
32
86
|
*/
|
|
33
87
|
export declare class GatewayService {
|
|
34
88
|
protected readonly flow: SignInFlow;
|
|
35
89
|
protected readonly tenants: TenantStore;
|
|
36
90
|
protected readonly environments: Environments;
|
|
37
|
-
protected readonly
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
91
|
+
protected readonly policy: GatewayPolicy;
|
|
92
|
+
protected readonly quotas: GatewayQuotas;
|
|
93
|
+
protected readonly usage: GatewayUsage;
|
|
94
|
+
protected readonly audit: GatewayAudit;
|
|
95
|
+
protected readonly hooks: GatewayParts['hooks'];
|
|
96
|
+
protected readonly meta: GatewayMeta;
|
|
97
|
+
protected readonly models?: ModelProxy;
|
|
98
|
+
constructor(parts: GatewayParts);
|
|
45
99
|
call(caller: GatewayCaller, method: string, params: unknown[]): Promise<unknown>;
|
|
100
|
+
protected handle(caller: GatewayCaller, service: string, name: string, params: unknown[]): Promise<unknown>;
|
|
101
|
+
protected record(caller: GatewayCaller, action: string, params: unknown[]): void;
|
|
46
102
|
info(caller: GatewayCaller): TaGatewayInfo;
|
|
47
|
-
protected ownAllowed(): boolean;
|
|
48
103
|
protected setEnvironment(caller: GatewayCaller, value: unknown): Promise<TaGatewayInfo>;
|
|
49
104
|
protected restart(caller: GatewayCaller): Promise<TaGatewayInfo>;
|
|
50
|
-
protected
|
|
105
|
+
protected tenantInfo(tenant: Tenant): TaGatewayTenant;
|
|
106
|
+
/** 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. */
|
|
107
|
+
protected console(caller: GatewayCaller): Promise<TaGatewayConsole>;
|
|
108
|
+
protected policyView(): TaGatewayPolicy;
|
|
109
|
+
protected tenant(id: unknown): Tenant;
|
|
110
|
+
/** 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. */
|
|
111
|
+
protected manage(caller: GatewayCaller, id: unknown): Tenant;
|
|
112
|
+
protected startTenant(caller: GatewayCaller, id: unknown): Promise<void>;
|
|
51
113
|
protected stopTenant(caller: GatewayCaller, id: unknown): Promise<void>;
|
|
114
|
+
protected restartTenant(caller: GatewayCaller, id: unknown): Promise<void>;
|
|
115
|
+
/** What its sandbox wrote, its secrets hidden: tokens and keys printed by what ran there do not reach the page. */
|
|
116
|
+
protected logs(id: unknown, lines: unknown): Promise<string>;
|
|
117
|
+
protected activity(id: unknown, sessionId: unknown): Promise<TaAgentActivity[]>;
|
|
118
|
+
protected trend(daysValue: unknown, id: unknown): Promise<TaUsageTrend>;
|
|
119
|
+
protected limits(value: unknown, nullable: boolean): TaGatewayLimits;
|
|
120
|
+
protected setTenantLimits(caller: GatewayCaller, id: unknown, value: unknown): void;
|
|
121
|
+
protected grantMinutes(caller: GatewayCaller, id: unknown, minutes: unknown): void;
|
|
122
|
+
protected setSuspended(caller: GatewayCaller, id: unknown, suspended: unknown): Promise<void>;
|
|
123
|
+
protected setDefaultLimits(value: unknown): TaGatewayPolicy;
|
|
124
|
+
protected setRole(caller: GatewayCaller, account: unknown, role: unknown): TaGatewayPolicy;
|
|
125
|
+
/** A sign-in of the caller's own account, named for where it is used. */
|
|
126
|
+
protected accessToken(caller: GatewayCaller, label: unknown): {
|
|
127
|
+
token: string;
|
|
128
|
+
url?: string;
|
|
129
|
+
};
|
|
52
130
|
protected access(caller: GatewayCaller): TaAccessInfo;
|
|
53
131
|
protected allow(account: unknown, name: unknown): void;
|
|
54
132
|
/** The browsers of the account are cut off, and what reaches its Ta otherwise (paired phones) goes with its sandbox. */
|
|
55
|
-
protected disallow(account: string): Promise<void>;
|
|
133
|
+
protected disallow(caller: GatewayCaller, account: string): Promise<void>;
|
|
56
134
|
protected signOut(caller: GatewayCaller, id: string): Promise<void>;
|
|
57
|
-
|
|
135
|
+
/**
|
|
136
|
+
* 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
|
|
137
|
+
* admin's, would let whoever makes the link into another's Ta. `ta gateway link`, where the gateway runs, may.
|
|
138
|
+
*/
|
|
139
|
+
protected signInLink(account: unknown, name: unknown): string;
|
|
58
140
|
}
|
|
141
|
+
export {};
|