Skip to content

Commit 6d1a716

Browse files
committed
fix(whatsapp): support Baileys rc10 postinstall patch
1 parent 0496063 commit 6d1a716

2 files changed

Lines changed: 127 additions & 5 deletions

File tree

‎scripts/postinstall-bundled-plugins.mjs‎

Lines changed: 34 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -96,6 +96,19 @@ const BAILEYS_MEDIA_DISPATCHER_HEADER_REPLACEMENT = [
9696
" // `dispatch`.",
9797
" ...(typeof fetchAgent?.dispatch === 'function' ? { dispatcher: fetchAgent } : {}),",
9898
].join("\n");
99+
const BAILEYS_MEDIA_UPLOAD_WITH_FETCH_DISPATCHER_NEEDLE = [
100+
" const response = await fetch(url, {",
101+
" dispatcher: agent,",
102+
" method: 'POST',",
103+
].join("\n");
104+
const BAILEYS_MEDIA_UPLOAD_WITH_FETCH_DISPATCHER_REPLACEMENT = [
105+
" const response = await fetch(url, {",
106+
" // Baileys may pass a generic agent in some runtimes. Undici's dispatcher",
107+
" // option only accepts Dispatcher-compatible implementations, so only wire",
108+
" // it through when the object actually implements dispatch.",
109+
" ...(typeof agent?.dispatch === 'function' ? { dispatcher: agent } : {}),",
110+
" method: 'POST',",
111+
].join("\n");
99112
const BAILEYS_MEDIA_ONCE_IMPORT_RE = /import\s+\{\s*once\s*\}\s+from\s+['"]events['"]/u;
100113
const BAILEYS_MEDIA_ASYNC_CONTEXT_RE =
101114
/async\s+function\s+encryptedStream|encryptedStream\s*=\s*async/u;
@@ -639,15 +652,22 @@ export function applyBaileysEncryptedStreamFinishHotfix(params = {}) {
639652
encryptedStreamResolved = true;
640653
}
641654

642-
const dispatcherAlreadyPatched = patchedText.includes(
643-
"...(typeof fetchAgent?.dispatch === 'function' ? { dispatcher: fetchAgent } : {}),",
644-
);
645-
const dispatcherPatchable =
655+
const dispatcherAlreadyPatched =
656+
patchedText.includes(
657+
"...(typeof fetchAgent?.dispatch === 'function' ? { dispatcher: fetchAgent } : {}),",
658+
) ||
659+
patchedText.includes(
660+
"...(typeof agent?.dispatch === 'function' ? { dispatcher: agent } : {}),",
661+
);
662+
const legacyDispatcherPatchable =
646663
patchedText.includes(BAILEYS_MEDIA_DISPATCHER_NEEDLE) &&
647664
patchedText.includes(BAILEYS_MEDIA_DISPATCHER_HEADER_NEEDLE);
665+
const uploadWithFetchDispatcherPatchable = patchedText.includes(
666+
BAILEYS_MEDIA_UPLOAD_WITH_FETCH_DISPATCHER_NEEDLE,
667+
);
648668
let dispatcherResolved = dispatcherAlreadyPatched;
649669

650-
if (!dispatcherResolved && dispatcherPatchable) {
670+
if (!dispatcherResolved && legacyDispatcherPatchable) {
651671
patchedText = patchedText
652672
.replace(BAILEYS_MEDIA_DISPATCHER_NEEDLE, BAILEYS_MEDIA_DISPATCHER_REPLACEMENT)
653673
.replace(
@@ -658,6 +678,15 @@ export function applyBaileysEncryptedStreamFinishHotfix(params = {}) {
658678
dispatcherResolved = true;
659679
}
660680

681+
if (!dispatcherResolved && uploadWithFetchDispatcherPatchable) {
682+
patchedText = patchedText.replace(
683+
BAILEYS_MEDIA_UPLOAD_WITH_FETCH_DISPATCHER_NEEDLE,
684+
BAILEYS_MEDIA_UPLOAD_WITH_FETCH_DISPATCHER_REPLACEMENT,
685+
);
686+
applied = true;
687+
dispatcherResolved = true;
688+
}
689+
661690
if (!dispatcherResolved) {
662691
return { applied: false, reason: "unexpected_content", targetPath };
663692
}

‎test/scripts/postinstall-bundled-plugins.test.ts‎

Lines changed: 93 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import { tmpdir } from "node:os";
44
import path from "node:path";
55
import { describe, expect, it, vi } from "vitest";
66
import {
7+
applyBaileysEncryptedStreamFinishHotfix,
78
collectLegacyPluginRuntimeDepsStateRoots,
89
isSourceCheckoutRoot,
910
isDirectPostinstallInvocation,
@@ -58,6 +59,21 @@ async function writePluginPackage(
5859
}
5960
}
6061

62+
async function writeBaileysMediaFile(packageRoot: string, text: string) {
63+
const mediaFile = path.join(
64+
packageRoot,
65+
"node_modules",
66+
"@whiskeysockets",
67+
"baileys",
68+
"lib",
69+
"Utils",
70+
"messages-media.js",
71+
);
72+
await fs.mkdir(path.dirname(mediaFile), { recursive: true });
73+
await fs.writeFile(mediaFile, text);
74+
return mediaFile;
75+
}
76+
6177
describe("bundled plugin postinstall", () => {
6278
function existsSyncWithoutGlobalCompileCache(value: string) {
6379
if (path.resolve(value) === path.join(tmpdir(), "node-compile-cache")) {
@@ -206,6 +222,83 @@ describe("bundled plugin postinstall", () => {
206222
expect(warn).not.toHaveBeenCalled();
207223
});
208224

225+
it("patches the Baileys rc10 upload helper dispatcher guard", async () => {
226+
const packageRoot = await createTempDirAsync("openclaw-baileys-postinstall-");
227+
const mediaFile = await writeBaileysMediaFile(
228+
packageRoot,
229+
[
230+
"import { once } from 'events';",
231+
"const encryptedStream = async () => {",
232+
" encFileWriteStream.write(mac);",
233+
" const encFinishPromise = once(encFileWriteStream, 'finish');",
234+
" const originalFinishPromise = originalFileStream ? once(originalFileStream, 'finish') : Promise.resolve();",
235+
" encFileWriteStream.end();",
236+
" originalFileStream?.end?.();",
237+
" stream.destroy();",
238+
" await encFinishPromise;",
239+
" await originalFinishPromise;",
240+
" logger?.debug('encrypted data successfully');",
241+
"};",
242+
"const uploadWithFetch = async ({ url, filePath, headers, timeoutMs, agent }) => {",
243+
" const nodeStream = createReadStream(filePath);",
244+
" const webStream = Readable.toWeb(nodeStream);",
245+
" const response = await fetch(url, {",
246+
" dispatcher: agent,",
247+
" method: 'POST',",
248+
" body: webStream,",
249+
" headers,",
250+
" duplex: 'half',",
251+
" signal: timeoutMs ? AbortSignal.timeout(timeoutMs) : undefined",
252+
" });",
253+
"};",
254+
"",
255+
].join("\n"),
256+
);
257+
258+
expect(applyBaileysEncryptedStreamFinishHotfix({ packageRoot })).toMatchObject({
259+
applied: true,
260+
reason: "patched",
261+
});
262+
const patchedText = await fs.readFile(mediaFile, "utf8");
263+
expect(patchedText).toContain(
264+
"...(typeof agent?.dispatch === 'function' ? { dispatcher: agent } : {}),",
265+
);
266+
expect(patchedText).not.toContain(" dispatcher: agent,");
267+
});
268+
269+
it("recognizes already patched Baileys rc10 upload helpers", async () => {
270+
const packageRoot = await createTempDirAsync("openclaw-baileys-postinstall-");
271+
await writeBaileysMediaFile(
272+
packageRoot,
273+
[
274+
"import { once } from 'events';",
275+
"const encryptedStream = async () => {",
276+
" encFileWriteStream.write(mac);",
277+
" const encFinishPromise = once(encFileWriteStream, 'finish');",
278+
" const originalFinishPromise = originalFileStream ? once(originalFileStream, 'finish') : Promise.resolve();",
279+
" encFileWriteStream.end();",
280+
" originalFileStream?.end?.();",
281+
" stream.destroy();",
282+
" await encFinishPromise;",
283+
" await originalFinishPromise;",
284+
" logger?.debug('encrypted data successfully');",
285+
"};",
286+
"const uploadWithFetch = async ({ url, filePath, headers, timeoutMs, agent }) => {",
287+
" const response = await fetch(url, {",
288+
" ...(typeof agent?.dispatch === 'function' ? { dispatcher: agent } : {}),",
289+
" method: 'POST',",
290+
" });",
291+
"};",
292+
"",
293+
].join("\n"),
294+
);
295+
296+
expect(applyBaileysEncryptedStreamFinishHotfix({ packageRoot })).toMatchObject({
297+
applied: false,
298+
reason: "already_patched",
299+
});
300+
});
301+
209302
it("does not classify published packages with source files as source checkouts", () => {
210303
const packageRoot = "/pkg";
211304
const existingPaths = new Set([

0 commit comments

Comments
 (0)