@mocrane/wecom 2026.2.5

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.
Files changed (49) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +0 -0
  3. package/clawdbot.plugin.json +10 -0
  4. package/index.ts +28 -0
  5. package/openclaw.plugin.json +10 -0
  6. package/package.json +81 -0
  7. package/src/accounts.ts +72 -0
  8. package/src/agent/api-client.ts +336 -0
  9. package/src/agent/handler.ts +566 -0
  10. package/src/agent/index.ts +12 -0
  11. package/src/channel.ts +259 -0
  12. package/src/config/accounts.ts +99 -0
  13. package/src/config/index.ts +12 -0
  14. package/src/config/media.ts +14 -0
  15. package/src/config/network.ts +16 -0
  16. package/src/config/schema.ts +104 -0
  17. package/src/config-schema.ts +41 -0
  18. package/src/crypto/aes.ts +108 -0
  19. package/src/crypto/index.ts +24 -0
  20. package/src/crypto/signature.ts +43 -0
  21. package/src/crypto/xml.ts +49 -0
  22. package/src/crypto.test.ts +32 -0
  23. package/src/crypto.ts +176 -0
  24. package/src/http.ts +102 -0
  25. package/src/media.test.ts +55 -0
  26. package/src/media.ts +55 -0
  27. package/src/monitor/state.queue.test.ts +185 -0
  28. package/src/monitor/state.ts +514 -0
  29. package/src/monitor/types.ts +136 -0
  30. package/src/monitor.active.test.ts +239 -0
  31. package/src/monitor.integration.test.ts +207 -0
  32. package/src/monitor.ts +1802 -0
  33. package/src/monitor.webhook.test.ts +311 -0
  34. package/src/onboarding.ts +472 -0
  35. package/src/outbound.test.ts +143 -0
  36. package/src/outbound.ts +200 -0
  37. package/src/runtime.ts +14 -0
  38. package/src/shared/command-auth.ts +101 -0
  39. package/src/shared/index.ts +5 -0
  40. package/src/shared/xml-parser.test.ts +30 -0
  41. package/src/shared/xml-parser.ts +183 -0
  42. package/src/target.ts +80 -0
  43. package/src/types/account.ts +76 -0
  44. package/src/types/config.ts +88 -0
  45. package/src/types/constants.ts +42 -0
  46. package/src/types/global.d.ts +9 -0
  47. package/src/types/index.ts +38 -0
  48. package/src/types/message.ts +185 -0
  49. package/src/types.ts +159 -0
@@ -0,0 +1,239 @@
1
+ import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
2
+ import { sendActiveMessage, handleWecomWebhookRequest, registerWecomWebhookTarget } from "./monitor.js";
3
+ import * as cryptoHelpers from "./crypto.js";
4
+ import * as runtime from "./runtime.js";
5
+ import * as agentApi from "./agent/api-client.js";
6
+ import { IncomingMessage, ServerResponse } from "node:http";
7
+ import { Socket } from "node:net";
8
+ import * as crypto from "node:crypto";
9
+
10
+ const { undiciFetch } = vi.hoisted(() => {
11
+ const undiciFetch = vi.fn();
12
+ return { undiciFetch };
13
+ });
14
+
15
+ vi.mock("undici", () => ({
16
+ fetch: undiciFetch,
17
+ ProxyAgent: class ProxyAgent { },
18
+ }));
19
+
20
+ vi.mock("./agent/api-client.js", () => ({
21
+ sendText: vi.fn(),
22
+ sendMedia: vi.fn(),
23
+ uploadMedia: vi.fn(),
24
+ }));
25
+
26
+ // Helpers
27
+ function createMockRequest(bodyObj: any): IncomingMessage {
28
+ const socket = new Socket();
29
+ const req = new IncomingMessage(socket);
30
+ req.method = "POST";
31
+ req.url = "/wecom?timestamp=123&nonce=456&signature=789";
32
+ req.push(JSON.stringify(bodyObj));
33
+ req.push(null);
34
+ return req;
35
+ }
36
+
37
+ function createMockResponse(): ServerResponse {
38
+ const req = new IncomingMessage(new Socket());
39
+ const res = new ServerResponse(req);
40
+ res.end = vi.fn() as any;
41
+ res.setHeader = vi.fn();
42
+ (res as any).statusCode = 200;
43
+ return res;
44
+ }
45
+
46
+ describe("Monitor Active Features", () => {
47
+ let capturedDeliver: ((payload: { text: string }) => Promise<void>) | undefined;
48
+ let mockCore: any;
49
+ let msgSeq = 0;
50
+ let senderUserId = "";
51
+ let senderChatId = "";
52
+ // Valid 32-byte AES Key (Base64 encoded)
53
+ const validKey = "jWmYm7qr5nMoCAstdRmNjt3p7vsH8HkK+qiJqQ0aaaa=";
54
+
55
+ beforeEach(() => {
56
+ vi.useFakeTimers();
57
+ capturedDeliver = undefined;
58
+ vi.restoreAllMocks();
59
+ undiciFetch.mockClear();
60
+ msgSeq += 1;
61
+ senderUserId = `zhangsan-${msgSeq}`;
62
+ senderChatId = `wr123-${msgSeq}`;
63
+
64
+ // Spy on crypto.randomBytes (default export in monitor.ts usage)
65
+ vi.spyOn(crypto.default, "randomBytes").mockImplementation((size) => {
66
+ return Buffer.alloc(size, 0x11);
67
+ });
68
+
69
+ // Mock Crypto Helpers
70
+ // Wespy on verifyWecomSignature to always pass
71
+ vi.spyOn(cryptoHelpers, "verifyWecomSignature").mockReturnValue(true);
72
+
73
+ // We spy on decryptWecomEncrypted to return our mock plaintext
74
+ // Note: For this to work despite direct import in monitor.ts, we rely on Vitest's
75
+ // module mocking capabilities or the fact that * exports might be live bindings.
76
+ // If this fails, we will know.
77
+ vi.spyOn(cryptoHelpers, "decryptWecomEncrypted").mockImplementation((opts) => {
78
+ return JSON.stringify({
79
+ msgid: `test-msg-id-${msgSeq}`,
80
+ aibotid: "bot-1",
81
+ chattype: "group",
82
+ chatid: senderChatId,
83
+ from: { userid: senderUserId },
84
+ msgtype: "text",
85
+ text: { content: "hello" },
86
+ response_url: "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=test-key"
87
+ });
88
+ });
89
+
90
+ mockCore = {
91
+ channel: {
92
+ text: {
93
+ resolveMarkdownTableMode: () => "off",
94
+ convertMarkdownTables: (t: string) => t.replace(/\|/g, "-")
95
+ },
96
+ commands: {
97
+ shouldComputeCommandAuthorized: () => false,
98
+ resolveCommandAuthorizedFromAuthorizers: () => true,
99
+ },
100
+ pairing: {
101
+ readAllowFromStore: async () => [],
102
+ },
103
+ reply: {
104
+ finalizeInboundContext: (c: any) => c,
105
+ resolveEnvelopeFormatOptions: () => ({}),
106
+ formatAgentEnvelope: () => "",
107
+ dispatchReplyWithBufferedBlockDispatcher: async (opts: any) => {
108
+ capturedDeliver = opts.dispatcherOptions.deliver;
109
+ return;
110
+ }
111
+ },
112
+ routing: { resolveAgentRoute: () => ({ agentId: "1", sessionKey: "1", accountId: "1" }) },
113
+ session: {
114
+ resolveStorePath: () => "",
115
+ readSessionUpdatedAt: () => 0,
116
+ recordInboundSession: vi.fn()
117
+ }
118
+ },
119
+ logging: { shouldLogVerbose: () => false }
120
+ };
121
+
122
+ vi.spyOn(runtime, "getWecomRuntime").mockReturnValue(mockCore);
123
+
124
+ registerWecomWebhookTarget({
125
+ account: { accountId: "1", enabled: true, configured: true, token: "T", encodingAESKey: validKey, receiveId: "R", config: {} as any },
126
+ config: {
127
+ channels: {
128
+ wecom: {
129
+ enabled: true,
130
+ agent: {
131
+ corpId: "corp",
132
+ corpSecret: "secret",
133
+ agentId: 1000002,
134
+ token: "token",
135
+ encodingAESKey: "aes",
136
+ },
137
+ },
138
+ },
139
+ } as any,
140
+ runtime: { log: () => { } },
141
+ core: mockCore,
142
+ path: "/wecom"
143
+ });
144
+ });
145
+
146
+ afterEach(() => {
147
+ vi.useRealTimers();
148
+ });
149
+
150
+ it("should protect <think> tags from table conversion", async () => {
151
+ const req = createMockRequest({ encrypt: "mock-encrypt" });
152
+ const res = createMockResponse();
153
+ await handleWecomWebhookRequest(req, res);
154
+
155
+ // The WeCom monitor debounces inbound messages before starting the agent.
156
+ // `flushPending` triggers async agent start without awaiting it, so give the
157
+ // microtask queue a chance to run after the timer fires.
158
+ await vi.runOnlyPendingTimersAsync();
159
+ await Promise.resolve();
160
+ await Promise.resolve();
161
+
162
+ expect(capturedDeliver).toBeDefined();
163
+
164
+ const payload = { text: "Out | side\n<think>Inside | Think</think>" };
165
+ const convertSpy = vi.spyOn(mockCore.channel.text, "convertMarkdownTables");
166
+
167
+ await capturedDeliver!(payload);
168
+
169
+ const calledArg = convertSpy.mock.calls[0][0];
170
+ expect(calledArg).toContain("__THINK_PLACEHOLDER_0__");
171
+ expect(calledArg).not.toContain("<think>");
172
+ });
173
+
174
+ it("should store response_url and allow active message sending", async () => {
175
+ const req = createMockRequest({ encrypt: "mock-encrypt" });
176
+ const res = createMockResponse();
177
+
178
+ // We use a real key but mocked randomBytes.
179
+ // However, `handleWecomWebhookRequest` calls `buildEncryptedJsonReply` -> `encryptWecomPlaintext`.
180
+ // `encryptWecomPlaintext` uses the key. Since it's valid, it should work fine.
181
+ // We don't verify the OUTPUT of handleWecomWebhookRequest, just that it runs and sets up state.
182
+
183
+ await handleWecomWebhookRequest(req, res);
184
+
185
+ const streamId = Buffer.alloc(16, 0x11).toString("hex");
186
+
187
+ undiciFetch.mockResolvedValue(new Response("ok", { status: 200 }));
188
+ await sendActiveMessage(streamId, "Active Hello");
189
+
190
+ expect(undiciFetch).toHaveBeenCalledWith(
191
+ "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=test-key",
192
+ expect.objectContaining({
193
+ method: "POST",
194
+ headers: expect.objectContaining({ "Content-Type": "application/json" }),
195
+ body: JSON.stringify({ msgtype: "text", text: { content: "Active Hello" } }),
196
+ }),
197
+ );
198
+ });
199
+
200
+ it("should fallback non-image media to agent DM (and push a Chinese prompt)", async () => {
201
+ const { uploadMedia, sendMedia } = agentApi as any;
202
+ uploadMedia.mockResolvedValue("media-id-1");
203
+ sendMedia.mockResolvedValue(undefined);
204
+
205
+ const req = createMockRequest({ encrypt: "mock-encrypt" });
206
+ const res = createMockResponse();
207
+ await handleWecomWebhookRequest(req, res);
208
+
209
+ await vi.advanceTimersByTimeAsync(600);
210
+ await Promise.resolve();
211
+ await Promise.resolve();
212
+
213
+ expect(capturedDeliver).toBeDefined();
214
+
215
+ // Create a local PDF to force non-image content-type inference.
216
+ const fs = await import("node:fs/promises");
217
+ const os = await import("node:os");
218
+ const path = await import("node:path");
219
+ const tmp = path.join(os.tmpdir(), `wecom-test-${Date.now()}.pdf`);
220
+ await fs.writeFile(tmp, Buffer.from("pdf"));
221
+
222
+ undiciFetch.mockResolvedValue(new Response("ok", { status: 200 }));
223
+
224
+ await capturedDeliver!({ text: "here", mediaUrls: [tmp] } as any);
225
+
226
+ expect(uploadMedia).toHaveBeenCalled();
227
+ expect(sendMedia).toHaveBeenCalledWith(
228
+ expect.objectContaining({
229
+ toUser: senderUserId,
230
+ mediaType: "file",
231
+ }),
232
+ );
233
+ // Ensure we attempted to push a prompt to response_url (uses undici fetch).
234
+ expect(undiciFetch).toHaveBeenCalled();
235
+ });
236
+
237
+ // 注:本机路径(/Users/... 或 /tmp/...)短路发图逻辑属于运行态特性,
238
+ // 单测在 fake timers + module singleton 状态下容易引入脆弱性;这里优先覆盖更关键的兜底链路与去重逻辑。
239
+ });
@@ -0,0 +1,207 @@
1
+ import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
2
+ import { handleWecomWebhookRequest, registerWecomWebhookTarget } from "./monitor.js";
3
+ import { encryptWecomPlaintext, computeWecomMsgSignature, WECOM_PKCS7_BLOCK_SIZE } from "./crypto.js";
4
+ import * as runtime from "./runtime.js";
5
+ import crypto from "node:crypto";
6
+ import { IncomingMessage, ServerResponse } from "node:http";
7
+ import { Socket } from "node:net";
8
+
9
+ const { undiciFetch } = vi.hoisted(() => {
10
+ const undiciFetch = vi.fn();
11
+ return { undiciFetch };
12
+ });
13
+
14
+ vi.mock("undici", () => ({
15
+ fetch: undiciFetch,
16
+ ProxyAgent: class ProxyAgent { },
17
+ }));
18
+
19
+ // Helpers to simulate HTTP request
20
+ function createMockRequest(bodyObj: any, query: URLSearchParams): IncomingMessage {
21
+ const socket = new Socket();
22
+ const req = new IncomingMessage(socket);
23
+ req.method = "POST";
24
+ req.url = `/wecom?${query.toString()}`;
25
+ req.push(JSON.stringify(bodyObj));
26
+ req.push(null);
27
+ return req;
28
+ }
29
+
30
+ function createMockResponse(): ServerResponse & { _getData: () => string, _getStatusCode: () => number } {
31
+ const req = new IncomingMessage(new Socket());
32
+ const res = new ServerResponse(req);
33
+ let data = "";
34
+ res.write = (chunk: any) => { data += chunk; return true; };
35
+ res.end = (chunk: any) => { if (chunk) data += chunk; return res; };
36
+ (res as any)._getData = () => data;
37
+ (res as any)._getStatusCode = () => res.statusCode;
38
+ return res as any;
39
+ }
40
+
41
+ // PKCS7 Pad Helper for manual encryption
42
+ function pkcs7Pad(buf: Buffer, blockSize: number): Buffer {
43
+ const mod = buf.length % blockSize;
44
+ const pad = mod === 0 ? blockSize : blockSize - mod;
45
+ const padByte = Buffer.from([pad]);
46
+ return Buffer.concat([buf, Buffer.alloc(pad, padByte[0]!)]);
47
+ }
48
+
49
+ describe("Monitor Integration: Inbound Image", () => {
50
+ const token = "MY_TOKEN";
51
+ const encodingAESKey = "jWmYm7qr5nMoCAstdRmNjt3p7vsH8HkK+qiJqQ0aaaa="; // 32 bytes key
52
+ const receiveId = "MY_CORPID";
53
+ let unregisterTarget: (() => void) | null = null;
54
+
55
+ // Mock Core Runtime
56
+ const mockDeliver = vi.fn();
57
+ const mockCore = {
58
+ channel: {
59
+ routing: { resolveAgentRoute: () => ({ agentId: "agent-1", sessionKey: "sess-1", accountId: "acc-1" }) },
60
+ commands: {
61
+ shouldComputeCommandAuthorized: () => false,
62
+ resolveCommandAuthorizedFromAuthorizers: () => true,
63
+ },
64
+ pairing: {
65
+ readAllowFromStore: async () => [],
66
+ },
67
+ session: {
68
+ resolveStorePath: () => "store/path",
69
+ readSessionUpdatedAt: () => 0,
70
+ recordInboundSession: vi.fn(),
71
+ },
72
+ reply: {
73
+ formatAgentEnvelope: () => "formatted-body",
74
+ finalizeInboundContext: (ctx: any) => ctx,
75
+ resolveEnvelopeFormatOptions: () => ({}),
76
+ dispatchReplyWithBufferedBlockDispatcher: async (opts: any) => {
77
+ // Simulate Agent processing by calling deliver immediately or later
78
+ // For this test, verifying the Inbound Body is enough.
79
+ // The delivery payload is what the AGENT sees.
80
+ // But wait, dispatchReply... is for OUTBOUND streaming replies.
81
+ // startAgentForStream calls it.
82
+ // We really want to spy on what `rawBody` was passed to startAgentForStream context.
83
+
84
+ // Actually `recordInboundSession` receives `ctx` which contains `RawBody`.
85
+ return;
86
+ },
87
+ },
88
+ text: { resolveMarkdownTableMode: () => "off", convertMarkdownTables: (t: string) => t },
89
+ },
90
+ logging: { shouldLogVerbose: () => true },
91
+ };
92
+
93
+ beforeEach(() => {
94
+ vi.spyOn(runtime, "getWecomRuntime").mockReturnValue(mockCore as any);
95
+
96
+ unregisterTarget?.();
97
+ unregisterTarget = registerWecomWebhookTarget({
98
+ account: {
99
+ accountId: "test-acc",
100
+ name: "Test",
101
+ enabled: true,
102
+ configured: true,
103
+ token,
104
+ encodingAESKey,
105
+ receiveId,
106
+ config: {} as any
107
+ },
108
+ config: {} as any,
109
+ runtime: { log: console.log, error: console.error },
110
+ core: mockCore as any,
111
+ path: "/wecom"
112
+ });
113
+ });
114
+
115
+ afterEach(() => {
116
+ unregisterTarget?.();
117
+ unregisterTarget = null;
118
+ vi.restoreAllMocks();
119
+ });
120
+
121
+ // Mock media saving
122
+ const mockSaveMediaBuffer = vi.fn().mockResolvedValue({ path: "/tmp/saved-image.jpg", contentType: "image/jpeg" });
123
+ (mockCore.channel as any).media = { saveMediaBuffer: mockSaveMediaBuffer };
124
+
125
+ it("should decrypt inbound image, save it, and inject into context", async () => {
126
+ // 1. Prepare Encrypted Media (The "File" on WeCom Server)
127
+ const fileContent = Buffer.from("fake-image-data");
128
+ const aesKey = Buffer.from(encodingAESKey + "=", "base64");
129
+ const iv = aesKey.subarray(0, 16);
130
+
131
+ // Encrypt content (WeCom does this)
132
+ const cipher = crypto.createCipheriv("aes-256-cbc", aesKey, iv);
133
+ cipher.setAutoPadding(false);
134
+ const encryptedMedia = Buffer.concat([cipher.update(pkcs7Pad(fileContent, WECOM_PKCS7_BLOCK_SIZE)), cipher.final()]);
135
+
136
+ // Mock HTTP fetch to return this encrypted media
137
+ undiciFetch.mockResolvedValue(new Response(encryptedMedia));
138
+
139
+ // 2. Prepare Inbound Message (The Webhook JSON)
140
+ const imageUrl = "http://wecom.server/media/123";
141
+ const inboundMsg = {
142
+ msgtype: "image",
143
+ image: { url: imageUrl },
144
+ from: { userid: "testuser" }
145
+ };
146
+
147
+ // 3. Encrypt the *Inbound Message* Payload (The Envelope)
148
+ const timestamp = String(Math.floor(Date.now() / 1000));
149
+ const nonce = "123456";
150
+ const encrypt = encryptWecomPlaintext({
151
+ encodingAESKey,
152
+ receiveId,
153
+ plaintext: JSON.stringify(inboundMsg)
154
+ });
155
+ const msgSignature = computeWecomMsgSignature({ token, timestamp, nonce, encrypt });
156
+
157
+ const query = new URLSearchParams({
158
+ msg_signature: msgSignature,
159
+ timestamp,
160
+ nonce
161
+ });
162
+
163
+ const bodyObj = {
164
+ touser: receiveId,
165
+ agentid: "10001",
166
+ encrypt, // Standard WeCom POST body structure
167
+ };
168
+
169
+ // 4. Send Request
170
+ const req = createMockRequest(bodyObj, query);
171
+ const res = createMockResponse();
172
+
173
+ await handleWecomWebhookRequest(req, res);
174
+
175
+ // Wait for debounce timer to trigger agent (DEFAULT_DEBOUNCE_MS = 500ms)
176
+ await new Promise(resolve => setTimeout(resolve, 600));
177
+
178
+ // 5. Verify
179
+ // Check recordInboundSession was called with correct RawBody and Media Context
180
+ expect(mockCore.channel.session.recordInboundSession).toHaveBeenCalled();
181
+ const recordCall = (mockCore.channel.session.recordInboundSession as any).mock.calls[0][0];
182
+ const ctx = recordCall.ctx;
183
+
184
+ // Expect: [image]
185
+ expect(ctx.RawBody).toBe("[image]");
186
+
187
+ // Expect media to be saved
188
+ expect(mockSaveMediaBuffer).toHaveBeenCalledWith(
189
+ expect.any(Buffer), // The decrypted buffer
190
+ "image/jpeg",
191
+ "inbound",
192
+ expect.any(Number), // maxBytes
193
+ "image.jpg"
194
+ );
195
+ const savedBuffer = mockSaveMediaBuffer.mock.calls[0][0];
196
+ expect(savedBuffer.toString()).toBe("fake-image-data");
197
+
198
+ // Expect Context Injection
199
+ expect(ctx.MediaPath).toBe("/tmp/saved-image.jpg");
200
+ expect(ctx.MediaType).toBe("image/jpeg");
201
+
202
+ expect(undiciFetch).toHaveBeenCalledWith(
203
+ imageUrl,
204
+ expect.objectContaining({ signal: expect.anything() }),
205
+ );
206
+ });
207
+ });