import { ed25519, ristretto255, ristretto255_hasher, x25519 } from "@noble/curves/ed25519.js"; import { sha256, sha512 } from "@noble/hashes/sha2.js"; const ORDER = ristretto255.Point.Fn.ORDER; const ED25519_SPKI_PREFIX = "302a300506032b6570032100"; const STORAGE_KEY = "socialpsi_browser_state_v2"; const enc = new TextEncoder(); const dec = new TextDecoder(); // ---- Hex & Bytes helpers ---- function bytesToHex(bytes) { return Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join(""); } function hexToBytes(hex) { const out = new Uint8Array(hex.length / 2); for (let i = 0; i < out.length; i++) out[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16); return out; } function randBytes(n) { const b = new Uint8Array(n); crypto.getRandomValues(b); return b; } function randScalar() { while (true) { const buf = randBytes(64); let v = 0n; for (let i = buf.length - 1; i >= 0; i--) v = (v << 8n) + BigInt(buf[i]); const s = v % ORDER; if (s > 1n) return s; } } function scalarToHex(s) { return s.toString(16).padStart(64, "0"); } function shuffle(arr) { const a = [...arr]; for (let i = a.length - 1; i > 0; i--) { const j = Math.floor(Math.random() * (i + 1)); [a[i], a[j]] = [a[j], a[i]]; } return a; } function hashToken(token) { return ristretto255_hasher.deriveToCurve(sha512(enc.encode("socialpsi:v1:" + token))); } function randDummyHex() { return ristretto255_hasher.deriveToCurve(randBytes(64)).toHex(); } // ---- Canonical JSON & PoW ---- function canonicalizeJson(value) { if (value === null || typeof value !== "object") return JSON.stringify(value); if (Array.isArray(value)) return "[" + value.map(canonicalizeJson).join(",") + "]"; const keys = Object.keys(value).sort(); const parts = []; for (const k of keys) { if (value[k] !== undefined) parts.push(`${JSON.stringify(k)}:${canonicalizeJson(value[k])}`); } return "{" + parts.join(",") + "}"; } function countLeadingZeroBits(hex) { let bits = 0; for (let i = 0; i < hex.length; i++) { const n = parseInt(hex[i], 16); if (n === 0) bits += 4; else { if (n < 2) bits += 3; else if (n < 4) bits += 2; else if (n < 8) bits += 1; break; } } return bits; } async function createSignedEventBrowser(identity, kind, content, minPowBits, onProgress) { const created_at = Math.floor(Date.now() / 1000); let nonce = 0; let id = ""; while (true) { const serialized = canonicalizeJson([0, identity.ed25519_pubkey, created_at, kind, content, nonce]); id = bytesToHex(sha256(enc.encode(serialized))); if (countLeadingZeroBits(id) >= minPowBits) break; nonce++; if (nonce % 2500 === 0) { if (onProgress) onProgress(nonce); await new Promise((r) => setTimeout(r, 0)); } } const sig = bytesToHex(ed25519.sign(hexToBytes(id), hexToBytes(identity.ed25519_seed))); return { pubkey: identity.ed25519_pubkey, created_at, kind, content, id, nonce, sig }; } function signInboxAuthBrowser(identity) { const ts = Math.floor(Date.now() / 1000); const payload = `socialpsi:inbox-auth:${identity.ed25519_pubkey}:${ts}`; const sig = bytesToHex(ed25519.sign(enc.encode(payload), hexToBytes(identity.ed25519_seed))); return `${identity.ed25519_pubkey}.${ts}.${sig}`; } // ---- X25519 + WebCrypto HKDF-SHA256 + AES-256-GCM ---- async function deriveAesKey(sharedSecretBytes, saltBytes) { const baseKey = await crypto.subtle.importKey("raw", sharedSecretBytes, "HKDF", false, ["deriveKey"]); return crypto.subtle.deriveKey( { name: "HKDF", hash: "SHA-256", salt: saltBytes, info: enc.encode("socialpsi:e2ee:v1") }, baseKey, { name: "AES-GCM", length: 256 }, false, ["encrypt", "decrypt"] ); } async function encryptE2EEBrowser(recipientX25519PubHex, payload) { const ephPriv = randBytes(32); const ephPub = x25519.getPublicKey(ephPriv); const shared = x25519.getSharedSecret(ephPriv, hexToBytes(recipientX25519PubHex)); const aesKey = await deriveAesKey(shared, ephPub); const nonce = randBytes(12); const ctBuf = await crypto.subtle.encrypt({ name: "AES-GCM", iv: nonce }, aesKey, enc.encode(JSON.stringify(payload))); return { version: "x25519-aes256gcm-v1", ephemeral_pubkey: bytesToHex(ephPub), nonce: bytesToHex(nonce), ciphertext: bytesToHex(new Uint8Array(ctBuf)), }; } async function decryptE2EEBrowser(myX25519PrivHex, envelope) { if (!envelope || envelope.version !== "x25519-aes256gcm-v1") throw new Error("Unsupported E2EE version"); const ephPub = hexToBytes(envelope.ephemeral_pubkey); const shared = x25519.getSharedSecret(hexToBytes(myX25519PrivHex), ephPub); const aesKey = await deriveAesKey(shared, ephPub); const ptBuf = await crypto.subtle.decrypt( { name: "AES-GCM", iv: hexToBytes(envelope.nonce) }, aesKey, hexToBytes(envelope.ciphertext) ); return JSON.parse(dec.decode(ptBuf)); } // ---- Client-side Prompt-Injection & URL Sanitizer ---- const UNSAFE_PATTERNS = [ /https?:\/\//i, /\bwww\.[a-z0-9-]+\.[a-z]{2,}/i, /\[[^\]]+\]\([^)]+\)/, /<\/?[a-z][^>]*>/i, /ignore\s+(?:all\s+)?(?:previous|prior|above)\s+(?:instructions|prompts)/i, /\bsystem\s*prompt\b/i, /\.ssh\/id_rsa|process\.env|API_KEY/i, ]; function isSafePlainText(s) { if (!s) return true; if (/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/.test(s)) return false; return !UNSAFE_PATTERNS.some((re) => re.test(s)); } // ---- Geohash 9-cell Halo ---- const BASE32 = "0123456789bcdefghjkmnpqrstuvwxyz"; function encodeGeohash(lat, lng, precision) { let latMin = -90, latMax = 90, lngMin = -180, lngMax = 180, isLng = true, bit = 0, ch = 0, out = ""; while (out.length < precision) { if (isLng) { const mid = (lngMin + lngMax) / 2; if (lng >= mid) { ch = (ch << 1) | 1; lngMin = mid; } else { ch <<= 1; lngMax = mid; } } else { const mid = (latMin + latMax) / 2; if (lat >= mid) { ch = (ch << 1) | 1; latMin = mid; } else { ch <<= 1; latMax = mid; } } isLng = !isLng; if (++bit === 5) { out += BASE32[ch]; bit = 0; ch = 0; } } return out; } function geohashHalo(lat, lng, precision) { const center = encodeGeohash(lat, lng, precision); let latMin = -90, latMax = 90, lngMin = -180, lngMax = 180, isLng = true; for (const c of center) { const idx = BASE32.indexOf(c); for (let m = 16; m > 0; m >>= 1) { if (isLng) { const mid = (lngMin + lngMax) / 2; if (idx & m) lngMin = mid; else lngMax = mid; } else { const mid = (latMin + latMax) / 2; if (idx & m) latMin = mid; else latMax = mid; } isLng = !isLng; } } const dLat = latMax - latMin, dLng = lngMax - lngMin; const cLat = (latMin + latMax) / 2, cLng = (lngMin + lngMax) / 2; const cells = new Set([center]); for (const dy of [-1, 0, 1]) { for (const dx of [-1, 0, 1]) { if (!dx && !dy) continue; let nl = Math.max(-89.9999, Math.min(89.9999, cLat + dy * dLat)); let ng = cLng + dx * dLng; if (ng > 180) ng -= 360; else if (ng < -180) ng += 360; cells.add(encodeGeohash(nl, ng, precision)); } } return Array.from(cells).sort(); } // ---- Local Browser State ---- function generateIdentity() { const edSeed = randBytes(32); const edPubRaw = ed25519.getPublicKey(edSeed); const edSpki = ED25519_SPKI_PREFIX + bytesToHex(edPubRaw); const xPriv = randBytes(32); const xPub = x25519.getPublicKey(xPriv); const shortId = "psid_" + bytesToHex(sha256(enc.encode(edSpki))).slice(0, 12); return { ed25519_seed: bytesToHex(edSeed), ed25519_pubkey: edSpki, x25519_privkey: bytesToHex(xPriv), x25519_pubkey: bytesToHex(xPub), short_id: shortId, created_at: Math.floor(Date.now() / 1000), }; } function loadState() { try { const raw = localStorage.getItem(STORAGE_KEY); if (raw) return JSON.parse(raw); } catch {} const fresh = { identity: generateIdentity(), selections: {}, // phrase_id -> 'top' | 'core' | 'enjoy' region_band: "us-northeast", intents: ["friendship", "intellectual-sparring"], lat: "", lng: "", quest_phrase_id: "", quest_locality: "neighborhood", psi_secret: null, known_peer_x25519: {}, evaluated_ids: [], matches: [], }; saveState(fresh); return fresh; } function saveState(st) { localStorage.setItem(STORAGE_KEY, JSON.stringify(st)); } // ---- App State & UI Wiring ---- let relayInfo = null; let taxonomy = null; let phraseMap = new Map(); let state = loadState(); function escapeHtml(str) { return String(str || "").replace(/[&<>"']/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" }[c])); } function setStatus(msg, cls = "muted") { const el = document.getElementById("live-status"); el.className = "result-box " + cls; el.innerHTML = msg; } function getSelectedBuckets() { const top = [], core = [], enjoy = []; for (const [id, tier] of Object.entries(state.selections)) { if (!phraseMap.has(id)) continue; if (tier === "top") { top.push(id); core.push(id); } else if (tier === "core") core.push(id); else if (tier === "enjoy") enjoy.push(id); } return { top, core, enjoy }; } function renderLivePicker(filterText = "") { const container = document.getElementById("live-picker"); const q = filterText.trim().toLowerCase(); const { top, core, enjoy } = getSelectedBuckets(); document.getElementById("selection-counts").textContent = `Top-5: ${top.length}/5 · Core: ${core.length}/12 · Enjoy: ${enjoy.length}/20`; container.innerHTML = ""; for (const cat of taxonomy.categories) { const phrases = taxonomy.phrases.filter((p) => { if (p.category !== cat.id) return false; if (!q) return true; return ( p.label.toLowerCase().includes(q) || p.id.toLowerCase().includes(q) || cat.label.toLowerCase().includes(q) || (p.aliases || []).some((a) => a.toLowerCase().includes(q)) ); }); if (!phrases.length) continue; const hdr = document.createElement("div"); hdr.className = "cat-hdr"; hdr.textContent = cat.label; container.appendChild(hdr); for (const p of phrases) { const row = document.createElement("div"); row.className = "phrase-row"; const cur = state.selections[p.id] || ""; row.innerHTML = ` ${escapeHtml(p.label)} w${p.specificity} `; row.querySelectorAll("button.pill").forEach((btn) => { btn.addEventListener("click", () => { const targetTier = btn.getAttribute("data-tier"); const current = state.selections[p.id]; const b = getSelectedBuckets(); if (current === targetTier) { delete state.selections[p.id]; } else { if (targetTier === "top" && b.top.length >= 5) return alert("Max 5 Top-Ranked interests."); if ((targetTier === "top" || targetTier === "core") && current !== "top" && current !== "core" && b.core.length >= 12) { return alert("Max 12 Core interests (including Top-5)."); } if (targetTier === "enjoy" && b.enjoy.length >= 20) return alert("Max 20 Enjoy interests."); state.selections[p.id] = targetTier; } saveState(state); renderLivePicker(document.getElementById("interest-search").value); }); }); container.appendChild(row); } } } function renderQuestOptions() { const sel = document.getElementById("quest-phrase"); sel.innerHTML = ``; for (const p of taxonomy.phrases.filter((x) => x.specificity === 3)) { const opt = document.createElement("option"); opt.value = p.id; opt.textContent = `${p.label} (${p.id})`; if (state.quest_phrase_id === p.id) opt.selected = true; sel.appendChild(opt); } } async function publishAndChallenge() { if (!document.getElementById("age-confirm").checked) { setStatus("Please confirm you are 18+ and accept the platonic/intellectual/hobby rules first.", "warn"); return; } const { top, core, enjoy } = getSelectedBuckets(); const allIds = [...core, ...enjoy]; if (allIds.length < 3) { setStatus("Pick at least 3 interests (Top / Core / Enjoy) before publishing.", "warn"); return; } const region = document.getElementById("region-select").value; const intents = Array.from(document.querySelectorAll("input[name='intent-cb']:checked")).map((c) => c.value); if (!intents.length || intents.length > 4) { setStatus("Select between 1 and 4 connection intents.", "warn"); return; } const latVal = document.getElementById("lat-input").value.trim(); const lngVal = document.getElementById("lng-input").value.trim(); let geoTokens = []; if (latVal !== "" && lngVal !== "") { const lat = Number(latVal), lng = Number(lngVal); if (!Number.isFinite(lat) || !Number.isFinite(lng) || lat < -90 || lat > 90 || lng < -180 || lng > 180) { setStatus("Invalid latitude/longitude coordinates.", "warn"); return; } const g5 = geohashHalo(lat, lng, 5).slice(0, 9).map((c) => ({ type: "geo5", id: c })); const g6 = geohashHalo(lat, lng, 6).slice(0, 9).map((c) => ({ type: "geo6", id: c })); geoTokens = [...g5, ...g6]; } const questPhrase = document.getElementById("quest-phrase").value; const questLoc = document.getElementById("quest-locality").value; const grailQuests = []; if (questPhrase) { if (!geoTokens.length) { setStatus("A single-interest Grail Quest requires optional Blind Locality coordinates (lat/lng) to prevent probing.", "warn"); return; } if (!allIds.includes(questPhrase)) { setStatus("Select your Grail Quest interest in your Top/Core/Enjoy list first.", "warn"); return; } grailQuests.push({ name: `Local ${phraseMap.get(questPhrase)?.label || questPhrase}`, require_all_phrase_ids: [questPhrase], require_top_tier: top.includes(questPhrase), require_locality: questLoc, }); } state.region_band = region; state.intents = intents; state.lat = latVal; state.lng = lngVal; state.quest_phrase_id = questPhrase; state.quest_locality = questLoc; setStatus("Step 1/3: Blinding interests locally with Ristretto255 (90 padded curve points)..."); const a = randScalar(); const buildBucket = (entries, padSize) => { const arr = entries.map((e) => ({ pt: hashToken(e.tok).multiply(a).toHex(), meta: e.meta })); while (arr.length < padSize) arr.push({ pt: randDummyHex(), meta: { token_type: "dummy" } }); const sh = shuffle(arr); return { points: sh.map((x) => x.pt), slots: sh.map((x) => x.meta) }; }; const topB = buildBucket(top.map((id) => ({ tok: `top:${id}`, meta: { token_type: "top", id, ...phraseMap.get(id) } })), 8); const coreB = buildBucket(core.map((id) => ({ tok: `core:${id}`, meta: { token_type: "core", id, ...phraseMap.get(id) } })), 16); const subcats = Array.from(new Set(allIds.map((id) => phraseMap.get(id).subcategory))); const anyRaw = [ ...allIds.map((id) => ({ tok: `any:${id}`, meta: { token_type: "any", id, ...phraseMap.get(id) } })), ...subcats.slice(0, Math.max(0, 48 - allIds.length)).map((s) => ({ tok: `sub:${s}`, meta: { token_type: "sub", id: s, category: s.split(":")[0], specificity: 1 }, })), ]; const anyB = buildBucket(anyRaw, 48); const geoB = buildBucket(geoTokens.map((g) => ({ tok: `${g.type}:${g.id}`, meta: { token_type: g.type, id: g.id } })), 18); const commitment = { version: "ristretto255-psi-v2", top_points: topB.points, core_points: coreB.points, any_points: anyB.points, geo_points: geoB.points, }; const info = await (await fetch("/api/v1/info")).json(); const profilePow = info.pow_bits?.profile ?? 18; const chalPow = info.pow_bits?.challenge ?? 16; setStatus(`Step 2/3: Mining ${profilePow}-bit SHA-256 Proof-of-Work locally in browser (~1-4s)...`); const regEv = await createSignedEventBrowser( state.identity, "profile_register", { x25519_pubkey: state.identity.x25519_pubkey, age_attestation: "18+", taxonomy_version: taxonomy.version, region_band: region, intents, commitment, }, profilePow, (n) => setStatus(`Step 2/3: Mining ${profilePow}-bit Proof-of-Work locally (${n.toLocaleString()} hashes)...`) ); const regResp = await ( await fetch("/api/v1/events", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(regEv) }) ).json(); if (!regResp.ok) { setStatus(`Registration rejected: ${escapeHtml(regResp.error)}`, "warn"); return; } state.psi_secret = { scalar_hex: scalarToHex(a), top_slots: topB.slots, core_slots: coreB.slots, any_slots: anyB.slots, geo_slots: geoB.slots, top_ids: top, core_ids: core, enjoy_ids: enjoy, subcats, geo_tokens: geoTokens, grail_quests: grailQuests, }; saveState(state); // Step 3: Challenge active matching-region peers blindly! setStatus("Step 3/3: Scanning active blinded profiles and sending zero-knowledge PSI challenges..."); const peersRes = await (await fetch(`/api/v1/profiles?region_band=${encodeURIComponent(region)}`)).json(); const peers = (peersRes.profiles || []).filter((p) => p.pubkey !== state.identity.ed25519_pubkey).slice(0, 8); let sentCount = 0; let skippedCount = 0; for (const peer of peers) { state.known_peer_x25519[peer.pubkey] = peer.x25519_pubkey; const b = randScalar(); const chalPayload = { version: "ristretto255-psi-v2", target_top_blinded: peer.commitment.top_points.map((h) => ristretto255.Point.fromHex(h).multiply(b).toHex()), target_core_blinded: peer.commitment.core_points.map((h) => ristretto255.Point.fromHex(h).multiply(b).toHex()), target_any_blinded: peer.commitment.any_points.map((h) => ristretto255.Point.fromHex(h).multiply(b).toHex()), target_geo_blinded: peer.commitment.geo_points.map((h) => ristretto255.Point.fromHex(h).multiply(b).toHex()), challenger_top: shuffle(top.map((id) => hashToken(`top:${id}`).multiply(b).toHex())), challenger_core: shuffle(core.map((id) => hashToken(`core:${id}`).multiply(b).toHex())), challenger_any: shuffle([ ...allIds.map((id) => hashToken(`any:${id}`).multiply(b).toHex()), ...subcats.slice(0, Math.max(0, 48 - allIds.length)).map((s) => hashToken(`sub:${s}`).multiply(b).toHex()), ]), challenger_geo: shuffle(geoTokens.map((g) => hashToken(`${g.type}:${g.id}`).multiply(b).toHex())), }; setStatus(`Step 3/3: Mining ${chalPow}-bit PoW for blind challenge to ${peer.short_id}...`); const chalEv = await createSignedEventBrowser( state.identity, "psi_challenge", { target_pubkey: peer.pubkey, challenger_x25519_pubkey: state.identity.x25519_pubkey, taxonomy_version: taxonomy.version, challenge: chalPayload, }, chalPow ); const cResp = await ( await fetch("/api/v1/events", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(chalEv) }) ).json(); if (cResp.ok) sentCount++; else skippedCount++; } saveState(state); setStatus( `Published blinded profile (${state.identity.short_id}, 90 padded curve points)!
` + `Sent ${sentCount} zero-knowledge PSI challenge(s) to peers in ${escapeHtml(region)}` + (skippedCount ? ` (${skippedCount} already challenged within 30-day cooldown)` : "") + `.
Keep your key backup saved and click Check My Inbox anytime to see if anyone matched your threshold!`, "" ); refreshRelayStats(); } async function checkInboxBrowser() { if (!state.psi_secret) { setStatus("Publish your blinded profile first so your local Ristretto255 secret scalar exists.", "warn"); return; } setStatus("Polling authenticated inbox and evaluating incoming PSI challenges strictly locally..."); const auth = signInboxAuthBrowser(state.identity); const inbox = await (await fetch("/api/v1/inbox", { headers: { "X-SocialPSI-Auth": auth } })).json(); if (!inbox.ok) { setStatus(`Inbox error: ${escapeHtml(inbox.error)}`, "warn"); return; } const a = BigInt("0x" + state.psi_secret.scalar_hex); const seen = new Set(state.evaluated_ids || []); let newMatches = 0; let silentDrops = 0; for (const item of inbox.challenges || []) { if (seen.has(item.id)) continue; seen.add(item.id); state.known_peer_x25519[item.sender_pubkey] = item.challenger_x25519_pubkey; const ch = item.challenge; const cTop = new Set(ch.challenger_top.map((h) => ristretto255.Point.fromHex(h).multiply(a).toHex())); const cCore = new Set(ch.challenger_core.map((h) => ristretto255.Point.fromHex(h).multiply(a).toHex())); const cAny = new Set(ch.challenger_any.map((h) => ristretto255.Point.fromHex(h).multiply(a).toHex())); const cGeo = new Set(ch.challenger_geo.map((h) => ristretto255.Point.fromHex(h).multiply(a).toHex())); let score = 0; const matchedTop = new Set(); const matchedIds = new Set(); const cats = new Set(); state.psi_secret.top_slots.forEach((s, i) => { if (s.token_type === "top" && cTop.has(ch.target_top_blinded[i])) { matchedTop.add(s.id); matchedIds.add(s.id); cats.add(s.category); score += 6 * (s.specificity || 1); } }); state.psi_secret.core_slots.forEach((s, i) => { if (s.token_type === "core" && !matchedIds.has(s.id) && cCore.has(ch.target_core_blinded[i])) { matchedIds.add(s.id); cats.add(s.category); score += 4 * (s.specificity || 1); } }); state.psi_secret.any_slots.forEach((s, i) => { if (s.token_type === "any" && !matchedIds.has(s.id) && cAny.has(ch.target_any_blinded[i])) { matchedIds.add(s.id); cats.add(s.category); score += 2 * (s.specificity || 1); } }); let locMatch = "none"; if (matchedIds.size > 0 && cGeo.size > 0) { state.psi_secret.geo_slots.forEach((s, i) => { if (s.token_type === "geo6" && cGeo.has(ch.target_geo_blinded[i])) locMatch = "neighborhood"; else if (s.token_type === "geo5" && locMatch === "none" && cGeo.has(ch.target_geo_blinded[i])) locMatch = "metro"; }); if (locMatch === "neighborhood") score += 4; else if (locMatch === "metro") score += 2; } const hitQuests = []; for (const q of state.psi_secret.grail_quests || []) { const okP = q.require_all_phrase_ids.every((pid) => (q.require_top_tier ? matchedTop.has(pid) : matchedIds.has(pid))); const okL = !q.require_locality || q.require_locality === "none" || locMatch === "neighborhood" || (q.require_locality === "metro" && locMatch === "metro"); if (okP && okL) hitQuests.push(q.name); } const passed = hitQuests.length > 0 || (score >= 16 && cats.size >= 2 && matchedIds.size >= 2); if (!passed) { silentDrops++; continue; } newMatches++; state.matches.push({ direction: "incoming_challenge", challenge_id: item.id, peer_pubkey: item.sender_pubkey, peer_short_id: item.sender_short_id, peer_x25519_pubkey: item.challenger_x25519_pubkey, score_band: hitQuests.length ? "grail" : score >= 32 ? "exceptional" : score >= 22 ? "strong" : "moderate", matched_categories: Array.from(cats), matched_phrase_labels: Array.from(matchedIds).map((id) => phraseMap.get(id)?.label || id), matched_quests: hitQuests, locality_match: locMatch, created_at: item.created_at, }); } let newOffers = 0; let blockedOffers = 0; const existingOffers = new Set(state.matches.map((m) => m.offer_id).filter(Boolean)); for (const off of inbox.offers || []) { if (existingOffers.has(off.id)) continue; try { const d = await decryptE2EEBrowser(state.identity.x25519_privkey, off.envelope); if (!isSafePlainText(d.intro_note) || (d.contact && !isSafePlainText(d.contact.handle))) { blockedOffers++; continue; } newOffers++; state.matches.push({ direction: "received_offer", offer_id: off.id, offer_stage: off.stage, challenge_id: off.challenge_id, peer_pubkey: off.sender_pubkey, peer_short_id: off.sender_short_id, peer_x25519_pubkey: state.known_peer_x25519[off.sender_pubkey] || "", score_band: d.score_band, matched_categories: d.matched_categories || [], matched_phrase_labels: d.matched_phrase_labels || [], matched_quests: d.matched_quests || [], locality_match: d.locality_match || "none", intro_note: d.intro_note || "", contact: d.contact || null, created_at: off.created_at, }); } catch { blockedOffers++; } } state.evaluated_ids = Array.from(seen); saveState(state); renderMatchesList(); setStatus( `Inbox checked: ${newMatches} new strong match(es), ${newOffers} new E2EE offer(s)` + (silentDrops ? `, ${silentDrops} below-threshold silently dropped` : "") + (blockedOffers ? `, ${blockedOffers} unsafe/injection offer(s) blocked` : "") + `.`, "" ); } function renderMatchesList() { const box = document.getElementById("matches-list"); if (!state.matches.length) { box.innerHTML = `
No matches yet. Once another compatible peer joins or evaluates your blind challenge, matches appear here.
`; return; } box.innerHTML = ""; for (const m of [...state.matches].reverse()) { const card = document.createElement("div"); card.className = "result-box"; const nextStage = m.direction === "incoming_challenge" ? "offer_initial" : m.offer_stage === "offer_initial" ? "accept_with_contact" : m.offer_stage === "accept_with_contact" ? "final_contact_release" : null; card.innerHTML = `
${escapeHtml(m.peer_short_id)} · ${escapeHtml((m.score_band || "match").toUpperCase())} ${m.locality_match && m.locality_match !== "none" ? ` · ${escapeHtml(m.locality_match)} match` : ""} ${m.offer_stage ? ` · ${escapeHtml(m.offer_stage)}` : ""}
${m.matched_quests?.length ? `
Grail Quest: ${m.matched_quests.map((q) => `${escapeHtml(q)}`).join(" ")}
` : ""} ${m.matched_phrase_labels?.length ? `
Shared interests: ${m.matched_phrase_labels.map((l) => `${escapeHtml(l)}`).join(" ")}
` : ""} ${m.intro_note ? `
Untrusted human note: "${escapeHtml(m.intro_note)}"
` : ""} ${m.contact ? `
Decrypted Contact: ${escapeHtml(m.contact.channel)} → ${escapeHtml(m.contact.handle)}
` : ""}
${nextStage ? `` : ""}
`; const replyBtn = card.querySelector(".reply-btn"); if (replyBtn && nextStage) { replyBtn.addEventListener("click", async () => { const note = prompt("Short plain-text intro note (no URLs, max 240 chars):", "Hi! Looks like we have strong overlap — want to connect?"); if (note === null) return; if (!isSafePlainText(note) || note.length > 240) return alert("Unsafe text or URLs blocked."); let contact = undefined; if (nextStage !== "offer_initial") { const channel = prompt("Contact channel (signal | matrix | email | discord | telegram | other_handle):", "signal"); const handle = prompt("Your contact handle (encrypted end-to-end to this peer only):"); if (!channel || !handle || !isSafePlainText(handle)) return alert("Valid contact handle required."); contact = { channel: channel.trim(), handle: handle.trim() }; } const peerX = m.peer_x25519_pubkey || state.known_peer_x25519[m.peer_pubkey]; if (!peerX) return alert("Missing peer X25519 key — re-scan /api/v1/profiles first."); const payload = { protocol: "socialpsi-offer-v1", stage: nextStage, score_band: m.score_band, matched_categories: m.matched_categories, matched_phrase_labels: m.matched_phrase_labels, matched_quests: m.matched_quests, locality_match: m.locality_match, intro_note: note, ...(contact ? { contact } : {}), }; const envelope = await encryptE2EEBrowser(peerX, payload); const info = await (await fetch("/api/v1/info")).json(); const ev = await createSignedEventBrowser( state.identity, "match_offer", { challenge_id: m.challenge_id, recipient_pubkey: m.peer_pubkey, stage: nextStage, parent_offer_id: m.offer_id || null, envelope, }, info.pow_bits?.general ?? 14 ); const res = await (await fetch("/api/v1/events", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(ev) })).json(); if (res.ok) alert("Encrypted match response sent!"); else alert("Error: " + res.error); }); } card.querySelector(".block-btn").addEventListener("click", async () => { if (!confirm(`Block ${m.peer_short_id}?`)) return; const info = await (await fetch("/api/v1/info")).json(); const ev = await createSignedEventBrowser(state.identity, "block_peer", { blocked_pubkey: m.peer_pubkey }, info.pow_bits?.general ?? 14); await fetch("/api/v1/events", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(ev) }); alert("Peer blocked."); }); box.appendChild(card); } } // ---- Educational Local Demo Sandbox (Tab 3) ---- const demoAlice = new Set(["math:probability-stochastics", "tech:privacy-cryptography", "games:euchre", "food:specialty-coffee", "style:deep-intellectual-sparring"]); const demoBob = new Set(["math:probability-stochastics", "tech:privacy-cryptography", "games:euchre", "outdoors:day-hiking", "music:jazz-improvisation"]); let demoGrailActive = false; function renderDemoPicker(elId, setObj, cntId) { const el = document.getElementById(elId); el.innerHTML = ""; document.getElementById(cntId).textContent = `(${setObj.size} selected)`; for (const cat of taxonomy.categories) { const hdr = document.createElement("div"); hdr.className = "cat-hdr"; hdr.textContent = cat.label; el.appendChild(hdr); for (const p of taxonomy.phrases.filter((x) => x.category === cat.id)) { const lbl = document.createElement("label"); const cb = document.createElement("input"); cb.type = "checkbox"; cb.checked = setObj.has(p.id); cb.addEventListener("change", () => { if (cb.checked) setObj.add(p.id); else setObj.delete(p.id); document.getElementById(cntId).textContent = `(${setObj.size} selected)`; }); lbl.appendChild(cb); lbl.appendChild(document.createTextNode(` ${p.label} [w${p.specificity}]`)); el.appendChild(lbl); } } } function runDemoHandshake() { const t0 = performance.now(); const a = randScalar(), b = randScalar(); const slots = [...demoAlice].map((id) => ({ pt: hashToken("any:" + id).multiply(a).toHex(), phrase: phraseMap.get(id) })); while (slots.length < 48) slots.push({ pt: randDummyHex(), phrase: null }); const shAlice = shuffle(slots); const tBlinded = shAlice.map((s) => ristretto255.Point.fromHex(s.pt).multiply(b).toHex()); const bobBlinded = shuffle([...demoBob].map((id) => hashToken("any:" + id).multiply(b).toHex())); const bobDouble = new Set(bobBlinded.map((h) => ristretto255.Point.fromHex(h).multiply(a).toHex())); const matched = []; const cats = new Set(); let score = 0; shAlice.forEach((slot, i) => { if (slot.phrase && bobDouble.has(tBlinded[i])) { matched.push(slot.phrase); cats.add(slot.phrase.category); score += 3 * slot.phrase.specificity; } }); const grailHit = demoGrailActive && matched.some((m) => m.id === "games:euchre"); if (matched.length && demoGrailActive) score += 4; const elapsed = (performance.now() - t0).toFixed(1); const passed = grailHit || (score >= 16 && cats.size >= 2 && matched.length >= 2); document.getElementById("psi-output").innerHTML = `
${grailHit ? `GRAIL QUEST MATCH! ("Neighborhood Euchre" — niche top-ranked interest + blind neighborhood geohash aligned!)` : passed ? `THRESHOLD PASSED (Score: ${score}, ${cats.size} categories, ${matched.length} shared phrases)` : `BELOW THRESHOLD — SILENT DROP (Score: ${score}; 0 bits returned to Bob or Relay!)`} · ${elapsed} ms locally
Alice learns ONLY X ∩ Y: ${matched.length ? matched.map((m) => `${escapeHtml(m.label)}`).join(" ") : "none"}
Relay sees: 90 random-looking Ristretto255 points (zero plaintext)
Alice blinded points A[0..2]:\n${shAlice.slice(0, 3).map((s, i) => `  A[${i}] = ${s.pt}`).join("\n")}
`; } async function refreshRelayStats() { relayInfo = await (await fetch("/api/v1/info")).json(); document.getElementById("relay-title").textContent = relayInfo.relay_name || "SocialPSI Public Relay"; document.getElementById("relay-stats").innerHTML = `
Active Blind Profiles${relayInfo.stats.active_profiles}
Pending PSI Challenges${relayInfo.stats.pending_psi_challenges}
Active E2EE Offers${relayInfo.stats.active_e2ee_offers}
Audited Taxonomy${taxonomy.phrases.length} phrases (${taxonomy.categories.length} cats)
PoW Bits (Profile / Challenge)${relayInfo.pow_bits.profile} / ${relayInfo.pow_bits.challenge}
`; } async function boot() { taxonomy = await (await fetch("/api/v1/taxonomy")).json(); phraseMap = new Map(taxonomy.phrases.map((p) => [p.id, p])); await refreshRelayStats(); // Tab switching document.querySelectorAll(".tab-btn").forEach((btn) => { btn.addEventListener("click", () => { document.querySelectorAll(".tab-btn").forEach((b) => b.classList.remove("active")); document.querySelectorAll(".tab-panel").forEach((p) => p.classList.remove("active")); btn.classList.add("active"); document.getElementById(btn.getAttribute("data-tab")).classList.add("active"); }); }); // Hydrate identity & form controls document.getElementById("my-short-id").textContent = state.identity.short_id; document.getElementById("region-select").value = state.region_band || "us-northeast"; document.querySelectorAll("input[name='intent-cb']").forEach((cb) => { cb.checked = (state.intents || []).includes(cb.value); }); document.getElementById("lat-input").value = state.lat || ""; document.getElementById("lng-input").value = state.lng || ""; renderLivePicker(""); renderQuestOptions(); renderMatchesList(); // Populate AI Agent prompt with current origin const origin = window.location.origin; const agentPrompt = `Read ${origin}/llms.txt and fetch ${origin}/api/v1/taxonomy. Map my interests locally onto canonical taxonomy phrase IDs (do NOT send my plaintext interests to any remote server). Download the zero-dependency Python Ristretto255 client from ${origin}/psi-client.py, run 'python3 psi-client.py register' and 'scan' against ${origin} to check for blind overlap with active profiles, and show me any matches before exchanging contact info.`; document.getElementById("agent-prompt-box").textContent = agentPrompt; document.getElementById("py-quickstart").textContent = `curl -sO ${origin}/psi-client.py\npython3 psi-client.py --selftest\npython3 psi-client.py register --relay ${origin} --region us-northeast \\\n --intents friendship,intellectual-sparring \\\n --top games:euchre --core games:euchre,tech:ai-agents-mcp,tech:privacy-cryptography\npython3 psi-client.py scan --relay ${origin} --region us-northeast\npython3 psi-client.py inbox --relay ${origin}`; document.getElementById("copy-agent-prompt-btn").addEventListener("click", async () => { await navigator.clipboard.writeText(agentPrompt); document.getElementById("copy-agent-prompt-btn").textContent = "Copied!"; setTimeout(() => (document.getElementById("copy-agent-prompt-btn").textContent = "Copy Prompt for Your AI Agent"), 1800); }); document.getElementById("interest-search").addEventListener("input", (e) => renderLivePicker(e.target.value)); document.getElementById("publish-btn").addEventListener("click", publishAndChallenge); document.getElementById("inbox-btn").addEventListener("click", checkInboxBrowser); document.getElementById("geo-locate-btn").addEventListener("click", () => { if (!navigator.geolocation) return alert("Browser geolocation unavailable."); navigator.geolocation.getCurrentPosition( (pos) => { document.getElementById("lat-input").value = pos.coords.latitude.toFixed(4); document.getElementById("lng-input").value = pos.coords.longitude.toFixed(4); }, (err) => alert("Geolocation error: " + err.message) ); }); document.getElementById("export-keys-btn").addEventListener("click", () => { const blob = new Blob([JSON.stringify(state, null, 2)], { type: "application/json" }); const url = URL.createObjectURL(blob); const a = document.createElement("a"); a.href = url; a.download = `socialpsi-backup-${state.identity.short_id}.json`; a.click(); URL.revokeObjectURL(url); }); document.getElementById("import-keys-input").addEventListener("change", async (e) => { const file = e.target.files?.[0]; if (!file) return; try { const parsed = JSON.parse(await file.text()); if (!parsed?.identity?.ed25519_pubkey) throw new Error("Invalid backup file"); state = parsed; saveState(state); location.reload(); } catch (err) { alert("Import failed: " + err.message); } }); document.getElementById("reset-keys-btn").addEventListener("click", () => { if (!confirm("Generate a brand-new local keypair and clear browser state?")) return; localStorage.removeItem(STORAGE_KEY); location.reload(); }); // Demo tab renderDemoPicker("alice-picker", demoAlice, "alice-count"); renderDemoPicker("bob-picker", demoBob, "bob-count"); runDemoHandshake(); document.getElementById("run-psi-btn").addEventListener("click", runDemoHandshake); document.getElementById("preset-match-btn").addEventListener("click", () => { demoGrailActive = false; demoBob.clear(); ["math:probability-stochastics", "tech:privacy-cryptography", "games:euchre", "outdoors:day-hiking"].forEach((x) => demoBob.add(x)); renderDemoPicker("bob-picker", demoBob, "bob-count"); runDemoHandshake(); }); document.getElementById("preset-grail-btn").addEventListener("click", () => { demoGrailActive = true; demoBob.clear(); ["games:euchre", "outdoors:birding-wildlife", "music:classical-chamber"].forEach((x) => demoBob.add(x)); renderDemoPicker("bob-picker", demoBob, "bob-count"); runDemoHandshake(); }); document.getElementById("preset-probe-btn").addEventListener("click", () => { demoGrailActive = false; demoBob.clear(); demoBob.add("math:probability-stochastics"); renderDemoPicker("bob-picker", demoBob, "bob-count"); runDemoHandshake(); }); } boot().catch((err) => { setStatus("Initialization error: " + escapeHtml(err.message), "warn"); });