A message crossing extension contexts is a request from another trust zone, even if every file ships in one package. A web page can influence DOM values and may send page messages; a content script can ask a more privileged background handler to use browser APIs or network access. The handler must verify sender context, message type, size, shape, and intended operation before acting. The extension should send only the data required for the user’s task. A message ID and response contract help distinguish retries from stale tab messages. A claimed origin or case ID inside the payload is not authority.
Extension Message Contracts and Page Data Boundary
Working case
The helper reads case 47 from the permitted portal and asks the background worker to open a checklist. A hostile page creates a similar DOM node and sends a forged message requesting an export of case 63. If the worker accepts any message named openChecklist, it can become a bridge from untrusted page content to private service access. The worker accepts only messages from its own content script on a permitted tab, validates a narrow schema, checks that the tab origin and user action match, and still asks the server to authorize case 47. It never accepts arbitrary URLs or attachment bytes in this message path.
Implementation boundary
function validChecklistMessage(message, sender) {
return sender.origin === 'https://permits.internal.test' &&
message.type === 'open-checklist' && /^CASE-[0-9]{2,6}$/.test(message.caseId) &&
Number.isInteger(message.revision) && message.revision >= 0 &&
typeof message.requestId === 'string' && message.requestId.length > 0 && message.requestId.length <= 96 &&
JSON.stringify(message).length <= 2048 &&
Object.keys(message).every(key => ['type', 'caseId', 'revision', 'requestId'].includes(key));
}
console.log(validChecklistMessage({ type: 'open-checklist', caseId: 'CASE-47', revision: 29, requestId: 'r-63', destination: 'outside' }, { origin: 'https://permits.internal.test' }));
// Output: falseDefine a small discriminated message set with version, type, request ID, and bounded fields. Reject unknown types, extra privilege-bearing fields, oversized text, and stale tab identities. Use sender metadata supplied by the extension runtime rather than a caller-written sender field. Keep page-to-content-script communication separate from content-script-to-background communication; the page can influence the former and cannot be allowed to impersonate the latter. Validate the server response again before rendering in the popup. If a message can trigger a side effect, require a user action record or confirmation bound to the exact target. Avoid broad relay functions such as fetchAnyUrl or executeCode. Log outcome category and request ID without copying private page text into a general diagnostic stream.
Cost and boundaries
Shape validation is O(B) for B message bytes after a strict maximum size check. Sender and permission checks add constant local work; server authorization adds network cost when required. A long-lived port can reduce setup overhead for repeated updates but must handle disconnect and stale tab state. Sending full page HTML multiplies data exposure and serialization cost, while a small case identifier and revision are cheap. Measure rejected message categories, average payload bytes, stale response count, and task completion. A high rejection count can reveal a broken adapter as well as an attack; inspect enough context to tell the difference without retaining raw private documents.
Failure trace
Send an allowed type from an unrelated tab and require denial. Add an unknown field requesting external upload and reject the message. Replay a valid message after the tab changes from case 47 to case 63; the old request ID must not affect the new popup. Close the content script while a background response is pending and avoid writing into a stale view. Supply 4 MiB of page text where 2 KiB is permitted; reject before parsing. Forge a page postMessage with the same type label and ensure it cannot reach privileged actions. Change tenant permission on the server and require denial even if the background handler accepted the local message.
Verification
- Unrelated and stale senders cannot trigger privileged work.
- Unexpected destinations and large payloads are rejected.
- Server authorization remains mandatory.
Practice drill
Define one versioned message for opening a case checklist. Permit case IDs such as CASE-47, a revision number, and a 96-character request ID; cap the encoded message at 2 KiB. Pass it from a content script on the portal to the worker, then ask the server to authorize it. Test an unrelated tab, a forged page message, a stale tab, an extra destination URL, a 4 MiB payload, and a revoked server session. Record the visible error state for each case and verify no private data was sent to a new destination.
Decision note
Every bridge from page data to extension privilege is a protocol that needs sender checks and server permission.
Common Mistakes
- Trusting a sender origin written inside the payload.
- Offering a generic privileged request relay.
- Treating a runtime message as permission to read another tenant.
Related lessons
Browser Extension Trust and Lifecycle; Extension Host Permissions and User Invocation; Content Script Isolation and DOM Mutation; Extension Background Events and Durable State; Cross-Window Messages: Origin, Source, Schema, and Replay; Embedded Interfaces and Cross-Window Contracts.
Connected practice
Build Project: permit checklist browser helper and review Web Development: extension boundary decisions quiz.
