@celljs/ta-gateway 4.9.1 → 4.11.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/README.en.md +1 -1
- package/README.md +1 -1
- package/esm/node/docker-sandbox.js +3 -0
- package/esm/node/gateway-server.d.ts +12 -0
- package/esm/node/gateway-server.js +34 -6
- package/esm/node/gateway-socket.d.ts +1 -0
- package/esm/node/gateway-socket.js +7 -1
- package/esm/node/local-sandbox.js +16 -3
- package/esm/node/sign-in-links.js +5 -1
- package/lib/node/docker-sandbox.js +3 -0
- package/lib/node/gateway-server.d.ts +12 -0
- package/lib/node/gateway-server.js +33 -5
- package/lib/node/gateway-socket.d.ts +1 -0
- package/lib/node/gateway-socket.js +7 -1
- package/lib/node/local-sandbox.js +16 -3
- package/lib/node/sign-in-links.js +5 -1
- package/package.json +4 -4
package/README.en.md
CHANGED
|
@@ -41,7 +41,7 @@ Without the file, there is the `docker` above only.
|
|
|
41
41
|
|
|
42
42
|
| Type | What it does |
|
|
43
43
|
| --- | --- |
|
|
44
|
-
| `docker` | A container per tenant (`ta-<tenant>`), its home a volume of its own (`/home/ta`: sessions, model accounts, workspace), with limits of memory, CPU and processes (`memory` 4g, `cpus` 2, `pids` 1024 by default), in a network whose containers cannot reach each other (`network`, default `ta-sandbox`, made with icc off when missing). Its port is published on `bind` only (default 127.0.0.1): the gateway is the way in. It calls the Docker Engine API (`host`: `unix://` or `tcp://`, default `DOCKER_HOST` or `/var/run/docker.sock`): no Docker CLI needed. `env` adds to the environment of every sandbox |
|
|
44
|
+
| `docker` | A container per tenant (`ta-<tenant>`), its home a volume of its own (`/home/ta`: sessions, model accounts, workspace), with limits of memory, CPU and processes (`memory` 4g, `cpus` 2, `pids` 1024 by default), in a network whose containers cannot reach each other (`network`, default `ta-sandbox`, made with icc off when missing), without the capability `NET_RAW` (a tenant may sudo in its container: without raw sockets it cannot forge ARP to reach a neighbour on the bridge). Its port is published on `bind` only (default 127.0.0.1): the gateway is the way in. It calls the Docker Engine API (`host`: `unix://` or `tcp://`, default `DOCKER_HOST` or `/var/run/docker.sock`): no Docker CLI needed. `env` adds to the environment of every sandbox |
|
|
45
45
|
| `command` | A platform the gateway has no type for (Kubernetes, a cloud's CLI, a script of one's own), as models.json takes a compatible endpoint: `start` makes or starts the sandbox and prints the address of its Ta service last; `stop` and `state` (prints running, stopped or missing) are optional. The commands have `TA_TENANT_ID`, `TA_TENANT_ACCOUNT` and `TA_SERVE_TOKEN` (which the Ta service there must take) in their environment |
|
|
46
46
|
| `module` | A provider of the operator's, as an extension of pi: the default export of `path` (relative to the directory of the gateway) is `(id, config, context) => SandboxProvider` (`start` / `stop` / `state`, see `sandbox-provider.ts`) |
|
|
47
47
|
| `ta` | A Ta service that runs already (`url`, `token`), which the gateway neither starts nor stops. Shared by all, it isolates nothing |
|
package/README.md
CHANGED
|
@@ -41,7 +41,7 @@ ta gateway link user:alice --name Alice # 一次性登录链接(一
|
|
|
41
41
|
|
|
42
42
|
| 类型 | 做什么 |
|
|
43
43
|
| --- | --- |
|
|
44
|
-
| `docker` | 每个租户一个容器(`ta-<租户>`),家目录是它自己的卷(`/home/ta`:会话、模型账号、工作区),限制内存、CPU、进程数(`memory` 默认 4g、`cpus` 默认 2、`pids` 默认 1024),放在容器之间互不相通的网络里(`network`,默认 `ta-sandbox`,不存在时创建并关闭 icc
|
|
44
|
+
| `docker` | 每个租户一个容器(`ta-<租户>`),家目录是它自己的卷(`/home/ta`:会话、模型账号、工作区),限制内存、CPU、进程数(`memory` 默认 4g、`cpus` 默认 2、`pids` 默认 1024),放在容器之间互不相通的网络里(`network`,默认 `ta-sandbox`,不存在时创建并关闭 icc),并去掉 `NET_RAW` 能力(容器里能 sudo,没有原始套接字就伪造不了 ARP 去够同一网桥上的邻居)。端口只发布在 `bind`(默认 127.0.0.1)上,网关是唯一入口。直接调用 Docker Engine API(`host`:`unix://` 或 `tcp://`,默认 `DOCKER_HOST` 或 `/var/run/docker.sock`),网关不需要 Docker 命令行。`env` 给每个沙箱加环境变量 |
|
|
45
45
|
| `command` | 网关没有对应类型的平台(Kubernetes、各家云的命令行、自己的脚本),像 models.json 接一个兼容的端点:`start` 创建或启动沙箱,并把它的 Ta 服务地址打印在最后一行;`stop`、`state`(打印 running / stopped / missing)可选。命令的环境里有 `TA_TENANT_ID`、`TA_TENANT_ACCOUNT`、`TA_SERVE_TOKEN`(沙箱里的 Ta 服务必须用它) |
|
|
46
46
|
| `module` | 运营方自己的提供方,像 pi 的扩展:`path`(相对网关目录)的默认导出是 `(id, config, context) => SandboxProvider`(`start` / `stop` / `state`,见 `sandbox-provider.ts`) |
|
|
47
47
|
| `ta` | 一个已经在运行的 Ta 服务(`url`、`token`),网关不启动也不停止它。所有人共用时没有隔离 |
|
|
@@ -98,6 +98,9 @@ export class DockerSandbox {
|
|
|
98
98
|
Memory: this.options.memory,
|
|
99
99
|
NanoCpus: this.options.cpus ? Math.round(this.options.cpus * 1e9) : undefined,
|
|
100
100
|
PidsLimit: this.options.pids,
|
|
101
|
+
// A tenant is root in its container (sudo): without raw sockets it cannot forge the packets
|
|
102
|
+
// (ARP) by which a neighbour on the bridge would be reached despite icc off.
|
|
103
|
+
CapDrop: ['NET_RAW'],
|
|
101
104
|
RestartPolicy: { Name: 'unless-stopped' },
|
|
102
105
|
Init: false,
|
|
103
106
|
},
|
|
@@ -23,6 +23,17 @@ export interface GatewayServerOptions {
|
|
|
23
23
|
export declare namespace GatewayServerUtil {
|
|
24
24
|
/** A file of `root` for a path of the page, never outside it; the page for what is not a file. */
|
|
25
25
|
function file(root: string, urlPath: string): string;
|
|
26
|
+
/**
|
|
27
|
+
* Where a request of `/api/files` goes in the Ta of its tenant: undefined for one whose path, once its dots
|
|
28
|
+
* are resolved (`/api/files/../../x`, `%2e%2e`), is not of `/api/files` there, which would reach any
|
|
29
|
+
* path of that address, and of any address a tenant names as its own Ta service.
|
|
30
|
+
*/
|
|
31
|
+
function filesTarget(requestUrl: string, endpoint: string): URL | undefined;
|
|
32
|
+
/**
|
|
33
|
+
* The headers of an answer of the Ta of a tenant, as the browser gets them: without cookies, which a Ta
|
|
34
|
+
* service of the user's (or what runs in a sandbox) would otherwise set on the gateway's origin.
|
|
35
|
+
*/
|
|
36
|
+
function filesHeaders(headers: IncomingMessage['headers']): IncomingMessage['headers'];
|
|
26
37
|
}
|
|
27
38
|
/**
|
|
28
39
|
* `ta gateway`: one sign-in for many people, each with a Ta of their own. An account that signs in is a
|
|
@@ -59,6 +70,7 @@ export declare class GatewayServer {
|
|
|
59
70
|
/** A link of `ta gateway link`: lets its account in, and signs this browser in as it. */
|
|
60
71
|
protected useLink(request: IncomingMessage, response: ServerResponse, secret: string): void;
|
|
61
72
|
protected signedIn(response: ServerResponse, token: string, account: SignInAccount, origin: string): void;
|
|
73
|
+
/** As the pages of signing in read it: behind a proxy of TLS, its X-Forwarded-Proto makes the cookie Secure. */
|
|
62
74
|
protected origin(request: IncomingMessage): string;
|
|
63
75
|
/** `/api/files` of the Ta of the tenant whose cookie came along. */
|
|
64
76
|
protected files(request: IncomingMessage, response: ServerResponse): Promise<void>;
|
|
@@ -5,7 +5,7 @@ import { extname, join, normalize, sep } from 'node:path';
|
|
|
5
5
|
import { pipeline } from 'node:stream';
|
|
6
6
|
import { WebSocketConnection } from '@celljs/rpc/lib/node/websocket/websocket-connection';
|
|
7
7
|
import { AccessStore, AccessUtil } from '@celljs/ta-host/lib/node/sign-in/access-store';
|
|
8
|
-
import { SignInFlow } from '@celljs/ta-host/lib/node/sign-in/sign-in-flow';
|
|
8
|
+
import { SignInFlow, SignInUtil } from '@celljs/ta-host/lib/node/sign-in/sign-in-flow';
|
|
9
9
|
import { SignInPages, SignInPageUtil } from '@celljs/ta-host/lib/node/sign-in/sign-in-pages';
|
|
10
10
|
import { SignInProviders } from '@celljs/ta-host/lib/node/sign-in/sign-in-provider';
|
|
11
11
|
import { TA_FILES_PATH, TA_WEBSOCKET_PATH } from '@celljs/ta-protocol';
|
|
@@ -60,6 +60,25 @@ export var GatewayServerUtil;
|
|
|
60
60
|
return join(root, 'index.html');
|
|
61
61
|
}
|
|
62
62
|
GatewayServerUtil.file = file;
|
|
63
|
+
/**
|
|
64
|
+
* Where a request of `/api/files` goes in the Ta of its tenant: undefined for one whose path, once its dots
|
|
65
|
+
* are resolved (`/api/files/../../x`, `%2e%2e`), is not of `/api/files` there, which would reach any
|
|
66
|
+
* path of that address, and of any address a tenant names as its own Ta service.
|
|
67
|
+
*/
|
|
68
|
+
function filesTarget(requestUrl, endpoint) {
|
|
69
|
+
const target = new URL(requestUrl, endpoint);
|
|
70
|
+
return target.origin === new URL(endpoint).origin && target.pathname.startsWith(`${TA_FILES_PATH}/`) ? target : undefined;
|
|
71
|
+
}
|
|
72
|
+
GatewayServerUtil.filesTarget = filesTarget;
|
|
73
|
+
/**
|
|
74
|
+
* The headers of an answer of the Ta of a tenant, as the browser gets them: without cookies, which a Ta
|
|
75
|
+
* service of the user's (or what runs in a sandbox) would otherwise set on the gateway's origin.
|
|
76
|
+
*/
|
|
77
|
+
function filesHeaders(headers) {
|
|
78
|
+
const { 'set-cookie': _cookies, ...rest } = headers;
|
|
79
|
+
return rest;
|
|
80
|
+
}
|
|
81
|
+
GatewayServerUtil.filesHeaders = filesHeaders;
|
|
63
82
|
})(GatewayServerUtil || (GatewayServerUtil = {}));
|
|
64
83
|
/**
|
|
65
84
|
* `ta gateway`: one sign-in for many people, each with a Ta of their own. An account that signs in is a
|
|
@@ -203,20 +222,29 @@ export class GatewayServer {
|
|
|
203
222
|
const list = Array.isArray(cookies) ? cookies : cookies ? [String(cookies)] : [];
|
|
204
223
|
response.setHeader('Set-Cookie', [...list, `${FILES_COOKIE}=${token}; Path=${TA_FILES_PATH}; Max-Age=31536000; HttpOnly; SameSite=Lax${secure}`]);
|
|
205
224
|
}
|
|
225
|
+
/** As the pages of signing in read it: behind a proxy of TLS, its X-Forwarded-Proto makes the cookie Secure. */
|
|
206
226
|
origin(request) {
|
|
207
|
-
|
|
208
|
-
return (_a = this.flow.publicUrl) !== null && _a !== void 0 ? _a : `http://${request.headers.host}`;
|
|
227
|
+
return SignInUtil.origin(request, this.flow.publicUrl);
|
|
209
228
|
}
|
|
210
229
|
/** `/api/files` of the Ta of the tenant whose cookie came along. */
|
|
211
230
|
async files(request, response) {
|
|
212
231
|
var _a, _b;
|
|
232
|
+
if (request.method !== 'GET' && request.method !== 'HEAD') {
|
|
233
|
+
response.setHeader('Allow', 'GET, HEAD');
|
|
234
|
+
SignInPageUtil.end(response, 405);
|
|
235
|
+
return;
|
|
236
|
+
}
|
|
213
237
|
const caller = this.caller((_a = SignInPageUtil.cookie(request.headers.cookie, FILES_COOKIE)) !== null && _a !== void 0 ? _a : '');
|
|
214
238
|
if (!caller) {
|
|
215
239
|
SignInPageUtil.end(response, 404);
|
|
216
240
|
return;
|
|
217
241
|
}
|
|
218
242
|
const endpoint = await this.environments.ensure(caller.tenant);
|
|
219
|
-
const target =
|
|
243
|
+
const target = GatewayServerUtil.filesTarget((_b = request.url) !== null && _b !== void 0 ? _b : '/', endpoint.url);
|
|
244
|
+
if (!target) {
|
|
245
|
+
SignInPageUtil.end(response, 404);
|
|
246
|
+
return;
|
|
247
|
+
}
|
|
220
248
|
const headers = {};
|
|
221
249
|
for (const name of ['range', 'if-none-match', 'accept', 'accept-encoding', 'user-agent']) {
|
|
222
250
|
const value = request.headers[name];
|
|
@@ -228,7 +256,7 @@ export class GatewayServer {
|
|
|
228
256
|
const send = target.protocol === 'https:' ? httpsRequest : httpRequest;
|
|
229
257
|
const outgoing = send(target, { method: request.method, headers }, incoming => {
|
|
230
258
|
var _a;
|
|
231
|
-
response.writeHead((_a = incoming.statusCode) !== null && _a !== void 0 ? _a : 502, incoming.headers);
|
|
259
|
+
response.writeHead((_a = incoming.statusCode) !== null && _a !== void 0 ? _a : 502, GatewayServerUtil.filesHeaders(incoming.headers));
|
|
232
260
|
// A browser that stops reading (a video seeking) closes the request to the Ta of the tenant too.
|
|
233
261
|
pipeline(incoming, response, () => resolve());
|
|
234
262
|
});
|
|
@@ -279,7 +307,7 @@ export class GatewayServer {
|
|
|
279
307
|
return;
|
|
280
308
|
}
|
|
281
309
|
this.tenants.update(caller.tenant.id, { lastActiveAt: Date.now() });
|
|
282
|
-
const connection = WebSocketConnection.open(socket, checked.key, head, { maxPayload: 32 * 1024 * 1024, heartbeat: 30000 });
|
|
310
|
+
const connection = WebSocketConnection.open(socket, checked.key, head, { maxPayload: 32 * 1024 * 1024, heartbeat: 30000, deflate: checked.deflate });
|
|
283
311
|
const gatewaySocket = new GatewaySocket(connection, caller, this.environments, this.service);
|
|
284
312
|
this.sockets.add(gatewaySocket);
|
|
285
313
|
connection.onClose(() => this.sockets.delete(gatewaySocket));
|
|
@@ -14,6 +14,7 @@ export declare class GatewaySocket {
|
|
|
14
14
|
protected readonly service: GatewayService;
|
|
15
15
|
protected inner?: WebSocket;
|
|
16
16
|
protected readonly queued: string[];
|
|
17
|
+
protected queuedBytes: number;
|
|
17
18
|
protected failure?: string;
|
|
18
19
|
protected closed: boolean;
|
|
19
20
|
/** Calls of the gateway being answered: a change of environment stops the one this socket is on meanwhile. */
|
|
@@ -2,6 +2,8 @@ import { TA_WEBSOCKET_PATH, TaErrorCode } from '@celljs/ta-protocol';
|
|
|
2
2
|
import { GatewayCallError, GatewayServiceUtil } from './gateway-service.js';
|
|
3
3
|
/** What a browser sends before the Ta of its tenant answers, at most: then it is cut off, to connect again. */
|
|
4
4
|
const MAX_QUEUED = 256;
|
|
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
|
+
const MAX_QUEUED_BYTES = 16 * 1024 * 1024;
|
|
5
7
|
/**
|
|
6
8
|
* One browser's WebSocket: the calls of the gateway's services answered here, everything else forwarded to
|
|
7
9
|
* the Ta of its tenant, whose token only the gateway has, and back. Until that Ta answers, what the browser
|
|
@@ -15,6 +17,7 @@ export class GatewaySocket {
|
|
|
15
17
|
this.environments = environments;
|
|
16
18
|
this.service = service;
|
|
17
19
|
this.queued = [];
|
|
20
|
+
this.queuedBytes = 0;
|
|
18
21
|
this.closed = false;
|
|
19
22
|
/** Calls of the gateway being answered: a change of environment stops the one this socket is on meanwhile. */
|
|
20
23
|
this.answering = 0;
|
|
@@ -47,6 +50,7 @@ export class GatewaySocket {
|
|
|
47
50
|
const inner = new WebSocket(url);
|
|
48
51
|
this.inner = inner;
|
|
49
52
|
inner.onopen = () => {
|
|
53
|
+
this.queuedBytes = 0;
|
|
50
54
|
for (const text of this.queued.splice(0)) {
|
|
51
55
|
inner.send(text);
|
|
52
56
|
}
|
|
@@ -98,8 +102,9 @@ export class GatewaySocket {
|
|
|
98
102
|
if (((_a = this.inner) === null || _a === void 0 ? void 0 : _a.readyState) === WebSocket.OPEN) {
|
|
99
103
|
this.inner.send(text);
|
|
100
104
|
}
|
|
101
|
-
else if (this.queued.length < MAX_QUEUED) {
|
|
105
|
+
else if (this.queued.length < MAX_QUEUED && this.queuedBytes + text.length <= MAX_QUEUED_BYTES) {
|
|
102
106
|
this.queued.push(text);
|
|
107
|
+
this.queuedBytes += text.length;
|
|
103
108
|
}
|
|
104
109
|
else {
|
|
105
110
|
this.close(1013, 'The environment is still starting.');
|
|
@@ -126,6 +131,7 @@ export class GatewaySocket {
|
|
|
126
131
|
/** The calls that wait, and those to come, fail; those of the gateway still work. */
|
|
127
132
|
fail(reason) {
|
|
128
133
|
this.failure = reason;
|
|
134
|
+
this.queuedBytes = 0;
|
|
129
135
|
for (const text of this.queued.splice(0)) {
|
|
130
136
|
this.fromBrowser(text);
|
|
131
137
|
}
|
|
@@ -3,6 +3,8 @@ import { mkdirSync } from 'node:fs';
|
|
|
3
3
|
import { createServer } from 'node:net';
|
|
4
4
|
import { join } from 'node:path';
|
|
5
5
|
import { SandboxProviders } from './sandbox-provider.js';
|
|
6
|
+
/** How long a ta serve has to end on SIGTERM before it is killed. */
|
|
7
|
+
const STOP_TIMEOUT_MS = 10000;
|
|
6
8
|
/**
|
|
7
9
|
* `local`: a `ta serve` process per tenant on the machine of the gateway, its agent directory and workspace
|
|
8
10
|
* under `<gateway>/local/<tenant>`. Not a sandbox: every tenant runs as the user of the gateway and can read
|
|
@@ -34,13 +36,19 @@ export class LocalSandbox {
|
|
|
34
36
|
stdio: 'ignore',
|
|
35
37
|
});
|
|
36
38
|
const url = `http://127.0.0.1:${port}`;
|
|
37
|
-
this
|
|
38
|
-
|
|
39
|
+
// A command that cannot start fails this tenant's start (nothing answers), not the gateway.
|
|
40
|
+
const gone = () => {
|
|
39
41
|
var _a;
|
|
40
42
|
if (((_a = this.running.get(tenant.id)) === null || _a === void 0 ? void 0 : _a.child) === child) {
|
|
41
43
|
this.running.delete(tenant.id);
|
|
42
44
|
}
|
|
45
|
+
};
|
|
46
|
+
child.once('error', error => {
|
|
47
|
+
console.warn(`ta gateway: the local sandbox of ${tenant.id} did not start: ${error.message}`);
|
|
48
|
+
gone();
|
|
43
49
|
});
|
|
50
|
+
this.running.set(tenant.id, { child, url });
|
|
51
|
+
child.once('exit', gone);
|
|
44
52
|
return { url, token: tenant.token };
|
|
45
53
|
}
|
|
46
54
|
async stop(tenant) {
|
|
@@ -48,7 +56,12 @@ export class LocalSandbox {
|
|
|
48
56
|
this.running.delete(tenant.id);
|
|
49
57
|
if (running && running.child.exitCode === null) {
|
|
50
58
|
await new Promise(done => {
|
|
51
|
-
|
|
59
|
+
// A ta serve that does not end on SIGTERM would hold the stop, and the gateway's close, for good.
|
|
60
|
+
const kill = setTimeout(() => running.child.kill('SIGKILL'), STOP_TIMEOUT_MS);
|
|
61
|
+
running.child.once('exit', () => {
|
|
62
|
+
clearTimeout(kill);
|
|
63
|
+
done();
|
|
64
|
+
});
|
|
52
65
|
running.child.kill('SIGTERM');
|
|
53
66
|
});
|
|
54
67
|
}
|
|
@@ -28,7 +28,11 @@ export class SignInLinks {
|
|
|
28
28
|
use(secret, now = Date.now()) {
|
|
29
29
|
const links = this.read(now);
|
|
30
30
|
const link = links.find(one => one.hash === hash(secret));
|
|
31
|
-
|
|
31
|
+
// Written only when a link was used: a request with a wrong secret, which anyone can send, writes nothing,
|
|
32
|
+
// and does not race `ta gateway link` writing the file from another process.
|
|
33
|
+
if (link) {
|
|
34
|
+
writePrivate(this.file, links.filter(one => one !== link));
|
|
35
|
+
}
|
|
32
36
|
return link && { account: link.account, name: link.name };
|
|
33
37
|
}
|
|
34
38
|
read(now) {
|
|
@@ -101,6 +101,9 @@ class DockerSandbox {
|
|
|
101
101
|
Memory: this.options.memory,
|
|
102
102
|
NanoCpus: this.options.cpus ? Math.round(this.options.cpus * 1e9) : undefined,
|
|
103
103
|
PidsLimit: this.options.pids,
|
|
104
|
+
// A tenant is root in its container (sudo): without raw sockets it cannot forge the packets
|
|
105
|
+
// (ARP) by which a neighbour on the bridge would be reached despite icc off.
|
|
106
|
+
CapDrop: ['NET_RAW'],
|
|
104
107
|
RestartPolicy: { Name: 'unless-stopped' },
|
|
105
108
|
Init: false,
|
|
106
109
|
},
|
|
@@ -23,6 +23,17 @@ export interface GatewayServerOptions {
|
|
|
23
23
|
export declare namespace GatewayServerUtil {
|
|
24
24
|
/** A file of `root` for a path of the page, never outside it; the page for what is not a file. */
|
|
25
25
|
function file(root: string, urlPath: string): string;
|
|
26
|
+
/**
|
|
27
|
+
* Where a request of `/api/files` goes in the Ta of its tenant: undefined for one whose path, once its dots
|
|
28
|
+
* are resolved (`/api/files/../../x`, `%2e%2e`), is not of `/api/files` there, which would reach any
|
|
29
|
+
* path of that address, and of any address a tenant names as its own Ta service.
|
|
30
|
+
*/
|
|
31
|
+
function filesTarget(requestUrl: string, endpoint: string): URL | undefined;
|
|
32
|
+
/**
|
|
33
|
+
* The headers of an answer of the Ta of a tenant, as the browser gets them: without cookies, which a Ta
|
|
34
|
+
* service of the user's (or what runs in a sandbox) would otherwise set on the gateway's origin.
|
|
35
|
+
*/
|
|
36
|
+
function filesHeaders(headers: IncomingMessage['headers']): IncomingMessage['headers'];
|
|
26
37
|
}
|
|
27
38
|
/**
|
|
28
39
|
* `ta gateway`: one sign-in for many people, each with a Ta of their own. An account that signs in is a
|
|
@@ -59,6 +70,7 @@ export declare class GatewayServer {
|
|
|
59
70
|
/** A link of `ta gateway link`: lets its account in, and signs this browser in as it. */
|
|
60
71
|
protected useLink(request: IncomingMessage, response: ServerResponse, secret: string): void;
|
|
61
72
|
protected signedIn(response: ServerResponse, token: string, account: SignInAccount, origin: string): void;
|
|
73
|
+
/** As the pages of signing in read it: behind a proxy of TLS, its X-Forwarded-Proto makes the cookie Secure. */
|
|
62
74
|
protected origin(request: IncomingMessage): string;
|
|
63
75
|
/** `/api/files` of the Ta of the tenant whose cookie came along. */
|
|
64
76
|
protected files(request: IncomingMessage, response: ServerResponse): Promise<void>;
|
|
@@ -63,6 +63,25 @@ var GatewayServerUtil;
|
|
|
63
63
|
return (0, node_path_1.join)(root, 'index.html');
|
|
64
64
|
}
|
|
65
65
|
GatewayServerUtil.file = file;
|
|
66
|
+
/**
|
|
67
|
+
* Where a request of `/api/files` goes in the Ta of its tenant: undefined for one whose path, once its dots
|
|
68
|
+
* are resolved (`/api/files/../../x`, `%2e%2e`), is not of `/api/files` there, which would reach any
|
|
69
|
+
* path of that address, and of any address a tenant names as its own Ta service.
|
|
70
|
+
*/
|
|
71
|
+
function filesTarget(requestUrl, endpoint) {
|
|
72
|
+
const target = new URL(requestUrl, endpoint);
|
|
73
|
+
return target.origin === new URL(endpoint).origin && target.pathname.startsWith(`${ta_protocol_1.TA_FILES_PATH}/`) ? target : undefined;
|
|
74
|
+
}
|
|
75
|
+
GatewayServerUtil.filesTarget = filesTarget;
|
|
76
|
+
/**
|
|
77
|
+
* The headers of an answer of the Ta of a tenant, as the browser gets them: without cookies, which a Ta
|
|
78
|
+
* service of the user's (or what runs in a sandbox) would otherwise set on the gateway's origin.
|
|
79
|
+
*/
|
|
80
|
+
function filesHeaders(headers) {
|
|
81
|
+
const { 'set-cookie': _cookies, ...rest } = headers;
|
|
82
|
+
return rest;
|
|
83
|
+
}
|
|
84
|
+
GatewayServerUtil.filesHeaders = filesHeaders;
|
|
66
85
|
})(GatewayServerUtil || (exports.GatewayServerUtil = GatewayServerUtil = {}));
|
|
67
86
|
/**
|
|
68
87
|
* `ta gateway`: one sign-in for many people, each with a Ta of their own. An account that signs in is a
|
|
@@ -206,20 +225,29 @@ class GatewayServer {
|
|
|
206
225
|
const list = Array.isArray(cookies) ? cookies : cookies ? [String(cookies)] : [];
|
|
207
226
|
response.setHeader('Set-Cookie', [...list, `${FILES_COOKIE}=${token}; Path=${ta_protocol_1.TA_FILES_PATH}; Max-Age=31536000; HttpOnly; SameSite=Lax${secure}`]);
|
|
208
227
|
}
|
|
228
|
+
/** As the pages of signing in read it: behind a proxy of TLS, its X-Forwarded-Proto makes the cookie Secure. */
|
|
209
229
|
origin(request) {
|
|
210
|
-
|
|
211
|
-
return (_a = this.flow.publicUrl) !== null && _a !== void 0 ? _a : `http://${request.headers.host}`;
|
|
230
|
+
return sign_in_flow_1.SignInUtil.origin(request, this.flow.publicUrl);
|
|
212
231
|
}
|
|
213
232
|
/** `/api/files` of the Ta of the tenant whose cookie came along. */
|
|
214
233
|
async files(request, response) {
|
|
215
234
|
var _a, _b;
|
|
235
|
+
if (request.method !== 'GET' && request.method !== 'HEAD') {
|
|
236
|
+
response.setHeader('Allow', 'GET, HEAD');
|
|
237
|
+
sign_in_pages_1.SignInPageUtil.end(response, 405);
|
|
238
|
+
return;
|
|
239
|
+
}
|
|
216
240
|
const caller = this.caller((_a = sign_in_pages_1.SignInPageUtil.cookie(request.headers.cookie, FILES_COOKIE)) !== null && _a !== void 0 ? _a : '');
|
|
217
241
|
if (!caller) {
|
|
218
242
|
sign_in_pages_1.SignInPageUtil.end(response, 404);
|
|
219
243
|
return;
|
|
220
244
|
}
|
|
221
245
|
const endpoint = await this.environments.ensure(caller.tenant);
|
|
222
|
-
const target =
|
|
246
|
+
const target = GatewayServerUtil.filesTarget((_b = request.url) !== null && _b !== void 0 ? _b : '/', endpoint.url);
|
|
247
|
+
if (!target) {
|
|
248
|
+
sign_in_pages_1.SignInPageUtil.end(response, 404);
|
|
249
|
+
return;
|
|
250
|
+
}
|
|
223
251
|
const headers = {};
|
|
224
252
|
for (const name of ['range', 'if-none-match', 'accept', 'accept-encoding', 'user-agent']) {
|
|
225
253
|
const value = request.headers[name];
|
|
@@ -231,7 +259,7 @@ class GatewayServer {
|
|
|
231
259
|
const send = target.protocol === 'https:' ? node_https_1.request : node_http_1.request;
|
|
232
260
|
const outgoing = send(target, { method: request.method, headers }, incoming => {
|
|
233
261
|
var _a;
|
|
234
|
-
response.writeHead((_a = incoming.statusCode) !== null && _a !== void 0 ? _a : 502, incoming.headers);
|
|
262
|
+
response.writeHead((_a = incoming.statusCode) !== null && _a !== void 0 ? _a : 502, GatewayServerUtil.filesHeaders(incoming.headers));
|
|
235
263
|
// A browser that stops reading (a video seeking) closes the request to the Ta of the tenant too.
|
|
236
264
|
(0, node_stream_1.pipeline)(incoming, response, () => resolve());
|
|
237
265
|
});
|
|
@@ -282,7 +310,7 @@ class GatewayServer {
|
|
|
282
310
|
return;
|
|
283
311
|
}
|
|
284
312
|
this.tenants.update(caller.tenant.id, { lastActiveAt: Date.now() });
|
|
285
|
-
const connection = websocket_connection_1.WebSocketConnection.open(socket, checked.key, head, { maxPayload: 32 * 1024 * 1024, heartbeat: 30000 });
|
|
313
|
+
const connection = websocket_connection_1.WebSocketConnection.open(socket, checked.key, head, { maxPayload: 32 * 1024 * 1024, heartbeat: 30000, deflate: checked.deflate });
|
|
286
314
|
const gatewaySocket = new gateway_socket_1.GatewaySocket(connection, caller, this.environments, this.service);
|
|
287
315
|
this.sockets.add(gatewaySocket);
|
|
288
316
|
connection.onClose(() => this.sockets.delete(gatewaySocket));
|
|
@@ -14,6 +14,7 @@ export declare class GatewaySocket {
|
|
|
14
14
|
protected readonly service: GatewayService;
|
|
15
15
|
protected inner?: WebSocket;
|
|
16
16
|
protected readonly queued: string[];
|
|
17
|
+
protected queuedBytes: number;
|
|
17
18
|
protected failure?: string;
|
|
18
19
|
protected closed: boolean;
|
|
19
20
|
/** Calls of the gateway being answered: a change of environment stops the one this socket is on meanwhile. */
|
|
@@ -5,6 +5,8 @@ const ta_protocol_1 = require("@celljs/ta-protocol");
|
|
|
5
5
|
const gateway_service_1 = require("./gateway-service");
|
|
6
6
|
/** What a browser sends before the Ta of its tenant answers, at most: then it is cut off, to connect again. */
|
|
7
7
|
const MAX_QUEUED = 256;
|
|
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
|
+
const MAX_QUEUED_BYTES = 16 * 1024 * 1024;
|
|
8
10
|
/**
|
|
9
11
|
* One browser's WebSocket: the calls of the gateway's services answered here, everything else forwarded to
|
|
10
12
|
* the Ta of its tenant, whose token only the gateway has, and back. Until that Ta answers, what the browser
|
|
@@ -18,6 +20,7 @@ class GatewaySocket {
|
|
|
18
20
|
this.environments = environments;
|
|
19
21
|
this.service = service;
|
|
20
22
|
this.queued = [];
|
|
23
|
+
this.queuedBytes = 0;
|
|
21
24
|
this.closed = false;
|
|
22
25
|
/** Calls of the gateway being answered: a change of environment stops the one this socket is on meanwhile. */
|
|
23
26
|
this.answering = 0;
|
|
@@ -50,6 +53,7 @@ class GatewaySocket {
|
|
|
50
53
|
const inner = new WebSocket(url);
|
|
51
54
|
this.inner = inner;
|
|
52
55
|
inner.onopen = () => {
|
|
56
|
+
this.queuedBytes = 0;
|
|
53
57
|
for (const text of this.queued.splice(0)) {
|
|
54
58
|
inner.send(text);
|
|
55
59
|
}
|
|
@@ -101,8 +105,9 @@ class GatewaySocket {
|
|
|
101
105
|
if (((_a = this.inner) === null || _a === void 0 ? void 0 : _a.readyState) === WebSocket.OPEN) {
|
|
102
106
|
this.inner.send(text);
|
|
103
107
|
}
|
|
104
|
-
else if (this.queued.length < MAX_QUEUED) {
|
|
108
|
+
else if (this.queued.length < MAX_QUEUED && this.queuedBytes + text.length <= MAX_QUEUED_BYTES) {
|
|
105
109
|
this.queued.push(text);
|
|
110
|
+
this.queuedBytes += text.length;
|
|
106
111
|
}
|
|
107
112
|
else {
|
|
108
113
|
this.close(1013, 'The environment is still starting.');
|
|
@@ -129,6 +134,7 @@ class GatewaySocket {
|
|
|
129
134
|
/** The calls that wait, and those to come, fail; those of the gateway still work. */
|
|
130
135
|
fail(reason) {
|
|
131
136
|
this.failure = reason;
|
|
137
|
+
this.queuedBytes = 0;
|
|
132
138
|
for (const text of this.queued.splice(0)) {
|
|
133
139
|
this.fromBrowser(text);
|
|
134
140
|
}
|
|
@@ -6,6 +6,8 @@ const node_fs_1 = require("node:fs");
|
|
|
6
6
|
const node_net_1 = require("node:net");
|
|
7
7
|
const node_path_1 = require("node:path");
|
|
8
8
|
const sandbox_provider_1 = require("./sandbox-provider");
|
|
9
|
+
/** How long a ta serve has to end on SIGTERM before it is killed. */
|
|
10
|
+
const STOP_TIMEOUT_MS = 10000;
|
|
9
11
|
/**
|
|
10
12
|
* `local`: a `ta serve` process per tenant on the machine of the gateway, its agent directory and workspace
|
|
11
13
|
* under `<gateway>/local/<tenant>`. Not a sandbox: every tenant runs as the user of the gateway and can read
|
|
@@ -37,13 +39,19 @@ class LocalSandbox {
|
|
|
37
39
|
stdio: 'ignore',
|
|
38
40
|
});
|
|
39
41
|
const url = `http://127.0.0.1:${port}`;
|
|
40
|
-
this
|
|
41
|
-
|
|
42
|
+
// A command that cannot start fails this tenant's start (nothing answers), not the gateway.
|
|
43
|
+
const gone = () => {
|
|
42
44
|
var _a;
|
|
43
45
|
if (((_a = this.running.get(tenant.id)) === null || _a === void 0 ? void 0 : _a.child) === child) {
|
|
44
46
|
this.running.delete(tenant.id);
|
|
45
47
|
}
|
|
48
|
+
};
|
|
49
|
+
child.once('error', error => {
|
|
50
|
+
console.warn(`ta gateway: the local sandbox of ${tenant.id} did not start: ${error.message}`);
|
|
51
|
+
gone();
|
|
46
52
|
});
|
|
53
|
+
this.running.set(tenant.id, { child, url });
|
|
54
|
+
child.once('exit', gone);
|
|
47
55
|
return { url, token: tenant.token };
|
|
48
56
|
}
|
|
49
57
|
async stop(tenant) {
|
|
@@ -51,7 +59,12 @@ class LocalSandbox {
|
|
|
51
59
|
this.running.delete(tenant.id);
|
|
52
60
|
if (running && running.child.exitCode === null) {
|
|
53
61
|
await new Promise(done => {
|
|
54
|
-
|
|
62
|
+
// A ta serve that does not end on SIGTERM would hold the stop, and the gateway's close, for good.
|
|
63
|
+
const kill = setTimeout(() => running.child.kill('SIGKILL'), STOP_TIMEOUT_MS);
|
|
64
|
+
running.child.once('exit', () => {
|
|
65
|
+
clearTimeout(kill);
|
|
66
|
+
done();
|
|
67
|
+
});
|
|
55
68
|
running.child.kill('SIGTERM');
|
|
56
69
|
});
|
|
57
70
|
}
|
|
@@ -31,7 +31,11 @@ class SignInLinks {
|
|
|
31
31
|
use(secret, now = Date.now()) {
|
|
32
32
|
const links = this.read(now);
|
|
33
33
|
const link = links.find(one => one.hash === hash(secret));
|
|
34
|
-
|
|
34
|
+
// Written only when a link was used: a request with a wrong secret, which anyone can send, writes nothing,
|
|
35
|
+
// and does not race `ta gateway link` writing the file from another process.
|
|
36
|
+
if (link) {
|
|
37
|
+
(0, tenant_store_1.writePrivate)(this.file, links.filter(one => one !== link));
|
|
38
|
+
}
|
|
35
39
|
return link && { account: link.account, name: link.name };
|
|
36
40
|
}
|
|
37
41
|
read(now) {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@celljs/ta-gateway",
|
|
3
|
-
"version": "4.
|
|
3
|
+
"version": "4.11.0",
|
|
4
4
|
"description": "ta gateway: one Ta per account, each in a sandbox of its own, behind one sign-in",
|
|
5
5
|
"homepage": "https://github.com/cellbang/cell",
|
|
6
6
|
"bugs": {
|
|
@@ -29,9 +29,9 @@
|
|
|
29
29
|
"watch": "tsc -b -w --preserveWatchOutput"
|
|
30
30
|
},
|
|
31
31
|
"dependencies": {
|
|
32
|
-
"@celljs/rpc": "4.
|
|
33
|
-
"@celljs/ta-host": "4.
|
|
34
|
-
"@celljs/ta-protocol": "4.
|
|
32
|
+
"@celljs/rpc": "4.11.0",
|
|
33
|
+
"@celljs/ta-host": "4.11.0",
|
|
34
|
+
"@celljs/ta-protocol": "4.11.0"
|
|
35
35
|
},
|
|
36
36
|
"publishConfig": {
|
|
37
37
|
"access": "public"
|