import { getShortId, SignedProtocolEvent, verifySignedEvent } from "./crypto.js"; import { CHALLENGE_TTL_SECONDS, checkAndIncrementRateLimit, db, OFFER_TTL_SECONDS, PAIR_COOLDOWN_SECONDS, PROFILE_TTL_SECONDS, pruneExpiredRecords, } from "./db.js"; import { validateBlindedChallenge, validateBlindedCommitment } from "./psi.js"; import { AbuseReportContentSchema, BlockPeerContentSchema, ChallengeSubmitContentSchema, MatchOfferContentSchema, ProfileRegisterContentSchema, } from "./safety.js"; export function getPowConfig() { return { profile: Number(process.env.POW_BITS_PROFILE ?? 18), challenge: Number(process.env.POW_BITS_CHALLENGE ?? 16), general: Number(process.env.POW_BITS_GENERAL ?? 14), }; } export const ABUSE_QUARANTINE_THRESHOLD = Number(process.env.ABUSE_QUARANTINE_THRESHOLD ?? 2); export const MAX_DAILY_CHALLENGES_PER_PUBKEY = Number(process.env.MAX_DAILY_CHALLENGES_PER_PUBKEY ?? 15); export const MAX_HOURLY_CHALLENGES_PER_SUBNET = Number(process.env.MAX_HOURLY_CHALLENGES_PER_SUBNET ?? 25); let registrationsPaused = false; export function setRegistrationsPaused(paused: boolean): void { registrationsPaused = paused; } export function areRegistrationsPaused(): boolean { return registrationsPaused; } /** * 1. Register or Refresh a Blinded Profile Card (Zero Plaintext Interests!) */ export function handleRegisterProfile( event: SignedProtocolEvent, subnetHash: string ): { ok: boolean; error?: string; profile?: any } { pruneExpiredRecords(); if (registrationsPaused) { return { ok: false, error: "Relay registrations are temporarily paused by operator" }; } const rl = checkAndIncrementRateLimit(`subnet:reg:${subnetHash}`, 20, 3600); if (!rl.allowed) { return { ok: false, error: `Rate limit exceeded. Retry in ${rl.retryAfterSeconds}s.` }; } const powBits = getPowConfig().profile; const verified = verifySignedEvent(event, powBits); if (!verified.valid) return { ok: false, error: verified.error }; if (event.kind !== "profile_register") { return { ok: false, error: "Expected event kind 'profile_register'" }; } const parsed = ProfileRegisterContentSchema.safeParse(event.content); if (!parsed.success) { return { ok: false, error: `Invalid profile payload: ${parsed.error.issues[0]?.message || "schema error"}` }; } const data = parsed.data; const psiCheck = validateBlindedCommitment(data.commitment); if (!psiCheck.valid) return { ok: false, error: psiCheck.error }; const existing = db.prepare("SELECT status, created_at FROM profiles WHERE pubkey = ?").get(event.pubkey) as | { status: string; created_at: number } | undefined; if (existing && existing.status === "suspended") { return { ok: false, error: "This pubkey has been suspended from this relay" }; } const now = Math.floor(Date.now() / 1000); const shortId = getShortId(event.pubkey); const expiresAt = now + PROFILE_TTL_SECONDS; db.prepare( `INSERT INTO profiles (pubkey, short_id, x25519_pubkey, age_attestation, taxonomy_version, region_band, intents_json, commitment_json, status, created_at, updated_at, expires_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'active', ?, ?, ?) ON CONFLICT(pubkey) DO UPDATE SET x25519_pubkey = excluded.x25519_pubkey, taxonomy_version = excluded.taxonomy_version, region_band = excluded.region_band, intents_json = excluded.intents_json, commitment_json = excluded.commitment_json, updated_at = excluded.updated_at, expires_at = excluded.expires_at` ).run( event.pubkey, shortId, data.x25519_pubkey, data.age_attestation, data.taxonomy_version, data.region_band, JSON.stringify(data.intents), JSON.stringify(data.commitment), existing ? existing.created_at : now, now, expiresAt ); return { ok: true, profile: { pubkey: event.pubkey, short_id: shortId, region_band: data.region_band, intents: data.intents, taxonomy_version: data.taxonomy_version, expires_at: expiresAt, pow_bits: verified.powBits, }, }; } /** * 2. Submit a Blinded Store-and-Forward PSI Challenge to a Target Peer's Inbox */ export function handleSubmitChallenge( event: SignedProtocolEvent, subnetHash: string ): { ok: boolean; error?: string; challenge_id?: string; expires_at?: number } { pruneExpiredRecords(); const subnetRl = checkAndIncrementRateLimit(`subnet:chal:${subnetHash}`, MAX_HOURLY_CHALLENGES_PER_SUBNET, 3600); if (!subnetRl.allowed) { return { ok: false, error: `Subnet challenge rate limit exceeded. Retry in ${subnetRl.retryAfterSeconds}s.` }; } const powBits = getPowConfig().challenge; const verified = verifySignedEvent(event, powBits); if (!verified.valid) return { ok: false, error: verified.error }; if (event.kind !== "psi_challenge") { return { ok: false, error: "Expected event kind 'psi_challenge'" }; } const senderRl = checkAndIncrementRateLimit(`pubkey:chal:${event.pubkey}`, MAX_DAILY_CHALLENGES_PER_PUBKEY, 86400); if (!senderRl.allowed) { return { ok: false, error: `Daily challenge quota (${MAX_DAILY_CHALLENGES_PER_PUBKEY}/day) exceeded.` }; } const parsed = ChallengeSubmitContentSchema.safeParse(event.content); if (!parsed.success) { return { ok: false, error: `Invalid challenge payload: ${parsed.error.issues[0]?.message || "schema error"}` }; } const data = parsed.data; if (data.target_pubkey === event.pubkey) { return { ok: false, error: "Cannot submit a PSI challenge to your own pubkey" }; } const senderProfile = db.prepare("SELECT status FROM profiles WHERE pubkey = ?").get(event.pubkey) as | { status: string } | undefined; if (senderProfile && senderProfile.status !== "active") { return { ok: false, error: `Sender pubkey is currently ${senderProfile.status}` }; } const target = db.prepare("SELECT pubkey, status, expires_at FROM profiles WHERE pubkey = ?").get(data.target_pubkey) as | { pubkey: string; status: string; expires_at: number } | undefined; const now = Math.floor(Date.now() / 1000); if (!target || target.status !== "active" || target.expires_at < now) { return { ok: false, error: "Target profile not found or inactive" }; } const psiValid = validateBlindedChallenge(data.challenge); if (!psiValid.valid) return { ok: false, error: psiValid.error }; // Enforce 30-day per-(sender, target) anti-probing cooldown const cooldown = db .prepare("SELECT last_challenged_at FROM challenge_cooldowns WHERE sender_pubkey = ? AND target_pubkey = ?") .get(event.pubkey, data.target_pubkey) as { last_challenged_at: number } | undefined; if (cooldown && now - cooldown.last_challenged_at < PAIR_COOLDOWN_SECONDS) { return { ok: false, error: "Anti-probing cooldown active: max 1 PSI challenge per target peer every 30 days", }; } // Silently accept without leaking whether target blocked sender (anti-oracle!) const blocked = db .prepare("SELECT 1 FROM blocks WHERE blocker_pubkey = ? AND blocked_pubkey = ?") .get(data.target_pubkey, event.pubkey); db.prepare( `INSERT INTO challenge_cooldowns (sender_pubkey, target_pubkey, last_challenged_at) VALUES (?, ?, ?) ON CONFLICT(sender_pubkey, target_pubkey) DO UPDATE SET last_challenged_at = excluded.last_challenged_at` ).run(event.pubkey, data.target_pubkey, now); const expiresAt = now + CHALLENGE_TTL_SECONDS; if (!blocked) { db.prepare( `INSERT INTO challenges (id, sender_pubkey, target_pubkey, challenger_x25519_pubkey, taxonomy_version, challenge_json, created_at, expires_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)` ).run( event.id, event.pubkey, data.target_pubkey, data.challenger_x25519_pubkey, data.taxonomy_version, JSON.stringify(data.challenge), now, expiresAt ); } return { ok: true, challenge_id: event.id, expires_at: expiresAt, }; } /** * 3. Submit an End-to-End Encrypted Match Offer / Acceptance / Final Contact Release */ export function handleSubmitMatchOffer( event: SignedProtocolEvent, subnetHash: string ): { ok: boolean; error?: string; offer_id?: string; expires_at?: number } { pruneExpiredRecords(); const rl = checkAndIncrementRateLimit(`subnet:offer:${subnetHash}`, 40, 3600); if (!rl.allowed) return { ok: false, error: `Rate limit exceeded. Retry in ${rl.retryAfterSeconds}s.` }; const verified = verifySignedEvent(event, getPowConfig().general); if (!verified.valid) return { ok: false, error: verified.error }; if (event.kind !== "match_offer") return { ok: false, error: "Expected event kind 'match_offer'" }; const parsed = MatchOfferContentSchema.safeParse(event.content); if (!parsed.success) { return { ok: false, error: `Invalid match_offer payload: ${parsed.error.issues[0]?.message || "schema error"}` }; } const data = parsed.data; const senderProfile = db.prepare("SELECT status FROM profiles WHERE pubkey = ?").get(event.pubkey) as | { status: string } | undefined; if (senderProfile && senderProfile.status !== "active") { return { ok: false, error: `Sender pubkey is ${senderProfile.status}` }; } // Verify the referenced challenge exists and connects these two peers! const challenge = db.prepare("SELECT sender_pubkey, target_pubkey FROM challenges WHERE id = ?").get(data.challenge_id) as | { sender_pubkey: string; target_pubkey: string } | undefined; if (!challenge) { return { ok: false, error: "Referenced challenge_id not found or expired" }; } if (data.stage === "offer_initial") { if (challenge.target_pubkey !== event.pubkey || challenge.sender_pubkey !== data.recipient_pubkey) { return { ok: false, error: "Only the challenged target peer may initiate an offer_initial back to the challenger" }; } } else if (data.stage === "accept_with_contact") { if (challenge.sender_pubkey !== event.pubkey || challenge.target_pubkey !== data.recipient_pubkey) { return { ok: false, error: "Only the original challenger may send accept_with_contact" }; } const prior = db .prepare("SELECT 1 FROM match_offers WHERE id = ? AND challenge_id = ? AND stage = 'offer_initial' AND recipient_pubkey = ?") .get(data.parent_offer_id || "", data.challenge_id, event.pubkey); if (!prior) { return { ok: false, error: "accept_with_contact requires a valid parent_offer_id from an offer_initial sent to you" }; } } else if (data.stage === "final_contact_release") { if (challenge.target_pubkey !== event.pubkey || challenge.sender_pubkey !== data.recipient_pubkey) { return { ok: false, error: "Only the target peer may send final_contact_release" }; } const prior = db .prepare("SELECT 1 FROM match_offers WHERE id = ? AND challenge_id = ? AND stage = 'accept_with_contact' AND recipient_pubkey = ?") .get(data.parent_offer_id || "", data.challenge_id, event.pubkey); if (!prior) { return { ok: false, error: "final_contact_release requires a valid parent_offer_id from accept_with_contact" }; } } const blocked = db .prepare("SELECT 1 FROM blocks WHERE blocker_pubkey = ? AND blocked_pubkey = ?") .get(data.recipient_pubkey, event.pubkey); const now = Math.floor(Date.now() / 1000); const expiresAt = now + OFFER_TTL_SECONDS; if (!blocked) { db.prepare( `INSERT INTO match_offers (id, challenge_id, sender_pubkey, recipient_pubkey, stage, parent_offer_id, envelope_json, created_at, expires_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)` ).run( event.id, data.challenge_id, event.pubkey, data.recipient_pubkey, data.stage, data.parent_offer_id || null, JSON.stringify(data.envelope), now, expiresAt ); } return { ok: true, offer_id: event.id, expires_at: expiresAt }; } /** * 4. Block a Peer Pubkey (Silent Drop of Future Challenges & Offers) */ export function handleBlockPeer(event: SignedProtocolEvent): { ok: boolean; error?: string } { const verified = verifySignedEvent(event, getPowConfig().general); if (!verified.valid) return { ok: false, error: verified.error }; if (event.kind !== "block_peer") return { ok: false, error: "Expected event kind 'block_peer'" }; const parsed = BlockPeerContentSchema.safeParse(event.content); if (!parsed.success) return { ok: false, error: "Invalid block_peer content" }; if (parsed.data.blocked_pubkey === event.pubkey) return { ok: false, error: "Cannot block yourself" }; const now = Math.floor(Date.now() / 1000); db.prepare( "INSERT OR IGNORE INTO blocks (blocker_pubkey, blocked_pubkey, created_at) VALUES (?, ?, ?)" ).run(event.pubkey, parsed.data.blocked_pubkey, now); // Immediately remove pending challenges & offers from the blocked peer to this user db.prepare("DELETE FROM challenges WHERE target_pubkey = ? AND sender_pubkey = ?").run( event.pubkey, parsed.data.blocked_pubkey ); db.prepare("DELETE FROM match_offers WHERE recipient_pubkey = ? AND sender_pubkey = ?").run( event.pubkey, parsed.data.blocked_pubkey ); return { ok: true }; } /** * 5. Interaction-Gated Signed Abuse Report (Anti-Brigading + Automatic Quarantine) */ export function handleAbuseReport(event: SignedProtocolEvent): { ok: boolean; error?: string; reported_status?: string; } { const verified = verifySignedEvent(event, getPowConfig().general); if (!verified.valid) return { ok: false, error: verified.error }; if (event.kind !== "abuse_report") return { ok: false, error: "Expected event kind 'abuse_report'" }; const parsed = AbuseReportContentSchema.safeParse(event.content); if (!parsed.success) { return { ok: false, error: `Invalid abuse_report: ${parsed.error.issues[0]?.message || "schema error"}` }; } const { reported_pubkey, offer_id, reason } = parsed.data; if (reported_pubkey === event.pubkey) { return { ok: false, error: "Cannot report yourself" }; } // Anti-brigading gate: reporter MUST have actually received the referenced match_offer from reported_pubkey! const offer = db .prepare("SELECT id FROM match_offers WHERE id = ? AND sender_pubkey = ? AND recipient_pubkey = ?") .get(offer_id, reported_pubkey, event.pubkey); if (!offer) { return { ok: false, error: "Interaction proof failed: abuse_report requires an offer_id actually sent to you by reported_pubkey", }; } const now = Math.floor(Date.now() / 1000); const insertRes = db .prepare( `INSERT OR IGNORE INTO abuse_reports (id, reporter_pubkey, reported_pubkey, offer_id, reason, created_at) VALUES (?, ?, ?, ?, ?, ?)` ) .run(event.id, event.pubkey, reported_pubkey, offer_id, reason, now); // Auto-block for the reporter db.prepare("INSERT OR IGNORE INTO blocks (blocker_pubkey, blocked_pubkey, created_at) VALUES (?, ?, ?)").run( event.pubkey, reported_pubkey, now ); if (insertRes.changes > 0) { db.prepare("UPDATE profiles SET report_count = report_count + 1 WHERE pubkey = ?").run(reported_pubkey); } const distinctReports = ( db.prepare("SELECT COUNT(DISTINCT reporter_pubkey) as c FROM abuse_reports WHERE reported_pubkey = ?").get( reported_pubkey ) as { c: number } ).c; let newStatus = "active"; if (reason === "underage_or_unsafe" || distinctReports >= ABUSE_QUARANTINE_THRESHOLD) { newStatus = "quarantined"; db.prepare("UPDATE profiles SET status = 'quarantined' WHERE pubkey = ? AND status = 'active'").run(reported_pubkey); } return { ok: true, reported_status: newStatus }; } /** * 6. Authenticated Inbox Fetch (Returns Pending PSI Challenges & E2EE Offers for This Pubkey Only) */ export function handleFetchInbox(authenticatedPubkey: string) { pruneExpiredRecords(); const challenges = db .prepare( `SELECT id, sender_pubkey, challenger_x25519_pubkey, taxonomy_version, challenge_json, created_at, expires_at FROM challenges WHERE target_pubkey = ? ORDER BY created_at ASC LIMIT 100` ) .all(authenticatedPubkey) as any[]; const offers = db .prepare( `SELECT id, challenge_id, sender_pubkey, stage, parent_offer_id, envelope_json, created_at, expires_at FROM match_offers WHERE recipient_pubkey = ? ORDER BY created_at ASC LIMIT 100` ) .all(authenticatedPubkey) as any[]; return { ok: true, pubkey: authenticatedPubkey, challenges: challenges.map((c) => ({ id: c.id, sender_pubkey: c.sender_pubkey, sender_short_id: getShortId(c.sender_pubkey), challenger_x25519_pubkey: c.challenger_x25519_pubkey, taxonomy_version: c.taxonomy_version, challenge: JSON.parse(c.challenge_json), created_at: c.created_at, expires_at: c.expires_at, })), offers: offers.map((o) => ({ id: o.id, challenge_id: o.challenge_id, sender_pubkey: o.sender_pubkey, sender_short_id: getShortId(o.sender_pubkey), stage: o.stage, parent_offer_id: o.parent_offer_id, envelope: JSON.parse(o.envelope_json), created_at: o.created_at, expires_at: o.expires_at, })), }; } /** * 7. List Active Public Blind Profiles (Zero Plaintext Interests, Zero Freeform Prose!) */ export function listPublicProfiles(filters: { region_band?: string; intent?: string; limit?: number } = {}) { pruneExpiredRecords(); const limit = Math.min(Math.max(Number(filters.limit) || 50, 1), 100); const now = Math.floor(Date.now() / 1000); let sql = ` SELECT pubkey, short_id, x25519_pubkey, taxonomy_version, region_band, intents_json, commitment_json, created_at, updated_at, expires_at FROM profiles WHERE status = 'active' AND expires_at >= ? `; const params: any[] = [now]; if (filters.region_band) { sql += " AND region_band = ?"; params.push(filters.region_band); } sql += " ORDER BY updated_at DESC LIMIT ?"; params.push(limit); const rows = db.prepare(sql).all(...params) as any[]; const profiles = rows .map((r) => { const intents: string[] = JSON.parse(r.intents_json); if (filters.intent && !intents.includes(filters.intent)) return null; return { pubkey: r.pubkey, short_id: r.short_id, x25519_pubkey: r.x25519_pubkey, taxonomy_version: r.taxonomy_version, region_band: r.region_band, intents, commitment: JSON.parse(r.commitment_json), created_at: r.created_at, updated_at: r.updated_at, expires_at: r.expires_at, }; }) .filter(Boolean); return { count: profiles.length, profiles }; } export function getRelayStats() { pruneExpiredRecords(); const activeProfiles = ( db.prepare("SELECT COUNT(*) as c FROM profiles WHERE status = 'active'").get() as { c: number } ).c; const quarantinedProfiles = ( db.prepare("SELECT COUNT(*) as c FROM profiles WHERE status != 'active'").get() as { c: number } ).c; const pendingChallenges = (db.prepare("SELECT COUNT(*) as c FROM challenges").get() as { c: number }).c; const activeOffers = (db.prepare("SELECT COUNT(*) as c FROM match_offers").get() as { c: number }).c; const peerRelays = db.prepare("SELECT url, name FROM peer_relays ORDER BY added_at ASC").all(); const today = new Date().toISOString().slice(0, 10); const telemetryToday = db .prepare("SELECT agent_class, COUNT(*) as hits FROM telemetry_events WHERE day = ? GROUP BY agent_class ORDER BY hits DESC") .all(today); return { active_profiles: activeProfiles, quarantined_profiles: quarantinedProfiles, pending_psi_challenges: pendingChallenges, active_e2ee_offers: activeOffers, federated_peer_relays: peerRelays, telemetry_today_zero_ip: telemetryToday, }; }