Vencord/src/webpack/patchWebpack.ts

357 lines
14 KiB
TypeScript
Raw Normal View History

2022-10-21 23:17:06 +00:00
/*
2024-05-20 01:49:58 +00:00
* Vencord, a Discord client mod
* Copyright (c) 2024 Vendicated and contributors
* SPDX-License-Identifier: GPL-3.0-or-later
*/
2024-05-23 09:04:21 +00:00
import { Settings } from "@api/Settings";
2023-05-05 23:36:00 +00:00
import { Logger } from "@utils/Logger";
2024-05-24 08:14:27 +00:00
import { canonicalizeReplacement } from "@utils/patches";
import { PatchReplacement } from "@utils/types";
import { traceFunction } from "../debug/Tracer";
import { patches } from "../plugins";
2024-05-24 08:14:27 +00:00
import { _initWebpack, factoryListeners, ModuleFactory, moduleListeners, subscriptions, WebpackRequire, wreq } from ".";
type PatchedModuleFactory = ModuleFactory & {
$$vencordOriginal?: ModuleFactory;
};
2024-05-24 10:59:56 +00:00
type PatchedModuleFactories = Record<PropertyKey, PatchedModuleFactory>;
const logger = new Logger("WebpackInterceptor", "#8caaee");
2022-08-29 00:25:27 +00:00
/** A set with all the module factories objects */
2024-05-24 08:14:27 +00:00
const allModuleFactories = new Set<PatchedModuleFactories>();
2024-05-23 09:04:21 +00:00
2024-05-24 08:14:27 +00:00
function defineModuleFactoryGetter(modulesFactories: PatchedModuleFactories, id: PropertyKey, factory: PatchedModuleFactory) {
2024-05-24 06:09:25 +00:00
Object.defineProperty(modulesFactories, id, {
2024-05-24 08:14:27 +00:00
configurable: true,
enumerable: true,
get() {
// $$vencordOriginal means the factory is already patched
if (factory.$$vencordOriginal != null) {
return factory;
}
2024-05-23 09:04:21 +00:00
// This patches factories if eagerPatches are disabled
return (factory = patchFactory(id, factory));
},
set(v: ModuleFactory) {
if (factory.$$vencordOriginal != null) {
factory.$$vencordOriginal = v;
} else {
factory = v;
}
2024-05-24 08:14:27 +00:00
}
});
}
2024-05-24 08:14:27 +00:00
const moduleFactoriesHandler: ProxyHandler<PatchedModuleFactories> = {
set: (target, p, newValue, receiver) => {
2024-05-23 09:04:21 +00:00
// If the property is not a number, we are not dealing with a module factory
if (Number.isNaN(Number(p))) {
return Reflect.set(target, p, newValue, receiver);
2024-05-23 09:04:21 +00:00
}
const existingFactory = Reflect.get(target, p, target);
if (!Settings.eagerPatches) {
// If existingFactory exists, its either wrapped in defineModuleFactoryGetter, or it has already been required
// so call Reflect.set with the new original and let the correct logic apply (normal set, or defineModuleFactoryGetter setter)
if (existingFactory != null) {
return Reflect.set(target, p, newValue, receiver);
}
defineModuleFactoryGetter(target, p, newValue);
return true;
2024-05-23 09:04:21 +00:00
}
2024-05-20 01:49:58 +00:00
2024-05-23 09:04:21 +00:00
// Check if this factory is already patched
2024-05-24 06:45:46 +00:00
if (existingFactory?.$$vencordOriginal != null) {
existingFactory.$$vencordOriginal = newValue;
2024-05-23 09:04:21 +00:00
return true;
}
2024-05-20 01:49:58 +00:00
2024-05-23 09:04:21 +00:00
const patchedFactory = patchFactory(p, newValue);
// Modules are only patched once, so we need to set the patched factory on all the modules
for (const moduleFactories of allModuleFactories) {
Object.defineProperty(moduleFactories, p, {
value: patchedFactory,
configurable: true,
enumerable: true,
writable: true
});
2024-05-23 09:04:21 +00:00
}
2024-05-20 01:49:58 +00:00
2024-05-23 09:04:21 +00:00
return true;
}
2024-05-20 01:49:58 +00:00
};
2024-05-24 08:19:12 +00:00
// wreq.m is the Webpack object containing module factories.
2024-05-24 08:14:27 +00:00
// This is pre-populated with module factories, and is also populated via webpackGlobal.push
2024-05-24 08:19:12 +00:00
// The sentry module also has their own Webpack with a pre-populated module factories object, so this also targets that
2024-05-24 08:14:27 +00:00
// We wrap it with our proxy, which is responsible for patching the module factories, or setting up getters for them
2024-05-24 08:19:12 +00:00
// If this is the main Webpack, we also set up the internal references to WebpackRequire
2024-05-24 08:14:27 +00:00
Object.defineProperty(Function.prototype, "m", {
configurable: true,
2024-05-24 08:14:27 +00:00
set(this: WebpackRequire, moduleFactories: PatchedModuleFactories) {
// When using React DevTools or other extensions, we may also catch their Webpack here.
// This ensures we actually got the right ones
const { stack } = new Error();
2024-05-24 08:14:27 +00:00
if ((stack?.includes("discord.com") || stack?.includes("discordapp.com")) && !Array.isArray(moduleFactories)) {
logger.info("Found Webpack module factories", stack.match(/\/assets\/(.+?\.js)/)?.[1] ?? "");
2024-05-24 08:14:27 +00:00
// setImmediate to clear this property setter if this is not the main Webpack
// If this is the main Webpack, wreq.m will always be set before the timeout runs
const setterTimeout = setTimeout(() => delete (this as Partial<WebpackRequire>).p, 0);
Object.defineProperty(this, "p", {
configurable: true,
2024-05-24 08:14:27 +00:00
set(this: WebpackRequire, v: WebpackRequire["p"]) {
if (v !== "/assets/") return;
2024-05-24 08:24:37 +00:00
logger.info("Main Webpack found, initializing internal references to WebpackRequire");
2024-05-24 08:14:27 +00:00
_initWebpack(this);
clearTimeout(setterTimeout);
Object.defineProperty(this, "p", {
value: v,
2024-05-23 09:04:21 +00:00
configurable: true,
enumerable: true,
writable: true
});
2024-05-23 06:36:53 +00:00
}
});
2024-05-20 01:49:58 +00:00
for (const id in moduleFactories) {
2024-05-23 09:04:21 +00:00
// If we have eagerPatches enabled we have to patch the pre-populated factories
if (Settings.eagerPatches) {
moduleFactories[id] = patchFactory(id, moduleFactories[id]);
2024-05-23 09:04:21 +00:00
} else {
defineModuleFactoryGetter(moduleFactories, id, moduleFactories[id]);
2024-05-23 09:04:21 +00:00
}
2024-05-20 01:49:58 +00:00
}
allModuleFactories.add(moduleFactories);
2024-05-24 02:18:43 +00:00
2024-05-24 10:59:56 +00:00
Object.defineProperty(moduleFactories, Symbol.toStringTag, {
value: "ModuleFactories",
configurable: true,
writable: true
});
moduleFactories = new Proxy(moduleFactories, moduleFactoriesHandler);
}
Object.defineProperty(this, "m", {
value: moduleFactories,
2024-05-23 09:04:21 +00:00
configurable: true,
enumerable: true,
writable: true
});
}
});
2022-08-29 00:25:27 +00:00
2024-05-20 01:49:58 +00:00
let webpackNotInitializedLogged = false;
2024-05-23 09:04:21 +00:00
function patchFactory(id: PropertyKey, factory: ModuleFactory) {
2024-05-20 01:49:58 +00:00
for (const factoryListener of factoryListeners) {
2022-08-29 00:25:27 +00:00
try {
2024-05-23 09:04:21 +00:00
factoryListener(factory);
2022-08-29 00:25:27 +00:00
} catch (err) {
2024-05-20 01:49:58 +00:00
logger.error("Error in Webpack factory listener:\n", err, factoryListener);
2022-08-29 00:25:27 +00:00
}
}
2024-05-23 09:04:21 +00:00
const originalFactory = factory;
2024-05-22 09:08:28 +00:00
const patchedBy = new Set<string>();
2024-05-20 01:49:58 +00:00
// Discords Webpack chunks for some ungodly reason contain random
// newlines. Cyn recommended this workaround and it seems to work fine,
// however this could potentially break code, so if anything goes weird,
// this is probably why.
// Additionally, `[actual newline]` is one less char than "\n", so if Discord
// ever targets newer browsers, the minifier could potentially use this trick and
// cause issues.
//
// 0, prefix is to turn it into an expression: 0,function(){} would be invalid syntax without the 0,
2024-05-23 23:02:41 +00:00
let code: string = "0," + String(factory).replaceAll("\n", "");
2024-05-20 01:49:58 +00:00
for (let i = 0; i < patches.length; i++) {
const patch = patches[i];
if (patch.predicate && !patch.predicate()) continue;
2024-05-20 01:49:58 +00:00
const moduleMatches = typeof patch.find === "string"
? code.includes(patch.find)
: patch.find.test(code);
2024-05-20 01:49:58 +00:00
if (!moduleMatches) continue;
2024-05-20 01:49:58 +00:00
patchedBy.add(patch.plugin);
2024-05-20 01:49:58 +00:00
const executePatch = traceFunction(`patch by ${patch.plugin}`, (match: string | RegExp, replace: string) => code.replace(match, replace));
2024-05-23 09:04:21 +00:00
const previousFactory = factory;
2024-05-20 01:49:58 +00:00
const previousCode = code;
2024-05-20 01:49:58 +00:00
// We change all patch.replacement to array in plugins/index
for (const replacement of patch.replacement as PatchReplacement[]) {
if (replacement.predicate && !replacement.predicate()) continue;
2024-05-23 09:04:21 +00:00
const lastFactory = factory;
2024-05-20 01:49:58 +00:00
const lastCode = code;
2024-05-20 01:49:58 +00:00
canonicalizeReplacement(replacement, patch.plugin);
2024-05-20 01:49:58 +00:00
try {
const newCode = executePatch(replacement.match, replacement.replace as string);
if (newCode === code) {
if (!patch.noWarn) {
2024-05-23 06:36:53 +00:00
logger.warn(`Patch by ${patch.plugin} had no effect (Module id is ${String(id)}): ${replacement.match}`);
2024-05-20 01:49:58 +00:00
if (IS_DEV) {
logger.debug("Function Source:\n", code);
}
}
2024-05-20 01:49:58 +00:00
if (patch.group) {
logger.warn(`Undoing patch group ${patch.find} by ${patch.plugin} because replacement ${replacement.match} had no effect`);
2024-05-23 09:04:21 +00:00
factory = previousFactory;
2024-05-20 01:49:58 +00:00
code = previousCode;
patchedBy.delete(patch.plugin);
break;
}
continue;
}
2024-05-20 01:49:58 +00:00
code = newCode;
2024-05-23 09:04:21 +00:00
factory = (0, eval)(`// Webpack Module ${String(id)} - Patched by ${[...patchedBy].join(", ")}\n${newCode}\n//# sourceURL=WebpackModule${String(id)}`);
2024-05-20 01:49:58 +00:00
} catch (err) {
2024-05-23 06:36:53 +00:00
logger.error(`Patch by ${patch.plugin} errored (Module id is ${String(id)}): ${replacement.match}\n`, err);
2024-05-20 01:49:58 +00:00
if (IS_DEV) {
const changeSize = code.length - lastCode.length;
const match = lastCode.match(replacement.match)!;
// Use 200 surrounding characters of context
const start = Math.max(0, match.index! - 200);
const end = Math.min(lastCode.length, match.index! + match[0].length + 200);
// (changeSize may be negative)
const endPatched = end + changeSize;
const context = lastCode.slice(start, end);
const patchedContext = code.slice(start, endPatched);
// inline require to avoid including it in !IS_DEV builds
const diff = (require("diff") as typeof import("diff")).diffWordsWithSpace(context, patchedContext);
let fmt = "%c %s ";
const elements = [] as string[];
for (const d of diff) {
const color = d.removed
? "red"
: d.added
? "lime"
: "grey";
fmt += "%c%s";
elements.push("color:" + color, d.value);
}
2024-05-20 01:49:58 +00:00
logger.errorCustomFmt(...Logger.makeTitle("white", "Before"), context);
logger.errorCustomFmt(...Logger.makeTitle("white", "After"), patchedContext);
const [titleFmt, ...titleElements] = Logger.makeTitle("white", "Diff");
logger.errorCustomFmt(titleFmt + fmt, ...titleElements, ...elements);
}
2024-05-20 01:49:58 +00:00
patchedBy.delete(patch.plugin);
2024-05-20 01:49:58 +00:00
if (patch.group) {
logger.warn(`Undoing patch group ${patch.find} by ${patch.plugin} because replacement ${replacement.match} errored`);
2024-05-23 09:04:21 +00:00
factory = previousFactory;
2024-05-20 01:49:58 +00:00
code = previousCode;
break;
}
2024-05-23 09:04:21 +00:00
factory = lastFactory;
2024-05-20 01:49:58 +00:00
code = lastCode;
}
}
2024-05-20 01:49:58 +00:00
if (!patch.all) patches.splice(i--, 1);
}
2024-05-24 11:23:41 +00:00
const patchedFactory: PatchedModuleFactory = function (module, exports, require) {
for (const moduleFactories of allModuleFactories) {
Object.defineProperty(moduleFactories, id, {
2024-05-24 06:49:14 +00:00
value: patchedFactory.$$vencordOriginal,
configurable: true,
enumerable: true,
writable: true
});
2024-05-23 09:04:21 +00:00
}
2024-05-20 01:49:58 +00:00
if (wreq == null && IS_DEV) {
if (!webpackNotInitializedLogged) {
webpackNotInitializedLogged = true;
logger.error("WebpackRequire was not initialized, running modules without patches instead.");
}
2024-05-24 11:23:41 +00:00
return void originalFactory.call(this, module, exports, require);
2024-05-20 01:49:58 +00:00
}
2024-05-20 01:49:58 +00:00
try {
2024-05-24 11:23:41 +00:00
factory.call(this, module, exports, require);
2024-05-20 01:49:58 +00:00
} catch (err) {
// Just rethrow Discord errors
2024-05-23 09:04:21 +00:00
if (factory === originalFactory) throw err;
2024-05-20 01:49:58 +00:00
logger.error("Error in patched module", err);
2024-05-24 11:23:41 +00:00
return void originalFactory.call(this, module, exports, require);
2024-05-20 01:49:58 +00:00
}
2024-05-20 01:49:58 +00:00
// Webpack sometimes sets the value of module.exports directly, so assign exports to it to make sure we properly handle it
exports = module.exports;
if (exports == null) return;
// There are (at the time of writing) 11 modules exporting the window
// Make these non enumerable to improve webpack search performance
if (exports === window && require.c) {
Object.defineProperty(require.c, id, {
value: require.c[id],
configurable: true,
2024-05-23 09:04:21 +00:00
enumerable: false,
writable: true
2024-05-20 01:49:58 +00:00
});
return;
}
2024-05-20 01:49:58 +00:00
for (const callback of moduleListeners) {
try {
callback(exports, id);
} catch (err) {
logger.error("Error in Webpack module listener:\n", err, callback);
}
}
2024-05-20 01:49:58 +00:00
for (const [filter, callback] of subscriptions) {
try {
if (filter(exports)) {
subscriptions.delete(filter);
callback(exports, id);
} else if (exports.default && filter(exports.default)) {
subscriptions.delete(filter);
callback(exports.default, id);
}
2024-05-20 01:49:58 +00:00
} catch (err) {
logger.error("Error while firing callback for Webpack subscription:\n", err, filter, callback);
}
}
2024-05-23 06:10:59 +00:00
};
2024-05-20 01:49:58 +00:00
2024-05-23 09:04:21 +00:00
patchedFactory.toString = originalFactory.toString.bind(originalFactory);
patchedFactory.$$vencordOriginal = originalFactory;
2024-05-20 01:49:58 +00:00
return patchedFactory;
}