cortico-world-wechat-claw 0.1.0 → 0.1.2
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/CHANGELOG.md +33 -0
- package/dist/webui.js +28 -2
- package/package.json +2 -1
- package/src/config.ts +5 -2
- package/src/driver.ts +63 -10
- package/src/webui/client.ts +34 -5
- package/src/world.ts +162 -11
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,38 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.1.2
|
|
4
|
+
|
|
5
|
+
安全修复:收件人钉死在绑定本人。
|
|
6
|
+
|
|
7
|
+
- **回复目标不再随入站消息变化**。早先用「最近一条消息的发送者」当收件人,任何人只要能让一条
|
|
8
|
+
消息进入收件流(群成员、服务通知、陌生人),文字和文件就会被发到对方。现在一律发往绑定记录里的
|
|
9
|
+
`userId`,拿不到就明确报错而不是乱发。
|
|
10
|
+
- **只接受绑定本人发来的消息**。发送者不是本人就丢弃并记一条 warn,不再进入上下文、
|
|
11
|
+
也不保存它的 `context_token`。
|
|
12
|
+
- 绑定记录缺少 `ilink_user_id` 时,把扫码后第一条消息的发送者认作本人并写回 `auth.json`,
|
|
13
|
+
认领只发生一次,之后严格比对。
|
|
14
|
+
- **配置页加安全提示**:说明启用后模型能把本机任意文件发到微信(含它自己的登录令牌),
|
|
15
|
+
且发送前不会确认。
|
|
16
|
+
- **主动声明 `unsafe` 标签**:这个能力确实符合该标签的定义,由作者声明而不是等维护者来加。
|
|
17
|
+
|
|
18
|
+
注意:这次没有收紧「能发哪些文件」。`wechat_send_image` / `wechat_send_file` 仍接受任意绝对路径,
|
|
19
|
+
所以 `unsafe`(能把本机任意文件发到微信)依然成立。要撤这个标签,得先收紧到白名单目录,
|
|
20
|
+
再向索引仓提 `[tags]` issue。
|
|
21
|
+
|
|
22
|
+
## 0.1.1
|
|
23
|
+
|
|
24
|
+
修三个线上问题。
|
|
25
|
+
|
|
26
|
+
- **收不到消息(严重)**:服务端返回空 `get_updates_buf` 时被当成「没有新游标」而忽略,
|
|
27
|
+
于是永远带着旧游标去问,从此收不到任何新消息,但发送仍然正常。现在区分「字段缺失」(保留旧游标)
|
|
28
|
+
与「字段为空串」(真的重置)。
|
|
29
|
+
- **重连可能并存两个驱动**:`#startDriver` 没有等待旧驱动退出,连续点几次重连会短暂出现两个
|
|
30
|
+
驱动各带游标抢消息。现在先 await 旧驱动停止。
|
|
31
|
+
- **面板时间显示成 UTC**:最近消息时间直接截了 ISO 字符串,北京时间 05:11 会显示成 21:11。
|
|
32
|
+
现在按部署时区格式化。
|
|
33
|
+
- 连续 3 轮拿不到服务端响应时主动重建连接,并在界面写明「长轮询长时间没有响应」。
|
|
34
|
+
- 新增**解绑**按钮:清掉本机保存的凭据与游标,回到未绑定状态。微信里的对话不受影响。
|
|
35
|
+
|
|
3
36
|
## 0.1.0
|
|
4
37
|
|
|
5
38
|
第一个版本。
|
package/dist/webui.js
CHANGED
|
@@ -169,6 +169,9 @@ var TEXT2 = {
|
|
|
169
169
|
refresh: "\u91CD\u65B0\u751F\u6210",
|
|
170
170
|
cancel: "\u53D6\u6D88\u626B\u7801",
|
|
171
171
|
reconnect: "\u91CD\u65B0\u8FDE\u63A5",
|
|
172
|
+
unbind: "\u89E3\u7ED1",
|
|
173
|
+
unbindConfirm: "\u89E3\u7ED1\u4F1A\u6E05\u6389\u672C\u673A\u4FDD\u5B58\u7684\u5FAE\u4FE1\u51ED\u636E\uFF0C\u4E4B\u540E\u8981\u91CD\u65B0\u626B\u7801\u624D\u80FD\u6536\u6D88\u606F\u3002\u5FAE\u4FE1\u91CC\u7684\u90A3\u4E2A\u5BF9\u8BDD\u4E0D\u4F1A\u6D88\u5931\u3002\u786E\u5B9A\u89E3\u7ED1\uFF1F",
|
|
174
|
+
unbindDone: "\u5DF2\u89E3\u7ED1\uFF0C\u672C\u673A\u4E0D\u518D\u6536\u53D1\u5FAE\u4FE1\u6D88\u606F\u3002",
|
|
172
175
|
verifyLabel: "\u624B\u673A\u5FAE\u4FE1\u663E\u793A\u7684\u6570\u5B57",
|
|
173
176
|
verifyPlaceholder: "\u4F8B\u5982 123456",
|
|
174
177
|
verifySubmit: "\u63D0\u4EA4\u9A8C\u8BC1\u7801",
|
|
@@ -192,6 +195,9 @@ var TEXT2 = {
|
|
|
192
195
|
refresh: "New QR code",
|
|
193
196
|
cancel: "Cancel",
|
|
194
197
|
reconnect: "Reconnect",
|
|
198
|
+
unbind: "Unbind",
|
|
199
|
+
unbindConfirm: "Unbinding clears the WeChat credentials saved on this machine; you will need to scan again to receive messages. The chat in WeChat itself stays. Continue?",
|
|
200
|
+
unbindDone: "Unbound. This machine no longer sends or receives WeChat messages.",
|
|
195
201
|
verifyLabel: "The number shown in WeChat",
|
|
196
202
|
verifyPlaceholder: "for example 123456",
|
|
197
203
|
verifySubmit: "Submit",
|
|
@@ -241,9 +247,11 @@ async function mountBinding(ctx) {
|
|
|
241
247
|
const generateButton = ui.button(t.generate, { variant: "primary" });
|
|
242
248
|
const cancelButton = ui.button(t.cancel, { size: "sm" });
|
|
243
249
|
const reconnectButton = ui.button(t.reconnect, { size: "sm" });
|
|
250
|
+
const unbindButton = ui.button(t.unbind, { variant: "danger", size: "sm" });
|
|
244
251
|
cancelButton.style.display = "none";
|
|
245
252
|
reconnectButton.style.display = "none";
|
|
246
|
-
|
|
253
|
+
unbindButton.style.display = "none";
|
|
254
|
+
actions.append(generateButton, cancelButton, reconnectButton, unbindButton);
|
|
247
255
|
sheet.body.append(stateLine, whoLine, tokenLine, messageLine, qrBox, linkRow, verifyRow, actions);
|
|
248
256
|
let currentState = {
|
|
249
257
|
bound: false,
|
|
@@ -252,6 +260,7 @@ async function mountBinding(ctx) {
|
|
|
252
260
|
accountId: "",
|
|
253
261
|
userId: "",
|
|
254
262
|
lastMessageAt: "",
|
|
263
|
+
lastMessageLocal: "",
|
|
255
264
|
lastError: "",
|
|
256
265
|
contextTokens: 0,
|
|
257
266
|
qrDataUrl: "",
|
|
@@ -269,7 +278,8 @@ async function mountBinding(ctx) {
|
|
|
269
278
|
whoLine.style.display = next.bound ? "" : "none";
|
|
270
279
|
tokenLine.textContent = next.bound ? t.tokenCount(next.contextTokens) : "";
|
|
271
280
|
tokenLine.style.display = next.bound ? "" : "none";
|
|
272
|
-
|
|
281
|
+
const stamp = next.lastMessageLocal || (next.lastMessageAt ? next.lastMessageAt.replace("T", " ").slice(0, 19) : "");
|
|
282
|
+
messageLine.textContent = stamp ? t.lastMessage(stamp) : next.bound ? t.noMessage : "";
|
|
273
283
|
messageLine.style.display = next.bound ? "" : "none";
|
|
274
284
|
if (next.loginError) {
|
|
275
285
|
stateLine.textContent = next.loginError;
|
|
@@ -289,6 +299,7 @@ async function mountBinding(ctx) {
|
|
|
289
299
|
generateButton.style.display = next.bound ? "none" : "";
|
|
290
300
|
cancelButton.style.display = binding && !next.bound ? "" : "none";
|
|
291
301
|
reconnectButton.style.display = next.bound ? "" : "none";
|
|
302
|
+
unbindButton.style.display = next.bound ? "" : "none";
|
|
292
303
|
};
|
|
293
304
|
const readState = async () => {
|
|
294
305
|
try {
|
|
@@ -328,6 +339,21 @@ async function mountBinding(ctx) {
|
|
|
328
339
|
}
|
|
329
340
|
})();
|
|
330
341
|
});
|
|
342
|
+
unbindButton.addEventListener("click", () => {
|
|
343
|
+
void (async () => {
|
|
344
|
+
const ok = await ui.confirm({ title: t.unbind, body: t.unbindConfirm, danger: true });
|
|
345
|
+
if (!ok) return;
|
|
346
|
+
unbindButton.disabled = true;
|
|
347
|
+
try {
|
|
348
|
+
paint(await ctx.invoke("unbind"));
|
|
349
|
+
ui.toast(t.unbindDone, "ok");
|
|
350
|
+
} catch (err) {
|
|
351
|
+
ui.toast(err instanceof Error ? err.message : String(err), "bad");
|
|
352
|
+
} finally {
|
|
353
|
+
unbindButton.disabled = false;
|
|
354
|
+
}
|
|
355
|
+
})();
|
|
356
|
+
});
|
|
331
357
|
const submitVerify = () => {
|
|
332
358
|
const code = verifyInput.value.trim();
|
|
333
359
|
if (!code) return;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "cortico-world-wechat-claw",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.2",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "在微信里和桌宠一对一聊天:文字、图片、文件双向收发,语音用微信的转写文本,视频可按需抽帧给模型看。",
|
|
6
6
|
"author": {
|
|
@@ -40,6 +40,7 @@
|
|
|
40
40
|
"webUiClient": "dist/webui.js",
|
|
41
41
|
"tags": [
|
|
42
42
|
"im",
|
|
43
|
+
"unsafe",
|
|
43
44
|
"unofficial-api"
|
|
44
45
|
],
|
|
45
46
|
"locales": {
|
package/src/config.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
|
|
1
|
+
import type { ConfigGroup } from 'cortico/core/types.ts';
|
|
2
2
|
|
|
3
3
|
/**
|
|
4
4
|
* `config.json` 的 `worlds.wechat-claw` 段。
|
|
@@ -59,7 +59,10 @@ export const WECHAT_CLAW_CONFIG_GROUP: ConfigGroup = {
|
|
|
59
59
|
schema: {
|
|
60
60
|
type: 'object',
|
|
61
61
|
title: '微信 ClawBot',
|
|
62
|
-
description:
|
|
62
|
+
description:
|
|
63
|
+
'微信一对一私聊的接入方式与收件范围。绑定状态在「微信绑定」面板。\n'
|
|
64
|
+
+ '⚠ 安全提示:启用后模型能把本机任意文件发到微信,包括它自己的登录令牌,'
|
|
65
|
+
+ '发送前不会向你确认。只在你信任这个微信账号、并清楚可能被发出去什么时启用。',
|
|
63
66
|
properties: {
|
|
64
67
|
'worlds.wechat-claw.networkMode': {
|
|
65
68
|
type: 'string',
|
package/src/driver.ts
CHANGED
|
@@ -6,6 +6,17 @@
|
|
|
6
6
|
* 上层只看到「连上了 / 断了 / 过期了 / 收到一条」。
|
|
7
7
|
*
|
|
8
8
|
* 令牌失效(-14)后暂停一小时再试,这是官方通道的约定:短时间内重复用旧令牌请求会被拒得更久。
|
|
9
|
+
*
|
|
10
|
+
* ## 两条容易出事的路径
|
|
11
|
+
*
|
|
12
|
+
* **长轮询超时是正常路径。** 服务端 hold 住请求,到点没消息就断开;`getUpdates` 把超时
|
|
13
|
+
* 折算成空批次返回。这不能算「连接成功」——否则界面一直显示已连接,而实际可能早就收不到了。
|
|
14
|
+
* 所以 `connected` 只在**真正拿到响应**(哪怕空)时置真,并且每轮都刷新 `lastPollAt`。
|
|
15
|
+
*
|
|
16
|
+
* **游标必须能被清空。** 服务端偶尔会返回空 `get_updates_buf`(重置信号)。早先的实现用
|
|
17
|
+
* `if (buf)` 判断,空串会被忽略,于是永远带着旧游标去问,服务端认为「你还在那个位置之前」,
|
|
18
|
+
* 从此再也推不出新消息——现象就是「能发不能收」。这里区分「字段缺失」(保留旧游标)与
|
|
19
|
+
* 「字段是空串」(真的重置)。
|
|
9
20
|
*/
|
|
10
21
|
import type { ILinkApi } from './protocol/api.ts';
|
|
11
22
|
import { ILinkError, errorText } from './protocol/api.ts';
|
|
@@ -17,6 +28,8 @@ import type { WeixinMessage } from './protocol/types.ts';
|
|
|
17
28
|
export const STALE_TOKEN_ERRCODE = -14;
|
|
18
29
|
/** 令牌失效后的暂停时长。 */
|
|
19
30
|
export const STALE_TOKEN_PAUSE_MS = 60 * 60 * 1000;
|
|
31
|
+
/** 连续这么多轮拿不到任何响应,就判定链路已死并强制重建。 */
|
|
32
|
+
export const DEAD_AFTER_SILENT_ROUNDS = 3;
|
|
20
33
|
|
|
21
34
|
export interface DriverStatus {
|
|
22
35
|
connected: boolean;
|
|
@@ -25,6 +38,8 @@ export interface DriverStatus {
|
|
|
25
38
|
error: string;
|
|
26
39
|
/** 令牌失效后的冷却截止时刻(毫秒)。 */
|
|
27
40
|
pausedUntilMs?: number;
|
|
41
|
+
/** 最近一次真正拿到响应(含空批次)的时刻,毫秒。 */
|
|
42
|
+
lastPollAtMs?: number;
|
|
28
43
|
}
|
|
29
44
|
|
|
30
45
|
export interface DriverOptions {
|
|
@@ -36,6 +51,13 @@ export interface DriverOptions {
|
|
|
36
51
|
pollTimeoutMs?: number;
|
|
37
52
|
reconnectBaseMs?: number;
|
|
38
53
|
reconnectMaxMs?: number;
|
|
54
|
+
/**
|
|
55
|
+
* 连续多少轮「既没消息也没响应」就重建连接。
|
|
56
|
+
* 0 表示不检查;默认 3 轮,约两分钟没有任何服务端响应就认为链路已死。
|
|
57
|
+
*/
|
|
58
|
+
deadAfterSilentRounds?: number;
|
|
59
|
+
/** 要求上层重建客户端(重连无望时的最后手段)。 */
|
|
60
|
+
onStalled?: () => void;
|
|
39
61
|
}
|
|
40
62
|
|
|
41
63
|
const sleep = (ms: number): Promise<void> => new Promise((resolve) => setTimeout(resolve, ms));
|
|
@@ -46,8 +68,10 @@ export class ILinkDriver {
|
|
|
46
68
|
readonly #log: Logger;
|
|
47
69
|
readonly #onMessage: DriverOptions['onMessage'];
|
|
48
70
|
readonly #onStatus: DriverOptions['onStatus'];
|
|
71
|
+
readonly #onStalled?: () => void;
|
|
49
72
|
readonly #reconnectBaseMs: number;
|
|
50
73
|
readonly #reconnectMaxMs: number;
|
|
74
|
+
readonly #deadAfterSilentRounds: number;
|
|
51
75
|
|
|
52
76
|
#pollTimeoutMs: number;
|
|
53
77
|
#loop: Promise<void> | null = null;
|
|
@@ -57,6 +81,9 @@ export class ILinkDriver {
|
|
|
57
81
|
|
|
58
82
|
connected = false;
|
|
59
83
|
running = false;
|
|
84
|
+
lastPollAtMs = 0;
|
|
85
|
+
/** 连续多少轮拿不到服务端响应。 */
|
|
86
|
+
silentRounds = 0;
|
|
60
87
|
|
|
61
88
|
constructor(opts: DriverOptions) {
|
|
62
89
|
this.#api = opts.api;
|
|
@@ -64,9 +91,11 @@ export class ILinkDriver {
|
|
|
64
91
|
this.#log = opts.log;
|
|
65
92
|
this.#onMessage = opts.onMessage;
|
|
66
93
|
this.#onStatus = opts.onStatus;
|
|
94
|
+
this.#onStalled = opts.onStalled;
|
|
67
95
|
this.#pollTimeoutMs = opts.pollTimeoutMs ?? 35_000;
|
|
68
96
|
this.#reconnectBaseMs = opts.reconnectBaseMs ?? 1_000;
|
|
69
97
|
this.#reconnectMaxMs = opts.reconnectMaxMs ?? 30_000;
|
|
98
|
+
this.#deadAfterSilentRounds = opts.deadAfterSilentRounds ?? DEAD_AFTER_SILENT_ROUNDS;
|
|
70
99
|
}
|
|
71
100
|
|
|
72
101
|
start(): void {
|
|
@@ -95,6 +124,7 @@ export class ILinkDriver {
|
|
|
95
124
|
let syncBuf = '';
|
|
96
125
|
try {
|
|
97
126
|
syncBuf = await this.#store.loadSyncBuf();
|
|
127
|
+
if (syncBuf) this.#log.info(`从已保存的游标继续(${syncBuf.length} 字节)`);
|
|
98
128
|
} catch (err) {
|
|
99
129
|
this.#log.warn('读不到同步游标,从空游标开始', { error: errorText(err) });
|
|
100
130
|
}
|
|
@@ -133,26 +163,39 @@ export class ILinkDriver {
|
|
|
133
163
|
);
|
|
134
164
|
}
|
|
135
165
|
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
166
|
+
// 游标:区分「字段缺失」与「字段为空串」。后者是服务端要求重置,必须照做,
|
|
167
|
+
// 否则会一直带着旧游标问,永远拿不到新消息。
|
|
168
|
+
const buf = response?.get_updates_buf;
|
|
169
|
+
if (typeof buf === 'string') {
|
|
170
|
+
if (buf !== syncBuf) {
|
|
171
|
+
syncBuf = buf;
|
|
172
|
+
try {
|
|
173
|
+
await this.#store.saveSyncBuf(syncBuf);
|
|
174
|
+
} catch (err) {
|
|
175
|
+
this.#log.warn('同步游标没存下来', { error: errorText(err) });
|
|
176
|
+
}
|
|
142
177
|
}
|
|
143
178
|
}
|
|
179
|
+
|
|
144
180
|
const suggested = Number(response?.longpolling_timeout_ms);
|
|
145
181
|
if (Number.isFinite(suggested) && suggested > 0) {
|
|
146
182
|
this.#pollTimeoutMs = Math.min(Math.max(suggested, 5_000), 60_000);
|
|
147
183
|
}
|
|
148
184
|
|
|
185
|
+
// 真正拿到了响应(哪怕没有消息):链路是活的。
|
|
149
186
|
backoff = this.#reconnectBaseMs;
|
|
187
|
+
this.silentRounds = 0;
|
|
188
|
+
this.lastPollAtMs = Date.now();
|
|
150
189
|
if (!this.connected) {
|
|
151
190
|
this.connected = true;
|
|
152
|
-
this.#emit({ connected: true, expired: false, error: '' });
|
|
191
|
+
this.#emit({ connected: true, expired: false, error: '', lastPollAtMs: this.lastPollAtMs });
|
|
153
192
|
}
|
|
154
193
|
|
|
155
|
-
|
|
194
|
+
const messages = Array.isArray(response?.msgs) ? response.msgs : [];
|
|
195
|
+
if (messages.length) {
|
|
196
|
+
this.#log.info(`收到 ${messages.length} 条微信消息`);
|
|
197
|
+
}
|
|
198
|
+
for (const message of messages) {
|
|
156
199
|
if (this.#stopped) break;
|
|
157
200
|
try {
|
|
158
201
|
await this.#onMessage(message);
|
|
@@ -168,8 +211,18 @@ export class ILinkDriver {
|
|
|
168
211
|
return;
|
|
169
212
|
}
|
|
170
213
|
this.connected = false;
|
|
171
|
-
this
|
|
172
|
-
this.#
|
|
214
|
+
this.silentRounds += 1;
|
|
215
|
+
this.#emit({ connected: false, expired: false, error: errorText(err), lastPollAtMs: this.lastPollAtMs });
|
|
216
|
+
this.#log.warn('轮询失败,准备重连', { error: errorText(err), backoffMs: backoff, silentRounds: this.silentRounds });
|
|
217
|
+
|
|
218
|
+
// 连续多轮连不上:光靠退避重试没用了,让上层重建客户端(新的 dispatcher / 新连接)。
|
|
219
|
+
if (this.#deadAfterSilentRounds > 0 && this.silentRounds >= this.#deadAfterSilentRounds) {
|
|
220
|
+
this.#log.warn(`连续 ${this.silentRounds} 轮没有响应,请求重建连接`);
|
|
221
|
+
this.silentRounds = 0;
|
|
222
|
+
this.#onStalled?.();
|
|
223
|
+
return;
|
|
224
|
+
}
|
|
225
|
+
|
|
173
226
|
await this.#sleep(backoff);
|
|
174
227
|
backoff = Math.min(backoff * 2, this.#reconnectMaxMs);
|
|
175
228
|
}
|
package/src/webui/client.ts
CHANGED
|
@@ -19,6 +19,8 @@ interface BindingState {
|
|
|
19
19
|
accountId: string;
|
|
20
20
|
userId: string;
|
|
21
21
|
lastMessageAt: string;
|
|
22
|
+
/** 已按部署时区格式化好的本地时间;优先用它,别直接截 lastMessageAt。 */
|
|
23
|
+
lastMessageLocal: string;
|
|
22
24
|
lastError: string;
|
|
23
25
|
contextTokens: number;
|
|
24
26
|
qrDataUrl: string;
|
|
@@ -36,6 +38,9 @@ const TEXT = {
|
|
|
36
38
|
refresh: '重新生成',
|
|
37
39
|
cancel: '取消扫码',
|
|
38
40
|
reconnect: '重新连接',
|
|
41
|
+
unbind: '解绑',
|
|
42
|
+
unbindConfirm: '解绑会清掉本机保存的微信凭据,之后要重新扫码才能收消息。微信里的那个对话不会消失。确定解绑?',
|
|
43
|
+
unbindDone: '已解绑,本机不再收发微信消息。',
|
|
39
44
|
verifyLabel: '手机微信显示的数字',
|
|
40
45
|
verifyPlaceholder: '例如 123456',
|
|
41
46
|
verifySubmit: '提交验证码',
|
|
@@ -59,6 +64,9 @@ const TEXT = {
|
|
|
59
64
|
refresh: 'New QR code',
|
|
60
65
|
cancel: 'Cancel',
|
|
61
66
|
reconnect: 'Reconnect',
|
|
67
|
+
unbind: 'Unbind',
|
|
68
|
+
unbindConfirm: 'Unbinding clears the WeChat credentials saved on this machine; you will need to scan again to receive messages. The chat in WeChat itself stays. Continue?',
|
|
69
|
+
unbindDone: 'Unbound. This machine no longer sends or receives WeChat messages.',
|
|
62
70
|
verifyLabel: 'The number shown in WeChat',
|
|
63
71
|
verifyPlaceholder: 'for example 123456',
|
|
64
72
|
verifySubmit: 'Submit',
|
|
@@ -120,9 +128,11 @@ async function mountBinding(ctx: WebUiPanelContext): Promise<void> {
|
|
|
120
128
|
const generateButton = ui.button(t.generate, { variant: 'primary' });
|
|
121
129
|
const cancelButton = ui.button(t.cancel, { size: 'sm' });
|
|
122
130
|
const reconnectButton = ui.button(t.reconnect, { size: 'sm' });
|
|
131
|
+
const unbindButton = ui.button(t.unbind, { variant: 'danger', size: 'sm' });
|
|
123
132
|
cancelButton.style.display = 'none';
|
|
124
133
|
reconnectButton.style.display = 'none';
|
|
125
|
-
|
|
134
|
+
unbindButton.style.display = 'none';
|
|
135
|
+
actions.append(generateButton, cancelButton, reconnectButton, unbindButton);
|
|
126
136
|
|
|
127
137
|
sheet.body.append(stateLine, whoLine, tokenLine, messageLine, qrBox, linkRow, verifyRow, actions);
|
|
128
138
|
|
|
@@ -133,6 +143,7 @@ async function mountBinding(ctx: WebUiPanelContext): Promise<void> {
|
|
|
133
143
|
accountId: '',
|
|
134
144
|
userId: '',
|
|
135
145
|
lastMessageAt: '',
|
|
146
|
+
lastMessageLocal: '',
|
|
136
147
|
lastError: '',
|
|
137
148
|
contextTokens: 0,
|
|
138
149
|
qrDataUrl: '',
|
|
@@ -166,9 +177,9 @@ async function mountBinding(ctx: WebUiPanelContext): Promise<void> {
|
|
|
166
177
|
tokenLine.textContent = next.bound ? t.tokenCount(next.contextTokens) : '';
|
|
167
178
|
tokenLine.style.display = next.bound ? '' : 'none';
|
|
168
179
|
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
180
|
+
// 用服务端给的本地时间;没有就退回原始值,但不截 UTC 钟点。
|
|
181
|
+
const stamp = next.lastMessageLocal || (next.lastMessageAt ? next.lastMessageAt.replace('T', ' ').slice(0, 19) : '');
|
|
182
|
+
messageLine.textContent = stamp ? t.lastMessage(stamp) : (next.bound ? t.noMessage : '');
|
|
172
183
|
messageLine.style.display = next.bound ? '' : 'none';
|
|
173
184
|
|
|
174
185
|
// 错误:优先显示扫码期的具体原因。
|
|
@@ -189,12 +200,13 @@ async function mountBinding(ctx: WebUiPanelContext): Promise<void> {
|
|
|
189
200
|
|
|
190
201
|
verifyRow.style.display = next.verifyRequired ? '' : 'none';
|
|
191
202
|
|
|
192
|
-
//
|
|
203
|
+
// 按钮:未绑定给「生成二维码」,扫码中给「取消」;已绑定给「重新连接」与「解绑」。
|
|
193
204
|
const binding = next.status === 'binding' || Boolean(next.qrDataUrl);
|
|
194
205
|
generateButton.textContent = binding ? t.refresh : t.generate;
|
|
195
206
|
generateButton.style.display = next.bound ? 'none' : '';
|
|
196
207
|
cancelButton.style.display = binding && !next.bound ? '' : 'none';
|
|
197
208
|
reconnectButton.style.display = next.bound ? '' : 'none';
|
|
209
|
+
unbindButton.style.display = next.bound ? '' : 'none';
|
|
198
210
|
};
|
|
199
211
|
|
|
200
212
|
const readState = async (): Promise<void> => {
|
|
@@ -239,6 +251,23 @@ async function mountBinding(ctx: WebUiPanelContext): Promise<void> {
|
|
|
239
251
|
})();
|
|
240
252
|
});
|
|
241
253
|
|
|
254
|
+
// 解绑会清凭据,先确认一次;不可撤销,所以给 danger 样式的确认框。
|
|
255
|
+
unbindButton.addEventListener('click', () => {
|
|
256
|
+
void (async () => {
|
|
257
|
+
const ok = await ui.confirm({ title: t.unbind, body: t.unbindConfirm, danger: true });
|
|
258
|
+
if (!ok) return;
|
|
259
|
+
unbindButton.disabled = true;
|
|
260
|
+
try {
|
|
261
|
+
paint(await ctx.invoke<BindingState>('unbind'));
|
|
262
|
+
ui.toast(t.unbindDone, 'ok');
|
|
263
|
+
} catch (err) {
|
|
264
|
+
ui.toast(err instanceof Error ? err.message : String(err), 'bad');
|
|
265
|
+
} finally {
|
|
266
|
+
unbindButton.disabled = false;
|
|
267
|
+
}
|
|
268
|
+
})();
|
|
269
|
+
});
|
|
270
|
+
|
|
242
271
|
const submitVerify = (): void => {
|
|
243
272
|
const code = verifyInput.value.trim();
|
|
244
273
|
if (!code) return;
|
package/src/world.ts
CHANGED
|
@@ -195,7 +195,6 @@ export class WechatClawWorld implements World {
|
|
|
195
195
|
#started = false;
|
|
196
196
|
#startedAt = '';
|
|
197
197
|
#lastError = '';
|
|
198
|
-
#lastUserId = '';
|
|
199
198
|
#lastMessageAt = '';
|
|
200
199
|
#contextCount = 0;
|
|
201
200
|
#networkProblem = '';
|
|
@@ -264,13 +263,21 @@ export class WechatClawWorld implements World {
|
|
|
264
263
|
}
|
|
265
264
|
}
|
|
266
265
|
|
|
267
|
-
/**
|
|
266
|
+
/**
|
|
267
|
+
* 回复目标:**永远是绑定的微信本人**。
|
|
268
|
+
*
|
|
269
|
+
* 不用「最近一条消息的发送者」当目标——那样任何人只要能让一条消息进入收件流
|
|
270
|
+
* (群聊成员、服务通知、陌生人),回复目标就会被改写成对方,文件和文字都会发错人。
|
|
271
|
+
* 这个插件只服务一对一私聊,所以收件人钉死在绑定记录里。
|
|
272
|
+
*/
|
|
268
273
|
#replyTarget(): { to: string; contextToken: string } {
|
|
269
274
|
if (!this.#driver || !this.#auth?.token) {
|
|
270
275
|
throw new Error('微信未连接:先在「微信绑定」面板扫码,并确认本 World 已启用。');
|
|
271
276
|
}
|
|
272
|
-
const to = this.#
|
|
273
|
-
if (!to)
|
|
277
|
+
const to = String(this.#auth.userId ?? '').trim();
|
|
278
|
+
if (!to) {
|
|
279
|
+
throw new Error('绑定记录里没有微信用户 ID,无法确定收件人。请在「微信绑定」面板解绑后重新扫码。');
|
|
280
|
+
}
|
|
274
281
|
return { to, contextToken: '' };
|
|
275
282
|
}
|
|
276
283
|
|
|
@@ -428,6 +435,13 @@ export class WechatClawWorld implements World {
|
|
|
428
435
|
accountId: auth?.accountId ?? '',
|
|
429
436
|
userId: auth?.userId ?? '',
|
|
430
437
|
lastMessageAt: this.#lastMessageAt,
|
|
438
|
+
/**
|
|
439
|
+
* 面板显示用的本地时间。`lastMessageAt` 是 UTC ISO,直接截字符串会让操作者
|
|
440
|
+
* 看到 UTC 钟点(比如北京时间 05:11 显示成 21:11),所以这里按部署时区格式化。
|
|
441
|
+
*/
|
|
442
|
+
lastMessageLocal: this.#lastMessageAt
|
|
443
|
+
? `${this.#localStamp(Date.parse(this.#lastMessageAt))}`
|
|
444
|
+
: '',
|
|
431
445
|
lastError: login?.error || this.#lastError,
|
|
432
446
|
contextTokens: this.#contextCount,
|
|
433
447
|
startedAt: this.#startedAt,
|
|
@@ -460,6 +474,7 @@ export class WechatClawWorld implements World {
|
|
|
460
474
|
case 'verify': return this.#submitVerify(args?.[0]);
|
|
461
475
|
case 'cancel': return this.#cancelBinding();
|
|
462
476
|
case 'reconnect': return this.#reconnect();
|
|
477
|
+
case 'unbind': return this.#unbind();
|
|
463
478
|
default: throw new Error(`未知方法:${panel}.${method}`);
|
|
464
479
|
}
|
|
465
480
|
}
|
|
@@ -569,6 +584,58 @@ export class WechatClawWorld implements World {
|
|
|
569
584
|
return this.#publicState();
|
|
570
585
|
}
|
|
571
586
|
|
|
587
|
+
/**
|
|
588
|
+
* 解绑:清掉本机保存的凭据与游标,停掉长轮询,回到未绑定状态。
|
|
589
|
+
*
|
|
590
|
+
* 只清本机。微信侧的绑定关系在手机微信里,这里碰不到,所以面板文案要说清楚:
|
|
591
|
+
* 解绑后本机不再收消息,但微信里的那个 ClawBot 对话还在。
|
|
592
|
+
*/
|
|
593
|
+
async #unbind(): Promise<unknown> {
|
|
594
|
+
const hadToken = Boolean(this.#auth?.token);
|
|
595
|
+
|
|
596
|
+
// 停掉轮询,避免解绑后还有请求带着旧令牌出去。
|
|
597
|
+
const driver = this.#driver;
|
|
598
|
+
this.#driver = null;
|
|
599
|
+
if (driver) {
|
|
600
|
+
try {
|
|
601
|
+
await driver.stop();
|
|
602
|
+
} catch {
|
|
603
|
+
/* 停不下来也继续清凭据。 */
|
|
604
|
+
}
|
|
605
|
+
}
|
|
606
|
+
|
|
607
|
+
// 绑定流程也一并取消。
|
|
608
|
+
if (this.#login?.active) {
|
|
609
|
+
this.#login.active = false;
|
|
610
|
+
this.#loginAbort?.abort();
|
|
611
|
+
}
|
|
612
|
+
this.#login = null;
|
|
613
|
+
this.#loginAbort = null;
|
|
614
|
+
|
|
615
|
+
this.#auth = null;
|
|
616
|
+
this.#contextCount = 0;
|
|
617
|
+
this.#lastMessageAt = '';
|
|
618
|
+
this.#typingTickets.clear();
|
|
619
|
+
this.#lastError = '';
|
|
620
|
+
|
|
621
|
+
await this.#store.clearSession().catch((err) => {
|
|
622
|
+
this.#host?.log?.warn?.('清凭据失败', { error: errorText(err) });
|
|
623
|
+
});
|
|
624
|
+
|
|
625
|
+
this.#host?.log?.info?.(hadToken ? '微信已解绑' : '微信本来就没绑定,已清空本地状态');
|
|
626
|
+
|
|
627
|
+
await this.#pushEvent({
|
|
628
|
+
type: EVENT_LINK,
|
|
629
|
+
ts: nowIso(this.#timezone),
|
|
630
|
+
source: ID,
|
|
631
|
+
origin: 'internal',
|
|
632
|
+
text: hadToken ? '微信已解绑,本机不再收发消息。' : '微信本地状态已清空(原本未绑定)。',
|
|
633
|
+
meta: { kind: 'link/unbound' },
|
|
634
|
+
});
|
|
635
|
+
|
|
636
|
+
return this.#publicState();
|
|
637
|
+
}
|
|
638
|
+
|
|
572
639
|
async #startBinding(): Promise<unknown> {
|
|
573
640
|
if (this.#auth?.token) return this.#publicState();
|
|
574
641
|
if (this.#login?.active) return this.#publicState();
|
|
@@ -759,7 +826,7 @@ export class WechatClawWorld implements World {
|
|
|
759
826
|
this.#login.verifyCode = '';
|
|
760
827
|
}
|
|
761
828
|
await this.#rebuildClient();
|
|
762
|
-
this.#startDriver();
|
|
829
|
+
await this.#startDriver();
|
|
763
830
|
this.#host?.log?.info?.('微信绑定成功', { accountId, userId: shortId(userId) });
|
|
764
831
|
await this.#pushEvent({
|
|
765
832
|
type: EVENT_LINK,
|
|
@@ -821,7 +888,7 @@ export class WechatClawWorld implements World {
|
|
|
821
888
|
{ label: t.badgeAccount, value: state.bound ? (who || '—') : '—', tone: state.bound ? 'on' : 'off' },
|
|
822
889
|
{
|
|
823
890
|
label: t.badgeLast,
|
|
824
|
-
value: state.
|
|
891
|
+
value: state.lastMessageLocal ? state.lastMessageLocal.slice(11, 19) : '—',
|
|
825
892
|
tone: state.lastMessageAt ? 'on' : 'off',
|
|
826
893
|
},
|
|
827
894
|
{ label: t.badgeState, value: stateText, tone: state.connected ? 'on' : 'off' },
|
|
@@ -876,7 +943,7 @@ export class WechatClawWorld implements World {
|
|
|
876
943
|
|
|
877
944
|
this.#started = true;
|
|
878
945
|
if (this.#auth?.token) {
|
|
879
|
-
this.#startDriver();
|
|
946
|
+
await this.#startDriver();
|
|
880
947
|
} else {
|
|
881
948
|
host.log.info('微信尚未绑定,等待扫码');
|
|
882
949
|
}
|
|
@@ -903,6 +970,25 @@ export class WechatClawWorld implements World {
|
|
|
903
970
|
}
|
|
904
971
|
}
|
|
905
972
|
|
|
973
|
+
/** 把毫秒时间按部署时区格式化成 `YYYY-MM-DD HH:MM:SS`,给面板与回执看。 */
|
|
974
|
+
#localStamp(ms: number): string {
|
|
975
|
+
const d = new Date(Number.isFinite(ms) ? ms : Date.now());
|
|
976
|
+
try {
|
|
977
|
+
const parts = new Intl.DateTimeFormat('sv-SE', {
|
|
978
|
+
timeZone: this.#timezone || undefined,
|
|
979
|
+
year: 'numeric', month: '2-digit', day: '2-digit',
|
|
980
|
+
hour: '2-digit', minute: '2-digit', second: '2-digit',
|
|
981
|
+
hour12: false,
|
|
982
|
+
}).format(d);
|
|
983
|
+
return parts.replace(' ', ' ');
|
|
984
|
+
} catch {
|
|
985
|
+
// 时区名无效时退回本机时区,总比显示 UTC 强。
|
|
986
|
+
const pad = (n: number) => String(n).padStart(2, '0');
|
|
987
|
+
return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} `
|
|
988
|
+
+ `${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`;
|
|
989
|
+
}
|
|
990
|
+
}
|
|
991
|
+
|
|
906
992
|
#binDir(): string {
|
|
907
993
|
return `${this.#dataDir}/${ID}/bin`;
|
|
908
994
|
}
|
|
@@ -945,13 +1031,27 @@ export class WechatClawWorld implements World {
|
|
|
945
1031
|
});
|
|
946
1032
|
}
|
|
947
1033
|
|
|
948
|
-
|
|
1034
|
+
/**
|
|
1035
|
+
* 启动长轮询。
|
|
1036
|
+
*
|
|
1037
|
+
* 旧驱动必须先**真正停下**再起新的:两个驱动会各带自己的游标去问,服务端把消息推给其中
|
|
1038
|
+
* 一个、另一个把它写回旧游标,于是两边都以为「没新消息」。连续点几次重连正好触发这个。
|
|
1039
|
+
* 所以这里先置空(让旧驱动的回调立刻失效),再 await 它退出。
|
|
1040
|
+
*/
|
|
1041
|
+
async #startDriver(): Promise<void> {
|
|
949
1042
|
const api = this.#api;
|
|
950
1043
|
const auth = this.#auth;
|
|
951
1044
|
if (!api || !auth?.token) return;
|
|
1045
|
+
|
|
952
1046
|
const previous = this.#driver;
|
|
953
1047
|
this.#driver = null;
|
|
954
|
-
if (previous)
|
|
1048
|
+
if (previous) {
|
|
1049
|
+
try {
|
|
1050
|
+
await previous.stop();
|
|
1051
|
+
} catch (err) {
|
|
1052
|
+
this.#host?.log?.warn?.('旧驱动停止失败', { error: errorText(err) });
|
|
1053
|
+
}
|
|
1054
|
+
}
|
|
955
1055
|
|
|
956
1056
|
// 回调要认「这条消息是不是当前驱动发来的」,所以先声明再赋值。
|
|
957
1057
|
let driver: ILinkDriver;
|
|
@@ -961,6 +1061,7 @@ export class WechatClawWorld implements World {
|
|
|
961
1061
|
log: this.#host?.log ?? nullLoggerShim(),
|
|
962
1062
|
onMessage: (message): Promise<void> => this.#handleInbound(driver, message),
|
|
963
1063
|
onStatus: (status): void => this.#handleStatus(driver, status),
|
|
1064
|
+
onStalled: (): void => this.#handleStalled(driver),
|
|
964
1065
|
});
|
|
965
1066
|
this.#driver = driver;
|
|
966
1067
|
driver.start();
|
|
@@ -970,9 +1071,24 @@ export class WechatClawWorld implements World {
|
|
|
970
1071
|
});
|
|
971
1072
|
}
|
|
972
1073
|
|
|
1074
|
+
/** 重连多次都没响应:重建客户端(新连接)再起驱动,并如实记一条。 */
|
|
1075
|
+
#handleStalled(driver: ILinkDriver): void {
|
|
1076
|
+
if (driver !== this.#driver) return;
|
|
1077
|
+
this.#host?.log?.warn?.('微信长轮询长时间没有响应,重建连接');
|
|
1078
|
+
this.#lastError = '长轮询长时间没有响应,已重建连接';
|
|
1079
|
+
void (async () => {
|
|
1080
|
+
try {
|
|
1081
|
+
await this.#rebuildClient();
|
|
1082
|
+
await this.#startDriver();
|
|
1083
|
+
} catch (err) {
|
|
1084
|
+
this.#host?.log?.warn?.('重建连接失败', { error: errorText(err) });
|
|
1085
|
+
}
|
|
1086
|
+
})();
|
|
1087
|
+
}
|
|
1088
|
+
|
|
973
1089
|
async #restartDriver(): Promise<void> {
|
|
974
1090
|
await this.#rebuildClient();
|
|
975
|
-
this.#startDriver();
|
|
1091
|
+
await this.#startDriver();
|
|
976
1092
|
}
|
|
977
1093
|
|
|
978
1094
|
#handleStatus(driver: ILinkDriver, status: { connected: boolean; expired: boolean; error: string }): void {
|
|
@@ -1009,6 +1125,37 @@ export class WechatClawWorld implements World {
|
|
|
1009
1125
|
});
|
|
1010
1126
|
}
|
|
1011
1127
|
|
|
1128
|
+
/**
|
|
1129
|
+
* 判断一条入站消息的发送者是不是绑定的微信本人。
|
|
1130
|
+
*
|
|
1131
|
+
* 正常绑定会带回 `ilink_user_id`,这里严格比对,不匹配就丢。
|
|
1132
|
+
* 极少数情况下服务端没给这个字段,则把**扫码绑定后第一条消息的发送者**认作本人并持久化
|
|
1133
|
+
* (首次信任:刚扫完码,第一个说话的就是操作者)。认领只发生一次,之后一律严格比对。
|
|
1134
|
+
*/
|
|
1135
|
+
#acceptSender(from: string): boolean {
|
|
1136
|
+
const auth = this.#auth;
|
|
1137
|
+
const owner = String(auth?.userId ?? '').trim();
|
|
1138
|
+
|
|
1139
|
+
if (owner) {
|
|
1140
|
+
if (from === owner) return true;
|
|
1141
|
+
this.#host?.log?.warn?.('丢弃非绑定用户发来的微信消息', { from: shortId(from) });
|
|
1142
|
+
return false;
|
|
1143
|
+
}
|
|
1144
|
+
|
|
1145
|
+
// 没有绑定记录,或绑定没带 userId:无法确定本人。
|
|
1146
|
+
if (!auth?.token) {
|
|
1147
|
+
this.#host?.log?.warn?.('未绑定状态下收到微信消息,已丢弃', { from: shortId(from) });
|
|
1148
|
+
return false;
|
|
1149
|
+
}
|
|
1150
|
+
|
|
1151
|
+
auth.userId = from;
|
|
1152
|
+
this.#host?.log?.warn?.('绑定记录缺少微信用户 ID,已把首个发送者认作本人', { userId: shortId(from) });
|
|
1153
|
+
void this.#store.saveAuth(auth).catch((err) => {
|
|
1154
|
+
this.#host?.log?.warn?.('保存微信用户 ID 失败', { error: errorText(err) });
|
|
1155
|
+
});
|
|
1156
|
+
return true;
|
|
1157
|
+
}
|
|
1158
|
+
|
|
1012
1159
|
async #handleInbound(driver: ILinkDriver, message: WeixinMessage): Promise<void> {
|
|
1013
1160
|
if (driver !== this.#driver) return;
|
|
1014
1161
|
// 自己发出去的消息不回到自己这里。
|
|
@@ -1017,6 +1164,11 @@ export class WechatClawWorld implements World {
|
|
|
1017
1164
|
if (!from) return;
|
|
1018
1165
|
if (this.#auth?.accountId && from === this.#auth.accountId) return;
|
|
1019
1166
|
|
|
1167
|
+
// 只接受绑定本人发来的消息。别的人(群成员、服务通知、陌生人)一律丢弃:
|
|
1168
|
+
// 收件人已经钉死在 auth.userId,这里再放行,非本人的内容就会进入上下文,
|
|
1169
|
+
// 并且「回复」的语义会被引到错误的人身上。
|
|
1170
|
+
if (!this.#acceptSender(from)) return;
|
|
1171
|
+
|
|
1020
1172
|
const contextToken = String(message?.context_token ?? '').trim();
|
|
1021
1173
|
if (contextToken) {
|
|
1022
1174
|
try {
|
|
@@ -1027,7 +1179,6 @@ export class WechatClawWorld implements World {
|
|
|
1027
1179
|
}
|
|
1028
1180
|
|
|
1029
1181
|
const atMs = messageTimeMs(message);
|
|
1030
|
-
this.#lastUserId = from;
|
|
1031
1182
|
this.#lastMessageAt = new Date(atMs).toISOString();
|
|
1032
1183
|
|
|
1033
1184
|
const maxBytes = Math.max(1, Number(this.#cfg.maxInboundMediaMb) || 20) * 1024 * 1024;
|