Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(wecom): 隔离测试发送与入站媒体

davidf650a2a0faa0
diff --git a/apps/desktop/src/main/__tests__/wecomGroupNotification.test.ts b/apps/desktop/src/main/__tests__/wecomGroupNotification.test.ts
index 5d56511a5c..907d11e642 100644
--- a/apps/desktop/src/main/__tests__/wecomGroupNotification.test.ts
+++ b/apps/desktop/src/main/__tests__/wecomGroupNotification.test.ts
@@ -1,5 +1,5 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
-import { ipcMain } from 'electron';
+import { ipcMain, net } from 'electron';
vi.mock('electron', () => ({
ipcMain: { handle: vi.fn() },
@@ -148,6 +148,29 @@ describe('WeCom group notification security boundary', () => {
expect(fetchImpl).toHaveBeenCalledOnce();
});
+ it('does not send a queued test after the account boundary changes', async () => {
+ let releasePublish: (() => void) | undefined;
+ let current = true;
+ const fetchImpl = vi.fn(async () => {
+ await new Promise<void>((resolve) => {
+ releasePublish = resolve;
+ });
+ return response({ errcode: 0, errmsg: 'ok' });
+ });
+ const url = 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=abcdefgh';
+ const service = new WecomGroupNotificationService(fetchImpl, createSecrets(url));
+
+ const publish = service.publishMarkdown('automation result');
+ const testing = service.test('Localized test message', () => current);
+ await vi.waitFor(() => expect(fetchImpl).toHaveBeenCalledOnce());
+ current = false;
+ releasePublish?.();
+
+ await expect(publish).resolves.toBeUndefined();
+ await expect(testing).rejects.toThrow('IM account changed');
+ expect(fetchImpl).toHaveBeenCalledOnce();
+ });
+
it('does not persist a webhook when the test call fails', async () => {
const fetchImpl = vi.fn(async () => response({ errcode: 93000, errmsg: 'invalid' }));
const secrets = createSecrets();
@@ -255,6 +278,7 @@ describe('WeCom group notification security boundary', () => {
});
it.each([
+ { channel: 'wecomGroupNotification:test', args: ['Localized test message'] },
{ channel: 'wecomGroupNotification:set-enabled', args: [false] },
{ channel: 'wecomGroupNotification:clear', args: [] },
])('rejects $channel when the account generation changes before mutation', async ({
@@ -276,6 +300,7 @@ describe('WeCom group notification security boundary', () => {
await expect(operation).rejects.toThrow('IM account changed');
expect(ownerScopedImSecrets.write).not.toHaveBeenCalled();
expect(ownerScopedImSecrets.remove).not.toHaveBeenCalled();
+ expect(net.fetch).not.toHaveBeenCalled();
});
it('clears both the webhook and its master switch', () => {
diff --git a/apps/desktop/src/main/wecomGroupNotification.ts b/apps/desktop/src/main/wecomGroupNotification.ts
index 6078b99abe..160842c0fc 100644
--- a/apps/desktop/src/main/wecomGroupNotification.ts
+++ b/apps/desktop/src/main/wecomGroupNotification.ts
@@ -183,10 +183,13 @@ export class WecomGroupNotificationService implements WecomGroupNotificationPubl
return { configured: true, enabled: true, maskedKey: maskWebhookKey(url) };
}
- async test(testMessage: string): Promise<void> {
+ async test(testMessage: string, isAccountCurrent: () => boolean = () => true): Promise<void> {
const url = this.requireStoredUrl();
const message = parseTestMessage(testMessage);
- await this.enqueue(() => this.send(url, message));
+ await this.enqueue(() => {
+ if (!isAccountCurrent()) throw new ImAccountScopeClosedError();
+ return this.send(url, message);
+ });
}
clear(): WecomGroupNotificationState {
@@ -263,12 +266,14 @@ export class WecomGroupNotificationService implements WecomGroupNotificationPubl
export const wecomGroupNotificationService = new WecomGroupNotificationService();
export function initWecomGroupNotificationIpc(): void {
- const runAccountScopedMutation = <T>(operation: () => T): Promise<T> => {
+ const runAccountScoped = <T>(
+ operation: (accountGeneration: number) => T | Promise<T>,
+ ): Promise<T> => {
const accountGeneration = captureImAccountGeneration();
if (accountGeneration === null) {
return Promise.reject(new ImAccountScopeClosedError());
}
- return runInImAccountGeneration(accountGeneration, async () => operation());
+ return runInImAccountGeneration(accountGeneration, async () => operation(accountGeneration));
};
ipcMain.handle('wecomGroupNotification:get-state', (event) => {
@@ -291,17 +296,21 @@ export function initWecomGroupNotificationIpc(): void {
);
ipcMain.handle('wecomGroupNotification:test', async (event, testMessage: unknown) => {
assertTrustedAppRendererEvent(event);
- await wecomGroupNotificationService.test(parseTestMessage(testMessage));
- return { ok: true as const };
+ return runAccountScoped(async (accountGeneration) => {
+ await wecomGroupNotificationService.test(parseTestMessage(testMessage), () =>
+ isImAccountGenerationCurrent(accountGeneration),
+ );
+ return { ok: true as const };
+ });
});
ipcMain.handle('wecomGroupNotification:set-enabled', (event, enabled: unknown) => {
assertTrustedAppRendererEvent(event);
if (typeof enabled !== 'boolean') throw new TypeError('enabled must be a boolean');
- return runAccountScopedMutation(() => wecomGroupNotificationService.setEnabled(enabled));
+ return runAccountScoped(() => wecomGroupNotificationService.setEnabled(enabled));
});
ipcMain.handle('wecomGroupNotification:clear', (event) => {
assertTrustedAppRendererEvent(event);
- return runAccountScopedMutation(() => wecomGroupNotificationService.clear());
+ return runAccountScoped(() => wecomGroupNotificationService.clear());
});
}
diff --git a/packages/lizi-im/src/wecom/__tests__/index.test.ts b/packages/lizi-im/src/wecom/__tests__/index.test.ts
index 045db9ebb0..7916f99fb4 100644
--- a/packages/lizi-im/src/wecom/__tests__/index.test.ts
+++ b/packages/lizi-im/src/wecom/__tests__/index.test.ts
@@ -1,3 +1,9 @@
+import { randomUUID } from "node:crypto";
+import { existsSync } from "node:fs";
+import { rm } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
import { describe, expect, it, vi } from "vitest";
import type { IMHost, IMMessageEvent } from "../../types.js";
@@ -396,6 +402,119 @@ describe("WecomIM routing and ownership", () => {
expect(received).toEqual(["image", "second"]);
});
+ it("does not cache an inbound image after the transport generation changes", async () => {
+ const { host, secrets } = createHost();
+ secrets.set("wecom-owner-user-id", "owner");
+ const client = new FakeClient();
+ const download = deferred<Awaited<ReturnType<FakeClient["downloadFile"]>>>();
+ client.downloadFile.mockImplementationOnce(() => download.promise);
+ const cacheImage = vi.fn(async () => ({
+ absPath: "C:\\managed\\photo.jpg",
+ url: "cindy-media://image",
+ }));
+ host.media = {
+ getCachedImage: vi.fn(async () => null),
+ cacheImage,
+ resolveMediaUrl: vi.fn(() => null),
+ };
+ const im = new WecomIM(host, { clientFactory: () => client as never });
+
+ await im.init();
+ client.emit("message.image", {
+ body: {
+ msgid: "stale-image",
+ aibotid: "bot-1",
+ chattype: "single",
+ from: { userid: "owner" },
+ msgtype: "image",
+ image: { url: "https://example.invalid/image" },
+ },
+ });
+ await vi.waitFor(() => expect(client.downloadFile).toHaveBeenCalledOnce());
+
+ await im.dispose();
+ download.resolve({ buffer: Buffer.from("image"), filename: "photo.jpg" });
+ await flush();
+ await flush();
+
+ expect(cacheImage).not.toHaveBeenCalled();
+ });
+
+ it("does not persist an inbound file after the transport generation changes", async () => {
+ const { host, secrets } = createHost();
+ secrets.set("wecom-owner-user-id", "owner");
+ const mediaDir = join(tmpdir(), `cindy-wecom-stale-${randomUUID()}`);
+ host.paths.wecomMediaDir = mediaDir;
+ const client = new FakeClient();
+ const download = deferred<Awaited<ReturnType<FakeClient["downloadFile"]>>>();
+ client.downloadFile.mockImplementationOnce(() => download.promise);
+ const im = new WecomIM(host, { clientFactory: () => client as never });
+
+ try {
+ await im.init();
+ client.emit("message.file", {
+ body: {
+ msgid: "stale-file",
+ aibotid: "bot-1",
+ chattype: "single",
+ from: { userid: "owner" },
+ msgtype: "file",
+ file: { url: "https://example.invalid/file" },
+ },
+ });
+ await vi.waitFor(() => expect(client.downloadFile).toHaveBeenCalledOnce());
+
+ await im.dispose();
+ download.resolve({ buffer: Buffer.from("file"), filename: "report.txt" });
+ await flush();
+ await flush();
+
+ expect(existsSync(mediaDir)).toBe(false);
+ } finally {
+ await rm(mediaDir, { recursive: true, force: true });
+ }
+ });
+
+ it("does not cache an inbound video after the transport generation changes", async () => {
+ const { host, secrets } = createHost();
+ secrets.set("wecom-owner-user-id", "owner");
+ const client = new FakeClient();
+ const download = deferred<Awaited<ReturnType<FakeClient["downloadFile"]>>>();
+ client.downloadFile.mockImplementationOnce(() => download.promise);
+ const cacheMedia = vi.fn(async () => ({
+ absPath: "C:\\managed\\clip.mp4",
+ url: `cindy-media://blobs/${"a".repeat(64)}.mp4`,
+ mimeType: "video/mp4",
+ }));
+ host.media = {
+ cacheImage: vi.fn(),
+ cacheMedia,
+ getCachedImage: vi.fn(async () => null),
+ resolveMediaUrl: vi.fn(() => null),
+ };
+ const im = new WecomIM(host, { clientFactory: () => client as never });
+
+ await im.init();
+ client.emit("message.video", {
+ body: {
+ msgid: "stale-video",
+ aibotid: "bot-1",
+ chattype: "single",
+ from: { userid: "owner" },
+ msgtype: "video",
+ video: { url: "https://example.invalid/video" },
+ },
+ });
+ await vi.waitFor(() => expect(client.downloadFile).toHaveBeenCalledOnce());
+
+ await im.dispose();
+ download.resolve({ buffer: Buffer.from("video"), filename: "clip.mp4" });
+ await flush();
+ await flush();
+
+ expect(cacheMedia).not.toHaveBeenCalled();
+ });
+
it("routes inbound video bytes through the host media ledger", async () => {
const { host, secrets } = createHost();
secrets.set("wecom-owner-user-id", "owner");
diff --git a/packages/lizi-im/src/wecom/index.ts b/packages/lizi-im/src/wecom/index.ts
index 8ada20ddd4..0a0b20cc4c 100644
--- a/packages/lizi-im/src/wecom/index.ts
+++ b/packages/lizi-im/src/wecom/index.ts
@@ -460,6 +460,7 @@ export class WecomIM extends BaseIM implements TextChannelIM {
if (!image) return unsupportedPayload("image", "图片内容缺失");
const attachment = await this.downloadImage(
client,
+ generation,
frame.body!.msgid,
0,
image,
@@ -489,6 +490,7 @@ export class WecomIM extends BaseIM implements TextChannelIM {
if (item.msgtype === "image" && item.image) {
const attachment = await this.downloadImage(
client,
+ generation,
frame.body!.msgid,
index,
item.image,
@@ -529,6 +531,9 @@ export class WecomIM extends BaseIM implements TextChannelIM {
if (!file) return unsupportedPayload("file", "文件内容缺失");
try {
const downloaded = await client.downloadFile(file.url, file.aeskey);
+ if (!this.isCurrent(client, generation)) {
+ return unsupportedPayload("file:stale", "文件下载已取消");
+ }
const persisted = await persistWecomDownload({
mediaDir: this.mediaDir,
buffer: downloaded.buffer,
@@ -560,6 +565,9 @@ export class WecomIM extends BaseIM implements TextChannelIM {
}
try {
const downloaded = await client.downloadFile(video.url, video.aeskey);
+ if (!this.isCurrent(client, generation)) {
+ return unsupportedPayload("video:stale", "视频下载已取消");
+ }
const originalName = safeWecomFilename(downloaded.filename, ".mp4");
const stored = await cacheMedia({
integration: "wecom",
@@ -670,6 +678,7 @@ export class WecomIM extends BaseIM implements TextChannelIM {
private async downloadImage(
client: WSClient,
+ generation: number,
messageId: string,
index: number,
image: { url: string; aeskey?: string },
@@ -690,6 +699,7 @@ export class WecomIM extends BaseIM implements TextChannelIM {
}
try {
const downloaded = await client.downloadFile(image.url, image.aeskey);
+ if (!this.isCurrent(client, generation)) return null;
const filename = safeWecomFilename(downloaded.filename, ".jpg");
const mimeType = mimeTypeForFilename(filename);
if (this.host.media) {