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(im): harden DingTalk uploads and reconnect

david66a3722d1b63
diff --git a/packages/lizi-im/src/dingtalk/__tests__/api.test.ts b/packages/lizi-im/src/dingtalk/__tests__/api.test.ts
index 74d59625e0..a8b8a401b5 100644
--- a/packages/lizi-im/src/dingtalk/__tests__/api.test.ts
+++ b/packages/lizi-im/src/dingtalk/__tests__/api.test.ts
@@ -1,3 +1,5 @@
+import { Buffer } from "node:buffer";
+
import { describe, expect, it, vi } from "vitest";
import { DingTalkApiClient } from "../api.js";
@@ -64,6 +66,49 @@ describe("DingTalkApiClient", () => {
});
});
+ it("uploads only the visible bytes from a Node Buffer view", async () => {
+ const backing = Buffer.from([0xde, 0xad, ...PNG_BYTES, 0xbe, 0xef]);
+ const imageView = backing.subarray(2, 2 + PNG_BYTES.byteLength);
+ 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")) {
+ const form = init?.body as FormData;
+ const media = form.get("media");
+ expect(media).toBeInstanceOf(Blob);
+ expect(
+ Array.from(new Uint8Array(await (media as Blob).arrayBuffer())),
+ ).toEqual(Array.from(PNG_BYTES));
+ 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,
+ },
+ imageView,
+ "picture.png",
+ );
+ });
+
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);
diff --git a/packages/lizi-im/src/dingtalk/__tests__/dingtalkIM.test.ts b/packages/lizi-im/src/dingtalk/__tests__/dingtalkIM.test.ts
index 0e3c3f8c94..3ee525513a 100644
--- a/packages/lizi-im/src/dingtalk/__tests__/dingtalkIM.test.ts
+++ b/packages/lizi-im/src/dingtalk/__tests__/dingtalkIM.test.ts
@@ -498,6 +498,42 @@ describe("DingTalkIM", () => {
});
});
+ it("publishes an error status when manual reconnect fails", async () => {
+ const { host, handlers, broadcasts } = makeHost();
+ const client = new FakeClient();
+ const fetcher = validCredentialFetcher();
+ const im = new DingTalkIM(host, {
+ clientFactory: () => client,
+ fetcher,
+ });
+ im.registerIpc();
+ await im.init();
+ fetcher.mockResolvedValueOnce(
+ new Response(JSON.stringify({ code: "InvalidParameter" }), {
+ status: 401,
+ }),
+ );
+ const reconnect = handlers.get("dingtalkBot:reconnect");
+
+ expect(reconnect).toBeTypeOf("function");
+ await expect(Promise.resolve(reconnect?.())).rejects.toThrow(
+ /DINGTALK_AUTH_FAILED/,
+ );
+ expect(im.getPublicState().status).toEqual({
+ kind: "error",
+ reason: "DINGTALK_AUTH_FAILED",
+ });
+ expect(broadcasts.at(-1)).toEqual({
+ channel: "dingtalkBot:status-change",
+ payload: {
+ status: {
+ kind: "error",
+ reason: "DINGTALK_AUTH_FAILED",
+ },
+ },
+ });
+ });
+
it("classifies a Stream socket that never opens", async () => {
const { host } = makeHost();
const client = new FakeClient();
diff --git a/packages/lizi-im/src/dingtalk/api.ts b/packages/lizi-im/src/dingtalk/api.ts
index e453bbe552..4e236fdd9e 100644
--- a/packages/lizi-im/src/dingtalk/api.ts
+++ b/packages/lizi-im/src/dingtalk/api.ts
@@ -282,7 +282,9 @@ export class DingTalkApiClient {
url.searchParams.set("access_token", token);
url.searchParams.set("type", "image");
const form = new FormData();
- const arrayBuffer = bytes.slice().buffer as ArrayBuffer;
+ // Buffer.slice() keeps sharing its pooled backing store. Copy the visible
+ // view so multipart uploads cannot include bytes outside byteOffset/length.
+ const arrayBuffer = new Uint8Array(bytes).buffer;
form.append("media", new Blob([arrayBuffer], { type: mimeType }), filename);
const res = await this.fetchWithTimeout(url, {
method: "POST",
diff --git a/packages/lizi-im/src/dingtalk/index.ts b/packages/lizi-im/src/dingtalk/index.ts
index 84fcf70b82..21b11b19c0 100644
--- a/packages/lizi-im/src/dingtalk/index.ts
+++ b/packages/lizi-im/src/dingtalk/index.ts
@@ -174,7 +174,15 @@ export class DingTalkIM extends BaseIM implements ChannelIM {
return this.runInAccountScope(async () => {
const credentials = this.readCredentials();
if (!credentials) throw new Error("DINGTALK_CREDENTIALS_MISSING");
- await this.connect(credentials);
+ try {
+ await this.connect(credentials);
+ } catch (error) {
+ this.setStatus({
+ kind: "error",
+ reason: safeConnectionError(error),
+ });
+ throw error;
+ }
return this.getPublicState();
});
});