js-confuser
Version:
JavaScript Obfuscation Tool.
269 lines (255 loc) • 14 kB
JavaScript
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 _order = require("../../order");
var _constants = require("../../constants");
var _astUtils = require("../../utils/ast-utils");
var _functionUtils = require("../../utils/function-utils");
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 ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; }
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; }
function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
function _slicedToArray(r, e) { return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest(); }
function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t["return"] && (u = t["return"](), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } }
function _arrayWithHoles(r) { if (Array.isArray(r)) return r; }
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 RENAMED = Symbol("Renamed");
var reusePreviousNames = true;
var _default = exports["default"] = function _default(_ref) {
var Plugin = _ref.Plugin;
var me = Plugin(_order.Order.RenameVariables, {
changeData: {
variables: 0
}
});
var definedMap = new Map();
var referencedMap = new Map();
var bindingMap = new Map();
var renamedVariables = new Map();
me.obfuscator.globalState.renamedVariables = renamedVariables;
var generated = Array.from(me.obfuscator.nameGen.generatedNames);
var VariableAnalysisVisitor = {
Program: {
enter: function enter(path) {
// Analyze all scopes
path.traverse({
Identifier: function Identifier(path) {
if (!(0, _astUtils.isVariableIdentifier)(path)) return;
var contextPaths = [(0, _astUtils.getParentFunctionOrProgram)(path)];
var isDefined = false;
if (path.isBindingIdentifier() && (0, _astUtils.isDefiningIdentifier)(path)) {
isDefined = true;
// Function ID is defined in the parent's function declaration
if (path.key === "id" && path.parentPath.isFunctionDeclaration()) {
contextPaths = [(0, _astUtils.getParentFunctionOrProgram)(path.parentPath)];
}
}
contextPaths.forEach(function (contextPath) {
// console.log(contextPath.node.type, path.node.name, isDefined);
if (isDefined) {
// Add to defined map
if (!definedMap.has(contextPath.node)) {
definedMap.set(contextPath.node, new Set());
}
definedMap.get(contextPath.node).add(path.node.name);
if (!bindingMap.has(contextPath.node)) {
bindingMap.set(contextPath.node, new Map());
}
bindingMap.get(contextPath.node).set(path.node.name, path);
} else {
// Add to reference map
if (!referencedMap.has(contextPath.node)) {
referencedMap.set(contextPath.node, new Set());
}
referencedMap.get(contextPath.node).add(path.node.name);
}
});
}
});
//
}
}
};
var VariableRenamingVisitor = {
Identifier: function Identifier(identifierPath) {
if (!(0, _astUtils.isVariableIdentifier)(identifierPath)) return;
var node = identifierPath.node;
var identifierName = node.name;
if (node[RENAMED]) {
return;
}
var contextPaths = identifierPath.getAncestry();
// A Function ID is not in the same context as it's body
if (identifierPath.key === "id" && identifierPath.parentPath.isFunctionDeclaration()) {
contextPaths = contextPaths.filter(function (x) {
return x !== identifierPath.parentPath;
});
}
var newName = null;
var _iterator = _createForOfIteratorHelper(contextPaths),
_step;
try {
for (_iterator.s(); !(_step = _iterator.n()).done;) {
var contextPath = _step.value;
var _node = contextPath.node;
var defined = definedMap.get(_node);
if (defined !== null && defined !== void 0 && defined.has(identifierName)) {
var renamed = renamedVariables.get(_node);
if (renamed !== null && renamed !== void 0 && renamed.has(identifierName)) {
newName = renamed.get(identifierName);
break;
}
}
}
} catch (err) {
_iterator.e(err);
} finally {
_iterator.f();
}
if (newName && typeof newName === "string") {
// __JS_CONFUSER_VAR__ function
if ((0, _functionUtils.isVariableFunctionIdentifier)(identifierPath)) {
identifierPath.parentPath.replaceWith(t.stringLiteral(newName));
return;
}
// 5. Update Identifier node's 'name' property
node.name = newName;
node[RENAMED] = true;
}
},
Scopable: function Scopable(scopePath) {
// 2. Notice this is on 'onEnter' (top-down)
var isGlobal = scopePath.isProgram();
var node = scopePath.scope.path.node;
if (renamedVariables.has(node)) return;
var defined = definedMap.get(node) || new Set();
var references = referencedMap.get(node) || new Set();
var bindings = bindingMap.get(node);
// No changes needed here
if (!defined && !renamedVariables.has(node)) {
renamedVariables.set(node, Object.create(null));
return;
}
var newNames = new Map();
// Names possible to be re-used here
var possible = new Set();
// 3. Try to re-use names when possible
if (reusePreviousNames && generated.length && !isGlobal) {
var allReferences = new Set();
var nope = new Set(defined);
scopePath.traverse({
Scopable: function Scopable(path) {
var node = path.scope.path.node;
var ref = referencedMap.get(node);
if (ref) {
ref.forEach(function (x) {
return allReferences.add(x);
});
}
var def = definedMap.get(node);
if (def) {
def.forEach(function (x) {
return allReferences.add(x);
});
}
}
});
var passed = new Set();
var parentPaths = scopePath.getAncestry();
parentPaths.forEach(function (p) {
if (p === scopePath) return;
var changes = renamedVariables.get(p.node);
if (changes) {
var _iterator2 = _createForOfIteratorHelper(changes),
_step2;
try {
for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
var _step2$value = _slicedToArray(_step2.value, 2),
oldName = _step2$value[0],
newName = _step2$value[1];
if (!allReferences.has(oldName) && !references.has(oldName)) {
passed.add(newName);
} else {
nope.add(newName);
}
}
} catch (err) {
_iterator2.e(err);
} finally {
_iterator2.f();
}
}
});
nope.forEach(function (x) {
return passed["delete"](x);
});
possible = passed;
}
function shouldRename(name) {
// __NO_JS_CONFUSER_RENAME__
if (name.startsWith(_constants.noRenameVariablePrefix)) return false;
// Placeholder variables should always be renamed
if (name.startsWith(_constants.placeholderVariablePrefix)) return true;
var binding = bindings === null || bindings === void 0 ? void 0 : bindings.get(name);
if (binding) {
// Do not rename exports
if ((0, _astUtils.isExportedIdentifier)(binding)) return false;
}
if (name === me.obfuscator.getStringCompressionLibraryName()) return false;
// Global variables are additionally checked against user option
if (isGlobal) {
if (!me.computeProbabilityMap(me.options.renameGlobals, name)) return false;
}
if (!me.computeProbabilityMap(me.options.renameVariables, name, isGlobal)) return false;
return true;
}
// 4. Defined names to new names
var _iterator3 = _createForOfIteratorHelper(defined),
_step3;
try {
for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) {
var name = _step3.value;
var newName = name;
if (shouldRename(name)) {
me.changeData.variables++;
// Create a new name from (1) or (2) methods
do {
if (possible.size) {
// (1) Re-use previously generated name
var first = possible.values().next().value;
possible["delete"](first);
newName = first;
} else {
// (2) Create a new name with global `nameGen`
var generatedName = me.obfuscator.nameGen.generate();
newName = generatedName;
generated.push(generatedName);
}
} while (scopePath.scope.hasGlobal(newName) || me.obfuscator.nameGen.notSafeForReuseNames.has(newName));
// Ensure global names aren't overridden
}
newNames.set(name, newName);
}
// console.log(node.type, newNames);
} catch (err) {
_iterator3.e(err);
} finally {
_iterator3.f();
}
renamedVariables.set(node, newNames);
}
};
return {
visitor: _objectSpread(_objectSpread({}, VariableAnalysisVisitor), VariableRenamingVisitor)
};
};
;