aboutsummaryrefslogtreecommitdiff
path: root/src/webpack-hook.ts
blob: 36f99523890e6806f166f06b9811d56837c70866 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
/* eslint-disable @typescript-eslint/no-unsafe-return */
/* eslint-disable @typescript-eslint/explicit-module-boundary-types */

import { hookNative } from "./anti-detection";
import { console, getUnsafeWindow } from "./utils";

const CHUNK_PUSH_FN = /^function [^r]\(\w\){/;

interface Module {
    (module, exports, __webpack_require__): void;
}

type WebpackJson = [(number | string)[], { [id: string]: Module }, any[]?][];

const moduleLookup = (id: string, globalWebpackJson: WebpackJson) => {
    const pack = globalWebpackJson.find((x) => x[1][id])!;
    return pack[1][id];
};

/**
 * Retrieve (webpack_require) a module from the page's webpack package
 *
 * I know this is super hacky.
 */
export const webpackHook = (
    moduleId: string,
    moduleOverrides: { [id: string]: Module } = {},
    globalWebpackJson: WebpackJson = window["webpackJsonpmusescore"]
) => {
    const t = Object.assign(
        (id: string, override = true) => {
            const r: any = {};
            const m: Module =
                override && moduleOverrides[id]
                    ? moduleOverrides[id]
                    : moduleLookup(id, globalWebpackJson);
            m(r, r, t);
            if (r.exports) return r.exports;
            return r;
        },
        {
            d(exp, name, fn) {
                return (
                    Object.prototype.hasOwnProperty.call(exp, name) ||
                    Object.defineProperty(exp, name, {
                        enumerable: true,
                        get: fn,
                    })
                );
            },
            n(e) {
                const m = e.__esModule ? () => e.default : () => e;
                t.d(m, "a", m);
                return m;
            },
            r(r) {
                Object.defineProperty(r, "__esModule", { value: true });
            },
            e() {
                return Promise.resolve();
            },
        }
    );

    return t(moduleId);
};

export const ALL = "*";

export const [webpackGlobalOverride, onPackLoad] = (() => {
    type OnPackLoadFn = (pack: WebpackJson[0]) => any;

    const moduleOverrides: { [id: string]: Module } = {};
    const onPackLoadFns: OnPackLoadFn[] = [];

    function applyOverride(pack: WebpackJson[0]) {
        let entries = Object.entries(moduleOverrides);
        // apply to all
        const all = moduleOverrides[ALL];
        if (all) {
            entries = Object.keys(pack[1]).map((id) => [id, all]);
        }

        entries.forEach(([id, override]) => {
            const mod = pack[1][id];
            if (mod) {
                pack[1][id] = function (n, r, t) {
                    // make exports configurable
                    t = Object.assign(t, {
                        d(exp, name, fn) {
                            return Object.defineProperty(exp, name, {
                                enumerable: true,
                                get: fn,
                                configurable: true,
                            });
                        },
                    });
                    mod(n, r, t);
                    override(n, r, t);
                };
            }
        });
    }

    // hook `webpackJsonpmusescore.push` as soon as `webpackJsonpmusescore` is available
    const _w = getUnsafeWindow();
    let jsonp = _w["webpackJsonpmusescore"];
    let hooked = false;
    Object.defineProperty(_w, "webpackJsonpmusescore", {
        get() {
            return jsonp;
        },
        set(v: WebpackJson) {
            jsonp = v;
            if (!hooked && v.push.toString().match(CHUNK_PUSH_FN)) {
                hooked = true;
                hookNative(v, "push", (_fn) => {
                    return function (pack) {
                        onPackLoadFns.forEach((fn) => fn(pack));
                        applyOverride(pack);
                        return _fn.call(this, pack);
                    };
                });
            }
        },
    });

    return [
        // set overrides
        (moduleId: string, override: Module) => {
            moduleOverrides[moduleId] = override;
        },
        // set onPackLoad listeners
        (fn: OnPackLoadFn) => {
            onPackLoadFns.push(fn);
        },
    ] as const;
})();

export const webpackContext = new Promise<any>((resolve) => {
    webpackGlobalOverride(ALL, (n, r, t) => {
        resolve(t);
    });
});

const PACK_ID_REG = /\+(\{.*?"\})\[\w\]\+/;

export const loadAllPacks = () => {
    return webpackContext.then((ctx) => {
        try {
            const fn = ctx.e.toString();
            const packsData = fn.match(PACK_ID_REG)[1] as string;
            // eslint-disable-next-line no-new-func, @typescript-eslint/no-implied-eval
            const packs = Function(`return (${packsData})`)() as {
                [id: string]: string;
            };

            Object.keys(packs).forEach((id) => {
                ctx.e(id);
            });
        } catch (err) {
            console.error(err);
        }
    });
};

const OBF_FN_REG =
    /\w\(".{4}"\),(\w)=(\[".+?\]);\w=\1,\w=(\d+).+?\);var (\w=.+?,\w\})/;
export const OBFUSCATED_REG = /(\w)\((\d+),"(.{4})"\)/g;

export const getObfuscationCtx = (
    mod: Module
): ((n: number, s: string) => string) => {
    const str = mod.toString();
    const m = str.match(OBF_FN_REG);
    if (!m) return () => "";

    try {
        const arrVar = m[1];
        const arr = JSON.parse(m[2]);

        let n = +m[3] + 1;
        for (; --n; ) arr.push(arr.shift());

        const fnStr = m[4];
        const ctxStr = `var ${arrVar}=${JSON.stringify(arr)};return (${fnStr})`;
        // eslint-disable-next-line no-new-func, @typescript-eslint/no-implied-eval
        const fn = new Function(ctxStr)();

        return fn;
    } catch (err) {
        console.error(err);
        return () => "";
    }
};

export default webpackHook;