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): close queued notification races

davide3d2b3db4c22
diff --git a/apps/desktop/src/main/__tests__/wecomGroupNotification.test.ts b/apps/desktop/src/main/__tests__/wecomGroupNotification.test.ts
index b16462b22d..4a622ad295 100644
--- a/apps/desktop/src/main/__tests__/wecomGroupNotification.test.ts
+++ b/apps/desktop/src/main/__tests__/wecomGroupNotification.test.ts
@@ -171,6 +171,28 @@ describe('WeCom group notification security boundary', () => {
expect(fetchImpl).toHaveBeenCalledOnce();
});
+ it('does not send a queued test after the webhook configuration changes', async () => {
+ let releasePublish: (() => void) | undefined;
+ 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');
+ await vi.waitFor(() => expect(fetchImpl).toHaveBeenCalledOnce());
+ service.clear();
+ releasePublish?.();
+
+ await expect(publish).resolves.toBeUndefined();
+ await expect(testing).rejects.toThrow('WECOM_GROUP_CONFIG_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();
diff --git a/apps/desktop/src/main/wecomGroupNotification.ts b/apps/desktop/src/main/wecomGroupNotification.ts
index bd84548e69..b44e981a85 100644
--- a/apps/desktop/src/main/wecomGroupNotification.ts
+++ b/apps/desktop/src/main/wecomGroupNotification.ts
@@ -195,8 +195,12 @@ export class WecomGroupNotificationService implements WecomGroupNotificationPubl
async test(testMessage: string, isAccountCurrent: () => boolean = () => true): Promise<void> {
const url = this.requireStoredUrl();
const message = parseTestMessage(testMessage);
+ const configGeneration = this.configGeneration;
await this.enqueue(() => {
if (!isAccountCurrent()) throw new ImAccountScopeClosedError();
+ if (configGeneration !== this.configGeneration) {
+ throw new Error('WECOM_GROUP_CONFIG_CHANGED');
+ }
return this.send(url, message);
});
}
diff --git a/packages/lizi-im/src/wecom/__tests__/index.test.ts b/packages/lizi-im/src/wecom/__tests__/index.test.ts
index 08d47a0b23..e3754a915f 100644
--- a/packages/lizi-im/src/wecom/__tests__/index.test.ts
+++ b/packages/lizi-im/src/wecom/__tests__/index.test.ts
@@ -767,6 +767,50 @@ describe("WecomIM routing and ownership", () => {
expect(received).toEqual([]);
});
+ it("carries image staging rollback through the final account ownership check", async () => {
+ const { host, secrets } = createHost();
+ secrets.set("wecom-owner-user-id", "owner");
+ const accountToken = { id: 1 };
+ let accountActive = true;
+ host.accountScope = {
+ capture: () => (accountActive ? accountToken : null),
+ isCurrent: (token) => accountActive && token === accountToken,
+ run: async (_token, operation) => operation(),
+ };
+ const client = new FakeClient();
+ const discard = vi.fn(async () => {});
+ host.media = {
+ getCachedImage: vi.fn(async () => null),
+ cacheImage: vi.fn(async () => ({
+ absPath: "C:\\managed\\photo.jpg",
+ get url() {
+ accountActive = false;
+ return "cindy-media://image";
+ },
+ discard,
+ })),
+ resolveMediaUrl: vi.fn(() => null),
+ };
+ const im = new WecomIM(host, { clientFactory: () => client as never });
+ const received: IMMessageEvent[] = [];
+ im.onMessage((event) => received.push(event));
+
+ await im.init();
+ client.emit("message.image", {
+ body: {
+ msgid: "stale-normalized-image",
+ aibotid: "bot-1",
+ chattype: "single",
+ from: { userid: "owner" },
+ msgtype: "image",
+ image: { url: "https://example.invalid/image" },
+ },
+ });
+
+ await vi.waitFor(() => expect(discard).toHaveBeenCalledOnce());
+ expect(received).toEqual([]);
+ });
+
it("does not pin or download a cached image after the owning account boundary closes", 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 ab52a5786b..e81e26157c 100644
--- a/packages/lizi-im/src/wecom/index.ts
+++ b/packages/lizi-im/src/wecom/index.ts
@@ -55,6 +55,11 @@ const MAX_TERMINAL_ATTACHMENTS = 4;
const SECRET_WRITE_FAILED_REASON = "无法使用系统安全存储保存企业微信机器人凭证";
const NO_ACCOUNT_SCOPE = Symbol("no-account-scope");
+type StagedImage = {
+ attachment: IMAttachment;
+ discard?: () => Promise<void>;
+};
+
type MessageHandler = (event: IMMessageEvent) => void;
type StatusHandler = (status: IMStatus) => void;
type TextInterceptor = (event: IMMessageEvent) => boolean;
@@ -560,15 +565,20 @@ export class WecomIM extends BaseIM implements TextChannelIM {
await this.emitInbound(frame, client, generation, async () => {
const image = frame.body?.image;
if (!image) return unsupportedPayload("image", "图片内容缺失");
- const attachment = await this.downloadImage(
+ const staged = await this.downloadImage(
client,
generation,
frame.body!.msgid,
0,
image,
);
- return attachment
- ? { text: "", attachments: [attachment], unsupported: [] }
+ return staged
+ ? {
+ text: "",
+ attachments: [staged.attachment],
+ unsupported: [],
+ discard: staged.discard,
+ }
: unsupportedPayload("image:download-failed", "图片下载失败");
});
}
@@ -582,6 +592,7 @@ export class WecomIM extends BaseIM implements TextChannelIM {
const text: string[] = [];
const attachments: IMAttachment[] = [];
const unsupported: IMUnsupportedEntry[] = [];
+ const discards: Array<() => Promise<void>> = [];
for (const [index, item] of (
frame.body?.mixed.msg_item ?? []
).entries()) {
@@ -590,14 +601,17 @@ export class WecomIM extends BaseIM implements TextChannelIM {
continue;
}
if (item.msgtype === "image" && item.image) {
- const attachment = await this.downloadImage(
+ const staged = await this.downloadImage(
client,
generation,
frame.body!.msgid,
index,
item.image,
);
- if (attachment) attachments.push(attachment);
+ if (staged) {
+ attachments.push(staged.attachment);
+ if (staged.discard) discards.push(staged.discard);
+ }
else
unsupported.push({
type: "image:download-failed",
@@ -605,7 +619,12 @@ export class WecomIM extends BaseIM implements TextChannelIM {
});
}
}
- return { text: text.join("\n"), attachments, unsupported };
+ return {
+ text: text.join("\n"),
+ attachments,
+ unsupported,
+ discard: combineDiscards(discards),
+ };
});
}
@@ -803,7 +822,7 @@ export class WecomIM extends BaseIM implements TextChannelIM {
messageId: string,
index: number,
image: { url: string; aeskey?: string },
- ): Promise<IMAttachment | null> {
+ ): Promise<StagedImage | null> {
const token = `${messageId}:${index}`;
const cached = await this.host.media?.getCachedImage("wecom", token, {
shouldReuse: () => this.isCurrent(client, generation),
@@ -811,14 +830,16 @@ export class WecomIM extends BaseIM implements TextChannelIM {
if (!this.isCurrent(client, generation)) return null;
if (cached) {
return {
- kind: "image",
- absPath: cached.absPath,
- originalName: safeWecomFilename(
- undefined,
- extensionForMime(cached.mimeType),
- ),
- mimeType: cached.mimeType,
- url: cached.url,
+ attachment: {
+ kind: "image",
+ absPath: cached.absPath,
+ originalName: safeWecomFilename(
+ undefined,
+ extensionForMime(cached.mimeType),
+ ),
+ mimeType: cached.mimeType,
+ url: cached.url,
+ },
};
}
try {
@@ -839,11 +860,14 @@ export class WecomIM extends BaseIM implements TextChannelIM {
return null;
}
return {
- kind: "image",
- absPath: stored.absPath,
- originalName: filename,
- mimeType,
- url: stored.url,
+ attachment: {
+ kind: "image",
+ absPath: stored.absPath,
+ originalName: filename,
+ mimeType,
+ url: stored.url,
+ },
+ discard: stored.discard,
};
}
const persisted = await persistWecomDownload({
@@ -853,7 +877,7 @@ export class WecomIM extends BaseIM implements TextChannelIM {
fallbackExtension: ".jpg",
shouldKeep: () => this.isCurrent(client, generation),
});
- return { kind: "image", ...persisted };
+ return { attachment: { kind: "image", ...persisted } };
} catch (error) {
this.log.warn("failed to stage inbound image", safeError(error));
return null;
@@ -1115,6 +1139,19 @@ function unsupportedPayload(type: string, label: string) {
};
}
+function combineDiscards(
+ discards: Array<() => Promise<void>>,
+): (() => Promise<void>) | undefined {
+ if (discards.length === 0) return undefined;
+ return async () => {
+ const results = await Promise.allSettled(discards.map((discard) => discard()));
+ const failed = results.find(
+ (result): result is PromiseRejectedResult => result.status === "rejected",
+ );
+ if (failed) throw failed.reason;
+ };
+}
+
function extensionForMime(mimeType: string): string {
if (mimeType === "image/png") return ".png";
if (mimeType === "image/gif") return ".gif";