Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support Conditional Clicking in Broker Protection #1141

Merged
merged 18 commits into from
Nov 21, 2024
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
64 changes: 64 additions & 0 deletions injected/integration-test/broker-protection.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -411,6 +411,70 @@ test.describe('Broker Protection communications', () => {
await page.waitForURL(url => url.hash === '#1-2', { timeout: 2000 })
})

test('conditional clicks - hard-coded success', async ({ page }, workerInfo) => {
const dbp = BrokerProtectionPage.create(page, workerInfo)
await dbp.enabled()
await dbp.navigatesTo('conditional-clicks.html')
await dbp.receivesAction('conditional-clicks-hard-coded-success.json')
const response = await dbp.waitForMessage('actionCompleted')

dbp.isSuccessMessage(response)
await page.waitForURL(url => url.hash === '#yes', { timeout: 2000 })
})

test('conditional clicks - hard-coded default', async ({ page }, workerInfo) => {
const dbp = BrokerProtectionPage.create(page, workerInfo)
await dbp.enabled()
await dbp.navigatesTo('conditional-clicks.html')
await dbp.receivesAction('conditional-clicks-hard-coded-default.json')
const response = await dbp.waitForMessage('actionCompleted')

dbp.isSuccessMessage(response)
await page.waitForURL(url => url.hash === '#no', { timeout: 2000 })
})

test('conditional clicks - do not throw error on defined (but empty) default', async ({ page }, workerInfo) => {
const dbp = BrokerProtectionPage.create(page, workerInfo)
await dbp.enabled()
await dbp.navigatesTo('conditional-clicks.html')
await dbp.receivesAction('conditional-clicks-hard-coded-null-default.json')
const response = await dbp.waitForMessage('actionCompleted')

dbp.isSuccessMessage(response)
})

test('conditional clicks - throw error if default is undefined', async ({ page }, workerInfo) => {
const dbp = BrokerProtectionPage.create(page, workerInfo)
await dbp.enabled()
await dbp.navigatesTo('conditional-clicks.html')
await dbp.receivesAction('conditional-clicks-hard-coded-undefined-default.json')
const response = await dbp.waitForMessage('actionCompleted')

dbp.isErrorMessage(response)
})

test('conditional clicks - interpolated success', async ({ page }, workerInfo) => {
const dbp = BrokerProtectionPage.create(page, workerInfo)
await dbp.enabled()
await dbp.navigatesTo('conditional-clicks.html')
await dbp.receivesAction('conditional-clicks-interpolated-success.json')
const response = await dbp.waitForMessage('actionCompleted')

dbp.isSuccessMessage(response)
await page.waitForURL(url => url.hash === '#yes', { timeout: 2000 })
})

test('conditional clicks - interpolated default', async ({ page }, workerInfo) => {
const dbp = BrokerProtectionPage.create(page, workerInfo)
await dbp.enabled()
await dbp.navigatesTo('conditional-clicks.html')
await dbp.receivesAction('conditional-clicks-interpolated-default.json')
const response = await dbp.waitForMessage('actionCompleted')

dbp.isSuccessMessage(response)
await page.waitForURL(url => url.hash === '#no', { timeout: 2000 })
})

test('getCaptchaInfo', async ({ page }, workerInfo) => {
const dbp = BrokerProtectionPage.create(page, workerInfo)
await dbp.enabled()
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
{
"state": {
"action": {
"actionType": "click",
"id": "1",
"choices": [
{
"condition": {
"left": "40",
"operation": ">=",
"right": "45"
},
"elements": [
{ "type": "button", "selector": ".//a[text()='Yes']" }
]
}
],
"default": {
"elements": [
{ "type": "button", "selector": ".//a[text()='No']" }
]
}
}
}
}

Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
{
"state": {
"action": {
"actionType": "click",
"id": "1",
"choices": [
{
"condition": {
"left": "40",
"operation": ">=",
"right": "45"
},
"elements": [
{ "type": "button", "selector": ".//a[text()='Yes']" }
]
}
],
"default": null
}
}
}

Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
{
"state": {
"action": {
"actionType": "click",
"id": "1",
"choices": [
{
"condition": {
"left": "50",
"operation": ">=",
"right": "45"
},
"elements": [
{ "type": "button", "selector": ".//a[text()='Yes']" }
]
}
],
"default": {
"elements": [
{ "type": "button", "selector": ".//a[text()='No']" }
]
}
}
}
}

Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
{
"state": {
"action": {
"actionType": "click",
"id": "1",
"retry": {
"environment": "web",
"interval": { "ms": 1000 },
"maxAttempts": 1
},
"choices": [
{
"condition": {
"left": "40",
"operation": ">=",
"right": "45"
},
"elements": [
{ "type": "button", "selector": ".//a[text()='Yes']" }
]
}
]
}
}
}

Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
{
"state": {
"action": {
"actionType": "click",
"id": "1",
"choices": [
{
"condition": {
"left": "${age}",
"operation": ">=",
"right": "45"
},
"elements": [
{ "type": "button", "selector": ".//a[text()='Yes']" }
]
}
],
"default": {
"elements": [
{ "type": "button", "selector": ".//a[text()='No']" }
]
}
},
"data": {
"userProfile": {
"age": "40"
}
}
}
}



Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
{
"state": {
"action": {
"actionType": "click",
"id": "1",
"choices": [
{
"condition": {
"left": "${age}",
"operation": ">=",
"right": "45"
},
"elements": [
{ "type": "button", "selector": ".//a[text()='Yes']" }
]
}
],
"default": {
"elements": [
{ "type": "button", "selector": ".//a[text()='No']" }
]
}
},
"data": {
"userProfile": {
"age": "50"
}
}
}
}



Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Broker Protection</title>
</head>
<body>
<div class="result">
<h3>Is John Doe over the age of 45?</h3>
<a href="#" class="answer" data-id="yes">Yes</a>
<a href="#" class="answer" data-id="no">No</a>
</div>
<script>
document.querySelectorAll('.answer').forEach(answer =>
answer.addEventListener('click', function(e) {
e.preventDefault();
const id = this.getAttribute('data-id');

window.location.hash = id;
this.removeEventListener('click', arguments.callee);
})
);
</script>
</body>
</html>
103 changes: 102 additions & 1 deletion injected/src/features/broker-protection/actions/click.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { getElements } from '../utils.js'
import { ErrorResponse, SuccessResponse } from '../types.js'
import { extractProfiles } from './extract.js'
import { processTemplateStringWithUserData } from './build-url-transforms.js'

/**
* @param {Record<string, any>} action
Expand All @@ -9,8 +10,80 @@
* @return {import('../types.js').ActionResponse}
*/
export function click (action, userData, root = document) {
let elements = [];

Check failure on line 13 in injected/src/features/broker-protection/actions/click.js

View workflow job for this annotation

GitHub Actions / unit (ubuntu-latest)

Extra semicolon

if (action.choices?.length) {
// const elements = evaluateChoices(action.choices, userData, root)
if ('elements' in action) {
return new ErrorResponse({ actionID: action.id, message: 'Elements should be nested inside of choices' });

Check failure on line 18 in injected/src/features/broker-protection/actions/click.js

View workflow job for this annotation

GitHub Actions / unit (ubuntu-latest)

Extra semicolon
}

let conditionMet = false;

Check failure on line 21 in injected/src/features/broker-protection/actions/click.js

View workflow job for this annotation

GitHub Actions / unit (ubuntu-latest)

Extra semicolon

for (const choice of action.choices) {
if (!('condition' in choice) || !('elements' in choice)) {
return new ErrorResponse({ actionID: action.id, message: 'All choices must have a condition and elements' });

Check failure on line 25 in injected/src/features/broker-protection/actions/click.js

View workflow job for this annotation

GitHub Actions / unit (ubuntu-latest)

Extra semicolon
}

let compare;

Check failure on line 28 in injected/src/features/broker-protection/actions/click.js

View workflow job for this annotation

GitHub Actions / unit (ubuntu-latest)

Extra semicolon

try {
compare = getComparisonFunction(choice.condition.operation);

Check failure on line 31 in injected/src/features/broker-protection/actions/click.js

View workflow job for this annotation

GitHub Actions / unit (ubuntu-latest)

Extra semicolon
} catch (error) {
return new ErrorResponse({ actionID: action.id, message: error.message });

Check failure on line 33 in injected/src/features/broker-protection/actions/click.js

View workflow job for this annotation

GitHub Actions / unit (ubuntu-latest)

Extra semicolon
}

// Test whether this works without a URL and change the type if so.
const left = processTemplateStringWithUserData(choice.condition.left, action, userData);

Check failure on line 37 in injected/src/features/broker-protection/actions/click.js

View workflow job for this annotation

GitHub Actions / unit (ubuntu-latest)

Extra semicolon
const right = processTemplateStringWithUserData(choice.condition.right, action, userData);

Check failure on line 38 in injected/src/features/broker-protection/actions/click.js

View workflow job for this annotation

GitHub Actions / unit (ubuntu-latest)

Extra semicolon

let result;

Check failure on line 40 in injected/src/features/broker-protection/actions/click.js

View workflow job for this annotation

GitHub Actions / unit (ubuntu-latest)

Extra semicolon

try {
result = compare(left, right);
} catch (error) {
return new ErrorResponse({ actionID: action.id, message: `Comparison failed with the following error: ${error.message}` });
}

if (result) {
// Should we bail here so we don't evaluate two true conditions?
elements = choice.elements;
conditionMet = true;
}
}

if (!conditionMet) {
// If there's no default defined, return an error.
if (!('default' in action)) {
return new ErrorResponse({ actionID: action.id, message: 'All conditions failed and no default action was provided' });
}

// If there is a default and it's null (meaning skip any further action) return success.
if (action.default === null) {
return new SuccessResponse({ actionID: action.id, actionType: action.actionType, response: null })
}

// If the default is defined and not null (without elements), return an error.
if (!('elements' in action.default)) {
return new ErrorResponse({ actionID: action.id, message: 'No elements were provided in the default action' });
}

elements = action.default.elements;
}
} else {
if (!('elements' in action)) {
return new ErrorResponse({ actionID: action.id, message: 'No elements provided to click action' });
}

elements = action.elements;
}

if (!elements.length) {
return new ErrorResponse({ actionID: action.id, message: 'No elements provided to click action' });
}

// there can be multiple elements provided by the action
for (const element of action.elements) {
for (const element of elements) {
const rootElement = selectRootElement(element, userData, root)
const elements = getElements(rootElement, element.selector)

Expand Down Expand Up @@ -63,3 +136,31 @@

throw new Error('`parent` was present on the element, but the configuration is not supported')
}

/**
*
* @param {string} operator
* @returns
*/
export function getComparisonFunction(operator) {
switch (operator) {
case "==":
return (a, b) => a == b;
case "===":
return (a, b) => a === b;
case "!=":
return (a, b) => a != b;
case "!==":
return (a, b) => a !== b;
case "<":
return (a, b) => a < b;
case "<=":
return (a, b) => a <= b;
case ">":
return (a, b) => a > b;
case ">=":
return (a, b) => a >= b;
default:
throw new Error(`Invalid operator: ${operator}`);
}
}
Loading