import crypto from "node:crypto"; import { x25519 } from "@noble/curves/ed25519.js"; export interface RawSignedEventInput { pubkey: string; // hex SPKI DER Ed25519 public key created_at: number; // unix epoch seconds kind: string; content: Record; } export interface SignedProtocolEvent extends RawSignedEventInput { id: string; // sha256 hex of canonical [0, pubkey, created_at, kind, content, nonce] nonce: number; // SHA-256 Proof-of-Work nonce sig: string; // hex Ed25519 signature over `id` bytes } export interface AgentIdentity { ed25519_pubkey: string; // hex SPKI DER ed25519_privkey: string; // hex PKCS8 DER x25519_pubkey: string; // 64-char hex raw 32-byte X25519 public key x25519_privkey: string; // 64-char hex raw 32-byte X25519 private key short_id: string; // psid_<12 hex> created_at: number; } export interface E2EEEnvelope { version: "x25519-aes256gcm-v1"; ephemeral_pubkey: string; // 64-char hex X25519 ephemeral public key nonce: string; // 24-char hex (12 bytes) ciphertext: string; // hex (ciphertext + 16-byte GCM auth tag) } export function canonicalizeJson(value: unknown): string { if (value === null || typeof value !== "object") { return JSON.stringify(value); } if (Array.isArray(value)) { return "[" + value.map((item) => canonicalizeJson(item)).join(",") + "]"; } const obj = value as Record; const sortedKeys = Object.keys(obj).sort(); const parts: string[] = []; for (const k of sortedKeys) { if (obj[k] !== undefined) { parts.push(`${JSON.stringify(k)}:${canonicalizeJson(obj[k])}`); } } return "{" + parts.join(",") + "}"; } export function getShortId(ed25519PubkeyHex: string): string { return "psid_" + crypto.createHash("sha256").update(ed25519PubkeyHex).digest("hex").slice(0, 12); } export function generateAgentIdentity(): AgentIdentity { const { publicKey, privateKey } = crypto.generateKeyPairSync("ed25519"); const edPub = publicKey.export({ type: "spki", format: "der" }).toString("hex"); const edPriv = privateKey.export({ type: "pkcs8", format: "der" }).toString("hex"); const xPrivBytes = crypto.randomBytes(32); const xPubBytes = x25519.getPublicKey(xPrivBytes); return { ed25519_pubkey: edPub, ed25519_privkey: edPriv, x25519_pubkey: Buffer.from(xPubBytes).toString("hex"), x25519_privkey: xPrivBytes.toString("hex"), short_id: getShortId(edPub), created_at: Math.floor(Date.now() / 1000), }; } export function computeEventId(input: RawSignedEventInput, nonce: number): string { const serialized = canonicalizeJson([ 0, input.pubkey, input.created_at, input.kind, input.content, nonce, ]); return crypto.createHash("sha256").update(serialized).digest("hex"); } export function countLeadingZeroBits(hexHash: string): number { let bits = 0; for (let i = 0; i < hexHash.length; i++) { const nibble = parseInt(hexHash[i], 16); if (Number.isNaN(nibble)) break; if (nibble === 0) { bits += 4; } else { if (nibble < 2) bits += 3; else if (nibble < 4) bits += 2; else if (nibble < 8) bits += 1; break; } } return bits; } export function createSignedEvent( input: RawSignedEventInput, ed25519PrivkeyHex: string, minPowBits = 16 ): SignedProtocolEvent { let nonce = 0; let id = ""; while (true) { id = computeEventId(input, nonce); if (countLeadingZeroBits(id) >= minPowBits) break; nonce++; } const privateKeyObj = crypto.createPrivateKey({ key: Buffer.from(ed25519PrivkeyHex, "hex"), format: "der", type: "pkcs8", }); const sig = crypto.sign(null, Buffer.from(id, "hex"), privateKeyObj).toString("hex"); return { ...input, id, nonce, sig }; } export function verifySignedEvent( event: SignedProtocolEvent, minPowBits = 16, maxClockSkewSeconds = 600 ): { valid: boolean; error?: string; powBits?: number } { try { if (!event || typeof event !== "object") { return { valid: false, error: "Invalid signed event object" }; } if (!event.pubkey || !event.id || !event.sig || typeof event.nonce !== "number" || typeof event.created_at !== "number") { return { valid: false, error: "Missing required cryptographic event fields" }; } const now = Math.floor(Date.now() / 1000); if (Math.abs(now - event.created_at) > maxClockSkewSeconds) { return { valid: false, error: `Event timestamp outside allowed skew (${maxClockSkewSeconds}s)` }; } const expectedId = computeEventId( { pubkey: event.pubkey, created_at: event.created_at, kind: event.kind, content: event.content, }, event.nonce ); if (expectedId !== event.id) { return { valid: false, error: "Event ID hash mismatch" }; } const powBits = countLeadingZeroBits(event.id); if (powBits < minPowBits) { return { valid: false, error: `Insufficient Proof-of-Work: got ${powBits} bits, required >= ${minPowBits}`, powBits }; } const publicKeyObj = crypto.createPublicKey({ key: Buffer.from(event.pubkey, "hex"), format: "der", type: "spki", }); const ok = crypto.verify(null, Buffer.from(event.id, "hex"), publicKeyObj, Buffer.from(event.sig, "hex")); if (!ok) { return { valid: false, error: "Invalid Ed25519 signature" }; } return { valid: true, powBits }; } catch (err: any) { return { valid: false, error: `Cryptographic verification error: ${err?.message || String(err)}` }; } } /** * Verify a lightweight Ed25519 request signature (used for authenticated inbox polling without burning PoW). */ export function signInboxAuthHeader(ed25519PubkeyHex: string, ed25519PrivkeyHex: string, timestampSec: number): string { const payload = `socialpsi:inbox-auth:${ed25519PubkeyHex}:${timestampSec}`; const privateKeyObj = crypto.createPrivateKey({ key: Buffer.from(ed25519PrivkeyHex, "hex"), format: "der", type: "pkcs8", }); const sig = crypto.sign(null, Buffer.from(payload, "utf-8"), privateKeyObj).toString("hex"); return `${ed25519PubkeyHex}.${timestampSec}.${sig}`; } export function verifyInboxAuthHeader( headerValue: string, maxSkewSeconds = 300 ): { valid: boolean; pubkey?: string; error?: string } { try { const parts = headerValue.trim().split("."); if (parts.length !== 3) return { valid: false, error: "Malformed auth header" }; const [pubkey, tsStr, sig] = parts; const ts = Number(tsStr); if (!Number.isFinite(ts)) return { valid: false, error: "Invalid timestamp" }; const now = Math.floor(Date.now() / 1000); if (Math.abs(now - ts) > maxSkewSeconds) return { valid: false, error: "Auth header expired" }; const payload = `socialpsi:inbox-auth:${pubkey}:${ts}`; const publicKeyObj = crypto.createPublicKey({ key: Buffer.from(pubkey, "hex"), format: "der", type: "spki", }); const ok = crypto.verify(null, Buffer.from(payload, "utf-8"), publicKeyObj, Buffer.from(sig, "hex")); if (!ok) return { valid: false, error: "Invalid auth signature" }; return { valid: true, pubkey }; } catch (err: any) { return { valid: false, error: err?.message || "Auth verification error" }; } } /** * Encrypt a JSON payload to a recipient's X25519 public key using ephemeral ECDH + HKDF-SHA256 + AES-256-GCM. */ export function encryptE2EEJson(recipientX25519PubkeyHex: string, payload: unknown): E2EEEnvelope { const recipientPub = Buffer.from(recipientX25519PubkeyHex, "hex"); if (recipientPub.length !== 32) { throw new Error("Invalid X25519 recipient public key length (expected 32 bytes)"); } const ephPriv = crypto.randomBytes(32); const ephPub = Buffer.from(x25519.getPublicKey(ephPriv)); const sharedSecret = x25519.getSharedSecret(ephPriv, recipientPub); const aesKey = Buffer.from( crypto.hkdfSync( "sha256", Buffer.from(sharedSecret), ephPub, Buffer.from("socialpsi:e2ee:v1", "utf-8"), 32 ) ); const nonce = crypto.randomBytes(12); const cipher = crypto.createCipheriv("aes-256-gcm", aesKey, nonce); const plaintext = Buffer.from(JSON.stringify(payload), "utf-8"); const encrypted = Buffer.concat([cipher.update(plaintext), cipher.final()]); const authTag = cipher.getAuthTag(); return { version: "x25519-aes256gcm-v1", ephemeral_pubkey: ephPub.toString("hex"), nonce: nonce.toString("hex"), ciphertext: Buffer.concat([encrypted, authTag]).toString("hex"), }; } /** * Decrypt an E2EEEnvelope using the recipient's local X25519 private key. */ export function decryptE2EEJson(recipientX25519PrivkeyHex: string, envelope: E2EEEnvelope): T { if (!envelope || envelope.version !== "x25519-aes256gcm-v1") { throw new Error("Unsupported E2EE envelope version"); } const priv = Buffer.from(recipientX25519PrivkeyHex, "hex"); const ephPub = Buffer.from(envelope.ephemeral_pubkey, "hex"); const nonce = Buffer.from(envelope.nonce, "hex"); const combined = Buffer.from(envelope.ciphertext, "hex"); if (priv.length !== 32 || ephPub.length !== 32 || nonce.length !== 12 || combined.length < 16) { throw new Error("Malformed E2EE envelope"); } const ciphertext = combined.subarray(0, combined.length - 16); const authTag = combined.subarray(combined.length - 16); const sharedSecret = x25519.getSharedSecret(priv, ephPub); const aesKey = Buffer.from( crypto.hkdfSync( "sha256", Buffer.from(sharedSecret), ephPub, Buffer.from("socialpsi:e2ee:v1", "utf-8"), 32 ) ); const decipher = crypto.createDecipheriv("aes-256-gcm", aesKey, nonce); decipher.setAuthTag(authTag); const decrypted = Buffer.concat([decipher.update(ciphertext), decipher.final()]); return JSON.parse(decrypted.toString("utf-8")) as T; } const EPHEMERAL_HMAC_SEED = process.env.RATE_LIMIT_HMAC_SECRET || crypto.randomBytes(32).toString("hex"); /** * Zero-IP privacy-preserving subnet bucket key (daily-rotated HMAC of /24 IPv4 or /48 IPv6 prefix). * Never stores or logs raw IP addresses. */ export function hashRateLimitSubject(rawIp: string | undefined): string { const day = new Date().toISOString().slice(0, 10); const ip = (rawIp || "unknown").replace(/^::ffff:/, ""); let prefix = ip; if (ip.includes(".")) { const octets = ip.split("."); prefix = octets.slice(0, 3).join(".") + ".0/24"; } else if (ip.includes(":")) { const groups = ip.split(":"); prefix = groups.slice(0, 3).join(":") + "::/48"; } return crypto .createHmac("sha256", `${EPHEMERAL_HMAC_SEED}:${day}`) .update(prefix) .digest("hex") .slice(0, 32); }