Skip to content

Commit

Permalink
fix?????
Browse files Browse the repository at this point in the history
  • Loading branch information
yofukashino committed Oct 28, 2023
1 parent 860e24c commit c510a4c
Show file tree
Hide file tree
Showing 8 changed files with 64 additions and 77 deletions.
12 changes: 5 additions & 7 deletions src/renderer/coremods/badges/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import React from "@common/react";
import { Logger } from "@replugged";
import type { User } from "discord-types/general";
import { Injector } from "../../modules/injector";
import { filters, getByProps, waitForModule } from "../../modules/webpack";
import { getByProps, waitForProps } from "../../modules/webpack";
import { generalSettings } from "../settings/pages/General";
import { APIBadges, BadgeSizes, Custom, badgeElements, getBadgeSizeClass } from "./badge";

Expand Down Expand Up @@ -37,17 +37,15 @@ const cache = new Map<string, BadgeCache>();
const REFRESH_INTERVAL = 1000 * 60 * 30;

export async function start(): Promise<void> {
const mod = await waitForModule<Record<string, BadgeMod>>(filters.bySource("getBadges()"));
const fnPropName = Object.entries(mod).find(([_, v]) => typeof v === "function")?.[0];
if (!fnPropName) {
throw new Error("Could not find badges function");
}
const mod = await waitForProps<{ BadgeSizes: Record<string, string>; default: BadgeMod }>(
"BadgeSizes",
);

const { containerWithContent } = getByProps<{ containerWithContent: "string" }>(
"containerWithContent",
)!;

injector.after(mod, fnPropName, ([props], res) => {
injector.after(mod, "default", ([props], res) => {
let {
user: { id },
shrinkAtCount,
Expand Down
50 changes: 18 additions & 32 deletions src/renderer/coremods/commands/index.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,7 @@
import type { AnyRepluggedCommand, RepluggedCommandSection } from "../../../types";
import { Injector } from "../../modules/injector";
import { Logger } from "../../modules/logger";
import {
filters,
getExportsForProps,
getFunctionKeyBySource,
waitForModule,
waitForProps,
} from "../../modules/webpack";
import { waitForProps } from "../../modules/webpack";

import { commandAndSections, defaultSection } from "../../apis/commands";
import { loadCommands, unloadCommands } from "./commands";
Expand All @@ -16,7 +10,7 @@ const logger = Logger.api("Commands");
const injector = new Injector();

interface ApplicationCommandSearchStoreMod {
[key: string]: (...args: unknown[]) =>
useDiscoveryState: (...args: unknown[]) =>
| {
sectionDescriptors: RepluggedCommandSection[];
commands: AnyRepluggedCommand[];
Expand All @@ -28,6 +22,10 @@ interface ApplicationCommandSearchStoreMod {
}>;
}
| undefined;
useQueryState: (...args: unknown[]) => unknown;
useSearchStoreOpenState: (...args: unknown[]) => unknown;
search: (...args: unknown[]) => unknown;
default: ApplicationCommandSearchStore;
}

interface ApplicationCommandSearchStore {
Expand Down Expand Up @@ -68,17 +66,16 @@ async function injectRepluggedSectionIcon(): Promise<void> {

async function injectApplicationCommandSearchStore(): Promise<void> {
// The module which contains the store
const ApplicationCommandSearchStoreMod = await waitForModule<ApplicationCommandSearchStoreMod>(
filters.bySource("ApplicationCommandSearchStore"),
);
const storeModFnKey = getFunctionKeyBySource(
ApplicationCommandSearchStoreMod,
"APPLICATION_COMMAND_SEARCH_STORE_UPDATE",
const ApplicationCommandSearchStoreMod = await waitForProps<ApplicationCommandSearchStoreMod>(
"useDiscoveryState",
"useQueryState",
"useSearchStoreOpenState",
"search",
);

// Base handler function for ApplicationCommandSearchStore which is ran to get the info in store
// commands are mainly added here
injector.after(ApplicationCommandSearchStoreMod, storeModFnKey!, (_, res) => {
injector.after(ApplicationCommandSearchStoreMod, "useDiscoveryState", (_, res) => {
const commandAndSectionsArray = Array.from(commandAndSections.values()).filter(
(commandAndSection) => commandAndSection.commands.size,
);
Expand Down Expand Up @@ -168,10 +165,7 @@ async function injectApplicationCommandSearchStore(): Promise<void> {
});

// The store itself
const ApplicationCommandSearchStore = getExportsForProps<ApplicationCommandSearchStore>(
ApplicationCommandSearchStoreMod,
["getApplicationSections", "getChannelState", "getQueryCommands"],
)!;
const ApplicationCommandSearchStore = ApplicationCommandSearchStoreMod.default;

// Channel state gets update with each character entered in text box and search so we patch this to keep our custom section
// even after updates happen
Expand Down Expand Up @@ -264,19 +258,11 @@ async function injectApplicationCommandSearchStore(): Promise<void> {
}

async function injectProfileFetch(): Promise<void> {
const mod = await waitForModule<
Record<
string,
(
id: string,
avatar: string,
{ guildId, channelId }: { guildId: string; channelId: string },
) => Promise<void>
>
>(filters.bySource(".preloadUserBanner,"), { raw: true });
const fnKey = getFunctionKeyBySource(mod.exports, ".apply(this");
injector.instead(mod.exports, fnKey!, (args, res) => {
if (args[1] === defaultSection.icon) {
const mod = await waitForProps<{
fetchProfile: (id: string) => Promise<void>;
}>("fetchProfile");
injector.instead(mod, "fetchProfile", (args, res) => {
if (args[0] === "replugged") {
return;
}
return res(...args);
Expand Down
6 changes: 3 additions & 3 deletions src/renderer/coremods/contextMenu/plaintextPatches.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,11 @@ export default [
],
},
{
find: "navId:",
find: ".Menu,{",
replacements: [
{
match: /navId:[\w"-]+,/g,
replace: (navId) => `${navId}data:arguments,`,
match: /\.Menu,{/g,
replace: (prefix) => `${prefix}data:arguments,`,
},
],
},
Expand Down
21 changes: 7 additions & 14 deletions src/renderer/coremods/rpc/index.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,10 @@
/* eslint-disable @typescript-eslint/consistent-type-definitions */
import { Injector, Logger } from "@replugged";
import { filters, getFunctionKeyBySource, waitForModule } from "src/renderer/modules/webpack";
import { Injector } from "@replugged";
import { filters, waitForModule, waitForProps } from "src/renderer/modules/webpack";
import { Jsonifiable } from "type-fest";

const injector = new Injector();

const logger = Logger.coremod("RPC");

type Socket = Record<string, unknown> & {
authorization: Record<string, unknown> & {
scopes: string[];
Expand Down Expand Up @@ -40,16 +38,11 @@ type RPCMod = { commands: Commands };
let commands: Commands = {};

async function injectRpc(): Promise<void> {
const rpcValidatorMod = await waitForModule<
Record<string, (socket: Socket, client_id: string, origin: string) => Promise<void>>
>(filters.bySource("Invalid Client ID"));
const validatorFunctionKey = getFunctionKeyBySource(rpcValidatorMod, "Invalid Client ID");
if (!validatorFunctionKey) {
logger.error("Failed to find RPC validator function.");
return;
}

injector.instead(rpcValidatorMod, validatorFunctionKey, (args, fn) => {
const rpcValidatorMod = await waitForProps<{
fetchApplicationsRPC: (socket: Socket, client_id: string, origin: string) => Promise<void>;
}>("fetchApplicationsRPC");

injector.instead(rpcValidatorMod, "fetchApplicationsRPC", (args, fn) => {
const [, clientId, origin] = args;
const isRepluggedClient = clientId.startsWith("REPLUGGED-");

Expand Down
25 changes: 14 additions & 11 deletions src/renderer/managers/coremods.ts
Original file line number Diff line number Diff line change
Expand Up @@ -74,15 +74,18 @@ export async function stopAll(): Promise<void> {
await Promise.allSettled(Object.values(coremods).map((c) => c.stop?.()));
}

export function runPlaintextPatches(): void {
[
experimentsPlaintext,
notrackPlaintext,
noDevtoolsWarningPlaintext,
messagePopover,
notices,
contextMenu,
languagePlaintext,
commandsPlaintext,
].forEach(patchPlaintext);
export function runPlaintextPatches(): Promise<void> {
return new Promise<void>((res) => {
[
experimentsPlaintext,
notrackPlaintext,
noDevtoolsWarningPlaintext,
messagePopover,
notices,
contextMenu,
languagePlaintext,
commandsPlaintext,
].forEach(patchPlaintext);
res();
});
}
2 changes: 1 addition & 1 deletion src/renderer/managers/ignition.ts
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ Load order:
export async function ignite(): Promise<void> {
// This is the function that will be called when loading the window.
// Plaintext patches are executed before Discord's preload.
coremods.runPlaintextPatches();
await coremods.runPlaintextPatches();
await plugins.loadAll();
await plugins.runPlaintextPatches();
// These next things will happen after Discord's preload is called.
Expand Down
11 changes: 6 additions & 5 deletions src/renderer/modules/webpack/patch-load.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,12 +45,13 @@ export const waitForStart = new Promise<void>((resolve) => (signalStart = resolv
*/
export const sourceStrings: Record<number, string> = {};

function patchChunk(chunk: WebpackChunk): void {
async function patchChunk(chunk: WebpackChunk): Promise<void> {
await waitForStart;
const modules = chunk[1];
for (const id in modules) {
const originalMod = modules[id];
sourceStrings[id] = originalMod.toString();
const mod = patchModuleSource(originalMod);
const mod = patchModuleSource(originalMod, id);
modules[id] = function (module, exports, require) {
mod(module, exports, require);

Expand All @@ -73,8 +74,8 @@ function patchChunk(chunk: WebpackChunk): void {
function patchPush(webpackChunk: WebpackChunkGlobal): void {
let original = webpackChunk.push;

function handlePush(chunk: WebpackChunk): unknown {
patchChunk(chunk);
async function handlePush(chunk: WebpackChunk): Promise<unknown> {
await patchChunk(chunk);
return original.call(webpackChunk, chunk);
}

Expand Down Expand Up @@ -123,7 +124,7 @@ function loadWebpackModules(chunksGlobal: WebpackChunkGlobal): void {
// Patch previously loaded chunks
if (Array.isArray(chunksGlobal)) {
for (const loadedChunk of chunksGlobal) {
patchChunk(loadedChunk);
void patchChunk(loadedChunk);
}
}

Expand Down
14 changes: 10 additions & 4 deletions src/renderer/modules/webpack/plaintext-patch.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import type { PlaintextPatch, RawPlaintextPatch, WebpackModule } from "../../../types";

import { Logger } from "../logger";
const logger = Logger.api("plaintext-patch");
/**
* All plaintext patches
*/
Expand All @@ -10,7 +11,7 @@ export const plaintextPatches: RawPlaintextPatch[] = [];
* @param mod Module
* @returns Patched module
*/
export function patchModuleSource(mod: WebpackModule): WebpackModule {
export function patchModuleSource(mod: WebpackModule, id: string): WebpackModule {
const originalSource = mod.toString();

const patchedSource = plaintextPatches.reduce((source, patch) => {
Expand Down Expand Up @@ -39,8 +40,13 @@ export function patchModuleSource(mod: WebpackModule): WebpackModule {
}
try {
// eslint-disable-next-line no-eval
return (0, eval)(patchedSource);
} catch {
return (0, eval)(
`${
patchedSource.startsWith("function(") ? `0,${patchedSource}` : patchedSource
}\n//# sourceURL=PatchedWebpack-${id}`,
);
} catch (err) {
logger.error(`PatchedWebpack-${id}`, err);
// Syntax error in patched module--fail
return mod;
}
Expand Down

0 comments on commit c510a4c

Please sign in to comment.