// Browser state: identity, pins, contacts and read markers in localStorage; // sealed envelopes in IndexedDB, opened only on demand, so nothing at rest // is plaintext (the seed excepted — it is the user's browser profile). import { hex, unhex } from "./crypto.js"; import { b32decode, b32encode, identityFromSeed } from "./proto.js"; const KEY = "gsmol"; // Every getter reads the whole blob and some are called per message row, so the // parse is cached. `derived` holds the identities that follow from it, which // cost an Ed25519 scalar multiplication each. let cached = null, derived = null; function load() { if (cached) return cached; try { cached = JSON.parse(localStorage.getItem(KEY) || "{}"); } catch { cached = {}; } return cached; } function save(state) { localStorage.setItem(KEY, JSON.stringify(state)); cached = state; derived = null; } // Another tab writing this key leaves our copy stale. window.addEventListener("storage", (event) => { if (event.key === KEY || event.key === null) cached = derived = null; }); function update(fn) { const state = load(); const next = fn(state); save(next ?? state); } // --- identity ---------------------------------------------------------------- export function seed() { const raw = load().seed; return raw ? unhex(raw) : null; } export function identity() { return identities()[0] ?? null; } export function setIdentity(newSeed) { if (seed()) throw new Error("an identity already exists; rotate it instead"); update(state => { state.seed = hex(newSeed); }); } // Rotation (§7): the old seed is retained, since mail sealed to a superseded // key is readable with nothing else. export function rotateIdentity(newSeed) { const old = seed(); if (!old) throw new Error("no identity to rotate"); update(state => { state.retired = [...(state.retired || []), { seed: hex(old), at: Date.now() }]; state.seed = hex(newSeed); }); } // §7: seeds rotated away from are retained, since mail sealed to a superseded // key is readable with nothing else. export function identities() { if (derived) return derived; const raw = seed(); if (!raw) return []; const retired = (load().retired || []).map(({ seed: s }) => identityFromSeed(unhex(s))); derived = [identityFromSeed(raw), ...retired]; return derived; } // --- account and server pins --------------------------------------------------- export function account() { const a = load().account; return a ? { ...a } : null; } export function setAccount(addr) { update(state => { state.account = { user: addr.user, host: addr.host, port: addr.port }; }); } export function serverPin(host) { const raw = (load().servers || {})[host]; return raw ? b32decode(raw) : null; } export function pinServer(host, keyBytes) { update(state => { state.servers = { ...(state.servers || {}), [host]: b32encode(keyBytes) }; }); } export function unpinServer(host) { update(state => { delete (state.servers || {})[host]; }); } export function allPins() { return Object.entries(load().servers || {}).map(([host, key]) => ({ host, key })); } // --- contacts ------------------------------------------------------------------ export function contact(address) { const c = (load().contacts || {})[address]; return c ? { key: b32decode(c.key), verified: c.verified, history: c.history ?? [] } : null; } // A key that displaces another is kept: it is the only local record that the // contact rotated, and §8 turns on the user being able to notice such changes. // Re-saving the same key is not a rotation and must not add an entry. export function saveContact(address, keyBytes, verified) { const key = b32encode(keyBytes); update(state => { const contacts = { ...(state.contacts || {}) }; const previous = contacts[address]; const history = previous && previous.key !== key ? [...(previous.history ?? []), { key: previous.key, until: Date.now() }] : previous?.history ?? []; contacts[address] = { key, verified, seenAt: Date.now(), ...(history.length && { history }) }; state.contacts = contacts; }); } export function addressForKey(keyBytes) { return Object.entries(load().contacts || {}) .find(([, c]) => c.key === b32encode(keyBytes))?.[0] ?? null; } export function allContacts() { return Object.entries(load().contacts || {}) .map(([address, c]) => ({ address, key: c.key, verified: c.verified, history: c.history ?? [] })); } // --- read markers --------------------------------------------------------------- export function markRead(idHex) { update(state => { state.read = { ...(state.read || {}), [idHex]: true }; }); } export function isRead(idHex) { return Boolean((load().read || {})[idHex]); } // --- appearance ------------------------------------------------------------ // "light" or "dark" to pin a side; null to follow the system. export function theme() { return load().theme ?? null; } export function setTheme(value) { update(state => { if (value) state.theme = value; else delete state.theme; }); } // --- sealed mail (IndexedDB) ------------------------------------------------------ const DB_NAME = "gsmol", DB_VERSION = 1; // Held open: reopening per read cost more than the reads themselves. let dbPromise = null; function openDb() { if (dbPromise) return dbPromise; dbPromise = new Promise((resolve, reject) => { const request = indexedDB.open(DB_NAME, DB_VERSION); request.onupgradeneeded = () => { const db = request.result; for (const box of ["inbox", "sent"]) { if (!db.objectStoreNames.contains(box)) db.createObjectStore(box, { keyPath: "id" }); } }; request.onsuccess = () => resolve(request.result); request.onerror = () => reject(request.error); }).catch(error => { dbPromise = null; throw error; }); return dbPromise; } function tx(db, box, mode, fn) { return new Promise((resolve, reject) => { const request = fn(db.transaction(box, mode).objectStore(box)); request.onsuccess = () => resolve(request.result); request.onerror = () => reject(request.error); }); } export async function storeMessage(box, record) { const db = await openDb(); await tx(db, box, "readwrite", store => store.put(record)); } // Returns null when the id already exists, so fetch can leave server state alone. export async function storeIfNew(box, record) { const db = await openDb(); const existing = await tx(db, box, "readonly", store => store.get(record.id)); if (existing) return null; await tx(db, box, "readwrite", store => store.put(record)); return record; } export async function listMessages(box) { const db = await openDb(); const rows = await tx(db, box, "readonly", store => store.getAll()); return rows.sort((a, b) => (b.receivedAt ?? b.sentAt) - (a.receivedAt ?? a.sentAt)); // newest first } export async function getMessage(box, id) { const db = await openDb(); return await tx(db, box, "readonly", store => store.get(id)) ?? null; } // The unread badge must survive leaving the inbox, so it is counted from ids // and read markers alone — no envelope is opened. export async function unreadCount() { const db = await openDb(); const ids = await tx(db, "inbox", "readonly", store => store.getAllKeys()); const read = load().read || {}; return ids.filter(id => !read[id]).length; }