286 lines
9.6 KiB
JavaScript
286 lines
9.6 KiB
JavaScript
import nodemailer from 'nodemailer'
|
|
import { encryptSecret, decryptSecret } from './secrets.js'
|
|
import { HttpError } from './service.js'
|
|
import { uid, now } from './db.js'
|
|
import { inboundSettings, saveInbound } from './inbound.js'
|
|
import { composeContent } from './content.js'
|
|
import { signatureContext } from './signature-placeholders.js'
|
|
export const defaultAcknowledgement = {
|
|
enabled: false,
|
|
subject: 'Ihre Anfrage {ticketnummer} ist eingegangen',
|
|
body: 'Guten Tag {kundenname},\n\nvielen Dank für Ihre Nachricht. Wir haben Ihre Anfrage erhalten und bearbeiten sie schnellstmöglich.\n\nIhre Ticketnummer: {ticketnummer}',
|
|
includeSignature: true,
|
|
}
|
|
export function mailSettings(s, id) {
|
|
const row = s.get('SELECT * FROM queue_mail WHERE queue_id=?', id)
|
|
const smtp = row
|
|
? JSON.parse(row.smtp)
|
|
: {
|
|
mode:
|
|
process.env.MAIL_MODE === 'smtp'
|
|
? 'legacy'
|
|
: process.env.NODE_ENV === 'production' || process.env.MAIL_MODE === 'disabled'
|
|
? 'disabled'
|
|
: 'development',
|
|
host: '',
|
|
port: 465,
|
|
security: 'tls',
|
|
username: '',
|
|
}
|
|
if (process.env.NODE_ENV === 'production' && smtp.mode === 'development') smtp.mode = 'disabled'
|
|
return {
|
|
allowDevelopment: process.env.NODE_ENV !== 'production',
|
|
imap: inboundSettings(s, id),
|
|
smtp,
|
|
passwordSet: !!row?.password,
|
|
acknowledgement: row ? JSON.parse(row.acknowledgement) : { ...defaultAcknowledgement },
|
|
}
|
|
}
|
|
export function readMailSettings(s, user, id) {
|
|
s.require(user, id, 'queue')
|
|
s.queue(id)
|
|
return mailSettings(s, id)
|
|
}
|
|
export function saveMailSettings(s, user, id, data) {
|
|
return s.tx(() => {
|
|
s.require(user, id, 'queue')
|
|
s.queue(id)
|
|
const before = mailSettings(s, id),
|
|
smtp = data.smtp,
|
|
ack = data.acknowledgement || before.acknowledgement
|
|
if (
|
|
!smtp ||
|
|
!['smtp', 'development', 'legacy', 'disabled'].includes(smtp.mode) ||
|
|
!['tls', 'starttls'].includes(smtp.security) ||
|
|
!Number.isInteger(Number(smtp.port)) ||
|
|
Number(smtp.port) < 1 ||
|
|
Number(smtp.port) > 65535
|
|
)
|
|
throw new HttpError(400, 'Gültigen Versandmodus, Port und TLS-Modus auswählen.')
|
|
if (process.env.NODE_ENV === 'production' && smtp.mode === 'development')
|
|
throw new HttpError(400, 'Der Entwicklungsadapter ist in Produktion deaktiviert.')
|
|
if (smtp.mode === 'legacy' && before.smtp.mode !== 'legacy')
|
|
throw new HttpError(400, 'Globale SMTP-Konfiguration ist nicht verfügbar.')
|
|
if (
|
|
smtp.mode === 'smtp' &&
|
|
(!/^[a-z0-9][a-z0-9.:-]*$/i.test(smtp.host || '') || !smtp.username?.trim())
|
|
)
|
|
throw new HttpError(400, 'SMTP-Server und Benutzername sind erforderlich.')
|
|
if (
|
|
typeof ack.enabled !== 'boolean' ||
|
|
typeof ack.includeSignature !== 'boolean' ||
|
|
typeof ack.subject !== 'string' ||
|
|
typeof ack.body !== 'string' ||
|
|
!ack.subject.trim() ||
|
|
!ack.body.trim() ||
|
|
ack.subject.length > 500 ||
|
|
ack.body.length > 20000 ||
|
|
/[\r\n]/.test(ack.subject)
|
|
)
|
|
throw new HttpError(
|
|
400,
|
|
'Betreff und Text der Eingangsbestätigung ausfüllen (max. 500 / 20.000 Zeichen).',
|
|
)
|
|
const tokens = (ack.subject + ' ' + ack.body).match(/\{[^{}]+\}/g) || []
|
|
if (tokens.some((t) => !['{ticketnummer}', '{betreff}', '{kundenname}', '{queue}'].includes(t)))
|
|
throw new HttpError(400, 'Unbekannter Platzhalter in der Eingangsbestätigung.')
|
|
if (
|
|
data.password !== undefined &&
|
|
(typeof data.password !== 'string' || data.password.length > 1024)
|
|
)
|
|
throw new HttpError(400, 'Ungültiges SMTP-Passwort.')
|
|
const old = s.get('SELECT password FROM queue_mail WHERE queue_id=?', id)
|
|
if (
|
|
old?.password &&
|
|
smtp.mode === 'smtp' &&
|
|
!data.password &&
|
|
(smtp.host.trim() !== before.smtp.host || smtp.username.trim() !== before.smtp.username)
|
|
)
|
|
throw new HttpError(
|
|
400,
|
|
'Bei einem anderen SMTP-Server oder Benutzernamen das Passwort erneut eingeben.',
|
|
)
|
|
let password = data.clearPassword ? '' : old?.password || ''
|
|
if (data.password) password = encryptSecret(data.password)
|
|
if (smtp.mode === 'smtp' && !password)
|
|
throw new HttpError(400, 'Ein SMTP-Passwort ist erforderlich.')
|
|
const clean = {
|
|
mode: smtp.mode,
|
|
host: String(smtp.host || '').trim(),
|
|
port: Number(smtp.port),
|
|
security: smtp.security,
|
|
username: String(smtp.username || '').trim(),
|
|
}
|
|
const cleanAck = {
|
|
enabled: ack.enabled,
|
|
subject: ack.subject.trim(),
|
|
body: ack.body.trim(),
|
|
includeSignature: ack.includeSignature,
|
|
}
|
|
s.run(
|
|
'INSERT INTO queue_mail VALUES(?,?,?,?) ON CONFLICT(queue_id) DO UPDATE SET smtp=excluded.smtp,password=excluded.password,acknowledgement=excluded.acknowledgement',
|
|
id,
|
|
JSON.stringify(clean),
|
|
password,
|
|
JSON.stringify(cleanAck),
|
|
)
|
|
if (data.imap) saveInbound(s, user, id, data.imap, data.imapPassword)
|
|
const after = mailSettings(s, id)
|
|
s.audit(
|
|
user.id,
|
|
'SMTP und Eingangsbestätigung konfiguriert',
|
|
id,
|
|
before,
|
|
{ ...after, passwordChanged: !!data.password || !!data.clearPassword },
|
|
null,
|
|
id,
|
|
)
|
|
return after
|
|
})
|
|
}
|
|
export function smtpTransport(s, id, factory = nodemailer.createTransport) {
|
|
const row = s.get('SELECT * FROM queue_mail WHERE queue_id=?', id)
|
|
const smtp = row ? JSON.parse(row.smtp) : null
|
|
if (
|
|
smtp?.mode === 'disabled' ||
|
|
(!smtp &&
|
|
process.env.MAIL_MODE !== 'smtp' &&
|
|
(process.env.NODE_ENV === 'production' || process.env.MAIL_MODE === 'disabled')) ||
|
|
(process.env.NODE_ENV === 'production' && smtp?.mode === 'development')
|
|
)
|
|
throw new HttpError(
|
|
409,
|
|
'SMTP-Versand ist deaktiviert. Mail-Einstellungen der Queue konfigurieren.',
|
|
)
|
|
if (smtp?.mode === 'development' || (!smtp && process.env.MAIL_MODE !== 'smtp')) return null
|
|
if (
|
|
(!smtp || smtp.mode === 'legacy') &&
|
|
(!process.env.SMTP_HOST || !process.env.SMTP_USER || !process.env.SMTP_PASSWORD)
|
|
)
|
|
throw new HttpError(
|
|
409,
|
|
'Globale SMTP-Konfiguration ist unvollständig. SMTP für die Queue einrichten.',
|
|
)
|
|
if (!smtp || smtp.mode === 'legacy')
|
|
return factory({
|
|
host: process.env.SMTP_HOST,
|
|
port: Number(process.env.SMTP_PORT || 465),
|
|
secure: process.env.SMTP_TLS !== 'false',
|
|
requireTLS: process.env.SMTP_TLS === 'false',
|
|
auth: { user: process.env.SMTP_USER, pass: process.env.SMTP_PASSWORD },
|
|
connectionTimeout: 10000,
|
|
greetingTimeout: 10000,
|
|
socketTimeout: 30000,
|
|
disableFileAccess: true,
|
|
disableUrlAccess: true,
|
|
})
|
|
return factory({
|
|
host: smtp.host,
|
|
port: smtp.port,
|
|
secure: smtp.security === 'tls',
|
|
requireTLS: smtp.security === 'starttls',
|
|
auth: { user: smtp.username, pass: decryptSecret(row.password) },
|
|
connectionTimeout: 10000,
|
|
greetingTimeout: 10000,
|
|
socketTimeout: 30000,
|
|
disableFileAccess: true,
|
|
disableUrlAccess: true,
|
|
})
|
|
}
|
|
export async function verifySmtp(s, user, id) {
|
|
s.require(user, id, 'queue')
|
|
s.queue(id)
|
|
const transport = smtpTransport(s, id)
|
|
if (!transport) throw new HttpError(400, 'Für diese Queue ist der Entwicklungsadapter aktiv.')
|
|
try {
|
|
await transport.verify()
|
|
s.audit(user.id, 'SMTP-Verbindung geprüft', id, null, { success: true }, null, id)
|
|
return {
|
|
ok: true,
|
|
message: 'Verbindung und Anmeldung erfolgreich. Es wurde keine E-Mail gesendet.',
|
|
}
|
|
} catch (e) {
|
|
s.audit(
|
|
user.id,
|
|
'SMTP-Verbindungsprüfung fehlgeschlagen',
|
|
id,
|
|
null,
|
|
{ success: false, code: String(e.code || 'unknown') },
|
|
null,
|
|
id,
|
|
)
|
|
throw new HttpError(
|
|
400,
|
|
'SMTP-Verbindung fehlgeschlagen. Server, Port, TLS-Modus und Zugangsdaten prüfen.',
|
|
)
|
|
} finally {
|
|
transport.close?.()
|
|
}
|
|
}
|
|
export function acknowledge(s, t, incoming) {
|
|
const q = s.queue(t.queue_id),
|
|
config = mailSettings(s, q.id).acknowledgement
|
|
if (!config.enabled) return
|
|
const sender = q.addresses.find((a) => a.outgoing && a.default)
|
|
if (!sender) throw new HttpError(409, 'Standardabsender für die Eingangsbestätigung fehlt.')
|
|
const values = {
|
|
ticketnummer: `SYN-${String(t.id).padStart(5, '0')}`,
|
|
betreff: t.subject,
|
|
kundenname: t.customer_name,
|
|
queue: q.name,
|
|
}
|
|
const render = (v) =>
|
|
v.replace(/\{(ticketnummer|betreff|kundenname|queue)\}/g, (_, k) => values[k])
|
|
const signature = config.includeSignature ? q.signatures.find((x) => x.default) : null
|
|
const content = composeContent(
|
|
render(config.body),
|
|
signature,
|
|
signatureContext(s, null, q, t, sender.email),
|
|
)
|
|
const body = content.text
|
|
const subject = render(config.subject)
|
|
.replace(/[\r\n]/g, ' ')
|
|
.slice(0, 998),
|
|
messageId = `<ack-${t.id}@syncova.local>`,
|
|
id = uid()
|
|
s.run(
|
|
'INSERT INTO messages VALUES(?,?,?,?,?,?,?,?,?,?)',
|
|
id,
|
|
t.id,
|
|
'outgoing',
|
|
sender.email,
|
|
t.customer,
|
|
body,
|
|
messageId,
|
|
JSON.stringify([incoming.messageId]),
|
|
now(),
|
|
'queued',
|
|
)
|
|
s.run(
|
|
'INSERT INTO outbox(id,message_id,payload,next_at) VALUES(?,?,?,?)',
|
|
uid(),
|
|
id,
|
|
JSON.stringify({
|
|
from: sender.email,
|
|
to: t.customer,
|
|
subject,
|
|
text: body,
|
|
...(content.html ? { html: content.html } : {}),
|
|
messageId,
|
|
inReplyTo: incoming.messageId,
|
|
references: [incoming.messageId],
|
|
}),
|
|
now(),
|
|
)
|
|
if (content.html) s.run('INSERT INTO message_html VALUES(?,?)', id, content.html)
|
|
s.audit(
|
|
'Eingangsbestätigung',
|
|
'Automatische Eingangsbestätigung vorgemerkt',
|
|
id,
|
|
null,
|
|
{ from: sender.email, messageId },
|
|
t.id,
|
|
t.queue_id,
|
|
)
|
|
}
|