332 lines
17 KiB
JavaScript
332 lines
17 KiB
JavaScript
import { createHash, randomUUID } from 'node:crypto'
|
|
import { rm } from 'node:fs/promises'
|
|
import { join } from 'node:path'
|
|
import { fileURLToPath } from 'node:url'
|
|
import compression from 'compression'
|
|
import express from 'express'
|
|
import helmet from 'helmet'
|
|
import multer from 'multer'
|
|
import { z } from 'zod'
|
|
import { boardSchema, email, password, uploadLimit, userSchema } from './config.js'
|
|
import { assetColumns, boardColumns, HttpError, initialise, newToken, pool, setReferences, transaction, userColumns } from './db.js'
|
|
import { mediaDir, prepareStorage, renderPage, saveUpload, staging } from './media.js'
|
|
import { getSession, hashPassword, limitLogin, makeSession, sessionCookie, sessionHash, sessionLifetime, sessionOptions, verifyPassword } from './security.js'
|
|
|
|
const app = express()
|
|
const port = Number(process.env.PORT || 8080)
|
|
const dist = fileURLToPath(new URL('../dist', import.meta.url))
|
|
const uuid = z.uuid()
|
|
const boardSave = z.object({ board: boardSchema, revision: z.number().int().positive(), publish: z.boolean().default(false) })
|
|
const revisionSchema = z.object({ revision: z.number().int().positive() })
|
|
const safeUser = user => ({ id: user.id, name: user.name, email: user.email, role: user.role, active: user.active, created_at: user.created_at })
|
|
const upload = multer({ dest: staging, limits: { fileSize: uploadLimit, files: 1, fields: 0, parts: 2 }, defParamCharset: 'utf8' })
|
|
let uploads = 0
|
|
|
|
app.disable('x-powered-by')
|
|
if (process.env.TRUST_PROXY_HOPS) app.set('trust proxy', Number(process.env.TRUST_PROXY_HOPS))
|
|
app.use(helmet({
|
|
contentSecurityPolicy: {
|
|
directives: {
|
|
imgSrc: ["'self'", 'data:', 'https:'],
|
|
scriptSrc: ["'self'"], styleSrc: ["'self'", "'unsafe-inline'"],
|
|
frameAncestors: ["'self'"], upgradeInsecureRequests: null,
|
|
},
|
|
},
|
|
referrerPolicy: { policy: 'no-referrer' },
|
|
strictTransportSecurity: sessionOptions.secure,
|
|
xFrameOptions: { action: 'sameorigin' },
|
|
}))
|
|
app.use(compression())
|
|
app.use('/api', (req, res, next) => {
|
|
res.set('Cache-Control', 'no-store')
|
|
if (!['GET', 'HEAD', 'OPTIONS'].includes(req.method) && ['cross-site', 'same-site'].includes(req.get('Sec-Fetch-Site'))) {
|
|
return next(new HttpError(403, 'Die Anfrage stammt von einer fremden Seite.'))
|
|
}
|
|
next()
|
|
})
|
|
app.use('/api', express.json({ limit: '1mb' }))
|
|
|
|
app.get('/api/health', async (_req, res) => {
|
|
await pool.query('SELECT 1')
|
|
res.json({ status: 'ok' })
|
|
})
|
|
|
|
async function requireUser(req, _res, next) {
|
|
const token = getSession(req)
|
|
if (!token) throw new HttpError(401, 'Bitte melde dich an.')
|
|
const { rows: [user] } = await pool.query(
|
|
'SELECT u.* FROM users u JOIN sessions s ON s.user_id=u.id WHERE s.token_hash=$1 AND s.expires_at > now() AND u.active',
|
|
[sessionHash(token)],
|
|
)
|
|
if (!user) throw new HttpError(401, 'Deine Sitzung ist abgelaufen. Bitte melde dich erneut an.')
|
|
req.user = user
|
|
next()
|
|
}
|
|
|
|
function requireAdmin(req, _res, next) {
|
|
if (req.user.role !== 'admin') throw new HttpError(403, 'Diese Aktion erfordert ein Administrationskonto.')
|
|
next()
|
|
}
|
|
|
|
app.post('/api/auth/login', limitLogin, async (req, res) => {
|
|
const parsed = z.object({ email, password: z.string().min(1).max(256) }).safeParse(req.body)
|
|
if (!parsed.success) throw new HttpError(401, 'E-Mail oder Passwort stimmt nicht.')
|
|
const { rows: [user] } = await pool.query('SELECT * FROM users WHERE email=$1', [parsed.data.email])
|
|
const valid = await verifyPassword(parsed.data.password, user?.password)
|
|
if (!valid || !user?.active) throw new HttpError(401, 'E-Mail oder Passwort stimmt nicht.')
|
|
const token = makeSession()
|
|
await transaction(async client => {
|
|
const { rowCount } = await client.query('SELECT id FROM users WHERE id=$1 AND password=$2 AND active FOR SHARE', [user.id, user.password])
|
|
if (!rowCount) throw new HttpError(401, 'E-Mail oder Passwort stimmt nicht.')
|
|
await client.query('DELETE FROM sessions WHERE expires_at <= now()')
|
|
await client.query('INSERT INTO sessions (token_hash,user_id,expires_at) VALUES ($1,$2,$3)', [sessionHash(token), user.id, new Date(Date.now() + sessionLifetime)])
|
|
})
|
|
res.cookie(sessionCookie, token, { ...sessionOptions, maxAge: sessionLifetime }).json(safeUser(user))
|
|
})
|
|
|
|
app.get('/api/auth/me', requireUser, (req, res) => res.json(safeUser(req.user)))
|
|
app.post('/api/auth/logout', async (req, res) => {
|
|
const token = getSession(req)
|
|
if (token) await pool.query('DELETE FROM sessions WHERE token_hash=$1', [sessionHash(token)])
|
|
res.clearCookie(sessionCookie, sessionOptions).status(204).end()
|
|
})
|
|
app.put('/api/auth/password', requireUser, async (req, res) => {
|
|
const input = z.object({ current: z.string().min(1).max(256), password }).parse(req.body)
|
|
if (!await verifyPassword(input.current, req.user.password)) throw new HttpError(422, 'Das bisherige Passwort stimmt nicht.')
|
|
const hashed = await hashPassword(input.password)
|
|
const tokenHash = sessionHash(getSession(req))
|
|
await transaction(async client => {
|
|
const result = await client.query('UPDATE users SET password=$1 WHERE id=$2 AND password=$3', [hashed, req.user.id, req.user.password])
|
|
if (!result.rowCount) throw new HttpError(409, 'Das Passwort wurde zwischenzeitlich geändert.')
|
|
await client.query('DELETE FROM sessions WHERE user_id=$1 AND token_hash<>$2', [req.user.id, tokenHash])
|
|
})
|
|
res.status(204).end()
|
|
})
|
|
|
|
app.get('/api/boards', requireUser, async (_req, res) => {
|
|
const { rows } = await pool.query(`SELECT ${boardColumns} FROM boards ORDER BY updated_at DESC, id`)
|
|
res.json(rows)
|
|
})
|
|
app.post('/api/boards', requireUser, async (req, res) => {
|
|
const board = boardSchema.parse(req.body)
|
|
const id = randomUUID()
|
|
const result = await transaction(async client => {
|
|
const { rows: [row] } = await client.query(`INSERT INTO boards (id,token,draft) VALUES ($1,$2,$3) RETURNING ${boardColumns}`, [id, newToken(), board])
|
|
await setReferences(client, id, board, false)
|
|
return row
|
|
})
|
|
res.status(201).json(result)
|
|
})
|
|
|
|
app.put('/api/boards/:id', requireUser, async (req, res) => {
|
|
const id = uuid.parse(req.params.id)
|
|
const { board, revision, publish } = boardSave.parse(req.body)
|
|
if (publish && !board.widgets.length) throw new HttpError(422, 'Füge vor dem Veröffentlichen mindestens einen Bereich hinzu.')
|
|
const result = await transaction(async client => {
|
|
const { rows: [current] } = await client.query('SELECT revision FROM boards WHERE id=$1 FOR UPDATE', [id])
|
|
if (!current) throw new HttpError(404, 'Der Bildschirm wurde nicht gefunden.')
|
|
if (current.revision !== revision) throw new HttpError(409, 'Der Bildschirm wurde anderweitig bearbeitet. Öffne ihn erneut, um den aktuellen Stand zu laden.')
|
|
await setReferences(client, id, board, false)
|
|
if (publish) await setReferences(client, id, board, true)
|
|
const { rows: [row] } = await client.query(`UPDATE boards SET draft=$2, revision=revision+1, updated_at=now(),
|
|
published=CASE WHEN $3 THEN $2 ELSE published END,
|
|
published_revision=CASE WHEN $3 THEN revision+1 ELSE published_revision END
|
|
WHERE id=$1 RETURNING ${boardColumns}`, [id, board, publish])
|
|
return row
|
|
})
|
|
res.json(result)
|
|
})
|
|
app.post('/api/boards/:id/token', requireUser, async (req, res) => {
|
|
const { revision } = revisionSchema.parse(req.body)
|
|
const { rows: [row] } = await pool.query(`UPDATE boards SET token=$2, last_seen=NULL, updated_at=now() WHERE id=$1 AND revision=$3 RETURNING ${boardColumns}`, [uuid.parse(req.params.id), newToken(), revision])
|
|
if (!row) throw new HttpError(409, 'Der Bildschirm wurde anderweitig bearbeitet.')
|
|
res.json(row)
|
|
})
|
|
app.post('/api/boards/:id/unpublish', requireUser, async (req, res) => {
|
|
const id = uuid.parse(req.params.id)
|
|
const { revision } = revisionSchema.parse(req.body)
|
|
const result = await transaction(async client => {
|
|
const { rows: [row] } = await client.query(`UPDATE boards SET published=NULL, published_revision=NULL,
|
|
updated_at=now(), revision=revision+1, last_seen=NULL WHERE id=$1 AND revision=$2 RETURNING ${boardColumns}`, [id, revision])
|
|
if (!row) throw new HttpError(409, 'Der Bildschirm wurde anderweitig bearbeitet.')
|
|
await client.query('DELETE FROM board_assets WHERE board_id=$1 AND live', [id])
|
|
return row
|
|
})
|
|
res.json(result)
|
|
})
|
|
app.delete('/api/boards/:id', requireUser, async (req, res) => {
|
|
const { revision } = revisionSchema.parse(req.body)
|
|
const result = await pool.query('DELETE FROM boards WHERE id=$1 AND revision=$2', [uuid.parse(req.params.id), revision])
|
|
if (!result.rowCount) throw new HttpError(409, 'Der Bildschirm wurde anderweitig bearbeitet.')
|
|
res.status(204).end()
|
|
})
|
|
|
|
app.get('/api/assets', requireUser, async (_req, res) => {
|
|
const { rows } = await pool.query(`SELECT ${assetColumns} FROM assets ORDER BY created_at DESC`)
|
|
res.json(rows)
|
|
})
|
|
function limitUploads(_req, res, next) {
|
|
if (uploads >= 3) throw new HttpError(503, 'Es laufen bereits mehrere Uploads. Bitte versuche es gleich erneut.')
|
|
uploads++
|
|
res.once('close', () => { uploads-- })
|
|
next()
|
|
}
|
|
app.post('/api/assets', requireUser, limitUploads, upload.single('file'), async (req, res) => {
|
|
if (!req.file) throw new HttpError(422, 'Wähle eine Datei aus.')
|
|
const id = randomUUID()
|
|
try {
|
|
let asset
|
|
try { asset = await saveUpload(req.file, id) } catch (error) {
|
|
if (error.syscall && !error.cmd) throw error
|
|
throw new HttpError(422, error.cmd ? 'Die PDF-Datei konnte nicht gelesen werden. Prüfe, ob sie intakt und unverschlüsselt ist.' : error.message)
|
|
}
|
|
const { rows: [row] } = await pool.query(
|
|
`INSERT INTO assets (id,name,kind,bytes,metadata) VALUES ($1,$2,$3,$4,$5) RETURNING ${assetColumns}`,
|
|
[id, asset.name, asset.kind, asset.bytes, asset.metadata],
|
|
)
|
|
res.status(201).json(row)
|
|
} catch (error) {
|
|
await rm(mediaDir(id), { recursive: true, force: true })
|
|
throw error
|
|
} finally {
|
|
await rm(req.file.path, { force: true })
|
|
}
|
|
})
|
|
app.delete('/api/assets/:id', requireUser, async (req, res) => {
|
|
const id = uuid.parse(req.params.id)
|
|
try {
|
|
const result = await pool.query('DELETE FROM assets WHERE id=$1', [id])
|
|
if (!result.rowCount) throw new HttpError(404, 'Die Datei wurde nicht gefunden.')
|
|
} catch (error) {
|
|
if (error.code === '23503' || error.code === '23001') {
|
|
throw new HttpError(409, 'Die Datei wird in einem Entwurf oder auf einem veröffentlichten Bildschirm verwendet.')
|
|
}
|
|
throw error
|
|
}
|
|
await rm(mediaDir(id), { recursive: true, force: true }).catch(error => console.error('Datei löschen:', error))
|
|
res.status(204).end()
|
|
})
|
|
|
|
async function findAsset(id, token) {
|
|
const columns = assetColumns.split(', ').map(column => `a.${column}`).join(', ')
|
|
const result = token
|
|
? await pool.query(`SELECT ${columns} FROM assets a JOIN board_assets r ON r.asset_id=a.id AND r.live
|
|
JOIN boards b ON b.id=r.board_id WHERE b.token=$1 AND a.id=$2 AND b.published IS NOT NULL`, [token, id])
|
|
: await pool.query(`SELECT ${assetColumns} FROM assets WHERE id=$1`, [id])
|
|
if (!result.rows[0]) throw new HttpError(404, 'Die Datei wurde nicht gefunden.')
|
|
return result.rows[0]
|
|
}
|
|
|
|
async function sendMedia(req, res) {
|
|
const token = req.params.token ? parseToken(req.params.token) : null
|
|
const asset = await findAsset(uuid.parse(req.params.id), token)
|
|
const item = String(req.params.item)
|
|
res.set('Cache-Control', 'private, no-cache')
|
|
const etag = `"${asset.id}-${item}"`
|
|
res.set('ETag', etag)
|
|
if (asset.kind === 'image' && item === 'image') return res.type('webp').sendFile(join(mediaDir(asset.id), 'display.webp'))
|
|
const pageRequest = item.match(/^page-(\d+)-(800|1600|2400)$/)
|
|
if (asset.kind !== 'pdf' || !pageRequest || Number(pageRequest[1]) < 1 || Number(pageRequest[1]) > asset.metadata.pages.length) {
|
|
throw new HttpError(404, 'Die Seite wurde nicht gefunden.')
|
|
}
|
|
if (req.fresh) return res.status(304).end()
|
|
const file = await renderPage(asset.id, Number(pageRequest[1]), Number(pageRequest[2]))
|
|
res.type('jpeg').sendFile(file)
|
|
}
|
|
|
|
function parseToken(value) {
|
|
if (!/^[\w-]{32}$/.test(value)) throw new HttpError(404, 'Die Anzeige wurde nicht gefunden.')
|
|
return value
|
|
}
|
|
app.get('/api/media/:id/:item', requireUser, sendMedia)
|
|
app.get('/api/display/:token/media/:id/:item', sendMedia)
|
|
app.get('/api/display/:token', async (req, res) => {
|
|
const token = parseToken(req.params.token)
|
|
const { rows: [row] } = await pool.query(`SELECT b.id, b.published AS board,
|
|
(b.last_seen IS NULL OR b.last_seen < now() - interval '25 seconds') AS record_visit,
|
|
COALESCE((SELECT jsonb_agg(jsonb_build_object('id', a.id, 'name', a.name, 'kind', a.kind, 'metadata', a.metadata) ORDER BY a.id)
|
|
FROM assets a JOIN board_assets r ON r.asset_id=a.id WHERE r.board_id=b.id AND r.live), '[]'::jsonb) AS assets
|
|
FROM boards b WHERE b.token=$1 AND b.published IS NOT NULL`, [token])
|
|
if (!row) throw new HttpError(404, 'Diese Anzeige ist nicht veröffentlicht oder der Link wurde erneuert.')
|
|
if (row.record_visit) {
|
|
await pool.query("UPDATE boards SET last_seen=now() WHERE id=$1 AND token=$2 AND published IS NOT NULL AND (last_seen IS NULL OR last_seen < now() - interval '25 seconds')", [row.id, token])
|
|
}
|
|
const body = JSON.stringify({ board: row.board, assets: row.assets })
|
|
const etag = `"${createHash('sha256').update(body).digest('base64url')}"`
|
|
res.set('Cache-Control', 'private, no-cache')
|
|
res.set('ETag', etag)
|
|
if (req.get('If-None-Match') === etag) return res.status(304).end()
|
|
res.type('json').send(body)
|
|
})
|
|
|
|
app.get('/api/users', requireUser, requireAdmin, async (_req, res) => {
|
|
const { rows } = await pool.query(`SELECT ${userColumns} FROM users ORDER BY created_at`)
|
|
res.json(rows)
|
|
})
|
|
const userEdit = userSchema.extend({ password: password.optional() })
|
|
app.post('/api/users', requireUser, requireAdmin, async (req, res) => {
|
|
const input = userEdit.required({ password: true }).parse(req.body)
|
|
const { rows: [row] } = await pool.query(
|
|
`INSERT INTO users (id,name,email,role,active,password) VALUES ($1,$2,$3,$4,$5,$6) RETURNING ${userColumns}`,
|
|
[randomUUID(), input.name, input.email, input.role, input.active, await hashPassword(input.password)],
|
|
)
|
|
res.status(201).json(row)
|
|
})
|
|
app.put('/api/users/:id', requireUser, requireAdmin, async (req, res) => {
|
|
const id = uuid.parse(req.params.id)
|
|
const input = userEdit.parse(req.body)
|
|
const hashed = input.password ? await hashPassword(input.password) : null
|
|
const user = await transaction(async client => {
|
|
await client.query('SELECT pg_advisory_xact_lock(701826125)')
|
|
const { rows: [actor] } = await client.query("SELECT id FROM users WHERE id=$1 AND role='admin' AND active", [req.user.id])
|
|
if (!actor) throw new HttpError(403, 'Deine Berechtigung wurde geändert.')
|
|
const { rows: [current] } = await client.query('SELECT role,active FROM users WHERE id=$1 FOR UPDATE', [id])
|
|
if (!current) throw new HttpError(404, 'Das Konto wurde nicht gefunden.')
|
|
if (current.role === 'admin' && current.active && (input.role !== 'admin' || !input.active)) {
|
|
const { rows: [other] } = await client.query("SELECT id FROM users WHERE id<>$1 AND role='admin' AND active LIMIT 1", [id])
|
|
if (!other) throw new HttpError(409, 'Mindestens ein aktives Administrationskonto muss erhalten bleiben.')
|
|
}
|
|
const { rows: [row] } = await client.query(`UPDATE users SET name=$2,email=$3,role=$4,active=$5,
|
|
password=COALESCE($6,password) WHERE id=$1 RETURNING ${userColumns}`, [id, input.name, input.email, input.role, input.active, hashed])
|
|
if (hashed || !input.active) await client.query('DELETE FROM sessions WHERE user_id=$1', [id])
|
|
return row
|
|
})
|
|
res.json(user)
|
|
})
|
|
|
|
app.use('/api', (_req, _res, next) => next(new HttpError(404, 'Diese Adresse wurde nicht gefunden.')))
|
|
app.use(express.static(dist, {
|
|
setHeaders(res, path) {
|
|
res.set('Cache-Control', path.startsWith(join(dist, 'assets') + '/') ? 'public, max-age=31536000, immutable' : 'no-cache')
|
|
},
|
|
}))
|
|
app.get(['/', '/admin', '/admin/{*section}', '/display/:token'], (_req, res) => {
|
|
res.set('Cache-Control', 'no-cache').sendFile(join(dist, 'index.html'))
|
|
})
|
|
|
|
app.use((error, _req, res, next) => {
|
|
if (res.headersSent) return next(error)
|
|
if (error instanceof z.ZodError) {
|
|
const issue = error.issues[0]
|
|
return res.status(422).json({ error: issue.code === 'custom' ? issue.message : 'Prüfe die Eingaben auf fehlende oder ungültige Werte.' })
|
|
}
|
|
if (error instanceof multer.MulterError) {
|
|
return res.status(error.code === 'LIMIT_FILE_SIZE' ? 413 : 422).json({ error: error.code === 'LIMIT_FILE_SIZE'
|
|
? `Die Datei ist größer als ${uploadLimit / 1024 / 1024} MB.` : 'Es kann genau eine Datei pro Upload verarbeitet werden.' })
|
|
}
|
|
if (error.code === '23505') return res.status(409).json({ error: 'Diese E-Mail-Adresse ist bereits vergeben.' })
|
|
if (error.status >= 400 && error.status < 500) return res.status(error.status).json({ error: error instanceof HttpError ? error.message : 'Die Anfrage konnte nicht verarbeitet werden.' })
|
|
console.error(error)
|
|
res.status(error.status === 503 ? 503 : 500).json({ error: error.status === 503 ? 'Die Verarbeitung ist gerade ausgelastet.' : 'Der Server konnte die Anfrage nicht verarbeiten.' })
|
|
})
|
|
|
|
await prepareStorage()
|
|
await initialise()
|
|
const server = app.listen(port, process.env.HOST || '0.0.0.0', () => console.log(`Syncova Display läuft auf Port ${port}.`))
|
|
server.requestTimeout = 300_000
|
|
for (const signal of ['SIGTERM', 'SIGINT']) {
|
|
process.once(signal, () => {
|
|
server.close(() => void pool.end())
|
|
})
|
|
}
|