Publish Container / docker (push) Failing after 10m40s
- Remove unused prop-types dep, deprecated useOutboundLinkTracking export - Fix missing linkClicks key in analyticsEvents initial state (B-01) - Export ADMIN_SESSION_COOKIE from auth.js; remove local copy in admin-auth.js (D-02) - Remove cookieFlags() wrapper in auth.js and study-helpers.js; use cookieSecureFlag() directly (U-04) - Remove ADMIN_SESSION_TTL_MS duplicate from config.js (D-01) - Remove DEFAULT_SEO/DEFAULT_LEGAL/DEFAULT_REDIRECT_RULES/DEFAULT_PODCAST_FEATURED_LINKS/DEFAULT_PUBLISH_STATE duplicates from config.js; re-export from helpers.js (D-04, fixes sitemapPaths divergence) - Fix email.js hardcoded fallback strings to use DEFAULT_RESEND_TO/DEFAULT_RESEND_REPLY_TO (M-02) - Remove duplicate normalizeIp, isPrivateOrLocalIp, normalizeRedirectPath, sanitizeUrl, sanitizeRedirectRules bodies from study-helpers.js; re-export from helpers.js (D-03) - Fix pruneStatsByDays to import VISITOR_RETENTION_DAYS_DEFAULT from config.js (B-02) - Fix createTitusDownloadToken to use DOWNLOAD_TOKEN_TTL_MS constant (B-03) - Remove normalizeMessageType duplicate from study-helpers.js (U-03/D-08) - Remove dead wantsWelcome variable in contact.js; use shouldSendWelcome (B-04) - Replace dynamic imports in contact.js with static imports (B-07) - Remove dead wantsWelcome=true in study-auth.js (B-05) - Merge duplicate import blocks in analytics.js and public.js (D-05, D-06) - Replace dynamic readFile re-import in nuggets-host-upload.js (B-06) - Replace hardcoded SITE_URL fallbacks with getCanonicalBaseUrl() (M-06) - Replace raw resend.emails.send in study-account.js with sendResendEmailWithRetry (M-01) Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
450 lines
21 KiB
JavaScript
450 lines
21 KiB
JavaScript
import { randomUUID } from 'node:crypto'
|
|
import { Resend } from 'resend'
|
|
import { requireAdminAuth } from '../auth.js'
|
|
import { escapeHtml, splitName, buildAbsoluteUrl } from '../helpers.js'
|
|
import {
|
|
MAX_CONTACT_SUBMISSIONS,
|
|
MAX_QUESTIONS,
|
|
USE_RESEND_AUTOMATION_WELCOME,
|
|
DEFAULT_SEO,
|
|
DATA_FILE,
|
|
} from '../config.js'
|
|
import { state } from '../state.js'
|
|
import {
|
|
queueContactSubmissionsWrite,
|
|
queueQuestionsWrite,
|
|
queueDraftQuestionsWrite,
|
|
normalizeContactEmailStatus,
|
|
normalizeMessageType,
|
|
fireWebhooks,
|
|
loadSiteContentFile,
|
|
} from '../data.js'
|
|
import {
|
|
noteContactEmailCooldown,
|
|
extractTagValue,
|
|
mapResendEventToStatus,
|
|
extractResendMessageId,
|
|
} from '../study-helpers.js'
|
|
import {
|
|
getResendFromAddress,
|
|
getResendReplyToAddress,
|
|
getResendInboxAddress,
|
|
buildContactWelcomeEmailTemplate,
|
|
buildContactAdminNotificationTemplate,
|
|
sendResendEmailWithRetry,
|
|
syncContactToResend,
|
|
} from '../email.js'
|
|
|
|
// RFC 5322 msg-id: "<" printable-ASCII-no-whitespace ">"
|
|
const MESSAGE_ID_RE = /^<[\x21-\x7E]+>$/
|
|
|
|
function upsertContactEmailStatus(submissionId, stream, patch) {
|
|
if (!submissionId || typeof submissionId !== 'string') return
|
|
if (!stream || typeof stream !== 'string') return
|
|
const at = typeof patch?.lastEventAt === 'string' ? patch.lastEventAt : new Date().toISOString()
|
|
let updated = false
|
|
|
|
state.contactSubmissions = state.contactSubmissions.map(submission => {
|
|
if (submission.id !== submissionId) return submission
|
|
const next = normalizeContactEmailStatus(submission.emailStatus, submission.subscribe === true)
|
|
const current = next[stream] ?? { status: 'pending', lastEventAt: null, lastEventType: null, resendEmailId: null, error: null }
|
|
next[stream] = { ...current, ...patch, lastEventAt: at }
|
|
updated = true
|
|
return { ...submission, emailStatus: next }
|
|
})
|
|
|
|
if (updated) queueContactSubmissionsWrite()
|
|
}
|
|
|
|
function registerResendMessageForSubmission(submissionId, stream, sendResult) {
|
|
const resendMessageId = extractResendMessageId(sendResult)
|
|
if (!resendMessageId || !submissionId || !stream) return
|
|
state.resendEmailSubmissionIndex.set(resendMessageId, { submissionId, stream })
|
|
// Trim the index when it grows large; oldest entries are least likely to receive webhooks
|
|
if (state.resendEmailSubmissionIndex.size > 2000) {
|
|
const firstKey = state.resendEmailSubmissionIndex.keys().next().value
|
|
state.resendEmailSubmissionIndex.delete(firstKey)
|
|
}
|
|
upsertContactEmailStatus(submissionId, stream, { resendEmailId: resendMessageId })
|
|
}
|
|
|
|
function shouldSendWelcomeEmail({ subscribe }) {
|
|
return subscribe === true
|
|
}
|
|
|
|
const contactHits = new Map()
|
|
|
|
function contactRateLimit(req, res, next) {
|
|
const ip = req.ip ?? 'unknown'
|
|
const now = Date.now()
|
|
const windowMs = 10 * 60 * 1000
|
|
const entry = contactHits.get(ip) ?? { count: 0, start: now }
|
|
if (now - entry.start > windowMs) { entry.count = 0; entry.start = now }
|
|
entry.count += 1
|
|
contactHits.set(ip, entry)
|
|
// Prune stale entries to prevent unbounded growth
|
|
if (contactHits.size > 5000) {
|
|
const cutoff = now - windowMs
|
|
for (const [k, v] of contactHits) { if (v.start < cutoff) contactHits.delete(k) }
|
|
}
|
|
if (entry.count > 5) {
|
|
res.status(429).json({ message: 'Too many messages. Please wait a few minutes.' })
|
|
return
|
|
}
|
|
next()
|
|
}
|
|
|
|
export function register(app) {
|
|
app.post('/api/contact', contactRateLimit, async (req, res) => {
|
|
try {
|
|
const { firstName, lastName, email, message, messageType, subscribe, notifyOnAnswer, _honey } = req.body ?? {}
|
|
|
|
if (_honey) { res.json({ ok: true }); return }
|
|
|
|
if (!firstName || typeof firstName !== 'string' || firstName.trim().length < 1 || firstName.trim().length > 100) {
|
|
res.status(400).json({ message: 'First name is required.' }); return
|
|
}
|
|
if (lastName !== undefined && lastName !== null && (typeof lastName !== 'string' || lastName.trim().length > 100)) {
|
|
res.status(400).json({ message: 'Last name is too long.' }); return
|
|
}
|
|
if (!email || typeof email !== 'string' || !/^[a-zA-Z0-9._%+\-]{1,64}@[a-zA-Z0-9.\-]{1,253}\.[a-zA-Z]{2,}$/.test(email.trim())) {
|
|
res.status(400).json({ message: 'A valid email address is required.' }); return
|
|
}
|
|
if (!message || typeof message !== 'string' || message.trim().length < 5 || message.trim().length > 3000) {
|
|
res.status(400).json({ message: 'Message must be between 5 and 3000 characters.' }); return
|
|
}
|
|
|
|
if (!process.env.RESEND_API_KEY) {
|
|
console.error('[contact] RESEND_API_KEY env var not set')
|
|
res.status(503).json({ message: 'The contact form is not yet configured on the server.' }); return
|
|
}
|
|
|
|
const trimmedName = [firstName.trim(), typeof lastName === 'string' ? lastName.trim() : ''].filter(Boolean).join(' ')
|
|
const trimmedEmail = email.trim()
|
|
const trimmedMessage = message.trim()
|
|
const normalizedMessageType = normalizeMessageType(messageType)
|
|
const cooldown = noteContactEmailCooldown(trimmedEmail)
|
|
if (!cooldown.ok) {
|
|
const retryAfterSeconds = Math.max(1, Math.ceil(cooldown.retryAfterMs / 1000))
|
|
res.status(429).json({ message: `Please wait ${retryAfterSeconds}s before sending another message from this email.` }); return
|
|
}
|
|
|
|
const submittedAt = new Date().toLocaleString('en-US', { dateStyle: 'medium', timeStyle: 'short' })
|
|
const shouldSendWelcome = shouldSendWelcomeEmail({ subscribe })
|
|
|
|
const submission = {
|
|
id: randomUUID(),
|
|
submittedAt: new Date().toISOString(),
|
|
name: trimmedName,
|
|
email: trimmedEmail,
|
|
message: trimmedMessage,
|
|
messageType: normalizedMessageType,
|
|
subscribe: shouldSendWelcome,
|
|
archived: false,
|
|
emailStatus: normalizeContactEmailStatus(null, shouldSendWelcome),
|
|
}
|
|
state.contactSubmissions.unshift(submission)
|
|
state.contactSubmissions = state.contactSubmissions.slice(0, MAX_CONTACT_SUBMISSIONS)
|
|
queueContactSubmissionsWrite()
|
|
fireWebhooks('contact.new', { name: trimmedName, email: trimmedEmail, message: trimmedMessage, messageType: normalizedMessageType, submittedAt: submission.submittedAt })
|
|
|
|
if (normalizedMessageType === 'question') {
|
|
const question = {
|
|
id: randomUUID(),
|
|
submittedAt: new Date().toISOString(),
|
|
firstName: splitName(trimmedName).firstName,
|
|
email: trimmedEmail,
|
|
question: trimmedMessage,
|
|
answer: '',
|
|
answeredAt: null,
|
|
isApproved: false,
|
|
approvedAt: null,
|
|
notifyOnAnswer: notifyOnAnswer === true,
|
|
}
|
|
state.questions.unshift(question)
|
|
state.questions = state.questions.slice(0, MAX_QUESTIONS)
|
|
if (state.draftQuestions !== null) {
|
|
state.draftQuestions.unshift(question)
|
|
state.draftQuestions = state.draftQuestions.slice(0, MAX_QUESTIONS)
|
|
queueDraftQuestionsWrite()
|
|
}
|
|
queueQuestionsWrite()
|
|
}
|
|
|
|
const resend = new Resend(process.env.RESEND_API_KEY)
|
|
const adminInbox = getResendInboxAddress()
|
|
const replyToAddress = getResendReplyToAddress()
|
|
const fromAddress = getResendFromAddress()
|
|
const safeMessageTypeTag = normalizedMessageType.replace(/[^a-z0-9_-]/gi, '-').toLowerCase()
|
|
const adminTemplate = buildContactAdminNotificationTemplate({ normalizedMessageType, trimmedName, trimmedEmail, submittedAt, trimmedMessage })
|
|
let welcomeSent = false
|
|
|
|
if (subscribe === true) {
|
|
await syncContactToResend(trimmedName, trimmedEmail)
|
|
}
|
|
|
|
if (shouldSendWelcome && !USE_RESEND_AUTOMATION_WELCOME) {
|
|
const greetingName = splitName(trimmedName).firstName?.trim() ?? ''
|
|
let publishedSiteContent = state.cachedSiteContent
|
|
if (!publishedSiteContent) {
|
|
try {
|
|
const published = await loadSiteContentFile(DATA_FILE)
|
|
publishedSiteContent = published?.siteContent ?? null
|
|
} catch { publishedSiteContent = null }
|
|
}
|
|
|
|
const emailConfig = publishedSiteContent ?? {}
|
|
const welcomeBaseUrl = typeof emailConfig?.seo?.canonicalUrl === 'string' && emailConfig.seo.canonicalUrl.trim()
|
|
? emailConfig.seo.canonicalUrl.trim()
|
|
: DEFAULT_SEO.canonicalUrl
|
|
const welcomeSubject = process.env.RESEND_WELCOME_SUBJECT ?? emailConfig.welcomeEmailSubject ?? 'Welcome to Verse by Verse with Nate'
|
|
const welcomeGreetingPrefix = emailConfig.welcomeEmailGreetingPrefix?.trim() || "Glad you're here"
|
|
const welcomeTemplate = buildContactWelcomeEmailTemplate({
|
|
greetingName,
|
|
welcomeGreetingPrefix,
|
|
welcomeIntro: emailConfig.welcomeEmailIntro?.trim() || 'Thanks for subscribing to Verse by Verse with Nate - a Bible teaching podcast where we slow down, dig into the text, and pull out the nuggets God has for us word by word.',
|
|
welcomeCurrentSeries: emailConfig.welcomeEmailCurrentSeries?.trim() || "Right now we're working through the book of Titus - a short letter packed with practical wisdom about grace, godliness, and what the Christian life looks like when it's rooted in sound doctrine.",
|
|
welcomeStartHereTitle: emailConfig.welcomeEmailStartHereTitle?.trim() || 'Episode 1 - Introduction to Titus',
|
|
welcomeStartHereSummary: emailConfig.welcomeEmailStartHereSummary?.trim() || 'Who wrote it, who received it, and why it still matters.',
|
|
welcomeExpect1: emailConfig.welcomeEmailWhatToExpect1?.trim() || 'Verse-by-verse teaching - we go slow and let the text speak for itself.',
|
|
welcomeExpect2: emailConfig.welcomeEmailWhatToExpect2?.trim() || 'Greek word studies - the kind that open up meaning without being a lecture.',
|
|
welcomeExpect3: emailConfig.welcomeEmailWhatToExpect3?.trim() || 'New episodes + study notes delivered right to your inbox.',
|
|
welcomeScripture: emailConfig.welcomeEmailScripture?.trim() || 'For the grace of God has appeared, bringing salvation to all people.',
|
|
welcomeScriptureRef: emailConfig.welcomeEmailScriptureRef?.trim() || 'Titus 2:11 - BSB',
|
|
welcomeSignoff: emailConfig.welcomeEmailSignoff?.trim() || 'Grace and peace,\nNate',
|
|
welcomeSpotifyUrl: buildAbsoluteUrl(welcomeBaseUrl, process.env.RESEND_WELCOME_SPOTIFY_URL ?? emailConfig.welcomeEmailSpotifyUrl ?? '/spotify'),
|
|
welcomeAppleUrl: buildAbsoluteUrl(welcomeBaseUrl, process.env.RESEND_WELCOME_APPLE_URL ?? emailConfig.welcomeEmailAppleUrl ?? '/apple'),
|
|
welcomeAmazonUrl: buildAbsoluteUrl(welcomeBaseUrl, process.env.RESEND_WELCOME_AMAZON_URL ?? emailConfig.welcomeEmailAmazonUrl ?? '/amazon'),
|
|
welcomeWebsiteUrl: buildAbsoluteUrl(welcomeBaseUrl, process.env.RESEND_WELCOME_WEBSITE_URL ?? emailConfig.welcomeEmailWebsiteUrl ?? '/'),
|
|
welcomeEpisodeUrl: buildAbsoluteUrl(welcomeBaseUrl, process.env.RESEND_WELCOME_EPISODE_URL ?? emailConfig.welcomeEmailStartHereUrl ?? '/start-here'),
|
|
welcomeImageUrl: buildAbsoluteUrl(welcomeBaseUrl, process.env.RESEND_WELCOME_IMAGE_URL ?? emailConfig.welcomeEmailImageUrl ?? '/images/podcast-art.jpeg'),
|
|
welcomeSpotifyBtnLabel: emailConfig.welcomeEmailSpotifyBtnLabel?.trim() || 'Listen on Spotify',
|
|
welcomeAppleBtnLabel: emailConfig.welcomeEmailAppleBtnLabel?.trim() || 'Apple Podcasts',
|
|
welcomeStartHereLinkLabel: emailConfig.welcomeEmailStartHereLinkLabel?.trim() || 'Open Start Here page',
|
|
})
|
|
|
|
try {
|
|
const welcomeSendResult = await sendResendEmailWithRetry({
|
|
resend,
|
|
context: 'contact-welcome',
|
|
payload: {
|
|
from: fromAddress,
|
|
to: [trimmedEmail],
|
|
replyTo: replyToAddress,
|
|
subject: welcomeSubject,
|
|
tags: [
|
|
{ name: 'flow', value: 'contact-welcome' },
|
|
{ name: 'message_type', value: safeMessageTypeTag },
|
|
{ name: 'submission_id', value: submission.id },
|
|
],
|
|
headers: {
|
|
'List-Unsubscribe': `<mailto:${replyToAddress}?subject=Unsubscribe>`,
|
|
'X-Contact-Submission-Id': submission.id,
|
|
},
|
|
text: welcomeTemplate.text,
|
|
html: welcomeTemplate.html,
|
|
},
|
|
})
|
|
registerResendMessageForSubmission(submission.id, 'welcome', welcomeSendResult)
|
|
upsertContactEmailStatus(submission.id, 'welcome', { status: 'sent', lastEventType: 'email.sent', error: null })
|
|
welcomeSent = true
|
|
} catch (welcomeErr) {
|
|
upsertContactEmailStatus(submission.id, 'welcome', {
|
|
status: 'failed',
|
|
lastEventType: 'email.failed',
|
|
error: String(welcomeErr?.message ?? welcomeErr ?? 'unknown error').slice(0, 600),
|
|
})
|
|
console.error('[contact] welcome email failed:', welcomeErr)
|
|
// Submission is already saved — don't 500 the user; fall through to admin notification.
|
|
}
|
|
} else if (shouldSendWelcome && USE_RESEND_AUTOMATION_WELCOME) {
|
|
upsertContactEmailStatus(submission.id, 'welcome', { status: 'automation-enabled', lastEventType: 'email.automation.enabled', error: null })
|
|
}
|
|
|
|
try {
|
|
const adminSendResult = await sendResendEmailWithRetry({
|
|
resend,
|
|
context: 'contact-admin-notification',
|
|
payload: {
|
|
from: fromAddress,
|
|
to: [adminInbox],
|
|
replyTo: trimmedEmail,
|
|
subject: adminTemplate.subject,
|
|
tags: [
|
|
{ name: 'flow', value: 'contact-admin' },
|
|
{ name: 'message_type', value: safeMessageTypeTag },
|
|
{ name: 'submission_id', value: submission.id },
|
|
],
|
|
headers: { 'X-Contact-Submission-Id': submission.id },
|
|
text: adminTemplate.text,
|
|
html: adminTemplate.html,
|
|
},
|
|
})
|
|
registerResendMessageForSubmission(submission.id, 'adminNotification', adminSendResult)
|
|
upsertContactEmailStatus(submission.id, 'adminNotification', { status: 'sent', lastEventType: 'email.sent', error: null })
|
|
} catch (adminSendErr) {
|
|
upsertContactEmailStatus(submission.id, 'adminNotification', {
|
|
status: 'failed',
|
|
lastEventType: 'email.failed',
|
|
error: String(adminSendErr?.message ?? adminSendErr ?? 'unknown error').slice(0, 600),
|
|
})
|
|
console.error('[contact] admin notification email failed:', adminSendErr)
|
|
// Submission is already saved — don't 500 the user.
|
|
}
|
|
|
|
res.json({ ok: true, welcomeSent, welcomeHandledByAutomation: shouldSendWelcome && USE_RESEND_AUTOMATION_WELCOME })
|
|
} catch (err) {
|
|
console.error('[contact] send error:', err)
|
|
res.status(500).json({ message: 'Failed to send your message. Please try again or email us directly.' })
|
|
}
|
|
})
|
|
|
|
app.post('/api/resend/webhook', (req, res) => {
|
|
const expectedToken = typeof process.env.RESEND_WEBHOOK_TOKEN === 'string' ? process.env.RESEND_WEBHOOK_TOKEN.trim() : ''
|
|
if (!expectedToken) {
|
|
res.status(503).json({ message: 'Webhook token is not configured.' }); return
|
|
}
|
|
|
|
const providedToken = (req.get('x-webhook-token') || '').trim()
|
|
|| (req.get('x-resend-webhook-token') || '').trim()
|
|
|| String(req.query?.token || '').trim()
|
|
|| (req.get('authorization') || '').replace(/^Bearer\s+/i, '').trim()
|
|
|
|
if (!providedToken || providedToken !== expectedToken) {
|
|
res.status(401).json({ message: 'Unauthorized webhook.' }); return
|
|
}
|
|
|
|
const body = req.body && typeof req.body === 'object' ? req.body : {}
|
|
const eventType = typeof body.type === 'string' ? body.type.trim() : ''
|
|
const data = body.data && typeof body.data === 'object' ? body.data : {}
|
|
const tags = Array.isArray(data.tags) ? data.tags : []
|
|
|
|
const resendMessageId = (
|
|
typeof data.email_id === 'string' && data.email_id.trim()
|
|
? data.email_id.trim()
|
|
: (typeof data.emailId === 'string' && data.emailId.trim()
|
|
? data.emailId.trim()
|
|
: (typeof data.id === 'string' && data.id.trim() ? data.id.trim() : ''))
|
|
)
|
|
|
|
const indexed = resendMessageId ? state.resendEmailSubmissionIndex.get(resendMessageId) : null
|
|
const taggedSubmissionId = extractTagValue(tags, 'submission_id')
|
|
const submissionId = indexed?.submissionId || taggedSubmissionId
|
|
|
|
const flow = extractTagValue(tags, 'flow')
|
|
const stream = indexed?.stream
|
|
|| (flow === 'contact-welcome' ? 'welcome' : '')
|
|
|| (flow === 'contact-admin' ? 'adminNotification' : '')
|
|
|| (flow === 'admin-reply' ? 'adminReply' : '')
|
|
|
|
if (!submissionId || !stream) {
|
|
res.json({ ok: true, ignored: true }); return
|
|
}
|
|
|
|
upsertContactEmailStatus(submissionId, stream, {
|
|
status: mapResendEventToStatus(eventType),
|
|
lastEventType: eventType || 'webhook.event',
|
|
resendEmailId: resendMessageId || null,
|
|
error: typeof data?.message === 'string' ? data.message.slice(0, 600) : null,
|
|
})
|
|
|
|
res.json({ ok: true })
|
|
})
|
|
|
|
|
|
app.get('/api/admin-contact-submissions', requireAdminAuth, (_req, res) => {
|
|
res.json({ submissions: state.contactSubmissions.slice(0, 300) })
|
|
})
|
|
|
|
app.patch('/api/admin-contact-submissions/:id', requireAdminAuth, (req, res) => {
|
|
const { id } = req.params
|
|
const { archived } = req.body ?? {}
|
|
if (typeof archived !== 'boolean') {
|
|
res.status(400).json({ message: 'archived must be a boolean.' }); return
|
|
}
|
|
const idx = state.contactSubmissions.findIndex(s => s.id === id)
|
|
if (idx === -1) {
|
|
res.status(404).json({ message: 'Submission not found.' }); return
|
|
}
|
|
state.contactSubmissions[idx] = { ...state.contactSubmissions[idx], archived }
|
|
queueContactSubmissionsWrite()
|
|
res.json({ ok: true, submission: state.contactSubmissions[idx] })
|
|
})
|
|
|
|
app.get('/api/admin-subscribers', requireAdminAuth, (_req, res) => {
|
|
const seen = new Set()
|
|
const subscribers = state.contactSubmissions
|
|
.filter(entry => entry.subscribe === true && entry.email && !seen.has(entry.email) && seen.add(entry.email))
|
|
.map(entry => ({
|
|
name: entry.name,
|
|
email: entry.email,
|
|
subscribedAt: entry.submittedAt,
|
|
source: entry.message?.startsWith('Requested') ? 'download' : 'contact-form',
|
|
}))
|
|
.sort((a, b) => new Date(b.subscribedAt).getTime() - new Date(a.subscribedAt).getTime())
|
|
res.json({ subscribers, total: subscribers.length })
|
|
})
|
|
|
|
app.post('/api/admin-subscribers/export', requireAdminAuth, (_req, res) => {
|
|
const seen = new Set()
|
|
const rows = [['Name', 'Email', 'Subscribed At', 'Source']]
|
|
state.contactSubmissions
|
|
.filter(entry => entry.subscribe === true && entry.email && !seen.has(entry.email) && seen.add(entry.email))
|
|
.sort((a, b) => new Date(b.submittedAt).getTime() - new Date(a.submittedAt).getTime())
|
|
.forEach(entry => {
|
|
const source = entry.message?.startsWith('Requested') ? 'download' : 'contact-form'
|
|
rows.push([entry.name, entry.email, entry.submittedAt, source])
|
|
})
|
|
const csv = rows.map(row => row.map(cell => `"${String(cell ?? '').replace(/"/g, '""')}"`).join(',')).join('\n')
|
|
res.setHeader('Content-Type', 'text/csv')
|
|
res.setHeader('Content-Disposition', `attachment; filename="subscribers-${new Date().toISOString().slice(0, 10)}.csv"`)
|
|
res.send(csv)
|
|
})
|
|
|
|
app.post('/api/admin-broadcast', requireAdminAuth, async (req, res) => {
|
|
const { subject, html } = req.body ?? {}
|
|
if (!subject || typeof subject !== 'string' || !subject.trim()) {
|
|
res.status(400).json({ message: 'Subject is required.' }); return
|
|
}
|
|
if (!html || typeof html !== 'string' || !html.trim()) {
|
|
res.status(400).json({ message: 'Email body is required.' }); return
|
|
}
|
|
if (!process.env.RESEND_API_KEY) {
|
|
res.status(500).json({ message: 'RESEND_API_KEY is not configured.' }); return
|
|
}
|
|
|
|
const seen = new Set()
|
|
const recipients = state.contactSubmissions
|
|
.filter(e => e.subscribe === true && e.email && !seen.has(e.email) && seen.add(e.email))
|
|
.map(e => ({ name: e.name ?? '', email: e.email }))
|
|
|
|
if (recipients.length === 0) {
|
|
res.status(400).json({ message: 'No subscribers to send to.' }); return
|
|
}
|
|
|
|
const resend = new Resend(process.env.RESEND_API_KEY)
|
|
const from = getResendFromAddress()
|
|
const replyTo = getResendReplyToAddress()
|
|
const BATCH = 50
|
|
let sent = 0
|
|
let failed = 0
|
|
|
|
for (let i = 0; i < recipients.length; i += BATCH) {
|
|
const batch = recipients.slice(i, i + BATCH)
|
|
const emails = batch.map(r => ({
|
|
from,
|
|
to: r.email,
|
|
reply_to: replyTo,
|
|
subject: subject.trim(),
|
|
html: html.replace(/\{\{name\}\}/g, escapeHtml(r.name || 'Friend')),
|
|
}))
|
|
try {
|
|
const { error } = await resend.batch.send(emails)
|
|
if (error) { failed += batch.length } else { sent += batch.length }
|
|
} catch { failed += batch.length }
|
|
}
|
|
|
|
res.json({ ok: true, sent, failed, total: recipients.length })
|
|
})
|
|
}
|