411 lines
13 KiB
JavaScript
411 lines
13 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'
|
|
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',
|
|
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 {
|
|
...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'].includes(data.security) ||
|
|
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,
|
|
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',
|
|
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' } = {}) {
|
|
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
|
|
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 addresses = this.s
|
|
.queue(id)
|
|
.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))
|
|
if (config.markRead && known.length)
|
|
await client.messageFlagsAdd(known.slice(0, 100), ['\\Seen'], { uid: true })
|
|
for (const uid of ids.filter((uid) => !receipts.has(uid)).slice(0, 100)) {
|
|
if (
|
|
this.s.get('SELECT revision FROM queue_inbound WHERE queue_id=?', id).revision !==
|
|
row.revision
|
|
)
|
|
break
|
|
try {
|
|
const meta = await client.fetchOne(uid, { size: true }, { uid: true })
|
|
if (!meta) continue
|
|
if (meta.size > 20 * 1024 * 1024) throw Error('MessageTooLarge')
|
|
const message = await client.fetchOne(uid, { source: true }, { uid: true })
|
|
if (!message) continue
|
|
if (message.source.length > 20 * 1024 * 1024) throw Error('MessageTooLarge')
|
|
const p = await simpleParser(message.source, { keepCidLinks: true })
|
|
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,
|
|
)
|
|
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,
|
|
})),
|
|
}
|
|
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,
|
|
)
|
|
return r
|
|
})
|
|
if (!result.ignored && !result.duplicate) imported++
|
|
if (config.markRead) await client.messageFlagsAdd(uid, ['\\Seen'], { uid: true })
|
|
} catch (e) {
|
|
failed++
|
|
this.s.audit(
|
|
actor,
|
|
'Nachricht konnte nicht importiert werden',
|
|
`${id}:${uid}`,
|
|
null,
|
|
{ code: String(e.code || e.name || 'Error') },
|
|
null,
|
|
id,
|
|
)
|
|
}
|
|
}
|
|
} finally {
|
|
lock.release()
|
|
}
|
|
await client.logout()
|
|
this.s.run(
|
|
'UPDATE queue_inbound SET last_success=?,error=?,next_run=? WHERE queue_id=? AND revision=?',
|
|
failed ? row.last_success : this.clock().toISOString(),
|
|
failed
|
|
? `${failed} Nachricht(en) konnten nicht verarbeitet werden. Systemprotokoll prüfen.`
|
|
: null,
|
|
nextFetch(config, this.clock()),
|
|
id,
|
|
row.revision,
|
|
)
|
|
this.s.audit(actor, 'Postfach abgerufen', id, null, { imported, failed }, null, id)
|
|
return {
|
|
ok: !failed,
|
|
imported,
|
|
failed,
|
|
message: `Abruf abgeschlossen: ${imported} neue Nachricht(en), ${failed} Fehler.`,
|
|
}
|
|
} 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,
|
|
{ code: String(e.code || e.name || 'Error') },
|
|
null,
|
|
id,
|
|
)
|
|
throw new HttpError(400, 'Postfachabruf fehlgeschlagen. Zugangsdaten und Ordner prüfen.')
|
|
} finally {
|
|
this.running.delete(id)
|
|
client?.close()
|
|
}
|
|
}
|
|
}
|