trusted-types
trusted-types copied to clipboard
JavaScript event for tracking (and blocking) policy creation
Pulling out from #222 and #235:
If policy name or rules would only be inspected, but not modified by the JS meta policy callback, and (apart from arbitrary side effects) the decision relevant to TT from the meta callback could be simply to stop the policy creation, then using regular events would work. In an imaginary implementation:
trustedTypes.browserInternalCreatePolicyImpl_ = function(name, rules) {
const details = {"detail": {
name: name,
rules: /* shallow clone to prevent mutation */ Object.assign({}, rules}}};
Object.freeze(details);
var event = new CustomEvent("beforecreatepolicy", details);
if (!trustedTypes.dispatchEvent(event)) {
// policy creation prevented. console.log something.
return;
}
actuallyCreatePolicy_(name, rules);
}
the following code would work:
trustedTypes.addEventListener('beforecreatepolicy', (e) => {
// inspect e.details.name or e.details.rules
// throw an Error to inspect the stack
e.preventDefault(); // don't let this policy be created.
});
In this model, multiple event handlers could be setup. Any of them could cancel policy creation, but none could undo that decision. You get inspectability into the body of the policies (so secrets in policy bodies could be revealed), and you could even call the inner policy functions, but that seems fine (inner policy functions return strings, not trusted types)
Any code can already do that by playing with prototypes, so we're not giving capabilities that don't already exist. It also seems to reuse a model familiar to authors, and gives enough control to implement practical limitations without allowing too much surprising and hard to debug behavior (e.g. the policy rules being suddenly replaced for a dependency from the event handler).
Originally posted by @koto in https://github.com/w3c/webappsec-trusted-types/issues/222#issuecomment-550484039
/cc @xtofian @bakkot @Siegrift @otherdaniel @Sora2455 from previous bugs about this.
First comment has a rough sketch of the proposal. Does it look OK on your end? We wanted to start speccing it.
While this would be a v2 feature and so not in the current spec draft it would be good if someone could make a draft PR to add in the beforecreatepolicy event, makes it easier to evaluate.