tailcat-webui 0.0.0-stage → 0.1.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 (54) hide show
  1. package/LICENSE +21 -0
  2. package/NOTICE +23 -0
  3. package/README.en.md +104 -0
  4. package/README.md +93 -2
  5. package/bin/tailcat-webui.js +12 -0
  6. package/docs/CORE-API.md +343 -0
  7. package/docs/DESIGN.md +378 -0
  8. package/docs/screenshots/01-overview-light.png +0 -0
  9. package/docs/screenshots/02-overview-dark.png +0 -0
  10. package/docs/screenshots/03-ticket-light.png +0 -0
  11. package/docs/screenshots/04-ticket-qr-light.png +0 -0
  12. package/docs/screenshots/05-settings-light.png +0 -0
  13. package/docs/screenshots/06-diagnostics-light.png +0 -0
  14. package/docs/screenshots/07-mobile-overview.png +0 -0
  15. package/docs/screenshots/08-install-missing.png +0 -0
  16. package/package.json +56 -4
  17. package/src/cli.js +238 -0
  18. package/src/config.js +167 -0
  19. package/src/devices.js +163 -0
  20. package/src/errors.js +24 -0
  21. package/src/index.js +19 -0
  22. package/src/installer.js +907 -0
  23. package/src/manager.js +647 -0
  24. package/src/parse.js +207 -0
  25. package/src/paths.js +97 -0
  26. package/src/preferences.js +190 -0
  27. package/src/qr.js +37 -0
  28. package/src/relay.js +76 -0
  29. package/src/runtime/node.js +281 -0
  30. package/src/serve-targets.js +127 -0
  31. package/src/server.js +669 -0
  32. package/src/settings.js +262 -0
  33. package/src/supervisor.js +833 -0
  34. package/vendor/qrcode.mjs +2289 -0
  35. package/web/api.js +114 -0
  36. package/web/boot.js +29 -0
  37. package/web/components.js +504 -0
  38. package/web/dict.js +655 -0
  39. package/web/drawer-access.js +318 -0
  40. package/web/drawer-address.js +271 -0
  41. package/web/drawer-automation.js +223 -0
  42. package/web/drawer-relay.js +128 -0
  43. package/web/drawer-tunnel.js +309 -0
  44. package/web/drawer.js +302 -0
  45. package/web/format.js +252 -0
  46. package/web/icon.svg +11 -0
  47. package/web/index.html +29 -0
  48. package/web/main.js +471 -0
  49. package/web/room-diagnostics.js +426 -0
  50. package/web/room-overview.js +416 -0
  51. package/web/room-settings.js +71 -0
  52. package/web/store.js +168 -0
  53. package/web/styles.css +2741 -0
  54. package/web/ticket.js +212 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 the tailcat-webui authors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/NOTICE ADDED
@@ -0,0 +1,23 @@
1
+ tailcat-webui
2
+ Copyright (c) 2026 ds-hu
3
+
4
+ Third-party attributions
5
+ ========================
6
+
7
+ Cat icon
8
+ icon.svg is adapted from Twemoji (https://github.com/jdecked/twemoji),
9
+ U+1F431 "cat face". Twemoji graphics are licensed under the Creative
10
+ Commons Attribution 4.0 International license (CC-BY 4.0):
11
+ https://creativecommons.org/licenses/by/4.0/
12
+ Copyright 2020 Twitter, Inc and other contributors.
13
+ Changes: recolored to the project palette, simplified for a 48 px tile,
14
+ and placed on a dark rounded tile.
15
+
16
+ tailcat
17
+ This package manages the tailcat CLI but does not redistribute it.
18
+ tailcat is Copyright (c) Tailscale Inc. and contributors, licensed under
19
+ the BSD 3-Clause license: https://github.com/tailscale/tailcat
20
+
21
+ qrcode-generator
22
+ vendor/qrcode.mjs is qrcode-generator by Kazuhiko Arase, licensed under
23
+ the MIT license: https://github.com/kazuhikoarase/qrcode-generator
package/README.en.md ADDED
@@ -0,0 +1,104 @@
1
+ English · [简体中文](README.md)
2
+
3
+ # tailcat-webui
4
+
5
+ A quiet console for [tailcat](https://github.com/tailscale/tailcat): manage the tunnel, port
6
+ mappings, and client tickets in a browser. The console listens on loopback only; remote access is
7
+ the tailcat tunnel itself.
8
+
9
+ ## Features
10
+
11
+ - **One command to start**: `npx tailcat-webui`, then open `http://127.0.0.1:17890/`.
12
+ - **Ticket**: address, QR code, and the `tailcat forward` command a client runs, on one ticket you
13
+ copy or scan.
14
+ - **Tunnel**: start, stop, restart, rotate the address, or pin the exit to a region or relay host.
15
+ - **Identity and access**: saved key or ephemeral address, PSK, hybrid post-quantum handshake, device
16
+ allow-list, access log.
17
+ - **Relay**: the default relay map, or a custom DERP map URL saved separately and copied to the client.
18
+ - **Install tailcat**: detect the local version and, when needed, install a verified upstream release
19
+ into the state directory; Homebrew works on macOS too.
20
+ - **Quiet and local**: binds `127.0.0.1`/`::1` only, opens no public port, and never touches the
21
+ system firewall or proxy settings.
22
+
23
+ ## Requirements
24
+
25
+ - Node.js >= 20.19 (ESM, no build step, no runtime dependencies)
26
+ - tailcat >= 0.8.0 on `PATH`, at a configured path, or installed from the console
27
+
28
+ ## Quick start
29
+
30
+ ```sh
31
+ npx tailcat-webui
32
+ # or from a checkout:
33
+ node bin/tailcat-webui.js
34
+ ```
35
+
36
+ 1. Open the URL the console prints (by default <http://127.0.0.1:17890/>).
37
+ 2. Under Settings → Tunnel and identity, add one port mapping, e.g. virtual port `13080` to
38
+ `localhost:8080`.
39
+ 3. Start the tunnel and hand the ticket's address, QR code, and command to the client.
40
+
41
+ ## The ticket
42
+
43
+ The standalone console pairs **the first saved port mapping**, and the command forwards that virtual
44
+ port to `18080` on the client:
45
+
46
+ ```
47
+ tailcat forward tc… 18080:13080
48
+ ```
49
+
50
+ With no mapping saved there is nothing to forward, so the ticket shows only the address and the QR
51
+ code, and no command. The address is never written to logs.
52
+
53
+ Run the forward on the client and open `http://127.0.0.1:18080/`. Both sides must use the same relay
54
+ map: if a custom DERP map URL is saved, copy it to the client as `TAILCAT_DERPMAP_URL=<url>` unless
55
+ the address embeds its relay nodes.
56
+
57
+ ## Options
58
+
59
+ ```
60
+ tailcat-webui [--port <n>] [--binary <path>] [--state-dir <dir>] [--no-open] [--open] [--version] [--help]
61
+ ```
62
+
63
+ | Flag | Meaning |
64
+ | --- | --- |
65
+ | `--port <n>` | Local console port (default `17890`). An occupied port is an error; no silent fallback. |
66
+ | `--binary <path>` | tailcat executable name or path (default `tailcat`). |
67
+ | `--state-dir <dir>` | Where preferences, the device allow-list, and a managed tailcat live. |
68
+ | `--open` / `--no-open` | Try to open the system browser after starting (default: do not). |
69
+ | `--version` / `--help` | Print the version or usage. |
70
+
71
+ `SIGINT` and `SIGTERM` stop the tunnel and exit 0. Configuration and startup failures exit 1.
72
+
73
+ ## Screenshots
74
+
75
+ The Screenshots workflow captures the interface against a real server and stores the images in
76
+ `docs/screenshots/`:
77
+
78
+ ![Overview, light](docs/screenshots/01-overview-light.png)
79
+
80
+ | Ticket | QR code |
81
+ | --- | --- |
82
+ | ![Ticket](docs/screenshots/03-ticket-light.png) | ![QR code](docs/screenshots/04-ticket-qr-light.png) |
83
+
84
+ | Settings | Diagnostics |
85
+ | --- | --- |
86
+ | ![Settings](docs/screenshots/05-settings-light.png) | ![Diagnostics](docs/screenshots/06-diagnostics-light.png) |
87
+
88
+ | Dark overview | Phone (390×844) |
89
+ | --- | --- |
90
+ | ![Dark overview](docs/screenshots/02-overview-dark.png) | ![Phone overview](docs/screenshots/07-mobile-overview.png) |
91
+
92
+ When tailcat is not installed:
93
+
94
+ ![tailcat is not installed](docs/screenshots/08-install-missing.png)
95
+
96
+ ## Documentation
97
+
98
+ - Core API contract and security model: [docs/CORE-API.md](docs/CORE-API.md)
99
+ - Visual and interaction spec: [docs/DESIGN.md](docs/DESIGN.md)
100
+ - Attribution for the bundled QR encoder: [NOTICE](NOTICE)
101
+
102
+ ## License
103
+
104
+ MIT.
package/README.md CHANGED
@@ -1,3 +1,94 @@
1
- # Temporary Holding Version
1
+ [English](README.en.md) · 简体中文
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
+ # tailcat-webui
4
+
5
+ 给 [tailcat](https://github.com/tailscale/tailcat) 的一间安静控制台:在浏览器里管理隧道、
6
+ 端口映射与客户端票根。控制台只监听本机回环地址,远程访问交给 tailcat 的加密隧道。
7
+
8
+ ## 功能
9
+
10
+ - **一条命令起控制台**:`npx tailcat-webui`,打开 `http://127.0.0.1:17890/` 即可用。
11
+ - **票根**:地址、二维码和客户端要执行的 `tailcat forward` 命令放在同一张票上,复制或扫码带走。
12
+ - **隧道**:启动、停止、重启、更换地址,按区域或中继主机固定出口。
13
+ - **身份与访问**:保存密钥或临时地址、PSK、混合后量子握手、设备白名单、访问日志。
14
+ - **中继**:默认中继表,或自定义 DERP map URL(独立保存,可同步给客户端)。
15
+ - **安装 tailcat**:检测本机版本,必要时把校验过的发布包装进状态目录;macOS 也可以用 Homebrew。
16
+ - **安静且本地**:只绑定 `127.0.0.1`/`::1`,只监听、不对外开端口,不接管系统防火墙或代理。
17
+
18
+ ## 环境要求
19
+
20
+ - Node.js >= 20.19(ESM,无构建步骤,无运行时依赖)
21
+ - tailcat >= 0.8.0:在 `PATH` 里、配置的路径上,或由控制台安装
22
+
23
+ ## 快速开始
24
+
25
+ ```sh
26
+ npx tailcat-webui
27
+ # 或在仓库里:
28
+ node bin/tailcat-webui.js
29
+ ```
30
+
31
+ 1. 打开控制台打印的本机地址(默认 <http://127.0.0.1:17890/>)。
32
+ 2. 在“设置 → 隧道与身份”里添加一条端口映射,例如虚拟端口 `13080` 指向 `localhost:8080`。
33
+ 3. 启动隧道,把总览里的票根地址、二维码和命令交给客户端。
34
+
35
+ ## 票根
36
+
37
+ 独立控制台的票根配对**第一条已保存的端口映射**,命令把那个虚拟端口转到客户端的 `18080`:
38
+
39
+ ```
40
+ tailcat forward tc… 18080:13080
41
+ ```
42
+
43
+ 还没有保存映射时,没有可转发的东西,票根只显示地址与二维码,不显示命令。地址不会写进日志。
44
+
45
+ 客户端执行转发后打开 `http://127.0.0.1:18080/`。两端必须使用同一张中继表:如果保存了自定义
46
+ DERP map URL,把它作为 `TAILCAT_DERPMAP_URL=<url>` 同步给客户端;地址自带中继节点时除外。
47
+
48
+ ## 参数
49
+
50
+ ```
51
+ tailcat-webui [--port <n>] [--binary <path>] [--state-dir <dir>] [--no-open] [--open] [--version] [--help]
52
+ ```
53
+
54
+ | 参数 | 含义 |
55
+ | --- | --- |
56
+ | `--port <n>` | 控制台本地端口(默认 `17890`)。端口被占用直接报错,不自动换端口。 |
57
+ | `--binary <path>` | tailcat 可执行文件的名字或路径(默认 `tailcat`)。 |
58
+ | `--state-dir <dir>` | 偏好、设备白名单和受管 tailcat 的存放目录。 |
59
+ | `--open` / `--no-open` | 启动后是否尝试打开系统浏览器(默认不打开)。 |
60
+ | `--version` / `--help` | 打印版本或帮助。 |
61
+
62
+ `SIGINT` / `SIGTERM` 会先停止隧道再以 0 退出;配置或启动失败以 1 退出。
63
+
64
+ ## 截图
65
+
66
+ 截图由仓库的 Screenshots 工作流在真实服务上生成,保存在 `docs/screenshots/`:
67
+
68
+ ![总览(浅色)](docs/screenshots/01-overview-light.png)
69
+
70
+ | 票根 | 二维码 |
71
+ | --- | --- |
72
+ | ![票根](docs/screenshots/03-ticket-light.png) | ![二维码](docs/screenshots/04-ticket-qr-light.png) |
73
+
74
+ | 设置 | 诊断 |
75
+ | --- | --- |
76
+ | ![设置](docs/screenshots/05-settings-light.png) | ![诊断](docs/screenshots/06-diagnostics-light.png) |
77
+
78
+ | 深色总览 | 手机(390×844) |
79
+ | --- | --- |
80
+ | ![深色总览](docs/screenshots/02-overview-dark.png) | ![手机总览](docs/screenshots/07-mobile-overview.png) |
81
+
82
+ 未安装 tailcat 时的状态:
83
+
84
+ ![未安装 tailcat](docs/screenshots/08-install-missing.png)
85
+
86
+ ## 文档
87
+
88
+ - 核心 API 契约与安全模型:[docs/CORE-API.md](docs/CORE-API.md)
89
+ - 视觉与交互规范:[docs/DESIGN.md](docs/DESIGN.md)
90
+ - 内置二维码编码器的版权说明:[NOTICE](NOTICE)
91
+
92
+ ## 许可证
93
+
94
+ MIT。
@@ -0,0 +1,12 @@
1
+ #!/usr/bin/env node
2
+ import { main } from '../src/cli.js';
3
+
4
+ main(process.argv.slice(2)).then(
5
+ (code) => {
6
+ process.exitCode = code;
7
+ },
8
+ (error) => {
9
+ process.stderr.write(`${error instanceof Error ? error.message : String(error)}\n`);
10
+ process.exitCode = 1;
11
+ },
12
+ );
@@ -0,0 +1,343 @@
1
+ # tailcat-webui 核心 API 契约
2
+
3
+ 本文是 `tailcat-webui` 的公共契约。嵌入方只允许通过这里列出的导出与选项使用它;
4
+ `tailcat-webui` **不认识、不引用、不提及任何嵌入方的专有概念**。
5
+
6
+ 包目标:零运行时依赖(只用 Node 内置模块),Node >= 20.19,ESM,直接发布源码,无构建步骤。
7
+
8
+ ## 1. 对外导出(`src/index.js`)
9
+
10
+ ```js
11
+ export { createTailcatManager, TailcatManager } from './manager.js';
12
+ export { resolveConfig, configView, CONFIG_DEFAULTS, MIN_TAILCAT_VERSION } from './config.js';
13
+ export { createFilePreferenceStore } from './preferences.js';
14
+ export { createFileDeviceStore } from './devices.js';
15
+ export { createNodeRuntime } from './runtime/node.js';
16
+ export { RemoteAccessError, errorMessage } from './errors.js';
17
+ export { normalizeServeTargets, normalizeServeTarget, serveTargetRow } from './serve-targets.js';
18
+ export { buildForwardCommand, buildGenkeyArgs, buildServeArgs, parseAddressLine, parseRegionLine, parseAccessLine, sanitizeLine } from './parse.js';
19
+ export { qrMatrix } from './qr.js';
20
+ export { tailcatKeyPath, userConfigDir, findKnownTailcat, knownTailcatPaths, defaultStateDir } from './paths.js';
21
+ export { TailcatInstaller, TAILCAT_VERSION, TAILCAT_TAG, MANUAL_INSTALL_URL, platformSpec } from './installer.js';
22
+ ```
23
+
24
+ `package.json` 导出:
25
+
26
+ ```json
27
+ {
28
+ "name": "tailcat-webui",
29
+ "type": "module",
30
+ "main": "src/index.js",
31
+ "exports": {
32
+ ".": "./src/index.js",
33
+ "./core": "./src/index.js",
34
+ "./server": "./src/server.js",
35
+ "./package.json": "./package.json"
36
+ },
37
+ "bin": { "tailcat-webui": "./bin/tailcat-webui.js" }
38
+ }
39
+ ```
40
+
41
+ ## 2. 配置
42
+
43
+ 核心配置只有 tailcat 自身的维度,没有宿主端口/监听方式。
44
+
45
+ ```jsonc
46
+ {
47
+ "binaryPath": "tailcat", // PATH 名或绝对路径
48
+ "keyName": "tailcat-webui", // 默认键名;嵌入方可传自己的键名
49
+ "addressMode": "stable", // stable | ephemeral
50
+ "derpMapUrl": "", // 部署级默认 DERP map;空 = tailcat 默认
51
+ "regionMode": "auto", // auto | explicit | hosts
52
+ "regionValue": "",
53
+ "psk": true,
54
+ "hybrid": false,
55
+ "fullAddress": false,
56
+ "verbose": false,
57
+ "extraTargets": [], // canonical "virtual:target" 列表
58
+ "autoStart": true,
59
+ "logAccess": true,
60
+ "restartEnabled": true,
61
+ "maxRestartAttempts": 10,
62
+ "restartBaseDelayMs": 500,
63
+ "restartMaxDelayMs": 30000
64
+ }
65
+ ```
66
+
67
+ `resolveConfig(input, { reservedPorts = [] } = {})`:容错归一化,任何非法值回退默认值;
68
+ `extraTargets` 用 `reservedPorts` 校验后保留合法项(非法项丢弃,不抛)。`configView(config)`
69
+ 只返回可展示字段(无密钥路径、无地址)。
70
+
71
+ `CONFIG_DEFAULTS` 是上述默认值的冻结对象。`MIN_TAILCAT_VERSION = '0.8.0'`。
72
+
73
+ ## 3. Manager
74
+
75
+ ```js
76
+ const manager = createTailcatManager({
77
+ config, // 原始或已 resolve 的配置;内部再 resolveConfig 一次
78
+ stateDir, // 必填:devices.json / preferences.json / bin/ 的父目录
79
+ logger, // 可选:{ info(msg), warn(msg), debug?(msg) }
80
+ runtime, // 可选:进程适配器,默认 createNodeRuntime()
81
+ preferences, // 可选:自定义偏好存储(嵌入方可用它保留自己的键)
82
+ devices, // 可选:自定义白名单存储
83
+ serve: {
84
+ targets: () => string[], // 必填:完整的 canonical serve 列表;空数组表示没有可服务目标
85
+ reservedPorts: () => number[], // 可选:额外端口不得使用的虚拟端口
86
+ ready: () => Promise<void>, // 可选:启动 tailcat 前的就绪钩子(如宿主的端点检查)
87
+ validate: (settings) => void, // 可选:宿主附加校验(抛 RemoteAccessError)
88
+ label: 'target' // 可选:错误文案里的目标称谓,默认 'serve target'
89
+ },
90
+ pairing: {
91
+ virtualPort: () => number | null, // 可选:票根命令使用的虚拟端口;null 则省略命令
92
+ localPort: 18080 // 可选:客户端本地端口,默认 18080
93
+ },
94
+ installer: {
95
+ enabled: true, // 默认 true
96
+ installDir: path.join(stateDir, 'bin'), // 默认
97
+ releaseTag: 'v0.1.0', // 可选:写入元数据的包版本标签
98
+ paths: { dataDir, binaryDir, binaryPath, stagingRoot } // 可选:完全覆盖安装路径
99
+ },
100
+ clientForwardHint: '…' // 可选:票根/命令说明的宿主补充文案(独立包不用)
101
+ });
102
+ ```
103
+
104
+ ### 3.1 方法
105
+
106
+ | 方法 | 行为 |
107
+ | --- | --- |
108
+ | `activate()` | `installer.detectSystem()`;若 `autoStart` 且 `serve.targets()` 非空则启动隧道。启动失败只记录日志、返回快照,不抛。 |
109
+ | `startTunnel()` | 串行:`serve.ready?.()` → `installer.detectSystem()` → `tailcat.start()` → 快照。 |
110
+ | `stopTunnel()` | 串行:`tailcat.stop()` → 快照。 |
111
+ | `restartTunnel()` | 串行:ready → detectSystem → `tailcat.restart()` → 快照。 |
112
+ | `rotateAddress(region?)` | 串行:先保存 region patch(仅 stable 模式;ephemeral 抛 `invalid-settings`)→ ready → detectSystem → `tailcat.rotate()` → 快照。 |
113
+ | `saveSettings(patch)` | 串行:归一化 → 合并 → 校验(核心 + `serve.reservedPorts` + `serve.validate`)→ 持久化 → 运行中且字段需要重启时重启并等 30s 上线;失败回滚旧覆盖并重启旧设置。失败抛 `settings-start-failed` / `settings-apply-failed`。 |
114
+ | `saveDevices(allow)` | 串行:持久化白名单;运行中则重启(重启失败只告警,白名单保留)。 |
115
+ | `saveDerpMapUrl(url)` | 串行:持久化 map 偏好;运行中重启并等上线,失败回滚旧 map 并重启。 |
116
+ | `installTailcat({force})` | 串行:`binaryPath` 不是 `tailcat` 时抛 `tailcat-binary-overridden`;停止 → 安装 → 重载可执行文件 → 恢复之前的运行意图。 |
117
+ | `detectSystem()` | 只读探测系统 tailcat(不下载、不写文件)。 |
118
+ | `action(action, payload)` | 分发表,见 3.4。 |
119
+ | `snapshot()` | 同步只读快照,见 3.2。 |
120
+ | `dispose()` | 取消安装、停子进程、等操作队列清空。幂等。 |
121
+
122
+ 所有变更操作内部串行(`enqueue`),两个并发请求不会起两个进程;`disposed` 后抛
123
+ `RemoteAccessError('disposed', …, 503)`。
124
+
125
+ ### 3.2 `snapshot()` 形状
126
+
127
+ ```jsonc
128
+ {
129
+ "now": "2026-12-05T12:00:00.000Z",
130
+ "config": {
131
+ "binaryPath": "tailcat", "keyName": "tailcat-webui", "addressMode": "stable",
132
+ "autoStart": true, "logAccess": true, "restartEnabled": true,
133
+ "maxRestartAttempts": 10, "restartBaseDelayMs": 500, "restartMaxDelayMs": 30000,
134
+ "customDerpMap": false
135
+ },
136
+ "settings": {
137
+ /* 生效值 + */
138
+ "sources": { "addressMode": "config|panel", "...": "..." }
139
+ },
140
+ "relay": {
141
+ "mapUrl": "", "custom": false, "source": "default|config|panel",
142
+ "insecure": false, "fullAddress": false, "needsClientMap": false, "clientEnv": ""
143
+ },
144
+ "tailcat": {
145
+ "phase": "stopped|starting|online|stopping|error",
146
+ "desired": true, "address": "tc…", "keyMode": "saved|ephemeral",
147
+ "keyName": "tailcat-webui", "addressMode": "stable",
148
+ "targets": ["13080:unix:/…/sock"],
149
+ "region": { "id": 304, "name": "Tokyo" },
150
+ "binary": { "requested": "tailcat", "resolved": "/usr/local/bin/tailcat", "source": "path|config|managed", "version": "v0.8.0", "error": null },
151
+ "restarts": 0, "lastError": null, "lastExit": null, "warnings": [],
152
+ "stderrTail": [], "recent": [], "refusals": 0,
153
+ "startedAt": null, "onlineAt": null, "nextRestartAt": null
154
+ },
155
+ "installer": { /* 见 installer.snapshot(),字段与现在一致 */ },
156
+ "devices": { "allow": [], "enforced": false, "count": 0, "file": "…", "updatedAt": null, "warnings": [] },
157
+ "preferences": { "derpMapUrl": "", "settings": {}, "file": "…", "updatedAt": null, "warnings": [], /* 自定义存储可附加字段 */ },
158
+ "pairing": {
159
+ "address": "tc…", "port": 13080, "localPort": 18080,
160
+ "command": "tailcat forward tc… 18080:13080",
161
+ "qr": { "size": 41, "rows": ["100…"] }, // 失败时 null
162
+ "targets": ["13080:unix:/…/sock"]
163
+ },
164
+ "warnings": [] // 顶层聚合:devices.warnings + preferences.warnings + installer.error(可空)
165
+ }
166
+ ```
167
+
168
+ - `pairing` 在地址为空时是 `null`。
169
+ - `pairing.command` 在 `pairing.virtualPort()` 为 null 或地址为空时是 `null`。
170
+ - 地址只发给宿主页面;不写进日志。
171
+ - `tailcat.endpoint` 是调用方的概念,不由核心输出;嵌入方在包装快照时自行补。
172
+
173
+ ### 3.3 错误
174
+
175
+ `RemoteAccessError(code, message, status)`,status 默认 500。核心使用的错误码:
176
+
177
+ `invalid-settings`(400) · `invalid-preference`(400) · `invalid-derp-map-url`(400) ·
178
+ `invalid-allow-list`(400) · `tailcat-not-found`(503) · `tailcat-version-too-old`(503) ·
179
+ `tailcat-spawn-failed`(503) · `tailcat-command-failed`(502) · `key-not-created`(500) ·
180
+ `settings-start-failed`(502) · `settings-apply-failed`(502) · `derp-map-start-failed`(502) ·
181
+ `derp-map-apply-failed`(502) · `tailcat-binary-overridden`(409) · `tailcat-platform-unsupported`(400) ·
182
+ `tailcat-checksum-missing`(502) · `tailcat-checksum-mismatch`(502) · `tailcat-archive-invalid`(502) ·
183
+ `tailcat-brew-missing`(503) · `tailcat-install-aborted`(503) · `install-busy`(409) · `disposed`(503)。
184
+ 消息用英文,面向操作者;不出现调用方的专有名词。
185
+
186
+ ### 3.4 `action(action, payload)`
187
+
188
+ `start` · `stop` · `restart` · `rotate`(payload 可有 `region`)· `settings`(`settings` patch)·
189
+ `devices`(`allow` 数组)· `derpMap`(`derpMapUrl`)· `install`(`force`)。未知动作抛
190
+ `unknown-action`(400)。嵌入方在此之上可加自己的动作(如界面偏好),但不得改核心动作含义。
191
+
192
+ ## 4. 进程适配器(runtime)
193
+
194
+ ```js
195
+ /**
196
+ * @typedef {object} ProcRuntime
197
+ * @property {(command: string, env?: Record<string,string>, signal?: AbortSignal) => Promise<string>} resolveExecutable
198
+ * @property {(spec: SpawnSpec) => ProcHandle} spawn
199
+ */
200
+
201
+ /** SpawnSpec */
202
+ {
203
+ argv: string[],
204
+ cwd: string,
205
+ env: Record<string, string>,
206
+ stdio: {
207
+ stdin: 'ignore',
208
+ stdout: 'pipe' | { maxBytes: number },
209
+ stderr: 'pipe' | { maxBytes: number }
210
+ },
211
+ graceMs?: number,
212
+ signal?: AbortSignal
213
+ }
214
+
215
+ /** ProcHandle */
216
+ {
217
+ stdout: NodeJS.ReadableStream | null, // 仅在 stdio=pipe 时非空
218
+ stderr: NodeJS.ReadableStream | null,
219
+ collected: { // 仅在 stdio={maxBytes} 时非空
220
+ stdout?: { readFrom(offset: number): { text: string, total?: number } },
221
+ stderr?: { readFrom(offset: number): { text: string, total?: number } }
222
+ },
223
+ done: Promise<{ exitCode: number | null, signal?: string } | { error: Error }>,
224
+ terminate(): void, // 优雅终止,graceMs 后升级
225
+ waitForExit(signal?: AbortSignal): Promise<{ exitCode: number | null }>
226
+ }
227
+ ```
228
+
229
+ - `createNodeRuntime()` 用 `node:child_process` 实现上述语义:`resolveExecutable` 走 PATH +
230
+ 绝对路径校验(不执行 shell);`spawn` 用 `child_process.spawn(argv[0], argv.slice(1))`,
231
+ collected 模式用带 maxBytes 上限的缓冲;`terminate` 先 SIGTERM,`graceMs` 后 SIGKILL;
232
+ Windows 用 `taskkill /T` 或等价手段。
233
+ - 嵌入方可以直接把自带的进程适配器作为 runtime 传入(接口与本契约兼容即可)。
234
+
235
+ ## 5. 存储
236
+
237
+ ### 5.1 偏好存储
238
+
239
+ ```js
240
+ createFilePreferenceStore({ dir, logger }) -> {
241
+ file,
242
+ snapshot(): { derpMapUrl, settings, file, updatedAt, warnings },
243
+ setDerpMapUrl(url),
244
+ setSettings(patch),
245
+ reload()
246
+ }
247
+ ```
248
+
249
+ - 文件:`<dir>/preferences.json`,版本 `2`,0600,原子写(临时文件 + rename)。
250
+ - 自定义键必须保留(嵌入方自己的键会出现在同一文件里;核心不读不懂,但要原样写回)。
251
+ - 损坏/缺字段回退默认并给 warnings,不抛。
252
+
253
+ ### 5.2 白名单存储
254
+
255
+ ```js
256
+ createFileDeviceStore({ dir, logger }) -> {
257
+ file,
258
+ snapshot(): { allow, enforced, count, file, updatedAt, warnings },
259
+ replace(list),
260
+ reload()
261
+ }
262
+ ```
263
+
264
+ - 文件:`<dir>/devices.json`,0600,原子写;接受 `{"allow": [...]}` 或裸数组;
265
+ 行首 `#` 注释与空行丢弃;去重保序;非法内容回退空列表 + warning。
266
+ - `enforced = allow.length > 0`。
267
+
268
+ ## 6. 模块与文件
269
+
270
+ | 文件 | 责任 |
271
+ | --- | --- |
272
+ | `src/index.js` | 公共导出,仅 re-export |
273
+ | `src/config.js` | 默认值、容错归一化、`configView` |
274
+ | `src/errors.js` | `RemoteAccessError` / `errorMessage` |
275
+ | `src/paths.js` | 平台配置/状态目录、tailcat key 路径、已知安装位置、`defaultStateDir()` |
276
+ | `src/parse.js` | tailcat stdout/stderr 解析、`buildServeArgs` / `buildGenkeyArgs` / `buildForwardCommand`、日志脱敏 |
277
+ | `src/serve-targets.js` | `virtual:target` 归一化、重复/保留端口校验(不依赖宿主) |
278
+ | `src/settings.js` | 生效值合并、patch 归一化、`settingsSources`、`settingsNeedRestart`、校验(调用 serve 校验钩子) |
279
+ | `src/relay.js` | DERP map URL 归一化、`relayView` |
280
+ | `src/qr.js` + `vendor/qrcode.mjs` | 地址 → 矩阵(vendored qrcode-generator,MIT,保留版权头) |
281
+ | `src/devices.js` | 白名单文件存储 |
282
+ | `src/preferences.js` | 偏好文件存储 |
283
+ | `src/supervisor.js` | tailcat `serve` 进程:argv、输出解析、状态、重启退避、地址轮换 |
284
+ | `src/installer.js` | 检测系统 tailcat、受管安装(release 下载/校验/解压、Homebrew)、元数据 |
285
+ | `src/manager.js` | 门面:串行操作、快照、action 分发 |
286
+ | `src/runtime/node.js` | Node 进程适配器 |
287
+ | `src/server.js` | 独立 HTTP 服务:REST + 静态资源 |
288
+ | `src/cli.js` / `bin/tailcat-webui.js` | 命令行入口 |
289
+ | `web/` | 独立包前端(见 docs/DESIGN.md) |
290
+
291
+ ## 7. 独立 HTTP 服务
292
+
293
+ ```js
294
+ const app = createTailcatWebui({ config, stateDir, logger, port = 17890, host = '127.0.0.1' });
295
+ await app.start(); // 监听成功后再 activate()
296
+ app.url // http://127.0.0.1:17890/
297
+ await app.stop();
298
+ app.manager // 供测试/嵌入
299
+ ```
300
+
301
+ - 只允许绑定回环地址(`127.0.0.1` / `::1`);`host` 非回环直接抛错。
302
+ - `GET /api/state` → `{ ok: true, ...manager.snapshot(), server: { url, host, port } }`。
303
+ - `POST /api/action` → JSON `{ action, ... }`,返回 `{ ok: true, ...snapshot, server }`;
304
+ 失败 `{ ok: false, error: { code, message } }` + 对应状态码。
305
+ - 静态:`/` → `web/index.html`;`/assets/*` → `web/*`;`/icon.svg`;正确 content-type;
306
+ `cache-control: no-store`。禁止目录穿越(解析后必须落在 `web/` 内)。
307
+ - 安全(必须实现):
308
+ - `Host` 必须是回环 host(`127.0.0.1`、`localhost`、`[::1]`)且端口匹配,否则 421。
309
+ - `POST` 必须 `content-type: application/json`、`origin` 为空或与自身同源、
310
+ `x-tailcat-webui: 1` 请求头,否则 403。请求体 ≤ 64 KiB。
311
+ - 不设置 CORS 头;不写浏览器端登录状态;不支持 `--host 0.0.0.0`。
312
+ - 安全响应头:`x-content-type-options: nosniff`、`referrer-policy: no-referrer`、
313
+ `content-security-policy: default-src 'self'; img-src 'self' data:; style-src 'self' 'unsafe-inline'; script-src 'self'; connect-src 'self'`。
314
+ - 日志只写方法、路径、状态;不写地址/nodekey/body。
315
+
316
+ ## 8. CLI
317
+
318
+ ```
319
+ tailcat-webui [--port <n>] [--binary <path>] [--state-dir <dir>] [--no-open] [--open] [--version] [--help]
320
+ ```
321
+
322
+ - 默认 `port=17890`、`binary=tailcat`、`stateDir=defaultStateDir()`;端口占用抛清晰错误(不自动换端口)。
323
+ - 启动后打印一行 URL;`--open` 时才尝试打开系统浏览器(失败只提示)。
324
+ - `SIGINT`/`SIGTERM` → `app.stop()` 后退出 0。
325
+ - 退出码:配置/启动失败 1;正常退出 0。
326
+
327
+ ## 9. 测试与 CI(包内)
328
+
329
+ - `node --test`:parse/settings/serve-targets/relay/qr/devices/preferences/supervisor(假 runtime)/
330
+ installer(假 fetch、假 runtime,平台矩阵)/manager(假 runtime 端到端)/server(假 manager 或临时 stateDir)。
331
+ - 不访问网络、不写真实用户目录(临时目录 + 注入路径)。
332
+ - CI:ubuntu/windows/macos × node 20/22;`npm test`、`node --check bin/tailcat-webui.js`、
333
+ `npm pack --dry-run`。截图工作流用 CI 专用 tailcat stub(打印地址/访问日志)起真实 server,
334
+ 用 Playwright 截宽屏/窄屏 × 浅/深四张图,上传 artifact。
335
+ - 遵守仓库 AGENTS.md:本地不跑测试/构建/截图,全部在 GitHub Actions 验证。
336
+
337
+ ## 10. 独立包的边界(不要做)
338
+
339
+ - 不 import 任何调用方的专有包;不出现调用方的专有名词。
340
+ - 不内置自己的鉴权账号体系;默认只监听回环,远程访问请用 tailcat forward 把端口带过去。
341
+ - 不接管防火墙、不改系统代理、不写系统目录;安装只写 `stateDir/bin`。
342
+ - 不实现 tailcat 已有的服务类型(ssh/files/exec/exit-node/perf/all),只做普通端口映射与授权。
343
+ - 不伪造 tailcat 的行为:所有能力都通过 `tailcat` CLI 调用。