UNPKG

js-confuser

Version:

JavaScript Obfuscation Tool.

231 lines (220 loc) 10.7 kB
"use strict"; function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } Object.defineProperty(exports, "__esModule", { value: true }); exports["default"] = void 0; var t = _interopRequireWildcard(require("@babel/types")); var _template = _interopRequireDefault(require("../templates/template")); var _order = require("../order"); var _constants = require("../constants"); var _astUtils = require("../utils/ast-utils"); var _functionUtils = require("../utils/function-utils"); var _assert = require("assert"); var _NameGen = require("../utils/NameGen"); var _randomUtils = require("../utils/random-utils"); var _node = require("../utils/node"); function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(e) { return e ? t : r; })(e); } function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != _typeof(e) && "function" != typeof e) return { "default": e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && {}.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n["default"] = e, t && t.set(e, n), n; } function _createForOfIteratorHelper(r, e) { var t = "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (!t) { if (Array.isArray(r) || (t = _unsupportedIterableToArray(r)) || e && r && "number" == typeof r.length) { t && (r = t); var _n = 0, F = function F() {}; return { s: F, n: function n() { return _n >= r.length ? { done: !0 } : { done: !1, value: r[_n++] }; }, e: function e(r) { throw r; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var o, a = !0, u = !1; return { s: function s() { t = t.call(r); }, n: function n() { var r = t.next(); return a = r.done, r; }, e: function e(r) { u = !0, o = r; }, f: function f() { try { a || null == t["return"] || t["return"](); } finally { if (u) throw o; } } }; } function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } } function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; } var _default = exports["default"] = function _default(_ref) { var Plugin = _ref.Plugin; var me = Plugin(_order.Order.VariableMasking, { changeData: { functions: 0 } }); var transformFunction = function transformFunction(fnPath) { // Do not apply to getter/setter methods if (fnPath.isObjectMethod() && fnPath.node.kind !== "method") { return; } // Do not apply to class getters/setters if (fnPath.isClassMethod() && fnPath.node.kind !== "method") { return; } // Do not apply to async or generator functions if (fnPath.node.generator || fnPath.node.async) { return; } // Do not apply to functions with rest parameters or destructuring if (fnPath.node.params.some(function (param) { return !t.isIdentifier(param); })) { return; } // Do not apply to 'use strict' functions if ((0, _astUtils.isStrictMode)(fnPath)) return; // Do not apply to functions marked unsafe if (fnPath.node[_constants.UNSAFE]) return; var functionName = (0, _astUtils.getFunctionName)(fnPath); if (!me.computeProbabilityMap(me.options.variableMasking, functionName)) { return; } var stackName = me.getPlaceholder() + "_varMask"; var stackMap = new Map(); var propertyGen = new _NameGen.NameGen("mangled"); var stackKeys = new Set(); var needsStack = false; var illegalBindings = new Set(); function checkBinding(binding) { // Custom illegal check // Variable Declarations with more than one declarator are not supported // They can be inserted from the user's code even though Preparation phase should prevent it // String Compression library includes such code // TODO: Support multiple declarators var variableDeclaration = binding.path.find(function (p) { return p.isVariableDeclaration(); }); if (variableDeclaration && variableDeclaration.node.declarations.length > 1) { return false; } function checkForUnsafe(valuePath) { var hasUnsafeNode = false; valuePath.traverse({ ThisExpression: function ThisExpression(path) { hasUnsafeNode = true; path.stop(); }, Function: function Function(path) { if (path.node[_constants.UNSAFE]) { hasUnsafeNode = true; path.stop(); } } }); return hasUnsafeNode; } // Check function value for 'this' // Adding function expression to the stack (member expression) // would break the 'this' context if (binding.path.isVariableDeclarator()) { var init = binding.path.get("init"); if (init.node) { if (checkForUnsafe(init)) return false; } } // x = function(){ return this } // Cannot be transformed to x = stack[0] as 'this' would change var _iterator = _createForOfIteratorHelper(binding.constantViolations), _step; try { for (_iterator.s(); !(_step = _iterator.n()).done;) { var assignment = _step.value; if (checkForUnsafe(assignment)) return false; } // __JS_CONFUSER_VAR__(identifier) -> __JS_CONFUSER_VAR__(stack.identifier) // This cannot be transformed as it would break the user's code } catch (err) { _iterator.e(err); } finally { _iterator.f(); } var _iterator2 = _createForOfIteratorHelper(binding.referencePaths), _step2; try { for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) { var referencePath = _step2.value; if ((0, _functionUtils.isVariableFunctionIdentifier)(referencePath)) { return false; } } } catch (err) { _iterator2.e(err); } finally { _iterator2.f(); } return true; } var _iterator3 = _createForOfIteratorHelper(fnPath.get("params")), _step3; try { for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) { var param = _step3.value; (0, _assert.ok)(param.isIdentifier()); var paramName = param.node.name; var binding = param.scope.getBinding(paramName); if (!binding || !checkBinding(binding)) return; (0, _assert.ok)(!stackMap.has(binding)); stackKeys.add(stackMap.size.toString()); stackMap.set(binding, stackMap.size); } } catch (err) { _iterator3.e(err); } finally { _iterator3.f(); } fnPath.traverse({ Identifier: function Identifier(path) { if (!(0, _astUtils.isVariableIdentifier)(path)) return; if (_constants.reservedIdentifiers.has(path.node.name)) return; if (me.options.globalVariables.has(path.node.name)) return; if (path.node.name === stackName) return; if (path.node.name === _constants.variableFunctionName) return; var binding = path.scope.getBinding(path.node.name); if (!binding || binding.scope !== fnPath.scope) return; if (illegalBindings.has(binding)) return; needsStack = true; var index = stackMap.get(binding); if (typeof index === "undefined") { // Only transform var and let bindings // Function declarations could be hoisted and changing them to declarations is breaking if (!["var", "let"].includes(binding.kind)) { illegalBindings.add(binding); return; } if (!checkBinding(binding)) { illegalBindings.add(binding); return; } do { index = (0, _randomUtils.choice)([stackMap.size, propertyGen.generate(), (0, _randomUtils.getRandomInteger)(-250, 250)]); } while (!index || stackKeys.has(index.toString())); stackMap.set(binding, index); stackKeys.add(index.toString()); } var memberExpression = t.memberExpression(t.identifier(stackName), (0, _node.createLiteral)(index), true); if ((0, _astUtils.isDefiningIdentifier)(path)) { (0, _astUtils.replaceDefiningIdentifierToMemberExpression)(path, memberExpression); return; } (0, _astUtils.ensureComputedExpression)(path); path.replaceWith(memberExpression); } }); if (!needsStack) return; var originalParamCount = fnPath.node.params.length; var originalLength = (0, _functionUtils.computeFunctionLength)(fnPath); fnPath.node.params = [t.restElement(t.identifier(stackName))]; // Discard extraneous parameters // Predictable functions are guaranteed to not have extraneous parameters if (!fnPath.node[_constants.PREDICTABLE]) { (0, _astUtils.prepend)(fnPath, new _template["default"]("".concat(stackName, "[\"length\"] = {originalParamCount};")).single({ originalParamCount: t.numericLiteral(originalParamCount) })); } // Function is no longer predictable fnPath.node[_constants.PREDICTABLE] = false; fnPath.scope.registerBinding("param", fnPath.get("params")[0], fnPath); me.setFunctionLength(fnPath, originalLength); me.changeData.functions++; }; return { visitor: { Function: { exit: function exit(path) { if (!path.get("body").isBlockStatement()) return; transformFunction(path); } }, Program: { enter: function enter(path) { path.scope.crawl(); } } } }; };