import crypto from "node:crypto"; import { ristretto255, ristretto255_hasher } from "@noble/curves/ed25519.js"; import { BlindLocalityTokens, buildLocalityTokens } from "./geohash.js"; import { getPhraseMap, getSubcategoryToCategoryMap, validatePhraseIds } from "./taxonomy.js"; export const PSI_DOMAIN_PREFIX = "socialpsi:v1:"; export const PADDED_TOP_SIZE = 8; export const PADDED_CORE_SIZE = 16; export const PADDED_ANY_SIZE = 48; export const PADDED_GEO_SIZE = 18; export const MAX_TOP_PHRASES = 5; export const MAX_CORE_PHRASES = 12; export const MAX_ENJOY_PHRASES = 20; export const MAX_CHALLENGE_TOP_POINTS = 5; export const MAX_CHALLENGE_CORE_POINTS = 12; export const MAX_CHALLENGE_ANY_POINTS = 48; export const MAX_CHALLENGE_GEO_POINTS = 18; const RISTRETTO_ORDER = ristretto255.Point.Fn.ORDER; export interface BlindedProfileCommitment { version: "ristretto255-psi-v2"; top_points: string[]; // fixed length PADDED_TOP_SIZE (8) core_points: string[]; // fixed length PADDED_CORE_SIZE (16) any_points: string[]; // fixed length PADDED_ANY_SIZE (48) geo_points: string[]; // fixed length PADDED_GEO_SIZE (18) — random dummies if locality disabled } export interface LocalSlotMeta { token_type: "top" | "core" | "any" | "sub" | "geo5" | "geo6" | "dummy"; id?: string; // phrase_id, subcategory_id, or geohash cell category?: string; subcategory?: string; specificity?: 1 | 2 | 3; } /** * Local compound niche compatibility rule ("Grail Quest"), e.g.: * { name: "Park Slope Euchre", require_all_phrase_ids: ["games:euchre"], require_top_tier: true, require_locality: "neighborhood" } * Kept 100% local on the owner's machine — never shared with relays or non-matching peers. */ export interface GrailQuest { name: string; require_all_phrase_ids: string[]; require_top_tier?: boolean; // if true, peer must also rank the required phrase(s) in their Top 5 require_locality?: "none" | "metro" | "neighborhood"; } export interface LocalBlindedSecretState { scalar_hex: string; // secret Ristretto255 scalar `a` (kept strictly local!) rotated_at: number; evaluations_count: number; top_slots: LocalSlotMeta[]; core_slots: LocalSlotMeta[]; any_slots: LocalSlotMeta[]; geo_slots: LocalSlotMeta[]; top_phrase_ids: string[]; core_phrase_ids: string[]; enjoy_phrase_ids: string[]; personal_ranks: Record; // local priority 1..5 (5 = highest importance) locality_enabled: boolean; grail_quests: GrailQuest[]; } export interface BlindedChallengePayload { version: "ristretto255-psi-v2"; target_top_blinded: string[]; // b * A.top (length 8) target_core_blinded: string[]; // b * A.core (length 16) target_any_blinded: string[]; // b * A.any (length 48) target_geo_blinded: string[]; // b * A.geo (length 18) challenger_top: string[]; // shuffle(b * H("top:" + y)), max 5 challenger_core: string[]; // shuffle(b * H("core:" + y)), max 12 challenger_any: string[]; // shuffle(b * H("any:" + y) U b * H("sub:" + sub)), max 48 challenger_geo: string[]; // shuffle(b * H("geo5:" + c) U b * H("geo6:" + c)), max 18 (may be empty) } export interface MatchThresholds { min_weighted_score: number; min_distinct_categories: number; min_exact_phrase_matches: number; } export const DEFAULT_MATCH_THRESHOLDS: MatchThresholds = { min_weighted_score: 16, min_distinct_categories: 2, min_exact_phrase_matches: 2, }; export interface LocalOverlapEvaluation { matched: boolean; weighted_score: number; score_band: "below_threshold" | "moderate" | "strong" | "exceptional" | "grail"; distinct_categories: string[]; matched_top_top: string[]; matched_core_core: string[]; matched_phrase_ids: string[]; matched_subcategories: string[]; locality_match: "none" | "metro" | "neighborhood"; matched_quests: string[]; } export interface CreateProfileOptions { top_phrase_ids?: string[]; core_phrase_ids: string[]; enjoy_phrase_ids: string[]; personal_ranks?: Record; // optional 1..5 priority per phrase locality?: { lat: number; lng: number } | BlindLocalityTokens | null; grail_quests?: GrailQuest[]; } function bytesToBigIntLE(bytes: Uint8Array): bigint { let result = 0n; for (let i = bytes.length - 1; i >= 0; i--) { result = (result << 8n) + BigInt(bytes[i]); } return result; } function bigIntToHex32(n: bigint): string { return n.toString(16).padStart(64, "0"); } function hexToScalar(hex: string): bigint { if (!/^[0-9a-f]{64}$/i.test(hex)) { throw new Error("Invalid 32-byte scalar hex"); } const s = BigInt("0x" + hex); if (s <= 0n || s >= RISTRETTO_ORDER) { throw new Error("Scalar out of valid Ristretto255 group order range"); } return s; } export function generateRandomScalar(): { scalar: bigint; hex: string } { while (true) { const raw = crypto.randomBytes(64); const s = bytesToBigIntLE(raw) % RISTRETTO_ORDER; if (s > 1n) { return { scalar: s, hex: bigIntToHex32(s) }; } } } function deriveUniformToPoint(uniform64Bytes: Uint8Array) { if (!ristretto255_hasher.deriveToCurve) { throw new Error("ristretto255_hasher.deriveToCurve is unavailable"); } return ristretto255_hasher.deriveToCurve(uniform64Bytes); } /** * Standard RFC 9496 element derivation: * H(token) = ristretto255_from_uniform_bytes(SHA-512("socialpsi:v1:" || token)) * Interoperable byte-for-byte with Rust curve25519-dalek, libsodium, Go, and pure Python. */ export function hashTokenToPoint(token: string) { const digest = crypto .createHash("sha512") .update(PSI_DOMAIN_PREFIX + token, "utf-8") .digest(); return deriveUniformToPoint(new Uint8Array(digest)); } function randomDummyPointHex(): string { const uniform = crypto.randomBytes(64); return deriveUniformToPoint(new Uint8Array(uniform)).toHex(); } function decodeValidNonZeroPoint(hex: string) { if (typeof hex !== "string" || !/^[0-9a-f]{64}$/i.test(hex)) { throw new Error("Point must be a 64-character hex string"); } const pt = ristretto255.Point.fromHex(hex); if (pt.is0()) { throw new Error("Identity (zero) Ristretto255 point is forbidden"); } return pt; } function cryptoShuffle(items: T[]): T[] { const arr = [...items]; for (let i = arr.length - 1; i > 0; i--) { const j = crypto.randomInt(0, i + 1); [arr[i], arr[j]] = [arr[j], arr[i]]; } return arr; } function resolveLocalityTokens(loc?: { lat: number; lng: number } | BlindLocalityTokens | null): BlindLocalityTokens | null { if (!loc) return null; if ("lat" in loc && "lng" in loc) { return buildLocalityTokens(loc.lat, loc.lng); } return loc; } /** * Anti-probing guard for Grail Quests: * Every quest must require at least 2 conjunctive constraints so neither a single common tag * nor a bare location probe can ever leak information. */ export function validateGrailQuest(quest: GrailQuest, localityEnabled: boolean): void { if (!quest.name || quest.name.length > 80) { throw new Error("GrailQuest name must be 1-80 chars"); } if (!Array.isArray(quest.require_all_phrase_ids) || quest.require_all_phrase_ids.length === 0) { throw new Error(`GrailQuest '${quest.name}' must require at least 1 canonical phrase (location-only quests are forbidden)`); } const check = validatePhraseIds(quest.require_all_phrase_ids); if (!check.valid) { throw new Error(`GrailQuest '${quest.name}' has invalid phrase IDs: ${check.invalidIds.join(", ")}`); } const needsLoc = quest.require_locality === "metro" || quest.require_locality === "neighborhood"; if (needsLoc && !localityEnabled) { throw new Error(`GrailQuest '${quest.name}' requires locality, but no local coordinates/geohash were provided`); } if (quest.require_all_phrase_ids.length === 1) { const phrase = getPhraseMap().get(quest.require_all_phrase_ids[0])!; if (!needsLoc || phrase.specificity < 3) { throw new Error( `Anti-probing guard: single-phrase GrailQuest '${quest.name}' must combine a niche (specificity=3) phrase with metro/neighborhood blind locality` ); } } } export function validateBlindedCommitment(commitment: BlindedProfileCommitment): { valid: boolean; error?: string } { try { if (!commitment || commitment.version !== "ristretto255-psi-v2") { return { valid: false, error: "Unsupported commitment version (expected ristretto255-psi-v2)" }; } const specs: Array<[string, string[] | undefined, number]> = [ ["top_points", commitment.top_points, PADDED_TOP_SIZE], ["core_points", commitment.core_points, PADDED_CORE_SIZE], ["any_points", commitment.any_points, PADDED_ANY_SIZE], ["geo_points", commitment.geo_points, PADDED_GEO_SIZE], ]; for (const [name, arr, expectedLen] of specs) { if (!Array.isArray(arr) || arr.length !== expectedLen) { return { valid: false, error: `${name} must have exact padded length ${expectedLen}` }; } const seen = new Set(); for (const hex of arr) { const canon = decodeValidNonZeroPoint(hex).toHex(); if (seen.has(canon)) return { valid: false, error: `Duplicate point in ${name}` }; seen.add(canon); } } return { valid: true }; } catch (err: any) { return { valid: false, error: `Invalid Ristretto255 commitment: ${err?.message || String(err)}` }; } } export function validateBlindedChallenge(challenge: BlindedChallengePayload): { valid: boolean; error?: string } { try { if (!challenge || challenge.version !== "ristretto255-psi-v2") { return { valid: false, error: "Unsupported challenge version (expected ristretto255-psi-v2)" }; } const fixedSpecs: Array<[string, string[] | undefined, number]> = [ ["target_top_blinded", challenge.target_top_blinded, PADDED_TOP_SIZE], ["target_core_blinded", challenge.target_core_blinded, PADDED_CORE_SIZE], ["target_any_blinded", challenge.target_any_blinded, PADDED_ANY_SIZE], ["target_geo_blinded", challenge.target_geo_blinded, PADDED_GEO_SIZE], ]; for (const [label, arr, expected] of fixedSpecs) { if (!Array.isArray(arr) || arr.length !== expected) { return { valid: false, error: `${label} must have length ${expected}` }; } } if (!Array.isArray(challenge.challenger_top) || challenge.challenger_top.length > MAX_CHALLENGE_TOP_POINTS) { return { valid: false, error: `challenger_top exceeds max (${MAX_CHALLENGE_TOP_POINTS})` }; } if (!Array.isArray(challenge.challenger_core) || challenge.challenger_core.length > MAX_CHALLENGE_CORE_POINTS) { return { valid: false, error: `challenger_core exceeds max (${MAX_CHALLENGE_CORE_POINTS})` }; } if ( !Array.isArray(challenge.challenger_any) || challenge.challenger_any.length === 0 || challenge.challenger_any.length > MAX_CHALLENGE_ANY_POINTS ) { return { valid: false, error: `challenger_any must have 1..${MAX_CHALLENGE_ANY_POINTS} points` }; } if (!Array.isArray(challenge.challenger_geo) || challenge.challenger_geo.length > MAX_CHALLENGE_GEO_POINTS) { return { valid: false, error: `challenger_geo exceeds max (${MAX_CHALLENGE_GEO_POINTS})` }; } const checkUnique = (arr: string[], label: string) => { const seen = new Set(); for (const h of arr) { const canon = decodeValidNonZeroPoint(h).toHex(); if (seen.has(canon)) throw new Error(`Duplicate point in ${label}`); seen.add(canon); } }; checkUnique(challenge.target_top_blinded, "target_top_blinded"); checkUnique(challenge.target_core_blinded, "target_core_blinded"); checkUnique(challenge.target_any_blinded, "target_any_blinded"); checkUnique(challenge.target_geo_blinded, "target_geo_blinded"); checkUnique(challenge.challenger_top, "challenger_top"); checkUnique(challenge.challenger_core, "challenger_core"); checkUnique(challenge.challenger_any, "challenger_any"); checkUnique(challenge.challenger_geo, "challenger_geo"); return { valid: true }; } catch (err: any) { return { valid: false, error: `Invalid Ristretto255 challenge: ${err?.message || String(err)}` }; } } /** * Step 1 (Local on Alice's device): * Build fixed-size padded blinded commitment `A` (top + core + any + geo) and keep scalar `a`, personal rankings, * and compound Grail Quests strictly local. */ export function createBlindedProfile( coreOrOpts: string[] | CreateProfileOptions, enjoyArg: string[] = [] ): { commitment: BlindedProfileCommitment; secretState: LocalBlindedSecretState } { const opts: CreateProfileOptions = Array.isArray(coreOrOpts) ? { core_phrase_ids: coreOrOpts, enjoy_phrase_ids: enjoyArg } : coreOrOpts; const topUnique = Array.from(new Set(opts.top_phrase_ids || [])); const coreUnique = Array.from(new Set([...topUnique, ...(opts.core_phrase_ids || [])])); const enjoyUnique = Array.from(new Set(opts.enjoy_phrase_ids || [])).filter((id) => !coreUnique.includes(id)); if (topUnique.length > MAX_TOP_PHRASES) throw new Error(`Maximum ${MAX_TOP_PHRASES} top-ranked phrases allowed`); if (coreUnique.length > MAX_CORE_PHRASES) throw new Error(`Maximum ${MAX_CORE_PHRASES} core phrases allowed`); if (enjoyUnique.length > MAX_ENJOY_PHRASES) throw new Error(`Maximum ${MAX_ENJOY_PHRASES} enjoy phrases allowed`); if (coreUnique.length + enjoyUnique.length < 3) { throw new Error("Select at least 3 canonical interests to participate meaningfully"); } const allPhraseIds = [...coreUnique, ...enjoyUnique]; const check = validatePhraseIds(allPhraseIds); if (!check.valid) { throw new Error(`Invalid canonical taxonomy IDs (custom uncurated strings are forbidden): ${check.invalidIds.join(", ")}`); } const localityTokens = resolveLocalityTokens(opts.locality); const grailQuests = opts.grail_quests || []; for (const q of grailQuests) { validateGrailQuest(q, Boolean(localityTokens)); } // Normalize personal ranks (1..5): top defaults to 5, core to 3, enjoy to 2 unless explicitly ranked const personalRanks: Record = {}; for (const id of enjoyUnique) personalRanks[id] = 2; for (const id of coreUnique) personalRanks[id] = 3; for (const id of topUnique) personalRanks[id] = 5; for (const [id, rank] of Object.entries(opts.personal_ranks || {})) { if (allPhraseIds.includes(id)) { personalRanks[id] = Math.max(1, Math.min(5, Math.round(rank))); } } const phraseMap = getPhraseMap(); const { scalar: a, hex: scalarHex } = generateRandomScalar(); // 1. Top bucket (padded to PADDED_TOP_SIZE = 8) const topEntries: { pointHex: string; meta: LocalSlotMeta }[] = []; for (const id of topUnique) { const p = phraseMap.get(id)!; topEntries.push({ pointHex: hashTokenToPoint(`top:${id}`).multiply(a).toHex(), meta: { token_type: "top", id, category: p.category, subcategory: p.subcategory, specificity: p.specificity }, }); } while (topEntries.length < PADDED_TOP_SIZE) { topEntries.push({ pointHex: randomDummyPointHex(), meta: { token_type: "dummy" } }); } const shuffledTop = cryptoShuffle(topEntries); // 2. Core bucket (padded to PADDED_CORE_SIZE = 16) const coreEntries: { pointHex: string; meta: LocalSlotMeta }[] = []; for (const id of coreUnique) { const p = phraseMap.get(id)!; coreEntries.push({ pointHex: hashTokenToPoint(`core:${id}`).multiply(a).toHex(), meta: { token_type: "core", id, category: p.category, subcategory: p.subcategory, specificity: p.specificity }, }); } while (coreEntries.length < PADDED_CORE_SIZE) { coreEntries.push({ pointHex: randomDummyPointHex(), meta: { token_type: "dummy" } }); } const shuffledCore = cryptoShuffle(coreEntries); // 3. Any bucket: all phrases + unique subcategories (padded to PADDED_ANY_SIZE = 48) const anyEntries: { pointHex: string; meta: LocalSlotMeta }[] = []; const subcatSet = new Set(); for (const id of allPhraseIds) { const p = phraseMap.get(id)!; anyEntries.push({ pointHex: hashTokenToPoint(`any:${id}`).multiply(a).toHex(), meta: { token_type: "any", id, category: p.category, subcategory: p.subcategory, specificity: p.specificity }, }); subcatSet.add(p.subcategory); } const subToCat = getSubcategoryToCategoryMap(); for (const sub of subcatSet) { if (anyEntries.length >= PADDED_ANY_SIZE) break; anyEntries.push({ pointHex: hashTokenToPoint(`sub:${sub}`).multiply(a).toHex(), meta: { token_type: "sub", id: sub, category: subToCat.get(sub), subcategory: sub, specificity: 1 }, }); } while (anyEntries.length < PADDED_ANY_SIZE) { anyEntries.push({ pointHex: randomDummyPointHex(), meta: { token_type: "dummy" } }); } const shuffledAny = cryptoShuffle(anyEntries); // 4. Geo bucket: 9-cell geo5 (metro) + 9-cell geo6 (neighborhood), padded to PADDED_GEO_SIZE = 18 // If user didn't enable locality, filled with 18 random dummy points so relay cannot even tell! const geoEntries: { pointHex: string; meta: LocalSlotMeta }[] = []; if (localityTokens) { for (const cell of localityTokens.metro_cells.slice(0, 9)) { geoEntries.push({ pointHex: hashTokenToPoint(`geo5:${cell}`).multiply(a).toHex(), meta: { token_type: "geo5", id: cell }, }); } for (const cell of localityTokens.neighborhood_cells.slice(0, 9)) { if (geoEntries.length >= PADDED_GEO_SIZE) break; geoEntries.push({ pointHex: hashTokenToPoint(`geo6:${cell}`).multiply(a).toHex(), meta: { token_type: "geo6", id: cell }, }); } } while (geoEntries.length < PADDED_GEO_SIZE) { geoEntries.push({ pointHex: randomDummyPointHex(), meta: { token_type: "dummy" } }); } const shuffledGeo = cryptoShuffle(geoEntries); const commitment: BlindedProfileCommitment = { version: "ristretto255-psi-v2", top_points: shuffledTop.map((e) => e.pointHex), core_points: shuffledCore.map((e) => e.pointHex), any_points: shuffledAny.map((e) => e.pointHex), geo_points: shuffledGeo.map((e) => e.pointHex), }; const secretState: LocalBlindedSecretState = { scalar_hex: scalarHex, rotated_at: Math.floor(Date.now() / 1000), evaluations_count: 0, top_slots: shuffledTop.map((e) => e.meta), core_slots: shuffledCore.map((e) => e.meta), any_slots: shuffledAny.map((e) => e.meta), geo_slots: shuffledGeo.map((e) => e.meta), top_phrase_ids: topUnique, core_phrase_ids: coreUnique, enjoy_phrase_ids: enjoyUnique, personal_ranks: personalRanks, locality_enabled: Boolean(localityTokens), grail_quests: grailQuests, }; return { commitment, secretState }; } /** * Step 2 (Local on Bob's device): * Build zero-knowledge blinded challenge using ephemeral scalar `b` (discarded immediately). */ export function createBlindedChallenge( targetCommitment: BlindedProfileCommitment, myCorePhraseIdsInput: string[], myEnjoyPhraseIdsInput: string[], extraOpts: { top_phrase_ids?: string[]; locality?: { lat: number; lng: number } | BlindLocalityTokens | null } = {} ): BlindedChallengePayload { const validTarget = validateBlindedCommitment(targetCommitment); if (!validTarget.valid) { throw new Error(`Target profile commitment invalid: ${validTarget.error}`); } const topUnique = Array.from(new Set(extraOpts.top_phrase_ids || [])); const coreUnique = Array.from(new Set([...topUnique, ...myCorePhraseIdsInput])); const enjoyUnique = Array.from(new Set(myEnjoyPhraseIdsInput)).filter((id) => !coreUnique.includes(id)); if (topUnique.length > MAX_TOP_PHRASES) throw new Error(`Max ${MAX_TOP_PHRASES} top phrases`); if (coreUnique.length > MAX_CORE_PHRASES) throw new Error(`Max ${MAX_CORE_PHRASES} core phrases`); if (enjoyUnique.length > MAX_ENJOY_PHRASES) throw new Error(`Max ${MAX_ENJOY_PHRASES} enjoy phrases`); const allPhraseIds = [...coreUnique, ...enjoyUnique]; if (allPhraseIds.length === 0) throw new Error("Must provide at least 1 canonical phrase"); const check = validatePhraseIds(allPhraseIds); if (!check.valid) { throw new Error(`Invalid canonical taxonomy IDs: ${check.invalidIds.join(", ")}`); } const phraseMap = getPhraseMap(); const { scalar: b } = generateRandomScalar(); const targetTopBlinded = targetCommitment.top_points.map((h) => decodeValidNonZeroPoint(h).multiply(b).toHex()); const targetCoreBlinded = targetCommitment.core_points.map((h) => decodeValidNonZeroPoint(h).multiply(b).toHex()); const targetAnyBlinded = targetCommitment.any_points.map((h) => decodeValidNonZeroPoint(h).multiply(b).toHex()); const targetGeoBlinded = targetCommitment.geo_points.map((h) => decodeValidNonZeroPoint(h).multiply(b).toHex()); const myTopPoints = cryptoShuffle(topUnique.map((id) => hashTokenToPoint(`top:${id}`).multiply(b).toHex())); const myCorePoints = cryptoShuffle(coreUnique.map((id) => hashTokenToPoint(`core:${id}`).multiply(b).toHex())); const myAnyRaw: string[] = []; const subcats = new Set(); for (const id of allPhraseIds) { myAnyRaw.push(hashTokenToPoint(`any:${id}`).multiply(b).toHex()); subcats.add(phraseMap.get(id)!.subcategory); } for (const sub of subcats) { if (myAnyRaw.length >= MAX_CHALLENGE_ANY_POINTS) break; myAnyRaw.push(hashTokenToPoint(`sub:${sub}`).multiply(b).toHex()); } const myAnyPoints = cryptoShuffle(myAnyRaw); const localityTokens = resolveLocalityTokens(extraOpts.locality); const myGeoRaw: string[] = []; if (localityTokens) { for (const c of localityTokens.metro_cells.slice(0, 9)) { myGeoRaw.push(hashTokenToPoint(`geo5:${c}`).multiply(b).toHex()); } for (const c of localityTokens.neighborhood_cells.slice(0, 9)) { if (myGeoRaw.length >= MAX_CHALLENGE_GEO_POINTS) break; myGeoRaw.push(hashTokenToPoint(`geo6:${c}`).multiply(b).toHex()); } } const myGeoPoints = cryptoShuffle(myGeoRaw); return { version: "ristretto255-psi-v2", target_top_blinded: targetTopBlinded, target_core_blinded: targetCoreBlinded, target_any_blinded: targetAnyBlinded, target_geo_blinded: targetGeoBlinded, challenger_top: myTopPoints, challenger_core: myCorePoints, challenger_any: myAnyPoints, challenger_geo: myGeoPoints, }; } function personalRankMultiplier(rank: number | undefined): number { switch (rank) { case 5: return 1.8; case 4: return 1.4; case 3: return 1.15; case 1: return 0.85; default: return 1.0; } } /** * Step 3 (Local on Alice's device): * Evaluate ranked overlap, blind locality match, and compound Grail Quests strictly locally. * Learns ONLY the shared intersection `X ∩ Y`; learns ZERO about Bob's non-matching interests or non-matching location. */ export function evaluateBlindedChallengeLocally( secretState: LocalBlindedSecretState, challenge: BlindedChallengePayload, thresholds: MatchThresholds = DEFAULT_MATCH_THRESHOLDS ): LocalOverlapEvaluation { const validChallenge = validateBlindedChallenge(challenge); if (!validChallenge.valid) { throw new Error(`Invalid challenge payload: ${validChallenge.error}`); } const a = hexToScalar(secretState.scalar_hex); const chalTopDouble = new Set(challenge.challenger_top.map((h) => decodeValidNonZeroPoint(h).multiply(a).toHex())); const chalCoreDouble = new Set(challenge.challenger_core.map((h) => decodeValidNonZeroPoint(h).multiply(a).toHex())); const chalAnyDouble = new Set(challenge.challenger_any.map((h) => decodeValidNonZeroPoint(h).multiply(a).toHex())); const chalGeoDouble = new Set(challenge.challenger_geo.map((h) => decodeValidNonZeroPoint(h).multiply(a).toHex())); const coreSet = new Set(secretState.core_phrase_ids); const topSet = new Set(secretState.top_phrase_ids || []); const ranks = secretState.personal_ranks || {}; const matchedTopTop = new Set(); const matchedCoreCore = new Set(); const matchedPhrases = new Set(); const matchedSubcats = new Set(); const matchedPhraseSubcats = new Set(); const distinctCats = new Set(); let weightedScore = 0; // 1. Top <-> Top mutual priority matches for (let i = 0; i < secretState.top_slots.length; i++) { const slot = secretState.top_slots[i]; if (slot.token_type !== "top" || !slot.id) continue; const pt = decodeValidNonZeroPoint(challenge.target_top_blinded[i]).toHex(); if (chalTopDouble.has(pt)) { matchedTopTop.add(slot.id); matchedCoreCore.add(slot.id); matchedPhrases.add(slot.id); if (slot.subcategory) matchedPhraseSubcats.add(slot.subcategory); if (slot.category) distinctCats.add(slot.category); weightedScore += Math.round(6 * (slot.specificity || 1) * personalRankMultiplier(ranks[slot.id])); } } // 2. Core <-> Core exact matches (not already counted in Top <-> Top) for (let i = 0; i < secretState.core_slots.length; i++) { const slot = secretState.core_slots[i]; if (slot.token_type !== "core" || !slot.id) continue; if (matchedTopTop.has(slot.id)) continue; const pt = decodeValidNonZeroPoint(challenge.target_core_blinded[i]).toHex(); if (chalCoreDouble.has(pt)) { matchedCoreCore.add(slot.id); matchedPhrases.add(slot.id); if (slot.subcategory) matchedPhraseSubcats.add(slot.subcategory); if (slot.category) distinctCats.add(slot.category); const base = topSet.has(slot.id) ? 5 : 4; weightedScore += Math.round(base * (slot.specificity || 1) * personalRankMultiplier(ranks[slot.id])); } } // 3. Any <-> Any exact phrase matches (not already counted in Core/Top) for (let i = 0; i < secretState.any_slots.length; i++) { const slot = secretState.any_slots[i]; if (slot.token_type !== "any" || !slot.id) continue; if (matchedCoreCore.has(slot.id)) continue; const pt = decodeValidNonZeroPoint(challenge.target_any_blinded[i]).toHex(); if (chalAnyDouble.has(pt)) { matchedPhrases.add(slot.id); if (slot.subcategory) matchedPhraseSubcats.add(slot.subcategory); if (slot.category) distinctCats.add(slot.category); const base = coreSet.has(slot.id) ? 3 : 2; weightedScore += Math.round(base * (slot.specificity || 1) * personalRankMultiplier(ranks[slot.id])); } } // 4. Subcategory semantic matches (if no exact phrase in that subcategory matched) for (let i = 0; i < secretState.any_slots.length; i++) { const slot = secretState.any_slots[i]; if (slot.token_type !== "sub" || !slot.id) continue; if (matchedPhraseSubcats.has(slot.id)) continue; const pt = decodeValidNonZeroPoint(challenge.target_any_blinded[i]).toHex(); if (chalAnyDouble.has(pt)) { matchedSubcats.add(slot.id); if (slot.category) distinctCats.add(slot.category); weightedScore += 1; } } // 5. Blind locality match (geo6 = neighborhood, geo5 = metro) // SECURITY INVARIANT: Locality NEVER adds points or triggers a match unless at least 1 exact interest matched! let localityMatch: "none" | "metro" | "neighborhood" = "none"; if (secretState.locality_enabled && chalGeoDouble.size > 0) { let hitGeo5 = false; let hitGeo6 = false; for (let i = 0; i < secretState.geo_slots.length; i++) { const slot = secretState.geo_slots[i]; if (slot.token_type !== "geo5" && slot.token_type !== "geo6") continue; const pt = decodeValidNonZeroPoint(challenge.target_geo_blinded[i]).toHex(); if (chalGeoDouble.has(pt)) { if (slot.token_type === "geo6") hitGeo6 = true; else hitGeo5 = true; } } if (hitGeo6) localityMatch = "neighborhood"; else if (hitGeo5) localityMatch = "metro"; } if (matchedPhrases.size > 0) { if (localityMatch === "neighborhood") weightedScore += 4; else if (localityMatch === "metro") weightedScore += 2; } // 6. Local Compound Grail Quests (e.g., "Park Slope Euchre Night": games:euchre in Top 5 + neighborhood locality!) const matchedQuests: string[] = []; for (const quest of secretState.grail_quests || []) { const allPhrasesHit = quest.require_all_phrase_ids.every((pid) => quest.require_top_tier ? matchedTopTop.has(pid) : matchedPhrases.has(pid) ); if (!allPhrasesHit) continue; const reqLoc = quest.require_locality || "none"; const locOk = reqLoc === "none" || (reqLoc === "metro" && (localityMatch === "metro" || localityMatch === "neighborhood")) || (reqLoc === "neighborhood" && localityMatch === "neighborhood"); if (locOk) { matchedQuests.push(quest.name); } } const standardMatched = weightedScore >= thresholds.min_weighted_score && distinctCats.size >= thresholds.min_distinct_categories && matchedPhrases.size >= thresholds.min_exact_phrase_matches; const matched = standardMatched || matchedQuests.length > 0; let scoreBand: LocalOverlapEvaluation["score_band"] = "below_threshold"; if (matchedQuests.length > 0) { scoreBand = "grail"; } else if (standardMatched) { if (weightedScore >= thresholds.min_weighted_score * 2) scoreBand = "exceptional"; else if (weightedScore >= Math.round(thresholds.min_weighted_score * 1.4)) scoreBand = "strong"; else scoreBand = "moderate"; } return { matched, weighted_score: weightedScore, score_band: scoreBand, distinct_categories: Array.from(distinctCats).sort(), matched_top_top: Array.from(matchedTopTop).sort(), matched_core_core: Array.from(matchedCoreCore).sort(), matched_phrase_ids: Array.from(matchedPhrases).sort(), matched_subcategories: Array.from(matchedSubcats).sort(), locality_match: matchedPhrases.size > 0 ? localityMatch : "none", matched_quests: matchedQuests, }; }