Skip to content

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

fix(recipient-guard): preserve authorized recipient roles when rebinding message recipients

Emre Sokullu2320b82c01f2
diff --git a/src/chrome/src/agent/agent.js b/src/chrome/src/agent/agent.js
index c52c74645..06e5f0fa5 100644
--- a/src/chrome/src/agent/agent.js
+++ b/src/chrome/src/agent/agent.js
@@ -43,7 +43,7 @@ import {
workflowControlLabelIsRequested,
workflowRequiredRowsAreProcessed,
} from './adapter-workflow-evidence.js';
-import { answerNamesAllObservedRecipients, answerNamesIdentity, messageTargetMatchesObservedIdentities, normalizeMessageTarget, normalizeRecipientAnswer, normalizeRecipientIdentity } from './message-recipient-guard.js';
+import { answerNamesAllObservedRecipients, answerNamesIdentity, messageTargetMatchesObservedIdentities, normalizeMessageTarget, normalizeRecipientAnswer, normalizeRecipientIdentity, resolveClarifiedRecipients } from './message-recipient-guard.js';
import {
fetchUrl,
executeHttpSkillTool,
@@ -17880,7 +17880,7 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
...(Array.isArray(context.options) ? context.options : []),
].filter(Boolean).join(' ').toLowerCase();
const changeWord = /(change|switch|different|instead|update|replace|another|new|更改|更换|切换|替换|换成)/i.test(text);
- const targetWord = /(recipient|conversation|contact|send to|person|address|target|someone else|收件人|联系人|发送)/i.test(text);
+ const targetWord = /(recipient|conversation|contact|send to|person|address|target|someone else|\b(?:to|cc|bcc|role|field)\b|收件人|联系人|发送)/i.test(text);
return changeWord && targetWord;
}
if (purpose === 'message_recipient' || purpose === 'recipient_change') return true;
@@ -17962,7 +17962,8 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
const normalizedAnswer = normalizeRecipientAnswer(answer);
if (!normalizedAnswer) return false;
if (!answerNamesAllObservedRecipients(normalizedAnswer, observed)) return false;
- const target = normalizeMessageTarget({ target_kind: 'named', recipients: observed });
+ const resolvedRecipients = resolveClarifiedRecipients(observed, guard.messaging, clarifyContext, answer);
+ const target = normalizeMessageTarget({ target_kind: 'named', recipients: resolvedRecipients });
if (!target) return false;
guard.messaging = target;
return true;
diff --git a/src/chrome/src/agent/message-recipient-guard.js b/src/chrome/src/agent/message-recipient-guard.js
index 45209c7eb..007fb1db9 100644
--- a/src/chrome/src/agent/message-recipient-guard.js
+++ b/src/chrome/src/agent/message-recipient-guard.js
@@ -213,3 +213,133 @@ export function messageTargetMatchesObservedIdentities(target, candidates) {
return expected.size === recipients.size
&& [...expected].every(key => recipients.has(key));
}
+
+/**
+ * Does the clarification context or user answer explicitly authorize targetRole
+ * (to, cc, or bcc) for candidateIdentity?
+ *
+ * For 'bcc' and 'cc', explicit mentions of BCC or CC in the text surrounding
+ * the recipient identity or in the answer authorize the role.
+ * For 'to', because "to" is also a ubiquitous preposition ("send to Alice"),
+ * an explicit role label ("To: Alice", "Alice (To)", "as To", "in To", "To field")
+ * or localized role indicator ("收件人", "主送") is required.
+ */
+export function clarificationAuthorizesRecipientRole(clarifyContext, answer, candidateIdentity, targetRole) {
+ const role = String(targetRole || '').trim().toLowerCase();
+ if (!MESSAGE_RECIPIENT_ROLES.has(role)) return false;
+
+ const answerText = String(answer ?? '').trim();
+ const contextTexts = clarifyContext && typeof clarifyContext === 'object'
+ ? [
+ clarifyContext.question,
+ clarifyContext.reason,
+ ...(Array.isArray(clarifyContext.options) ? clarifyContext.options : []),
+ ].filter(Boolean).map(s => String(s).trim())
+ : [];
+
+ const normId = normalizeRecipientIdentity(candidateIdentity);
+
+ function snippetHasExplicitRole(snippet, roleToCheck) {
+ if (!snippet) return false;
+ if (roleToCheck === 'bcc') {
+ return /\b(?:bcc|blind\s+carbon\s+copy)\b|密送|暗送/i.test(snippet);
+ }
+ if (roleToCheck === 'cc') {
+ return /\b(?:cc|carbon\s+copy)\b|抄送/i.test(snippet);
+ }
+ if (roleToCheck === 'to') {
+ if (/\bto\s*[::]/i.test(snippet)) return true;
+ if (/[(\[【]\s*to\s*[)\]】]/i.test(snippet)) return true;
+ if (/\b(?:as|in|into|role|field)\s+to\b/i.test(snippet)) return true;
+ if (/\bto\s+(?:field|role|recipient)\b/i.test(snippet)) return true;
+ if (/\bfrom\s+(?:bcc|cc)\s+to\s+to\b/i.test(snippet)) return true;
+ if (/\b(?:bcc|cc)\s*(?:->|=>|→)\s*to\b/i.test(snippet)) return true;
+ if (/(?:作为|设为)?(?:收件人|主送)/i.test(snippet)) return true;
+ const trimmed = snippet.trim();
+ if (/^(?:to|as\s+to)$/i.test(trimmed)) return true;
+ return false;
+ }
+ return false;
+ }
+
+ const clauseDelimiters = /[,;\n\r|/]|(?:\s+(?:and|or|以及|与|及)\s+)/i;
+
+ function textAuthorizesRoleForIdentity(text) {
+ if (!text) return false;
+ const clauses = text.split(clauseDelimiters).map(s => s.trim()).filter(Boolean);
+ let matchedClause = false;
+ for (const clause of clauses) {
+ if (normId && answerNamesIdentity(clause, normId)) {
+ matchedClause = true;
+ if (snippetHasExplicitRole(clause, role)) return true;
+ }
+ }
+ if (!matchedClause) {
+ if (normId && answerNamesIdentity(text, normId)) {
+ const spans = findCandidateAnswerSpans(text, normId);
+ for (const span of spans) {
+ const window = text.slice(Math.max(0, span.start - 40), Math.min(text.length, span.end + 40));
+ if (snippetHasExplicitRole(window, role)) return true;
+ }
+ } else if (!normId || clauses.length <= 1) {
+ if (snippetHasExplicitRole(text, role)) return true;
+ }
+ }
+ return false;
+ }
+
+ if (answerText && textAuthorizesRoleForIdentity(answerText)) {
+ return true;
+ }
+
+ for (const contextText of contextTexts) {
+ if (contextText && textAuthorizesRoleForIdentity(contextText)) {
+ return true;
+ }
+ }
+
+ return false;
+}
+
+/**
+ * Resolve observed recipient candidates against previously authorized recipients
+ * and clarification context/answer.
+ *
+ * When an observed candidate was already authorized with a different role (for
+ * example, authorized as 'bcc' while the composer exposes 'to'), require the
+ * clarification to explicitly authorize each changed To/CC/BCC role, or retain
+ * the previously authorized role when only the identity was confirmed.
+ */
+export function resolveClarifiedRecipients(observedCandidates, previousTarget, clarifyContext, answer) {
+ const previous = normalizeMessageTarget(previousTarget);
+ const previousRolesByIdentity = new Map();
+ if (previous?.recipients) {
+ for (const r of previous.recipients) {
+ const norm = normalizeRecipientIdentity(r.identity);
+ if (norm && r.role) {
+ previousRolesByIdentity.set(norm, r.role);
+ }
+ }
+ }
+
+ const rawList = Array.isArray(observedCandidates) ? observedCandidates : [];
+ return rawList.map(candidate => {
+ const legacy = typeof candidate === 'string' || typeof candidate === 'number';
+ const identity = compact(legacy ? candidate : (candidate?.identity ?? candidate?.recipient), 240);
+ const observedRole = compact(legacy ? 'to' : candidate?.role, 12).toLowerCase() || 'to';
+ const norm = normalizeRecipientIdentity(identity);
+ const previousRole = previousRolesByIdentity.get(norm);
+ if (previousRole && previousRole !== observedRole) {
+ const authorized = clarificationAuthorizesRecipientRole(clarifyContext, answer, identity, observedRole);
+ return {
+ identity,
+ role: authorized ? observedRole : previousRole,
+ };
+ }
+ return {
+ identity,
+ role: observedRole,
+ };
+ });
+}
+
diff --git a/src/firefox/src/agent/agent.js b/src/firefox/src/agent/agent.js
index 718b45050..fb5766c9d 100644
--- a/src/firefox/src/agent/agent.js
+++ b/src/firefox/src/agent/agent.js
@@ -42,7 +42,7 @@ import {
workflowControlLabelIsRequested,
workflowRequiredRowsAreProcessed,
} from './adapter-workflow-evidence.js';
-import { answerNamesAllObservedRecipients, answerNamesIdentity, messageTargetMatchesObservedIdentities, normalizeMessageTarget, normalizeRecipientAnswer, normalizeRecipientIdentity } from './message-recipient-guard.js';
+import { answerNamesAllObservedRecipients, answerNamesIdentity, messageTargetMatchesObservedIdentities, normalizeMessageTarget, normalizeRecipientAnswer, normalizeRecipientIdentity, resolveClarifiedRecipients } from './message-recipient-guard.js';
import {
fetchUrl,
executeHttpSkillTool,
@@ -15633,7 +15633,7 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
...(Array.isArray(context.options) ? context.options : []),
].filter(Boolean).join(' ').toLowerCase();
const changeWord = /(change|switch|different|instead|update|replace|another|new|更改|更换|切换|替换|换成)/i.test(text);
- const targetWord = /(recipient|conversation|contact|send to|person|address|target|someone else|收件人|联系人|发送)/i.test(text);
+ const targetWord = /(recipient|conversation|contact|send to|person|address|target|someone else|\b(?:to|cc|bcc|role|field)\b|收件人|联系人|发送)/i.test(text);
return changeWord && targetWord;
}
if (purpose === 'message_recipient' || purpose === 'recipient_change') return true;
@@ -15715,7 +15715,8 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
const normalizedAnswer = normalizeRecipientAnswer(answer);
if (!normalizedAnswer) return false;
if (!answerNamesAllObservedRecipients(normalizedAnswer, observed)) return false;
- const target = normalizeMessageTarget({ target_kind: 'named', recipients: observed });
+ const resolvedRecipients = resolveClarifiedRecipients(observed, guard.messaging, clarifyContext, answer);
+ const target = normalizeMessageTarget({ target_kind: 'named', recipients: resolvedRecipients });
if (!target) return false;
guard.messaging = target;
return true;
diff --git a/src/firefox/src/agent/message-recipient-guard.js b/src/firefox/src/agent/message-recipient-guard.js
index 45209c7eb..007fb1db9 100644
--- a/src/firefox/src/agent/message-recipient-guard.js
+++ b/src/firefox/src/agent/message-recipient-guard.js
@@ -213,3 +213,133 @@ export function messageTargetMatchesObservedIdentities(target, candidates) {
return expected.size === recipients.size
&& [...expected].every(key => recipients.has(key));
}
+
+/**
+ * Does the clarification context or user answer explicitly authorize targetRole
+ * (to, cc, or bcc) for candidateIdentity?
+ *
+ * For 'bcc' and 'cc', explicit mentions of BCC or CC in the text surrounding
+ * the recipient identity or in the answer authorize the role.
+ * For 'to', because "to" is also a ubiquitous preposition ("send to Alice"),
+ * an explicit role label ("To: Alice", "Alice (To)", "as To", "in To", "To field")
+ * or localized role indicator ("收件人", "主送") is required.
+ */
+export function clarificationAuthorizesRecipientRole(clarifyContext, answer, candidateIdentity, targetRole) {
+ const role = String(targetRole || '').trim().toLowerCase();
+ if (!MESSAGE_RECIPIENT_ROLES.has(role)) return false;
+
+ const answerText = String(answer ?? '').trim();
+ const contextTexts = clarifyContext && typeof clarifyContext === 'object'
+ ? [
+ clarifyContext.question,
+ clarifyContext.reason,
+ ...(Array.isArray(clarifyContext.options) ? clarifyContext.options : []),
+ ].filter(Boolean).map(s => String(s).trim())
+ : [];
+
+ const normId = normalizeRecipientIdentity(candidateIdentity);
+
+ function snippetHasExplicitRole(snippet, roleToCheck) {
+ if (!snippet) return false;
+ if (roleToCheck === 'bcc') {
+ return /\b(?:bcc|blind\s+carbon\s+copy)\b|密送|暗送/i.test(snippet);
+ }
+ if (roleToCheck === 'cc') {
+ return /\b(?:cc|carbon\s+copy)\b|抄送/i.test(snippet);
+ }
+ if (roleToCheck === 'to') {
+ if (/\bto\s*[::]/i.test(snippet)) return true;
+ if (/[(\[【]\s*to\s*[)\]】]/i.test(snippet)) return true;
+ if (/\b(?:as|in|into|role|field)\s+to\b/i.test(snippet)) return true;
+ if (/\bto\s+(?:field|role|recipient)\b/i.test(snippet)) return true;
+ if (/\bfrom\s+(?:bcc|cc)\s+to\s+to\b/i.test(snippet)) return true;
+ if (/\b(?:bcc|cc)\s*(?:->|=>|→)\s*to\b/i.test(snippet)) return true;
+ if (/(?:作为|设为)?(?:收件人|主送)/i.test(snippet)) return true;
+ const trimmed = snippet.trim();
+ if (/^(?:to|as\s+to)$/i.test(trimmed)) return true;
+ return false;
+ }
+ return false;
+ }
+
+ const clauseDelimiters = /[,;\n\r|/]|(?:\s+(?:and|or|以及|与|及)\s+)/i;
+
+ function textAuthorizesRoleForIdentity(text) {
+ if (!text) return false;
+ const clauses = text.split(clauseDelimiters).map(s => s.trim()).filter(Boolean);
+ let matchedClause = false;
+ for (const clause of clauses) {
+ if (normId && answerNamesIdentity(clause, normId)) {
+ matchedClause = true;
+ if (snippetHasExplicitRole(clause, role)) return true;
+ }
+ }
+ if (!matchedClause) {
+ if (normId && answerNamesIdentity(text, normId)) {
+ const spans = findCandidateAnswerSpans(text, normId);
+ for (const span of spans) {
+ const window = text.slice(Math.max(0, span.start - 40), Math.min(text.length, span.end + 40));
+ if (snippetHasExplicitRole(window, role)) return true;
+ }
+ } else if (!normId || clauses.length <= 1) {
+ if (snippetHasExplicitRole(text, role)) return true;
+ }
+ }
+ return false;
+ }
+
+ if (answerText && textAuthorizesRoleForIdentity(answerText)) {
+ return true;
+ }
+
+ for (const contextText of contextTexts) {
+ if (contextText && textAuthorizesRoleForIdentity(contextText)) {
+ return true;
+ }
+ }
+
+ return false;
+}
+
+/**
+ * Resolve observed recipient candidates against previously authorized recipients
+ * and clarification context/answer.
+ *
+ * When an observed candidate was already authorized with a different role (for
+ * example, authorized as 'bcc' while the composer exposes 'to'), require the
+ * clarification to explicitly authorize each changed To/CC/BCC role, or retain
+ * the previously authorized role when only the identity was confirmed.
+ */
+export function resolveClarifiedRecipients(observedCandidates, previousTarget, clarifyContext, answer) {
+ const previous = normalizeMessageTarget(previousTarget);
+ const previousRolesByIdentity = new Map();
+ if (previous?.recipients) {
+ for (const r of previous.recipients) {
+ const norm = normalizeRecipientIdentity(r.identity);
+ if (norm && r.role) {
+ previousRolesByIdentity.set(norm, r.role);
+ }
+ }
+ }
+
+ const rawList = Array.isArray(observedCandidates) ? observedCandidates : [];
+ return rawList.map(candidate => {
+ const legacy = typeof candidate === 'string' || typeof candidate === 'number';
+ const identity = compact(legacy ? candidate : (candidate?.identity ?? candidate?.recipient), 240);
+ const observedRole = compact(legacy ? 'to' : candidate?.role, 12).toLowerCase() || 'to';
+ const norm = normalizeRecipientIdentity(identity);
+ const previousRole = previousRolesByIdentity.get(norm);
+ if (previousRole && previousRole !== observedRole) {
+ const authorized = clarificationAuthorizesRecipientRole(clarifyContext, answer, identity, observedRole);
+ return {
+ identity,
+ role: authorized ? observedRole : previousRole,
+ };
+ }
+ return {
+ identity,
+ role: observedRole,
+ };
+ });
+}
+
diff --git a/test/run.js b/test/run.js
index b675dd9a7..6b8f81368 100644
--- a/test/run.js
+++ b/test/run.js
@@ -4708,6 +4708,72 @@ test('direct-message recipient guard uses structured intent and exact active ide
{ identity: '[email protected]', role: 'to' },
],
), false, 'moving a BCC recipient into To must fail closed');
+
+ // Role authorization and resolution tests:
+ assert.equal(
+ helper.clarificationAuthorizesRecipientRole(null, 'Send to Alice', 'Alice', 'to'),
+ false,
+ 'prepositional "to" must not explicitly authorize the To delivery role',
+ );
+ assert.equal(
+ helper.clarificationAuthorizesRecipientRole(null, 'To: Alice', 'Alice', 'to'),
+ true,
+ 'explicit "To:" label must authorize the To delivery role',
+ );
+ assert.equal(
+ helper.clarificationAuthorizesRecipientRole(null, 'Alice (To)', 'Alice', 'to'),
+ true,
+ 'parenthesized "(To)" label must authorize the To delivery role',
+ );
+ assert.equal(
+ helper.clarificationAuthorizesRecipientRole(null, 'Send to Alice as To', 'Alice', 'to'),
+ true,
+ '"as To" must authorize the To delivery role',
+ );
+ assert.equal(
+ helper.clarificationAuthorizesRecipientRole(null, 'Put Alice in the To field', 'Alice', 'to'),
+ true,
+ '"To field" must authorize the To delivery role',
+ );
+ assert.equal(
+ helper.clarificationAuthorizesRecipientRole(null, 'CC: Alice', 'Alice', 'cc'),
+ true,
+ 'explicit "CC:" must authorize the CC delivery role',
+ );
+ assert.equal(
+ helper.clarificationAuthorizesRecipientRole(null, 'BCC: Alice', 'Alice', 'bcc'),
+ true,
+ 'explicit "BCC:" must authorize the BCC delivery role',
+ );
+ assert.equal(
+ helper.clarificationAuthorizesRecipientRole(null, 'To: Bob, BCC: Alice', 'Alice', 'to'),
+ false,
+ 'multi-recipient clause must not attribute another recipient\'s To role to Alice',
+ );
+ assert.equal(
+ helper.clarificationAuthorizesRecipientRole(null, 'To: Bob, BCC: Alice', 'Alice', 'bcc'),
+ true,
+ 'multi-recipient clause must attribute BCC role to Alice',
+ );
+
+ const prevBccTarget = { target_kind: 'named', recipients: [{ identity: '[email protected]', role: 'bcc' }] };
+ const observedToCandidates = [{ identity: '[email protected]', role: 'to' }];
+ assert.deepEqual(
+ helper.resolveClarifiedRecipients(observedToCandidates, prevBccTarget, null, '[email protected]'),
+ [{ identity: '[email protected]', role: 'bcc' }],
+ 'identity-only answer must retain previously authorized bcc role',
+ );
+ assert.deepEqual(
+ helper.resolveClarifiedRecipients(observedToCandidates, prevBccTarget, null, 'Send to [email protected]'),
+ [{ identity: '[email protected]', role: 'bcc' }],
+ 'prepositional "to" answer must retain previously authorized bcc role',
+ );
+ assert.deepEqual(
+ helper.resolveClarifiedRecipients(observedToCandidates, prevBccTarget, null, 'To: [email protected]'),
+ [{ identity: '[email protected]', role: 'to' }],
+ 'explicit "To:" answer must update to the authorized To role',
+ );
+
assert.equal(helper.messageTargetMatchesObservedIdentities(
{ target_kind: 'named', recipients: ['Alice', '[email protected]'] },
['Alice'],
@@ -5336,6 +5402,46 @@ test('direct-message recipient guard uses structured intent and exact active ide
target_kind: 'named',
recipients: [{ identity: '[email protected]', role: 'to' }],
}, `${label}: recipient change did not update target`);
+
+ // Role preservation during recipient-change clarification:
+ // A plan authorizing Alice as BCC when composer exposes Alice as To must retain BCC
+ // on an identity-only answer, preventing unauthorized exposure on next send.
+ const bccPlanState = {
+ messaging: { target_kind: 'named', recipients: [{ identity: '[email protected]', role: 'bcc' }] },
+ requiresSubmission: true,
+ requiresStateChange: true,
+ pendingRecipientAuthorization: 'recipient_change',
+ observedRecipientCandidates: [{ identity: '[email protected]', role: 'to' }],
+ };
+
+ agent._planExecutionGuards.set(tabId, { ...bccPlanState });
+ assert.equal(
+ agent._bindClarifiedMessageRecipient(tabId, '[email protected]', 'user', {
+ question: 'Do you want to send to Alice instead?',
+ purpose: 'recipient_change',
+ }),
+ true,
+ `${label}: identity-confirmed clarify answer bound`,
+ );
+ assert.deepEqual(agent._planExecutionGuards.get(tabId)?.messaging, {
+ target_kind: 'named',
+ recipients: [{ identity: '[email protected]', role: 'bcc' }],
+ }, `${label}: identity-only answer must retain previously authorized BCC role`);
+
+ // Explicit role authorization in answer ("To: [email protected]") updates the role to To.
+ agent._planExecutionGuards.set(tabId, { ...bccPlanState });
+ assert.equal(
+ agent._bindClarifiedMessageRecipient(tabId, 'To: [email protected]', 'user', {
+ question: 'Do you want to switch Alice to To?',
+ purpose: 'recipient_change',
+ }),
+ true,
+ `${label}: explicit role change clarification bound`,
+ );
+ assert.deepEqual(agent._planExecutionGuards.get(tabId)?.messaging, {
+ target_kind: 'named',
+ recipients: [{ identity: '[email protected]', role: 'to' }],
+ }, `${label}: explicit role answer must adopt the authorized To role`);
}
});