said simply:
I am trying to create a protective barrier around a JavaScript Object, using a Proxy to set 'traps' for any form of retrieval or manipulation. These traps will require the SessionKey parameter to be provided with any such Object manipulations or else default into clearing out -all- information and properties of the Object.
(This SessionKey is of course the one provided by the User Sign-in PHP which is sent back upon successful sign-in.)
If I have this right, and I'm not the most veteran coder here certainly, the Object will only call functions with the corresponding SessionKey parameter being provided - as this Object knows the SessionKey.
I cannot be 100% to thwart any or all such efforts to get into my code, but perhaps I can set up a 'trip' alarm that makes all such efforts unsuccessful. No SessionKey? NO DOM (.empty()), no WebServices/API. Nothing.
Thank you for your help, I appreciate it immensely.
What you are wanting can't really be done. You CAN create a proxy to trap retrieval/manipulation calls but you can't make the underlying object private in any way.
For example, if you have object
const privateObj = { name: 'John Smith', ssn: '123-45-6789' };
and proxy
const proxy = new Proxy(privateObj, {} /* handler for getter/setter traps */);
you can console log the proxy to get something like this:
[[Handler]]: Object
[[Target]]: Object
[[IsRevoked]]: false
and you can expand [[Target]]
to see the properties of the underlying object. So if you want this property to be fully private you won't want to use proxies. Furthermore, if the user can inspect the proxy, they can easily get access to the underlying object and mutate it outside of the proxy traps.
If you want to be able to really protect that object, it would be better to protect it in a function closure and have getter/setter wrappers around that object.
You could try as a first step:
const protectObject = (SessionKey, ...objectProps) => {
const protectedObject = { // Do something here to create the object
...objectProps // and its properties you want to protect
};
return {
accessProp(_SessionKey, prop) {
if (_SessionKey !== SessionKey) throw Error("Your session key doesn't match");
return protectedObject[prop];
},
setProp(_SessionKey, prop, val) {
if (_SessionKey !== SessionKey) throw Error("Your session key doesn't match");
protectedObject[prop] = val;
}
};
};
So now you have a private object that is protected:
const privateObj = protectObject('12345', 'John Smith', '7/20/1992', '123-45-6789');
privateObj.accessProp('12345', 1); // '7/20/1992'
privateObj.accessProp('1234', 2); // Uncaught Error: Your session key doesn't match
privateObj.setProp('12345', 1, '7/21/1993');
privateObj.accessProp('12345', 1); // '7/21/1993'