@celljs/ta-gateway 4.9.1 → 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
  },
@@ -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,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,16 @@ 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;
63
73
  })(GatewayServerUtil || (GatewayServerUtil = {}));
64
74
  /**
65
75
  * `ta gateway`: one sign-in for many people, each with a Ta of their own. An account that signs in is a
@@ -203,20 +213,29 @@ export class GatewayServer {
203
213
  const list = Array.isArray(cookies) ? cookies : cookies ? [String(cookies)] : [];
204
214
  response.setHeader('Set-Cookie', [...list, `${FILES_COOKIE}=${token}; Path=${TA_FILES_PATH}; Max-Age=31536000; HttpOnly; SameSite=Lax${secure}`]);
205
215
  }
216
+ /** As the pages of signing in read it: behind a proxy of TLS, its X-Forwarded-Proto makes the cookie Secure. */
206
217
  origin(request) {
207
- var _a;
208
- return (_a = this.flow.publicUrl) !== null && _a !== void 0 ? _a : `http://${request.headers.host}`;
218
+ return SignInUtil.origin(request, this.flow.publicUrl);
209
219
  }
210
220
  /** `/api/files` of the Ta of the tenant whose cookie came along. */
211
221
  async files(request, response) {
212
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
+ }
213
228
  const caller = this.caller((_a = SignInPageUtil.cookie(request.headers.cookie, FILES_COOKIE)) !== null && _a !== void 0 ? _a : '');
214
229
  if (!caller) {
215
230
  SignInPageUtil.end(response, 404);
216
231
  return;
217
232
  }
218
233
  const endpoint = await this.environments.ensure(caller.tenant);
219
- 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
+ }
220
239
  const headers = {};
221
240
  for (const name of ['range', 'if-none-match', 'accept', 'accept-encoding', 'user-agent']) {
222
241
  const value = request.headers[name];
@@ -279,7 +298,7 @@ export class GatewayServer {
279
298
  return;
280
299
  }
281
300
  this.tenants.update(caller.tenant.id, { lastActiveAt: Date.now() });
282
- 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 });
283
302
  const gatewaySocket = new GatewaySocket(connection, caller, this.environments, this.service);
284
303
  this.sockets.add(gatewaySocket);
285
304
  connection.onClose(() => this.sockets.delete(gatewaySocket));
@@ -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
  },
@@ -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>;
@@ -63,6 +63,16 @@ 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;
66
76
  })(GatewayServerUtil || (exports.GatewayServerUtil = GatewayServerUtil = {}));
67
77
  /**
68
78
  * `ta gateway`: one sign-in for many people, each with a Ta of their own. An account that signs in is a
@@ -206,20 +216,29 @@ class GatewayServer {
206
216
  const list = Array.isArray(cookies) ? cookies : cookies ? [String(cookies)] : [];
207
217
  response.setHeader('Set-Cookie', [...list, `${FILES_COOKIE}=${token}; Path=${ta_protocol_1.TA_FILES_PATH}; Max-Age=31536000; HttpOnly; SameSite=Lax${secure}`]);
208
218
  }
219
+ /** As the pages of signing in read it: behind a proxy of TLS, its X-Forwarded-Proto makes the cookie Secure. */
209
220
  origin(request) {
210
- var _a;
211
- 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);
212
222
  }
213
223
  /** `/api/files` of the Ta of the tenant whose cookie came along. */
214
224
  async files(request, response) {
215
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
+ }
216
231
  const caller = this.caller((_a = sign_in_pages_1.SignInPageUtil.cookie(request.headers.cookie, FILES_COOKIE)) !== null && _a !== void 0 ? _a : '');
217
232
  if (!caller) {
218
233
  sign_in_pages_1.SignInPageUtil.end(response, 404);
219
234
  return;
220
235
  }
221
236
  const endpoint = await this.environments.ensure(caller.tenant);
222
- 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
+ }
223
242
  const headers = {};
224
243
  for (const name of ['range', 'if-none-match', 'accept', 'accept-encoding', 'user-agent']) {
225
244
  const value = request.headers[name];
@@ -282,7 +301,7 @@ class GatewayServer {
282
301
  return;
283
302
  }
284
303
  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 });
304
+ const connection = websocket_connection_1.WebSocketConnection.open(socket, checked.key, head, { maxPayload: 32 * 1024 * 1024, heartbeat: 30000, deflate: checked.deflate });
286
305
  const gatewaySocket = new gateway_socket_1.GatewaySocket(connection, caller, this.environments, this.service);
287
306
  this.sockets.add(gatewaySocket);
288
307
  connection.onClose(() => this.sockets.delete(gatewaySocket));
@@ -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.1",
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.1",
33
- "@celljs/ta-host": "4.9.1",
34
- "@celljs/ta-protocol": "4.9.1"
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"