From a8977f8c5c84b0c37c4fb36f0a0be5bf6f492f3d Mon Sep 17 00:00:00 2001 From: Adam Soltys Date: Wed, 18 Mar 2026 11:39:05 -0700 Subject: stop republishing external events and add NWC rate limiting Co-Authored-By: Claude Opus 4.6 (1M context) --- lib/nwc.ts | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) (limited to 'lib/nwc.ts') diff --git a/lib/nwc.ts b/lib/nwc.ts index b0f1021f..0d18f744 100644 --- a/lib/nwc.ts +++ b/lib/nwc.ts @@ -37,6 +37,11 @@ const nwcEventMaxAgeSeconds = 5 * 60; const handledKey = "handled:nwc"; const handledMaxSize = 200000; +// Per-pubkey rate limiting for NWC requests +const nwcRateLimit = 5; // max requests per minute per pubkey +const nwcRateWindow = 60 * 1000; // 1 minute in ms +const nwcRequestTimes: Map = new Map(); + export default () => { let r: any; @@ -45,7 +50,7 @@ export default () => { r.on("open", async (_) => { l("nwc connected to strfry"); - r.subscribe("nwc", { kinds: [23194], "#p": [serverPubkey, serverPubkey2] }); + r.subscribe("nwc", { kinds: [23194], "#p": [serverPubkey, serverPubkey2], since: Math.floor(Date.now() / 1000) - nwcEventMaxAgeSeconds }); const info = await finalizeEvent( { created_at: Math.floor(Date.now() / 1000), @@ -89,6 +94,14 @@ export default () => { if (ev.created_at && now - ev.created_at > nwcEventMaxAgeSeconds) return; if (await db.zScore(handledKey, ev.id)) return; + // Per-pubkey rate limiting + const times = nwcRequestTimes.get(ev.pubkey) || []; + const cutoff = Date.now() - nwcRateWindow; + const recent = times.filter((t) => t > cutoff); + if (recent.length >= nwcRateLimit) return; + recent.push(Date.now()); + nwcRequestTimes.set(ev.pubkey, recent); + db.zAdd(handledKey, { score: now, value: ev.id }); db.zRemRangeByScore(handledKey, 0, now - nwcEventMaxAgeSeconds); const size = await db.zCard(handledKey); -- cgit v1.2.3