Skip to content

Open-source AI browser agent for Chrome and Firefox (monorepo) 🧠

fix(permission): group low-risk search approvals

alectimison-makerf21e6fb9c7cf
diff --git a/src/chrome/src/agent/agent.js b/src/chrome/src/agent/agent.js
index 74a64ad1c..f82e8b38b 100644
--- a/src/chrome/src/agent/agent.js
+++ b/src/chrome/src/agent/agent.js
@@ -93,7 +93,7 @@ import {
normalizeCloudflareManagedChallengeState,
} from './cloudflare-managed-challenge.js';
import { getRecordingStateFresh as recorderStateFresh } from '../recorder/host.js';
-import { Capability, CAPABILITY_LABEL, capabilitiesFor, requiredHosts, frameHostMatches, isNetworkMutation, normalizeHost, PermissionManager, UNTRUSTED_CONTENT_TOOLS } from './permission-gate.js';
+import { Capability, CAPABILITY_LABEL, SubmitRisk, capabilitiesFor, classifySearchNavigation, classifySubmitRisk, requiredHosts, frameHostMatches, isNetworkMutation, normalizeHost, PermissionManager, submitActionKey, UNTRUSTED_CONTENT_TOOLS } from './permission-gate.js';
import {
buildPlannerMessages,
buildPlannerIntentMessages,
@@ -11742,6 +11742,7 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
&& this._isFormValidationCandidate(fnName, fnArgs);
let formValidationAllFrames = false;
let detectedSubmitAction = null;
+ let groupedSearchForm = null;
let formValidationBefore = [];
let validationBlock = null;
if (formValidationCandidate) {
@@ -11869,8 +11870,25 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
const requiresMandatoryWebMCPGates = fnName === 'execute_webmcp_tool';
const bypassesConsequentialGates = !requiresMandatoryWebMCPGates
&& (this._skipPermissionGate || scheduledBypassesGate);
+ if (
+ !protectedPageFailure
+ && !bypassesConsequentialGates
+ && this.permissions.hasIntentCandidate(tabId)
+ && ['type_ax', 'type_text', 'iframe_type'].includes(fnName)
+ ) {
+ try {
+ const resolvedForm = await detectSubmitWithDeadline();
+ if (resolvedForm?.resolvedForm === true) groupedSearchForm = resolvedForm;
+ } catch (error) {
+ if (error?.code !== 'content_action_timeout') throw error;
+ const loopStop = await recordPagePreparationTimeout(error, 'grouped-search form detection');
+ if (loopStop) return loopStop;
+ if (interruptFailedBrowserAction(toolIndex, fnName)) { navNotices.length = 0; break; }
+ continue;
+ }
+ }
if (!protectedPageFailure && !bypassesConsequentialGates) {
- let submitConfirmation = detectedSubmitAction;
+ let submitConfirmation = detectedSubmitAction || groupedSearchForm;
if (!submitConfirmation) {
try {
submitConfirmation = await detectSubmitWithDeadline();
@@ -11881,10 +11899,51 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
if (interruptFailedBrowserAction(toolIndex, fnName)) { navNotices.length = 0; break; }
continue;
}
+ if (
+ submitConfirmation?.resolvedForm === true
+ && ['type_ax', 'type_text', 'iframe_type'].includes(fnName)
+ ) {
+ groupedSearchForm = submitConfirmation;
+ }
}
detectedSubmitAction = submitConfirmation;
if (submitConfirmation?.isSubmit) {
- const choice = await this._promptSubmitConfirmation(tabId, submitConfirmation, onUpdate);
+ const submitRisk = classifySubmitRisk(submitConfirmation, submitConfirmation.url);
+ const canGroupSearch = submitRisk.risk === SubmitRisk.LOW_RISK_SEARCH
+ && ['click', 'click_ax', 'press_keys'].includes(fnName);
+ let choice = null;
+ if (canGroupSearch) {
+ const intentKey = submitActionKey(submitConfirmation, submitConfirmation.url);
+ const intentVerdict = this.permissions.checkIntent(intentKey, tabId);
+ if (intentVerdict.allowed) {
+ choice = 'once';
+ } else if (intentVerdict.needsPrompt) {
+ choice = await this._promptGroupedSearchPermission(tabId, submitRisk.host, onUpdate);
+ if (choice === null) {
+ const value = '[Stopped by user before executing requested tool calls.]';
+ this._appendSyntheticToolResults(tabId, toolCalls, toolIndex, messages, onUpdate, step, () => ({
+ success: false,
+ cancelled: true,
+ error: value,
+ }));
+ onUpdate('warning', { message: 'Stopped by user.' });
+ return { action: 'abort', value };
+ }
+ this.permissions.recordIntent(
+ intentKey,
+ [Capability.NAVIGATE, Capability.TYPE, Capability.CLICK],
+ choice === 'once' ? 'allow' : 'deny',
+ tabId,
+ );
+ } else {
+ choice = 'deny';
+ }
+ if (choice === 'once') {
+ capabilities = capabilities.filter(capability => capability !== Capability.CLICK);
+ }
+ } else {
+ choice = await this._promptSubmitConfirmation(tabId, submitConfirmation, onUpdate);
+ }
if (choice === null) {
const value = '[Stopped by user before executing requested tool calls.]';
this._appendSyntheticToolResults(tabId, toolCalls, toolIndex, messages, onUpdate, step, () => ({
@@ -11902,11 +11961,13 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
content: JSON.stringify({
success: false,
denied: true,
- submitConfirmationRequired: true,
- error: `The user did not confirm submitting the form on ${submitConfirmation.host || 'this site'}. Do NOT retry this submit action unless the user explicitly confirms it.`,
+ ...(canGroupSearch ? { permissionRequired: true, groupedPermission: true } : { submitConfirmationRequired: true }),
+ error: canGroupSearch
+ ? `The user did not allow the grouped low-risk search actions on ${submitRisk.host || submitConfirmation.host || 'this site'}. Do NOT retry this unchanged search unless the user explicitly allows it.`
+ : `The user did not confirm submitting the form on ${submitConfirmation.host || 'this site'}. Do NOT retry this submit action unless the user explicitly confirms it.`,
}),
});
- onUpdate('warning', { message: 'Form submission blocked until the user confirms.' });
+ onUpdate('warning', { message: canGroupSearch ? 'Low-risk search blocked until the user allows the grouped actions.' : 'Form submission blocked until the user confirms.' });
if (interruptFailedBrowserAction(toolIndex, fnName)) { navNotices.length = 0; break; }
continue;
}
@@ -11916,11 +11977,58 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
// card for same-frame submissions. iframe_click is different: the
// generic gate is what identifies and fail-closes the target frame host
// when urlFilter is missing, so keep CLICK for that tool.
- if (fnName !== 'iframe_click' && !requiresMandatoryWebMCPGates) {
+ if (!canGroupSearch && fnName !== 'iframe_click' && !requiresMandatoryWebMCPGates) {
capabilities = capabilities.filter(capability => capability !== Capability.CLICK);
}
}
}
+ if (
+ groupedSearchForm
+ && capabilities.includes(Capability.TYPE)
+ && !bypassesConsequentialGates
+ ) {
+ const groupedRisk = classifySubmitRisk(
+ { ...groupedSearchForm, isSubmit: true },
+ groupedSearchForm.url,
+ );
+ if (groupedRisk.risk === SubmitRisk.LOW_RISK_SEARCH) {
+ const intentKey = submitActionKey(groupedSearchForm, groupedSearchForm.url);
+ const choice = await this._authorizeGroupedSearch(
+ tabId,
+ groupedRisk.host,
+ intentKey,
+ [Capability.NAVIGATE, Capability.TYPE, Capability.CLICK],
+ onUpdate,
+ );
+ if (choice === null) {
+ const value = '[Stopped by user before executing requested tool calls.]';
+ this._appendSyntheticToolResults(tabId, toolCalls, toolIndex, messages, onUpdate, step, () => ({
+ success: false,
+ cancelled: true,
+ error: value,
+ }));
+ onUpdate('warning', { message: 'Stopped by user.' });
+ return { action: 'abort', value };
+ }
+ if (choice !== 'once') {
+ messages.push({
+ role: 'tool',
+ tool_call_id: tc.id,
+ content: JSON.stringify({
+ success: false,
+ denied: true,
+ permissionRequired: true,
+ groupedPermission: true,
+ error: `The user did not allow the grouped low-risk search actions on ${groupedRisk.host || 'this site'}. Do NOT retry this unchanged search unless the user explicitly allows it.`,
+ }),
+ });
+ onUpdate('warning', { message: 'Low-risk search blocked until the user allows the grouped actions.' });
+ if (interruptFailedBrowserAction(toolIndex, fnName)) { navNotices.length = 0; break; }
+ continue;
+ }
+ capabilities = capabilities.filter(capability => capability !== Capability.TYPE);
+ }
+ }
if (
formValidationCandidate
&& formValidationBefore.length === 0
@@ -11943,6 +12051,46 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
if (capabilities.length && !bypassesConsequentialGates) {
await this.permissions.hydrate();
const curUrl = await this._currentUrl(tabId);
+ if (fnName === 'navigate' && capabilities.includes(Capability.NAVIGATE)) {
+ const navigationRisk = classifySearchNavigation(fnArgs?.url, curUrl);
+ if (navigationRisk.risk === SubmitRisk.LOW_RISK_SEARCH) {
+ const choice = await this._authorizeGroupedSearch(
+ tabId,
+ navigationRisk.host,
+ '',
+ [Capability.NAVIGATE, Capability.TYPE, Capability.CLICK],
+ onUpdate,
+ { candidateOnly: true },
+ );
+ if (choice === null) {
+ const value = '[Stopped by user before executing requested tool calls.]';
+ this._appendSyntheticToolResults(tabId, toolCalls, toolIndex, messages, onUpdate, step, () => ({
+ success: false,
+ cancelled: true,
+ error: value,
+ }));
+ onUpdate('warning', { message: 'Stopped by user.' });
+ return { action: 'abort', value };
+ }
+ if (choice !== 'once') {
+ messages.push({
+ role: 'tool',
+ tool_call_id: tc.id,
+ content: JSON.stringify({
+ success: false,
+ denied: true,
+ permissionRequired: true,
+ groupedPermission: true,
+ error: `The user did not allow the grouped low-risk search actions on ${navigationRisk.host || 'this site'}. Do NOT retry this unchanged search unless the user explicitly allows it.`,
+ }),
+ });
+ onUpdate('warning', { message: 'Low-risk search blocked until the user allows the grouped actions.' });
+ if (interruptFailedBrowserAction(toolIndex, fnName)) { navNotices.length = 0; break; }
+ continue;
+ }
+ capabilities = capabilities.filter(capability => capability !== Capability.NAVIGATE);
+ }
+ }
let blocked = null; // { capability, host }
let aborted = false;
let failClosed = false;
@@ -21435,6 +21583,77 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
return 'deny'; // 'deny', or anything unexpected β†’ fail safe
}
+ /**
+ * Ask once for the narrowly scoped, same-site GET-search bundle. This is a
+ * task grant, never an "always" permission, and its form fingerprint lives
+ * in PermissionManager so an unchanged retry does not reopen the card.
+ */
+ async _promptGroupedSearchPermission(tabId, host, onUpdate) {
+ const clarifyId = `perm_group_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 8)}`;
+ const tabPending = this._pendingClarifications.get(tabId) || new Map();
+ this._pendingClarifications.set(tabId, tabPending);
+ const responsePromise = new Promise((resolve) => {
+ tabPending.set(clarifyId, { resolve, ts: Date.now() });
+ });
+
+ if (typeof onUpdate === 'function') {
+ try {
+ onUpdate('clarify', {
+ promptKind: 'permission',
+ clarifyId,
+ permission: {
+ capability: Capability.CLICK,
+ host,
+ grouped: true,
+ groupedCapabilities: [Capability.NAVIGATE, Capability.TYPE, Capability.CLICK],
+ },
+ question: `WebBrain wants to run a same-site, read-only GET search on ${host}. Allow this task-scoped bundle to navigate, type the query, and submit the search once?`,
+ options: ['once', 'deny'],
+ });
+ } catch { /* UI emit must never break the run */ }
+ }
+
+ const response = await responsePromise;
+ tabPending.delete(clarifyId);
+ if (tabPending.size === 0) this._pendingClarifications.delete(tabId);
+ if (response && response.cancelled) return null;
+ return String(response?.answer || '').trim().toLowerCase() === 'once' ? 'once' : 'deny';
+ }
+
+ async _authorizeGroupedSearch(tabId, host, intentKey, capabilities, onUpdate, { candidateOnly = false } = {}) {
+ let verdict = candidateOnly
+ ? this.permissions.checkIntentCandidate(host, tabId)
+ : this.permissions.checkIntent(intentKey, tabId);
+ if (!candidateOnly && !verdict.allowed && verdict.needsPrompt) {
+ const candidateVerdict = this.permissions.checkIntentCandidate(host, tabId);
+ if (candidateVerdict.allowed) {
+ this.permissions.recordIntent(intentKey, capabilities, 'allow', tabId);
+ return 'once';
+ }
+ if (!candidateVerdict.needsPrompt) return 'deny';
+ }
+ if (verdict.allowed) return 'once';
+ if (!verdict.needsPrompt) return 'deny';
+ const choice = await this._promptGroupedSearchPermission(tabId, host, onUpdate);
+ if (choice === null) return null;
+ if (candidateOnly) {
+ this.permissions.recordIntentCandidate(
+ host,
+ capabilities,
+ choice === 'once' ? 'allow' : 'deny',
+ tabId,
+ );
+ } else {
+ this.permissions.recordIntent(
+ intentKey,
+ capabilities,
+ choice === 'once' ? 'allow' : 'deny',
+ tabId,
+ );
+ }
+ return choice;
+ }
+
_isFormValidationCandidate(toolName, args = {}) {
const name = String(toolName || '');
if (name === 'click' || name === 'click_ax' || name === 'iframe_click' || name === 'execute_js') return true;
@@ -22769,7 +22988,7 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
async _detectLikelySubmitAction(tabId, toolName, args = {}, options = {}) {
const name = String(toolName || '');
- const submitCapableTools = new Set(['click', 'click_ax', 'iframe_click', 'set_field', 'press_keys', 'execute_js', 'execute_webmcp_tool']);
+ const submitCapableTools = new Set(['click', 'click_ax', 'iframe_click', 'type_ax', 'type_text', 'iframe_type', 'set_field', 'press_keys', 'execute_js', 'execute_webmcp_tool']);
if (!submitCapableTools.has(name)) return null;
if (name === 'set_field' && !args?.submit) return null;
@@ -22804,6 +23023,7 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
try {
let probeArgs = args || {};
let allFrames = name === 'iframe_click' || name === 'press_keys';
+ if (name === 'iframe_type') allFrames = true;
if (name === 'click' && args?.x != null && args?.y != null && globalThis.chrome?.scripting?.executeScript) {
const frameCoordinateRects = Array.isArray(options?.coordinateFrames)
? options.coordinateFrames
@@ -22838,12 +23058,16 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
return {
isSubmit: true,
host,
+ url: String(detected.url || '').slice(0, 300),
tool: name,
reason: String(detected.reason || 'likely form submission').slice(0, 200),
validationSubmitEvidence: detected.validationSubmitEvidence === 'strong' ? 'strong' : 'heuristic',
summary: String(detected.summary || '').slice(0, 1200),
fields: Array.isArray(detected.fields) ? detected.fields.slice(0, 12) : [],
changedFields: Array.isArray(detected.changedFields) ? detected.changedFields.slice(0, 8) : [],
+ method: String(detected.method || 'GET').slice(0, 20).toUpperCase(),
+ action: String(detected.action || '').slice(0, 300),
+ actionUrl: String(detected.actionUrl || detected.action || '').slice(0, 300),
githubCommitDialogLauncher: detected.githubCommitDialogLauncher === true,
...(Array.isArray(detected.publicationResourceUrls) ? { publicationResourceUrls: detected.publicationResourceUrls.slice(0, 200) } : {}),
publicationResourceUrlsComplete: detected.publicationResourceUrlsComplete === true,
@@ -22861,6 +23085,22 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
transactionPageOrderIdsComplete: detected.transactionPageOrderIdsComplete === true,
};
}
+ const resolvedForm = rawResults.find(item => item?.resolvedForm === true);
+ if (resolvedForm) {
+ return {
+ isSubmit: false,
+ resolvedForm: true,
+ host: normalizeHost(resolvedForm.host || resolvedForm.url || currentUrl) || 'this site',
+ url: String(resolvedForm.url || '').slice(0, 300),
+ tool: name,
+ summary: String(resolvedForm.summary || '').slice(0, 1200),
+ fields: Array.isArray(resolvedForm.fields) ? resolvedForm.fields.slice(0, 12) : [],
+ changedFields: Array.isArray(resolvedForm.changedFields) ? resolvedForm.changedFields.slice(0, 8) : [],
+ method: String(resolvedForm.method || 'GET').slice(0, 20).toUpperCase(),
+ action: String(resolvedForm.action || '').slice(0, 300),
+ actionUrl: String(resolvedForm.actionUrl || resolvedForm.action || '').slice(0, 300),
+ };
+ }
const nonSubmit = rawResults.find(item => item?.resolvedNonSubmitTarget === true);
if (nonSubmit) return { isSubmit: false, resolvedNonSubmitTarget: true };
// Explicit negative: the probe resolved the click target to an editable
@@ -23113,16 +23353,24 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
const summarizeForm = (form, pendingEl = null, pendingValue = null) => {
if (!form) return { summary: '', fields: [], changedFields: [] };
const method = compact(form.getAttribute('method') || form.method || 'GET', 20).toUpperCase();
- const action = (() => {
+ const actionUrl = (() => {
try {
const actionUrl = new URL(form.getAttribute('action') || location.href, location.href);
- actionUrl.search = '';
- actionUrl.hash = '';
- return compact(actionUrl.href, 160);
+ return compact(actionUrl.href, 300);
} catch {
return compact(form.getAttribute('action') || location.href, 160);
}
})();
+ const action = (() => {
+ try {
+ const displayUrl = new URL(actionUrl, location.href);
+ displayUrl.search = '';
+ displayUrl.hash = '';
+ return compact(displayUrl.href, 160);
+ } catch {
+ return actionUrl;
+ }
+ })();
const controls = Array.from(form.querySelectorAll('input, textarea, select, [contenteditable="true"]'))
.filter((el) => {
const type = String(el.type || '').toLowerCase();
@@ -23135,6 +23383,11 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
const changed = el === pendingEl || (!!value && value !== before);
return {
label: labelFor(el),
+ name: compact(el.getAttribute?.('name') || '', 80),
+ id: compact(el.getAttribute?.('id') || '', 80),
+ autocomplete: compact(el.getAttribute?.('autocomplete') || '', 80),
+ ariaLabel: compact(el.getAttribute?.('aria-label') || '', 120),
+ placeholder: compact(el.getAttribute?.('placeholder') || '', 120),
type: compact(el.type || el.tagName || '', 40),
value,
changed,
@@ -23153,6 +23406,9 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
summary: `${origin} ${changedText}`,
fields: fields.slice(0, 12),
changedFields,
+ method,
+ action,
+ actionUrl,
};
};
const transactionOrderScan = (root) => {
@@ -23696,7 +23952,7 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
'a, button, [role="button"], [role="link"], [role="tab"], [role="menuitem"], input:not([type="hidden"]), textarea, select, input[type="button"], input[type="submit"], summary, label, [onclick], [data-action]'
)).filter(isVisible);
const resolveClickTarget = () => {
- if (toolName === 'click_ax' || toolName === 'set_field') {
+ if (toolName === 'click_ax' || toolName === 'set_field' || toolName === 'type_ax') {
try {
if (typeof window.__wb_ax_lookup === 'function' && typeof args.ref_id === 'string') {
return window.__wb_ax_lookup(args.ref_id);
@@ -23705,7 +23961,7 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
return null;
}
if (toolName === 'press_keys') return doc.activeElement;
- if (toolName === 'iframe_click') {
+ if (toolName === 'iframe_click' || toolName === 'iframe_type') {
const filter = compact(args.urlFilter || '', 300).toLowerCase();
const frameUrl = url.toLowerCase();
const frameHost = host.toLowerCase();
@@ -23722,6 +23978,15 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
}
return null;
}
+ if (toolName === 'type_text') {
+ if (args.selector) return deepQuerySelector(doc, args.selector);
+ if (args.index != null) {
+ const index = Number(args.index);
+ const all = interactiveElements();
+ return Number.isFinite(index) ? all[index] || null : null;
+ }
+ return isFormField(doc.activeElement) ? doc.activeElement : null;
+ }
if (toolName !== 'click') return null;
if (args.selector) {
return deepQuerySelector(doc, args.selector);
@@ -23792,6 +24057,17 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
try {
const target = resolveClickTarget();
+ if (['type_ax', 'type_text', 'iframe_type'].includes(toolName)) {
+ const form = target?.form || target?.closest?.('form') || null;
+ if (form) {
+ return {
+ resolvedForm: true,
+ host,
+ url,
+ ...summarizeForm(form, target, args.text || ''),
+ };
+ }
+ }
if (toolName === 'set_field' && args.submit) {
const form = target?.form || target?.closest?.('form') || null;
return submitInfo(form, 'set_field({submit:true})', target, args.text || '', 'strong', target);
diff --git a/src/chrome/src/agent/permission-gate.js b/src/chrome/src/agent/permission-gate.js
index 88042a733..e74e05cab 100644
--- a/src/chrome/src/agent/permission-gate.js
+++ b/src/chrome/src/agent/permission-gate.js
@@ -136,6 +136,188 @@ export const UNTRUSTED_CONTENT_TOOLS = new Set([
const MUTATION_METHODS = new Set(['POST', 'PUT', 'PATCH', 'DELETE']);
+// Keep this small public-suffix approximation local to the pure gate. The
+// permission key itself still uses the exact host; only the conservative
+// same-site search classifier needs registrable-domain comparison.
+const MULTI_LABEL_SITE_SUFFIXES = new Set([
+ 'co.uk', 'co.jp', 'co.kr', 'co.nz', 'co.za', 'co.in', 'co.il', 'co.th',
+ 'com.au', 'com.br', 'com.cn', 'com.mx', 'com.tr', 'com.sg', 'com.hk',
+ 'com.tw', 'com.ar', 'com.co', 'com.pe', 'com.ph', 'com.my', 'com.vn',
+ 'gov.uk', 'gov.au', 'gov.in', 'gov.cn', 'ac.uk', 'ac.jp', 'ac.in', 'ac.kr',
+ 'org.uk', 'org.au', 'org.nz', 'net.au', 'net.uk',
+ 'github.io', 'gitlab.io', 'netlify.app', 'netlify.com', 'vercel.app',
+ 'pages.dev', 'workers.dev', 'herokuapp.com', 'firebaseapp.com', 'web.app',
+ 'glitch.me', 'cloudfront.net', 'azurewebsites.net', 'r2.dev', 'github.dev',
+]);
+
+export const SubmitRisk = {
+ LOW_RISK_SEARCH: 'low_risk_search',
+ FRESH_CONFIRMATION: 'fresh_confirmation',
+};
+
+const SENSITIVE_SUBMIT_FIELD_RE = /(?:password|passwd|pwd|secret|token|api[-_\s]?key|otp|2fa|mfa|credential|verification[-_\s]?code|recovery[-_\s]?code|backup[-_\s]?code|private[-_\s]?key|seed[-_\s]?phrase|passphrase|pin[-_\s]?code|card(?:[-_\s]?(?:number|no|num|holder|expiry|expiration))?|credit[-_\s]?card|cc[-_\s]?(?:number|num|exp)|cvv|cvc|security[-_\s]?code|exp(?:iry|iration)?[-_\s]?(?:date|month|year)?)/i;
+const SEARCH_FIELD_RE = /(?:^|[\s_\-.])(?:q|query|search|keyword|keywords|term|terms|search[-_\s]?query)(?:$|[\s_\-.])/i;
+const SEARCH_PATH_RE = /(?:^|[\s/_-])(?:search|scholar|find|results?)(?:$|[\s/?#_-])/i;
+const SIDE_EFFECT_ACTION_RE = /(?:logout|log[-_]?out|sign[-_]?out|delete|remove|destroy|cancel|unsubscribe|disable|close[-_]?account|terminate|pay|checkout|purchase|order|payment|transfer|withdraw|publish|post|send|message|create|update|save|confirm|approve|register|login|sign[-_]?in|password|account)/i;
+
+function submitFieldDescriptor(field = {}) {
+ return [
+ field.type,
+ field.name,
+ field.id,
+ field.autocomplete,
+ field.ariaLabel,
+ field.placeholder,
+ field.label,
+ ].map(value => String(value || '').trim()).filter(Boolean).join(' ');
+}
+
+function shortHash(value) {
+ let hash = 2166136261;
+ const text = String(value || '');
+ for (let i = 0; i < text.length; i++) {
+ hash ^= text.charCodeAt(i);
+ hash = Math.imul(hash, 16777619);
+ }
+ return (hash >>> 0).toString(16);
+}
+
+export function registrableHost(input) {
+ const host = normalizeHost(input);
+ if (!host) return '';
+ if (host.includes(':') || /^\d+\.\d+\.\d+\.\d+$/.test(host)) return host;
+ const parts = host.split('.');
+ if (parts.length < 2) return host;
+ const suffix = parts.slice(-2).join('.');
+ return parts.length >= 3 && MULTI_LABEL_SITE_SUFFIXES.has(suffix)
+ ? parts.slice(-3).join('.')
+ : suffix;
+}
+
+function submitActionUrl(submitInfo = {}, currentUrlOrHost = '') {
+ const rawAction = submitInfo.actionUrl || submitInfo.action || submitInfo.url || currentUrlOrHost;
+ const base = submitInfo.url || currentUrlOrHost;
+ try {
+ const parsed = new URL(rawAction, base);
+ if (!/^https?:$/i.test(parsed.protocol)) return null;
+ return parsed;
+ } catch {
+ return null;
+ }
+}
+
+function freshSubmitRisk(reason) {
+ return { risk: SubmitRisk.FRESH_CONFIRMATION, lowRisk: false, reason };
+}
+
+/**
+ * Classify the resolved form, not the task wording or arbitrary page prose.
+ * This is deliberately conservative: only a same-registrable-site GET search
+ * with no credential/payment fields and no side-effect marker is grouped.
+ */
+export function classifySubmitRisk(submitInfo = {}, currentUrlOrHost = '') {
+ if (submitInfo?.isSubmit !== true) return freshSubmitRisk('not a resolved form submission');
+ const method = String(submitInfo.method || 'GET').trim().toUpperCase();
+ if (method !== 'GET') return freshSubmitRisk(`HTTP ${method || 'GET'} form method`);
+
+ const actionUrl = submitActionUrl(submitInfo, currentUrlOrHost);
+ const pageUrl = submitInfo.url || currentUrlOrHost;
+ let pageParsed = null;
+ try { pageParsed = new URL(pageUrl); } catch {}
+ if (!actionUrl || !pageParsed || !/^https?:$/i.test(pageParsed.protocol)) {
+ return freshSubmitRisk('unresolved HTTP form action');
+ }
+ const actionHost = normalizeHost(actionUrl.hostname);
+ const pageHost = normalizeHost(pageUrl);
+ if (!actionHost || !pageHost || registrableHost(actionHost) !== registrableHost(pageHost)) {
+ return freshSubmitRisk('cross-site form action');
+ }
+
+ const fields = Array.isArray(submitInfo.fields) ? submitInfo.fields.slice(0, 20) : [];
+ if (!fields.length) return freshSubmitRisk('form has no resolved search fields');
+ if (fields.some(field => SENSITIVE_SUBMIT_FIELD_RE.test(submitFieldDescriptor(field)))) {
+ return freshSubmitRisk('form contains a credential or payment field');
+ }
+
+ const pathname = actionUrl.pathname || '/';
+ const actionParameters = [...actionUrl.searchParams.keys()].join(' ');
+ if (SIDE_EFFECT_ACTION_RE.test(`${pathname} ${actionParameters}`)) {
+ return freshSubmitRisk('form action may have side effects');
+ }
+ const fieldMetadata = fields.map(submitFieldDescriptor).join(' ');
+ const searchLike = SEARCH_PATH_RE.test(pathname) || SEARCH_FIELD_RE.test(fieldMetadata) || SEARCH_FIELD_RE.test(actionParameters);
+ if (!searchLike) return freshSubmitRisk('form is not a resolved search');
+
+ return {
+ risk: SubmitRisk.LOW_RISK_SEARCH,
+ lowRisk: true,
+ reason: 'same-site GET search with non-sensitive fields',
+ host: actionHost,
+ method,
+ action: actionUrl.href,
+ };
+}
+
+/**
+ * A navigation can be the first action in a search flow, before the target
+ * form exists. This is only a provisional candidate: the type path must still
+ * re-run classifySubmitRisk against the resolved form before it can use the
+ * grouped grant for data entry or submission.
+ */
+export function classifySearchNavigation(targetUrl, currentUrlOrHost = '') {
+ let target = null;
+ let current = null;
+ try { target = new URL(targetUrl); } catch {}
+ try { current = new URL(currentUrlOrHost); } catch {}
+ if (!target || !/^https?:$/i.test(target.protocol)) return freshSubmitRisk('unresolved search navigation');
+ const targetHost = normalizeHost(target.hostname);
+ const currentHost = current && /^https?:$/i.test(current.protocol)
+ ? normalizeHost(current.hostname)
+ : '';
+ if (currentHost && registrableHost(targetHost) !== registrableHost(currentHost)) {
+ return freshSubmitRisk('cross-site search navigation');
+ }
+ const pathname = target.pathname || '/';
+ const parameters = [...target.searchParams.keys()].join(' ');
+ if (SIDE_EFFECT_ACTION_RE.test(`${pathname} ${parameters}`)) {
+ return freshSubmitRisk('navigation target may have side effects');
+ }
+ if (!SEARCH_PATH_RE.test(pathname) && !SEARCH_FIELD_RE.test(parameters)) {
+ return freshSubmitRisk('navigation target is not a resolved search');
+ }
+ return {
+ risk: SubmitRisk.LOW_RISK_SEARCH,
+ lowRisk: true,
+ reason: 'same-site GET search navigation candidate',
+ host: targetHost,
+ method: 'GET',
+ action: target.href,
+ };
+}
+
+/**
+ * Stable, task-scoped identity for retry deduplication. Values are hashed and
+ * never returned, so a retry key cannot become a secret-bearing telemetry field.
+ */
+export function submitActionKey(submitInfo = {}, currentUrlOrHost = '') {
+ const actionUrl = submitActionUrl(submitInfo, currentUrlOrHost);
+ const host = normalizeHost(actionUrl?.hostname || submitInfo.host || currentUrlOrHost);
+ const method = String(submitInfo.method || 'GET').trim().toUpperCase();
+ const fields = Array.isArray(submitInfo.fields) ? submitInfo.fields : [];
+ const sensitive = fields
+ .filter(field => SENSITIVE_SUBMIT_FIELD_RE.test(submitFieldDescriptor(field)))
+ .map(field => submitFieldDescriptor(field));
+ const changed = (Array.isArray(submitInfo.changedFields) ? submitInfo.changedFields : fields.filter(field => field?.changed))
+ .map(field => [submitFieldDescriptor(field), field?.value || ''].join('='));
+ return [
+ host,
+ actionUrl?.href || String(submitInfo.actionUrl || submitInfo.action || ''),
+ method,
+ `s:${shortHash(sensitive.join('|'))}`,
+ `c:${shortHash(changed.join('|'))}`,
+ ].join('|');
+}
+
/**
* True only for a fetch_url/research_url call carrying a write HTTP method β€”
* the egress the `/allow-api` override was meant to pre-authorize. A GET is NOT
@@ -398,6 +580,8 @@ export class PermissionManager {
this._save = typeof opts.save === 'function' ? opts.save : null;
this._skipAll = typeof opts.skipAll === 'function' ? opts.skipAll : (() => false);
this.permissions = [];
+ this.intentGrants = [];
+ this.intentCandidates = [];
this._hydrated = false;
}
@@ -440,6 +624,68 @@ export class PermissionManager {
*/
beginTurn(tabId) {
this.permissions = this.permissions.filter(p => p.duration === 'always' || p.tabId !== tabId);
+ this.intentGrants = this.intentGrants.filter(grant => grant.tabId !== tabId);
+ this.intentCandidates = this.intentCandidates.filter(candidate => candidate.tabId !== tabId);
+ }
+
+ /**
+ * Check a task-scoped grouped approval. Unlike an "always" grant this is
+ * never persisted or shared with another tab, and the key binds the approval
+ * to the resolved form plus its changed fields.
+ */
+ checkIntent(key, tabId, capability = null) {
+ const grant = this.intentGrants.find(item =>
+ item.key === String(key || '')
+ && item.tabId === tabId
+ && (!capability || item.capabilities.includes(capability))
+ );
+ if (!grant) return { allowed: false, needsPrompt: true };
+ return { allowed: grant.action === 'allow', needsPrompt: false, grant };
+ }
+
+ recordIntent(key, capabilities, action, tabId) {
+ const normalizedKey = String(key || '');
+ if (!normalizedKey) return;
+ this.intentGrants = this.intentGrants.filter(item => !(item.key === normalizedKey && item.tabId === tabId));
+ this.intentGrants.push({
+ key: normalizedKey,
+ capabilities: [...new Set(Array.isArray(capabilities) ? capabilities : [])],
+ action: action === 'allow' ? 'allow' : 'deny',
+ tabId,
+ ts: Date.now(),
+ });
+ }
+
+ hasIntentCandidate(tabId) {
+ return this.intentCandidates.some(candidate => candidate.tabId === tabId);
+ }
+
+ checkIntentCandidate(host, tabId, capability = null) {
+ const targetSite = registrableHost(host);
+ const candidate = this.intentCandidates.find(item =>
+ item.tabId === tabId
+ && registrableHost(item.host) === targetSite
+ && (!capability || item.capabilities.includes(capability))
+ );
+ if (!candidate) return { allowed: false, needsPrompt: true };
+ return { allowed: candidate.action === 'allow', needsPrompt: false, candidate };
+ }
+
+ recordIntentCandidate(host, capabilities, action, tabId) {
+ const normalizedHost = normalizeHost(host);
+ if (!normalizedHost) return;
+ this.intentCandidates = this.intentCandidates.filter(candidate => candidate.tabId !== tabId);
+ this.intentCandidates.push({
+ host: normalizedHost,
+ capabilities: [...new Set(Array.isArray(capabilities) ? capabilities : [])],
+ action: action === 'allow' ? 'allow' : 'deny',
+ tabId,
+ ts: Date.now(),
+ });
+ }
+
+ clearIntentCandidates(tabId) {
+ this.intentCandidates = this.intentCandidates.filter(candidate => candidate.tabId !== tabId);
}
/**
diff --git a/src/chrome/src/agent/scheduler.js b/src/chrome/src/agent/scheduler.js
index 3a3413770..7e28b6909 100644
--- a/src/chrome/src/agent/scheduler.js
+++ b/src/chrome/src/agent/scheduler.js
@@ -101,6 +101,10 @@ function normalizePendingClarify(data, now = Date.now()) {
pending.permission = {
capability: String(permission.capability || '').slice(0, 80),
host: String(permission.host || '').slice(0, 300),
+ ...(permission.grouped === true ? { grouped: true } : {}),
+ ...(Array.isArray(permission.groupedCapabilities)
+ ? { groupedCapabilities: permission.groupedCapabilities.map(value => String(value).slice(0, 80)).slice(0, 6) }
+ : {}),
};
}
const submitConfirmation = asObject(obj.submitConfirmation);
diff --git a/src/chrome/src/ui/sidepanel.js b/src/chrome/src/ui/sidepanel.js
index 00aa3391f..aff78675b 100644
--- a/src/chrome/src/ui/sidepanel.js
+++ b/src/chrome/src/ui/sidepanel.js
@@ -10260,7 +10260,7 @@ function renderClarifyCard(data) {
return;
}
- // Permission-prompt mode: localized question + three fixed choices that
+ // Permission-prompt mode: localized question + fixed choices that
// return a stable VALUE ('once'/'always'/'deny'), and NO free-text input β€”
// so there's nothing to parse and no English/locale dependency.
if (data.permission && data.permission.capability) {
@@ -10273,20 +10273,30 @@ function renderClarifyCard(data) {
// consent wording cannot drift between two English copies; other locales
// carry their own translation under the key.
const resolvedVerb = verb === verbKey ? (CAPABILITY_LABEL[cap] || cap) : verb;
- qEl.textContent = t('sp.perm.question', { verb: resolvedVerb, host });
+ const grouped = data.permission.grouped === true;
+ qEl.textContent = grouped
+ ? String(data.question || `WebBrain wants to run a task-scoped low-risk search on ${host}.`).slice(0, 600)
+ : t('sp.perm.question', { verb: resolvedVerb, host });
const reasonEl = document.createElement('div');
reasonEl.className = 'clarify-reason';
- reasonEl.textContent = t('sp.perm.reason');
+ reasonEl.textContent = grouped
+ ? 'This one-time approval covers only this unchanged search on this tab. It does not allow passwords, payments, mutations, JavaScript, or future tasks.'
+ : t('sp.perm.reason');
card.appendChild(reasonEl);
const optionsEl = document.createElement('div');
optionsEl.className = 'clarify-options';
- const choices = [
- ['once', t('sp.perm.allow_once')],
- ['always', t('sp.perm.always_allow', { host })],
- ['deny', t('sp.perm.dont_allow')],
- ];
+ const choices = grouped
+ ? [
+ ['once', t('sp.perm.allow_once')],
+ ['deny', t('sp.perm.dont_allow')],
+ ]
+ : [
+ ['once', t('sp.perm.allow_once')],
+ ['always', t('sp.perm.always_allow', { host })],
+ ['deny', t('sp.perm.dont_allow')],
+ ];
for (const [value, label] of choices) {
const b = document.createElement('button');
b.type = 'button';
diff --git a/src/firefox/src/agent/agent.js b/src/firefox/src/agent/agent.js
index 2620dec01..d1958ddc0 100644
--- a/src/firefox/src/agent/agent.js
+++ b/src/firefox/src/agent/agent.js
@@ -87,7 +87,7 @@ import {
cloudflareManagedChallengeStorageKey,
normalizeCloudflareManagedChallengeState,
} from './cloudflare-managed-challenge.js';
-import { Capability, CAPABILITY_LABEL, capabilitiesFor, requiredHosts, frameHostMatches, isNetworkMutation, normalizeHost, PermissionManager, UNTRUSTED_CONTENT_TOOLS } from './permission-gate.js';
+import { Capability, CAPABILITY_LABEL, SubmitRisk, capabilitiesFor, classifySearchNavigation, classifySubmitRisk, requiredHosts, frameHostMatches, isNetworkMutation, normalizeHost, PermissionManager, submitActionKey, UNTRUSTED_CONTENT_TOOLS } from './permission-gate.js';
import {
buildPlannerMessages,
buildPlannerIntentMessages,
@@ -10323,6 +10323,7 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
const formValidationCandidate = this._isFormValidationCandidate(fnName, fnArgs);
let formValidationAllFrames = false;
let detectedSubmitAction = null;
+ let groupedSearchForm = null;
let formValidationBefore = [];
let validationBlock = null;
if (formValidationCandidate) {
@@ -10420,8 +10421,25 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
}
const scheduledPolicy = this.scheduledRunPolicies.get(tabId);
const scheduledBypassesGate = scheduledPolicy?.requireConsequentialConfirmation === false;
+ if (
+ !this._skipPermissionGate
+ && !scheduledBypassesGate
+ && this.permissions.hasIntentCandidate(tabId)
+ && ['type_ax', 'type_text', 'iframe_type'].includes(fnName)
+ ) {
+ try {
+ const resolvedForm = await detectSubmitWithDeadline();
+ if (resolvedForm?.resolvedForm === true) groupedSearchForm = resolvedForm;
+ } catch (error) {
+ if (error?.code !== 'content_action_timeout') throw error;
+ const loopStop = await recordPagePreparationTimeout(error, 'grouped-search form detection');
+ if (loopStop) return loopStop;
+ if (interruptFailedBrowserAction(toolIndex, fnName)) { navNotices.length = 0; break; }
+ continue;
+ }
+ }
if (!this._skipPermissionGate && !scheduledBypassesGate) {
- let submitConfirmation = detectedSubmitAction;
+ let submitConfirmation = detectedSubmitAction || groupedSearchForm;
if (!submitConfirmation) {
try {
submitConfirmation = await detectSubmitWithDeadline();
@@ -10432,10 +10450,51 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
if (interruptFailedBrowserAction(toolIndex, fnName)) { navNotices.length = 0; break; }
continue;
}
+ if (
+ submitConfirmation?.resolvedForm === true
+ && ['type_ax', 'type_text', 'iframe_type'].includes(fnName)
+ ) {
+ groupedSearchForm = submitConfirmation;
+ }
}
detectedSubmitAction = submitConfirmation;
if (submitConfirmation?.isSubmit) {
- const choice = await this._promptSubmitConfirmation(tabId, submitConfirmation, onUpdate);
+ const submitRisk = classifySubmitRisk(submitConfirmation, submitConfirmation.url);
+ const canGroupSearch = submitRisk.risk === SubmitRisk.LOW_RISK_SEARCH
+ && ['click', 'click_ax', 'press_keys'].includes(fnName);
+ let choice = null;
+ if (canGroupSearch) {
+ const intentKey = submitActionKey(submitConfirmation, submitConfirmation.url);
+ const intentVerdict = this.permissions.checkIntent(intentKey, tabId);
+ if (intentVerdict.allowed) {
+ choice = 'once';
+ } else if (intentVerdict.needsPrompt) {
+ choice = await this._promptGroupedSearchPermission(tabId, submitRisk.host, onUpdate);
+ if (choice === null) {
+ const value = '[Stopped by user before executing requested tool calls.]';
+ this._appendSyntheticToolResults(tabId, toolCalls, toolIndex, messages, onUpdate, step, () => ({
+ success: false,
+ cancelled: true,
+ error: value,
+ }));
+ onUpdate('warning', { message: 'Stopped by user.' });
+ return { action: 'abort', value };
+ }
+ this.permissions.recordIntent(
+ intentKey,
+ [Capability.NAVIGATE, Capability.TYPE, Capability.CLICK],
+ choice === 'once' ? 'allow' : 'deny',
+ tabId,
+ );
+ } else {
+ choice = 'deny';
+ }
+ if (choice === 'once') {
+ capabilities = capabilities.filter(capability => capability !== Capability.CLICK);
+ }
+ } else {
+ choice = await this._promptSubmitConfirmation(tabId, submitConfirmation, onUpdate);
+ }
if (choice === null) {
const value = '[Stopped by user before executing requested tool calls.]';
this._appendSyntheticToolResults(tabId, toolCalls, toolIndex, messages, onUpdate, step, () => ({
@@ -10453,11 +10512,13 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
content: JSON.stringify({
success: false,
denied: true,
- submitConfirmationRequired: true,
- error: `The user did not confirm submitting the form on ${submitConfirmation.host || 'this site'}. Do NOT retry this submit action unless the user explicitly confirms it.`,
+ ...(canGroupSearch ? { permissionRequired: true, groupedPermission: true } : { submitConfirmationRequired: true }),
+ error: canGroupSearch
+ ? `The user did not allow the grouped low-risk search actions on ${submitRisk.host || submitConfirmation.host || 'this site'}. Do NOT retry this unchanged search unless the user explicitly allows it.`
+ : `The user did not confirm submitting the form on ${submitConfirmation.host || 'this site'}. Do NOT retry this submit action unless the user explicitly confirms it.`,
}),
});
- onUpdate('warning', { message: 'Form submission blocked until the user confirms.' });
+ onUpdate('warning', { message: canGroupSearch ? 'Low-risk search blocked until the user allows the grouped actions.' : 'Form submission blocked until the user confirms.' });
if (interruptFailedBrowserAction(toolIndex, fnName)) { navNotices.length = 0; break; }
continue;
}
@@ -10467,11 +10528,59 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
// card for same-frame submissions. iframe_click is different: the
// generic gate is what identifies and fail-closes the target frame host
// when urlFilter is missing, so keep CLICK for that tool.
- if (fnName !== 'iframe_click') {
+ if (!canGroupSearch && fnName !== 'iframe_click') {
capabilities = capabilities.filter(capability => capability !== Capability.CLICK);
}
}
}
+ if (
+ groupedSearchForm
+ && capabilities.includes(Capability.TYPE)
+ && !this._skipPermissionGate
+ && !scheduledBypassesGate
+ ) {
+ const groupedRisk = classifySubmitRisk(
+ { ...groupedSearchForm, isSubmit: true },
+ groupedSearchForm.url,
+ );
+ if (groupedRisk.risk === SubmitRisk.LOW_RISK_SEARCH) {
+ const intentKey = submitActionKey(groupedSearchForm, groupedSearchForm.url);
+ const choice = await this._authorizeGroupedSearch(
+ tabId,
+ groupedRisk.host,
+ intentKey,
+ [Capability.NAVIGATE, Capability.TYPE, Capability.CLICK],
+ onUpdate,
+ );
+ if (choice === null) {
+ const value = '[Stopped by user before executing requested tool calls.]';
+ this._appendSyntheticToolResults(tabId, toolCalls, toolIndex, messages, onUpdate, step, () => ({
+ success: false,
+ cancelled: true,
+ error: value,
+ }));
+ onUpdate('warning', { message: 'Stopped by user.' });
+ return { action: 'abort', value };
+ }
+ if (choice !== 'once') {
+ messages.push({
+ role: 'tool',
+ tool_call_id: tc.id,
+ content: JSON.stringify({
+ success: false,
+ denied: true,
+ permissionRequired: true,
+ groupedPermission: true,
+ error: `The user did not allow the grouped low-risk search actions on ${groupedRisk.host || 'this site'}. Do NOT retry this unchanged search unless the user explicitly allows it.`,
+ }),
+ });
+ onUpdate('warning', { message: 'Low-risk search blocked until the user allows the grouped actions.' });
+ if (interruptFailedBrowserAction(toolIndex, fnName)) { navNotices.length = 0; break; }
+ continue;
+ }
+ capabilities = capabilities.filter(capability => capability !== Capability.TYPE);
+ }
+ }
if (
formValidationCandidate
&& formValidationBefore.length === 0
@@ -10494,6 +10603,46 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
if (capabilities.length && !this._skipPermissionGate && !scheduledBypassesGate) {
await this.permissions.hydrate();
const curUrl = await this._currentUrl(tabId);
+ if (fnName === 'navigate' && capabilities.includes(Capability.NAVIGATE)) {
+ const navigationRisk = classifySearchNavigation(fnArgs?.url, curUrl);
+ if (navigationRisk.risk === SubmitRisk.LOW_RISK_SEARCH) {
+ const choice = await this._authorizeGroupedSearch(
+ tabId,
+ navigationRisk.host,
+ '',
+ [Capability.NAVIGATE, Capability.TYPE, Capability.CLICK],
+ onUpdate,
+ { candidateOnly: true },
+ );
+ if (choice === null) {
+ const value = '[Stopped by user before executing requested tool calls.]';
+ this._appendSyntheticToolResults(tabId, toolCalls, toolIndex, messages, onUpdate, step, () => ({
+ success: false,
+ cancelled: true,
+ error: value,
+ }));
+ onUpdate('warning', { message: 'Stopped by user.' });
+ return { action: 'abort', value };
+ }
+ if (choice !== 'once') {
+ messages.push({
+ role: 'tool',
+ tool_call_id: tc.id,
+ content: JSON.stringify({
+ success: false,
+ denied: true,
+ permissionRequired: true,
+ groupedPermission: true,
+ error: `The user did not allow the grouped low-risk search actions on ${navigationRisk.host || 'this site'}. Do NOT retry this unchanged search unless the user explicitly allows it.`,
+ }),
+ });
+ onUpdate('warning', { message: 'Low-risk search blocked until the user allows the grouped actions.' });
+ if (interruptFailedBrowserAction(toolIndex, fnName)) { navNotices.length = 0; break; }
+ continue;
+ }
+ capabilities = capabilities.filter(capability => capability !== Capability.NAVIGATE);
+ }
+ }
let blocked = null; // { capability, host }
let aborted = false;
let failClosed = false;
@@ -19191,6 +19340,77 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
return 'deny'; // 'deny', or anything unexpected β†’ fail safe
}
+ /**
+ * Ask once for the narrowly scoped, same-site GET-search bundle. This is a
+ * task grant, never an "always" permission, and its form fingerprint lives
+ * in PermissionManager so an unchanged retry does not reopen the card.
+ */
+ async _promptGroupedSearchPermission(tabId, host, onUpdate) {
+ const clarifyId = `perm_group_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 8)}`;
+ const tabPending = this._pendingClarifications.get(tabId) || new Map();
+ this._pendingClarifications.set(tabId, tabPending);
+ const responsePromise = new Promise((resolve) => {
+ tabPending.set(clarifyId, { resolve, ts: Date.now() });
+ });
+
+ if (typeof onUpdate === 'function') {
+ try {
+ onUpdate('clarify', {
+ promptKind: 'permission',
+ clarifyId,
+ permission: {
+ capability: Capability.CLICK,
+ host,
+ grouped: true,
+ groupedCapabilities: [Capability.NAVIGATE, Capability.TYPE, Capability.CLICK],
+ },
+ question: `WebBrain wants to run a same-site, read-only GET search on ${host}. Allow this task-scoped bundle to navigate, type the query, and submit the search once?`,
+ options: ['once', 'deny'],
+ });
+ } catch { /* UI emit must never break the run */ }
+ }
+
+ const response = await responsePromise;
+ tabPending.delete(clarifyId);
+ if (tabPending.size === 0) this._pendingClarifications.delete(tabId);
+ if (response && response.cancelled) return null;
+ return String(response?.answer || '').trim().toLowerCase() === 'once' ? 'once' : 'deny';
+ }
+
+ async _authorizeGroupedSearch(tabId, host, intentKey, capabilities, onUpdate, { candidateOnly = false } = {}) {
+ let verdict = candidateOnly
+ ? this.permissions.checkIntentCandidate(host, tabId)
+ : this.permissions.checkIntent(intentKey, tabId);
+ if (!candidateOnly && !verdict.allowed && verdict.needsPrompt) {
+ const candidateVerdict = this.permissions.checkIntentCandidate(host, tabId);
+ if (candidateVerdict.allowed) {
+ this.permissions.recordIntent(intentKey, capabilities, 'allow', tabId);
+ return 'once';
+ }
+ if (!candidateVerdict.needsPrompt) return 'deny';
+ }
+ if (verdict.allowed) return 'once';
+ if (!verdict.needsPrompt) return 'deny';
+ const choice = await this._promptGroupedSearchPermission(tabId, host, onUpdate);
+ if (choice === null) return null;
+ if (candidateOnly) {
+ this.permissions.recordIntentCandidate(
+ host,
+ capabilities,
+ choice === 'once' ? 'allow' : 'deny',
+ tabId,
+ );
+ } else {
+ this.permissions.recordIntent(
+ intentKey,
+ capabilities,
+ choice === 'once' ? 'allow' : 'deny',
+ tabId,
+ );
+ }
+ return choice;
+ }
+
_isFormValidationCandidate(toolName, args = {}) {
const name = String(toolName || '');
if (name === 'click' || name === 'click_ax' || name === 'iframe_click' || name === 'execute_js') return true;
@@ -20533,7 +20753,7 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
async _detectLikelySubmitAction(tabId, toolName, args = {}) {
const name = String(toolName || '');
- const submitCapableTools = new Set(['click', 'click_ax', 'iframe_click', 'set_field', 'press_keys', 'execute_js']);
+ const submitCapableTools = new Set(['click', 'click_ax', 'iframe_click', 'type_ax', 'type_text', 'iframe_type', 'set_field', 'press_keys', 'execute_js']);
if (!submitCapableTools.has(name)) return null;
if (name === 'set_field' && !args?.submit) return null;
@@ -20558,7 +20778,8 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
}
try {
- const allFrames = name === 'iframe_click' || name === 'press_keys';
+ let allFrames = name === 'iframe_click' || name === 'press_keys';
+ if (name === 'iframe_type') allFrames = true;
let rawResults = [];
if (globalThis.chrome?.scripting?.executeScript) {
rawResults = await chrome.scripting.executeScript({
@@ -20572,7 +20793,7 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
if (!/^\s*(?:async\s+)?function\b/.test(probeSource)) {
probeSource = `function ${probeSource}`;
}
- const safeName = ['click', 'click_ax', 'iframe_click', 'set_field', 'press_keys', 'execute_js'].includes(name) ? name : '';
+ const safeName = ['click', 'click_ax', 'iframe_click', 'type_ax', 'type_text', 'iframe_type', 'set_field', 'press_keys', 'execute_js'].includes(name) ? name : '';
const serializedSafeName = JSON.stringify(safeName).replace(/[<>\u2028\u2029/]/g, ch => (
ch === '<' ? '\\u003C'
: ch === '>' ? '\\u003E'
@@ -20597,12 +20818,16 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
return {
isSubmit: true,
host,
+ url: String(detected.url || '').slice(0, 300),
tool: name,
reason: String(detected.reason || 'likely form submission').slice(0, 200),
validationSubmitEvidence: detected.validationSubmitEvidence === 'strong' ? 'strong' : 'heuristic',
summary: String(detected.summary || '').slice(0, 1200),
fields: Array.isArray(detected.fields) ? detected.fields.slice(0, 12) : [],
changedFields: Array.isArray(detected.changedFields) ? detected.changedFields.slice(0, 8) : [],
+ method: String(detected.method || 'GET').slice(0, 20).toUpperCase(),
+ action: String(detected.action || '').slice(0, 300),
+ actionUrl: String(detected.actionUrl || detected.action || '').slice(0, 300),
githubCommitDialogLauncher: detected.githubCommitDialogLauncher === true,
...(Array.isArray(detected.publicationResourceUrls) ? { publicationResourceUrls: detected.publicationResourceUrls.slice(0, 200) } : {}),
publicationResourceUrlsComplete: detected.publicationResourceUrlsComplete === true,
@@ -20620,6 +20845,22 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
transactionPageOrderIdsComplete: detected.transactionPageOrderIdsComplete === true,
};
}
+ const resolvedForm = rawResults.find(item => item?.resolvedForm === true);
+ if (resolvedForm) {
+ return {
+ isSubmit: false,
+ resolvedForm: true,
+ host: normalizeHost(resolvedForm.host || resolvedForm.url || currentUrl) || 'this site',
+ url: String(resolvedForm.url || '').slice(0, 300),
+ tool: name,
+ summary: String(resolvedForm.summary || '').slice(0, 1200),
+ fields: Array.isArray(resolvedForm.fields) ? resolvedForm.fields.slice(0, 12) : [],
+ changedFields: Array.isArray(resolvedForm.changedFields) ? resolvedForm.changedFields.slice(0, 8) : [],
+ method: String(resolvedForm.method || 'GET').slice(0, 20).toUpperCase(),
+ action: String(resolvedForm.action || '').slice(0, 300),
+ actionUrl: String(resolvedForm.actionUrl || resolvedForm.action || '').slice(0, 300),
+ };
+ }
const nonSubmit = rawResults.find(item => item?.resolvedNonSubmitTarget === true);
if (nonSubmit) return { isSubmit: false, resolvedNonSubmitTarget: true };
// Explicit negative: the probe resolved the click target to an editable
@@ -20784,16 +21025,24 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
const summarizeForm = (form, pendingEl = null, pendingValue = null) => {
if (!form) return { summary: '', fields: [], changedFields: [] };
const method = compact(form.getAttribute('method') || form.method || 'GET', 20).toUpperCase();
- const action = (() => {
+ const actionUrl = (() => {
try {
const actionUrl = new URL(form.getAttribute('action') || location.href, location.href);
- actionUrl.search = '';
- actionUrl.hash = '';
- return compact(actionUrl.href, 160);
+ return compact(actionUrl.href, 300);
} catch {
return compact(form.getAttribute('action') || location.href, 160);
}
})();
+ const action = (() => {
+ try {
+ const displayUrl = new URL(actionUrl, location.href);
+ displayUrl.search = '';
+ displayUrl.hash = '';
+ return compact(displayUrl.href, 160);
+ } catch {
+ return actionUrl;
+ }
+ })();
const controls = Array.from(form.querySelectorAll('input, textarea, select, [contenteditable="true"]'))
.filter((el) => {
const type = String(el.type || '').toLowerCase();
@@ -20806,6 +21055,11 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
const changed = el === pendingEl || (!!value && value !== before);
return {
label: labelFor(el),
+ name: compact(el.getAttribute?.('name') || '', 80),
+ id: compact(el.getAttribute?.('id') || '', 80),
+ autocomplete: compact(el.getAttribute?.('autocomplete') || '', 80),
+ ariaLabel: compact(el.getAttribute?.('aria-label') || '', 120),
+ placeholder: compact(el.getAttribute?.('placeholder') || '', 120),
type: compact(el.type || el.tagName || '', 40),
value,
changed,
@@ -20824,6 +21078,9 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
summary: `${origin} ${changedText}`,
fields: fields.slice(0, 12),
changedFields,
+ method,
+ action,
+ actionUrl,
};
};
const transactionOrderScan = (root) => {
@@ -21367,7 +21624,7 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
'a, button, [role="button"], [role="link"], [role="tab"], [role="menuitem"], input:not([type="hidden"]), textarea, select, input[type="button"], input[type="submit"], summary, label, [onclick], [data-action]'
)).filter(isVisible);
const resolveClickTarget = () => {
- if (toolName === 'click_ax' || toolName === 'set_field') {
+ if (toolName === 'click_ax' || toolName === 'set_field' || toolName === 'type_ax') {
try {
if (typeof window.__wb_ax_lookup === 'function' && typeof args.ref_id === 'string') {
return window.__wb_ax_lookup(args.ref_id);
@@ -21376,7 +21633,7 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
return null;
}
if (toolName === 'press_keys') return doc.activeElement;
- if (toolName === 'iframe_click') {
+ if (toolName === 'iframe_click' || toolName === 'iframe_type') {
const filter = compact(args.urlFilter || '', 300).toLowerCase();
const frameUrl = url.toLowerCase();
const frameHost = host.toLowerCase();
@@ -21393,6 +21650,15 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
}
return null;
}
+ if (toolName === 'type_text') {
+ if (args.selector) return deepQuerySelector(doc, args.selector);
+ if (args.index != null) {
+ const index = Number(args.index);
+ const all = interactiveElements();
+ return Number.isFinite(index) ? all[index] || null : null;
+ }
+ return isFormField(doc.activeElement) ? doc.activeElement : null;
+ }
if (toolName !== 'click') return null;
if (args.selector) {
return deepQuerySelector(doc, args.selector);
@@ -21428,6 +21694,17 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
try {
const target = resolveClickTarget();
+ if (['type_ax', 'type_text', 'iframe_type'].includes(toolName)) {
+ const form = target?.form || target?.closest?.('form') || null;
+ if (form) {
+ return {
+ resolvedForm: true,
+ host,
+ url,
+ ...summarizeForm(form, target, args.text || ''),
+ };
+ }
+ }
if (toolName === 'set_field' && args.submit) {
const form = target?.form || target?.closest?.('form') || null;
return submitInfo(form, 'set_field({submit:true})', target, args.text || '', 'strong', target);
diff --git a/src/firefox/src/agent/permission-gate.js b/src/firefox/src/agent/permission-gate.js
index 2fbb57de3..071c350c4 100644
--- a/src/firefox/src/agent/permission-gate.js
+++ b/src/firefox/src/agent/permission-gate.js
@@ -127,6 +127,188 @@ export const UNTRUSTED_CONTENT_TOOLS = new Set([
const MUTATION_METHODS = new Set(['POST', 'PUT', 'PATCH', 'DELETE']);
+// Keep this small public-suffix approximation local to the pure gate. The
+// permission key itself still uses the exact host; only the conservative
+// same-site search classifier needs registrable-domain comparison.
+const MULTI_LABEL_SITE_SUFFIXES = new Set([
+ 'co.uk', 'co.jp', 'co.kr', 'co.nz', 'co.za', 'co.in', 'co.il', 'co.th',
+ 'com.au', 'com.br', 'com.cn', 'com.mx', 'com.tr', 'com.sg', 'com.hk',
+ 'com.tw', 'com.ar', 'com.co', 'com.pe', 'com.ph', 'com.my', 'com.vn',
+ 'gov.uk', 'gov.au', 'gov.in', 'gov.cn', 'ac.uk', 'ac.jp', 'ac.in', 'ac.kr',
+ 'org.uk', 'org.au', 'org.nz', 'net.au', 'net.uk',
+ 'github.io', 'gitlab.io', 'netlify.app', 'netlify.com', 'vercel.app',
+ 'pages.dev', 'workers.dev', 'herokuapp.com', 'firebaseapp.com', 'web.app',
+ 'glitch.me', 'cloudfront.net', 'azurewebsites.net', 'r2.dev', 'github.dev',
+]);
+
+export const SubmitRisk = {
+ LOW_RISK_SEARCH: 'low_risk_search',
+ FRESH_CONFIRMATION: 'fresh_confirmation',
+};
+
+const SENSITIVE_SUBMIT_FIELD_RE = /(?:password|passwd|pwd|secret|token|api[-_\s]?key|otp|2fa|mfa|credential|verification[-_\s]?code|recovery[-_\s]?code|backup[-_\s]?code|private[-_\s]?key|seed[-_\s]?phrase|passphrase|pin[-_\s]?code|card(?:[-_\s]?(?:number|no|num|holder|expiry|expiration))?|credit[-_\s]?card|cc[-_\s]?(?:number|num|exp)|cvv|cvc|security[-_\s]?code|exp(?:iry|iration)?[-_\s]?(?:date|month|year)?)/i;
+const SEARCH_FIELD_RE = /(?:^|[\s_\-.])(?:q|query|search|keyword|keywords|term|terms|search[-_\s]?query)(?:$|[\s_\-.])/i;
+const SEARCH_PATH_RE = /(?:^|[\s/_-])(?:search|scholar|find|results?)(?:$|[\s/?#_-])/i;
+const SIDE_EFFECT_ACTION_RE = /(?:logout|log[-_]?out|sign[-_]?out|delete|remove|destroy|cancel|unsubscribe|disable|close[-_]?account|terminate|pay|checkout|purchase|order|payment|transfer|withdraw|publish|post|send|message|create|update|save|confirm|approve|register|login|sign[-_]?in|password|account)/i;
+
+function submitFieldDescriptor(field = {}) {
+ return [
+ field.type,
+ field.name,
+ field.id,
+ field.autocomplete,
+ field.ariaLabel,
+ field.placeholder,
+ field.label,
+ ].map(value => String(value || '').trim()).filter(Boolean).join(' ');
+}
+
+function shortHash(value) {
+ let hash = 2166136261;
+ const text = String(value || '');
+ for (let i = 0; i < text.length; i++) {
+ hash ^= text.charCodeAt(i);
+ hash = Math.imul(hash, 16777619);
+ }
+ return (hash >>> 0).toString(16);
+}
+
+export function registrableHost(input) {
+ const host = normalizeHost(input);
+ if (!host) return '';
+ if (host.includes(':') || /^\d+\.\d+\.\d+\.\d+$/.test(host)) return host;
+ const parts = host.split('.');
+ if (parts.length < 2) return host;
+ const suffix = parts.slice(-2).join('.');
+ return parts.length >= 3 && MULTI_LABEL_SITE_SUFFIXES.has(suffix)
+ ? parts.slice(-3).join('.')
+ : suffix;
+}
+
+function submitActionUrl(submitInfo = {}, currentUrlOrHost = '') {
+ const rawAction = submitInfo.actionUrl || submitInfo.action || submitInfo.url || currentUrlOrHost;
+ const base = submitInfo.url || currentUrlOrHost;
+ try {
+ const parsed = new URL(rawAction, base);
+ if (!/^https?:$/i.test(parsed.protocol)) return null;
+ return parsed;
+ } catch {
+ return null;
+ }
+}
+
+function freshSubmitRisk(reason) {
+ return { risk: SubmitRisk.FRESH_CONFIRMATION, lowRisk: false, reason };
+}
+
+/**
+ * Classify the resolved form, not the task wording or arbitrary page prose.
+ * This is deliberately conservative: only a same-registrable-site GET search
+ * with no credential/payment fields and no side-effect marker is grouped.
+ */
+export function classifySubmitRisk(submitInfo = {}, currentUrlOrHost = '') {
+ if (submitInfo?.isSubmit !== true) return freshSubmitRisk('not a resolved form submission');
+ const method = String(submitInfo.method || 'GET').trim().toUpperCase();
+ if (method !== 'GET') return freshSubmitRisk(`HTTP ${method || 'GET'} form method`);
+
+ const actionUrl = submitActionUrl(submitInfo, currentUrlOrHost);
+ const pageUrl = submitInfo.url || currentUrlOrHost;
+ let pageParsed = null;
+ try { pageParsed = new URL(pageUrl); } catch {}
+ if (!actionUrl || !pageParsed || !/^https?:$/i.test(pageParsed.protocol)) {
+ return freshSubmitRisk('unresolved HTTP form action');
+ }
+ const actionHost = normalizeHost(actionUrl.hostname);
+ const pageHost = normalizeHost(pageUrl);
+ if (!actionHost || !pageHost || registrableHost(actionHost) !== registrableHost(pageHost)) {
+ return freshSubmitRisk('cross-site form action');
+ }
+
+ const fields = Array.isArray(submitInfo.fields) ? submitInfo.fields.slice(0, 20) : [];
+ if (!fields.length) return freshSubmitRisk('form has no resolved search fields');
+ if (fields.some(field => SENSITIVE_SUBMIT_FIELD_RE.test(submitFieldDescriptor(field)))) {
+ return freshSubmitRisk('form contains a credential or payment field');
+ }
+
+ const pathname = actionUrl.pathname || '/';
+ const actionParameters = [...actionUrl.searchParams.keys()].join(' ');
+ if (SIDE_EFFECT_ACTION_RE.test(`${pathname} ${actionParameters}`)) {
+ return freshSubmitRisk('form action may have side effects');
+ }
+ const fieldMetadata = fields.map(submitFieldDescriptor).join(' ');
+ const searchLike = SEARCH_PATH_RE.test(pathname) || SEARCH_FIELD_RE.test(fieldMetadata) || SEARCH_FIELD_RE.test(actionParameters);
+ if (!searchLike) return freshSubmitRisk('form is not a resolved search');
+
+ return {
+ risk: SubmitRisk.LOW_RISK_SEARCH,
+ lowRisk: true,
+ reason: 'same-site GET search with non-sensitive fields',
+ host: actionHost,
+ method,
+ action: actionUrl.href,
+ };
+}
+
+/**
+ * A navigation can be the first action in a search flow, before the target
+ * form exists. This is only a provisional candidate: the type path must still
+ * re-run classifySubmitRisk against the resolved form before it can use the
+ * grouped grant for data entry or submission.
+ */
+export function classifySearchNavigation(targetUrl, currentUrlOrHost = '') {
+ let target = null;
+ let current = null;
+ try { target = new URL(targetUrl); } catch {}
+ try { current = new URL(currentUrlOrHost); } catch {}
+ if (!target || !/^https?:$/i.test(target.protocol)) return freshSubmitRisk('unresolved search navigation');
+ const targetHost = normalizeHost(target.hostname);
+ const currentHost = current && /^https?:$/i.test(current.protocol)
+ ? normalizeHost(current.hostname)
+ : '';
+ if (currentHost && registrableHost(targetHost) !== registrableHost(currentHost)) {
+ return freshSubmitRisk('cross-site search navigation');
+ }
+ const pathname = target.pathname || '/';
+ const parameters = [...target.searchParams.keys()].join(' ');
+ if (SIDE_EFFECT_ACTION_RE.test(`${pathname} ${parameters}`)) {
+ return freshSubmitRisk('navigation target may have side effects');
+ }
+ if (!SEARCH_PATH_RE.test(pathname) && !SEARCH_FIELD_RE.test(parameters)) {
+ return freshSubmitRisk('navigation target is not a resolved search');
+ }
+ return {
+ risk: SubmitRisk.LOW_RISK_SEARCH,
+ lowRisk: true,
+ reason: 'same-site GET search navigation candidate',
+ host: targetHost,
+ method: 'GET',
+ action: target.href,
+ };
+}
+
+/**
+ * Stable, task-scoped identity for retry deduplication. Values are hashed and
+ * never returned, so a retry key cannot become a secret-bearing telemetry field.
+ */
+export function submitActionKey(submitInfo = {}, currentUrlOrHost = '') {
+ const actionUrl = submitActionUrl(submitInfo, currentUrlOrHost);
+ const host = normalizeHost(actionUrl?.hostname || submitInfo.host || currentUrlOrHost);
+ const method = String(submitInfo.method || 'GET').trim().toUpperCase();
+ const fields = Array.isArray(submitInfo.fields) ? submitInfo.fields : [];
+ const sensitive = fields
+ .filter(field => SENSITIVE_SUBMIT_FIELD_RE.test(submitFieldDescriptor(field)))
+ .map(field => submitFieldDescriptor(field));
+ const changed = (Array.isArray(submitInfo.changedFields) ? submitInfo.changedFields : fields.filter(field => field?.changed))
+ .map(field => [submitFieldDescriptor(field), field?.value || ''].join('='));
+ return [
+ host,
+ actionUrl?.href || String(submitInfo.actionUrl || submitInfo.action || ''),
+ method,
+ `s:${shortHash(sensitive.join('|'))}`,
+ `c:${shortHash(changed.join('|'))}`,
+ ].join('|');
+}
+
/**
* True only for a fetch_url/research_url call carrying a write HTTP method β€”
* the egress the `/allow-api` override was meant to pre-authorize. A GET is NOT
@@ -383,6 +565,8 @@ export class PermissionManager {
this._save = typeof opts.save === 'function' ? opts.save : null;
this._skipAll = typeof opts.skipAll === 'function' ? opts.skipAll : (() => false);
this.permissions = [];
+ this.intentGrants = [];
+ this.intentCandidates = [];
this._hydrated = false;
}
@@ -425,6 +609,68 @@ export class PermissionManager {
*/
beginTurn(tabId) {
this.permissions = this.permissions.filter(p => p.duration === 'always' || p.tabId !== tabId);
+ this.intentGrants = this.intentGrants.filter(grant => grant.tabId !== tabId);
+ this.intentCandidates = this.intentCandidates.filter(candidate => candidate.tabId !== tabId);
+ }
+
+ /**
+ * Check a task-scoped grouped approval. Unlike an "always" grant this is
+ * never persisted or shared with another tab, and the key binds the approval
+ * to the resolved form plus its changed fields.
+ */
+ checkIntent(key, tabId, capability = null) {
+ const grant = this.intentGrants.find(item =>
+ item.key === String(key || '')
+ && item.tabId === tabId
+ && (!capability || item.capabilities.includes(capability))
+ );
+ if (!grant) return { allowed: false, needsPrompt: true };
+ return { allowed: grant.action === 'allow', needsPrompt: false, grant };
+ }
+
+ recordIntent(key, capabilities, action, tabId) {
+ const normalizedKey = String(key || '');
+ if (!normalizedKey) return;
+ this.intentGrants = this.intentGrants.filter(item => !(item.key === normalizedKey && item.tabId === tabId));
+ this.intentGrants.push({
+ key: normalizedKey,
+ capabilities: [...new Set(Array.isArray(capabilities) ? capabilities : [])],
+ action: action === 'allow' ? 'allow' : 'deny',
+ tabId,
+ ts: Date.now(),
+ });
+ }
+
+ hasIntentCandidate(tabId) {
+ return this.intentCandidates.some(candidate => candidate.tabId === tabId);
+ }
+
+ checkIntentCandidate(host, tabId, capability = null) {
+ const targetSite = registrableHost(host);
+ const candidate = this.intentCandidates.find(item =>
+ item.tabId === tabId
+ && registrableHost(item.host) === targetSite
+ && (!capability || item.capabilities.includes(capability))
+ );
+ if (!candidate) return { allowed: false, needsPrompt: true };
+ return { allowed: candidate.action === 'allow', needsPrompt: false, candidate };
+ }
+
+ recordIntentCandidate(host, capabilities, action, tabId) {
+ const normalizedHost = normalizeHost(host);
+ if (!normalizedHost) return;
+ this.intentCandidates = this.intentCandidates.filter(candidate => candidate.tabId !== tabId);
+ this.intentCandidates.push({
+ host: normalizedHost,
+ capabilities: [...new Set(Array.isArray(capabilities) ? capabilities : [])],
+ action: action === 'allow' ? 'allow' : 'deny',
+ tabId,
+ ts: Date.now(),
+ });
+ }
+
+ clearIntentCandidates(tabId) {
+ this.intentCandidates = this.intentCandidates.filter(candidate => candidate.tabId !== tabId);
}
/**
diff --git a/src/firefox/src/agent/scheduler.js b/src/firefox/src/agent/scheduler.js
index c0debdb92..b603c412d 100644
--- a/src/firefox/src/agent/scheduler.js
+++ b/src/firefox/src/agent/scheduler.js
@@ -100,6 +100,10 @@ function normalizePendingClarify(data, now = Date.now()) {
pending.permission = {
capability: String(permission.capability || '').slice(0, 80),
host: String(permission.host || '').slice(0, 300),
+ ...(permission.grouped === true ? { grouped: true } : {}),
+ ...(Array.isArray(permission.groupedCapabilities)
+ ? { groupedCapabilities: permission.groupedCapabilities.map(value => String(value).slice(0, 80)).slice(0, 6) }
+ : {}),
};
}
const submitConfirmation = asObject(obj.submitConfirmation);
diff --git a/src/firefox/src/ui/sidepanel.js b/src/firefox/src/ui/sidepanel.js
index 0a571f93e..30a3b4cac 100644
--- a/src/firefox/src/ui/sidepanel.js
+++ b/src/firefox/src/ui/sidepanel.js
@@ -9735,7 +9735,7 @@ function renderClarifyCard(data) {
return;
}
- // Permission-prompt mode: localized question + three fixed choices that
+ // Permission-prompt mode: localized question + fixed choices that
// return a stable VALUE ('once'/'always'/'deny'), and NO free-text input β€”
// so there's nothing to parse and no English/locale dependency.
if (data.permission && data.permission.capability) {
@@ -9748,20 +9748,30 @@ function renderClarifyCard(data) {
// consent wording cannot drift between two English copies; other locales
// carry their own translation under the key.
const resolvedVerb = verb === verbKey ? (CAPABILITY_LABEL[cap] || cap) : verb;
- qEl.textContent = t('sp.perm.question', { verb: resolvedVerb, host });
+ const grouped = data.permission.grouped === true;
+ qEl.textContent = grouped
+ ? String(data.question || `WebBrain wants to run a task-scoped low-risk search on ${host}.`).slice(0, 600)
+ : t('sp.perm.question', { verb: resolvedVerb, host });
const reasonEl = document.createElement('div');
reasonEl.className = 'clarify-reason';
- reasonEl.textContent = t('sp.perm.reason');
+ reasonEl.textContent = grouped
+ ? 'This one-time approval covers only this unchanged search on this tab. It does not allow passwords, payments, mutations, JavaScript, or future tasks.'
+ : t('sp.perm.reason');
card.appendChild(reasonEl);
const optionsEl = document.createElement('div');
optionsEl.className = 'clarify-options';
- const choices = [
- ['once', t('sp.perm.allow_once')],
- ['always', t('sp.perm.always_allow', { host })],
- ['deny', t('sp.perm.dont_allow')],
- ];
+ const choices = grouped
+ ? [
+ ['once', t('sp.perm.allow_once')],
+ ['deny', t('sp.perm.dont_allow')],
+ ]
+ : [
+ ['once', t('sp.perm.allow_once')],
+ ['always', t('sp.perm.always_allow', { host })],
+ ['deny', t('sp.perm.dont_allow')],
+ ];
for (const [value, label] of choices) {
const b = document.createElement('button');
b.type = 'button';
diff --git a/test/run.js b/test/run.js
index f95b124b8..8151e9d61 100644
--- a/test/run.js
+++ b/test/run.js
@@ -724,18 +724,23 @@ const { createContextMenuPromptHandler: createContextMenuPromptHandlerFx } = awa
);
// permission-gate.js is pure JS (deterministic capability Γ— origin gate).
-const { Capability, CAPABILITY_LABEL, capabilityFor, capabilitiesFor, normalizeHost, hostForCapability, requiredHosts, frameHostMatches, isNetworkMutation, PermissionManager, UNTRUSTED_CONTENT_TOOLS } = await import(
+const { Capability, CAPABILITY_LABEL, SubmitRisk, capabilityFor, capabilitiesFor, classifySearchNavigation, classifySubmitRisk, normalizeHost, registrableHost, hostForCapability, requiredHosts, frameHostMatches, isNetworkMutation, PermissionManager, submitActionKey, UNTRUSTED_CONTENT_TOOLS } = await import(
'file://' + path.join(ROOT, 'src/firefox/src/agent/permission-gate.js').replace(/\\/g, '/')
);
const {
Capability: CapabilityCh,
CAPABILITY_LABEL: CAPABILITY_LABEL_CH,
+ SubmitRisk: SubmitRiskCh,
capabilityFor: capabilityForCh,
capabilitiesFor: capabilitiesForCh,
+ classifySubmitRisk: classifySubmitRiskCh,
+ classifySearchNavigation: classifySearchNavigationCh,
PermissionManager: PermissionManagerCh,
normalizeHost: normalizeHostCh,
+ registrableHost: registrableHostCh,
hostForCapability: hostForCapabilityCh,
requiredHosts: requiredHostsCh,
+ submitActionKey: submitActionKeyCh,
UNTRUSTED_CONTENT_TOOLS: UNTRUSTED_CONTENT_TOOLS_CH,
} = await import(
'file://' + path.join(ROOT, 'src/chrome/src/agent/permission-gate.js').replace(/\\/g, '/')
@@ -75666,6 +75671,212 @@ test('approved submit confirmation is one-time and skips generic click always gr
}
});
+test('low-risk GET searches use one task-scoped approval and deduplicate unchanged retries', async () => {
+ for (const AgentClass of [AgentCh, AgentFx]) {
+ const agent = new AgentClass({ getVisionProvider: async () => null });
+ const tabId = 5112;
+ let executed = 0;
+ let groupedPrompts = 0;
+ let submitPrompts = 0;
+ const makeSubmitInfo = () => ({
+ isSubmit: true,
+ host: 'scholar.google.com',
+ url: 'https://www.google.com/search',
+ method: 'GET',
+ action: 'https://scholar.google.com/scholar',
+ actionUrl: 'https://scholar.google.com/scholar',
+ tool: 'click_ax',
+ reason: 'submit button/control activation',
+ fields: [{ type: 'text', name: 'q', label: 'Search articles', value: 'agents', changed: true }],
+ changedFields: [{ type: 'text', name: 'q', label: 'Search articles', value: 'agents', changed: true }],
+ });
+ const runSearch = async (id) => {
+ const messages = [];
+ await agent._executeToolBatch(
+ tabId,
+ [{ id, function: { name: 'click_ax', arguments: '{"ref_id":"ref_submit"}' } }],
+ messages,
+ () => {},
+ { supportsVision: false },
+ '',
+ new Set(['click_ax']),
+ 1,
+ );
+ return messages;
+ };
+
+ agent._ensureGateSetting = async () => false;
+ agent._skipPermissionGate = false;
+ agent._currentUrl = async () => 'https://www.google.com/search';
+ agent._recordProgressObservation = async () => null;
+ agent._autoRecordProgressAction = () => null;
+ agent._progressWarningForAction = () => '';
+ agent._persist = () => {};
+ agent._detectLikelySubmitAction = async () => makeSubmitInfo();
+ agent._promptGroupedSearchPermission = async () => {
+ groupedPrompts += 1;
+ return 'once';
+ };
+ agent._promptSubmitConfirmation = async () => {
+ submitPrompts += 1;
+ throw new Error(`${AgentClass.name}: low-risk search used a fresh submit prompt`);
+ };
+ agent._promptPermission = async () => {
+ throw new Error(`${AgentClass.name}: low-risk search used a generic capability prompt`);
+ };
+ agent.executeTool = async () => {
+ executed += 1;
+ return { success: true, searched: true };
+ };
+
+ const first = await runSearch('tool_grouped_search_1');
+ const second = await runSearch('tool_grouped_search_2');
+ assert.equal(executed, 2, `${AgentClass.name}: unchanged search retry did not execute`);
+ assert.equal(groupedPrompts, 1, `${AgentClass.name}: expected one grouped approval across retries`);
+ assert.equal(submitPrompts, 0, `${AgentClass.name}: grouped search requested a fresh submit prompt`);
+ assert.equal(first.length, 1, `${AgentClass.name}: first search result missing`);
+ assert.equal(second.length, 1, `${AgentClass.name}: retry search result missing`);
+ assert.equal(JSON.parse(agent._unwrapUntrusted(first[0].content)).success, true);
+ assert.equal(JSON.parse(agent._unwrapUntrusted(second[0].content)).success, true);
+ }
+});
+
+test('search navigation, typing, and submit share one grouped approval', async () => {
+ for (const AgentClass of [AgentCh, AgentFx]) {
+ const agent = new AgentClass({ getVisionProvider: async () => null });
+ const tabId = 5114;
+ const searchUrl = 'https://scholar.google.com/scholar';
+ let pageUrl = 'about:blank';
+ let groupedPrompts = 0;
+ let capabilityPrompts = 0;
+ let submitPrompts = 0;
+ const executed = [];
+
+ const formInfo = (name) => ({
+ isSubmit: name === 'click_ax',
+ ...(name === 'click_ax' ? {} : { resolvedForm: true }),
+ host: 'scholar.google.com',
+ url: searchUrl,
+ method: 'GET',
+ action: searchUrl,
+ actionUrl: searchUrl,
+ tool: name,
+ fields: [{ type: 'text', name: 'q', label: 'Search articles', value: 'agents', changed: true }],
+ changedFields: [{ type: 'text', name: 'q', label: 'Search articles', value: 'agents', changed: true }],
+ });
+
+ agent._ensureGateSetting = async () => false;
+ agent._skipPermissionGate = false;
+ agent._currentUrl = async () => pageUrl;
+ agent._recordProgressObservation = async () => null;
+ agent._autoRecordProgressAction = () => null;
+ agent._progressWarningForAction = () => '';
+ agent._persist = () => {};
+ agent._promptGroupedSearchPermission = async () => {
+ groupedPrompts += 1;
+ return 'once';
+ };
+ agent._promptPermission = async () => {
+ capabilityPrompts += 1;
+ throw new Error(`${AgentClass.name}: grouped search requested a generic capability prompt`);
+ };
+ agent._promptSubmitConfirmation = async () => {
+ submitPrompts += 1;
+ throw new Error(`${AgentClass.name}: grouped search requested fresh submit confirmation`);
+ };
+ agent._detectLikelySubmitAction = async (_tabId, name) => formInfo(name);
+ agent.executeTool = async (_tabId, name, args) => {
+ executed.push(name);
+ if (name === 'navigate') pageUrl = args.url;
+ return { success: true, tool: name };
+ };
+
+ const run = async (id, name, args, advertisedName = name) => {
+ const messages = [];
+ await agent._executeToolBatch(
+ tabId,
+ [{ id, function: { name, arguments: JSON.stringify(args) } }],
+ messages,
+ () => {},
+ { supportsVision: false },
+ '',
+ new Set([advertisedName]),
+ 1,
+ );
+ assert.equal(messages.length, 1, `${AgentClass.name} ${name}: expected one tool result`);
+ assert.equal(JSON.parse(agent._unwrapUntrusted(messages[0].content)).success, true, `${AgentClass.name} ${name}: tool did not execute successfully`);
+ };
+
+ await run('tool_search_navigation', 'navigate', { url: searchUrl });
+ await run('tool_search_type', 'type_ax', { ref_id: 'ref_query', text: 'agents' });
+ await run('tool_search_submit', 'click_ax', { ref_id: 'ref_submit' });
+
+ assert.deepEqual(executed, ['navigate', 'type_ax', 'click_ax'], `${AgentClass.name}: search flow did not execute in order`);
+ assert.equal(groupedPrompts, 1, `${AgentClass.name}: navigation/type/submit should use one grouped approval`);
+ assert.equal(capabilityPrompts, 0, `${AgentClass.name}: grouped search requested a generic capability prompt`);
+ assert.equal(submitPrompts, 0, `${AgentClass.name}: grouped search requested fresh submit confirmation`);
+ }
+});
+
+test('set_field submit stays outside the grouped low-risk search bypass', async () => {
+ for (const AgentClass of [AgentCh, AgentFx]) {
+ const agent = new AgentClass({ getVisionProvider: async () => null });
+ const messages = [];
+ let groupedPrompts = 0;
+ let submitPrompts = 0;
+ let capabilityPrompts = 0;
+ let executed = false;
+ agent._ensureGateSetting = async () => false;
+ agent._skipPermissionGate = false;
+ agent._currentUrl = async () => 'https://scholar.google.com/scholar';
+ agent._recordProgressObservation = async () => null;
+ agent._autoRecordProgressAction = () => null;
+ agent._progressWarningForAction = () => '';
+ agent._persist = () => {};
+ agent._detectLikelySubmitAction = async () => ({
+ isSubmit: true,
+ host: 'scholar.google.com',
+ url: 'https://scholar.google.com/scholar',
+ method: 'GET',
+ action: 'https://scholar.google.com/scholar',
+ actionUrl: 'https://scholar.google.com/scholar',
+ fields: [{ type: 'text', name: 'q', label: 'Search articles', value: 'agents', changed: true }],
+ changedFields: [{ type: 'text', name: 'q', label: 'Search articles', value: 'agents', changed: true }],
+ });
+ agent._promptGroupedSearchPermission = async () => {
+ groupedPrompts += 1;
+ throw new Error(`${AgentClass.name}: set_field submit entered grouped search permission`);
+ };
+ agent._promptSubmitConfirmation = async () => {
+ submitPrompts += 1;
+ return 'once';
+ };
+ agent._promptPermission = async () => {
+ capabilityPrompts += 1;
+ return 'once';
+ };
+ agent.executeTool = async () => {
+ executed = true;
+ return { success: true };
+ };
+
+ await agent._executeToolBatch(
+ 5113,
+ [{ id: 'tool_set_field_submit', function: { name: 'set_field', arguments: '{"ref_id":"ref_query","text":"agents","submit":true}' } }],
+ messages,
+ () => {},
+ { supportsVision: false },
+ '',
+ new Set(['set_field']),
+ 1,
+ );
+ assert.equal(executed, true, `${AgentClass.name}: approved set_field submit did not execute`);
+ assert.equal(groupedPrompts, 0, `${AgentClass.name}: set_field submit used grouped approval`);
+ assert.equal(submitPrompts, 1, `${AgentClass.name}: set_field submit skipped fresh submit confirmation`);
+ assert.equal(capabilityPrompts, 1, `${AgentClass.name}: set_field submit skipped TYPE permission`);
+ }
+});
+
test('iframe submit without urlFilter fails before confirmation or dispatch', async () => {
for (const AgentClass of [AgentCh, AgentFx]) {
const agent = new AgentClass({ getVisionProvider: async () => null });
@@ -106455,10 +106666,80 @@ test('skipAll hook allows everything without prompting', () => {
assert.equal(v.needsPrompt, false);
});
+test('submit risk classifier groups only conservative same-site GET searches', () => {
+ const search = {
+ isSubmit: true,
+ url: 'https://www.scholar.google.com/scholar',
+ method: 'GET',
+ actionUrl: 'https://scholar.google.com/scholar',
+ fields: [{ type: 'text', name: 'q', label: 'Search articles', value: 'agents', changed: true }],
+ changedFields: [{ type: 'text', name: 'q', label: 'Search articles', value: 'agents', changed: true }],
+ };
+ assert.equal(classifySubmitRisk(search, search.url).risk, SubmitRisk.LOW_RISK_SEARCH);
+ assert.equal(classifySubmitRisk(search, search.url).lowRisk, true);
+ assert.equal(
+ classifySearchNavigation(search.actionUrl, 'about:blank').risk,
+ SubmitRisk.LOW_RISK_SEARCH,
+ );
+ assert.equal(
+ classifySearchNavigationCh(search.actionUrl, search.url).risk,
+ SubmitRiskCh.LOW_RISK_SEARCH,
+ );
+ assert.equal(registrableHost('api.example.co.uk'), 'example.co.uk');
+ assert.equal(registrableHostCh('www.example.co.uk'), 'example.co.uk');
+
+ for (const [label, classify] of [['firefox', classifySubmitRisk], ['chrome', classifySubmitRiskCh]]) {
+ const cases = [
+ [{ ...search, method: 'POST' }, 'HTTP POST'],
+ [{ ...search, actionUrl: 'https://evil.example/search' }, 'cross-site'],
+ [{ ...search, actionUrl: 'https://scholar.google.com/logout?action=delete' }, 'side effects'],
+ [{ ...search, fields: [{ type: 'text', name: 'cardnumber', label: 'Card number' }] }, 'payment'],
+ [{ ...search, fields: [{ type: 'password', name: 'q', label: 'Search' }] }, 'credential'],
+ [{ ...search, actionUrl: 'https://scholar.google.com/account', fields: [{ type: 'text', name: 'title', label: 'Title' }] }, 'resolved search'],
+ ];
+ for (const [info, reason] of cases) {
+ const result = classify(info, search.url);
+ assert.equal(result.risk, SubmitRisk.FRESH_CONFIRMATION, `${label}: ${reason} must keep fresh confirmation`);
+ assert.equal(result.lowRisk, false, `${label}: ${reason} must not be grouped`);
+ }
+ }
+});
+
+test('submit action keys deduplicate unchanged retries without exposing values', () => {
+ const base = {
+ isSubmit: true,
+ url: 'https://scholar.google.com/scholar',
+ method: 'GET',
+ actionUrl: 'https://scholar.google.com/scholar',
+ fields: [{ type: 'text', name: 'q', label: 'Search', value: 'machine learning', changed: true }],
+ changedFields: [{ type: 'text', name: 'q', label: 'Search', value: 'machine learning', changed: true }],
+ };
+ const key = submitActionKey(base, base.url);
+ const chromeKey = submitActionKeyCh(base, base.url);
+ assert.equal(key, chromeKey, 'Chrome and Firefox retry keys must match');
+ assert.doesNotMatch(key, /machine learning/i, 'retry keys must hash field values');
+ assert.notEqual(key, submitActionKey({ ...base, changedFields: [{ ...base.changedFields[0], value: 'deep learning' }] }, base.url));
+ assert.notEqual(key, submitActionKey({ ...base, actionUrl: 'https://scholar.google.com/logout' }, base.url));
+});
+
+test('task-scoped grouped approvals stay per-tab, deny retries, and expire at turn boundaries', () => {
+ const pm = new PermissionManager();
+ const key = 'scholar.google.com|https://scholar.google.com/scholar|GET|s:0|c:1';
+ pm.recordIntent(key, [Capability.NAVIGATE, Capability.TYPE, Capability.CLICK], 'allow', 1);
+ assert.equal(pm.checkIntent(key, 1, Capability.CLICK).allowed, true);
+ assert.equal(pm.checkIntent(key, 2, Capability.CLICK).needsPrompt, true);
+ pm.recordIntent(key, [Capability.NAVIGATE, Capability.TYPE, Capability.CLICK], 'deny', 1);
+ assert.equal(pm.checkIntent(key, 1, Capability.CLICK).allowed, false);
+ assert.equal(pm.checkIntent(key, 1, Capability.CLICK).needsPrompt, false);
+ pm.beginTurn(1);
+ assert.equal(pm.checkIntent(key, 1, Capability.CLICK).needsPrompt, true);
+});
+
test('parity: chrome & firefox permission-gate behave identically', async () => {
assert.equal(capabilityForCh('click', {}), capabilityFor('click', {}));
assert.equal(capabilityForCh('read_page', {}), capabilityFor('read_page', {}));
assert.equal(normalizeHostCh('https://www.GitHub.com/x'), normalizeHost('https://www.GitHub.com/x'));
+ assert.equal(SubmitRiskCh.LOW_RISK_SEARCH, SubmitRisk.LOW_RISK_SEARCH);
const a = new PermissionManager(); const b = new PermissionManagerCh();
await a.record('x.com', 'click', 'allow', 'always');
await b.record('x.com', 'click', 'allow', 'always');