@napuketto/cli 0.6.23 → 0.6.25
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 +3 -2
- package/dist/index.mjs +232 -71
- package/dist/index.mjs.map +1 -1
- package/package.json +4 -4
package/README.md
CHANGED
|
@@ -8,8 +8,9 @@ napuketto -q <QQ号> # 指定账号快速登录
|
|
|
8
8
|
napuketto -q A -q B # 多账号 supervisor 编排
|
|
9
9
|
napuketto supervisor # 读全局配置 accounts 拉起多账号子进程
|
|
10
10
|
napuketto config init # 生成默认全局配置(napuketto.toml)
|
|
11
|
-
napuketto config list #
|
|
12
|
-
napuketto config apply <file> #
|
|
11
|
+
napuketto config list # 列出全局配置与账号配置(token 等敏感字段默认脱敏)
|
|
12
|
+
napuketto config apply <file> # 应用外部配置(主配置 + 协议段校验后写回;输出默认脱敏)
|
|
13
13
|
```
|
|
14
14
|
|
|
15
15
|
常用选项:`-d, --data-dir <dir>` 数据根目录(缺省 `<项目根>/.napuketto`);`--stub-dir <dir>` stub QQNT.dll 目录。
|
|
16
|
+
`config list` / `config apply` 的 `--show-secrets` 输出明文敏感字段;`-q/--qq` 必须是 5-11 位真实 QQ 号,重复值会被拒绝。
|
package/dist/index.mjs
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import process from "node:process";
|
|
3
|
-
import { ConfigBase, ConfigError, EXIT_CONFIG_INVALID, configError, createLogger, errorMessage, hasNumberProp, hasStringProp, isRecord, kernelError, parseLogConfig, parseToml, resolveConfigPath, resolveDataRoot, stringifyToml } from "@napuketto/kernel";
|
|
3
|
+
import { CONFIG_FILE_MODE, ConfigBase, ConfigError, EXIT_CONFIG_INVALID, configError, createLogger, errorMessage, hasNumberProp, hasStringProp, isRecord, kernelError, parseLogConfig, parseToml, resolveConfigPath, resolveDataRoot, stringifyToml } from "@napuketto/kernel";
|
|
4
4
|
import { Command } from "commander";
|
|
5
5
|
import { mkdirSync, readFileSync, readdirSync, writeFileSync } from "node:fs";
|
|
6
6
|
import { access, readFile, writeFile } from "node:fs/promises";
|
|
7
|
-
import
|
|
7
|
+
import { dirname, extname, isAbsolute, join, resolve, sep } from "node:path";
|
|
8
8
|
import { QR_LINE_PREFIX, checkInstanceLock, defaultStubDir, isNativeNoiseLine, launchSelfHost, removeStopSentinel, resolveQqFiles, watchStopSentinel, writeStopSentinel } from "@napuketto/loader";
|
|
9
9
|
import { spawn } from "node:child_process";
|
|
10
10
|
import { createInterface } from "node:readline";
|
|
@@ -18,8 +18,8 @@ import { encode } from "uqr";
|
|
|
18
18
|
* 2026-08-08 结构拍板:**一个 QQ 账号一个 [[accounts]] 段,协议与通信配置嵌在
|
|
19
19
|
* 账号内**([accounts.onebot11] / [accounts.satori]);账号必填(至少一个)。
|
|
20
20
|
* 协议段为宽松对象,装配时由对应协议包的 zod schema 严格校验;
|
|
21
|
-
* `config validate` 例外(见 protocol-validate.ts
|
|
22
|
-
*
|
|
21
|
+
* `config validate` / `config apply` 例外(见 protocol-validate.ts:两条路径承诺与
|
|
22
|
+
* 装配同 schema,否则「校验/apply 通过但启动 78」,故仅在这两处懒加载 adapter 补校验)。
|
|
23
23
|
* 全部校验错误为 ConfigError(2026-10-25 嵌入式退出码契约:CLI exit 78 一族,
|
|
24
24
|
* 内联与文件两形态共用本校验器)。
|
|
25
25
|
*/
|
|
@@ -33,6 +33,21 @@ const DEFAULT_NATIVE_MEDIA_PATCH = true;
|
|
|
33
33
|
const DEFAULT_RESTART_DELAY_MS = 2e3;
|
|
34
34
|
/** QQ 号格式:纯数字 5-11 位(QQ 号合法范围,勿写死 11 位)。 */
|
|
35
35
|
const QQ_IN_FORMAT_RE = /^\d{5,11}$/;
|
|
36
|
+
/** 判定 QQ 号是否非法(undefined = 合法)。主配置校验与 CLI `-q` 入口共用。 */
|
|
37
|
+
function qqInvalidReason(qq) {
|
|
38
|
+
if (!QQ_IN_FORMAT_RE.test(qq)) return "format";
|
|
39
|
+
if (RESERVED_PLACEHOLDER_QINS.some((placeholder) => placeholder === qq)) return "placeholder";
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* CLI `-q/--qq` 入口校验(复用主配置 QQ 号规则):非法格式 / 模板占位值 /
|
|
43
|
+
* 路径穿越值一律 ConfigError(exit 78 一族)。返回原值便于链式使用。
|
|
44
|
+
*/
|
|
45
|
+
function parseCliQq(qq) {
|
|
46
|
+
const reason = qqInvalidReason(qq);
|
|
47
|
+
if (reason === "format") throw configError(`-q/--qq 参数 "${qq}" 非法:必须是 5-11 位纯数字 QQ 号`);
|
|
48
|
+
if (reason === "placeholder") throw configError(`-q/--qq 参数 "${qq}" 是模板占位值,请传入真实 QQ 号`);
|
|
49
|
+
return qq;
|
|
50
|
+
}
|
|
36
51
|
/** 解析账号内协议段(宽松对象,装配时由 zod schema 严格校验)。 */
|
|
37
52
|
function parseProtocolSection(raw, key) {
|
|
38
53
|
const section = raw[key];
|
|
@@ -73,7 +88,13 @@ function parseAccounts(raw) {
|
|
|
73
88
|
if (raw["accounts"] === void 0) throw configError("主配置缺少 accounts(必须至少一个账号);首次启动已生成模板,请编辑后重试");
|
|
74
89
|
if (!Array.isArray(raw["accounts"]) || raw["accounts"].length === 0) throw configError("主配置 accounts 必须是非空数组(至少一个 QQ 账号);首次启动已生成模板,请编辑后重试");
|
|
75
90
|
const accounts = [];
|
|
76
|
-
|
|
91
|
+
const seen = /* @__PURE__ */ new Set();
|
|
92
|
+
for (const item of raw["accounts"]) {
|
|
93
|
+
const account = parseAccount(item);
|
|
94
|
+
if (seen.has(account.qq)) throw configError(`主配置账号 qq 重复: "${account.qq}"(一个 QQ 号只允许一个 [[accounts]] 段)`);
|
|
95
|
+
seen.add(account.qq);
|
|
96
|
+
accounts.push(account);
|
|
97
|
+
}
|
|
77
98
|
return accounts;
|
|
78
99
|
}
|
|
79
100
|
/** 账号 qq 必填校验(非空字符串)。 */
|
|
@@ -85,8 +106,9 @@ function parseAccountQq(raw) {
|
|
|
85
106
|
}
|
|
86
107
|
/** qq 格式与占位值校验(5-11 位纯数字;模板占位号显式指路不静默)。 */
|
|
87
108
|
function assertValidQqFormat(qq) {
|
|
88
|
-
|
|
89
|
-
if (
|
|
109
|
+
const reason = qqInvalidReason(qq);
|
|
110
|
+
if (reason === "format") throw configError("主配置账号 qq 必须是 5-11 位纯数字 QQ 号");
|
|
111
|
+
if (reason === "placeholder") throw configError(`主配置账号 qq "${qq}" 是模板占位值,请编辑配置文件填入真实 QQ 号后再启动`);
|
|
90
112
|
}
|
|
91
113
|
/** 账号 enabled 可选校验(缺省 = 启用;显式给值必须是布尔)。 */
|
|
92
114
|
function applyAccountEnabled(out, enabled) {
|
|
@@ -237,14 +259,14 @@ function parseInlineConfig(text) {
|
|
|
237
259
|
}
|
|
238
260
|
// src/config/protocol-validate.ts
|
|
239
261
|
/**
|
|
240
|
-
* 协议段严格校验(`config validate`
|
|
262
|
+
* 协议段严格校验(`config validate` / `config apply` 共用)。
|
|
241
263
|
*
|
|
242
264
|
* 主配置解析(schema.ts)刻意保持协议段为宽松对象:普通启动路径不把协议包
|
|
243
265
|
* 拉进 CLI 进程,字段级校验由 loader 装配时用各协议自己的 zod schema 完成。
|
|
244
266
|
* 但 `config validate` 的承诺是「与运行时同一校验器落地」——只做 `isRecord`
|
|
245
267
|
* 浅校验会让 `httpServers = "not-an-array"` 报「配置合法」,真正启动却以 78
|
|
246
|
-
*
|
|
247
|
-
* adapter
|
|
268
|
+
* 退出;`config apply` 若跳过这层,则会把非法协议段写进主配置。因此两条路径
|
|
269
|
+
* 懒加载 adapter 补校验(普通 CLI 启动与 supervisor 不引入协议包)。
|
|
248
270
|
*
|
|
249
271
|
* 空段与 loader 装配语义一致:`{}` = 不启用该协议,跳过校验(kurobot 的
|
|
250
272
|
* url 必填只在段非空时生效)。
|
|
@@ -481,7 +503,10 @@ async function ensureConfigTemplate(path, onInfo) {
|
|
|
481
503
|
await access(path);
|
|
482
504
|
} catch {
|
|
483
505
|
mkdirSync(dirname(path), { recursive: true });
|
|
484
|
-
await writeFile(path, `${configTemplate()}\n`,
|
|
506
|
+
await writeFile(path, `${configTemplate()}\n`, {
|
|
507
|
+
encoding: "utf8",
|
|
508
|
+
...process.platform === "win32" ? {} : { mode: CONFIG_FILE_MODE }
|
|
509
|
+
});
|
|
485
510
|
onInfo?.({ path }, "配置文件不存在,已生成默认模板(请编辑 accounts 段填入 QQ 号)");
|
|
486
511
|
}
|
|
487
512
|
}
|
|
@@ -668,6 +693,24 @@ function toRecord(config) {
|
|
|
668
693
|
...config.log === void 0 ? {} : { log: config.log }
|
|
669
694
|
};
|
|
670
695
|
}
|
|
696
|
+
/** stdout 敏感字段默认脱敏(协议段 token 等;`--show-secrets` 才输出明文)。 */
|
|
697
|
+
const SENSITIVE_KEY_RE = /^(?:token|access[_-]?token|secret|password)$/i;
|
|
698
|
+
/** 脱敏占位(保持 TOML 字符串类型,便于脚本继续 parse)。 */
|
|
699
|
+
const SECRET_MASK = "***";
|
|
700
|
+
/** 深度复制并脱敏敏感字段(空串 = 未配置凭据,保持原样)。 */
|
|
701
|
+
function maskSecrets(value) {
|
|
702
|
+
if (Array.isArray(value)) return value.map(maskSecrets);
|
|
703
|
+
if (!isRecord(value)) return value;
|
|
704
|
+
const out = {};
|
|
705
|
+
for (const [key, val] of Object.entries(value)) out[key] = SENSITIVE_KEY_RE.test(key) && typeof val === "string" && val !== "" ? SECRET_MASK : maskSecrets(val);
|
|
706
|
+
return out;
|
|
707
|
+
}
|
|
708
|
+
/** stdout 输出用配置对象(默认脱敏;写盘始终用未脱敏原对象)。 */
|
|
709
|
+
function toOutputRecord(config, showSecrets) {
|
|
710
|
+
const record = toRecord(config);
|
|
711
|
+
if (showSecrets === true) return record;
|
|
712
|
+
return maskSecrets(record);
|
|
713
|
+
}
|
|
671
714
|
/** config init:生成全局 TOML 配置文件(项目根)+ 数据根目录。
|
|
672
715
|
* 文件不存在 → 写带注释模板;已存在 → 跳过(不覆盖用户配置)。
|
|
673
716
|
* 输出原始模板内容(账号未填时解析会校验失败,init 只负责生成不校验)。 */
|
|
@@ -680,7 +723,10 @@ async function cmdConfigInit(opts) {
|
|
|
680
723
|
await access(store.path);
|
|
681
724
|
} catch {
|
|
682
725
|
mkdirSync(dirname(store.path), { recursive: true });
|
|
683
|
-
await writeFile(store.path, `${configTemplate()}\n`,
|
|
726
|
+
await writeFile(store.path, `${configTemplate()}\n`, {
|
|
727
|
+
encoding: "utf8",
|
|
728
|
+
...process.platform === "win32" ? {} : { mode: CONFIG_FILE_MODE }
|
|
729
|
+
});
|
|
684
730
|
created = true;
|
|
685
731
|
}
|
|
686
732
|
const raw = await readFile(store.path, "utf8");
|
|
@@ -689,14 +735,14 @@ async function cmdConfigInit(opts) {
|
|
|
689
735
|
else logger.info({ path: store.path }, "全局配置已存在(跳过生成,避免覆盖用户配置)");
|
|
690
736
|
process.stdout.write(raw);
|
|
691
737
|
}
|
|
692
|
-
/** config list
|
|
738
|
+
/** config list:列出全局配置与各账号目录(stdout 敏感字段默认脱敏)。 */
|
|
693
739
|
async function cmdConfigList(opts) {
|
|
694
740
|
const dataRoot = resolveDataRoot(opts.dataDir);
|
|
695
741
|
const store = new CliConfigStore(dataRoot);
|
|
696
742
|
const config = await store.load();
|
|
697
743
|
logger.info({ dataRoot }, "数据根");
|
|
698
744
|
logger.info({ path: store.path }, "全局配置");
|
|
699
|
-
process.stdout.write(`${stringifyToml(
|
|
745
|
+
process.stdout.write(`${stringifyToml(toOutputRecord(config, opts.showSecrets))}\n`);
|
|
700
746
|
let entries;
|
|
701
747
|
try {
|
|
702
748
|
entries = readdirSync(dataRoot, { withFileTypes: true });
|
|
@@ -721,16 +767,16 @@ function printAccountConfig(account, dataRoot) {
|
|
|
721
767
|
files: fileList
|
|
722
768
|
}, "账号配置");
|
|
723
769
|
}
|
|
724
|
-
/** 解析外部配置文本(按扩展名推断 TOML/JSON)。 */
|
|
770
|
+
/** 解析外部配置文本(按扩展名推断 TOML/JSON,语法错误统一 INVALID_PARAM)。 */
|
|
725
771
|
function parseExternalConfig(file, rawText) {
|
|
726
|
-
|
|
772
|
+
const format = extname(file).toLowerCase() === ".toml" ? "TOML" : "JSON";
|
|
727
773
|
try {
|
|
728
|
-
return JSON.parse(rawText);
|
|
729
|
-
} catch {
|
|
730
|
-
throw kernelError(`外部配置 ${file} 不是合法
|
|
774
|
+
return format === "TOML" ? parseToml(rawText) : JSON.parse(rawText);
|
|
775
|
+
} catch (err) {
|
|
776
|
+
throw kernelError(`外部配置 ${file} 不是合法 ${format}`, "INVALID_PARAM", { cause: err });
|
|
731
777
|
}
|
|
732
778
|
}
|
|
733
|
-
/** config apply
|
|
779
|
+
/** config apply:应用外部配置(顶层覆盖合并、主配置 + 协议段校验后写回全局配置)。 */
|
|
734
780
|
async function cmdConfigApply(file, opts) {
|
|
735
781
|
const store = new CliConfigStore(resolveDataRoot(opts.dataDir));
|
|
736
782
|
const existing = await store.load();
|
|
@@ -747,9 +793,10 @@ async function cmdConfigApply(file, opts) {
|
|
|
747
793
|
...existing,
|
|
748
794
|
...partial
|
|
749
795
|
});
|
|
796
|
+
await validateProtocolSections(next);
|
|
750
797
|
await store.save(next);
|
|
751
798
|
logger.info({ path: store.path }, "全局配置已更新");
|
|
752
|
-
process.stdout.write(`${stringifyToml(
|
|
799
|
+
process.stdout.write(`${stringifyToml(toOutputRecord(next, opts.showSecrets))}\n`);
|
|
753
800
|
}
|
|
754
801
|
/** 读取配置文件文本(validate 纯只读:ENOENT 不落模板,按「配置缺失」报 ConfigError)。 */
|
|
755
802
|
async function readConfigTextForValidate(path) {
|
|
@@ -817,9 +864,22 @@ async function cmdConfigValidate(opts) {
|
|
|
817
864
|
const RUNTIME_FILE = "runtime.json";
|
|
818
865
|
/** supervisor.json 文件名。 */
|
|
819
866
|
const SUPERVISOR_FILE = "supervisor.json";
|
|
820
|
-
/**
|
|
867
|
+
/**
|
|
868
|
+
* 账号数据目录(数据根路径边界防御):uin 必须是单一路径段,解析后必须落在
|
|
869
|
+
* dataRoot 内。CLI `-q` 入口已按 QQ 号格式校验,这里兜底任何直接调用方
|
|
870
|
+
* (`-q ../../x` / 绝对路径等不得逃出数据根)。非法值抛 ConfigError(exit 78)。
|
|
871
|
+
*/
|
|
872
|
+
function accountDir(dataRoot, uin) {
|
|
873
|
+
if (uin === "" || uin === "." || uin === ".." || isAbsolute(uin)) throw configError(`非法账号标识 "${uin}":必须是单个路径段(不允许绝对路径)`);
|
|
874
|
+
if (uin.includes("/") || uin.includes("\\")) throw configError(`非法账号标识 "${uin}":不允许包含路径分隔符`);
|
|
875
|
+
const root = resolve(dataRoot);
|
|
876
|
+
const resolved = resolve(root, uin);
|
|
877
|
+
if (resolved !== root && !resolved.startsWith(`${root}${sep}`)) throw configError(`账号数据目录越界: ${resolved} 不在数据根 ${root} 内`);
|
|
878
|
+
return join(dataRoot, uin);
|
|
879
|
+
}
|
|
880
|
+
/** 账号状态文件路径(经 accountDir 边界校验)。 */
|
|
821
881
|
function runtimeStatePath(dataRoot, uin) {
|
|
822
|
-
return join(dataRoot, uin, RUNTIME_FILE);
|
|
882
|
+
return join(accountDir(dataRoot, uin), RUNTIME_FILE);
|
|
823
883
|
}
|
|
824
884
|
/** supervisor 状态文件路径。 */
|
|
825
885
|
function supervisorStatePath(dataRoot) {
|
|
@@ -948,6 +1008,13 @@ function aggregateStatus(runtimes, aliveFn = isPidAlive) {
|
|
|
948
1008
|
const GRACEFUL_STOP_WAIT_MS = 8e3;
|
|
949
1009
|
/** 存活轮询间隔(毫秒)。 */
|
|
950
1010
|
const LIVENESS_POLL_MS = 200;
|
|
1011
|
+
/**
|
|
1012
|
+
* 运维命令 `-q` 入口校验(复用主配置 QQ 规则):非法值抛 ConfigError(exit 78),
|
|
1013
|
+
* 避免 `-q all` 命中全局停止哨兵或 `-q ../..` 拼出数据根之外的路径。
|
|
1014
|
+
*/
|
|
1015
|
+
function assertOpsQq(opts) {
|
|
1016
|
+
if (opts.qq !== void 0) parseCliQq(opts.qq);
|
|
1017
|
+
}
|
|
951
1018
|
/** 等待 pid 列表全部退出(返回超时仍未退的 pid)。 */
|
|
952
1019
|
async function waitForPidsExit(pids) {
|
|
953
1020
|
const deadline = Date.now() + GRACEFUL_STOP_WAIT_MS;
|
|
@@ -960,6 +1027,7 @@ async function waitForPidsExit(pids) {
|
|
|
960
1027
|
}
|
|
961
1028
|
/** status:聚合输出各账号运行状态(含 supervisor 自身)。 */
|
|
962
1029
|
function cmdStatus(dataRoot, opts) {
|
|
1030
|
+
assertOpsQq(opts);
|
|
963
1031
|
const supervisor = readSupervisorRuntime(dataRoot);
|
|
964
1032
|
if (supervisor !== null) logger.info({
|
|
965
1033
|
pid: supervisor.pid,
|
|
@@ -1017,6 +1085,7 @@ async function stopSingleAccount(dataRoot, target) {
|
|
|
1017
1085
|
if (supervisor !== null) logger.warn({ supervisorPid: supervisor.pid }, "supervisor 仍在运行且 autoRestart 开启时会自动拉起该账号;如需彻底停止请执行 napuketto stop(停 supervisor)");
|
|
1018
1086
|
}
|
|
1019
1087
|
async function cmdStop(dataRoot, opts) {
|
|
1088
|
+
assertOpsQq(opts);
|
|
1020
1089
|
const runtimes = listAccountRuntimes(dataRoot);
|
|
1021
1090
|
if (opts.qq !== void 0) {
|
|
1022
1091
|
const target = runtimes.find((r) => r.uin === opts.qq);
|
|
@@ -1045,6 +1114,7 @@ async function cmdStop(dataRoot, opts) {
|
|
|
1045
1114
|
}
|
|
1046
1115
|
/** restart:stop 同目标 + detached 拉起。 */
|
|
1047
1116
|
async function cmdRestart(dataRoot, opts) {
|
|
1117
|
+
assertOpsQq(opts);
|
|
1048
1118
|
await cmdStop(dataRoot, opts);
|
|
1049
1119
|
await new Promise((resolve) => setTimeout(resolve, 1500));
|
|
1050
1120
|
const entry = process.argv[1] ?? "";
|
|
@@ -1311,19 +1381,34 @@ function installGracefulStop(child, dataRoot, account) {
|
|
|
1311
1381
|
process.on("SIGBREAK", () => onSignal("SIGBREAK"));
|
|
1312
1382
|
return () => stopArmed;
|
|
1313
1383
|
}
|
|
1314
|
-
/**
|
|
1384
|
+
/**
|
|
1385
|
+
* 常驻:等待自建宿主进程退出(exit / error 两路径均 resolve,去留由 self-host 决定)。
|
|
1386
|
+
*
|
|
1387
|
+
* 退出码契约(issue #144):boot 进程必须把 self-host 的失败退出码透传给父进程
|
|
1388
|
+
* (supervisor / 容器编排),否则 supervisor 的 `EXIT_CONFIG_INVALID(78)` 免重启
|
|
1389
|
+
* 判定永远不命中,所有失败都被当成 code=0 正常退出。规则:
|
|
1390
|
+
* - 收到停止请求(isStopping)→ 0(请求式正常退出,与崩溃区分);
|
|
1391
|
+
* - 非停止状态下异常退出(code 非 0 或被 signal 杀死)→ 透传 code(signal 无 code 时为 1);
|
|
1392
|
+
* - 非停止状态 code=0 视为 self-host 自行正常结束,保持 0;
|
|
1393
|
+
* - spawn error 无退出码可透传 → 1。
|
|
1394
|
+
*/
|
|
1315
1395
|
async function waitSelfHostExit(child, dataRoot, account, isStopping) {
|
|
1316
1396
|
await new Promise((resolve) => {
|
|
1317
|
-
child.on("exit", (code) => {
|
|
1397
|
+
child.on("exit", (code, signal) => {
|
|
1398
|
+
const graceful = isStopping();
|
|
1318
1399
|
logger.info({
|
|
1319
1400
|
code,
|
|
1320
|
-
|
|
1401
|
+
signal: signal ?? "none",
|
|
1402
|
+
graceful
|
|
1321
1403
|
}, "自建宿主进程退出");
|
|
1322
1404
|
recordRuntimeState(dataRoot, account, child, "exited", code);
|
|
1405
|
+
if (graceful) process.exitCode = 0;
|
|
1406
|
+
else if (code !== 0 || signal !== null) process.exitCode = code ?? 1;
|
|
1323
1407
|
resolve();
|
|
1324
1408
|
});
|
|
1325
1409
|
child.on("error", (err) => {
|
|
1326
1410
|
logger.error({ err }, "自建宿主进程启动失败");
|
|
1411
|
+
process.exitCode = 1;
|
|
1327
1412
|
resolve();
|
|
1328
1413
|
});
|
|
1329
1414
|
});
|
|
@@ -1331,10 +1416,11 @@ async function waitSelfHostExit(child, dataRoot, account, isStopping) {
|
|
|
1331
1416
|
/** 启动单个账号(自建宿主 + 常驻)。 */
|
|
1332
1417
|
async function runSingleAccount(opts = {}) {
|
|
1333
1418
|
const dataRoot = resolveDataRoot(opts.dataDir);
|
|
1419
|
+
const account = opts.qq ?? "default";
|
|
1420
|
+
if (account === "all") throw configError("账号 \"all\" 是停止哨兵保留值,拒绝启动");
|
|
1421
|
+
const cfgDir = accountDir(dataRoot, account);
|
|
1334
1422
|
const qq = await locateQqFiles(dataRoot, opts);
|
|
1335
1423
|
if (qq === void 0) return;
|
|
1336
|
-
const account = opts.qq ?? "default";
|
|
1337
|
-
const cfgDir = path.join(dataRoot, account);
|
|
1338
1424
|
if (!ensureInstanceLockFree(cfgDir)) return;
|
|
1339
1425
|
const { child } = await startSelfHost(opts, qq, cfgDir, dataRoot);
|
|
1340
1426
|
forwardChildOutput(child);
|
|
@@ -1356,9 +1442,38 @@ async function runSingleAccount(opts = {}) {
|
|
|
1356
1442
|
const EXIT_POLL_MS = 100;
|
|
1357
1443
|
/** 子进程优雅退出时限(毫秒):哨兵/信号后子进程自行停止,超时强杀兜底。 */
|
|
1358
1444
|
const FORCE_EXIT_MS = 8e3;
|
|
1359
|
-
/**
|
|
1445
|
+
/**
|
|
1446
|
+
* 短生命周期崩溃阈值(毫秒,issue #144):运行不足该时长的退出视为「连续秒退」,
|
|
1447
|
+
* 重启延迟按 `restartDelayMs * 2^n` 指数退避,避免登录后立刻崩溃时高频循环重登
|
|
1448
|
+
* 触发 QQ 风控;稳定运行超过该时长后退避计数清零。
|
|
1449
|
+
*/
|
|
1450
|
+
const SHORT_LIVED_CRASH_MS = 3e4;
|
|
1451
|
+
/** 指数退避延迟上限(毫秒):连续秒退时单次重启最多等 60s。 */
|
|
1452
|
+
const MAX_RESTART_DELAY_MS = 6e4;
|
|
1453
|
+
/**
|
|
1454
|
+
* 计算下一次守护重启延迟(issue #144)。
|
|
1455
|
+
* @param baseDelayMs 配置的首次重启延迟(restartDelayMs)
|
|
1456
|
+
* @param consecutiveFailures 连续短生命周期失败次数(从 1 起)
|
|
1457
|
+
*/
|
|
1458
|
+
function computeRestartDelayMs(baseDelayMs, consecutiveFailures) {
|
|
1459
|
+
const exponent = Math.max(consecutiveFailures - 1, 0);
|
|
1460
|
+
return Math.min(baseDelayMs * 2 ** exponent, MAX_RESTART_DELAY_MS);
|
|
1461
|
+
}
|
|
1462
|
+
/**
|
|
1463
|
+
* 解析账号列表(显式 -q 优先,否则主配置 accounts 过滤启用项)。
|
|
1464
|
+
* 显式 -q 在此再次校验格式并拒绝重复:重复 qq 会并发拉起同一账号,后一个
|
|
1465
|
+
* 子进程覆盖 ctx.children 的 Map 项,导致实例锁冲突与状态文件互相覆盖。
|
|
1466
|
+
*/
|
|
1360
1467
|
function resolveAccounts(opts, config) {
|
|
1361
|
-
if (opts.qqs !== void 0 && opts.qqs.length > 0)
|
|
1468
|
+
if (opts.qqs !== void 0 && opts.qqs.length > 0) {
|
|
1469
|
+
const seen = /* @__PURE__ */ new Set();
|
|
1470
|
+
return opts.qqs.map((qq) => {
|
|
1471
|
+
parseCliQq(qq);
|
|
1472
|
+
if (seen.has(qq)) throw configError(`-q/--qq 重复指定账号: "${qq}"(每个账号只能出现一次)`);
|
|
1473
|
+
seen.add(qq);
|
|
1474
|
+
return { qq };
|
|
1475
|
+
});
|
|
1476
|
+
}
|
|
1362
1477
|
return config.accounts.filter((acct) => acct.enabled !== false);
|
|
1363
1478
|
}
|
|
1364
1479
|
/** 解析重启延迟(显式 -q 用默认,主配置场景用配置值)。 */
|
|
@@ -1377,6 +1492,65 @@ function forwardPrefixed(stream, uin, prefixEnabled) {
|
|
|
1377
1492
|
process.stdout.write(prefixEnabled ? `[${uin}] ${line}\n` : `${line}\n`);
|
|
1378
1493
|
});
|
|
1379
1494
|
}
|
|
1495
|
+
/** 账号进程退出落 runtime exited(status/stop 消费)。 */
|
|
1496
|
+
function writeAccountExited(ctx, acct, child, exitCode, restartCount) {
|
|
1497
|
+
writeAccountRuntime(ctx.dataRoot, {
|
|
1498
|
+
uin: acct.qq,
|
|
1499
|
+
pid: child.pid ?? 0,
|
|
1500
|
+
startedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
1501
|
+
kind: "supervisor-child",
|
|
1502
|
+
status: "exited",
|
|
1503
|
+
exitCode,
|
|
1504
|
+
restartCount
|
|
1505
|
+
});
|
|
1506
|
+
}
|
|
1507
|
+
/**
|
|
1508
|
+
* 守护重启编排(issue #144):短生命周期崩溃按指数退避,稳定运行超过阈值后
|
|
1509
|
+
* 计数清零(恢复配置的基础延迟)。日志始终带连续失败次数与下次重启延迟。
|
|
1510
|
+
*/
|
|
1511
|
+
function scheduleRestart(ctx, acct, code, signal, startedAtMs, restartCount) {
|
|
1512
|
+
const uptimeMs = Date.now() - startedAtMs;
|
|
1513
|
+
const shortLived = uptimeMs < SHORT_LIVED_CRASH_MS;
|
|
1514
|
+
const consecutiveFailures = shortLived ? (ctx.crashCounts.get(acct.qq) ?? 0) + 1 : 0;
|
|
1515
|
+
ctx.crashCounts.set(acct.qq, consecutiveFailures);
|
|
1516
|
+
const delayMs = consecutiveFailures > 0 ? computeRestartDelayMs(ctx.restartDelayMs, consecutiveFailures) : ctx.restartDelayMs;
|
|
1517
|
+
const fields = {
|
|
1518
|
+
qq: acct.qq,
|
|
1519
|
+
code,
|
|
1520
|
+
signal: signal ?? "none",
|
|
1521
|
+
uptimeMs,
|
|
1522
|
+
consecutiveFailures,
|
|
1523
|
+
nextDelayMs: delayMs
|
|
1524
|
+
};
|
|
1525
|
+
if (shortLived) logger.warn(fields, "账号启动后短时间内退出,指数退避后重启");
|
|
1526
|
+
else logger.info(fields, "账号退出,准备重启");
|
|
1527
|
+
ctx.restartCounts.set(acct.qq, restartCount + 1);
|
|
1528
|
+
setTimeout(() => {
|
|
1529
|
+
startAccount(ctx, acct);
|
|
1530
|
+
}, delayMs);
|
|
1531
|
+
}
|
|
1532
|
+
/** 账号子进程退出编排:配置失败免重启(78)/ 守护重启 / 落 runtime exited。 */
|
|
1533
|
+
function handleAccountExit(ctx, acct, child, code, signal, startedAtMs, restartCount) {
|
|
1534
|
+
ctx.children.delete(acct.qq);
|
|
1535
|
+
logger.info({
|
|
1536
|
+
qq: acct.qq,
|
|
1537
|
+
code,
|
|
1538
|
+
signal: signal ?? "none"
|
|
1539
|
+
}, "账号退出");
|
|
1540
|
+
if (code === EXIT_CONFIG_INVALID) {
|
|
1541
|
+
logger.error({
|
|
1542
|
+
qq: acct.qq,
|
|
1543
|
+
code
|
|
1544
|
+
}, "账号因配置校验失败退出(78),不自动重启");
|
|
1545
|
+
writeAccountExited(ctx, acct, child, code, restartCount);
|
|
1546
|
+
return;
|
|
1547
|
+
}
|
|
1548
|
+
if (!ctx.isStopping() && ctx.autoRestart) {
|
|
1549
|
+
scheduleRestart(ctx, acct, code, signal, startedAtMs, restartCount);
|
|
1550
|
+
return;
|
|
1551
|
+
}
|
|
1552
|
+
writeAccountExited(ctx, acct, child, code, restartCount);
|
|
1553
|
+
}
|
|
1380
1554
|
/** 启动一个账号子进程(exit 后按 autoRestart 守护重启)。 */
|
|
1381
1555
|
function startAccount(ctx, acct) {
|
|
1382
1556
|
if (ctx.isStopping()) return;
|
|
@@ -1406,6 +1580,7 @@ function startAccount(ctx, acct) {
|
|
|
1406
1580
|
...ctx.childEnv
|
|
1407
1581
|
}
|
|
1408
1582
|
});
|
|
1583
|
+
const startedAtMs = Date.now();
|
|
1409
1584
|
forwardPrefixed(child.stdout, acct.qq, ctx.prefixEnabled);
|
|
1410
1585
|
forwardPrefixed(child.stderr, acct.qq, ctx.prefixEnabled);
|
|
1411
1586
|
ctx.children.set(acct.qq, child);
|
|
@@ -1418,42 +1593,7 @@ function startAccount(ctx, acct) {
|
|
|
1418
1593
|
restartCount
|
|
1419
1594
|
});
|
|
1420
1595
|
child.on("exit", (code, signal) => {
|
|
1421
|
-
ctx
|
|
1422
|
-
logger.info({
|
|
1423
|
-
qq: acct.qq,
|
|
1424
|
-
code,
|
|
1425
|
-
signal: signal ?? "none"
|
|
1426
|
-
}, "账号退出");
|
|
1427
|
-
if (code === EXIT_CONFIG_INVALID) {
|
|
1428
|
-
logger.error({
|
|
1429
|
-
qq: acct.qq,
|
|
1430
|
-
code
|
|
1431
|
-
}, "账号因配置校验失败退出(78),不自动重启");
|
|
1432
|
-
writeAccountRuntime(ctx.dataRoot, {
|
|
1433
|
-
uin: acct.qq,
|
|
1434
|
-
pid: child.pid ?? 0,
|
|
1435
|
-
startedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
1436
|
-
kind: "supervisor-child",
|
|
1437
|
-
status: "exited",
|
|
1438
|
-
exitCode: code,
|
|
1439
|
-
restartCount
|
|
1440
|
-
});
|
|
1441
|
-
return;
|
|
1442
|
-
}
|
|
1443
|
-
if (!ctx.isStopping() && ctx.autoRestart) {
|
|
1444
|
-
ctx.restartCounts.set(acct.qq, restartCount + 1);
|
|
1445
|
-
setTimeout(() => {
|
|
1446
|
-
startAccount(ctx, acct);
|
|
1447
|
-
}, ctx.restartDelayMs);
|
|
1448
|
-
} else writeAccountRuntime(ctx.dataRoot, {
|
|
1449
|
-
uin: acct.qq,
|
|
1450
|
-
pid: child.pid ?? 0,
|
|
1451
|
-
startedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
1452
|
-
kind: "supervisor-child",
|
|
1453
|
-
status: "exited",
|
|
1454
|
-
exitCode: code,
|
|
1455
|
-
restartCount
|
|
1456
|
-
});
|
|
1596
|
+
handleAccountExit(ctx, acct, child, code, signal, startedAtMs, restartCount);
|
|
1457
1597
|
});
|
|
1458
1598
|
child.on("error", (err) => {
|
|
1459
1599
|
const { message } = err;
|
|
@@ -1503,6 +1643,7 @@ async function runSupervisor(opts = {}) {
|
|
|
1503
1643
|
const [, entry = ""] = process.argv;
|
|
1504
1644
|
const children = /* @__PURE__ */ new Map();
|
|
1505
1645
|
const restartCounts = /* @__PURE__ */ new Map();
|
|
1646
|
+
const crashCounts = /* @__PURE__ */ new Map();
|
|
1506
1647
|
let stopping = false;
|
|
1507
1648
|
const logCfg = resolveCliLogConfig(opts.dataDir);
|
|
1508
1649
|
const ctx = {
|
|
@@ -1513,6 +1654,7 @@ async function runSupervisor(opts = {}) {
|
|
|
1513
1654
|
...opts.stubDir !== void 0 ? { stubDir: opts.stubDir } : {},
|
|
1514
1655
|
children,
|
|
1515
1656
|
restartCounts,
|
|
1657
|
+
crashCounts,
|
|
1516
1658
|
childEnv: {
|
|
1517
1659
|
...effectiveConsoleEnv(logCfg),
|
|
1518
1660
|
...config.nativeMediaPatch === false ? { NAPUTO_DISABLE_MEDIA_PATCH: "1" } : {}
|
|
@@ -1572,9 +1714,22 @@ async function autoStart(opts) {
|
|
|
1572
1714
|
...opts.stubDir === void 0 ? {} : { stubDir: opts.stubDir }
|
|
1573
1715
|
});
|
|
1574
1716
|
}
|
|
1717
|
+
/**
|
|
1718
|
+
* -q 列表入口校验(2026-11 安全加固):格式/占位值复用主配置规则,重复值直接报错。
|
|
1719
|
+
* ConfigError → exit 78;放在分发最前,非法值不会进入数据目录拼接或 supervisor。
|
|
1720
|
+
*/
|
|
1721
|
+
function parseQqList(qqs) {
|
|
1722
|
+
const seen = /* @__PURE__ */ new Set();
|
|
1723
|
+
for (const qq of qqs) {
|
|
1724
|
+
parseCliQq(qq);
|
|
1725
|
+
if (seen.has(qq)) throw configError(`-q/--qq 重复指定账号: "${qq}"(每个账号只能出现一次)`);
|
|
1726
|
+
seen.add(qq);
|
|
1727
|
+
}
|
|
1728
|
+
return qqs;
|
|
1729
|
+
}
|
|
1575
1730
|
/** 主命令分发:无 -q 读配置 supervisor 拉起 / 单 -q 单账号 / 多 -q supervisor。 */
|
|
1576
1731
|
async function dispatchMainAction(opts) {
|
|
1577
|
-
const qqs = opts.qq ?? [];
|
|
1732
|
+
const qqs = parseQqList(opts.qq ?? []);
|
|
1578
1733
|
if (qqs.length === 0) {
|
|
1579
1734
|
await autoStart(opts);
|
|
1580
1735
|
return;
|
|
@@ -1687,16 +1842,22 @@ function registerConfigCommands(program) {
|
|
|
1687
1842
|
handleActionError(err);
|
|
1688
1843
|
}
|
|
1689
1844
|
});
|
|
1690
|
-
configCmd.command("list").description("列出全局配置与账号配置").action(async () => {
|
|
1845
|
+
configCmd.command("list").description("列出全局配置与账号配置").option("--show-secrets", "输出明文敏感字段(协议 token 等;默认脱敏)").action(async (opts) => {
|
|
1691
1846
|
try {
|
|
1692
|
-
await cmdConfigList(
|
|
1847
|
+
await cmdConfigList({
|
|
1848
|
+
...rootDataDir(program),
|
|
1849
|
+
...opts.showSecrets === true ? { showSecrets: true } : {}
|
|
1850
|
+
});
|
|
1693
1851
|
} catch (err) {
|
|
1694
1852
|
handleActionError(err);
|
|
1695
1853
|
}
|
|
1696
1854
|
});
|
|
1697
|
-
configCmd.command("apply <file>").description("应用外部配置(TOML/JSON,校验后写回全局配置)").action(async (file) => {
|
|
1855
|
+
configCmd.command("apply <file>").description("应用外部配置(TOML/JSON,校验后写回全局配置)").option("--show-secrets", "输出明文敏感字段(协议 token 等;默认脱敏)").action(async (file, opts) => {
|
|
1698
1856
|
try {
|
|
1699
|
-
await cmdConfigApply(file,
|
|
1857
|
+
await cmdConfigApply(file, {
|
|
1858
|
+
...rootDataDir(program),
|
|
1859
|
+
...opts.showSecrets === true ? { showSecrets: true } : {}
|
|
1860
|
+
});
|
|
1700
1861
|
} catch (err) {
|
|
1701
1862
|
handleActionError(err);
|
|
1702
1863
|
}
|