Frontend System Design17 min readPremium

Design a Password Manager Extension – Frontend System Design

67. Design a Password Manager Extension

We’ll walk through the frontend system design for a password manager browser extension: a product that reads login forms on arbitrary sites, unlocks a vault, and fills a username and password without ever handing the wrapping key to the page. You’ll see why content scripts share a DOM and not a JavaScript heap, why autofill is a heuristic problem, why an iframe must use its own origin, and why crypto belongs on a chrome-extension:// page.

This is not “inject a script and set input.value.” The interviewer is asking you to put secrets next to hostile JavaScript and still be able to explain the boundary. A page can watch the DOM, spoof an unlock modal, and lie about its URL in a message body. The design is the set of rules that still work when that is true.

Problem Statement

Design the frontend for a password manager browser extension like 1Password, Bitwarden, or Chrome’s password manager.

Requirements:

  • Detect login fields on web pages, including fields inside iframes and shadow roots
  • Suggest and fill the right item for the current origin, after the vault is unlocked
  • Keep the vault locked at rest; unlock with a master password or the OS
  • Never run key derivation or decryption in the page
  • Sync an encrypted vault blob across the user’s devices
  • Resist phishing: a lookalike host must not receive the real item

Describe the extension processes, the isolation boundary, autofill, and the vault session.

Interviewers are checking three things. Can you name the JavaScript worlds an extension actually has? Do you authorize a fill from MessageSender instead of from a string the content script sent? And do you put the unlock UI on an extension-origin page, where the site cannot draw a fake one on top?


Clarifying Questions

# Question Interviewer’s Answer
1 Chrome MV3, or also Firefox and Safari? Design for Chromium MV3. Call out Firefox if you have time.
2 Master password, passkey, or OS unlock? Master password on day one. OS unlock is a follow-up on the same session object.
3 Do we fill credit cards and TOTP? Store them as other item kinds. Do not autofill TOTP into a password field.
4 Inline unlock on the page, or only the popup? Unlock is an extension page. The page never sees the prompt.
5 Related domains: should login.bank.com see bank.com items? Only when the item opts into subdomains, using the public suffix list.
6 Enterprise SSO / passkeys as a first-class login? Out of scope. Mention WebAuthn as a vault unlock factor, not as a site login.
7 How many items and how fast is fill? A few thousand items. Fill should feel instant after the vault is unlocked.

Question 1 decides the process model: a killed service worker cannot hold a CryptoKey. Question 4 is the phishing question in disguise. Question 5 decides whether origin matching is equality or a suffix rule you have to get right.


Requirements

Functional

  • Detect username and password fields using autocomplete first, then type, then conservative name hints.
  • Show an inline icon that opens the extension popup. Do not draw an unlock form in the page.
  • Fill only after the vault is unlocked, and only into the frame that requested it.
  • Ask the user when more than one item matches, or when the item is marked “always confirm.”
  • Lock on idle, on browser close, and when the crypto document dies.
  • Save a new login only from an extension page, after the user confirms the origin the browser reported.
  • Sync the sealed vault blob. The server never sees plaintext items or the wrapping key.

Non-Functional

  • The wrapping key never appears in a content script, in chrome.storage, or in a page-world variable.
  • A fill uses the sender’s origin. A payload URL is ignored.
  • Key derivation stays off the page you are filling, and it does not freeze the popup for seconds without feedback.
  • Content scripts stay small. They classify fields and apply one short-lived grant.
  • Extension pages ship with a strict CSP and no remotely hosted script, which MV3 already forbids.
  • A hostile page that watches input events still cannot unlock the vault or list other origins’ items.

The load-bearing requirement is the last one. Autofill always reveals one secret to the page you meant to log into. The design is about not revealing anything else, and not filling the wrong origin.

Napkin Math

Metric Estimate Calculation So what?
Vault on disk ~1–4 MB 2,000 items × 1–2 KB sealed Fine in IndexedDB. Do not decode every item into the content script.
Unlocked working set ~2–6 MB Same items in memory on the crypto page Acceptable in an offscreen document. Not in every tab’s content script.
KDF on unlock 200–800 ms Argon2id or a high PBKDF2 iteration count Show a progress state. Never run this in the page or in a content script.
Fill after unlock < 50 ms One origin index lookup + one decrypt + one message If this is slow, you are decrypting the whole vault per keystroke.
Idle lock 10 min default chrome.idle plus an alarm as backup A killed worker is not a lock. The crypto document must drop the key.
Grant lifetime 2 s One request id, then drop A late content script cannot reuse an old plaintext grant.

Architecture

Password manager extension architecture: untrusted page, isolated-world content script, service worker router, extension-page crypto session, locked vault storage, and sync API

A Manifest V3 extension is several processes that do not share a heap. Name them, and say what each is allowed to hold.

Process Origin / world Owns Must not own
Page The site Its own JS, the DOM it created Wrapping key, unlock UI, vault
Content script Isolated world, same DOM Field detection, one fill, a port Wrapping key, item list for other hosts
Service worker Extension Routing, MessageSender checks, alarms A long-lived CryptoKey
Popup / unlock page chrome-extension:// Master password prompt, item picker Nothing from the current site’s DOM
Offscreen document chrome-extension:// Crypto session, in-memory key A copy of the key in storage

The service worker is a router. It is killed under memory pressure and after idle. If you unwrap the key there, a restart leaves you with either a locked vault (good) or a key you persisted to chrome.storage (a breach). MV3’s offscreen document is the place that can hold a CryptoKey for the session and still be closed on lock.

“The content script sees the form. The popup collects the master password. The offscreen page unwraps the key. The service worker only checks who asked and forwards one item.”

Firefox can keep a background page alive. Do not build the Chromium design around that. The same session object still lives off the page world.

Why not a content-script vault?

The tempting shortcut is a modal over the form and a key in the content script. That modal is in the page’s DOM. The site can clone it, cover it, or listen to the field you labeled “Master password.” Isolated-world JavaScript does not save you: the user is typing into a node the page can observe. Keep the key on an origin the site cannot read.


Data Model

Password manager data model: locked vault blob, vault item, origin grant, field hint, crypto session, and autofill request

Split durable sealed data from the session. The disk format is a blob plus KDF parameters. The live format is a wrapping key and a decrypted index used only on the crypto page.


type ItemId = string;
type ItemKind = "login" | "note" | "card" | "totp";
type VaultState = "locked" | "unlocking" | "unlocked" | "idleSoon";

interface OriginGrant {
  readonly origin: string;          // https://bank.example  (scheme + host + port)
  readonly includeSubdomains: boolean;
  readonly exactPort: boolean;
}

interface VaultItem {
  readonly id: ItemId;
  readonly kind: ItemKind;
  readonly label: string;
  readonly username?: string;
  readonly secret?: string;         // password; TOTP seeds are a different field
  readonly origins: readonly OriginGrant[];
  readonly updatedAt: string;
}

interface LockedVault {
  readonly vaultId: string;
  readonly kdf: "PBKDF2" | "Argon2id";
  readonly kdfParams: { iterations: number; memoryKiB?: number; salt: ArrayBuffer };
  readonly wrappedKey: ArrayBuffer;
  readonly itemsCiphertext: ArrayBuffer;
  readonly rev: number;
}

interface CryptoSession {
  readonly state: VaultState;
  readonly wrappingKey?: CryptoKey; // present only when unlocked or idleSoon
  readonly idleMs: number;
}

type FieldRole = "username" | "password" | "newPassword" | "otp" | "ignored";

interface FieldHint {
  readonly role: FieldRole;
  readonly source: "autocomplete" | "type" | "name";
  readonly visible: boolean;
}

interface AutofillRequest {
  readonly requestId: string;
  readonly hints: readonly FieldHint[];
  // no url, no origin: the worker reads MessageSender
}

interface AutofillGrant {
  readonly requestId: string;
  readonly itemId: ItemId;
  readonly username?: string;
  readonly secret?: string;
  readonly ttlMs: 2000;
}

Four choices are worth defending.

Origins are parsed URLs, not host substrings. bank.example is not a suffix match on notbank.example, and it is not a prefix match on bank.example.evil.example. Store a canonical origin string you produced with the URL parser, then compare fields.

Subdomains are an opt-in on the grant. Users want login.bank.example to see the bank.example item. That is an eTLD+1 rule, not endsWith("bank.example"). mybank.example and bank.example share nothing. Use the public suffix list on the crypto page, never a home-grown split on dots.

The content script never receives the vault. It receives labels for a picker, or one AutofillGrant. Decrypt-one-item is the API. A bug in the detector then leaks one password for this origin, not the user’s email logins.

TOTP is another kind. A one-time code field is autocomplete="one-time-code". Filling the password there locks the user out and teaches the page the wrong secret. Keep TOTP off the password path.


Isolated Worlds

Chrome injects content scripts into an isolated JavaScript world. That world has its own Object, its own window wrappers, and the extension APIs. It shares the underlying DOM with the page. This is the whole security story, and both halves matter.

What Shared with the page? So what?
JS heap, closures, chrome.* No The page cannot call your functions or read your variables.
DOM tree, input values, events Yes A fill is visible. An in-page unlock field is visible.
DOM prototypes the page patched No (you see native accessors) Page value getters do not fool the isolated world.
Visual pixels Yes The page can overlay your in-page icon or a fake prompt.

Isolated worlds stop a site from reading your variables. They do not stop it from drawing a lock that looks like yours. That is why the master password is typed into a popup or extension tab — a chrome-extension:// document the site cannot style.

When you fill, write through the native value setter from your world, then dispatch input and change so React-controlled fields update. Then drop the strings. You are not hiding the password from the site you just logged into. You are refusing to keep a copy after the turn.

The fill routine is two small steps in the content script. For each target input, call the native value setter from HTMLInputElement.prototype (so a page-patched setter can’t intercept or block it), then dispatch bubbling input and change events so framework-controlled fields see the new value. After filling the username and password, the routine replaces its grant reference with an id-only copy, so the plaintext strings have no live reference left in the content script’s scope.

That is the entire content-script privilege: native accessors plus chrome.runtime. Do not keep an item cache in the tab, log grants, or write them to sessionStorage. A refresh can ask again.

Set all_frames: true and, where you need it, match_about_blank for srcdoc and about:blank children. Each frame gets its own content script and frameId. A top-level script that reaches into a child is how you fill the wrong document.


Autofill Heuristics

Field classification is a ranked set of signals, not a regex over every input on the page. The WHATWG autocomplete tokens are the contract sites already use for browsers. Start there.

The field classifier is a pure function from an input element to a hint ({ role, source, visible }) or nothing. It checks signals in a fixed order and stops at the first match:

  1. Disqualifiers. Disconnected, disabled, read-only, hidden, or aria-hidden="true" inputs are skipped.
  2. autocomplete token. Take the last token. username and email map to username, current-password to password, new-password to new password, one-time-code to OTP, and the cc-* tokens to ignored.
  3. Input type. password is a password and email is a username.
  4. Name or id. A text input named like user, login, or email is a username. One named like pass, passwd, or pwd is a password, unless it is a search input.

The source field records which signal won, so the pairing step can trust an autocomplete match more than a name guess.

Prefer the visible field in the same form. Sites often keep a hidden password input next to a visible one. Skip type="search" and anything whose accessible name is “Search.”

Pairing. A username without a password is not a login. Walk the containing form first. If there is no form, pair the nearest visible password in the same shadow root or document. Open shadow roots are walkable. Closed ones are not unless the site put autocomplete on a light-DOM input — say that limitation out loud.

SPAs. Observe added nodes, and listen to chrome.webNavigation so a same-document navigation re-runs detection. Tear down icons from the previous view. A leftover icon on a settings page offers a fill on new-password.

When not to fill automatically. More than one item, a confirm-always flag, a password-change form, a first visit to a host, and any frame that is not visible. Silent fill on a lookalike host is the phishing bug with a product hat on.


Iframe Pitfalls

Sequence diagram of password-manager autofill: field detection, sender origin check, one-item decrypt on the extension page, user confirm, fill, and forget

The hard case is a visible tab on shop.partner.example and a login form in an iframe on accounts.bank.example. The omnibox shows the shop. The password belongs to the bank. If you match on the tab URL, you either refuse a real bank login or, worse, offer the shop item to the bank frame.

Rules that keep this straight:

  • Each frame’s content script reports hints only. It does not send a URL.
  • The worker reads sender.origin, sender.url, sender.tab, and sender.frameId.
  • The crypto page matches vault grants against sender.origin, not against the top frame.
  • A grant is addressed to that requestId and that frame. The worker does not broadcast plaintext to every script in the tab.

interface SenderView {
  readonly origin: string;
  readonly url: string;
  readonly tabId: number;
  readonly frameId: number;
}

The worker builds a SenderView from the browser-supplied MessageSender and rejects the message if any field is missing. Nothing in it comes from the message payload.

The origin matcher takes a saved grant, the sender’s origin, and a public-suffix lookup, and answers yes or no. It parses both with the URL parser, and any parse failure is a no. Schemes must be equal and must be http: or https:. If the grant pins a port, the effective ports (filling in 443 or 80) must match. Identical hostnames match. Otherwise the grant must opt in to subdomains, both hosts must share the same registrable domain from the public suffix list, and the frame host must be that domain or end in a dot followed by it.

Notice what the matcher never does: string includes, stripping www as a global rule, or trusting location.href from the payload. Homograph hosts are compared as the URL parser emits them (punycode). Display the Unicode form in the popup so the user can see еxample is not example, but match on the parsed host, not on painted text.

Sandboxed frames and some srcdoc documents have a null origin and never match a saved https grant. Do not fall back to the top origin. A transparent overlay on an in-page icon can steal a click, so prefer opening the popup. One-click fill needs an unlocked session, a single exact-origin match, and a first-save confirm.


Vault Unlock and Crypto

Vault states: locked, unlocking, unlocked, idle soon, and locked again after idle, failure, or process death

The vault is a state machine with one privilege bit: whether a wrapping key exists in memory on the extension page.

  • Locked. IndexedDB holds LockedVault. No CryptoKey.
  • Unlocking. The popup collected a master password. The offscreen page runs the KDF and tries to unwrap. The password string is dropped after the derive call.
  • Unlocked. The wrapping key sits in the offscreen document. Decrypt-one-item is allowed after an origin check.
  • IdleSoon. Same key, UI warns. Activity returns to Unlocked. Timeout goes to Locked and wipes the key.
  • Failed / process gone. UI or a dead document. Durable state is Locked. Never rebuild the key from storage.

Use Web Crypto on the extension page: a KDF (PBKDF2 in the platform, or Argon2id in a Wasm module you ship with the extension), then AES-GCM for the item blob and for wrapping the data key. The server stores the same sealed blob. There is no “decrypt on the API.”


type SessionEvent =
  | { type: "unlock"; password: string }
  | { type: "lock" }
  | { type: "activity" }
  | { type: "tick"; now: number };

A pure reducer handles everything except unlock. lock always returns Locked. activity moves Unlocked or IdleSoon back to Unlocked and resets the timer. tick compares time since the last activity with the idle limit: past the limit means Locked, within 30 seconds of it means IdleSoon, and otherwise nothing changes.

The unlock branch is I/O: load the blob, derive, unwrap, or throw. Keep it out of the reducer. On failure, increment a backoff in the popup and stay Locked. On success, hold the CryptoKey in a closure the document owns, not in globalThis you log later.

The service worker will die. A woken worker starts with empty memory. That is a lock, which is fine, unless you wrote the key into chrome.storage.session. Storage is a dump of bits. A Web Crypto CryptoKey can be non-extractable. Prefer that in the offscreen document, and treat teardown as lock.

OS unlock is the same state machine with a different unlock implementation. It still happens on the extension page, not as a prompt the content script starts so the page can style around it.


Phishing and Origin Checks

Isolation boundary for a password manager: page world, isolated-world content script, chrome-extension pages, and a table of allowed and rejected crossings

Phishing against a password manager is usually not a crypto break. It is a confused fill: the extension treats a bad frame as a good one.

Attack shape Wrong design Rule
Lookalike host Substring or “contains bank” Parsed origin equality, punycode host
Evil iframe on a good tab Match the tab URL Match sender.origin for that frame
Good iframe on an evil tab Match the top URL Same: the frame that owns the fields
Script-reported URL payload.url Ignore it; use MessageSender
Fake unlock UI Modal in the page Unlock only on chrome-extension://
Open redirect to the real host Fill as soon as the host matches Confirm on first use; do not race a redirect

The content script’s location.href is the real frame URL, but it is still not the authorization source. A buggy script can put any URL in a message. The browser-stamped sender is the field you cannot forge from that frame.

Save is an extension-page dialog that reprints the origin from the sender, not from the page title. Auto-saving every password field is how a lookalike harvests a new item under the wrong host. http: and https: stay different. localhost, IPs, and file: are exact match only; there is no public suffix story for an IP.


API and Messages

There is no REST call on the fill path. The hot path is extension messages. Sync is a sealed blob.


type ContentToWorker =
  | { type: "fillRequest"; requestId: string; hints: FieldHint[] }
  | { type: "saveOffer"; requestId: string };

type WorkerToContent =
  | { type: "needUnlock"; requestId: string }
  | { type: "pickItem"; requestId: string; labels: { id: ItemId; label: string }[] }
  | { type: "grant"; grant: AutofillGrant }
  | { type: "deny"; requestId: string; reason: "locked" | "noMatch" | "origin" };

type WorkerToCrypto =
  | { type: "lookup"; senderOrigin: string; hints: FieldHint[] }
  | { type: "decryptOne"; itemId: ItemId; senderOrigin: string }
  | { type: "lock" };

// REST, sealed only
GET  /api/vault                 // { data: LockedVault }
PUT  /api/vault                 // If-Match: rev; body LockedVault
POST /api/vault/register        // device enrollment, not items

On needUnlock, the content script does not draw a password field. It opens the popup or a badge. After unlock, replay the pending fillRequest with the same requestId and stored sender. If the tab navigated, the request dies. Sync is last-writer-wins on rev and a sealed blob. The API never receives a password or the wrapping key.


Optimizations

Problem Technique Effect
Decrypting the vault per fill In-memory index on the crypto page after unlock Fill is a map lookup plus one item
Fat content scripts in every frame Detect + fill only; no KDF, no item list Small inject, smaller leak surface
Service worker death mid-fill Offscreen session; worker is stateless A killed router does not lock by accident or leave a key
KDF jank in the popup Run derive in the offscreen page, show Unlocking The popup stays responsive
SPA field churn Debounced mutation observer + navigation events No fill loop on every React render
Thousands of icons One icon per classified form, not per input Less layout noise, fewer clickjack targets

On unlock, index each canonical origin and each opted-in eTLD+1 to item ids. Rebuild on vault write, not on every focus.


Handling Edge Cases

  • Multiple password fields. new-password is not a fill of the current secret. Two current-password fields: fill both only if they are visible mirrors, otherwise ask.
  • Web components. Open shadow roots are searchable. Closed ones are not. Do not pretend to pierce them.
  • Generate vs fill. Registration is a new secret from the extension page, not a fill of an old one.
  • Clipboard. Copy lasts longer than a 2s grant. Clear it from the extension page. Never write the wrapping key there.
  • Incognito. Do not reuse one offscreen session across a private and a normal window if the product says they are separate.
  • Host permissions. Inject only on http and https, never chrome:// or other extensions.
  • Save phish. A hidden login-shaped form is not a save. Saves start in the popup, with the sender origin printed back.
  • Unlock in flight. The offscreen page owns the KDF. A second click waits.

Accessibility and Security

Accessibility

  • The inline icon is a real button named “Open password manager,” not a background image on the field.
  • The popup is a document: focus on open, Esc closes, and a live region for “Vault locked” / “Filled username.”
  • Do not fill a field the user cannot see, including a screen-reader-only password sitting next to the active one.
  • Respect prefers-reduced-motion on the idle warning.
  • Generated passwords need text in the popup, not only dots, so a screen reader can read them before save.

Security and CSP

Extension pages are still web pages. They get a CSP in the manifest so a bug cannot load a script from the network.


{
  "content_security_policy": {
    "extension_pages": "default-src 'self'; script-src 'self'; object-src 'self'; connect-src 'self' https://api.example.com; img-src 'self' data:; style-src 'self'; frame-ancestors 'none'"
  }
}
  • No 'unsafe-eval', no remote script URL. MV3 already bans remotely hosted code; the CSP is defense in depth for the popup and the offscreen page.
  • Content scripts are not page scripts. Page CSP does not govern isolated-world JS. Do not use that as permission to inject inline page-world scripts. Stay in the isolated world.
  • connect-src is the sync API only. The content script does not fetch the vault.
  • frame-ancestors 'none' on extension pages stops a site from framing your unlock UI if a browser bug or a web-accessible resource ever made that possible.
  • Web-accessible resources should be empty for this product. You do not need the page to <img src="chrome-extension://...">.
  • Permissions: host access for http/https, storage, alarms, idle, offscreen, scripting only if you need it. Avoid <all_urls> on privileged APIs you are not using.

For a broader treatment of origin isolation in the browser, see Design a Coding Playground. The playground keeps untrusted code off the app origin. This product keeps trusted secrets off the site origin. The geometry is the same idea from the other side.


What a Strong Answer Sounds Like

Topic Junior answer Senior answer
Isolation “Content scripts are sandboxed” Isolated JS heap, shared DOM; unlock UI cannot live in that DOM
Autofill Query input[type=password] autocomplete first, pairing, visibility, SPA, no OTP or new-password
Iframes Use the tab URL all_frames, per-frame script, sender.origin + frameId
Vault Store the key in chrome.storage Sealed blob in IndexedDB, non-extractable key in an extension page
Phishing “Check the domain” Parsed origins, PSL for opt-in subdomains, ignore payload URLs

Conclusion: How to Design a Password Manager Extension

Start with the worlds. The page is hostile. The content script can see the form and must not see the wrapping key. The service worker can see MessageSender and must not be your key store. The extension page is the only place that unlocks, derives, and decrypts.

Then make fill a narrow grant: classify fields without sending a URL, authorize the frame the browser reported, decrypt one item, write through the native setter, and forget. If you can explain why an in-page master-password modal is a phishing UI, why a tab URL is the wrong origin for an iframe, and why a Manifest V3 service worker cannot hold the key, you have answered the question the interviewer is actually asking.