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
smtpHost Requirement vs.noneSimulation ModeOut of the box,
AppConfigdefaults toemailProvider = "smtp"andsmsProvider = "none". InMultiChannelMessagingProvider(src/features/broadcast/providers/index.ts):
emailProvider = "smtp"(sendSmtpEmailat src/features/broadcast/providers/index.ts): Connects overnode:net/node:tlswith strict server certificate verification (rejectUnauthorized: true), enforcing implicit TLS on port465(smtpSecure: true) and mandatorySTARTTLSupgrade on ports25,587, and2525beforeAUTH PLAIN,AUTH LOGIN, orMAIL FROM(with SSRF host resolution viavalidateAndResolveHostand a 10-second socket timeout), and returns{ success: false }whensmtpHostis blank.testConnection(src/features/broadcast/providers/index.ts) executes a live220greeting,EHLO/HELO, mandatorySTARTTLS(whensmtpSecureisfalse),AUTH, andQUIThandshake withrejectUnauthorized: true.emailProvider = "none"(sendEmailat src/features/broadcast/providers/index.ts) andsmsProvider = "none"(sendSmsat 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) andBroadcastService.retryFailedRecipients(src/features/broadcast/service.ts) recordBroadcastRecipientrows asSENTand mark the parentBroadcastMessageSENTwithout external network traffic. Production operators must configure a validsmtpHost(forsmtp),resend, orsendgridfor live email delivery andtwiliofor 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).
| Endpoint | Method | Access Tier | Responsibility |
|---|---|---|---|
/api/admin/broadcast/preview | POST | Admin-only | Validates 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-connection | POST | Admin-only | Validates TestConnectionSchema and invokes MultiChannelMessagingProvider.testConnection (src/features/broadcast/providers/index.ts) against live or unsaved admin credential overrides. |
/api/admin/broadcast/test-send | POST | Admin-only | Validates 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/send | POST | Admin-only | Validates 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/history | GET | Admin-only | Calls 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] | GET | Admin-only | Calls 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] | DELETE | Admin-only | Calls BroadcastService.cancelScheduledBroadcast (src/features/broadcast/service.ts) to transition a SCHEDULED message to CANCELLED. |
/api/admin/broadcast/retry | POST | Admin-only | Validates RetryBroadcastSchema and invokes BroadcastService.retryFailedRecipients (src/features/broadcast/service.ts) to retry FAILED entries or resend explicit recipientIds. |
/api/cron/broadcasts | GET, POST | Bearer (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):
| Channel | AppConfig Provider Value | Implementation | Network Behavior |
|---|---|---|---|
resend | sendResendEmail (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'. | |
sendgrid | sendSendGridEmail (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'. | |
smtp (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. | |
none | sendEmail (src/features/broadcast/providers/index.ts) | Simulation mode: returns { success: true } immediately without performing network I/O. | |
| SMS | twilio | sendTwilioSms (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. |
| SMS | none (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:
- Live Sample Data Exclusion (
isSample: true) vs. Static Showcase Previews: In live server execution (STATIC_EXPORTunset orfalse),BroadcastService.resolveTargetGuests(src/features/broadcast/service.ts) filters out onboarding sampleInvitationCoderows (isSample: true) so live previews, immediate broadcasts, and scheduled jobs never target sample guests. In static showcase builds (STATIC_EXPORT=true),resolveTargetGuestsand the client-sidefilterTargetGuestsInMemory/summarizeBroadcastAudiencehelpers (src/features/broadcast/audience.ts) retain seeded sample guests so interactive demo persona previews continue reporting audience counts. - Self-Submitted
address-collectionExclusion by Default: Every valid submission on the unauthenticated public form (POST /api/guest/address/publicin src/app/api/guest/address/public/route.ts) is quarantined as a newInvitationCoderow withpartyTags: ['address-collection'](ADDRESS_COLLECTION_TAGin src/features/broadcast/audience.ts) for administrator review and duplicate merge viaPOST /api/admin/invitation-codes/merge(src/app/api/admin/invitation-codes/merge/route.ts), rather than matching or updating invitedInvitationCoderows in place. BothfilterTargetGuestsInMemory(src/features/broadcast/audience.ts) andBroadcastService.resolveTargetGuests(src/features/broadcast/service.ts) exclude any guest carrying theaddress-collectiontag unless'address-collection'is explicitly included intargetFilters.partyTagsor the guest's record ID is explicitly listed intargetFilters.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. - Composable Audience Filters (
BroadcastTargetFiltersSchemaat src/features/broadcast/schemas.ts):selectedIds: ExplicitInvitationCodeID allowlist; when non-empty, overrides tag, household, pass status, address, dietary, party-group, and sub-event predicates while still applyingattendanceStatusif specified.partyTags,partyGroup,householdName, andsearchQuery: Filters by tag overlap (partyTags), party side/group (partyGroupwhen not'all'), case-insensitive household substring (householdName), and free-text guest/email/code/plus-one query (searchQueryviamatchesGuestSearchQuery).attendanceStatus('attending' | 'declined' | 'pending' | 'all') andstatus('redeemed' | 'unused' | 'all'): Filters by projected RSVP attendance status (getAttendanceStatus) and invitation pass redemption (InvitationCode.used).addressStatus/addressFilter('complete' | 'missing' | 'all') anddietaryCategory/dietaryFilter('all' | 'has_restriction' | 'gluten-free' | 'vegetarian' | 'vegan' | 'dairy-free' | 'nut-free' | 'other'or custom string): Filters by mailing-address completeness (isAddressComplete, evaluatingaddressStatus ?? addressFilter) and dietary restrictions (matchDietaryCategory, evaluatingdietaryCategory ?? dietaryFilter).subEventId&subEventRsvpStatus: Targets guests invited to a specific sub-event (all invited guests for publicSubEventrows whereisPrivate === false, or explicitSubEventAccessgrants for private sub-events) and matches theirSubEventRsvpstatus ('pending'matches invited guests with no submittedSubEventRsvprow orstatus === 'pending';'all'matches all invited guests).
- Channel Contact Eligibility:
hasBroadcastChannelContact(src/features/broadcast/audience.ts) requires a non-emptyemailforEMAILbroadcasts and resolvesphonefromInvitationCode.extraFieldsJSON (phone,mobile,phoneNumber, or'Phone Number'viagetGuestPhoneat src/features/broadcast/audience.ts) forSMSbroadcasts.
Dispatch, Batching, Scheduling, & Retry Lifecycle
- Immediate Dispatch (
BroadcastService.executeDispatchat src/features/broadcast/service.ts):- Creates a
BroadcastMessageinSENDINGstatus and pre-insertsPENDING(orFAILEDwhen contact info is missing)BroadcastRecipientrows in chunks ofRECIPIENT_CHUNK_SIZE = 250(src/features/broadcast/service.ts). - Iterates through recipients in configurable batches (
config.broadcastBatchSize, default50, clamped1..500), sleepingconfig.broadcastBatchDelayMs(default500 ms, clamped0..10000 ms) between batches to respect upstream provider rate limits. - Updates each
BroadcastRecipienttoSENTorFAILED(recording provider failure details inerror) and finalizes the parentBroadcastMessageviaderiveBroadcastStatus(src/features/broadcast/service.ts) asSENT(failedCount === 0or zero recipients),PARTIALLY_SENT(sentCount > 0 && failedCount > 0), orFAILED(sentCount === 0 && failedCount > 0). When invited non-sample guests sign in or validate their code,SENTrecipient rows transition toVIEWEDfor open tracking.
- Creates a
- Scheduled Broadcasts & Atomic Cron Claim (
BroadcastService.processScheduledBroadcastsat src/features/broadcast/service.ts):- Passing a future
scheduledForISO timestamp persists theBroadcastMessagewithstatus: 'SCHEDULED'without dispatching immediately (SendBroadcastSchemastrictly rejects unrecognized scheduling keys such asscheduledAt). - When an external scheduler triggers
GETorPOST /api/cron/broadcastswithAuthorization: Bearer <CRON_SECRET>,processScheduledBroadcastsqueries dueSCHEDULEDjobs (scheduledFor <= now) and executes an atomicprisma.broadcastMessage.updateMany({ where: { id: broadcast.id, status: 'SCHEDULED' }, data: { status: 'SENDING' } })claim (updateResult.count === 0skips concurrent duplicate workers) before resolving current target guests and runningexecuteDispatch.
- Passing a future
- Failed Recipient Retry & Per-Recipient Resend (
BroadcastService.retryFailedRecipientsat src/features/broadcast/service.ts):- Loads the
BroadcastMessageand itsBroadcastRecipientrecords, filtersFAILEDrecipients (or explicitrecipientIdswhen provided), re-renders personalized templates in throttled batches viapersistRetryBatch, recountsSENT+VIEWED(sentCount) versusFAILED(failedCount), and updates the parentBroadcastMessagestatus viaderiveBroadcastStatus(SENT,PARTIALLY_SENT, orFAILED).
- Loads the
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_PLACEHOLDERSat src/features/broadcast/template.ts): Exports the six composer tokens{{guestName}},{{invitationCode}},{{rsvpUrl}},{{householdName}},{{weddingDate}}, and{{venueName}}(renderBroadcastTemplatealso supports{{code}}as an alias for{{invitationCode}}). Personalized{{rsvpUrl}}links are constructed viabuildGuestRsvpUrl(src/features/broadcast/template.ts) usingresolveBroadcastBaseUrl(src/features/broadcast/service.ts), which resolves the base URL in strict fallback order: configuredAppConfig.baseUrl-> incomingrequestOrigin->'http://localhost:3000'(emitting abaseUrlWarningwheneverAppConfig.baseUrlis blank;NEXT_PUBLIC_SITE_URLis not consulted). - Context-Aware Escaping (
renderBroadcastTemplateat src/features/broadcast/template.ts):- Plain-Text, Preview, & SMS Default (
escapeHtml: false, default):renderBroadcastTemplateevaluatesBoolean(options?.escapeHtml)and defaultsescapeHtmltofalseso previews, SMS payloads, and email subjects do not double-encode apostrophes or ampersands. - HTML Email Body Context (
escapeHtml: true): When rendering outboundEMAILbodies (escapeEmailBody ?? trueinBroadcastService.renderMessageContentat src/features/broadcast/service.ts),{ escapeHtml: true }passes every substituted placeholder value throughescapeHtmlEntities(src/features/broadcast/template.ts), encoding&,<,>,", and'so untrusted guest names or venue strings cannot inject HTML or<script>tags into emails.
- Plain-Text, Preview, & SMS Default (
- Email Subject Header-Injection Defense (
sanitizeEmailSubjectat src/features/broadcast/template.ts): Strips CR, LF, and angle-bracket characters viasubject.replace(/[\r\n<>]/g, '')before passing subjects to SMTP, Resend, or SendGrid. - HTML Body & Stationery Card Formatting (
formatEmailHtmlBodyat src/features/broadcast/providers/index.ts andrenderStationeryCardHtmlat src/features/broadcast/template.ts): Renders[CARD:save-the-date]and[CARD:formal-invitation]templates into themed HTML stationery cards with couple branding,AppConfigcolors, event details, calendar links, and{{rsvpUrl}}CTA buttons, while escaping plain-text drafts into<p>/<br />HTML blocks.