From 0ba55a30f76ecca0fcb7fbbfde7ffbf242311504 Mon Sep 17 00:00:00 2001 From: Samual Norman Date: Mon, 14 Feb 2022 20:47:21 +0000 Subject: [PATCH] add support for scripts that contain illegal strings like `SC$` and convert them to be hackmud compatible --- src/processScript/index.ts | 73 +++++++++++++++++++++++++++++++- src/processScript/minify.ts | 37 +++++++++++++++- src/processScript/postprocess.ts | 8 +++- src/processScript/preprocess.ts | 4 -- src/processScript/shared.ts | 13 ++++++ 5 files changed, 127 insertions(+), 8 deletions(-) diff --git a/src/processScript/index.ts b/src/processScript/index.ts index ccd76b0..32cdad4 100644 --- a/src/processScript/index.ts +++ b/src/processScript/index.ts @@ -21,7 +21,7 @@ import babelPluginProposalThrowExpressions from "@babel/plugin-proposal-throw-ex import babelPluginTransformExponentiationOperator from "@babel/plugin-transform-exponentiation-operator" import babelPluginTransformTypescript from "@babel/plugin-transform-typescript" import babelTraverse from "@babel/traverse" -import t from "@babel/types" +import t, { LVal } from "@babel/types" import rollupPluginBabel_ from "@rollup/plugin-babel" import rollupPluginCommonJS from "@rollup/plugin-commonjs" import rollupPluginJSON from "@rollup/plugin-json" @@ -35,6 +35,7 @@ import { supportedExtensions as extensions } from "../constants.json" import minify from "./minify" import postprocess from "./postprocess" import preprocess from "./preprocess" +import { includesIllegalString, replaceIllegalStrings } from "./shared" import transform from "./transform" const { default: rollupPluginBabel } = rollupPluginBabel_ as any as typeof import("@rollup/plugin-babel") @@ -256,11 +257,74 @@ export async function processScript( } else if (memberExpression.property.name == `__proto__`) { memberExpression.computed = true memberExpression.property = t.stringLiteral(`__proto__`) + } else if (includesIllegalString(memberExpression.property.name)) { + memberExpression.computed = true + + memberExpression.property = t.stringLiteral( + replaceIllegalStrings(uniqueID, memberExpression.property.name) + ) + } + }, + + VariableDeclarator(path) { + renameVariables(path.node.id) + + function renameVariables(lValue: LVal) { + switch (lValue.type) { + case `Identifier`: { + if (includesIllegalString(lValue.name)) + path.scope.rename(lValue.name, `$${Math.floor(Math.random() * (2 ** 52)).toString(36).padStart(11, `0`)}`) + } break + + case `ObjectPattern`: { + for (const property of lValue.properties) { + assert(property.type == `ObjectProperty`) + renameVariables(property.value as LVal) + } + } break + + case `ArrayPattern`: { + for (const element of lValue.elements) { + if (element) + renameVariables(element) + } + } break + + default: + throw new Error(`unknown lValue type "${lValue.type}"`) + } + } + }, + + ObjectProperty({ node: objectProperty }) { + if (objectProperty.key.type == `Identifier` && includesIllegalString(objectProperty.key.name)) { + objectProperty.key = t.stringLiteral(replaceIllegalStrings(uniqueID, objectProperty.key.name)) + objectProperty.shorthand = false + } + }, + + StringLiteral({ node }) { + node.value = replaceIllegalStrings(uniqueID, node.value) + }, + + TemplateLiteral({ node }) { + for (const templateElement of node.quasis) { + if (templateElement.value.cooked) { + templateElement.value.cooked = replaceIllegalStrings(uniqueID, templateElement.value.cooked) + + templateElement.value.raw = templateElement.value.cooked + .replace(/`/g, `\\\``) + // eslint-disable-next-line unicorn/better-regex, optimize-regex/optimize-regex + .replace(/\$\{/g, `$\\{`) + .replace(/\\/g, `\\\\`) + } else + templateElement.value.raw = replaceIllegalStrings(uniqueID, templateElement.value.raw) } } }) - code = format(generate(file).code, { + // we can't have comments because they may contain illegal strings + code = format(generate(file, { comments: false }).code, { parser: `babel`, arrowParens: `avoid`, semi: false, @@ -270,6 +334,11 @@ export async function processScript( code = postprocess(code, seclevel, uniqueID) + if (includesIllegalString(code)) + throw new Error(`you found a weird edge case where I wasn't able to replace illegal strings like "SC$", please report thx`) + + // TODO it is not neccesary to record the time took since the caller can do that + return { srcLength: sourceLength, script: code, diff --git a/src/processScript/minify.ts b/src/processScript/minify.ts index 4b8039f..718aa85 100644 --- a/src/processScript/minify.ts +++ b/src/processScript/minify.ts @@ -4,7 +4,7 @@ import t, { Expression, File, FunctionDeclaration, Program } from "@babel/types" import { assert, countHackmudCharacters, spliceString } from "@samual/lib" import { tokenizer as tokenize, tokTypes as tokenTypes } from "acorn" import * as terser from "terser" -import { getReferencePathsToGlobal } from "./shared" +import { getReferencePathsToGlobal, includesIllegalString, replaceIllegalStrings } from "./shared" const { default: generate } = babelGenerator as any as typeof import("@babel/generator") const { default: traverse } = babelTraverse as any as typeof import("@babel/traverse") @@ -19,6 +19,7 @@ type MinifyOptions = { // TODO move autocomplete code outside this function // TODO allow not mangling class and function names +// TODO replace references to `arguments` /** * @param code compiled code and/or hackmud compatible code @@ -120,6 +121,38 @@ export async function minify(file: File, autocomplete?: string, { } else if (memberExpression.property.name == `__proto__`) { memberExpression.computed = true memberExpression.property = t.identifier(`_PROTO_PROPERTY_${uniqueID}_`) + } else if (includesIllegalString(memberExpression.property.name)) { + memberExpression.computed = true + + memberExpression.property = t.stringLiteral( + replaceIllegalStrings(uniqueID, memberExpression.property.name) + ) + } + }, + + ObjectProperty({ node: objectProperty }) { + if (objectProperty.key.type == `Identifier` && includesIllegalString(objectProperty.key.name)) { + objectProperty.key = t.stringLiteral(replaceIllegalStrings(uniqueID, objectProperty.key.name)) + objectProperty.shorthand = false + } + }, + + StringLiteral({ node }) { + node.value = replaceIllegalStrings(uniqueID, node.value) + }, + + TemplateLiteral({ node }) { + for (const templateElement of node.quasis) { + if (templateElement.value.cooked) { + templateElement.value.cooked = replaceIllegalStrings(uniqueID, templateElement.value.cooked) + + templateElement.value.raw = templateElement.value.cooked + .replace(/`/g, `\\\``) + // eslint-disable-next-line unicorn/better-regex, optimize-regex/optimize-regex + .replace(/\$\{/g, `$\\{`) + .replace(/\\/g, `\\\\`) + } else + templateElement.value.raw = replaceIllegalStrings(uniqueID, templateElement.value.raw) } } }) @@ -287,6 +320,8 @@ export async function minify(file: File, autocomplete?: string, { }, StringLiteral(path) { + path.node.value = replaceIllegalStrings(uniqueID, path.node.value) + // eslint-disable-next-line @typescript-eslint/no-base-to-string -- the `NodePath`'s `.toString()` method compiles and returns the contained `Node` if (path.node.value.includes(`\u0000`) || path.toString().length < 4) return diff --git a/src/processScript/postprocess.ts b/src/processScript/postprocess.ts index c3efe60..f6917bf 100644 --- a/src/processScript/postprocess.ts +++ b/src/processScript/postprocess.ts @@ -1,7 +1,13 @@ import { findMatches, spliceString } from "@samual/lib" export function postprocess(code: string, seclevel: number, uniqueID: string) { - code = code.replace(/^function\s*\w+\(/, `function(`) + code = code + .replace(/^function\s*\w+\(/, `function(`) + .replace(new RegExp(`\\$${uniqueID}\\$\\\\\\\\0\\$SC_DOLLAR\\$`, `g`), `SC\\$`) + .replace(new RegExp(`\\$${uniqueID}\\$\\\\\\\\0\\$DB_DOLLAR\\$`, `g`), `DB\\$`) + .replace(new RegExp(`\\$${uniqueID}\\$\\\\\\\\0\\$D\\$`, `g`), `__D_\\S`) + .replace(new RegExp(`\\$${uniqueID}\\$\\\\\\\\0\\$FMCL\\$`, `g`), `__FMCL\\_`) + .replace(new RegExp(`\\$${uniqueID}\\$\\\\\\\\0\\$G\\$`, `g`), `__G\\_`) for (const { index, match } of [ ...findMatches(new RegExp(`\\$${uniqueID}\\$[\\w$]+`, `g`), code) ].reverse()) { const [ type, ...arguments_ ] = match.slice(13).split(`$`) diff --git a/src/processScript/preprocess.ts b/src/processScript/preprocess.ts index 44b553d..d841e79 100644 --- a/src/processScript/preprocess.ts +++ b/src/processScript/preprocess.ts @@ -19,10 +19,6 @@ export type PreprocessOptions = { export function preprocess(code: string, { uniqueID = `00000000000` }: Partial = {}) { assert(/^\w{11}$/.test(uniqueID)) - // TODO rename variables that trips this - if (/(?:SC|DB)\$/.test(code)) - throw new Error(`SC$ and DB$ are protected and cannot appear in a script`) - const sourceCode = code let lengthBefore diff --git a/src/processScript/shared.ts b/src/processScript/shared.ts index 4f8331f..9153b10 100644 --- a/src/processScript/shared.ts +++ b/src/processScript/shared.ts @@ -19,3 +19,16 @@ export function getReferencePathsToGlobal(name: string, program: NodePath[] } + +export function includesIllegalString(toCheck: string) { + return toCheck.includes(`SC$`) || toCheck.includes(`DB$`) || toCheck.includes(`__D_S`) || toCheck.includes(`__FMCL_`) || toCheck.includes(`__G_`) +} + +export function replaceIllegalStrings(uniqueID: string, toReplace: string) { + return toReplace + .replace(/SC\$/g, `$${uniqueID}$\\0$SC_DOLLAR$`) + .replace(/DB\$/g, `$${uniqueID}$\\0$DB_DOLLAR$`) + .replace(/__D_S/g, `$${uniqueID}$\\0$D$`) + .replace(/__FMCL_/g, `$${uniqueID}$\\0$FMCL$`) + .replace(/__G_/g, `$${uniqueID}$\\0$G$`) +} -- knotmirror 0.0.1