javascript-private-state icon indicating copy to clipboard operation
javascript-private-state copied to clipboard

Reflect mechanism to determine if a slot is accessible or not

Open ljharb opened this issue 10 years ago • 4 comments

Having to try/catch in order to prevent a runtime ReferenceError doesn't seem like an elegant or performant approach - could there also be a Reflect.hasDataSlot or similar, that takes an object and a data slot name, and returns true or false?

Assuming #2, we'd only want one method that returned false when the slot was either absent or inaccessible.

ljharb avatar Nov 12 '15 01:11 ljharb

One of our starting requirements was that there would be no reflection APIs for accessing private slots. This was security motivated.

Note that a "name" would not be sufficient for making that query. The "key" of a private slot (called a "slot key") in the document is a pair consisting of a name and a declaration site. "Declaration sites" are not reified values. They are only implicitly accessible from within the class body that declares a private slot (or the body of a class that inherits a protected slot).

A class could expose a method for testing for the existence of a slot it declares:

class Foo {
   private #bar;
   static hasBar(obj) {
       try {
          obj.#bar;
          return true;
        } catch (e) {
          return false
         }
      }
}
Foo.hasBar( {} ); //should answer false

allenwb avatar Nov 12 '15 04:11 allenwb

There are a lot of methods that Reflect offers that return a boolean where the Object method would throw - would the same motivation not apply here? Forcing try/catch to protect against an almost inevitable runtime error doesn't seem like a good API choice - there are many complaints about JSON.parse in the same vein.

Note that this isn't a request for a general reflection mechanism, merely a non-try/catch-based way to protect against runtime errors.

ljharb avatar Nov 12 '15 04:11 ljharb

No reflection is a starting position. If some reflection operation can be demonstrated to be security safe and sufficiently useful, there should be a problem.

Note that Reflect methods exist in order to fully rectify MOP calls. The Boolean results weren't a primary requirement but something that turned out to be reasonable and useful.

allenwb avatar Nov 12 '15 04:11 allenwb

What you are really asking for, I think, is a nominal type test. One option might be to (later) introduce a new context-sensitive binary operator to perform such a test.

zenparsing avatar Nov 12 '15 05:11 zenparsing