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): 保护账号边界与视频附件

david609dfed0e5ac
diff --git a/apps/desktop/src/main/im/__tests__/messagePersistence.test.ts b/apps/desktop/src/main/im/__tests__/messagePersistence.test.ts
new file mode 100644
index 0000000000..f349a4d34d
--- /dev/null
+++ b/apps/desktop/src/main/im/__tests__/messagePersistence.test.ts
@@ -0,0 +1,37 @@
+import { describe, expect, it, vi } from 'vitest';
+
+import type { IMAttachment } from '@cindy/im';
+
+vi.mock('../../localDb/ipc/messages', () => ({
+ createMessage: vi.fn(),
+}));
+vi.mock('../../logger', () => ({
+ createLogger: () => ({ warn: vi.fn() }),
+}));
+
+import { buildPersistedUserContent } from '../messagePersistence';
+
+describe('IM message persistence content', () => {
+ it('retains a managed file URL so message persistence pins the media blob', () => {
+ const url = `cindy-media://blobs/${'a'.repeat(64)}.mp4`;
+ const attachment: IMAttachment = {
+ kind: 'file',
+ absPath: 'C:\\managed\\clip.mp4',
+ originalName: 'clip.mp4',
+ mimeType: 'video/mp4',
+ url,
+ };
+
+ expect(buildPersistedUserContent('', [attachment])).toEqual({
+ text: '',
+ images: [],
+ files: [
+ {
+ name: 'clip.mp4',
+ path: 'C:\\managed\\clip.mp4',
+ url,
+ },
+ ],
+ });
+ });
+});
diff --git a/apps/desktop/src/main/im/host.ts b/apps/desktop/src/main/im/host.ts
index edcee09837..5a249f2cd5 100644
--- a/apps/desktop/src/main/im/host.ts
+++ b/apps/desktop/src/main/im/host.ts
@@ -89,6 +89,21 @@ const host: IMHost = {
});
return { absPath: hit.absPath, url: hit.url };
},
+ cacheMedia: async ({ integration, token, buffer, mimeType }) => {
+ const hit = await integrationCachePut({
+ cacheKey: integrationCacheKey(integration, token),
+ integration,
+ buffer,
+ mimeType,
+ // IM 入站媒体与图片同属不可再生的用户附件,不参与缓存回收。
+ isCache: false,
+ });
+ return {
+ absPath: hit.absPath,
+ url: hit.url,
+ mimeType: hit.mimeType,
+ };
+ },
getCachedImage: async (integration, token) => {
const hit = await integrationCacheGet(integrationCacheKey(integration, token));
if (!hit) return null;
diff --git a/apps/desktop/src/main/im/messagePersistence.ts b/apps/desktop/src/main/im/messagePersistence.ts
index a89c0a124b..352c623a85 100644
--- a/apps/desktop/src/main/im/messagePersistence.ts
+++ b/apps/desktop/src/main/im/messagePersistence.ts
@@ -46,30 +46,7 @@ export async function persistUserMessage(args: {
}): Promise<{ clientId: string } | null> {
const { sessionId, text, attachments = [] } = args;
const clientId = createId();
-
- let content: unknown;
- if (attachments.length === 0) {
- content = text;
- } else {
- // Keep durable content aligned with renderer/lib/imageRef.ts. The media
- // URL is retained so createMessage can pin the blob to this session.
- content = {
- text,
- images: attachments
- .filter((att) => att.kind === 'image')
- .map((att) => ({
- originalName: att.originalName,
- mimeType: att.mimeType,
- ...(att.url ? { url: att.url } : {}),
- })),
- files: attachments
- .filter((att) => att.kind === 'file')
- .map((att) => ({
- name: att.originalName,
- path: att.absPath,
- })),
- };
- }
+ const content = buildPersistedUserContent(text, attachments);
try {
await createMessage(sessionId, {
@@ -87,6 +64,35 @@ export async function persistUserMessage(args: {
}
}
+/** Build the durable content shape while retaining cindy-media URLs for ledger pinning. */
+export function buildPersistedUserContent(
+ text: string,
+ attachments: readonly IMAttachment[],
+): unknown {
+ if (attachments.length === 0) {
+ return text;
+ }
+ // Keep durable content aligned with renderer/lib/imageRef.ts. Media URLs
+ // remain embedded so createMessage can pin every blob to this session.
+ return {
+ text,
+ images: attachments
+ .filter((att) => att.kind === 'image')
+ .map((att) => ({
+ originalName: att.originalName,
+ mimeType: att.mimeType,
+ ...(att.url ? { url: att.url } : {}),
+ })),
+ files: attachments
+ .filter((att) => att.kind === 'file')
+ .map((att) => ({
+ name: att.originalName,
+ path: att.absPath,
+ ...(att.url ? { url: att.url } : {}),
+ })),
+ };
+}
+
// 注: assistant 消息不在本模块落库 — IM 会话统一经 wireSessionToIpcExternal
// 接入 desktop 事件管线, assistant / tool_use / tool_result / thinking 由
// messagePersistBroadcaster 单点落库(原 persistAssistantMessage 已随之移除)。
diff --git a/packages/lizi-im/src/types.ts b/packages/lizi-im/src/types.ts
index c50862abad..ef330252f7 100644
--- a/packages/lizi-im/src/types.ts
+++ b/packages/lizi-im/src/types.ts
@@ -60,16 +60,14 @@ export interface IMHost {
discordMediaDir?: string;
/** Root for downloaded telegram media. Optional — only hosts that wire the telegram channel provide it. */
telegramMediaDir?: string;
- /** Root for downloaded WeCom files and videos. */
+ /** Root for downloaded WeCom files and legacy image fallback. */
wecomMediaDir?: string;
};
/**
- * host 托管的媒体缓存(cindy-media 媒体总仓)。可选——注入后
- * 入站**图片**改走 host 内容寻址仓(按 token 免重下、全局去重、吃缓存回收
- * 策略);缺省时回落 `paths.*MediaDir` 的老目录写盘。非图片文件始终走老
- * 目录(host 侧规则 25 边界:非媒体不进字节仓)。包侧只摸字节和字符串,
- * 落盘/记账细节全在 host(规则 2)。
+ * host 托管的媒体缓存(cindy-media 媒体总仓)。可选——注入后入站图片及
+ * host 明确支持的其它媒体改走内容寻址仓;非媒体文件仍走
+ * `paths.*MediaDir`。包侧只摸字节和字符串,落盘/记账细节全在 host。
*/
media?: IMHostMediaCache;
@@ -93,6 +91,16 @@ export interface IMHostMediaCache {
buffer: Uint8Array;
mimeType: string;
}): Promise<{ absPath: string; url: string }>;
+ /**
+ * 其它 Cindy 托管媒体入总仓。未提供时 transport 必须降级为 unsupported,
+ * 不得新增写入冻结的 `cc-agent/*-media` 历史目录。
+ */
+ cacheMedia?(params: {
+ integration: 'feishu' | 'discord' | 'telegram' | 'wecom';
+ token: string;
+ buffer: Uint8Array;
+ mimeType: string;
+ }): Promise<{ absPath: string; url: string; mimeType: string }>;
/** 按 token 查已缓存图片;未缓存返回 null(调用方去真下载)。 */
getCachedImage(
integration: 'feishu' | 'discord' | 'telegram' | 'dingtalk' | 'wecom',
diff --git a/packages/lizi-im/src/wecom/__tests__/index.test.ts b/packages/lizi-im/src/wecom/__tests__/index.test.ts
index e4cf18382e..14f5dc7149 100644
--- a/packages/lizi-im/src/wecom/__tests__/index.test.ts
+++ b/packages/lizi-im/src/wecom/__tests__/index.test.ts
@@ -5,6 +5,7 @@ import { decodeWecomLane } from "../codec.js";
import { WecomIM } from "../index.js";
type Handler = (payload?: unknown) => void;
+type IpcHandler = (payload?: unknown) => Promise<unknown> | unknown;
class FakeClient {
readonly handlers = new Map<string, Handler[]>();
@@ -56,6 +57,7 @@ function createHost() {
["wecom-bot-secret", "secret-1"],
]);
const broadcasts: unknown[] = [];
+ const ipcHandlers = new Map<string, IpcHandler>();
const host: IMHost = {
secrets: {
read: (name) => secrets.get(name) ?? null,
@@ -67,7 +69,7 @@ function createHost() {
isAvailable: () => true,
},
ipc: {
- handle: vi.fn(),
+ handle: (channel, handler) => void ipcHandlers.set(channel, handler),
broadcast: (_channel, payload) => broadcasts.push(payload),
},
paths: {
@@ -76,7 +78,7 @@ function createHost() {
},
httpPostForm: async () => ({ status: 200, body: {} }),
};
- return { host, secrets, broadcasts };
+ return { host, secrets, broadcasts, ipcHandlers };
}
function message(args: {
@@ -100,6 +102,14 @@ function message(args: {
const flush = () => new Promise<void>((resolve) => setTimeout(resolve, 0));
+function deferred<T>() {
+ let resolve!: (value: T) => void;
+ const promise = new Promise<T>((done) => {
+ resolve = done;
+ });
+ return { promise, resolve };
+}
+
describe("WecomIM routing and ownership", () => {
it("TOFU-binds the first DM sender and only accepts that owner afterwards", async () => {
const { host, secrets } = createHost();
@@ -286,6 +296,55 @@ describe("WecomIM routing and ownership", () => {
});
});
+ it.each([
+ {
+ channel: "wecomBot:set-config",
+ payload: { botId: "bot-2", secret: "secret-2" },
+ },
+ { channel: "wecomBot:reconnect", payload: undefined },
+ ])(
+ "does not mutate transport through $channel after the account generation changes",
+ async ({ channel, payload }) => {
+ const { host, secrets, ipcHandlers } = createHost();
+ const gate = deferred<void>();
+ let active = true;
+ let accountToken = 1;
+ const accountRun = vi.fn();
+ host.accountScope = {
+ capture: () => (active ? accountToken : null),
+ isCurrent: (token) => active && token === accountToken,
+ async run<T>(
+ token: unknown,
+ operation: () => Promise<T>,
+ ): Promise<T> {
+ accountRun(token);
+ await gate.promise;
+ if (!active || token !== accountToken) {
+ throw new Error("[IM_NOT_READY] stale account generation");
+ }
+ return operation();
+ },
+ };
+ const clientFactory = vi.fn(() => new FakeClient() as never);
+ const im = new WecomIM(host, { clientFactory });
+ im.registerIpc();
+
+ const invoke = ipcHandlers.get(channel);
+ expect(invoke).toBeDefined();
+ const operation = Promise.resolve(invoke?.(payload));
+ await vi.waitFor(() => expect(accountRun).toHaveBeenCalledWith(1));
+
+ active = false;
+ accountToken += 1;
+ gate.resolve();
+
+ await expect(operation).rejects.toThrow("[IM_NOT_READY]");
+ expect(clientFactory).not.toHaveBeenCalled();
+ expect(secrets.get("wecom-bot-id")).toBe("bot-1");
+ expect(secrets.get("wecom-bot-secret")).toBe("secret-1");
+ },
+ );
+
it("preserves arrival order when media download is slower than a following text message", async () => {
const { host, secrets } = createHost();
secrets.set("wecom-owner-user-id", "owner");
@@ -335,4 +394,58 @@ describe("WecomIM routing and ownership", () => {
await flush();
expect(received).toEqual(["image", "second"]);
});
+
+ it("routes inbound video bytes through the host media ledger", async () => {
+ const { host, secrets } = createHost();
+ secrets.set("wecom-owner-user-id", "owner");
+ const client = new FakeClient();
+ client.downloadFile.mockResolvedValueOnce({
+ buffer: Buffer.from("video"),
+ filename: "clip.mp4",
+ });
+ 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 });
+ const received: IMMessageEvent[] = [];
+ im.onMessage((event) => received.push(event));
+
+ await im.init();
+ client.emit("message.video", {
+ body: {
+ msgid: "video-1",
+ aibotid: "bot-1",
+ chattype: "single",
+ from: { userid: "owner" },
+ msgtype: "video",
+ video: { url: "https://example.invalid/video" },
+ },
+ });
+ await flush();
+ await flush();
+
+ expect(cacheMedia).toHaveBeenCalledWith({
+ integration: "wecom",
+ token: "video-1:video",
+ buffer: Buffer.from("video"),
+ mimeType: "video/mp4",
+ });
+ expect(received[0]?.attachments).toEqual([
+ {
+ kind: "file",
+ absPath: "C:\\managed\\clip.mp4",
+ originalName: "clip.mp4",
+ mimeType: "video/mp4",
+ url: `cindy-media://blobs/${"a".repeat(64)}.mp4`,
+ },
+ ]);
+ });
});
diff --git a/packages/lizi-im/src/wecom/index.ts b/packages/lizi-im/src/wecom/index.ts
index e4ac2808f3..cab870318f 100644
--- a/packages/lizi-im/src/wecom/index.ts
+++ b/packages/lizi-im/src/wecom/index.ts
@@ -130,65 +130,81 @@ export class WecomIM extends BaseIM implements TextChannelIM {
ownerUserId: this.ownerUserId || null,
...(saveErrorStatus ? { saveErrorStatus } : {}),
});
+ const runAccountScoped = <T>(operation: () => Promise<T>): Promise<T> => {
+ const accountScope = this.host.accountScope;
+ if (!accountScope) return operation();
+ const token = accountScope.capture();
+ if (token === null) {
+ return Promise.reject(
+ new Error("[IM_NOT_READY] IM account is not active"),
+ );
+ }
+ return accountScope.run(token, operation);
+ };
this.host.ipc.handle("wecomBot:get-status", () => state());
- this.host.ipc.handle("wecomBot:set-config", async (payload) => {
- const record = isRecord(payload) ? payload : {};
- const botId = typeof record.botId === "string" ? record.botId.trim() : "";
- const secret =
- typeof record.secret === "string" ? record.secret.trim() : "";
- if (!botId || !secret) {
- const failed: IMStatus = {
- kind: "error",
- reason: "Bot ID 和 Secret 不能为空",
- };
- this.setStatus(failed);
- return state(failed);
- }
- if (!this.host.secrets.isAvailable()) {
- const failed: IMStatus = {
- kind: "error",
- reason: SECRET_WRITE_FAILED_REASON,
- };
- this.setStatus(failed);
- return state(failed);
- }
+ this.host.ipc.handle("wecomBot:set-config", (payload) =>
+ runAccountScoped(async () => {
+ const record = isRecord(payload) ? payload : {};
+ const botId =
+ typeof record.botId === "string" ? record.botId.trim() : "";
+ const secret =
+ typeof record.secret === "string" ? record.secret.trim() : "";
+ if (!botId || !secret) {
+ const failed: IMStatus = {
+ kind: "error",
+ reason: "Bot ID 和 Secret 不能为空",
+ };
+ this.setStatus(failed);
+ return state(failed);
+ }
+ if (!this.host.secrets.isAvailable()) {
+ const failed: IMStatus = {
+ kind: "error",
+ reason: SECRET_WRITE_FAILED_REASON,
+ };
+ this.setStatus(failed);
+ return state(failed);
+ }
- const previousBotId = this.host.secrets.read(BOT_ID_SECRET_KEY);
- const previousSecret = this.host.secrets.read(BOT_SECRET_SECRET_KEY);
- const previousOwner = this.host.secrets.read(OWNER_USER_ID_SECRET_KEY);
- const botChanged = Boolean(
- previousBotId?.trim() && previousBotId.trim() !== botId,
- );
- const saved =
- this.host.secrets.write(BOT_ID_SECRET_KEY, botId) &&
- this.host.secrets.write(BOT_SECRET_SECRET_KEY, secret);
- if (!saved) {
- this.restoreSecret(BOT_ID_SECRET_KEY, previousBotId);
- this.restoreSecret(BOT_SECRET_SECRET_KEY, previousSecret);
- this.restoreSecret(OWNER_USER_ID_SECRET_KEY, previousOwner);
- const failed: IMStatus = {
- kind: "error",
- reason: SECRET_WRITE_FAILED_REASON,
- };
- this.setStatus(failed);
- return state(failed);
- }
- if (botChanged) {
- this.host.secrets.remove(OWNER_USER_ID_SECRET_KEY);
- this.ownerUserId = "";
- }
- this.botId = botId;
- this.connect(botId, secret);
- return state();
- });
- this.host.ipc.handle("wecomBot:reconnect", () => {
- const botId = this.host.secrets.read(BOT_ID_SECRET_KEY)?.trim() ?? "";
- const secret =
- this.host.secrets.read(BOT_SECRET_SECRET_KEY)?.trim() ?? "";
- if (botId && secret) this.connect(botId, secret);
- return state();
- });
+ const previousBotId = this.host.secrets.read(BOT_ID_SECRET_KEY);
+ const previousSecret = this.host.secrets.read(BOT_SECRET_SECRET_KEY);
+ const previousOwner = this.host.secrets.read(OWNER_USER_ID_SECRET_KEY);
+ const botChanged = Boolean(
+ previousBotId?.trim() && previousBotId.trim() !== botId,
+ );
+ const saved =
+ this.host.secrets.write(BOT_ID_SECRET_KEY, botId) &&
+ this.host.secrets.write(BOT_SECRET_SECRET_KEY, secret);
+ if (!saved) {
+ this.restoreSecret(BOT_ID_SECRET_KEY, previousBotId);
+ this.restoreSecret(BOT_SECRET_SECRET_KEY, previousSecret);
+ this.restoreSecret(OWNER_USER_ID_SECRET_KEY, previousOwner);
+ const failed: IMStatus = {
+ kind: "error",
+ reason: SECRET_WRITE_FAILED_REASON,
+ };
+ this.setStatus(failed);
+ return state(failed);
+ }
+ if (botChanged) {
+ this.host.secrets.remove(OWNER_USER_ID_SECRET_KEY);
+ this.ownerUserId = "";
+ }
+ this.botId = botId;
+ this.connect(botId, secret);
+ return state();
+ }),
+ );
+ this.host.ipc.handle("wecomBot:reconnect", () =>
+ runAccountScoped(async () => {
+ const botId = this.host.secrets.read(BOT_ID_SECRET_KEY)?.trim() ?? "";
+ const secret =
+ this.host.secrets.read(BOT_SECRET_SECRET_KEY)?.trim() ?? "";
+ if (botId && secret) this.connect(botId, secret);
+ return state();
+ }),
+ );
this.host.ipc.handle("wecomBot:disconnect", async () => {
this.generation += 1;
this.client?.disconnect();
@@ -536,17 +552,30 @@ export class WecomIM extends BaseIM implements TextChannelIM {
await this.emitInbound(frame, client, generation, async () => {
const video = frame.body?.video;
if (!video) return unsupportedPayload("video", "视频内容缺失");
+ const cacheMedia = this.host.media?.cacheMedia;
+ if (!cacheMedia) {
+ return unsupportedPayload("video:unsupported", "视频暂不支持");
+ }
try {
const downloaded = await client.downloadFile(video.url, video.aeskey);
- const persisted = await persistWecomDownload({
- mediaDir: this.mediaDir,
+ const originalName = safeWecomFilename(downloaded.filename, ".mp4");
+ const stored = await cacheMedia({
+ integration: "wecom",
+ token: `${frame.body!.msgid}:video`,
buffer: downloaded.buffer,
- filename: downloaded.filename,
- fallbackExtension: ".mp4",
+ mimeType: mimeTypeForFilename(originalName),
});
return {
text: "",
- attachments: [{ kind: "file", ...persisted }],
+ attachments: [
+ {
+ kind: "file",
+ absPath: stored.absPath,
+ originalName,
+ mimeType: stored.mimeType,
+ url: stored.url,
+ },
+ ],
unsupported: [],
};
} catch (error) {