A team ships a voice assistant for personal notes. Users dictate things they would never put in a ticket: a diagnosis they are worried about, an argument with a landlord, a half-formed business idea. The privacy page says "your data stays with you". Six months later a developer adds an error reporter to catch a rare crash. It captures the last few breadcrumbs, and one breadcrumb is the text of the final transcript segment. Nobody decided to collect transcripts. The promise broke through an unremarkable dependency.
This is the realistic failure mode of privacy-first design. It is rarely a dramatic breach; it is a thousand small egress paths, each added for a good reason. A local-first assistant is therefore a property you have to enforce structurally: where bytes are stored, what the storage looks like if someone copies it, which origins the page may contact, and which components are able to see plaintext at all. This article walks through that structure for browser-based assistants, with an honest account of what it protects, what it does not, and when you should choose a different architecture.
1. What "Never Leaves the Device" Has to Mean in Practice
The phrase is easy to say and hard to keep, so pin it to a testable statement. A useful one is: no byte derived from the user's transcripts, audio or embeddings is sent to any origin that the user did not explicitly choose, and the stored form of those bytes is unreadable without a secret that never leaves the device. Each clause maps to something you can check. The first maps to network behaviour. The second maps to encryption at rest and key handling.
Three egress paths cause most of the damage and deserve names. Intentional egress is the model call or sync you designed. Incidental egress is the analytics snippet, error reporter, font CDN, or update check that carries the page URL, user agent, or application state. Platform egress is behaviour you inherit from the browser or an API, such as a speech-recognition API that streams microphone audio to a vendor service. A privacy-first architecture inventories all three, because the user does not care which category leaked.
2. Threat Model: Who Are You Defending Against?
Local storage is not automatically private storage. It moves the trust boundary from "the vendor's servers" to "this browser profile on this machine", and that boundary has its own adversaries. Writing them down first prevents encrypting against the wrong one.
- The vendor and its subprocessors. The main reason to go local. Defended by never transmitting plaintext and by not having a server that could be compelled or breached for transcripts.
- A curious person with the device. A shared family laptop, a borrowed phone, a coworker at an unlocked desk. Defended by encryption at rest with a key that is not sitting next to the data, and by an easy "lock" action.
- Disk theft or a stolen backup. Browser profiles are ordinary files. Operating-system disk encryption covers a powered-off device; app-level encryption additionally covers profile backups and copied directories.
- Malicious or over-permissioned browser extensions. They can read page content and often storage. Largely out of your control; the honest answer is to state it in the threat model rather than claim immunity.
- Cross-site scripting in your own page. If an attacker can run script in your origin, they can call your own decrypt function. Encryption at rest does not stop this; a strict Content Security Policy and a tiny dependency surface do.
- Malware with full user privileges. Out of scope for a web app. Say so.
Notice what is missing from the list: a nation-state attacker, and the user who forgets their passphrase. The first is out of scope for a consumer web app. The second is in scope as a product decision, because a design that makes data unrecoverable on forgotten secrets has to say so loudly, offer an export, and never imply that a "reset" is possible.
3. Where the Bytes Live: Browser Storage Options Compared
Browsers offer several places to put data, and they differ in exactly the ways that matter for an assistant that accumulates long transcripts and possibly audio. The table below is qualitative on purpose; quotas vary by browser, device and available disk, so check the current behaviour of your target browsers rather than trusting any number printed in an article.
| Storage | Access model | Typical capacity | Good for | Privacy-relevant caveat |
|---|---|---|---|---|
| Cookies | Sent to the server with matching requests | Very small | Nothing in this design | Automatic transmission defeats the purpose |
| localStorage | Synchronous string key-value | Small (a few megabytes in most browsers) | Non-sensitive preferences | Blocks the main thread; strings only; readable by any script in the origin |
| IndexedDB | Asynchronous transactional object store | Large, quota-managed | Encrypted transcript records, embeddings, metadata | Stores structured-cloneable values including typed arrays and CryptoKey objects |
| Origin Private File System | File-like handles, usable from workers | Large, quota-managed | Audio blobs, model weights, vector index files | Not visible to the user in a file manager, which is neither privacy nor a security boundary |
| Cache API | Request/response pairs | Large, quota-managed | Model files fetched once | Fine for public weights; never put user data here |
A sound default split is: IndexedDB for structured, encrypted records; the Origin Private File System for large binary blobs that you encrypt in chunks; the Cache API only for public assets such as model weights; localStorage for a theme flag and nothing else. Whatever you choose, request persistence with navigator.storage.persist() after a meaningful user action. Without it, "best-effort" storage can be evicted under disk pressure, and some browsers also clear script-written storage for sites a user has not visited for a while. Users experience eviction as "the assistant forgot everything", which is a privacy feature nobody asked for.
4. Encrypting at Rest with the Web Crypto API
The Web Crypto API (crypto.subtle, available in secure contexts only) gives you audited primitives so you never hand-roll cryptography. The standard choice for authenticated encryption is AES-GCM with a 256-bit key and a fresh random 96-bit initialization vector per record. Two rules carry most of the weight. First, never reuse an IV with the same key; with random 96-bit IVs, rotate the key well before the number of records under one key reaches the low billions, which a personal assistant will not approach but a shared tenant might. Second, bind each ciphertext to its record by passing the record identifier as additional authenticated data, so an attacker cannot swap two ciphertexts around inside the database without detection.
The following module derives a key from a passphrase, seals one transcript record, and opens it again. It is intentionally small enough to audit in one sitting.
// secure-store.js: encrypted transcript records in IndexedDB
const DB_NAME = 'assistant';
const STORE = 'transcripts';
const enc = new TextEncoder();
const dec = new TextDecoder();
function openDb() {
return new Promise((resolve, reject) => {
const req = indexedDB.open(DB_NAME, 1);
req.onupgradeneeded = () => req.result.createObjectStore(STORE, { keyPath: 'id' });
req.onsuccess = () => resolve(req.result);
req.onerror = () => reject(req.error);
});
}
// Derive a non-extractable AES-GCM key from a passphrase.
// The salt is random, stored beside the data, and not secret.
export async function deriveKey(passphrase, salt) {
const material = await crypto.subtle.importKey(
'raw', enc.encode(passphrase), 'PBKDF2', false, ['deriveKey']
);
return crypto.subtle.deriveKey(
{ name: 'PBKDF2', salt, iterations: 600000, hash: 'SHA-256' },
material,
{ name: 'AES-GCM', length: 256 },
false, // extractable: false, so script cannot read the raw key bytes
['encrypt', 'decrypt']
);
}
export async function saveRecord(key, id, body) {
const iv = crypto.getRandomValues(new Uint8Array(12));
const ciphertext = await crypto.subtle.encrypt(
{ name: 'AES-GCM', iv, additionalData: enc.encode(id) },
key,
enc.encode(JSON.stringify(body))
);
const db = await openDb();
await new Promise((resolve, reject) => {
const tx = db.transaction(STORE, 'readwrite');
tx.objectStore(STORE).put({ id, iv, ciphertext });
tx.oncomplete = resolve;
tx.onerror = () => reject(tx.error);
});
}
export async function loadRecord(key, id) {
const db = await openDb();
const row = await new Promise((resolve, reject) => {
const req = db.transaction(STORE).objectStore(STORE).get(id);
req.onsuccess = () => resolve(req.result);
req.onerror = () => reject(req.error);
});
if (!row) return null;
// Throws if the ciphertext, IV or id was tampered with.
const plain = await crypto.subtle.decrypt(
{ name: 'AES-GCM', iv: row.iv, additionalData: enc.encode(id) },
key,
row.ciphertext
);
return JSON.parse(dec.decode(plain));
}
Two details are easy to miss. The iteration count of 600,000 for PBKDF2 with SHA-256 follows current published guidance at the time of writing; treat it as a floor that moves upward, and store the parameters alongside the salt so you can raise them later and re-wrap. And encrypting the record body still leaves metadata in the clear: record identifiers, timestamps, and sizes. If the existence or timing of a conversation is sensitive, use random identifiers and consider padding, or accept the leak and say so.
5. Keys: Passphrases, Passkeys and Non-Extractable Handles
Encryption only moves the problem to key custody. There are three realistic ways to hold the key, and each trades convenience against how much an attacker with the profile directory can do.
Passphrase-derived key
The user types a secret, you derive the key, and nothing key-like is ever stored. This is the strongest option against a copied profile and the weakest for usability: it must be typed at every unlock, and a forgotten passphrase means permanent loss. Its security is exactly the strength of the passphrase combined with the cost of the key-derivation function. Memory-hard functions such as Argon2 resist GPU guessing better than PBKDF2, but they are not built into Web Crypto, so you would ship a WebAssembly implementation and take on that dependency.
Device-bound key
Generate a random key once, mark it non-extractable, and store the CryptoKey object in IndexedDB. Script can use it but cannot read its bytes, so a copied database dump is useless without the browser's own key storage. The limits are important: any code running in your origin can still ask the key to decrypt, so this defends against offline copying, not against XSS, and the key does not roam between devices. It suits "unlock without friction on my own laptop" and pairs well with an auto-lock timer.
Passkey-derived secret
Some browsers and authenticators support the WebAuthn PRF extension, which lets a passkey yield a stable secret that you feed into key derivation. The user unlocks with a fingerprint or device PIN, and the secret never exists as a string anyone typed. Support is uneven across browsers and authenticators, so treat it as a progressive enhancement over a passphrase fallback, and test the recovery path as carefully as the happy path.
Whichever you pick, add two product features that are really security features. A visible lock now button that drops the in-memory key and clears decrypted state. And a plain-language export and delete screen: one action writes an encrypted backup the user controls, another wipes every store, the Cache API entries, and any registered service worker for the origin.
6. Zero Telemetry Is a Build Property, Not a Promise
You cannot audit a promise, but you can audit a Content Security Policy and a test suite. The CSP is the most valuable single control for this architecture because it makes the browser itself refuse requests to origins you did not list, which turns "we do not phone home" into something enforced even when a dependency tries.
Content-Security-Policy:
default-src 'none';
script-src 'self' 'wasm-unsafe-eval';
style-src 'self';
img-src 'self' data: blob:;
media-src 'self' blob:;
font-src 'self';
worker-src 'self' blob:;
connect-src 'self';
base-uri 'none';
form-action 'none';
frame-ancestors 'none'
With connect-src 'self' the page can only fetch, open WebSockets, or beacon to its own origin; there is no allowlisted analytics host to abuse. If you load model weights from a model hub, add that single origin explicitly and nothing else, and consider mirroring weights to your own origin so the policy can stay at 'self'. The 'wasm-unsafe-eval' source is needed by many WebAssembly runtimes; confirm whether your stack requires it rather than adding it reflexively.
Policy is the seatbelt; tests are the inspection. A browser-automation test that loads the app, performs a representative session, and fails if any request goes to an origin outside an explicit allowlist catches the incidental egress that CSP might have been loosened to permit. Run it on every build. Also audit what you do not import: a font loaded from a public CDN leaks the visitor's IP address and the page URL to a third party, and a crash reporter configured with default breadcrumbs can capture application text. If you need crash data, report an error class, a build identifier and a stack with message strings scrubbed, and let the user inspect the payload before it is sent.
7. Running the Model and the Voice Pipeline Locally
Storing transcripts locally means little if every utterance is sent to a remote model to produce them. The privacy boundary has to cover inference too, and the browser now offers credible ways to do that: WebGPU-accelerated runtimes for small and mid-sized language models, WebAssembly builds of speech-to-text engines, and ONNX-based neural text-to-speech voices. The exact models change quickly, so choose by constraint rather than name: weights small enough to download once and cache, quantized so they fit in the memory a typical user device can spare, and licensed for your distribution.
Voice deserves its own warning. The browser's built-in speech-recognition API is not guaranteed to run on the device; in some browsers it streams microphone audio to a vendor service for recognition. That is platform egress, and it will not show up in your own network code. For a privacy claim you can defend, use an on-device speech-to-text model in a worker, feed it audio from getUserMedia in short chunks, and keep audio buffers in memory unless the user explicitly asks to save a recording. When recordings are saved, encrypt them with the same envelope as transcripts.
Be realistic about quality. A small local model is not a frontier model. It will follow instructions less reliably, handle long contexts poorly, and be slower on modest hardware. Compensate in the design rather than hoping: keep prompts short, retrieve a few relevant notes from a local encrypted index rather than stuffing history, constrain outputs with a schema, and keep the prompt contract narrow enough that a weaker model can meet it. Check device capability at start-up and degrade gracefully to text-only or to an explicit opt-in remote mode rather than failing silently.
8. When Not to Go Local-Only: Hybrid Designs and Their Honest Costs
Local-only is a good fit for a single user on a single device with modest quality needs. It is a poor fit when users expect sync across phone and laptop, when the task needs a frontier-scale model, when you must satisfy audit or retention rules that require server-side records, or when a team shares the data. Pretending otherwise produces worse privacy, not better, because users route around the limitations with screenshots and copy-paste into other tools.
If you add a remote path, make it a deliberate, visible, per-request choice with a narrow contract:
- Minimize before sending. Send the smallest excerpt needed, with obvious identifiers redacted locally first. Show the user what will be sent.
- Keep the default local. Remote mode is opt-in per session or per action, never a silent fallback when the local model is slow.
- Sync ciphertext, not plaintext. If you offer cross-device sync, the server stores encrypted blobs and never holds the key. Key exchange between devices is the hard part: design it before promising it, and note that any server-assisted recovery weakens the guarantee.
- Be precise in the policy. "Remote mode sends the selected excerpt to the model provider you chose" is a sentence a user can act on. "We take privacy seriously" is not.
9. Putting It Together: A Worked Example, a Checklist, and What to Do Monday
A worked example: the dictated-notes assistant
Return to the notes app from the opening. A defensible build looks like this. On first run the app asks for a passphrase and derives a non-extractable key; the salt and parameters are stored in IndexedDB beside the data. A worker runs an on-device speech-to-text model and a small local language model that summarizes each note and extracts tasks. Every transcript, summary and embedding is sealed with AES-GCM, with the record identifier as authenticated data. The CSP allows only the app's own origin, plus a single weights host used during first install, then the weights are cached and the policy tightens on the next release. The app never loads third-party scripts. An end-to-end test records the origins contacted during a scripted session and fails the build on any new one. The settings page has lock, export and delete-everything actions, and an optional remote summarizer that is off by default and shows the exact text to be sent.
Now replay the opening incident. A developer adds an error reporter. The CSP blocks its endpoint immediately in development, the origin test fails in CI, and the conversation happens before release instead of after a user asks why their dictation was in a vendor dashboard.
Decision checklist
- Is there a written threat model listing who you defend against and who you do not?
- Can you state, as a testable sentence, what never leaves the device?
- Is user data encrypted at rest with authenticated encryption, with record identifiers bound as associated data?
- Is the key either passphrase-derived or non-extractable and device-bound, and is the lock action real?
- Does the CSP restrict
connect-srcto origins you can name, and does CI fail when a new origin appears? - Does every third-party script, font, crash reporter and update check have a documented reason, or has it been removed?
- Does speech recognition run on the device, and have you verified that rather than assumed it?
- Is any remote mode opt-in, minimized, visible and honest about what it sends?
- Can the user export everything and delete everything, and does deletion reach caches and workers?
- Have you written down what happens when the user forgets the secret or clears site data?
Common mistakes
- Encrypting with a key stored in plain localStorage next to the ciphertext. That is obfuscation.
- Reusing an IV, or deriving it from the record counter in a way that can repeat after an import.
- Assuming the browser's speech API is on-device.
- Putting user text into URLs, query strings or analytics event names, which are logged by intermediaries.
- Logging decrypted content to the console in development and shipping the logging.
- Calling the product "end-to-end encrypted" when there is no server-side peer and no sync. The accurate term is "encrypted at rest on your device".
FAQ
Does this make the app GDPR-proof? No. Processing that happens entirely on a user's own device often falls outside what you control as a service, but any remote path, account system or support tooling is still processing. Treat regulation as a separate review.
Can I still improve the product without telemetry? Yes, with consent-based, user-reviewable reports, opt-in feedback attached to a specific action, and local-only usage counters the user can export if they choose. The key is that the user sees and approves the payload.
What if users want sync? Offer encrypted sync as a separate, clearly described feature, and design key exchange first. Do not retrofit it by uploading plaintext "just for sync".
What to do Monday
- List every origin your production build contacts, and every script and font it loads. Delete what you cannot justify.
- Ship a restrictive CSP in report-only mode, read the reports for a week, then enforce it.
- Add the origin-allowlist test to CI.
- Move any sensitive record from localStorage into encrypted IndexedDB, with a migration that deletes the old copy.
- Add lock, export and delete-everything to the settings page, and test each on a clean profile.