Skip to content

Guest Broadcasts & Messaging ​

This specification documents the architecture, provider adapters, audience resolution rules, scheduling lifecycle, and template sanitization controls for outbound guest email and SMS broadcasts in src/features/broadcast/.

Operational Note — Default smtp Host Requirement vs. none Simulation Mode

Out of the box, AppConfig defaults to emailProvider = "smtp" and smsProvider = "none". In MultiChannelMessagingProvider (src/features/broadcast/providers/index.ts):

  • emailProvider = "smtp" (sendSmtpEmail at src/features/broadcast/providers/index.ts): Connects over node:net / node:tls with strict server certificate verification (rejectUnauthorized: true), enforcing implicit TLS on port 465 (smtpSecure: true) and mandatory STARTTLS upgrade on ports 25, 587, and 2525 before AUTH PLAIN, AUTH LOGIN, or MAIL FROM (with SSRF host resolution via validateAndResolveHost and a 10-second socket timeout), and returns { success: false } when smtpHost is blank. testConnection (src/features/broadcast/providers/index.ts) executes a live 220 greeting, EHLO/HELO, mandatory STARTTLS (when smtpSecure is false), AUTH, and QUIT handshake with rejectUnauthorized: true.
  • emailProvider = "none" (sendEmail at src/features/broadcast/providers/index.ts) and smsProvider = "none" (sendSms at src/features/broadcast/providers/index.ts): Explicitly simulate delivery and return { success: true } without performing network delivery.

When simulation mode (none) is enabled, BroadcastService.executeDispatch (src/features/broadcast/service.ts) and BroadcastService.retryFailedRecipients (src/features/broadcast/service.ts) record BroadcastRecipient rows as SENT and mark the parent BroadcastMessage SENT without external network traffic. Production operators must configure a valid smtpHost (for smtp), resend, or sendgrid for live email delivery and twilio for live SMS delivery.


Architecture & API Endpoints ​

The broadcast domain (src/features/broadcast/, public barrel src/features/broadcast/index.ts) exposes BroadcastService (src/features/broadcast/service.ts), Zod request schemas (src/features/broadcast/schemas.ts), audience filtering helpers (src/features/broadcast/audience.ts), and template & stationery card rendering utilities (src/features/broadcast/template.ts).

EndpointMethodAccess TierResponsibility
/api/admin/broadcast/previewPOSTAdmin-onlyValidates PreviewBroadcastSchema and calls BroadcastService.renderPreview (src/features/broadcast/service.ts) to compute matching recipient counts and render a sample guest message (including htmlBody stationery cards) without persisting or dispatching.
/api/admin/broadcast/test-connectionPOSTAdmin-onlyValidates TestConnectionSchema and invokes MultiChannelMessagingProvider.testConnection (src/features/broadcast/providers/index.ts) against live or unsaved admin credential overrides.
/api/admin/broadcast/test-sendPOSTAdmin-onlyValidates SendTestBroadcastSchema (src/features/broadcast/schemas.ts) and executes BroadcastService.sendTestBroadcast (src/features/broadcast/service.ts) to send a [TEST] email or SMS to an optional destination override (validated as an email address for EMAIL or E.164 phone number for SMS, falling back to AppConfig.contactEmail or AppConfig.twilioFromNumber) without creating BroadcastMessage rows.
/api/admin/broadcast/sendPOSTAdmin-onlyValidates strict SendBroadcastSchema (src/features/broadcast/schemas.ts, rejecting unrecognized keys such as legacy scheduledAt with HTTP 400) and invokes BroadcastService.sendBroadcast (src/features/broadcast/service.ts) for immediate batched dispatch or future scheduling via scheduledFor.
/api/admin/broadcast/historyGETAdmin-onlyCalls BroadcastService.getBroadcastHistory and BroadcastService.countBroadcastHistory (src/features/broadcast/service.ts) to return bounded BroadcastMessage summary rows (limit default 50, capped at 100, including aggregated viewedCount) with pagination headers and without BroadcastRecipient joins.
/api/admin/broadcast/[id]GETAdmin-onlyCalls BroadcastService.getBroadcastById (src/features/broadcast/service.ts) to return the full BroadcastMessage body and ordered BroadcastRecipient delivery statuses for a single broadcast.
/api/admin/broadcast/schedule/[id]DELETEAdmin-onlyCalls BroadcastService.cancelScheduledBroadcast (src/features/broadcast/service.ts) to transition a SCHEDULED message to CANCELLED.
/api/admin/broadcast/retryPOSTAdmin-onlyValidates RetryBroadcastSchema and invokes BroadcastService.retryFailedRecipients (src/features/broadcast/service.ts) to retry FAILED entries or resend explicit recipientIds.
/api/cron/broadcastsGET, POSTBearer (CRON_SECRET)Edge-authenticated scheduler hook (src/app/api/cron/broadcasts/route.ts) invoking BroadcastService.processScheduledBroadcasts (src/features/broadcast/service.ts).

Provider Adapters (MultiChannelMessagingProvider) ​

MultiChannelMessagingProvider (src/features/broadcast/providers/index.ts) resolves provider credentials from AppConfig (stored in PostgreSQL and masked in /api/admin/settings via toAdminAppConfig in src/lib/config.ts):

ChannelAppConfig Provider ValueImplementationNetwork Behavior
EmailresendsendResendEmail (src/features/broadcast/providers/index.ts)Live HTTPS (POST https://api.resend.com/emails) using resendApiKey and resendFrom (or smtpFrom / sendgridFrom / contactEmail fallback). Sends sanitized html formatted via formatEmailHtmlBody, or unescaped html + generated text fallback when isHtml: true / format: 'html'.
EmailsendgridsendSendGridEmail (src/features/broadcast/providers/index.ts)Live HTTPS (POST https://api.sendgrid.com/v3/mail/send) using sendgridApiKey and sendgridFrom (or smtpFrom / resendFrom / contactEmail fallback). Sends sanitized text/html content formatted via formatEmailHtmlBody, or text/plain + unescaped text/html parts when isHtml: true / format: 'html'.
Emailsmtp (default)sendSmtpEmail (src/features/broadcast/providers/index.ts)Live Native SMTP (node:net / node:tls) enforcing strict certificate validation (rejectUnauthorized: true), implicit TLS (465 / smtpSecure: true), mandatory STARTTLS (25, 587, 2525), AUTH PLAIN / AUTH LOGIN, CRLF header sanitization, RFC 5321 dot-stuffing, and multipart/alternative (text/plain + text/html). Returns { success: false } if smtpHost is empty or STARTTLS is omitted/rejected.
EmailnonesendEmail (src/features/broadcast/providers/index.ts)Simulation mode: returns { success: true } immediately without performing network I/O.
SMStwiliosendTwilioSms (src/features/broadcast/providers/index.ts)Live HTTPS (POST https://api.twilio.com/2010-04-01/Accounts/<SID>/Messages.json) using HTTP Basic auth (twilioAccountSid + twilioAuthToken) and twilioFromNumber.
SMSnone (default)sendSms (src/features/broadcast/providers/index.ts)Simulation mode: returns { success: true } immediately without performing network I/O.

Audience Resolution & address-collection Filtering ​

Target recipient resolution runs through BroadcastService.resolveTargetGuests (src/features/broadcast/service.ts) and shares core predicate logic with the admin composer via filterTargetGuestsInMemory and summarizeBroadcastAudience in src/features/broadcast/audience.ts:

  1. Live Sample Data Exclusion (isSample: true) vs. Static Showcase Previews: In live server execution (STATIC_EXPORT unset or false), BroadcastService.resolveTargetGuests (src/features/broadcast/service.ts) filters out onboarding sample InvitationCode rows (isSample: true) so live previews, immediate broadcasts, and scheduled jobs never target sample guests. In static showcase builds (STATIC_EXPORT=true), resolveTargetGuests and the client-side filterTargetGuestsInMemory / summarizeBroadcastAudience helpers (src/features/broadcast/audience.ts) retain seeded sample guests so interactive demo persona previews continue reporting audience counts.
  2. Self-Submitted address-collection Exclusion by Default: Every valid submission on the unauthenticated public form (POST /api/guest/address/public in src/app/api/guest/address/public/route.ts) is quarantined as a new InvitationCode row with partyTags: ['address-collection'] (ADDRESS_COLLECTION_TAG in src/features/broadcast/audience.ts) for administrator review and duplicate merge via POST /api/admin/invitation-codes/merge (src/app/api/admin/invitation-codes/merge/route.ts), rather than matching or updating invited InvitationCode rows in place. Both filterTargetGuestsInMemory (src/features/broadcast/audience.ts) and BroadcastService.resolveTargetGuests (src/features/broadcast/service.ts) exclude any guest carrying the address-collection tag unless 'address-collection' is explicitly included in targetFilters.partyTags or the guest's record ID is explicitly listed in targetFilters.selectedIds. This prevents unverified public form submissions from attaching contacts to invited households or receiving private event announcements, invitation codes, or RSVP links before admin verification.
  3. Composable Audience Filters (BroadcastTargetFiltersSchema at src/features/broadcast/schemas.ts):
    • selectedIds: Explicit InvitationCode ID allowlist; when non-empty, overrides tag, household, pass status, address, dietary, party-group, and sub-event predicates while still applying attendanceStatus if specified.
    • partyTags, partyGroup, householdName, and searchQuery: Filters by tag overlap (partyTags), party side/group (partyGroup when not 'all'), case-insensitive household substring (householdName), and free-text guest/email/code/plus-one query (searchQuery via matchesGuestSearchQuery).
    • attendanceStatus ('attending' | 'declined' | 'pending' | 'all') and status ('redeemed' | 'unused' | 'all'): Filters by projected RSVP attendance status (getAttendanceStatus) and invitation pass redemption (InvitationCode.used).
    • addressStatus / addressFilter ('complete' | 'missing' | 'all') and dietaryCategory / dietaryFilter ('all' | 'has_restriction' | 'gluten-free' | 'vegetarian' | 'vegan' | 'dairy-free' | 'nut-free' | 'other' or custom string): Filters by mailing-address completeness (isAddressComplete, evaluating addressStatus ?? addressFilter) and dietary restrictions (matchDietaryCategory, evaluating dietaryCategory ?? dietaryFilter).
    • subEventId & subEventRsvpStatus: Targets guests invited to a specific sub-event (all invited guests for public SubEvent rows where isPrivate === false, or explicit SubEventAccess grants for private sub-events) and matches their SubEventRsvp status ('pending' matches invited guests with no submitted SubEventRsvp row or status === 'pending'; 'all' matches all invited guests).
  4. Channel Contact Eligibility: hasBroadcastChannelContact (src/features/broadcast/audience.ts) requires a non-empty email for EMAIL broadcasts and resolves phone from InvitationCode.extraFields JSON (phone, mobile, phoneNumber, or 'Phone Number' via getGuestPhone at src/features/broadcast/audience.ts) for SMS broadcasts.

Dispatch, Batching, Scheduling, & Retry Lifecycle ​

  1. Immediate Dispatch (BroadcastService.executeDispatch at src/features/broadcast/service.ts):
    • Creates a BroadcastMessage in SENDING status and pre-inserts PENDING (or FAILED when contact info is missing) BroadcastRecipient rows in chunks of RECIPIENT_CHUNK_SIZE = 250 (src/features/broadcast/service.ts).
    • Iterates through recipients in configurable batches (config.broadcastBatchSize, default 50, clamped 1..500), sleeping config.broadcastBatchDelayMs (default 500 ms, clamped 0..10000 ms) between batches to respect upstream provider rate limits.
    • Updates each BroadcastRecipient to SENT or FAILED (recording provider failure details in error) and finalizes the parent BroadcastMessage via deriveBroadcastStatus (src/features/broadcast/service.ts) as SENT (failedCount === 0 or zero recipients), PARTIALLY_SENT (sentCount > 0 && failedCount > 0), or FAILED (sentCount === 0 && failedCount > 0). When invited non-sample guests sign in or validate their code, SENT recipient rows transition to VIEWED for open tracking.
  2. Scheduled Broadcasts & Atomic Cron Claim (BroadcastService.processScheduledBroadcasts at src/features/broadcast/service.ts):
    • Passing a future scheduledFor ISO timestamp persists the BroadcastMessage with status: 'SCHEDULED' without dispatching immediately (SendBroadcastSchema strictly rejects unrecognized scheduling keys such as scheduledAt).
    • When an external scheduler triggers GET or POST /api/cron/broadcasts with Authorization: Bearer <CRON_SECRET>, processScheduledBroadcasts queries due SCHEDULED jobs (scheduledFor <= now) and executes an atomic prisma.broadcastMessage.updateMany({ where: { id: broadcast.id, status: 'SCHEDULED' }, data: { status: 'SENDING' } }) claim (updateResult.count === 0 skips concurrent duplicate workers) before resolving current target guests and running executeDispatch.
  3. Failed Recipient Retry & Per-Recipient Resend (BroadcastService.retryFailedRecipients at src/features/broadcast/service.ts):
    • Loads the BroadcastMessage and its BroadcastRecipient records, filters FAILED recipients (or explicit recipientIds when provided), re-renders personalized templates in throttled batches via persistRetryBatch, recounts SENT + VIEWED (sentCount) versus FAILED (failedCount), and updates the parent BroadcastMessage status via deriveBroadcastStatus (SENT, PARTIALLY_SENT, or FAILED).

Template Placeholders & HTML / Header Sanitization ​

Template interpolation and output encoding are enforced across src/features/broadcast/template.ts, src/features/broadcast/service.ts, and src/features/broadcast/providers/index.ts:

  • Supported Placeholders (AVAILABLE_TEMPLATE_PLACEHOLDERS at src/features/broadcast/template.ts): Exports the six composer tokens {{guestName}}, {{invitationCode}}, {{rsvpUrl}}, {{householdName}}, {{weddingDate}}, and {{venueName}} (renderBroadcastTemplate also supports {{code}} as an alias for {{invitationCode}}). Personalized {{rsvpUrl}} links are constructed via buildGuestRsvpUrl (src/features/broadcast/template.ts) using resolveBroadcastBaseUrl (src/features/broadcast/service.ts), which resolves the base URL in strict fallback order: configured AppConfig.baseUrl -> incoming requestOrigin -> 'http://localhost:3000' (emitting a baseUrlWarning whenever AppConfig.baseUrl is blank; NEXT_PUBLIC_SITE_URL is not consulted).
  • Context-Aware Escaping (renderBroadcastTemplate at src/features/broadcast/template.ts):
    • Plain-Text, Preview, & SMS Default (escapeHtml: false, default): renderBroadcastTemplate evaluates Boolean(options?.escapeHtml) and defaults escapeHtml to false so previews, SMS payloads, and email subjects do not double-encode apostrophes or ampersands.
    • HTML Email Body Context (escapeHtml: true): When rendering outbound EMAIL bodies (escapeEmailBody ?? true in BroadcastService.renderMessageContent at src/features/broadcast/service.ts), { escapeHtml: true } passes every substituted placeholder value through escapeHtmlEntities (src/features/broadcast/template.ts), encoding &, <, >, ", and ' so untrusted guest names or venue strings cannot inject HTML or <script> tags into emails.
  • Email Subject Header-Injection Defense (sanitizeEmailSubject at src/features/broadcast/template.ts): Strips CR, LF, and angle-bracket characters via subject.replace(/[\r\n<>]/g, '') before passing subjects to SMTP, Resend, or SendGrid.
  • HTML Body & Stationery Card Formatting (formatEmailHtmlBody at src/features/broadcast/providers/index.ts and renderStationeryCardHtml at src/features/broadcast/template.ts): Renders [CARD:save-the-date] and [CARD:formal-invitation] templates into themed HTML stationery cards with couple branding, AppConfig colors, event details, calendar links, and {{rsvpUrl}} CTA buttons, while escaping plain-text drafts into <p> / <br /> HTML blocks.

Released under the AGPL-3.0 License.