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 stops and outbound files

david1d922d706f2a
diff --git a/apps/desktop/src/main/im/shared/__tests__/turnRunnerSendOutcome.test.ts b/apps/desktop/src/main/im/shared/__tests__/turnRunnerSendOutcome.test.ts
index da049b2c47..5e23ca146c 100644
--- a/apps/desktop/src/main/im/shared/__tests__/turnRunnerSendOutcome.test.ts
+++ b/apps/desktop/src/main/im/shared/__tests__/turnRunnerSendOutcome.test.ts
@@ -1274,6 +1274,7 @@ describe('turnRunner send outcome policy (feishu adapter characterization)', ()
text: 'complete text only',
terminal: 'done',
threadTs: undefined,
+ allowedFileRoots: ['F:\\XDMaker'],
});
} finally {
fakeAdapter.output = previousOutput;
diff --git a/apps/desktop/src/main/im/shared/controlCommands.ts b/apps/desktop/src/main/im/shared/controlCommands.ts
new file mode 100644
index 0000000000..84090c7a1c
--- /dev/null
+++ b/apps/desktop/src/main/im/shared/controlCommands.ts
@@ -0,0 +1,9 @@
+/**
+ * `!stop` control command shared by the normal message router and channel
+ * interaction interceptors. Keep this leaf module dependency-free so prompts
+ * can bypass stop handling without importing the full message pipeline.
+ */
+export function isStopCommand(text: string): boolean {
+ const normalized = text.trim().toLowerCase();
+ return normalized === '!stop' || normalized === '!stop';
+}
diff --git a/apps/desktop/src/main/im/shared/messageHandler.ts b/apps/desktop/src/main/im/shared/messageHandler.ts
index e563a80299..422a0cafc4 100644
--- a/apps/desktop/src/main/im/shared/messageHandler.ts
+++ b/apps/desktop/src/main/im/shared/messageHandler.ts
@@ -27,6 +27,7 @@ import {
} from '../accountBoundary';
import { getControlScope, isInControl } from './controlState';
+import { isStopCommand } from './controlCommands';
import type { ImSlashHandlers } from './slashCommands';
import { looksLikeSlashCommand } from './slashCommands';
import type { ImTurnRunner } from './turnRunner';
@@ -37,10 +38,7 @@ import type { ImChannelAdapter } from './types';
* 用 `!` 而非 slash 前缀: Slack 会把 `/` 开头的输入截为原生 slash command,
* 普通 DM 文本里只有 `!` 前缀能原样到达 bot。
*/
-export function isStopCommand(text: string): boolean {
- const normalized = text.trim().toLowerCase();
- return normalized === '!stop' || normalized === '!stop';
-}
+export { isStopCommand } from './controlCommands';
export function createMessageHandler(
adapter: ImChannelAdapter,
diff --git a/apps/desktop/src/main/im/shared/turnRunner.ts b/apps/desktop/src/main/im/shared/turnRunner.ts
index b35fbf8cd0..2478961d45 100644
--- a/apps/desktop/src/main/im/shared/turnRunner.ts
+++ b/apps/desktop/src/main/im/shared/turnRunner.ts
@@ -140,6 +140,8 @@ interface TurnState {
buffer: string;
/** Managed images discovered in tool output for durable text channels. */
mediaAbsPaths: string[];
+ /** Current session root used to confine model-authored local file links. */
+ workingDir: string;
done: boolean;
/** 过程展示(tool_use 时间线)状态 — 见 turnActivity.ts。 */
activity: TurnActivityState;
@@ -612,6 +614,7 @@ export function createTurnRunner(
streamingHandlePromise: null,
buffer: '',
mediaAbsPaths: [],
+ workingDir: row.workingDir,
done: false,
activity: createTurnActivity(Date.now()),
activityTicker: null,
@@ -2221,6 +2224,7 @@ export function createTurnRunner(
terminal: turn.terminalKind,
threadTs: turn.scopeKey,
...(turn.mediaAbsPaths.length > 0 ? { mediaAbsPaths: turn.mediaAbsPaths } : {}),
+ allowedFileRoots: [turn.workingDir],
...(turn.terminalErrorCode ? { errorCode: turn.terminalErrorCode } : {}),
});
}
diff --git a/apps/desktop/src/main/im/wecom/__tests__/textInteractions.test.ts b/apps/desktop/src/main/im/wecom/__tests__/textInteractions.test.ts
index 8fac950846..850248214e 100644
--- a/apps/desktop/src/main/im/wecom/__tests__/textInteractions.test.ts
+++ b/apps/desktop/src/main/im/wecom/__tests__/textInteractions.test.ts
@@ -1,5 +1,5 @@
import type { InteractionRequest } from '@cindy/maker-core';
-import type { IMStatus, WecomIM } from '@cindy/im';
+import type { IMMessageEvent, IMStatus, WecomIM } from '@cindy/im';
import { describe, expect, it, vi } from 'vitest';
import { formatWecomInteractionPrompt, WecomTextInteractions } from '../textInteractions';
@@ -78,4 +78,42 @@ describe('formatWecomInteractionPrompt', () => {
statusHandler?.({ kind: 'idle' });
await result;
});
+
+ it('待审批时让 !stop 绕过拦截器并收口当前请求', async () => {
+ let intercept: ((event: IMMessageEvent) => boolean) | undefined;
+ const sendMarkdownText = vi.fn(async () => ({ messageId: 'message-1' }));
+ const sendText = vi.fn(async () => ({ messageId: 'message-2' }));
+ const im = {
+ onTextMessageIntercept: vi.fn((handler: (event: IMMessageEvent) => boolean) => {
+ intercept = handler;
+ return () => undefined;
+ }),
+ onStatusChange: vi.fn(() => () => undefined),
+ sendMarkdownText,
+ sendText,
+ } as unknown as WecomIM;
+ const interactions = new WecomTextInteractions(im);
+
+ const result = interactions.handle('owner', permissionRequest({ command: 'rm -rf build' }));
+ await vi.waitFor(() => expect(sendMarkdownText).toHaveBeenCalledOnce());
+
+ const consumed = intercept?.({
+ channelName: 'wecom',
+ senderId: 'owner',
+ chatId: 'owner',
+ contextId: 'bot-1',
+ messageId: 'stop-1',
+ text: ' !STOP ',
+ attachments: [],
+ unsupported: [],
+ });
+
+ expect(consumed).toBe(false);
+ await expect(result).resolves.toEqual({
+ kind: 'permission',
+ behavior: 'deny',
+ reason: 'wecom_interaction_cancelled_by_stop',
+ });
+ expect(sendText).not.toHaveBeenCalled();
+ });
});
diff --git a/apps/desktop/src/main/im/wecom/textInteractions.ts b/apps/desktop/src/main/im/wecom/textInteractions.ts
index efb79a9e89..2441ef1c45 100644
--- a/apps/desktop/src/main/im/wecom/textInteractions.ts
+++ b/apps/desktop/src/main/im/wecom/textInteractions.ts
@@ -1,6 +1,8 @@
import type { InteractionDecision, InteractionRequest } from '@cindy/maker-core';
import { escapeWecomMarkdown, type IMMessageEvent, type WecomIM } from '@cindy/im';
+import { isStopCommand } from '../shared/controlCommands';
+
interface PendingInteraction {
request: InteractionRequest;
resolve: (decision: InteractionDecision) => void;
@@ -65,6 +67,12 @@ export class WecomTextInteractions {
private consume(event: IMMessageEvent): boolean {
const pending = this.pending.get(event.senderId);
if (!pending) return false;
+ if (isStopCommand(event.text)) {
+ clearTimeout(pending.timer);
+ this.pending.delete(event.senderId);
+ pending.resolve(defaultDecision(pending.request, 'wecom_interaction_cancelled_by_stop'));
+ return false;
+ }
const decision = parseReply(pending.request, event.text);
if (!decision) {
void this.im.sendText(
diff --git a/packages/lizi-im/src/channelIM.ts b/packages/lizi-im/src/channelIM.ts
index e32268fe97..410103e139 100644
--- a/packages/lizi-im/src/channelIM.ts
+++ b/packages/lizi-im/src/channelIM.ts
@@ -120,6 +120,8 @@ export interface ImFinalOutput {
errorCode?: string;
/** Managed local media discovered in the terminal assistant output. */
mediaAbsPaths?: string[];
+ /** Host-approved roots for model-authored local file attachment links. */
+ allowedFileRoots?: string[];
}
/**
diff --git a/packages/lizi-im/src/wecom/__tests__/index.test.ts b/packages/lizi-im/src/wecom/__tests__/index.test.ts
index 84d98fce36..84937f1e9c 100644
--- a/packages/lizi-im/src/wecom/__tests__/index.test.ts
+++ b/packages/lizi-im/src/wecom/__tests__/index.test.ts
@@ -26,7 +26,13 @@ class FakeClient {
) => Promise<Record<string, never>>
>(async () => ({}));
readonly replyMedia = vi.fn(async () => ({}));
- readonly uploadMedia = vi.fn(async () => ({ media_id: "media-1" }));
+ readonly uploadMedia = vi.fn(
+ async (buffer: Buffer, options: { type: string; filename: string }) => {
+ void buffer;
+ void options;
+ return { media_id: "media-1" };
+ },
+ );
readonly downloadFile = vi.fn(async () => ({
buffer: Buffer.from("image"),
filename: "photo.jpg",
@@ -276,6 +282,7 @@ describe("WecomIM routing and ownership", () => {
text: `done\n[report.txt](${fileUrl})\n![chart](${imageUrl})`,
terminal: "done",
mediaAbsPaths: [imagePath],
+ allowedFileRoots: [mediaDir],
});
expect(client.sendMessage).toHaveBeenCalledWith("owner", {
@@ -293,6 +300,54 @@ describe("WecomIM routing and ownership", () => {
}
});
+ it("does not upload model-authored xdt-file links outside allowed roots", async () => {
+ const { host, secrets } = createHost();
+ secrets.set("wecom-owner-user-id", "owner");
+ const client = new FakeClient();
+ const allowedDir = join(tmpdir(), `cindy-wecom-allowed-${randomUUID()}`);
+ const outsideDir = join(tmpdir(), `cindy-wecom-outside-${randomUUID()}`);
+ const allowedPath = join(allowedDir, "report.txt");
+ const outsidePath = join(outsideDir, "secret.txt");
+ const im = new WecomIM(host, { clientFactory: () => client as never });
+
+ await Promise.all([
+ mkdir(allowedDir, { recursive: true }),
+ mkdir(outsideDir, { recursive: true }),
+ ]);
+ await Promise.all([
+ writeFile(allowedPath, "report"),
+ writeFile(outsidePath, "secret"),
+ ]);
+ try {
+ await im.init();
+ const allowedUrl = `xdt-file:///${encodeURI(allowedPath.replaceAll("\\", "/"))}`;
+ const outsideUrl = `xdt-file:///${encodeURI(outsidePath.replaceAll("\\", "/"))}`;
+ await im.commitFinal({
+ userId: "owner",
+ text: `done\n[report](${allowedUrl})\n[secret](${outsideUrl})`,
+ terminal: "done",
+ allowedFileRoots: [allowedDir],
+ });
+
+ expect(client.uploadMedia).toHaveBeenCalledOnce();
+ expect(client.uploadMedia.mock.calls[0]?.[0]).toEqual(Buffer.from("report"));
+ expect(JSON.stringify(client.uploadMedia.mock.calls)).not.toContain("secret");
+ expect(client.sendMessage).toHaveBeenCalledWith("owner", {
+ msgtype: "markdown",
+ markdown: {
+ content:
+ "done\n\n⚠️ 有 1 个文件附件未发送(不在当前工作目录内或无法验证)。",
+ },
+ });
+ } finally {
+ await im.dispose();
+ await Promise.all([
+ rm(allowedDir, { recursive: true, force: true }),
+ rm(outsideDir, { recursive: true, force: true }),
+ ]);
+ }
+ });
+
it("reports attachments omitted by the outbound safety cap", async () => {
const { host, secrets } = createHost();
secrets.set("wecom-owner-user-id", "owner");
diff --git a/packages/lizi-im/src/wecom/__tests__/media.test.ts b/packages/lizi-im/src/wecom/__tests__/media.test.ts
index 7b61dc7fca..5265634234 100644
--- a/packages/lizi-im/src/wecom/__tests__/media.test.ts
+++ b/packages/lizi-im/src/wecom/__tests__/media.test.ts
@@ -8,6 +8,7 @@ import {
mimeTypeForFilename,
persistWecomDownload,
readWecomOutboundFile,
+ resolveAllowedWecomOutboundFile,
safeWecomFilename,
} from "../media.js";
@@ -62,4 +63,40 @@ describe("WeCom media helpers", () => {
expect(outbound.filename).toBe("picture.png");
expect(mimeTypeForFilename("README")).toBe("application/octet-stream");
});
+
+ it("confines outbound files to an allowed root and returns the canonical path", async () => {
+ const root = await fs.mkdtemp(path.join(os.tmpdir(), "cindy-wecom-root-"));
+ const outside = await fs.mkdtemp(
+ path.join(os.tmpdir(), "cindy-wecom-outside-"),
+ );
+ tempDirs.push(root, outside);
+ const allowedFile = path.join(root, "report.txt");
+ const outsideFile = path.join(outside, "secret.txt");
+ await Promise.all([
+ fs.writeFile(allowedFile, "report"),
+ fs.writeFile(outsideFile, "secret"),
+ ]);
+
+ await expect(
+ resolveAllowedWecomOutboundFile(allowedFile, [root]),
+ ).resolves.toBe(await fs.realpath(allowedFile));
+ await expect(
+ resolveAllowedWecomOutboundFile(outsideFile, [root]),
+ ).resolves.toBeNull();
+ await expect(
+ resolveAllowedWecomOutboundFile(allowedFile, []),
+ ).resolves.toBeNull();
+ });
+
+ it("rejects a lexical in-root path whose realpath escapes the root", async () => {
+ const root = path.resolve("workspace");
+ const candidate = path.join(root, "linked", "secret.txt");
+ const escaped = path.resolve("outside", "secret.txt");
+ const realpath = async (target: string): Promise<string> =>
+ target === root ? root : escaped;
+
+ await expect(
+ resolveAllowedWecomOutboundFile(candidate, [root], realpath),
+ ).resolves.toBeNull();
+ });
});
diff --git a/packages/lizi-im/src/wecom/index.ts b/packages/lizi-im/src/wecom/index.ts
index 4ca8c1a399..4e494e1671 100644
--- a/packages/lizi-im/src/wecom/index.ts
+++ b/packages/lizi-im/src/wecom/index.ts
@@ -40,6 +40,7 @@ import {
mimeTypeForFilename,
persistWecomDownload,
readWecomOutboundFile,
+ resolveAllowedWecomOutboundFile,
safeWecomFilename,
} from "./media.js";
@@ -353,7 +354,19 @@ export class WecomIM extends BaseIM implements TextChannelIM {
...(displayName ? { displayName } : {}),
});
};
- for (const link of fileLinks) addAttachment(link.absPath, link.alt || undefined);
+ let rejectedFileCount = 0;
+ for (const link of fileLinks) {
+ const resolved = await resolveAllowedWecomOutboundFile(
+ link.absPath,
+ output.allowedFileRoots ?? [],
+ );
+ if (!resolved) {
+ rejectedFileCount += 1;
+ this.log.warn("skipped terminal file attachment outside allowed roots");
+ continue;
+ }
+ addAttachment(resolved, link.alt || undefined);
+ }
for (const url of imageUrls) {
const absPath = this.host.media?.resolveMediaUrl(url) ?? null;
if (absPath) {
@@ -371,9 +384,13 @@ export class WecomIM extends BaseIM implements TextChannelIM {
const attachmentNotice = omittedAttachmentCount
? `⚠️ 另有 ${omittedAttachmentCount} 个附件未发送(企业微信单次最多发送 ${MAX_TERMINAL_ATTACHMENTS} 个)。`
: "";
+ const rejectedFileNotice = rejectedFileCount
+ ? `⚠️ 有 ${rejectedFileCount} 个文件附件未发送(不在当前工作目录内或无法验证)。`
+ : "";
const visibleText = [
stripXdtFileLinks(stripXdtImageLinks(output.text)).trim(),
attachmentNotice,
+ rejectedFileNotice,
]
.filter(Boolean)
.join("\n\n");
diff --git a/packages/lizi-im/src/wecom/media.ts b/packages/lizi-im/src/wecom/media.ts
index ea80fb88fd..fba0d9d611 100644
--- a/packages/lizi-im/src/wecom/media.ts
+++ b/packages/lizi-im/src/wecom/media.ts
@@ -47,6 +47,46 @@ const MIME_BY_EXTENSION: Readonly<Record<string, string>> = {
".wav": "audio/wav",
};
+function isPathWithin(base: string, target: string): boolean {
+ const normalize = (value: string): string => {
+ const resolved = path.resolve(value);
+ return process.platform === "win32" ? resolved.toLowerCase() : resolved;
+ };
+ const relative = path.relative(normalize(base), normalize(target));
+ return (
+ relative === "" ||
+ (!relative.startsWith("..") && !path.isAbsolute(relative))
+ );
+}
+
+/**
+ * Resolve a model-authored attachment only when both its lexical path and
+ * canonical target stay under a host-approved root. Returning the canonical
+ * path keeps the later stat/read on the same symlink-resolved target.
+ */
+export async function resolveAllowedWecomOutboundFile(
+ absPath: string,
+ allowedRoots: readonly string[],
+ realpath: (target: string) => Promise<string> = fs.realpath,
+): Promise<string | null> {
+ const targetAbs = path.resolve(absPath);
+ for (const root of allowedRoots) {
+ if (!root.trim()) continue;
+ const rootAbs = path.resolve(root);
+ if (!isPathWithin(rootAbs, targetAbs)) continue;
+ try {
+ const [rootReal, targetReal] = await Promise.all([
+ realpath(rootAbs),
+ realpath(targetAbs),
+ ]);
+ if (isPathWithin(rootReal, targetReal)) return targetReal;
+ } catch {
+ // Missing, unreadable, or cyclic paths fail closed.
+ }
+ }
+ return null;
+}
+
export function mimeTypeForFilename(filename: string | undefined): string {
const extension = path.extname(filename ?? "").toLowerCase();
return MIME_BY_EXTENSION[extension] ?? "application/octet-stream";
@@ -58,6 +98,7 @@ export function safeWecomFilename(
): string {
const sanitized = path
.basename(filename?.trim() || `attachment${fallbackExtension}`)
+ // eslint-disable-next-line no-control-regex -- filenames must strip ASCII control characters
.replace(/[<>:"/\\|?*\u0000-\u001f]/g, "_")
.slice(0, 160);
let end = sanitized.length;