526 lines
18 KiB
JavaScript
526 lines
18 KiB
JavaScript
import { ImapFlow } from 'imapflow'
|
|
import { simpleParser } from 'mailparser'
|
|
import { CronExpressionParser } from 'cron-parser'
|
|
import { encryptSecret, decryptSecret } from './secrets.js'
|
|
import { HttpError } from './service.js'
|
|
import { now } from './db.js'
|
|
import { mailIdentity, mailFailure, retryAt } from './inbound-errors.js'
|
|
export function nextFetch(config, at = new Date()) {
|
|
if (!config.enabled) return null
|
|
if (config.schedule.mode === 'interval')
|
|
return new Date(+at + config.schedule.seconds * 1000).toISOString()
|
|
return CronExpressionParser.parse(config.schedule.cron, {
|
|
currentDate: at,
|
|
tz: config.schedule.timezone,
|
|
})
|
|
.next()
|
|
.toDate()
|
|
.toISOString()
|
|
}
|
|
function ensure(s, id) {
|
|
s.queue(id)
|
|
let row = s.get('SELECT * FROM queue_inbound WHERE queue_id=?', id)
|
|
if (!row) {
|
|
const config = {
|
|
enabled: !!process.env.IMAP_HOST,
|
|
host: process.env.IMAP_HOST || '',
|
|
port: Number(process.env.IMAP_PORT || 993),
|
|
security: 'tls',
|
|
validateCertificate: true,
|
|
username: process.env.IMAP_USER || '',
|
|
folder: 'INBOX',
|
|
onlyUnread: true,
|
|
markRead: true,
|
|
schedule: { mode: 'interval', seconds: 30, cron: '* * * * *', timezone: 'Europe/Berlin' },
|
|
}
|
|
s.run(
|
|
'INSERT INTO queue_inbound(queue_id,config,password,next_run) VALUES(?,?,?,?)',
|
|
id,
|
|
JSON.stringify(config),
|
|
process.env.IMAP_PASSWORD ? encryptSecret(process.env.IMAP_PASSWORD) : '',
|
|
config.enabled ? now() : null,
|
|
)
|
|
row = s.get('SELECT * FROM queue_inbound WHERE queue_id=?', id)
|
|
}
|
|
return row
|
|
}
|
|
export function inboundSettings(s, id) {
|
|
const r = ensure(s, id)
|
|
return {
|
|
validateCertificate: true,
|
|
...JSON.parse(r.config),
|
|
passwordSet: !!r.password,
|
|
runtime: {
|
|
nextRun: r.next_run,
|
|
lastRun: r.last_run,
|
|
lastSuccess: r.last_success,
|
|
error: r.error,
|
|
},
|
|
}
|
|
}
|
|
export function saveInbound(s, user, id, data, password) {
|
|
s.require(user, id, 'queue')
|
|
const row = ensure(s, id),
|
|
before = inboundSettings(s, id)
|
|
if (
|
|
!data ||
|
|
typeof data.enabled !== 'boolean' ||
|
|
!['tls', 'starttls', 'none'].includes(data.security) ||
|
|
(data.validateCertificate !== undefined && typeof data.validateCertificate !== 'boolean') ||
|
|
typeof data.host !== 'string' ||
|
|
typeof data.username !== 'string' ||
|
|
!Number.isInteger(Number(data.port)) ||
|
|
Number(data.port) < 1 ||
|
|
Number(data.port) > 65535 ||
|
|
typeof data.folder !== 'string' ||
|
|
!data.folder.trim() ||
|
|
data.folder.length > 200 ||
|
|
/[\r\n\0]/.test(data.folder) ||
|
|
typeof data.onlyUnread !== 'boolean' ||
|
|
typeof data.markRead !== 'boolean'
|
|
)
|
|
throw new HttpError(400, 'Gültige IMAP-Einstellungen und einen Postfachordner angeben.')
|
|
if (data.enabled && (!/^[a-z0-9][a-z0-9.:-]*$/i.test(data.host) || !data.username.trim()))
|
|
throw new HttpError(400, 'IMAP-Server und Benutzername fehlen.')
|
|
const p = data.schedule
|
|
if (
|
|
!p ||
|
|
!['interval', 'cron'].includes(p.mode) ||
|
|
!Number.isInteger(Number(p.seconds)) ||
|
|
Number(p.seconds) < 15 ||
|
|
Number(p.seconds) > 86400 ||
|
|
typeof p.cron !== 'string' ||
|
|
p.cron.length > 120 ||
|
|
typeof p.timezone !== 'string'
|
|
)
|
|
throw new HttpError(400, 'Abrufintervall muss zwischen 15 und 86.400 Sekunden liegen.')
|
|
try {
|
|
new Intl.DateTimeFormat('de', { timeZone: p.timezone }).format()
|
|
if (!p.timezone) throw Error()
|
|
if (p.mode === 'cron') {
|
|
if (p.cron.trim().split(/\s+/).length !== 5 || /[H?]/.test(p.cron)) throw Error()
|
|
CronExpressionParser.parse(p.cron, { currentDate: new Date(), tz: p.timezone }).next()
|
|
}
|
|
} catch {
|
|
throw new HttpError(
|
|
400,
|
|
'Gültigen Cron-Ausdruck mit fünf Feldern und eine IANA-Zeitzone angeben.',
|
|
)
|
|
}
|
|
if (password !== undefined && (typeof password !== 'string' || password.length > 1024))
|
|
throw new HttpError(400, 'Ungültiges IMAP-Passwort.')
|
|
if (
|
|
row.password &&
|
|
data.enabled &&
|
|
!password &&
|
|
(before.host !== data.host.trim() || before.username !== data.username.trim())
|
|
)
|
|
throw new HttpError(
|
|
400,
|
|
'Bei geändertem IMAP-Server oder Benutzer das Passwort erneut eingeben.',
|
|
)
|
|
const secret = password ? encryptSecret(password) : row.password
|
|
if (data.enabled && !secret) throw new HttpError(400, 'IMAP-Passwort erforderlich.')
|
|
const config = {
|
|
enabled: data.enabled,
|
|
host: data.host.trim(),
|
|
port: Number(data.port),
|
|
security: data.security,
|
|
validateCertificate: data.validateCertificate ?? before.validateCertificate,
|
|
username: data.username.trim(),
|
|
folder: data.folder.trim(),
|
|
onlyUnread: data.onlyUnread,
|
|
markRead: data.markRead,
|
|
schedule: {
|
|
mode: p.mode,
|
|
seconds: Number(p.seconds),
|
|
cron: p.cron.trim(),
|
|
timezone: p.timezone,
|
|
},
|
|
}
|
|
s.run(
|
|
'UPDATE queue_inbound SET config=?,password=?,next_run=?,error=NULL,revision=revision+1 WHERE queue_id=?',
|
|
JSON.stringify(config),
|
|
secret,
|
|
nextFetch(config),
|
|
id,
|
|
)
|
|
const after = inboundSettings(s, id)
|
|
s.audit(
|
|
user.id,
|
|
'IMAP und Abrufzeitplan konfiguriert',
|
|
id,
|
|
before,
|
|
{ ...after, passwordChanged: !!password },
|
|
null,
|
|
id,
|
|
)
|
|
return after
|
|
}
|
|
export function imapOptions(s, id) {
|
|
const r = ensure(s, id),
|
|
c = JSON.parse(r.config)
|
|
if (!c.enabled) throw new HttpError(400, 'IMAP-Empfang ist für diese Queue deaktiviert.')
|
|
return {
|
|
host: c.host,
|
|
port: c.port,
|
|
secure: c.security === 'tls',
|
|
doSTARTTLS: c.security === 'starttls',
|
|
tls: { rejectUnauthorized: c.validateCertificate !== false },
|
|
auth: { user: c.username, pass: decryptSecret(r.password) },
|
|
connectionTimeout: 10000,
|
|
greetingTimeout: 10000,
|
|
socketTimeout: 30000,
|
|
logger: false,
|
|
}
|
|
}
|
|
export class InboundWorker {
|
|
constructor(
|
|
s,
|
|
{ clientFactory = (options) => new ImapFlow(options), clock = () => new Date() } = {},
|
|
) {
|
|
this.s = s
|
|
this.clientFactory = clientFactory
|
|
this.clock = clock
|
|
this.running = new Set()
|
|
}
|
|
async verify(user, id) {
|
|
this.s.require(user, id, 'queue')
|
|
const c = inboundSettings(this.s, id),
|
|
client = this.clientFactory(imapOptions(this.s, id))
|
|
try {
|
|
await client.connect()
|
|
const lock = await client.getMailboxLock(c.folder)
|
|
lock.release()
|
|
await client.logout()
|
|
this.s.audit(user.id, 'IMAP-Verbindung geprüft', id, null, { success: true }, null, id)
|
|
return {
|
|
ok: true,
|
|
message:
|
|
'IMAP-Anmeldung und Postfachzugriff erfolgreich. Keine Nachrichten wurden importiert.',
|
|
}
|
|
} catch (e) {
|
|
this.s.audit(
|
|
user.id,
|
|
'IMAP-Verbindungsprüfung fehlgeschlagen',
|
|
id,
|
|
null,
|
|
{ code: String(e.code || 'unknown') },
|
|
null,
|
|
id,
|
|
)
|
|
throw new HttpError(
|
|
400,
|
|
'IMAP-Verbindung fehlgeschlagen. Server, TLS, Zugangsdaten und Ordner prüfen.',
|
|
)
|
|
} finally {
|
|
client.close()
|
|
}
|
|
}
|
|
async due() {
|
|
const jobs = []
|
|
for (const q of this.s.all('SELECT id FROM queues WHERE deleted_at IS NULL')) {
|
|
const r = ensure(this.s, q.id)
|
|
if (
|
|
JSON.parse(r.config).enabled &&
|
|
r.next_run &&
|
|
r.next_run <= this.clock().toISOString() &&
|
|
!this.running.has(q.id)
|
|
)
|
|
jobs.push(this.run(q.id).catch(() => {}))
|
|
}
|
|
await Promise.all(jobs)
|
|
}
|
|
async run(id, { actor = 'IMAP-Abrufprozess', retryFailed = false } = {}) {
|
|
if (this.running.has(id)) throw new HttpError(409, 'Für diese Queue läuft bereits ein Abruf.')
|
|
const row = ensure(this.s, id),
|
|
config = JSON.parse(row.config)
|
|
if (!config.enabled) throw new HttpError(400, 'IMAP-Empfang ist deaktiviert.')
|
|
this.running.add(id)
|
|
let client,
|
|
imported = 0,
|
|
failed = 0,
|
|
pending = 0,
|
|
flagFailed = 0,
|
|
retried = 0
|
|
const started = this.clock().toISOString()
|
|
this.s.run(
|
|
'UPDATE queue_inbound SET last_run=?,next_run=? WHERE queue_id=? AND revision=?',
|
|
started,
|
|
started,
|
|
id,
|
|
row.revision,
|
|
)
|
|
try {
|
|
client = this.clientFactory(imapOptions(this.s, id))
|
|
await client.connect()
|
|
const lock = await client.getMailboxLock(config.folder)
|
|
try {
|
|
const queue = this.s.queue(id)
|
|
const addresses = queue.addresses
|
|
.filter((a) => a.incoming)
|
|
.map((a) => a.email.toLowerCase())
|
|
.sort()
|
|
const validity = String(client.mailbox.uidValidity),
|
|
mailboxKey = JSON.stringify([
|
|
config.host,
|
|
config.port,
|
|
config.username,
|
|
config.folder,
|
|
validity,
|
|
addresses,
|
|
])
|
|
const ids =
|
|
(await client.search(config.onlyUnread ? { seen: false } : { all: true }, {
|
|
uid: true,
|
|
})) || []
|
|
if (
|
|
this.s.get('SELECT revision FROM queue_inbound WHERE queue_id=?', id).revision !==
|
|
row.revision
|
|
)
|
|
return {
|
|
ok: false,
|
|
imported: 0,
|
|
failed: 0,
|
|
message: 'Abruf wegen geänderter Mail-Einstellungen beendet.',
|
|
}
|
|
const storedReceipts = this.s.all(
|
|
'SELECT uid,outcome FROM inbound_receipts WHERE queue_id=? AND mailbox_key=?',
|
|
id,
|
|
mailboxKey,
|
|
)
|
|
const receipts = new Set(storedReceipts.map((r) => r.uid))
|
|
const processed = new Set(
|
|
storedReceipts.filter((r) => r.outcome !== 'skipped').map((r) => r.uid),
|
|
)
|
|
const known = ids.filter((uid) => processed.has(uid))
|
|
const markRead = async (uids, identity = {}) => {
|
|
if (!config.markRead) return
|
|
try {
|
|
await client.messageFlagsAdd(uids, ['\\Seen'], { uid: true })
|
|
} catch (e) {
|
|
flagFailed++
|
|
this.s.audit(
|
|
actor,
|
|
'Gelesen-Markierung fehlgeschlagen',
|
|
id,
|
|
null,
|
|
{
|
|
...mailFailure(e, 'markRead'),
|
|
...identity,
|
|
queue: queue.name,
|
|
folder: config.folder,
|
|
uid: uids,
|
|
uidValidity: validity,
|
|
continuation:
|
|
'Bereits verarbeitet; kein erneuter Ticketimport. Markierung wird beim nächsten Abruf erneut versucht.',
|
|
},
|
|
null,
|
|
id,
|
|
)
|
|
}
|
|
}
|
|
if (known.length) await markRead(known.slice(0, 100))
|
|
const failures = new Map(
|
|
this.s
|
|
.all(
|
|
'SELECT uid,attempts,next_retry FROM inbound_failures WHERE queue_id=? AND mailbox_key=?',
|
|
id,
|
|
mailboxKey,
|
|
)
|
|
.map((f) => [f.uid, f]),
|
|
)
|
|
const fresh = ids.filter((uid) => !receipts.has(uid) && !failures.has(uid)).slice(0, 100)
|
|
const retries = ids
|
|
.filter(
|
|
(uid) =>
|
|
!receipts.has(uid) &&
|
|
failures.has(uid) &&
|
|
(retryFailed || failures.get(uid).next_retry <= this.clock().toISOString()),
|
|
)
|
|
.sort(
|
|
(a, b) => failures.get(a).next_retry.localeCompare(failures.get(b).next_retry) || a - b,
|
|
)
|
|
.slice(0, 10)
|
|
for (const uid of [...fresh, ...retries]) {
|
|
if (
|
|
this.s.get('SELECT revision FROM queue_inbound WHERE queue_id=?', id).revision !==
|
|
row.revision
|
|
)
|
|
break
|
|
let meta,
|
|
parsed,
|
|
size,
|
|
stage = 'metadata'
|
|
if (failures.has(uid)) retried++
|
|
try {
|
|
meta = await client.fetchOne(uid, { size: true, envelope: true }, { uid: true })
|
|
if (!meta) continue
|
|
size = meta.size
|
|
if (meta.size > 20 * 1024 * 1024) throw Error('MessageTooLarge')
|
|
stage = 'download'
|
|
const message = await client.fetchOne(uid, { source: true }, { uid: true })
|
|
if (!message) continue
|
|
size = message.source.length
|
|
if (message.source.length > 20 * 1024 * 1024) throw Error('MessageTooLarge')
|
|
stage = 'parse'
|
|
const p = await simpleParser(message.source, { keepCidLinks: true })
|
|
parsed = p
|
|
const to = [...(p.to?.value || []), ...(p.cc?.value || [])]
|
|
.map((x) => x.address)
|
|
.filter(Boolean)
|
|
if (
|
|
this.s.get('SELECT revision FROM queue_inbound WHERE queue_id=?', id).revision !==
|
|
row.revision
|
|
)
|
|
break
|
|
if (!to.some((a) => addresses.includes(a.toLowerCase()))) {
|
|
this.s.run(
|
|
"INSERT OR IGNORE INTO inbound_receipts VALUES(?,?,?,'skipped')",
|
|
id,
|
|
mailboxKey,
|
|
uid,
|
|
)
|
|
this.s.run(
|
|
'DELETE FROM inbound_failures WHERE queue_id=? AND mailbox_key=? AND uid=?',
|
|
id,
|
|
mailboxKey,
|
|
uid,
|
|
)
|
|
failures.delete(uid)
|
|
continue
|
|
}
|
|
const data = {
|
|
messageId: p.messageId,
|
|
from: p.from?.value[0]?.address,
|
|
name: p.from?.value[0]?.name,
|
|
to,
|
|
subject: p.subject,
|
|
body: p.text || '(HTML-Nachricht ohne Textalternative)',
|
|
html: typeof p.html === 'string' ? p.html : null,
|
|
source: Buffer.from(message.source),
|
|
inReplyTo: p.inReplyTo,
|
|
references: typeof p.references === 'string' ? [p.references] : p.references || [],
|
|
autoSubmitted: p.headers.get('auto-submitted'),
|
|
precedence: p.headers.get('precedence'),
|
|
attachments: p.attachments.map((a) => ({
|
|
name: a.filename,
|
|
mime: a.contentType,
|
|
content: a.content.toString('base64'),
|
|
contentId: a.contentId || a.cid,
|
|
})),
|
|
}
|
|
stage = 'import'
|
|
const result = this.s.tx(() => {
|
|
const r = this.s.ingest(data, id)
|
|
this.s.run(
|
|
"INSERT OR IGNORE INTO inbound_receipts VALUES(?,?,?,'imported')",
|
|
id,
|
|
mailboxKey,
|
|
uid,
|
|
)
|
|
this.s.run(
|
|
'DELETE FROM inbound_failures WHERE queue_id=? AND mailbox_key=? AND uid=?',
|
|
id,
|
|
mailboxKey,
|
|
uid,
|
|
)
|
|
return r
|
|
})
|
|
failures.delete(uid)
|
|
if (!result.ignored && !result.duplicate) imported++
|
|
await markRead(uid, mailIdentity(meta.envelope, parsed, size))
|
|
} catch (e) {
|
|
failed++
|
|
const attempts = (failures.get(uid)?.attempts || 0) + 1
|
|
const nextRetry = retryAt(attempts, this.clock())
|
|
this.s.run(
|
|
`INSERT INTO inbound_failures VALUES(?,?,?,?,?) ON CONFLICT(queue_id,mailbox_key,uid)
|
|
DO UPDATE SET attempts=excluded.attempts,next_retry=excluded.next_retry`,
|
|
id,
|
|
mailboxKey,
|
|
uid,
|
|
attempts,
|
|
nextRetry,
|
|
)
|
|
failures.set(uid, { attempts, next_retry: nextRetry })
|
|
this.s.audit(
|
|
actor,
|
|
'Nachricht konnte nicht importiert werden',
|
|
`${id}:${uid}`,
|
|
null,
|
|
{
|
|
...mailIdentity(meta?.envelope, parsed, size),
|
|
...mailFailure(e, stage, parsed),
|
|
queue: queue.name,
|
|
folder: config.folder,
|
|
uid,
|
|
uidValidity: validity,
|
|
attempts,
|
|
nextRetry,
|
|
continuation:
|
|
'Abruf läuft mit den übrigen Nachrichten weiter. Diese Mail bleibt unverändert im Postfach und wird separat erneut versucht.',
|
|
},
|
|
null,
|
|
id,
|
|
)
|
|
}
|
|
}
|
|
pending = ids.filter((uid) => !receipts.has(uid) && failures.has(uid)).length
|
|
} finally {
|
|
lock.release()
|
|
}
|
|
await client.logout()
|
|
this.s.run(
|
|
'UPDATE queue_inbound SET last_success=?,error=?,next_run=? WHERE queue_id=? AND revision=?',
|
|
pending || flagFailed ? row.last_success : this.clock().toISOString(),
|
|
pending || flagFailed
|
|
? `${pending} Nachricht(en) warten auf erneuten Import; ${flagFailed} Fehler bei der Gelesen-Markierung. Weitere Mails werden weiter abgerufen. Systemprotokoll prüfen.`
|
|
: null,
|
|
nextFetch(config, this.clock()),
|
|
id,
|
|
row.revision,
|
|
)
|
|
this.s.audit(
|
|
actor,
|
|
'Postfach abgerufen',
|
|
id,
|
|
null,
|
|
{ imported, failed, pending, retried, flagFailed },
|
|
null,
|
|
id,
|
|
)
|
|
return {
|
|
ok: !pending && !flagFailed,
|
|
imported,
|
|
failed,
|
|
pending,
|
|
retried,
|
|
flagFailed,
|
|
message: `Abruf abgeschlossen: ${imported} neue Nachricht(en), ${failed} Importfehler, ${pending} zur Wiederholung vorgemerkt, ${flagFailed} Fehler bei der Gelesen-Markierung. Weitere Nachrichten werden nach Zeitplan abgerufen.`,
|
|
}
|
|
} catch (e) {
|
|
this.s.run(
|
|
'UPDATE queue_inbound SET error=?,next_run=? WHERE queue_id=? AND revision=?',
|
|
'Abruf fehlgeschlagen. Zugangsdaten und Ordner prüfen.',
|
|
nextFetch(config, this.clock()),
|
|
id,
|
|
row.revision,
|
|
)
|
|
this.s.audit(
|
|
actor,
|
|
'Postfachabruf fehlgeschlagen',
|
|
id,
|
|
null,
|
|
{ ...mailFailure(e, 'connection'), folder: config.folder, imported, failed },
|
|
null,
|
|
id,
|
|
)
|
|
throw new HttpError(400, 'Postfachabruf fehlgeschlagen. Zugangsdaten und Ordner prüfen.')
|
|
} finally {
|
|
this.running.delete(id)
|
|
client?.close()
|
|
}
|
|
}
|
|
}
|