1640 lines
62 KiB
JavaScript
1640 lines
62 KiB
JavaScript
import { test } from 'node:test'
|
|
import assert from 'node:assert/strict'
|
|
import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'
|
|
import os from 'node:os'
|
|
import path from 'node:path'
|
|
import { openDb, seed, uid, now } from '../server/db.js'
|
|
import { Service } from '../server/service.js'
|
|
import { Worker } from '../server/worker.js'
|
|
import { createApp } from '../server/app.js'
|
|
import { scheduledTime } from '../server/time.js'
|
|
import { readMailSettings, saveMailSettings, smtpTransport } from '../server/mail-config.js'
|
|
import { InboundWorker, nextFetch, imapOptions } from '../server/inbound.js'
|
|
import nodemailer from 'nodemailer'
|
|
import { simpleParser } from 'mailparser'
|
|
import { safeHtml, signatureValue } from '../server/content.js'
|
|
import { signatureContext } from '../server/signature-placeholders.js'
|
|
import { loadRuntimeSecrets, validateRuntime, proxyHops } from '../server/runtime.js'
|
|
process.env.SMTP_ENCRYPTION_KEY = 'a9'.repeat(32)
|
|
function setup(file = ':memory:') {
|
|
const db = openDb(file)
|
|
seed(db)
|
|
const s = new Service(db)
|
|
return { db, s, admin: s.user('admin'), agent: s.user('leon'), reader: s.user('mira') }
|
|
}
|
|
function mail(queue = 'support', extra = {}) {
|
|
return {
|
|
messageId: `<${uid()}@example.com>`,
|
|
from: 'anna@example.com',
|
|
to: [`${queue}@syncova.local`],
|
|
name: 'Anna',
|
|
subject: 'Eine Frage',
|
|
body: 'Bitte helfen',
|
|
...extra,
|
|
}
|
|
}
|
|
function status(s, q, b) {
|
|
return s.queue(q).statuses.find((x) => x.behavior === b).id
|
|
}
|
|
test('Production startup requires HTTPS, secure cookies, explicit mail mode and bounded proxy trust', () => {
|
|
const valid = {
|
|
NODE_ENV: 'production',
|
|
APP_ORIGIN: 'https://tickets.example.org',
|
|
COOKIE_SECURE: 'true',
|
|
TRUST_PROXY: '1',
|
|
MAIL_MODE: 'disabled',
|
|
}
|
|
assert.doesNotThrow(() => validateRuntime(valid))
|
|
assert.equal(proxyHops(valid), 1)
|
|
for (const change of [
|
|
{ APP_ORIGIN: 'http://tickets.example.org' },
|
|
{ APP_ORIGIN: 'https://tickets.example.org/path' },
|
|
{ APP_ORIGIN: 'https://user:password@tickets.example.org' },
|
|
{ APP_ORIGIN: 'https://tickets.example.org/' },
|
|
{ COOKIE_SECURE: 'false' },
|
|
{ TRUST_PROXY: 'true' },
|
|
{ MAIL_MODE: 'development' },
|
|
{ SMTP_ENCRYPTION_KEY: 'wrong' },
|
|
])
|
|
assert.throws(() => validateRuntime({ ...valid, ...change }))
|
|
assert.doesNotThrow(() => validateRuntime({ NODE_ENV: 'development', TRUST_PROXY: '0' }))
|
|
})
|
|
test('Production bootstrap rejects weak passwords and starts without named demo accounts', () => {
|
|
const fields = ['NODE_ENV', 'ADMIN_EMAIL', 'ADMIN_PASSWORD', 'ADMIN_NAME'],
|
|
prior = Object.fromEntries(fields.map((k) => [k, process.env[k]])),
|
|
db = openDb(':memory:')
|
|
try {
|
|
Object.assign(process.env, {
|
|
NODE_ENV: 'production',
|
|
ADMIN_EMAIL: 'ADMIN@example.org',
|
|
ADMIN_PASSWORD: 'weak',
|
|
})
|
|
delete process.env.ADMIN_NAME
|
|
assert.throws(() => seed(db), /16 bis 256/)
|
|
assert.equal(db.prepare('SELECT count(*) n FROM users').get().n, 0)
|
|
process.env.ADMIN_PASSWORD = 'Production-Bootstrap-2026!'
|
|
seed(db)
|
|
assert.deepEqual(
|
|
db
|
|
.prepare('SELECT name,email FROM users')
|
|
.all()
|
|
.map((u) => ({ ...u })),
|
|
[{ name: 'Administrator', email: 'admin@example.org' }],
|
|
)
|
|
assert.equal(db.prepare('SELECT count(*) n FROM tickets').get().n, 0)
|
|
} finally {
|
|
for (const field of fields) {
|
|
if (prior[field] === undefined) delete process.env[field]
|
|
else process.env[field] = prior[field]
|
|
}
|
|
db.close()
|
|
}
|
|
})
|
|
test('Mounted bootstrap secrets load without echoing values and cannot silently override environment values', () => {
|
|
const dir = mkdtempSync(path.join(os.tmpdir(), 'syncova-secret-')),
|
|
file = path.join(dir, 'password')
|
|
try {
|
|
writeFileSync(file, 'Test-Production-Secret-2026!\n')
|
|
const env = { ADMIN_PASSWORD_FILE: file }
|
|
loadRuntimeSecrets(env)
|
|
assert.equal(env.ADMIN_PASSWORD, 'Test-Production-Secret-2026!')
|
|
assert.throws(
|
|
() => loadRuntimeSecrets({ ADMIN_PASSWORD_FILE: file, ADMIN_PASSWORD: 'another' }),
|
|
/gleichzeitig/,
|
|
)
|
|
assert.throws(
|
|
() => loadRuntimeSecrets({ ADMIN_PASSWORD_FILE: path.join(dir, 'missing') }),
|
|
/nicht gelesen/,
|
|
)
|
|
} finally {
|
|
rmSync(dir, { recursive: true, force: true })
|
|
}
|
|
})
|
|
test('Production never simulates mail delivery and blocks queues without SMTP configuration', async () => {
|
|
const { db, s, admin } = setup(),
|
|
prior = process.env.NODE_ENV,
|
|
priorMode = process.env.MAIL_MODE
|
|
try {
|
|
const config = readMailSettings(s, admin, 'support')
|
|
saveMailSettings(s, admin, 'support', config)
|
|
process.env.NODE_ENV = 'production'
|
|
process.env.MAIL_MODE = 'disabled'
|
|
assert.equal(readMailSettings(s, admin, 'support').smtp.mode, 'disabled')
|
|
assert.equal(readMailSettings(s, admin, 'support').allowDevelopment, false)
|
|
assert.throws(() => saveMailSettings(s, admin, 'support', config), { status: 400 })
|
|
assert.throws(() => smtpTransport(s, 'support'), { status: 409 })
|
|
const id = s.ingest(mail()).ticket_id
|
|
s.reply(admin, id, {
|
|
key: uid(),
|
|
from: 'support@syncova.local',
|
|
body: 'Keine simulierte Produktivzustellung',
|
|
})
|
|
await new Worker(s).tick()
|
|
assert.equal(s.get('SELECT count(*) n FROM dev_mail').n, 0)
|
|
const job = s.get('SELECT state,error FROM outbox WHERE message_id IS NOT NULL')
|
|
assert.equal(job.state, 'blocked')
|
|
assert.match(job.error, /deaktiviert/)
|
|
assert.equal(s.detail(admin, id).messages.find((m) => m.kind === 'outgoing').delivery, 'queued')
|
|
} finally {
|
|
if (prior === undefined) delete process.env.NODE_ENV
|
|
else process.env.NODE_ENV = prior
|
|
if (priorMode === undefined) delete process.env.MAIL_MODE
|
|
else process.env.MAIL_MODE = priorMode
|
|
db.close()
|
|
}
|
|
})
|
|
test('Deleting a user revokes sessions, clears assignments, preserves history and permits email reuse', () => {
|
|
const { db, s, admin, agent } = setup()
|
|
try {
|
|
s.run(
|
|
'UPDATE users SET prefs=? WHERE id=?',
|
|
JSON.stringify({ new: { bell: true, email: true } }),
|
|
agent.id,
|
|
)
|
|
s.run(
|
|
'INSERT INTO sessions VALUES(?,?,?)',
|
|
'user-delete-session',
|
|
agent.id,
|
|
'2099-01-01T00:00:00Z',
|
|
)
|
|
const id = s.ingest(
|
|
mail('support', { attachments: [{ name: 'info.txt', content: 'YQ==' }] }),
|
|
).ticket_id
|
|
s.run('UPDATE tickets SET assignee=? WHERE id=?', agent.id, id)
|
|
s.reply(agent, id, { kind: 'note', body: 'Historische Notiz', key: uid() })
|
|
const before = s.detail(admin, id),
|
|
messages = before.messages
|
|
assert.equal(s.userDeletion(admin, agent.id).assignedTickets, 1)
|
|
assert.throws(() => s.deleteUser(agent, admin.id, { confirm: admin.email }), { status: 403 })
|
|
assert.throws(() => s.deleteUser(admin, agent.id, { confirm: 'falsch' }), { status: 400 })
|
|
assert.equal(s.user(agent.id).name, agent.name)
|
|
assert.equal(s.deleteUser(admin, agent.id, { confirm: agent.email }).assignedTickets, 1)
|
|
assert.throws(() => s.user(agent.id), { status: 401 })
|
|
assert.equal(s.get('SELECT * FROM sessions WHERE user_id=?', agent.id), undefined)
|
|
assert.equal(s.get('SELECT * FROM memberships WHERE user_id=?', agent.id), undefined)
|
|
const after = s.detail(admin, id)
|
|
assert.equal(after.assignee, null)
|
|
assert.equal(after.revision, before.revision + 1)
|
|
assert.deepEqual(after.messages, messages)
|
|
assert.equal(after.activities.find((a) => a.actor === agent.id).actor_name, agent.name)
|
|
assert.equal(
|
|
s.get(
|
|
'SELECT state FROM outbox o JOIN notifications n ON n.id=o.notification_id WHERE n.user_id=?',
|
|
agent.id,
|
|
).state,
|
|
'cancelled',
|
|
)
|
|
assert(!s.admin(admin).users.some((u) => u.id === agent.id))
|
|
assert(!s.bootstrap(admin).users.some((u) => u.id === agent.id))
|
|
assert.throws(() => s.saveUser(admin, { ...agent, active: 1, groups: ['agent'] }), {
|
|
status: 404,
|
|
})
|
|
assert.throws(() => s.deleteUser(admin, agent.id, { confirm: agent.email }), { status: 404 })
|
|
const replacement = s.saveUser(admin, {
|
|
name: 'Neues Konto',
|
|
email: agent.email,
|
|
groups: ['agent'],
|
|
active: true,
|
|
password: 'New-Password-2026!',
|
|
})
|
|
assert.notEqual(replacement.id, agent.id)
|
|
assert.equal(s.user(replacement.id).email, agent.email)
|
|
assert.equal(s.logs(admin).find((a) => a.action === 'Benutzer gelöscht').entity, agent.id)
|
|
assert.deepEqual(db.pragma('foreign_key_check'), [])
|
|
} finally {
|
|
db.close()
|
|
}
|
|
})
|
|
test('Self deletion, the last active administrator and the administrator group are protected', () => {
|
|
const { db, s, admin } = setup()
|
|
try {
|
|
const manager = s.saveUser(admin, {
|
|
name: 'Verwaltung',
|
|
email: 'verwaltung@example.org',
|
|
active: true,
|
|
groups: ['manager'],
|
|
password: 'Manager-Password-2026!',
|
|
})
|
|
const group = s.saveGroup(admin, {
|
|
name: 'Benutzerverwaltung',
|
|
permissions: { '*': ['users'] },
|
|
})
|
|
s.run('INSERT INTO memberships VALUES(?,?)', manager.id, group.id)
|
|
const actor = s.user(manager.id)
|
|
assert.throws(() => s.deleteUser(admin, admin.id, { confirm: admin.email }), { status: 409 })
|
|
assert.throws(() => s.deleteUser(actor, admin.id, { confirm: admin.email }), { status: 409 })
|
|
assert.throws(() => s.saveUser(actor, { ...admin, active: false, groups: ['admins'] }), {
|
|
status: 409,
|
|
})
|
|
assert.equal(s.user(admin.id).active, 1)
|
|
assert.throws(() => s.deleteGroup(admin, 'admins', { confirm: 'Administrator' }), {
|
|
status: 409,
|
|
})
|
|
assert.throws(() => s.deleteGroup(actor, group.id, { confirm: 'Benutzerverwaltung' }), {
|
|
status: 409,
|
|
})
|
|
assert(s.can(actor, '*', 'users'))
|
|
const second = s.saveUser(admin, {
|
|
name: 'Zweiter Admin',
|
|
email: 'zweiter@example.org',
|
|
active: true,
|
|
groups: ['admins'],
|
|
password: 'Second-Admin-2026!',
|
|
})
|
|
s.deleteUser(s.user(second.id), admin.id, { confirm: admin.email })
|
|
assert.throws(() => s.user(admin.id), { status: 401 })
|
|
assert.equal(s.user(second.id).active, 1)
|
|
} finally {
|
|
db.close()
|
|
}
|
|
})
|
|
test('Deleting a group removes only its rights, releases inaccessible assignments and rejects stale editors', () => {
|
|
const { db, s, admin, agent, reader } = setup()
|
|
try {
|
|
const group = s.saveGroup(admin, {
|
|
name: 'Zusatzrechte',
|
|
permissions: { support: ['view', 'reply'] },
|
|
})
|
|
s.run('INSERT INTO memberships VALUES(?,?)', agent.id, group.id)
|
|
s.run('INSERT INTO memberships VALUES(?,?)', reader.id, group.id)
|
|
s.run('DELETE FROM memberships WHERE user_id=? AND group_id=?', reader.id, 'reader')
|
|
const first = s.ingest(mail()).ticket_id,
|
|
second = s.ingest(mail()).ticket_id
|
|
s.run('UPDATE tickets SET assignee=? WHERE id=?', agent.id, first)
|
|
s.run('UPDATE tickets SET assignee=? WHERE id=?', reader.id, second)
|
|
assert.equal(s.groupDeletion(admin, group.id).members, 2)
|
|
assert.throws(() => s.deleteGroup(agent, group.id, { confirm: 'Zusatzrechte' }), {
|
|
status: 403,
|
|
})
|
|
assert.throws(() => s.deleteGroup(admin, group.id, { confirm: 'falsch' }), { status: 400 })
|
|
assert(s.can(reader, 'support', 'view'))
|
|
assert.equal(s.deleteGroup(admin, group.id, { confirm: 'Zusatzrechte' }).assignedTickets, 1)
|
|
assert.equal(s.get('SELECT * FROM groups_ WHERE id=?', group.id), undefined)
|
|
assert.equal(s.get('SELECT * FROM memberships WHERE group_id=?', group.id), undefined)
|
|
assert(s.can(agent, 'support', 'reply'))
|
|
assert(!s.can(reader, 'support', 'view'))
|
|
assert.equal(s.detail(admin, first).assignee, agent.id)
|
|
assert.equal(s.detail(admin, second).assignee, null)
|
|
assert.equal(s.user(reader.id).active, 1)
|
|
assert.throws(
|
|
() => s.saveGroup(admin, { id: group.id, name: 'Zusatzrechte', permissions: {} }),
|
|
{ status: 404 },
|
|
)
|
|
assert.throws(() => s.deleteGroup(admin, group.id, { confirm: 'Zusatzrechte' }), {
|
|
status: 404,
|
|
})
|
|
assert.deepEqual(db.pragma('foreign_key_check'), [])
|
|
} finally {
|
|
db.close()
|
|
}
|
|
})
|
|
test('Deleted users and groups stay removed after restarting the database', () => {
|
|
const dir = mkdtempSync(path.join(os.tmpdir(), 'syncova-identities-')),
|
|
file = path.join(dir, 'test.db')
|
|
let db
|
|
try {
|
|
const initial = setup(file)
|
|
db = initial.db
|
|
initial.s.deleteUser(initial.admin, initial.agent.id, { confirm: initial.agent.email })
|
|
initial.s.deleteGroup(initial.admin, 'agent', { confirm: 'Bearbeiter' })
|
|
db.close()
|
|
db = openDb(file)
|
|
const s = new Service(db),
|
|
admin = s.user('admin')
|
|
assert(!s.admin(admin).users.some((u) => u.id === 'leon'))
|
|
assert(!s.admin(admin).groups.some((g) => g.id === 'agent'))
|
|
assert.throws(() => s.user('leon'), { status: 401 })
|
|
} finally {
|
|
db?.close()
|
|
rmSync(dir, { recursive: true, force: true })
|
|
}
|
|
})
|
|
function configureImap(s, user, q, changes = {}) {
|
|
const settings = readMailSettings(s, user, q)
|
|
return saveMailSettings(s, user, q, {
|
|
...settings,
|
|
imap: {
|
|
...settings.imap,
|
|
enabled: true,
|
|
host: 'imap.example.invalid',
|
|
username: q,
|
|
...changes,
|
|
},
|
|
imapPassword: 'imap-secret-' + q,
|
|
})
|
|
}
|
|
function mime(id, to = 'support@syncova.local') {
|
|
return Buffer.from(
|
|
`From: Anna <anna@example.com>\r\nTo: ${to}\r\nMessage-ID: <imap-${id}@example.com>\r\nSubject: Anfrage ${id}\r\nContent-Type: text/plain; charset=utf-8\r\n\r\nBitte helfen.\r\n`,
|
|
)
|
|
}
|
|
function fakeImap(messages, record = [], hooks = {}) {
|
|
return (options) => ({
|
|
mailbox: { uidValidity: 1n },
|
|
async connect() {
|
|
record.push({ connect: options })
|
|
await hooks.connect?.()
|
|
},
|
|
async getMailboxLock(folder) {
|
|
record.push({ folder })
|
|
return { release() {} }
|
|
},
|
|
async search() {
|
|
return [...messages.keys()]
|
|
},
|
|
async fetchOne(uid, query) {
|
|
if (query.size) return { size: messages.get(uid).length }
|
|
await hooks.source?.(uid)
|
|
return { source: messages.get(uid) }
|
|
},
|
|
async messageFlagsAdd(uid) {
|
|
record.push({ seen: uid })
|
|
},
|
|
async logout() {},
|
|
close() {},
|
|
})
|
|
}
|
|
test('Signature profile fields are admin managed, persisted and preserved by older clients', () => {
|
|
const { db, s, admin, agent } = setup()
|
|
try {
|
|
const data = {
|
|
...agent,
|
|
groups: ['agent'],
|
|
phone: ' +49 123 ',
|
|
job_title: 'Support Engineer',
|
|
department: 'Service',
|
|
}
|
|
assert.throws(() => s.saveUser(agent, data), { status: 403 })
|
|
s.saveUser(admin, data)
|
|
assert.equal(s.user(agent.id).phone, '+49 123')
|
|
assert.equal(s.admin(admin).users.find((u) => u.id === agent.id).job_title, 'Support Engineer')
|
|
const { phone, job_title, department, ...legacy } = data
|
|
s.saveUser(admin, { ...legacy, name: 'Leon Test' })
|
|
assert.equal(s.user(agent.id).department, 'Service')
|
|
assert.throws(() => s.saveUser(admin, { ...data, phone: 'x'.repeat(201) }), { status: 400 })
|
|
} finally {
|
|
db.close()
|
|
}
|
|
})
|
|
test('Signature placeholders use the replying user, actual ticket and queue sender, and snapshot the result', () => {
|
|
const { db, s, admin, agent } = setup()
|
|
try {
|
|
s.saveUser(admin, {
|
|
...agent,
|
|
groups: ['agent'],
|
|
phone: '+49 123',
|
|
job_title: 'Support',
|
|
department: 'Service',
|
|
})
|
|
const q = s.queue('support')
|
|
const body =
|
|
'{benutzer.name}|{benutzer.vorname}|{benutzer.nachname}|{benutzer.email}|{benutzer.telefon}|{benutzer.position}|{benutzer.abteilung}|{queue.name}|{queue.email}|{absender.email}|{ticket.nummer}|{ticket.betreff}|{ticket.status}|{kunde.name}|{kunde.email}|{bearbeiter.name}|{bearbeiter.email}'
|
|
s.saveSignatures(admin, q.id, [{ ...q.signatures[0], format: 'text', body }])
|
|
const id = s.ingest(mail()).ticket_id
|
|
s.run('UPDATE tickets SET assignee=? WHERE id=?', admin.id, id)
|
|
const actor = s.user(agent.id),
|
|
from = q.addresses.find((a) => a.outgoing && !a.default).email
|
|
s.reply(actor, id, { key: 'placeholder-reply', from, body: 'Antwort' })
|
|
const message = s.detail(admin, id).messages.find((m) => m.kind === 'outgoing')
|
|
assert.equal(
|
|
message.body,
|
|
`Antwort\n\n${actor.name}|Leon|Fischer|${actor.email}|+49 123|Support|Service|Support|support@syncova.local|${from}|SYN-${String(id).padStart(5, '0')}|Eine Frage|Neu|Anna|anna@example.com|${admin.name}|${admin.email}`,
|
|
)
|
|
assert(!message.body.includes('{benutzer.'))
|
|
const payload = s.get('SELECT payload FROM outbox WHERE message_id=?', message.id).payload
|
|
assert.equal(JSON.parse(payload).text, message.body)
|
|
s.saveUser(admin, { ...actor, groups: ['agent'], name: 'Geänderter Name' })
|
|
s.reply(s.user(agent.id), id, { key: 'placeholder-reply', from, body: 'Wiederholung' })
|
|
assert.equal(
|
|
s.get('SELECT payload FROM outbox WHERE message_id=?', message.id).payload,
|
|
payload,
|
|
)
|
|
assert.equal(s.get('SELECT body FROM messages WHERE id=?', message.id).body, message.body)
|
|
} finally {
|
|
db.close()
|
|
}
|
|
})
|
|
test('HTML placeholder values are escaped, sanitised and expanded once; unknown tokens are rejected', () => {
|
|
const { db, s, admin } = setup()
|
|
try {
|
|
const rendered = signatureValue(
|
|
{
|
|
format: 'html',
|
|
body: '<strong>{benutzer.name}</strong><a href="mailto:{benutzer.email}">{benutzer.email}</a><a href="{kunde.name}">Kontakt</a>',
|
|
},
|
|
{
|
|
'benutzer.name': '<img src=x onerror="alert(1)"> & {queue.name}',
|
|
'benutzer.email': 'person@example.org',
|
|
'kunde.name': 'javascript:alert(1)',
|
|
'queue.name': 'NICHT ERSETZEN',
|
|
},
|
|
)
|
|
assert(rendered.html.includes('<img'))
|
|
assert(rendered.html.includes('& {queue.name}'))
|
|
assert(!rendered.html.includes('<img'))
|
|
assert(!rendered.html.includes('href="javascript:'))
|
|
assert(rendered.html.includes('href="mailto:person@example.org"'))
|
|
assert.equal(
|
|
signatureValue(
|
|
{ body: '{user.name} / {ticket.number}' },
|
|
{ 'benutzer.name': 'Jana', 'ticket.nummer': 'SYN-00001' },
|
|
).text,
|
|
'Jana / SYN-00001',
|
|
)
|
|
const q = s.queue('support')
|
|
const legacy = signatureValue(
|
|
{
|
|
format: 'html',
|
|
body: '<p>{%user.firstName%} {%user.lastName%}<br>Tel.: {%user.phone%}<br><a href="mailto:{%mailbox.email%}">{%mailbox.email%}</a></p>',
|
|
},
|
|
{
|
|
'benutzer.vorname': 'Jana',
|
|
'benutzer.nachname': 'Weber',
|
|
'benutzer.telefon': '+49 123',
|
|
'absender.email': 'team@example.org',
|
|
},
|
|
)
|
|
assert.equal(
|
|
legacy.html,
|
|
'<p>Jana Weber<br />Tel.: +49 123<br /><a href="mailto:team@example.org">team@example.org</a></p>',
|
|
)
|
|
assert(!legacy.text.includes('{%'))
|
|
for (const body of [
|
|
'{unbekannt}',
|
|
'{constructor}',
|
|
'{__proto__}',
|
|
'{toString}',
|
|
'{%unknown%}',
|
|
'{%constructor%}',
|
|
])
|
|
assert.throws(() => s.saveSignatures(admin, q.id, [{ ...q.signatures[0], body }]), {
|
|
status: 400,
|
|
})
|
|
assert.deepEqual(s.queue(q.id).signatures, q.signatures)
|
|
} finally {
|
|
db.close()
|
|
}
|
|
})
|
|
test('Automatic acknowledgement signatures use queue identity and blank personal fields', () => {
|
|
const { db, s, admin } = setup()
|
|
try {
|
|
const q = s.queue('support')
|
|
s.saveSignatures(admin, q.id, [
|
|
{
|
|
...q.signatures[0],
|
|
format: 'html',
|
|
body: '<p>{benutzer.name}|{benutzer.email}|{benutzer.telefon}|{benutzer.position}|{benutzer.abteilung}|{benutzer.vorname}|{bearbeiter.name}|{kunde.name}|{ticket.nummer}</p>',
|
|
},
|
|
])
|
|
const config = readMailSettings(s, admin, q.id)
|
|
saveMailSettings(s, admin, q.id, {
|
|
...config,
|
|
acknowledgement: { ...config.acknowledgement, enabled: true, includeSignature: true },
|
|
})
|
|
const id = s.ingest(mail()).ticket_id
|
|
const auto = s.detail(admin, id).messages.find((m) => m.kind === 'outgoing')
|
|
assert(
|
|
auto.body.endsWith(
|
|
`Support|support@syncova.local||||||Anna|SYN-${String(id).padStart(5, '0')}`,
|
|
),
|
|
)
|
|
assert(!auto.body.includes(admin.name))
|
|
const context = signatureContext(
|
|
s,
|
|
null,
|
|
s.queue(q.id),
|
|
s.get('SELECT * FROM tickets WHERE id=?', id),
|
|
null,
|
|
new Date('2026-11-03T12:45:00Z'),
|
|
)
|
|
assert.equal(context.datum, '03.11.2026')
|
|
assert.equal(context.uhrzeit, '13:45')
|
|
} finally {
|
|
db.close()
|
|
}
|
|
})
|
|
test('Existing databases migrate optional signature profile fields without losing users', () => {
|
|
const dir = mkdtempSync(path.join(os.tmpdir(), 'syncova-profile-')),
|
|
file = path.join(dir, 'old.db')
|
|
let db
|
|
try {
|
|
db = openDb(file)
|
|
seed(db)
|
|
for (const name of ['phone', 'job_title', 'department'])
|
|
db.exec(`ALTER TABLE users DROP COLUMN ${name}`)
|
|
db.close()
|
|
db = openDb(file)
|
|
const user = new Service(db).user('admin')
|
|
assert.equal(user.phone, '')
|
|
assert.equal(user.job_title, '')
|
|
assert.equal(user.department, '')
|
|
assert.equal(user.name, 'Jana Weber')
|
|
} finally {
|
|
db?.close()
|
|
rmSync(dir, { recursive: true, force: true })
|
|
}
|
|
})
|
|
test('Queue deletion moves every ticket and attachment atomically, removes access and preserves history', () => {
|
|
const { db, s, admin, agent } = setup()
|
|
try {
|
|
const q = s.queue('support')
|
|
assert.throws(() => s.deleteQueue(agent, 'support', { confirm: q.name, target: 'vertrieb' }), {
|
|
status: 403,
|
|
})
|
|
assert.throws(() => s.deleteQueue(admin, 'support', { confirm: q.name }), { status: 409 })
|
|
const m = mail('support', {
|
|
attachments: [
|
|
{
|
|
name: 'vertrag.pdf',
|
|
mime: 'application/pdf',
|
|
content: Buffer.from('pdf-test').toString('base64'),
|
|
},
|
|
],
|
|
})
|
|
const ticket = s.ingest(m).ticket_id
|
|
s.updateTicket(admin, ticket, {
|
|
status_id: status(s, 'support', 'wait_date'),
|
|
due_at: '2030-01-01T12:00:00+01:00',
|
|
timezone: 'Europe/Berlin',
|
|
})
|
|
const before = s.detail(admin, ticket)
|
|
assert.throws(
|
|
() => s.deleteQueue(admin, 'support', { confirm: 'falsch', target: 'vertrieb' }),
|
|
{ status: 400 },
|
|
)
|
|
const result = s.deleteQueue(admin, 'support', { confirm: q.name, target: 'vertrieb' })
|
|
assert(result.moved > 0)
|
|
assert.throws(() => s.queue('support'), { status: 404 })
|
|
assert(!s.bootstrap(admin).queues.some((q) => q.id === 'support'))
|
|
assert.equal(s.get('SELECT count(*) n FROM tickets WHERE queue_id=?', 'support').n, 0)
|
|
const moved = s.detail(admin, ticket)
|
|
assert.equal(moved.queue_id, 'vertrieb')
|
|
assert.equal(moved.due_at, before.due_at)
|
|
assert.equal(moved.messages[0].attachments[0].name, 'vertrag.pdf')
|
|
assert(moved.activities.some((a) => a.action === 'Queue gewechselt'))
|
|
assert(s.logs(admin).some((a) => a.action === 'Queue gelöscht'))
|
|
assert(!s.can(agent, 'support', 'view'))
|
|
assert.throws(() => s.ingest(mail('support')), { status: 400 })
|
|
const replacement = s.saveQueue(admin, null, { name: 'Neuer Support', addresses: q.addresses })
|
|
assert(replacement.id)
|
|
} finally {
|
|
db.close()
|
|
}
|
|
})
|
|
test('Queue deletion blocks active inbound processing and invalid target mappings without partial changes', () => {
|
|
const { db, s, admin } = setup()
|
|
try {
|
|
const empty = s.saveQueue(admin, null, {
|
|
name: 'Leer',
|
|
addresses: [{ email: 'leer@example.com', incoming: true, outgoing: true, default: true }],
|
|
})
|
|
configureImap(s, admin, empty.id)
|
|
assert.throws(() => s.deleteQueue(admin, empty.id, { confirm: 'Leer' }), { status: 409 })
|
|
const c = readMailSettings(s, admin, empty.id)
|
|
saveMailSettings(s, admin, empty.id, { ...c, imap: { ...c.imap, enabled: false } })
|
|
s.deleteQueue(admin, empty.id, { confirm: 'Leer' })
|
|
assert.throws(() => s.queue(empty.id), { status: 404 })
|
|
const before = s.tickets(admin).filter((t) => t.queue_id === 'support').length
|
|
assert.throws(
|
|
() =>
|
|
s.deleteQueue(admin, 'support', {
|
|
confirm: 'Support',
|
|
target: 'vertrieb',
|
|
mapping: { [status(s, 'support', 'new')]: 'not-a-target-status' },
|
|
}),
|
|
{ status: 400 },
|
|
)
|
|
assert.equal(s.tickets(admin).filter((t) => t.queue_id === 'support').length, before)
|
|
assert(s.queue('support'))
|
|
} finally {
|
|
db.close()
|
|
}
|
|
})
|
|
test('HTML signatures are sanitised, snapshotted and sent with text alternatives and durable attachments', async () => {
|
|
const { db, s, admin } = setup()
|
|
try {
|
|
const q = s.queue('support')
|
|
s.saveSignatures(admin, q.id, [
|
|
{
|
|
id: q.signatures[0].id,
|
|
name: 'HTML',
|
|
default: true,
|
|
format: 'html',
|
|
body: '<p style="color:#7040c0"><strong>Ihr Support-Team</strong><br><a href="https://example.com">Website</a></p><script>alert(1)</script><img src="x" onerror="alert(1)"><a href="javascript:alert(1)">X</a>',
|
|
},
|
|
])
|
|
const signature = s.queue('support').signatures[0]
|
|
assert(!signature.body.includes('<script'))
|
|
assert(!signature.body.includes('onerror'))
|
|
assert(!signature.body.includes('javascript:'))
|
|
assert(signature.body.includes('<strong>'))
|
|
const ticket = s.ingest(mail()).ticket_id
|
|
const data = {
|
|
key: uid(),
|
|
kind: 'outgoing',
|
|
from: 'support@syncova.local',
|
|
body: 'Hallo <script>untrusted</script>',
|
|
signature_id: signature.id,
|
|
attachments: [
|
|
{
|
|
name: 'bericht.pdf',
|
|
mime: 'application/pdf',
|
|
content: Buffer.from('PDF-BINARY-TEST').toString('base64'),
|
|
},
|
|
],
|
|
}
|
|
const first = s.reply(admin, ticket, data)
|
|
assert.equal(s.reply(admin, ticket, data).id, first.id)
|
|
const detail = s.detail(admin, ticket),
|
|
reply = detail.messages.find((m) => m.id === first.id)
|
|
assert(reply.html.includes('<script>'))
|
|
assert(reply.html.includes('<strong>Ihr Support-Team</strong>'))
|
|
assert.equal(reply.body.match(/Ihr Support-Team/g).length, 1)
|
|
assert.equal(reply.attachments.length, 1)
|
|
let captured
|
|
const mimeTransport = nodemailer.createTransport({
|
|
streamTransport: true,
|
|
buffer: true,
|
|
newline: 'windows',
|
|
})
|
|
const config = readMailSettings(s, admin, 'support')
|
|
saveMailSettings(s, admin, 'support', {
|
|
...config,
|
|
smtp: { mode: 'smtp', host: 'smtp.invalid', port: 465, security: 'tls', username: 'user' },
|
|
password: 'smtp-secret',
|
|
})
|
|
const worker = new Worker(s, {
|
|
transportFactory: () => ({
|
|
async sendMail(payload) {
|
|
captured = await mimeTransport.sendMail(payload)
|
|
},
|
|
close() {},
|
|
}),
|
|
})
|
|
await worker.tick()
|
|
await worker.tick()
|
|
const parsed = await simpleParser(captured.message)
|
|
assert(parsed.html.includes('Ihr Support-Team'))
|
|
assert(parsed.text.includes('Ihr Support-Team'))
|
|
assert.equal(parsed.attachments[0].filename, 'bericht.pdf')
|
|
assert.equal(parsed.attachments[0].content.toString(), 'PDF-BINARY-TEST')
|
|
const incoming = new InboundWorker(s, {
|
|
clientFactory: fakeImap(new Map([[99, captured.message]])),
|
|
})
|
|
configureImap(s, admin, 'support')
|
|
const rowsBefore = s.all('SELECT * FROM attachments').length
|
|
assert((await incoming.run('support')).imported === 0)
|
|
assert.equal(s.all('SELECT * FROM attachments').length, rowsBefore)
|
|
} finally {
|
|
db.close()
|
|
}
|
|
})
|
|
test('Received MIME attachments are persisted with content and queue-checked download access', async () => {
|
|
const { db, s, admin } = setup()
|
|
try {
|
|
configureImap(s, admin, 'support')
|
|
const transport = nodemailer.createTransport({ streamTransport: true, buffer: true })
|
|
const message = await transport.sendMail({
|
|
from: 'customer@example.com',
|
|
to: 'support@syncova.local',
|
|
subject: 'Mit Anhang',
|
|
text: 'Anbei die Unterlagen',
|
|
messageId: '<received-attachment@example.com>',
|
|
attachments: [
|
|
{
|
|
filename: 'rechnung.txt',
|
|
content: Buffer.from('INVOICE-CONTENT'),
|
|
contentType: 'text/plain',
|
|
},
|
|
],
|
|
})
|
|
const worker = new InboundWorker(s, {
|
|
clientFactory: fakeImap(new Map([[1, message.message]])),
|
|
})
|
|
assert.equal((await worker.run('support')).imported, 1)
|
|
const row = s.get(
|
|
'SELECT * FROM messages WHERE message_id=?',
|
|
'<received-attachment@example.com>',
|
|
)
|
|
const detail = s.detail(admin, row.ticket_id)
|
|
assert.equal(detail.messages[0].attachments[0].name, 'rechnung.txt')
|
|
assert.equal(
|
|
s.get('SELECT content FROM attachments WHERE message_id=?', row.id).content.toString(),
|
|
'INVOICE-CONTENT',
|
|
)
|
|
assert.equal((await worker.run('support')).imported, 0)
|
|
} finally {
|
|
db.close()
|
|
}
|
|
})
|
|
test('Attachment limits and internal note isolation are enforced server-side', async () => {
|
|
const { db, s, admin } = setup()
|
|
try {
|
|
const ticket = s.ingest(mail()).ticket_id
|
|
assert.throws(
|
|
() =>
|
|
s.reply(admin, ticket, {
|
|
key: uid(),
|
|
from: 'support@syncova.local',
|
|
body: 'x',
|
|
attachments: [{ name: 'bad', content: '%%%=' }],
|
|
}),
|
|
{ status: 400 },
|
|
)
|
|
assert.throws(
|
|
() =>
|
|
s.reply(admin, ticket, {
|
|
key: uid(),
|
|
from: 'support@syncova.local',
|
|
body: 'x',
|
|
attachments: Array.from({ length: 21 }, () => ({ name: 'x', content: 'YQ==' })),
|
|
}),
|
|
{ status: 400 },
|
|
)
|
|
s.reply(admin, ticket, {
|
|
key: uid(),
|
|
kind: 'note',
|
|
body: 'Intern',
|
|
attachments: [{ name: 'intern.txt', content: 'YQ==' }],
|
|
})
|
|
assert.equal(s.all('SELECT * FROM outbox').length, 0)
|
|
const msg = s.reply(admin, ticket, {
|
|
key: uid(),
|
|
from: 'support@syncova.local',
|
|
body: '',
|
|
attachments: [{ name: 'datei.txt', content: 'YQ==' }],
|
|
})
|
|
await new Worker(s).tick()
|
|
assert.equal(s.get('SELECT count(*) n FROM attachments WHERE message_id=?', msg.id).n, 1)
|
|
assert.equal(
|
|
JSON.parse(s.get('SELECT payload FROM dev_mail').payload).attachments[0].content,
|
|
'YQ==',
|
|
)
|
|
assert(
|
|
!safeHtml(
|
|
'<iframe src="https://example.com"></iframe><svg onload="alert(1)"></svg>',
|
|
).includes('iframe'),
|
|
)
|
|
} finally {
|
|
db.close()
|
|
}
|
|
})
|
|
test('Manual tickets enforce queue permissions, are idempotent, audited and do not send customer acknowledgements', () => {
|
|
const { db, s, admin, agent, reader } = setup()
|
|
try {
|
|
const c = readMailSettings(s, admin, 'support')
|
|
saveMailSettings(s, admin, 'support', {
|
|
...c,
|
|
acknowledgement: { ...c.acknowledgement, enabled: true },
|
|
})
|
|
const data = {
|
|
queue_id: 'support',
|
|
customer: 'caller@example.com',
|
|
customer_name: 'Anrufer',
|
|
subject: 'Telefonische Anfrage',
|
|
body: 'Bitte um Rückruf',
|
|
key: uid(),
|
|
}
|
|
assert.throws(() => s.createTicket(reader, data), { status: 403 })
|
|
assert.throws(() => s.createTicket(agent, { ...data, queue_id: 'vertrieb' }), { status: 403 })
|
|
const ticket = s.createTicket(agent, data)
|
|
assert.equal(s.createTicket(agent, data).id, ticket.id)
|
|
assert.equal(ticket.messages[0].kind, 'manual')
|
|
assert.equal(ticket.customer_name, 'Anrufer')
|
|
assert(ticket.activities.some((a) => a.action === 'Ticket manuell erstellt'))
|
|
assert.equal(s.all('SELECT * FROM outbox').length, 0)
|
|
assert.equal(s.notifications(admin).filter((n) => n.ticket_id === ticket.id).length, 1)
|
|
} finally {
|
|
db.close()
|
|
}
|
|
})
|
|
test('IMAP secrets, TLS, configuration validation and atomic mail settings', () => {
|
|
const { db, s, admin, reader } = setup()
|
|
try {
|
|
assert.throws(() => configureImap(s, reader, 'support'), { status: 403 })
|
|
const c = configureImap(s, admin, 'support')
|
|
const row = s.get('SELECT * FROM queue_inbound WHERE queue_id=?', 'support')
|
|
assert(!JSON.stringify(row).includes('imap-secret-support'))
|
|
assert(!JSON.stringify(c).includes('imap-secret-support'))
|
|
assert(!JSON.stringify(s.logs(admin)).includes('imap-secret-support'))
|
|
assert.equal(imapOptions(s, 'support').auth.pass, 'imap-secret-support')
|
|
assert.equal(imapOptions(s, 'support').secure, true)
|
|
saveMailSettings(s, admin, 'support', {
|
|
...c,
|
|
imap: { ...c.imap, security: 'starttls', port: 143 },
|
|
imapPassword: '',
|
|
})
|
|
assert.equal(imapOptions(s, 'support').doSTARTTLS, true)
|
|
assert.equal(imapOptions(s, 'support').secure, false)
|
|
assert.throws(
|
|
() =>
|
|
saveMailSettings(s, admin, 'support', {
|
|
...c,
|
|
imap: { ...c.imap, host: 'other.invalid' },
|
|
imapPassword: '',
|
|
}),
|
|
{ status: 400 },
|
|
)
|
|
assert.throws(
|
|
() =>
|
|
saveMailSettings(s, admin, 'support', {
|
|
...c,
|
|
smtp: { ...c.smtp, host: 'changed.invalid' },
|
|
imap: { ...c.imap, schedule: { ...c.imap.schedule, mode: 'cron', cron: 'not cron' } },
|
|
}),
|
|
{ status: 400 },
|
|
)
|
|
assert.equal(readMailSettings(s, admin, 'support').smtp.host, c.smtp.host)
|
|
assert.equal(readMailSettings(s, admin, 'vertrieb').imap.enabled, false)
|
|
} finally {
|
|
db.close()
|
|
}
|
|
})
|
|
test('Cron expressions and IANA zones produce deterministic next fetches', () => {
|
|
const config = {
|
|
enabled: true,
|
|
schedule: { mode: 'cron', cron: '0 8 * * 1-5', timezone: 'Europe/Berlin' },
|
|
}
|
|
assert.equal(nextFetch(config, new Date('2026-11-03T06:30:00Z')), '2026-11-03T07:00:00.000Z')
|
|
assert.equal(nextFetch(config, new Date('2026-07-03T05:30:00Z')), '2026-07-03T06:00:00.000Z')
|
|
assert.equal(nextFetch({ ...config, enabled: false }), null)
|
|
assert.equal(
|
|
nextFetch(
|
|
{ enabled: true, schedule: { mode: 'interval', seconds: 30 } },
|
|
new Date('2026-11-03T06:30:00Z'),
|
|
),
|
|
'2026-11-03T06:30:30.000Z',
|
|
)
|
|
})
|
|
test('Queue IMAP imports only its recipients, leaves unrelated mail unread and persists UID deduplication', async () => {
|
|
const { db, s, admin } = setup()
|
|
try {
|
|
configureImap(s, admin, 'support')
|
|
configureImap(s, admin, 'vertrieb')
|
|
const messages = new Map([
|
|
[1, mime(1)],
|
|
[2, mime(2, 'vertrieb@syncova.local')],
|
|
]),
|
|
record = []
|
|
const worker = new InboundWorker(s, { clientFactory: fakeImap(messages, record) })
|
|
const a = await worker.run('support')
|
|
assert.equal(a.imported, 1)
|
|
assert(!record.some((r) => r.seen === 2))
|
|
await worker.run('support')
|
|
assert(!record.some((r) => Array.isArray(r.seen) && r.seen.includes(2)))
|
|
const b = await worker.run('vertrieb')
|
|
assert.equal(b.imported, 1)
|
|
const count = s.all('SELECT * FROM messages').length
|
|
const restarted = new InboundWorker(s, { clientFactory: fakeImap(messages) })
|
|
assert.equal((await restarted.run('support')).imported, 0)
|
|
assert.equal(s.all('SELECT * FROM messages').length, count)
|
|
assert(s.get('SELECT last_success FROM queue_inbound WHERE queue_id=?', 'support').last_success)
|
|
assert.equal(record[0].connect.auth.user, 'support')
|
|
} finally {
|
|
db.close()
|
|
}
|
|
})
|
|
test('Shared mailboxes make progress past unrelated messages without changing their read flags', async () => {
|
|
const { db, s, admin } = setup()
|
|
try {
|
|
configureImap(s, admin, 'support')
|
|
const messages = new Map()
|
|
for (let i = 1; i <= 101; i++) messages.set(i, mime(i, 'vertrieb@syncova.local'))
|
|
messages.set(102, mime(102))
|
|
const record = [],
|
|
worker = new InboundWorker(s, { clientFactory: fakeImap(messages, record) })
|
|
assert.equal((await worker.run('support')).imported, 0)
|
|
assert.equal((await worker.run('support')).imported, 1)
|
|
assert(record.filter((r) => r.seen !== undefined).every((r) => r.seen === 102))
|
|
} finally {
|
|
db.close()
|
|
}
|
|
})
|
|
test('Due fetches survive restart, advance independently per queue, and disabled schedules stay quiet', async () => {
|
|
const dir = mkdtempSync(path.join(os.tmpdir(), 'syncova-imap-'))
|
|
let db
|
|
try {
|
|
let c = setup(path.join(dir, 'db.sqlite'))
|
|
db = c.db
|
|
configureImap(c.s, c.admin, 'support')
|
|
c.s.run(
|
|
'UPDATE queue_inbound SET next_run=? WHERE queue_id=?',
|
|
'2020-01-01T00:00:00Z',
|
|
'support',
|
|
)
|
|
db.close()
|
|
db = openDb(path.join(dir, 'db.sqlite'))
|
|
const s = new Service(db),
|
|
record = [],
|
|
clock = () => new Date('2030-01-01T00:00:00Z'),
|
|
worker = new InboundWorker(s, { clientFactory: fakeImap(new Map(), record), clock })
|
|
await worker.due()
|
|
await worker.due()
|
|
assert.equal(record.filter((x) => x.connect).length, 1)
|
|
assert.equal(
|
|
s.get('SELECT next_run FROM queue_inbound WHERE queue_id=?', 'support').next_run,
|
|
'2030-01-01T00:00:30.000Z',
|
|
)
|
|
const settings = readMailSettings(s, s.user('admin'), 'support')
|
|
saveMailSettings(s, s.user('admin'), 'support', {
|
|
...settings,
|
|
imap: { ...settings.imap, enabled: false },
|
|
})
|
|
await worker.due()
|
|
assert.equal(record.filter((x) => x.connect).length, 1)
|
|
} finally {
|
|
db?.close()
|
|
rmSync(dir, { recursive: true, force: true })
|
|
}
|
|
})
|
|
test('Concurrent fetches are rejected and config changes during network I/O prevent stale imports', async () => {
|
|
const { db, s, admin } = setup()
|
|
try {
|
|
configureImap(s, admin, 'support')
|
|
let release
|
|
const gate = new Promise((r) => (release = r))
|
|
const worker = new InboundWorker(s, {
|
|
clientFactory: fakeImap(new Map([[1, mime(1)]]), [], {
|
|
connect: () => gate,
|
|
source: () => {
|
|
const c = readMailSettings(s, admin, 'support')
|
|
saveMailSettings(s, admin, 'support', { ...c, imap: { ...c.imap, enabled: false } })
|
|
},
|
|
}),
|
|
})
|
|
const first = worker.run('support')
|
|
await assert.rejects(worker.run('support'), { status: 409 })
|
|
release()
|
|
const result = await first
|
|
assert.equal(result.imported, 0)
|
|
assert.equal(s.all("SELECT * FROM messages WHERE message_id='<imap-1@example.com>'").length, 0)
|
|
assert.equal(
|
|
s.get('SELECT next_run FROM queue_inbound WHERE queue_id=?', 'support').next_run,
|
|
null,
|
|
)
|
|
} finally {
|
|
db.close()
|
|
}
|
|
})
|
|
test('Queue SMTP secrets are encrypted, redacted, preserved on blank updates and permission checked', () => {
|
|
const { db, s, admin, agent, reader } = setup()
|
|
try {
|
|
assert.throws(() => readMailSettings(s, reader, 'support'), { status: 403 })
|
|
const config = readMailSettings(s, admin, 'support')
|
|
const data = {
|
|
...config,
|
|
smtp: {
|
|
mode: 'smtp',
|
|
host: 'smtp.support.invalid',
|
|
port: 465,
|
|
security: 'tls',
|
|
username: 'support-user',
|
|
},
|
|
password: 'super-secret-credential',
|
|
}
|
|
assert.throws(() => saveMailSettings(s, agent, 'support', data), { status: 403 })
|
|
const result = saveMailSettings(s, admin, 'support', data)
|
|
assert.equal(result.passwordSet, true)
|
|
assert(!JSON.stringify(result).includes(data.password))
|
|
const row = s.get('SELECT * FROM queue_mail WHERE queue_id=?', 'support')
|
|
assert(!JSON.stringify(row).includes(data.password))
|
|
assert(!JSON.stringify(s.all('SELECT * FROM audits')).includes(data.password))
|
|
assert.equal(readMailSettings(s, admin, 'vertrieb').smtp.mode, 'development')
|
|
saveMailSettings(s, admin, 'support', { ...result, password: '' })
|
|
assert.throws(
|
|
() =>
|
|
saveMailSettings(s, admin, 'support', {
|
|
...result,
|
|
smtp: { ...result.smtp, host: 'smtp.other.invalid' },
|
|
password: '',
|
|
}),
|
|
{ status: 400 },
|
|
)
|
|
let options
|
|
smtpTransport(s, 'support', (o) => {
|
|
options = o
|
|
return {}
|
|
})
|
|
assert.equal(options.auth.pass, data.password)
|
|
assert.equal(options.secure, true)
|
|
assert.throws(() => saveMailSettings(s, admin, 'support', { ...result, clearPassword: true }), {
|
|
status: 400,
|
|
})
|
|
assert.equal(
|
|
s.get('SELECT password FROM queue_mail WHERE queue_id=?', 'support').password,
|
|
row.password,
|
|
)
|
|
} finally {
|
|
db.close()
|
|
}
|
|
})
|
|
test('SMTP transport routing uses each ticket queue including queued automatic acknowledgements', async () => {
|
|
const { db, s, admin } = setup()
|
|
try {
|
|
for (const q of ['support', 'vertrieb']) {
|
|
const c = readMailSettings(s, admin, q)
|
|
saveMailSettings(s, admin, q, {
|
|
...c,
|
|
smtp: {
|
|
mode: 'smtp',
|
|
host: `smtp.${q}.invalid`,
|
|
port: q === 'support' ? 465 : 587,
|
|
security: q === 'support' ? 'tls' : 'starttls',
|
|
username: q,
|
|
},
|
|
password: q + '-password',
|
|
acknowledgement: { ...c.acknowledgement, enabled: true },
|
|
})
|
|
s.ingest(mail(q))
|
|
}
|
|
const sent = []
|
|
const worker = new Worker(s, {
|
|
transportFactory: (options) => ({
|
|
sendMail: async (payload) => {
|
|
sent.push({ options, payload })
|
|
},
|
|
close() {},
|
|
}),
|
|
})
|
|
await worker.tick()
|
|
await worker.tick()
|
|
assert.equal(sent.length, 2)
|
|
for (const { options, payload } of sent) {
|
|
const q = options.auth.user
|
|
assert.equal(options.host, `smtp.${q}.invalid`)
|
|
assert.equal(options.auth.pass, q + '-password')
|
|
assert.equal(payload.from, `${q}@syncova.local`)
|
|
assert.equal(payload.headers['Auto-Submitted'], 'auto-generated')
|
|
assert.equal(options.secure, q === 'support')
|
|
assert.equal(options.requireTLS, q === 'vertrieb')
|
|
}
|
|
assert.equal(s.all('SELECT * FROM dev_mail').length, 0)
|
|
assert(s.all('SELECT state FROM outbox').every((j) => j.state === 'sent'))
|
|
} finally {
|
|
db.close()
|
|
}
|
|
})
|
|
test('Automatic acknowledgements are opt-in, queue-local, transactional, threaded, signed and exactly once per new ticket', async () => {
|
|
const { db, s, admin } = setup()
|
|
try {
|
|
s.ingest(mail())
|
|
assert.equal(s.all('SELECT * FROM outbox').length, 0)
|
|
const config = readMailSettings(s, admin, 'support')
|
|
saveMailSettings(s, admin, 'support', {
|
|
...config,
|
|
acknowledgement: {
|
|
enabled: true,
|
|
subject: 'Eingang {ticketnummer}: {betreff}',
|
|
body: 'Hallo {kundenname}, Ihre Anfrage ist bei {queue} eingegangen.',
|
|
includeSignature: true,
|
|
},
|
|
})
|
|
const incoming = mail('support', { name: 'Anna Beispiel' }),
|
|
id = s.ingest(incoming).ticket_id
|
|
s.ingest(incoming)
|
|
assert.equal(s.all('SELECT * FROM outbox').length, 1)
|
|
const auto = s.detail(admin, id).messages.find((m) => m.kind === 'outgoing')
|
|
assert(auto.body.includes('Anna Beispiel'))
|
|
assert(auto.body.includes('Support'))
|
|
assert(auto.body.endsWith(s.queue('support').signatures[0].body))
|
|
s.ingest(mail('support', { references: [auto.message_id], subject: 'Neuer Betreff' }))
|
|
assert.equal(s.detail(admin, id).messages.length, 3)
|
|
assert.equal(s.all('SELECT * FROM outbox').length, 1)
|
|
s.ingest(mail('vertrieb'))
|
|
assert.equal(s.all('SELECT * FROM outbox').length, 1)
|
|
assert(s.ingest(mail('support', { autoSubmitted: 'auto-generated' })).ignored)
|
|
assert(s.ingest(mail('support', { precedence: 'bulk' })).ignored)
|
|
const worker = new Worker(s)
|
|
await worker.tick()
|
|
await worker.tick()
|
|
assert.equal(s.all('SELECT * FROM dev_mail').length, 1)
|
|
assert(s.detail(admin, id).activities.some((a) => a.actor === 'Eingangsbestätigung'))
|
|
assert.throws(
|
|
() =>
|
|
saveMailSettings(s, admin, 'support', {
|
|
...config,
|
|
acknowledgement: { ...config.acknowledgement, body: '{unknown}' },
|
|
}),
|
|
{ status: 400 },
|
|
)
|
|
} finally {
|
|
db.close()
|
|
}
|
|
})
|
|
test('IANA local times resolve correct winter/summer offsets and reject DST gaps', () => {
|
|
assert.equal(scheduledTime('2026-11-05T14:30', 'Europe/Berlin'), '2026-11-05T13:30:00.000Z')
|
|
assert.equal(scheduledTime('2026-07-05T14:30', 'Europe/Berlin'), '2026-07-05T12:30:00.000Z')
|
|
assert.throws(() => scheduledTime('2026-03-29T02:30', 'Europe/Berlin'))
|
|
assert.throws(() => scheduledTime('2026-11-05T14:30', 'invalid/zone'))
|
|
})
|
|
test('Queue isolation covers list, detail, changes, notifications, attachments and logs', () => {
|
|
const { db, s, agent, reader, admin } = setup()
|
|
try {
|
|
const id = s.ingest(
|
|
mail('vertrieb', {
|
|
attachments: [
|
|
{
|
|
name: 'a.html',
|
|
mime: 'text/html',
|
|
content: Buffer.from('<script>alert(1)</script>').toString('base64'),
|
|
},
|
|
],
|
|
}),
|
|
).ticket_id
|
|
assert(!s.tickets(agent).some((t) => t.id === id))
|
|
assert.throws(() => s.detail(agent, id), { status: 403 })
|
|
assert.throws(
|
|
() => s.reply(agent, id, { body: 'x', from: 'vertrieb@syncova.local', key: uid() }),
|
|
{ status: 403 },
|
|
)
|
|
assert(!s.notifications(agent).some((n) => n.ticket_id === id))
|
|
assert.throws(() => s.updateTicket(agent, s.tickets(agent)[0].id, { queue_id: 'vertrieb' }), {
|
|
status: 403,
|
|
})
|
|
assert.throws(() => s.reply(reader, s.tickets(reader)[0].id, { body: 'x', key: uid() }), {
|
|
status: 403,
|
|
})
|
|
assert.throws(() => s.saveQueue(agent, 'support', s.queue('support')), { status: 403 })
|
|
assert.equal(s.detail(admin, id).messages[0].attachments[0].mime, 'text/html')
|
|
} finally {
|
|
db.close()
|
|
}
|
|
})
|
|
test('Two queues, multiple addresses, references, changed subjects and duplicate inbound messages', () => {
|
|
const { db, s, admin } = setup()
|
|
try {
|
|
let a = mail('support', { to: ['support.team@syncova.local'] })
|
|
const id = s.ingest(a).ticket_id
|
|
const sales = s.ingest(mail('vertrieb')).ticket_id
|
|
assert.notEqual(id, sales)
|
|
assert(s.ingest(a).duplicate)
|
|
const reply = mail('support', { subject: 'Völlig anderer Betreff', references: [a.messageId] })
|
|
assert.equal(s.ingest(reply).ticket_id, id)
|
|
assert.notEqual(s.ingest(mail('support', { subject: a.subject })).ticket_id, id)
|
|
assert.notEqual(s.ingest(mail('vertrieb', { references: [a.messageId] })).ticket_id, id)
|
|
assert.notEqual(
|
|
s.ingest(mail('support', { from: 'other@example.com', references: [a.messageId] })).ticket_id,
|
|
id,
|
|
)
|
|
assert.equal(s.detail(admin, id).messages.length, 2)
|
|
assert(s.ingest(mail('support', { autoSubmitted: 'auto-replied' })).ignored)
|
|
assert(s.ingest(mail('support', { from: 'vertrieb@syncova.local' })).ignored)
|
|
} finally {
|
|
db.close()
|
|
}
|
|
})
|
|
test('Waiting for customer reopens only on a genuine referenced customer reply', () => {
|
|
const { db, s, admin } = setup()
|
|
try {
|
|
const m = mail()
|
|
const id = s.ingest(m).ticket_id
|
|
s.updateTicket(admin, id, { status_id: status(s, 'support', 'wait_customer') })
|
|
s.ingest(mail('support', { references: [m.messageId] }))
|
|
assert.equal(s.detail(admin, id).status_id, status(s, 'support', 'open'))
|
|
assert(s.detail(admin, id).activities.some((a) => a.actor === 'Kundenantwort'))
|
|
} finally {
|
|
db.close()
|
|
}
|
|
})
|
|
test('Persisted deadlines survive restart and obsolete deadlines cannot fire', () => {
|
|
const dir = mkdtempSync(path.join(os.tmpdir(), 'syncova-test-'))
|
|
let db
|
|
try {
|
|
let ctx = setup(path.join(dir, 'test.db'))
|
|
db = ctx.db
|
|
const id = ctx.s.ingest(mail()).ticket_id
|
|
const id2 = ctx.s.ingest(mail()).ticket_id
|
|
for (const i of [id, id2])
|
|
ctx.s.updateTicket(ctx.admin, i, {
|
|
status_id: status(ctx.s, 'support', 'wait_date'),
|
|
due_at: '2020-01-01T12:00:00+01:00',
|
|
timezone: 'Europe/Berlin',
|
|
})
|
|
ctx.s.updateTicket(ctx.admin, id2, { status_id: status(ctx.s, 'support', 'active') })
|
|
db.close()
|
|
db = openDb(path.join(dir, 'test.db'))
|
|
const s = new Service(db)
|
|
assert.equal(s.due(), 1)
|
|
assert.equal(s.due(), 0)
|
|
assert.equal(s.detail(s.user('admin'), id).due_at, null)
|
|
assert.equal(s.detail(s.user('admin'), id2).status_id, status(s, 'support', 'active'))
|
|
assert.equal(
|
|
s.notifications(s.user('admin')).filter((n) => n.ticket_id === id && n.event === 'reopened')
|
|
.length,
|
|
1,
|
|
)
|
|
} finally {
|
|
db?.close()
|
|
rmSync(dir, { recursive: true, force: true })
|
|
}
|
|
})
|
|
test('Goods receipt is permission checked and audited; repeated confirmation is rejected', () => {
|
|
const { db, s, admin, reader } = setup()
|
|
try {
|
|
const id = s.ingest(mail()).ticket_id
|
|
s.updateTicket(admin, id, { status_id: status(s, 'support', 'wait_goods') })
|
|
assert.throws(() => s.goods(reader, id), { status: 403 })
|
|
s.goods(admin, id)
|
|
assert.equal(s.detail(admin, id).status_id, status(s, 'support', 'open'))
|
|
assert(s.detail(admin, id).activities.some((a) => a.action === 'Wareneingang bestätigt'))
|
|
assert.throws(() => s.goods(admin, id), { status: 409 })
|
|
} finally {
|
|
db.close()
|
|
}
|
|
})
|
|
test('Queue-local status rename, mandatory open target, replacement mapping, rollback', () => {
|
|
const { db, s, admin } = setup()
|
|
try {
|
|
const q = s.queue('support'),
|
|
other = s.queue('vertrieb')
|
|
const id = s.ingest(mail()).ticket_id
|
|
q.statuses.find((x) => x.behavior === 'new').name = 'Eingang'
|
|
s.saveStatuses(admin, q.id, q.statuses)
|
|
assert.deepEqual(s.queue('vertrieb').statuses, other.statuses)
|
|
assert.equal(s.detail(admin, id).status_id, status(s, 'support', 'new'))
|
|
const old = status(s, 'support', 'new')
|
|
q.statuses.find((x) => x.id === old).active = 0
|
|
assert.throws(() => s.saveStatuses(admin, q.id, q.statuses), { status: 409 })
|
|
assert.equal(s.queue('support').statuses.find((x) => x.id === old).active, 1)
|
|
s.saveStatuses(admin, q.id, q.statuses, { [old]: status(s, 'support', 'open') })
|
|
assert.equal(s.detail(admin, id).status_id, status(s, 'support', 'open'))
|
|
const noOpen = s
|
|
.queue('support')
|
|
.statuses.map((x) => ({ ...x, active: x.behavior === 'open' ? 0 : x.active }))
|
|
assert.throws(() => s.saveStatuses(admin, q.id, noOpen), { status: 400 })
|
|
} finally {
|
|
db.close()
|
|
}
|
|
})
|
|
test('Allowed sender only, stable reply key, internal notes never enter outbox, exact-once dev delivery', async () => {
|
|
const { db, s, admin } = setup()
|
|
try {
|
|
const id = s.ingest(mail()).ticket_id
|
|
assert.throws(
|
|
() =>
|
|
s.reply(admin, id, {
|
|
kind: 'outgoing',
|
|
body: 'test',
|
|
from: 'vertrieb@syncova.local',
|
|
key: uid(),
|
|
}),
|
|
{ status: 400 },
|
|
)
|
|
const data = {
|
|
kind: 'outgoing',
|
|
body: 'Hallo\n\nFreundliche Grüße\nIhr Support-Team\nSyncova',
|
|
from: 'support@syncova.local',
|
|
key: uid(),
|
|
}
|
|
const first = s.reply(admin, id, data)
|
|
assert.equal(s.reply(admin, id, data).id, first.id)
|
|
s.reply(admin, id, { kind: 'note', body: 'Intern', key: uid() })
|
|
assert.equal(s.all('SELECT * FROM outbox').length, 1)
|
|
const worker = new Worker(s)
|
|
await worker.tick()
|
|
await worker.tick()
|
|
assert.equal(s.all('SELECT * FROM dev_mail').length, 1)
|
|
assert.equal(s.detail(admin, id).messages.find((m) => m.id === first.id).delivery, 'sent')
|
|
assert(s.detail(admin, id).activities.some((a) => a.action === 'E-Mail versendet'))
|
|
assert.throws(() => s.run('DELETE FROM audits'), /immutable/)
|
|
} finally {
|
|
db.close()
|
|
}
|
|
})
|
|
test('Notification union, idempotency, revocation at creation, display and delivery', async () => {
|
|
const { db, s, admin, agent } = setup()
|
|
try {
|
|
s.run(
|
|
'UPDATE users SET prefs=? WHERE id=?',
|
|
JSON.stringify({ new: { bell: true, email: true } }),
|
|
agent.id,
|
|
)
|
|
const m = mail()
|
|
const id = s.ingest(m).ticket_id
|
|
s.ingest(m)
|
|
assert.equal(s.notifications(agent).filter((n) => n.ticket_id === id).length, 1)
|
|
assert.equal(s.all('SELECT * FROM outbox').length, 1)
|
|
s.run('INSERT INTO memberships VALUES(?,?)', agent.id, 'reader')
|
|
assert(s.can(agent, 'support', 'reply'))
|
|
s.run('DELETE FROM memberships WHERE user_id=?', agent.id)
|
|
assert.equal(s.notifications(agent).length, 0)
|
|
await new Worker(s).tick()
|
|
assert.equal(s.all('SELECT * FROM dev_mail').length, 0)
|
|
assert.equal(s.get('SELECT state FROM outbox').state, 'cancelled')
|
|
} finally {
|
|
db.close()
|
|
}
|
|
})
|
|
test('Queue moves map behavior, clear ownership, reject stale writes and blocked sender configuration', () => {
|
|
const { db, s, admin } = setup()
|
|
try {
|
|
const id = s.ingest(mail()).ticket_id
|
|
s.updateTicket(admin, id, { status_id: status(s, 'support', 'active'), assignee: 'admin' })
|
|
const t = s.detail(admin, id)
|
|
s.updateTicket(admin, id, { queue_id: 'vertrieb', revision: t.revision })
|
|
const moved = s.detail(admin, id)
|
|
assert.equal(moved.status_id, status(s, 'vertrieb', 'active'))
|
|
assert.equal(moved.assignee, null)
|
|
assert.throws(() => s.updateTicket(admin, id, { revision: t.revision, assignee: 'admin' }), {
|
|
status: 409,
|
|
})
|
|
assert.throws(() => s.updateTicket(admin, id, { assignee: 'leon' }), { status: 400 })
|
|
assert.throws(
|
|
() =>
|
|
s.saveQueue(admin, 'vertrieb', {
|
|
...s.queue('vertrieb'),
|
|
addresses: [
|
|
{ email: 'support@syncova.local', incoming: true, outgoing: true, default: true },
|
|
],
|
|
}),
|
|
{ status: 409 },
|
|
)
|
|
} finally {
|
|
db.close()
|
|
}
|
|
})
|
|
test('HTTP production: proxy client IPs have separate login limits and secure session headers', async () => {
|
|
const { db, admin } = setup(),
|
|
fields = ['NODE_ENV', 'APP_ORIGIN', 'COOKIE_SECURE', 'TRUST_PROXY'],
|
|
prior = Object.fromEntries(fields.map((k) => [k, process.env[k]]))
|
|
Object.assign(process.env, {
|
|
NODE_ENV: 'production',
|
|
APP_ORIGIN: 'https://tickets.example.org',
|
|
COOKIE_SECURE: 'true',
|
|
TRUST_PROXY: '1',
|
|
})
|
|
const { app } = createApp(db),
|
|
server = app.listen(0, '127.0.0.1')
|
|
await new Promise((r) => server.once('listening', r))
|
|
const url = `http://127.0.0.1:${server.address().port}/api/login`
|
|
const login = (
|
|
ip,
|
|
email = 'unknown@example.invalid',
|
|
password = 'wrong',
|
|
origin = 'https://tickets.example.org',
|
|
) =>
|
|
fetch(url, {
|
|
method: 'POST',
|
|
headers: {
|
|
'Content-Type': 'application/json',
|
|
'X-Forwarded-For': ip,
|
|
'X-Forwarded-Proto': 'https',
|
|
Origin: origin,
|
|
},
|
|
body: JSON.stringify({ email, password }),
|
|
})
|
|
try {
|
|
for (let i = 0; i < 15; i++) assert.equal((await login('192.0.2.1')).status, 401)
|
|
assert.equal((await login('192.0.2.1')).status, 429)
|
|
assert.equal((await login('192.0.2.2')).status, 401)
|
|
assert.equal(
|
|
(await login('192.0.2.3', admin.email, 'Syncova-Demo-2026!', 'https://evil.example')).status,
|
|
403,
|
|
)
|
|
const response = await login('192.0.2.3', admin.email, 'Syncova-Demo-2026!')
|
|
assert.equal(response.status, 200)
|
|
assert.match(response.headers.get('set-cookie'), /HttpOnly; SameSite=Strict;.*Secure/)
|
|
assert.equal(response.headers.get('strict-transport-security'), 'max-age=31536000')
|
|
assert.match(response.headers.get('content-security-policy'), /script-src 'self';/)
|
|
} finally {
|
|
server.closeAllConnections()
|
|
await new Promise((r) => server.close(r))
|
|
for (const field of fields) {
|
|
if (prior[field] === undefined) delete process.env[field]
|
|
else process.env[field] = prior[field]
|
|
}
|
|
db.close()
|
|
}
|
|
})
|
|
test('HTTP: identity deletion requires administration, confirmation and same-origin access; deleted sessions fail immediately', async () => {
|
|
const { db, s, admin, agent, reader } = setup(),
|
|
{ app } = createApp(db)
|
|
const server = app.listen(0, '127.0.0.1')
|
|
await new Promise((r) => server.once('listening', r))
|
|
const base = `http://127.0.0.1:${server.address().port}`
|
|
const call = (url, method = 'GET', body, cookie = '', extra = {}) =>
|
|
fetch(base + '/api' + url, {
|
|
method,
|
|
headers: { cookie, 'Content-Type': 'application/json', ...extra },
|
|
...(body === undefined ? {} : { body: JSON.stringify(body) }),
|
|
})
|
|
try {
|
|
const login = async (email) => {
|
|
const r = await call('/login', 'POST', { email, password: 'Syncova-Demo-2026!' })
|
|
assert.equal(r.status, 200)
|
|
return r.headers.get('set-cookie').split(';')[0]
|
|
}
|
|
const adminCookie = await login(admin.email),
|
|
agentCookie = await login(agent.email)
|
|
assert.equal((await call('/users/leon', 'DELETE', { confirm: agent.email })).status, 401)
|
|
assert.equal(
|
|
(await call('/users/mira', 'DELETE', { confirm: reader.email }, agentCookie)).status,
|
|
403,
|
|
)
|
|
assert.equal((await call('/groups/agent/deletion', 'GET', undefined, agentCookie)).status, 403)
|
|
assert.equal(
|
|
(await call('/groups/agent', 'DELETE', { confirm: 'Bearbeiter' }, agentCookie)).status,
|
|
403,
|
|
)
|
|
assert.equal(
|
|
(await call('/users/admin', 'DELETE', { confirm: admin.email }, adminCookie)).status,
|
|
409,
|
|
)
|
|
assert.equal(
|
|
(await call('/groups/admins', 'DELETE', { confirm: 'Administrator' }, adminCookie)).status,
|
|
409,
|
|
)
|
|
assert.equal(
|
|
(
|
|
await call('/users/mira', 'DELETE', { confirm: reader.email }, adminCookie, {
|
|
Origin: 'https://evil.example',
|
|
})
|
|
).status,
|
|
403,
|
|
)
|
|
assert.equal(
|
|
(await call('/groups/reader', 'DELETE', { confirm: 'falsch' }, adminCookie)).status,
|
|
400,
|
|
)
|
|
const groupPreview = await call('/groups/reader/deletion', 'GET', undefined, adminCookie)
|
|
assert.equal(groupPreview.status, 200)
|
|
assert.equal((await groupPreview.json()).members, 1)
|
|
assert.equal(
|
|
(await call('/groups/reader', 'DELETE', { confirm: 'Leser' }, adminCookie)).status,
|
|
200,
|
|
)
|
|
assert.equal((await call('/groups/reader/deletion', 'GET', undefined, adminCookie)).status, 404)
|
|
assert.equal((await call('/users/leon/deletion', 'GET', undefined, adminCookie)).status, 200)
|
|
assert.equal(
|
|
(await call('/users/leon', 'DELETE', { confirm: agent.email }, adminCookie)).status,
|
|
200,
|
|
)
|
|
assert.equal((await call('/bootstrap', 'GET', undefined, agentCookie)).status, 401)
|
|
assert.equal(
|
|
(await call('/login', 'POST', { email: agent.email, password: 'Syncova-Demo-2026!' })).status,
|
|
401,
|
|
)
|
|
assert.equal((await call('/bootstrap', 'GET', undefined, adminCookie)).status, 200)
|
|
const data = await (await call('/admin', 'GET', undefined, adminCookie)).json()
|
|
assert(!data.users.some((u) => u.id === agent.id))
|
|
assert(!data.groups.some((g) => g.id === 'reader'))
|
|
} finally {
|
|
server.closeAllConnections()
|
|
await new Promise((r) => server.close(r))
|
|
db.close()
|
|
}
|
|
})
|
|
test('HTTP: sessions, origin guard, unauthorized direct access and attachment isolation', async () => {
|
|
const { db, s } = setup()
|
|
const { app } = createApp(db)
|
|
app.locals.worker = new Worker(s)
|
|
const server = app.listen(0, '127.0.0.1')
|
|
await new Promise((r) => server.once('listening', r))
|
|
const base = `http://127.0.0.1:${server.address().port}`
|
|
try {
|
|
assert.equal((await fetch(base + '/api/tickets')).status, 401)
|
|
const r = await fetch(base + '/api/login', {
|
|
method: 'POST',
|
|
headers: { 'Content-Type': 'application/json' },
|
|
body: JSON.stringify({ email: 'leon@syncova.local', password: 'Syncova-Demo-2026!' }),
|
|
})
|
|
assert.equal(r.status, 200)
|
|
const cookie = r.headers.get('set-cookie').split(';')[0]
|
|
const manual = {
|
|
queue_id: 'support',
|
|
customer: 'phone@example.com',
|
|
customer_name: 'Telefonkontakt',
|
|
subject: 'Manuell über HTTP',
|
|
body: 'Bitte zurückrufen',
|
|
key: uid(),
|
|
}
|
|
const created = await fetch(base + '/api/tickets', {
|
|
method: 'POST',
|
|
headers: { cookie, 'Content-Type': 'application/json' },
|
|
body: JSON.stringify(manual),
|
|
})
|
|
assert.equal(created.status, 200)
|
|
const manualTicket = await created.json()
|
|
assert.equal(manualTicket.messages[0].kind, 'manual')
|
|
const signatures = s.queue('support').signatures
|
|
s.saveSignatures(s.user('admin'), 'support', [
|
|
{ ...signatures[0], body: '{benutzer.name} / {ticket.nummer} / {kunde.name}' },
|
|
])
|
|
const previewResponse = await fetch(
|
|
`${base}/api/tickets/${manualTicket.id}/signature-preview`,
|
|
{
|
|
method: 'POST',
|
|
headers: { cookie, 'Content-Type': 'application/json' },
|
|
body: JSON.stringify({
|
|
signature_id: signatures[0].id,
|
|
from: 'support@syncova.local',
|
|
user_id: 'admin',
|
|
}),
|
|
},
|
|
)
|
|
assert.equal(previewResponse.status, 200)
|
|
const preview = await previewResponse.json()
|
|
assert.equal(
|
|
preview.text,
|
|
`Leon Fischer / SYN-${String(manualTicket.id).padStart(5, '0')} / Telefonkontakt`,
|
|
)
|
|
const sent = await fetch(`${base}/api/tickets/${manualTicket.id}/messages`, {
|
|
method: 'POST',
|
|
headers: { cookie, 'Content-Type': 'application/json' },
|
|
body: JSON.stringify({
|
|
key: uid(),
|
|
body: 'Antwort',
|
|
from: 'support@syncova.local',
|
|
signature_id: signatures[0].id,
|
|
}),
|
|
})
|
|
assert.equal(sent.status, 200)
|
|
assert(
|
|
s
|
|
.get("SELECT body FROM messages WHERE ticket_id=? AND kind='outgoing'", manualTicket.id)
|
|
.body.endsWith(preview.text),
|
|
)
|
|
assert.equal(
|
|
(
|
|
await fetch(`${base}/api/queues/support/signatures/preview`, {
|
|
method: 'POST',
|
|
headers: { cookie, 'Content-Type': 'application/json' },
|
|
body: JSON.stringify({ body: '{benutzer.name}' }),
|
|
})
|
|
).status,
|
|
403,
|
|
)
|
|
assert.equal(
|
|
(
|
|
await fetch(`${base}/api/tickets/${manualTicket.id}/signature-preview`, {
|
|
method: 'POST',
|
|
headers: { cookie, 'Content-Type': 'application/json' },
|
|
body: JSON.stringify({ signature_id: s.queue('vertrieb').signatures[0].id }),
|
|
})
|
|
).status,
|
|
400,
|
|
)
|
|
const duplicate = await (
|
|
await fetch(base + '/api/tickets', {
|
|
method: 'POST',
|
|
headers: { cookie, 'Content-Type': 'application/json' },
|
|
body: JSON.stringify(manual),
|
|
})
|
|
).json()
|
|
assert.equal(duplicate.id, manualTicket.id)
|
|
for (const route of [
|
|
'/api/queues/support/mail',
|
|
'/api/queues/support/mail/fetch',
|
|
'/api/queues/support/mail/verify-imap',
|
|
])
|
|
assert.equal(
|
|
(
|
|
await fetch(base + route, {
|
|
method: route.endsWith('/mail') ? 'GET' : 'POST',
|
|
headers: { cookie, 'Content-Type': 'application/json' },
|
|
...(route.endsWith('/mail') ? {} : { body: '{}' }),
|
|
})
|
|
).status,
|
|
403,
|
|
)
|
|
const id = s.ingest(
|
|
mail('vertrieb', { attachments: [{ name: 'secret.txt', content: 'YQ==' }] }),
|
|
).ticket_id
|
|
const a = s.all(
|
|
'SELECT a.id FROM attachments a JOIN messages m ON m.id=a.message_id WHERE m.ticket_id=?',
|
|
id,
|
|
)[0]
|
|
assert.equal((await fetch(`${base}/api/tickets/${id}`, { headers: { cookie } })).status, 403)
|
|
assert.equal(
|
|
(
|
|
await fetch(`${base}/api/tickets/${id}/signature-preview`, {
|
|
method: 'POST',
|
|
headers: { cookie, 'Content-Type': 'application/json' },
|
|
body: '{}',
|
|
})
|
|
).status,
|
|
403,
|
|
)
|
|
assert.equal(
|
|
(await fetch(`${base}/api/attachments/${a.id}`, { headers: { cookie } })).status,
|
|
403,
|
|
)
|
|
assert.equal(
|
|
(
|
|
await fetch(base + '/api/preferences', {
|
|
method: 'PUT',
|
|
headers: { cookie, Origin: 'https://evil.example', 'Content-Type': 'application/json' },
|
|
body: '{}',
|
|
})
|
|
).status,
|
|
403,
|
|
)
|
|
const rows = await (await fetch(base + '/api/tickets', { headers: { cookie } })).json()
|
|
assert(rows.every((t) => t.queue_id === 'support'))
|
|
} finally {
|
|
server.closeAllConnections()
|
|
await new Promise((r) => server.close(r))
|
|
db.close()
|
|
}
|
|
})
|