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 = `
${escapeHtml(m.locality_match)} match` : ""}
${m.offer_stage ? ` · ${escapeHtml(m.offer_stage)}` : ""}
${escapeHtml(q)}`).join(" ")}${escapeHtml(l)}`).join(" ")}${escapeHtml(m.contact.handle)}${escapeHtml(m.label)}`).join(" ") : "none"}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 = `