Add email threading, snooze, bulk actions, scheduled send, stars, and attachments; v1.1.21
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
@@ -439,8 +439,14 @@ export function register(app) {
|
||||
|
||||
const patch = {}
|
||||
if (typeof req.body?.archived === 'boolean') patch.archived = req.body.archived
|
||||
if (typeof req.body?.starred === 'boolean') patch.starred = req.body.starred
|
||||
if (typeof req.body?.name === 'string') patch.name = req.body.name.trim().slice(0, 200)
|
||||
if (typeof req.body?.notes === 'string') patch.notes = req.body.notes.trim().slice(0, 2000)
|
||||
if ('snoozedUntil' in (req.body ?? {})) {
|
||||
const v = req.body.snoozedUntil
|
||||
patch.snoozedUntil = v === null ? null : (typeof v === 'string' && !isNaN(Date.parse(v)) ? v : undefined)
|
||||
if (patch.snoozedUntil === undefined) delete patch.snoozedUntil
|
||||
}
|
||||
|
||||
let found = false
|
||||
state.contactSubmissions = state.contactSubmissions.map(item => {
|
||||
@@ -473,6 +479,46 @@ export function register(app) {
|
||||
res.json({ ok: true })
|
||||
})
|
||||
|
||||
app.post('/api/admin-contact-submissions/bulk', requireAdminAuth, (req, res) => {
|
||||
const { ids, action } = req.body ?? {}
|
||||
if (!Array.isArray(ids) || !['archive', 'unarchive', 'delete', 'star', 'unstar'].includes(action)) {
|
||||
res.status(400).json({ message: 'Invalid bulk action.' }); return
|
||||
}
|
||||
const idSet = new Set(ids.filter(id => typeof id === 'string'))
|
||||
if (idSet.size === 0) { res.json({ ok: true, affected: 0 }); return }
|
||||
|
||||
let affected = 0
|
||||
if (action === 'delete') {
|
||||
const before = state.contactSubmissions.length
|
||||
state.contactSubmissions = state.contactSubmissions.filter(s => !idSet.has(s.id))
|
||||
affected = before - state.contactSubmissions.length
|
||||
} else {
|
||||
const patch = action === 'archive' ? { archived: true }
|
||||
: action === 'unarchive' ? { archived: false }
|
||||
: action === 'star' ? { starred: true }
|
||||
: { starred: false }
|
||||
state.contactSubmissions = state.contactSubmissions.map(s => {
|
||||
if (!idSet.has(s.id)) return s
|
||||
affected++
|
||||
return { ...s, ...patch }
|
||||
})
|
||||
}
|
||||
queueContactSubmissionsWrite()
|
||||
res.json({ ok: true, affected })
|
||||
})
|
||||
|
||||
app.get('/api/admin-contact-submissions/:id/attachments/:attachmentId', requireAdminAuth, (req, res) => {
|
||||
const { id, attachmentId } = req.params
|
||||
const submission = state.contactSubmissions.find(s => s.id === id)
|
||||
if (!submission) { res.status(404).send('Not found.'); return }
|
||||
const attachment = (submission.attachments ?? []).find(a => a.id === attachmentId)
|
||||
if (!attachment) { res.status(404).send('Attachment not found.'); return }
|
||||
const safe = attachment.filename.replace(/[^\w.\-]/g, '_')
|
||||
res.setHeader('Content-Disposition', `attachment; filename="${safe}"`)
|
||||
res.setHeader('Content-Type', attachment.contentType || 'application/octet-stream')
|
||||
res.send(Buffer.from(attachment.data, 'base64'))
|
||||
})
|
||||
|
||||
app.get('/api/admin-reply-config', requireAdminAuth, (_req, res) => {
|
||||
res.json({
|
||||
fromEmail: getResendReplyToAddress(),
|
||||
@@ -510,6 +556,7 @@ export function register(app) {
|
||||
const subject = typeof req.body?.subject === 'string' ? req.body.subject.trim() : ''
|
||||
const message = typeof req.body?.message === 'string' ? req.body.message.trim() : ''
|
||||
const requestedFrom = typeof req.body?.fromAddress === 'string' ? req.body.fromAddress.trim() : ''
|
||||
const scheduledAt = typeof req.body?.scheduledAt === 'string' && !isNaN(Date.parse(req.body.scheduledAt)) && new Date(req.body.scheduledAt) > new Date() ? req.body.scheduledAt : null
|
||||
|
||||
if (!id || typeof id !== 'string') {
|
||||
res.status(400).json({ message: 'Invalid submission id.' }); return
|
||||
@@ -546,6 +593,7 @@ export function register(app) {
|
||||
to: [submission.email],
|
||||
subject,
|
||||
replyTo: replyToAddress,
|
||||
...(scheduledAt ? { scheduledAt } : {}),
|
||||
tags: [
|
||||
{ name: 'flow', value: 'admin-reply' },
|
||||
{ name: 'message_type', value: submission.messageType ?? 'general' },
|
||||
@@ -574,11 +622,12 @@ export function register(app) {
|
||||
subject,
|
||||
preview: message.slice(0, 500),
|
||||
sentAt: new Date().toISOString(),
|
||||
scheduledAt: scheduledAt ?? null,
|
||||
})
|
||||
state.replyHistory = state.replyHistory.slice(0, 500)
|
||||
queueReplyHistoryWrite()
|
||||
|
||||
res.json({ ok: true })
|
||||
res.json({ ok: true, scheduled: Boolean(scheduledAt), scheduledAt: scheduledAt ?? null })
|
||||
} catch (err) {
|
||||
if (typeof req.params?.id === 'string' && req.params.id.trim()) {
|
||||
upsertContactEmailStatus(req.params.id.trim(), 'adminReply', {
|
||||
@@ -602,6 +651,7 @@ export function register(app) {
|
||||
const subject = typeof req.body?.subject === 'string' ? req.body.subject.trim() : ''
|
||||
const message = typeof req.body?.message === 'string' ? req.body.message.trim() : ''
|
||||
const requestedFrom = typeof req.body?.fromAddress === 'string' ? req.body.fromAddress.trim() : ''
|
||||
const scheduledAt = typeof req.body?.scheduledAt === 'string' && !isNaN(Date.parse(req.body.scheduledAt)) && new Date(req.body.scheduledAt) > new Date() ? req.body.scheduledAt : null
|
||||
|
||||
if (!to || !/^[a-zA-Z0-9._%+\-]{1,64}@[a-zA-Z0-9.\-]{1,253}\.[a-zA-Z]{2,}$/.test(to)) {
|
||||
res.status(400).json({ message: 'A valid recipient email address is required.' }); return
|
||||
@@ -630,6 +680,7 @@ export function register(app) {
|
||||
to: [to],
|
||||
subject,
|
||||
replyTo: replyToAddress,
|
||||
...(scheduledAt ? { scheduledAt } : {}),
|
||||
tags: [{ name: 'flow', value: 'admin-reply' }],
|
||||
text,
|
||||
html,
|
||||
@@ -645,11 +696,12 @@ export function register(app) {
|
||||
subject,
|
||||
preview: message.slice(0, 500),
|
||||
sentAt: new Date().toISOString(),
|
||||
scheduledAt: scheduledAt ?? null,
|
||||
})
|
||||
state.replyHistory = state.replyHistory.slice(0, 500)
|
||||
queueReplyHistoryWrite()
|
||||
|
||||
res.json({ ok: true })
|
||||
res.json({ ok: true, scheduled: Boolean(scheduledAt), scheduledAt: scheduledAt ?? null })
|
||||
} catch (err) {
|
||||
console.error('[admin-compose] send error:', err)
|
||||
res.status(500).json({ message: 'Failed to send email.' })
|
||||
|
||||
@@ -3,13 +3,13 @@ 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]+>$/
|
||||
const MAX_ATTACHMENT_BYTES = 5 * 1024 * 1024 // 5 MB total per email
|
||||
|
||||
function decodeHtmlBody(raw) {
|
||||
if (typeof raw !== 'string' || !raw.trim()) return null
|
||||
const s = raw.trim()
|
||||
if (s.startsWith('<')) return s // already plain HTML
|
||||
if (s.startsWith('<')) return s
|
||||
try {
|
||||
const decoded = Buffer.from(s.replace(/\s+/g, ''), 'base64').toString('utf8')
|
||||
return decoded.trimStart().startsWith('<') ? decoded : s
|
||||
@@ -18,6 +18,50 @@ function decodeHtmlBody(raw) {
|
||||
}
|
||||
}
|
||||
|
||||
function normalizeSubject(subject) {
|
||||
return (subject ?? '').toLowerCase().replace(/^(re|fwd?):\s*/i, '').trim()
|
||||
}
|
||||
|
||||
function resolveThreadId(fromEmail, normalizedSubject, inReplyTo) {
|
||||
// 1. Exact In-Reply-To match
|
||||
if (inReplyTo) {
|
||||
const parent = state.contactSubmissions.find(s => s.messageId === inReplyTo)
|
||||
if (parent?.threadId) return parent.threadId
|
||||
}
|
||||
// 2. Same sender + matching subject within 30 days
|
||||
const cutoff = Date.now() - 30 * 24 * 60 * 60 * 1000
|
||||
const match = state.contactSubmissions.find(s =>
|
||||
s.email === fromEmail &&
|
||||
normalizedSubject &&
|
||||
normalizeSubject(s.message.match(/^Subject:\s*(.+)/m)?.[1] ?? '') === normalizedSubject &&
|
||||
new Date(s.submittedAt).getTime() > cutoff,
|
||||
)
|
||||
if (match?.threadId) return match.threadId
|
||||
// 3. New thread
|
||||
return randomUUID()
|
||||
}
|
||||
|
||||
function parseAttachments(raw) {
|
||||
if (!Array.isArray(raw)) return []
|
||||
let totalBytes = 0
|
||||
const out = []
|
||||
for (const a of raw.slice(0, 10)) {
|
||||
if (!a || typeof a.filename !== 'string') continue
|
||||
const dataStr = typeof a.content === 'string' ? a.content : ''
|
||||
const size = typeof a.size === 'number' ? a.size : Math.floor(dataStr.length * 0.75)
|
||||
if (totalBytes + size > MAX_ATTACHMENT_BYTES) continue
|
||||
totalBytes += size
|
||||
out.push({
|
||||
id: randomUUID(),
|
||||
filename: a.filename.slice(0, 255),
|
||||
contentType: typeof a.contentType === 'string' ? a.contentType : 'application/octet-stream',
|
||||
size,
|
||||
data: dataStr,
|
||||
})
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
export function register(app) {
|
||||
app.post('/api/inbound-email', (req, res) => {
|
||||
const secret = process.env.INBOUND_EMAIL_SECRET
|
||||
@@ -32,20 +76,19 @@ export function register(app) {
|
||||
res.status(401).json({ message: 'Unauthorized.' }); return
|
||||
}
|
||||
|
||||
const { from, to, subject, body, htmlBody, date, messageId, source } = req.body ?? {}
|
||||
const { from, to, subject, body, htmlBody, date, messageId, inReplyTo, attachments: rawAttachments, 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() : ''
|
||||
const normalizedInReplyTo = typeof inReplyTo === 'string' && MESSAGE_ID_RE.test(inReplyTo.trim()) ? inReplyTo.trim() : ''
|
||||
|
||||
// Deduplicate by messageId if provided
|
||||
if (normalizedMessageId) {
|
||||
const exists = state.contactSubmissions.some(s => s.messageId === normalizedMessageId)
|
||||
if (exists) {
|
||||
@@ -53,19 +96,26 @@ export function register(app) {
|
||||
}
|
||||
}
|
||||
|
||||
const subjectStr = typeof subject === 'string' ? subject.trim() : ''
|
||||
const threadId = resolveThreadId(fromEmail, normalizeSubject(subjectStr), normalizedInReplyTo)
|
||||
|
||||
const submission = {
|
||||
id: randomUUID(),
|
||||
threadId,
|
||||
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'),
|
||||
message: [subjectStr ? `Subject: ${subjectStr}` : '', body ?? ''].filter(Boolean).join('\n\n'),
|
||||
htmlBody: decodeHtmlBody(htmlBody),
|
||||
messageType: 'general',
|
||||
subscribe: false,
|
||||
archived: false,
|
||||
starred: false,
|
||||
snoozedUntil: null,
|
||||
source: 'inbound-email',
|
||||
inboundTo: typeof to === 'string' ? to : '',
|
||||
messageId: normalizedMessageId,
|
||||
attachments: parseAttachments(rawAttachments),
|
||||
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 },
|
||||
@@ -77,7 +127,7 @@ export function register(app) {
|
||||
state.contactSubmissions = state.contactSubmissions.slice(0, MAX_CONTACT_SUBMISSIONS)
|
||||
queueContactSubmissionsWrite()
|
||||
|
||||
console.log(`[inbound-email] received from ${fromEmail} — subject: ${subject ?? '(none)'}`)
|
||||
console.log(`[inbound-email] received from ${fromEmail} — subject: ${subjectStr || '(none)'} — thread: ${threadId}`)
|
||||
res.json({ ok: true })
|
||||
})
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user