Skip to content

Commit

Permalink
Add trusted modifier (#6149)
Browse files Browse the repository at this point in the history
Fixes #6137

Adding a trusted modifier to make events not be dispatchable by console/sourcecode.
Useful to prevent injected code to automatically dispatch event for preventing botting
  • Loading branch information
Kapsonfire-DE authored Jun 27, 2021
1 parent e43778a commit b464320
Show file tree
Hide file tree
Showing 6 changed files with 25 additions and 2 deletions.
3 changes: 2 additions & 1 deletion src/compiler/compile/nodes/Element.ts
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,8 @@ const valid_modifiers = new Set([
'once',
'passive',
'nonpassive',
'self'
'self',
'trusted'
]);

const passive_events = new Set([
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ export default class EventHandlerWrapper {
if (this.node.modifiers.has('preventDefault')) snippet = x`@prevent_default(${snippet})`;
if (this.node.modifiers.has('stopPropagation')) snippet = x`@stop_propagation(${snippet})`;
if (this.node.modifiers.has('self')) snippet = x`@self(${snippet})`;
if (this.node.modifiers.has('trusted')) snippet = x`@trusted(${snippet})`;

const args = [];

Expand Down
7 changes: 7 additions & 0 deletions src/runtime/internal/dom.ts
Original file line number Diff line number Diff line change
Expand Up @@ -214,6 +214,13 @@ export function self(fn) {
};
}

export function trusted(fn) {
return function(event) {
// @ts-ignore
if (event.isTrusted) fn.call(this, event);
};
}

export function attr(node: Element, attribute: string, value?: string) {
if (value == null) node.removeAttribute(attribute);
else if (node.getAttribute(attribute) !== value) node.setAttribute(attribute, value);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
export default {
async test({ assert, component, target, window }) {
const button = target.querySelector('button');
const event = new window.MouseEvent('click');

await button.dispatchEvent(event);
assert.equal(component.trusted, true);
}
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
<script>
export let trusted = true;
</script>

<button on:click|trusted="{() => trusted = false}">Only trusted events: {trusted?'true':'false'}</button>
2 changes: 1 addition & 1 deletion test/validator/samples/event-modifiers-invalid/errors.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
[{
"message": "Valid event modifiers are preventDefault, stopPropagation, capture, once, passive, nonpassive or self",
"message": "Valid event modifiers are preventDefault, stopPropagation, capture, once, passive, nonpassive, self or trusted",
"code": "invalid-event-modifier",
"start": {
"line": 1,
Expand Down

0 comments on commit b464320

Please sign in to comment.