|
| 1 | +import { createCommandResult } from '../../utils/messages' |
| 2 | +import { createLogger } from '../../factories/logger-factory' |
| 3 | +import { Event } from '../../@types/event' |
| 4 | +import { EventTags } from '../../constants/base' |
| 5 | +import { IEventRepository } from '../../@types/repositories' |
| 6 | +import { IEventStrategy } from '../../@types/message-handlers' |
| 7 | +import { IWebSocketAdapter } from '../../@types/adapters' |
| 8 | +import { WebSocketAdapterEvent } from '../../constants/adapter' |
| 9 | + |
| 10 | +const logger = createLogger('group-event-strategy') |
| 11 | + |
| 12 | +export class GroupEventStrategy implements IEventStrategy<Event, Promise<void>> { |
| 13 | + public constructor( |
| 14 | + private readonly webSocket: IWebSocketAdapter, |
| 15 | + private readonly eventRepository: IEventRepository, |
| 16 | + ) {} |
| 17 | + |
| 18 | + public async execute(event: Event): Promise<void> { |
| 19 | + logger('received group event: %o', event) |
| 20 | + |
| 21 | + const reason = this.validateGroupEvent(event) |
| 22 | + if (reason) { |
| 23 | + this.webSocket.emit(WebSocketAdapterEvent.Message, createCommandResult(event.id, false, `invalid: ${reason}`)) |
| 24 | + return |
| 25 | + } |
| 26 | + |
| 27 | + const count = await this.eventRepository.create(event) |
| 28 | + this.webSocket.emit(WebSocketAdapterEvent.Message, createCommandResult(event.id, true, count ? '' : 'duplicate:')) |
| 29 | + |
| 30 | + if (count) { |
| 31 | + this.webSocket.emit(WebSocketAdapterEvent.Broadcast, event) |
| 32 | + } |
| 33 | + } |
| 34 | + |
| 35 | + // MIP-03: kind:445 Group Events MUST carry exactly one `h` tag whose value is the |
| 36 | + // 64-character lowercase hex-encoded nostr_group_id from the Marmot Group Data Extension. |
| 37 | + // The relay enforces this so that #h tag subscriptions always work correctly. |
| 38 | + private validateGroupEvent(event: Event): string | undefined { |
| 39 | + const groupTags = event.tags.filter((tag) => tag.length >= 2 && tag[0] === EventTags.Group) |
| 40 | + |
| 41 | + if (groupTags.length === 0) { |
| 42 | + return 'group event (kind 445) must have an h tag identifying the group' |
| 43 | + } |
| 44 | + |
| 45 | + if (groupTags.length > 1) { |
| 46 | + return 'group event (kind 445) must have exactly one h tag' |
| 47 | + } |
| 48 | + |
| 49 | + const groupId = groupTags[0][1] |
| 50 | + if (!/^[0-9a-f]{64}$/.test(groupId)) { |
| 51 | + return 'group event (kind 445) h tag must contain a valid 64-character lowercase hex group id' |
| 52 | + } |
| 53 | + |
| 54 | + return undefined |
| 55 | + } |
| 56 | +} |
0 commit comments