@celljs/ta-gateway 0.0.0-stage → 4.9.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.
Files changed (60) hide show
  1. package/README.en.md +80 -0
  2. package/README.md +79 -2
  3. package/esm/node/command-sandbox.d.ts +28 -0
  4. package/esm/node/command-sandbox.js +83 -0
  5. package/esm/node/docker-engine.d.ts +56 -0
  6. package/esm/node/docker-engine.js +151 -0
  7. package/esm/node/docker-sandbox.d.ts +45 -0
  8. package/esm/node/docker-sandbox.js +110 -0
  9. package/esm/node/environments.d.ts +68 -0
  10. package/esm/node/environments.js +236 -0
  11. package/esm/node/gateway-cli.d.ts +9 -0
  12. package/esm/node/gateway-cli.js +99 -0
  13. package/esm/node/gateway-server.d.ts +67 -0
  14. package/esm/node/gateway-server.js +283 -0
  15. package/esm/node/gateway-service.d.ts +56 -0
  16. package/esm/node/gateway-service.js +182 -0
  17. package/esm/node/gateway-socket.d.ts +32 -0
  18. package/esm/node/gateway-socket.js +135 -0
  19. package/esm/node/index.d.ts +13 -0
  20. package/esm/node/index.js +14 -0
  21. package/esm/node/local-sandbox.d.ts +23 -0
  22. package/esm/node/local-sandbox.js +73 -0
  23. package/esm/node/sandbox-provider.d.ts +72 -0
  24. package/esm/node/sandbox-provider.js +83 -0
  25. package/esm/node/sign-in-links.d.ts +25 -0
  26. package/esm/node/sign-in-links.js +44 -0
  27. package/esm/node/ta-sandbox.d.ts +23 -0
  28. package/esm/node/ta-sandbox.js +47 -0
  29. package/esm/node/tenant-store.d.ts +36 -0
  30. package/esm/node/tenant-store.js +83 -0
  31. package/esm/package.json +3 -0
  32. package/lib/node/command-sandbox.d.ts +29 -0
  33. package/lib/node/command-sandbox.js +87 -0
  34. package/lib/node/docker-engine.d.ts +57 -0
  35. package/lib/node/docker-engine.js +156 -0
  36. package/lib/node/docker-sandbox.d.ts +46 -0
  37. package/lib/node/docker-sandbox.js +114 -0
  38. package/lib/node/environments.d.ts +69 -0
  39. package/lib/node/environments.js +241 -0
  40. package/lib/node/gateway-cli.d.ts +10 -0
  41. package/lib/node/gateway-cli.js +102 -0
  42. package/lib/node/gateway-server.d.ts +68 -0
  43. package/lib/node/gateway-server.js +287 -0
  44. package/lib/node/gateway-service.d.ts +57 -0
  45. package/lib/node/gateway-service.js +187 -0
  46. package/lib/node/gateway-socket.d.ts +33 -0
  47. package/lib/node/gateway-socket.js +139 -0
  48. package/lib/node/index.d.ts +14 -0
  49. package/lib/node/index.js +30 -0
  50. package/lib/node/local-sandbox.d.ts +24 -0
  51. package/lib/node/local-sandbox.js +77 -0
  52. package/lib/node/sandbox-provider.d.ts +73 -0
  53. package/lib/node/sandbox-provider.js +87 -0
  54. package/lib/node/sign-in-links.d.ts +26 -0
  55. package/lib/node/sign-in-links.js +48 -0
  56. package/lib/node/ta-sandbox.d.ts +24 -0
  57. package/lib/node/ta-sandbox.js +51 -0
  58. package/lib/node/tenant-store.d.ts +37 -0
  59. package/lib/node/tenant-store.js +88 -0
  60. package/package.json +57 -4
package/README.en.md ADDED
@@ -0,0 +1,80 @@
1
+ # Cell - Ta Gateway
2
+
3
+ `ta gateway`: one address, one sign-in, and a Ta of their own for everyone. Whoever signs in with an account is a tenant, whose Ta runs in a sandbox of its own (a container per person by default), or in a Ta service of their own. The gateway serves the web client and forwards each browser's connection to the Ta of its tenant; sessions, model accounts, files and terminals are in that sandbox, which other tenants neither see nor reach.
4
+
5
+ ```bash
6
+ ta gateway --host 0.0.0.0 --port 4100 # directory: TA_GATEWAY_DIR, default ~/.ta/gateway
7
+ ta gateway link user:alice --name Alice # a sign-in link used once (within a day), without a provider of accounts
8
+ ```
9
+
10
+ ## Tenants and Signing In
11
+
12
+ - The ways to sign in are those of `ta serve`: GitHub, Google, WeChat, OpenID Connect (`TA_GITHUB_*`, `TA_GOOGLE_*`, `TA_WECHAT_*`, `TA_OIDC_*`; see "Signing In with Accounts" of [@celljs/ta-host](../ta-host/README.en.md)), with the same code (`SignInFlow`, `SignInPages`). `ta gateway link <account>` makes a link used once: opening it signs in as the account, and lets it in.
13
+ - Who gets in: the accounts of `TA_ALLOWED_USERS`, those administrators (`TA_GATEWAY_ADMINS`) let in, and the administrators. Anyone else who signs in becomes a request, which an administrator lets in with a tap under Settings, Access.
14
+ - One tenant per account (`tenants/<id>.json`, the id the first 16 hex digits of a hash of the account). Browsers hold a token of the gateway; the token of the tenant's Ta service (`TA_SERVE_TOKEN`) is known to the gateway and the sandbox only, never to a browser.
15
+ - The gateway answers `TaGatewayServer` (the environment, the tenants) and `TaAccessServer` (access: administrators manage every account, the others see their own browsers) itself on the same WebSocket, and forwards every other call to the tenant's Ta as it is. `/api/files` finds its tenant by an HttpOnly cookie set at sign-in (sent to `/api/files` only).
16
+ - An account removed, or a browser signed out, is cut off at once. When an account is removed, the gateway also unpairs the devices paired with the tenant's Ta and stops its sandbox (a Ta service of the user's is left as it is).
17
+
18
+ ## Phones
19
+
20
+ - **The Ta app**: sign in to the gateway in a browser of a computer, then gear menu, Use on your phone…, and scan the QR code with the Ta app. What is paired is that person's own Ta (`TaRelayServer` goes to the tenant like every other call): the phone reaches their sandbox through the relay directly, encrypted end to end, from anywhere, not through the gateway. The list of computers shows the account as the name of the machine (the host name of the `docker` container).
21
+ - **A phone's browser**: where the address of the gateway is reachable, open it and sign in (an account, or a link of `ta gateway link`); the phone layout is the same as on a computer.
22
+
23
+ ## Providers of Sandboxes (sandboxes.json)
24
+
25
+ As pi connects models: a few built-in types, a file to configure one, and a module when none fits. `sandboxes.json` in the directory of the gateway:
26
+
27
+ ```json
28
+ {
29
+ "default": "docker",
30
+ "ownEnvironments": true,
31
+ "idleMinutes": 0,
32
+ "providers": {
33
+ "docker": { "type": "docker", "name": "Docker", "image": "ta:latest", "memory": "4g", "cpus": 2, "pids": 1024 },
34
+ "k8s": { "type": "command", "name": "Kubernetes", "start": "./k8s-start.sh", "stop": "./k8s-stop.sh" },
35
+ "e2b": { "type": "module", "path": "./e2b-sandbox.mjs", "name": "E2B" }
36
+ }
37
+ }
38
+ ```
39
+
40
+ Without the file, there is the `docker` above only.
41
+
42
+ | Type | What it does |
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 |
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
+ | `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
+ | `ta` | A Ta service that runs already (`url`, `token`), which the gateway neither starts nor stops. Shared by all, it isolates nothing |
48
+ | `local` | A `ta serve` process per tenant on the machine of the gateway (`<gateway>/local/<tenant>`). No isolation: for trying out and tests |
49
+
50
+ - **An environment of one's own**: with `ownEnvironments` true (the default), users can run their Ta in a Ta service of their own under Settings, Environment (`docker run … ta` or `ta serve --host 0.0.0.0` anywhere, its address and token). The token is kept in the tenant's file of the gateway (mode 0600), never back in a browser. They can switch between the providers of the gateway too. Conversations, model accounts and files belong to an environment: another starts without them, and switching back finds them again.
51
+ - **Starting and stopping**: on a tenant's first connection the gateway starts its sandbox (once, for all the connections that come meanwhile) and waits for its Ta service to answer (2 minutes for a new container, 10 seconds for a Ta service that runs), the page waiting; one that does not start shows why on the page, which can try again or switch. With `idleMinutes` above 0, a sandbox nobody has been connected to for that long is stopped (and starts again on the next connection); by default none is, as scheduled tasks and the double's work run in the background.
52
+ - **Administrators** see every tenant under Settings, Environment, with its environment and connections, and can stop a tenant's sandbox.
53
+
54
+ ## Deployment
55
+
56
+ The gateway can run in the image of Ta too (the Dockerfile of [apps/ta](../../apps/ta/README.en.md)), on the network of the host, with Docker's socket:
57
+
58
+ ```bash
59
+ docker network create -o com.docker.network.bridge.enable_icc=false -o com.docker.network.bridge.name=ta-sandbox ta-sandbox
60
+ docker run -d --name ta-gateway --restart unless-stopped --network host \
61
+ --group-add $(stat -c %g /var/run/docker.sock) -v /var/run/docker.sock:/var/run/docker.sock \
62
+ -v ta-gateway:/home/ta -e TA_PUBLIC_URL=https://ta.example.com -e TA_GATEWAY_ADMINS=github:octocat \
63
+ --entrypoint tini ta -- ta gateway --host 0.0.0.0 --port 4100
64
+ docker exec ta-gateway ta gateway link github:octocat # the first sign-in link of the administrator
65
+ ```
66
+
67
+ Using Docker's socket is being root on the host: give it to the gateway, never to a sandbox. Sandboxes cannot reach each other already; to keep them from the services of the host, other Docker networks and the metadata service of a cloud, add firewall rules on the host (again after a restart, from root's `@reboot` crontab for example):
68
+
69
+ ```bash
70
+ iptables -I INPUT -i ta-sandbox -m conntrack --ctstate NEW -j DROP
71
+ iptables -I DOCKER-USER -i ta-sandbox -d 172.16.0.0/12 -m conntrack --ctstate NEW -j DROP
72
+ iptables -I DOCKER-USER -i ta-sandbox -d 169.254.0.0/16 -j DROP
73
+ ```
74
+
75
+ ## Known Limitations
76
+
77
+ - The gateway connects to the address of a user's own Ta service: whoever can give an address can make the gateway request it (`/`, `/api/ws` and `/api/files` only). Set `ownEnvironments` to false to prevent it.
78
+ - A browser signed in by pasting a token has no cookie for `/api/files`: pictures and page previews of the workspace do not load; signed in with an account or a link, they do.
79
+ - The module scripts of a page of the workspace (in a sandboxed iframe, of origin `null`) request `/api/files` without the cookie.
80
+ - A tenant is an account: no team or organization shares a sandbox yet.
package/README.md CHANGED
@@ -1,3 +1,80 @@
1
- # Temporary Holding Version
1
+ # Cell - Ta Gateway
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ `ta gateway`:一个入口、一次登录,给每个人一个自己的 Ta。用账号登录的人就是一个租户,他的 Ta 运行在只属于他的沙箱里(默认每人一个容器),或他自己的 Ta 服务里。网关提供 Web 客户端,把每个浏览器的连接转给它所属租户的 Ta;会话、模型账号、文件、终端都在那个沙箱里,别的租户看不到也碰不到。
4
+
5
+ ```bash
6
+ ta gateway --host 0.0.0.0 --port 4100 # 目录:TA_GATEWAY_DIR,默认 ~/.ta/gateway
7
+ ta gateway link user:alice --name Alice # 一次性登录链接(一天内有效),没有第三方账号时用
8
+ ```
9
+
10
+ ## 租户与登录
11
+
12
+ - 登录方式和 `ta serve` 相同:GitHub、Google、微信、OpenID Connect(`TA_GITHUB_*`、`TA_GOOGLE_*`、`TA_WECHAT_*`、`TA_OIDC_*`,见 [@celljs/ta-host](../ta-host/README.md) 的「账号登录」),代码也是同一份(`SignInFlow`、`SignInPages`)。还可以用 `ta gateway link <账号>` 发一次性链接:打开它就以这个账号登录,并允许它。
13
+ - 谁能进:`TA_ALLOWED_USERS` 里的账号,管理员(`TA_GATEWAY_ADMINS`)允许的账号,以及管理员本身。其他人登录后成为一条请求,管理员在 设置 → 访问 里一点就能允许。
14
+ - 一个账号一个租户(`tenants/<id>.json`,id 是账号的哈希前 16 位)。浏览器拿到的是网关发的 token;租户 Ta 服务的 token(`TA_SERVE_TOKEN`)只有网关和沙箱知道,不会到浏览器。
15
+ - 网关自己回答同一条 WebSocket 上的 `TaGatewayServer`(运行环境、租户列表)和 `TaAccessServer`(访问管理:管理员管理所有账号,其他人只看到自己的浏览器),其余调用原样转给租户的 Ta。`/api/files` 按登录时设下的 HttpOnly cookie(只发往 `/api/files`)找到租户。
16
+ - 移除账号或退出某个浏览器,它的连接立即断开。移除账号时,网关还会取消这个租户的 Ta 配对过的设备,并停掉它的沙箱(用户自己的 Ta 服务不动)。
17
+
18
+ ## 手机
19
+
20
+ - **Ta 应用**:在电脑浏览器里登录网关,点 齿轮菜单 → 在手机上使用…,用 Ta 应用扫二维码。配对的是这个人自己的 Ta(`TaRelayServer` 和其他调用一样转给租户),手机经 Relay 直接连到他的沙箱,端到端加密,在哪里都能用,不经过网关。电脑列表里显示的机器名是账号名(`docker` 的容器主机名)。
21
+ - **手机浏览器**:能访问网关地址时,直接打开它并登录(账号或 `ta gateway link` 的链接),手机界面和电脑同一套。
22
+
23
+ ## 沙箱提供方(sandboxes.json)
24
+
25
+ 照 pi 接入模型的方式:内置几种类型,配置文件写一个就能用,没有合适的就写一个模块。网关目录的 `sandboxes.json`:
26
+
27
+ ```json
28
+ {
29
+ "default": "docker",
30
+ "ownEnvironments": true,
31
+ "idleMinutes": 0,
32
+ "providers": {
33
+ "docker": { "type": "docker", "name": "Docker", "image": "ta:latest", "memory": "4g", "cpus": 2, "pids": 1024 },
34
+ "k8s": { "type": "command", "name": "Kubernetes", "start": "./k8s-start.sh", "stop": "./k8s-stop.sh" },
35
+ "e2b": { "type": "module", "path": "./e2b-sandbox.mjs", "name": "E2B" }
36
+ }
37
+ }
38
+ ```
39
+
40
+ 没有这个文件时等于只有上面的 `docker`。
41
+
42
+ | 类型 | 做什么 |
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` 给每个沙箱加环境变量 |
45
+ | `command` | 网关没有对应类型的平台(Kubernetes、各家云的命令行、自己的脚本),像 models.json 接一个兼容的端点:`start` 创建或启动沙箱,并把它的 Ta 服务地址打印在最后一行;`stop`、`state`(打印 running / stopped / missing)可选。命令的环境里有 `TA_TENANT_ID`、`TA_TENANT_ACCOUNT`、`TA_SERVE_TOKEN`(沙箱里的 Ta 服务必须用它) |
46
+ | `module` | 运营方自己的提供方,像 pi 的扩展:`path`(相对网关目录)的默认导出是 `(id, config, context) => SandboxProvider`(`start` / `stop` / `state`,见 `sandbox-provider.ts`) |
47
+ | `ta` | 一个已经在运行的 Ta 服务(`url`、`token`),网关不启动也不停止它。所有人共用时没有隔离 |
48
+ | `local` | 网关所在机器上每个租户一个 `ta serve` 进程(`<网关目录>/local/<租户>`)。没有隔离,只用于试用和测试 |
49
+
50
+ - **用户自己的环境**:`ownEnvironments` 为 true(默认)时,用户可以在 设置 → 运行环境 里把自己的 Ta 换到自己的 Ta 服务上(随便在哪台机器 `docker run … ta` 或 `ta serve --host 0.0.0.0`,填地址和 token)。token 存在网关的租户文件里(权限 0600),不会回到浏览器。也可以在网关的几个提供方之间切换。对话、模型账号、文件属于各自的环境,换过去从头开始,换回来还在。
51
+ - **启动与停止**:租户第一次连接时网关启动它的沙箱(同时来的连接共用一次启动),等它的 Ta 服务应答(新容器最多等 2 分钟,已在运行的 Ta 服务 10 秒),期间页面等待;启动失败时页面显示原因,可以重试或换环境。`idleMinutes` 大于 0 时,没有连接这么久后停掉沙箱(下次连接再启动);默认不停,因为定时任务、分身的任务要在后台跑。
52
+ - **管理员**:设置 → 运行环境 列出所有租户、它们的环境和连接数,可以停止某个租户的沙箱。
53
+
54
+ ## 部署
55
+
56
+ 网关本身也可以跑在 Ta 的镜像里([apps/ta](../../apps/ta/README.md) 的 Dockerfile),用宿主网络,挂上 Docker 的套接字:
57
+
58
+ ```bash
59
+ docker network create -o com.docker.network.bridge.enable_icc=false -o com.docker.network.bridge.name=ta-sandbox ta-sandbox
60
+ docker run -d --name ta-gateway --restart unless-stopped --network host \
61
+ --group-add $(stat -c %g /var/run/docker.sock) -v /var/run/docker.sock:/var/run/docker.sock \
62
+ -v ta-gateway:/home/ta -e TA_PUBLIC_URL=https://ta.example.com -e TA_GATEWAY_ADMINS=github:octocat \
63
+ --entrypoint tini ta -- ta gateway --host 0.0.0.0 --port 4100
64
+ docker exec ta-gateway ta gateway link github:octocat # 管理员的第一个登录链接
65
+ ```
66
+
67
+ 能使用 Docker 套接字就等于宿主的 root:只给网关,不要给沙箱。容器之间已经不通;要让沙箱连不到宿主上的服务、其他 Docker 网络和云的元数据服务,在宿主上加防火墙规则(重启后要重新加,例如写进 root 的 `@reboot` crontab):
68
+
69
+ ```bash
70
+ iptables -I INPUT -i ta-sandbox -m conntrack --ctstate NEW -j DROP
71
+ iptables -I DOCKER-USER -i ta-sandbox -d 172.16.0.0/12 -m conntrack --ctstate NEW -j DROP
72
+ iptables -I DOCKER-USER -i ta-sandbox -d 169.254.0.0/16 -j DROP
73
+ ```
74
+
75
+ ## 已知限制
76
+
77
+ - 用户自己的 Ta 服务地址由网关去连接:能填地址的人就能让网关访问那个地址(只请求 `/`、`/api/ws` 和 `/api/files`)。不希望这样就把 `ownEnvironments` 设为 false。
78
+ - 粘贴 token 登录的浏览器没有 `/api/files` 的 cookie,工作区里的图片、网页预览打不开;用账号或链接登录的没有这个问题。
79
+ - 沙箱里网页的模块脚本(在沙箱化的 iframe 里,来源是 `null`)请求 `/api/files` 时不带 cookie。
80
+ - 一个租户就是一个账号,还没有团队或组织共用一个沙箱。
@@ -0,0 +1,28 @@
1
+ import { type SandboxEndpoint, type SandboxProvider, type SandboxProviderConfig, type SandboxState, type SandboxTenant } from './sandbox-provider.js';
2
+ export declare namespace CommandSandboxUtil {
3
+ /** The last line of what `start` printed that is an address. */
4
+ function url(stdout: string): string | undefined;
5
+ }
6
+ /**
7
+ * `command`: the sandboxes of a platform the gateway has no type for (Kubernetes, a cloud's CLI, a script),
8
+ * by shell commands, as pi's models.json takes an endpoint it has no provider for. Each runs with
9
+ * TA_TENANT_ID, TA_TENANT_ACCOUNT and TA_SERVE_TOKEN in its environment: `start` makes or starts the sandbox
10
+ * of the tenant, whose Ta service takes TA_SERVE_TOKEN, and prints its address last; `stop` stops it;
11
+ * `state` prints running, stopped or missing.
12
+ */
13
+ export declare class CommandSandbox implements SandboxProvider {
14
+ readonly id: string;
15
+ readonly type = "command";
16
+ readonly name: string;
17
+ protected readonly commands: {
18
+ start: string;
19
+ stop?: string;
20
+ state?: string;
21
+ };
22
+ protected readonly env: Record<string, string>;
23
+ constructor(id: string, config: SandboxProviderConfig);
24
+ start(tenant: SandboxTenant): Promise<SandboxEndpoint>;
25
+ stop(tenant: SandboxTenant): Promise<void>;
26
+ state(tenant: SandboxTenant): Promise<SandboxState>;
27
+ protected run(command: string, tenant: SandboxTenant): Promise<string>;
28
+ }
@@ -0,0 +1,83 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { SandboxProviders, } from './sandbox-provider.js';
3
+ const TIMEOUT_MS = 10 * 60 * 1000;
4
+ export var CommandSandboxUtil;
5
+ (function (CommandSandboxUtil) {
6
+ /** The last line of what `start` printed that is an address. */
7
+ function url(stdout) {
8
+ var _a;
9
+ return (_a = stdout
10
+ .split('\n')
11
+ .map(line => line.trim())
12
+ .reverse()
13
+ .find(line => /^https?:\/\/\S+$/.test(line))) === null || _a === void 0 ? void 0 : _a.replace(/\/+$/, '');
14
+ }
15
+ CommandSandboxUtil.url = url;
16
+ })(CommandSandboxUtil || (CommandSandboxUtil = {}));
17
+ /**
18
+ * `command`: the sandboxes of a platform the gateway has no type for (Kubernetes, a cloud's CLI, a script),
19
+ * by shell commands, as pi's models.json takes an endpoint it has no provider for. Each runs with
20
+ * TA_TENANT_ID, TA_TENANT_ACCOUNT and TA_SERVE_TOKEN in its environment: `start` makes or starts the sandbox
21
+ * of the tenant, whose Ta service takes TA_SERVE_TOKEN, and prints its address last; `stop` stops it;
22
+ * `state` prints running, stopped or missing.
23
+ */
24
+ export class CommandSandbox {
25
+ constructor(id, config) {
26
+ this.id = id;
27
+ this.type = 'command';
28
+ this.name = SandboxProviders.string(config, 'name', id);
29
+ const start = SandboxProviders.string(config, 'start');
30
+ if (!start) {
31
+ throw new Error(`The provider "${id}" of the type command needs "start", a command that prints the address of the Ta service.`);
32
+ }
33
+ this.commands = { start, stop: SandboxProviders.string(config, 'stop'), state: SandboxProviders.string(config, 'state') };
34
+ this.env = SandboxProviders.env(config);
35
+ }
36
+ async start(tenant) {
37
+ const stdout = await this.run(this.commands.start, tenant);
38
+ const url = CommandSandboxUtil.url(stdout);
39
+ if (!url) {
40
+ throw new Error(`"start" of the provider "${this.id}" printed no address (http:// or https://) last.`);
41
+ }
42
+ return { url, token: tenant.token };
43
+ }
44
+ async stop(tenant) {
45
+ if (this.commands.stop) {
46
+ await this.run(this.commands.stop, tenant);
47
+ }
48
+ }
49
+ async state(tenant) {
50
+ if (!this.commands.state) {
51
+ return 'missing';
52
+ }
53
+ const word = (await this.run(this.commands.state, tenant)).trim().split(/\s+/).pop();
54
+ return word === 'running' || word === 'stopped' ? word : 'missing';
55
+ }
56
+ run(command, tenant) {
57
+ return new Promise((resolve, reject) => {
58
+ const child = spawn('sh', ['-c', command], {
59
+ env: { ...process.env, ...this.env, TA_TENANT_ID: tenant.id, TA_TENANT_ACCOUNT: tenant.account, TA_SERVE_TOKEN: tenant.token },
60
+ stdio: ['ignore', 'pipe', 'pipe'],
61
+ });
62
+ let stdout = '';
63
+ let stderr = '';
64
+ child.stdout.on('data', data => (stdout += data));
65
+ child.stderr.on('data', data => (stderr += data));
66
+ const timer = setTimeout(() => child.kill('SIGKILL'), TIMEOUT_MS);
67
+ child.on('error', error => {
68
+ clearTimeout(timer);
69
+ reject(error);
70
+ });
71
+ child.on('close', code => {
72
+ clearTimeout(timer);
73
+ if (code === 0) {
74
+ resolve(stdout);
75
+ }
76
+ else {
77
+ reject(new Error(`"${command.split(/\s+/)[0]}…" of the provider "${this.id}" exited with ${code}: ${stderr.trim().slice(-300)}`));
78
+ }
79
+ });
80
+ });
81
+ }
82
+ }
83
+ //# sourceMappingURL=command-sandbox.js.map
@@ -0,0 +1,56 @@
1
+ export declare class DockerError extends Error {
2
+ readonly status: number;
3
+ constructor(message: string, status: number);
4
+ }
5
+ export interface DockerEngineOptions {
6
+ /** `unix:///var/run/docker.sock` or `tcp://host:2375`: DOCKER_HOST's form; default that of DOCKER_HOST, else the socket. */
7
+ host?: string;
8
+ }
9
+ /**
10
+ * The Docker Engine API, as far as sandboxes need it, over its socket: no Docker CLI in the image of the
11
+ * gateway, nothing to install.
12
+ */
13
+ export declare class DockerEngine {
14
+ protected readonly target: {
15
+ socketPath: string;
16
+ } | {
17
+ host: string;
18
+ port: number;
19
+ };
20
+ constructor(options?: DockerEngineOptions);
21
+ /** The answer of the Engine, parsed when it is JSON; a status of 400 and above throws. */
22
+ call<T = unknown>(method: string, path: string, body?: unknown, timeoutMs?: number): Promise<{
23
+ status: number;
24
+ body: T;
25
+ }>;
26
+ /** undefined for a container that is not there. */
27
+ inspect(name: string): Promise<DockerContainer | undefined>;
28
+ create(name: string, spec: object): Promise<void>;
29
+ /** Started, or already running (304). */
30
+ start(name: string): Promise<void>;
31
+ /** Stopped, already stopped (304) or not there (404). */
32
+ stop(name: string, seconds?: number): Promise<void>;
33
+ /** A bridge network, made when missing; `isolated`: its containers cannot reach each other. */
34
+ ensureNetwork(name: string, isolated: boolean): Promise<void>;
35
+ /** Pulled when it is not here; one built here (ta:latest) is. */
36
+ ensureImage(image: string): Promise<void>;
37
+ }
38
+ export interface DockerContainer {
39
+ Id: string;
40
+ State: {
41
+ Running: boolean;
42
+ Status: string;
43
+ };
44
+ NetworkSettings: {
45
+ Ports?: Record<string, {
46
+ HostIp: string;
47
+ HostPort: string;
48
+ }[] | null>;
49
+ };
50
+ }
51
+ export declare namespace DockerEngineUtil {
52
+ /** `ghcr.io:443/me/ta:1.0` → `ghcr.io:443/me/ta`, `1.0`: the tag after the last `:` that is past the last `/`. */
53
+ function splitImage(image: string): [string, string?];
54
+ /** `512m`, `4g`, a number of bytes: Docker's `--memory`. */
55
+ function bytes(value: string | number | undefined): number | undefined;
56
+ }
@@ -0,0 +1,151 @@
1
+ import { request } from 'node:http';
2
+ export class DockerError extends Error {
3
+ constructor(message, status) {
4
+ super(message);
5
+ this.status = status;
6
+ }
7
+ }
8
+ /**
9
+ * The Docker Engine API, as far as sandboxes need it, over its socket: no Docker CLI in the image of the
10
+ * gateway, nothing to install.
11
+ */
12
+ export class DockerEngine {
13
+ constructor(options = {}) {
14
+ const host = options.host || process.env.DOCKER_HOST || 'unix:///var/run/docker.sock';
15
+ if (host.startsWith('unix://')) {
16
+ this.target = { socketPath: host.slice('unix://'.length) };
17
+ }
18
+ else if (host.startsWith('tcp://')) {
19
+ const url = new URL(`http://${host.slice('tcp://'.length)}`);
20
+ this.target = { host: url.hostname, port: Number(url.port || 2375) };
21
+ }
22
+ else {
23
+ throw new DockerError(`${host} is not a Docker host: write unix://<socket> or tcp://<host>:<port>.`, 0);
24
+ }
25
+ }
26
+ /** The answer of the Engine, parsed when it is JSON; a status of 400 and above throws. */
27
+ call(method, path, body, timeoutMs = 120000) {
28
+ return new Promise((resolve, reject) => {
29
+ const payload = body === undefined ? undefined : JSON.stringify(body);
30
+ const req = request({
31
+ ...this.target,
32
+ method,
33
+ path,
34
+ headers: payload ? { 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(payload) } : {},
35
+ timeout: timeoutMs,
36
+ }, res => {
37
+ const chunks = [];
38
+ res.on('data', chunk => chunks.push(chunk));
39
+ res.on('end', () => {
40
+ var _a, _b;
41
+ const text = Buffer.concat(chunks).toString('utf8');
42
+ let parsed = text;
43
+ try {
44
+ parsed = text ? JSON.parse(text) : undefined;
45
+ }
46
+ catch (_c) {
47
+ // Streams of progress (a pull) are lines of JSON: kept as text.
48
+ }
49
+ const status = (_a = res.statusCode) !== null && _a !== void 0 ? _a : 0;
50
+ if (status >= 400) {
51
+ const message = (_b = parsed === null || parsed === void 0 ? void 0 : parsed.message) !== null && _b !== void 0 ? _b : text;
52
+ reject(new DockerError(`Docker: ${method} ${path.split('?')[0]} answered ${status}: ${message}`, status));
53
+ }
54
+ else {
55
+ resolve({ status, body: parsed });
56
+ }
57
+ });
58
+ });
59
+ req.on('timeout', () => req.destroy(new DockerError(`Docker: ${method} ${path} took too long`, 0)));
60
+ req.on('error', error => reject(error instanceof DockerError
61
+ ? error
62
+ : new DockerError(`Docker is not reachable (${'socketPath' in this.target ? this.target.socketPath : this.target.host}): ${error.message}`, 0)));
63
+ req.end(payload);
64
+ });
65
+ }
66
+ /** undefined for a container that is not there. */
67
+ async inspect(name) {
68
+ try {
69
+ return (await this.call('GET', `/containers/${encodeURIComponent(name)}/json`)).body;
70
+ }
71
+ catch (error) {
72
+ if (error instanceof DockerError && error.status === 404) {
73
+ return undefined;
74
+ }
75
+ throw error;
76
+ }
77
+ }
78
+ async create(name, spec) {
79
+ await this.call('POST', `/containers/create?name=${encodeURIComponent(name)}`, spec);
80
+ }
81
+ /** Started, or already running (304). */
82
+ async start(name) {
83
+ await this.call('POST', `/containers/${encodeURIComponent(name)}/start`);
84
+ }
85
+ /** Stopped, already stopped (304) or not there (404). */
86
+ async stop(name, seconds = 10) {
87
+ try {
88
+ await this.call('POST', `/containers/${encodeURIComponent(name)}/stop?t=${seconds}`, undefined, (seconds + 30) * 1000);
89
+ }
90
+ catch (error) {
91
+ if (!(error instanceof DockerError && error.status === 404)) {
92
+ throw error;
93
+ }
94
+ }
95
+ }
96
+ /** A bridge network, made when missing; `isolated`: its containers cannot reach each other. */
97
+ async ensureNetwork(name, isolated) {
98
+ try {
99
+ await this.call('GET', `/networks/${encodeURIComponent(name)}`);
100
+ return;
101
+ }
102
+ catch (error) {
103
+ if (!(error instanceof DockerError && error.status === 404)) {
104
+ throw error;
105
+ }
106
+ }
107
+ const options = isolated ? { 'com.docker.network.bridge.enable_icc': 'false' } : {};
108
+ await this.call('POST', '/networks/create', { Name: name, Driver: 'bridge', Options: options, Labels: { 'cell.ta.gateway': '1' } });
109
+ }
110
+ /** Pulled when it is not here; one built here (ta:latest) is. */
111
+ async ensureImage(image) {
112
+ try {
113
+ await this.call('GET', `/images/${encodeURIComponent(image)}/json`);
114
+ return;
115
+ }
116
+ catch (error) {
117
+ if (!(error instanceof DockerError && error.status === 404)) {
118
+ throw error;
119
+ }
120
+ }
121
+ const [repository, tag = 'latest'] = DockerEngineUtil.splitImage(image);
122
+ await this.call('POST', `/images/create?fromImage=${encodeURIComponent(repository)}&tag=${encodeURIComponent(tag)}`, undefined, 30 * 60 * 1000);
123
+ }
124
+ }
125
+ export var DockerEngineUtil;
126
+ (function (DockerEngineUtil) {
127
+ /** `ghcr.io:443/me/ta:1.0` → `ghcr.io:443/me/ta`, `1.0`: the tag after the last `:` that is past the last `/`. */
128
+ function splitImage(image) {
129
+ const slash = image.lastIndexOf('/');
130
+ const colon = image.lastIndexOf(':');
131
+ return colon > slash ? [image.slice(0, colon), image.slice(colon + 1)] : [image];
132
+ }
133
+ DockerEngineUtil.splitImage = splitImage;
134
+ /** `512m`, `4g`, a number of bytes: Docker's `--memory`. */
135
+ function bytes(value) {
136
+ if (value === undefined || value === '') {
137
+ return undefined;
138
+ }
139
+ if (typeof value === 'number') {
140
+ return value;
141
+ }
142
+ const match = /^(\d+(?:\.\d+)?)\s*([kmg]?)b?$/i.exec(value.trim());
143
+ if (!match) {
144
+ throw new DockerError(`${value} is not an amount of memory: write 512m or 4g.`, 0);
145
+ }
146
+ const unit = { '': 1, k: 1024, m: 1024 ** 2, g: 1024 ** 3 }[match[2].toLowerCase()];
147
+ return Math.round(Number(match[1]) * unit);
148
+ }
149
+ DockerEngineUtil.bytes = bytes;
150
+ })(DockerEngineUtil || (DockerEngineUtil = {}));
151
+ //# sourceMappingURL=docker-engine.js.map
@@ -0,0 +1,45 @@
1
+ import { DockerEngine } from './docker-engine.js';
2
+ import { type SandboxEndpoint, type SandboxProvider, type SandboxProviderConfig, type SandboxState, type SandboxTenant } from './sandbox-provider.js';
3
+ export declare namespace DockerSandboxUtil {
4
+ /** `github:Octo.Cat` → `octo-cat`: a name of a host from the account, `ta` when nothing is left. */
5
+ function hostname(account: string): string;
6
+ }
7
+ export interface DockerSandboxOptions {
8
+ /** The image of Ta: default `ta:latest`, built from apps/ta/Dockerfile. */
9
+ image: string;
10
+ /** DOCKER_HOST's form; default DOCKER_HOST, else /var/run/docker.sock. */
11
+ host?: string;
12
+ /** Each sandbox at most: `--memory`, `--cpus`, `--pids-limit`. */
13
+ memory?: number;
14
+ cpus?: number;
15
+ pids?: number;
16
+ /** A network of the sandboxes, whose containers cannot reach each other. */
17
+ network: string;
18
+ /** Where the port of each sandbox is published, and where the gateway reaches it. */
19
+ bind: string;
20
+ address: string;
21
+ /** Names of containers and volumes: `<prefix><tenant>`. */
22
+ prefix: string;
23
+ /** More of the environment of every sandbox, such as a proxy. */
24
+ env: Record<string, string>;
25
+ }
26
+ /**
27
+ * `docker`: a container per tenant, its home (sessions, model accounts, workspace) in a volume of its own,
28
+ * with limits of memory, CPU and processes, in a network where sandboxes cannot reach each other. Its port is
29
+ * published on `bind` only (127.0.0.1): the gateway is the way in.
30
+ */
31
+ export declare class DockerSandbox implements SandboxProvider {
32
+ readonly id: string;
33
+ protected readonly options: DockerSandboxOptions;
34
+ readonly type = "docker";
35
+ readonly name: string;
36
+ protected readonly engine: DockerEngine;
37
+ static options(config: SandboxProviderConfig): DockerSandboxOptions;
38
+ constructor(id: string, config: SandboxProviderConfig, options?: DockerSandboxOptions, engine?: DockerEngine);
39
+ start(tenant: SandboxTenant): Promise<SandboxEndpoint>;
40
+ stop(tenant: SandboxTenant): Promise<void>;
41
+ state(tenant: SandboxTenant): Promise<SandboxState>;
42
+ /** What `docker run` would be given. */
43
+ spec(tenant: SandboxTenant): object;
44
+ protected containerName(tenant: SandboxTenant): string;
45
+ }
@@ -0,0 +1,110 @@
1
+ import { DockerEngine, DockerEngineUtil } from './docker-engine.js';
2
+ import { SandboxProviders, } from './sandbox-provider.js';
3
+ export var DockerSandboxUtil;
4
+ (function (DockerSandboxUtil) {
5
+ /** `github:Octo.Cat` → `octo-cat`: a name of a host from the account, `ta` when nothing is left. */
6
+ function hostname(account) {
7
+ const name = account
8
+ .slice(account.indexOf(':') + 1)
9
+ .split('@')[0]
10
+ .toLowerCase()
11
+ .replace(/[^a-z0-9]+/g, '-')
12
+ .replace(/^-+|-+$/g, '')
13
+ .slice(0, 48)
14
+ .replace(/-+$/, '');
15
+ return name || 'ta';
16
+ }
17
+ DockerSandboxUtil.hostname = hostname;
18
+ })(DockerSandboxUtil || (DockerSandboxUtil = {}));
19
+ /** The port of ta serve in the image (its Dockerfile). */
20
+ const PORT = '4100/tcp';
21
+ /**
22
+ * `docker`: a container per tenant, its home (sessions, model accounts, workspace) in a volume of its own,
23
+ * with limits of memory, CPU and processes, in a network where sandboxes cannot reach each other. Its port is
24
+ * published on `bind` only (127.0.0.1): the gateway is the way in.
25
+ */
26
+ export class DockerSandbox {
27
+ static options(config) {
28
+ var _a;
29
+ const number = (key, fallback) => {
30
+ var _a;
31
+ const value = (_a = config[key]) !== null && _a !== void 0 ? _a : fallback;
32
+ if (typeof value !== 'number' || value < 0) {
33
+ throw new Error(`"${key}" of a provider of the type docker is a number.`);
34
+ }
35
+ return value || undefined;
36
+ };
37
+ return {
38
+ image: SandboxProviders.string(config, 'image', 'ta:latest'),
39
+ host: SandboxProviders.string(config, 'host'),
40
+ memory: DockerEngineUtil.bytes((_a = config.memory) !== null && _a !== void 0 ? _a : '4g'),
41
+ cpus: number('cpus', 2),
42
+ pids: number('pids', 1024),
43
+ network: SandboxProviders.string(config, 'network', 'ta-sandbox'),
44
+ bind: SandboxProviders.string(config, 'bind', '127.0.0.1'),
45
+ address: SandboxProviders.string(config, 'address', '127.0.0.1'),
46
+ prefix: SandboxProviders.string(config, 'prefix', 'ta-'),
47
+ env: SandboxProviders.env(config),
48
+ };
49
+ }
50
+ constructor(id, config, options = DockerSandbox.options(config), engine) {
51
+ this.id = id;
52
+ this.options = options;
53
+ this.type = 'docker';
54
+ this.name = SandboxProviders.string(config, 'name', 'Docker');
55
+ this.engine = engine !== null && engine !== void 0 ? engine : new DockerEngine({ host: options.host });
56
+ }
57
+ async start(tenant) {
58
+ var _a, _b, _c;
59
+ const name = this.containerName(tenant);
60
+ let container = await this.engine.inspect(name);
61
+ if (!container) {
62
+ await this.engine.ensureImage(this.options.image);
63
+ await this.engine.ensureNetwork(this.options.network, true);
64
+ await this.engine.create(name, this.spec(tenant));
65
+ container = await this.engine.inspect(name);
66
+ }
67
+ if (!(container === null || container === void 0 ? void 0 : container.State.Running)) {
68
+ await this.engine.start(name);
69
+ container = await this.engine.inspect(name);
70
+ }
71
+ const port = (_c = (_b = (_a = container === null || container === void 0 ? void 0 : container.NetworkSettings.Ports) === null || _a === void 0 ? void 0 : _a[PORT]) === null || _b === void 0 ? void 0 : _b[0]) === null || _c === void 0 ? void 0 : _c.HostPort;
72
+ if (!port) {
73
+ throw new Error(`The container ${name} publishes no port for ${PORT}.`);
74
+ }
75
+ return { url: `http://${this.options.address}:${port}`, token: tenant.token };
76
+ }
77
+ async stop(tenant) {
78
+ await this.engine.stop(this.containerName(tenant));
79
+ }
80
+ async state(tenant) {
81
+ const container = await this.engine.inspect(this.containerName(tenant));
82
+ return !container ? 'missing' : container.State.Running ? 'running' : 'stopped';
83
+ }
84
+ /** What `docker run` would be given. */
85
+ spec(tenant) {
86
+ const name = this.containerName(tenant);
87
+ return {
88
+ Image: this.options.image,
89
+ // What the Ta of the tenant tells its clients its machine is, as the list of computers of the phone shows it.
90
+ Hostname: DockerSandboxUtil.hostname(tenant.account),
91
+ Env: [`TA_SERVE_TOKEN=${tenant.token}`, ...Object.entries(this.options.env).map(([key, value]) => `${key}=${value}`)],
92
+ Labels: { 'cell.ta.tenant': tenant.id, 'cell.ta.account': tenant.account },
93
+ ExposedPorts: { [PORT]: {} },
94
+ HostConfig: {
95
+ PortBindings: { [PORT]: [{ HostIp: this.options.bind, HostPort: '' }] },
96
+ Mounts: [{ Type: 'volume', Source: name, Target: '/home/ta' }],
97
+ NetworkMode: this.options.network,
98
+ Memory: this.options.memory,
99
+ NanoCpus: this.options.cpus ? Math.round(this.options.cpus * 1e9) : undefined,
100
+ PidsLimit: this.options.pids,
101
+ RestartPolicy: { Name: 'unless-stopped' },
102
+ Init: false,
103
+ },
104
+ };
105
+ }
106
+ containerName(tenant) {
107
+ return `${this.options.prefix}${tenant.id}`;
108
+ }
109
+ }
110
+ //# sourceMappingURL=docker-sandbox.js.map