@alicloud/autowonder 0.3.33 → 0.3.34
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.md +15 -13
- package/bin/cli.js +25 -47
- package/bin/token-proxy-ca.js +129 -0
- package/bin/token-proxy-helper.js +52 -0
- package/bin/token-proxy-manager.js +114 -0
- package/bin/token-proxy-service.js +57 -0
- package/bin/token-proxy.js +27 -15
- package/package.json +1 -1
- package/vendor/autowonder-daemon-darwin-amd64 +0 -0
- package/vendor/autowonder-daemon-darwin-arm64 +0 -0
- package/vendor/autowonder-daemon-linux-amd64 +0 -0
- package/vendor/autowonder-daemon-linux-arm64 +0 -0
- package/vendor/autowonder-daemon-win32-amd64.exe +0 -0
- package/vendor/autowonder-daemon-win32-arm64.exe +0 -0
package/README.md
CHANGED
|
@@ -6,10 +6,10 @@ AutoWonder 本地 agent runtime。安装后启动 daemon,持续轮询本地 as
|
|
|
6
6
|
|
|
7
7
|
```bash
|
|
8
8
|
# Qoder CLI(模型使用 provider model ID;Context Window 使用固定档位)
|
|
9
|
-
npx -y autowonder@0.3.
|
|
9
|
+
npx -y @alicloud/autowonder@0.3.34 connect --ws-url <wss-endpoint> --token <executor-token> --executor-id <executor-id> --provider qoder --model qmodel_latest --reasoning-effort medium --context-window 260000
|
|
10
10
|
|
|
11
11
|
# Qoder CLI CN
|
|
12
|
-
npx -y autowonder@0.3.
|
|
12
|
+
npx -y @alicloud/autowonder@0.3.34 connect --ws-url <wss-endpoint> --token <executor-token> --executor-id <executor-id> --provider qodercn
|
|
13
13
|
```
|
|
14
14
|
|
|
15
15
|
`connect` 会安装当前 npm 包内置的 daemon,并使用页面生成的 WebSocket endpoint、Token 和执行器 ID 建立连接。客户端只支持通过 Qoder 系列 CLI 启动(`qoder` 对应 `qodercli`,`qodercn` 对应 `qodercn`),其他 `--provider` 取值会在启动 daemon 前直接报错拦截并提示 `Unsupported provider`。选择 Qoder CLI 或 Qoder CLI CN 时需要 Node.js 20+;runtime 会在缺少对应 CLI 时自动通过 npm 安装,并在尚未登录时打开浏览器登录。runtime 会继承当前用户的 HOME、环境变量和 CLI 登录状态。
|
|
@@ -39,11 +39,11 @@ daemon 还在协议能力位里声明 `TASK_MODEL_SELECTION_V1`:服务端可
|
|
|
39
39
|
|
|
40
40
|
daemon 建立执行器接入连接时会在 WebSocket URL 上附带本机主机名(取不到时不带该参数,服务端按未上报处理),服务端据此在执行器列表区分同一数字员工在多台机器上的执行器。对执行机用户无新增参数或环境变量。
|
|
41
41
|
|
|
42
|
-
daemon 还在协议能力位里声明 `terminal_steer_v1`:服务端可对当前正在执行的派单下发 `TASK_STEER` 终端插话(含 `guidanceId`、`dispatchId` 与内容)。daemon 只在该派单存在活跃 provider 回合时受理:协作式取消当前回合、等待退出后在同一 agent
|
|
42
|
+
daemon 还在协议能力位里声明 `terminal_steer_v1`:服务端可对当前正在执行的派单下发 `TASK_STEER` 终端插话(含 `guidanceId`、`dispatchId` 与内容)。daemon 只在该派单存在活跃 provider 回合时受理:协作式取消当前回合、等待退出后在同一 agent 会话内携带插话内容继续执行。终端插话的回执时机是「已交给 ACP 会话」而不是「插话回合执行成功」:插话内容写入 `session/prompt` 后立即回传 `TASK_STEER_ACK`(`APPLIED`),同一批插话只回执一次,插话回合随后失败、取消或超时都不会改写这条回执;提交本身失败时仍按回合结果回传 `FAILED`。评论续接等非终端插话批次仍在回合结束后回执。无活跃回合、回合已结束或接收队列已满时明确返回失败,不影响原任务状态。插话与评论投递、工作流回复路由相互独立(重复投递去重、回执可重放)。该能力对执行机用户无新增参数或环境变量。
|
|
43
43
|
|
|
44
44
|
daemon 还会响应服务端的 `CONVERSATION_COMMANDS_PROBE` 帧,用独立会话抓取该会话工作目录下可用的斜杠命令,回传 `CONVERSATION_COMMANDS_RESULT` 帧,让会话面板在用户输入 `/` 时列出真实可用的命令。该探测与回合执行完全隔离:任何失败只产生 `FAILED` / `TIMEOUT` 帧,不影响进行中的会话;provider 后端不支持抓取时同样降级为 `FAILED` 帧。帧里的 `executorId` 与本机不一致或非正数时直接忽略,避免在别的执行器工作区里建目录或启动 CLI。daemon 侧给整个探测 25 秒硬上限,刻意长于 agent 侧的 20 秒预算,使 agent 自己的超时先触发并可被归类。
|
|
45
45
|
|
|
46
|
-
给 `connect` 追加 `--token-aware-enable` 可开启 qoder / qodercn 的 token 用量采集:CLI
|
|
46
|
+
给 `connect` 追加 `--token-aware-enable` 可开启 qoder / qodercn 的 token 用量采集:CLI 会确保本机存在一个**共享**的本地 HTTPS 转发代理(`bin/token-proxy.js`)——同一用户、同一配置根、同一端口只保留一个实例,监听者属于共享服务而不是某个 daemon,退出某个执行器不会主动停掉它,数据目录为 `~/.autowonder/token-tap/`。代理从 Qoder API 的 SSE 响应流中提取 usage 数据并按 dispatch ID 归属上报。启用的 `connect` 用已安装 daemon 提供的 `token-proxy-helper` 核验监听者身份(系统监听者 owner、用户、进程出生时间、可执行路径与参数、脚本内容、profile),核验不通过的一律拒绝接管,健康响应里的 PID 本身不足以授权终止;健康检查同时验证到回环 echo 服务的 CONNECT 转发,模型/上游错误不触发重启,只有连续三次本地故障观测才在原生锁(macOS/Linux `flock`,Windows 按用户/scope 命名 mutex)下替换进程,且每 60 秒最多 3 次重启。CA 使用不可变 generation 目录加原子 `current.json` 指针,旧版代理的可用 CA 经私有 `takeover-ca.json` 接管,替换进程绑定端口后才消费它。用量日志把旧路径与新路径显式合并并按文件维护偏移。usage 解析失败只丢失计量数据;代理不可用时仅告警并继续。代理端口可用 `TOKEN_PROXY_PORT` 环境变量调整(默认 19876,自定义端口的数据目录为 `~/.autowonder/token-tap/ports/<port>/`)。启用后模型流量经过代理,连接失败由客户端处理重试,不保证自动直连。代理对 TCP 建连和两端 TLS 握手设置 15 秒期限,对无读写活动的连接设置 120 秒空闲期限;超时、报错或任一端关闭时释放两端连接,持续有数据的 SSE 流不受总时长限制,连续静默超过 120 秒的流会断开。平台差异:Linux 恢复依赖 pidfd(Linux 5.3+)且锁目录必须是受支持的本地文件系统(不支持 NFS/virtiofs);Windows 原生恢复只在 amd64 验证,ARM64 与 32 位 Node 未验证;macOS 在发信号前重新核对进程出生时间,但不像 pidfd/进程句柄那样原子。关键生命周期事件写入 `~/.autowonder/token-tap/lifecycle.log`。
|
|
47
47
|
|
|
48
48
|
`connect` 支持 `--workspace-root <path>` 指定 dispatch 仓库与任务工作区所在目录(默认 `~/autowonder_workspaces`)。该参数会转发给 daemon,等价于设置 `AUTOWONDER_WORKSPACE_ROOT` 环境变量,适合把工作区放在非默认路径的执行机上(如 Windows 的 `D:\autowonder`)。
|
|
49
49
|
|
|
@@ -105,6 +105,8 @@ daemon 重启或崩溃后重新接管未完成的派单时,runtime 不会直
|
|
|
105
105
|
|
|
106
106
|
暂停也走同一条持久化回执链路:`TASK_PAUSED` 只有在服务端确认接受后才从结果 outbox 删除,未接受时保留并可重发;服务端再次下发同一派单的暂停指令时,runtime 直接从 capsule 中已落盘的暂停结果(`runtime-result.json`,先校验租户、工单、派单、attempt 与 checkpoint 回执)重放该回执,而不要求暂停协调器仍留在内存里等待,因此 daemon 重启或回执丢失都不会让等待该派单返工的一方永久挂起。
|
|
107
107
|
|
|
108
|
+
暂停边界本身是冻结的:收到暂停指令后 runtime 先停掉普通检查点保存,再把结果与归档(含检查点序号与 SHA-256)原子写入 capsule 的 `state/pause-checkpoint.json`(0600),此后该派单不再落新检查点。服务端确认暂停并回传同一序号与 SHA-256 后,runtime 先写小而持久的确认凭据 `state/pause-checkpoint-confirmed.json`(仅当身份与回执匹配),再删除体积较大的归档;未被确认的暂停结果与归档一直保留,因此暂停 ACK 丢失只会占盘,不会让暂停事实消失。等待恢复期间若本地归档已缺失但确认凭据存在,runtime 会按 capsule 中保留的仓库状态重建检查点并回写新的序号与 SHA-256;恢复只上传冻结的本地状态,不会重新启动 provider 或执行 hooks。工作区 GC 只有在暂停归档已释放且存在与租户、工单、派单、attempt 完全匹配的确认凭据时才把暂停尝试视为终态并回收 capsule,避免提前删除仍可重建的暂停现场。
|
|
109
|
+
|
|
108
110
|
派单回合以 Qoder 自报的 `cancelled the prompt` 结束、而 runtime 并未发起取消,且本轮既无助手输出也无工具/提问活动时,不再直接判为失败:runtime 最多做 2 次有界恢复,第二次改用新会话并重建同一 workflow 上下文,重试前按退避等待,期间的暂停请求仍即时生效。只要已产生输出或工具副作用、存在待处理插话,或取消来自外部上下文,就不会重试;由多次调用组合而成的回合也不会授权重放其前置轮次。
|
|
109
111
|
|
|
110
112
|
Qoder 取消会在失败历史里附带 runtime 侧上下文诊断(是否尝试过取消、上下文状态),随 telemetry 一起导出,用于区分「模型自行中止」与「真实取消」。该诊断对执行机用户无新增参数或环境变量。
|
|
@@ -117,7 +119,7 @@ conversation 回合只有在其结果成功、未被取消且取得 provider 返
|
|
|
117
119
|
|
|
118
120
|
## 自动更新
|
|
119
121
|
|
|
120
|
-
|
|
122
|
+
自 0.3.33 起正式 npm 包迁移为 `@alicloud/autowonder`(命令名与二进制身份仍是 `autowonder`),旧包 `autowonder` 的 `beta` 停在 0.3.32(`latest` 仍为 0.2.130)。平台触发升级时,版本元数据及 tarball 从 `@alicloud/autowonder` 获取(最新版本查询使用 `latest`,指定版本查询使用对应版本号)。旧客户端先升级到旧包中的桥接版本,再由平台指派版本号更高的组织包;新包未发布或查询失败时保留当前版本,不回退查询旧包。组织包必须延续递增版本号,不能用 `0.0.1` 替代已安装的 `0.3.x`。此变更不启用后台自动检查。
|
|
121
123
|
|
|
122
124
|
daemon 不会自行追新:后台自动更新策略默认关闭,且没有环境变量可以重新开启,因此 daemon 不会主动查询 npm 的 `@alicloud/autowonder/latest`、下载、安装或重启。版本由平台决定,见下文的服务端指定版本升级;没有服务端升级指令时,即使本地配置了更短的检查周期也不会产生任何 npm 请求。
|
|
123
125
|
|
|
@@ -128,7 +130,7 @@ daemon 不会自行追新:后台自动更新策略默认关闭,且没有环
|
|
|
128
130
|
```bash
|
|
129
131
|
# 使用兼容的 npm registry(仅影响按平台指令解析版本时使用的源)
|
|
130
132
|
AUTOWONDER_NPM_REGISTRY=https://registry.npmjs.org \
|
|
131
|
-
npx -y autowonder@latest connect ...
|
|
133
|
+
npx -y @alicloud/autowonder@latest connect ...
|
|
132
134
|
```
|
|
133
135
|
|
|
134
136
|
## 在线应用启动命令
|
|
@@ -195,7 +197,7 @@ mv "$queue/.assignment.tmp" "$queue/assignment.json"
|
|
|
195
197
|
也可以直接提交到本地 API:
|
|
196
198
|
|
|
197
199
|
```bash
|
|
198
|
-
npx -y autowonder@0.3.
|
|
200
|
+
npx -y @alicloud/autowonder@0.3.34 dispatch ./assignment.json
|
|
199
201
|
```
|
|
200
202
|
|
|
201
203
|
## 上传工单附件
|
|
@@ -203,7 +205,7 @@ npx -y autowonder@0.3.30 dispatch ./assignment.json
|
|
|
203
205
|
把本地需求/设计文档直接上传到工单,避免在会话里传递大文件:
|
|
204
206
|
|
|
205
207
|
```bash
|
|
206
|
-
npx -y autowonder@0.3.
|
|
208
|
+
npx -y @alicloud/autowonder@0.3.34 workitem upload --server-url <autowonder-server-url> --workitem-id <id> --file <filepath-1> --file <filepath-2> --json
|
|
207
209
|
```
|
|
208
210
|
|
|
209
211
|
上传令牌通过 MCP 工具 `autowonder.workitem_cli_upload_token` 签发,经 `--token` 或 `AUTOWONDER_UPLOAD_TOKEN` 环境变量传入。`--file` 可重复指定多个文件;`--json` 输出机器可读结果。失败时按错误类型返回不同退出码(401→3、403→4、404→5、409→6、413→7、其他 4xx→8、网络/重定向→9)。
|
|
@@ -213,7 +215,7 @@ npx -y autowonder@0.3.30 workitem upload --server-url <autowonder-server-url> --
|
|
|
213
215
|
把工单上已有的需求/设计文档下载到本地目录,再用本地文件工具阅读,避免把大文件或二进制附件搬进会话上下文:
|
|
214
216
|
|
|
215
217
|
```bash
|
|
216
|
-
npx -y autowonder@0.3.
|
|
218
|
+
npx -y @alicloud/autowonder@0.3.34 workitem download --server-url <autowonder-server-url> --workitem-id <id> --file <name-or-id> --output-dir <dir> --json
|
|
217
219
|
```
|
|
218
220
|
|
|
219
221
|
下载令牌通过 MCP 工具 `autowonder.workitem_cli_download_token` 签发(与上传令牌相互独立),经 `--token` 或 `AUTOWONDER_DOWNLOAD_TOKEN` 环境变量传入。`--file` 可重复指定文档名或 artifact id,省略则下载该工单的全部附件;`--output-dir` 默认为当前目录;`--json` 输出机器可读结果,含每个文件的 `id`、`name`、`path`、`size`。退出码约定与 `workitem upload` 相同(401→3、403→4、404→5、409→6、413→7、其他 4xx→8、网络/重定向→9)。
|
|
@@ -223,7 +225,7 @@ npx -y autowonder@0.3.30 workitem download --server-url <autowonder-server-url>
|
|
|
223
225
|
把需求/设计文档上传到 7x24 定时任务,用法与工单附件一致(同一套上传令牌与预检规则):
|
|
224
226
|
|
|
225
227
|
```bash
|
|
226
|
-
npx -y autowonder@0.3.
|
|
228
|
+
npx -y @alicloud/autowonder@0.3.34 scheduled-task upload --server-url <autowonder-server-url> --scheduled-task-id <id> --file <filepath-1> --file <filepath-2> --json
|
|
227
229
|
```
|
|
228
230
|
|
|
229
231
|
上传令牌同样通过 `autowonder.workitem_cli_upload_token` 签发(令牌为用户级,对当前可修改的任意定时任务生效),经 `--token` 或 `AUTOWONDER_UPLOAD_TOKEN` 传入;退出码约定与 `workitem upload` 相同。
|
|
@@ -231,8 +233,8 @@ npx -y autowonder@0.3.30 scheduled-task upload --server-url <autowonder-server-u
|
|
|
231
233
|
## 管理 daemon
|
|
232
234
|
|
|
233
235
|
```bash
|
|
234
|
-
npx -y autowonder@0.3.
|
|
235
|
-
npx -y autowonder@0.3.
|
|
236
|
+
npx -y @alicloud/autowonder@0.3.34 status
|
|
237
|
+
npx -y @alicloud/autowonder@0.3.34 stop
|
|
236
238
|
```
|
|
237
239
|
|
|
238
240
|
默认 API 是 `http://127.0.0.1:34989`,日志位于 `~/.autowonder/daemon.log`。npm 包不包含任何 agent、MCP 或服务端凭证。
|
|
@@ -255,7 +257,7 @@ daemon 内置独立于工作区 GC 的保留清扫:默认每小时运行一次
|
|
|
255
257
|
## 调试
|
|
256
258
|
|
|
257
259
|
```bash
|
|
258
|
-
npx -y autowonder@0.3.
|
|
260
|
+
npx -y @alicloud/autowonder@0.3.34 connect ... --debug
|
|
259
261
|
```
|
|
260
262
|
|
|
261
263
|
`--debug` 会让 CLI 以 `AUTOWONDER_DEBUG=1` 启动 daemon,把完整的 daemon 与 agent 活动(runtime 事件流、provider 事件解码、重试退避与会话门等待、空闲时的阻塞点)同时输出到控制台和会话调试日志。调试日志不做脱敏,仅用于本机排障;不传 `--debug` 时该环境变量不会注入。
|
package/bin/cli.js
CHANGED
|
@@ -504,65 +504,43 @@ async function cmdConnect(args) {
|
|
|
504
504
|
delete env[selectedAccessTokenEnv];
|
|
505
505
|
}
|
|
506
506
|
|
|
507
|
-
//
|
|
508
|
-
let
|
|
507
|
+
// The listener belongs to the shared service, never to an individual daemon.
|
|
508
|
+
let stopProxyWatch = () => {};
|
|
509
509
|
if (flags["token-aware-enable"]) {
|
|
510
|
-
const
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
spawnSync(process.execPath, ["-e", "setTimeout(()=>{},200)"], { stdio: "ignore" }); // cross-platform sleep
|
|
531
|
-
}
|
|
532
|
-
|
|
533
|
-
if (fs.existsSync(caCertPath)) {
|
|
534
|
-
// Pass proxy config to daemon via env. The daemon will set per-dispatch
|
|
535
|
-
// HTTPS_PROXY=http://d-{dispatchId}:x@host:port for each qodercli process,
|
|
536
|
-
// so the proxy can tag token records with the exact dispatch ID.
|
|
537
|
-
env.AUTOWONDER_TOKEN_PROXY_PORT = String(proxyPort);
|
|
538
|
-
env.AUTOWONDER_TOKEN_PROXY_CA = caCertPath;
|
|
539
|
-
env.AUTOWONDER_TOKEN_PROXY_DIAG_LOG = path.join(AUTOWONDER_HOME, "token-tap", "proxy-diag.log");
|
|
540
|
-
env.NODE_EXTRA_CA_CERTS = caCertPath;
|
|
541
|
-
log(`Token tracking enabled (proxy pid=${tokenProxyChild.pid}, port=${proxyPort})`);
|
|
542
|
-
} else {
|
|
543
|
-
log("WARN: token-proxy CA cert not ready, continuing without token tracking");
|
|
544
|
-
}
|
|
545
|
-
} catch (e) {
|
|
546
|
-
log(`WARN: token-proxy start failed (${e.message}), continuing without token tracking`);
|
|
547
|
-
}
|
|
548
|
-
} else {
|
|
549
|
-
log(`WARN: token-proxy.js not found at ${tokenProxyScript}, --token-aware-enable ignored`);
|
|
550
|
-
}
|
|
510
|
+
const { configuration, ensureSharedProxy, watchSharedProxy } = require("./token-proxy-manager");
|
|
511
|
+
const proxy = configuration();
|
|
512
|
+
proxy.debug = Boolean(flags.debug);
|
|
513
|
+
proxy.helper = DAEMON_BIN;
|
|
514
|
+
const ready = await ensureSharedProxy(proxy);
|
|
515
|
+
env.AUTOWONDER_TOKEN_PROXY_PORT = String(proxy.port);
|
|
516
|
+
env.AUTOWONDER_TOKEN_PROXY_MANAGED = "1";
|
|
517
|
+
env.AUTOWONDER_TOKEN_PROXY_LEGACY_ALLOWED = "1";
|
|
518
|
+
env.AUTOWONDER_TOKEN_PROXY_BASE_DIR = proxy.baseDir;
|
|
519
|
+
env.AUTOWONDER_TOKEN_PROXY_NODE_PATH = process.execPath;
|
|
520
|
+
env.AUTOWONDER_TOKEN_PROXY_SCRIPT_PATH = path.join(__dirname, "token-proxy.js");
|
|
521
|
+
env.AUTOWONDER_TOKEN_PROXY_LEGACY_USAGE_LOG = path.join(proxy.baseDir, "token-usage.jsonl");
|
|
522
|
+
env.AUTOWONDER_TOKEN_PROXY_USAGE_LOG = path.join(proxy.dataDir, "token-usage.jsonl");
|
|
523
|
+
env.AUTOWONDER_TOKEN_PROXY_SCOPE = proxy.scope;
|
|
524
|
+
env.AUTOWONDER_TOKEN_PROXY_STATE_DIR = path.join(proxy.dataDir, "managed");
|
|
525
|
+
env.AUTOWONDER_TOKEN_PROXY_CA = ready.caPath || path.join(proxy.dataDir, "managed", ready.generation, "ca.pem");
|
|
526
|
+
env.NODE_EXTRA_CA_CERTS = env.AUTOWONDER_TOKEN_PROXY_CA;
|
|
527
|
+
env.AUTOWONDER_TOKEN_PROXY_DIAG_LOG = path.join(proxy.dataDir, "proxy-diag.log");
|
|
528
|
+
stopProxyWatch = watchSharedProxy(proxy, log);
|
|
529
|
+
log(`Shared token tracking enabled (port=${proxy.port})`);
|
|
551
530
|
}
|
|
552
531
|
|
|
553
532
|
const child = spawn(DAEMON_BIN, [], { env, stdio: "inherit" });
|
|
554
533
|
child.on("exit", (code) => {
|
|
555
|
-
|
|
556
|
-
if (tokenProxyChild) { try { process.kill(tokenProxyChild.pid); } catch (_) {} }
|
|
534
|
+
stopProxyWatch();
|
|
557
535
|
process.exit(code || 0);
|
|
558
536
|
});
|
|
559
537
|
process.on("SIGINT", () => {
|
|
560
538
|
child.kill("SIGINT");
|
|
561
|
-
|
|
539
|
+
stopProxyWatch();
|
|
562
540
|
});
|
|
563
541
|
process.on("SIGTERM", () => {
|
|
564
542
|
child.kill("SIGTERM");
|
|
565
|
-
|
|
543
|
+
stopProxyWatch();
|
|
566
544
|
});
|
|
567
545
|
}
|
|
568
546
|
|
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
// Caller must own the proxy listener before changing this store.
|
|
3
|
+
const fs = require('fs');
|
|
4
|
+
const path = require('path');
|
|
5
|
+
const crypto = require('crypto');
|
|
6
|
+
const { execFile } = require('child_process');
|
|
7
|
+
const { promisify } = require('util');
|
|
8
|
+
const run = promisify(execFile);
|
|
9
|
+
const GENERATION = /^gen-[0-9a-f-]{36}$/;
|
|
10
|
+
const OPENSSL_CANDIDATES = ['openssl', '/usr/bin/openssl', '/opt/homebrew/bin/openssl',
|
|
11
|
+
'C:\\Program Files\\Git\\usr\\bin\\openssl.exe', 'C:\\Program Files\\OpenSSL-Win64\\bin\\openssl.exe'];
|
|
12
|
+
let openssl;
|
|
13
|
+
async function resolveOpenSSL() {
|
|
14
|
+
if (openssl) return openssl;
|
|
15
|
+
for (const cmd of OPENSSL_CANDIDATES) {
|
|
16
|
+
try { await run(cmd, ['version'], { timeout: 5000, windowsHide: true }); openssl = cmd; return cmd; } catch (_) {}
|
|
17
|
+
}
|
|
18
|
+
throw new Error('TokenProxy requires OpenSSL; install it before enabling token tracking');
|
|
19
|
+
}
|
|
20
|
+
function validPair(cert, key) {
|
|
21
|
+
const x = new crypto.X509Certificate(cert);
|
|
22
|
+
if (!x.ca || !x.checkPrivateKey(crypto.createPrivateKey(key)) || Date.parse(x.validFrom) > Date.now() || Date.parse(x.validTo) <= Date.now()) throw new Error('Invalid or expired TokenProxy CA pair');
|
|
23
|
+
return { cert, key, fingerprint: crypto.createHash('sha256').update(x.raw).digest('hex') };
|
|
24
|
+
}
|
|
25
|
+
function readPair(certPath, keyPath) { return validPair(fs.readFileSync(certPath), fs.readFileSync(keyPath)); }
|
|
26
|
+
function readGeneration(root, name) {
|
|
27
|
+
if (!GENERATION.test(name || '')) throw new Error('Invalid TokenProxy generation');
|
|
28
|
+
const dir = path.join(root, name);
|
|
29
|
+
return { ...readPair(path.join(dir, 'ca.pem'), path.join(dir, 'key.pem')), generation: name,
|
|
30
|
+
certPath: path.join(dir, 'ca.pem'), keyPath: path.join(dir, 'key.pem'), cacheDir: path.join(dir, 'hosts') };
|
|
31
|
+
}
|
|
32
|
+
function newGeneration(root, pair) {
|
|
33
|
+
const name = `gen-${crypto.randomUUID()}`, dir = path.join(root, name);
|
|
34
|
+
fs.mkdirSync(dir, { mode: 0o700 });
|
|
35
|
+
fs.writeFileSync(path.join(dir, 'key.pem'), pair.key, { mode: 0o600, flag: 'wx' });
|
|
36
|
+
fs.writeFileSync(path.join(dir, 'ca.pem'), pair.cert, { mode: 0o600, flag: 'wx' });
|
|
37
|
+
return readGeneration(root, name);
|
|
38
|
+
}
|
|
39
|
+
function publish(root, current, backup) {
|
|
40
|
+
const file = path.join(root, `.current-${crypto.randomUUID()}.tmp`);
|
|
41
|
+
try {
|
|
42
|
+
fs.writeFileSync(file, JSON.stringify({ version: 1, generation: current.generation, fingerprint: current.fingerprint, backup: backup.generation }), { mode: 0o600 });
|
|
43
|
+
fs.renameSync(file, path.join(root, 'current.json'));
|
|
44
|
+
} finally { try { fs.unlinkSync(file); } catch (_) {} }
|
|
45
|
+
prune(root, new Set([current.generation, backup.generation]));
|
|
46
|
+
}
|
|
47
|
+
function prune(root, keep) {
|
|
48
|
+
// Failed publication and crash leftovers are bounded too, not just successful rotations.
|
|
49
|
+
const retired = fs.readdirSync(root).filter(n => GENERATION.test(n) && !keep.has(n))
|
|
50
|
+
.map(n => ({ n, time: fs.statSync(path.join(root, n)).mtimeMs })).sort((a, b) => b.time - a.time);
|
|
51
|
+
for (const { n } of retired.slice(6)) fs.rmSync(path.join(root, n), { recursive: true, force: true });
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
async function generate(root) {
|
|
55
|
+
const dir = path.join(root, `gen-${crypto.randomUUID()}`);
|
|
56
|
+
fs.mkdirSync(dir, { mode: 0o700 });
|
|
57
|
+
const keyPath = path.join(dir, 'key.pem'), certPath = path.join(dir, 'ca.pem');
|
|
58
|
+
const config = path.join(dir, 'openssl.cnf');
|
|
59
|
+
fs.writeFileSync(config, '[req]\ndistinguished_name=dn\nx509_extensions=v3_ca\nprompt=no\n[dn]\nCN=AutoWonder Token Tap CA\n[v3_ca]\nbasicConstraints=critical,CA:TRUE\nkeyUsage=critical,keyCertSign,cRLSign\n', { mode: 0o600 });
|
|
60
|
+
try {
|
|
61
|
+
await run(await resolveOpenSSL(), ['req', '-new', '-x509', '-newkey', 'rsa:2048', '-nodes', '-keyout', keyPath, '-out', certPath, '-days', '3650', '-config', config], { timeout: 15000, windowsHide: true, maxBuffer: 1024 * 1024 });
|
|
62
|
+
fs.chmodSync(keyPath, 0o600);
|
|
63
|
+
return readGeneration(root, path.basename(dir));
|
|
64
|
+
} catch (e) { try { fs.rmSync(dir, { recursive: true, force: true }); } catch (_) {} throw e; }
|
|
65
|
+
}
|
|
66
|
+
async function updateManagedCA(dataDir) {
|
|
67
|
+
const root = path.join(dataDir, 'managed');
|
|
68
|
+
fs.mkdirSync(root, { recursive: true, mode: 0o700 });
|
|
69
|
+
// Written only by the native helper after validating the live legacy owner.
|
|
70
|
+
// Consume only after this service has bound the listener; publication is
|
|
71
|
+
// retryable if the helper/service dies before unlinking the bundle.
|
|
72
|
+
const takeover = path.join(dataDir, 'takeover-ca.json');
|
|
73
|
+
if (fs.existsSync(takeover)) {
|
|
74
|
+
let pair;
|
|
75
|
+
if (fs.statSync(takeover).size <= 2 * 1024 * 1024) {
|
|
76
|
+
const raw = fs.readFileSync(takeover, 'utf8');
|
|
77
|
+
try { const bundle = JSON.parse(raw); pair = validPair(bundle.cert, bundle.key); } catch (_) {}
|
|
78
|
+
}
|
|
79
|
+
if (pair) {
|
|
80
|
+
const active = newGeneration(root, pair), backup = newGeneration(root, pair);
|
|
81
|
+
publish(root, active, backup);
|
|
82
|
+
fs.unlinkSync(takeover);
|
|
83
|
+
return active;
|
|
84
|
+
}
|
|
85
|
+
// Invalid contents cannot establish trust. Existing managed recovery or
|
|
86
|
+
// a new generation handles this case; filesystem errors still retry.
|
|
87
|
+
fs.unlinkSync(takeover);
|
|
88
|
+
}
|
|
89
|
+
const pointer = path.join(root, 'current.json');
|
|
90
|
+
const alreadyManaged = fs.existsSync(pointer) || fs.readdirSync(root).some(n => GENERATION.test(n));
|
|
91
|
+
let meta, active, backup;
|
|
92
|
+
try { meta = JSON.parse(fs.readFileSync(pointer, 'utf8')); } catch (_) {}
|
|
93
|
+
prune(root, new Set(meta ? [meta.generation, meta.backup] : []));
|
|
94
|
+
if (meta && meta.version === 1) {
|
|
95
|
+
try { active = readGeneration(root, meta.generation); if (active.fingerprint !== meta.fingerprint) active = null; } catch (_) {}
|
|
96
|
+
try { backup = readGeneration(root, meta.backup); if (backup.fingerprint !== meta.fingerprint) backup = null; } catch (_) {}
|
|
97
|
+
}
|
|
98
|
+
if (active) {
|
|
99
|
+
if (!backup) { backup = newGeneration(root, active); publish(root, active, backup); }
|
|
100
|
+
return active;
|
|
101
|
+
}
|
|
102
|
+
if (backup) active = newGeneration(root, backup);
|
|
103
|
+
// Only the initial migration imports the legacy CA. A stale legacy file must
|
|
104
|
+
// never roll an already-managed installation back to a retired trust root.
|
|
105
|
+
if (!active && !alreadyManaged) {
|
|
106
|
+
try { active = newGeneration(root, readPair(path.join(dataDir, 'ca-cert.pem'), path.join(dataDir, 'ca-key.pem'))); } catch (_) {}
|
|
107
|
+
}
|
|
108
|
+
if (!active) active = await generate(root);
|
|
109
|
+
if (!backup || backup.fingerprint !== active.fingerprint) backup = newGeneration(root, active);
|
|
110
|
+
publish(root, active, backup);
|
|
111
|
+
return active;
|
|
112
|
+
}
|
|
113
|
+
async function ensureManagedCA(dataDir) {
|
|
114
|
+
const root = path.join(dataDir, 'managed');
|
|
115
|
+
fs.mkdirSync(root, { recursive: true, mode: 0o700 });
|
|
116
|
+
const before = new Set(fs.readdirSync(root));
|
|
117
|
+
try { return await updateManagedCA(dataDir); }
|
|
118
|
+
catch (error) {
|
|
119
|
+
let published = {};
|
|
120
|
+
try { published = JSON.parse(fs.readFileSync(path.join(root, 'current.json'), 'utf8')); } catch (_) {}
|
|
121
|
+
for (const name of fs.readdirSync(root)) {
|
|
122
|
+
if (GENERATION.test(name) && !before.has(name) && name !== published.generation && name !== published.backup) {
|
|
123
|
+
try { fs.rmSync(path.join(root, name), { recursive: true, force: true }); } catch (_) {}
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
throw error;
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
module.exports = { ensureManagedCA, resolveOpenSSL, validPair };
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
const { spawn } = require('child_process');
|
|
3
|
+
const net = require('net');
|
|
4
|
+
const crypto = require('crypto');
|
|
5
|
+
function runHelper(cfg, action, { timeoutMs = 25000, stopped = () => false } = {}) {
|
|
6
|
+
return new Promise((resolve, reject) => {
|
|
7
|
+
const child = spawn(cfg.helper, ['token-proxy-helper', action], { windowsHide: true, stdio: ['pipe', 'pipe', 'pipe'] });
|
|
8
|
+
let out = '', err = '', done = false;
|
|
9
|
+
const finish = (error, value) => { if (done) return; done = true; clearTimeout(timer); clearInterval(cancelPoll); error ? reject(error) : resolve(value); };
|
|
10
|
+
const timer = setTimeout(() => { child.kill('SIGKILL'); finish(new Error('TokenProxy helper exceeded hard deadline')); }, timeoutMs);
|
|
11
|
+
const cancelPoll = setInterval(() => { if (stopped()) { child.kill('SIGKILL'); finish(new Error('TokenProxy helper cancelled')); } }, 100);
|
|
12
|
+
child.on('error', finish);
|
|
13
|
+
child.stdin.on('error', () => {});
|
|
14
|
+
child.stdout.on('data', b => { out += b; if (out.length > 65536) { child.kill('SIGKILL'); finish(new Error('TokenProxy helper output too large')); } });
|
|
15
|
+
child.stderr.on('data', b => { err = (err + b).slice(-4096); });
|
|
16
|
+
child.on('close', code => {
|
|
17
|
+
if (code !== 0) return finish(new Error(`TokenProxy helper failed: ${err.trim() || code}`));
|
|
18
|
+
try { const result = JSON.parse(out); if (!result || typeof result.state !== 'string') throw new Error('missing state'); finish(null, result); }
|
|
19
|
+
catch (_) { finish(new Error('Invalid TokenProxy helper response')); }
|
|
20
|
+
});
|
|
21
|
+
child.stdin.end(JSON.stringify({ debug: Boolean(cfg.debug), port: cfg.port, dataDir: cfg.dataDir, baseDir: cfg.baseDir, scope: cfg.scope,
|
|
22
|
+
nodePath: process.execPath, scriptPath: require('path').join(__dirname, 'token-proxy.js') }));
|
|
23
|
+
});
|
|
24
|
+
}
|
|
25
|
+
// Local forwarding is checked separately from health so a responsive health
|
|
26
|
+
// endpoint cannot conceal a stalled CONNECT handler. Never touches the model.
|
|
27
|
+
function forwardingHealthy(port, timeoutMs = 1500) {
|
|
28
|
+
return new Promise(resolve => {
|
|
29
|
+
const sockets = new Set(); let done = false, timer;
|
|
30
|
+
const server = net.createServer(s => { sockets.add(s); s.on('error', () => finish(false)); s.on('data', b => s.write(b)); });
|
|
31
|
+
const finish = value => { if (done) return; done = true; clearTimeout(timer); for (const s of sockets) s.destroy(); server.close(); resolve(value); };
|
|
32
|
+
timer = setTimeout(() => finish(false), timeoutMs);
|
|
33
|
+
server.on('error', () => finish(false));
|
|
34
|
+
server.listen(0, '127.0.0.1', () => {
|
|
35
|
+
if (done) { server.close(); return; }
|
|
36
|
+
const target = `127.0.0.1:${server.address().port}`;
|
|
37
|
+
const s = net.connect(port, '127.0.0.1'); sockets.add(s);
|
|
38
|
+
let buf = Buffer.alloc(0), connected = false; const nonce = crypto.randomBytes(32);
|
|
39
|
+
s.on('error', () => finish(false)); s.on('end', () => finish(false));
|
|
40
|
+
s.on('connect', () => s.write(`CONNECT ${target} HTTP/1.1\r\nHost: ${target}\r\n\r\n`));
|
|
41
|
+
s.on('data', b => {
|
|
42
|
+
buf = Buffer.concat([buf, b]); if (buf.length > 8192) return finish(false);
|
|
43
|
+
if (!connected) { const end = buf.indexOf('\r\n\r\n'); if (end < 0) return;
|
|
44
|
+
if (!buf.toString('ascii', 0, end).startsWith('HTTP/1.1 200 ')) return finish(false);
|
|
45
|
+
connected = true; buf = buf.subarray(end + 4); s.write(nonce);
|
|
46
|
+
}
|
|
47
|
+
if (buf.length >= 32) finish(buf.equals(nonce));
|
|
48
|
+
});
|
|
49
|
+
});
|
|
50
|
+
});
|
|
51
|
+
}
|
|
52
|
+
module.exports = { runHelper, forwardingHealthy };
|
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
const fs = require('fs');
|
|
3
|
+
const path = require('path');
|
|
4
|
+
const os = require('os');
|
|
5
|
+
const http = require('http');
|
|
6
|
+
const crypto = require('crypto');
|
|
7
|
+
const { spawn } = require('child_process');
|
|
8
|
+
const HEALTH_PATH = '/__autowonder_token_proxy/health';
|
|
9
|
+
const SERVICE = 'autowonder-token-proxy';
|
|
10
|
+
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
|
|
11
|
+
function configuration({ port = process.env.TOKEN_PROXY_PORT || 19876, dataDir = path.join(os.homedir(), '.autowonder', 'token-tap') } = {}) {
|
|
12
|
+
port = Number(port);
|
|
13
|
+
if (!Number.isInteger(port) || port < 1 || port > 65535) throw new Error('TOKEN_PROXY_PORT must be an integer between 1 and 65535');
|
|
14
|
+
const baseDir = path.resolve(dataDir);
|
|
15
|
+
if (port !== 19876) dataDir = path.join(baseDir, 'ports', String(port));
|
|
16
|
+
fs.mkdirSync(dataDir, { recursive: true, mode: 0o700 });
|
|
17
|
+
dataDir = fs.realpathSync(dataDir);
|
|
18
|
+
return { port, dataDir, baseDir, scope: crypto.createHash('sha256').update(dataDir).digest('hex') };
|
|
19
|
+
}
|
|
20
|
+
function probeProxy(cfg) {
|
|
21
|
+
return new Promise(resolve => {
|
|
22
|
+
let timer;
|
|
23
|
+
const finish = value => { clearTimeout(timer); resolve(value); };
|
|
24
|
+
const req = http.get({ hostname: '127.0.0.1', port: cfg.port, path: HEALTH_PATH, agent: false, timeout: 1500 }, res => {
|
|
25
|
+
if (res.statusCode === 405) { res.resume(); finish({ state: 'legacy' }); return; }
|
|
26
|
+
let body = '';
|
|
27
|
+
res.on('data', b => { body += b; if (body.length > 16384) { finish({ state: 'foreign' }); res.destroy(); } });
|
|
28
|
+
res.on('error', () => finish({ state: 'unresponsive' }));
|
|
29
|
+
res.on('end', () => { try { finish(JSON.parse(body)); } catch (_) { finish({ state: 'foreign' }); } });
|
|
30
|
+
});
|
|
31
|
+
timer = setTimeout(() => { finish({ state: 'unresponsive' }); req.destroy(); }, 1500);
|
|
32
|
+
timer.unref();
|
|
33
|
+
req.on('timeout', () => req.destroy());
|
|
34
|
+
req.on('error', e => finish({ state: e.code === 'ECONNREFUSED' ? 'absent' : 'unresponsive' }));
|
|
35
|
+
});
|
|
36
|
+
}
|
|
37
|
+
function classify(h, cfg) {
|
|
38
|
+
if (!h || typeof h !== 'object') return 'foreign';
|
|
39
|
+
if (h.service === SERVICE) {
|
|
40
|
+
if (h.protocol !== 1 || h.scope !== cfg.scope) return 'incompatible';
|
|
41
|
+
if (h.state === 'ready' && (!/^gen-[0-9a-f-]{36}$/.test(h.generation || '') || !/^[0-9a-f]{64}$/.test(h.fingerprint || ''))) return 'incompatible';
|
|
42
|
+
return h.state;
|
|
43
|
+
}
|
|
44
|
+
return ['absent', 'unresponsive'].includes(h.state) ? h.state : 'foreign';
|
|
45
|
+
}
|
|
46
|
+
function launchProxy(cfg) {
|
|
47
|
+
const child = spawn(process.execPath, [path.join(__dirname, 'token-proxy.js'), 'start', '--managed', '--port', String(cfg.port)], {
|
|
48
|
+
detached: true, windowsHide: true, stdio: 'ignore',
|
|
49
|
+
env: { ...process.env, AUTOWONDER_TOKEN_PROXY_DATA_DIR: cfg.dataDir, AUTOWONDER_TOKEN_PROXY_BASE_DIR: cfg.baseDir, ...(cfg.debug ? { AUTOWONDER_DEBUG: "1" } : {}) },
|
|
50
|
+
});
|
|
51
|
+
// spawn errors are asynchronous; always attach a listener even when detached.
|
|
52
|
+
const started = new Promise((resolve, reject) => { child.once('spawn', resolve); child.once('error', reject); });
|
|
53
|
+
child.unref();
|
|
54
|
+
return started;
|
|
55
|
+
}
|
|
56
|
+
async function ensureSharedProxy(cfg, { timeoutMs = 30000, stopped = () => false, monitorOnly = false } = {}) {
|
|
57
|
+
const deadline = Date.now() + timeoutMs;
|
|
58
|
+
if (cfg.helper) {
|
|
59
|
+
const { runHelper, forwardingHealthy } = require('./token-proxy-helper');
|
|
60
|
+
let last;
|
|
61
|
+
while (!stopped() && Date.now() < deadline) {
|
|
62
|
+
const health = await probeProxy(cfg);
|
|
63
|
+
const state = classify(health, cfg);
|
|
64
|
+
const cached = cfg.verified;
|
|
65
|
+
if (monitorOnly && cached && Date.now() - cached.at < 30000 &&
|
|
66
|
+
((state === 'ready' && health.instanceId === cached.value.instanceId && health.fingerprint === cached.value.fingerprint) ||
|
|
67
|
+
(health.state === 'legacy' && cached.value.state === 'legacy')) && await forwardingHealthy(cfg.port)) return cached.value;
|
|
68
|
+
const remaining = deadline - Date.now();
|
|
69
|
+
if (remaining <= 0 || stopped()) break;
|
|
70
|
+
last = await runHelper(cfg, 'recover', { timeoutMs: Math.min(25000, remaining), stopped });
|
|
71
|
+
if (['ready', 'legacy'].includes(last.state)) {
|
|
72
|
+
cfg.verified = { at: Date.now(), value: last };
|
|
73
|
+
return last;
|
|
74
|
+
}
|
|
75
|
+
if (!['starting', 'blocked', 'absent', 'unresponsive'].includes(last.state)) throw new Error(`TokenProxy cannot be admitted (${last.state})`);
|
|
76
|
+
await sleep(500);
|
|
77
|
+
}
|
|
78
|
+
throw new Error(`TokenProxy is not ready (${last && last.state || 'unavailable'})`);
|
|
79
|
+
}
|
|
80
|
+
let nextSpawn = 0, attempts = 0, last;
|
|
81
|
+
while (!stopped() && Date.now() < deadline) {
|
|
82
|
+
last = await probeProxy(cfg);
|
|
83
|
+
const state = classify(last, cfg);
|
|
84
|
+
if (state === 'ready') return last;
|
|
85
|
+
if (state === 'foreign' || state === 'incompatible') throw new Error(`TokenProxy port ${cfg.port} is occupied by a legacy, foreign or incompatible service; drain and migrate the old executors without terminating other users' processes`);
|
|
86
|
+
if (state === 'absent' && Date.now() >= nextSpawn) {
|
|
87
|
+
await sleep(50 + Math.random() * 200);
|
|
88
|
+
if (stopped()) break;
|
|
89
|
+
if (classify(await probeProxy(cfg), cfg) === 'absent' && !stopped()) {
|
|
90
|
+
await launchProxy(cfg);
|
|
91
|
+
nextSpawn = Date.now() + Math.min(10000, 1000 * 2 ** Math.min(attempts++, 4));
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
await sleep(200);
|
|
95
|
+
}
|
|
96
|
+
throw new Error(`TokenProxy is not ready (${last && last.state || 'unavailable'}); see ${path.join(cfg.dataDir, 'lifecycle.log')}`);
|
|
97
|
+
}
|
|
98
|
+
function watchSharedProxy(cfg, log = () => {}, { intervalMs = 2000 } = {}) {
|
|
99
|
+
let stopped = false, timer, previous = '';
|
|
100
|
+
const tick = async () => {
|
|
101
|
+
if (stopped) return;
|
|
102
|
+
try {
|
|
103
|
+
const h = await ensureSharedProxy(cfg, { timeoutMs: 10000, stopped: () => stopped, monitorOnly: true });
|
|
104
|
+
const status = `ready:${h.instanceId}:${h.fingerprint}`;
|
|
105
|
+
if (status !== previous && !stopped) { log(`Shared TokenProxy ready on ${cfg.port}`); previous = status; }
|
|
106
|
+
} catch (e) {
|
|
107
|
+
if (!stopped && previous !== e.message) { log(`WARN: ${e.message}`); previous = e.message; }
|
|
108
|
+
}
|
|
109
|
+
if (!stopped) { timer = setTimeout(tick, intervalMs); timer.unref(); }
|
|
110
|
+
};
|
|
111
|
+
timer = setTimeout(tick, intervalMs); timer.unref();
|
|
112
|
+
return () => { stopped = true; clearTimeout(timer); };
|
|
113
|
+
}
|
|
114
|
+
module.exports = { configuration, probeProxy, ensureSharedProxy, watchSharedProxy, classify, HEALTH_PATH, SERVICE };
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
const path = require('path');
|
|
3
|
+
const crypto = require('crypto');
|
|
4
|
+
const { configuration, HEALTH_PATH, SERVICE } = require('./token-proxy-manager');
|
|
5
|
+
const { ensureManagedCA, resolveOpenSSL } = require('./token-proxy-ca');
|
|
6
|
+
async function startManagedProxy(port) {
|
|
7
|
+
const { createProxyServer, getHostCert, createRotatingWriter, installDiagLog } = require('./token-proxy');
|
|
8
|
+
const cfg = configuration({ port, dataDir: process.env.AUTOWONDER_TOKEN_PROXY_BASE_DIR });
|
|
9
|
+
let ca, state = 'starting', retry = 0, timer, closed = false, failure = '', writer;
|
|
10
|
+
const instanceId = crypto.randomUUID();
|
|
11
|
+
const server = createProxyServer({ ca: {}, hostCertificate: host => getHostCert(host, ca) });
|
|
12
|
+
const handlers = server.listeners('connect');
|
|
13
|
+
server.removeAllListeners('connect');
|
|
14
|
+
server.on('connect', (...args) => {
|
|
15
|
+
if (state !== 'ready') { args[1].end('HTTP/1.1 503 TokenProxy recovering\r\nConnection: close\r\n\r\n'); return; }
|
|
16
|
+
for (const handler of handlers) handler(...args);
|
|
17
|
+
});
|
|
18
|
+
server.removeAllListeners('request');
|
|
19
|
+
server.on('request', (req, res) => {
|
|
20
|
+
if (req.method !== 'GET' || req.url !== HEALTH_PATH) { res.writeHead(405); res.end(); return; }
|
|
21
|
+
res.setHeader('Content-Type', 'application/json');
|
|
22
|
+
res.setHeader('Cache-Control', 'no-store');
|
|
23
|
+
res.end(JSON.stringify({ service: SERVICE, protocol: 1, scope: cfg.scope, state, instanceId,
|
|
24
|
+
pid: process.pid, fingerprint: ca && ca.fingerprint, generation: ca && ca.generation, error: failure }));
|
|
25
|
+
});
|
|
26
|
+
server.on('error', e => {
|
|
27
|
+
// Losing a bind race is normal; losers never touch shared CA/log files.
|
|
28
|
+
if (e.code !== 'EADDRINUSE') console.error(`[token-proxy] listen failed: ${e.code || e.message}`);
|
|
29
|
+
process.exit(e.code === 'EADDRINUSE' ? 0 : 1);
|
|
30
|
+
});
|
|
31
|
+
await new Promise(resolve => server.listen({ host: '127.0.0.1', port: cfg.port, exclusive: true }, resolve));
|
|
32
|
+
try { installDiagLog(); } catch (_) {}
|
|
33
|
+
try { writer = createRotatingWriter(path.join(cfg.dataDir, 'lifecycle.log'), { maxBytes: 4 * 1024 * 1024, maxArchives: 3 }); } catch (_) {}
|
|
34
|
+
const log = message => writer && writer.write(`${new Date().toISOString()} pid=${process.pid} instance=${instanceId} ${message}\n`);
|
|
35
|
+
log(`listening port=${cfg.port}`);
|
|
36
|
+
const maintain = async () => {
|
|
37
|
+
try {
|
|
38
|
+
const next = await ensureManagedCA(cfg.dataDir);
|
|
39
|
+
next.openssl = await resolveOpenSSL();
|
|
40
|
+
if (!ca || ca.generation !== next.generation) log(`ready generation=${next.generation}`);
|
|
41
|
+
ca = next; state = 'ready'; retry = 0; failure = '';
|
|
42
|
+
} catch (e) {
|
|
43
|
+
state = 'blocked'; failure = String(e.code || 'CA_INITIALIZATION_FAILED');
|
|
44
|
+
log(`blocked reason=${failure}`);
|
|
45
|
+
retry++;
|
|
46
|
+
}
|
|
47
|
+
if (!closed) {
|
|
48
|
+
timer = setTimeout(maintain, state === 'ready' ? 15000 : Math.min(30000, 1000 * 2 ** Math.min(retry, 5)));
|
|
49
|
+
timer.unref();
|
|
50
|
+
}
|
|
51
|
+
};
|
|
52
|
+
const shutdown = () => { closed = true; clearTimeout(timer); log('shutdown'); server.close(); process.exit(0); };
|
|
53
|
+
process.on('SIGINT', shutdown); process.on('SIGTERM', shutdown);
|
|
54
|
+
await maintain();
|
|
55
|
+
return server;
|
|
56
|
+
}
|
|
57
|
+
module.exports = { startManagedProxy };
|
package/bin/token-proxy.js
CHANGED
|
@@ -35,7 +35,7 @@ const MAX_LOG_SIZE = 10 * 1024 * 1024; // 10MB, then rotate
|
|
|
35
35
|
const DEFAULT_LOG_MAX_BYTES = 100 * 1024 * 1024; // 100MiB, then rotate
|
|
36
36
|
const LOG_MAX_BYTES = intEnv('AUTOWONDER_LOG_MAX_BYTES', DEFAULT_LOG_MAX_BYTES);
|
|
37
37
|
const RAW_LOG_MAX_BYTES = intEnv('AUTOWONDER_RAW_LOG_MAX_BYTES', DEFAULT_LOG_MAX_BYTES);
|
|
38
|
-
const DATA_DIR = path.join(os.homedir(), '.autowonder', 'token-tap');
|
|
38
|
+
const DATA_DIR = process.env.AUTOWONDER_TOKEN_PROXY_DATA_DIR || path.join(os.homedir(), '.autowonder', 'token-tap');
|
|
39
39
|
const CA_KEY_PATH = path.join(DATA_DIR, 'ca-key.pem');
|
|
40
40
|
const CA_CERT_PATH = path.join(DATA_DIR, 'ca-cert.pem');
|
|
41
41
|
const USAGE_LOG_PATH = path.join(DATA_DIR, 'token-usage.jsonl');
|
|
@@ -79,7 +79,7 @@ function shouldSniffHost(hostname, exactHosts = SNIFF_HOSTS, suffixes = SNIFF_HO
|
|
|
79
79
|
// a name carrying the timestamp and pid, and reopens a fresh file at the same
|
|
80
80
|
// path. A live descriptor is never truncated or unlinked, so no diagnostic
|
|
81
81
|
// line is lost mid-write.
|
|
82
|
-
function createRotatingWriter(filePath, { maxBytes = DEFAULT_LOG_MAX_BYTES } = {}) {
|
|
82
|
+
function createRotatingWriter(filePath, { maxBytes = DEFAULT_LOG_MAX_BYTES, maxArchives = 0 } = {}) {
|
|
83
83
|
fs.mkdirSync(path.dirname(filePath), { recursive: true });
|
|
84
84
|
let fd = fs.openSync(filePath, 'a', 0o600);
|
|
85
85
|
let size = fs.fstatSync(fd).size;
|
|
@@ -108,6 +108,11 @@ function createRotatingWriter(filePath, { maxBytes = DEFAULT_LOG_MAX_BYTES } = {
|
|
|
108
108
|
fs.closeSync(fd);
|
|
109
109
|
try {
|
|
110
110
|
fs.renameSync(filePath, archivePath());
|
|
111
|
+
if (maxArchives > 0) {
|
|
112
|
+
const ext = path.extname(filePath), prefix = path.basename(filePath, ext) + '.';
|
|
113
|
+
const entries = fs.readdirSync(path.dirname(filePath)).filter(n => n.startsWith(prefix) && n.endsWith(ext) && n !== path.basename(filePath)).sort().reverse();
|
|
114
|
+
for (const name of entries.slice(maxArchives)) { try { fs.unlinkSync(path.join(path.dirname(filePath), name)); } catch (_) {} }
|
|
115
|
+
}
|
|
111
116
|
} catch (_) {
|
|
112
117
|
// Archive failure keeps the live file in place; the incoming line
|
|
113
118
|
// still has to land somewhere.
|
|
@@ -231,15 +236,20 @@ function isCertExpired(certPath) {
|
|
|
231
236
|
}
|
|
232
237
|
|
|
233
238
|
function getHostCert(hostname, ca) {
|
|
234
|
-
if (
|
|
239
|
+
if (!/^[a-zA-Z0-9.-]+$/.test(hostname)) return null;
|
|
240
|
+
if (hostCertCache.size > 256) hostCertCache.clear();
|
|
241
|
+
const cacheKey = `${ca.fingerprint || 'legacy'}:${hostname}`;
|
|
242
|
+
if (hostCertCache.has(cacheKey)) return hostCertCache.get(cacheKey);
|
|
243
|
+
const certDir = ca.cacheDir || DATA_DIR;
|
|
244
|
+
fs.mkdirSync(certDir, { recursive: true, mode: 0o700 });
|
|
235
245
|
|
|
236
|
-
const certPath = path.join(
|
|
237
|
-
const keyPath = path.join(
|
|
246
|
+
const certPath = path.join(certDir, `${hostname}.pem`);
|
|
247
|
+
const keyPath = path.join(certDir, `${hostname}-key.pem`);
|
|
238
248
|
|
|
239
249
|
// Return cached cert from disk if still valid
|
|
240
250
|
const onDisk = readCertPair(certPath, keyPath);
|
|
241
251
|
if (onDisk && !isCertExpired(certPath)) {
|
|
242
|
-
hostCertCache.set(
|
|
252
|
+
hostCertCache.set(cacheKey, onDisk);
|
|
243
253
|
return onDisk;
|
|
244
254
|
}
|
|
245
255
|
if (!onDisk) {
|
|
@@ -258,27 +268,27 @@ function getHostCert(hostname, ca) {
|
|
|
258
268
|
const { execFileSync } = require('child_process');
|
|
259
269
|
// Per-process temp names keep two proxies that share one data dir from
|
|
260
270
|
// overwriting each other's signing inputs.
|
|
261
|
-
const csrPath = path.join(
|
|
262
|
-
const extPath = path.join(
|
|
271
|
+
const csrPath = path.join(certDir, `${hostname}.${process.pid}.csr`);
|
|
272
|
+
const extPath = path.join(certDir, `${hostname}.${process.pid}.ext`);
|
|
263
273
|
fs.writeFileSync(keyPath, privateKey, { mode: 0o600 });
|
|
264
274
|
fs.writeFileSync(extPath, `[v3_ext]\nsubjectAltName=DNS:${hostname}\n`, { mode: 0o600 });
|
|
265
275
|
|
|
266
276
|
// A per-signing random serial removes the shared ca-cert.srl file that
|
|
267
277
|
// concurrent signings used to race on. The ext file is a real path because
|
|
268
278
|
// openssl cannot reopen /dev/stdin when stdin is a Node pipe.
|
|
269
|
-
const sign = extraArgs => execFileSync('openssl', [
|
|
270
|
-
'x509', '-req', '-in', csrPath, '-CA', CA_CERT_PATH, '-CAkey', CA_KEY_PATH,
|
|
279
|
+
const sign = extraArgs => execFileSync(ca.openssl || 'openssl', [
|
|
280
|
+
'x509', '-req', '-in', csrPath, '-CA', ca.certPath || CA_CERT_PATH, '-CAkey', ca.keyPath || CA_KEY_PATH,
|
|
271
281
|
'-set_serial', `0x${crypto.randomBytes(16).toString('hex')}`,
|
|
272
282
|
'-out', certPath, '-days', '365', ...extraArgs,
|
|
273
|
-
], { stdio: 'pipe' });
|
|
283
|
+
], { stdio: 'pipe', timeout: 15000, windowsHide: true });
|
|
274
284
|
|
|
275
285
|
try {
|
|
276
|
-
execFileSync('openssl', ['req', '-new', '-key', keyPath, '-out', csrPath, '-subj', `/CN=${hostname}`], { stdio: 'pipe' });
|
|
286
|
+
execFileSync(ca.openssl || 'openssl', ['req', '-new', '-key', keyPath, '-out', csrPath, '-subj', `/CN=${hostname}`], { stdio: 'pipe', timeout: 15000, windowsHide: true });
|
|
277
287
|
sign(['-extfile', extPath, '-extensions', 'v3_ext']);
|
|
278
288
|
} catch (_) {
|
|
279
289
|
// Windows fallback: without SAN extension
|
|
280
290
|
try {
|
|
281
|
-
execFileSync('openssl', ['req', '-new', '-key', keyPath, '-out', csrPath, '-subj', `/CN=${hostname}`], { stdio: 'pipe' });
|
|
291
|
+
execFileSync(ca.openssl || 'openssl', ['req', '-new', '-key', keyPath, '-out', csrPath, '-subj', `/CN=${hostname}`], { stdio: 'pipe', timeout: 15000, windowsHide: true });
|
|
282
292
|
sign([]);
|
|
283
293
|
} catch (e2) {
|
|
284
294
|
// Cannot generate host cert — report and fall back to a blind tunnel.
|
|
@@ -299,7 +309,7 @@ function getHostCert(hostname, ca) {
|
|
|
299
309
|
try { fs.unlinkSync(extPath); } catch (_) {}
|
|
300
310
|
return null;
|
|
301
311
|
}
|
|
302
|
-
hostCertCache.set(
|
|
312
|
+
hostCertCache.set(cacheKey, result);
|
|
303
313
|
// Cleanup temp files
|
|
304
314
|
try { fs.unlinkSync(csrPath); } catch (_) {}
|
|
305
315
|
try { fs.unlinkSync(extPath); } catch (_) {}
|
|
@@ -1100,7 +1110,9 @@ if (require.main === module) {
|
|
|
1100
1110
|
if (command === 'start') {
|
|
1101
1111
|
const portIdx = args.indexOf('--port');
|
|
1102
1112
|
const port = portIdx >= 0 ? parseInt(args[portIdx + 1]) : DEFAULT_PORT;
|
|
1103
|
-
|
|
1113
|
+
if (args.includes('--managed')) {
|
|
1114
|
+
setImmediate(() => require('./token-proxy-service').startManagedProxy(port).catch(e => { console.error(e.message); process.exit(1); }));
|
|
1115
|
+
} else { startProxy(port); }
|
|
1104
1116
|
} else if (command === 'query') {
|
|
1105
1117
|
const jsonFlag = args.includes('--json');
|
|
1106
1118
|
const sinceIdx = args.indexOf('--since');
|
package/package.json
CHANGED
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|