@mrrisega/dsh-remote 0.7.12-beta.4 → 0.7.12-beta.6

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.
@@ -0,0 +1,302 @@
1
+ /**
2
+ * im-commands — 三家 IM 机器人(企微 / 钉钉 / 飞书)共用的**命令层**(2026-11-08)。
3
+ *
4
+ * 业主实测:在钉钉里发 `/ls` 期望列会话,但当时没有命令层 → `/ls` 被当成 prompt 转给了模型。
5
+ * 命令层把这类「控制类消息」在**进模型之前**拦下、自己执行并回复;解析器/文案/能力门禁三家共用,
6
+ * 各通道只负责把回复发出去(企微被动回复 / 钉钉 sessionWebhook / 飞书 im/v1/messages)。
7
+ *
8
+ * 命令表(能力门禁复用 `WECHAT_CAPABILITY_TABLE`,与会员升级文案同口径):
9
+ * | 命令 | 能力 | 免费 | 说明 |
10
+ * | /help | 无 | ✅ | 列出全部命令(含会员命令标注) |
11
+ * | /status | 无 | ✅ | 连接状态 + 当前会话 + 本月剩余指令 |
12
+ * | /stop | 无 | ✅ | 急停当前任务(安全阀必须免费、立即生效)|
13
+ * | /ls | sessions | ❌ | 最近 ≤10 个会话(标题/索引/当前标记) |
14
+ * | /use <N> | sessions | ❌ | 切换当前绑定会话(写配置 sessionId) |
15
+ * | /unbind | 无 | ✅ | 解绑/退订本会话推送(合规:随时可退订)|
16
+ *
17
+ * 未命中的 `/xxx`:回帮助提示(含"未知命令"),**绝不转给模型**。
18
+ * 回复一律用纯文本列表(不用 Markdown 表格;各通道发送前还会走 im-format 兜底)。
19
+ */
20
+
21
+ import path from "node:path";
22
+
23
+ import { WECHAT_CAPABILITY_TABLE, grantsCap } from "./wechat-runtime.mjs";
24
+ import { IM_BOTS_FILE, atomicWriteJson, readJsonFile } from "./wecom-bot.mjs";
25
+
26
+ /** 命令表(顺序即 /help 展示顺序)。`free` 只是文档标记;真正门禁看 caps。 */
27
+ export const IM_COMMANDS = Object.freeze([
28
+ Object.freeze({ name: "/help", caps: Object.freeze([]), free: true, usage: "/help", summary: "查看命令" }),
29
+ Object.freeze({ name: "/status", caps: Object.freeze([]), free: true, usage: "/status", summary: "连接状态 / 当前会话 / 本月额度" }),
30
+ Object.freeze({ name: "/stop", caps: Object.freeze([]), free: true, usage: "/stop", summary: "急停当前任务" }),
31
+ Object.freeze({ name: "/ls", caps: Object.freeze(["sessions"]), free: false, usage: "/ls", summary: "列出最近会话(会员)" }),
32
+ Object.freeze({ name: "/use", caps: Object.freeze(["sessions"]), free: false, usage: "/use <序号>", summary: "切换当前会话(会员)" }),
33
+ Object.freeze({ name: "/unbind", caps: Object.freeze([]), free: true, usage: "/unbind", summary: "解绑本会话推送(随时可退订)" })
34
+ ]);
35
+
36
+ /** 会话标题截断(按码点,避免切坏 emoji/中文)。 */
37
+ export function truncateTitle(title, max = 24) {
38
+ const s = String(title == null ? "" : title).replace(/\s+/g, " ").trim();
39
+ if (!s) return "";
40
+ const chars = Array.from(s);
41
+ return chars.length <= max ? s : `${chars.slice(0, Math.max(1, max - 1)).join("")}…`;
42
+ }
43
+
44
+ function pad2(n) { return String(n).padStart(2, "0"); }
45
+ function fmtTime(at) {
46
+ const n = Number(at) || 0;
47
+ if (!n) return "";
48
+ try {
49
+ const d = new Date(n);
50
+ return `${pad2(d.getMonth() + 1)}-${pad2(d.getDate())} ${pad2(d.getHours())}:${pad2(d.getMinutes())}`;
51
+ } catch { return ""; }
52
+ }
53
+
54
+ /**
55
+ * 解析一条消息是否为命令。
56
+ * @returns {{name:string, arg:string, unknown?:boolean, raw:string}|null} null = 普通文本(照旧转给模型)
57
+ */
58
+ export function parseImCommand(text) {
59
+ const raw = String(text == null ? "" : text).trim();
60
+ if (!raw.startsWith("/")) return null;
61
+ const m = /^\/([a-zA-Z]*)(?:\s+([^\s]+))?(?:\s+([\s\S]*))?$/.exec(raw);
62
+ if (!m) return { name: "/", arg: "", unknown: true, raw };
63
+ const word = String(m[1] || "").toLowerCase();
64
+ return { name: word ? `/${word}` : "/", arg: String(m[2] || "").toLowerCase(), rest: m[3] || "", unknown: !word, raw };
65
+ }
66
+
67
+ /** 当前 caps 是否具备该命令要求(点号前缀规则,与会员表同源)。 */
68
+ export function commandAllowed(command, caps) {
69
+ const list = Array.isArray(caps) ? caps : [];
70
+ return (command.caps || []).every((c) => grantsCap(list, c));
71
+ }
72
+
73
+ function appPromo(ctx) {
74
+ const base = String((ctx && ctx.appUrl) || "").trim().replace(/\/+$/, "");
75
+ if (!base) return "";
76
+ return `${base}/promo`;
77
+ }
78
+
79
+ /** /help:列出全部命令(免费/会员标注;免费档会提示哪些需要会员)。 */
80
+ export function helpText(ctx = {}) {
81
+ const caps = Array.isArray(ctx.caps) ? ctx.caps : [];
82
+ const lines = ["📋 可用命令(命令不会发给模型,直接执行)", ""];
83
+ for (const cmd of IM_COMMANDS) {
84
+ const allowed = commandAllowed(cmd, caps);
85
+ const mark = cmd.free ? "" : allowed ? "(会员)" : "(会员·当前档不可用)";
86
+ lines.push(`${cmd.usage} — ${cmd.summary}${mark}`);
87
+ }
88
+ lines.push("", "免费档可用的命令:/help /status /stop /unbind(急停与退订永远免费)。");
89
+ if (caps.includes("sessions")) lines.push("你的档位已包含会话管理(/ls、/use)。");
90
+ return lines.join("\n");
91
+ }
92
+
93
+ /** 未知 /xxx:不转给模型,回"未知命令 + 帮助提示"。 */
94
+ export function unknownCommandText(cmd, ctx = {}) {
95
+ const name = cmd && cmd.name && cmd.name !== "/" ? cmd.name : cmd && cmd.raw ? String(cmd.raw).split(/\s+/)[0] : "/?";
96
+ return `未知命令:${name}\n\n${helpText(ctx)}`;
97
+ }
98
+
99
+ /** 会员功能被拦:与现有升级文案同口径(能做什么/去哪升级),只是更简短。 */
100
+ export function upgradeText(commandName, ctx = {}) {
101
+ const promo = appPromo(ctx);
102
+ const lines = [
103
+ `🔒 ${commandName} 是会员功能(列出/切换会话)`,
104
+ "",
105
+ "免费可用:/help /status /stop /unbind(急停、退订永远免费)",
106
+ "升级 Pro:指令不限量、可开新任务、可切换/多会话"
107
+ ];
108
+ if (promo) lines.push(`👉 ${promo}`);
109
+ return lines.join("\n");
110
+ }
111
+
112
+ /** /status:与状态文件同源的连接/会话/额度摘要。 */
113
+ export async function statusText(ctx = {}) {
114
+ const snap = typeof ctx.statusSnapshot === "function" ? await ctx.statusSnapshot() : (ctx.status || {});
115
+ const s = snap && typeof snap === "object" ? snap : {};
116
+ const channel = String(s.channelLabel || ctx.channelLabel || "IM");
117
+ const connected = s.connected === true;
118
+ const authed = s.authenticated === true;
119
+ const state = String(s.state || (connected ? "connected" : "idle"));
120
+ const stateLine = connected
121
+ ? (authed ? "✅ 已连接(认证通过)" : "✅ 已连接(等待认证)")
122
+ : `⚠️ 未连接(${state}${s.lastError ? `:${truncateTitle(s.lastError, 40)}` : ""})`;
123
+ const conv = truncateTitle(s.currentSessionTitle || s.boundSessionTitle || "", 24) || "未选择";
124
+ const convId = String(s.currentSessionId || s.boundSessionId || "");
125
+ const shortId = convId ? convId.replace(/^session-/, "").slice(0, 8) : "";
126
+ const limit = Number(s.messagesPerMonth) || 0;
127
+ const used = Number(s.usage && s.usage.messages) || 0;
128
+ const quotaLine = limit > 0
129
+ ? `本月指令:已用 ${used}/${limit}${s.tier ? `(${s.tier})` : ""}`
130
+ : `本月指令:不限${s.tier ? `(${s.tier})` : ""}`;
131
+ const lines = [
132
+ "📊 连接状态",
133
+ `· 通道:${channel}`,
134
+ `· 状态:${stateLine}`,
135
+ `· 当前会话:${conv}${shortId ? `(#${shortId})` : ""}`,
136
+ `· ${quotaLine}`
137
+ ];
138
+ if (s.remainingMessages !== null && s.remainingMessages !== undefined && limit > 0) {
139
+ lines.push(`· 剩余:${Number(s.remainingMessages) || 0} 条`);
140
+ }
141
+ return lines.join("\n");
142
+ }
143
+
144
+ /** ctx 的 currentSessionId/currentSessionTitle 允许函数或字符串(各通道实现风格不一)。 */
145
+ function resolveMaybeFn(value) {
146
+ try { return typeof value === "function" ? String(value() || "") : String(value || ""); } catch { return ""; }
147
+ }
148
+
149
+ /** 统一取最近会话列表(ctx.sessions 返回 [{sessionId,title,updatedAt,running}])。 */
150
+ export async function listSessions(ctx = {}) {
151
+ if (typeof ctx.sessions !== "function") return [];
152
+ const rows = await ctx.sessions();
153
+ if (!Array.isArray(rows)) return [];
154
+ return rows
155
+ .filter((r) => r && typeof r.sessionId === "string" && r.sessionId)
156
+ .slice(0, 10)
157
+ .map((r) => ({
158
+ sessionId: r.sessionId,
159
+ title: String(r.title || r.sessionTitle || "").trim() || r.sessionId,
160
+ updatedAt: Number(r.updatedAt) || 0,
161
+ running: r.running === true
162
+ }));
163
+ }
164
+
165
+ /** /ls:≤10 个会话,标题截断 24 + 索引 + 当前标记 + 更新时间。 */
166
+ export async function lsText(ctx = {}) {
167
+ const rows = await listSessions(ctx);
168
+ const current = resolveMaybeFn(ctx.currentSessionId) || String(ctx.activeSessionId || "");
169
+ if (!rows.length) {
170
+ return "📂 最近没有可列出的会话。\n\n先在电脑的 DeepSeek Harness 里打开/运行一个会话,再发 /ls。";
171
+ }
172
+ const lines = ["📂 最近会话(最多 10 个)", ""];
173
+ rows.forEach((r, i) => {
174
+ const isCurrent = r.sessionId === current;
175
+ const time = fmtTime(r.updatedAt);
176
+ const marks = [isCurrent ? "(当前)" : "", r.running ? "· 运行中" : "", time ? `· ${time}` : ""].filter(Boolean).join(" ");
177
+ lines.push(`${i + 1}. ${truncateTitle(r.title, 24)}${marks ? ` ${marks}` : ""}`);
178
+ });
179
+ lines.push("", "回复 /use <序号> 切换会话(例如 /use 1)。");
180
+ return { text: lines.join("\n"), rows };
181
+ }
182
+
183
+ /** /use <N>:切换当前绑定会话(写配置 sessionId/sessionTitle)。 */
184
+ export async function useText(ctx = {}, arg = "") {
185
+ const rows = await listSessions(ctx);
186
+ if (!rows.length) return "现在没有可切换的会话。先在电脑上打开一个会话,再发 /ls 看看。";
187
+ const raw = String(arg || "").trim();
188
+ if (!raw) return "用法:/use <序号>(先发 /ls 查看会话列表,例如 /use 1)";
189
+ const n = Number(raw);
190
+ if (!Number.isInteger(n) || n < 1 || n > rows.length) {
191
+ return `序号超出范围:当前列表是 1-${rows.length}。先发 /ls 查看列表,再用 /use <序号> 切换。`;
192
+ }
193
+ const pick = rows[n - 1];
194
+ if (typeof ctx.switchSession !== "function") return "当前通道还不支持切换会话(订阅器未就绪),请在电脑上切换。";
195
+ const r = await ctx.switchSession({ sessionId: pick.sessionId, title: pick.title });
196
+ if (!r || r.ok !== true) {
197
+ return `切换失败:${truncateTitle((r && (r.message || r.reason)) || "未知错误", 60)}。可以到电脑上切换,或稍后再试。`;
198
+ }
199
+ return `✅ 已切换到 #${n} ${truncateTitle(pick.title, 24) || pick.sessionId}`;
200
+ }
201
+
202
+ /** /stop:急停当前任务(免费、立即生效;回执明确)。 */
203
+ export async function stopText(ctx = {}) {
204
+ const current = resolveMaybeFn(ctx.currentSessionId) || String(ctx.activeSessionId || "");
205
+ if (!current) return "当前没有正在运行的会话,无需急停。";
206
+ if (typeof ctx.cancelSession !== "function") return "急停失败:后台还没连上事件通道(订阅器未就绪)。请在电脑上停止任务。";
207
+ const title = truncateTitle(resolveMaybeFn(ctx.currentSessionTitle) || ctx.activeSessionTitle || current, 24);
208
+ let r;
209
+ try { r = await ctx.cancelSession({ sessionId: current }); } catch (e) {
210
+ r = { ok: false, message: e && e.message ? e.message : String(e) };
211
+ }
212
+ if (r && r.ok === true) return `⏹ 已急停:${title}(已发送中止,正在停止当前任务)`;
213
+ return `⏹ 急停请求已发出,但没收到确认:${truncateTitle((r && (r.message || r.reason)) || "未知错误", 60)}。请到电脑上确认任务是否已停。`;
214
+ }
215
+
216
+ /** /unbind:解绑本会话推送(免费;合规要求任何人可退订)。 */
217
+ export async function unbindText(ctx = {}) {
218
+ if (typeof ctx.unbind !== "function") return "解绑失败:当前通道暂不支持解绑,请在电脑的「远程访问」里关闭该通道。";
219
+ let r;
220
+ try { r = await ctx.unbind(); } catch (e) { r = { ok: false, message: e && e.message ? e.message : String(e) }; }
221
+ if (r && r.ok === true) return "✅ 已解绑:这台电脑不再向本会话推送通知。想重新接收,发任意消息即可重新绑定。";
222
+ return `解绑失败:${truncateTitle((r && (r.message || r.reason)) || "未知错误", 60)}`;
223
+ }
224
+
225
+ /**
226
+ * 执行一条命令(**命中即返回 handled:true,调用方直接回复 text 并 return,绝不进模型**)。
227
+ *
228
+ * @param {{text:string, ctx:object}} args
229
+ * ctx 契约(各通道按自己能力提供,缺的降级):
230
+ * · caps[]、tier、appUrl、channelLabel
231
+ * · sessions(): Promise<[{sessionId,title,updatedAt,running}]>
232
+ * · currentSessionId(): string、currentSessionTitle?: string、activeSessionId?
233
+ * · cancelSession({sessionId})、switchSession({sessionId,title})、unbind()
234
+ * · statusSnapshot(): Promise<{connected,authenticated,state,lastError,tier,usage,messagesPerMonth,remainingMessages,currentSessionTitle,currentSessionId}>
235
+ * @returns {Promise<{handled:boolean, ok?:boolean, gated?:boolean, command?:string, text?:string, rows?:Array}>}
236
+ */
237
+ export async function executeImCommand({ text, ctx = {} } = {}) {
238
+ const cmd = parseImCommand(text);
239
+ if (!cmd) return { handled: false };
240
+ const caps = Array.isArray(ctx.caps) ? ctx.caps : [];
241
+ const known = IM_COMMANDS.find((c) => c.name === cmd.name);
242
+ if (!known) return { handled: true, ok: false, command: cmd.name, text: unknownCommandText(cmd, ctx) };
243
+ if (!commandAllowed(known, caps)) {
244
+ return { handled: true, ok: false, gated: true, command: known.name, text: upgradeText(known.name, ctx) };
245
+ }
246
+ try {
247
+ switch (known.name) {
248
+ case "/help":
249
+ return { handled: true, ok: true, command: known.name, text: helpText(ctx) };
250
+ case "/status":
251
+ return { handled: true, ok: true, command: known.name, text: await statusText(ctx) };
252
+ case "/stop":
253
+ return { handled: true, ok: true, command: known.name, text: await stopText(ctx) };
254
+ case "/unbind":
255
+ return { handled: true, ok: true, command: known.name, text: await unbindText(ctx) };
256
+ case "/ls": {
257
+ const r = await lsText(ctx);
258
+ return { handled: true, ok: true, command: known.name, text: typeof r === "string" ? r : r.text, rows: typeof r === "string" ? [] : r.rows };
259
+ }
260
+ case "/use":
261
+ return { handled: true, ok: true, command: known.name, text: await useText(ctx, cmd.arg) };
262
+ default:
263
+ return { handled: true, ok: false, command: known.name, text: unknownCommandText(cmd, ctx) };
264
+ }
265
+ } catch (e) {
266
+ return {
267
+ handled: true,
268
+ ok: false,
269
+ command: known.name,
270
+ text: `命令执行失败:${truncateTitle(e && e.message ? e.message : e, 60)}。可以到电脑上看一眼,或稍后再试。`
271
+ };
272
+ }
273
+ }
274
+
275
+ /** 能力表(导出方便各通道显示"会员功能"标记;单一真相源)。 */
276
+ export const IM_COMMAND_CAPABILITY_TABLE = WECHAT_CAPABILITY_TABLE;
277
+
278
+ /**
279
+ * 切换会话时写 `im-bots.json` 对应通道的 `sessionId/sessionTitle`(0600 原子写,保留其它段)。
280
+ * 各通道 controller 会热更新并在下一次入站用新会话。
281
+ */
282
+ export function writeImBotsSession(relayDir, channel, { sessionId, sessionTitle } = {}) {
283
+ const dir = String(relayDir || "");
284
+ const ch = String(channel || "");
285
+ if (!dir || !ch) return { ok: false, reason: "no_target" };
286
+ const sid = String(sessionId || "").trim();
287
+ if (!sid) return { ok: false, reason: "no_session_id" };
288
+ try {
289
+ const file = path.join(dir, IM_BOTS_FILE);
290
+ const prev = readJsonFile(file);
291
+ const base = prev && typeof prev === "object" && !Array.isArray(prev) ? prev : {};
292
+ const cur = base[ch] && typeof base[ch] === "object" ? base[ch] : {};
293
+ atomicWriteJson(file, {
294
+ ...base,
295
+ version: 1,
296
+ [ch]: { ...cur, sessionId: sid, sessionTitle: truncateTitle(sessionTitle || "", 60) }
297
+ }, { onWarn: () => { /* 静默 */ } });
298
+ return { ok: true };
299
+ } catch (e) {
300
+ return { ok: false, reason: e && e.message ? e.message : String(e) };
301
+ }
302
+ }
@@ -0,0 +1,138 @@
1
+ import test from "node:test";
2
+ import assert from "node:assert/strict";
3
+ import fs from "node:fs";
4
+ import os from "node:os";
5
+ import path from "node:path";
6
+
7
+ import {
8
+ startDingtalkAuthCommandWatcher,
9
+ stopDingtalkAuthCommandWatcher,
10
+ handleDingtalkAuthCommand,
11
+ beginDingtalkAuth,
12
+ resumeDingtalkAuth,
13
+ cancelDingtalkAuth,
14
+ authStatus,
15
+ readDingtalkAuthSession,
16
+ DINGTALK_AUTH_FILE,
17
+ DINGTALK_AUTH_CMD_FILE,
18
+ __resetDingtalkAuthForTest,
19
+ __resetDingtalkAuthCmdForTest
20
+ } from "../dingtalk-auth.mjs";
21
+
22
+ /**
23
+ * 工程化端到端:**扫码授权整条生命周期**(全注入 fetch,零真实网络)。
24
+ *
25
+ * 这组用例存在的理由:真机上发生过「钉钉侧显示连接成功、我们没接住」——
26
+ * 根因是授权会话只在内存里,进程一重启就丢。这里把 5 个真实场景钉死:
27
+ * ① 面板写命令文件 → 桥监听 → begin 落盘(0600)→ 状态 waiting
28
+ * ② 模拟桥重启(停监听、保留文件)→ resume 续轮询 → 拿到凭据写 im-bots.json → 清理 auth
29
+ * ③ 同一 at 的重复命令不重复执行
30
+ * ④ 钉钉明确拒绝 → 中文人话 + 清理
31
+ * ⑤ 用户取消 → 清理
32
+ * 任何一环退化(例如把会话放回内存、忘记重启后续轮询、泄露 deviceCode/secret)都会红。
33
+ */
34
+
35
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
36
+ const fileMode = (f) => fs.statSync(f).mode & 0o777;
37
+ const tmpDir = () => {
38
+ const d = fs.mkdtempSync(path.join(os.tmpdir(), "dt-auth-e2e-"));
39
+ fs.writeFileSync(path.join(d, "im-bots.json"), "{}\n");
40
+ fs.chmodSync(path.join(d, "im-bots.json"), 0o600);
41
+ return d;
42
+ };
43
+
44
+ function makeFetch(state) {
45
+ return async (url) => {
46
+ const u = String(url);
47
+ const json = (o) => ({ ok: true, status: 200, json: async () => o });
48
+ if (u.endsWith("/init")) return json({ errcode: 0, nonce: "nr_e2e_" + state.seq++, expires_in: 300 });
49
+ if (u.endsWith("/begin")) {
50
+ return json({
51
+ errcode: 0,
52
+ device_code: "DEV_e2e_" + state.seq++,
53
+ interval: 1,
54
+ expires_in: 7200,
55
+ verification_uri_complete: "https://open-dev.dingtalk.com/openapp/registration/openClaw?user_code=E2E-CODE&source=DING_DWS_CLAW"
56
+ });
57
+ }
58
+ if (u.endsWith("/poll")) {
59
+ state.polls += 1;
60
+ if (state.mode === "fail") return json({ errcode: 0, status: "FAIL", fail_reason: "user_cancelled" });
61
+ if (state.mode === "waiting") return json({ errcode: 0, status: "WAITING" });
62
+ if (state.polls < 2) return json({ errcode: 0, status: "WAITING" });
63
+ return json({ errcode: 0, status: "SUCCESS", client_id: "cli_e2e_123456", client_secret: "SECRET_E2E_VALUE" });
64
+ }
65
+ throw new Error("unexpected url " + u);
66
+ };
67
+ }
68
+
69
+ test("钉钉扫码授权端到端:命令→落盘→重启续轮询→成功写配置→失败/取消", async () => {
70
+ const state = { mode: "waiting", polls: 0, seq: 1 };
71
+ const fetchImpl = makeFetch(state);
72
+
73
+ // ① 面板写命令文件 → 桥监听 → begin 落盘
74
+ let relayDir = tmpDir();
75
+ fs.writeFileSync(path.join(relayDir, DINGTALK_AUTH_CMD_FILE), JSON.stringify({ action: "begin", at: Date.now() }));
76
+ fs.chmodSync(path.join(relayDir, DINGTALK_AUTH_CMD_FILE), 0o600);
77
+ startDingtalkAuthCommandWatcher({ relayDir, fetchImpl, intervalMs: 50, pollMs: 50 });
78
+ await sleep(500);
79
+ assert.equal(fs.existsSync(path.join(relayDir, DINGTALK_AUTH_CMD_FILE)), false, "命令文件必须被消费删除");
80
+ const session = readDingtalkAuthSession(relayDir);
81
+ assert.ok(session && session.deviceCode && session.url, "auth 文件必须落盘 deviceCode/url");
82
+ assert.equal(fileMode(path.join(relayDir, DINGTALK_AUTH_FILE)), 0o600, "auth 文件必须 0600");
83
+ const st = authStatus({ relayDir });
84
+ assert.equal(st.status, "waiting");
85
+ const stFile = JSON.parse(fs.readFileSync(path.join(relayDir, "im-bot-status.json"), "utf8"));
86
+ assert.equal(stFile.dingtalk.auth.state, "waiting", "状态文件必须透出 dingtalk.auth.state");
87
+ assert.ok(stFile.dingtalk.auth.remainingSec > 0);
88
+ assert.ok(!JSON.stringify(stFile).includes("DEV_e2e_"), "状态文件不得含 deviceCode");
89
+
90
+ // ② 模拟桥重启 → resume 续轮询 → 成功写配置
91
+ stopDingtalkAuthCommandWatcher(relayDir);
92
+ assert.ok(fs.existsSync(path.join(relayDir, DINGTALK_AUTH_FILE)), "桥退出后 auth 文件必须保留(否则重启丢会话)");
93
+ state.mode = "success";
94
+ state.polls = 0;
95
+ await resumeDingtalkAuth({ relayDir, fetchImpl, pollMs: 50 });
96
+ await sleep(400);
97
+ const bots = JSON.parse(fs.readFileSync(path.join(relayDir, "im-bots.json"), "utf8"));
98
+ assert.equal(bots.dingtalk.enabled, true);
99
+ assert.equal(bots.dingtalk.credentialSource, "scan");
100
+ assert.equal(bots.dingtalk.robotCode, bots.dingtalk.clientId, "robotCode 缺省应等于 clientId");
101
+ assert.equal(fileMode(path.join(relayDir, "im-bots.json")), 0o600, "im-bots.json 必须 0600");
102
+ assert.equal(fs.existsSync(path.join(relayDir, DINGTALK_AUTH_FILE)), false, "成功后必须删除 auth 文件");
103
+ const st2 = authStatus({ relayDir });
104
+ assert.equal(st2.status, "success");
105
+ assert.ok(!JSON.stringify(st2).includes("SECRET_E2E_VALUE"), "摘要不得泄露 secret");
106
+
107
+ // ③ 同一 at 重复命令不重复执行
108
+ const atSame = Date.now();
109
+ fs.writeFileSync(path.join(relayDir, DINGTALK_AUTH_CMD_FILE), JSON.stringify({ action: "begin", at: atSame }));
110
+ await handleDingtalkAuthCommand({ relayDir, fetchImpl });
111
+ fs.writeFileSync(path.join(relayDir, DINGTALK_AUTH_CMD_FILE), JSON.stringify({ action: "begin", at: atSame }));
112
+ const dup = await handleDingtalkAuthCommand({ relayDir, fetchImpl });
113
+ assert.equal(dup.skipped, true, "同一 at 的命令必须跳过");
114
+
115
+ // ④ 钉钉明确拒绝 → 中文人话 + 清理
116
+ __resetDingtalkAuthForTest();
117
+ __resetDingtalkAuthCmdForTest();
118
+ relayDir = tmpDir();
119
+ state.mode = "fail";
120
+ state.polls = 0;
121
+ await beginDingtalkAuth({ relayDir, fetchImpl, pollMs: 50 });
122
+ await sleep(300);
123
+ const failed = authStatus({ relayDir });
124
+ assert.equal(failed.status, "failed");
125
+ assert.match(String(failed.message || ""), /[\u4e00-\u9fa5]/, "失败原因必须是中文人话");
126
+ assert.equal(fs.existsSync(path.join(relayDir, DINGTALK_AUTH_FILE)), false, "失败必须清理 auth 文件");
127
+
128
+ // ⑤ 取消
129
+ __resetDingtalkAuthForTest();
130
+ relayDir = tmpDir();
131
+ state.mode = "waiting";
132
+ state.polls = 0;
133
+ await beginDingtalkAuth({ relayDir, fetchImpl, pollMs: 50 });
134
+ assert.ok(fs.existsSync(path.join(relayDir, DINGTALK_AUTH_FILE)));
135
+ cancelDingtalkAuth({ relayDir });
136
+ await sleep(100);
137
+ assert.equal(fs.existsSync(path.join(relayDir, DINGTALK_AUTH_FILE)), false, "取消必须清理 auth 文件");
138
+ });