// Passkey backup enrolment (the messenger side of the cross-origin handoff). // // Passkeys are bound to the HOME origin, so this instance can't run the WebAuthn // ceremony itself — it navigates (same tab) to the home server's /enroll page, // handing over the current session in the URL *fragment* (fragments never reach // any server, same model as invite secrets). /enroll runs the ceremony as a // plain top-level page — Safari blocks WebAuthn in a cross-origin-opened popup — // then redirects back here with a one-time nonce we can verify. No secret ever // returns; only the nonce marker. // // The reverse — RESTORE — brings a signed-out browser back in: it navigates to // /restore with an ephemeral public key, the home server wraps the stored // credentials to it (never plaintext in the return URL), and we unwrap and adopt // the session here. A one-time nonce ties the return to a restore we started. // // A small inline banner in the sidebar nudges un-backed-up users to enrol. It // occupies layout space — never a floating toast (see CLAUDE.md). // Relative specifier (not /static/) so this module resolves both in the browser // — where it loads as /static/backup.js, making ./crypto.js == /static/crypto.js // — and in Node unit tests that import it from web/static/. import { bytesToB64url, b64urlToBytes, generateUserKeypair, unwrapThreadKey } from "./crypto.js"; const SESSION_KEY = "lchat_session"; // where shell.js keeps the signed-in session // localStorage keys. localStorage is already per-origin, so "enrolled" naturally // means "this instance is backed up" without us keying by origin ourselves. const ENROLLED_KEY = "lchat_home_enrolled"; // "1" once the home server confirms const SNOOZE_KEY = "lchat_backup_snooze"; // unix-ms timestamp the snooze expires at const DISMISSED_KEY = "lchat_backup_dismissed"; // "1" = opted out for good const PENDING_KEY = "lchat_home_enrol_pending"; // nonce for the in-flight enrolment const RETURN_MARK = "lchat_backup"; // return fragment key: #lchat_backup= const RESTORE_PENDING_KEY = "lchat_home_restore_pending"; // {nonce, ephPriv} in flight const RESTORE_MARK = "lchat_restore"; // return fragment key: #lchat_restore= const SNOOZE_MS = 7 * 24 * 60 * 60 * 1000; // "remind me later" = ~7 days // The escalating reminder schedule after someone SKIPS the key backup in the // setup conversation: quiet for a day, then a nudge, again at three days, and a // final one at a week — after which the classic snooze/opt-out cycle takes // over. Eleven already delivered the double-prompt in chat, so the banner // doesn't pile on immediately. export const REMIND_RUNGS_MS = [24, 72, 168].map((h) => h * 60 * 60 * 1000); const DEFERRED_KEY = "lchat_backup_deferred_at"; // unix-ms the setup skip happened const STAGE_KEY = "lchat_backup_remind_stage"; // reminders dismissed so far (0..) // backupBannerState is the PURE visibility rule (no DOM, no storage), so it's // unit-testable. Enrolment and a permanent dismissal hide it forever; an active // deferral schedule (a setup-time skip) hides it until its next rung is due; a // live snooze hides it until it expires; otherwise we nudge. export function backupBannerState({ enrolled, dismissed, snoozedUntil, deferredAt, remindStage, now }) { if (enrolled) return "hidden"; if (dismissed) return "hidden"; if (deferredAt && (remindStage || 0) < REMIND_RUNGS_MS.length) { return now < deferredAt + REMIND_RUNGS_MS[remindStage || 0] ? "hidden" : "show"; } if (snoozedUntil && now < snoozedUntil) return "hidden"; return "show"; } // deferBackupNudges starts the reminder schedule: called when the setup // conversation's key step is skipped, so the banner stays quiet for the first // day instead of contradicting the conversation that just happened. export function deferBackupNudges() { localStorage.setItem(DEFERRED_KEY, String(Date.now())); localStorage.setItem(STAGE_KEY, "0"); } function deferredAt() { const n = parseInt(localStorage.getItem(DEFERRED_KEY) || "", 10); return Number.isFinite(n) ? n : 0; } function remindStage() { const n = parseInt(localStorage.getItem(STAGE_KEY) || "", 10); return Number.isFinite(n) ? n : 0; } // isEnrolled reads the local record set once the home server confirms a backup. export function isEnrolled() { return localStorage.getItem(ENROLLED_KEY) === "1"; } function isDismissed() { return localStorage.getItem(DISMISSED_KEY) === "1"; } // Snooze expiry as unix-ms (0 when unset / unparseable → treated as not snoozed). function snoozedUntil() { const n = parseInt(localStorage.getItem(SNOOZE_KEY) || "", 10); return Number.isFinite(n) ? n : 0; } // The group name rides along for the home server's confirmation UI. shell.js puts // the (substituted) group name in the page title; fall back to the host. function groupName() { const t = (document.title || "").trim(); return t || location.host; } // The instance branding photo as a small data: URI, prefetched when the backup // banner renders so launchEnrol can hand it to the home server *synchronously* // (awaiting a fetch inside launchEnrol would risk the click gesture the native // window.open relies on). Stays null when this instance has no photo set. let serverIconDataURI = null; async function prefetchServerIcon() { if (serverIconDataURI) return; try { const g = await (await fetch("/api/group")).json(); if (!g.avatar) return; const blob = await (await fetch("/api/server-avatar")).blob(); serverIconDataURI = await shrinkToDataURI(blob, 96); } catch {} } // Shrink an image blob to a small JPEG data: URI for the handoff fragment (kept // tiny so the URL stays short — it's display-only chrome). Returns null on any // failure, so the icon is simply omitted. async function shrinkToDataURI(blob, maxDim) { try { const bitmap = await createImageBitmap(blob); const scale = Math.min(1, maxDim / Math.max(bitmap.width, bitmap.height)); const w = Math.round(bitmap.width * scale); const h = Math.round(bitmap.height * scale); const canvas = document.createElement("canvas"); canvas.width = w; canvas.height = h; canvas.getContext("2d").drawImage(bitmap, 0, 0, w, h); return canvas.toDataURL("image/jpeg", 0.8); } catch { return null; } } function bannerEl() { return document.getElementById("backup-banner"); } function removeBanner() { const el = bannerEl(); if (!el) return; el.textContent = ""; el.classList.add("hidden"); } // initBackupBanner renders the inline nudge into #backup-banner when the state // rule says to show it. opts.now lets a caller pin "now" (defaults to real time). export function initBackupBanner(session, opts = {}) { if (!session || !session.token) return; // nothing to back up // If we've just returned from the home server's /enroll page, record the // backup (and scrub the marker) before deciding whether to nudge. checkEnrolReturn(); // An enrolment that's still pending (the redirect never reached us — see // startEnrolPoll) may have finished in another browsing context: ask the // home server. Runs before the suppress bail so a mid-conversation reload // still picks the completion up. startEnrolPoll(); // While the setup conversation is running, backup messaging is Eleven's job — // one voice, not a sidebar banner competing with the in-chat key ceremony. if (opts.suppress) return; const el = bannerEl(); if (!el) return; const state = backupBannerState({ enrolled: isEnrolled(), dismissed: isDismissed(), snoozedUntil: snoozedUntil(), deferredAt: deferredAt(), remindStage: remindStage(), now: opts.now ?? Date.now(), }); if (state !== "show") return; // leaves it .hidden renderBanner(el, session); } function renderBanner(el, session) { el.textContent = ""; prefetchServerIcon(); // ready the branding photo before the user taps "Sign in" const title = document.createElement("div"); title.className = "backup-banner-title"; title.textContent = "Keep your access safe"; const body = document.createElement("div"); body.className = "backup-banner-body"; body.textContent = "Sign in with Eleven and you can get back to your chats anytime, on any device — one tap, nothing to remember."; const cta = document.createElement("button"); cta.className = "backup-banner-cta"; cta.textContent = "Sign in"; cta.addEventListener("click", () => launchEnrol(session)); // Dismissal. On the deferral schedule's early rungs (24h / 72h), "later" just // advances to the next rung. The final rung — and the no-schedule case — keeps // the double-dismiss: first click snoozes for a week and escalates the label // to spell out the consequence; a second click on the escalated control opts // out for good. "I never want this" stays a deliberate, informed choice. const dismiss = document.createElement("button"); dismiss.className = "backup-banner-dismiss linkish"; dismiss.textContent = "Remind me later"; let escalated = false; dismiss.addEventListener("click", () => { const stage = remindStage(); if (deferredAt() && stage < REMIND_RUNGS_MS.length - 1) { // Re-anchor the schedule at THIS dismissal: the rungs are minimum gaps // from the last time the user waved it away, not absolute deadlines — or // a user who first sees the banner days late would dismiss it only to // have an already-elapsed rung bring it straight back. localStorage.setItem(DEFERRED_KEY, String(Date.now())); localStorage.setItem(STAGE_KEY, String(stage + 1)); removeBanner(); return; } if (!escalated) { localStorage.setItem(SNOOZE_KEY, String(Date.now() + SNOOZE_MS)); // Leaving the final rung: the classic snooze cycle owns it from here. if (deferredAt()) localStorage.setItem(STAGE_KEY, String(REMIND_RUNGS_MS.length)); dismiss.textContent = "I understand — I can lose access to this chat"; dismiss.classList.add("danger"); escalated = true; } else { localStorage.setItem(DISMISSED_KEY, "1"); removeBanner(); } }); el.append(title, body, cta, dismiss); el.classList.remove("hidden"); } // launchEnrol hands off to the home server's /enroll page via a SAME-TAB // navigation, with the session in the URL fragment (never sent to a server). // // Why same-tab and not a popup: Safari blocks WebAuthn in a window opened by a // cross-origin page (the popup's create() aborts with NotAllowedError the // instant it opens). A same-tab navigation makes /enroll a plain top-level page // — the context where the ceremony works — and the home server redirects back // here on success. A one-time nonce (stored locally, echoed in the return // fragment) makes that return signal unforgeable: another site can't send you // back with a fake success marker to suppress the backup reminder. export function launchEnrol(session, opts = {}) { const home = window.__homeOrigin; if (!home) return; const native = isNativeWrapper(); // "Stay" contexts keep THIS page alive and run the ceremony elsewhere: the // native wrapper opens the system browser, and an iOS home-screen app opens // cross-origin links in an in-app overlay whose storage we don't share — a // redirect back would land in the wrong context (and, in the overlay, boot // the whole app inside it). In stay mode /enroll ends on a "done" screen // instead of redirecting, and completion reaches us via startEnrolPoll. const stay = native || isStandalonePWA(); const nonce = randomNonce(); localStorage.setItem(PENDING_KEY, nonce); const payload = { v: 1, nonce, // echoed back in the return fragment to prove the redirect is genuine ret: location.origin, // where /enroll sends the user back to (web only) native: stay, // stay mode: /enroll ends on a "done" screen, no redirect back // auto: a post-claim handoff from the signup-first join — /enroll tries its // live-session fast path without a tap (and only that; see enroll.js). auto: !!opts.auto, entry: { url: location.origin, // the instance being enrolled name: groupName(), // best-effort, for the confirmation UI // Small data: URI of the instance photo for the confirmation card. Omitted // when unset/not-yet-prefetched (JSON.stringify drops undefined). Display // only — enroll.js strips it before persisting the backup blob. icon: serverIconDataURI || undefined, credentials: { token: session.token, userPub: session.userPub, userPriv: session.userPriv, name: session.name, }, }, }; const encoded = bytesToB64url(new TextEncoder().encode(JSON.stringify(payload))); const url = `${home}/enroll#${encoded}`; // payload rides in the #fragment — never sent to a server if (stay) { // Native wrapper: the ceremony can't run in the WKWebView, and navigating // the instance's own webview cross-origin trips the app's join fallback — // the app routes window.open to the system browser, where passkeys work. // Standalone PWA: window.open keeps the app page alive under the overlay. // Either way this page survives, so the poller below picks up completion // and flips the flag the conversation flows are settling on. The native // snooze stays as a belt-and-braces fallback should the poll miss. if (native) localStorage.setItem(SNOOZE_KEY, String(Date.now() + SNOOZE_MS)); window.open(url, "_blank"); startEnrolPoll(); } else { location.assign(url); // same-tab redirect: Safari blocks WebAuthn in a popup } } function isNativeWrapper() { return document.documentElement.classList.contains("native"); } // Standalone (installed / home-screen) PWA display context — where cross-origin // navigations open an in-app browser overlay instead of leaving the page. function isStandalonePWA() { try { return (window.matchMedia && window.matchMedia("(display-mode: standalone)").matches) || window.navigator.standalone === true; } catch { return false; } } // ---- enrolment completion poll ------------------------------------------------ // The success redirect can land in a DIFFERENT browsing context than the page // that launched the enrolment: iOS home-screen apps open cross-origin links in // an in-app overlay with its own storage, and the native wrapper hands off to // the system browser. So the redirect's nonce marker (checkEnrolReturn) can't be // the only completion signal. While an enrolment is pending, ask the home // server's completion oracle — keyed by the same client-random nonce — and flip // the local flag the moment it confirms; the conversation flows' settle polls // (and the banner rules) advance from there on their own. An old home server // without the oracle 404s — we stop quietly and behave exactly as before. let enrolPollActive = false; export function startEnrolPoll() { const home = window.__homeOrigin; if (enrolPollActive || !home || isEnrolled() || !localStorage.getItem(PENDING_KEY)) return; enrolPollActive = true; const deadline = Date.now() + 10 * 60 * 1000; // long enough for a slow ceremony, not forever let timer = null; let misses = 0; // consecutive 404s → the home server has no oracle const stop = () => { enrolPollActive = false; clearTimeout(timer); document.removeEventListener("visibilitychange", kick); }; const schedule = () => { timer = setTimeout(tick, 3000); }; // A hidden tab pauses the loop; coming back (tabbing back from the ceremony) // checks immediately — that's the moment completion is most likely. const kick = () => { if (!document.hidden) { clearTimeout(timer); tick(); } }; const tick = async () => { if (!enrolPollActive) return; const nonce = localStorage.getItem(PENDING_KEY); if (!nonce || isEnrolled() || Date.now() > deadline) return stop(); if (document.hidden) return; // resumes via the visibilitychange kick try { const r = await fetch(`${home}/api/enroll-status?nonce=${encodeURIComponent(nonce)}`); if (r.status === 404) { if (++misses >= 3) return stop(); } else if (r.ok) { misses = 0; if ((await r.json()).done) { localStorage.setItem(ENROLLED_KEY, "1"); localStorage.removeItem(PENDING_KEY); removeBanner(); return stop(); } } } catch {} schedule(); }; document.addEventListener("visibilitychange", kick); schedule(); } function randomNonce() { const b = new Uint8Array(16); crypto.getRandomValues(b); return bytesToB64url(b); } // parseReturnNonce pulls our nonce out of a return fragment like // "#lchat_backup=" (pure, so it's unit-testable). Returns "" if absent. export function parseReturnNonce(hash) { const m = new RegExp("(?:^#|[#&])" + RETURN_MARK + "=([^&]+)").exec(hash || ""); return m ? decodeURIComponent(m[1]) : ""; } // checkEnrolReturn runs on load: if we've come back from /enroll with a nonce // that matches the one we stored before leaving, record enrolment and scrub the // marker from the URL. A mismatched/forged marker is ignored (but still scrubbed). export function checkEnrolReturn() { const got = parseReturnNonce(location.hash); if (!got) return false; const pending = localStorage.getItem(PENDING_KEY); const ok = !!pending && got === pending; if (ok) { localStorage.setItem(ENROLLED_KEY, "1"); localStorage.removeItem(PENDING_KEY); } // Drop the marker fragment either way (the return URL carries only our marker). try { history.replaceState(null, "", location.pathname + location.search); } catch {} return ok; } // ---- restore (get back in on a fresh browser) -------------------------------- // autoRestoreRequested recognises links from home's unlocked space list. Keep // this exact-value check in sync with the tiny pre-paint gate in index.html. export function autoRestoreRequested(search) { return new URLSearchParams(search || "").get("restore") === "1"; } // canRestore: offer restore only when a home server is configured and we're in a // real browser. In the native wrapper the passkey ceremony can't run in the // webview (native restore is a separate, later flow), so we don't offer it there. export function canRestore() { return !!window.__homeOrigin && !isNativeWrapper(); } // launchRestore navigates (same tab) to the home server's /restore page. We send // our origin (which instance to restore), a one-time nonce, and a freshly // generated ephemeral ECDH public key. The home server wraps our credentials to // that key so they never travel back in the clear; the private half stays here, // stashed across the navigation so we can unwrap on return. export async function launchRestore() { const home = window.__homeOrigin; if (!home) return; const nonce = randomNonce(); const eph = await generateUserKeypair(); // sessionStorage, not localStorage: the ephemeral PRIVATE key is tab-scoped and // an abandoned restore (tab closed mid-ceremony) is auto-cleared. It survives // the same-tab navigation to /restore and back. sessionStorage.setItem(RESTORE_PENDING_KEY, JSON.stringify({ nonce, ephPriv: eph.privateKey })); const payload = { v: 1, ret: location.origin, nonce, ephPub: eph.publicKey }; const encoded = bytesToB64url(new TextEncoder().encode(JSON.stringify(payload))); location.assign(`${home}/restore#${encoded}`); } // parseRestoreReturn pulls { nonce, wrapped } out of a "#lchat_restore=" // return fragment (pure, unit-testable). Returns null if absent or malformed. export function parseRestoreReturn(hash) { const m = new RegExp("(?:^#|[#&])" + RESTORE_MARK + "=([^&]+)").exec(hash || ""); if (!m) return null; try { const obj = JSON.parse(new TextDecoder().decode(b64urlToBytes(decodeURIComponent(m[1])))); if (!obj || typeof obj.nonce !== "string" || typeof obj.wrapped !== "string") return null; return obj; } catch { return null; } } // checkRestoreReturn runs on load BEFORE routing: if we've come back from // /restore, verify the nonce (so a foreign page can't inject a session), unwrap // the credentials with our ephemeral private key, and write the session. Returns // the restored session object, or null. Always scrubs the marker. export async function checkRestoreReturn() { // Clean up unconditionally on every exit: scrub the marker from the URL and // drop the ephemeral private key (it's single-use, useless without the // matching ciphertext, and must not linger on a failed/forged return). const scrub = () => { try { history.replaceState(null, "", location.pathname + location.search); } catch {} }; const done = () => { scrub(); sessionStorage.removeItem(RESTORE_PENDING_KEY); }; const ret = parseRestoreReturn(location.hash); if (!ret) { done(); return null; } let pending; try { pending = JSON.parse(sessionStorage.getItem(RESTORE_PENDING_KEY) || "null"); } catch { pending = null; } if (!pending || !pending.ephPriv || ret.nonce !== pending.nonce) { done(); return null; } try { const credsB64 = await unwrapThreadKey(ret.wrapped, pending.ephPriv); const creds = JSON.parse(new TextDecoder().decode(b64urlToBytes(credsB64))); if (!creds || !creds.token || !creds.userPub || !creds.userPriv) return null; const session = { token: creds.token, name: creds.name || "", userPub: creds.userPub, userPriv: creds.userPriv }; localStorage.setItem(SESSION_KEY, JSON.stringify(session)); // This session came straight from the backup, so this browser is already // backed up — don't nag with the "save securely" banner. localStorage.setItem(ENROLLED_KEY, "1"); return session; } catch { return null; } finally { done(); } }