// Paid access levels + billing (subscriptions.go). The tier list load/render, // the per-tier key unwrap, and the member subscription calls (subscribe / // cancel / resume / change / portal — each returns {url} to redirect, true for // a plain ok, or null on failure). Extracted verbatim from shell.js; the 8 // verbs newchat/groupactions reach through the seam stay registered there. import { verbs } from "/static/shellverbs.js"; import { session, roster, myUserId, tiers, tierKeys, tierKeyB64, setTiers } from "/static/shellstate.js"; import { wrapThreadKey, unwrapThreadKey, importKey, generateKey } from "/static/crypto.js"; // Fetch the access levels and unwrap our tier keys (each an instance-key-style // wrapped blob). A level we belong to but hold no key for yet gets a targeted // nudge — the server prods current holders, one of whom wraps it to us. export async function loadTiers() { let rows; try { rows = (await (await fetch(`/api/tiers?token=${encodeURIComponent(session.token)}`)).json()).tiers || []; } catch { return; // offline — the next boot or WS prod retries } verbs.cacheTiersRaw(rows); // shell owns the boot-store cache await applyTiers(rows, true); } // The apply half of loadTiers. `live` gates the nudge/grant side-effects — // a cached-snapshot hydrate only unwraps keys; the real fetch that follows // does the network housekeeping. export async function applyTiers(rows, live) { setTiers(rows); for (const t of tiers) { if (!tierKeys[t.id] && t.wrapped) { try { const b64 = await unwrapThreadKey(t.wrapped, session.userPriv); tierKeys[t.id] = await importKey(b64); tierKeyB64[t.id] = b64; } catch (e) { console.error("unwrap tier", t.id, e); } } if (!live) continue; if (t.mine && !t.wrapped && (t.have || []).length) { fetch(`/api/tiers/${encodeURIComponent(t.id)}/nudge`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ token: session.token }), }).catch(() => {}); } // Holder-side self-healing (grantInstanceKeyTo's rule, per level): wrap // our copy to any member still missing theirs — no nudge needed, so key // delivery survives the one-shot prod being missed. if (tierKeyB64[t.id]) { const have = new Set(t.have || []); const grants = []; for (const uid of (t.members || []).filter((u) => !have.has(u))) { const e = roster.find((x) => x.user_id === uid && x.public_key); if (e) grants.push({ user_id: uid, wrapped: await wrapThreadKey(tierKeyB64[t.id], e.public_key) }); } if (grants.length) { fetch(`/api/tiers/${encodeURIComponent(t.id)}/keys`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ token: session.token, grants }), }).catch(() => {}); } } } } // Access levels re-sync on focus (throttled): the instance key polls on a // timer; levels get the cheaper version — returning to the tab retries key // delivery both ways (our nudge, our holder backfill). let tiersFocusSyncAt = 0; window.addEventListener("focus", () => { if (!session || Date.now() - tiersFocusSyncAt < 60000) return; tiersFocusSyncAt = Date.now(); loadTiers(); }); // A member's own show/hide for a level (honoured only under the "user" // policy). Used by the self-view in Edit profile; returns true on success. export async function setTierShown(id, show) { try { const r = await fetch(`/api/tiers/${encodeURIComponent(id)}/show`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ token: session.token, show }), }); return r.ok; } catch { return false; } } // Each returns {url} for a redirect, true for a plain ok, or null on failure. async function billingPost(path, body) { try { const r = await fetch(path, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ token: session.token, ...body }), }); if (!r.ok) return null; return await r.json().catch(() => ({})); } catch { return null; } } export const subscribeToLevel = (id) => billingPost(`/api/tiers/${encodeURIComponent(id)}/subscribe`, {}); export const cancelLevelSub = (id) => billingPost(`/api/tiers/${encodeURIComponent(id)}/cancel-subscription`, {}); // Resume un-cancels the EXISTING subscription (clears cancel-at-period-end) — // never a fresh checkout, which would open a second, double-charging sub. export const resumeLevelSub = (id) => billingPost(`/api/tiers/${encodeURIComponent(id)}/resume`, {}); export const changeLevelSub = (fromId, toId) => billingPost(`/api/tiers/${encodeURIComponent(fromId)}/change`, { to_tier: toId }); export const levelPortal = (id) => billingPost(`/api/tiers/${encodeURIComponent(id)}/portal`, {}); // The five const-arrow billing verbs can't join the boot-time assign above // (no hoisting); register them here, once they exist. Object.assign(verbs, { subscribeToLevel, cancelLevelSub, resumeLevelSub, changeLevelSub, levelPortal }); // A calm, dated day like "5 February 2026" from unix seconds. export function billingDate(unixSecs) { if (!unixSecs) return ""; try { return new Date(unixSecs * 1000).toLocaleDateString(undefined, { day: "numeric", month: "long", year: "numeric" }); } catch { return ""; } } // A level's price as "€5 / month" (symbol-lite: uses the currency code when we // don't know the symbol — clearer than guessing). export function levelPrice(t) { if (!t.price_cents) return ""; const amount = (t.price_cents / 100).toFixed(t.price_cents % 100 ? 2 : 0); const sym = { usd: "$", eur: "€", gbp: "£" }[(t.currency || "").toLowerCase()] || (t.currency || "").toUpperCase() + " "; // 'once' is a lifetime purchase — rendered "· once", never "/ once". const per = t.interval === "once" ? "once" : t.interval === "year" ? "year" : "month"; return { text: `${sym}${amount}`, per, once: t.interval === "once" }; } // Make sure every member of a level holds its key, as far as THIS client can: // wrap with our copy if we hold one, or mint if nobody holds one yet (the mint // moment — the server allows it for admins only). A minting admin who isn't a // member of the level DISCARDS the raw key after wrapping: curating a level // must not silently grant the curator read access to what it will gate. export async function ensureTierKeys(id) { await loadTiers(); const level = tiers.find((t) => t.id === id); if (!level) return; const have = new Set(level.have || []); const need = (level.members || []).filter((uid) => !have.has(uid)); if (!need.length) return; let b64 = tierKeyB64[id]; let minting = false; if (!b64) { if (have.size) return; // holders exist — the server's prod asks them instead minting = true; b64 = (await generateKey()).b64; } const grants = []; for (const uid of need) { const e = roster.find((x) => x.user_id === uid && x.public_key); if (e) grants.push({ user_id: uid, wrapped: await wrapThreadKey(b64, e.public_key) }); } if (!grants.length) return; // a key that reached nobody must not be installed const r = await fetch(`/api/tiers/${encodeURIComponent(id)}/keys`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ token: session.token, grants }), }); if (!r.ok) { // Lost a mint race (409), the level's key is gone (410), or auth/server // trouble — NEVER install a key the server rejected: a locally-kept // loser key would gate groups nobody else can open. Reload and let the // holder/nudge machinery take over from the server's truth. await loadTiers(); return; } if (minting && (level.members || []).includes(myUserId)) { tierKeyB64[id] = b64; tierKeys[id] = await importKey(b64); } // minting && not a member → b64 goes out of scope right here, on purpose. }