Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(im): follow trusted DingTalk media redirects
david328d9a617b14
diff --git a/packages/lizi-im/src/dingtalk/__tests__/api.test.ts b/packages/lizi-im/src/dingtalk/__tests__/api.test.tsindex 8bfe0438c0..cce3a65e19 100644--- a/packages/lizi-im/src/dingtalk/__tests__/api.test.ts+++ b/packages/lizi-im/src/dingtalk/__tests__/api.test.ts@@ -9,6 +9,10 @@ function jsonResponse(body: unknown, status = 200): Response {});}+const PNG_BYTES = Uint8Array.from([+ 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a,+]);+describe("DingTalkApiClient", () => {it("never posts to an untrusted session webhook and falls back to the fixed API", async () => {const fetcher = vi@@ -51,4 +55,61 @@ describe("DingTalkApiClient", () => {);expect(fetcher).toHaveBeenCalledTimes(2);});++ it("follows a bounded redirect between trusted DingTalk media hosts", async () => {+ const fetcher = vi+ .fn<typeof fetch>()+ .mockResolvedValueOnce(+ jsonResponse({ accessToken: "token", expireIn: 7200 }),+ )+ .mockResolvedValueOnce(+ jsonResponse({+ downloadUrl: "https://media.dingtalk.com/temporary/image",+ }),+ )+ .mockResolvedValueOnce(+ new Response(null, {+ status: 302,+ headers: {+ location: "https://download.dingtalk.com/final/image.png",+ },+ }),+ )+ .mockResolvedValueOnce(new Response(PNG_BYTES));+ const api = new DingTalkApiClient("app-key", "app-secret", fetcher);++ await expect(api.downloadImage("download-code")).resolves.toEqual({+ buffer: PNG_BYTES,+ mimeType: "image/png",+ });+ expect(fetcher.mock.calls.slice(2).map(([url]) => String(url))).toEqual([+ "https://media.dingtalk.com/temporary/image",+ "https://download.dingtalk.com/final/image.png",+ ]);+ });++ it("rejects a trusted media URL that redirects outside the allowlist", async () => {+ const fetcher = vi+ .fn<typeof fetch>()+ .mockResolvedValueOnce(+ jsonResponse({ accessToken: "token", expireIn: 7200 }),+ )+ .mockResolvedValueOnce(+ jsonResponse({+ downloadUrl: "https://media.dingtalk.com/temporary/image",+ }),+ )+ .mockResolvedValueOnce(+ new Response(null, {+ status: 302,+ headers: { location: "https://example.invalid/collect" },+ }),+ );+ const api = new DingTalkApiClient("app-key", "app-secret", fetcher);++ await expect(api.downloadImage("download-code")).rejects.toThrow(+ /untrusted URL/,+ );+ expect(fetcher).toHaveBeenCalledTimes(3);+ });});diff --git a/packages/lizi-im/src/dingtalk/api.ts b/packages/lizi-im/src/dingtalk/api.tsindex a1f58cc825..ac1af1afd3 100644--- a/packages/lizi-im/src/dingtalk/api.ts+++ b/packages/lizi-im/src/dingtalk/api.ts@@ -5,6 +5,7 @@ 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;+const MAX_MEDIA_REDIRECTS = 3;const HTTP_TIMEOUT_MS = 30_000;export type DingTalkFetch = typeof fetch;@@ -94,12 +95,7 @@ export class DingTalkApiClient {const downloadUrl = stringField(response, "downloadUrl");if (!downloadUrl)throw new Error("dingtalk media response missing downloadUrl");- const parsed = new URL(downloadUrl);- if (!isAllowedMediaHost(parsed)) {- throw new Error("dingtalk media response returned an untrusted URL");- }-- const res = await this.fetchWithTimeout(downloadUrl, { redirect: "error" });+ const res = await this.fetchTrustedMedia(downloadUrl);if (!res.ok)throw new Error(`dingtalk media download failed: HTTP ${res.status}`);const declaredLength = Number(res.headers.get("content-length") ?? 0);@@ -117,6 +113,29 @@ export class DingTalkApiClient {return { buffer: bytes, mimeType };}+ private async fetchTrustedMedia(downloadUrl: string): Promise<Response> {+ let currentUrl = new URL(downloadUrl);+ for (let redirects = 0; redirects <= MAX_MEDIA_REDIRECTS; redirects += 1) {+ if (!isAllowedMediaHost(currentUrl)) {+ throw new Error("dingtalk media response returned an untrusted URL");+ }+ const response = await this.fetchWithTimeout(currentUrl, {+ redirect: "manual",+ });+ if (!isRedirectResponse(response)) return response;+ const location = response.headers.get("location");+ await response.body?.cancel();+ if (!location) {+ throw new Error("dingtalk media redirect is missing a location");+ }+ if (redirects === MAX_MEDIA_REDIRECTS) {+ throw new Error("dingtalk media response has too many redirects");+ }+ currentUrl = new URL(location, currentUrl);+ }+ throw new Error("dingtalk media response has too many redirects");+ }+private isWebhookUsable(target: DingTalkOutboundTarget): boolean {if (!target.sessionWebhook) return false;let url: URL;@@ -217,6 +236,10 @@ function isAllowedMediaHost(url: URL): boolean {);}+function isRedirectResponse(response: Response): boolean {+ return [301, 302, 303, 307, 308].includes(response.status);+}+function isRecord(value: unknown): value is Record<string, unknown> {return Boolean(value) && typeof value === "object" && !Array.isArray(value);}