@celljs/ta-gateway 4.9.0 → 4.10.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 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)。端口只发布在 `bind`(默认 127.0.0.1)上,网关是唯一入口。直接调用 Docker Engine API(`host`:`unix://` 或 `tcp://`,默认 `DOCKER_HOST` 或 `/var/run/docker.sock`),网关不需要 Docker 命令行。`env` 给每个沙箱加环境变量 |
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
  },
@@ -215,7 +215,8 @@ export class Environments {
215
215
  const next = this.tenants.update(tenant.id, { environment: choice });
216
216
  // What is picked must be there: an id of none throws here, not on the next start.
217
217
  this.provider(next);
218
- this.running.delete(tenant.id);
218
+ // The state stays: the connections it counts close and open again, and release it as they do.
219
+ Object.assign(this.state(tenant.id), { status: 'stopped', endpoint: undefined, error: undefined });
219
220
  return next;
220
221
  }
221
222
  async dispose() {
@@ -1,5 +1,5 @@
1
1
  import { type IncomingMessage, type Server, type ServerResponse } from 'node:http';
2
- import type { Duplex } from 'node:stream';
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
5
  import { Environments } from './environments.js';
@@ -23,6 +23,12 @@ 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;
26
32
  }
27
33
  /**
28
34
  * `ta gateway`: one sign-in for many people, each with a Ta of their own. An account that signs in is a
@@ -59,6 +65,7 @@ export declare class GatewayServer {
59
65
  /** A link of `ta gateway link`: lets its account in, and signs this browser in as it. */
60
66
  protected useLink(request: IncomingMessage, response: ServerResponse, secret: string): void;
61
67
  protected signedIn(response: ServerResponse, token: string, account: SignInAccount, origin: string): void;
68
+ /** As the pages of signing in read it: behind a proxy of TLS, its X-Forwarded-Proto makes the cookie Secure. */
62
69
  protected origin(request: IncomingMessage): string;
63
70
  /** `/api/files` of the Ta of the tenant whose cookie came along. */
64
71
  protected files(request: IncomingMessage, response: ServerResponse): Promise<void>;
@@ -2,9 +2,10 @@ import { createReadStream, existsSync, mkdirSync, statSync } from 'node:fs';
2
2
  import { createServer, request as httpRequest } from 'node:http';
3
3
  import { request as httpsRequest } from 'node:https';
4
4
  import { extname, join, normalize, sep } from 'node:path';
5
+ import { pipeline } from 'node:stream';
5
6
  import { WebSocketConnection } from '@celljs/rpc/lib/node/websocket/websocket-connection';
6
7
  import { AccessStore, AccessUtil } from '@celljs/ta-host/lib/node/sign-in/access-store';
7
- 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';
8
9
  import { SignInPages, SignInPageUtil } from '@celljs/ta-host/lib/node/sign-in/sign-in-pages';
9
10
  import { SignInProviders } from '@celljs/ta-host/lib/node/sign-in/sign-in-provider';
10
11
  import { TA_FILES_PATH, TA_WEBSOCKET_PATH } from '@celljs/ta-protocol';
@@ -59,6 +60,16 @@ export var GatewayServerUtil;
59
60
  return join(root, 'index.html');
60
61
  }
61
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;
62
73
  })(GatewayServerUtil || (GatewayServerUtil = {}));
63
74
  /**
64
75
  * `ta gateway`: one sign-in for many people, each with a Ta of their own. An account that signs in is a
@@ -202,20 +213,29 @@ export class GatewayServer {
202
213
  const list = Array.isArray(cookies) ? cookies : cookies ? [String(cookies)] : [];
203
214
  response.setHeader('Set-Cookie', [...list, `${FILES_COOKIE}=${token}; Path=${TA_FILES_PATH}; Max-Age=31536000; HttpOnly; SameSite=Lax${secure}`]);
204
215
  }
216
+ /** As the pages of signing in read it: behind a proxy of TLS, its X-Forwarded-Proto makes the cookie Secure. */
205
217
  origin(request) {
206
- var _a;
207
- return (_a = this.flow.publicUrl) !== null && _a !== void 0 ? _a : `http://${request.headers.host}`;
218
+ return SignInUtil.origin(request, this.flow.publicUrl);
208
219
  }
209
220
  /** `/api/files` of the Ta of the tenant whose cookie came along. */
210
221
  async files(request, response) {
211
222
  var _a, _b;
223
+ if (request.method !== 'GET' && request.method !== 'HEAD') {
224
+ response.setHeader('Allow', 'GET, HEAD');
225
+ SignInPageUtil.end(response, 405);
226
+ return;
227
+ }
212
228
  const caller = this.caller((_a = SignInPageUtil.cookie(request.headers.cookie, FILES_COOKIE)) !== null && _a !== void 0 ? _a : '');
213
229
  if (!caller) {
214
230
  SignInPageUtil.end(response, 404);
215
231
  return;
216
232
  }
217
233
  const endpoint = await this.environments.ensure(caller.tenant);
218
- const target = new URL((_b = request.url) !== null && _b !== void 0 ? _b : '/', endpoint.url);
234
+ const target = GatewayServerUtil.filesTarget((_b = request.url) !== null && _b !== void 0 ? _b : '/', endpoint.url);
235
+ if (!target) {
236
+ SignInPageUtil.end(response, 404);
237
+ return;
238
+ }
219
239
  const headers = {};
220
240
  for (const name of ['range', 'if-none-match', 'accept', 'accept-encoding', 'user-agent']) {
221
241
  const value = request.headers[name];
@@ -228,11 +248,11 @@ export class GatewayServer {
228
248
  const outgoing = send(target, { method: request.method, headers }, incoming => {
229
249
  var _a;
230
250
  response.writeHead((_a = incoming.statusCode) !== null && _a !== void 0 ? _a : 502, incoming.headers);
231
- incoming.pipe(response);
232
- incoming.on('end', () => resolve());
233
- incoming.on('error', reject);
251
+ // A browser that stops reading (a video seeking) closes the request to the Ta of the tenant too.
252
+ pipeline(incoming, response, () => resolve());
234
253
  });
235
254
  outgoing.on('error', reject);
255
+ response.once('close', () => outgoing.destroy());
236
256
  outgoing.end();
237
257
  });
238
258
  }
@@ -252,7 +272,11 @@ export class GatewayServer {
252
272
  response.end();
253
273
  return;
254
274
  }
255
- createReadStream(file).pipe(response);
275
+ // A file gone meanwhile (the web client being replaced) fails this request, not the gateway.
276
+ const stream = createReadStream(file);
277
+ stream.once('error', () => (response.headersSent ? response.destroy() : SignInPageUtil.end(response, 404)));
278
+ response.once('close', () => stream.destroy());
279
+ stream.pipe(response);
256
280
  }
257
281
  upgrade(request, socket, head) {
258
282
  var _a, _b;
@@ -274,7 +298,7 @@ export class GatewayServer {
274
298
  return;
275
299
  }
276
300
  this.tenants.update(caller.tenant.id, { lastActiveAt: Date.now() });
277
- const connection = WebSocketConnection.open(socket, checked.key, head, { maxPayload: 32 * 1024 * 1024, heartbeat: 30000 });
301
+ const connection = WebSocketConnection.open(socket, checked.key, head, { maxPayload: 32 * 1024 * 1024, heartbeat: 30000, deflate: checked.deflate });
278
302
  const gatewaySocket = new GatewaySocket(connection, caller, this.environments, this.service);
279
303
  this.sockets.add(gatewaySocket);
280
304
  connection.onClose(() => this.sockets.delete(gatewaySocket));
@@ -18,6 +18,8 @@ export declare namespace GatewayServiceUtil {
18
18
  /** The services the gateway answers itself, not the Ta of the tenant. */
19
19
  const SERVICES: string[];
20
20
  function owns(method: unknown): method is string;
21
+ /** Whether the text of a message may be a call of {@link SERVICES}: those that are not are not parsed. */
22
+ function mayOwn(text: string): boolean;
21
23
  /** The error of a JSON-RPC answer, as ta serve sends an ApplicationError: the client reads its code and hint. */
22
24
  function error(id: unknown, message: string, code: TaErrorCode, hint: string): string;
23
25
  function result(id: unknown, result: unknown): string;
@@ -16,6 +16,11 @@ export var GatewayServiceUtil;
16
16
  return typeof method === 'string' && GatewayServiceUtil.SERVICES.includes(method.split('/')[0]);
17
17
  }
18
18
  GatewayServiceUtil.owns = owns;
19
+ /** Whether the text of a message may be a call of {@link SERVICES}: those that are not are not parsed. */
20
+ function mayOwn(text) {
21
+ return GatewayServiceUtil.SERVICES.some(service => text.includes(`"${service}/`));
22
+ }
23
+ GatewayServiceUtil.mayOwn = mayOwn;
19
24
  /** The error of a JSON-RPC answer, as ta serve sends an ApplicationError: the client reads its code and hint. */
20
25
  function error(id, message, code, hint) {
21
26
  return JSON.stringify({ jsonrpc: '2.0', id, error: { code: TA_RPC_ERROR_CODE, message, data: { kind: 'application', data: { code, hint } } } });
@@ -25,6 +25,7 @@ export declare class GatewaySocket {
25
25
  close(code: number, reason: string): void;
26
26
  protected open(): Promise<void>;
27
27
  protected fromBrowser(text: string): void;
28
+ protected forward(text: string): void;
28
29
  protected answer(id: unknown, method: string, params: unknown[]): Promise<void>;
29
30
  /** The calls that wait, and those to come, fail; those of the gateway still work. */
30
31
  protected fail(reason: string): void;
@@ -68,12 +68,16 @@ export class GatewaySocket {
68
68
  };
69
69
  }
70
70
  fromBrowser(text) {
71
- var _a;
71
+ // Most messages are the Ta's, some large (pictures): forwarded without being read.
72
+ if (this.failure === undefined && !GatewayServiceUtil.mayOwn(text)) {
73
+ this.forward(text);
74
+ return;
75
+ }
72
76
  let message;
73
77
  try {
74
78
  message = JSON.parse(text);
75
79
  }
76
- catch (_b) {
80
+ catch (_a) {
77
81
  this.close(1007, 'Not JSON.');
78
82
  return;
79
83
  }
@@ -87,6 +91,10 @@ export class GatewaySocket {
87
91
  }
88
92
  return;
89
93
  }
94
+ this.forward(text);
95
+ }
96
+ forward(text) {
97
+ var _a;
90
98
  if (((_a = this.inner) === null || _a === void 0 ? void 0 : _a.readyState) === WebSocket.OPEN) {
91
99
  this.inner.send(text);
92
100
  }
@@ -34,13 +34,19 @@ export class LocalSandbox {
34
34
  stdio: 'ignore',
35
35
  });
36
36
  const url = `http://127.0.0.1:${port}`;
37
- this.running.set(tenant.id, { child, url });
38
- child.once('exit', () => {
37
+ // A command that cannot start fails this tenant's start (nothing answers), not the gateway.
38
+ const gone = () => {
39
39
  var _a;
40
40
  if (((_a = this.running.get(tenant.id)) === null || _a === void 0 ? void 0 : _a.child) === child) {
41
41
  this.running.delete(tenant.id);
42
42
  }
43
+ };
44
+ child.once('error', error => {
45
+ console.warn(`ta gateway: the local sandbox of ${tenant.id} did not start: ${error.message}`);
46
+ gone();
43
47
  });
48
+ this.running.set(tenant.id, { child, url });
49
+ child.once('exit', gone);
44
50
  return { url, token: tenant.token };
45
51
  }
46
52
  async stop(tenant) {
@@ -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
  },
@@ -219,7 +219,8 @@ class Environments {
219
219
  const next = this.tenants.update(tenant.id, { environment: choice });
220
220
  // What is picked must be there: an id of none throws here, not on the next start.
221
221
  this.provider(next);
222
- this.running.delete(tenant.id);
222
+ // The state stays: the connections it counts close and open again, and release it as they do.
223
+ Object.assign(this.state(tenant.id), { status: 'stopped', endpoint: undefined, error: undefined });
223
224
  return next;
224
225
  }
225
226
  async dispose() {
@@ -1,5 +1,5 @@
1
1
  import { type IncomingMessage, type Server, type ServerResponse } from 'node:http';
2
- import type { Duplex } from 'node:stream';
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
5
  import { Environments } from './environments';
@@ -23,6 +23,12 @@ 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;
26
32
  }
27
33
  /**
28
34
  * `ta gateway`: one sign-in for many people, each with a Ta of their own. An account that signs in is a
@@ -59,6 +65,7 @@ export declare class GatewayServer {
59
65
  /** A link of `ta gateway link`: lets its account in, and signs this browser in as it. */
60
66
  protected useLink(request: IncomingMessage, response: ServerResponse, secret: string): void;
61
67
  protected signedIn(response: ServerResponse, token: string, account: SignInAccount, origin: string): void;
68
+ /** As the pages of signing in read it: behind a proxy of TLS, its X-Forwarded-Proto makes the cookie Secure. */
62
69
  protected origin(request: IncomingMessage): string;
63
70
  /** `/api/files` of the Ta of the tenant whose cookie came along. */
64
71
  protected files(request: IncomingMessage, response: ServerResponse): Promise<void>;
@@ -5,6 +5,7 @@ const node_fs_1 = require("node:fs");
5
5
  const node_http_1 = require("node:http");
6
6
  const node_https_1 = require("node:https");
7
7
  const node_path_1 = require("node:path");
8
+ const node_stream_1 = require("node:stream");
8
9
  const websocket_connection_1 = require("@celljs/rpc/lib/node/websocket/websocket-connection");
9
10
  const access_store_1 = require("@celljs/ta-host/lib/node/sign-in/access-store");
10
11
  const sign_in_flow_1 = require("@celljs/ta-host/lib/node/sign-in/sign-in-flow");
@@ -62,6 +63,16 @@ var GatewayServerUtil;
62
63
  return (0, node_path_1.join)(root, 'index.html');
63
64
  }
64
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;
65
76
  })(GatewayServerUtil || (exports.GatewayServerUtil = GatewayServerUtil = {}));
66
77
  /**
67
78
  * `ta gateway`: one sign-in for many people, each with a Ta of their own. An account that signs in is a
@@ -205,20 +216,29 @@ class GatewayServer {
205
216
  const list = Array.isArray(cookies) ? cookies : cookies ? [String(cookies)] : [];
206
217
  response.setHeader('Set-Cookie', [...list, `${FILES_COOKIE}=${token}; Path=${ta_protocol_1.TA_FILES_PATH}; Max-Age=31536000; HttpOnly; SameSite=Lax${secure}`]);
207
218
  }
219
+ /** As the pages of signing in read it: behind a proxy of TLS, its X-Forwarded-Proto makes the cookie Secure. */
208
220
  origin(request) {
209
- var _a;
210
- return (_a = this.flow.publicUrl) !== null && _a !== void 0 ? _a : `http://${request.headers.host}`;
221
+ return sign_in_flow_1.SignInUtil.origin(request, this.flow.publicUrl);
211
222
  }
212
223
  /** `/api/files` of the Ta of the tenant whose cookie came along. */
213
224
  async files(request, response) {
214
225
  var _a, _b;
226
+ if (request.method !== 'GET' && request.method !== 'HEAD') {
227
+ response.setHeader('Allow', 'GET, HEAD');
228
+ sign_in_pages_1.SignInPageUtil.end(response, 405);
229
+ return;
230
+ }
215
231
  const caller = this.caller((_a = sign_in_pages_1.SignInPageUtil.cookie(request.headers.cookie, FILES_COOKIE)) !== null && _a !== void 0 ? _a : '');
216
232
  if (!caller) {
217
233
  sign_in_pages_1.SignInPageUtil.end(response, 404);
218
234
  return;
219
235
  }
220
236
  const endpoint = await this.environments.ensure(caller.tenant);
221
- const target = new URL((_b = request.url) !== null && _b !== void 0 ? _b : '/', endpoint.url);
237
+ const target = GatewayServerUtil.filesTarget((_b = request.url) !== null && _b !== void 0 ? _b : '/', endpoint.url);
238
+ if (!target) {
239
+ sign_in_pages_1.SignInPageUtil.end(response, 404);
240
+ return;
241
+ }
222
242
  const headers = {};
223
243
  for (const name of ['range', 'if-none-match', 'accept', 'accept-encoding', 'user-agent']) {
224
244
  const value = request.headers[name];
@@ -231,11 +251,11 @@ class GatewayServer {
231
251
  const outgoing = send(target, { method: request.method, headers }, incoming => {
232
252
  var _a;
233
253
  response.writeHead((_a = incoming.statusCode) !== null && _a !== void 0 ? _a : 502, incoming.headers);
234
- incoming.pipe(response);
235
- incoming.on('end', () => resolve());
236
- incoming.on('error', reject);
254
+ // A browser that stops reading (a video seeking) closes the request to the Ta of the tenant too.
255
+ (0, node_stream_1.pipeline)(incoming, response, () => resolve());
237
256
  });
238
257
  outgoing.on('error', reject);
258
+ response.once('close', () => outgoing.destroy());
239
259
  outgoing.end();
240
260
  });
241
261
  }
@@ -255,7 +275,11 @@ class GatewayServer {
255
275
  response.end();
256
276
  return;
257
277
  }
258
- (0, node_fs_1.createReadStream)(file).pipe(response);
278
+ // A file gone meanwhile (the web client being replaced) fails this request, not the gateway.
279
+ const stream = (0, node_fs_1.createReadStream)(file);
280
+ stream.once('error', () => (response.headersSent ? response.destroy() : sign_in_pages_1.SignInPageUtil.end(response, 404)));
281
+ response.once('close', () => stream.destroy());
282
+ stream.pipe(response);
259
283
  }
260
284
  upgrade(request, socket, head) {
261
285
  var _a, _b;
@@ -277,7 +301,7 @@ class GatewayServer {
277
301
  return;
278
302
  }
279
303
  this.tenants.update(caller.tenant.id, { lastActiveAt: Date.now() });
280
- const connection = websocket_connection_1.WebSocketConnection.open(socket, checked.key, head, { maxPayload: 32 * 1024 * 1024, heartbeat: 30000 });
304
+ const connection = websocket_connection_1.WebSocketConnection.open(socket, checked.key, head, { maxPayload: 32 * 1024 * 1024, heartbeat: 30000, deflate: checked.deflate });
281
305
  const gatewaySocket = new gateway_socket_1.GatewaySocket(connection, caller, this.environments, this.service);
282
306
  this.sockets.add(gatewaySocket);
283
307
  connection.onClose(() => this.sockets.delete(gatewaySocket));
@@ -18,6 +18,8 @@ export declare namespace GatewayServiceUtil {
18
18
  /** The services the gateway answers itself, not the Ta of the tenant. */
19
19
  const SERVICES: string[];
20
20
  function owns(method: unknown): method is string;
21
+ /** Whether the text of a message may be a call of {@link SERVICES}: those that are not are not parsed. */
22
+ function mayOwn(text: string): boolean;
21
23
  /** The error of a JSON-RPC answer, as ta serve sends an ApplicationError: the client reads its code and hint. */
22
24
  function error(id: unknown, message: string, code: TaErrorCode, hint: string): string;
23
25
  function result(id: unknown, result: unknown): string;
@@ -20,6 +20,11 @@ var GatewayServiceUtil;
20
20
  return typeof method === 'string' && GatewayServiceUtil.SERVICES.includes(method.split('/')[0]);
21
21
  }
22
22
  GatewayServiceUtil.owns = owns;
23
+ /** Whether the text of a message may be a call of {@link SERVICES}: those that are not are not parsed. */
24
+ function mayOwn(text) {
25
+ return GatewayServiceUtil.SERVICES.some(service => text.includes(`"${service}/`));
26
+ }
27
+ GatewayServiceUtil.mayOwn = mayOwn;
23
28
  /** The error of a JSON-RPC answer, as ta serve sends an ApplicationError: the client reads its code and hint. */
24
29
  function error(id, message, code, hint) {
25
30
  return JSON.stringify({ jsonrpc: '2.0', id, error: { code: ta_protocol_1.TA_RPC_ERROR_CODE, message, data: { kind: 'application', data: { code, hint } } } });
@@ -25,6 +25,7 @@ export declare class GatewaySocket {
25
25
  close(code: number, reason: string): void;
26
26
  protected open(): Promise<void>;
27
27
  protected fromBrowser(text: string): void;
28
+ protected forward(text: string): void;
28
29
  protected answer(id: unknown, method: string, params: unknown[]): Promise<void>;
29
30
  /** The calls that wait, and those to come, fail; those of the gateway still work. */
30
31
  protected fail(reason: string): void;
@@ -71,12 +71,16 @@ class GatewaySocket {
71
71
  };
72
72
  }
73
73
  fromBrowser(text) {
74
- var _a;
74
+ // Most messages are the Ta's, some large (pictures): forwarded without being read.
75
+ if (this.failure === undefined && !gateway_service_1.GatewayServiceUtil.mayOwn(text)) {
76
+ this.forward(text);
77
+ return;
78
+ }
75
79
  let message;
76
80
  try {
77
81
  message = JSON.parse(text);
78
82
  }
79
- catch (_b) {
83
+ catch (_a) {
80
84
  this.close(1007, 'Not JSON.');
81
85
  return;
82
86
  }
@@ -90,6 +94,10 @@ class GatewaySocket {
90
94
  }
91
95
  return;
92
96
  }
97
+ this.forward(text);
98
+ }
99
+ forward(text) {
100
+ var _a;
93
101
  if (((_a = this.inner) === null || _a === void 0 ? void 0 : _a.readyState) === WebSocket.OPEN) {
94
102
  this.inner.send(text);
95
103
  }
@@ -37,13 +37,19 @@ class LocalSandbox {
37
37
  stdio: 'ignore',
38
38
  });
39
39
  const url = `http://127.0.0.1:${port}`;
40
- this.running.set(tenant.id, { child, url });
41
- child.once('exit', () => {
40
+ // A command that cannot start fails this tenant's start (nothing answers), not the gateway.
41
+ const gone = () => {
42
42
  var _a;
43
43
  if (((_a = this.running.get(tenant.id)) === null || _a === void 0 ? void 0 : _a.child) === child) {
44
44
  this.running.delete(tenant.id);
45
45
  }
46
+ };
47
+ child.once('error', error => {
48
+ console.warn(`ta gateway: the local sandbox of ${tenant.id} did not start: ${error.message}`);
49
+ gone();
46
50
  });
51
+ this.running.set(tenant.id, { child, url });
52
+ child.once('exit', gone);
47
53
  return { url, token: tenant.token };
48
54
  }
49
55
  async stop(tenant) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@celljs/ta-gateway",
3
- "version": "4.9.0",
3
+ "version": "4.10.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.9.0",
33
- "@celljs/ta-host": "4.9.0",
34
- "@celljs/ta-protocol": "4.9.0"
32
+ "@celljs/rpc": "4.10.0",
33
+ "@celljs/ta-host": "4.10.0",
34
+ "@celljs/ta-protocol": "4.10.0"
35
35
  },
36
36
  "publishConfig": {
37
37
  "access": "public"