22// Runs after install to keep packaged dist safe and compatible.
33// Keep packaged dist safe and compatible. Plugin package dependencies are
44// installed only by explicit plugin install/update flows, never postinstall.
5- import { randomUUID } from "node:crypto" ;
65import {
7- chmodSync ,
8- closeSync ,
96 existsSync ,
107 lstatSync ,
118 opendirSync ,
12- openSync ,
139 readdirSync ,
1410 readFileSync ,
1511 readlinkSync ,
1612 realpathSync ,
17- renameSync ,
1813 rmdirSync ,
1914 rmSync ,
2015 unlinkSync ,
21- writeFileSync ,
2216} from "node:fs" ;
2317import { homedir } from "node:os" ;
2418import { basename , dirname , isAbsolute , join , relative , resolve as pathResolve } from "node:path" ;
@@ -36,81 +30,6 @@ const DIST_INVENTORY_PATH = "dist/postinstall-inventory.json";
3630// pathological/unbounded trees.
3731export const MAX_INSTALLED_DIST_SCAN_ENTRIES = 100_000 ;
3832const LEGACY_PLUGIN_RUNTIME_DEPS_DIR = "plugin-runtime-deps" ;
39- const BAILEYS_MEDIA_FILE = join ( "node_modules" , "baileys" , "lib" , "Utils" , "messages-media.js" ) ;
40- const BAILEYS_MEDIA_HOTFIX_NEEDLE = [
41- " encFileWriteStream.write(mac);" ,
42- " encFileWriteStream.end();" ,
43- " originalFileStream?.end?.();" ,
44- " stream.destroy();" ,
45- " logger?.debug('encrypted data successfully');" ,
46- ] . join ( "\n" ) ;
47- const BAILEYS_MEDIA_HOTFIX_REPLACEMENT = [
48- " encFileWriteStream.write(mac);" ,
49- " const encFinishPromise = once(encFileWriteStream, 'finish');" ,
50- " const originalFinishPromise = originalFileStream ? once(originalFileStream, 'finish') : Promise.resolve();" ,
51- " encFileWriteStream.end();" ,
52- " originalFileStream?.end?.();" ,
53- " stream.destroy();" ,
54- " await Promise.all([encFinishPromise, originalFinishPromise]);" ,
55- " logger?.debug('encrypted data successfully');" ,
56- ] . join ( "\n" ) ;
57- const BAILEYS_MEDIA_HOTFIX_SEQUENTIAL_REPLACEMENT = [
58- " encFileWriteStream.write(mac);" ,
59- " const encFinishPromise = once(encFileWriteStream, 'finish');" ,
60- " const originalFinishPromise = originalFileStream ? once(originalFileStream, 'finish') : Promise.resolve();" ,
61- " encFileWriteStream.end();" ,
62- " originalFileStream?.end?.();" ,
63- " stream.destroy();" ,
64- " await encFinishPromise;" ,
65- " await originalFinishPromise;" ,
66- " logger?.debug('encrypted data successfully');" ,
67- ] . join ( "\n" ) ;
68- const BAILEYS_MEDIA_HOTFIX_FINISH_PROMISES_RE =
69- / c o n s t \s + e n c F i n i s h P r o m i s e \s * = \s * o n c e \( e n c F i l e W r i t e S t r e a m , \s * ' f i n i s h ' \) ; \s * \n [ \s \S ] * c o n s t \s + o r i g i n a l F i n i s h P r o m i s e \s * = \s * o r i g i n a l F i l e S t r e a m \s * \? \s * o n c e \( o r i g i n a l F i l e S t r e a m , \s * ' f i n i s h ' \) \s * : \s * P r o m i s e \. r e s o l v e \( \) ; / u;
70- const BAILEYS_MEDIA_HOTFIX_PROMISE_ALL_RE =
71- / a w a i t \s + P r o m i s e \. a l l \( \[ \s * e n c F i n i s h P r o m i s e \s * , \s * o r i g i n a l F i n i s h P r o m i s e \s * \] \) ; / u;
72- const BAILEYS_MEDIA_HOTFIX_SEQUENTIAL_AWAITS_RE =
73- / a w a i t \s + e n c F i n i s h P r o m i s e ; \s * (?: \/ \/ [ ^ \n ] * \n | \s ) * a w a i t \s + o r i g i n a l F i n i s h P r o m i s e ; / u;
74- const BAILEYS_MEDIA_DISPATCHER_NEEDLE = [
75- " const response = await fetch(url, {" ,
76- " dispatcher: fetchAgent," ,
77- " method: 'POST'," ,
78- ] . join ( "\n" ) ;
79- const BAILEYS_MEDIA_DISPATCHER_REPLACEMENT = [
80- " const response = await fetch(url, {" ,
81- " method: 'POST'," ,
82- ] . join ( "\n" ) ;
83- const BAILEYS_MEDIA_DISPATCHER_HEADER_NEEDLE = [
84- " 'Content-Type': 'application/octet-stream'," ,
85- " Origin: DEFAULT_ORIGIN" ,
86- " }," ,
87- ] . join ( "\n" ) ;
88- const BAILEYS_MEDIA_DISPATCHER_HEADER_REPLACEMENT = [
89- " 'Content-Type': 'application/octet-stream'," ,
90- " Origin: DEFAULT_ORIGIN" ,
91- " }," ,
92- " // Baileys passes a generic agent here in some runtimes. Undici's" ,
93- " // `dispatcher` only works with Dispatcher-compatible implementations," ,
94- " // so only wire it through when the object actually implements" ,
95- " // `dispatch`." ,
96- " ...(typeof fetchAgent?.dispatch === 'function' ? { dispatcher: fetchAgent } : {})," ,
97- ] . join ( "\n" ) ;
98- const BAILEYS_MEDIA_UPLOAD_WITH_FETCH_DISPATCHER_NEEDLE = [
99- " const response = await fetch(url, {" ,
100- " dispatcher: agent," ,
101- " method: 'POST'," ,
102- ] . join ( "\n" ) ;
103- const BAILEYS_MEDIA_UPLOAD_WITH_FETCH_DISPATCHER_REPLACEMENT = [
104- " const response = await fetch(url, {" ,
105- " // Baileys may pass a generic agent in some runtimes. Undici's dispatcher" ,
106- " // option only accepts Dispatcher-compatible implementations, so only wire" ,
107- " // it through when the object actually implements dispatch." ,
108- " ...(typeof agent?.dispatch === 'function' ? { dispatcher: agent } : {})," ,
109- " method: 'POST'," ,
110- ] . join ( "\n" ) ;
111- const BAILEYS_MEDIA_ONCE_IMPORT_RE = / i m p o r t \s + \{ \s * o n c e \s * \} \s + f r o m \s + [ ' " ] e v e n t s [ ' " ] / u;
112- const BAILEYS_MEDIA_ASYNC_CONTEXT_RE =
113- / a s y n c \s + f u n c t i o n \s + e n c r y p t e d S t r e a m | e n c r y p t e d S t r e a m \s * = \s * a s y n c / u;
11433class InstalledDistScanLimitError extends Error { }
11534
11635function normalizeRelativePath ( filePath ) {
@@ -633,175 +552,6 @@ export function pruneInstalledPackageDist(params = {}) {
633552 return removed ;
634553}
635554
636- export function applyBaileysEncryptedStreamFinishHotfix ( params = { } ) {
637- const packageRoot = params . packageRoot ?? DEFAULT_PACKAGE_ROOT ;
638- const pathExists = params . existsSync ?? existsSync ;
639- const pathLstat = params . lstatSync ?? lstatSync ;
640- const readFile = params . readFileSync ?? readFileSync ;
641- const resolveRealPath = params . realpathSync ?? realpathSync ;
642- const chmodFile = params . chmodSync ?? chmodSync ;
643- const openFile = params . openSync ?? openSync ;
644- const closeFile = params . closeSync ?? closeSync ;
645- const renameFile = params . renameSync ?? renameSync ;
646- const removePath = params . rmSync ?? rmSync ;
647- const createTempPath =
648- params . createTempPath ??
649- ( ( unsafeTargetPath ) =>
650- join (
651- dirname ( unsafeTargetPath ) ,
652- `.${ basename ( unsafeTargetPath ) } .openclaw-hotfix-${ randomUUID ( ) } ` ,
653- ) ) ;
654- const writeFile =
655- params . writeFileSync ?? ( ( filePath , value ) => writeFileSync ( filePath , value , "utf8" ) ) ;
656- const targetPath = join ( packageRoot , BAILEYS_MEDIA_FILE ) ;
657- const nodeModulesRoot = join ( packageRoot , "node_modules" ) ;
658-
659- function validateTargetPath ( ) {
660- if ( ! pathExists ( targetPath ) ) {
661- return { ok : false , reason : "missing" } ;
662- }
663-
664- const targetStats = pathLstat ( targetPath ) ;
665- if ( ! targetStats . isFile ( ) || targetStats . isSymbolicLink ( ) ) {
666- return { ok : false , reason : "unsafe_target" , targetPath } ;
667- }
668-
669- const nodeModulesRootReal = resolveRealPath ( nodeModulesRoot ) ;
670- const targetPathReal = resolveRealPath ( targetPath ) ;
671- const relativeTargetPath = relative ( nodeModulesRootReal , targetPathReal ) ;
672- if ( relativeTargetPath . startsWith ( ".." ) || isAbsolute ( relativeTargetPath ) ) {
673- return { ok : false , reason : "path_escape" , targetPath } ;
674- }
675-
676- return { ok : true , targetPathReal, mode : targetStats . mode & 0o777 } ;
677- }
678-
679- try {
680- const initialTargetValidation = validateTargetPath ( ) ;
681- if ( ! initialTargetValidation . ok ) {
682- return { applied : false , reason : initialTargetValidation . reason , targetPath } ;
683- }
684-
685- const currentText = readFile ( targetPath , "utf8" ) ;
686- let patchedText = currentText ;
687- let applied = false ;
688-
689- const encryptedStreamAlreadyPatched =
690- patchedText . includes ( BAILEYS_MEDIA_HOTFIX_REPLACEMENT ) ||
691- patchedText . includes ( BAILEYS_MEDIA_HOTFIX_SEQUENTIAL_REPLACEMENT ) ||
692- ( BAILEYS_MEDIA_HOTFIX_FINISH_PROMISES_RE . test ( patchedText ) &&
693- ( BAILEYS_MEDIA_HOTFIX_PROMISE_ALL_RE . test ( patchedText ) ||
694- BAILEYS_MEDIA_HOTFIX_SEQUENTIAL_AWAITS_RE . test ( patchedText ) ) ) ;
695- const encryptedStreamPatchable = patchedText . includes ( BAILEYS_MEDIA_HOTFIX_NEEDLE ) ;
696-
697- let encryptedStreamResolved = encryptedStreamAlreadyPatched ;
698- if ( ! encryptedStreamResolved && encryptedStreamPatchable ) {
699- if ( ! BAILEYS_MEDIA_ONCE_IMPORT_RE . test ( patchedText ) ) {
700- return { applied : false , reason : "missing_once_import" , targetPath } ;
701- }
702- if ( ! BAILEYS_MEDIA_ASYNC_CONTEXT_RE . test ( patchedText ) ) {
703- return { applied : false , reason : "not_async_context" , targetPath } ;
704- }
705- patchedText = patchedText . replace (
706- BAILEYS_MEDIA_HOTFIX_NEEDLE ,
707- BAILEYS_MEDIA_HOTFIX_REPLACEMENT ,
708- ) ;
709- applied = true ;
710- encryptedStreamResolved = true ;
711- }
712-
713- const dispatcherAlreadyPatched =
714- patchedText . includes (
715- "...(typeof fetchAgent?.dispatch === 'function' ? { dispatcher: fetchAgent } : {})," ,
716- ) ||
717- patchedText . includes (
718- "...(typeof agent?.dispatch === 'function' ? { dispatcher: agent } : {})," ,
719- ) ||
720- ( patchedText . includes (
721- "const dispatcher = typeof agent?.dispatch === 'function' ? agent : undefined;" ,
722- ) &&
723- patchedText . includes ( "...(dispatcher ? { dispatcher } : {})," ) ) ;
724- const legacyDispatcherPatchable =
725- patchedText . includes ( BAILEYS_MEDIA_DISPATCHER_NEEDLE ) &&
726- patchedText . includes ( BAILEYS_MEDIA_DISPATCHER_HEADER_NEEDLE ) ;
727- const uploadWithFetchDispatcherPatchable = patchedText . includes (
728- BAILEYS_MEDIA_UPLOAD_WITH_FETCH_DISPATCHER_NEEDLE ,
729- ) ;
730- let dispatcherResolved = dispatcherAlreadyPatched ;
731-
732- if ( ! dispatcherResolved && legacyDispatcherPatchable ) {
733- patchedText = patchedText
734- . replace ( BAILEYS_MEDIA_DISPATCHER_NEEDLE , BAILEYS_MEDIA_DISPATCHER_REPLACEMENT )
735- . replace (
736- BAILEYS_MEDIA_DISPATCHER_HEADER_NEEDLE ,
737- BAILEYS_MEDIA_DISPATCHER_HEADER_REPLACEMENT ,
738- ) ;
739- applied = true ;
740- dispatcherResolved = true ;
741- }
742-
743- if ( ! dispatcherResolved && uploadWithFetchDispatcherPatchable ) {
744- patchedText = patchedText . replace (
745- BAILEYS_MEDIA_UPLOAD_WITH_FETCH_DISPATCHER_NEEDLE ,
746- BAILEYS_MEDIA_UPLOAD_WITH_FETCH_DISPATCHER_REPLACEMENT ,
747- ) ;
748- applied = true ;
749- dispatcherResolved = true ;
750- }
751-
752- if ( ! dispatcherResolved ) {
753- return { applied : false , reason : "unexpected_content" , targetPath } ;
754- }
755-
756- if ( ! applied ) {
757- return { applied : false , reason : "already_patched" } ;
758- }
759- const tempPath = createTempPath ( targetPath ) ;
760- const tempFd = openFile ( tempPath , "wx" , initialTargetValidation . mode ) ;
761- let tempFdClosed = false ;
762- try {
763- writeFile ( tempFd , patchedText , "utf8" ) ;
764- closeFile ( tempFd ) ;
765- tempFdClosed = true ;
766- const finalTargetValidation = validateTargetPath ( ) ;
767- if ( ! finalTargetValidation . ok ) {
768- return { applied : false , reason : finalTargetValidation . reason , targetPath } ;
769- }
770- renameFile ( tempPath , targetPath ) ;
771- chmodFile ( targetPath , initialTargetValidation . mode ) ;
772- } finally {
773- if ( ! tempFdClosed ) {
774- try {
775- closeFile ( tempFd ) ;
776- } catch {
777- // ignore failed-open cleanup
778- }
779- }
780- removePath ( tempPath , { force : true } ) ;
781- }
782- return { applied : true , reason : "patched" , targetPath } ;
783- } catch ( error ) {
784- return {
785- applied : false ,
786- reason : "error" ,
787- targetPath,
788- error : error instanceof Error ? error . message : String ( error ) ,
789- } ;
790- }
791- }
792-
793- function applyBundledPluginRuntimeHotfixes ( params = { } ) {
794- const log = params . log ?? console ;
795- const baileysResult = applyBaileysEncryptedStreamFinishHotfix ( params ) ;
796- if ( baileysResult . applied ) {
797- log . log ( "[postinstall] patched baileys runtime hotfixes" ) ;
798- return ;
799- }
800- if ( baileysResult . reason !== "missing" && baileysResult . reason !== "already_patched" ) {
801- log . warn ( `[postinstall] could not patch baileys runtime hotfixes: ${ baileysResult . reason } ` ) ;
802- }
803- }
804-
805555function resolveDistModuleUrl ( packageRoot , distPath ) {
806556 return pathToFileURL ( join ( packageRoot , distPath ) ) . href ;
807557}
@@ -893,20 +643,9 @@ export function pruneBundledPluginSourceNodeModules(params = {}) {
893643 }
894644}
895645
896- function shouldRunBundledPluginPostinstall ( params ) {
897- if ( params . env ?. [ DISABLE_POSTINSTALL_ENV ] ?. trim ( ) ) {
898- return false ;
899- }
900- if ( ! params . existsSync ( params . extensionsDir ) ) {
901- return false ;
902- }
903- return true ;
904- }
905-
906646export function runBundledPluginPostinstall ( params = { } ) {
907647 const env = params . env ?? process . env ;
908648 const packageRoot = params . packageRoot ?? DEFAULT_PACKAGE_ROOT ;
909- const extensionsDir = params . extensionsDir ?? join ( packageRoot , "dist" , "extensions" ) ;
910649 const pathExists = params . existsSync ?? existsSync ;
911650 const log = params . log ?? console ;
912651 if ( env ?. [ DISABLE_POSTINSTALL_ENV ] ?. trim ( ) ) {
@@ -923,13 +662,6 @@ export function runBundledPluginPostinstall(params = {}) {
923662 } catch ( e ) {
924663 log . warn ( `[postinstall] could not prune bundled plugin source node_modules: ${ String ( e ) } ` ) ;
925664 }
926- applyBundledPluginRuntimeHotfixes ( {
927- packageRoot,
928- existsSync : pathExists ,
929- readFileSync : params . readFileSync ,
930- writeFileSync : params . writeFileSync ,
931- log,
932- } ) ;
933665 return ;
934666 }
935667 pruneLegacyPluginRuntimeDepsState ( {
@@ -951,23 +683,6 @@ export function runBundledPluginPostinstall(params = {}) {
951683 rmSync : params . rmSync ,
952684 log,
953685 } ) ;
954- if (
955- ! shouldRunBundledPluginPostinstall ( {
956- env,
957- extensionsDir,
958- packageRoot,
959- existsSync : pathExists ,
960- } )
961- ) {
962- return ;
963- }
964- applyBundledPluginRuntimeHotfixes ( {
965- packageRoot,
966- existsSync : pathExists ,
967- readFileSync : params . readFileSync ,
968- writeFileSync : params . writeFileSync ,
969- log,
970- } ) ;
971686}
972687
973688export function isDirectPostinstallInvocation ( params = { } ) {
0 commit comments