317 lines
13 KiB
JavaScript
317 lines
13 KiB
JavaScript
import express from 'express'
|
|
import { randomBytes, createHash } from 'node:crypto'
|
|
import { now, verifyPassword } from './db.js'
|
|
import { Service, HttpError } from './service.js'
|
|
import { readMailSettings, saveMailSettings, verifySmtp } from './mail-config.js'
|
|
import { signatureValue } from './content.js'
|
|
import { signatureTokens, signatureContext } from './signature-placeholders.js'
|
|
import { proxyHops } from './runtime.js'
|
|
import { htmlPreviewDocument } from './html-preview.js'
|
|
export function createApp(db) {
|
|
const app = express(),
|
|
s = new Service(db)
|
|
app.disable('x-powered-by')
|
|
app.set('trust proxy', proxyHops())
|
|
app.use((req, res, next) => {
|
|
res.set({
|
|
'X-Content-Type-Options': 'nosniff',
|
|
'Referrer-Policy': 'same-origin',
|
|
'Permissions-Policy': 'camera=(), microphone=(), geolocation=()',
|
|
'Content-Security-Policy':
|
|
"default-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; connect-src 'self'; script-src 'self'; frame-src 'self'; frame-ancestors 'none'; base-uri 'none'; object-src 'none'; form-action 'self'",
|
|
})
|
|
if (process.env.NODE_ENV === 'production')
|
|
res.set('Strict-Transport-Security', 'max-age=31536000')
|
|
if (req.path.startsWith('/api')) res.set('Cache-Control', 'no-store')
|
|
if (
|
|
!['GET', 'HEAD', 'OPTIONS'].includes(req.method) &&
|
|
req.headers.origin &&
|
|
!new Set([
|
|
process.env.APP_ORIGIN || `${req.protocol}://${req.headers.host}`,
|
|
...(process.env.NODE_ENV !== 'production' && !process.env.APP_ORIGIN
|
|
? ['http://127.0.0.1:5173', 'http://localhost:5173']
|
|
: []),
|
|
]).has(req.headers.origin)
|
|
) {
|
|
return res.status(403).json({ error: 'Ungültiger Ursprung.' })
|
|
}
|
|
next()
|
|
})
|
|
app.use(express.json({ limit: '30mb' }))
|
|
app.get('/healthz', (req, res) => {
|
|
s.get('SELECT 1 ok')
|
|
res.json({ status: 'ok' })
|
|
})
|
|
const sessions = (req) => {
|
|
const raw = req.headers.cookie
|
|
?.split(';')
|
|
.map((c) => c.trim())
|
|
.find((c) => c.startsWith('syncova='))
|
|
?.slice(8)
|
|
return raw ? createHash('sha256').update(raw).digest('hex') : ''
|
|
}
|
|
const attempts = new Map()
|
|
app.post('/api/login', (req, res) => {
|
|
const key = req.ip
|
|
if (attempts.size >= 10000) {
|
|
for (const [ip, value] of attempts) if (value.until < Date.now()) attempts.delete(ip)
|
|
if (!attempts.has(key) && attempts.size >= 10000)
|
|
return res
|
|
.status(429)
|
|
.json({ error: 'Zu viele Anmeldeversuche. Bitte später erneut versuchen.' })
|
|
}
|
|
const entry = attempts.get(key) || { n: 0, until: Date.now() + 900000 }
|
|
if (entry.until < Date.now()) {
|
|
entry.n = 0
|
|
entry.until = Date.now() + 900000
|
|
}
|
|
if (entry.n >= 15)
|
|
return res
|
|
.status(429)
|
|
.json({ error: 'Zu viele Anmeldeversuche. Bitte später erneut versuchen.' })
|
|
entry.n++
|
|
attempts.set(key, entry)
|
|
if (
|
|
typeof req.body.email !== 'string' ||
|
|
typeof req.body.password !== 'string' ||
|
|
req.body.password.length > 256
|
|
)
|
|
return res.status(400).json({ error: 'Ungültige Anmeldung.' })
|
|
const u = s.get('SELECT * FROM users WHERE email=? AND active=1', req.body.email.toLowerCase())
|
|
if (!u || !verifyPassword(req.body.password, u.password))
|
|
return res.status(401).json({ error: 'E-Mail-Adresse oder Passwort falsch.' })
|
|
attempts.delete(key)
|
|
const raw = randomBytes(32).toString('hex')
|
|
s.run('DELETE FROM sessions WHERE expires<?', now())
|
|
s.run(
|
|
'INSERT INTO sessions VALUES(?,?,?)',
|
|
createHash('sha256').update(raw).digest('hex'),
|
|
u.id,
|
|
new Date(Date.now() + 43200000).toISOString(),
|
|
)
|
|
res.setHeader(
|
|
'Set-Cookie',
|
|
`syncova=${raw}; HttpOnly; SameSite=Strict; Path=/; Max-Age=43200${process.env.COOKIE_SECURE === 'true' ? '; Secure' : ''}`,
|
|
)
|
|
res.json({ ok: true })
|
|
})
|
|
app.use('/api', (req, res, next) => {
|
|
try {
|
|
const session = s.get(
|
|
'SELECT user_id FROM sessions WHERE id=? AND expires>?',
|
|
sessions(req),
|
|
now(),
|
|
)
|
|
if (!session) throw new HttpError(401, 'Bitte anmelden.')
|
|
req.user = s.user(session.user_id)
|
|
next()
|
|
} catch (e) {
|
|
next(e)
|
|
}
|
|
})
|
|
app.post('/api/logout', (req, res) => {
|
|
s.run('DELETE FROM sessions WHERE id=?', sessions(req))
|
|
res.setHeader(
|
|
'Set-Cookie',
|
|
`syncova=; HttpOnly; SameSite=Strict; Path=/; Max-Age=0${process.env.COOKIE_SECURE === 'true' ? '; Secure' : ''}`,
|
|
)
|
|
res.json({ ok: true })
|
|
})
|
|
app.get('/api/bootstrap', (req, res) => res.json(s.bootstrap(req.user)))
|
|
app.get('/api/html-preview', (req, res) => {
|
|
const preview = htmlPreviewDocument({
|
|
dark: req.query.theme === 'dark',
|
|
remoteImages: req.query.images === '1',
|
|
})
|
|
res.set({
|
|
'Content-Security-Policy': preview.csp,
|
|
'Referrer-Policy': 'no-referrer',
|
|
})
|
|
res.type('html').send(preview.html)
|
|
})
|
|
app.get('/api/signature-placeholders', (req, res) => res.json(signatureTokens))
|
|
app.get('/api/tickets', (req, res) => res.json(s.tickets(req.user, req.query)))
|
|
app.get('/api/search', (req, res) => res.json(s.searchTickets(req.user, req.query.q ?? '')))
|
|
app.post('/api/tickets', (req, res) => res.json(s.createTicket(req.user, req.body)))
|
|
app.get('/api/tickets/:id', (req, res) => res.json(s.detail(req.user, Number(req.params.id))))
|
|
app.patch('/api/tickets/:id', (req, res) =>
|
|
res.json(s.updateTicket(req.user, Number(req.params.id), req.body)),
|
|
)
|
|
app.post('/api/tickets/:id/goods', (req, res) =>
|
|
res.json(s.goods(req.user, Number(req.params.id))),
|
|
)
|
|
app.post('/api/tickets/:id/messages', (req, res) =>
|
|
res.json(s.reply(req.user, Number(req.params.id), req.body)),
|
|
)
|
|
app.post('/api/tickets/:id/signature-preview', (req, res) => {
|
|
const t = s.ticket(req.user, Number(req.params.id), 'reply'),
|
|
q = s.queue(t.queue_id)
|
|
const signature = req.body.signature_id
|
|
? q.signatures.find((v) => v.id === req.body.signature_id)
|
|
: q.signatures.find((v) => v.default)
|
|
if (!signature) throw new HttpError(400, 'Signatur gehört nicht zur Queue.')
|
|
const from = req.body.from || q.addresses.find((a) => a.default && a.outgoing)?.email
|
|
if (!q.addresses.some((a) => a.email === from && a.outgoing))
|
|
throw new HttpError(400, 'Absender ist für diese Queue nicht freigegeben.')
|
|
res.json(signatureValue(signature, signatureContext(s, req.user, q, t, from)))
|
|
})
|
|
app.get('/api/attachments/:id', (req, res) => {
|
|
const a = s.get(
|
|
'SELECT a.*,m.ticket_id FROM attachments a JOIN messages m ON m.id=a.message_id WHERE a.id=?',
|
|
req.params.id,
|
|
)
|
|
if (!a) throw new HttpError(404, 'Anhang nicht gefunden.')
|
|
s.ticket(req.user, a.ticket_id)
|
|
res.set({
|
|
'Content-Type': 'application/octet-stream',
|
|
'Content-Disposition': `attachment; filename*=UTF-8''${encodeURIComponent(a.name)}`,
|
|
'Content-Security-Policy': "sandbox; default-src 'none'",
|
|
})
|
|
res.send(a.content)
|
|
})
|
|
app.get('/api/messages/:id/view', (req, res) => res.json(s.viewMessage(req.user, req.params.id)))
|
|
app.get('/api/messages/:id/original', (req, res) => {
|
|
const m = s.message(req.user, req.params.id),
|
|
original = s.get('SELECT source FROM message_originals WHERE message_id=?', m.id)
|
|
if (!original?.source)
|
|
throw new HttpError(404, 'Für diese Nachricht liegt keine Originaldatei vor.')
|
|
res.set({
|
|
'Content-Type': 'application/octet-stream',
|
|
'Content-Disposition': `attachment; filename="nachricht-${m.ticket_id}.eml"`,
|
|
'Content-Security-Policy': "sandbox; default-src 'none'",
|
|
})
|
|
res.send(original.source)
|
|
})
|
|
app.put('/api/queues/:id/templates', (req, res) =>
|
|
res.json(s.saveTemplates(req.user, req.params.id, req.body.templates)),
|
|
)
|
|
app.post('/api/tickets/:id/templates/:templateId', (req, res) =>
|
|
res.json(
|
|
s.renderTemplate(req.user, Number(req.params.id), req.params.templateId, req.body.from),
|
|
),
|
|
)
|
|
app.get('/api/notifications', (req, res) => res.json(s.notifications(req.user)))
|
|
app.post('/api/notifications/read', (req, res) => {
|
|
s.readNotifications(req.user, req.body.id)
|
|
res.json({ ok: true })
|
|
})
|
|
app.put('/api/preferences', (req, res) => {
|
|
const clean = {}
|
|
for (const e of ['new', 'reply', 'assigned', 'reopened'])
|
|
clean[e] = { bell: !!req.body[e]?.bell, email: !!req.body[e]?.email }
|
|
s.run('UPDATE users SET prefs=? WHERE id=?', JSON.stringify(clean), req.user.id)
|
|
res.json(clean)
|
|
})
|
|
app.post('/api/queues', (req, res) => res.json(s.saveQueue(req.user, null, req.body)))
|
|
app.put('/api/queues/:id', (req, res) => res.json(s.saveQueue(req.user, req.params.id, req.body)))
|
|
app.get('/api/queues/:id/mail', (req, res) => {
|
|
const settings = readMailSettings(s, req.user, req.params.id)
|
|
settings.imap.runtime.running = !!app.locals.worker?.inbound.running.has(req.params.id)
|
|
res.json(settings)
|
|
})
|
|
app.put('/api/queues/:id/mail', (req, res) =>
|
|
res.json(saveMailSettings(s, req.user, req.params.id, req.body)),
|
|
)
|
|
app.post('/api/queues/:id/mail/verify', async (req, res) =>
|
|
res.json(await verifySmtp(s, req.user, req.params.id)),
|
|
)
|
|
app.post('/api/queues/:id/mail/verify-imap', async (req, res) => {
|
|
s.require(req.user, req.params.id, 'queue')
|
|
res.json(await app.locals.worker.inbound.verify(req.user, req.params.id))
|
|
})
|
|
app.post('/api/queues/:id/mail/fetch', async (req, res) => {
|
|
s.require(req.user, req.params.id, 'queue')
|
|
res.json(await app.locals.worker.inbound.run(req.params.id, { actor: req.user.id }))
|
|
})
|
|
app.put('/api/queues/:id/statuses', (req, res) =>
|
|
res.json(s.saveStatuses(req.user, req.params.id, req.body.statuses, req.body.mapping)),
|
|
)
|
|
app.put('/api/queues/:id/signatures', (req, res) => {
|
|
s.saveSignatures(req.user, req.params.id, req.body.signatures)
|
|
res.json({ ok: true })
|
|
})
|
|
app.post('/api/queues/:id/signatures/preview', (req, res) => {
|
|
s.require(req.user, req.params.id, 'signatures')
|
|
const q = s.queue(req.params.id),
|
|
body = req.body.body ?? req.body.html
|
|
const format = req.body.format || (req.body.html !== undefined ? 'html' : 'text')
|
|
if (typeof body !== 'string' || body.length > 100000 || !['text', 'html'].includes(format))
|
|
throw new HttpError(400, 'Ungültige Signatur (max. 100.000 Zeichen).')
|
|
const automatic = req.body.mode === 'system'
|
|
const example = {
|
|
id: 123,
|
|
subject: 'Beispielanfrage',
|
|
customer_name: 'Anna Beispiel',
|
|
customer: 'kunde@example.org',
|
|
status_id: q.statuses.find((v) => v.behavior === 'open')?.id,
|
|
assignee: automatic ? null : req.user.id,
|
|
}
|
|
res.json(
|
|
signatureValue(
|
|
{ body, format },
|
|
signatureContext(s, automatic ? null : req.user, q, example),
|
|
),
|
|
)
|
|
})
|
|
app.get('/api/queues/:id/deletion', (req, res) =>
|
|
res.json(s.queueDeletion(req.user, req.params.id)),
|
|
)
|
|
app.delete('/api/queues/:id', (req, res) => {
|
|
if (app.locals.worker?.inbound.running.has(req.params.id))
|
|
throw new HttpError(
|
|
409,
|
|
'Postfachabruf läuft. Empfang zuerst deaktivieren und den Abruf abwarten.',
|
|
)
|
|
res.json(s.deleteQueue(req.user, req.params.id, req.body))
|
|
})
|
|
app.get('/api/admin', (req, res) => res.json(s.admin(req.user)))
|
|
app.post('/api/users', (req, res) => res.json(s.saveUser(req.user, req.body)))
|
|
app.post('/api/groups', (req, res) => res.json(s.saveGroup(req.user, req.body)))
|
|
app.get('/api/users/:id/deletion', (req, res) =>
|
|
res.json(s.userDeletion(req.user, req.params.id)),
|
|
)
|
|
app.delete('/api/users/:id', (req, res) =>
|
|
res.json(s.deleteUser(req.user, req.params.id, req.body)),
|
|
)
|
|
app.get('/api/groups/:id/deletion', (req, res) =>
|
|
res.json(s.groupDeletion(req.user, req.params.id)),
|
|
)
|
|
app.delete('/api/groups/:id', (req, res) =>
|
|
res.json(s.deleteGroup(req.user, req.params.id, req.body)),
|
|
)
|
|
app.get('/api/logs', (req, res) => res.json(s.logs(req.user)))
|
|
app.get('/api/outbox', (req, res) => {
|
|
s.require(req.user, '*', 'logs')
|
|
res.json(
|
|
s.all('SELECT id,state,attempts,error,next_at FROM outbox ORDER BY next_at DESC LIMIT 100'),
|
|
)
|
|
})
|
|
app.post('/api/dev/incoming', (req, res) => {
|
|
if (process.env.MAIL_MODE === 'smtp' || process.env.NODE_ENV === 'production')
|
|
throw new HttpError(404, 'Entwicklungsadapter deaktiviert.')
|
|
s.require(req.user, '*', 'queue')
|
|
try {
|
|
res.json(s.ingest(req.body))
|
|
} catch (e) {
|
|
s.audit(req.user.id, 'E-Mail-Verarbeitung fehlgeschlagen', 'development', null, {
|
|
error: e.name,
|
|
})
|
|
throw e
|
|
}
|
|
})
|
|
app.get('/api/dev/mail', (req, res) => {
|
|
if (process.env.NODE_ENV === 'production')
|
|
throw new HttpError(404, 'Entwicklungsadapter deaktiviert.')
|
|
s.require(req.user, '*', 'logs')
|
|
res.json(s.all('SELECT * FROM dev_mail ORDER BY created_at DESC LIMIT 100'))
|
|
})
|
|
app.use((e, req, res, next) => {
|
|
res.status(e.status || 500).json({
|
|
error: e.status
|
|
? e.message
|
|
: 'Die Aktion konnte nicht ausgeführt werden. Bitte Eingaben und Serverkonfiguration prüfen.',
|
|
})
|
|
})
|
|
return { app, service: s }
|
|
}
|