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。

feat(im): send native DingTalk images

david11cdeb5d591c
diff --git a/apps/desktop/src/main/im/dingtalk/__tests__/publicImageFetch.test.ts b/apps/desktop/src/main/im/dingtalk/__tests__/publicImageFetch.test.ts
new file mode 100644
index 0000000000..2cc3a6bb45
--- /dev/null
+++ b/apps/desktop/src/main/im/dingtalk/__tests__/publicImageFetch.test.ts
@@ -0,0 +1,50 @@
+import { describe, expect, it, vi } from 'vitest';
+
+import { fetchPublicImageBytes, type GuardedImageFetch } from '../../publicImageFetch';
+
+const PNG_BYTES = Uint8Array.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
+
+describe('IM public image fetch', () => {
+ it('requires guarded HTTPS redirects and releases the pinned dispatcher', async () => {
+ const release = vi.fn(async () => undefined);
+ const guardedFetch = vi.fn<GuardedImageFetch>(async () => ({
+ response: new Response(PNG_BYTES, {
+ headers: { 'content-type': 'image/png' },
+ }),
+ finalUrl: 'https://cdn.example/image.png',
+ release,
+ }));
+
+ await expect(
+ fetchPublicImageBytes('https://cdn.example/image.png', 1024, guardedFetch),
+ ).resolves.toEqual({
+ buffer: PNG_BYTES,
+ mimeType: 'image/png',
+ });
+ expect(guardedFetch).toHaveBeenCalledWith(
+ expect.objectContaining({
+ url: 'https://cdn.example/image.png',
+ requireHttps: true,
+ maxRedirects: 3,
+ signal: expect.any(AbortSignal),
+ }),
+ );
+ expect(release).toHaveBeenCalledOnce();
+ });
+
+ it('rejects an oversized response before reading its body', async () => {
+ const release = vi.fn(async () => undefined);
+ const guardedFetch: GuardedImageFetch = async () => ({
+ response: new Response(PNG_BYTES, {
+ headers: { 'content-length': '2048' },
+ }),
+ finalUrl: 'https://cdn.example/image.png',
+ release,
+ });
+
+ await expect(
+ fetchPublicImageBytes('https://cdn.example/image.png', 1024, guardedFetch),
+ ).rejects.toThrow(/size limit/);
+ expect(release).toHaveBeenCalledOnce();
+ });
+});
diff --git a/apps/desktop/src/main/im/host.ts b/apps/desktop/src/main/im/host.ts
index d7f480797e..1aa7c3bcc2 100644
--- a/apps/desktop/src/main/im/host.ts
+++ b/apps/desktop/src/main/im/host.ts
@@ -53,6 +53,7 @@ import {
WECHAT_COMPATIBILITY_POLICY_PRODUCTION_CONFIG,
WechatCompatibilityPolicyService,
} from './wechat/compatibilityPolicy';
+import { fetchPublicImageBytes } from './publicImageFetch';
const log = createLogger('im/host');
@@ -111,6 +112,7 @@ const host: IMHost = {
return null;
}
},
+ fetchRemoteImage: (url, maxBytes) => fetchPublicImageBytes(url, maxBytes),
},
secrets: ownerScopedImSecrets,
ipc: {
diff --git a/apps/desktop/src/main/im/publicImageFetch.ts b/apps/desktop/src/main/im/publicImageFetch.ts
new file mode 100644
index 0000000000..ca5e1c9129
--- /dev/null
+++ b/apps/desktop/src/main/im/publicImageFetch.ts
@@ -0,0 +1,84 @@
+/**
+ * IM 出站公网图片下载器。
+ *
+ * Agent Markdown 属于不可信输入。下载必须逐跳校验 HTTPS、DNS 解析结果与
+ * 重定向,避免 main 进程成为内网 / metadata SSRF 读原语;字节边读边限流,
+ * 不创建临时文件,也不把带查询参数的 URL 写入日志。
+ */
+import {
+ fetchWithSsrFGuard,
+ type GuardedFetchResult,
+} from '@cindy/browser-control-runtime/ssrf-runtime';
+
+const FETCH_TIMEOUT_MS = 30_000;
+const MAX_REDIRECTS = 3;
+
+export type GuardedImageFetch = (params: {
+ url: string;
+ signal: AbortSignal;
+ requireHttps: true;
+ maxRedirects: number;
+}) => Promise<GuardedFetchResult>;
+
+async function readBodyLimited(response: Response, maxBytes: number): Promise<Uint8Array> {
+ if (!response.body) throw new Error('remote image response has no body');
+ const reader = response.body.getReader();
+ const chunks: Uint8Array[] = [];
+ let total = 0;
+ try {
+ for (;;) {
+ const { done, value } = await reader.read();
+ if (done) break;
+ total += value.byteLength;
+ if (total > maxBytes) {
+ await reader.cancel();
+ throw new Error('remote image exceeds the size limit');
+ }
+ chunks.push(value);
+ }
+ } finally {
+ reader.releaseLock();
+ }
+ if (total === 0) throw new Error('remote image response is empty');
+ const output = new Uint8Array(total);
+ let offset = 0;
+ for (const chunk of chunks) {
+ output.set(chunk, offset);
+ offset += chunk.byteLength;
+ }
+ return output;
+}
+
+export async function fetchPublicImageBytes(
+ url: string,
+ maxBytes: number,
+ guardedFetch: GuardedImageFetch = fetchWithSsrFGuard,
+): Promise<{ buffer: Uint8Array; mimeType?: string }> {
+ if (!Number.isSafeInteger(maxBytes) || maxBytes <= 0) {
+ throw new Error('invalid remote image size limit');
+ }
+ const controller = new AbortController();
+ const timer = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS);
+ let result: GuardedFetchResult | null = null;
+ try {
+ result = await guardedFetch({
+ url,
+ signal: controller.signal,
+ requireHttps: true,
+ maxRedirects: MAX_REDIRECTS,
+ });
+ const { response } = result;
+ if (!response.ok) throw new Error(`remote image request failed: HTTP ${response.status}`);
+ const declaredLength = Number(response.headers.get('content-length') ?? 0);
+ if (declaredLength > maxBytes) throw new Error('remote image exceeds the size limit');
+ const buffer = await readBodyLimited(response, maxBytes);
+ const contentType = response.headers.get('content-type')?.split(';')[0]?.trim();
+ return {
+ buffer,
+ ...(contentType?.startsWith('image/') ? { mimeType: contentType } : {}),
+ };
+ } finally {
+ clearTimeout(timer);
+ await result?.release();
+ }
+}
diff --git a/packages/browser-control-runtime/package.json b/packages/browser-control-runtime/package.json
index 0f1a78ef8d..4ef5281e8e 100644
--- a/packages/browser-control-runtime/package.json
+++ b/packages/browser-control-runtime/package.json
@@ -7,7 +7,8 @@
"main": "./src/index.ts",
"types": "./src/index.ts",
"exports": {
- ".": "./src/index.ts"
+ ".": "./src/index.ts",
+ "./ssrf-runtime": "./src/shim/ssrf-runtime.ts"
},
"scripts": {
"build": "tsc --noEmit",
diff --git a/packages/lizi-im/src/dingtalk/__tests__/api.test.ts b/packages/lizi-im/src/dingtalk/__tests__/api.test.ts
index cce3a65e19..a3c73b665e 100644
--- a/packages/lizi-im/src/dingtalk/__tests__/api.test.ts
+++ b/packages/lizi-im/src/dingtalk/__tests__/api.test.ts
@@ -14,6 +14,74 @@ const PNG_BYTES = Uint8Array.from([
]);
describe("DingTalkApiClient", () => {
+ it("uploads image bytes and sends a native direct image message", async () => {
+ const fetcher = vi.fn<typeof fetch>(async (input, init) => {
+ const url = String(input);
+ if (url.startsWith("https://oapi.dingtalk.com/gettoken")) {
+ return jsonResponse({
+ errcode: 0,
+ access_token: "oapi-token",
+ expires_in: 7200,
+ });
+ }
+ if (url.startsWith("https://oapi.dingtalk.com/media/upload")) {
+ expect(init?.method).toBe("POST");
+ expect(init?.body).toBeInstanceOf(FormData);
+ return jsonResponse({ errcode: 0, media_id: "@media-1" });
+ }
+ if (url === "https://api.dingtalk.com/v1.0/oauth2/accessToken") {
+ return jsonResponse({ accessToken: "api-token", expireIn: 7200 });
+ }
+ if (url === "https://api.dingtalk.com/v1.0/robot/oToMessages/batchSend") {
+ return jsonResponse({});
+ }
+ throw new Error(`unexpected URL: ${url}`);
+ });
+ const api = new DingTalkApiClient("app-key", "app-secret", fetcher);
+
+ await api.sendImage(
+ {
+ kind: "direct",
+ id: "owner-1",
+ sessionWebhook: null,
+ sessionWebhookExpiresAt: null,
+ },
+ PNG_BYTES,
+ "picture.png",
+ );
+
+ const sendCall = fetcher.mock.calls.find(
+ ([url]) =>
+ String(url) ===
+ "https://api.dingtalk.com/v1.0/robot/oToMessages/batchSend",
+ );
+ expect(sendCall).toBeDefined();
+ expect(JSON.parse(String(sendCall?.[1]?.body))).toEqual({
+ robotCode: "app-key",
+ userIds: ["owner-1"],
+ msgKey: "sampleImageMsg",
+ msgParam: JSON.stringify({ photoURL: "@media-1" }),
+ });
+ });
+
+ it("rejects non-image outbound bytes before making a request", async () => {
+ const fetcher = vi.fn<typeof fetch>();
+ const api = new DingTalkApiClient("app-key", "app-secret", fetcher);
+
+ await expect(
+ api.sendImage(
+ {
+ kind: "direct",
+ id: "owner-1",
+ sessionWebhook: null,
+ sessionWebhookExpiresAt: null,
+ },
+ new TextEncoder().encode("<html>not an image</html>"),
+ ),
+ ).rejects.toThrow(/not an image/);
+ expect(fetcher).not.toHaveBeenCalled();
+ });
+
it("never posts to an untrusted session webhook and falls back to the fixed API", async () => {
const fetcher = vi
.fn<typeof fetch>()
diff --git a/packages/lizi-im/src/dingtalk/__tests__/dingtalkIM.test.ts b/packages/lizi-im/src/dingtalk/__tests__/dingtalkIM.test.ts
index 3f1a730009..d102cf31f9 100644
--- a/packages/lizi-im/src/dingtalk/__tests__/dingtalkIM.test.ts
+++ b/packages/lizi-im/src/dingtalk/__tests__/dingtalkIM.test.ts
@@ -1,3 +1,7 @@
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+
import { describe, expect, it, vi } from "vitest";
import type { DWClientDownStream } from "dingtalk-stream";
@@ -78,6 +82,33 @@ function validCredentialFetcher() {
);
}
+function outboundImageFetcher() {
+ return vi.fn<typeof fetch>(async (input) => {
+ const url = String(input);
+ if (url === "https://api.dingtalk.com/v1.0/oauth2/accessToken") {
+ return new Response(
+ JSON.stringify({ accessToken: "api-token", expireIn: 7200 }),
+ );
+ }
+ if (url.startsWith("https://oapi.dingtalk.com/gettoken")) {
+ return new Response(
+ JSON.stringify({
+ errcode: 0,
+ access_token: "oapi-token",
+ expires_in: 7200,
+ }),
+ );
+ }
+ if (url.startsWith("https://oapi.dingtalk.com/media/upload")) {
+ return new Response(JSON.stringify({ errcode: 0, media_id: "@media-1" }));
+ }
+ if (url === "https://api.dingtalk.com/v1.0/robot/oToMessages/batchSend") {
+ return new Response(JSON.stringify({}));
+ }
+ throw new Error(`unexpected URL: ${url}`);
+ });
+}
+
function directMessage(overrides: Record<string, unknown> = {}) {
return {
conversationId: "direct-chat",
@@ -94,6 +125,105 @@ function directMessage(overrides: Record<string, unknown> = {}) {
}
describe("DingTalkIM", () => {
+ it("uploads remote Markdown images and sends native image messages", async () => {
+ const { host } = makeHost();
+ const fetchRemoteImage = vi.fn(async () => ({
+ buffer: Uint8Array.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]),
+ mimeType: "image/png",
+ }));
+ host.media = {
+ getCachedImage: vi.fn(async () => null),
+ cacheImage: vi.fn(async () => ({
+ absPath: "/media/image.png",
+ url: "cindy-media://image.png",
+ })),
+ resolveMediaUrl: vi.fn(() => null),
+ fetchRemoteImage,
+ };
+ const fetcher = outboundImageFetcher();
+ const client = new FakeClient();
+ const im = new DingTalkIM(host, {
+ clientFactory: () => client,
+ fetcher,
+ });
+ await im.init();
+
+ await im.commitFinal({
+ userId: "owner-1",
+ text: ["给你一张图:", "![测试图片](https://cdn.example/image.png)"].join(
+ "\n",
+ ),
+ terminal: "done",
+ });
+
+ expect(fetchRemoteImage).toHaveBeenCalledWith(
+ "https://cdn.example/image.png",
+ 20 * 1024 * 1024,
+ );
+ const outboundBodies = fetcher.mock.calls
+ .filter(
+ ([url]) =>
+ String(url) ===
+ "https://api.dingtalk.com/v1.0/robot/oToMessages/batchSend",
+ )
+ .map(([, init]) => JSON.parse(String(init?.body)));
+ expect(outboundBodies).toEqual([
+ {
+ robotCode: "app-key",
+ userIds: ["owner-1"],
+ msgKey: "sampleText",
+ msgParam: JSON.stringify({ content: "给你一张图:\n测试图片" }),
+ },
+ {
+ robotCode: "app-key",
+ userIds: ["owner-1"],
+ msgKey: "sampleImageMsg",
+ msgParam: JSON.stringify({ photoURL: "@media-1" }),
+ },
+ ]);
+ });
+
+ it("uploads managed local output images carried by commitFinal", async () => {
+ const { host } = makeHost();
+ const client = new FakeClient();
+ const fetcher = outboundImageFetcher();
+ const im = new DingTalkIM(host, {
+ clientFactory: () => client,
+ fetcher,
+ });
+ const tempDir = fs.mkdtempSync(
+ path.join(os.tmpdir(), "dingtalk-outbound-"),
+ );
+ const imagePath = path.join(tempDir, "generated.png");
+ fs.writeFileSync(
+ imagePath,
+ Uint8Array.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]),
+ );
+ try {
+ await im.init();
+ await im.commitFinal({
+ userId: "owner-1",
+ text: "生成完成",
+ terminal: "done",
+ mediaAbsPaths: [imagePath],
+ });
+ } finally {
+ fs.rmSync(tempDir, { recursive: true, force: true });
+ }
+
+ const outboundMessageTypes = fetcher.mock.calls
+ .filter(
+ ([url]) =>
+ String(url) ===
+ "https://api.dingtalk.com/v1.0/robot/oToMessages/batchSend",
+ )
+ .map(([, init]) => {
+ const body = JSON.parse(String(init?.body)) as { msgKey: string };
+ return body.msgKey;
+ });
+ expect(outboundMessageTypes).toEqual(["sampleText", "sampleImageMsg"]);
+ });
+
it("claims the first direct sender, acknowledges immediately, and drops other direct users", async () => {
const { host, secrets } = makeHost();
const client = new FakeClient();
diff --git a/packages/lizi-im/src/dingtalk/__tests__/outbound.test.ts b/packages/lizi-im/src/dingtalk/__tests__/outbound.test.ts
new file mode 100644
index 0000000000..155753c8e5
--- /dev/null
+++ b/packages/lizi-im/src/dingtalk/__tests__/outbound.test.ts
@@ -0,0 +1,44 @@
+import { describe, expect, it } from "vitest";
+
+import {
+ collectRemoteMarkdownImages,
+ replaceUploadedRemoteImages,
+} from "../outbound.js";
+
+describe("dingtalk outbound markdown images", () => {
+ it("collects unique HTTPS images with a strict limit", () => {
+ const text = [
+ "![first](https://cdn.example/one.png)",
+ "![duplicate](https://cdn.example/one.png)",
+ "![second](https://cdn.example/two.jpg)",
+ "![third](https://cdn.example/three.webp)",
+ ].join("\n");
+
+ expect(collectRemoteMarkdownImages(text, 2)).toEqual([
+ { alt: "first", url: "https://cdn.example/one.png" },
+ { alt: "second", url: "https://cdn.example/two.jpg" },
+ ]);
+ });
+
+ it("rejects credentials and non-HTTPS image URLs", () => {
+ const text = [
+ "![http](http://cdn.example/image.png)",
+ "![credentials](https://user:[email protected]/image.png)",
+ "![safe](https://cdn.example/image.png)",
+ ].join("\n");
+
+ expect(collectRemoteMarkdownImages(text, 4)).toEqual([
+ { alt: "safe", url: "https://cdn.example/image.png" },
+ ]);
+ });
+
+ it("removes only successfully uploaded image URLs", () => {
+ const uploaded = "https://cdn.example/uploaded.png";
+ const failed = "https://cdn.example/failed.png";
+ const text = `before\n![uploaded](${uploaded})\n![failed](${failed})\nafter`;
+
+ expect(replaceUploadedRemoteImages(text, new Set([uploaded]))).toBe(
+ `before\nuploaded\n![failed](${failed})\nafter`,
+ );
+ });
+});
diff --git a/packages/lizi-im/src/dingtalk/api.ts b/packages/lizi-im/src/dingtalk/api.ts
index ac1af1afd3..58375ecf9f 100644
--- a/packages/lizi-im/src/dingtalk/api.ts
+++ b/packages/lizi-im/src/dingtalk/api.ts
@@ -1,10 +1,12 @@
const ACCESS_TOKEN_URL = "https://api.dingtalk.com/v1.0/oauth2/accessToken";
+const OAPI_ACCESS_TOKEN_URL = "https://oapi.dingtalk.com/gettoken";
+const OAPI_MEDIA_UPLOAD_URL = "https://oapi.dingtalk.com/media/upload";
const DOWNLOAD_URL =
"https://api.dingtalk.com/v1.0/robot/messageFiles/download";
const DIRECT_SEND_URL =
"https://api.dingtalk.com/v1.0/robot/oToMessages/batchSend";
const GROUP_SEND_URL = "https://api.dingtalk.com/v1.0/robot/groupMessages/send";
-const MAX_IMAGE_BYTES = 20 * 1024 * 1024;
+export const MAX_DINGTALK_IMAGE_BYTES = 20 * 1024 * 1024;
const MAX_MEDIA_REDIRECTS = 3;
const HTTP_TIMEOUT_MS = 30_000;
@@ -24,6 +26,7 @@ export interface DingTalkOutboundTarget {
export class DingTalkApiClient {
private accessToken: AccessTokenCache | null = null;
+ private oapiAccessToken: AccessTokenCache | null = null;
private readonly activeRequests = new Set<AbortController>();
private closed = false;
@@ -35,11 +38,13 @@ export class DingTalkApiClient {
clearAccessToken(): void {
this.accessToken = null;
+ this.oapiAccessToken = null;
}
close(): void {
this.closed = true;
this.accessToken = null;
+ this.oapiAccessToken = null;
for (const controller of this.activeRequests) controller.abort();
this.activeRequests.clear();
}
@@ -83,6 +88,54 @@ export class DingTalkApiClient {
);
}
+ async sendImage(
+ target: DingTalkOutboundTarget,
+ bytes: Uint8Array,
+ filename?: string,
+ ): Promise<void> {
+ const mediaId = await this.uploadImage(bytes, filename);
+ await this.sendUploadedImage(target, mediaId);
+ }
+
+ async uploadImage(bytes: Uint8Array, filename?: string): Promise<string> {
+ if (bytes.byteLength === 0 || bytes.byteLength > MAX_DINGTALK_IMAGE_BYTES) {
+ throw new Error("dingtalk outbound image has an invalid size");
+ }
+ const mimeType = detectImageMime(bytes);
+ if (!mimeType) throw new Error("dingtalk outbound media is not an image");
+ return this.uploadImageBytes(
+ bytes,
+ mimeType,
+ filename || `image.${extensionForMime(mimeType)}`,
+ );
+ }
+
+ async sendUploadedImage(
+ target: DingTalkOutboundTarget,
+ mediaId: string,
+ ): Promise<void> {
+ const token = await this.getAccessToken();
+ const body =
+ target.kind === "group"
+ ? {
+ robotCode: this.appKey,
+ openConversationId: target.id,
+ msgKey: "sampleImageMsg",
+ msgParam: JSON.stringify({ photoURL: `@${mediaId}` }),
+ }
+ : {
+ robotCode: this.appKey,
+ userIds: [target.id],
+ msgKey: "sampleImageMsg",
+ msgParam: JSON.stringify({ photoURL: `@${mediaId}` }),
+ };
+ await this.postJson(
+ target.kind === "group" ? GROUP_SEND_URL : DIRECT_SEND_URL,
+ body,
+ token,
+ );
+ }
+
async downloadImage(
downloadCode: string,
): Promise<{ buffer: Uint8Array; mimeType: string }> {
@@ -99,10 +152,10 @@ export class DingTalkApiClient {
if (!res.ok)
throw new Error(`dingtalk media download failed: HTTP ${res.status}`);
const declaredLength = Number(res.headers.get("content-length") ?? 0);
- if (declaredLength > MAX_IMAGE_BYTES) {
+ if (declaredLength > MAX_DINGTALK_IMAGE_BYTES) {
throw new Error("dingtalk media exceeds the image size limit");
}
- const bytes = await readBodyLimited(res, MAX_IMAGE_BYTES);
+ const bytes = await readBodyLimited(res, MAX_DINGTALK_IMAGE_BYTES);
if (bytes.byteLength === 0) {
throw new Error("dingtalk media has an invalid image size");
}
@@ -174,6 +227,64 @@ export class DingTalkApiClient {
return value;
}
+ private async getOapiAccessToken(): Promise<string> {
+ if (
+ this.oapiAccessToken &&
+ this.oapiAccessToken.expiresAt - 60_000 > Date.now()
+ ) {
+ return this.oapiAccessToken.value;
+ }
+ const url = new URL(OAPI_ACCESS_TOKEN_URL);
+ url.searchParams.set("appkey", this.appKey);
+ url.searchParams.set("appsecret", this.appSecret);
+ const res = await this.fetchWithTimeout(url, {
+ method: "GET",
+ redirect: "error",
+ });
+ const payload = (await res.json().catch(() => null)) as unknown;
+ if (!res.ok)
+ throw new Error(`dingtalk OAPI auth failed: HTTP ${res.status}`);
+ const value = stringField(payload, "access_token");
+ const errorCode = numberField(payload, "errcode");
+ if (!value || (errorCode !== null && errorCode !== 0)) {
+ throw new Error("dingtalk OAPI access token response is invalid");
+ }
+ const expiresIn = numberField(payload, "expires_in") ?? 7_200;
+ this.oapiAccessToken = {
+ value,
+ expiresAt: Date.now() + Math.max(60, expiresIn) * 1_000,
+ };
+ return value;
+ }
+
+ private async uploadImageBytes(
+ bytes: Uint8Array,
+ mimeType: string,
+ filename: string,
+ ): Promise<string> {
+ const token = await this.getOapiAccessToken();
+ const url = new URL(OAPI_MEDIA_UPLOAD_URL);
+ url.searchParams.set("access_token", token);
+ url.searchParams.set("type", "image");
+ const form = new FormData();
+ const arrayBuffer = bytes.slice().buffer as ArrayBuffer;
+ form.append("media", new Blob([arrayBuffer], { type: mimeType }), filename);
+ const res = await this.fetchWithTimeout(url, {
+ method: "POST",
+ redirect: "error",
+ body: form,
+ });
+ const payload = (await res.json().catch(() => null)) as unknown;
+ if (!res.ok)
+ throw new Error(`dingtalk media upload failed: HTTP ${res.status}`);
+ const errorCode = numberField(payload, "errcode");
+ const rawMediaId = stringField(payload, "media_id");
+ if (!rawMediaId || (errorCode !== null && errorCode !== 0)) {
+ throw new Error("dingtalk media upload response is invalid");
+ }
+ return rawMediaId.startsWith("@") ? rawMediaId.slice(1) : rawMediaId;
+ }
+
private async postJson(
url: string,
body: Record<string, unknown>,
@@ -320,3 +431,16 @@ function detectImageMime(bytes: Uint8Array): string | null {
}
return null;
}
+
+function extensionForMime(mimeType: string): string {
+ switch (mimeType) {
+ case "image/jpeg":
+ return "jpg";
+ case "image/gif":
+ return "gif";
+ case "image/webp":
+ return "webp";
+ default:
+ return "png";
+ }
+}
diff --git a/packages/lizi-im/src/dingtalk/index.ts b/packages/lizi-im/src/dingtalk/index.ts
index ad6accc2e3..e7fa67662a 100644
--- a/packages/lizi-im/src/dingtalk/index.ts
+++ b/packages/lizi-im/src/dingtalk/index.ts
@@ -1,3 +1,6 @@
+import fs from "node:fs";
+import path from "node:path";
+
import {
DWClient,
TOPIC_ROBOT,
@@ -17,6 +20,7 @@ import type {
} from "../types.js";
import {
DingTalkApiClient,
+ MAX_DINGTALK_IMAGE_BYTES,
type DingTalkFetch,
type DingTalkOutboundTarget,
} from "./api.js";
@@ -27,6 +31,10 @@ import {
parseInboundEnvelope,
type DingTalkInboundEnvelope,
} from "./inbound.js";
+import {
+ collectRemoteMarkdownImages,
+ replaceUploadedRemoteImages,
+} from "./outbound.js";
const APP_KEY_SECRET = "dingtalk-bot-app-key";
const APP_SECRET_SECRET = "dingtalk-bot-app-secret";
@@ -36,6 +44,7 @@ const DEDUP_CAPACITY = 2_048;
const STATUS_POLL_MS = 2_000;
const INTERACTION_TIMEOUT_MS = 30 * 60 * 1_000;
const OUTBOUND_CHUNK_SIZE = 3_500;
+const MAX_OUTBOUND_IMAGES = 4;
const CONNECTION_ERROR_CODES = [
"DINGTALK_AUTH_FAILED",
"DINGTALK_NETWORK_FAILED",
@@ -268,7 +277,67 @@ export class DingTalkIM extends BaseIM implements ChannelIM {
}
async commitFinal(output: ImFinalOutput): Promise<void> {
- await this.sendText(output.userId, normalizeFinalText(output.text));
+ const api = this.requireApi();
+ const target = this.resolveTarget(output.userId);
+ const uploadedMedia: Array<{ mediaId: string; fallbackUrl?: string }> = [];
+
+ for (const absPath of Array.from(new Set(output.mediaAbsPaths ?? []))) {
+ if (uploadedMedia.length >= MAX_OUTBOUND_IMAGES) break;
+ try {
+ const stat = await fs.promises.stat(absPath);
+ if (!stat.isFile() || stat.size > MAX_DINGTALK_IMAGE_BYTES) {
+ throw new Error("dingtalk outbound image has an invalid size");
+ }
+ const bytes = await fs.promises.readFile(absPath);
+ uploadedMedia.push({
+ mediaId: await api.uploadImage(bytes, path.basename(absPath)),
+ });
+ } catch {
+ this.log.warn("dingtalk outbound managed image upload failed");
+ }
+ }
+
+ const uploadedRemoteUrls = new Set<string>();
+ const fetchRemoteImage = this.host.media?.fetchRemoteImage;
+ if (fetchRemoteImage && uploadedMedia.length < MAX_OUTBOUND_IMAGES) {
+ const remoteImages = collectRemoteMarkdownImages(
+ output.text,
+ MAX_OUTBOUND_IMAGES - uploadedMedia.length,
+ );
+ for (const image of remoteImages) {
+ try {
+ const fetched = await fetchRemoteImage(
+ image.url,
+ MAX_DINGTALK_IMAGE_BYTES,
+ );
+ uploadedMedia.push({
+ mediaId: await api.uploadImage(fetched.buffer),
+ fallbackUrl: image.url,
+ });
+ uploadedRemoteUrls.add(image.url);
+ } catch {
+ this.log.warn("dingtalk outbound remote image upload failed");
+ }
+ }
+ }
+
+ const finalText = replaceUploadedRemoteImages(
+ output.text,
+ uploadedRemoteUrls,
+ );
+ await this.sendText(output.userId, normalizeFinalText(finalText));
+ const failedRemoteUrls: string[] = [];
+ for (const media of uploadedMedia) {
+ try {
+ await api.sendUploadedImage(target, media.mediaId);
+ } catch {
+ this.log.warn("dingtalk outbound image send failed");
+ if (media.fallbackUrl) failedRemoteUrls.push(media.fallbackUrl);
+ }
+ }
+ if (failedRemoteUrls.length > 0) {
+ await this.sendText(output.userId, failedRemoteUrls.join("\n"));
+ }
}
async requestTextReply<T>(
diff --git a/packages/lizi-im/src/dingtalk/outbound.ts b/packages/lizi-im/src/dingtalk/outbound.ts
new file mode 100644
index 0000000000..9a45fa18fb
--- /dev/null
+++ b/packages/lizi-im/src/dingtalk/outbound.ts
@@ -0,0 +1,44 @@
+export interface RemoteMarkdownImage {
+ alt: string;
+ url: string;
+}
+
+const REMOTE_MARKDOWN_IMAGE =
+ /!\[([^\]\r\n]{0,512})\]\((https:\/\/[^)\s]{1,2048})\)/g;
+
+function isSafePublicImageUrl(value: string): boolean {
+ try {
+ const url = new URL(value);
+ return url.protocol === "https:" && !url.username && !url.password;
+ } catch {
+ return false;
+ }
+}
+
+/** Collect unique HTTPS image references without fetching them. */
+export function collectRemoteMarkdownImages(
+ text: string,
+ limit: number,
+): RemoteMarkdownImage[] {
+ const images = new Map<string, RemoteMarkdownImage>();
+ for (const match of text.matchAll(REMOTE_MARKDOWN_IMAGE)) {
+ const url = match[2];
+ if (!isSafePublicImageUrl(url) || images.has(url)) continue;
+ images.set(url, { alt: match[1].trim(), url });
+ if (images.size >= limit) break;
+ }
+ return Array.from(images.values());
+}
+
+/**
+ * Replace only images that were successfully uploaded. Failed downloads retain
+ * the original Markdown URL as a usable fallback.
+ */
+export function replaceUploadedRemoteImages(
+ text: string,
+ uploadedUrls: ReadonlySet<string>,
+): string {
+ return text.replace(REMOTE_MARKDOWN_IMAGE, (raw, alt: string, url: string) =>
+ uploadedUrls.has(url) ? alt.trim() || "图片" : raw,
+ );
+}
diff --git a/packages/lizi-im/src/types.ts b/packages/lizi-im/src/types.ts
index 5f19cb86a8..057fc64591 100644
--- a/packages/lizi-im/src/types.ts
+++ b/packages/lizi-im/src/types.ts
@@ -98,6 +98,14 @@ export interface IMHostMediaCache {
): Promise<{ absPath: string; url: string; mimeType: string } | null>;
/** host 托管媒体 URL(cindy-media://)→ 绝对路径;认不出返回 null(出站上传用)。 */
resolveMediaUrl(url: string): string | null;
+ /**
+ * 下载公开 HTTPS 图片供 IM 出站上传。host 必须逐跳执行 SSRF / DNS
+ * rebinding 防护并在读取过程中执行 maxBytes 上限;返回字节不落盘。
+ */
+ fetchRemoteImage?(
+ url: string,
+ maxBytes: number,
+ ): Promise<{ buffer: Uint8Array; mimeType?: string }>;
}
export interface IMAttachment {