From a69e78389fee24feaf7da94963d9d9735ea48901 Mon Sep 17 00:00:00 2001 From: Danny Morabito Date: Tue, 11 Mar 2025 20:50:33 +0100 Subject: [PATCH 01/11] MLS implementation --- deno.json | 1 + deno.lock | 5 + index.ts | 25 +- mls.ts | 674 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ utils.ts | 44 ++++ 5 files changed, 743 insertions(+), 6 deletions(-) create mode 100644 mls.ts diff --git a/deno.json b/deno.json index d505ec8..6443181 100644 --- a/deno.json +++ b/deno.json @@ -5,6 +5,7 @@ "imports": { "@db/sqlite": "jsr:@db/sqlite@^0.12.0", "@noble/ciphers": "jsr:@noble/ciphers@^1.2.1", + "@noble/secp256k1": "jsr:@noble/secp256k1@^2.2.3", "@nostr/tools": "jsr:@nostr/tools@^2.10.4", "@nostrify/nostrify": "jsr:@nostrify/nostrify@^0.37.0", "@nostrify/types": "jsr:@nostrify/types@^0.36.0", diff --git a/deno.lock b/deno.lock index 21a17b3..e3ff4d5 100644 --- a/deno.lock +++ b/deno.lock @@ -5,6 +5,7 @@ "jsr:@db/sqlite@0.12": "0.12.0", "jsr:@denosaurs/plug@1": "1.0.6", "jsr:@noble/ciphers@^1.2.1": "1.2.1", + "jsr:@noble/secp256k1@^2.2.3": "2.2.3", "jsr:@nostr/tools@^2.10.4": "2.10.4", "jsr:@nostrify/nostrify@*": "0.37.0", "jsr:@nostrify/nostrify@0.37": "0.37.0", @@ -66,6 +67,9 @@ "@noble/ciphers@1.2.1": { "integrity": "e8eba45a1a6fefa6e522872d2f6b2bcc40d6ff928bdacfb3add5e245c1656819" }, + "@noble/secp256k1@2.2.3": { + "integrity": "830435da513d7d65fa6868061a0048b0f3ade456646c0f79a0675e7f4e965600" + }, "@nostr/tools@2.10.4": { "integrity": "7fda015c96b4f674727843aecb990e2af1989e4724588415ccf6f69066abfd4f", "dependencies": [ @@ -266,6 +270,7 @@ "dependencies": [ "jsr:@db/sqlite@0.12", "jsr:@noble/ciphers@^1.2.1", + "jsr:@noble/secp256k1@^2.2.3", "jsr:@nostr/tools@^2.10.4", "jsr:@nostrify/nostrify@0.37", "jsr:@nostrify/types@0.36", diff --git a/index.ts b/index.ts index 7cfb67a..a25e7b5 100644 --- a/index.ts +++ b/index.ts @@ -7,6 +7,7 @@ import type { import { getCCNPrivateKey, getCCNPubkey, + getMLSPrivateKey, isArray, isLocalhost, isValidJSON, @@ -21,6 +22,7 @@ import { mixQuery, sql, sqlPartial } from "./utils/queries.ts"; import { log, setupLogger } from "./utils/logs.ts"; import { getEveFilePath } from "./utils/files.ts"; import { MIN_POW, POW_TO_MINE } from "./consts.ts"; +import { MLS } from "./mls.ts"; await setupLogger(); @@ -36,6 +38,7 @@ if (!Deno.env.has("ENCRYPTION_KEY")) { } const db = new Database(await getEveFilePath("db")); +const mls = new MLS(await getMLSPrivateKey()); const pool = new nostrTools.SimplePool(); const relays = [ "wss://relay.arx-ccn.com/", @@ -114,10 +117,14 @@ async function createEncryptedEvent( const randomPrivateKey = nostrTools.generateSecretKey(); const randomPrivateKeyPubKey = nostrTools.getPublicKey(randomPrivateKey); const conversationKey = nip44.getConversationKey(randomPrivateKey, ccnPubKey); + const mlsEncryptedEvent = JSON.stringify(mls.encryptMessage( + ccnPubKey, + JSON.stringify(event), + )); const sealTemplate = { kind: 13, created_at: randomTimeUpTo2DaysInThePast(), - content: nip44.encrypt(JSON.stringify(event), conversationKey), + content: nip44.encrypt(mlsEncryptedEvent, conversationKey), tags: [], }; const seal = nostrTools.finalizeEvent(sealTemplate, ccnPrivateKey); @@ -136,25 +143,31 @@ async function createEncryptedEvent( async function decryptEvent( event: nostrTools.Event, ): Promise { - const ccnPrivkey = await getCCNPrivateKey(); - if (event.kind !== 1059) { throw new Error("Cannot decrypt event -- not a gift wrap"); } const pow = nostrTools.nip13.getPow(event.id); - if (pow < MIN_POW) { throw new Error("Cannot decrypt event -- PoW too low"); } - const conversationKey = nip44.getConversationKey(ccnPrivkey, event.pubkey); + const ccnPrivateKey = await getCCNPrivateKey(); + const conversationKey = nip44.getConversationKey(ccnPrivateKey, event.pubkey); const seal = JSON.parse(nip44.decrypt(event.content, conversationKey)); if (!seal) throw new Error("Cannot decrypt event -- no seal"); if (seal.kind !== 13) { throw new Error("Cannot decrypt event subevent -- not a seal"); } - const content = JSON.parse(nip44.decrypt(seal.content, conversationKey)); + const mlsEncryptedContent = JSON.parse( + nip44.decrypt(seal.content, conversationKey), + ); + if (!mlsEncryptedContent) { + throw new Error("Cannot decrypt event -- no mls content"); + } + const content = JSON.parse( + mls.decryptMessage(await getCCNPubkey(), mlsEncryptedContent)!, + ); return content as nostrTools.VerifiedEvent; } diff --git a/mls.ts b/mls.ts new file mode 100644 index 0000000..4aaba46 --- /dev/null +++ b/mls.ts @@ -0,0 +1,674 @@ +import type { NPub, NSec } from "@nostr/tools/nip19"; +import * as nip19 from "@nostr/tools/nip19"; +import * as nostrTools from "@nostr/tools"; +import { hkdf } from "npm:@noble/hashes@1.3.1/hkdf"; +import { sha256 } from "npm:@noble/hashes@1.3.1/sha256"; +import * as secp256k1 from "@noble/secp256k1"; +import { randomBytes } from "@noble/ciphers/webcrypto"; +import { xchacha20poly1305 } from "@noble/ciphers/chacha"; +import { bytesEqual, getCCNPrivateKey } from "./utils.ts"; +import { decodeBase64, encodeBase64 } from "jsr:@std/encoding/base64"; +import { + decryptUint8Array, + encryptionKey, + encryptUint8Array, +} from "./utils/encryption.ts"; + +type CCNId = string; +type Epoch = number; + +interface CCNState { + id: CCNId; + epoch: Epoch; + members: Map; + ccnKey: Uint8Array; + privateKey: NSec; + ratchetTree: RatchetNode[]; +} + +interface RatchetNode { + publicKey: NPub | null; + path: number[]; + parent: number | null; + children: number[]; +} + +interface EncryptedMessage { + sender: NPub; + epoch: Epoch; + ciphertext: Uint8Array; + nonce: Uint8Array; + signature: Uint8Array; +} + +interface Welcome { + ccnId: CCNId; + epoch: Epoch; + encryptedCCNState: Uint8Array; + pathSecret: Uint8Array; + inviterPublicKey: NPub; + nonce: Uint8Array; +} + +interface SerializedCCN { + version: number; + id: CCNId; + epoch: Epoch; + members: [NPub, NPub][]; + ccnKey: string; + privateKey: NSec; + ratchetTree: SerializedRatchetNode[]; +} + +interface SerializedRatchetNode { + publicKey: NPub | null; + path: number[]; + parent: number | null; + children: number[]; +} + +const textEncoder = new TextEncoder(); +const textDecoder = new TextDecoder(); + +function generateNonce(): Uint8Array { + return randomBytes(24); +} + +function deriveCCNKey( + secret: Uint8Array, + ccnId: CCNId, + epoch: Epoch, +): Uint8Array { + const info = textEncoder.encode(`MLS CCN Key ${ccnId} ${epoch}`); + return hkdf(sha256, secret, new Uint8Array(0), info, 32); +} + +function derivePathSecret(secret: Uint8Array, path: number[]): Uint8Array { + const pathStr = path.join("/"); + const info = textEncoder.encode(`MLS Path Secret ${pathStr}`); + return hkdf(sha256, secret, new Uint8Array(0), info, 32); +} + +interface UpdateMessage { + sender: NPub; + ccnId: CCNId; + epoch: Epoch; + pathSecrets: Map; + updatedPublicKeys: Map; + signature: Uint8Array; +} + +interface EncryptedPathSecret { + ciphertext: Uint8Array; + nonce: Uint8Array; +} + +export class MLS { + private ccns: Map = new Map(); + private identity: { publicKey: NPub; privateKey: NSec }; + + constructor(privateKey?: NSec) { + const privateKeyBytes = privateKey + ? nip19.decode(privateKey).data + : nostrTools.generateSecretKey(); + if (!privateKey) { + privateKey = nip19.nsecEncode(privateKeyBytes); + } + this.identity = { + privateKey: privateKey, + publicKey: nip19.npubEncode( + nostrTools.getPublicKey(privateKeyBytes), + ), + }; + } + + get memberId(): NPub { + return nip19.npubEncode(nostrTools.getPublicKey( + nip19.decode(this.identity.privateKey).data, + )); + } + + createCCN(ccnId: CCNId): CCNId { + const secret = randomBytes(32); + const epoch = 0; + const ccnKey = deriveCCNKey(secret, ccnId, epoch); + + const ratchetTree: RatchetNode[] = [ + { + publicKey: this.identity.publicKey, + path: [0], + parent: null, + children: [], + }, + ]; + + const ccnState: CCNState = { + id: ccnId, + epoch, + members: new Map([[this.memberId, this.identity.publicKey]]), + ccnKey, + privateKey: this.identity.privateKey, + ratchetTree, + }; + + this.ccns.set(ccnId, ccnState); + return ccnId; + } + + serializeCCN(ccnId: CCNId) { + const CCN = this.ccns.get(ccnId); + if (!CCN) { + throw new Error(`CCN ${ccnId} not found`); + } + const serializedCCN: SerializedCCN = { + version: 1, // For future compatibility + id: CCN.id, + epoch: CCN.epoch, + members: Array.from(CCN.members.entries()), + ccnKey: encodeBase64(CCN.ccnKey), + privateKey: CCN.privateKey, + ratchetTree: CCN.ratchetTree, + }; + const json = JSON.stringify(serializedCCN); + const encrypted = encryptUint8Array( + textEncoder.encode(json), + encryptionKey, + ); + return encodeBase64(encrypted); + } + + deserializeCCN(serialized: string) { + const encrypted = decodeBase64(serialized); + const decrypted = decryptUint8Array(encrypted, encryptionKey); + const json = textDecoder.decode(decrypted); + const serializedCCN = JSON.parse(json) as SerializedCCN; + + if (serializedCCN.version !== 1) { + throw new Error( + `Unknown CCN serialization version: ${serializedCCN.version}`, + ); + } + + this.ccns.set( + serializedCCN.id, + { + id: serializedCCN.id, + epoch: serializedCCN.epoch, + members: new Map(serializedCCN.members), + ccnKey: decodeBase64(serializedCCN.ccnKey), + privateKey: serializedCCN.privateKey, + ratchetTree: serializedCCN.ratchetTree, + }, + ); + } + + addMember( + ccnId: CCNId, + memberId: NPub, + ): Welcome | null { + const CCN = this.ccns.get(ccnId); + if (!CCN) return null; + + CCN.epoch += 1; + CCN.members.set(memberId, memberId); + + const newNodeIndex = CCN.ratchetTree.length; + CCN.ratchetTree.push({ + publicKey: memberId, + path: [newNodeIndex], + parent: null, + children: [], + }); + + const newSecret = randomBytes(32); + CCN.ccnKey = deriveCCNKey(newSecret, ccnId, CCN.epoch); + + const pathSecret = derivePathSecret(newSecret, [newNodeIndex]); + const serializedState = JSON.stringify({ + id: CCN.id, + epoch: CCN.epoch, + members: Array.from(CCN.members.entries()), + ratchetTree: CCN.ratchetTree, + }); + const nonce = generateNonce(); + const sharedSecret = secp256k1.getSharedSecret( + this.identity.privateKey, + memberId, + true, + ).slice(1); // Remove the prefix byte + + const cipher = xchacha20poly1305(sharedSecret, nonce); + const encryptedCCNState = cipher.encrypt( + textEncoder.encode(serializedState), + ); + + const welcome: Welcome = { + ccnId, + epoch: CCN.epoch, + encryptedCCNState, + pathSecret, + inviterPublicKey: this.identity.publicKey, + nonce, + }; + + return welcome; + } + + joinCCN(welcome: Welcome): CCNId | null { + try { + const { + ccnId, + epoch, + encryptedCCNState, + pathSecret, + inviterPublicKey, + nonce, + } = welcome; + + const ccnKey = deriveCCNKey(pathSecret, ccnId, epoch); + + const sharedSecret = secp256k1.getSharedSecret( + this.identity.privateKey, + inviterPublicKey, + true, + ).slice(1); // Remove the prefix byte + + const decipher = xchacha20poly1305(sharedSecret, nonce); + const decryptedStateBytes = decipher.decrypt(encryptedCCNState); + const decryptedState = JSON.parse( + textDecoder.decode(decryptedStateBytes), + ); + + const members = new Map(decryptedState.members); + const ratchetTree = decryptedState.ratchetTree; + + const ccnState: CCNState = { + id: ccnId, + epoch, + members, + ccnKey, + privateKey: this.identity.privateKey, + ratchetTree, + }; + + this.ccns.set(ccnId, ccnState); + return ccnId; + } catch (error) { + console.error("Failed to join ccn:", error); + return null; + } + } + + encryptMessage(ccnId: CCNId, plaintext: string): EncryptedMessage | null { + const CCN = this.ccns.get(ccnId); + if (!CCN) return null; + + const nonce = generateNonce(); + const cipher = xchacha20poly1305(CCN.ccnKey, nonce); + const ciphertext = cipher.encrypt(textEncoder.encode(plaintext)); + + const messageToSign = new Uint8Array([ + ...textEncoder.encode(ccnId), + ...new Uint8Array(new BigUint64Array([BigInt(CCN.epoch)]).buffer), + ...ciphertext, + ...nonce, + ]); + + const messageHash = sha256(messageToSign); + const signature = secp256k1.sign(messageHash, this.identity.privateKey); + + return { + sender: this.memberId, + epoch: CCN.epoch, + ciphertext, + nonce, + signature: signature.toCompactRawBytes(), + }; + } + + decryptMessage(ccnId: CCNId, message: EncryptedMessage): string | null { + const CCN = this.ccns.get(ccnId); + if (!CCN) return null; + + if (message.epoch !== CCN.epoch) { + console.error("Message from wrong epoch"); + return null; + } + + const senderPublicKey = CCN.members.get(message.sender); + if (!senderPublicKey) { + console.error("Message from unknown sender"); + return null; + } + + // Verify signature + const messageToVerify = new Uint8Array([ + ...textEncoder.encode(ccnId), + ...new Uint8Array(new BigUint64Array([BigInt(message.epoch)]).buffer), + ...message.ciphertext, + ...message.nonce, + ]); + + const messageHash = sha256(messageToVerify); + const isValid = secp256k1.verify( + message.signature, + messageHash, + senderPublicKey, + ); + + if (!isValid) { + console.error("Invalid message signature"); + return null; + } + + try { + const decipher = xchacha20poly1305(CCN.ccnKey, message.nonce); + const plaintext = decipher.decrypt(message.ciphertext); + return textDecoder.decode(plaintext); + } catch (error) { + console.error("Failed to decrypt message:", error); + return null; + } + } + + updateCCNKey(ccnId: CCNId): UpdateMessage | null { + const CCN = this.ccns.get(ccnId); + if (!CCN) return null; + + const newEpoch = CCN.epoch + 1; + const newRootSecret = randomBytes(32); + const updatedTree = [...CCN.ratchetTree]; + const myLeafIndex = updatedTree.findIndex((node) => + node.publicKey && + bytesEqual(node.publicKey, this.identity.publicKey) + ); + + if (myLeafIndex === -1) { + console.error("Cannot find self in ratchet tree"); + return null; + } + + const myPath: number[] = [myLeafIndex]; + let currentNode = myLeafIndex; + + while (updatedTree[currentNode].parent !== null) { + currentNode = updatedTree[currentNode].parent!; + myPath.unshift(currentNode); + } + + const pathSecrets: Uint8Array[] = [newRootSecret]; + const updatedPublicKeys = new Map(); + + for (let i = 0; i < myPath.length; i++) { + const nodeIndex = myPath[i]; + + let newPublicKey: NPub; + + if (i === 0) { + newPublicKey = nip19.npubEncode(nostrTools.getPublicKey(newRootSecret)); + } else { + const parentIndex = myPath[i - 1]; + const childSecret = derivePathSecret(pathSecrets[i - 1], [ + parentIndex, + nodeIndex, + ]); + pathSecrets.push(childSecret); + + newPublicKey = nip19.npubEncode(nostrTools.getPublicKey(childSecret)); + } + + updatedTree[nodeIndex].publicKey = newPublicKey; + updatedPublicKeys.set(nodeIndex, newPublicKey); + } + + const encryptedPathSecrets = new Map(); + + for (const [memberId, memberPublicKey] of CCN.members.entries()) { + if (memberId === this.memberId) continue; + + const memberLeafIndex = updatedTree.findIndex((node) => + node.publicKey && + bytesEqual(node.publicKey, memberPublicKey) + ); + + if (memberLeafIndex === -1) continue; + + let memberNode = memberLeafIndex; + const memberPath: number[] = [memberLeafIndex]; + + while (updatedTree[memberNode].parent !== null) { + memberNode = updatedTree[memberNode].parent!; + memberPath.unshift(memberNode); + } + + let commonAncestorIndex = 0; + while ( + commonAncestorIndex < myPath.length && + commonAncestorIndex < memberPath.length && + myPath[commonAncestorIndex] === memberPath[commonAncestorIndex] + ) { + commonAncestorIndex++; + } + + const secretToShare = pathSecrets[commonAncestorIndex - 1]; + + const nonce = generateNonce(); + const sharedSecret = secp256k1.getSharedSecret( + this.identity.privateKey, + memberPublicKey, + true, + ).slice(1); + + const cipher = xchacha20poly1305(sharedSecret, nonce); + const ciphertext = cipher.encrypt(secretToShare); + + encryptedPathSecrets.set(memberId, { ciphertext, nonce }); + } + + const updateData = new Uint8Array([ + ...textEncoder.encode(ccnId), + ...new Uint8Array(new BigUint64Array([BigInt(newEpoch)]).buffer), + ...textEncoder.encode( + JSON.stringify(Array.from(encryptedPathSecrets.entries())), + ), + ...textEncoder.encode( + JSON.stringify(Array.from(updatedPublicKeys.entries())), + ), + ]); + + const updateHash = sha256(updateData); + const signature = secp256k1.sign(updateHash, this.identity.privateKey); + + CCN.epoch = newEpoch; + CCN.ratchetTree = updatedTree; + CCN.ccnKey = deriveCCNKey(newRootSecret, ccnId, newEpoch); + + const updateMessage: UpdateMessage = { + sender: this.memberId, + ccnId, + epoch: newEpoch, + pathSecrets: encryptedPathSecrets, + updatedPublicKeys, + signature: signature.toCompactRawBytes(), + }; + + return updateMessage; + } + + processUpdate(updateMessage: UpdateMessage): boolean { + const { + sender, + ccnId, + epoch, + pathSecrets, + updatedPublicKeys, + signature, + } = updateMessage; + const CCN = this.ccns.get(ccnId); + if (!CCN) { + console.error("Unknown CCN"); + return false; + } + if (epoch !== CCN.epoch + 1) { + console.error("Invalid epoch in update"); + return false; + } + const senderPublicKey = CCN.members.get(sender); + if (!senderPublicKey) { + console.error("Update from unknown sender"); + return false; + } + + const updateData = new Uint8Array([ + ...textEncoder.encode(ccnId), + ...new Uint8Array(new BigUint64Array([BigInt(epoch)]).buffer), + ...textEncoder.encode(JSON.stringify(Array.from(pathSecrets.entries()))), + ...textEncoder.encode( + JSON.stringify(Array.from(updatedPublicKeys.entries())), + ), + ]); + + const updateHash = sha256(updateData); + const isValid = secp256k1.verify( + signature, + updateHash, + senderPublicKey, + ); + + if (!isValid) { + console.error("Invalid update signature"); + return false; + } + + const myPathSecret = pathSecrets.get(this.memberId); + if (!myPathSecret) { + console.error("No path secret for me in update"); + return false; + } + + try { + const sharedSecret = secp256k1.getSharedSecret( + this.identity.privateKey, + senderPublicKey, + true, + ).slice(1); + + const decipher = xchacha20poly1305(sharedSecret, myPathSecret.nonce); + const decryptedSecret = decipher.decrypt(myPathSecret.ciphertext); + + const myLeafIndex = CCN.ratchetTree.findIndex((node) => + node.publicKey && + bytesEqual(node.publicKey, this.identity.publicKey) + ); + + if (myLeafIndex === -1) { + console.error("Cannot find self in ratchet tree"); + return false; + } + + const myPath: number[] = [myLeafIndex]; + let currentNode = myLeafIndex; + + while (CCN.ratchetTree[currentNode].parent !== null) { + currentNode = CCN.ratchetTree[currentNode].parent!; + myPath.unshift(currentNode); + } + + const updatedTree = [...CCN.ratchetTree]; + for (const [nodeIndex, newPublicKey] of updatedPublicKeys.entries()) { + const index = Number(nodeIndex); + if (index >= 0 && index < updatedTree.length) { + updatedTree[index].publicKey = newPublicKey; + } + } + + CCN.epoch = epoch; + CCN.ratchetTree = updatedTree; + CCN.ccnKey = deriveCCNKey(decryptedSecret, ccnId, epoch); + + return true; + } catch (error) { + console.error("Failed to process update:", error); + return false; + } + } + + generateInvite(ccnId: CCNId, recipientPubkey: NPub): string { + const welcome = this.addMember( + ccnId, + recipientPubkey, + ); + + if (!welcome) { + throw new Error("Failed to create welcome message"); + } + + const ccn = this.ccns.get(ccnId); + if (!ccn) { + throw new Error("CCN not found"); + } + + const ccnPrivateKey = ccn.ccnKey; + const conversationKey = nostrTools.nip44.getConversationKey( + ccnPrivateKey, + recipientPubkey, + ); + + const invite = { + type: "ccn-invite", + version: 1, + ccnId, + welcome, + metadata: { + createdAt: Math.floor(Date.now() / 1000), + memberCount: ccn.members.size, + }, + }; + + const encryptedInvite = nostrTools.nip44.encrypt( + JSON.stringify(invite), + conversationKey, + ); + + return `ccn:${ccnId}:${btoa(encryptedInvite)}`; + } + + acceptInvite(inviteString: string): CCNId | null { + try { + // Parse the invite string format: ccn:ccnId:encryptedData + const parts = inviteString.split(":"); + if (parts.length !== 3 || parts[0] !== "ccn") { + throw new Error("Invalid invite format"); + } + + const ccnId = parts[1]; + const encryptedInvite = atob(parts[2]); + + const parsedData = JSON.parse(nostrTools.nip44.decrypt( + encryptedInvite, + nip19.decode<"nsec">(this.identity.privateKey).data, + )); + + if (parsedData.type !== "ccn-invite" || parsedData.version !== 1) { + throw new Error("Invalid invite type or version"); + } + + const welcome = parsedData.welcome; + + const joinResult = this.joinCCN(welcome); + + if (!joinResult) { + throw new Error("Failed to join CCN"); + } + + if (!this.ccns.has(ccnId)) { + throw new Error("CCN was not properly added to the ccns map"); + } + + return ccnId; + } catch (error) { + console.error("Failed to accept invite:", error); + return null; + } + } +} diff --git a/utils.ts b/utils.ts index 1ec0095..58fe189 100644 --- a/utils.ts +++ b/utils.ts @@ -8,6 +8,7 @@ import { encryptionKey, encryptUint8Array, } from "./utils/encryption.ts"; +import { NSec } from "@nostr/tools/nip19"; export function isLocalhost(req: Request): boolean { const url = new URL(req.url); @@ -61,9 +62,52 @@ export async function getCCNPubkey(): Promise { return ccnPublicKey; } +export async function getMLSPrivateKey(): Promise { + const mlsPrivPath = await getEveFilePath("mls.priv"); + const doWeHaveKey = await exists(mlsPrivPath); + if (doWeHaveKey) { + const encryptedPrivateKey = Deno.readTextFileSync(mlsPrivPath); + const decryptedPrivateKey = decryptUint8Array( + decodeBase64(encryptedPrivateKey), + encryptionKey, + ); + return nostrTools.nip19.nsecEncode(decryptedPrivateKey); + } + const mlsPrivateKey = nostrTools.generateSecretKey(); + const encryptedPrivateKey = encryptUint8Array(mlsPrivateKey, encryptionKey); + Deno.writeTextFileSync(mlsPrivPath, encodeBase64(encryptedPrivateKey)); + return nostrTools.nip19.nsecEncode(mlsPrivateKey); +} + export async function getCCNPrivateKey(): Promise { const encryptedPrivateKey = Deno.readTextFileSync( await getEveFilePath("ccn.priv"), ); return decryptUint8Array(decodeBase64(encryptedPrivateKey), encryptionKey); } + +/** + * Compares two byte-like objects in a constant-time manner to prevent timing attacks. + * + * @param a - First byte-like object to compare + * @param b - Second byte-like object to compare + * @returns boolean indicating whether the inputs contain identical bytes + */ +export function bytesEqual< + T extends Uint8Array | number[] | string, +>(a: T, b: T): boolean { + const aLength = a.length; + const bLength = b.length; + let result = aLength !== bLength ? 1 : 0; + const maxLength = Math.max(aLength, bLength); + for (let i = 0; i < maxLength; i++) { + const aVal = i < aLength + ? (typeof a === "string" ? a.charCodeAt(i) : a[i]) + : 0; + const bVal = i < bLength + ? (typeof b === "string" ? b.charCodeAt(i) : b[i]) + : 0; + result |= aVal ^ bVal; + } + return result === 0; +} From 7dbb4a522f47346d83fd76c28232255740641d92 Mon Sep 17 00:00:00 2001 From: Danny Morabito Date: Tue, 18 Mar 2025 15:06:13 +0000 Subject: [PATCH 02/11] replaceable-events (#1) --- index.ts | 175 +++++++++++++++++++++++++---- migrations/3-replaceableEvents.sql | 2 + utils.ts | 32 ++++++ 3 files changed, 187 insertions(+), 22 deletions(-) create mode 100644 migrations/3-replaceableEvents.sql diff --git a/index.ts b/index.ts index 7cfb67a..4186bc0 100644 --- a/index.ts +++ b/index.ts @@ -7,9 +7,13 @@ import type { import { getCCNPrivateKey, getCCNPubkey, + isAddressableEvent, isArray, + isCCNReplaceableEvent, isLocalhost, + isReplaceableEvent, isValidJSON, + parseATagQuery, randomTimeUpTo2DaysInThePast, } from "./utils.ts"; import * as nostrTools from "@nostr/tools"; @@ -171,6 +175,58 @@ function addEventToDb( if (existingEvent) throw new EventAlreadyExistsException(); try { db.run("BEGIN TRANSACTION"); + + if (isReplaceableEvent(decryptedEvent.kind)) { + sql` + UPDATE events + SET replaced = 1 + WHERE kind = ${decryptedEvent.kind} + AND pubkey = ${decryptedEvent.pubkey} + AND created_at < ${decryptedEvent.created_at} + `(db); + } + + if (isAddressableEvent(decryptedEvent.kind)) { + const dTag = decryptedEvent.tags.find((tag) => tag[0] === "d")?.[1]; + if (dTag) { + sql` + UPDATE events + SET replaced = 1 + WHERE kind = ${decryptedEvent.kind} + AND pubkey = ${decryptedEvent.pubkey} + AND created_at < ${decryptedEvent.created_at} + AND id IN ( + SELECT event_id FROM event_tags + WHERE tag_name = 'd' + AND tag_id IN ( + SELECT tag_id FROM event_tags_values + WHERE value_position = 1 + AND value = ${dTag} + ) + ) + `(db); + } + } + + if (isCCNReplaceableEvent(decryptedEvent.kind)) { + const dTag = decryptedEvent.tags.find((tag) => tag[0] === "d")?.[1]; + sql` + UPDATE events + SET replaced = 1 + WHERE kind = ${decryptedEvent.kind} + AND created_at < ${decryptedEvent.created_at} + AND id IN ( + SELECT event_id FROM event_tags + WHERE tag_name = 'd' + AND tag_id IN ( + SELECT tag_id FROM event_tags_values + WHERE value_position = 1 + AND value = ${dTag} + ) + ) + `(db); + } + sql` INSERT INTO events (id, original_id, pubkey, created_at, kind, content, sig, first_seen) VALUES ( ${decryptedEvent.id}, @@ -353,7 +409,7 @@ function handleRequest(connection: UserConnection, request: NostrClientREQ) { }`, ); - let query = sqlPartial`SELECT * FROM events`; + let query = sqlPartial`SELECT * FROM events WHERE replaced = 0`; const filtersAreNotEmpty = filters.some((filter) => { return Object.values(filter).some((value) => { @@ -362,7 +418,7 @@ function handleRequest(connection: UserConnection, request: NostrClientREQ) { }); if (filtersAreNotEmpty) { - query = mixQuery(query, sqlPartial`WHERE`); + query = mixQuery(query, sqlPartial`AND`); for (let i = 0; i < filters.length; i++) { // filters act as OR, filter groups act as AND @@ -431,22 +487,73 @@ function handleRequest(connection: UserConnection, request: NostrClientREQ) { const uniqueValues = [...new Set(value)]; query = mixQuery(query, sqlPartial`(`); for (let k = 0; k < uniqueValues.length; k++) { - const value = uniqueValues[k] as string; + const tagValue = uniqueValues[k] as string; + if (tag === "a") { + const aTagInfo = parseATagQuery(tagValue); + + if (aTagInfo.dTag && aTagInfo.dTag !== "") { + if (isCCNReplaceableEvent(aTagInfo.kind)) { + // CCN replaceable event reference + query = mixQuery( + query, + sqlPartial`id IN ( + SELECT e.id + FROM events e + JOIN event_tags t ON e.id = t.event_id + JOIN event_tags_values v ON t.tag_id = v.tag_id + WHERE e.kind = ${aTagInfo.kind} + AND t.tag_name = 'd' + AND v.value_position = 1 + AND v.value = ${aTagInfo.dTag} + )`, + ); + } else { + // Addressable event reference + query = mixQuery( + query, + sqlPartial`id IN ( + SELECT e.id + FROM events e + JOIN event_tags t ON e.id = t.event_id + JOIN event_tags_values v ON t.tag_id = v.tag_id + WHERE e.kind = ${aTagInfo.kind} + AND e.pubkey = ${aTagInfo.pubkey} + AND t.tag_name = 'd' + AND v.value_position = 1 + AND v.value = ${aTagInfo.dTag} + )`, + ); + } + } else { + // Replaceable event reference + query = mixQuery( + query, + sqlPartial`id IN ( + SELECT id + FROM events + WHERE kind = ${aTagInfo.kind} + AND pubkey = ${aTagInfo.pubkey} + )`, + ); + } + } else { + // Regular tag handling (unchanged) + query = mixQuery( + query, + sqlPartial`id IN ( + SELECT t.event_id + FROM event_tags t + WHERE t.tag_name = ${tag} + AND t.tag_id IN ( + SELECT v.tag_id + FROM event_tags_values v + WHERE v.value_position = 1 + AND v.value = ${tagValue} + ) + )`, + ); + } - query = mixQuery( - query, - sqlPartial`id IN ( - SELECT t.event_id - FROM event_tags t - WHERE t.tag_name = ${tag} - AND t.tag_id IN ( - SELECT v.tag_id - FROM event_tags_values v - WHERE v.value_position = 1 - AND v.value = ${value} - ) - )`, - ); if (k < uniqueValues.length - 1) { query = mixQuery(query, sqlPartial`OR`); } @@ -481,12 +588,36 @@ function handleRequest(connection: UserConnection, request: NostrClientREQ) { const rawTags = sql`SELECT * FROM event_tags_view WHERE event_id = ${ events[i].id }`(connection.db); - const tags: { [key: string]: string[] } = {}; - for (const item of rawTags) { - if (!tags[item.tag_name]) tags[item.tag_name] = [item.tag_name]; - tags[item.tag_name].push(item.tag_value); + const tagsByIndex = new Map; + }>(); + + for (const tag of rawTags) { + let tagData = tagsByIndex.get(tag.tag_index); + if (!tagData) { + tagData = { + name: tag.tag_name, + values: new Map(), + }; + tagsByIndex.set(tag.tag_index, tagData); + } + + tagData.values.set(tag.tag_value_position, tag.tag_value); } - const tagsArray = Object.values(tags); + + const tagsArray = Array.from(tagsByIndex.entries()) + .sort(([indexA], [indexB]) => indexA - indexB) + .map(([_, tagData]) => { + const { name, values } = tagData; + + return [ + name, + ...Array.from(values.entries()) + .sort(([posA], [posB]) => posA - posB) + .map(([_, value]) => value), + ]; + }); const event = { id: events[i].id, diff --git a/migrations/3-replaceableEvents.sql b/migrations/3-replaceableEvents.sql new file mode 100644 index 0000000..67ba8fc --- /dev/null +++ b/migrations/3-replaceableEvents.sql @@ -0,0 +1,2 @@ +ALTER TABLE events +ADD COLUMN replaced INTEGER NOT NULL DEFAULT 0; diff --git a/utils.ts b/utils.ts index 1ec0095..aecc1fd 100644 --- a/utils.ts +++ b/utils.ts @@ -67,3 +67,35 @@ export async function getCCNPrivateKey(): Promise { ); return decryptUint8Array(decodeBase64(encryptedPrivateKey), encryptionKey); } + +export function isReplaceableEvent(kind: number): boolean { + return (kind >= 10000 && kind < 20000) || kind === 0 || kind === 3; +} + +export function isAddressableEvent(kind: number): boolean { + return kind >= 30000 && kind < 40000; +} + +export function isRegularEvent(kind: number): boolean { + return (kind >= 1000 && kind < 10000) || + (kind >= 4 && kind < 45) || + kind === 1 || + kind === 2; +} + +export function isCCNReplaceableEvent(kind: number): boolean { + return (kind >= 60000 && kind < 65536) || kind === 0; +} + +export function parseATagQuery( + aTagValue: string, +): { kind: number; pubkey: string; dTag?: string } { + const parts = aTagValue.split(":"); + if (parts.length < 2) return { kind: 0, pubkey: "" }; + + return { + kind: Number.parseInt(parts[0], 10), + pubkey: parts[1], + dTag: parts.length > 2 ? parts[2] : undefined, + }; +} From 4bd08396695806826dbc22d3c959bd7d2d6b29a2 Mon Sep 17 00:00:00 2001 From: Danny Morabito Date: Wed, 19 Mar 2025 19:09:48 +0100 Subject: [PATCH 03/11] fix bug where profile can be replaced by anyone in the CCN --- utils.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/utils.ts b/utils.ts index aecc1fd..94e930c 100644 --- a/utils.ts +++ b/utils.ts @@ -84,7 +84,7 @@ export function isRegularEvent(kind: number): boolean { } export function isCCNReplaceableEvent(kind: number): boolean { - return (kind >= 60000 && kind < 65536) || kind === 0; + return (kind >= 60000 && kind < 65536); } export function parseATagQuery( From a4134fa416a8ef8ce5c49aff4f1d80f06ef58653 Mon Sep 17 00:00:00 2001 From: Danny Morabito Date: Mon, 24 Mar 2025 19:20:24 +0100 Subject: [PATCH 04/11] =?UTF-8?q?=F0=9F=94=84=20Synchronize=20Biome=20lint?= =?UTF-8?q?ing=20rules=20between=20relay=20and=20frontend?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ๐Ÿ› ๏ธ Apply identical Biome configuration from frontend to relay service ๐Ÿงน Ensure consistent code formatting and quality standards across components ๐Ÿ“ Maintain unified development experience throughout the project --- biome.json | 44 ++++++++ deno.json | 13 +-- deno.lock | 40 ++++++++ index.ts | 240 ++++++++++++++++++++++---------------------- utils.ts | 47 +++++---- utils/encryption.ts | 8 +- utils/files.ts | 12 +-- utils/logs.ts | 56 +++++------ utils/queries.ts | 8 +- 9 files changed, 273 insertions(+), 195 deletions(-) create mode 100644 biome.json diff --git a/biome.json b/biome.json new file mode 100644 index 0000000..4101319 --- /dev/null +++ b/biome.json @@ -0,0 +1,44 @@ +{ + "$schema": "https://biomejs.dev/schemas/1.9.4/schema.json", + "files": { + "include": ["index.ts", "**/*.ts"] + }, + "vcs": { + "enabled": true, + "clientKind": "git", + "useIgnoreFile": true + }, + "linter": { + "enabled": true, + "rules": { + "style": { + "noNonNullAssertion": "off", + "useNodejsImportProtocol": "warn" + }, + "complexity": { + "useLiteralKeys": "off" + } + } + }, + "formatter": { + "enabled": true, + "formatWithErrors": true, + "ignore": [], + "attributePosition": "auto", + "indentStyle": "space", + "indentWidth": 2, + "lineWidth": 80, + "lineEnding": "lf" + }, + "javascript": { + "formatter": { + "arrowParentheses": "always", + "bracketSameLine": true, + "bracketSpacing": true, + "quoteStyle": "single", + "quoteProperties": "asNeeded", + "semicolons": "always", + "trailingCommas": "all" + } + } +} diff --git a/deno.json b/deno.json index d505ec8..2738627 100644 --- a/deno.json +++ b/deno.json @@ -1,8 +1,11 @@ { "tasks": { - "dev": "deno run --allow-read --allow-write --allow-net --allow-ffi --allow-env --env-file --watch index.ts" + "dev": "deno run --allow-read --allow-write --allow-net --allow-ffi --allow-env --env-file --watch index.ts", + "lint": "biome check", + "lint:fix": "biome check --write --unsafe" }, "imports": { + "@biomejs/biome": "npm:@biomejs/biome@^1.9.4", "@db/sqlite": "jsr:@db/sqlite@^0.12.0", "@noble/ciphers": "jsr:@noble/ciphers@^1.2.1", "@nostr/tools": "jsr:@nostr/tools@^2.10.4", @@ -12,13 +15,5 @@ "@std/fmt": "jsr:@std/fmt@^1.0.4", "@std/log": "jsr:@std/log@^0.224.13", "@types/deno": "npm:@types/deno@^2.0.0" - }, - "fmt": { - "indentWidth": 2, - "useTabs": false, - "lineWidth": 80, - "proseWrap": "always", - "semiColons": true, - "singleQuote": false } } diff --git a/deno.lock b/deno.lock index 21a17b3..6957956 100644 --- a/deno.lock +++ b/deno.lock @@ -30,6 +30,8 @@ "jsr:@std/path@0.217": "0.217.0", "jsr:@std/path@0.221": "0.221.0", "jsr:@std/path@^1.0.8": "1.0.8", + "npm:@biomejs/biome@1.9.4": "1.9.4", + "npm:@biomejs/biome@^1.9.4": "1.9.4", "npm:@noble/ciphers@~0.5.1": "0.5.3", "npm:@noble/curves@1.2.0": "1.2.0", "npm:@noble/hashes@1.3.1": "1.3.1", @@ -168,6 +170,43 @@ } }, "npm": { + "@biomejs/biome@1.9.4": { + "integrity": "sha512-1rkd7G70+o9KkTn5KLmDYXihGoTaIGO9PIIN2ZB7UJxFrWw04CZHPYiMRjYsaDvVV7hP1dYNRLxSANLaBFGpog==", + "dependencies": [ + "@biomejs/cli-darwin-arm64", + "@biomejs/cli-darwin-x64", + "@biomejs/cli-linux-arm64", + "@biomejs/cli-linux-arm64-musl", + "@biomejs/cli-linux-x64", + "@biomejs/cli-linux-x64-musl", + "@biomejs/cli-win32-arm64", + "@biomejs/cli-win32-x64" + ] + }, + "@biomejs/cli-darwin-arm64@1.9.4": { + "integrity": "sha512-bFBsPWrNvkdKrNCYeAp+xo2HecOGPAy9WyNyB/jKnnedgzl4W4Hb9ZMzYNbf8dMCGmUdSavlYHiR01QaYR58cw==" + }, + "@biomejs/cli-darwin-x64@1.9.4": { + "integrity": "sha512-ngYBh/+bEedqkSevPVhLP4QfVPCpb+4BBe2p7Xs32dBgs7rh9nY2AIYUL6BgLw1JVXV8GlpKmb/hNiuIxfPfZg==" + }, + "@biomejs/cli-linux-arm64-musl@1.9.4": { + "integrity": "sha512-v665Ct9WCRjGa8+kTr0CzApU0+XXtRgwmzIf1SeKSGAv+2scAlW6JR5PMFo6FzqqZ64Po79cKODKf3/AAmECqA==" + }, + "@biomejs/cli-linux-arm64@1.9.4": { + "integrity": "sha512-fJIW0+LYujdjUgJJuwesP4EjIBl/N/TcOX3IvIHJQNsAqvV2CHIogsmA94BPG6jZATS4Hi+xv4SkBBQSt1N4/g==" + }, + "@biomejs/cli-linux-x64-musl@1.9.4": { + "integrity": "sha512-gEhi/jSBhZ2m6wjV530Yy8+fNqG8PAinM3oV7CyO+6c3CEh16Eizm21uHVsyVBEB6RIM8JHIl6AGYCv6Q6Q9Tg==" + }, + "@biomejs/cli-linux-x64@1.9.4": { + "integrity": "sha512-lRCJv/Vi3Vlwmbd6K+oQ0KhLHMAysN8lXoCI7XeHlxaajk06u7G+UsFSO01NAs5iYuWKmVZjmiOzJ0OJmGsMwg==" + }, + "@biomejs/cli-win32-arm64@1.9.4": { + "integrity": "sha512-tlbhLk+WXZmgwoIKwHIHEBZUwxml7bRJgk0X2sPyNR3S93cdRq6XulAZRQJ17FYGGzWne0fgrXBKpl7l4M87Hg==" + }, + "@biomejs/cli-win32-x64@1.9.4": { + "integrity": "sha512-8Y5wMhVIPaWe6jw2H+KlEm4wP/f7EW3810ZLmDlrEEy5KvBsb9ECEfu/kMWD484ijfQ8+nIi0giMgu9g1UAuuA==" + }, "@noble/ciphers@0.5.3": { "integrity": "sha512-B0+6IIHiqEs3BPMT0hcRmHvEj2QHOLu+uwt+tqDDeVd0oyVzh7BPrDcPjRnV1PV/5LaknXJJQvOuRGR0zQJz+w==" }, @@ -272,6 +311,7 @@ "jsr:@std/encoding@^1.0.6", "jsr:@std/fmt@^1.0.4", "jsr:@std/log@~0.224.13", + "npm:@biomejs/biome@^1.9.4", "npm:@types/deno@2" ] } diff --git a/index.ts b/index.ts index 4186bc0..b33b149 100644 --- a/index.ts +++ b/index.ts @@ -1,9 +1,15 @@ -import { NSchema as n } from "jsr:@nostrify/nostrify"; +import { Database } from 'jsr:@db/sqlite'; +import { NSchema as n } from 'jsr:@nostrify/nostrify'; import type { NostrClientREQ, NostrEvent, NostrFilter, -} from "jsr:@nostrify/types"; +} from 'jsr:@nostrify/types'; +import { encodeBase64 } from 'jsr:@std/encoding@0.224/base64'; +import { randomBytes } from '@noble/ciphers/webcrypto'; +import * as nostrTools from '@nostr/tools'; +import { nip44 } from '@nostr/tools'; +import { MIN_POW, POW_TO_MINE } from './consts.ts'; import { getCCNPrivateKey, getCCNPubkey, @@ -15,56 +21,48 @@ import { isValidJSON, parseATagQuery, randomTimeUpTo2DaysInThePast, -} from "./utils.ts"; -import * as nostrTools from "@nostr/tools"; -import { nip44 } from "@nostr/tools"; -import { randomBytes } from "@noble/ciphers/webcrypto"; -import { encodeBase64 } from "jsr:@std/encoding@0.224/base64"; -import { Database } from "jsr:@db/sqlite"; -import { mixQuery, sql, sqlPartial } from "./utils/queries.ts"; -import { log, setupLogger } from "./utils/logs.ts"; -import { getEveFilePath } from "./utils/files.ts"; -import { MIN_POW, POW_TO_MINE } from "./consts.ts"; +} from './utils.ts'; +import { getEveFilePath } from './utils/files.ts'; +import { log, setupLogger } from './utils/logs.ts'; +import { mixQuery, sql, sqlPartial } from './utils/queries.ts'; await setupLogger(); -if (!Deno.env.has("ENCRYPTION_KEY")) { +if (!Deno.env.has('ENCRYPTION_KEY')) { log.error( - `Missing ENCRYPTION_KEY. Please set it in your env.\nA new one has been generated for you: ENCRYPTION_KEY="${ - encodeBase64( - randomBytes(32), - ) - }"`, + `Missing ENCRYPTION_KEY. Please set it in your env.\nA new one has been generated for you: ENCRYPTION_KEY="${encodeBase64( + randomBytes(32), + )}"`, ); Deno.exit(1); } -const db = new Database(await getEveFilePath("db")); +const db = new Database(await getEveFilePath('db')); const pool = new nostrTools.SimplePool(); const relays = [ - "wss://relay.arx-ccn.com/", - "wss://relay.dannymorabito.com/", - "wss://nos.lol/", - "wss://nostr.einundzwanzig.space/", - "wss://nostr.massmux.com/", - "wss://nostr.mom/", - "wss://nostr.wine/", - "wss://purplerelay.com/", - "wss://relay.damus.io/", - "wss://relay.goodmorningbitcoin.com/", - "wss://relay.lexingtonbitcoin.org/", - "wss://relay.nostr.band/", - "wss://relay.primal.net/", - "wss://relay.snort.social/", - "wss://strfry.iris.to/", - "wss://cache2.primal.net/v1", + 'wss://relay.arx-ccn.com/', + 'wss://relay.dannymorabito.com/', + 'wss://nos.lol/', + 'wss://nostr.einundzwanzig.space/', + 'wss://nostr.massmux.com/', + 'wss://nostr.mom/', + 'wss://nostr.wine/', + 'wss://purplerelay.com/', + 'wss://relay.damus.io/', + 'wss://relay.goodmorningbitcoin.com/', + 'wss://relay.lexingtonbitcoin.org/', + 'wss://relay.nostr.band/', + 'wss://relay.primal.net/', + 'wss://relay.snort.social/', + 'wss://strfry.iris.to/', + 'wss://cache2.primal.net/v1', ]; export function runMigrations(db: Database, latestVersion: number) { const migrations = Deno.readDirSync(`${import.meta.dirname}/migrations`); for (const migrationFile of migrations) { const migrationVersion = Number.parseInt( - migrationFile.name.split("-")[0], + migrationFile.name.split('-')[0], 10, ); @@ -76,34 +74,31 @@ export function runMigrations(db: Database, latestVersion: number) { const migrationSql = Deno.readTextFileSync( `${import.meta.dirname}/migrations/${migrationFile.name}`, ); - db.run("BEGIN TRANSACTION"); + db.run('BEGIN TRANSACTION'); try { db.run(migrationSql); const end = Date.now(); const durationMs = end - start; sql` - INSERT INTO migration_history (migration_version, migration_name, executed_at, duration_ms, status) VALUES (${migrationVersion}, ${migrationFile.name}, ${ - new Date().toISOString() - }, ${durationMs}, 'success'); + INSERT INTO migration_history (migration_version, migration_name, executed_at, duration_ms, status) VALUES (${migrationVersion}, ${migrationFile.name}, ${new Date().toISOString()}, ${durationMs}, 'success'); db.run("COMMIT TRANSACTION"); `(db); } catch (e) { - db.run("ROLLBACK TRANSACTION"); - const error = e instanceof Error - ? e - : typeof e === "string" - ? new Error(e) - : new Error(JSON.stringify(e)); + db.run('ROLLBACK TRANSACTION'); + const error = + e instanceof Error + ? e + : typeof e === 'string' + ? new Error(e) + : new Error(JSON.stringify(e)); const end = Date.now(); const durationMs = end - start; sql` - INSERT INTO migration_history (migration_version, migration_name, executed_at, duration_ms, status, error_message) VALUES (${migrationVersion}, ${migrationFile.name}, ${ - new Date().toISOString() - }, ${durationMs}, 'failed', ${error.message}); + INSERT INTO migration_history (migration_version, migration_name, executed_at, duration_ms, status, error_message) VALUES (${migrationVersion}, ${migrationFile.name}, ${new Date().toISOString()}, ${durationMs}, 'failed', ${error.message}); `(db); throw e; } - db.run("END TRANSACTION"); + db.run('END TRANSACTION'); } } } @@ -111,8 +106,8 @@ export function runMigrations(db: Database, latestVersion: number) { async function createEncryptedEvent( event: nostrTools.VerifiedEvent, ): Promise { - if (!event.id) throw new Error("Event must have an ID"); - if (!event.sig) throw new Error("Event must be signed"); + if (!event.id) throw new Error('Event must have an ID'); + if (!event.sig) throw new Error('Event must be signed'); const ccnPubKey = await getCCNPubkey(); const ccnPrivateKey = await getCCNPrivateKey(); const randomPrivateKey = nostrTools.generateSecretKey(); @@ -129,7 +124,7 @@ async function createEncryptedEvent( kind: 1059, created_at: randomTimeUpTo2DaysInThePast(), content: nip44.encrypt(JSON.stringify(seal), conversationKey), - tags: [["p", ccnPubKey]], + tags: [['p', ccnPubKey]], pubkey: randomPrivateKeyPubKey, }; const minedGiftWrap = nostrTools.nip13.minePow(giftWrapTemplate, POW_TO_MINE); @@ -143,20 +138,20 @@ async function decryptEvent( const ccnPrivkey = await getCCNPrivateKey(); if (event.kind !== 1059) { - throw new Error("Cannot decrypt event -- not a gift wrap"); + throw new Error('Cannot decrypt event -- not a gift wrap'); } const pow = nostrTools.nip13.getPow(event.id); if (pow < MIN_POW) { - throw new Error("Cannot decrypt event -- PoW too low"); + throw new Error('Cannot decrypt event -- PoW too low'); } const conversationKey = nip44.getConversationKey(ccnPrivkey, event.pubkey); const seal = JSON.parse(nip44.decrypt(event.content, conversationKey)); - if (!seal) throw new Error("Cannot decrypt event -- no seal"); + if (!seal) throw new Error('Cannot decrypt event -- no seal'); if (seal.kind !== 13) { - throw new Error("Cannot decrypt event subevent -- not a seal"); + throw new Error('Cannot decrypt event subevent -- not a seal'); } const content = JSON.parse(nip44.decrypt(seal.content, conversationKey)); return content as nostrTools.VerifiedEvent; @@ -174,7 +169,7 @@ function addEventToDb( if (existingEvent) throw new EventAlreadyExistsException(); try { - db.run("BEGIN TRANSACTION"); + db.run('BEGIN TRANSACTION'); if (isReplaceableEvent(decryptedEvent.kind)) { sql` @@ -187,7 +182,7 @@ function addEventToDb( } if (isAddressableEvent(decryptedEvent.kind)) { - const dTag = decryptedEvent.tags.find((tag) => tag[0] === "d")?.[1]; + const dTag = decryptedEvent.tags.find((tag) => tag[0] === 'd')?.[1]; if (dTag) { sql` UPDATE events @@ -209,7 +204,7 @@ function addEventToDb( } if (isCCNReplaceableEvent(decryptedEvent.kind)) { - const dTag = decryptedEvent.tags.find((tag) => tag[0] === "d")?.[1]; + const dTag = decryptedEvent.tags.find((tag) => tag[0] === 'd')?.[1]; sql` UPDATE events SET replaced = 1 @@ -259,9 +254,9 @@ function addEventToDb( } } } - db.run("COMMIT TRANSACTION"); + db.run('COMMIT TRANSACTION'); } catch (e) { - db.run("ROLLBACK TRANSACTION"); + db.run('ROLLBACK TRANSACTION'); throw e; } } @@ -281,7 +276,8 @@ async function setupAndSubscribeToExternalEvents() { if (!isInitialized) runMigrations(db, -1); - const latestVersion = sql` + const latestVersion = + sql` SELECT migration_version FROM migration_history WHERE status = 'success' ORDER BY migration_version DESC LIMIT 1 `(db)[0]?.migration_version ?? -1; @@ -291,7 +287,7 @@ async function setupAndSubscribeToExternalEvents() { relays, [ { - "#p": [ccnPubkey], + '#p': [ccnPubkey], kinds: [1059], }, ], @@ -303,7 +299,7 @@ async function setupAndSubscribeToExternalEvents() { } if (knownOriginalEvents.indexOf(event.id) >= 0) return; if (!nostrTools.verifyEvent(event)) { - log.warn("Invalid event received"); + log.warn('Invalid event received'); return; } if (encryptedEventIsInDb(event)) return; @@ -328,20 +324,19 @@ async function setupAndSubscribeToExternalEvents() { const ccnCreationEventTemplate = { kind: 0, content: JSON.stringify({ - display_name: "New CCN", - name: "New CCN", + display_name: 'New CCN', + name: 'New CCN', bot: true, }), created_at: Math.floor(Date.now() / 1000), - tags: [["p", ccnPubkey]], + tags: [['p', ccnPubkey]], }; const ccnCreationEvent = nostrTools.finalizeEvent( ccnCreationEventTemplate, await getCCNPrivateKey(), ); - const encryptedCCNCreationEvent = await createEncryptedEvent( - ccnCreationEvent, - ); + const encryptedCCNCreationEvent = + await createEncryptedEvent(ccnCreationEvent); if (timerCleaned) return; // in case we get an event before the timer is cleaned await Promise.any(pool.publish(relays, encryptedCCNCreationEvent)); }, 10000); @@ -375,20 +370,20 @@ function filtersMatchingEvent( if (!filters) continue; const isMatching = filters.every((filter) => Object.entries(filter).every(([type, value]) => { - if (type === "ids") return value.includes(event.id); - if (type === "kinds") return value.includes(event.kind); - if (type === "authors") return value.includes(event.pubkey); - if (type === "since") return event.created_at >= value; - if (type === "until") return event.created_at <= value; - if (type === "limit") return event.created_at <= value; - if (type.startsWith("#")) { + if (type === 'ids') return value.includes(event.id); + if (type === 'kinds') return value.includes(event.kind); + if (type === 'authors') return value.includes(event.pubkey); + if (type === 'since') return event.created_at >= value; + if (type === 'until') return event.created_at <= value; + if (type === 'limit') return event.created_at <= value; + if (type.startsWith('#')) { const tagName = type.slice(1); return event.tags.some( (tag: string[]) => tag[0] === tagName && value.includes(tag[1]), ); } return false; - }) + }), ); if (isMatching) matching.push(subscription); } @@ -398,15 +393,13 @@ function filtersMatchingEvent( function handleRequest(connection: UserConnection, request: NostrClientREQ) { const [, subscriptionId, ...filters] = request; if (connection.subscriptions.has(subscriptionId)) { - return log.warn("Duplicate subscription ID"); + return log.warn('Duplicate subscription ID'); } log.info( - `New subscription: ${subscriptionId} with filters: ${ - JSON.stringify( - filters, - ) - }`, + `New subscription: ${subscriptionId} with filters: ${JSON.stringify( + filters, + )}`, ); let query = sqlPartial`SELECT * FROM events WHERE replaced = 0`; @@ -425,19 +418,19 @@ function handleRequest(connection: UserConnection, request: NostrClientREQ) { query = mixQuery(query, sqlPartial`(`); const filter = Object.entries(filters[i]).filter(([type, value]) => { - if (type === "ids") return value.length > 0; - if (type === "authors") return value.length > 0; - if (type === "kinds") return value.length > 0; - if (type.startsWith("#")) return value.length > 0; - if (type === "since") return value > 0; - if (type === "until") return value > 0; + if (type === 'ids') return value.length > 0; + if (type === 'authors') return value.length > 0; + if (type === 'kinds') return value.length > 0; + if (type.startsWith('#')) return value.length > 0; + if (type === 'since') return value > 0; + if (type === 'until') return value > 0; return false; }); for (let j = 0; j < filter.length; j++) { const [type, value] = filter[j]; - if (type === "ids") { + if (type === 'ids') { const uniqueIds = [...new Set(value)]; query = mixQuery(query, sqlPartial`id IN (`); for (let k = 0; k < uniqueIds.length; k++) { @@ -452,7 +445,7 @@ function handleRequest(connection: UserConnection, request: NostrClientREQ) { query = mixQuery(query, sqlPartial`)`); } - if (type === "authors") { + if (type === 'authors') { const uniqueAuthors = [...new Set(value)]; query = mixQuery(query, sqlPartial`pubkey IN (`); for (let k = 0; k < uniqueAuthors.length; k++) { @@ -467,7 +460,7 @@ function handleRequest(connection: UserConnection, request: NostrClientREQ) { query = mixQuery(query, sqlPartial`)`); } - if (type === "kinds") { + if (type === 'kinds') { const uniqueKinds = [...new Set(value)]; query = mixQuery(query, sqlPartial`kind IN (`); for (let k = 0; k < uniqueKinds.length; k++) { @@ -482,16 +475,16 @@ function handleRequest(connection: UserConnection, request: NostrClientREQ) { query = mixQuery(query, sqlPartial`)`); } - if (type.startsWith("#")) { + if (type.startsWith('#')) { const tag = type.slice(1); const uniqueValues = [...new Set(value)]; query = mixQuery(query, sqlPartial`(`); for (let k = 0; k < uniqueValues.length; k++) { const tagValue = uniqueValues[k] as string; - if (tag === "a") { + if (tag === 'a') { const aTagInfo = parseATagQuery(tagValue); - if (aTagInfo.dTag && aTagInfo.dTag !== "") { + if (aTagInfo.dTag && aTagInfo.dTag !== '') { if (isCCNReplaceableEvent(aTagInfo.kind)) { // CCN replaceable event reference query = mixQuery( @@ -561,11 +554,11 @@ function handleRequest(connection: UserConnection, request: NostrClientREQ) { query = mixQuery(query, sqlPartial`)`); } - if (type === "since") { + if (type === 'since') { query = mixQuery(query, sqlPartial`created_at >= ${value}`); } - if (type === "until") { + if (type === 'until') { query = mixQuery(query, sqlPartial`created_at <= ${value}`); } @@ -588,10 +581,13 @@ function handleRequest(connection: UserConnection, request: NostrClientREQ) { const rawTags = sql`SELECT * FROM event_tags_view WHERE event_id = ${ events[i].id }`(connection.db); - const tagsByIndex = new Map; - }>(); + const tagsByIndex = new Map< + number, + { + name: string; + values: Map; + } + >(); for (const tag of rawTags) { let tagData = tagsByIndex.get(tag.tag_index); @@ -629,9 +625,9 @@ function handleRequest(connection: UserConnection, request: NostrClientREQ) { sig: events[i].sig, }; - connection.socket.send(JSON.stringify(["EVENT", subscriptionId, event])); + connection.socket.send(JSON.stringify(['EVENT', subscriptionId, event])); } - connection.socket.send(JSON.stringify(["EOSE", subscriptionId])); + connection.socket.send(JSON.stringify(['EOSE', subscriptionId])); connection.subscriptions.set(subscriptionId, filters); } @@ -642,8 +638,8 @@ async function handleEvent( ) { const valid = nostrTools.verifyEvent(event); if (!valid) { - connection.socket.send(JSON.stringify(["NOTICE", "Invalid event"])); - return log.warn("Invalid event"); + connection.socket.send(JSON.stringify(['NOTICE', 'Invalid event'])); + return log.warn('Invalid event'); } const encryptedEvent = await createEncryptedEvent(event); @@ -651,19 +647,19 @@ async function handleEvent( addEventToDb(event, encryptedEvent); } catch (e) { if (e instanceof EventAlreadyExistsException) { - log.warn("Event already exists"); + log.warn('Event already exists'); return; } } await Promise.any(pool.publish(relays, encryptedEvent)); - connection.socket.send(JSON.stringify(["OK", event.id, true, "Event added"])); + connection.socket.send(JSON.stringify(['OK', event.id, true, 'Event added'])); const filtersThatMatchEvent = filtersMatchingEvent(event, connection); for (let i = 0; i < filtersThatMatchEvent.length; i++) { const filter = filtersThatMatchEvent[i]; - connection.socket.send(JSON.stringify(["EVENT", filter, event])); + connection.socket.send(JSON.stringify(['EVENT', filter, event])); } } @@ -680,10 +676,10 @@ function handleClose(connection: UserConnection, subscriptionId: string) { Deno.serve({ port: 6942, handler: (request) => { - if (request.headers.get("upgrade") === "websocket") { + if (request.headers.get('upgrade') === 'websocket') { if (!isLocalhost(request)) { return new Response( - "Forbidden. Please read the Arx-CCN documentation for more information on how to interact with the relay.", + 'Forbidden. Please read the Arx-CCN documentation for more information on how to interact with the relay.', { status: 403 }, ); } @@ -692,31 +688,31 @@ Deno.serve({ const connection = new UserConnection(socket, new Map(), db); - socket.onopen = () => log.info("User connected"); + socket.onopen = () => log.info('User connected'); socket.onmessage = (event) => { log.debug(`Received: ${event.data}`); - if (typeof event.data !== "string" || !isValidJSON(event.data)) { - return log.warn("Invalid request"); + if (typeof event.data !== 'string' || !isValidJSON(event.data)) { + return log.warn('Invalid request'); } const data = JSON.parse(event.data); - if (!isArray(data)) return log.warn("Invalid request"); + if (!isArray(data)) return log.warn('Invalid request'); const msg = n.clientMsg().parse(data); switch (msg[0]) { - case "REQ": + case 'REQ': return handleRequest(connection, n.clientREQ().parse(data)); - case "EVENT": + case 'EVENT': return handleEvent(connection, n.clientEVENT().parse(data)[1]); - case "CLOSE": + case 'CLOSE': return handleClose(connection, n.clientCLOSE().parse(data)[1]); default: - return log.warn("Invalid request"); + return log.warn('Invalid request'); } }; - socket.onclose = () => log.info("User disconnected"); + socket.onclose = () => log.info('User disconnected'); return response; } - return new Response("Eve Relay"); + return new Response('Eve Relay'); }, }); diff --git a/utils.ts b/utils.ts index 94e930c..6b6b63f 100644 --- a/utils.ts +++ b/utils.ts @@ -1,19 +1,19 @@ -import { exists } from "jsr:@std/fs"; -import * as nostrTools from "@nostr/tools"; -import * as nip06 from "@nostr/tools/nip06"; -import { decodeBase64, encodeBase64 } from "jsr:@std/encoding@0.224/base64"; -import { getEveFilePath } from "./utils/files.ts"; +import { decodeBase64, encodeBase64 } from 'jsr:@std/encoding@0.224/base64'; +import { exists } from 'jsr:@std/fs'; +import * as nostrTools from '@nostr/tools'; +import * as nip06 from '@nostr/tools/nip06'; import { decryptUint8Array, - encryptionKey, encryptUint8Array, -} from "./utils/encryption.ts"; + encryptionKey, +} from './utils/encryption.ts'; +import { getEveFilePath } from './utils/files.ts'; export function isLocalhost(req: Request): boolean { const url = new URL(req.url); const hostname = url.hostname; return ( - hostname === "127.0.0.1" || hostname === "::1" || hostname === "localhost" + hostname === '127.0.0.1' || hostname === '::1' || hostname === 'localhost' ); } @@ -39,11 +39,12 @@ export function randomTimeUpTo2DaysInThePast() { } export async function getCCNPubkey(): Promise { - const ccnPubPath = await getEveFilePath("ccn.pub"); - const seedPath = await getEveFilePath("ccn.seed"); + const ccnPubPath = await getEveFilePath('ccn.pub'); + const seedPath = await getEveFilePath('ccn.seed'); const doWeHaveKey = await exists(ccnPubPath); if (doWeHaveKey) return Deno.readTextFileSync(ccnPubPath); - const ccnSeed = Deno.env.get("CCN_SEED") || + const ccnSeed = + Deno.env.get('CCN_SEED') || ((await exists(seedPath)) ? Deno.readTextFileSync(seedPath) : nip06.generateSeedWords()); @@ -53,7 +54,7 @@ export async function getCCNPubkey(): Promise { Deno.writeTextFileSync(ccnPubPath, ccnPublicKey); Deno.writeTextFileSync( - await getEveFilePath("ccn.priv"), + await getEveFilePath('ccn.priv'), encodeBase64(encryptedPrivateKey), ); Deno.writeTextFileSync(seedPath, ccnSeed); @@ -63,7 +64,7 @@ export async function getCCNPubkey(): Promise { export async function getCCNPrivateKey(): Promise { const encryptedPrivateKey = Deno.readTextFileSync( - await getEveFilePath("ccn.priv"), + await getEveFilePath('ccn.priv'), ); return decryptUint8Array(decodeBase64(encryptedPrivateKey), encryptionKey); } @@ -77,21 +78,25 @@ export function isAddressableEvent(kind: number): boolean { } export function isRegularEvent(kind: number): boolean { - return (kind >= 1000 && kind < 10000) || + return ( + (kind >= 1000 && kind < 10000) || (kind >= 4 && kind < 45) || kind === 1 || - kind === 2; + kind === 2 + ); } export function isCCNReplaceableEvent(kind: number): boolean { - return (kind >= 60000 && kind < 65536); + return kind >= 60000 && kind < 65536; } -export function parseATagQuery( - aTagValue: string, -): { kind: number; pubkey: string; dTag?: string } { - const parts = aTagValue.split(":"); - if (parts.length < 2) return { kind: 0, pubkey: "" }; +export function parseATagQuery(aTagValue: string): { + kind: number; + pubkey: string; + dTag?: string; +} { + const parts = aTagValue.split(':'); + if (parts.length < 2) return { kind: 0, pubkey: '' }; return { kind: Number.parseInt(parts[0], 10), diff --git a/utils/encryption.ts b/utils/encryption.ts index 9973c37..311b624 100644 --- a/utils/encryption.ts +++ b/utils/encryption.ts @@ -1,7 +1,7 @@ -import { xchacha20poly1305 } from "@noble/ciphers/chacha"; -import { managedNonce } from "@noble/ciphers/webcrypto"; -import { decodeBase64 } from "jsr:@std/encoding/base64"; -export const encryptionKey = decodeBase64(Deno.env.get("ENCRYPTION_KEY") || ""); +import { decodeBase64 } from 'jsr:@std/encoding/base64'; +import { xchacha20poly1305 } from '@noble/ciphers/chacha'; +import { managedNonce } from '@noble/ciphers/webcrypto'; +export const encryptionKey = decodeBase64(Deno.env.get('ENCRYPTION_KEY') || ''); /** * Encrypts a given Uint8Array using the XChaCha20-Poly1305 algorithm. diff --git a/utils/files.ts b/utils/files.ts index a51b6f5..f1cb209 100644 --- a/utils/files.ts +++ b/utils/files.ts @@ -1,4 +1,4 @@ -import { exists } from "jsr:@std/fs"; +import { exists } from 'jsr:@std/fs'; /** * Return the path to Eve's configuration directory and ensures its existence. @@ -14,13 +14,11 @@ import { exists } from "jsr:@std/fs"; export async function getEveConfigHome(): Promise { let storagePath: string; - if (Deno.build.os === "darwin") { - storagePath = `${ - Deno.env.get("HOME") - }/Library/Application Support/eve/arx/Eve`; + if (Deno.build.os === 'darwin') { + storagePath = `${Deno.env.get('HOME')}/Library/Application Support/eve/arx/Eve`; } else { - const xdgConfigHome = Deno.env.get("XDG_CONFIG_HOME") ?? - `${Deno.env.get("HOME")}/.config`; + const xdgConfigHome = + Deno.env.get('XDG_CONFIG_HOME') ?? `${Deno.env.get('HOME')}/.config`; storagePath = `${xdgConfigHome}/arx/Eve`; } if (!(await exists(storagePath))) { diff --git a/utils/logs.ts b/utils/logs.ts index 0e32f93..3e5a58f 100644 --- a/utils/logs.ts +++ b/utils/logs.ts @@ -1,59 +1,59 @@ -import * as colors from "jsr:@std/fmt@^1.0.4/colors"; -import * as log from "jsr:@std/log"; -import { getEveFilePath } from "./files.ts"; -export * as log from "jsr:@std/log"; +import * as colors from 'jsr:@std/fmt@^1.0.4/colors'; +import * as log from 'jsr:@std/log'; +import { getEveFilePath } from './files.ts'; +export * as log from 'jsr:@std/log'; export async function setupLogger() { const formatLevel = (level: number): string => { return ( { - 10: colors.gray("[DEBUG]"), - 20: colors.green("[INFO] "), - 30: colors.yellow("[WARN] "), - 40: colors.red("[ERROR]"), - 50: colors.bgRed("[FATAL]"), + 10: colors.gray('[DEBUG]'), + 20: colors.green('[INFO] '), + 30: colors.yellow('[WARN] '), + 40: colors.red('[ERROR]'), + 50: colors.bgRed('[FATAL]'), }[level] || `[LVL${level}]` ); }; const levelName = (level: number): string => { - return { - 10: "DEBUG", - 20: "INFO", - 30: "WARN", - 40: "ERROR", - 50: "FATAL", - }[level] || `LVL${level}`; + return ( + { + 10: 'DEBUG', + 20: 'INFO', + 30: 'WARN', + 40: 'ERROR', + 50: 'FATAL', + }[level] || `LVL${level}` + ); }; const formatArg = (arg: unknown): string => { - if (typeof arg === "object") return JSON.stringify(arg); + if (typeof arg === 'object') return JSON.stringify(arg); return String(arg); }; await log.setup({ handlers: { - console: new log.ConsoleHandler("DEBUG", { + console: new log.ConsoleHandler('DEBUG', { useColors: true, formatter: (record) => { const timestamp = new Date().toISOString(); - let msg = `${colors.dim(`[${timestamp}]`)} ${ - formatLevel(record.level) - } ${record.msg}`; + let msg = `${colors.dim(`[${timestamp}]`)} ${formatLevel(record.level)} ${record.msg}`; if (record.args.length > 0) { const args = record.args .map((arg, i) => `${colors.dim(`arg${i}:`)} ${formatArg(arg)}`) - .join(" "); - msg += ` ${colors.dim("|")} ${args}`; + .join(' '); + msg += ` ${colors.dim('|')} ${args}`; } return msg; }, }), - file: new log.FileHandler("DEBUG", { - filename: Deno.env.get("LOG_FILE") || - await getEveFilePath("eve-logs.jsonl"), + file: new log.FileHandler('DEBUG', { + filename: + Deno.env.get('LOG_FILE') || (await getEveFilePath('eve-logs.jsonl')), formatter: (record) => { const timestamp = new Date().toISOString(); return JSON.stringify({ @@ -67,8 +67,8 @@ export async function setupLogger() { }, loggers: { default: { - level: "DEBUG", - handlers: ["console", "file"], + level: 'DEBUG', + handlers: ['console', 'file'], }, }, }); diff --git a/utils/queries.ts b/utils/queries.ts index ddf7ebb..aedfa5e 100644 --- a/utils/queries.ts +++ b/utils/queries.ts @@ -1,4 +1,4 @@ -import type { BindValue, Database } from "@db/sqlite"; +import type { BindValue, Database } from '@db/sqlite'; /** * Construct a SQL query with placeholders for values. @@ -23,8 +23,8 @@ export function sqlPartial( ) { return { query: segments.reduce( - (acc, str, i) => acc + str + (i < values.length ? "?" : ""), - "", + (acc, str, i) => acc + str + (i < values.length ? '?' : ''), + '', ), values: values, }; @@ -72,7 +72,7 @@ export function mixQuery(...queries: { query: string; values: BindValue[] }[]) { query: `${acc.query} ${query}`, values: [...acc.values, ...values], }), - { query: "", values: [] }, + { query: '', values: [] }, ); return { query, values }; } From 89d9dc3cbeb0e7a1ee94ee42cff88e33debb994f Mon Sep 17 00:00:00 2001 From: Danny Morabito Date: Mon, 24 Mar 2025 20:14:52 +0100 Subject: [PATCH 05/11] =?UTF-8?q?=E2=9C=82=EF=B8=8F=20Implement=20message?= =?UTF-8?q?=20chunking=20mechanism=20for=20NIP-44=20size=20limit=20complia?= =?UTF-8?q?nce?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit This ensures all messages can be properly encrypted and transmitted regardless of size. Fixes issue #2 --- consts.ts | 24 ++++ eventEncryptionDecryption.ts | 174 +++++++++++++++++++++++++++++ index.ts | 100 ++++++----------- migrations/4-createChunksStore.sql | 13 +++ 4 files changed, 246 insertions(+), 65 deletions(-) create mode 100644 eventEncryptionDecryption.ts create mode 100644 migrations/4-createChunksStore.sql diff --git a/consts.ts b/consts.ts index cb2ce39..2b8235f 100644 --- a/consts.ts +++ b/consts.ts @@ -18,3 +18,27 @@ export const MIN_POW = 8; * - Difficulty 21: ~5-6 seconds */ export const POW_TO_MINE = 10; + +/** + * Maximum size of a note chunk in bytes. + * + * This value determines the maximum size of a note that can be encrypted and + * sent in a single chunk. + */ +export const MAX_CHUNK_SIZE = 32768; + +/** + * Interval for cleaning up expired note chunks in milliseconds. + * + * This value determines how often the relay will check for and remove expired + * note chunks from the database. + */ +export const CHUNK_CLEANUP_INTERVAL = 1000 * 60 * 60; + +/** + * Maximum age of a note chunk in milliseconds. + * + * This value determines the maximum duration a note chunk can remain in the + * database before it is considered expired and eligible for cleanup. + */ +export const CHUNK_MAX_AGE = 1000 * 60 * 60 * 24; diff --git a/eventEncryptionDecryption.ts b/eventEncryptionDecryption.ts new file mode 100644 index 0000000..d77e2f5 --- /dev/null +++ b/eventEncryptionDecryption.ts @@ -0,0 +1,174 @@ +import type { Database } from '@db/sqlite'; +import * as nostrTools from '@nostr/tools'; +import { nip44 } from '@nostr/tools'; +import { MAX_CHUNK_SIZE, MIN_POW, POW_TO_MINE } from './consts.ts'; +import { + getCCNPrivateKey, + getCCNPubkey, + randomTimeUpTo2DaysInThePast, +} from './utils.ts'; +import { sql } from './utils/queries.ts'; + +export class EventAlreadyExistsException extends Error {} +export class ChunkedEventReceived extends Error {} + +export async function createEncryptedEvent( + event: nostrTools.VerifiedEvent, +): Promise { + if (!event.id) throw new Error('Event must have an ID'); + if (!event.sig) throw new Error('Event must be signed'); + + const ccnPubKey = await getCCNPubkey(); + const ccnPrivateKey = await getCCNPrivateKey(); + + const eventJson = JSON.stringify(event); + if (eventJson.length <= MAX_CHUNK_SIZE) { + const randomPrivateKey = nostrTools.generateSecretKey(); + const randomPrivateKeyPubKey = nostrTools.getPublicKey(randomPrivateKey); + const conversationKey = nip44.getConversationKey( + randomPrivateKey, + ccnPubKey, + ); + const sealTemplate = { + kind: 13, + created_at: randomTimeUpTo2DaysInThePast(), + content: nip44.encrypt(eventJson, conversationKey), + tags: [], + }; + const seal = nostrTools.finalizeEvent(sealTemplate, ccnPrivateKey); + const giftWrapTemplate = { + kind: 1059, + created_at: randomTimeUpTo2DaysInThePast(), + content: nip44.encrypt(JSON.stringify(seal), conversationKey), + tags: [['p', ccnPubKey]], + pubkey: randomPrivateKeyPubKey, + }; + const minedGiftWrap = nostrTools.nip13.minePow( + giftWrapTemplate, + POW_TO_MINE, + ); + const giftWrap = nostrTools.finalizeEvent(minedGiftWrap, randomPrivateKey); + return giftWrap; + } + + const chunks: string[] = []; + for (let i = 0; i < eventJson.length; i += MAX_CHUNK_SIZE) + chunks.push(eventJson.slice(i, i + MAX_CHUNK_SIZE)); + + const messageId = crypto.randomUUID(); + const totalChunks = chunks.length; + + const encryptedChunks = []; + for (let i = 0; i < chunks.length; i++) { + const chunk = chunks[i]; + const randomPrivateKey = nostrTools.generateSecretKey(); + const randomPrivateKeyPubKey = nostrTools.getPublicKey(randomPrivateKey); + const conversationKey = nip44.getConversationKey( + randomPrivateKey, + ccnPubKey, + ); + + const sealTemplate = { + kind: 13, + created_at: randomTimeUpTo2DaysInThePast(), + content: nip44.encrypt(chunk, conversationKey), + tags: [['chunk', String(i), String(totalChunks), messageId]], + }; + + const seal = nostrTools.finalizeEvent(sealTemplate, ccnPrivateKey); + const giftWrapTemplate = { + kind: 1059, + created_at: randomTimeUpTo2DaysInThePast(), + content: nip44.encrypt(JSON.stringify(seal), conversationKey), + tags: [['p', ccnPubKey]], + pubkey: randomPrivateKeyPubKey, + }; + + const minedGiftWrap = nostrTools.nip13.minePow( + giftWrapTemplate, + POW_TO_MINE, + ); + encryptedChunks.push( + nostrTools.finalizeEvent(minedGiftWrap, randomPrivateKey), + ); + } + + return encryptedChunks; +} +export async function decryptEvent( + db: Database, + event: nostrTools.Event, +): Promise { + const ccnPrivkey = await getCCNPrivateKey(); + + if (event.kind !== 1059) { + throw new Error('Cannot decrypt event -- not a gift wrap'); + } + + const pow = nostrTools.nip13.getPow(event.id); + + if (pow < MIN_POW) { + throw new Error('Cannot decrypt event -- PoW too low'); + } + + const conversationKey = nip44.getConversationKey(ccnPrivkey, event.pubkey); + const seal = JSON.parse(nip44.decrypt(event.content, conversationKey)); + if (!seal) throw new Error('Cannot decrypt event -- no seal'); + if (seal.kind !== 13) { + throw new Error('Cannot decrypt event subevent -- not a seal'); + } + + const chunkTag = seal.tags.find((tag: string[]) => tag[0] === 'chunk'); + if (!chunkTag) { + const content = JSON.parse(nip44.decrypt(seal.content, conversationKey)); + return content as nostrTools.VerifiedEvent; + } + + const [_, chunkIndex, totalChunks, messageId] = chunkTag; + const chunk = nip44.decrypt(seal.content, conversationKey); + + try { + sql` + INSERT INTO event_chunks ( + message_id, + chunk_index, + total_chunks, + chunk_data, + conversation_key, + created_at + ) VALUES ( + ${messageId}, + ${Number(chunkIndex)}, + ${Number(totalChunks)}, + ${chunk}, + ${conversationKey}, + ${Math.floor(Date.now() / 1000)} + ) + `(db); + + const chunks = sql` + SELECT chunk_data + FROM event_chunks + WHERE message_id = ${messageId} + ORDER BY chunk_index ASC + `(db); + + if (chunks.length === Number(totalChunks)) { + const completeEventJson = chunks.map((c) => c.chunk_data).join(''); + + sql`DELETE FROM event_chunks WHERE message_id = ${messageId}`(db); + + return JSON.parse(completeEventJson) as nostrTools.VerifiedEvent; + } + + throw new ChunkedEventReceived( + `Chunked event received (${chunks.length}/${totalChunks}) - messageId: ${messageId}`, + ); + } catch (e) { + if (e instanceof Error && e.message.includes('UNIQUE constraint failed')) + throw new Error( + `Duplicate chunk received (${Number(chunkIndex) + 1}/${totalChunks}) - messageId: ${messageId}`, + ); + throw e; + } +} diff --git a/index.ts b/index.ts index b33b149..c3f110f 100644 --- a/index.ts +++ b/index.ts @@ -1,3 +1,5 @@ +import { randomBytes } from '@noble/ciphers/webcrypto'; +import * as nostrTools from '@nostr/tools'; import { Database } from 'jsr:@db/sqlite'; import { NSchema as n } from 'jsr:@nostrify/nostrify'; import type { @@ -6,10 +8,13 @@ import type { NostrFilter, } from 'jsr:@nostrify/types'; import { encodeBase64 } from 'jsr:@std/encoding@0.224/base64'; -import { randomBytes } from '@noble/ciphers/webcrypto'; -import * as nostrTools from '@nostr/tools'; -import { nip44 } from '@nostr/tools'; -import { MIN_POW, POW_TO_MINE } from './consts.ts'; +import { CHUNK_CLEANUP_INTERVAL, CHUNK_MAX_AGE } from './consts.ts'; +import { + ChunkedEventReceived, + EventAlreadyExistsException, + createEncryptedEvent, + decryptEvent, +} from './eventEncryptionDecryption.ts'; import { getCCNPrivateKey, getCCNPubkey, @@ -20,7 +25,6 @@ import { isReplaceableEvent, isValidJSON, parseATagQuery, - randomTimeUpTo2DaysInThePast, } from './utils.ts'; import { getEveFilePath } from './utils/files.ts'; import { log, setupLogger } from './utils/logs.ts'; @@ -103,62 +107,6 @@ export function runMigrations(db: Database, latestVersion: number) { } } -async function createEncryptedEvent( - event: nostrTools.VerifiedEvent, -): Promise { - if (!event.id) throw new Error('Event must have an ID'); - if (!event.sig) throw new Error('Event must be signed'); - const ccnPubKey = await getCCNPubkey(); - const ccnPrivateKey = await getCCNPrivateKey(); - const randomPrivateKey = nostrTools.generateSecretKey(); - const randomPrivateKeyPubKey = nostrTools.getPublicKey(randomPrivateKey); - const conversationKey = nip44.getConversationKey(randomPrivateKey, ccnPubKey); - const sealTemplate = { - kind: 13, - created_at: randomTimeUpTo2DaysInThePast(), - content: nip44.encrypt(JSON.stringify(event), conversationKey), - tags: [], - }; - const seal = nostrTools.finalizeEvent(sealTemplate, ccnPrivateKey); - const giftWrapTemplate = { - kind: 1059, - created_at: randomTimeUpTo2DaysInThePast(), - content: nip44.encrypt(JSON.stringify(seal), conversationKey), - tags: [['p', ccnPubKey]], - pubkey: randomPrivateKeyPubKey, - }; - const minedGiftWrap = nostrTools.nip13.minePow(giftWrapTemplate, POW_TO_MINE); - const giftWrap = nostrTools.finalizeEvent(minedGiftWrap, randomPrivateKey); - return giftWrap; -} - -async function decryptEvent( - event: nostrTools.Event, -): Promise { - const ccnPrivkey = await getCCNPrivateKey(); - - if (event.kind !== 1059) { - throw new Error('Cannot decrypt event -- not a gift wrap'); - } - - const pow = nostrTools.nip13.getPow(event.id); - - if (pow < MIN_POW) { - throw new Error('Cannot decrypt event -- PoW too low'); - } - - const conversationKey = nip44.getConversationKey(ccnPrivkey, event.pubkey); - const seal = JSON.parse(nip44.decrypt(event.content, conversationKey)); - if (!seal) throw new Error('Cannot decrypt event -- no seal'); - if (seal.kind !== 13) { - throw new Error('Cannot decrypt event subevent -- not a seal'); - } - const content = JSON.parse(nip44.decrypt(seal.content, conversationKey)); - return content as nostrTools.VerifiedEvent; -} - -class EventAlreadyExistsException extends Error {} - function addEventToDb( decryptedEvent: nostrTools.VerifiedEvent, encryptedEvent: nostrTools.VerifiedEvent, @@ -267,6 +215,11 @@ function encryptedEventIsInDb(event: nostrTools.VerifiedEvent) { `(db)[0]; } +function cleanupOldChunks() { + const cutoffTime = Math.floor((Date.now() - CHUNK_MAX_AGE) / 1000); + sql`DELETE FROM event_chunks WHERE created_at < ${cutoffTime}`(db); +} + async function setupAndSubscribeToExternalEvents() { const ccnPubkey = await getCCNPubkey(); @@ -303,11 +256,14 @@ async function setupAndSubscribeToExternalEvents() { return; } if (encryptedEventIsInDb(event)) return; - const decryptedEvent = await decryptEvent(event); try { + const decryptedEvent = await decryptEvent(db, event); addEventToDb(decryptedEvent, event); } catch (e) { if (e instanceof EventAlreadyExistsException) return; + if (e instanceof ChunkedEventReceived) { + return; + } } }, }, @@ -338,8 +294,15 @@ async function setupAndSubscribeToExternalEvents() { const encryptedCCNCreationEvent = await createEncryptedEvent(ccnCreationEvent); if (timerCleaned) return; // in case we get an event before the timer is cleaned - await Promise.any(pool.publish(relays, encryptedCCNCreationEvent)); + if (Array.isArray(encryptedCCNCreationEvent)) { + for (const event of encryptedCCNCreationEvent) + await Promise.any(pool.publish(relays, event)); + } else { + await Promise.any(pool.publish(relays, encryptedCCNCreationEvent)); + } }, 10000); + + setInterval(cleanupOldChunks, CHUNK_CLEANUP_INTERVAL); } await setupAndSubscribeToExternalEvents(); @@ -644,14 +607,21 @@ async function handleEvent( const encryptedEvent = await createEncryptedEvent(event); try { - addEventToDb(event, encryptedEvent); + if (Array.isArray(encryptedEvent)) { + await Promise.all( + encryptedEvent.map((chunk) => Promise.any(pool.publish(relays, chunk))), + ); + addEventToDb(event, encryptedEvent[0]); + } else { + addEventToDb(event, encryptedEvent); + await Promise.any(pool.publish(relays, encryptedEvent)); + } } catch (e) { if (e instanceof EventAlreadyExistsException) { log.warn('Event already exists'); return; } } - await Promise.any(pool.publish(relays, encryptedEvent)); connection.socket.send(JSON.stringify(['OK', event.id, true, 'Event added'])); diff --git a/migrations/4-createChunksStore.sql b/migrations/4-createChunksStore.sql new file mode 100644 index 0000000..d554cd4 --- /dev/null +++ b/migrations/4-createChunksStore.sql @@ -0,0 +1,13 @@ +CREATE TABLE event_chunks ( + chunk_id INTEGER PRIMARY KEY AUTOINCREMENT, + message_id TEXT NOT NULL, + chunk_index INTEGER NOT NULL, + total_chunks INTEGER NOT NULL, + chunk_data TEXT NOT NULL, + conversation_key TEXT NOT NULL, + created_at INTEGER NOT NULL, + UNIQUE(message_id, chunk_index) +); + +CREATE INDEX idx_event_chunks_message_id ON event_chunks(message_id); +CREATE INDEX idx_event_chunks_created_at ON event_chunks(created_at); \ No newline at end of file From 8906d8f7f79c239128c0010f11d81c807a3c57d1 Mon Sep 17 00:00:00 2001 From: Danny Morabito Date: Wed, 26 Mar 2025 19:27:33 +0100 Subject: [PATCH 06/11] make sure migrations always run from 0 to n --- index.ts | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/index.ts b/index.ts index c3f110f..f9cbd6b 100644 --- a/index.ts +++ b/index.ts @@ -63,7 +63,12 @@ const relays = [ ]; export function runMigrations(db: Database, latestVersion: number) { - const migrations = Deno.readDirSync(`${import.meta.dirname}/migrations`); + const migrations = [...Deno.readDirSync(`${import.meta.dirname}/migrations`)]; + migrations.sort((a, b) => { + const aVersion = Number.parseInt(a.name.split('-')[0], 10); + const bVersion = Number.parseInt(b.name.split('-')[0], 10); + return aVersion - bVersion; + }); for (const migrationFile of migrations) { const migrationVersion = Number.parseInt( migrationFile.name.split('-')[0], From a8ffce918ef2043a4b45b30df379ab8c4b2f2752 Mon Sep 17 00:00:00 2001 From: Danny Morabito Date: Wed, 9 Apr 2025 13:40:02 +0200 Subject: [PATCH 07/11] =?UTF-8?q?=E2=9C=A8=20Feat:=20Implement=20support?= =?UTF-8?q?=20for=20multiple=20CCNs?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Makefile | 14 ++ eventEncryptionDecryption.ts | 187 ++++++++++++------ index.ts | 367 +++++++++++++++++++++++++++-------- migrations/5-multiCCN.sql | 21 ++ public/landing.html | 212 ++++++++++++++++++++ utils.ts | 106 +++++++--- utils/option.ts | 40 ++++ 7 files changed, 778 insertions(+), 169 deletions(-) create mode 100644 Makefile create mode 100644 migrations/5-multiCCN.sql create mode 100644 public/landing.html create mode 100644 utils/option.ts diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..41f978e --- /dev/null +++ b/Makefile @@ -0,0 +1,14 @@ +TARGETS = x86_64-unknown-linux-gnu aarch64-unknown-linux-gnu x86_64-apple-darwin aarch64-apple-darwin + +.PHONY: all clean + +all: $(TARGETS:%=dist/relay-%) + +dist/relay-%: | dist/ + deno compile -A -r --target $* --include migrations --include public --no-lock --output $@ index.ts + +dist/: + mkdir -p dist + +clean: + rm -f dist/* \ No newline at end of file diff --git a/eventEncryptionDecryption.ts b/eventEncryptionDecryption.ts index d77e2f5..3ca4292 100644 --- a/eventEncryptionDecryption.ts +++ b/eventEncryptionDecryption.ts @@ -3,10 +3,12 @@ import * as nostrTools from '@nostr/tools'; import { nip44 } from '@nostr/tools'; import { MAX_CHUNK_SIZE, MIN_POW, POW_TO_MINE } from './consts.ts'; import { - getCCNPrivateKey, - getCCNPubkey, + getActiveCCN, + getAllCCNs, + getCCNPrivateKeyByPubkey, randomTimeUpTo2DaysInThePast, } from './utils.ts'; +import { None, type Option, Some, flatMap, map } from './utils/option.ts'; import { sql } from './utils/queries.ts'; export class EventAlreadyExistsException extends Error {} @@ -14,12 +16,16 @@ export class ChunkedEventReceived extends Error {} export async function createEncryptedEvent( event: nostrTools.VerifiedEvent, + db: Database, ): Promise { if (!event.id) throw new Error('Event must have an ID'); if (!event.sig) throw new Error('Event must be signed'); - const ccnPubKey = await getCCNPubkey(); - const ccnPrivateKey = await getCCNPrivateKey(); + const activeCCN = getActiveCCN(db); + if (!activeCCN) throw new Error('No active CCN found'); + + const ccnPubKey = activeCCN.pubkey; + const ccnPrivateKey = await getCCNPrivateKeyByPubkey(ccnPubKey); const eventJson = JSON.stringify(event); if (eventJson.length <= MAX_CHUNK_SIZE) { @@ -95,12 +101,101 @@ export async function createEncryptedEvent( return encryptedChunks; } + +/** + * Attempts to decrypt an event using a specific CCN private key + * @returns The decrypted event with CCN pubkey if successful, None otherwise + */ +function attemptDecryptWithKey( + event: nostrTools.Event, + ccnPrivkey: Uint8Array, + ccnPubkey: string, +): Option { + const conversationKey = nip44.getConversationKey(ccnPrivkey, event.pubkey); + const sealResult = map( + Some(nip44.decrypt(event.content, conversationKey)), + JSON.parse, + ); + + return flatMap(sealResult, (seal) => { + if (!seal || seal.kind !== 13) return None(); + + const chunkTag = seal.tags.find((tag: string[]) => tag[0] === 'chunk'); + if (!chunkTag) { + const contentResult = map( + Some(nip44.decrypt(seal.content, conversationKey)), + JSON.parse, + ); + return map(contentResult, (content) => ({ ...content, ccnPubkey })); + } + + return None(); + }); +} + +/** + * Handles a chunked message by storing it in the database and checking if all chunks are received + * @returns The complete decrypted event if all chunks are received, throws ChunkedEventReceived otherwise + */ +function handleChunkedMessage( + db: Database, + event: nostrTools.Event, + ccnPrivkey: Uint8Array, + ccnPubkey: string, +): nostrTools.VerifiedEvent { + const conversationKey = nip44.getConversationKey(ccnPrivkey, event.pubkey); + const sealResult = map( + Some(nip44.decrypt(event.content, conversationKey)), + JSON.parse, + ); + + const seal = sealResult.isSome ? sealResult.value : null; + if (!seal) { + throw new Error('Invalid chunked message format'); + } + + const chunkTag = seal.tags.find((tag: string[]) => tag[0] === 'chunk'); + if (!chunkTag) { + throw new Error('Invalid chunked message format'); + } + + const [_, chunkIndex, totalChunks, messageId] = chunkTag; + const chunk = nip44.decrypt(seal.content, conversationKey); + + const storedChunks = sql` + SELECT COUNT(*) as count + FROM event_chunks + WHERE message_id = ${messageId} + `(db)[0].count; + + sql` + INSERT INTO event_chunks (message_id, chunk_index, total_chunks, content, created_at, ccn_pubkey) + VALUES (${messageId}, ${chunkIndex}, ${totalChunks}, ${chunk}, ${Math.floor(Date.now() / 1000)}, ${ccnPubkey}) + `(db); + + if (storedChunks + 1 === Number(totalChunks)) { + const allChunks = sql` + SELECT * FROM event_chunks + WHERE message_id = ${messageId} + ORDER BY chunk_index + `(db); + + let fullContent = ''; + for (const chunk of allChunks) { + fullContent += chunk.content; + } + + const content = JSON.parse(fullContent); + return { ...content, ccnPubkey }; + } + + throw new ChunkedEventReceived(); +} + export async function decryptEvent( db: Database, event: nostrTools.Event, -): Promise { - const ccnPrivkey = await getCCNPrivateKey(); - +): Promise { if (event.kind !== 1059) { throw new Error('Cannot decrypt event -- not a gift wrap'); } @@ -111,64 +206,30 @@ export async function decryptEvent( throw new Error('Cannot decrypt event -- PoW too low'); } - const conversationKey = nip44.getConversationKey(ccnPrivkey, event.pubkey); - const seal = JSON.parse(nip44.decrypt(event.content, conversationKey)); - if (!seal) throw new Error('Cannot decrypt event -- no seal'); - if (seal.kind !== 13) { - throw new Error('Cannot decrypt event subevent -- not a seal'); + const allCCNs = getAllCCNs(db); + if (allCCNs.length === 0) { + throw new Error('No CCNs found'); } - const chunkTag = seal.tags.find((tag: string[]) => tag[0] === 'chunk'); - if (!chunkTag) { - const content = JSON.parse(nip44.decrypt(seal.content, conversationKey)); - return content as nostrTools.VerifiedEvent; - } - - const [_, chunkIndex, totalChunks, messageId] = chunkTag; - const chunk = nip44.decrypt(seal.content, conversationKey); - - try { - sql` - INSERT INTO event_chunks ( - message_id, - chunk_index, - total_chunks, - chunk_data, - conversation_key, - created_at - ) VALUES ( - ${messageId}, - ${Number(chunkIndex)}, - ${Number(totalChunks)}, - ${chunk}, - ${conversationKey}, - ${Math.floor(Date.now() / 1000)} - ) - `(db); - - const chunks = sql` - SELECT chunk_data - FROM event_chunks - WHERE message_id = ${messageId} - ORDER BY chunk_index ASC - `(db); - - if (chunks.length === Number(totalChunks)) { - const completeEventJson = chunks.map((c) => c.chunk_data).join(''); - - sql`DELETE FROM event_chunks WHERE message_id = ${messageId}`(db); - - return JSON.parse(completeEventJson) as nostrTools.VerifiedEvent; + for (const ccn of allCCNs) { + const ccnPrivkey = await getCCNPrivateKeyByPubkey(ccn.pubkey); + const decryptedEvent = attemptDecryptWithKey(event, ccnPrivkey, ccn.pubkey); + if (decryptedEvent.isSome) { + return { ...decryptedEvent.value, ccnPubkey: ccn.pubkey }; } - - throw new ChunkedEventReceived( - `Chunked event received (${chunks.length}/${totalChunks}) - messageId: ${messageId}`, - ); - } catch (e) { - if (e instanceof Error && e.message.includes('UNIQUE constraint failed')) - throw new Error( - `Duplicate chunk received (${Number(chunkIndex) + 1}/${totalChunks}) - messageId: ${messageId}`, - ); - throw e; } + + for (const ccn of allCCNs) { + const ccnPrivkey = await getCCNPrivateKeyByPubkey(ccn.pubkey); + try { + const chuncked = handleChunkedMessage(db, event, ccnPrivkey, ccn.pubkey); + return { ...chuncked, ccnPubkey: ccn.pubkey }; + } catch (e) { + if (e instanceof ChunkedEventReceived) { + throw e; + } + } + } + + throw new Error('Failed to decrypt event with any CCN key'); } diff --git a/index.ts b/index.ts index f9cbd6b..8f3a4f2 100644 --- a/index.ts +++ b/index.ts @@ -16,8 +16,9 @@ import { decryptEvent, } from './eventEncryptionDecryption.ts'; import { - getCCNPrivateKey, - getCCNPubkey, + createNewCCN, + getActiveCCN, + getAllCCNs, isAddressableEvent, isArray, isCCNReplaceableEvent, @@ -115,6 +116,7 @@ export function runMigrations(db: Database, latestVersion: number) { function addEventToDb( decryptedEvent: nostrTools.VerifiedEvent, encryptedEvent: nostrTools.VerifiedEvent, + ccnPubkey: string, ) { const existingEvent = sql` SELECT * FROM events WHERE id = ${decryptedEvent.id} @@ -131,6 +133,7 @@ function addEventToDb( WHERE kind = ${decryptedEvent.kind} AND pubkey = ${decryptedEvent.pubkey} AND created_at < ${decryptedEvent.created_at} + AND ccn_pubkey = ${ccnPubkey} `(db); } @@ -143,6 +146,7 @@ function addEventToDb( WHERE kind = ${decryptedEvent.kind} AND pubkey = ${decryptedEvent.pubkey} AND created_at < ${decryptedEvent.created_at} + AND ccn_pubkey = ${ccnPubkey} AND id IN ( SELECT event_id FROM event_tags WHERE tag_name = 'd' @@ -163,6 +167,7 @@ function addEventToDb( SET replaced = 1 WHERE kind = ${decryptedEvent.kind} AND created_at < ${decryptedEvent.created_at} + AND ccn_pubkey = ${ccnPubkey} AND id IN ( SELECT event_id FROM event_tags WHERE tag_name = 'd' @@ -176,7 +181,7 @@ function addEventToDb( } sql` - INSERT INTO events (id, original_id, pubkey, created_at, kind, content, sig, first_seen) VALUES ( + INSERT INTO events (id, original_id, pubkey, created_at, kind, content, sig, first_seen, ccn_pubkey) VALUES ( ${decryptedEvent.id}, ${encryptedEvent.id}, ${decryptedEvent.pubkey}, @@ -184,7 +189,8 @@ function addEventToDb( ${decryptedEvent.kind}, ${decryptedEvent.content}, ${decryptedEvent.sig}, - unixepoch() + unixepoch(), + ${ccnPubkey} ) `(db); if (decryptedEvent.tags) { @@ -225,9 +231,58 @@ function cleanupOldChunks() { sql`DELETE FROM event_chunks WHERE created_at < ${cutoffTime}`(db); } -async function setupAndSubscribeToExternalEvents() { - const ccnPubkey = await getCCNPubkey(); +let knownOriginalEventsCache: string[] = []; +function updateKnownEventsCache() { + knownOriginalEventsCache = sql`SELECT original_id FROM events`(db).flatMap( + (row) => row.original_id, + ); +} + +/** + * Creates a subscription event handler for processing encrypted events. + * This handler decrypts and adds valid events to the database. + * @param database The database instance to use + * @returns An event handler function + */ +function createSubscriptionEventHandler(database: Database) { + return async (event: nostrTools.Event) => { + if (knownOriginalEventsCache.indexOf(event.id) >= 0) return; + if (!nostrTools.verifyEvent(event)) { + log.warn('Invalid event received'); + return; + } + if (encryptedEventIsInDb(event)) return; + try { + const decryptedEvent = await decryptEvent(database, event); + addEventToDb(decryptedEvent, event, decryptedEvent.ccnPubkey); + updateKnownEventsCache(); + } catch (e) { + if (e instanceof EventAlreadyExistsException) return; + if (e instanceof ChunkedEventReceived) { + return; + } + } + }; +} + +/** + * Publishes an event to relays, handling both single events and chunked events + * @param encryptedEvent The encrypted event or array of chunked events + */ +async function publishToRelays( + encryptedEvent: nostrTools.Event | nostrTools.Event[], +): Promise { + if (Array.isArray(encryptedEvent)) { + for (const chunk of encryptedEvent) { + await Promise.any(pool.publish(relays, chunk)); + } + } else { + await Promise.any(pool.publish(relays, encryptedEvent)); + } +} + +function setupAndSubscribeToExternalEvents() { const isInitialized = sql` SELECT name FROM sqlite_master WHERE type='table' AND name='migration_history' `(db)[0]; @@ -241,72 +296,23 @@ async function setupAndSubscribeToExternalEvents() { runMigrations(db, latestVersion); + const allCCNs = sql`SELECT pubkey FROM ccns`(db); + const ccnPubkeys = allCCNs.map((ccn) => ccn.pubkey); + pool.subscribeMany( relays, [ { - '#p': [ccnPubkey], + '#p': ccnPubkeys, kinds: [1059], }, ], { - async onevent(event: nostrTools.Event) { - if (timer) { - timerCleaned = true; - clearTimeout(timer); - } - if (knownOriginalEvents.indexOf(event.id) >= 0) return; - if (!nostrTools.verifyEvent(event)) { - log.warn('Invalid event received'); - return; - } - if (encryptedEventIsInDb(event)) return; - try { - const decryptedEvent = await decryptEvent(db, event); - addEventToDb(decryptedEvent, event); - } catch (e) { - if (e instanceof EventAlreadyExistsException) return; - if (e instanceof ChunkedEventReceived) { - return; - } - } - }, + onevent: createSubscriptionEventHandler(db), }, ); - let timerCleaned = false; - - const knownOriginalEvents = sql`SELECT original_id FROM events`(db).flatMap( - (row) => row.original_id, - ); - - const timer = setTimeout(async () => { - // if nothing is found in 10 seconds, create a new CCN, TODO: change logic - const ccnCreationEventTemplate = { - kind: 0, - content: JSON.stringify({ - display_name: 'New CCN', - name: 'New CCN', - bot: true, - }), - created_at: Math.floor(Date.now() / 1000), - tags: [['p', ccnPubkey]], - }; - const ccnCreationEvent = nostrTools.finalizeEvent( - ccnCreationEventTemplate, - await getCCNPrivateKey(), - ); - const encryptedCCNCreationEvent = - await createEncryptedEvent(ccnCreationEvent); - if (timerCleaned) return; // in case we get an event before the timer is cleaned - if (Array.isArray(encryptedCCNCreationEvent)) { - for (const event of encryptedCCNCreationEvent) - await Promise.any(pool.publish(relays, event)); - } else { - await Promise.any(pool.publish(relays, encryptedCCNCreationEvent)); - } - }, 10000); - + updateKnownEventsCache(); setInterval(cleanupOldChunks, CHUNK_CLEANUP_INTERVAL); } @@ -326,6 +332,49 @@ class UserConnection { this.subscriptions = subscriptions; this.db = db; } + + /** + * Sends a response to the client + * @param responseArray The response array to send + */ + sendResponse(responseArray: unknown[]): void { + this.socket.send(JSON.stringify(responseArray)); + } + + /** + * Sends a notice to the client + * @param message The message to send + */ + sendNotice(message: string): void { + this.sendResponse(['NOTICE', message]); + } + + /** + * Sends an event to the client + * @param subscriptionId The subscription ID + * @param event The event to send + */ + sendEvent(subscriptionId: string, event: NostrEvent): void { + this.sendResponse(['EVENT', subscriptionId, event]); + } + + /** + * Sends an end of stored events message + * @param subscriptionId The subscription ID + */ + sendEOSE(subscriptionId: string): void { + this.sendResponse(['EOSE', subscriptionId]); + } + + /** + * Sends an OK response + * @param eventId The event ID + * @param success Whether the operation was successful + * @param message The message to send + */ + sendOK(eventId: string, success: boolean, message: string): void { + this.sendResponse(['OK', eventId, success, message]); + } } function filtersMatchingEvent( @@ -370,7 +419,13 @@ function handleRequest(connection: UserConnection, request: NostrClientREQ) { )}`, ); - let query = sqlPartial`SELECT * FROM events WHERE replaced = 0`; + const activeCCN = getActiveCCN(connection.db); + if (!activeCCN) { + connection.sendNotice('No active CCN found'); + return log.warn('No active CCN found'); + } + + let query = sqlPartial`SELECT * FROM events WHERE replaced = 0 AND ccn_pubkey = ${activeCCN.pubkey}`; const filtersAreNotEmpty = filters.some((filter) => { return Object.values(filter).some((value) => { @@ -593,9 +648,9 @@ function handleRequest(connection: UserConnection, request: NostrClientREQ) { sig: events[i].sig, }; - connection.socket.send(JSON.stringify(['EVENT', subscriptionId, event])); + connection.sendEvent(subscriptionId, event); } - connection.socket.send(JSON.stringify(['EOSE', subscriptionId])); + connection.sendEOSE(subscriptionId); connection.subscriptions.set(subscriptionId, filters); } @@ -606,20 +661,24 @@ async function handleEvent( ) { const valid = nostrTools.verifyEvent(event); if (!valid) { - connection.socket.send(JSON.stringify(['NOTICE', 'Invalid event'])); + connection.sendNotice('Invalid event'); return log.warn('Invalid event'); } - const encryptedEvent = await createEncryptedEvent(event); + const activeCCN = getActiveCCN(connection.db); + if (!activeCCN) { + connection.sendNotice('No active CCN found'); + return log.warn('No active CCN found'); + } + + const encryptedEvent = await createEncryptedEvent(event, connection.db); try { if (Array.isArray(encryptedEvent)) { - await Promise.all( - encryptedEvent.map((chunk) => Promise.any(pool.publish(relays, chunk))), - ); - addEventToDb(event, encryptedEvent[0]); + await publishToRelays(encryptedEvent); + addEventToDb(event, encryptedEvent[0], activeCCN.pubkey); } else { - addEventToDb(event, encryptedEvent); - await Promise.any(pool.publish(relays, encryptedEvent)); + addEventToDb(event, encryptedEvent, activeCCN.pubkey); + await publishToRelays(encryptedEvent); } } catch (e) { if (e instanceof EventAlreadyExistsException) { @@ -628,13 +687,13 @@ async function handleEvent( } } - connection.socket.send(JSON.stringify(['OK', event.id, true, 'Event added'])); + connection.sendOK(event.id, true, 'Event added'); const filtersThatMatchEvent = filtersMatchingEvent(event, connection); for (let i = 0; i < filtersThatMatchEvent.length; i++) { const filter = filtersThatMatchEvent[i]; - connection.socket.send(JSON.stringify(['EVENT', filter, event])); + connection.sendEvent(filter, event); } } @@ -648,6 +707,153 @@ function handleClose(connection: UserConnection, subscriptionId: string) { connection.subscriptions.delete(subscriptionId); } +/** + * Activates a CCN by setting it as the active one in the database + * @param database The database instance to use + * @param pubkey The public key of the CCN to activate + */ +function activateCCN(database: Database, pubkey: string): void { + sql`UPDATE ccns SET is_active = 0`(database); + sql`UPDATE ccns SET is_active = 1 WHERE pubkey = ${pubkey}`(database); +} + +/** + * Handles errors in socket operations, logs them and sends a notification to the client + * @param connection The WebSocket connection + * @param operation The operation that failed + * @param error The error that occurred + */ +function handleSocketError( + connection: UserConnection, + operation: string, + error: unknown, +): void { + const errorMessage = error instanceof Error ? error.message : 'Unknown error'; + log.error(`Error ${operation}: ${errorMessage}`); + connection.sendNotice(`Failed to ${operation}`); +} + +async function handleCreateCCN( + connection: UserConnection, + data: { name: string; seed?: string }, +): Promise { + try { + if (!data.name || typeof data.name !== 'string') { + connection.sendNotice('Name is required'); + return; + } + + const newCcn = await createNewCCN(connection.db, data.name, data.seed); + + activateCCN(connection.db, newCcn.pubkey); + + pool.subscribeMany( + relays, + [ + { + '#p': [newCcn.pubkey], + kinds: [1059], + }, + ], + { + onevent: createSubscriptionEventHandler(connection.db), + }, + ); + + connection.sendResponse([ + 'OK', + 'CCN CREATED', + true, + JSON.stringify({ + pubkey: newCcn.pubkey, + name: data.name, + }), + ]); + + log.info(`CCN created: ${data.name}`); + } catch (error: unknown) { + handleSocketError(connection, 'create CCN', error); + } +} + +function handleGetCCNs(connection: UserConnection): void { + try { + const ccns = getAllCCNs(connection.db); + connection.sendResponse(['OK', 'CCN LIST', true, JSON.stringify(ccns)]); + } catch (error: unknown) { + handleSocketError(connection, 'get CCNs', error); + } +} + +function handleActivateCCN( + connection: UserConnection, + data: { pubkey: string }, +): void { + try { + if (!data.pubkey || typeof data.pubkey !== 'string') { + connection.sendNotice('CCN pubkey is required'); + return; + } + + const ccnExists = sql` + SELECT COUNT(*) as count FROM ccns WHERE pubkey = ${data.pubkey} + `(connection.db)[0].count; + + if (ccnExists === 0) { + connection.sendNotice('CCN not found'); + return; + } + + for (const subscriptionId of connection.subscriptions.keys()) { + connection.sendResponse([ + 'CLOSED', + subscriptionId, + 'Subscription closed due to CCN activation', + ]); + } + + connection.subscriptions.clear(); + log.info('All subscriptions cleared due to CCN activation'); + + activateCCN(connection.db, data.pubkey); + + const activatedCCN = sql` + SELECT pubkey, name FROM ccns WHERE pubkey = ${data.pubkey} + `(connection.db)[0]; + + connection.sendResponse([ + 'OK', + 'CCN ACTIVATED', + true, + JSON.stringify(activatedCCN), + ]); + + log.info(`CCN activated: ${activatedCCN.name}`); + } catch (error: unknown) { + handleSocketError(connection, 'activate CCN', error); + } +} + +function handleCCNCommands( + connection: UserConnection, + command: string, + data: unknown, +) { + switch (command) { + case 'CREATE': + return handleCreateCCN( + connection, + data as { name: string; seed?: string }, + ); + case 'LIST': + return handleGetCCNs(connection); + case 'ACTIVATE': + return handleActivateCCN(connection, data as { pubkey: string }); + default: + return log.warn('Invalid CCN command'); + } +} + Deno.serve({ port: 6942, handler: (request) => { @@ -672,14 +878,16 @@ Deno.serve({ const data = JSON.parse(event.data); if (!isArray(data)) return log.warn('Invalid request'); - const msg = n.clientMsg().parse(data); - switch (msg[0]) { + const msgType = data[0]; + switch (msgType) { case 'REQ': return handleRequest(connection, n.clientREQ().parse(data)); case 'EVENT': return handleEvent(connection, n.clientEVENT().parse(data)[1]); case 'CLOSE': return handleClose(connection, n.clientCLOSE().parse(data)[1]); + case 'CCN': + return handleCCNCommands(connection, data[1] as string, data[2]); default: return log.warn('Invalid request'); } @@ -688,6 +896,11 @@ Deno.serve({ return response; } - return new Response('Eve Relay'); + return new Response( + Deno.readTextFileSync(`${import.meta.dirname}/public/landing.html`), + { + headers: { 'Content-Type': 'text/html' }, + }, + ); }, }); diff --git a/migrations/5-multiCCN.sql b/migrations/5-multiCCN.sql new file mode 100644 index 0000000..ef01788 --- /dev/null +++ b/migrations/5-multiCCN.sql @@ -0,0 +1,21 @@ +CREATE TABLE ccns ( + ccn_id TEXT PRIMARY KEY DEFAULT (lower(hex(randomblob(16)))), + pubkey TEXT NOT NULL UNIQUE, + name TEXT NOT NULL, + created_at INTEGER NOT NULL DEFAULT (unixepoch()), + is_active INTEGER NOT NULL DEFAULT 1 +); + +ALTER TABLE events +ADD COLUMN ccn_pubkey TEXT; + +CREATE INDEX idx_events_ccn_pubkey ON events(ccn_pubkey); + +ALTER TABLE event_chunks RENAME COLUMN chunk_data TO content; +ALTER TABLE event_chunks ADD COLUMN ccn_pubkey TEXT; +ALTER TABLE event_chunks DROP COLUMN conversation_key; +CREATE INDEX idx_event_chunks_ccn_pubkey ON event_chunks(ccn_pubkey); + +UPDATE ccns SET is_active = 0; +UPDATE ccns SET is_active = 1 +WHERE pubkey = (SELECT pubkey FROM ccns LIMIT 1); \ No newline at end of file diff --git a/public/landing.html b/public/landing.html new file mode 100644 index 0000000..d0642ae --- /dev/null +++ b/public/landing.html @@ -0,0 +1,212 @@ + + + + + + Eve Relay - Secure Nostr Relay with CCN + + + + +
+ +

Eve Relay

+

A secure and efficient Nostr relay with Closed Community Network (CCN) functionality

+
+ +
+
+ Important: This relay is designed for WebSocket connections only. HTTP requests are not supported for data operations. +
+ +

Connection Details

+

Connect to the relay using WebSocket:

+
ws://localhost:6942
+ +
+
+

Nostr Commands

+
    +
  • REQ - Subscribe to events
  • +
  • EVENT - Publish an event
  • +
  • CLOSE - Close a subscription
  • +
+
+ +
+

CCN Commands

+
    +
  • CCN CREATE - Create a new CCN
  • +
  • CCN LIST - List all active CCNs
  • +
  • CCN ACTIVATE - Activate a specific CCN
  • +
+
+
+ +

Documentation

+

For detailed information about Arx-CCN functionality and best practices, please refer to the official documentation.

+ View Documentation +
+ + \ No newline at end of file diff --git a/utils.ts b/utils.ts index 6b6b63f..fd83c36 100644 --- a/utils.ts +++ b/utils.ts @@ -1,13 +1,15 @@ -import { decodeBase64, encodeBase64 } from 'jsr:@std/encoding@0.224/base64'; -import { exists } from 'jsr:@std/fs'; import * as nostrTools from '@nostr/tools'; import * as nip06 from '@nostr/tools/nip06'; +import type { Database } from 'jsr:@db/sqlite'; +import { decodeBase64, encodeBase64 } from 'jsr:@std/encoding@0.224/base64'; +import { exists } from 'jsr:@std/fs'; import { decryptUint8Array, encryptUint8Array, encryptionKey, } from './utils/encryption.ts'; import { getEveFilePath } from './utils/files.ts'; +import { sql } from './utils/queries.ts'; export function isLocalhost(req: Request): boolean { const url = new URL(req.url); @@ -38,35 +40,66 @@ export function randomTimeUpTo2DaysInThePast() { ); } -export async function getCCNPubkey(): Promise { - const ccnPubPath = await getEveFilePath('ccn.pub'); - const seedPath = await getEveFilePath('ccn.seed'); - const doWeHaveKey = await exists(ccnPubPath); - if (doWeHaveKey) return Deno.readTextFileSync(ccnPubPath); - const ccnSeed = - Deno.env.get('CCN_SEED') || - ((await exists(seedPath)) - ? Deno.readTextFileSync(seedPath) - : nip06.generateSeedWords()); - const ccnPrivateKey = nip06.privateKeyFromSeedWords(ccnSeed); - const ccnPublicKey = nostrTools.getPublicKey(ccnPrivateKey); - const encryptedPrivateKey = encryptUint8Array(ccnPrivateKey, encryptionKey); - - Deno.writeTextFileSync(ccnPubPath, ccnPublicKey); - Deno.writeTextFileSync( - await getEveFilePath('ccn.priv'), - encodeBase64(encryptedPrivateKey), - ); - Deno.writeTextFileSync(seedPath, ccnSeed); - - return ccnPublicKey; +/** + * Get all CCNs from the database + */ +export function getAllCCNs(db: Database): { pubkey: string; name: string }[] { + return sql`SELECT pubkey, name FROM ccns`(db) as { + pubkey: string; + name: string; + }[]; } -export async function getCCNPrivateKey(): Promise { - const encryptedPrivateKey = Deno.readTextFileSync( - await getEveFilePath('ccn.priv'), - ); - return decryptUint8Array(decodeBase64(encryptedPrivateKey), encryptionKey); +/** + * Create a new CCN and store it in the database + * + * @param db - The database instance + * @param name - The name of the CCN + * @param seed - The seed words for the CCN + * @returns The public key and private key of the CCN + */ +export async function createNewCCN( + db: Database, + name: string, + seed?: string, +): Promise<{ pubkey: string; privkey: Uint8Array }> { + const ccnSeed = seed || nip06.generateSeedWords(); + const ccnPrivateKey = nip06.privateKeyFromSeedWords(ccnSeed); + const ccnPublicKey = nostrTools.getPublicKey(ccnPrivateKey); + + const ccnSeedPath = await getEveFilePath(`ccn_seeds/${ccnPublicKey}`); + const ccnPrivPath = await getEveFilePath(`ccn_keys/${ccnPublicKey}`); + + await Deno.mkdir(await getEveFilePath('ccn_seeds'), { recursive: true }); + await Deno.mkdir(await getEveFilePath('ccn_keys'), { recursive: true }); + + const encryptedPrivateKey = encryptUint8Array(ccnPrivateKey, encryptionKey); + + Deno.writeTextFileSync(ccnSeedPath, ccnSeed); + Deno.writeTextFileSync(ccnPrivPath, encodeBase64(encryptedPrivateKey)); + + sql`INSERT INTO ccns (pubkey, name) VALUES (${ccnPublicKey}, ${name})`(db); + + return { + pubkey: ccnPublicKey, + privkey: ccnPrivateKey, + }; +} + +/** + * Get the private key for a specific CCN + */ +export async function getCCNPrivateKeyByPubkey( + pubkey: string, +): Promise { + const ccnPrivPath = await getEveFilePath(`ccn_keys/${pubkey}`); + + if (await exists(ccnPrivPath)) { + const encryptedPrivateKey = Deno.readTextFileSync(ccnPrivPath); + return decryptUint8Array(decodeBase64(encryptedPrivateKey), encryptionKey); + } + + throw new Error(`CCN private key for ${pubkey} not found`); } export function isReplaceableEvent(kind: number): boolean { @@ -104,3 +137,18 @@ export function parseATagQuery(aTagValue: string): { dTag: parts.length > 2 ? parts[2] : undefined, }; } + +/** + * Get the single active CCN from the database + * @returns The active CCN or null if none is active + */ +export function getActiveCCN( + db: Database, +): { pubkey: string; name: string } | null { + const result = sql`SELECT pubkey, name FROM ccns WHERE is_active = 1 LIMIT 1`( + db, + ); + return result.length > 0 + ? (result[0] as { pubkey: string; name: string }) + : null; +} diff --git a/utils/option.ts b/utils/option.ts new file mode 100644 index 0000000..0add74e --- /dev/null +++ b/utils/option.ts @@ -0,0 +1,40 @@ +export type Option = + | { + value: T; + isSome: true; + } + | { + value: undefined; + isSome: false; + }; + +export function Some(value: T): Option { + return { value, isSome: true }; +} + +export function None(): Option { + return { value: undefined, isSome: false }; +} + +export function map(option: Option, fn: (value: T) => U): Option { + return option.isSome ? Some(fn(option.value)) : None(); +} + +export function flatMap( + option: Option, + fn: (value: T) => Option, +): Option { + return option.isSome ? fn(option.value) : None(); +} + +export function getOrElse(option: Option, defaultValue: T): T { + return option.isSome ? option.value : defaultValue; +} + +export function fold( + option: Option, + onNone: () => U, + onSome: (value: T) => U, +): U { + return option.isSome ? onSome(option.value) : onNone(); +} From 36c7401fa8702d9fc3be69c6d674f03b228ed068 Mon Sep 17 00:00:00 2001 From: Danny Morabito Date: Wed, 23 Apr 2025 18:13:29 +0200 Subject: [PATCH 08/11] CCN invitation and write permissions to CCN --- eventEncryptionDecryption.ts | 247 +++++++++++++++++++++-------------- index.ts | 211 ++++++++++++++++++++++++++++-- migrations/6-invitations.sql | 24 ++++ utils.ts | 8 ++ utils/invites.ts | 12 ++ 5 files changed, 395 insertions(+), 107 deletions(-) create mode 100644 migrations/6-invitations.sql create mode 100644 utils/invites.ts diff --git a/eventEncryptionDecryption.ts b/eventEncryptionDecryption.ts index 3ca4292..2553ee5 100644 --- a/eventEncryptionDecryption.ts +++ b/eventEncryptionDecryption.ts @@ -14,6 +14,71 @@ import { sql } from './utils/queries.ts'; export class EventAlreadyExistsException extends Error {} export class ChunkedEventReceived extends Error {} +export function createEncryptedEventForPubkey( + pubkey: string, + event: nostrTools.VerifiedEvent, +) { + const randomPrivateKey = nostrTools.generateSecretKey(); + const randomPrivateKeyPubKey = nostrTools.getPublicKey(randomPrivateKey); + const conversationKey = nip44.getConversationKey(randomPrivateKey, pubkey); + + const eventJson = JSON.stringify(event); + const encryptedEvent = nip44.encrypt(eventJson, conversationKey); + + const sealTemplate = { + kind: 13, + created_at: randomTimeUpTo2DaysInThePast(), + content: encryptedEvent, + tags: [], + }; + + const seal = nostrTools.finalizeEvent(sealTemplate, randomPrivateKey); + const giftWrapTemplate = { + kind: 1059, + created_at: randomTimeUpTo2DaysInThePast(), + content: nip44.encrypt(JSON.stringify(seal), conversationKey), + tags: [['p', pubkey]], + pubkey: randomPrivateKeyPubKey, + }; + const minedGiftWrap = nostrTools.nip13.minePow(giftWrapTemplate, POW_TO_MINE); + + const giftWrap = nostrTools.finalizeEvent(minedGiftWrap, randomPrivateKey); + return giftWrap; +} + +export function createEncryptedChunkForPubkey( + pubkey: string, + chunk: string, + chunkIndex: number, + totalChunks: number, + messageId: string, + privateKey: Uint8Array, +) { + const randomPrivateKey = nostrTools.generateSecretKey(); + const randomPrivateKeyPubKey = nostrTools.getPublicKey(randomPrivateKey); + const conversationKey = nip44.getConversationKey(randomPrivateKey, pubkey); + + const sealTemplate = { + kind: 13, + created_at: randomTimeUpTo2DaysInThePast(), + content: nip44.encrypt(chunk, conversationKey), + tags: [['chunk', String(chunkIndex), String(totalChunks), messageId]], + }; + + const seal = nostrTools.finalizeEvent(sealTemplate, privateKey); + const giftWrapTemplate = { + kind: 1059, + created_at: randomTimeUpTo2DaysInThePast(), + content: nip44.encrypt(JSON.stringify(seal), conversationKey), + tags: [['p', pubkey]], + pubkey: randomPrivateKeyPubKey, + }; + + const minedGiftWrap = nostrTools.nip13.minePow(giftWrapTemplate, POW_TO_MINE); + const giftWrap = nostrTools.finalizeEvent(minedGiftWrap, randomPrivateKey); + return giftWrap; +} + export async function createEncryptedEvent( event: nostrTools.VerifiedEvent, db: Database, @@ -29,32 +94,7 @@ export async function createEncryptedEvent( const eventJson = JSON.stringify(event); if (eventJson.length <= MAX_CHUNK_SIZE) { - const randomPrivateKey = nostrTools.generateSecretKey(); - const randomPrivateKeyPubKey = nostrTools.getPublicKey(randomPrivateKey); - const conversationKey = nip44.getConversationKey( - randomPrivateKey, - ccnPubKey, - ); - const sealTemplate = { - kind: 13, - created_at: randomTimeUpTo2DaysInThePast(), - content: nip44.encrypt(eventJson, conversationKey), - tags: [], - }; - const seal = nostrTools.finalizeEvent(sealTemplate, ccnPrivateKey); - const giftWrapTemplate = { - kind: 1059, - created_at: randomTimeUpTo2DaysInThePast(), - content: nip44.encrypt(JSON.stringify(seal), conversationKey), - tags: [['p', ccnPubKey]], - pubkey: randomPrivateKeyPubKey, - }; - const minedGiftWrap = nostrTools.nip13.minePow( - giftWrapTemplate, - POW_TO_MINE, - ); - const giftWrap = nostrTools.finalizeEvent(minedGiftWrap, randomPrivateKey); - return giftWrap; + return createEncryptedEventForPubkey(ccnPubKey, event); } const chunks: string[] = []; @@ -67,35 +107,15 @@ export async function createEncryptedEvent( const encryptedChunks = []; for (let i = 0; i < chunks.length; i++) { const chunk = chunks[i]; - const randomPrivateKey = nostrTools.generateSecretKey(); - const randomPrivateKeyPubKey = nostrTools.getPublicKey(randomPrivateKey); - const conversationKey = nip44.getConversationKey( - randomPrivateKey, - ccnPubKey, - ); - - const sealTemplate = { - kind: 13, - created_at: randomTimeUpTo2DaysInThePast(), - content: nip44.encrypt(chunk, conversationKey), - tags: [['chunk', String(i), String(totalChunks), messageId]], - }; - - const seal = nostrTools.finalizeEvent(sealTemplate, ccnPrivateKey); - const giftWrapTemplate = { - kind: 1059, - created_at: randomTimeUpTo2DaysInThePast(), - content: nip44.encrypt(JSON.stringify(seal), conversationKey), - tags: [['p', ccnPubKey]], - pubkey: randomPrivateKeyPubKey, - }; - - const minedGiftWrap = nostrTools.nip13.minePow( - giftWrapTemplate, - POW_TO_MINE, - ); encryptedChunks.push( - nostrTools.finalizeEvent(minedGiftWrap, randomPrivateKey), + createEncryptedChunkForPubkey( + ccnPubKey, + chunk, + i, + totalChunks, + messageId, + ccnPrivateKey, + ), ); } @@ -111,26 +131,30 @@ function attemptDecryptWithKey( ccnPrivkey: Uint8Array, ccnPubkey: string, ): Option { - const conversationKey = nip44.getConversationKey(ccnPrivkey, event.pubkey); - const sealResult = map( - Some(nip44.decrypt(event.content, conversationKey)), - JSON.parse, - ); + try { + const conversationKey = nip44.getConversationKey(ccnPrivkey, event.pubkey); + const sealResult = map( + Some(nip44.decrypt(event.content, conversationKey)), + JSON.parse, + ); - return flatMap(sealResult, (seal) => { - if (!seal || seal.kind !== 13) return None(); + return flatMap(sealResult, (seal) => { + if (!seal || seal.kind !== 13) return None(); - const chunkTag = seal.tags.find((tag: string[]) => tag[0] === 'chunk'); - if (!chunkTag) { - const contentResult = map( - Some(nip44.decrypt(seal.content, conversationKey)), - JSON.parse, - ); - return map(contentResult, (content) => ({ ...content, ccnPubkey })); - } + const chunkTag = seal.tags.find((tag: string[]) => tag[0] === 'chunk'); + if (!chunkTag) { + const contentResult = map( + Some(nip44.decrypt(seal.content, conversationKey)), + JSON.parse, + ); + return map(contentResult, (content) => ({ ...content, ccnPubkey })); + } + return None(); + }); + } catch { return None(); - }); + } } /** @@ -163,8 +187,8 @@ function handleChunkedMessage( const chunk = nip44.decrypt(seal.content, conversationKey); const storedChunks = sql` - SELECT COUNT(*) as count - FROM event_chunks + SELECT COUNT(*) as count + FROM event_chunks WHERE message_id = ${messageId} `(db)[0].count; @@ -175,8 +199,8 @@ function handleChunkedMessage( if (storedChunks + 1 === Number(totalChunks)) { const allChunks = sql` - SELECT * FROM event_chunks - WHERE message_id = ${messageId} + SELECT * FROM event_chunks + WHERE message_id = ${messageId} ORDER BY chunk_index `(db); @@ -200,34 +224,67 @@ export async function decryptEvent( throw new Error('Cannot decrypt event -- not a gift wrap'); } - const pow = nostrTools.nip13.getPow(event.id); - - if (pow < MIN_POW) { - throw new Error('Cannot decrypt event -- PoW too low'); - } - const allCCNs = getAllCCNs(db); if (allCCNs.length === 0) { throw new Error('No CCNs found'); } - for (const ccn of allCCNs) { - const ccnPrivkey = await getCCNPrivateKeyByPubkey(ccn.pubkey); - const decryptedEvent = attemptDecryptWithKey(event, ccnPrivkey, ccn.pubkey); - if (decryptedEvent.isSome) { - return { ...decryptedEvent.value, ccnPubkey: ccn.pubkey }; - } + const pow = nostrTools.nip13.getPow(event.id); + const isInvite = + event.tags.findIndex( + (tag: string[]) => tag[0] === 'type' && tag[1] === 'invite', + ) !== -1; + const eventDestination = event.tags.find( + (tag: string[]) => tag[0] === 'p', + )?.[1]; + + if (!eventDestination) { + throw new Error('Cannot decrypt event -- no destination'); } - for (const ccn of allCCNs) { - const ccnPrivkey = await getCCNPrivateKeyByPubkey(ccn.pubkey); - try { - const chuncked = handleChunkedMessage(db, event, ccnPrivkey, ccn.pubkey); - return { ...chuncked, ccnPubkey: ccn.pubkey }; - } catch (e) { - if (e instanceof ChunkedEventReceived) { - throw e; - } + if (isInvite) { + const ccnPrivkey = await getCCNPrivateKeyByPubkey(eventDestination); + const decryptedEvent = attemptDecryptWithKey( + event, + ccnPrivkey, + eventDestination, + ); + if (decryptedEvent.isSome) { + const recipient = decryptedEvent.value.tags.find( + (tag: string[]) => tag[0] === 'p', + )?.[1]; + if (recipient !== eventDestination) + throw new Error('Cannot decrypt invite'); + return { ...decryptedEvent.value, ccnPubkey: eventDestination }; + } + throw new Error('Cannot decrypt invite'); + } + + if (pow < MIN_POW) { + throw new Error('Cannot decrypt event -- PoW too low'); + } + + const ccnPrivkey = await getCCNPrivateKeyByPubkey(eventDestination); + const decryptedEvent = attemptDecryptWithKey( + event, + ccnPrivkey, + eventDestination, + ); + if (decryptedEvent.isSome) { + return { ...decryptedEvent.value, ccnPubkey: eventDestination }; + } + + try { + const chuncked = handleChunkedMessage( + db, + event, + ccnPrivkey, + eventDestination, + ); + return { ...chuncked, ccnPubkey: eventDestination }; + } catch (e) { + if (e instanceof ChunkedEventReceived) { + throw e; } } diff --git a/index.ts b/index.ts index 8f3a4f2..104eaba 100644 --- a/index.ts +++ b/index.ts @@ -1,5 +1,8 @@ +import { bytesToHex, hexToBytes } from '@noble/ciphers/utils'; import { randomBytes } from '@noble/ciphers/webcrypto'; +import { sha512 } from '@noble/hashes/sha2'; import * as nostrTools from '@nostr/tools'; +import { base64 } from '@scure/base'; import { Database } from 'jsr:@db/sqlite'; import { NSchema as n } from 'jsr:@nostrify/nostrify'; import type { @@ -8,17 +11,23 @@ import type { NostrFilter, } from 'jsr:@nostrify/types'; import { encodeBase64 } from 'jsr:@std/encoding@0.224/base64'; -import { CHUNK_CLEANUP_INTERVAL, CHUNK_MAX_AGE } from './consts.ts'; +import { + CHUNK_CLEANUP_INTERVAL, + CHUNK_MAX_AGE, + POW_TO_MINE, +} from './consts.ts'; import { ChunkedEventReceived, EventAlreadyExistsException, createEncryptedEvent, + createEncryptedEventForPubkey, decryptEvent, } from './eventEncryptionDecryption.ts'; import { createNewCCN, getActiveCCN, getAllCCNs, + getCCNPrivateKeyByPubkey, isAddressableEvent, isArray, isCCNReplaceableEvent, @@ -42,6 +51,8 @@ if (!Deno.env.has('ENCRYPTION_KEY')) { Deno.exit(1); } +await Deno.mkdir(await getEveFilePath('ccn_keys'), { recursive: true }); + const db = new Database(await getEveFilePath('db')); const pool = new nostrTools.SimplePool(); const relays = [ @@ -123,12 +134,106 @@ function addEventToDb( `(db)[0]; if (existingEvent) throw new EventAlreadyExistsException(); + + const isInvite = + decryptedEvent.tags.findIndex( + (tag: string[]) => tag[0] === 'type' && tag[1] === 'invite', + ) !== -1; + + if (isInvite) { + const shadContent = bytesToHex( + sha512.create().update(decryptedEvent.content).digest(), + ); + + const inviteUsed = sql` + SELECT COUNT(*) as count FROM inviter_invitee WHERE invite_hash = ${shadContent} + `(db)[0].count; + + if (inviteUsed > 0) { + throw new Error('Invite already used'); + } + + const inviteEvent = sql` + SELECT * FROM events WHERE kind = 9999 AND id IN ( + SELECT event_id FROM event_tags WHERE tag_name = 'i' AND tag_id IN ( + SELECT tag_id FROM event_tags_values WHERE value_position = 1 AND value = ${shadContent} + ) + ) + `(db)[0]; + + if (!inviteEvent) { + throw new Error('Invite event not found'); + } + + const inviterPubkey = inviteEvent.pubkey; + const inviteePubkey = decryptedEvent.pubkey; + + db.run('BEGIN TRANSACTION'); + + sql` + INSERT INTO inviter_invitee (ccn_pubkey, inviter_pubkey, invitee_pubkey, invite_hash) VALUES (${ccnPubkey}, ${inviterPubkey}, ${inviteePubkey}, ${shadContent}) + `(db); + + sql` + INSERT INTO allowed_writes (ccn_pubkey, pubkey) VALUES (${ccnPubkey}, ${inviteePubkey}) + `(db); + + db.run('COMMIT TRANSACTION'); + + const allowedPubkeys = sql` + SELECT pubkey FROM allowed_writes WHERE ccn_pubkey = ${ccnPubkey} + `(db).flatMap((row) => row.pubkey); + const ccnName = sql` + SELECT name FROM ccns WHERE pubkey = ${ccnPubkey} + `(db)[0].name; + + getCCNPrivateKeyByPubkey(ccnPubkey).then((ccnPrivateKey) => { + if (!ccnPrivateKey) { + throw new Error('CCN private key not found'); + } + + const tags = allowedPubkeys.map((pubkey) => ['p', pubkey]); + tags.push(['t', 'invite']); + tags.push(['name', ccnName]); + + const privateKeyEvent = nostrTools.finalizeEvent( + nostrTools.nip13.minePow( + { + kind: 9998, + created_at: Date.now(), + content: base64.encode(ccnPrivateKey), + tags, + pubkey: ccnPubkey, + }, + POW_TO_MINE, + ), + ccnPrivateKey, + ); + + const encryptedKeyEvent = createEncryptedEventForPubkey( + inviteePubkey, + privateKeyEvent, + ); + publishToRelays(encryptedKeyEvent); + }); + + return; + } + + const isAllowedWrite = sql` + SELECT COUNT(*) as count FROM allowed_writes WHERE ccn_pubkey = ${ccnPubkey} AND pubkey = ${decryptedEvent.pubkey} + `(db)[0].count; + + if (isAllowedWrite === 0) { + throw new Error('Not allowed to write to this CCN'); + } + try { db.run('BEGIN TRANSACTION'); if (isReplaceableEvent(decryptedEvent.kind)) { sql` - UPDATE events + UPDATE events SET replaced = 1 WHERE kind = ${decryptedEvent.kind} AND pubkey = ${decryptedEvent.pubkey} @@ -141,15 +246,15 @@ function addEventToDb( const dTag = decryptedEvent.tags.find((tag) => tag[0] === 'd')?.[1]; if (dTag) { sql` - UPDATE events + UPDATE events SET replaced = 1 WHERE kind = ${decryptedEvent.kind} AND pubkey = ${decryptedEvent.pubkey} AND created_at < ${decryptedEvent.created_at} AND ccn_pubkey = ${ccnPubkey} AND id IN ( - SELECT event_id FROM event_tags - WHERE tag_name = 'd' + SELECT event_id FROM event_tags + WHERE tag_name = 'd' AND tag_id IN ( SELECT tag_id FROM event_tags_values WHERE value_position = 1 @@ -163,14 +268,14 @@ function addEventToDb( if (isCCNReplaceableEvent(decryptedEvent.kind)) { const dTag = decryptedEvent.tags.find((tag) => tag[0] === 'd')?.[1]; sql` - UPDATE events + UPDATE events SET replaced = 1 WHERE kind = ${decryptedEvent.kind} AND created_at < ${decryptedEvent.created_at} AND ccn_pubkey = ${ccnPubkey} AND id IN ( - SELECT event_id FROM event_tags - WHERE tag_name = 'd' + SELECT event_id FROM event_tags + WHERE tag_name = 'd' AND tag_id IN ( SELECT tag_id FROM event_tags_values WHERE value_position = 1 @@ -561,7 +666,7 @@ function handleRequest(connection: UserConnection, request: NostrClientREQ) { FROM event_tags t WHERE t.tag_name = ${tag} AND t.tag_id IN ( - SELECT v.tag_id + SELECT v.tag_id FROM event_tags_values v WHERE v.value_position = 1 AND v.value = ${tagValue} @@ -735,7 +840,7 @@ function handleSocketError( async function handleCreateCCN( connection: UserConnection, - data: { name: string; seed?: string }, + data: { name: string; seed?: string; creator: string }, ): Promise { try { if (!data.name || typeof data.name !== 'string') { @@ -743,7 +848,17 @@ async function handleCreateCCN( return; } - const newCcn = await createNewCCN(connection.db, data.name, data.seed); + if (!data.creator || typeof data.creator !== 'string') { + connection.sendNotice('Creator is required'); + return; + } + + const newCcn = await createNewCCN( + connection.db, + data.name, + data.creator, + data.seed, + ); activateCCN(connection.db, newCcn.pubkey); @@ -834,6 +949,73 @@ function handleActivateCCN( } } +async function handleAddCCN( + connection: UserConnection, + data: { name: string; allowedPubkeys: string[]; privateKey: string }, +): Promise { + try { + if (!data.privateKey || typeof data.privateKey !== 'string') { + connection.sendNotice('CCN private key is required'); + return; + } + + const privateKeyBytes = hexToBytes(data.privateKey); + const pubkey = nostrTools.getPublicKey(privateKeyBytes); + + const ccnExists = sql` + SELECT COUNT(*) as count FROM ccns WHERE pubkey = ${pubkey} + `(connection.db)[0].count; + + if (ccnExists > 0) { + connection.sendNotice('CCN already exists'); + return; + } + + const ccnPublicKey = nostrTools.getPublicKey(privateKeyBytes); + const ccnPrivPath = await getEveFilePath(`ccn_keys/${ccnPublicKey}`); + Deno.writeTextFileSync(ccnPrivPath, encodeBase64(privateKeyBytes)); + + db.run('BEGIN TRANSACTION'); + + sql`INSERT INTO ccns (pubkey, name) VALUES (${ccnPublicKey}, ${data.name})`( + db, + ); + for (const allowedPubkey of data.allowedPubkeys) + sql`INSERT INTO allowed_writes (ccn_pubkey, pubkey) VALUES (${ccnPublicKey}, ${allowedPubkey})`( + db, + ); + + db.run('COMMIT TRANSACTION'); + + activateCCN(connection.db, ccnPublicKey); + + pool.subscribeMany( + relays, + [ + { + '#p': [ccnPublicKey], + kinds: [1059], + }, + ], + { + onevent: createSubscriptionEventHandler(connection.db), + }, + ); + + connection.sendResponse([ + 'OK', + 'CCN ADDED', + true, + JSON.stringify({ + pubkey: ccnPublicKey, + name: 'New CCN', + }), + ]); + } catch (error: unknown) { + handleSocketError(connection, 'ADD CCN', error); + } +} + function handleCCNCommands( connection: UserConnection, command: string, @@ -843,7 +1025,12 @@ function handleCCNCommands( case 'CREATE': return handleCreateCCN( connection, - data as { name: string; seed?: string }, + data as { name: string; seed?: string; creator: string }, + ); + case 'ADD': + return handleAddCCN( + connection, + data as { name: string; allowedPubkeys: string[]; privateKey: string }, ); case 'LIST': return handleGetCCNs(connection); diff --git a/migrations/6-invitations.sql b/migrations/6-invitations.sql new file mode 100644 index 0000000..ab6aeba --- /dev/null +++ b/migrations/6-invitations.sql @@ -0,0 +1,24 @@ +CREATE TABLE inviter_invitee( + id TEXT PRIMARY KEY NOT NULL DEFAULT (lower(hex(randomblob(16)))), + ccn_pubkey TEXT NOT NULL, + inviter_pubkey TEXT NOT NULL, + invitee_pubkey TEXT NOT NULL, + invite_hash TEXT NOT NULL, + created_at INTEGER NOT NULL DEFAULT (unixepoch()), + FOREIGN KEY (ccn_pubkey) REFERENCES ccns(pubkey) ON DELETE CASCADE +); + +CREATE INDEX idx_inviter_invitee_ccn_pubkey ON inviter_invitee(ccn_pubkey); +CREATE INDEX idx_inviter_invitee_inviter_pubkey ON inviter_invitee(inviter_pubkey); +CREATE INDEX idx_inviter_invitee_invitee_pubkey ON inviter_invitee(invitee_pubkey); + +CREATE TABLE allowed_writes ( + id TEXT PRIMARY KEY NOT NULL DEFAULT (lower(hex(randomblob(16)))), + ccn_pubkey TEXT NOT NULL, + pubkey TEXT NOT NULL, + created_at INTEGER NOT NULL DEFAULT (unixepoch()), + FOREIGN KEY (ccn_pubkey) REFERENCES ccns(pubkey) ON DELETE CASCADE +); + +CREATE INDEX idx_allowed_writes_ccn_pubkey ON allowed_writes(ccn_pubkey); +CREATE INDEX idx_allowed_writes_pubkey ON allowed_writes(pubkey); diff --git a/utils.ts b/utils.ts index fd83c36..7c67aa5 100644 --- a/utils.ts +++ b/utils.ts @@ -61,6 +61,7 @@ export function getAllCCNs(db: Database): { pubkey: string; name: string }[] { export async function createNewCCN( db: Database, name: string, + creator: string, seed?: string, ): Promise<{ pubkey: string; privkey: Uint8Array }> { const ccnSeed = seed || nip06.generateSeedWords(); @@ -78,7 +79,14 @@ export async function createNewCCN( Deno.writeTextFileSync(ccnSeedPath, ccnSeed); Deno.writeTextFileSync(ccnPrivPath, encodeBase64(encryptedPrivateKey)); + db.run('BEGIN TRANSACTION'); + sql`INSERT INTO ccns (pubkey, name) VALUES (${ccnPublicKey}, ${name})`(db); + sql`INSERT INTO allowed_writes (ccn_pubkey, pubkey) VALUES (${ccnPublicKey}, ${creator})`( + db, + ); + + db.run('COMMIT TRANSACTION'); return { pubkey: ccnPublicKey, diff --git a/utils/invites.ts b/utils/invites.ts new file mode 100644 index 0000000..45a61ec --- /dev/null +++ b/utils/invites.ts @@ -0,0 +1,12 @@ +import { bytesToHex } from '@noble/ciphers/utils'; +import { nip19 } from '@nostr/tools'; +import { bech32m } from '@scure/base'; + +export function readInvite(invite: `${string}1${string}`) { + const decoded = bech32m.decode(invite, false); + if (decoded.prefix !== 'eveinvite') return false; + const hexBytes = bech32m.fromWords(decoded.words); + const npub = nip19.npubEncode(bytesToHex(hexBytes.slice(0, 32))); + const inviteCode = bytesToHex(hexBytes.slice(32)); + return { npub, invite: inviteCode }; +} From 107504050e98f977f0cb37727c7030edc08864a9 Mon Sep 17 00:00:00 2001 From: Danny Morabito Date: Thu, 24 Apr 2025 19:37:50 +0200 Subject: [PATCH 09/11] bug: adding ccn instead of creating doesn't encrypt key --- index.ts | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/index.ts b/index.ts index 104eaba..2182675 100644 --- a/index.ts +++ b/index.ts @@ -36,6 +36,7 @@ import { isValidJSON, parseATagQuery, } from './utils.ts'; +import { encryptUint8Array, encryptionKey } from './utils/encryption.ts'; import { getEveFilePath } from './utils/files.ts'; import { log, setupLogger } from './utils/logs.ts'; import { mixQuery, sql, sqlPartial } from './utils/queries.ts'; @@ -973,7 +974,11 @@ async function handleAddCCN( const ccnPublicKey = nostrTools.getPublicKey(privateKeyBytes); const ccnPrivPath = await getEveFilePath(`ccn_keys/${ccnPublicKey}`); - Deno.writeTextFileSync(ccnPrivPath, encodeBase64(privateKeyBytes)); + const encryptedPrivateKey = encryptUint8Array( + privateKeyBytes, + encryptionKey, + ); + Deno.writeTextFileSync(ccnPrivPath, encodeBase64(encryptedPrivateKey)); db.run('BEGIN TRANSACTION'); From 20ffbd4c6de23b39e3c0f3486278920d27f323d1 Mon Sep 17 00:00:00 2001 From: Danny Morabito Date: Wed, 4 Jun 2025 12:43:23 +0200 Subject: [PATCH 10/11] =?UTF-8?q?=E2=9C=A8=20Fully=20rewrite=20relay?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Makefile | 4 +- Readme.md | 7 +- biome.json | 2 +- deno.json | 4 +- .../3-replaceableAndDeleteableEvents.sql | 4 + migrations/3-replaceableEvents.sql | 2 - migrations/7-createLogsTable.sql | 32 ++ migrations/8-fixChunksTableSchema.sql | 44 ++ migrations/9-createOutboundEventQueue.sql | 41 ++ src/UserConnection.ts | 61 +++ src/commands/ccn.ts | 314 ++++++++++++++ src/commands/close.ts | 15 + src/commands/event.ts | 85 ++++ src/commands/request.ts | 291 +++++++++++++ consts.ts => src/consts.ts | 15 + src/dbEvents/addEventToDb.ts | 331 +++++++++++++++ src/dbEvents/deletionEvent.ts | 143 +++++++ .../eventEncryptionDecryption.ts | 177 ++++++-- src/index.ts | 397 ++++++++++++++++++ src/migrations.ts | 55 +++ src/relays.ts | 39 ++ src/utils/cleanupOldChunks.ts | 8 + src/utils/createNewCCN.ts | 52 +++ src/utils/databaseLogger.ts | 217 ++++++++++ {utils => src/utils}/encryption.ts | 0 src/utils/eventTypes.ts | 24 ++ {utils => src/utils}/files.ts | 0 src/utils/filtersMatchingEvent.ts | 32 ++ src/utils/getActiveCCN.ts | 17 + src/utils/getAllCCNs.ts | 13 + src/utils/getCCNPrivateKeyByPubkey.ts | 20 + src/utils/getEncryptedEventByOriginalId.ts | 12 + src/utils/invites.ts | 76 ++++ src/utils/isArray.ts | 3 + src/utils/isLocalhost.ts | 39 ++ src/utils/isValidJSON.ts | 8 + src/utils/knownEventsCache.ts | 14 + src/utils/logQueries.ts | 162 +++++++ src/utils/logs.ts | 140 ++++++ {utils => src/utils}/option.ts | 0 src/utils/outboundQueue.ts | 389 +++++++++++++++++ src/utils/parseATagQuery.ts | 14 + {utils => src/utils}/queries.ts | 0 src/utils/randomTimeUpTo2DaysInThePast.ts | 7 + src/utils/securityLogs.ts | 220 ++++++++++ utils/invites.ts | 12 - utils/logs.ts | 75 ---- 47 files changed, 3489 insertions(+), 128 deletions(-) create mode 100644 migrations/3-replaceableAndDeleteableEvents.sql delete mode 100644 migrations/3-replaceableEvents.sql create mode 100644 migrations/7-createLogsTable.sql create mode 100644 migrations/8-fixChunksTableSchema.sql create mode 100644 migrations/9-createOutboundEventQueue.sql create mode 100644 src/UserConnection.ts create mode 100644 src/commands/ccn.ts create mode 100644 src/commands/close.ts create mode 100644 src/commands/event.ts create mode 100644 src/commands/request.ts rename consts.ts => src/consts.ts (76%) create mode 100644 src/dbEvents/addEventToDb.ts create mode 100644 src/dbEvents/deletionEvent.ts rename eventEncryptionDecryption.ts => src/eventEncryptionDecryption.ts (63%) create mode 100644 src/index.ts create mode 100644 src/migrations.ts create mode 100644 src/relays.ts create mode 100644 src/utils/cleanupOldChunks.ts create mode 100644 src/utils/createNewCCN.ts create mode 100644 src/utils/databaseLogger.ts rename {utils => src/utils}/encryption.ts (100%) create mode 100644 src/utils/eventTypes.ts rename {utils => src/utils}/files.ts (100%) mode change 100644 => 100755 create mode 100644 src/utils/filtersMatchingEvent.ts create mode 100644 src/utils/getActiveCCN.ts create mode 100644 src/utils/getAllCCNs.ts create mode 100644 src/utils/getCCNPrivateKeyByPubkey.ts create mode 100644 src/utils/getEncryptedEventByOriginalId.ts create mode 100644 src/utils/invites.ts create mode 100644 src/utils/isArray.ts create mode 100644 src/utils/isLocalhost.ts create mode 100644 src/utils/isValidJSON.ts create mode 100644 src/utils/knownEventsCache.ts create mode 100644 src/utils/logQueries.ts create mode 100644 src/utils/logs.ts rename {utils => src/utils}/option.ts (100%) create mode 100644 src/utils/outboundQueue.ts create mode 100644 src/utils/parseATagQuery.ts rename {utils => src/utils}/queries.ts (100%) create mode 100644 src/utils/randomTimeUpTo2DaysInThePast.ts create mode 100644 src/utils/securityLogs.ts delete mode 100644 utils/invites.ts delete mode 100644 utils/logs.ts diff --git a/Makefile b/Makefile index 41f978e..813ae48 100644 --- a/Makefile +++ b/Makefile @@ -5,10 +5,10 @@ TARGETS = x86_64-unknown-linux-gnu aarch64-unknown-linux-gnu x86_64-apple-darwin all: $(TARGETS:%=dist/relay-%) dist/relay-%: | dist/ - deno compile -A -r --target $* --include migrations --include public --no-lock --output $@ index.ts + deno compile -A -r --target $* --include migrations --include public --no-lock --output $@ src/index.ts dist/: mkdir -p dist clean: - rm -f dist/* \ No newline at end of file + rm -f dist/* diff --git a/Readme.md b/Readme.md index 433a2eb..d54463f 100644 --- a/Readme.md +++ b/Readme.md @@ -1,6 +1,11 @@ # EVE Relay -> โš ๏ธ ALPHA STAGE DISCLAIMER: EVE is currently in early alpha development. Many features described here are still in development or planned for future releases. The platform is rapidly evolving, and you may encounter bugs, incomplete functionality, or significant changes between versions. We welcome early adopters and contributors who share our vision, but please be aware of the platform's developmental status. +> โš ๏ธ ALPHA STAGE DISCLAIMER: EVE is currently in early alpha development. Many +> features described here are still in development or planned for future +> releases. The platform is rapidly evolving, and you may encounter bugs, +> incomplete functionality, or significant changes between versions. We welcome +> early adopters and contributors who share our vision, but please be aware of +> the platform's developmental status. # Requirements diff --git a/biome.json b/biome.json index 4101319..2f825f4 100644 --- a/biome.json +++ b/biome.json @@ -1,7 +1,7 @@ { "$schema": "https://biomejs.dev/schemas/1.9.4/schema.json", "files": { - "include": ["index.ts", "**/*.ts"] + "include": ["**/*.ts"] }, "vcs": { "enabled": true, diff --git a/deno.json b/deno.json index 2738627..39192bb 100644 --- a/deno.json +++ b/deno.json @@ -1,6 +1,6 @@ { "tasks": { - "dev": "deno run --allow-read --allow-write --allow-net --allow-ffi --allow-env --env-file --watch index.ts", + "dev": "deno run --allow-read --allow-write --allow-net --allow-ffi --allow-env --env-file --watch src/index.ts", "lint": "biome check", "lint:fix": "biome check --write --unsafe" }, @@ -8,9 +8,11 @@ "@biomejs/biome": "npm:@biomejs/biome@^1.9.4", "@db/sqlite": "jsr:@db/sqlite@^0.12.0", "@noble/ciphers": "jsr:@noble/ciphers@^1.2.1", + "@noble/hashes": "jsr:@noble/hashes@^1.8.0", "@nostr/tools": "jsr:@nostr/tools@^2.10.4", "@nostrify/nostrify": "jsr:@nostrify/nostrify@^0.37.0", "@nostrify/types": "jsr:@nostrify/types@^0.36.0", + "@scure/base": "jsr:@scure/base@^1.2.4", "@std/encoding": "jsr:@std/encoding@^1.0.6", "@std/fmt": "jsr:@std/fmt@^1.0.4", "@std/log": "jsr:@std/log@^0.224.13", diff --git a/migrations/3-replaceableAndDeleteableEvents.sql b/migrations/3-replaceableAndDeleteableEvents.sql new file mode 100644 index 0000000..9c9d4cb --- /dev/null +++ b/migrations/3-replaceableAndDeleteableEvents.sql @@ -0,0 +1,4 @@ +ALTER TABLE events +ADD COLUMN replaced INTEGER NOT NULL DEFAULT 0; +ALTER TABLE events +ADD COLUMN deleted INTEGER NOT NULL DEFAULT 0; diff --git a/migrations/3-replaceableEvents.sql b/migrations/3-replaceableEvents.sql deleted file mode 100644 index 67ba8fc..0000000 --- a/migrations/3-replaceableEvents.sql +++ /dev/null @@ -1,2 +0,0 @@ -ALTER TABLE events -ADD COLUMN replaced INTEGER NOT NULL DEFAULT 0; diff --git a/migrations/7-createLogsTable.sql b/migrations/7-createLogsTable.sql new file mode 100644 index 0000000..30b72d1 --- /dev/null +++ b/migrations/7-createLogsTable.sql @@ -0,0 +1,32 @@ +CREATE TABLE logs ( + log_id TEXT PRIMARY KEY DEFAULT (lower(hex(randomblob(16)))), + timestamp TEXT NOT NULL, + level TEXT NOT NULL CHECK (level IN ('DEBUG', 'INFO', 'WARN', 'ERROR', 'FATAL')), + message TEXT NOT NULL, + args TEXT, -- JSON string of log arguments + source TEXT, -- tag or source component + created_at INTEGER NOT NULL DEFAULT (unixepoch()), + -- Security-specific fields + event_type TEXT, -- For security events + severity TEXT, -- For security events + remote_addr TEXT, + ccn_pubkey TEXT, + event_id TEXT, + risk_score REAL +); + +CREATE INDEX idx_logs_timestamp ON logs(timestamp); +CREATE INDEX idx_logs_level ON logs(level); +CREATE INDEX idx_logs_created_at ON logs(created_at); +CREATE INDEX idx_logs_source ON logs(source); +CREATE INDEX idx_logs_event_type ON logs(event_type); +CREATE INDEX idx_logs_severity ON logs(severity); +CREATE INDEX idx_logs_ccn_pubkey ON logs(ccn_pubkey); + +CREATE TRIGGER cleanup_old_logs +AFTER INSERT ON logs +WHEN (SELECT COUNT(*) FROM logs) > 100000 +BEGIN + DELETE FROM logs + WHERE created_at < (unixepoch() - 2592000); -- 30 days +END; diff --git a/migrations/8-fixChunksTableSchema.sql b/migrations/8-fixChunksTableSchema.sql new file mode 100644 index 0000000..6b15540 --- /dev/null +++ b/migrations/8-fixChunksTableSchema.sql @@ -0,0 +1,44 @@ +-- Fix event_chunks table schema to add proper security constraints for chunked message handling + +-- Drop the old table if it exists +DROP TABLE IF EXISTS event_chunks; + +-- Create the event_chunks table with correct schema and security constraints +CREATE TABLE event_chunks ( + chunk_id INTEGER PRIMARY KEY AUTOINCREMENT, + message_id TEXT NOT NULL, + chunk_index INTEGER NOT NULL, + total_chunks INTEGER NOT NULL CHECK (total_chunks > 0 AND total_chunks <= 1000), + content TEXT NOT NULL, + created_at INTEGER NOT NULL, + ccn_pubkey TEXT NOT NULL, + + -- SECURITY: Prevent duplicate chunks and enforce data integrity + UNIQUE(message_id, chunk_index, ccn_pubkey), + + -- SECURITY: Ensure chunk_index is within valid bounds + CHECK (chunk_index >= 0 AND chunk_index < total_chunks), + + -- SECURITY: Limit message_id length to prevent DoS + CHECK (length(message_id) <= 100), + + -- SECURITY: Limit content size to prevent memory exhaustion + CHECK (length(content) <= 65536), + + -- SECURITY: Foreign key reference to ensure CCN exists + FOREIGN KEY (ccn_pubkey) REFERENCES ccns(pubkey) ON DELETE CASCADE +); + +-- Indexes for performance +CREATE INDEX idx_event_chunks_message_id ON event_chunks(message_id); +CREATE INDEX idx_event_chunks_created_at ON event_chunks(created_at); +CREATE INDEX idx_event_chunks_ccn_pubkey ON event_chunks(ccn_pubkey); + +-- SECURITY: Automatic cleanup trigger for old chunks to prevent storage exhaustion +CREATE TRIGGER cleanup_old_chunks +AFTER INSERT ON event_chunks +WHEN (SELECT COUNT(*) FROM event_chunks WHERE created_at < (unixepoch() - 86400)) > 0 +BEGIN + DELETE FROM event_chunks + WHERE created_at < (unixepoch() - 86400); +END; diff --git a/migrations/9-createOutboundEventQueue.sql b/migrations/9-createOutboundEventQueue.sql new file mode 100644 index 0000000..4dd06d5 --- /dev/null +++ b/migrations/9-createOutboundEventQueue.sql @@ -0,0 +1,41 @@ +-- Create outbound event queue for offline event creation and reliable relay transmission +-- This allows users to create events when offline and sync them when connectivity is restored + +CREATE TABLE outbound_event_queue ( + queue_id INTEGER PRIMARY KEY AUTOINCREMENT, + event_id TEXT NOT NULL, + encrypted_event TEXT NOT NULL, + ccn_pubkey TEXT NOT NULL, + created_at INTEGER NOT NULL DEFAULT (unixepoch()), + attempts INTEGER NOT NULL DEFAULT 0, + last_attempt INTEGER NULL, + status TEXT NOT NULL DEFAULT 'pending' CHECK (status IN ('pending', 'sending', 'sent', 'failed')), + error_message TEXT NULL, + + -- Ensure one queue entry per event + UNIQUE(event_id), + + -- Foreign key constraints + FOREIGN KEY (ccn_pubkey) REFERENCES ccns(pubkey) ON DELETE CASCADE, + FOREIGN KEY (event_id) REFERENCES events(id) ON DELETE CASCADE +); + +-- Indexes for efficient querying +CREATE INDEX idx_outbound_queue_status ON outbound_event_queue(status); +CREATE INDEX idx_outbound_queue_ccn_pubkey ON outbound_event_queue(ccn_pubkey); +CREATE INDEX idx_outbound_queue_created_at ON outbound_event_queue(created_at); +CREATE INDEX idx_outbound_queue_last_attempt ON outbound_event_queue(last_attempt); + +-- Cleanup trigger for old completed/failed events +CREATE TRIGGER cleanup_old_queue_entries +AFTER UPDATE ON outbound_event_queue +WHEN NEW.status IN ('sent', 'failed') AND NEW.attempts >= 5 +BEGIN + -- Keep failed events for 30 days for debugging, sent events for 1 day + DELETE FROM outbound_event_queue + WHERE queue_id = NEW.queue_id + AND ( + (status = 'sent' AND created_at < (unixepoch() - 86400)) OR + (status = 'failed' AND created_at < (unixepoch() - 2592000)) + ); +END; diff --git a/src/UserConnection.ts b/src/UserConnection.ts new file mode 100644 index 0000000..e03c936 --- /dev/null +++ b/src/UserConnection.ts @@ -0,0 +1,61 @@ +import type { Database } from 'jsr:@db/sqlite'; +import type { NostrEvent, NostrFilter } from 'jsr:@nostrify/types'; + +export class UserConnection { + public socket: WebSocket; + public subscriptions: Map; + public db: Database; + + constructor( + socket: WebSocket, + subscriptions: Map, + db: Database, + ) { + this.socket = socket; + this.subscriptions = subscriptions; + this.db = db; + } + + /** + * Sends a response to the client + * @param responseArray The response array to send + */ + sendResponse(responseArray: unknown[]): void { + this.socket.send(JSON.stringify(responseArray)); + } + + /** + * Sends a notice to the client + * @param message The message to send + */ + sendNotice(message: string): void { + this.sendResponse(['NOTICE', message]); + } + + /** + * Sends an event to the client + * @param subscriptionId The subscription ID + * @param event The event to send + */ + sendEvent(subscriptionId: string, event: NostrEvent): void { + this.sendResponse(['EVENT', subscriptionId, event]); + } + + /** + * Sends an end of stored events message + * @param subscriptionId The subscription ID + */ + sendEOSE(subscriptionId: string): void { + this.sendResponse(['EOSE', subscriptionId]); + } + + /** + * Sends an OK response + * @param eventId The event ID + * @param success Whether the operation was successful + * @param message The message to send + */ + sendOK(eventId: string, success: boolean, message: string): void { + this.sendResponse(['OK', eventId, success, message]); + } +} diff --git a/src/commands/ccn.ts b/src/commands/ccn.ts new file mode 100644 index 0000000..e7c6a01 --- /dev/null +++ b/src/commands/ccn.ts @@ -0,0 +1,314 @@ +import type { Database } from 'jsr:@db/sqlite'; +import { encodeBase64 } from 'jsr:@std/encoding@0.224/base64'; +import { hexToBytes } from '@noble/ciphers/utils'; +import * as nostrTools from '@nostr/tools'; +import type { UserConnection } from '../UserConnection.ts'; +import { handleSocketError } from '../index.ts'; +import { createNewCCN } from '../utils/createNewCCN.ts'; +import { encryptUint8Array, encryptionKey } from '../utils/encryption.ts'; +import { getEveFilePath } from '../utils/files.ts'; +import { getAllCCNs } from '../utils/getAllCCNs.ts'; +import { log } from '../utils/logs.ts'; +import { sql } from '../utils/queries.ts'; +import { + SecurityEventType, + SecuritySeverity, + logAuthEvent, + logSecurityEvent, +} from '../utils/securityLogs.ts'; + +function activateCCN(database: Database, pubkey: string): void { + sql`UPDATE ccns SET is_active = 0`(database); + sql`UPDATE ccns SET is_active = 1 WHERE pubkey = ${pubkey}`(database); + + logAuthEvent(SecurityEventType.CCN_ACTIVATION_ATTEMPT, true, { + ccn_pubkey: pubkey, + }); +} + +async function handleCreateCCN( + connection: UserConnection, + data: { name: string; seed?: string; creator: string }, +): Promise { + log.debug('start', { tag: 'handleCreateCCN', data }); + + logSecurityEvent({ + eventType: SecurityEventType.CCN_CREATION_ATTEMPT, + severity: SecuritySeverity.MEDIUM, + source: 'ccn_management', + details: { + ccn_name: data.name, + creator: data.creator, + has_seed: !!data.seed, + }, + }); + + try { + if (!data.name || typeof data.name !== 'string') { + logSecurityEvent({ + eventType: SecurityEventType.CCN_CREATION_ATTEMPT, + severity: SecuritySeverity.MEDIUM, + source: 'ccn_management', + details: { + error: 'invalid_name', + name_provided: !!data.name, + name_type: typeof data.name, + }, + }); + + connection.sendNotice('Name is required'); + return; + } + + if (!data.creator || typeof data.creator !== 'string') { + logSecurityEvent({ + eventType: SecurityEventType.CCN_CREATION_ATTEMPT, + severity: SecuritySeverity.MEDIUM, + source: 'ccn_management', + details: { + error: 'invalid_creator', + creator_provided: !!data.creator, + creator_type: typeof data.creator, + }, + }); + + connection.sendNotice('Creator is required'); + return; + } + + const newCcn = await createNewCCN( + connection.db, + data.name, + data.creator, + data.seed, + ); + log.debug('created new CCN', { + tag: 'handleCreateCCN', + pubkey: newCcn.pubkey, + }); + activateCCN(connection.db, newCcn.pubkey); + log.debug('activated new CCN', { + tag: 'handleCreateCCN', + pubkey: newCcn.pubkey, + }); + + logSecurityEvent({ + eventType: SecurityEventType.CCN_CREATION_ATTEMPT, + severity: SecuritySeverity.LOW, + source: 'ccn_management', + details: { + success: true, + ccn_pubkey: newCcn.pubkey, + ccn_name: data.name, + creator: data.creator, + }, + }); + + connection.sendResponse([ + 'OK', + 'CCN CREATED', + true, + JSON.stringify({ + pubkey: newCcn.pubkey, + name: data.name, + }), + ]); + + log.info('CCN created', data); + } catch (error: unknown) { + log.error('error', { tag: 'handleCreateCCN', error }); + + logSecurityEvent({ + eventType: SecurityEventType.CCN_CREATION_ATTEMPT, + severity: SecuritySeverity.HIGH, + source: 'ccn_management', + details: { + success: false, + error_message: error instanceof Error ? error.message : 'Unknown error', + ccn_name: data.name, + creator: data.creator, + }, + }); + + handleSocketError(connection, 'create CCN', error); + } + log.debug('end', { tag: 'handleCreateCCN' }); +} + +function handleGetCCNs(connection: UserConnection): void { + try { + const ccns = getAllCCNs(connection.db); + connection.sendResponse(['OK', 'CCN LIST', true, JSON.stringify(ccns)]); + } catch (error: unknown) { + handleSocketError(connection, 'get CCNs', error); + } +} + +function handleActivateCCN( + connection: UserConnection, + data: { pubkey: string }, +): void { + log.debug('start', { tag: 'handleActivateCCN', data }); + try { + if (!data.pubkey || typeof data.pubkey !== 'string') { + connection.sendNotice('CCN pubkey is required'); + return; + } + + const ccnExists = sql` + SELECT COUNT(*) as count FROM ccns WHERE pubkey = ${data.pubkey} + `(connection.db)[0].count; + + if (ccnExists === 0) { + connection.sendNotice('CCN not found'); + log.debug('CCN not found', { + tag: 'handleActivateCCN', + pubkey: data.pubkey, + }); + return; + } + + for (const subscriptionId of connection.subscriptions.keys()) { + connection.sendResponse([ + 'CLOSED', + subscriptionId, + 'Subscription closed due to CCN activation', + ]); + log.debug('closed subscription', { + tag: 'handleActivateCCN', + subscriptionId, + }); + } + + connection.subscriptions.clear(); + log.info('All subscriptions cleared due to CCN activation', {}); + + activateCCN(connection.db, data.pubkey); + log.debug('activated CCN', { + tag: 'handleActivateCCN', + pubkey: data.pubkey, + }); + + const activatedCCN = sql` + SELECT pubkey, name FROM ccns WHERE pubkey = ${data.pubkey} + `(connection.db)[0]; + + connection.sendResponse([ + 'OK', + 'CCN ACTIVATED', + true, + JSON.stringify(activatedCCN), + ]); + + log.info(`CCN activated: ${activatedCCN.name}`, {}); + } catch (error: unknown) { + log.error('error', { tag: 'handleActivateCCN', error }); + handleSocketError(connection, 'activate CCN', error); + } + log.debug('end', { tag: 'handleActivateCCN' }); +} + +async function handleAddCCN( + connection: UserConnection, + data: { name: string; allowedPubkeys: string[]; privateKey: string }, +): Promise { + log.debug('start', { tag: 'handleAddCCN', data }); + try { + if (!data.privateKey || typeof data.privateKey !== 'string') { + connection.sendNotice('CCN private key is required'); + return; + } + + const privateKeyBytes = hexToBytes(data.privateKey); + const pubkey = nostrTools.getPublicKey(privateKeyBytes); + log.debug('derived pubkey', { tag: 'handleAddCCN', pubkey }); + + const ccnExists = sql` + SELECT COUNT(*) as count FROM ccns WHERE pubkey = ${pubkey} + `(connection.db)[0].count; + + if (ccnExists > 0) { + connection.sendNotice('CCN already exists'); + log.debug('CCN already exists', { + tag: 'handleAddCCN', + pubkey, + }); + return; + } + + const ccnPublicKey = nostrTools.getPublicKey(privateKeyBytes); + const ccnPrivPath = await getEveFilePath(`ccn_keys/${ccnPublicKey}`); + const encryptedPrivateKey = encryptUint8Array( + privateKeyBytes, + encryptionKey, + ); + Deno.writeTextFileSync(ccnPrivPath, encodeBase64(encryptedPrivateKey)); + + connection.db.run('BEGIN TRANSACTION'); + log.debug('begin transaction', { tag: 'handleAddCCN' }); + + sql`INSERT INTO ccns (pubkey, name) VALUES (${ccnPublicKey}, ${data.name})`( + connection.db, + ); + for (const allowedPubkey of data.allowedPubkeys) + sql`INSERT INTO allowed_writes (ccn_pubkey, pubkey) VALUES (${ccnPublicKey}, ${allowedPubkey})`( + connection.db, + ); + + connection.db.run('COMMIT TRANSACTION'); + log.debug('committed transaction', { tag: 'handleAddCCN' }); + activateCCN(connection.db, ccnPublicKey); + log.debug('activated CCN', { + tag: 'handleAddCCN', + pubkey: ccnPublicKey, + }); + + connection.sendResponse([ + 'OK', + 'CCN ADDED', + true, + JSON.stringify({ + pubkey: ccnPublicKey, + name: 'New CCN', + }), + ]); + } catch (error: unknown) { + log.error('error', { tag: 'handleAddCCN', error }); + handleSocketError(connection, 'ADD CCN', error); + } + log.debug('end', { tag: 'handleAddCCN' }); +} + +function handleCCNCommands( + connection: UserConnection, + command: string, + data: unknown, +) { + switch (command) { + case 'CREATE': + return handleCreateCCN( + connection, + data as { name: string; seed?: string; creator: string }, + ); + case 'ADD': + return handleAddCCN( + connection, + data as { name: string; allowedPubkeys: string[]; privateKey: string }, + ); + case 'LIST': + return handleGetCCNs(connection); + case 'ACTIVATE': + return handleActivateCCN(connection, data as { pubkey: string }); + default: + return log.warn('Invalid CCN command', {}); + } +} + +export { + activateCCN, + handleActivateCCN, + handleAddCCN, + handleCCNCommands, + handleCreateCCN, + handleGetCCNs, +}; diff --git a/src/commands/close.ts b/src/commands/close.ts new file mode 100644 index 0000000..ed9897a --- /dev/null +++ b/src/commands/close.ts @@ -0,0 +1,15 @@ +import type { UserConnection } from '../UserConnection.ts'; +import { log } from '../utils/logs.ts'; + +export function handleClose( + connection: UserConnection, + subscriptionId: string, +) { + if (!connection.subscriptions.has(subscriptionId)) { + return log.warn( + `Closing unknown subscription? That's weird. Subscription ID: ${subscriptionId}`, + ); + } + + connection.subscriptions.delete(subscriptionId); +} diff --git a/src/commands/event.ts b/src/commands/event.ts new file mode 100644 index 0000000..25a3e06 --- /dev/null +++ b/src/commands/event.ts @@ -0,0 +1,85 @@ +import * as nostrTools from '@nostr/tools'; +import type { UserConnection } from '../UserConnection.ts'; +import { addEventToDb } from '../dbEvents/addEventToDb.ts'; +import { + EventAlreadyExistsException, + createEncryptedEvent, +} from '../eventEncryptionDecryption.ts'; +import { filtersMatchingEvent } from '../utils/filtersMatchingEvent.ts'; +import { getActiveCCN } from '../utils/getActiveCCN.ts'; +import { isArray } from '../utils/isArray.ts'; +import { log } from '../utils/logs.ts'; +import { queueEventForTransmission } from '../utils/outboundQueue.ts'; + +export async function handleEvent( + connection: UserConnection, + event: nostrTools.Event, +) { + log.debug('start', { tag: 'handleEvent', eventId: event.id }); + const valid = nostrTools.verifyEvent(event); + if (!valid) { + connection.sendNotice('Invalid event'); + return log.warn('Invalid event', { tag: 'handleEvent' }); + } + + const activeCCN = getActiveCCN(connection.db); + if (!activeCCN) { + connection.sendNotice('No active CCN found'); + return log.warn('No active CCN found', { tag: 'handleEvent' }); + } + + const encryptedEvent = await createEncryptedEvent(event, connection.db); + try { + if (isArray(encryptedEvent)) { + log.debug('adding chunked event to database', { + tag: 'handleEvent', + }); + addEventToDb(connection.db, event, encryptedEvent[0], activeCCN.pubkey); + } else { + addEventToDb(connection.db, event, encryptedEvent, activeCCN.pubkey); + } + + queueEventForTransmission( + connection.db, + event.id, + encryptedEvent, + activeCCN.pubkey, + ); + + log.debug('event queued for transmission', { + tag: 'handleEvent', + eventId: event.id, + }); + } catch (e) { + if (e instanceof EventAlreadyExistsException) { + log.warn('Event already exists'); + return; + } + if (e instanceof Error) + log.error('error adding event', { + tag: 'handleEvent', + error: e.stack, + }); + else + log.error('error adding event', { + tag: 'handleEvent', + error: String(e), + }); + } + + connection.sendOK(event.id, true, 'Event added'); + log.debug('sent OK', { tag: 'handleEvent', eventId: event.id }); + + const filtersThatMatchEvent = filtersMatchingEvent(event, connection); + + for (let i = 0; i < filtersThatMatchEvent.length; i++) { + const filter = filtersThatMatchEvent[i]; + connection.sendEvent(filter, event); + log.debug('sent event to filter', { + tag: 'handleEvent', + filter, + eventId: event.id, + }); + } + log.debug('end', { tag: 'handleEvent', eventId: event.id }); +} diff --git a/src/commands/request.ts b/src/commands/request.ts new file mode 100644 index 0000000..02c761e --- /dev/null +++ b/src/commands/request.ts @@ -0,0 +1,291 @@ +import type { NostrClientREQ } from 'jsr:@nostrify/types'; +import type { UserConnection } from '../UserConnection.ts'; +import { isCCNReplaceableEvent } from '../utils/eventTypes.ts'; +import { getActiveCCN } from '../utils/getActiveCCN.ts'; +import { log } from '../utils/logs.ts'; +import { parseATagQuery } from '../utils/parseATagQuery.ts'; +import { mixQuery, sql, sqlPartial } from '../utils/queries.ts'; + +export function handleRequest( + connection: UserConnection, + request: NostrClientREQ, +) { + log.debug('start', { tag: 'handleRequest', request }); + const [, subscriptionId, ...filters] = request; + if (connection.subscriptions.has(subscriptionId)) { + return log.warn('Duplicate subscription ID', { + tag: 'handleRequest', + }); + } + + log.info( + `New subscription: ${subscriptionId} with filters: ${JSON.stringify( + filters, + )}`, + ); + + const activeCCN = getActiveCCN(connection.db); + if (!activeCCN) { + connection.sendNotice('No active CCN found'); + return log.warn('No active CCN found', { tag: 'handleRequest' }); + } + + let query = sqlPartial`SELECT * FROM events WHERE replaced = 0 AND deleted = 0 AND ccn_pubkey = ${activeCCN.pubkey}`; + + let minLimit: number | null = null; + for (const filter of filters) { + if (filter.limit && filter.limit > 0) { + minLimit = + minLimit === null ? filter.limit : Math.min(minLimit, filter.limit); + } + } + + const filtersAreNotEmpty = filters.some((filter) => { + return Object.values(filter).some((value) => { + return value.length > 0; + }); + }); + + if (filtersAreNotEmpty) { + query = mixQuery(query, sqlPartial`AND`); + + for (let i = 0; i < filters.length; i++) { + // filters act as OR, filter groups act as AND + query = mixQuery(query, sqlPartial`(`); + + const filter = Object.entries(filters[i]).filter(([type, value]) => { + if (type === 'ids') return value.length > 0; + if (type === 'authors') return value.length > 0; + if (type === 'kinds') return value.length > 0; + if (type.startsWith('#')) return value.length > 0; + if (type === 'since') return value > 0; + if (type === 'until') return value > 0; + if (type === 'limit') return value > 0; + return false; + }); + + const filterWithoutLimit = filter.filter(([type]) => type !== 'limit'); + + for (let j = 0; j < filter.length; j++) { + const [type, value] = filter[j]; + + if (type === 'ids') { + const uniqueIds = [...new Set(value)]; + query = mixQuery(query, sqlPartial`(`); + for (let k = 0; k < uniqueIds.length; k++) { + const id = uniqueIds[k] as string; + + query = mixQuery(query, sqlPartial`(id = ${id})`); + + if (k < uniqueIds.length - 1) { + query = mixQuery(query, sqlPartial`OR`); + } + } + query = mixQuery(query, sqlPartial`)`); + } + + if (type === 'authors') { + const uniqueAuthors = [...new Set(value)]; + query = mixQuery(query, sqlPartial`(`); + for (let k = 0; k < uniqueAuthors.length; k++) { + const author = uniqueAuthors[k] as string; + + query = mixQuery(query, sqlPartial`(pubkey = ${author})`); + + if (k < uniqueAuthors.length - 1) { + query = mixQuery(query, sqlPartial`OR`); + } + } + query = mixQuery(query, sqlPartial`)`); + } + + if (type === 'kinds') { + const uniqueKinds = [...new Set(value)]; + query = mixQuery(query, sqlPartial`(`); + for (let k = 0; k < uniqueKinds.length; k++) { + const kind = uniqueKinds[k] as number; + + query = mixQuery(query, sqlPartial`(kind = ${kind})`); + + if (k < uniqueKinds.length - 1) { + query = mixQuery(query, sqlPartial`OR`); + } + } + query = mixQuery(query, sqlPartial`)`); + } + + if (type.startsWith('#')) { + const tag = type.slice(1); + const uniqueValues = [...new Set(value)]; + query = mixQuery(query, sqlPartial`(`); + for (let k = 0; k < uniqueValues.length; k++) { + const tagValue = uniqueValues[k] as string; + if (tag === 'a') { + const aTagInfo = parseATagQuery(tagValue); + + if (aTagInfo.dTag && aTagInfo.dTag !== '') { + if (isCCNReplaceableEvent(aTagInfo.kind)) { + // CCN replaceable event reference + query = mixQuery( + query, + sqlPartial`id IN ( + SELECT e.id + FROM events e + JOIN event_tags t ON e.id = t.event_id + JOIN event_tags_values v ON t.tag_id = v.tag_id + WHERE e.kind = ${aTagInfo.kind} + AND t.tag_name = 'd' + AND v.value_position = 1 + AND v.value = ${aTagInfo.dTag} + )`, + ); + } else { + // Addressable event reference + query = mixQuery( + query, + sqlPartial`id IN ( + SELECT e.id + FROM events e + JOIN event_tags t ON e.id = t.event_id + JOIN event_tags_values v ON t.tag_id = v.tag_id + WHERE e.kind = ${aTagInfo.kind} + AND e.pubkey = ${aTagInfo.pubkey} + AND t.tag_name = 'd' + AND v.value_position = 1 + AND v.value = ${aTagInfo.dTag} + )`, + ); + } + } else { + // Replaceable event reference + query = mixQuery( + query, + sqlPartial`id IN ( + SELECT id + FROM events + WHERE kind = ${aTagInfo.kind} + AND pubkey = ${aTagInfo.pubkey} + )`, + ); + } + } else { + // Regular tag handling (unchanged) + query = mixQuery( + query, + sqlPartial`id IN ( + SELECT t.event_id + FROM event_tags t + WHERE t.tag_name = ${tag} + AND t.tag_id IN ( + SELECT v.tag_id + FROM event_tags_values v + WHERE v.value_position = 1 + AND v.value = ${tagValue} + ) + )`, + ); + } + + if (k < uniqueValues.length - 1) { + query = mixQuery(query, sqlPartial`OR`); + } + } + query = mixQuery(query, sqlPartial`)`); + } + + if (type === 'since') { + query = mixQuery(query, sqlPartial`created_at > ${value}`); + } + + if (type === 'until') { + query = mixQuery(query, sqlPartial`created_at <= ${value}`); + } + + if (j < filterWithoutLimit.length - 1) + query = mixQuery(query, sqlPartial`AND`); + } + + query = mixQuery(query, sqlPartial`)`); + + if (i < filters.length - 1) query = mixQuery(query, sqlPartial`OR`); + } + } + + query = mixQuery(query, sqlPartial`ORDER BY created_at ASC`); + + if (minLimit !== null) { + query = mixQuery(query, sqlPartial`LIMIT ${minLimit}`); + } + + log.debug('built query', { + tag: 'handleRequest', + query: query.query, + values: query.values, + }); + + const events = connection.db.prepare(query.query).all(...query.values); + log.debug('found events', { + tag: 'handleRequest', + count: events.length, + }); + + for (let i = 0; i < events.length; i++) { + const rawTags = sql`SELECT * FROM event_tags_view WHERE event_id = ${ + events[i].id + }`(connection.db); + const tagsByIndex = new Map< + number, + { + name: string; + values: Map; + } + >(); + + for (const tag of rawTags) { + let tagData = tagsByIndex.get(tag.tag_index); + if (!tagData) { + tagData = { + name: tag.tag_name, + values: new Map(), + }; + tagsByIndex.set(tag.tag_index, tagData); + } + + tagData.values.set(tag.tag_value_position, tag.tag_value); + } + + const tagsArray = Array.from(tagsByIndex.entries()) + .sort(([indexA], [indexB]) => indexA - indexB) + .map(([_, tagData]) => { + const { name, values } = tagData; + + return [ + name, + ...Array.from(values.entries()) + .sort(([posA], [posB]) => posA - posB) + .map(([_, value]) => value), + ]; + }); + + const event = { + id: events[i].id, + pubkey: events[i].pubkey, + created_at: events[i].created_at, + kind: events[i].kind, + tags: tagsArray, + content: events[i].content, + sig: events[i].sig, + }; + + connection.sendEvent(subscriptionId, event); + log.debug('sent event', { + tag: 'handleRequest', + subscriptionId, + eventId: event.id, + }); + } + connection.sendEOSE(subscriptionId); + log.debug('sent EOSE', { tag: 'handleRequest', subscriptionId }); + connection.subscriptions.set(subscriptionId, filters); + log.debug('end', { tag: 'handleRequest', subscriptionId }); +} diff --git a/consts.ts b/src/consts.ts similarity index 76% rename from consts.ts rename to src/consts.ts index 2b8235f..c018653 100644 --- a/consts.ts +++ b/src/consts.ts @@ -42,3 +42,18 @@ export const CHUNK_CLEANUP_INTERVAL = 1000 * 60 * 60; * database before it is considered expired and eligible for cleanup. */ export const CHUNK_MAX_AGE = 1000 * 60 * 60 * 24; + +/** + * Interval for processing the outbound event queue in milliseconds. + * + * This determines how often the relay will attempt to send pending events + * to external relays. + */ +export const QUEUE_PROCESS_INTERVAL = 10000; + +/** + * Maximum number of transmission attempts for outbound events. + * + * Events that fail to transmit this many times will be marked as permanently failed. + */ +export const MAX_TRANSMISSION_ATTEMPTS = 5; diff --git a/src/dbEvents/addEventToDb.ts b/src/dbEvents/addEventToDb.ts new file mode 100644 index 0000000..be4ffe9 --- /dev/null +++ b/src/dbEvents/addEventToDb.ts @@ -0,0 +1,331 @@ +import { bytesToHex } from '@noble/ciphers/utils'; +import { sha512 } from '@noble/hashes/sha2'; +import * as nostrTools from '@nostr/tools'; +import { base64 } from '@scure/base'; +import type { Database } from 'jsr:@db/sqlite'; +import { POW_TO_MINE } from '../consts.ts'; +import { handleDeletionEvent } from '../dbEvents/deletionEvent.ts'; +import { + EventAlreadyExistsException, + createEncryptedEventForPubkey, +} from '../eventEncryptionDecryption.ts'; +import { publishToRelays } from '../relays.ts'; +import { + isAddressableEvent, + isCCNReplaceableEvent, + isDeleteEvent, + isReplaceableEvent, +} from '../utils/eventTypes.ts'; +import { getCCNPrivateKeyByPubkey } from '../utils/getCCNPrivateKeyByPubkey.ts'; +import { log } from '../utils/logs.ts'; +import { sql } from '../utils/queries.ts'; +import { + SecurityEventType, + SecuritySeverity, + logCCNViolation, + logSecurityEvent, +} from '../utils/securityLogs.ts'; + +export function addEventToDb( + db: Database, + decryptedEvent: nostrTools.VerifiedEvent, + encryptedEvent: nostrTools.VerifiedEvent, + ccnPubkey: string, +) { + log.debug('start', { + tag: 'addEventToDb', + decryptedId: decryptedEvent.id, + encryptedId: encryptedEvent.id, + kind: decryptedEvent.kind, + ccnPubkey, + }); + const existingEvent = sql` + SELECT * FROM events WHERE id = ${decryptedEvent.id} + `(db)[0]; + + if (existingEvent) throw new EventAlreadyExistsException(); + + if (isDeleteEvent(decryptedEvent.kind)) { + log.debug('isDeleteEvent, delegating to handleDeletionEvent', { + tag: 'addEventToDb', + decryptId: decryptedEvent.id, + }); + handleDeletionEvent(db, decryptedEvent, encryptedEvent, ccnPubkey); + return; + } + + const isInvite = + decryptedEvent.tags.findIndex( + (tag: string[]) => tag[0] === 'type' && tag[1] === 'invite', + ) !== -1; + + if (isInvite) { + log.debug('isInvite event', { tag: 'addEventToDb' }); + const shadContent = bytesToHex( + sha512.create().update(decryptedEvent.content).digest(), + ); + + const inviteUsed = sql` + SELECT COUNT(*) as count FROM inviter_invitee WHERE invite_hash = ${shadContent} + `(db)[0].count; + + if (inviteUsed > 0) { + log.debug('invite already used', { tag: 'addEventToDb' }); + + logSecurityEvent({ + eventType: SecurityEventType.INVITE_ALREADY_USED, + severity: SecuritySeverity.HIGH, + source: 'invite_processing', + details: { + invite_hash: shadContent, + event_id: decryptedEvent.id, + ccn_pubkey: ccnPubkey, + invitee_pubkey: decryptedEvent.pubkey, + }, + }); + + throw new Error('Invite already used'); + } + + const inviteEvent = sql` + SELECT * FROM events WHERE kind = 9999 AND id IN ( + SELECT event_id FROM event_tags WHERE tag_name = 'i' AND tag_id IN ( + SELECT tag_id FROM event_tags_values WHERE value_position = 1 AND value = ${shadContent} + ) + ) + `(db)[0]; + + if (!inviteEvent) { + log.debug('invite event not found', { tag: 'addEventToDb' }); + + logSecurityEvent({ + eventType: SecurityEventType.INVITE_VALIDATION_FAILURE, + severity: SecuritySeverity.HIGH, + source: 'invite_processing', + details: { + error: 'invite_event_not_found', + invite_hash: shadContent, + event_id: decryptedEvent.id, + ccn_pubkey: ccnPubkey, + }, + }); + + throw new Error('Invite event not found'); + } + + const inviterPubkey = inviteEvent.pubkey; + const inviteePubkey = decryptedEvent.pubkey; + + db.run('BEGIN TRANSACTION'); + log.debug('inserting inviter_invitee and allowed_writes', { + tag: 'addEventToDb', + }); + sql` + INSERT INTO inviter_invitee (ccn_pubkey, inviter_pubkey, invitee_pubkey, invite_hash) VALUES (${ccnPubkey}, ${inviterPubkey}, ${inviteePubkey}, ${shadContent}) + `(db); + + sql` + INSERT INTO allowed_writes (ccn_pubkey, pubkey) VALUES (${ccnPubkey}, ${inviteePubkey}) + `(db); + + db.run('COMMIT TRANSACTION'); + log.debug('committed invite transaction', { tag: 'addEventToDb' }); + + const allowedPubkeys = sql` + SELECT pubkey FROM allowed_writes WHERE ccn_pubkey = ${ccnPubkey} + `(db).flatMap((row) => row.pubkey); + const ccnName = sql` + SELECT name FROM ccns WHERE pubkey = ${ccnPubkey} + `(db)[0].name; + + getCCNPrivateKeyByPubkey(ccnPubkey).then((ccnPrivateKey) => { + if (!ccnPrivateKey) { + log.error('CCN private key not found', { tag: 'addEventToDb' }); + throw new Error('CCN private key not found'); + } + + const tags = allowedPubkeys.map((pubkey) => ['p', pubkey]); + tags.push(['t', 'invite']); + tags.push(['name', ccnName]); + + const privateKeyEvent = nostrTools.finalizeEvent( + nostrTools.nip13.minePow( + { + kind: 9998, + created_at: Date.now(), + content: base64.encode(ccnPrivateKey), + tags, + pubkey: ccnPubkey, + }, + POW_TO_MINE, + ), + ccnPrivateKey, + ); + + const encryptedKeyEvent = createEncryptedEventForPubkey( + inviteePubkey, + privateKeyEvent, + ); + publishToRelays(encryptedKeyEvent); + log.debug('published encryptedKeyEvent to relays', { + tag: 'addEventToDb', + }); + }); + + return; + } + + const isAllowedWrite = sql` + SELECT COUNT(*) as count FROM allowed_writes WHERE ccn_pubkey = ${ccnPubkey} AND pubkey = ${decryptedEvent.pubkey} + `(db)[0].count; + + if (isAllowedWrite === 0) { + log.debug('not allowed to write to this CCN', { + tag: 'addEventToDb', + pubkey: decryptedEvent.pubkey, + }); + + logCCNViolation( + SecurityEventType.UNAUTHORIZED_WRITE_ATTEMPT, + ccnPubkey, + 'write_event', + { + attempted_pubkey: decryptedEvent.pubkey, + event_id: decryptedEvent.id, + event_kind: decryptedEvent.kind, + ccn_pubkey: ccnPubkey, + }, + ); + + throw new Error('Not allowed to write to this CCN'); + } + + try { + db.run('BEGIN TRANSACTION'); + log.debug('begin transaction', { tag: 'addEventToDb' }); + + if (isReplaceableEvent(decryptedEvent.kind)) { + log.debug('isReplaceableEvent, updating replaced events', { + tag: 'addEventToDb', + }); + sql` + UPDATE events + SET replaced = 1 + WHERE kind = ${decryptedEvent.kind} + AND pubkey = ${decryptedEvent.pubkey} + AND ccn_pubkey = ${ccnPubkey} + AND (created_at < ${decryptedEvent.created_at} OR + (created_at = ${decryptedEvent.created_at} AND id > ${decryptedEvent.id})) + `(db); + } + + if (isAddressableEvent(decryptedEvent.kind)) { + log.debug('isAddressableEvent, updating replaced events', { + tag: 'addEventToDb', + }); + const dTag = decryptedEvent.tags.find((tag) => tag[0] === 'd')?.[1]; + if (dTag) { + sql` + UPDATE events + SET replaced = 1 + WHERE kind = ${decryptedEvent.kind} + AND pubkey = ${decryptedEvent.pubkey} + AND ccn_pubkey = ${ccnPubkey} + AND (created_at < ${decryptedEvent.created_at} OR + (created_at = ${decryptedEvent.created_at} AND id > ${decryptedEvent.id})) + AND id IN ( + SELECT event_id FROM event_tags + WHERE tag_name = 'd' + AND tag_id IN ( + SELECT tag_id FROM event_tags_values + WHERE value_position = 1 + AND value = ${dTag} + ) + ) + `(db); + } + } + + if (isCCNReplaceableEvent(decryptedEvent.kind)) { + log.debug('isCCNReplaceableEvent, updating replaced events', { + tag: 'addEventToDb', + }); + const dTag = decryptedEvent.tags.find((tag) => tag[0] === 'd')?.[1]; + log.debug('dTag', { tag: 'addEventToDb', dTag }); + if (dTag) { + sql` + UPDATE events + SET replaced = 1 + WHERE kind = ${decryptedEvent.kind} + AND ccn_pubkey = ${ccnPubkey} + AND (created_at < ${decryptedEvent.created_at} OR + (created_at = ${decryptedEvent.created_at} AND id > ${decryptedEvent.id})) + AND id IN ( + SELECT event_id FROM event_tags + WHERE tag_name = 'd' + AND tag_id IN ( + SELECT tag_id FROM event_tags_values + WHERE value_position = 1 + AND value = ${dTag} + ) + ) + `(db); + } else { + sql` + UPDATE events + SET replaced = 1 + WHERE kind = ${decryptedEvent.kind} + AND ccn_pubkey = ${ccnPubkey} + AND (created_at < ${decryptedEvent.created_at} OR + (created_at = ${decryptedEvent.created_at} AND id > ${decryptedEvent.id})) + `(db); + } + } + + sql` + INSERT INTO events (id, original_id, pubkey, created_at, kind, content, sig, first_seen, ccn_pubkey) VALUES ( + ${decryptedEvent.id}, + ${encryptedEvent.id}, + ${decryptedEvent.pubkey}, + ${decryptedEvent.created_at}, + ${decryptedEvent.kind}, + ${decryptedEvent.content}, + ${decryptedEvent.sig}, + unixepoch(), + ${ccnPubkey} + ) + `(db); + log.debug('inserted event', { tag: 'addEventToDb', id: decryptedEvent.id }); + if (decryptedEvent.tags) { + for (let i = 0; i < decryptedEvent.tags.length; i++) { + const tag = sql` + INSERT INTO event_tags(event_id, tag_name, tag_index) VALUES ( + ${decryptedEvent.id}, + ${decryptedEvent.tags[i][0]}, + ${i} + ) RETURNING tag_id + `(db)[0]; + for (let j = 1; j < decryptedEvent.tags[i].length; j++) { + sql` + INSERT INTO event_tags_values(tag_id, value_position, value) VALUES ( + ${tag.tag_id}, + ${j}, + ${decryptedEvent.tags[i][j]} + ) + `(db); + } + } + log.debug('inserted tags for event', { + tag: 'addEventToDb', + id: decryptedEvent.id, + }); + } + db.run('COMMIT TRANSACTION'); + log.debug('committed transaction', { tag: 'addEventToDb' }); + } catch (e) { + db.run('ROLLBACK TRANSACTION'); + log.error('transaction rolled back', { tag: 'addEventToDb', error: e }); + throw e; + } + log.debug('end', { tag: 'addEventToDb', id: decryptedEvent.id }); +} diff --git a/src/dbEvents/deletionEvent.ts b/src/dbEvents/deletionEvent.ts new file mode 100644 index 0000000..f98c72f --- /dev/null +++ b/src/dbEvents/deletionEvent.ts @@ -0,0 +1,143 @@ +import type { Database } from '@db/sqlite'; +import type * as nostrTools from '@nostr/tools'; +import { isAddressableEvent, isReplaceableEvent } from '../utils/eventTypes.ts'; +import { log } from '../utils/logs.ts'; +import { parseATagQuery } from '../utils/parseATagQuery.ts'; +import { sql } from '../utils/queries.ts'; + +export function handleDeletionEvent( + db: Database, + deletionEvent: nostrTools.VerifiedEvent, + encryptedEvent: nostrTools.VerifiedEvent, + ccnPubkey: string, +): void { + log.debug('start', { + tag: 'handleDeletionEvent', + decryptId: deletionEvent.id, + encryptedId: encryptedEvent.id, + kind: deletionEvent.kind, + ccnPubkey, + }); + + try { + db.run('BEGIN TRANSACTION'); + log.debug('begin transaction', { tag: 'handleDeletionEvent' }); + + sql` + INSERT INTO events (id, original_id, pubkey, created_at, kind, content, sig, first_seen, ccn_pubkey) VALUES ( + ${deletionEvent.id}, + ${encryptedEvent.id}, + ${deletionEvent.pubkey}, + ${deletionEvent.created_at}, + ${deletionEvent.kind}, + ${deletionEvent.content}, + ${deletionEvent.sig}, + unixepoch(), + ${ccnPubkey} + ) + `(db); + + if (deletionEvent.tags) { + for (let i = 0; i < deletionEvent.tags.length; i++) { + const tag = sql` + INSERT INTO event_tags(event_id, tag_name, tag_index) VALUES ( + ${deletionEvent.id}, + ${deletionEvent.tags[i][0]}, + ${i} + ) RETURNING tag_id + `(db)[0]; + + for (let j = 1; j < deletionEvent.tags[i].length; j++) { + sql` + INSERT INTO event_tags_values(tag_id, value_position, value) VALUES ( + ${tag.tag_id}, + ${j}, + ${deletionEvent.tags[i][j]} + ) + `(db); + } + } + } + + for (const tag of deletionEvent.tags) { + if (tag[0] === 'e' && tag[1]) { + sql` + UPDATE events + SET deleted = 1 + WHERE id = ${tag[1]} + AND pubkey = ${deletionEvent.pubkey} + AND ccn_pubkey = ${ccnPubkey} + `(db); + log.debug('deleted event by id', { + tag: 'handleDeletionEvent', + eventId: tag[1], + }); + } else if (tag[0] === 'a' && tag[1]) { + const { kind, pubkey, dTag } = parseATagQuery(tag[1]); + if (!kind || !pubkey) continue; + if (pubkey !== deletionEvent.pubkey) continue; + if (isReplaceableEvent(kind)) { + sql` + UPDATE events + SET deleted = 1 + WHERE kind = ${kind} + AND pubkey = ${pubkey} + AND ccn_pubkey = ${ccnPubkey} + AND created_at <= ${deletionEvent.created_at} + `(db); + log.debug('deleted replaceable event', { + tag: 'handleDeletionEvent', + kind, + pubkey, + }); + } else if (isAddressableEvent(kind) && dTag) { + sql` + UPDATE events + SET deleted = 1 + WHERE kind = ${kind} + AND pubkey = ${pubkey} + AND ccn_pubkey = ${ccnPubkey} + AND created_at <= ${deletionEvent.created_at} + AND id IN ( + SELECT event_id FROM event_tags + WHERE tag_name = 'd' + AND tag_id IN ( + SELECT tag_id FROM event_tags_values + WHERE value_position = 1 AND value = ${dTag} + ) + ) + `(db); + log.debug('deleted addressable event', { + tag: 'handleDeletionEvent', + kind, + pubkey, + dTag, + }); + } + } else if (tag[0] === 'k') { + sql` + UPDATE events + SET deleted = 1 + WHERE kind = ${tag[1]} + AND pubkey = ${deletionEvent.pubkey} + AND ccn_pubkey = ${ccnPubkey} + AND created_at <= ${deletionEvent.created_at} + `(db); + log.debug('deleted events of kind', { + tag: 'handleDeletionEvent', + kind: tag[1], + }); + } + } + db.run('COMMIT TRANSACTION'); + log.debug('committed transaction', { tag: 'handleDeletionEvent' }); + } catch (e) { + db.run('ROLLBACK TRANSACTION'); + log.error('transaction rolled back', { + tag: 'handleDeletionEvent', + error: e, + }); + throw e; + } + log.debug('end', { tag: 'handleDeletionEvent', id: deletionEvent.id }); +} diff --git a/eventEncryptionDecryption.ts b/src/eventEncryptionDecryption.ts similarity index 63% rename from eventEncryptionDecryption.ts rename to src/eventEncryptionDecryption.ts index 2553ee5..f21f6fb 100644 --- a/eventEncryptionDecryption.ts +++ b/src/eventEncryptionDecryption.ts @@ -2,14 +2,13 @@ import type { Database } from '@db/sqlite'; import * as nostrTools from '@nostr/tools'; import { nip44 } from '@nostr/tools'; import { MAX_CHUNK_SIZE, MIN_POW, POW_TO_MINE } from './consts.ts'; -import { - getActiveCCN, - getAllCCNs, - getCCNPrivateKeyByPubkey, - randomTimeUpTo2DaysInThePast, -} from './utils.ts'; +import { getActiveCCN } from './utils/getActiveCCN.ts'; +import { getAllCCNs } from './utils/getAllCCNs.ts'; +import { getCCNPrivateKeyByPubkey } from './utils/getCCNPrivateKeyByPubkey.ts'; +import { log } from './utils/logs.ts'; import { None, type Option, Some, flatMap, map } from './utils/option.ts'; import { sql } from './utils/queries.ts'; +import { randomTimeUpTo2DaysInThePast } from './utils/randomTimeUpTo2DaysInThePast.ts'; export class EventAlreadyExistsException extends Error {} export class ChunkedEventReceived extends Error {} @@ -183,34 +182,142 @@ function handleChunkedMessage( throw new Error('Invalid chunked message format'); } - const [_, chunkIndex, totalChunks, messageId] = chunkTag; + const [_, chunkIndexStr, totalChunksStr, messageId] = chunkTag; + const chunkIndex = Number(chunkIndexStr); + const totalChunks = Number(totalChunksStr); + + if (!Number.isInteger(chunkIndex) || chunkIndex < 0) { + throw new Error('Invalid chunk index'); + } + if ( + !Number.isInteger(totalChunks) || + totalChunks <= 0 || + totalChunks > 1000 + ) { + throw new Error('Invalid total chunks count'); + } + if (chunkIndex >= totalChunks) { + throw new Error('Chunk index exceeds total chunks'); + } + if (!messageId || typeof messageId !== 'string' || messageId.length > 100) { + throw new Error('Invalid message ID'); + } + const chunk = nip44.decrypt(seal.content, conversationKey); - const storedChunks = sql` - SELECT COUNT(*) as count - FROM event_chunks - WHERE message_id = ${messageId} - `(db)[0].count; + if (chunk.length > MAX_CHUNK_SIZE * 3) { + throw new Error('Chunk content too large'); + } - sql` - INSERT INTO event_chunks (message_id, chunk_index, total_chunks, content, created_at, ccn_pubkey) - VALUES (${messageId}, ${chunkIndex}, ${totalChunks}, ${chunk}, ${Math.floor(Date.now() / 1000)}, ${ccnPubkey}) - `(db); + let isMessageComplete = false; + let reconstructedEvent: nostrTools.VerifiedEvent | null = null; - if (storedChunks + 1 === Number(totalChunks)) { - const allChunks = sql` - SELECT * FROM event_chunks - WHERE message_id = ${messageId} - ORDER BY chunk_index - `(db); + try { + db.run('BEGIN IMMEDIATE TRANSACTION'); - let fullContent = ''; - for (const chunk of allChunks) { - fullContent += chunk.content; + const insertStmt = db.prepare(` + INSERT OR IGNORE INTO event_chunks + (message_id, chunk_index, total_chunks, content, created_at, ccn_pubkey) + VALUES (?, ?, ?, ?, ?, ?) + `); + + const insertResult = insertStmt.run( + messageId, + chunkIndex, + totalChunks, + chunk, + Math.floor(Date.now() / 1000), + ccnPubkey, + ); + + if (insertResult === 0) { + db.run('ROLLBACK TRANSACTION'); + throw new ChunkedEventReceived(); } - const content = JSON.parse(fullContent); - return { ...content, ccnPubkey }; + const currentChunkCount = sql` + SELECT COUNT(DISTINCT chunk_index) as count + FROM event_chunks + WHERE message_id = ${messageId} + AND ccn_pubkey = ${ccnPubkey} + AND total_chunks = ${totalChunks} + `(db)[0].count; + + if (currentChunkCount === totalChunks) { + const chunkGapCheck = sql` + SELECT COUNT(*) as count + FROM event_chunks + WHERE message_id = ${messageId} + AND ccn_pubkey = ${ccnPubkey} + AND chunk_index NOT IN ( + SELECT DISTINCT chunk_index + FROM event_chunks + WHERE message_id = ${messageId} + AND ccn_pubkey = ${ccnPubkey} + ORDER BY chunk_index + LIMIT ${totalChunks} + ) + `(db)[0].count; + + if (chunkGapCheck > 0) { + db.run('ROLLBACK TRANSACTION'); + throw new Error('Chunk sequence validation failed'); + } + + const allChunks = sql` + SELECT content, chunk_index + FROM event_chunks + WHERE message_id = ${messageId} + AND ccn_pubkey = ${ccnPubkey} + ORDER BY chunk_index + `(db); + + let fullContent = ''; + for (let i = 0; i < allChunks.length; i++) { + const chunkData = allChunks[i]; + if (chunkData.chunk_index !== i) { + db.run('ROLLBACK TRANSACTION'); + throw new Error('Chunk sequence integrity violation'); + } + fullContent += chunkData.content; + } + + if (fullContent.length === 0) { + db.run('ROLLBACK TRANSACTION'); + throw new Error('Empty reconstructed content'); + } + + try { + const content = JSON.parse(fullContent); + reconstructedEvent = { ...content, ccnPubkey }; + isMessageComplete = true; + + sql` + DELETE FROM event_chunks + WHERE message_id = ${messageId} + AND ccn_pubkey = ${ccnPubkey} + `(db); + } catch { + db.run('ROLLBACK TRANSACTION'); + throw new Error('Failed to parse reconstructed message content'); + } + } + + db.run('COMMIT TRANSACTION'); + } catch (error) { + try { + db.run('ROLLBACK TRANSACTION'); + } catch (rollbackError) { + log.error('Failed to rollback transaction', { + tag: 'handleChunkedMessage', + error: rollbackError, + }); + } + throw error; + } + + if (isMessageComplete && reconstructedEvent) { + return reconstructedEvent; } throw new ChunkedEventReceived(); @@ -229,7 +336,13 @@ export async function decryptEvent( throw new Error('No CCNs found'); } - const pow = nostrTools.nip13.getPow(event.id); + if ( + nostrTools.nip13.getPow(event.id) < MIN_POW && + !event.tags.some((t) => t[0] === 'type' && t[1] === 'invite') + ) { + throw new Error('Cannot decrypt event -- PoW too low'); + } + const isInvite = event.tags.findIndex( (tag: string[]) => tag[0] === 'type' && tag[1] === 'invite', @@ -260,10 +373,6 @@ export async function decryptEvent( throw new Error('Cannot decrypt invite'); } - if (pow < MIN_POW) { - throw new Error('Cannot decrypt event -- PoW too low'); - } - const ccnPrivkey = await getCCNPrivateKeyByPubkey(eventDestination); const decryptedEvent = attemptDecryptWithKey( event, @@ -275,13 +384,13 @@ export async function decryptEvent( } try { - const chuncked = handleChunkedMessage( + const chunked = handleChunkedMessage( db, event, ccnPrivkey, eventDestination, ); - return { ...chuncked, ccnPubkey: eventDestination }; + return { ...chunked, ccnPubkey: eventDestination }; } catch (e) { if (e instanceof ChunkedEventReceived) { throw e; diff --git a/src/index.ts b/src/index.ts new file mode 100644 index 0000000..311752a --- /dev/null +++ b/src/index.ts @@ -0,0 +1,397 @@ +import { randomBytes } from '@noble/ciphers/webcrypto'; +import * as nostrTools from '@nostr/tools'; +import { Database } from 'jsr:@db/sqlite'; +import { NSchema as n } from 'jsr:@nostrify/nostrify'; +import { encodeBase64 } from 'jsr:@std/encoding@0.224/base64'; +import { UserConnection } from './UserConnection.ts'; +import { handleCCNCommands } from './commands/ccn.ts'; +import { handleClose } from './commands/close.ts'; +import { handleEvent } from './commands/event.ts'; +import { handleRequest } from './commands/request.ts'; +import { CHUNK_CLEANUP_INTERVAL, QUEUE_PROCESS_INTERVAL } from './consts.ts'; +import { addEventToDb } from './dbEvents/addEventToDb.ts'; +import { + ChunkedEventReceived, + EventAlreadyExistsException, + decryptEvent, +} from './eventEncryptionDecryption.ts'; +import { runMigrations } from './migrations.ts'; +import { pool, relays } from './relays.ts'; +import { cleanupOldChunks } from './utils/cleanupOldChunks.ts'; +import { getEveFilePath } from './utils/files.ts'; +import { getEncryptedEventByOriginalId } from './utils/getEncryptedEventByOriginalId.ts'; +import { isArray } from './utils/isArray.ts'; +import { isLocalhost } from './utils/isLocalhost.ts'; +import { isValidJSON } from './utils/isValidJSON.ts'; +import { + isOriginalEventIdCached, + updateKnownEventsCache, +} from './utils/knownEventsCache.ts'; +import { log, setupLogger } from './utils/logs.ts'; +import { + getQueueStats, + processOutboundQueue, + processStartupQueue, +} from './utils/outboundQueue.ts'; +import { sql } from './utils/queries.ts'; +import { + SecurityEventType, + SecuritySeverity, + logSecurityEvent, + logSystemEvent, +} from './utils/securityLogs.ts'; + +await setupLogger(null); +await Deno.mkdir(await getEveFilePath('ccn_keys'), { recursive: true }); + +logSystemEvent(SecurityEventType.SYSTEM_STARTUP, { + version: 'alpha', + deno_version: Deno.version.deno, + timestamp: new Date().toISOString(), +}); + +if (!Deno.env.has('ENCRYPTION_KEY')) { + const newKey = encodeBase64(randomBytes(32)); + log.error( + `Missing ENCRYPTION_KEY. Please set it in your env.\nA new one has been generated for you: ENCRYPTION_KEY="${newKey}"`, + ); + + logSecurityEvent({ + eventType: SecurityEventType.CONFIGURATION_LOADED, + severity: SecuritySeverity.CRITICAL, + source: 'startup', + details: { + error: 'missing_encryption_key', + generated_new_key: true, + }, + }); + + Deno.exit(1); +} + +logSystemEvent(SecurityEventType.CONFIGURATION_LOADED, { + encryption_key_present: true, + ccn_keys_directory: await getEveFilePath('ccn_keys'), +}); + +export const db = new Database(await getEveFilePath('db')); +await setupLogger(db); + +/** + * Creates a subscription event handler for processing encrypted events. + * This handler decrypts and adds valid events to the database. + * @param database The database instance to use + * @returns An event handler function + */ +function createSubscriptionEventHandler(db: Database) { + return async (event: nostrTools.Event) => { + if (isOriginalEventIdCached(event.id)) return; + if (!nostrTools.verifyEvent(event)) { + log.warn('Invalid event received'); + + logSecurityEvent({ + eventType: SecurityEventType.INVALID_SIGNATURE, + severity: SecuritySeverity.MEDIUM, + source: 'event_processing', + details: { + event_id: event.id, + event_kind: event.kind, + pubkey: event.pubkey, + }, + }); + + return; + } + if (getEncryptedEventByOriginalId(db, event)) return; + try { + const decryptedEvent = await decryptEvent(db, event); + addEventToDb(db, decryptedEvent, event, decryptedEvent.ccnPubkey); + updateKnownEventsCache(); + } catch (e) { + if (e instanceof EventAlreadyExistsException) { + logSecurityEvent({ + eventType: SecurityEventType.DUPLICATE_EVENT_BLOCKED, + severity: SecuritySeverity.LOW, + source: 'event_processing', + details: { + event_id: event.id, + reason: 'event_already_exists', + }, + }); + return; + } + if (e instanceof ChunkedEventReceived) { + logSecurityEvent({ + eventType: SecurityEventType.CHUNKED_EVENT_RECEIVED, + severity: SecuritySeverity.LOW, + source: 'event_processing', + details: { + event_id: event.id, + event_kind: event.kind, + }, + }); + return; + } + + logSecurityEvent({ + eventType: SecurityEventType.DECRYPTION_FAILURE, + severity: SecuritySeverity.MEDIUM, + source: 'event_processing', + details: { + operation: 'event_decryption', + event_id: event.id, + event_kind: event.kind, + error_message: e instanceof Error ? e.message : 'Unknown error', + }, + }); + } + }; +} + +function setupAndSubscribeToExternalEvents() { + const isInitialized = sql` + SELECT name FROM sqlite_master WHERE type='table' AND name='migration_history' + `(db)[0]; + + if (!isInitialized) runMigrations(db, -1); + + const latestVersion = + sql` + SELECT migration_version FROM migration_history WHERE status = 'success' ORDER BY migration_version DESC LIMIT 1 + `(db)[0]?.migration_version ?? -1; + + runMigrations(db, latestVersion); + + logSystemEvent(SecurityEventType.SYSTEM_STARTUP, { + database_logging_enabled: true, + migrations_complete: true, + }); + + const allCCNs = sql`SELECT pubkey FROM ccns`(db); + const ccnPubkeys = allCCNs.map((ccn) => ccn.pubkey); + + pool.subscribeMany( + relays, + [ + { + '#p': ccnPubkeys, + kinds: [1059], + }, + ], + { + onevent: createSubscriptionEventHandler(db), + }, + ); + + updateKnownEventsCache(); + setInterval(() => cleanupOldChunks(db), CHUNK_CLEANUP_INTERVAL); + + processStartupQueue(db).catch((error: unknown) => { + log.error('Startup queue processing failed', { + tag: 'outboundQueue', + error: error instanceof Error ? error.message : 'Unknown error', + }); + }); + + setInterval(async () => { + try { + await processOutboundQueue(db); + + const stats = getQueueStats(db); + if (stats.total > 0) { + log.info('Outbound queue status', { + tag: 'outboundQueue', + ...stats, + }); + } + } catch (error) { + log.error('Error processing outbound queue', { + tag: 'outboundQueue', + error: error instanceof Error ? error.message : 'Unknown error', + }); + } + }, QUEUE_PROCESS_INTERVAL); + + processOutboundQueue(db).catch((error) => { + log.error('Initial queue processing failed', { + tag: 'outboundQueue', + error: error instanceof Error ? error.message : 'Unknown error', + }); + }); + + log.info('Outbound queue processor started', { + tag: 'outboundQueue', + interval: QUEUE_PROCESS_INTERVAL, + }); +} + +setupAndSubscribeToExternalEvents(); + +export function handleSocketError( + connection: UserConnection, + operation: string, + error: unknown, +): void { + const errorMessage = error instanceof Error ? error.message : 'Unknown error'; + log.error(`Error ${operation}: ${errorMessage}`); + connection.sendNotice(`Failed to ${operation}`); +} + +Deno.serve({ + port: 6942, + handler: (request, connInfo) => { + if (request.headers.get('upgrade') === 'websocket') { + if (!isLocalhost(request, connInfo)) { + logSecurityEvent({ + eventType: SecurityEventType.NON_LOCALHOST_CONNECTION_BLOCKED, + severity: SecuritySeverity.HIGH, + source: 'connection_security', + details: { + remote_addr: connInfo?.remoteAddr, + user_agent: request.headers.get('user-agent'), + host: request.headers.get('host'), + origin: request.headers.get('origin'), + }, + remoteAddr: + connInfo?.remoteAddr?.transport === 'tcp' + ? connInfo.remoteAddr.hostname + : 'unknown', + }); + + return new Response( + 'Forbidden. Please read the Arx-CCN documentation for more information on how to interact with the relay.', + { status: 403 }, + ); + } + + log.info('upgrading connection', { tag: 'WebSocket' }); + const { socket, response } = Deno.upgradeWebSocket(request); + + const connection = new UserConnection(socket, new Map(), db); + + socket.onopen = () => { + log.info('User connected'); + + logSecurityEvent({ + eventType: SecurityEventType.WEBSOCKET_CONNECTION_ESTABLISHED, + severity: SecuritySeverity.LOW, + source: 'connection_security', + details: { + remote_addr: connInfo?.remoteAddr, + user_agent: request.headers.get('user-agent'), + connection_time: new Date().toISOString(), + }, + remoteAddr: + connInfo?.remoteAddr?.transport === 'tcp' + ? connInfo.remoteAddr.hostname + : 'localhost', + }); + }; + + socket.onmessage = (event) => { + log.debug('Received', { + tag: 'WebSocket', + data: event.data, + }); + + if (typeof event.data !== 'string' || !isValidJSON(event.data)) { + log.warn('Invalid request', { tag: 'WebSocket' }); + + logSecurityEvent({ + eventType: SecurityEventType.MALFORMED_EVENT, + severity: SecuritySeverity.MEDIUM, + source: 'websocket_handler', + details: { + data_type: typeof event.data, + is_valid_json: isValidJSON(event.data), + data_length: event.data?.length || 0, + }, + remoteAddr: + connInfo?.remoteAddr?.transport === 'tcp' + ? connInfo.remoteAddr.hostname + : 'localhost', + }); + + return; + } + + const data = JSON.parse(event.data); + if (!isArray(data)) { + logSecurityEvent({ + eventType: SecurityEventType.MALFORMED_EVENT, + severity: SecuritySeverity.MEDIUM, + source: 'websocket_handler', + details: { + error: 'message_not_array', + received_type: typeof data, + }, + remoteAddr: + connInfo?.remoteAddr?.transport === 'tcp' + ? connInfo.remoteAddr.hostname + : 'localhost', + }); + + return log.warn('Invalid request', { tag: 'WebSocket' }); + } + + const msgType = data[0]; + log.debug('received message', { tag: 'WebSocket', msgType }); + + switch (msgType) { + case 'REQ': + return handleRequest(connection, n.clientREQ().parse(data)); + case 'EVENT': + return handleEvent(connection, n.clientEVENT().parse(data)[1]); + case 'CLOSE': + return handleClose(connection, n.clientCLOSE().parse(data)[1]); + case 'CCN': + return handleCCNCommands(connection, data[1] as string, data[2]); + default: + logSecurityEvent({ + eventType: SecurityEventType.MALFORMED_EVENT, + severity: SecuritySeverity.MEDIUM, + source: 'websocket_handler', + details: { + error: 'unknown_message_type', + message_type: msgType, + data_preview: data.slice(0, 3), // First 3 elements for debugging + }, + remoteAddr: + connInfo?.remoteAddr?.transport === 'tcp' + ? connInfo.remoteAddr.hostname + : 'localhost', + }); + + log.warn('Invalid request', { tag: 'WebSocket' }); + return; + } + }; + + socket.onclose = () => { + log.info('User disconnected'); + + logSecurityEvent({ + eventType: SecurityEventType.WEBSOCKET_CONNECTION_CLOSED, + severity: SecuritySeverity.LOW, + source: 'connection_security', + details: { + disconnect_time: new Date().toISOString(), + subscriptions_count: connection.subscriptions.size, + }, + remoteAddr: + connInfo?.remoteAddr?.transport === 'tcp' + ? connInfo.remoteAddr.hostname + : 'localhost', + }); + }; + + return response; + } + return new Response( + Deno.readTextFileSync(`${import.meta.dirname}/../public/landing.html`), + { + headers: { 'Content-Type': 'text/html' }, + }, + ); + }, +}); diff --git a/src/migrations.ts b/src/migrations.ts new file mode 100644 index 0000000..9488a6f --- /dev/null +++ b/src/migrations.ts @@ -0,0 +1,55 @@ +import type { Database } from '@db/sqlite'; +import { log } from './utils/logs.ts'; +import { sql } from './utils/queries.ts'; + +export function runMigrations(db: Database, latestVersion: number) { + const migrations = [ + ...Deno.readDirSync(`${import.meta.dirname}/../migrations`), + ]; + migrations.sort((a, b) => { + const aVersion = Number.parseInt(a.name.split('-')[0], 10); + const bVersion = Number.parseInt(b.name.split('-')[0], 10); + return aVersion - bVersion; + }); + for (const migrationFile of migrations) { + const migrationVersion = Number.parseInt( + migrationFile.name.split('-')[0], + 10, + ); + + if (migrationVersion > latestVersion) { + log.info( + `Running migration ${migrationFile.name} (version ${migrationVersion})`, + ); + const start = Date.now(); + const migrationSql = Deno.readTextFileSync( + `${import.meta.dirname}/../migrations/${migrationFile.name}`, + ); + db.run('BEGIN TRANSACTION'); + try { + db.run(migrationSql); + const end = Date.now(); + const durationMs = end - start; + sql` + INSERT INTO migration_history (migration_version, migration_name, executed_at, duration_ms, status) VALUES (${migrationVersion}, ${migrationFile.name}, ${new Date().toISOString()}, ${durationMs}, 'success'); + db.run("COMMIT TRANSACTION"); + `(db); + } catch (e) { + db.run('ROLLBACK TRANSACTION'); + const error = + e instanceof Error + ? e + : typeof e === 'string' + ? new Error(e) + : new Error(JSON.stringify(e)); + const end = Date.now(); + const durationMs = end - start; + sql` + INSERT INTO migration_history (migration_version, migration_name, executed_at, duration_ms, status, error_message) VALUES (${migrationVersion}, ${migrationFile.name}, ${new Date().toISOString()}, ${durationMs}, 'failed', ${error.message}); + `(db); + throw e; + } + db.run('END TRANSACTION'); + } + } +} diff --git a/src/relays.ts b/src/relays.ts new file mode 100644 index 0000000..a1807f4 --- /dev/null +++ b/src/relays.ts @@ -0,0 +1,39 @@ +import * as nostrTools from '@nostr/tools'; +import { isArray } from './utils/isArray.ts'; + +export const pool = new nostrTools.SimplePool(); +export const relays = [ + 'wss://relay.arx-ccn.com/', + 'wss://relay.dannymorabito.com/', + 'wss://nos.lol/', + 'wss://nostr.einundzwanzig.space/', + 'wss://nostr.massmux.com/', + 'wss://nostr.mom/', + 'wss://nostr.wine/', + 'wss://purplerelay.com/', + 'wss://relay.damus.io/', + 'wss://relay.goodmorningbitcoin.com/', + 'wss://relay.lexingtonbitcoin.org/', + 'wss://relay.nostr.band/', + 'wss://relay.primal.net/', + 'wss://relay.snort.social/', + 'wss://strfry.iris.to/', + 'wss://cache2.primal.net/v1', +]; + +/** + * FIXME: make sure to somehow tag encryptedEvents and add asserts, so that it's not possible to accidentally call this function with unencrypted events + * + * @param encryptedEvent the event to publish to the relay + */ +export async function publishToRelays( + encryptedEvent: nostrTools.Event | nostrTools.Event[], +): Promise { + if (isArray(encryptedEvent)) { + for (const chunk of encryptedEvent) { + await Promise.any(pool.publish(relays, chunk)); + } + } else { + await Promise.any(pool.publish(relays, encryptedEvent)); + } +} diff --git a/src/utils/cleanupOldChunks.ts b/src/utils/cleanupOldChunks.ts new file mode 100644 index 0000000..899baf3 --- /dev/null +++ b/src/utils/cleanupOldChunks.ts @@ -0,0 +1,8 @@ +import type { Database } from 'jsr:@db/sqlite'; +import { CHUNK_MAX_AGE } from '../consts.ts'; +import { sql } from './queries.ts'; + +export function cleanupOldChunks(db: Database) { + const cutoffTime = Math.floor((Date.now() - CHUNK_MAX_AGE) / 1000); + sql`DELETE FROM event_chunks WHERE created_at < ${cutoffTime}`(db); +} diff --git a/src/utils/createNewCCN.ts b/src/utils/createNewCCN.ts new file mode 100644 index 0000000..ac9124c --- /dev/null +++ b/src/utils/createNewCCN.ts @@ -0,0 +1,52 @@ +import { encodeBase64 } from 'jsr:@std/encoding@~0.224.1/base64'; +import type { Database } from '@db/sqlite'; +import * as nostrTools from '@nostr/tools'; +import * as nip06 from '@nostr/tools/nip06'; +import { encryptUint8Array, encryptionKey } from './encryption.ts'; +import { getEveFilePath } from './files.ts'; +import { sql } from './queries.ts'; + +/** + * Create a new CCN and store it in the database + * + * @param db - The database instance + * @param name - The name of the CCN + * @param seed - The seed words for the CCN + * @returns The public key and private key of the CCN + */ + +export async function createNewCCN( + db: Database, + name: string, + creator: string, + seed?: string, +): Promise<{ pubkey: string; privkey: Uint8Array }> { + const ccnSeed = seed || nip06.generateSeedWords(); + const ccnPrivateKey = nip06.privateKeyFromSeedWords(ccnSeed); + const ccnPublicKey = nostrTools.getPublicKey(ccnPrivateKey); + + const ccnSeedPath = await getEveFilePath(`ccn_seeds/${ccnPublicKey}`); + const ccnPrivPath = await getEveFilePath(`ccn_keys/${ccnPublicKey}`); + + await Deno.mkdir(await getEveFilePath('ccn_seeds'), { recursive: true }); + await Deno.mkdir(await getEveFilePath('ccn_keys'), { recursive: true }); + + const encryptedPrivateKey = encryptUint8Array(ccnPrivateKey, encryptionKey); + + Deno.writeTextFileSync(ccnSeedPath, ccnSeed); + Deno.writeTextFileSync(ccnPrivPath, encodeBase64(encryptedPrivateKey)); + + db.run('BEGIN TRANSACTION'); + + sql`INSERT INTO ccns (pubkey, name) VALUES (${ccnPublicKey}, ${name})`(db); + sql`INSERT INTO allowed_writes (ccn_pubkey, pubkey) VALUES (${ccnPublicKey}, ${creator})`( + db, + ); + + db.run('COMMIT TRANSACTION'); + + return { + pubkey: ccnPublicKey, + privkey: ccnPrivateKey, + }; +} diff --git a/src/utils/databaseLogger.ts b/src/utils/databaseLogger.ts new file mode 100644 index 0000000..779f646 --- /dev/null +++ b/src/utils/databaseLogger.ts @@ -0,0 +1,217 @@ +import type { Database, Statement } from '@db/sqlite'; +import * as log from '@std/log'; + +interface DatabaseHandlerOptions extends log.BaseHandlerOptions { + db?: Database; +} + +export class DatabaseHandler extends log.BaseHandler { + private db: Database | null = null; + private insertStmt: Statement | null = null; + + constructor(levelName: log.LevelName, options: DatabaseHandlerOptions = {}) { + super(levelName, options); + if (options.db) { + this.setDatabase(options.db); + } + } + + setDatabase(db: Database): void { + this.db = db; + try { + this.insertStmt = this.db.prepare(` + INSERT INTO logs (timestamp, level, message, args, source, event_type, severity, remote_addr, ccn_pubkey, event_id, risk_score) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) + `); + } catch (error) { + console.warn('Database logger not ready:', error); + } + } + + override log(msg: string): void { + // Required by the abstract base class but not used in our implementation + } + + override handle(logRecord: log.LogRecord): void { + if (this.shouldSkipLogging(logRecord)) { + return; + } + + if (!this.db || !this.insertStmt) { + return; + } + + try { + const timestamp = new Date(logRecord.datetime).toISOString(); + const level = this.getLevelName(logRecord.level); + const message = logRecord.msg; + + const securityData = this.extractSecurityData(logRecord.args); + const sanitizedArgs = this.sanitizeArgs(logRecord.args); + const argsJson = + sanitizedArgs.length > 0 ? JSON.stringify(sanitizedArgs) : null; + const source = this.extractSource(logRecord.args); + + this.insertStmt.run( + timestamp, + level, + message, + argsJson, + source, + securityData.eventType, + securityData.severity, + securityData.remoteAddr, + securityData.ccnPubkey, + securityData.eventId, + securityData.riskScore, + ); + } catch (error) { + console.error('Failed to write log to database:', error); + } + } + + private getLevelName(level: number): string { + switch (level) { + case 10: + return 'DEBUG'; + case 20: + return 'INFO'; + case 30: + return 'WARN'; + case 40: + return 'ERROR'; + case 50: + return 'FATAL'; + default: + return `LVL${level}`; + } + } + + private shouldSkipLogging(logRecord: log.LogRecord): boolean { + const message = logRecord.msg.toLowerCase(); + + if ( + message.includes('sql') || + message.includes('database') || + message.includes('migration') || + message.includes('sqlite') + ) { + return true; + } + + if (message.includes('log') && message.includes('database')) { + return true; + } + + return false; + } + + private extractSecurityData(args: unknown[]): { + eventType: string | null; + severity: string | null; + remoteAddr: string | null; + ccnPubkey: string | null; + eventId: string | null; + riskScore: number | null; + } { + let eventType = null; + let severity = null; + let remoteAddr = null; + let ccnPubkey = null; + let eventId = null; + let riskScore = null; + + for (const arg of args) { + if (typeof arg === 'object' && arg !== null) { + const obj = arg as Record; + + if (obj.eventType && typeof obj.eventType === 'string') { + eventType = obj.eventType; + } + if (obj.severity && typeof obj.severity === 'string') { + severity = obj.severity; + } + if (obj.remoteAddr && typeof obj.remoteAddr === 'string') { + remoteAddr = obj.remoteAddr; + } + if (obj.ccnPubkey && typeof obj.ccnPubkey === 'string') { + ccnPubkey = obj.ccnPubkey; + } + if (obj.eventId && typeof obj.eventId === 'string') { + eventId = obj.eventId; + } + if (obj.risk_score && typeof obj.risk_score === 'number') { + riskScore = obj.risk_score; + } + } + } + + return { eventType, severity, remoteAddr, ccnPubkey, eventId, riskScore }; + } + + private extractSource(args: unknown[]): string | null { + for (const arg of args) { + if (typeof arg === 'object' && arg !== null) { + const obj = arg as Record; + if (obj.tag && typeof obj.tag === 'string') { + return obj.tag; + } + if (obj.source && typeof obj.source === 'string') { + return obj.source; + } + } + } + return null; + } + + private sanitizeArgs(args: unknown[]): unknown[] { + const sensitiveKeys = [ + 'privatekey', + 'private_key', + 'privkey', + 'priv_key', + 'secretkey', + 'secret_key', + 'seckey', + 'sec_key', + 'password', + 'pass', + 'pwd', + 'token', + 'auth', + 'ccnprivatekey', + 'ccn_private_key', + 'ccnprivkey', + ]; + + return args.map((arg) => { + if (typeof arg === 'object' && arg !== null) { + const sanitized: Record = {}; + + for (const [key, value] of Object.entries( + arg as Record, + )) { + const lowerKey = key.toLowerCase(); + + if ( + sensitiveKeys.some((sensitiveKey) => + lowerKey.includes(sensitiveKey), + ) + ) { + sanitized[key] = '[REDACTED]'; + } else if (value instanceof Uint8Array) { + sanitized[key] = `[Uint8Array length=${value.length}]`; + } else { + sanitized[key] = value; + } + } + + return sanitized; + } + + return arg; + }); + } +} + +export const dbHandler: DatabaseHandler | null = null; diff --git a/utils/encryption.ts b/src/utils/encryption.ts similarity index 100% rename from utils/encryption.ts rename to src/utils/encryption.ts diff --git a/src/utils/eventTypes.ts b/src/utils/eventTypes.ts new file mode 100644 index 0000000..03d2722 --- /dev/null +++ b/src/utils/eventTypes.ts @@ -0,0 +1,24 @@ +export function isReplaceableEvent(kind: number): boolean { + return (kind >= 10000 && kind < 20000) || kind === 0 || kind === 3; +} + +export function isAddressableEvent(kind: number): boolean { + return kind >= 30000 && kind < 40000; +} + +export function isRegularEvent(kind: number): boolean { + return ( + (kind >= 1000 && kind < 10000) || + (kind >= 4 && kind < 45) || + kind === 1 || + kind === 2 + ); +} + +export function isDeleteEvent(kind: number): boolean { + return kind === 5; +} + +export function isCCNReplaceableEvent(kind: number): boolean { + return kind >= 60000 && kind < 65536; +} diff --git a/utils/files.ts b/src/utils/files.ts old mode 100644 new mode 100755 similarity index 100% rename from utils/files.ts rename to src/utils/files.ts diff --git a/src/utils/filtersMatchingEvent.ts b/src/utils/filtersMatchingEvent.ts new file mode 100644 index 0000000..fc8e3ce --- /dev/null +++ b/src/utils/filtersMatchingEvent.ts @@ -0,0 +1,32 @@ +import type { NostrEvent } from 'jsr:@nostrify/types'; +import type { UserConnection } from '../UserConnection.ts'; + +export function filtersMatchingEvent( + event: NostrEvent, + connection: UserConnection, +): string[] { + const matching = []; + for (const subscription of connection.subscriptions.keys()) { + const filters = connection.subscriptions.get(subscription); + if (!filters) continue; + const isMatching = filters.some((filter) => + Object.entries(filter).every(([type, value]) => { + if (type === 'ids') return value.includes(event.id); + if (type === 'kinds') return value.includes(event.kind); + if (type === 'authors') return value.includes(event.pubkey); + if (type === 'since') return event.created_at > value; + if (type === 'until') return event.created_at <= value; + if (type === 'limit') return true; + if (type.startsWith('#')) { + const tagName = type.slice(1); + return event.tags.some( + (tag: string[]) => tag[0] === tagName && value.includes(tag[1]), + ); + } + return false; + }), + ); + if (isMatching) matching.push(subscription); + } + return matching; +} diff --git a/src/utils/getActiveCCN.ts b/src/utils/getActiveCCN.ts new file mode 100644 index 0000000..67a302e --- /dev/null +++ b/src/utils/getActiveCCN.ts @@ -0,0 +1,17 @@ +import type { Database } from '@db/sqlite'; +import { sql } from './queries.ts'; + +/** + * Get the single active CCN from the database + * @returns The active CCN or null if none is active + */ +export function getActiveCCN( + db: Database, +): { pubkey: string; name: string } | null { + const result = sql`SELECT pubkey, name FROM ccns WHERE is_active = 1 LIMIT 1`( + db, + ); + return result.length > 0 + ? (result[0] as { pubkey: string; name: string }) + : null; +} diff --git a/src/utils/getAllCCNs.ts b/src/utils/getAllCCNs.ts new file mode 100644 index 0000000..730cb45 --- /dev/null +++ b/src/utils/getAllCCNs.ts @@ -0,0 +1,13 @@ +import type { Database } from '@db/sqlite'; +import { sql } from './queries.ts'; + +/** + * Get all CCNs from the database + */ + +export function getAllCCNs(db: Database): { pubkey: string; name: string }[] { + return sql`SELECT pubkey, name FROM ccns`(db) as { + pubkey: string; + name: string; + }[]; +} diff --git a/src/utils/getCCNPrivateKeyByPubkey.ts b/src/utils/getCCNPrivateKeyByPubkey.ts new file mode 100644 index 0000000..71eab38 --- /dev/null +++ b/src/utils/getCCNPrivateKeyByPubkey.ts @@ -0,0 +1,20 @@ +import { decodeBase64 } from 'jsr:@std/encoding@~0.224.1/base64'; +import { exists } from 'jsr:@std/fs/exists'; +import { decryptUint8Array, encryptionKey } from './encryption.ts'; +import { getEveFilePath } from './files.ts'; + +/** + * Get the private key for a specific CCN + */ +export async function getCCNPrivateKeyByPubkey( + pubkey: string, +): Promise { + const ccnPrivPath = await getEveFilePath(`ccn_keys/${pubkey}`); + + if (await exists(ccnPrivPath)) { + const encryptedPrivateKey = Deno.readTextFileSync(ccnPrivPath); + return decryptUint8Array(decodeBase64(encryptedPrivateKey), encryptionKey); + } + + throw new Error(`CCN private key for ${pubkey} not found`); +} diff --git a/src/utils/getEncryptedEventByOriginalId.ts b/src/utils/getEncryptedEventByOriginalId.ts new file mode 100644 index 0000000..41fd9b7 --- /dev/null +++ b/src/utils/getEncryptedEventByOriginalId.ts @@ -0,0 +1,12 @@ +import type { Database } from '@db/sqlite'; +import type * as nostrTools from '@nostr/tools'; +import { sql } from '../utils/queries.ts'; + +export function getEncryptedEventByOriginalId( + db: Database, + event: nostrTools.VerifiedEvent, +) { + return sql` + SELECT * FROM events WHERE original_id = ${event.id} + `(db)[0]; +} diff --git a/src/utils/invites.ts b/src/utils/invites.ts new file mode 100644 index 0000000..fae7948 --- /dev/null +++ b/src/utils/invites.ts @@ -0,0 +1,76 @@ +import type { Database } from 'jsr:@db/sqlite'; +import { bytesToHex } from '@noble/ciphers/utils'; +import { nip19 } from '@nostr/tools'; +import { bech32m } from '@scure/base'; +import { sql } from './queries.ts'; + +export class InviteTree { + public root: InviteNode; + + constructor(npub: string) { + this.root = new InviteNode(npub); + } + + public addChild(npub: string) { + const child = new InviteNode(npub); + this.root.children.push(child); + } +} + +export class InviteNode { + public readonly npub: string; + public readonly children: InviteNode[]; + + constructor(npub: string) { + this.npub = npub; + this.children = []; + } + + public addChild(npub: string) { + const child = new InviteNode(npub); + this.children.push(child); + } +} + +export function buildInviteTree(db: Database, ccnPubkey: string) { + const ccnCreator = sql` + SELECT pubkey FROM allowed_writes WHERE ccn_pubkey = ${ccnPubkey} AND pubkey NOT IN ( + SELECT invitee_pubkey FROM inviter_invitee WHERE ccn_pubkey = ${ccnPubkey} + ) + `(db)[0]?.pubkey; + + if (!ccnCreator) { + throw new Error('CCN creator not found'); + } + + const inviteTree = new InviteTree(ccnCreator); + + const invitees = sql` + SELECT inviter_pubkey, invitee_pubkey FROM inviter_invitee WHERE ccn_pubkey = ${ccnPubkey} + `(db); + + // populate the invite tree by traversing the inviters + for (const invitee of invitees) { + let inviterNode = inviteTree.root.children.find( + (child) => child.npub === invitee.inviter_pubkey, + ); + + if (!inviterNode) { + inviterNode = new InviteNode(invitee.inviter_pubkey); + inviteTree.root.children.push(inviterNode); + } + + inviterNode.addChild(invitee.invitee_pubkey); + } + + return inviteTree; +} + +export function readInvite(invite: `${string}1${string}`) { + const decoded = bech32m.decode(invite, false); + if (decoded.prefix !== 'eveinvite') return false; + const hexBytes = bech32m.fromWords(decoded.words); + const npub = nip19.npubEncode(bytesToHex(hexBytes.slice(0, 32))); + const inviteCode = bytesToHex(hexBytes.slice(32)); + return { npub, invite: inviteCode }; +} diff --git a/src/utils/isArray.ts b/src/utils/isArray.ts new file mode 100644 index 0000000..f199993 --- /dev/null +++ b/src/utils/isArray.ts @@ -0,0 +1,3 @@ +export function isArray(obj: unknown): obj is T[] { + return Array.isArray(obj); +} diff --git a/src/utils/isLocalhost.ts b/src/utils/isLocalhost.ts new file mode 100644 index 0000000..a384fff --- /dev/null +++ b/src/utils/isLocalhost.ts @@ -0,0 +1,39 @@ +export function isLocalhost( + req: Request, + connInfo?: Deno.ServeHandlerInfo, +): boolean { + if (connInfo?.remoteAddr) { + const remoteAddr = connInfo.remoteAddr; + if (remoteAddr.transport === 'tcp') { + const hostname = remoteAddr.hostname; + return hostname === '127.0.0.1' || hostname === '::1'; + } + if (remoteAddr.transport === 'unix') { + return true; + } + } + const url = new URL(req.url); + const hostname = url.hostname; + if (hostname === '127.0.0.1' || hostname === '::1') { + return true; + } + if (hostname === 'localhost') { + const suspiciousHeaders = [ + 'x-forwarded-for', + 'x-forwarded-host', + 'x-real-ip', + 'cf-connecting-ip', + 'x-cluster-client-ip', + ]; + + for (const header of suspiciousHeaders) { + if (req.headers.get(header)) { + return false; + } + } + + return true; + } + + return false; +} diff --git a/src/utils/isValidJSON.ts b/src/utils/isValidJSON.ts new file mode 100644 index 0000000..63c9263 --- /dev/null +++ b/src/utils/isValidJSON.ts @@ -0,0 +1,8 @@ +export function isValidJSON(str: string) { + try { + JSON.parse(str); + } catch { + return false; + } + return true; +} diff --git a/src/utils/knownEventsCache.ts b/src/utils/knownEventsCache.ts new file mode 100644 index 0000000..54fac98 --- /dev/null +++ b/src/utils/knownEventsCache.ts @@ -0,0 +1,14 @@ +import { db } from '../index.ts'; +import { sql } from './queries.ts'; + +let knownOriginalEventsCache: string[] = []; + +export function isOriginalEventIdCached(eventId: string) { + return knownOriginalEventsCache.includes(eventId); +} + +export function updateKnownEventsCache() { + knownOriginalEventsCache = sql`SELECT original_id FROM events`(db).flatMap( + (row) => row.original_id, + ); +} diff --git a/src/utils/logQueries.ts b/src/utils/logQueries.ts new file mode 100644 index 0000000..94fbf08 --- /dev/null +++ b/src/utils/logQueries.ts @@ -0,0 +1,162 @@ +import type { Database } from '@db/sqlite'; +import { sql } from './queries.ts'; + +export interface LogEntry { + log_id: string; + timestamp: string; + level: string; + message: string; + args: string | null; + source: string | null; + created_at: number; + event_type: string | null; + severity: string | null; + remote_addr: string | null; + ccn_pubkey: string | null; + event_id: string | null; + risk_score: number | null; +} + +export function getRecentLogs( + db: Database, + limit = 100, + level?: string, +): LogEntry[] { + if (level) { + return sql` + SELECT * FROM logs + WHERE level = ${level} + ORDER BY created_at DESC + LIMIT ${limit} + `(db) as LogEntry[]; + } + + return sql` + SELECT * FROM logs + ORDER BY created_at DESC + LIMIT ${limit} + `(db) as LogEntry[]; +} + +export function getSecurityLogs( + db: Database, + limit = 100, + severity?: string, +): LogEntry[] { + if (severity) { + return sql` + SELECT * FROM logs + WHERE event_type IS NOT NULL AND severity = ${severity} + ORDER BY created_at DESC + LIMIT ${limit} + `(db) as LogEntry[]; + } + + return sql` + SELECT * FROM logs + WHERE event_type IS NOT NULL + ORDER BY created_at DESC + LIMIT ${limit} + `(db) as LogEntry[]; +} + +export function getLogsByTimeRange( + db: Database, + startTime: number, + endTime: number, + level?: string, +): LogEntry[] { + if (level) { + return sql` + SELECT * FROM logs + WHERE created_at >= ${startTime} AND created_at <= ${endTime} AND level = ${level} + ORDER BY created_at DESC + `(db) as LogEntry[]; + } + + return sql` + SELECT * FROM logs + WHERE created_at >= ${startTime} AND created_at <= ${endTime} + ORDER BY created_at DESC + `(db) as LogEntry[]; +} + +export function getLogsByCCN( + db: Database, + ccnPubkey: string, + limit = 100, +): LogEntry[] { + return sql` + SELECT * FROM logs + WHERE ccn_pubkey = ${ccnPubkey} + ORDER BY created_at DESC + LIMIT ${limit} + `(db) as LogEntry[]; +} + +export function getHighRiskLogs( + db: Database, + minRiskScore = 7.0, + limit = 50, +): LogEntry[] { + return sql` + SELECT * FROM logs + WHERE risk_score >= ${minRiskScore} + ORDER BY risk_score DESC, created_at DESC + LIMIT ${limit} + `(db) as LogEntry[]; +} + +export function getLogStats(db: Database): { + total_logs: number; + logs_by_level: Record; + security_events: number; + high_risk_events: number; + last_24h_logs: number; +} { + const totalLogs = sql`SELECT COUNT(*) as count FROM logs`(db)[0].count; + + const logsByLevel = sql` + SELECT level, COUNT(*) as count + FROM logs + GROUP BY level + `(db); + + const securityEvents = sql` + SELECT COUNT(*) as count + FROM logs + WHERE event_type IS NOT NULL + `(db)[0].count; + + const highRiskEvents = sql` + SELECT COUNT(*) as count + FROM logs + WHERE risk_score >= 7.0 + `(db)[0].count; + + const last24hLogs = sql` + SELECT COUNT(*) as count + FROM logs + WHERE created_at >= ${Math.floor(Date.now() / 1000) - 86400} + `(db)[0].count; + + const levelStats: Record = {}; + for (const row of logsByLevel) { + levelStats[row.level] = row.count; + } + + return { + total_logs: totalLogs, + logs_by_level: levelStats, + security_events: securityEvents, + high_risk_events: highRiskEvents, + last_24h_logs: last24hLogs, + }; +} + +export function cleanupOldLogs(db: Database, daysToKeep = 30): number { + const cutoffTime = Math.floor(Date.now() / 1000) - daysToKeep * 86400; + + const stmt = db.prepare('DELETE FROM logs WHERE created_at < ?'); + return stmt.run(cutoffTime); +} diff --git a/src/utils/logs.ts b/src/utils/logs.ts new file mode 100644 index 0000000..fb8de8b --- /dev/null +++ b/src/utils/logs.ts @@ -0,0 +1,140 @@ +import type { Database } from '@db/sqlite'; +import * as colors from 'jsr:@std/fmt@^1.0.4/colors'; +import * as log from 'jsr:@std/log'; +import { DatabaseHandler } from './databaseLogger.ts'; +import { getEveFilePath } from './files.ts'; +export * as log from 'jsr:@std/log'; + +/** + * Sanitizes data before logging to prevent accidental exposure of sensitive information + * @param data The data to sanitize + * @returns Sanitized data safe for logging + */ +function sanitizeForLogging(data: unknown): unknown { + if (data === null || data === undefined || typeof data !== 'object') { + return data; + } + + if (data instanceof Uint8Array) { + // Never log raw binary data that could contain keys + return `[Uint8Array length=${data.length}]`; + } + + if (Array.isArray(data)) { + return data.map(sanitizeForLogging); + } + + const sanitized: Record = {}; + const sensitiveKeys = [ + 'privatekey', + 'private_key', + 'privkey', + 'priv_key', + 'secretkey', + 'secret_key', + 'seckey', + 'sec_key', + 'password', + 'pass', + 'pwd', + 'token', + 'auth', + 'ccnprivatekey', + 'ccn_private_key', + 'ccnprivkey', + 'seed', + 'seedphrase', + 'seed_phrase', + 'mnemonic', + 'mnemonic_phrase', + 'mnemonic_phrase_words', + ]; + + for (const [key, value] of Object.entries(data as Record)) { + const lowerKey = key.toLowerCase(); + + if (sensitiveKeys.some((sensitiveKey) => lowerKey.includes(sensitiveKey))) { + sanitized[key] = '[REDACTED]'; + } else { + sanitized[key] = sanitizeForLogging(value); + } + } + + return sanitized; +} + +export async function setupLogger(db: Database | null) { + const formatLevel = (level: number): string => { + return ( + { + 10: colors.gray('[DEBUG]'), + 20: colors.green('[INFO] '), + 30: colors.yellow('[WARN] '), + 40: colors.red('[ERROR]'), + 50: colors.bgRed('[FATAL]'), + }[level] || `[LVL${level}]` + ); + }; + + const levelName = (level: number): string => { + return ( + { + 10: 'DEBUG', + 20: 'INFO', + 30: 'WARN', + 40: 'ERROR', + 50: 'FATAL', + }[level] || `LVL${level}` + ); + }; + + const formatArg = (arg: unknown): string => { + const sanitized = sanitizeForLogging(arg); + if (typeof sanitized === 'object') return JSON.stringify(sanitized); + return String(sanitized); + }; + + const handlers: Record = { + console: new log.ConsoleHandler('DEBUG', { + useColors: true, + formatter: (record) => { + const timestamp = new Date().toISOString(); + let msg = `${colors.dim(`[${timestamp}]`)} ${formatLevel(record.level)} ${record.msg}`; + + if (record.args.length > 0) { + const args = record.args + .map((arg, i) => `${colors.dim(`arg${i}:`)} ${formatArg(arg)}`) + .join(' '); + msg += ` ${colors.dim('|')} ${args}`; + } + + return msg; + }, + }), + file: new log.FileHandler('DEBUG', { + filename: + Deno.env.get('LOG_FILE') || (await getEveFilePath('eve-logs.jsonl')), + formatter: (record) => { + const timestamp = new Date().toISOString(); + return JSON.stringify({ + timestamp, + level: levelName(record.level), + msg: record.msg, + args: record.args.map(sanitizeForLogging), + }); + }, + }), + }; + if (db) { + handlers.database = new DatabaseHandler('DEBUG', { db }); + } + log.setup({ + handlers, + loggers: { + default: { + level: 'DEBUG', + handlers: ['console', 'file', 'database'], + }, + }, + }); +} diff --git a/utils/option.ts b/src/utils/option.ts similarity index 100% rename from utils/option.ts rename to src/utils/option.ts diff --git a/src/utils/outboundQueue.ts b/src/utils/outboundQueue.ts new file mode 100644 index 0000000..4858e44 --- /dev/null +++ b/src/utils/outboundQueue.ts @@ -0,0 +1,389 @@ +import type * as nostrTools from '@nostr/tools'; +import type { Database } from 'jsr:@db/sqlite'; +import { MAX_TRANSMISSION_ATTEMPTS } from '../consts.ts'; +import { publishToRelays, relays } from '../relays.ts'; +import { log } from './logs.ts'; +import { sql } from './queries.ts'; +import { + SecurityEventType, + SecuritySeverity, + logSecurityEvent, +} from './securityLogs.ts'; + +export interface QueuedEvent { + queue_id: number; + event_id: string; + encrypted_event: string; + ccn_pubkey: string; + created_at: number; + attempts: number; + last_attempt: number | null; + status: 'pending' | 'sending' | 'sent' | 'failed' | 'stale'; + error_message: string | null; +} + +let isConnectedToRelays = false; +let lastSuccessfulTransmission = 0; +let consecutiveFailures = 0; + +export function queueEventForTransmission( + db: Database, + eventId: string, + encryptedEvent: nostrTools.VerifiedEvent | nostrTools.VerifiedEvent[], + ccnPubkey: string, +): void { + try { + const encryptedEventJson = JSON.stringify(encryptedEvent); + + sql` + INSERT OR REPLACE INTO outbound_event_queue + (event_id, encrypted_event, ccn_pubkey, status) + VALUES (${eventId}, ${encryptedEventJson}, ${ccnPubkey}, 'pending') + `(db); + + log.debug('Event queued for transmission', { + tag: 'outboundQueue', + eventId, + ccnPubkey, + connectionState: isConnectedToRelays ? 'connected' : 'offline', + }); + + logSecurityEvent({ + eventType: SecurityEventType.EVENT_QUEUED_FOR_TRANSMISSION, + severity: SecuritySeverity.LOW, + source: 'outbound_queue', + details: { + action: 'event_queued', + event_id: eventId, + ccn_pubkey: ccnPubkey, + is_chunked: Array.isArray(encryptedEvent), + connection_state: isConnectedToRelays, + }, + }); + } catch (error) { + log.error('Failed to queue event for transmission', { + tag: 'outboundQueue', + eventId, + error, + }); + throw error; + } +} + +export function getPendingEvents(db: Database, limit = 50): QueuedEvent[] { + const now = Math.floor(Date.now() / 1000); + const maxAge = 30 * 24 * 60 * 60; + + sql` + UPDATE outbound_event_queue + SET status = 'stale' + WHERE status IN ('pending', 'failed') + AND created_at < ${now - maxAge} + `(db); + + return sql` + SELECT * FROM outbound_event_queue + WHERE ( + status = 'pending' + OR ( + status = 'failed' + AND attempts < ${MAX_TRANSMISSION_ATTEMPTS} + AND ( + last_attempt IS NULL OR + last_attempt < ${now - getAdaptiveRetryDelay(consecutiveFailures)} + ) + ) + ) + AND status != 'stale' + ORDER BY + CASE WHEN status = 'pending' THEN 0 ELSE 1 END, + created_at ASC + LIMIT ${limit} + `(db) as QueuedEvent[]; +} + +function getAdaptiveRetryDelay(failures: number): number { + return Math.min(300, 2 ** failures * 10); +} + +async function checkRelayConnectivity(): Promise { + const connectivityTests = relays.map(async (relay) => { + try { + const ws = new WebSocket(relay); + + return new Promise((resolve) => { + const timeout = setTimeout(() => { + ws.close(); + resolve(false); + }, 3000); // 3 second timeout + + ws.onopen = () => { + clearTimeout(timeout); + ws.close(); + resolve(true); + }; + + ws.onerror = () => { + clearTimeout(timeout); + resolve(false); + }; + + ws.onclose = () => { + clearTimeout(timeout); + resolve(false); + }; + }); + } catch { + return false; + } + }); + + try { + const results = await Promise.allSettled(connectivityTests); + const successfulConnections = results.filter( + (result) => result.status === 'fulfilled' && result.value === true, + ).length; + + const isConnected = successfulConnections > 0; + + log.debug('Relay connectivity check completed', { + tag: 'outboundQueue', + successfulConnections, + totalTested: relays.length, + isConnected, + }); + + return isConnected; + } catch { + return false; + } +} + +export async function processStartupQueue(db: Database): Promise { + const startupEvents = sql` + SELECT COUNT(*) as count FROM outbound_event_queue + WHERE status IN ('pending', 'failed', 'sending') + `(db)[0].count; + + if (startupEvents > 0) { + log.info(`Found ${startupEvents} events from previous session`, { + tag: 'outboundQueue', + }); + + sql` + UPDATE outbound_event_queue + SET status = 'failed', + attempts = attempts + 1, + error_message = 'Interrupted by shutdown' + WHERE status = 'sending' + `(db); + + await processOutboundQueue(db); + } +} + +export function markEventSending(db: Database, queueId: number): void { + const now = Math.floor(Date.now() / 1000); + + sql` + UPDATE outbound_event_queue + SET status = 'sending', last_attempt = ${now} + WHERE queue_id = ${queueId} + `(db); +} + +export function markEventSent(db: Database, queueId: number): void { + sql` + UPDATE outbound_event_queue + SET status = 'sent' + WHERE queue_id = ${queueId} + `(db); + + isConnectedToRelays = true; + lastSuccessfulTransmission = Math.floor(Date.now() / 1000); + consecutiveFailures = 0; + + log.debug('Event marked as sent', { + tag: 'outboundQueue', + queueId, + }); +} + +export function markEventFailed( + db: Database, + queueId: number, + errorMessage: string, +): void { + sql` + UPDATE outbound_event_queue + SET status = 'failed', + attempts = attempts + 1, + error_message = ${errorMessage} + WHERE queue_id = ${queueId} + `(db); + + consecutiveFailures++; + const timeSinceLastSuccess = + Math.floor(Date.now() / 1000) - lastSuccessfulTransmission; + + if (consecutiveFailures >= 3 || timeSinceLastSuccess > 300) { + isConnectedToRelays = false; + } + + log.warn('Event transmission failed', { + tag: 'outboundQueue', + queueId, + errorMessage, + consecutiveFailures, + timeSinceLastSuccess, + connectionState: isConnectedToRelays ? 'connected' : 'offline', + }); + + logSecurityEvent({ + eventType: SecurityEventType.SYSTEM_STARTUP, + severity: SecuritySeverity.MEDIUM, + source: 'outbound_queue', + details: { + action: 'transmission_failed', + queue_id: queueId, + error_message: errorMessage, + consecutive_failures: consecutiveFailures, + }, + }); +} + +async function batchProcessEvents( + db: Database, + events: QueuedEvent[], +): Promise { + const BATCH_SIZE = 10; + const batches = []; + + for (let i = 0; i < events.length; i += BATCH_SIZE) { + batches.push(events.slice(i, i + BATCH_SIZE)); + } + + for (const batch of batches) { + const promises = batch.map(async (queuedEvent) => { + try { + const encryptedEvent = JSON.parse(queuedEvent.encrypted_event); + await publishToRelays(encryptedEvent); + return { queueId: queuedEvent.queue_id, success: true }; + } catch (error) { + const errorMessage = + error instanceof Error ? error.message : 'Unknown error'; + return { + queueId: queuedEvent.queue_id, + success: false, + error: errorMessage, + }; + } + }); + + const results = await Promise.allSettled(promises); + + results.forEach((result, index) => { + const queuedEvent = batch[index]; + if (result.status === 'fulfilled' && result.value.success) { + markEventSent(db, queuedEvent.queue_id); + } else { + const error = + result.status === 'fulfilled' + ? result.value.error + : 'Promise rejected'; + markEventFailed(db, queuedEvent.queue_id, error || 'Unknown error'); + } + }); + + if (batches.indexOf(batch) < batches.length - 1) { + await new Promise((resolve) => setTimeout(resolve, 1000)); + } + } +} + +export async function processOutboundQueue(db: Database): Promise { + const pendingEvents = getPendingEvents(db); + + if (pendingEvents.length === 0) { + return; + } + + const connectivityResult = await checkRelayConnectivity(); + if (!connectivityResult && consecutiveFailures > 5) { + log.debug('Skipping queue processing - appears to be offline', { + tag: 'outboundQueue', + consecutiveFailures, + }); + return; + } + + log.info(`Processing ${pendingEvents.length} pending events`, { + tag: 'outboundQueue', + connectionState: isConnectedToRelays ? 'connected' : 'unknown', + }); + + for (const event of pendingEvents) { + markEventSending(db, event.queue_id); + } + + await batchProcessEvents(db, pendingEvents); +} + +export function getQueueStats(db: Database): { + pending: number; + sending: number; + sent: number; + failed: number; + stale: number; + total: number; + connectionState: string; + consecutiveFailures: number; +} { + const stats = sql` + SELECT + status, + COUNT(*) as count + FROM outbound_event_queue + GROUP BY status + `(db); + + const result = { + pending: 0, + sending: 0, + sent: 0, + failed: 0, + stale: 0, + total: 0, + connectionState: isConnectedToRelays ? 'connected' : 'offline', + consecutiveFailures, + }; + + for (const stat of stats) { + const status = stat.status as + | 'pending' + | 'sending' + | 'sent' + | 'failed' + | 'stale'; + switch (status) { + case 'pending': + result.pending = stat.count; + break; + case 'sending': + result.sending = stat.count; + break; + case 'sent': + result.sent = stat.count; + break; + case 'failed': + result.failed = stat.count; + break; + case 'stale': + result.stale = stat.count; + break; + } + result.total += stat.count; + } + + return result; +} diff --git a/src/utils/parseATagQuery.ts b/src/utils/parseATagQuery.ts new file mode 100644 index 0000000..3d88803 --- /dev/null +++ b/src/utils/parseATagQuery.ts @@ -0,0 +1,14 @@ +export function parseATagQuery(aTagValue: string): { + kind: number; + pubkey: string; + dTag?: string; +} { + const parts = aTagValue.split(':'); + if (parts.length < 2) return { kind: 0, pubkey: '' }; + + return { + kind: Number.parseInt(parts[0], 10), + pubkey: parts[1], + dTag: parts.length > 2 ? parts[2] : undefined, + }; +} diff --git a/utils/queries.ts b/src/utils/queries.ts similarity index 100% rename from utils/queries.ts rename to src/utils/queries.ts diff --git a/src/utils/randomTimeUpTo2DaysInThePast.ts b/src/utils/randomTimeUpTo2DaysInThePast.ts new file mode 100644 index 0000000..da05326 --- /dev/null +++ b/src/utils/randomTimeUpTo2DaysInThePast.ts @@ -0,0 +1,7 @@ +export function randomTimeUpTo2DaysInThePast() { + const now = Date.now(); + const twoDaysAgo = now - 2 * 24 * 60 * 60 * 1000 - 3600 * 1000; // 1 hour buffer in case of clock skew + return Math.floor( + (Math.floor(Math.random() * (now - twoDaysAgo)) + twoDaysAgo) / 1000, + ); +} diff --git a/src/utils/securityLogs.ts b/src/utils/securityLogs.ts new file mode 100644 index 0000000..20380e8 --- /dev/null +++ b/src/utils/securityLogs.ts @@ -0,0 +1,220 @@ +import { log } from './logs.ts'; + +export enum SecurityEventType { + // Authentication & Authorization + CCN_ACCESS_DENIED = 'ccn_access_denied', + CCN_ACTIVATION_ATTEMPT = 'ccn_activation_attempt', + CCN_CREATION_ATTEMPT = 'ccn_creation_attempt', + UNAUTHORIZED_WRITE_ATTEMPT = 'unauthorized_write_attempt', + + // Connection Security + NON_LOCALHOST_CONNECTION_BLOCKED = 'non_localhost_connection_blocked', + SUSPICIOUS_HEADER_DETECTED = 'suspicious_header_detected', + WEBSOCKET_CONNECTION_ESTABLISHED = 'websocket_connection_established', + WEBSOCKET_CONNECTION_CLOSED = 'websocket_connection_closed', + + // Cryptographic Operations + DECRYPTION_FAILURE = 'decryption_failure', + INVALID_SIGNATURE = 'invalid_signature', + POW_VALIDATION_FAILURE = 'pow_validation_failure', + ENCRYPTION_ERROR = 'encryption_error', + + // Event Processing + DUPLICATE_EVENT_BLOCKED = 'duplicate_event_blocked', + MALFORMED_EVENT = 'malformed_event', + CHUNKED_EVENT_RECEIVED = 'chunked_event_received', + CHUNKED_EVENT_COMPLETED = 'chunked_event_completed', + EVENT_QUEUED_FOR_TRANSMISSION = 'event_queued_for_transmission', + + // Resource Usage & DoS Protection + SUBSCRIPTION_LIMIT_EXCEEDED = 'subscription_limit_exceeded', + MEMORY_USAGE_HIGH = 'memory_usage_high', + LARGE_PAYLOAD_DETECTED = 'large_payload_detected', + + // Database Security + SQL_QUERY_EXECUTED = 'sql_query_executed', + MIGRATION_EXECUTED = 'migration_executed', + TRANSACTION_ROLLBACK = 'transaction_rollback', + + // CCN Boundary Violations + CCN_BOUNDARY_VIOLATION_ATTEMPT = 'ccn_boundary_violation_attempt', + INVITE_VALIDATION_FAILURE = 'invite_validation_failure', + INVITE_ALREADY_USED = 'invite_already_used', + + // System Events + SYSTEM_STARTUP = 'system_startup', + SYSTEM_SHUTDOWN = 'system_shutdown', + CONFIGURATION_LOADED = 'configuration_loaded', + ERROR_THRESHOLD_EXCEEDED = 'error_threshold_exceeded', +} + +export enum SecuritySeverity { + LOW = 'low', + MEDIUM = 'medium', + HIGH = 'high', + CRITICAL = 'critical', +} + +export interface SecurityEventData { + eventType: SecurityEventType; + severity: SecuritySeverity; + timestamp: string; + source: string; + details: Record; + userAgent?: string; + remoteAddr?: string; + ccnPubkey?: string; + userId?: string; + eventId?: string; + subscriptionId?: string; + risk_score?: number; +} + +class SecurityLogger { + private readonly eventCounts = new Map(); + private readonly lastEventTime = new Map(); + + logSecurityEvent(data: Omit): void { + const eventData: SecurityEventData = { + ...data, + timestamp: new Date().toISOString(), + }; + + this.updateEventTracking(data.eventType); + + switch (data.severity) { + case SecuritySeverity.CRITICAL: + log.error(`SECURITY_CRITICAL: ${data.eventType}`, eventData); + break; + case SecuritySeverity.HIGH: + log.error(`SECURITY_HIGH: ${data.eventType}`, eventData); + break; + case SecuritySeverity.MEDIUM: + log.warn(`SECURITY_MEDIUM: ${data.eventType}`, eventData); + break; + case SecuritySeverity.LOW: + log.info(`SECURITY_LOW: ${data.eventType}`, eventData); + break; + } + } + + logAuthEvent( + eventType: SecurityEventType, + success: boolean, + details: Record, + remoteAddr?: string, + ): void { + this.logSecurityEvent({ + eventType, + severity: success ? SecuritySeverity.LOW : SecuritySeverity.MEDIUM, + source: 'authentication', + details: { success, ...details }, + remoteAddr, + }); + } + + logCCNViolation( + eventType: SecurityEventType, + ccnPubkey: string, + attemptedAction: string, + details: Record, + ): void { + this.logSecurityEvent({ + eventType, + severity: SecuritySeverity.HIGH, + source: 'ccn_boundary', + ccnPubkey, + details: { attemptedAction, ...details }, + risk_score: 8.5, + }); + } + + logCryptoFailure( + eventType: SecurityEventType, + operation: string, + details: Record, + ): void { + this.logSecurityEvent({ + eventType, + severity: SecuritySeverity.MEDIUM, + source: 'cryptography', + details: { operation, ...details }, + }); + } + + logDoSEvent( + eventType: SecurityEventType, + details: Record, + remoteAddr?: string, + ): void { + this.logSecurityEvent({ + eventType, + severity: SecuritySeverity.HIGH, + source: 'dos_protection', + details, + remoteAddr, + risk_score: 7.0, + }); + } + + logSystemEvent( + eventType: SecurityEventType, + details: Record, + ): void { + this.logSecurityEvent({ + eventType, + severity: SecuritySeverity.LOW, + source: 'system', + details, + }); + } + + private updateEventTracking(eventType: SecurityEventType): void { + const now = Date.now(); + const count = this.eventCounts.get(eventType) || 0; + this.eventCounts.set(eventType, count + 1); + this.lastEventTime.set(eventType, now); + } +} + +export const securityLogger = new SecurityLogger(); + +export const logSecurityEvent = (data: Omit) => + securityLogger.logSecurityEvent(data); + +export const logAuthEvent = ( + eventType: SecurityEventType, + success: boolean, + details: Record, + remoteAddr?: string, +) => securityLogger.logAuthEvent(eventType, success, details, remoteAddr); + +export const logCCNViolation = ( + eventType: SecurityEventType, + ccnPubkey: string, + attemptedAction: string, + details: Record, +) => + securityLogger.logCCNViolation( + eventType, + ccnPubkey, + attemptedAction, + details, + ); + +export const logCryptoFailure = ( + eventType: SecurityEventType, + operation: string, + details: Record, +) => securityLogger.logCryptoFailure(eventType, operation, details); + +export const logDoSEvent = ( + eventType: SecurityEventType, + details: Record, + remoteAddr?: string, +) => securityLogger.logDoSEvent(eventType, details, remoteAddr); + +export const logSystemEvent = ( + eventType: SecurityEventType, + details: Record, +) => securityLogger.logSystemEvent(eventType, details); diff --git a/utils/invites.ts b/utils/invites.ts deleted file mode 100644 index 45a61ec..0000000 --- a/utils/invites.ts +++ /dev/null @@ -1,12 +0,0 @@ -import { bytesToHex } from '@noble/ciphers/utils'; -import { nip19 } from '@nostr/tools'; -import { bech32m } from '@scure/base'; - -export function readInvite(invite: `${string}1${string}`) { - const decoded = bech32m.decode(invite, false); - if (decoded.prefix !== 'eveinvite') return false; - const hexBytes = bech32m.fromWords(decoded.words); - const npub = nip19.npubEncode(bytesToHex(hexBytes.slice(0, 32))); - const inviteCode = bytesToHex(hexBytes.slice(32)); - return { npub, invite: inviteCode }; -} diff --git a/utils/logs.ts b/utils/logs.ts deleted file mode 100644 index 3e5a58f..0000000 --- a/utils/logs.ts +++ /dev/null @@ -1,75 +0,0 @@ -import * as colors from 'jsr:@std/fmt@^1.0.4/colors'; -import * as log from 'jsr:@std/log'; -import { getEveFilePath } from './files.ts'; -export * as log from 'jsr:@std/log'; - -export async function setupLogger() { - const formatLevel = (level: number): string => { - return ( - { - 10: colors.gray('[DEBUG]'), - 20: colors.green('[INFO] '), - 30: colors.yellow('[WARN] '), - 40: colors.red('[ERROR]'), - 50: colors.bgRed('[FATAL]'), - }[level] || `[LVL${level}]` - ); - }; - - const levelName = (level: number): string => { - return ( - { - 10: 'DEBUG', - 20: 'INFO', - 30: 'WARN', - 40: 'ERROR', - 50: 'FATAL', - }[level] || `LVL${level}` - ); - }; - - const formatArg = (arg: unknown): string => { - if (typeof arg === 'object') return JSON.stringify(arg); - return String(arg); - }; - - await log.setup({ - handlers: { - console: new log.ConsoleHandler('DEBUG', { - useColors: true, - formatter: (record) => { - const timestamp = new Date().toISOString(); - let msg = `${colors.dim(`[${timestamp}]`)} ${formatLevel(record.level)} ${record.msg}`; - - if (record.args.length > 0) { - const args = record.args - .map((arg, i) => `${colors.dim(`arg${i}:`)} ${formatArg(arg)}`) - .join(' '); - msg += ` ${colors.dim('|')} ${args}`; - } - - return msg; - }, - }), - file: new log.FileHandler('DEBUG', { - filename: - Deno.env.get('LOG_FILE') || (await getEveFilePath('eve-logs.jsonl')), - formatter: (record) => { - const timestamp = new Date().toISOString(); - return JSON.stringify({ - timestamp, - level: levelName(record.level), - msg: record.msg, - args: record.args, - }); - }, - }), - }, - loggers: { - default: { - level: 'DEBUG', - handlers: ['console', 'file'], - }, - }, - }); -} From 6dfa73a3d3ab01e4c1d3eb969991135bdd2b5667 Mon Sep 17 00:00:00 2001 From: dannym Date: Thu, 5 Jun 2025 12:02:40 +0000 Subject: [PATCH 11/11] forgot to remove this file after the rewrite Signed-off-by: dannym --- index.ts | 1098 ------------------------------------------------------ 1 file changed, 1098 deletions(-) delete mode 100644 index.ts diff --git a/index.ts b/index.ts deleted file mode 100644 index 2182675..0000000 --- a/index.ts +++ /dev/null @@ -1,1098 +0,0 @@ -import { bytesToHex, hexToBytes } from '@noble/ciphers/utils'; -import { randomBytes } from '@noble/ciphers/webcrypto'; -import { sha512 } from '@noble/hashes/sha2'; -import * as nostrTools from '@nostr/tools'; -import { base64 } from '@scure/base'; -import { Database } from 'jsr:@db/sqlite'; -import { NSchema as n } from 'jsr:@nostrify/nostrify'; -import type { - NostrClientREQ, - NostrEvent, - NostrFilter, -} from 'jsr:@nostrify/types'; -import { encodeBase64 } from 'jsr:@std/encoding@0.224/base64'; -import { - CHUNK_CLEANUP_INTERVAL, - CHUNK_MAX_AGE, - POW_TO_MINE, -} from './consts.ts'; -import { - ChunkedEventReceived, - EventAlreadyExistsException, - createEncryptedEvent, - createEncryptedEventForPubkey, - decryptEvent, -} from './eventEncryptionDecryption.ts'; -import { - createNewCCN, - getActiveCCN, - getAllCCNs, - getCCNPrivateKeyByPubkey, - isAddressableEvent, - isArray, - isCCNReplaceableEvent, - isLocalhost, - isReplaceableEvent, - isValidJSON, - parseATagQuery, -} from './utils.ts'; -import { encryptUint8Array, encryptionKey } from './utils/encryption.ts'; -import { getEveFilePath } from './utils/files.ts'; -import { log, setupLogger } from './utils/logs.ts'; -import { mixQuery, sql, sqlPartial } from './utils/queries.ts'; - -await setupLogger(); - -if (!Deno.env.has('ENCRYPTION_KEY')) { - log.error( - `Missing ENCRYPTION_KEY. Please set it in your env.\nA new one has been generated for you: ENCRYPTION_KEY="${encodeBase64( - randomBytes(32), - )}"`, - ); - Deno.exit(1); -} - -await Deno.mkdir(await getEveFilePath('ccn_keys'), { recursive: true }); - -const db = new Database(await getEveFilePath('db')); -const pool = new nostrTools.SimplePool(); -const relays = [ - 'wss://relay.arx-ccn.com/', - 'wss://relay.dannymorabito.com/', - 'wss://nos.lol/', - 'wss://nostr.einundzwanzig.space/', - 'wss://nostr.massmux.com/', - 'wss://nostr.mom/', - 'wss://nostr.wine/', - 'wss://purplerelay.com/', - 'wss://relay.damus.io/', - 'wss://relay.goodmorningbitcoin.com/', - 'wss://relay.lexingtonbitcoin.org/', - 'wss://relay.nostr.band/', - 'wss://relay.primal.net/', - 'wss://relay.snort.social/', - 'wss://strfry.iris.to/', - 'wss://cache2.primal.net/v1', -]; - -export function runMigrations(db: Database, latestVersion: number) { - const migrations = [...Deno.readDirSync(`${import.meta.dirname}/migrations`)]; - migrations.sort((a, b) => { - const aVersion = Number.parseInt(a.name.split('-')[0], 10); - const bVersion = Number.parseInt(b.name.split('-')[0], 10); - return aVersion - bVersion; - }); - for (const migrationFile of migrations) { - const migrationVersion = Number.parseInt( - migrationFile.name.split('-')[0], - 10, - ); - - if (migrationVersion > latestVersion) { - log.info( - `Running migration ${migrationFile.name} (version ${migrationVersion})`, - ); - const start = Date.now(); - const migrationSql = Deno.readTextFileSync( - `${import.meta.dirname}/migrations/${migrationFile.name}`, - ); - db.run('BEGIN TRANSACTION'); - try { - db.run(migrationSql); - const end = Date.now(); - const durationMs = end - start; - sql` - INSERT INTO migration_history (migration_version, migration_name, executed_at, duration_ms, status) VALUES (${migrationVersion}, ${migrationFile.name}, ${new Date().toISOString()}, ${durationMs}, 'success'); - db.run("COMMIT TRANSACTION"); - `(db); - } catch (e) { - db.run('ROLLBACK TRANSACTION'); - const error = - e instanceof Error - ? e - : typeof e === 'string' - ? new Error(e) - : new Error(JSON.stringify(e)); - const end = Date.now(); - const durationMs = end - start; - sql` - INSERT INTO migration_history (migration_version, migration_name, executed_at, duration_ms, status, error_message) VALUES (${migrationVersion}, ${migrationFile.name}, ${new Date().toISOString()}, ${durationMs}, 'failed', ${error.message}); - `(db); - throw e; - } - db.run('END TRANSACTION'); - } - } -} - -function addEventToDb( - decryptedEvent: nostrTools.VerifiedEvent, - encryptedEvent: nostrTools.VerifiedEvent, - ccnPubkey: string, -) { - const existingEvent = sql` - SELECT * FROM events WHERE id = ${decryptedEvent.id} - `(db)[0]; - - if (existingEvent) throw new EventAlreadyExistsException(); - - const isInvite = - decryptedEvent.tags.findIndex( - (tag: string[]) => tag[0] === 'type' && tag[1] === 'invite', - ) !== -1; - - if (isInvite) { - const shadContent = bytesToHex( - sha512.create().update(decryptedEvent.content).digest(), - ); - - const inviteUsed = sql` - SELECT COUNT(*) as count FROM inviter_invitee WHERE invite_hash = ${shadContent} - `(db)[0].count; - - if (inviteUsed > 0) { - throw new Error('Invite already used'); - } - - const inviteEvent = sql` - SELECT * FROM events WHERE kind = 9999 AND id IN ( - SELECT event_id FROM event_tags WHERE tag_name = 'i' AND tag_id IN ( - SELECT tag_id FROM event_tags_values WHERE value_position = 1 AND value = ${shadContent} - ) - ) - `(db)[0]; - - if (!inviteEvent) { - throw new Error('Invite event not found'); - } - - const inviterPubkey = inviteEvent.pubkey; - const inviteePubkey = decryptedEvent.pubkey; - - db.run('BEGIN TRANSACTION'); - - sql` - INSERT INTO inviter_invitee (ccn_pubkey, inviter_pubkey, invitee_pubkey, invite_hash) VALUES (${ccnPubkey}, ${inviterPubkey}, ${inviteePubkey}, ${shadContent}) - `(db); - - sql` - INSERT INTO allowed_writes (ccn_pubkey, pubkey) VALUES (${ccnPubkey}, ${inviteePubkey}) - `(db); - - db.run('COMMIT TRANSACTION'); - - const allowedPubkeys = sql` - SELECT pubkey FROM allowed_writes WHERE ccn_pubkey = ${ccnPubkey} - `(db).flatMap((row) => row.pubkey); - const ccnName = sql` - SELECT name FROM ccns WHERE pubkey = ${ccnPubkey} - `(db)[0].name; - - getCCNPrivateKeyByPubkey(ccnPubkey).then((ccnPrivateKey) => { - if (!ccnPrivateKey) { - throw new Error('CCN private key not found'); - } - - const tags = allowedPubkeys.map((pubkey) => ['p', pubkey]); - tags.push(['t', 'invite']); - tags.push(['name', ccnName]); - - const privateKeyEvent = nostrTools.finalizeEvent( - nostrTools.nip13.minePow( - { - kind: 9998, - created_at: Date.now(), - content: base64.encode(ccnPrivateKey), - tags, - pubkey: ccnPubkey, - }, - POW_TO_MINE, - ), - ccnPrivateKey, - ); - - const encryptedKeyEvent = createEncryptedEventForPubkey( - inviteePubkey, - privateKeyEvent, - ); - publishToRelays(encryptedKeyEvent); - }); - - return; - } - - const isAllowedWrite = sql` - SELECT COUNT(*) as count FROM allowed_writes WHERE ccn_pubkey = ${ccnPubkey} AND pubkey = ${decryptedEvent.pubkey} - `(db)[0].count; - - if (isAllowedWrite === 0) { - throw new Error('Not allowed to write to this CCN'); - } - - try { - db.run('BEGIN TRANSACTION'); - - if (isReplaceableEvent(decryptedEvent.kind)) { - sql` - UPDATE events - SET replaced = 1 - WHERE kind = ${decryptedEvent.kind} - AND pubkey = ${decryptedEvent.pubkey} - AND created_at < ${decryptedEvent.created_at} - AND ccn_pubkey = ${ccnPubkey} - `(db); - } - - if (isAddressableEvent(decryptedEvent.kind)) { - const dTag = decryptedEvent.tags.find((tag) => tag[0] === 'd')?.[1]; - if (dTag) { - sql` - UPDATE events - SET replaced = 1 - WHERE kind = ${decryptedEvent.kind} - AND pubkey = ${decryptedEvent.pubkey} - AND created_at < ${decryptedEvent.created_at} - AND ccn_pubkey = ${ccnPubkey} - AND id IN ( - SELECT event_id FROM event_tags - WHERE tag_name = 'd' - AND tag_id IN ( - SELECT tag_id FROM event_tags_values - WHERE value_position = 1 - AND value = ${dTag} - ) - ) - `(db); - } - } - - if (isCCNReplaceableEvent(decryptedEvent.kind)) { - const dTag = decryptedEvent.tags.find((tag) => tag[0] === 'd')?.[1]; - sql` - UPDATE events - SET replaced = 1 - WHERE kind = ${decryptedEvent.kind} - AND created_at < ${decryptedEvent.created_at} - AND ccn_pubkey = ${ccnPubkey} - AND id IN ( - SELECT event_id FROM event_tags - WHERE tag_name = 'd' - AND tag_id IN ( - SELECT tag_id FROM event_tags_values - WHERE value_position = 1 - AND value = ${dTag} - ) - ) - `(db); - } - - sql` - INSERT INTO events (id, original_id, pubkey, created_at, kind, content, sig, first_seen, ccn_pubkey) VALUES ( - ${decryptedEvent.id}, - ${encryptedEvent.id}, - ${decryptedEvent.pubkey}, - ${decryptedEvent.created_at}, - ${decryptedEvent.kind}, - ${decryptedEvent.content}, - ${decryptedEvent.sig}, - unixepoch(), - ${ccnPubkey} - ) - `(db); - if (decryptedEvent.tags) { - for (let i = 0; i < decryptedEvent.tags.length; i++) { - const tag = sql` - INSERT INTO event_tags(event_id, tag_name, tag_index) VALUES ( - ${decryptedEvent.id}, - ${decryptedEvent.tags[i][0]}, - ${i} - ) RETURNING tag_id - `(db)[0]; - for (let j = 1; j < decryptedEvent.tags[i].length; j++) { - sql` - INSERT INTO event_tags_values(tag_id, value_position, value) VALUES ( - ${tag.tag_id}, - ${j}, - ${decryptedEvent.tags[i][j]} - ) - `(db); - } - } - } - db.run('COMMIT TRANSACTION'); - } catch (e) { - db.run('ROLLBACK TRANSACTION'); - throw e; - } -} - -function encryptedEventIsInDb(event: nostrTools.VerifiedEvent) { - return sql` - SELECT * FROM events WHERE original_id = ${event.id} - `(db)[0]; -} - -function cleanupOldChunks() { - const cutoffTime = Math.floor((Date.now() - CHUNK_MAX_AGE) / 1000); - sql`DELETE FROM event_chunks WHERE created_at < ${cutoffTime}`(db); -} - -let knownOriginalEventsCache: string[] = []; - -function updateKnownEventsCache() { - knownOriginalEventsCache = sql`SELECT original_id FROM events`(db).flatMap( - (row) => row.original_id, - ); -} - -/** - * Creates a subscription event handler for processing encrypted events. - * This handler decrypts and adds valid events to the database. - * @param database The database instance to use - * @returns An event handler function - */ -function createSubscriptionEventHandler(database: Database) { - return async (event: nostrTools.Event) => { - if (knownOriginalEventsCache.indexOf(event.id) >= 0) return; - if (!nostrTools.verifyEvent(event)) { - log.warn('Invalid event received'); - return; - } - if (encryptedEventIsInDb(event)) return; - try { - const decryptedEvent = await decryptEvent(database, event); - addEventToDb(decryptedEvent, event, decryptedEvent.ccnPubkey); - updateKnownEventsCache(); - } catch (e) { - if (e instanceof EventAlreadyExistsException) return; - if (e instanceof ChunkedEventReceived) { - return; - } - } - }; -} - -/** - * Publishes an event to relays, handling both single events and chunked events - * @param encryptedEvent The encrypted event or array of chunked events - */ -async function publishToRelays( - encryptedEvent: nostrTools.Event | nostrTools.Event[], -): Promise { - if (Array.isArray(encryptedEvent)) { - for (const chunk of encryptedEvent) { - await Promise.any(pool.publish(relays, chunk)); - } - } else { - await Promise.any(pool.publish(relays, encryptedEvent)); - } -} - -function setupAndSubscribeToExternalEvents() { - const isInitialized = sql` - SELECT name FROM sqlite_master WHERE type='table' AND name='migration_history' - `(db)[0]; - - if (!isInitialized) runMigrations(db, -1); - - const latestVersion = - sql` - SELECT migration_version FROM migration_history WHERE status = 'success' ORDER BY migration_version DESC LIMIT 1 - `(db)[0]?.migration_version ?? -1; - - runMigrations(db, latestVersion); - - const allCCNs = sql`SELECT pubkey FROM ccns`(db); - const ccnPubkeys = allCCNs.map((ccn) => ccn.pubkey); - - pool.subscribeMany( - relays, - [ - { - '#p': ccnPubkeys, - kinds: [1059], - }, - ], - { - onevent: createSubscriptionEventHandler(db), - }, - ); - - updateKnownEventsCache(); - setInterval(cleanupOldChunks, CHUNK_CLEANUP_INTERVAL); -} - -await setupAndSubscribeToExternalEvents(); - -class UserConnection { - public socket: WebSocket; - public subscriptions: Map; - public db: Database; - - constructor( - socket: WebSocket, - subscriptions: Map, - db: Database, - ) { - this.socket = socket; - this.subscriptions = subscriptions; - this.db = db; - } - - /** - * Sends a response to the client - * @param responseArray The response array to send - */ - sendResponse(responseArray: unknown[]): void { - this.socket.send(JSON.stringify(responseArray)); - } - - /** - * Sends a notice to the client - * @param message The message to send - */ - sendNotice(message: string): void { - this.sendResponse(['NOTICE', message]); - } - - /** - * Sends an event to the client - * @param subscriptionId The subscription ID - * @param event The event to send - */ - sendEvent(subscriptionId: string, event: NostrEvent): void { - this.sendResponse(['EVENT', subscriptionId, event]); - } - - /** - * Sends an end of stored events message - * @param subscriptionId The subscription ID - */ - sendEOSE(subscriptionId: string): void { - this.sendResponse(['EOSE', subscriptionId]); - } - - /** - * Sends an OK response - * @param eventId The event ID - * @param success Whether the operation was successful - * @param message The message to send - */ - sendOK(eventId: string, success: boolean, message: string): void { - this.sendResponse(['OK', eventId, success, message]); - } -} - -function filtersMatchingEvent( - event: NostrEvent, - connection: UserConnection, -): string[] { - const matching = []; - for (const subscription of connection.subscriptions.keys()) { - const filters = connection.subscriptions.get(subscription); - if (!filters) continue; - const isMatching = filters.every((filter) => - Object.entries(filter).every(([type, value]) => { - if (type === 'ids') return value.includes(event.id); - if (type === 'kinds') return value.includes(event.kind); - if (type === 'authors') return value.includes(event.pubkey); - if (type === 'since') return event.created_at >= value; - if (type === 'until') return event.created_at <= value; - if (type === 'limit') return event.created_at <= value; - if (type.startsWith('#')) { - const tagName = type.slice(1); - return event.tags.some( - (tag: string[]) => tag[0] === tagName && value.includes(tag[1]), - ); - } - return false; - }), - ); - if (isMatching) matching.push(subscription); - } - return matching; -} - -function handleRequest(connection: UserConnection, request: NostrClientREQ) { - const [, subscriptionId, ...filters] = request; - if (connection.subscriptions.has(subscriptionId)) { - return log.warn('Duplicate subscription ID'); - } - - log.info( - `New subscription: ${subscriptionId} with filters: ${JSON.stringify( - filters, - )}`, - ); - - const activeCCN = getActiveCCN(connection.db); - if (!activeCCN) { - connection.sendNotice('No active CCN found'); - return log.warn('No active CCN found'); - } - - let query = sqlPartial`SELECT * FROM events WHERE replaced = 0 AND ccn_pubkey = ${activeCCN.pubkey}`; - - const filtersAreNotEmpty = filters.some((filter) => { - return Object.values(filter).some((value) => { - return value.length > 0; - }); - }); - - if (filtersAreNotEmpty) { - query = mixQuery(query, sqlPartial`AND`); - - for (let i = 0; i < filters.length; i++) { - // filters act as OR, filter groups act as AND - query = mixQuery(query, sqlPartial`(`); - - const filter = Object.entries(filters[i]).filter(([type, value]) => { - if (type === 'ids') return value.length > 0; - if (type === 'authors') return value.length > 0; - if (type === 'kinds') return value.length > 0; - if (type.startsWith('#')) return value.length > 0; - if (type === 'since') return value > 0; - if (type === 'until') return value > 0; - return false; - }); - - for (let j = 0; j < filter.length; j++) { - const [type, value] = filter[j]; - - if (type === 'ids') { - const uniqueIds = [...new Set(value)]; - query = mixQuery(query, sqlPartial`id IN (`); - for (let k = 0; k < uniqueIds.length; k++) { - const id = uniqueIds[k] as string; - - query = mixQuery(query, sqlPartial`${id}`); - - if (k < uniqueIds.length - 1) { - query = mixQuery(query, sqlPartial`,`); - } - } - query = mixQuery(query, sqlPartial`)`); - } - - if (type === 'authors') { - const uniqueAuthors = [...new Set(value)]; - query = mixQuery(query, sqlPartial`pubkey IN (`); - for (let k = 0; k < uniqueAuthors.length; k++) { - const author = uniqueAuthors[k] as string; - - query = mixQuery(query, sqlPartial`${author}`); - - if (k < uniqueAuthors.length - 1) { - query = mixQuery(query, sqlPartial`,`); - } - } - query = mixQuery(query, sqlPartial`)`); - } - - if (type === 'kinds') { - const uniqueKinds = [...new Set(value)]; - query = mixQuery(query, sqlPartial`kind IN (`); - for (let k = 0; k < uniqueKinds.length; k++) { - const kind = uniqueKinds[k] as number; - - query = mixQuery(query, sqlPartial`${kind}`); - - if (k < uniqueKinds.length - 1) { - query = mixQuery(query, sqlPartial`,`); - } - } - query = mixQuery(query, sqlPartial`)`); - } - - if (type.startsWith('#')) { - const tag = type.slice(1); - const uniqueValues = [...new Set(value)]; - query = mixQuery(query, sqlPartial`(`); - for (let k = 0; k < uniqueValues.length; k++) { - const tagValue = uniqueValues[k] as string; - if (tag === 'a') { - const aTagInfo = parseATagQuery(tagValue); - - if (aTagInfo.dTag && aTagInfo.dTag !== '') { - if (isCCNReplaceableEvent(aTagInfo.kind)) { - // CCN replaceable event reference - query = mixQuery( - query, - sqlPartial`id IN ( - SELECT e.id - FROM events e - JOIN event_tags t ON e.id = t.event_id - JOIN event_tags_values v ON t.tag_id = v.tag_id - WHERE e.kind = ${aTagInfo.kind} - AND t.tag_name = 'd' - AND v.value_position = 1 - AND v.value = ${aTagInfo.dTag} - )`, - ); - } else { - // Addressable event reference - query = mixQuery( - query, - sqlPartial`id IN ( - SELECT e.id - FROM events e - JOIN event_tags t ON e.id = t.event_id - JOIN event_tags_values v ON t.tag_id = v.tag_id - WHERE e.kind = ${aTagInfo.kind} - AND e.pubkey = ${aTagInfo.pubkey} - AND t.tag_name = 'd' - AND v.value_position = 1 - AND v.value = ${aTagInfo.dTag} - )`, - ); - } - } else { - // Replaceable event reference - query = mixQuery( - query, - sqlPartial`id IN ( - SELECT id - FROM events - WHERE kind = ${aTagInfo.kind} - AND pubkey = ${aTagInfo.pubkey} - )`, - ); - } - } else { - // Regular tag handling (unchanged) - query = mixQuery( - query, - sqlPartial`id IN ( - SELECT t.event_id - FROM event_tags t - WHERE t.tag_name = ${tag} - AND t.tag_id IN ( - SELECT v.tag_id - FROM event_tags_values v - WHERE v.value_position = 1 - AND v.value = ${tagValue} - ) - )`, - ); - } - - if (k < uniqueValues.length - 1) { - query = mixQuery(query, sqlPartial`OR`); - } - } - query = mixQuery(query, sqlPartial`)`); - } - - if (type === 'since') { - query = mixQuery(query, sqlPartial`created_at >= ${value}`); - } - - if (type === 'until') { - query = mixQuery(query, sqlPartial`created_at <= ${value}`); - } - - if (j < filter.length - 1) query = mixQuery(query, sqlPartial`AND`); - } - - query = mixQuery(query, sqlPartial`)`); - - if (i < filters.length - 1) query = mixQuery(query, sqlPartial`OR`); - } - } - - query = mixQuery(query, sqlPartial`ORDER BY created_at ASC`); - - log.debug(query.query, ...query.values); - - const events = connection.db.prepare(query.query).all(...query.values); - - for (let i = 0; i < events.length; i++) { - const rawTags = sql`SELECT * FROM event_tags_view WHERE event_id = ${ - events[i].id - }`(connection.db); - const tagsByIndex = new Map< - number, - { - name: string; - values: Map; - } - >(); - - for (const tag of rawTags) { - let tagData = tagsByIndex.get(tag.tag_index); - if (!tagData) { - tagData = { - name: tag.tag_name, - values: new Map(), - }; - tagsByIndex.set(tag.tag_index, tagData); - } - - tagData.values.set(tag.tag_value_position, tag.tag_value); - } - - const tagsArray = Array.from(tagsByIndex.entries()) - .sort(([indexA], [indexB]) => indexA - indexB) - .map(([_, tagData]) => { - const { name, values } = tagData; - - return [ - name, - ...Array.from(values.entries()) - .sort(([posA], [posB]) => posA - posB) - .map(([_, value]) => value), - ]; - }); - - const event = { - id: events[i].id, - pubkey: events[i].pubkey, - created_at: events[i].created_at, - kind: events[i].kind, - tags: tagsArray, - content: events[i].content, - sig: events[i].sig, - }; - - connection.sendEvent(subscriptionId, event); - } - connection.sendEOSE(subscriptionId); - - connection.subscriptions.set(subscriptionId, filters); -} - -async function handleEvent( - connection: UserConnection, - event: nostrTools.Event, -) { - const valid = nostrTools.verifyEvent(event); - if (!valid) { - connection.sendNotice('Invalid event'); - return log.warn('Invalid event'); - } - - const activeCCN = getActiveCCN(connection.db); - if (!activeCCN) { - connection.sendNotice('No active CCN found'); - return log.warn('No active CCN found'); - } - - const encryptedEvent = await createEncryptedEvent(event, connection.db); - try { - if (Array.isArray(encryptedEvent)) { - await publishToRelays(encryptedEvent); - addEventToDb(event, encryptedEvent[0], activeCCN.pubkey); - } else { - addEventToDb(event, encryptedEvent, activeCCN.pubkey); - await publishToRelays(encryptedEvent); - } - } catch (e) { - if (e instanceof EventAlreadyExistsException) { - log.warn('Event already exists'); - return; - } - } - - connection.sendOK(event.id, true, 'Event added'); - - const filtersThatMatchEvent = filtersMatchingEvent(event, connection); - - for (let i = 0; i < filtersThatMatchEvent.length; i++) { - const filter = filtersThatMatchEvent[i]; - connection.sendEvent(filter, event); - } -} - -function handleClose(connection: UserConnection, subscriptionId: string) { - if (!connection.subscriptions.has(subscriptionId)) { - return log.warn( - `Closing unknown subscription? That's weird. Subscription ID: ${subscriptionId}`, - ); - } - - connection.subscriptions.delete(subscriptionId); -} - -/** - * Activates a CCN by setting it as the active one in the database - * @param database The database instance to use - * @param pubkey The public key of the CCN to activate - */ -function activateCCN(database: Database, pubkey: string): void { - sql`UPDATE ccns SET is_active = 0`(database); - sql`UPDATE ccns SET is_active = 1 WHERE pubkey = ${pubkey}`(database); -} - -/** - * Handles errors in socket operations, logs them and sends a notification to the client - * @param connection The WebSocket connection - * @param operation The operation that failed - * @param error The error that occurred - */ -function handleSocketError( - connection: UserConnection, - operation: string, - error: unknown, -): void { - const errorMessage = error instanceof Error ? error.message : 'Unknown error'; - log.error(`Error ${operation}: ${errorMessage}`); - connection.sendNotice(`Failed to ${operation}`); -} - -async function handleCreateCCN( - connection: UserConnection, - data: { name: string; seed?: string; creator: string }, -): Promise { - try { - if (!data.name || typeof data.name !== 'string') { - connection.sendNotice('Name is required'); - return; - } - - if (!data.creator || typeof data.creator !== 'string') { - connection.sendNotice('Creator is required'); - return; - } - - const newCcn = await createNewCCN( - connection.db, - data.name, - data.creator, - data.seed, - ); - - activateCCN(connection.db, newCcn.pubkey); - - pool.subscribeMany( - relays, - [ - { - '#p': [newCcn.pubkey], - kinds: [1059], - }, - ], - { - onevent: createSubscriptionEventHandler(connection.db), - }, - ); - - connection.sendResponse([ - 'OK', - 'CCN CREATED', - true, - JSON.stringify({ - pubkey: newCcn.pubkey, - name: data.name, - }), - ]); - - log.info(`CCN created: ${data.name}`); - } catch (error: unknown) { - handleSocketError(connection, 'create CCN', error); - } -} - -function handleGetCCNs(connection: UserConnection): void { - try { - const ccns = getAllCCNs(connection.db); - connection.sendResponse(['OK', 'CCN LIST', true, JSON.stringify(ccns)]); - } catch (error: unknown) { - handleSocketError(connection, 'get CCNs', error); - } -} - -function handleActivateCCN( - connection: UserConnection, - data: { pubkey: string }, -): void { - try { - if (!data.pubkey || typeof data.pubkey !== 'string') { - connection.sendNotice('CCN pubkey is required'); - return; - } - - const ccnExists = sql` - SELECT COUNT(*) as count FROM ccns WHERE pubkey = ${data.pubkey} - `(connection.db)[0].count; - - if (ccnExists === 0) { - connection.sendNotice('CCN not found'); - return; - } - - for (const subscriptionId of connection.subscriptions.keys()) { - connection.sendResponse([ - 'CLOSED', - subscriptionId, - 'Subscription closed due to CCN activation', - ]); - } - - connection.subscriptions.clear(); - log.info('All subscriptions cleared due to CCN activation'); - - activateCCN(connection.db, data.pubkey); - - const activatedCCN = sql` - SELECT pubkey, name FROM ccns WHERE pubkey = ${data.pubkey} - `(connection.db)[0]; - - connection.sendResponse([ - 'OK', - 'CCN ACTIVATED', - true, - JSON.stringify(activatedCCN), - ]); - - log.info(`CCN activated: ${activatedCCN.name}`); - } catch (error: unknown) { - handleSocketError(connection, 'activate CCN', error); - } -} - -async function handleAddCCN( - connection: UserConnection, - data: { name: string; allowedPubkeys: string[]; privateKey: string }, -): Promise { - try { - if (!data.privateKey || typeof data.privateKey !== 'string') { - connection.sendNotice('CCN private key is required'); - return; - } - - const privateKeyBytes = hexToBytes(data.privateKey); - const pubkey = nostrTools.getPublicKey(privateKeyBytes); - - const ccnExists = sql` - SELECT COUNT(*) as count FROM ccns WHERE pubkey = ${pubkey} - `(connection.db)[0].count; - - if (ccnExists > 0) { - connection.sendNotice('CCN already exists'); - return; - } - - const ccnPublicKey = nostrTools.getPublicKey(privateKeyBytes); - const ccnPrivPath = await getEveFilePath(`ccn_keys/${ccnPublicKey}`); - const encryptedPrivateKey = encryptUint8Array( - privateKeyBytes, - encryptionKey, - ); - Deno.writeTextFileSync(ccnPrivPath, encodeBase64(encryptedPrivateKey)); - - db.run('BEGIN TRANSACTION'); - - sql`INSERT INTO ccns (pubkey, name) VALUES (${ccnPublicKey}, ${data.name})`( - db, - ); - for (const allowedPubkey of data.allowedPubkeys) - sql`INSERT INTO allowed_writes (ccn_pubkey, pubkey) VALUES (${ccnPublicKey}, ${allowedPubkey})`( - db, - ); - - db.run('COMMIT TRANSACTION'); - - activateCCN(connection.db, ccnPublicKey); - - pool.subscribeMany( - relays, - [ - { - '#p': [ccnPublicKey], - kinds: [1059], - }, - ], - { - onevent: createSubscriptionEventHandler(connection.db), - }, - ); - - connection.sendResponse([ - 'OK', - 'CCN ADDED', - true, - JSON.stringify({ - pubkey: ccnPublicKey, - name: 'New CCN', - }), - ]); - } catch (error: unknown) { - handleSocketError(connection, 'ADD CCN', error); - } -} - -function handleCCNCommands( - connection: UserConnection, - command: string, - data: unknown, -) { - switch (command) { - case 'CREATE': - return handleCreateCCN( - connection, - data as { name: string; seed?: string; creator: string }, - ); - case 'ADD': - return handleAddCCN( - connection, - data as { name: string; allowedPubkeys: string[]; privateKey: string }, - ); - case 'LIST': - return handleGetCCNs(connection); - case 'ACTIVATE': - return handleActivateCCN(connection, data as { pubkey: string }); - default: - return log.warn('Invalid CCN command'); - } -} - -Deno.serve({ - port: 6942, - handler: (request) => { - if (request.headers.get('upgrade') === 'websocket') { - if (!isLocalhost(request)) { - return new Response( - 'Forbidden. Please read the Arx-CCN documentation for more information on how to interact with the relay.', - { status: 403 }, - ); - } - - const { socket, response } = Deno.upgradeWebSocket(request); - - const connection = new UserConnection(socket, new Map(), db); - - socket.onopen = () => log.info('User connected'); - socket.onmessage = (event) => { - log.debug(`Received: ${event.data}`); - if (typeof event.data !== 'string' || !isValidJSON(event.data)) { - return log.warn('Invalid request'); - } - const data = JSON.parse(event.data); - if (!isArray(data)) return log.warn('Invalid request'); - - const msgType = data[0]; - switch (msgType) { - case 'REQ': - return handleRequest(connection, n.clientREQ().parse(data)); - case 'EVENT': - return handleEvent(connection, n.clientEVENT().parse(data)[1]); - case 'CLOSE': - return handleClose(connection, n.clientCLOSE().parse(data)[1]); - case 'CCN': - return handleCCNCommands(connection, data[1] as string, data[2]); - default: - return log.warn('Invalid request'); - } - }; - socket.onclose = () => log.info('User disconnected'); - - return response; - } - return new Response( - Deno.readTextFileSync(`${import.meta.dirname}/public/landing.html`), - { - headers: { 'Content-Type': 'text/html' }, - }, - ); - }, -});