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): guard queued sends and deliver attachments

david2b2c2f6cf06d
diff --git a/apps/desktop/src/main/__tests__/wecomGroupNotification.test.ts b/apps/desktop/src/main/__tests__/wecomGroupNotification.test.ts
index 907d11e642..9ec742055e 100644
--- a/apps/desktop/src/main/__tests__/wecomGroupNotification.test.ts
+++ b/apps/desktop/src/main/__tests__/wecomGroupNotification.test.ts
@@ -249,6 +249,26 @@ describe('WeCom group notification security boundary', () => {
expect(bodies[1]).toContain('second');
});
+ it('stops queued chunks after the master switch is disabled', async () => {
+ let releaseFirstChunk: (() => void) | undefined;
+ const fetchImpl = vi.fn(async () => {
+ await new Promise<void>((resolve) => {
+ releaseFirstChunk = resolve;
+ });
+ return response({ errcode: 0 });
+ });
+ const url = 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=abcdefgh';
+ const service = new WecomGroupNotificationService(fetchImpl, createSecrets(url));
+
+ const publishing = service.publishMarkdown('a'.repeat(4_001));
+ await vi.waitFor(() => expect(fetchImpl).toHaveBeenCalledOnce());
+ service.setEnabled(false);
+ releaseFirstChunk?.();
+
+ await expect(publishing).rejects.toThrow('WECOM_GROUP_NOTIFICATIONS_DISABLED');
+ expect(fetchImpl).toHaveBeenCalledOnce();
+ });
+
it('does not send a queued publish through a replacement account webhook', async () => {
let releaseFirst: (() => void) | undefined;
const firstUrl = 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=account-one';
diff --git a/apps/desktop/src/main/im/host.ts b/apps/desktop/src/main/im/host.ts
index 5a249f2cd5..57e8288624 100644
--- a/apps/desktop/src/main/im/host.ts
+++ b/apps/desktop/src/main/im/host.ts
@@ -124,7 +124,9 @@ const host: IMHost = {
},
resolveMediaUrl: (url) => {
try {
- return url.startsWith('cindy-media://') ? resolveCindyMediaUrl(url).absPath : null;
+ return url.startsWith('cindy-media://') || url.startsWith('xdt-image://')
+ ? resolveManagedImageAbsPath(url)
+ : null;
} catch {
return null;
}
diff --git a/apps/desktop/src/main/wecomGroupNotification.ts b/apps/desktop/src/main/wecomGroupNotification.ts
index 160842c0fc..e970bcc6c2 100644
--- a/apps/desktop/src/main/wecomGroupNotification.ts
+++ b/apps/desktop/src/main/wecomGroupNotification.ts
@@ -204,14 +204,16 @@ export class WecomGroupNotificationService implements WecomGroupNotificationPubl
}
const accountGeneration = captureImAccountGeneration();
if (accountGeneration === null) throw new ImAccountScopeClosedError();
- const url = this.requireStoredUrl();
return this.enqueue(async () => {
const chunks = splitUtf8(markdown.trim() || 'Cindy 通知');
for (const chunk of chunks) {
if (!isImAccountGenerationCurrent(accountGeneration)) {
throw new ImAccountScopeClosedError();
}
- await this.send(url, chunk);
+ if (!this.getState().enabled) {
+ throw new Error('WECOM_GROUP_NOTIFICATIONS_DISABLED');
+ }
+ await this.send(this.requireStoredUrl(), chunk);
}
});
}
diff --git a/packages/lizi-im/src/wecom/__tests__/index.test.ts b/packages/lizi-im/src/wecom/__tests__/index.test.ts
index 7916f99fb4..db76fdf0e1 100644
--- a/packages/lizi-im/src/wecom/__tests__/index.test.ts
+++ b/packages/lizi-im/src/wecom/__tests__/index.test.ts
@@ -1,6 +1,6 @@
import { randomUUID } from "node:crypto";
import { existsSync } from "node:fs";
-import { rm } from "node:fs/promises";
+import { mkdir, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
@@ -248,6 +248,51 @@ describe("WecomIM routing and ownership", () => {
});
});
+ it("delivers terminal file and managed-image links without leaking local URLs", async () => {
+ const { host, secrets } = createHost();
+ secrets.set("wecom-owner-user-id", "owner");
+ const client = new FakeClient();
+ const mediaDir = join(tmpdir(), `cindy-wecom-outbound-${randomUUID()}`);
+ const filePath = join(mediaDir, "report.txt");
+ const imagePath = join(mediaDir, "chart.png");
+ const imageUrl = "cindy-media://blobs/chart.png";
+ host.media = {
+ getCachedImage: async () => null,
+ cacheImage: async () => ({ absPath: imagePath, url: imageUrl }),
+ resolveMediaUrl: vi.fn((url) => (url === imageUrl ? imagePath : null)),
+ };
+ const im = new WecomIM(host, { clientFactory: () => client as never });
+
+ await mkdir(mediaDir, { recursive: true });
+ await Promise.all([
+ writeFile(filePath, "report"),
+ writeFile(imagePath, "image"),
+ ]);
+ try {
+ await im.init();
+ const fileUrl = `xdt-file:///${encodeURI(filePath.replaceAll("\\", "/"))}`;
+ await im.commitFinal({
+ userId: "owner",
+ text: `done\n[report.txt](${fileUrl})\n![chart](${imageUrl})`,
+ terminal: "done",
+ mediaAbsPaths: [imagePath],
+ });
+
+ expect(client.sendMessage).toHaveBeenCalledWith("owner", {
+ msgtype: "markdown",
+ markdown: { content: "done" },
+ });
+ expect(JSON.stringify(client.sendMessage.mock.calls)).not.toContain("xdt-file://");
+ expect(JSON.stringify(client.sendMessage.mock.calls)).not.toContain("cindy-media://");
+ expect(client.uploadMedia).toHaveBeenCalledTimes(2);
+ expect(client.sendMediaMessage).toHaveBeenCalledTimes(2);
+ expect(host.media.resolveMediaUrl).toHaveBeenCalledWith(imageUrl);
+ } finally {
+ await im.dispose();
+ await rm(mediaDir, { recursive: true, force: true });
+ }
+ });
+
it("deduplicates repeated callback message ids", 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 0a0b20cc4c..e269f69a6e 100644
--- a/packages/lizi-im/src/wecom/index.ts
+++ b/packages/lizi-im/src/wecom/index.ts
@@ -24,6 +24,12 @@ import type {
IMUnsupportedEntry,
SendFileResult,
} from "../types.js";
+import {
+ collectXdtFileLinks,
+ collectXdtImageUrls,
+ stripXdtFileLinks,
+ XDT_IMAGE_REGEX,
+} from "../xdtRefs.js";
import {
chunkWecomMarkdown,
decodeWecomLane,
@@ -332,10 +338,40 @@ export class WecomIM extends BaseIM implements TextChannelIM {
}
async commitFinal(output: ImFinalOutput): Promise<void> {
- const chunks = chunkWecomMarkdown(output.text);
+ const fileLinks = collectXdtFileLinks(output.text);
+ const imageUrls = collectXdtImageUrls(output.text);
+ const attachments: Array<{ absPath: string; displayName?: string }> = [];
+ const seenPaths = new Set<string>();
+ const addAttachment = (absPath: string, displayName?: string) => {
+ if (seenPaths.has(absPath)) return;
+ seenPaths.add(absPath);
+ attachments.push({
+ absPath,
+ ...(displayName ? { displayName } : {}),
+ });
+ };
+ for (const link of fileLinks) addAttachment(link.absPath, link.alt || undefined);
+ for (const url of imageUrls) {
+ const absPath = this.host.media?.resolveMediaUrl(url) ?? null;
+ if (absPath) {
+ addAttachment(absPath);
+ } else {
+ this.log.warn("failed to resolve terminal managed image", { url });
+ }
+ }
+ for (const absPath of output.mediaAbsPaths ?? []) addAttachment(absPath);
+
+ const visibleText = stripXdtFileLinks(output.text.replace(XDT_IMAGE_REGEX, "")).trim();
+ const chunks = chunkWecomMarkdown(
+ visibleText || (attachments.length > 0 ? "📎 附件如下" : "_(空回复)_"),
+ );
await this.sendFinalChunks(output.userId, chunks);
- for (const absPath of output.mediaAbsPaths?.slice(0, 4) ?? []) {
- const result = await this.sendFile(output.userId, absPath);
+ for (const attachment of attachments.slice(0, 4)) {
+ const result = await this.sendFile(
+ output.userId,
+ attachment.absPath,
+ attachment.displayName,
+ );
if (!result.ok) {
this.log.warn("failed to send terminal attachment", {
reason: result.reason,