Last active
October 24, 2018 15:00
-
-
Save zhibirc/f18d161e6990e82bcbefd53864a840af to your computer and use it in GitHub Desktop.
Protect API methods or arbitrary functions from introspection
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* 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); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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. :)