1d43875e5a
Critical fixes: - sanitizeLoadedHitStats/VisitorStats: restore full state shape so a snapshot restore no longer crashes hit-counting middleware (missing byPathReal, byPathBot, byDayReal, byDayBot, botReasons, ipHashIndex) - /questions/share/🆔 read state.questions only, not draft questions - inbound-email: validate date with Number.isFinite before toISOString - study-reminders: wrap each send in try/catch so one failure doesn't block remaining users; persist sent-markers after each success Security: - getClientIp: use req.ip (trust-proxy-resolved) instead of raw x-forwarded-for header to prevent IP spoofing - env-snapshot.env: delete immediately after backup tar stream ends so secrets don't linger on disk between exports Correctness / UX: - contact form: email failures no longer 500 the user after the submission is already saved; log and fall through instead - study-account profile: cap data URI avatar at 6 MB - admin enrollment PATCH: validate slug against study catalog - signup: return 503 at MAX_STUDY_USERS instead of silently dropping oldest accounts Memory leaks: - contactHits, downloadHits Maps: prune stale entries at 5000 entries - resendEmailSubmissionIndex: trim to 2000 entries (oldest first) Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
72 lines
3.0 KiB
JavaScript
72 lines
3.0 KiB
JavaScript
import { randomUUID, timingSafeEqual } from 'node:crypto'
|
|
import { state } from '../state.js'
|
|
import { queueContactSubmissionsWrite } from '../data.js'
|
|
import { MAX_CONTACT_SUBMISSIONS } from '../config.js'
|
|
|
|
// RFC 5322 msg-id: "<" printable-ASCII-no-whitespace ">"
|
|
const MESSAGE_ID_RE = /^<[\x21-\x7E]+>$/
|
|
|
|
export function register(app) {
|
|
app.post('/api/inbound-email', (req, res) => {
|
|
const secret = process.env.INBOUND_EMAIL_SECRET
|
|
if (!secret) {
|
|
res.status(503).json({ message: 'Inbound email not configured.' }); return
|
|
}
|
|
|
|
const provided = req.get('x-webhook-secret') ?? ''
|
|
const a = Buffer.from(provided, 'utf8')
|
|
const b = Buffer.from(secret, 'utf8')
|
|
if (!provided || a.length !== b.length || !timingSafeEqual(a, b)) {
|
|
res.status(401).json({ message: 'Unauthorized.' }); return
|
|
}
|
|
|
|
const { from, to, subject, body, htmlBody, date, messageId, source } = req.body ?? {}
|
|
|
|
if (!from || typeof from !== 'string') {
|
|
res.status(400).json({ message: 'Missing from address.' }); return
|
|
}
|
|
|
|
// Extract display name and email address from "Name <email>" format
|
|
const fromMatch = /^(.*?)\s*<([^>]+)>$/.exec(from.trim())
|
|
const fromEmail = fromMatch ? fromMatch[2].trim() : from.trim()
|
|
const fromName = fromMatch ? fromMatch[1].trim() : from.trim()
|
|
|
|
const normalizedMessageId = typeof messageId === 'string' && MESSAGE_ID_RE.test(messageId.trim()) ? messageId.trim() : ''
|
|
|
|
// Deduplicate by messageId if provided
|
|
if (normalizedMessageId) {
|
|
const exists = state.contactSubmissions.some(s => s.messageId === normalizedMessageId)
|
|
if (exists) {
|
|
res.json({ ok: true, duplicate: true }); return
|
|
}
|
|
}
|
|
|
|
const submission = {
|
|
id: randomUUID(),
|
|
submittedAt: (typeof date === 'string' || typeof date === 'number') && Number.isFinite(Date.parse(date)) ? new Date(date).toISOString() : new Date().toISOString(),
|
|
name: fromName || fromEmail,
|
|
email: fromEmail,
|
|
message: [subject ? `Subject: ${subject}` : '', body ?? ''].filter(Boolean).join('\n\n'),
|
|
htmlBody: typeof htmlBody === 'string' && htmlBody.trim() ? htmlBody.trim() : null,
|
|
messageType: 'general',
|
|
subscribe: false,
|
|
archived: false,
|
|
source: 'inbound-email',
|
|
inboundTo: typeof to === 'string' ? to : '',
|
|
messageId: normalizedMessageId,
|
|
emailStatus: {
|
|
welcome: { status: 'not-applicable', lastEventAt: null, lastEventType: null, resendEmailId: null, error: null },
|
|
adminNotification: { status: 'not-applicable', lastEventAt: null, lastEventType: null, resendEmailId: null, error: null },
|
|
adminReply: { status: 'pending', lastEventAt: null, lastEventType: null, resendEmailId: null, error: null },
|
|
},
|
|
}
|
|
|
|
state.contactSubmissions.unshift(submission)
|
|
state.contactSubmissions = state.contactSubmissions.slice(0, MAX_CONTACT_SUBMISSIONS)
|
|
queueContactSubmissionsWrite()
|
|
|
|
console.log(`[inbound-email] received from ${fromEmail} — subject: ${subject ?? '(none)'}`)
|
|
res.json({ ok: true })
|
|
})
|
|
}
|