Skip to content

Instantly share code, notes, and snippets.

@zhibirc
Last active October 24, 2018 15:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zhibirc/f18d161e6990e82bcbefd53864a840af to your computer and use it in GitHub Desktop.
Save zhibirc/f18d161e6990e82bcbefd53864a840af to your computer and use it in GitHub Desktop.
Protect API methods or arbitrary functions from introspection
/* Aim:
"function <function name>() {
[native code]
}"
*/
function protect ( fn ) {
fn.toString = fn.toLocaleString = fn.toSource = function () {
return 'function ' + fn.name + '() { [native code] }';
};
}
// but indirect call still available, so fix it
var protect = (function () {
// function can be reassign with different name, so use functions itself instead of string names
// due to browser optimizations it isn't an overhead probably
var protectedFunctions = [];
Function.prototype.toString.call =
Function.prototype.toSource.call =
Function.prototype.toLocaleString.call =
Function.prototype.toString.apply =
Function.prototype.toSource.apply =
Function.prototype.toLocaleString.apply = function ( thisArg ) {
if ( ~protectedFunctions.indexOf(thisArg) ) {
return 'function ' + thisArg.name + '() { [native code] }';
}
};
return function ( fn ) {
if ( !~protectedFunctions.indexOf(fn) ) {
protectedFunctions.push(fn);
fn.toString = fn.toLocaleString = fn.toSource = function () {
return 'function ' + fn.name + '() { [native code] }';
};
}
};
}());
// some function that should be protected
function apiMethod () { /* code here */ }
// protection
protect(apiMethod);
@zhibirc
Copy link
Author

zhibirc commented Oct 24, 2018

It's not 100% guarantee of safety, honestly speaking isn't even 50%... But as a small piece of large and comprehensive security subsystem -- why not? In any case it was a funny task in former times. :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment