// Optional "View full email" links. // // Chat delivery is lossy by design: bodies are truncated to fit a message, // and an image-only email has nothing readable to show at all. A webview // link trades that for keeping the body somewhere for a week, which is a // real privacy cost -- so it is opt-in per owner, and nothing is stored for // anyone who has not turned it on. // // What makes the cost bearable is that the Worker cannot read what it // stores. Each message is sealed with a fresh AES-GCM key that exists only // in the link's URL fragment, which browsers never put in a request. The // row in D1 is the ciphertext and its IV; the key is in the chat message, // which already contained the whole email anyway. Reading a stolen database // gives you nothing, and neither does reading the Worker's own logs. // Long enough to be useful (a verification link still works days later), // short enough that a leaked chat history isn't a permanent archive. export const WEBVIEW_RETENTION_SECONDS = 7 * 24 * 60 * 60; // The id is the only thing authenticating a fetch of the ciphertext, so it // gets the same treatment as an address: crypto-random, not guessable. 16 // bytes is 128 bits of id on top of the 256-bit key an attacker would still // need afterward. const ID_BYTES = 16; const IV_BYTES = 12; // Bodies past this are not stored at all, and the chat message says so // rather than linking to a page that would fail. Keeps one enormous email // from eating a user's D1 row budget for a week. export const MAX_WEBVIEW_BYTES = 512 * 1024; // What a webview page shows. Attachments are deliberately absent: they are // already delivered to chat, and storing them would multiply both the size // cap and the retention cost for no gain. export interface WebviewPayload { from: string; to: string; subject: string; text: string; html?: string; } export interface SealedWebview { id: string; iv: string; ciphertext: string; // Goes in the link's fragment, never in the database. key: string; } function toBase64Url(bytes: Uint8Array): string { let binary = ""; for (const byte of bytes) { binary += String.fromCharCode(byte); } return btoa(binary).replaceAll("+", "-").replaceAll("/", "_").replace(/=+$/, ""); } function fromBase64Url(value: string): Uint8Array { const binary = atob(value.replaceAll("-", "+").replaceAll("_", "/")); const bytes = new Uint8Array(binary.length); for (let i = 0; i < binary.length; i++) { bytes[i] = binary.charCodeAt(i); } return bytes; } function randomBase64Url(length: number): string { const bytes = new Uint8Array(length); crypto.getRandomValues(bytes); return toBase64Url(bytes); } export async function sealWebviewPayload(payload: WebviewPayload): Promise { const plaintext = new TextEncoder().encode(JSON.stringify(payload)); // Cast because generateKey's return type covers key pairs too; AES-GCM // only ever yields a single CryptoKey. const key = (await crypto.subtle.generateKey({ name: "AES-GCM", length: 256 }, true, [ "encrypt", "decrypt", ])) as CryptoKey; const iv = new Uint8Array(IV_BYTES); crypto.getRandomValues(iv); const sealed = await crypto.subtle.encrypt({ name: "AES-GCM", iv }, key, plaintext); const rawKey = new Uint8Array((await crypto.subtle.exportKey("raw", key)) as ArrayBuffer); return { id: randomBase64Url(ID_BYTES), iv: toBase64Url(iv), ciphertext: toBase64Url(new Uint8Array(sealed)), key: toBase64Url(rawKey), }; } // Only ever runs in a browser, from the inline script in webview-page.ts. // Exported here so the tests can prove a sealed payload actually round-trips // rather than trusting the page's copy of the same six calls. export async function openWebviewPayload( keyValue: string, iv: string, ciphertext: string ): Promise { const key = await crypto.subtle.importKey("raw", fromBase64Url(keyValue) as BufferSource, "AES-GCM", false, [ "decrypt", ]); const opened = await crypto.subtle.decrypt( { name: "AES-GCM", iv: fromBase64Url(iv) as BufferSource }, key, fromBase64Url(ciphertext) as BufferSource ); return JSON.parse(new TextDecoder().decode(opened)) as WebviewPayload; } // The fragment is what keeps the key out of the Worker: browsers don't send // it, so it appears in no request line, no log and no referrer. export function webviewLink(baseUrl: string, sealed: SealedWebview): string { return `${baseUrl.replace(/\/+$/, "")}/v/${sealed.id}#${sealed.key}`; } // Ids come back from a URL path, so they're checked against the alphabet // toBase64Url produces before they reach a query. export function isWebviewId(value: string): boolean { return /^[A-Za-z0-9_-]{22}$/.test(value); }