cortico-world-wechat-claw 0.1.1 → 0.1.3

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 CHANGED
@@ -1,4 +1,32 @@
1
- # Changelog
1
+ # Changelog
2
+
3
+ ## 0.1.3
4
+
5
+ - **正文里的图片尺寸改成真图尺寸。** 之前用的是 `image_item.thumb_width` / `thumb_height`,
6
+ 那是微信给的缩略图尺寸(实测普遍 210 像素宽),而同一张图的文件实际是 868×1920、1440×1699。
7
+ 模型看到 `[图片 210x465]` 会按「这是一张小图」处理,于是把图判成糊的。现在从落盘文件本身读
8
+ (JPEG 的 SOF、PNG 的 IHDR、GIF/BMP/WebP 各自的文件头),读不出就不写尺寸,不猜。
9
+ - **上报版本号只认 `package.json`。** 早先 `world.ts` 里另抄了一份常量,停在 `0.1.0`,
10
+ 于是 `base_info.channel_version` 连续两个版本都在报旧号。现在直接读 `package.json`。
11
+
12
+ ## 0.1.2
13
+
14
+ 安全修复:收件人钉死在绑定本人。
15
+
16
+ - **回复目标不再随入站消息变化**。早先用「最近一条消息的发送者」当收件人,任何人只要能让一条
17
+ 消息进入收件流(群成员、服务通知、陌生人),文字和文件就会被发到对方。现在一律发往绑定记录里的
18
+ `userId`,拿不到就明确报错而不是乱发。
19
+ - **只接受绑定本人发来的消息**。发送者不是本人就丢弃并记一条 warn,不再进入上下文、
20
+ 也不保存它的 `context_token`。
21
+ - 绑定记录缺少 `ilink_user_id` 时,把扫码后第一条消息的发送者认作本人并写回 `auth.json`,
22
+ 认领只发生一次,之后严格比对。
23
+ - **配置页加安全提示**:说明启用后模型能把本机任意文件发到微信(含它自己的登录令牌),
24
+ 且发送前不会确认。
25
+ - **主动声明 `unsafe` 标签**:这个能力确实符合该标签的定义,由作者声明而不是等维护者来加。
26
+
27
+ 注意:这次没有收紧「能发哪些文件」。`wechat_send_image` / `wechat_send_file` 仍接受任意绝对路径,
28
+ 所以 `unsafe`(能把本机任意文件发到微信)依然成立。要撤这个标签,得先收紧到白名单目录,
29
+ 再向索引仓提 `[tags]` issue。
2
30
 
3
31
  ## 0.1.1
4
32
 
package/README.md CHANGED
@@ -133,6 +133,10 @@ POST 密文到微信 CDN → 从响应头 `x-encrypted-param` 取下载参数
133
133
  落到 `<dataDir>/wechat-claw/inbox/{images,files,videos,voices}/` → 路径写进事件正文 →
134
134
  模型接受该 MIME 时字节作为附件随事件到达。
135
135
 
136
+ 正文里的图片尺寸读自落盘文件本身(JPEG 的 SOF 段、PNG 的 IHDR 等)。微信消息里的
137
+ `thumb_width` / `thumb_height` 是缩略图尺寸,普遍只有 210 像素宽,和真图差一个数量级,
138
+ 所以不用它。
139
+
136
140
  ## 限制
137
141
 
138
142
  - 只支持 1v1 私聊;没有群聊、好友列表、朋友圈、转账或红包。
package/dist/webui.js CHANGED
@@ -1,4 +1,4 @@
1
- // src/webui/ffmpeg.ts
1
+ // ../../extensions/cortico-world-wechat-claw/src/webui/ffmpeg.ts
2
2
  var TEXT = {
3
3
  zh: {
4
4
  sheet: "ffmpeg",
@@ -160,7 +160,7 @@ async function mountFfmpeg(ctx) {
160
160
  await readState();
161
161
  }
162
162
 
163
- // src/webui/client.ts
163
+ // ../../extensions/cortico-world-wechat-claw/src/webui/client.ts
164
164
  var TEXT2 = {
165
165
  zh: {
166
166
  sheet: "\u5FAE\u4FE1\u7ED1\u5B9A",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cortico-world-wechat-claw",
3
- "version": "0.1.1",
3
+ "version": "0.1.3",
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
- import type { ConfigGroup } from 'cortico/core/types.ts';
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',
@@ -8,7 +8,7 @@
8
8
  import { mkdir, writeFile } from 'node:fs/promises';
9
9
  import { join } from 'node:path';
10
10
 
11
- import { extensionForInbound, mimeFromFilename, sniffImageMime } from './mime.ts';
11
+ import { extensionForInbound, imageSize, mimeFromFilename, sniffImageMime } from './mime.ts';
12
12
  import type { MediaTransfer } from './media.ts';
13
13
  import { MessageItemType, type MessageItem, type WeixinMessage } from './types.ts';
14
14
 
@@ -20,6 +20,9 @@ export interface InboundMedia {
20
20
  label: string;
21
21
  kind: 'image' | 'file' | 'video' | 'voice';
22
22
  bytes: number;
23
+ /** 图片的真实像素尺寸;读不出文件头时缺省。 */
24
+ width?: number;
25
+ height?: number;
23
26
  }
24
27
 
25
28
  /** 一条入站消息渲染后的结果。 */
@@ -200,9 +203,9 @@ export async function renderInbound(
200
203
  lines.push(missText(fetched, '图片', opts.maxBytes));
201
204
  continue;
202
205
  }
203
- const dims = item.image_item?.thumb_width && item.image_item?.thumb_height
204
- ? ` ${item.image_item.thumb_width}x${item.image_item.thumb_height}`
205
- : '';
206
+ // 尺寸取落盘文件本身。`image_item.thumb_width` 是缩略图尺寸(微信普遍给 210 宽),
207
+ // 拿它当图片尺寸会让上下文里的数字比真图小一个数量级。
208
+ const dims = fetched.width && fetched.height ? ` ${fetched.width}x${fetched.height}` : '';
206
209
  lines.push(`[图片${dims},${sizeText(fetched.bytes)},已存为 ${fetched.path}]`);
207
210
  media.push({ ...fetched, kind: 'image', label: `[图片${dims}]` });
208
211
  continue;
@@ -255,7 +258,7 @@ export async function renderInbound(
255
258
 
256
259
  /** 媒体取回的结果:成功给路径,失败给一句能区分原因的话。 */
257
260
  type FetchOutcome =
258
- | { ok: true; path: string; mime: string; bytes: number }
261
+ | { ok: true; path: string; mime: string; bytes: number; width?: number; height?: number }
259
262
  | { ok: false; reason: 'too-large' | 'no-ref' | 'failed' };
260
263
 
261
264
  /** 取一个媒体项的字节并按类型落盘。 */
@@ -285,7 +288,14 @@ async function fetchItem(
285
288
  dir: join(opts.mediaDir, 'images'),
286
289
  prefix: 'wx-image',
287
290
  });
288
- return { ok: true, path, mime, bytes: bytes.length };
291
+ const size = imageSize(bytes);
292
+ return {
293
+ ok: true,
294
+ path,
295
+ mime,
296
+ bytes: bytes.length,
297
+ ...(size ? { width: size.width, height: size.height } : {}),
298
+ };
289
299
  }
290
300
  if (kind === 'file') {
291
301
  const file = item.file_item;
@@ -1,5 +1,5 @@
1
1
  /**
2
- * 按扩展名判 MIME,以及反向取扩展名。
2
+ * 按扩展名判 MIME、反向取扩展名,以及读图片文件头的像素尺寸。
3
3
  *
4
4
  * 微信按 MIME 决定一条媒体走图片、视频还是文件通道(见 `sendMedia`),
5
5
  * 所以这张表决定「发出去是一张图还是一个附件」。
@@ -90,3 +90,75 @@ export function extensionForInbound(mime: string, bytes: Uint8Array): string {
90
90
  if (mime && mime !== OCTET_STREAM) return extensionFromMime(mime);
91
91
  return extensionFromMime(sniffImageMime(bytes) || OCTET_STREAM);
92
92
  }
93
+
94
+ /** 读图片文件头里的像素尺寸;格式认不出或数据不够时返回 null。 */
95
+ export function imageSize(bytes: Uint8Array): { width: number; height: number } | null {
96
+ const b = bytes;
97
+ const be16 = (i: number): number => (b[i]! << 8) | b[i + 1]!;
98
+ const be32 = (i: number): number => ((b[i]! << 24) | (b[i + 1]! << 16) | (b[i + 2]! << 8) | b[i + 3]!) >>> 0;
99
+ const le16 = (i: number): number => b[i]! | (b[i + 1]! << 8);
100
+ const le32 = (i: number): number => (b[i]! | (b[i + 1]! << 8) | (b[i + 2]! << 16) | (b[i + 3]! << 24)) >>> 0;
101
+
102
+ if (b.length >= 24 && b[0] === 0x89 && b[1] === 0x50 && b[2] === 0x4e && b[3] === 0x47) {
103
+ return { width: be32(16), height: be32(20) };
104
+ }
105
+ if (b.length >= 10 && b[0] === 0x47 && b[1] === 0x49 && b[2] === 0x46) {
106
+ return { width: le16(6), height: le16(8) };
107
+ }
108
+ if (b.length >= 30 && b[0] === 0x52 && b[1] === 0x49 && b[2] === 0x46 && b[3] === 0x46
109
+ && b[8] === 0x57 && b[9] === 0x45 && b[10] === 0x42 && b[11] === 0x50) {
110
+ return webpSize(b, le16, le32);
111
+ }
112
+ if (b.length >= 26 && b[0] === 0x42 && b[1] === 0x4d) {
113
+ return { width: le32(18), height: Math.abs(le32(22) | 0) };
114
+ }
115
+ if (b.length >= 4 && b[0] === 0xff && b[1] === 0xd8) return jpegSize(b);
116
+ return null;
117
+ }
118
+
119
+ /** JPEG 的尺寸在 SOF 段里;逐段走到 SOF 为止,跳过填充字节与独立的 RSTn。 */
120
+ function jpegSize(b: Uint8Array): { width: number; height: number } | null {
121
+ let i = 2;
122
+ while (i + 9 < b.length) {
123
+ if (b[i] !== 0xff) return null;
124
+ const marker = b[i + 1]!;
125
+ if (marker === 0xff) { i += 1; continue; }
126
+ if (marker === 0x01 || (marker >= 0xd0 && marker <= 0xd7)) { i += 2; continue; }
127
+ // 到了扫描数据或文件尾还没见到 SOF,说明这个文件没有可读的尺寸。
128
+ if (marker === 0xd9 || marker === 0xda) return null;
129
+ const length = (b[i + 2]! << 8) | b[i + 3]!;
130
+ if (length < 2) return null;
131
+ // SOF0–SOF15 里 C4(DHT)、C8(JPG)、CC(DAC) 不是帧头。
132
+ if (marker >= 0xc0 && marker <= 0xcf && marker !== 0xc4 && marker !== 0xc8 && marker !== 0xcc) {
133
+ return { height: (b[i + 5]! << 8) | b[i + 6]!, width: (b[i + 7]! << 8) | b[i + 8]! };
134
+ }
135
+ i += 2 + length;
136
+ }
137
+ return null;
138
+ }
139
+
140
+ /** WebP 三种子格式各有一套宽高编码。 */
141
+ function webpSize(
142
+ b: Uint8Array,
143
+ le16: (i: number) => number,
144
+ le32: (i: number) => number,
145
+ ): { width: number; height: number } | null {
146
+ const chunk = String.fromCharCode(b[12]!, b[13]!, b[14]!, b[15]!);
147
+ if (chunk === 'VP8X') {
148
+ return {
149
+ width: 1 + (b[24]! | (b[25]! << 8) | (b[26]! << 16)),
150
+ height: 1 + (b[27]! | (b[28]! << 8) | (b[29]! << 16)),
151
+ };
152
+ }
153
+ if (chunk === 'VP8 ') {
154
+ // 关键帧起始码 9D 01 2A 之后是 14 位宽、14 位高。
155
+ if (b[23] !== 0x9d || b[24] !== 0x01 || b[25] !== 0x2a) return null;
156
+ return { width: le16(26) & 0x3fff, height: le16(28) & 0x3fff };
157
+ }
158
+ if (chunk === 'VP8L') {
159
+ if (b[20] !== 0x2f) return null;
160
+ const bits = le32(21);
161
+ return { width: (bits & 0x3fff) + 1, height: ((bits >>> 14) & 0x3fff) + 1 };
162
+ }
163
+ return null;
164
+ }
package/src/world.ts CHANGED
@@ -1,4 +1,4 @@
1
- /**
1
+ /**
2
2
  * 微信 ClawBot World。
3
3
  *
4
4
  * 一个 iLink 一对一通道:扫码绑定、长轮询收消息、按类型回复文字/图片/文件。
@@ -14,6 +14,8 @@ import { fileURLToPath } from 'node:url';
14
14
 
15
15
  import QRCode from 'qrcode';
16
16
 
17
+ import pkg from '../package.json' with { type: 'json' };
18
+
17
19
  import type {
18
20
  BlobInput,
19
21
  Logger,
@@ -49,7 +51,8 @@ export const EVENT_MESSAGE = 'wechat-claw.message';
49
51
  export const EVENT_LINK = 'wechat-claw.link';
50
52
 
51
53
  const ENV_PROMPT_FILE = fileURLToPath(new URL('./ENV_PROMPT.md', import.meta.url));
52
- const PACKAGE_VERSION = '0.1.0';
54
+ /** 版本号只认 package.json;这里再抄一份会漂。 */
55
+ const PACKAGE_VERSION: string = pkg.version;
53
56
  /** 发消息时上报的观测标识,形状是 UA 的 `Name/Version`。 */
54
57
  const BOT_AGENT = `Cortico/6 (Coopanion; cortico-world-wechat-claw/${PACKAGE_VERSION})`;
55
58
 
@@ -195,7 +198,6 @@ export class WechatClawWorld implements World {
195
198
  #started = false;
196
199
  #startedAt = '';
197
200
  #lastError = '';
198
- #lastUserId = '';
199
201
  #lastMessageAt = '';
200
202
  #contextCount = 0;
201
203
  #networkProblem = '';
@@ -264,13 +266,21 @@ export class WechatClawWorld implements World {
264
266
  }
265
267
  }
266
268
 
267
- /** 回复目标:最近一条入站消息的发送者,没有就用绑定账号本人。 */
269
+ /**
270
+ * 回复目标:**永远是绑定的微信本人**。
271
+ *
272
+ * 不用「最近一条消息的发送者」当目标——那样任何人只要能让一条消息进入收件流
273
+ * (群聊成员、服务通知、陌生人),回复目标就会被改写成对方,文件和文字都会发错人。
274
+ * 这个插件只服务一对一私聊,所以收件人钉死在绑定记录里。
275
+ */
268
276
  #replyTarget(): { to: string; contextToken: string } {
269
277
  if (!this.#driver || !this.#auth?.token) {
270
278
  throw new Error('微信未连接:先在「微信绑定」面板扫码,并确认本 World 已启用。');
271
279
  }
272
- const to = this.#lastUserId || this.#auth.userId;
273
- if (!to) throw new Error('还没有收到过微信消息,等对方先说话。');
280
+ const to = String(this.#auth.userId ?? '').trim();
281
+ if (!to) {
282
+ throw new Error('绑定记录里没有微信用户 ID,无法确定收件人。请在「微信绑定」面板解绑后重新扫码。');
283
+ }
274
284
  return { to, contextToken: '' };
275
285
  }
276
286
 
@@ -607,7 +617,6 @@ export class WechatClawWorld implements World {
607
617
 
608
618
  this.#auth = null;
609
619
  this.#contextCount = 0;
610
- this.#lastUserId = '';
611
620
  this.#lastMessageAt = '';
612
621
  this.#typingTickets.clear();
613
622
  this.#lastError = '';
@@ -1119,6 +1128,37 @@ export class WechatClawWorld implements World {
1119
1128
  });
1120
1129
  }
1121
1130
 
1131
+ /**
1132
+ * 判断一条入站消息的发送者是不是绑定的微信本人。
1133
+ *
1134
+ * 正常绑定会带回 `ilink_user_id`,这里严格比对,不匹配就丢。
1135
+ * 极少数情况下服务端没给这个字段,则把**扫码绑定后第一条消息的发送者**认作本人并持久化
1136
+ * (首次信任:刚扫完码,第一个说话的就是操作者)。认领只发生一次,之后一律严格比对。
1137
+ */
1138
+ #acceptSender(from: string): boolean {
1139
+ const auth = this.#auth;
1140
+ const owner = String(auth?.userId ?? '').trim();
1141
+
1142
+ if (owner) {
1143
+ if (from === owner) return true;
1144
+ this.#host?.log?.warn?.('丢弃非绑定用户发来的微信消息', { from: shortId(from) });
1145
+ return false;
1146
+ }
1147
+
1148
+ // 没有绑定记录,或绑定没带 userId:无法确定本人。
1149
+ if (!auth?.token) {
1150
+ this.#host?.log?.warn?.('未绑定状态下收到微信消息,已丢弃', { from: shortId(from) });
1151
+ return false;
1152
+ }
1153
+
1154
+ auth.userId = from;
1155
+ this.#host?.log?.warn?.('绑定记录缺少微信用户 ID,已把首个发送者认作本人', { userId: shortId(from) });
1156
+ void this.#store.saveAuth(auth).catch((err) => {
1157
+ this.#host?.log?.warn?.('保存微信用户 ID 失败', { error: errorText(err) });
1158
+ });
1159
+ return true;
1160
+ }
1161
+
1122
1162
  async #handleInbound(driver: ILinkDriver, message: WeixinMessage): Promise<void> {
1123
1163
  if (driver !== this.#driver) return;
1124
1164
  // 自己发出去的消息不回到自己这里。
@@ -1127,6 +1167,11 @@ export class WechatClawWorld implements World {
1127
1167
  if (!from) return;
1128
1168
  if (this.#auth?.accountId && from === this.#auth.accountId) return;
1129
1169
 
1170
+ // 只接受绑定本人发来的消息。别的人(群成员、服务通知、陌生人)一律丢弃:
1171
+ // 收件人已经钉死在 auth.userId,这里再放行,非本人的内容就会进入上下文,
1172
+ // 并且「回复」的语义会被引到错误的人身上。
1173
+ if (!this.#acceptSender(from)) return;
1174
+
1130
1175
  const contextToken = String(message?.context_token ?? '').trim();
1131
1176
  if (contextToken) {
1132
1177
  try {
@@ -1137,7 +1182,6 @@ export class WechatClawWorld implements World {
1137
1182
  }
1138
1183
 
1139
1184
  const atMs = messageTimeMs(message);
1140
- this.#lastUserId = from;
1141
1185
  this.#lastMessageAt = new Date(atMs).toISOString();
1142
1186
 
1143
1187
  const maxBytes = Math.max(1, Number(this.#cfg.maxInboundMediaMb) || 20) * 1024 * 1024;