diff --git a/.changeset/peering-admission-policy.md b/.changeset/peering-admission-policy.md new file mode 100644 index 000000000..c1cf9b182 --- /dev/null +++ b/.changeset/peering-admission-policy.md @@ -0,0 +1,17 @@ +--- +"nostream": patch +--- + +fix(peering): apply the relay's admission policy to live feed events + +A peer could previously push an event over the live peering feed that a local +client would have been refused for: the sync worker wrote live traffic through +the bulk-import persister, which applies vanish and delete semantics but not +content, tag, `created_at`, PoW, blocklist, admission or NIP-05 policy. + +The admission decision is now shared with the normal `EVENT` path. Live peering +events are checked before they are stored or broadcast, so a blocked pubkey, +over-limit content, insufficient PoW or unverified author no longer reaches the +relay through a feed. Accepted live events feed the adaptive PoW rate, and a +live kind-0 profile starts the same NIP-05 verification as a local one. +Historical backfill keeps the policy-free batch persister. diff --git a/docs/PEERING.md b/docs/PEERING.md index 200754391..8be2faf82 100644 --- a/docs/PEERING.md +++ b/docs/PEERING.md @@ -111,8 +111,15 @@ their relay tags target this relay. Ephemeral events are broadcast live but never stored. Authors under an active vanish request are skipped, with the vanish check cached once per author per batch. Live events are also broadcast to local subscribers, so a peer feed is indistinguishable from a locally published -event to this relay's clients. Backfilled history is not broadcast, because it -predates any live subscription. +event to this relay's clients. Live events also clear the relay's admission +policy first: content and tag limits, `created_at` bounds, PoW, pubkey and kind +allow/block lists, active requests to vanish, NIP-43 or payment admission, and +NIP-05 verification. A live event the relay would refuse from a local client is +neither stored nor broadcast. Accepted live events also feed the adaptive PoW +rate, and a live kind-0 profile starts the same NIP-05 verification as a local +one. Historical backfill keeps the policy-free batch persister, because it +predates the live subscription and is fetched rather than pushed. Backfilled +history is not broadcast, because it predates any live subscription. If the peer rejects a filter as too large, the worker splits it by kind and then by time range and retries. A fetch batch that exceeds the byte budget is split diff --git a/src/app/peering-sync-worker.ts b/src/app/peering-sync-worker.ts index 86b8ce200..8a71d246c 100644 --- a/src/app/peering-sync-worker.ts +++ b/src/app/peering-sync-worker.ts @@ -4,8 +4,13 @@ import { ICacheAdapter } from '../@types/adapters' import { IRunnable } from '../@types/base' import { Event } from '../@types/event' import { PeeringAdvertisement, PeeringPeerSyncState } from '../@types/peering' -import { IEventRepository, IUserRepository } from '../@types/repositories' -import { IPeeringBuyerService } from '../@types/services' +import { + IEventRepository, + INip05VerificationRepository, + IUserRepository, + IUserSubscriptionRepository, +} from '../@types/repositories' +import { IPeeringBuyerService, IWotGraphService } from '../@types/services' import { PeeringPeer, PeeringScope, Settings } from '../@types/settings' import { SubscriptionFilter } from '../@types/subscription' import { createLogger } from '../factories/logger-factory' @@ -25,6 +30,9 @@ import { isExpiredEvent, isRequestToVanishEvent, } from '../utils/event' +import { recordEvent as recordAdaptivePowEvent } from '../utils/adaptive-pow' +import { admitEvent, EventAdmissionContext } from '../utils/event-admission' +import { processNip05MetadataIfCurrent } from '../utils/nip05-metadata' import { delayMs } from '../utils/misc' import { FetchPeeringAdvertisementOptions, fetchPeeringAdvertisement } from '../utils/peering-advertisement' import { @@ -104,7 +112,11 @@ export interface PeeringSyncWorkerOptions { createConnection?: (socket: AuthenticatedPeerConnection['socket']) => PeeringSyncConnection stateStore?: PeeringSyncStateStore opsCache?: ICacheAdapter - userRepository?: Pick + userRepository?: Pick + nip05VerificationRepository?: Pick + admissionCache?: ICacheAdapter + wotGraphService?: Pick + userSubscriptionRepository?: Pick privateKey?: () => string reconnectDelayMs?: number reconcileIntervalMs?: number @@ -172,6 +184,10 @@ class PeeringPeerSession { | 'reconcileIntervalMs' | 'eventBatchSize' | 'userRepository' + | 'nip05VerificationRepository' + | 'admissionCache' + | 'wotGraphService' + | 'userSubscriptionRepository' | 'stateHeartbeatMs' | 'buyerService' >, @@ -771,6 +787,26 @@ class PeeringPeerSession { } } + private admissionContext(): EventAdmissionContext { + return { + settings: this.settings, + relayPubkey: () => { + try { + return getPublicKey(getRelayPrivateKey(this.settings().info.relay_url)) + } catch { + // Without SECRET the relay identity is unknown, so no event can claim + // the relay-author exemption. The rest of the policy still applies. + return '' + } + }, + userRepository: this.options.userRepository, + nip05VerificationRepository: this.options.nip05VerificationRepository, + cache: this.options.admissionCache, + wotGraphService: this.options.wotGraphService, + userSubscriptionRepository: this.options.userSubscriptionRepository, + } + } + /** * Accepts only events that were asked for and still match the scope, then * verifies the event id and signature. A peer cannot inject an arbitrary @@ -817,12 +853,43 @@ class PeeringPeerSession { let stored = 0 if (broadcast) { + // The live feed must not be a hole in the relay's write policy. The + // historical backfill below deliberately keeps the policy-free persister. + const admitted: Event[] = [] + // Live traffic is one event at a time, so we can tell which write // actually stored or changed something. Only those are rebroadcast: // an overlap replay of an event both relays already hold must not echo. for (const event of accepted) { + const reason = await admitEvent(event, this.admissionContext()) + if (reason) { + logger.warn( + 'peer %s sent a live event rejected by the admission policy: %s (%s)', + this.peer.relayUrl, + event.id, + reason, + ) + continue + } + + const powSettings = this.settings().limits?.event?.pow + if (powSettings?.enabled && event.kind !== EventKinds.PEERING_REQUEST) { + recordAdaptivePowEvent(powSettings.periodMs) + } + const count = await this.persistEvents([event]) stored += count + admitted.push(event) + + if (event.kind === EventKinds.SET_METADATA) { + void processNip05MetadataIfCurrent(event, { + settings: this.settings, + eventRepository: this.eventRepository, + nip05VerificationRepository: this.options.nip05VerificationRepository, + }).catch((error) => { + logger.error('failed to verify the NIP-05 metadata of %s: %o', event.id, error) + }) + } if ((count > 0 || isEphemeralEvent(event)) && !isRequestToVanishEvent(event)) { void broadcastEvent(event).catch((error) => { @@ -831,7 +898,7 @@ class PeeringPeerSession { } } - return { events: accepted, stored } + return { events: admitted, stored } } // Backfill is deliberately not broadcast: those events predate any live @@ -970,6 +1037,10 @@ export class PeeringSyncWorker implements IRunnable { privateKey: this.options.privateKey ?? (() => getRelayPrivateKey(this.settings().info?.relay_url)), stateStore: this.options.stateStore, userRepository: this.options.userRepository, + nip05VerificationRepository: this.options.nip05VerificationRepository, + admissionCache: this.options.admissionCache, + wotGraphService: this.options.wotGraphService, + userSubscriptionRepository: this.options.userSubscriptionRepository, reconnectDelayMs: this.options.reconnectDelayMs, reconcileIntervalMs: this.options.reconcileIntervalMs, eventBatchSize: this.options.eventBatchSize, diff --git a/src/factories/peering-sync-worker-factory.ts b/src/factories/peering-sync-worker-factory.ts index 564b0f6c2..ffbc23f56 100644 --- a/src/factories/peering-sync-worker-factory.ts +++ b/src/factories/peering-sync-worker-factory.ts @@ -1,11 +1,15 @@ import { PeeringSyncWorker } from '../app/peering-sync-worker' import { getMasterDbClient, getReadReplicaDbClient } from '../database/client' +import { Nip05VerificationRepository } from '../repositories/nip05-verification-repository' import { UserRepository } from '../repositories/user-repository' +import { UserSubscriptionRepository } from '../repositories/user-subscription-repository' import { PeeringSyncStateStore } from '../utils/peering-sync-state' import { createAdminOpsCacheAdapter } from './admin-ops-cache-adapter-factory' import { createEventRepository } from './event-repository-factory' +import { getCache } from './message-handler-factory' import { createPeeringBuyerService } from './peering-buyer-service-factory' import { createSettings } from './settings-factory' +import { wotGraphServiceFactory } from './wot-graph-service-factory' export const peeringSyncWorkerFactory = () => { const cache = createAdminOpsCacheAdapter() @@ -16,6 +20,11 @@ export const peeringSyncWorkerFactory = () => { return new PeeringSyncWorker(process, createSettings, eventRepository, { ...(cache ? { opsCache: cache, stateStore: new PeeringSyncStateStore(cache) } : {}), userRepository, + // The live feed has to clear the same admission policy as a local EVENT. + nip05VerificationRepository: new Nip05VerificationRepository(dbClient), + admissionCache: getCache(), + wotGraphService: wotGraphServiceFactory(getCache(), eventRepository, createSettings), + userSubscriptionRepository: new UserSubscriptionRepository(dbClient), buyerService: createPeeringBuyerService(), }) } diff --git a/src/handlers/event-message-handler.ts b/src/handlers/event-message-handler.ts index a2a8b704a..0b4aeedf3 100644 --- a/src/handlers/event-message-handler.ts +++ b/src/handlers/event-message-handler.ts @@ -1,38 +1,19 @@ -import { - getCurrentDifficulty as getAdaptivePowDifficulty, - recordEvent as recordAdaptivePowEvent, -} from '../utils/adaptive-pow' -import { applyWotPowPolicy } from '../utils/wot-pow-policy' +import { recordEvent as recordAdaptivePowEvent } from '../utils/adaptive-pow' import { ContextMetadataKey, EventExpirationTimeMetadataKey, EventKinds } from '../constants/base' import { attemptValidation } from '../utils/validation' import { eventSchema } from '../schemas/event-schema' -import { - DEFAULT_NIP05_VERIFY_EXPIRATION_MS, - extractNip05FromEvent, - isDomainAllowed, - Nip05VerificationOutcome, - parseNip05Identifier, - verifyNip05Identifier, -} from '../utils/nip05' import { Event, ExpiringEvent } from '../@types/event' import { UserSubscription } from '../@types/user-subscription' -import { EventRateLimit, FeeSchedule, Settings } from '../@types/settings' +import { EventRateLimit, Settings } from '../@types/settings' import { getEventExpiration, - getEventProofOfWork, - getPubkeyProofOfWork, getPublicKey, getRelayPrivateKey, - isDirectMessageEvent, isEventIdValid, isEventKindOrRangeMatch, isEventSignatureValid, isExpiredEvent, - isFileMessageEvent, isProtectedEvent, - isRequestToVanishEvent, - isSealEvent, - isWelcomeRumorEvent, } from '../utils/event' import { areSubscriptionsEnabled, @@ -50,21 +31,31 @@ import { } from '../@types/repositories' import { IEventStrategy, IMessageHandler } from '../@types/message-handlers' import { - admissionCacheKey, - CacheAdmissionState, NO_SUBSCRIPTION_PLAN, SUBSCRIPTION_PLAN_PREFIX, subscriptionPlanCacheKey, } from '../constants/caching' import { createEventCommandResult } from '../telemetry/event-metrics' import { createLogger } from '../factories/logger-factory' +import { + EventAdmissionContext, + getEventLimitError, + getEventValidationError, + getNip05VerificationError, + getRequestToVanishError, + getUserAdmissionError, +} from '../utils/event-admission' +import { + isSupersededProfile, + Nip05MetadataContext, + processNip05Metadata, +} from '../utils/nip05-metadata' import { Factory } from '../@types/base' import { ICacheAdapter } from '../@types/adapters' import { IncomingEventMessage } from '../@types/messages' import { IRateLimiter, IRateLimiterResult } from '../@types/utils' import { IWebSocketAdapter } from '../@types/adapters' import { IWotGraphService } from '../@types/services' -import { Nip05Verification } from '../@types/nip05' import { WebSocketAdapterEvent } from '../constants/adapter' import { recordModerationRateLimitHitSafely } from '../utils/moderation-rate-limit-stats' @@ -223,123 +214,7 @@ export class EventMessageHandler implements IMessageHandler { } protected async canAcceptEvent(event: Event): Promise { - if (this.getRelayPublicKey() === event.pubkey) { - return - } - const now = Math.floor(Date.now() / 1000) - - const limits = this.settings().limits?.event ?? {} - - if (Array.isArray(limits.content)) { - for (const limit of limits.content) { - if ( - typeof limit.maxLength !== 'undefined' && - limit.maxLength > 0 && - event.content.length > limit.maxLength && - (!Array.isArray(limit.kinds) || limit.kinds.some(isEventKindOrRangeMatch(event))) - ) { - return `rejected: content is longer than ${limit.maxLength} bytes` - } - } - } else if ( - typeof limits.content?.maxLength !== 'undefined' && - limits.content?.maxLength > 0 && - event.content.length > limits.content.maxLength && - (!Array.isArray(limits.content.kinds) || limits.content.kinds.some(isEventKindOrRangeMatch(event))) - ) { - return `rejected: content is longer than ${limits.content.maxLength} bytes` - } - - if ( - typeof limits.createdAt?.maxPositiveDelta !== 'undefined' && - limits.createdAt.maxPositiveDelta > 0 && - event.created_at > now + limits.createdAt.maxPositiveDelta - ) { - return `rejected: created_at is more than ${limits.createdAt.maxPositiveDelta} seconds in the future` - } - - if ( - typeof limits.createdAt?.maxNegativeDelta !== 'undefined' && - limits.createdAt.maxNegativeDelta > 0 && - event.created_at < now - limits.createdAt.maxNegativeDelta - ) { - return `rejected: created_at is more than ${limits.createdAt.maxNegativeDelta} seconds in the past` - } - - // Adaptive PoW applies to the eventId check only: a pubkey requirement is a - // one-time, offline identity cost, not a per-event load signal, so it can't - // respond to relay load the way an event id's mined-per-submission pow can. - // The static pubkey.minLeadingZeroBits knob is left untouched regardless of - // pow.enabled -- per maintainer direction on PR #756. - if (event.kind === EventKinds.PEERING_REQUEST) { - // Peering requests carry their own NIP-13 requirement, checked by the - // strategy after the owner signature and AUTH identity are known. - } else if (limits.pow?.enabled) { - const computedDifficulty = getAdaptivePowDifficulty(limits.pow) - // Only consult the WoT graph when thresholds are actually configured -- - // a distance lookup is unnecessary work otherwise, and skipping it also - // means wot.enabled=false relays never pay for it. - const distance = limits.pow.wotThresholds?.length - ? await this.wotGraphService.getDistance(event.pubkey) - : undefined - const requiredBits = applyWotPowPolicy(computedDifficulty, distance, limits.pow.wotThresholds) - - const pow = getEventProofOfWork(event.id) - if (pow < requiredBits) { - return `pow: difficulty ${pow}<${requiredBits}` - } - } else if (typeof limits.eventId?.minLeadingZeroBits !== 'undefined' && limits.eventId.minLeadingZeroBits > 0) { - const pow = getEventProofOfWork(event.id) - if (pow < limits.eventId.minLeadingZeroBits) { - return `pow: difficulty ${pow}<${limits.eventId.minLeadingZeroBits}` - } - } - - if ( - event.kind !== EventKinds.PEERING_REQUEST && - typeof limits.pubkey?.minLeadingZeroBits !== 'undefined' && - limits.pubkey.minLeadingZeroBits > 0 - ) { - const pow = getPubkeyProofOfWork(event.pubkey) - if (pow < limits.pubkey.minLeadingZeroBits) { - return `pow: pubkey difficulty ${pow}<${limits.pubkey.minLeadingZeroBits}` - } - } - - if ( - event.kind !== EventKinds.PEERING_REQUEST && - typeof limits.pubkey?.whitelist !== 'undefined' && - limits.pubkey.whitelist.length > 0 && - !limits.pubkey.whitelist.includes(event.pubkey) - ) { - return 'blocked: pubkey not allowed' - } - - if ( - typeof limits.pubkey?.blacklist !== 'undefined' && - limits.pubkey.blacklist.length > 0 && - limits.pubkey.blacklist.includes(event.pubkey) - ) { - return 'blocked: pubkey not allowed' - } - - if ( - event.kind !== EventKinds.PEERING_REQUEST && - typeof limits.kind?.whitelist !== 'undefined' && - limits.kind.whitelist.length > 0 && - !limits.kind.whitelist.some(isEventKindOrRangeMatch(event)) - ) { - return `blocked: event kind ${event.kind} not allowed` - } - - if ( - event.kind !== EventKinds.PEERING_REQUEST && - typeof limits.kind?.blacklist !== 'undefined' && - limits.kind.blacklist.length > 0 && - limits.kind.blacklist.some(isEventKindOrRangeMatch(event)) - ) { - return `blocked: event kind ${event.kind} not allowed` - } + return getEventLimitError(event, this.admissionContext()) } protected isAuthenticationRequired(event: Event): string | undefined { @@ -397,46 +272,11 @@ export class EventMessageHandler implements IMessageHandler { } protected async isEventValid(event: Event): Promise { - if (!(await isEventIdValid(event))) { - return 'invalid: event id does not match' - } - if (!(await isEventSignatureValid(event))) { - return 'invalid: event signature verification failed' - } - - if (event.kind === EventKinds.REQUEST_TO_VANISH && !isRequestToVanishEvent(event, this.settings().info.relay_url)) { - return 'invalid: request to vanish relay tag invalid' - } - - // NIP-17: kind 13 (Seal) and kind 14 (Direct Message) are inner events that - // must never be published directly to a relay. They are encrypted inside a - // kind 1059 Gift Wrap (NIP-59) before being sent here. - // Marmot MIP-02: kind 444 (Welcome rumor) is similarly an inner event that - // must only be delivered inside a kind 1059 gift wrap. - if (isSealEvent(event) || isDirectMessageEvent(event) || isFileMessageEvent(event) || isWelcomeRumorEvent(event)) { - return `blocked: kind ${event.kind} events must not be published directly; wrap them in a kind 1059 gift wrap` - } - - // NIP-42: auth events must use the AUTH message type - if (event.kind === EventKinds.AUTH) { - return 'invalid: auth events must be sent using the AUTH message type' - } + return getEventValidationError(event, this.settings().info.relay_url) } protected async isBlockedByRequestToVanish(event: Event): Promise { - if (isRequestToVanishEvent(event)) { - return - } - - const relayPubkey = this.getRelayPublicKey() - if (relayPubkey === event.pubkey) { - return - } - - const isVanished = await this.userRepository.isVanished(event.pubkey) - if (isVanished) { - return 'blocked: request to vanish active for pubkey' - } + return getRequestToVanishError(event, this.admissionContext()) } /** @@ -602,103 +442,20 @@ export class EventMessageHandler implements IMessageHandler { } protected async isUserAdmitted(event: Event): Promise { - const currentSettings = this.settings() - const paymentsEnabled = currentSettings.payments?.enabled === true - // NIP-43: membership mode gates writes on admission even without payments - const nip43Enabled = currentSettings.nip43?.enabled === true - if (!paymentsEnabled && !nip43Enabled) { - return - } - - if (this.getRelayPublicKey() === event.pubkey) { - return - } - - // NIP-43: join/leave requests must bypass admission — they ARE the admission - // flow. Invite requests bypass it too, not because they are valid to publish - // (they never are) but so InviteRequestEventStrategy can tell the client to - // use a REQ instead. Without this the people most likely to get 28935 wrong — - // non-members trying to obtain a code — are the only ones who never see that - // message. - if ( - event.kind === EventKinds.NIP43_JOIN_REQUEST || - event.kind === EventKinds.NIP43_LEAVE_REQUEST || - event.kind === EventKinds.NIP43_INVITE_REQUEST || - event.kind === EventKinds.PEERING_REQUEST - ) { - return - } - - const isApplicableFee = (feeSchedule: FeeSchedule) => - feeSchedule.enabled && - !feeSchedule.whitelists?.pubkeys?.includes(event.pubkey) && - !feeSchedule.whitelists?.event_kinds?.some(isEventKindOrRangeMatch(event)) - - const feeSchedules = paymentsEnabled - ? currentSettings.payments?.feeSchedules?.admission?.filter(isApplicableFee) - : undefined - // With plans and no admission fee at all, a plan is what admits a user. - const subscriptionsEnabled = areSubscriptionsEnabled(currentSettings) - const onlyPlansAdmit = - subscriptionsEnabled && !currentSettings.payments?.feeSchedules?.admission?.some((schedule) => schedule.enabled) - const admissionFeeRequired = (Array.isArray(feeSchedules) && feeSchedules.length > 0) || onlyPlansAdmit - if (!admissionFeeRequired && !nip43Enabled) { - return - } - - const notAdmittedReason = nip43Enabled - ? 'restricted: pubkey not admitted; send a join request (kind 28934) with a valid invite code' - : 'blocked: pubkey not admitted' - - const cacheKey = admissionCacheKey(event.pubkey) - - try { - const cachedValue = await this.cache.getKey(cacheKey) - if (cachedValue === CacheAdmissionState.ADMITTED) { - logger('cache hit for %s admission: admitted', event.pubkey) - return - } - if (cachedValue === CacheAdmissionState.BLOCKED_NOT_ADMITTED) { - logger('cache hit for %s admission: blocked', event.pubkey) - return notAdmittedReason - } - if (cachedValue === CacheAdmissionState.BLOCKED_INSUFFICIENT_BALANCE) { - logger('cache hit for %s admission: insufficient balance', event.pubkey) - return 'blocked: insufficient balance' - } - } catch (error) { - logger('cache error for %s: %o', event.pubkey, error) - } - - const user = await this.userRepository.findByPubkey(event.pubkey) - if (!user || !user.isAdmitted) { - this.cacheSet(cacheKey, CacheAdmissionState.BLOCKED_NOT_ADMITTED, 60) - return notAdmittedReason - } - - const minBalance = paymentsEnabled ? (currentSettings.limits?.event?.pubkey?.minBalance ?? 0n) : 0n - if (minBalance > 0n && user.balance < minBalance) { - this.cacheSet(cacheKey, CacheAdmissionState.BLOCKED_INSUFFICIENT_BALANCE, 60) - return 'blocked: insufficient balance' - } - - let admittedTtl = 300 - if (subscriptionsEnabled && this.userSubscriptionRepository) { - const subscription = await this.readSubscription(event) - const now = new Date() - if (!hasSubscriptionAccess(subscription, now)) { - this.cacheSet(cacheKey, CacheAdmissionState.BLOCKED_NOT_ADMITTED, 60) - return 'blocked: subscription expired' - } + return getUserAdmissionError(event, this.admissionContext()) + } - // Cache no longer than access lasts, so the block lands when the period ends rather than minutes later. - const accessEndsAt = subscription ? getAccessEndsAt(subscription) : undefined - admittedTtl = this.cacheTtlUntil(admittedTtl, accessEndsAt, now) - // The plan was just read, so what the rate limits need is cached with it. - this.cacheSubscriptionPlan(event.pubkey, subscription?.planId, accessEndsAt, now) + private admissionContext(): EventAdmissionContext { + return { + settings: this.settings, + relayPubkey: () => this.getRelayPublicKey(), + userRepository: this.userRepository, + nip05VerificationRepository: this.nip05VerificationRepository, + cache: this.cache, + wotGraphService: this.wotGraphService, + userSubscriptionRepository: this.userSubscriptionRepository, + readSubscription: (event) => this.readSubscription(event), } - - this.cacheSet(cacheKey, CacheAdmissionState.ADMITTED, admittedTtl) } private cacheSet(key: string, value: string, ttl: number): void { @@ -720,57 +477,7 @@ export class EventMessageHandler implements IMessageHandler { } protected async checkNip05Verification(event: Event): Promise { - const nip05Settings = this.settings().nip05 - if (!nip05Settings || nip05Settings.mode !== 'enabled') { - return - } - - if (this.getRelayPublicKey() === event.pubkey) { - return - } - - // NIP-43: join/leave requests bypass NIP-05 — a new user won't have a - // verification record yet, and requiring one would block the join flow. - if ( - event.kind === EventKinds.NIP43_JOIN_REQUEST || - event.kind === EventKinds.NIP43_LEAVE_REQUEST || - event.kind === EventKinds.PEERING_REQUEST - ) { - return - } - - if (event.kind === EventKinds.SET_METADATA) { - return - } - - const verification = await this.nip05VerificationRepository.findByPubkey(event.pubkey) - - if (!verification) { - return 'blocked: NIP-05 verification required' - } - - if (!isDomainAllowed(verification.domain, nip05Settings.domainWhitelist, nip05Settings.domainBlacklist)) { - return 'blocked: NIP-05 domain not allowed' - } - - // `lastVerifiedAt` is the single source of truth for "currently allowed". - // A transient network error during background re-verification leaves this - // value intact, so a verified author keeps publishing until the configured - // expiration elapses. Only a definitive mismatch (handled in the maintenance - // worker / processNip05Metadata) nulls this field and blocks the author. - // - // Historical rows could theoretically have `isVerified=true` with a null - // `lastVerifiedAt`; treat that as "needs re-verification" rather than - // "verified forever". - if (!verification.lastVerifiedAt) { - return 'blocked: NIP-05 verification required' - } - - const expirationMs = nip05Settings.verifyExpiration ?? DEFAULT_NIP05_VERIFY_EXPIRATION_MS - const elapsed = Date.now() - verification.lastVerifiedAt.getTime() - if (elapsed > expirationMs) { - return 'blocked: NIP-05 verification expired' - } + return getNip05VerificationError(event, this.admissionContext()) } /** @@ -783,7 +490,7 @@ export class EventMessageHandler implements IMessageHandler { const nip05Settings = this.settings().nip05 if (event.kind === EventKinds.SET_METADATA && nip05Settings && nip05Settings.mode !== 'disabled') { try { - if (await this.isSupersededProfile(event)) { + if (await isSupersededProfile(event, this.eventRepository)) { logger('kind-0 %s from %s was replaced by a newer profile, NIP-05 left as is', event.id, event.pubkey) return } @@ -796,133 +503,16 @@ export class EventMessageHandler implements IMessageHandler { this.processNip05Metadata(event) } - // Mirrors which of two kind-0 events the replaceable upsert keeps: the later created_at, and for equal - // created_at the lower id. The stored profile is read the way the upsert sees it, so a profile that - // subscriptions hide (a NIP-56 report, a soft delete) still holds the slot. A stored profile that is not - // newer does not count as superseding. - private async isSupersededProfile(event: Event): Promise { - const [stored] = await this.eventRepository.findStoredReplaceable(event.pubkey, EventKinds.SET_METADATA) - if (!stored) { - return false - } - - const storedId = stored.event_id.toString('hex') - return ( - stored.event_created_at > event.created_at || - (stored.event_created_at === event.created_at && storedId < event.id) - ) - } - protected processNip05Metadata(event: Event): void { - const nip05Settings = this.settings().nip05 - if (!nip05Settings || nip05Settings.mode === 'disabled') { - return - } - - if (event.kind !== EventKinds.SET_METADATA) { - return - } - - const nip05Identifier = extractNip05FromEvent(event) - if (!nip05Identifier) { - this.nip05VerificationRepository.deleteByPubkey(event.pubkey).catch((error) => { - logger('failed to remove NIP-05 verification for %s: %o', event.pubkey, error) - }) - return - } - - const parsed = parseNip05Identifier(nip05Identifier) - if (!parsed) { - return - } - - if (!isDomainAllowed(parsed.domain, nip05Settings.domainWhitelist, nip05Settings.domainBlacklist)) { - logger('NIP-05 domain %s not allowed for %s', parsed.domain, event.pubkey) - return - } - - const repo = this.nip05VerificationRepository - Promise.all([repo.findByPubkey(event.pubkey), verifyNip05Identifier(nip05Identifier, event.pubkey)]) - .then(([existing, outcome]) => { - const verification = buildMetadataVerification(event.pubkey, nip05Identifier, parsed.domain, existing, outcome) - return repo.upsert(verification) - }) - .catch((error) => { - logger('NIP-05 verification failed for %s: %o', event.pubkey, error) - }) + processNip05Metadata(event, this.nip05MetadataContext()) } -} -/** - * Build the row to upsert after a kind-0 verification attempt. - * - * - `verified` resets failureCount and refreshes lastVerifiedAt. - * - `mismatch` / `invalid` are definitive: flip to unverified, null out - * lastVerifiedAt (the author is no longer the domain's owner), and bump - * failureCount relative to any prior row. - * - `error` is transient: keep the prior isVerified/lastVerifiedAt so - * previously-verified authors aren't blocked by a single network hiccup, but - * only when the identifier is the one that was verified. A changed identifier - * (or domain) has not been proven yet, so it starts unverified instead of - * inheriting the earlier identity's verification. failureCount and - * lastCheckedAt are bumped either way so the re-verification backoff can - * take effect. - */ -function buildMetadataVerification( - pubkey: string, - nip05: string, - domain: string, - existing: Nip05Verification | undefined, - outcome: Nip05VerificationOutcome, -): Nip05Verification { - const now = new Date() - const priorFailureCount = existing?.failureCount ?? 0 - const createdAt = existing?.createdAt ?? now - - switch (outcome.status) { - case 'verified': - return { - pubkey, - nip05, - domain, - isVerified: true, - lastVerifiedAt: now, - lastCheckedAt: now, - failureCount: 0, - createdAt, - updatedAt: now, - } - case 'mismatch': - case 'invalid': - return { - pubkey, - nip05, - domain, - isVerified: false, - lastVerifiedAt: null, - lastCheckedAt: now, - failureCount: priorFailureCount + 1, - createdAt, - updatedAt: now, - } - case 'error': - default: { - const sameIdentity = - existing !== undefined && - existing.nip05.toLowerCase() === nip05.toLowerCase() && - existing.domain.toLowerCase() === domain.toLowerCase() - - return { - pubkey, - nip05, - domain, - isVerified: sameIdentity ? existing.isVerified : false, - lastVerifiedAt: sameIdentity ? existing.lastVerifiedAt : null, - lastCheckedAt: now, - failureCount: priorFailureCount + 1, - createdAt, - updatedAt: now, - } + private nip05MetadataContext(): Nip05MetadataContext { + return { + settings: this.settings, + eventRepository: this.eventRepository, + nip05VerificationRepository: this.nip05VerificationRepository, } } } + diff --git a/src/utils/event-admission.ts b/src/utils/event-admission.ts new file mode 100644 index 000000000..e5c42e830 --- /dev/null +++ b/src/utils/event-admission.ts @@ -0,0 +1,444 @@ +import { ICacheAdapter } from '../@types/adapters' +import { Event } from '../@types/event' +import { INip05VerificationRepository, IUserRepository, IUserSubscriptionRepository } from '../@types/repositories' +import { IWotGraphService } from '../@types/services' +import { FeeSchedule, Settings } from '../@types/settings' +import { UserSubscription } from '../@types/user-subscription' +import { EventKinds } from '../constants/base' +import { + admissionCacheKey, + CacheAdmissionState, + NO_SUBSCRIPTION_PLAN, + SUBSCRIPTION_PLAN_PREFIX, + subscriptionPlanCacheKey, +} from '../constants/caching' +import { createLogger } from '../factories/logger-factory' +import { getCurrentDifficulty as getAdaptivePowDifficulty } from './adaptive-pow' +import { + getEventProofOfWork, + getPubkeyProofOfWork, + isDirectMessageEvent, + isEventIdValid, + isEventKindOrRangeMatch, + isEventSignatureValid, + isFileMessageEvent, + isRequestToVanishEvent, + isSealEvent, + isWelcomeRumorEvent, +} from './event' +import { + DEFAULT_NIP05_VERIFY_EXPIRATION_MS, + isDomainAllowed, +} from './nip05' +import { + areSubscriptionsEnabled, + getAccessEndsAt, + hasSubscriptionAccess, +} from './subscription' +import { applyWotPowPolicy } from './wot-pow-policy' + +const logger = createLogger('event-admission') + +/** + * The relay's admission policy, independent of the transport that delivered the + * event. The live EVENT path and the peering live-feed path both use it, so a + * configured peer cannot store or fan out what a local client would be refused + * for. + * + * Deliberately excludes checks that only make sense for a client socket: + * rate limiting, AUTH-derived author identity and protected events. Peering + * connections authenticate as a relay, not as each event's author. + */ +export interface EventAdmissionContext { + settings: () => Settings + relayPubkey: () => string + userRepository?: Pick + nip05VerificationRepository?: Pick + cache?: ICacheAdapter + wotGraphService?: Pick + userSubscriptionRepository?: Pick + /** Lets a caller memoize the subscription read it also needs for rate limits. */ + readSubscription?: (event: Event) => Promise +} + +/** The same decision `EventMessageHandler.handleMessage` applies to a local EVENT. */ +export const admitEvent = async (event: Event, context: EventAdmissionContext): Promise => { + const reason = await getEventValidationError(event, context.settings().info.relay_url) + if (reason) { + return reason + } + + return ( + (await getEventLimitError(event, context)) ?? + (await getRequestToVanishError(event, context)) ?? + (await getUserAdmissionError(event, context)) ?? + (await getNip05VerificationError(event, context)) + ) +} + +export const getEventValidationError = async (event: Event, relayUrl: string): Promise => { + if (!(await isEventIdValid(event))) { + return 'invalid: event id does not match' + } + if (!(await isEventSignatureValid(event))) { + return 'invalid: event signature verification failed' + } + + if (event.kind === EventKinds.REQUEST_TO_VANISH && !isRequestToVanishEvent(event, relayUrl)) { + return 'invalid: request to vanish relay tag invalid' + } + + // NIP-17: kind 13 (Seal) and kind 14 (Direct Message) are inner events that + // must never be published directly to a relay. They are encrypted inside a + // kind 1059 Gift Wrap (NIP-59) before being sent here. + // Marmot MIP-02: kind 444 (Welcome rumor) is similarly an inner event that + // must only be delivered inside a kind 1059 gift wrap. + if (isSealEvent(event) || isDirectMessageEvent(event) || isFileMessageEvent(event) || isWelcomeRumorEvent(event)) { + return `blocked: kind ${event.kind} events must not be published directly; wrap them in a kind 1059 gift wrap` + } + + // NIP-42: auth events must use the AUTH message type + if (event.kind === EventKinds.AUTH) { + return 'invalid: auth events must be sent using the AUTH message type' + } +} + +export const getEventLimitError = async ( + event: Event, + context: EventAdmissionContext, +): Promise => { + if (context.relayPubkey() === event.pubkey) { + return + } + const now = Math.floor(Date.now() / 1000) + + const limits = context.settings().limits?.event ?? {} + + if (Array.isArray(limits.content)) { + for (const limit of limits.content) { + if ( + typeof limit.maxLength !== 'undefined' && + limit.maxLength > 0 && + event.content.length > limit.maxLength && + (!Array.isArray(limit.kinds) || limit.kinds.some(isEventKindOrRangeMatch(event))) + ) { + return `rejected: content is longer than ${limit.maxLength} bytes` + } + } + } else if ( + typeof limits.content?.maxLength !== 'undefined' && + limits.content?.maxLength > 0 && + event.content.length > limits.content.maxLength && + (!Array.isArray(limits.content.kinds) || limits.content.kinds.some(isEventKindOrRangeMatch(event))) + ) { + return `rejected: content is longer than ${limits.content.maxLength} bytes` + } + + if ( + typeof limits.createdAt?.maxPositiveDelta !== 'undefined' && + limits.createdAt.maxPositiveDelta > 0 && + event.created_at > now + limits.createdAt.maxPositiveDelta + ) { + return `rejected: created_at is more than ${limits.createdAt.maxPositiveDelta} seconds in the future` + } + + if ( + typeof limits.createdAt?.maxNegativeDelta !== 'undefined' && + limits.createdAt.maxNegativeDelta > 0 && + event.created_at < now - limits.createdAt.maxNegativeDelta + ) { + return `rejected: created_at is more than ${limits.createdAt.maxNegativeDelta} seconds in the past` + } + + // Adaptive PoW applies to the eventId check only: a pubkey requirement is a + // one-time, offline identity cost, not a per-event load signal, so it can't + // respond to relay load the way an event id's mined-per-submission pow can. + // The static pubkey.minLeadingZeroBits knob is left untouched regardless of + // pow.enabled -- per maintainer direction on PR #756. + if (event.kind === EventKinds.PEERING_REQUEST) { + // Peering requests carry their own NIP-13 requirement, checked by the + // strategy after the owner signature and AUTH identity are known. + } else if (limits.pow?.enabled) { + const computedDifficulty = getAdaptivePowDifficulty(limits.pow) + // Only consult the WoT graph when thresholds are actually configured -- + // a distance lookup is unnecessary work otherwise, and skipping it also + // means wot.enabled=false relays never pay for it. + const distance = limits.pow.wotThresholds?.length + ? await context.wotGraphService?.getDistance(event.pubkey) + : undefined + const requiredBits = applyWotPowPolicy(computedDifficulty, distance, limits.pow.wotThresholds) + + const pow = getEventProofOfWork(event.id) + if (pow < requiredBits) { + return `pow: difficulty ${pow}<${requiredBits}` + } + } else if (typeof limits.eventId?.minLeadingZeroBits !== 'undefined' && limits.eventId.minLeadingZeroBits > 0) { + const pow = getEventProofOfWork(event.id) + if (pow < limits.eventId.minLeadingZeroBits) { + return `pow: difficulty ${pow}<${limits.eventId.minLeadingZeroBits}` + } + } + + if ( + event.kind !== EventKinds.PEERING_REQUEST && + typeof limits.pubkey?.minLeadingZeroBits !== 'undefined' && + limits.pubkey.minLeadingZeroBits > 0 + ) { + const pow = getPubkeyProofOfWork(event.pubkey) + if (pow < limits.pubkey.minLeadingZeroBits) { + return `pow: pubkey difficulty ${pow}<${limits.pubkey.minLeadingZeroBits}` + } + } + + if ( + event.kind !== EventKinds.PEERING_REQUEST && + typeof limits.pubkey?.whitelist !== 'undefined' && + limits.pubkey.whitelist.length > 0 && + !limits.pubkey.whitelist.includes(event.pubkey) + ) { + return 'blocked: pubkey not allowed' + } + + if ( + typeof limits.pubkey?.blacklist !== 'undefined' && + limits.pubkey.blacklist.length > 0 && + limits.pubkey.blacklist.includes(event.pubkey) + ) { + return 'blocked: pubkey not allowed' + } + + if ( + event.kind !== EventKinds.PEERING_REQUEST && + typeof limits.kind?.whitelist !== 'undefined' && + limits.kind.whitelist.length > 0 && + !limits.kind.whitelist.some(isEventKindOrRangeMatch(event)) + ) { + return `blocked: event kind ${event.kind} not allowed` + } + + if ( + event.kind !== EventKinds.PEERING_REQUEST && + typeof limits.kind?.blacklist !== 'undefined' && + limits.kind.blacklist.length > 0 && + limits.kind.blacklist.some(isEventKindOrRangeMatch(event)) + ) { + return `blocked: event kind ${event.kind} not allowed` + } +} + +export const getRequestToVanishError = async ( + event: Event, + context: EventAdmissionContext, +): Promise => { + if (isRequestToVanishEvent(event)) { + return + } + + if (context.relayPubkey() === event.pubkey) { + return + } + + const isVanished = await context.userRepository?.isVanished(event.pubkey) + if (isVanished) { + return 'blocked: request to vanish active for pubkey' + } +} + +export const getUserAdmissionError = async ( + event: Event, + context: EventAdmissionContext, +): Promise => { + const currentSettings = context.settings() + const paymentsEnabled = currentSettings.payments?.enabled === true + // NIP-43: membership mode gates writes on admission even without payments + const nip43Enabled = currentSettings.nip43?.enabled === true + if (!paymentsEnabled && !nip43Enabled) { + return + } + + if (context.relayPubkey() === event.pubkey) { + return + } + + // NIP-43: join/leave requests must bypass admission — they ARE the admission + // flow. Invite requests bypass it too, not because they are valid to publish + // (they never are) but so InviteRequestEventStrategy can tell the client to + // use a REQ instead. Without this the people most likely to get 28935 wrong — + // non-members trying to obtain a code — are the only ones who never see that + // message. + if ( + event.kind === EventKinds.NIP43_JOIN_REQUEST || + event.kind === EventKinds.NIP43_LEAVE_REQUEST || + event.kind === EventKinds.NIP43_INVITE_REQUEST || + event.kind === EventKinds.PEERING_REQUEST + ) { + return + } + + const userRepository = context.userRepository + if (!userRepository) { + // Admission is configured but the peering worker cannot read users. Fail + // closed rather than letting the feed bypass the policy. + return 'blocked: pubkey not admitted' + } + + const isApplicableFee = (feeSchedule: FeeSchedule) => + feeSchedule.enabled && + !feeSchedule.whitelists?.pubkeys?.includes(event.pubkey) && + !feeSchedule.whitelists?.event_kinds?.some(isEventKindOrRangeMatch(event)) + + const feeSchedules = paymentsEnabled + ? currentSettings.payments?.feeSchedules?.admission?.filter(isApplicableFee) + : undefined + // With plans and no admission fee at all, a plan is what admits a user. + const subscriptionsEnabled = areSubscriptionsEnabled(currentSettings) + const onlyPlansAdmit = + subscriptionsEnabled && !currentSettings.payments?.feeSchedules?.admission?.some((schedule) => schedule.enabled) + const admissionFeeRequired = (Array.isArray(feeSchedules) && feeSchedules.length > 0) || onlyPlansAdmit + if (!admissionFeeRequired && !nip43Enabled) { + return + } + + const notAdmittedReason = nip43Enabled + ? 'restricted: pubkey not admitted; send a join request (kind 28934) with a valid invite code' + : 'blocked: pubkey not admitted' + + const cacheKey = admissionCacheKey(event.pubkey) + + try { + const cachedValue = await context.cache?.getKey(cacheKey) + if (cachedValue === CacheAdmissionState.ADMITTED) { + logger('cache hit for %s admission: admitted', event.pubkey) + return + } + if (cachedValue === CacheAdmissionState.BLOCKED_NOT_ADMITTED) { + logger('cache hit for %s admission: blocked', event.pubkey) + return notAdmittedReason + } + if (cachedValue === CacheAdmissionState.BLOCKED_INSUFFICIENT_BALANCE) { + logger('cache hit for %s admission: insufficient balance', event.pubkey) + return 'blocked: insufficient balance' + } + } catch (error) { + logger('cache error for %s: %o', event.pubkey, error) + } + + const user = await userRepository.findByPubkey(event.pubkey) + if (!user || !user.isAdmitted) { + cacheSet(context.cache, cacheKey, CacheAdmissionState.BLOCKED_NOT_ADMITTED, 60) + return notAdmittedReason + } + + const minBalance = paymentsEnabled ? (currentSettings.limits?.event?.pubkey?.minBalance ?? 0n) : 0n + if (minBalance > 0n && user.balance < minBalance) { + cacheSet(context.cache, cacheKey, CacheAdmissionState.BLOCKED_INSUFFICIENT_BALANCE, 60) + return 'blocked: insufficient balance' + } + + let admittedTtl = 300 + if (subscriptionsEnabled && context.userSubscriptionRepository) { + const subscription = await readSubscription(event, context) + const now = new Date() + if (!hasSubscriptionAccess(subscription, now)) { + cacheSet(context.cache, cacheKey, CacheAdmissionState.BLOCKED_NOT_ADMITTED, 60) + return 'blocked: subscription expired' + } + + // Cache no longer than access lasts, so the block lands when the period ends rather than minutes later. + const accessEndsAt = subscription ? getAccessEndsAt(subscription) : undefined + admittedTtl = cacheTtlUntil(admittedTtl, accessEndsAt, now) + // The plan was just read, so what the rate limits need is cached with it. + cacheSubscriptionPlan(context.cache, event.pubkey, subscription?.planId, accessEndsAt, now) + } + + cacheSet(context.cache, cacheKey, CacheAdmissionState.ADMITTED, admittedTtl) +} + +export const getNip05VerificationError = async ( + event: Event, + context: EventAdmissionContext, +): Promise => { + const nip05Settings = context.settings().nip05 + if (!nip05Settings || nip05Settings.mode !== 'enabled') { + return + } + + if (context.relayPubkey() === event.pubkey) { + return + } + + // NIP-43: join/leave requests bypass NIP-05 — a new user won't have a + // verification record yet, and requiring one would block the join flow. + if ( + event.kind === EventKinds.NIP43_JOIN_REQUEST || + event.kind === EventKinds.NIP43_LEAVE_REQUEST || + event.kind === EventKinds.PEERING_REQUEST + ) { + return + } + + if (event.kind === EventKinds.SET_METADATA) { + return + } + + const verification = await context.nip05VerificationRepository?.findByPubkey(event.pubkey) + if (!verification) { + return 'blocked: NIP-05 verification required' + } + + if (!isDomainAllowed(verification.domain, nip05Settings.domainWhitelist, nip05Settings.domainBlacklist)) { + return 'blocked: NIP-05 domain not allowed' + } + + // `lastVerifiedAt` is the single source of truth for "currently allowed". + // A transient network error during background re-verification leaves this + // value intact, so a verified author keeps publishing until the configured + // expiration elapses. Only a definitive mismatch (handled in the maintenance + // worker / processNip05Metadata) nulls this field and blocks the author. + // + // Historical rows could theoretically have `isVerified=true` with a null + // `lastVerifiedAt`; treat that as "needs re-verification" rather than + // "verified forever". + if (!verification.lastVerifiedAt) { + return 'blocked: NIP-05 verification required' + } + + const expirationMs = nip05Settings.verifyExpiration ?? DEFAULT_NIP05_VERIFY_EXPIRATION_MS + const elapsed = Date.now() - verification.lastVerifiedAt.getTime() + if (elapsed > expirationMs) { + return 'blocked: NIP-05 verification expired' + } +} + +/** No longer than access lasts, so a plan's limits end when its period does rather than minutes later. */ +const cacheTtlUntil = (ttl: number, accessEndsAt: Date | undefined, now: Date): number => { + if (!accessEndsAt) { + return ttl + } + + return Math.max(1, Math.min(ttl, Math.ceil((accessEndsAt.getTime() - now.getTime()) / 1000))) +} + +const readSubscription = (event: Event, context: EventAdmissionContext): Promise => { + if (context.readSubscription) { + return context.readSubscription(event) + } + + return context.userSubscriptionRepository?.findByPubkey(event.pubkey) ?? Promise.resolve(undefined) +} + +const cacheSet = (cache: ICacheAdapter | undefined, key: string, value: string, ttl: number): void => { + cache?.setKey(key, value, ttl).catch((error) => logger('unable to cache %s: %o', key, error)) +} + +const cacheSubscriptionPlan = ( + cache: ICacheAdapter | undefined, + pubkey: string, + planId: string | undefined, + accessEndsAt: Date | undefined, + now: Date, +): void => { + // Only a plan that is being cached ends with access; "no plan" is rechecked after a minute whatever the end was. + const ttl = planId ? cacheTtlUntil(300, accessEndsAt, now) : 60 + cacheSet(cache, subscriptionPlanCacheKey(pubkey), planId ? `${SUBSCRIPTION_PLAN_PREFIX}${planId}` : NO_SUBSCRIPTION_PLAN, ttl) +} diff --git a/src/utils/nip05-metadata.ts b/src/utils/nip05-metadata.ts new file mode 100644 index 000000000..9f9797eef --- /dev/null +++ b/src/utils/nip05-metadata.ts @@ -0,0 +1,192 @@ +import { Event } from '../@types/event' +import { Nip05Verification } from '../@types/nip05' +import { IEventRepository, INip05VerificationRepository } from '../@types/repositories' +import { Settings } from '../@types/settings' +import { EventKinds } from '../constants/base' +import { createLogger } from '../factories/logger-factory' +import { + extractNip05FromEvent, + isDomainAllowed, + Nip05VerificationOutcome, + parseNip05Identifier, + verifyNip05Identifier, +} from './nip05' + +const logger = createLogger('nip05-metadata') + +export interface Nip05MetadataContext { + settings: () => Settings + eventRepository?: Pick + nip05VerificationRepository?: Pick +} + +/** + * Mirrors which of two kind-0 events the replaceable upsert keeps: the later + * created_at, and for equal created_at the lower id. The stored profile is read + * the way the upsert sees it, so a profile that subscriptions hide (a NIP-56 + * report, a soft delete) still holds the slot. A stored profile that is not + * newer does not count as superseding. + */ +export const isSupersededProfile = async ( + event: Event, + eventRepository: Pick, +): Promise => { + const [stored] = await eventRepository.findStoredReplaceable(event.pubkey, EventKinds.SET_METADATA) + if (!stored) { + return false + } + + const storedId = stored.event_id.toString('hex') + return ( + stored.event_created_at > event.created_at || + (stored.event_created_at === event.created_at && storedId < event.id) + ) +} + +/** + * A kind-0 profile the relay already replaced with a newer one is still + * accepted by the replaceable-event strategy (the write is a no-op and the + * client gets `duplicate:`), but it must not change the author's NIP-05 state: + * replaying someone's older signed profile would otherwise delete or swap the + * verification that belongs to their current profile. Only a profile that is + * the author's current one is processed. + */ +export const processNip05MetadataIfCurrent = async ( + event: Event, + context: Nip05MetadataContext, +): Promise => { + const nip05Settings = context.settings().nip05 + if (event.kind === EventKinds.SET_METADATA && nip05Settings && nip05Settings.mode !== 'disabled') { + if (context.eventRepository) { + try { + if (await isSupersededProfile(event, context.eventRepository)) { + logger('kind-0 %s from %s was replaced by a newer profile, NIP-05 left as is', event.id, event.pubkey) + return + } + } catch (error) { + // Not being able to tell is not a reason to skip a genuine profile update. + logger('unable to check whether kind-0 %s is the current profile: %o', event.id, error) + } + } + } + + processNip05Metadata(event, context) +} + +/** Verify a kind-0 profile's NIP-05 identifier in the background and upsert the result. */ +export const processNip05Metadata = (event: Event, context: Nip05MetadataContext): void => { + const nip05Settings = context.settings().nip05 + if (!nip05Settings || nip05Settings.mode === 'disabled') { + return + } + + if (event.kind !== EventKinds.SET_METADATA) { + return + } + + const repo = context.nip05VerificationRepository + if (!repo) { + return + } + + const nip05Identifier = extractNip05FromEvent(event) + if (!nip05Identifier) { + repo.deleteByPubkey(event.pubkey).catch((error) => { + logger('failed to remove NIP-05 verification for %s: %o', event.pubkey, error) + }) + return + } + + const parsed = parseNip05Identifier(nip05Identifier) + if (!parsed) { + return + } + + if (!isDomainAllowed(parsed.domain, nip05Settings.domainWhitelist, nip05Settings.domainBlacklist)) { + logger('NIP-05 domain %s not allowed for %s', parsed.domain, event.pubkey) + return + } + + Promise.all([repo.findByPubkey(event.pubkey), verifyNip05Identifier(nip05Identifier, event.pubkey)]) + .then(([existing, outcome]) => { + const verification = buildMetadataVerification(event.pubkey, nip05Identifier, parsed.domain, existing, outcome) + return repo.upsert(verification) + }) + .catch((error) => { + logger('NIP-05 verification failed for %s: %o', event.pubkey, error) + }) +} + +/** + * Build the row to upsert after a kind-0 verification attempt. + * + * - `verified` resets failureCount and refreshes lastVerifiedAt. + * - `mismatch` / `invalid` are definitive: flip to unverified, null out + * lastVerifiedAt (the author is no longer the domain's owner), and bump + * failureCount relative to any prior row. + * - `error` is transient: keep the prior isVerified/lastVerifiedAt so + * previously-verified authors aren't blocked by a single network hiccup, but + * only when the identifier is the one that was verified. A changed identifier + * (or domain) has not been proven yet, so it starts unverified instead of + * inheriting the earlier identity's verification. failureCount and + * lastCheckedAt are bumped either way so the re-verification backoff can + * take effect. + */ +export const buildMetadataVerification = ( + pubkey: string, + nip05: string, + domain: string, + existing: Nip05Verification | undefined, + outcome: Nip05VerificationOutcome, +): Nip05Verification => { + const now = new Date() + const priorFailureCount = existing?.failureCount ?? 0 + const createdAt = existing?.createdAt ?? now + + switch (outcome.status) { + case 'verified': + return { + pubkey, + nip05, + domain, + isVerified: true, + lastVerifiedAt: now, + lastCheckedAt: now, + failureCount: 0, + createdAt, + updatedAt: now, + } + case 'mismatch': + case 'invalid': + return { + pubkey, + nip05, + domain, + isVerified: false, + lastVerifiedAt: null, + lastCheckedAt: now, + failureCount: priorFailureCount + 1, + createdAt, + updatedAt: now, + } + case 'error': + default: { + const sameIdentity = + existing !== undefined && + existing.nip05.toLowerCase() === nip05.toLowerCase() && + existing.domain.toLowerCase() === domain.toLowerCase() + + return { + pubkey, + nip05, + domain, + isVerified: sameIdentity ? existing.isVerified : false, + lastVerifiedAt: sameIdentity ? existing.lastVerifiedAt : null, + lastCheckedAt: now, + failureCount: priorFailureCount + 1, + createdAt, + updatedAt: now, + } + } + } +} diff --git a/test/unit/app/peering-sync-worker.spec.ts b/test/unit/app/peering-sync-worker.spec.ts index 455d5ef5c..d087e7a73 100644 --- a/test/unit/app/peering-sync-worker.spec.ts +++ b/test/unit/app/peering-sync-worker.spec.ts @@ -223,9 +223,15 @@ describe('PeeringSyncWorker', () => { stateHeartbeatMs?: number configureConnection?: (connection: FakeConnection) => void userRepository?: { + findByPubkey: (pubkey: string) => Promise isVanished: (pubkey: string) => Promise setVanished: (pubkey: string) => Promise } + nip05VerificationRepository?: { + findByPubkey: (pubkey: string) => Promise + upsert: (verification: any) => Promise + deleteByPubkey: (pubkey: string) => Promise + } } const startWorker = (remoteEvents: Event[], options: StartWorkerOptions = {}): void => { @@ -249,6 +255,7 @@ describe('PeeringSyncWorker', () => { stateHeartbeatMs: options.stateHeartbeatMs, reconnectDelayMs: 10, userRepository: options.userRepository, + nip05VerificationRepository: options.nip05VerificationRepository as any, buyerService: options.buyerService as any, }) @@ -459,6 +466,104 @@ describe('PeeringSyncWorker', () => { expect(localEvents[0].id).to.equal(fresh.id) }) + it('refuses a live peering event that the local admission policy rejects', async () => { + settingsState = { + ...settingsState, + limits: { event: { content: { maxLength: 10 } } }, + } as Settings + + startWorker([]) + await waitFor(() => connection.liveOnEvent !== undefined) + + const rejected = await makeEvent('this content is far too long', Math.floor(Date.now() / 1000)) + const accepted = await makeEvent('short', Math.floor(Date.now() / 1000)) + + connection.liveOnEvent?.(rejected) + connection.liveOnEvent?.(accepted) + + await waitFor(() => localEvents.some((event) => event.id === accepted.id)) + expect(localEvents.some((event) => event.id === rejected.id)).to.equal(false) + }) + + it('stores a live peering event that is within the admission limits', async () => { + settingsState = { + ...settingsState, + limits: { event: { content: { maxLength: 64 } } }, + } as Settings + + startWorker([]) + await waitFor(() => connection.liveOnEvent !== undefined) + + const event = await makeEvent('within limits', Math.floor(Date.now() / 1000)) + connection.liveOnEvent?.(event) + + await waitFor(() => localEvents.some((local) => local.id === event.id)) + expect(localEvents).to.have.length(1) + }) + + it('forwards NIP-05 verification to the sessions that admit live events', async () => { + settingsState = { + ...settingsState, + nip05: { mode: 'enabled', verifyExpiration: 86_400_000, domainWhitelist: [], domainBlacklist: [] }, + } as Settings + + startWorker([], { + nip05VerificationRepository: { + findByPubkey: async () => ({ + pubkey, + nip05: 'author@example.com', + domain: 'example.com', + isVerified: true, + lastVerifiedAt: new Date(), + }), + upsert: async () => 1, + deleteByPubkey: async () => 0, + }, + }) + + await waitFor(() => connection.liveOnEvent !== undefined) + + const event = await makeEvent('allowed by NIP-05', Math.floor(Date.now() / 1000)) + connection.liveOnEvent?.(event) + + await waitFor(() => localEvents.some((local) => local.id === event.id)) + }) + + it('re-verifies NIP-05 metadata for a live peer profile', async () => { + settingsState = { + ...settingsState, + nip05: { mode: 'enabled', verifyExpiration: 86_400_000, domainWhitelist: [], domainBlacklist: [] }, + } as Settings + + const removed: string[] = [] + startWorker([], { + scopes: [{ kinds: [0, 1] }], + nip05VerificationRepository: { + findByPubkey: async () => undefined, + upsert: async () => 1, + deleteByPubkey: async (pubkey) => { + removed.push(pubkey) + return 1 + }, + }, + }) + + await waitFor(() => connection.liveOnEvent !== undefined) + + const profile = await signEvent(privateKey)( + await identifyEvent({ + pubkey, + created_at: Math.floor(Date.now() / 1000), + kind: 0, + tags: [], + content: '{}', + }), + ) + connection.liveOnEvent?.(profile) + + await waitFor(() => removed.includes(pubkey)) + }) + it('stops a session when its peer is disabled in reloaded settings', async () => { startWorker([], { peerRefreshMs: 20 }) await waitFor(() => connection.liveOnEvent !== undefined) @@ -478,6 +583,7 @@ describe('PeeringSyncWorker', () => { const event = await makeEvent('from vanished author', now) startWorker([event], { userRepository: { + findByPubkey: async () => undefined, isVanished: async () => true, setVanished: async () => 1, },