import { createHash, randomBytes, timingSafeEqual } from 'node:crypto'; import { fileURLToPath } from 'node:url'; import { join } from 'node:path'; import express from 'express'; import { z, ZodError } from 'zod'; import { magazines } from './magazines.js'; import { library } from './library.js'; import { HttpError, idSchema } from './model.js'; import { releasePath, startPublishing } from './publisher.js'; import { seed } from './seed.js'; import { adminPassword, adminUsername, demoMode, pool, publicBase, setup, uploadPath } from './storage.js'; const app = express(); const dist = fileURLToPath(new URL('../dist/', import.meta.url)); const port = Number(process.env.PORT || 4170); const cookie = 'folio_session'; const sessionAge = 12 * 60 * 60 * 1000; const cookieOptions = { httpOnly: true, secure: publicBase.protocol === 'https:', sameSite: 'strict', path: '/api/admin' }; const hash = (value) => createHash('sha256').update(value).digest('hex'); let attemptWindow = 0; let failures = 0; app.disable('x-powered-by'); app.use((req, res, next) => { const reader = req.path.startsWith('/ausgabe/'); res.set('X-Content-Type-Options', 'nosniff'); res.set('Referrer-Policy', 'no-referrer'); res.set('Content-Security-Policy', `default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; font-src 'self' data:; img-src 'self' data: blob:; media-src 'self'; frame-src 'self' about:; object-src 'none'; base-uri 'none'; form-action 'self'${reader ? '' : "; frame-ancestors 'none'"}`); if (req.path.startsWith('/api')) res.set('Cache-Control', 'no-store'); next(); }); app.use('/api', express.json({ limit: '16mb' })); app.get('/api/health', async (_req, res) => { await pool.query('SELECT 1'); res.json({ ok: true }); }); const admin = express.Router(); app.use('/api/admin', admin); admin.use((req, _res, next) => { if (['GET', 'HEAD'].includes(req.method) || req.get('X-Folio-Request') === 'studio') return next(); next(new HttpError(403, 'Ungültige Anfrage.')); }); function tokenFrom(req) { const match = req.headers.cookie?.match(/(?:^|;\s*)folio_session=([a-f0-9]{64})(?:;|$)/); return match ? hash(match[1]) : ''; } async function authorized(req) { if (demoMode) return true; const token = tokenFrom(req); if (!token) return false; return (await pool.query('SELECT 1 FROM sessions WHERE digest=$1 AND expires_at>now()', [token])).rowCount > 0; } admin.get('/session', async (req, res) => res.json({ authorized: await authorized(req), demo: demoMode })); admin.post('/login', async (req, res) => { const { username, password } = z.object({ username: z.string().trim().min(1).max(128), password: z.string().max(1024), }).parse(req.body); if (demoMode) return res.json({ authorized: true, demo: true }); if (Date.now() >= attemptWindow) { failures = 0; attemptWindow = Date.now() + 60_000; } if (failures >= 10) throw new HttpError(429, 'Zu viele Anmeldeversuche. Versuche es in einer Minute erneut.'); const usernameMatches = timingSafeEqual(Buffer.from(hash(username)), Buffer.from(hash(adminUsername))); const passwordMatches = timingSafeEqual(Buffer.from(hash(password)), Buffer.from(hash(adminPassword))); if (!usernameMatches || !passwordMatches) { failures += 1; throw new HttpError(401, 'Benutzername oder Passwort stimmt nicht.'); } const token = randomBytes(32).toString('hex'); await pool.query('DELETE FROM sessions WHERE expires_at<=now()'); await pool.query('INSERT INTO sessions (digest,expires_at) VALUES ($1,$2)', [hash(token), new Date(Date.now() + sessionAge)]); res.cookie(cookie, token, { ...cookieOptions, maxAge: sessionAge }).json({ authorized: true, demo: false }); }); admin.use(async (req, _res, next) => { if (!(await authorized(req))) throw new HttpError(401, 'Bitte melde dich an.'); next(); }); admin.post('/logout', async (req, res) => { await pool.query('DELETE FROM sessions WHERE digest=$1', [tokenFrom(req)]); res.clearCookie(cookie, cookieOptions).status(204).end(); }); admin.use(magazines, library); async function publicRelease(slug) { const result = await pool.query(`SELECT m.id AS magazine_id,r.id,r.pages,r.draft->>'title' AS title,r.draft->>'issue' AS issue FROM magazines m JOIN releases r ON r.id=m.current_release WHERE m.slug=$1 AND m.deleted_at IS NULL AND r.state='ready'`, [slug]); if (!result.rowCount) throw new HttpError(404, 'Diese Ausgabe ist nicht verfügbar.'); return result.rows[0]; } app.get('/api/public/:slug', async (req, res) => { const publication = await publicRelease(req.params.slug); const base = `/api/public/${req.params.slug}`; res.json({ pages: publication.pages, title: publication.title, issue: publication.issue, pdf: `${base}/pdf` }); }); app.post('/api/public/:slug/view', async (req, res) => { await pool.query('UPDATE magazines SET views=views+1 WHERE slug=$1 AND deleted_at IS NULL AND current_release IS NOT NULL', [req.params.slug]); res.status(204).end(); }); app.get('/api/public/:slug/media/:release/:media', async (req, res) => { const result = await pool.query(`SELECT f.* FROM magazines m JOIN releases r ON r.magazine_id=m.id JOIN media f ON f.id=ANY(r.media_ids) WHERE m.slug=$1 AND m.deleted_at IS NULL AND m.current_release IS NOT NULL AND r.id=$2 AND r.state='ready' AND f.id=$3`, [req.params.slug, idSchema.parse(req.params.release), idSchema.parse(req.params.media)]); if (!result.rowCount) throw new HttpError(404, 'Datei nicht gefunden.'); res.type(result.rows[0].mime).sendFile(uploadPath(result.rows[0]), { cacheControl: false }); }); app.get('/api/public/:slug/pdf', async (req, res, next) => { const publication = await publicRelease(req.params.slug); res.download(releasePath(publication.id, 'pdf'), `${req.params.slug}.pdf`, { acceptRanges: false, cacheControl: false }, (error) => { if (error) return next(error); if (req.method === 'GET') pool.query('UPDATE magazines SET downloads=downloads+1 WHERE id=$1', [publication.magazine_id]) .catch((err) => console.error('Downloadzähler:', err.message)); }); }); app.get('/ausgabe/:slug/html', async (req, res) => { const publication = await publicRelease(req.params.slug); res.set('Cache-Control', 'no-store').sendFile(releasePath(publication.id, 'html')); }); app.use('/api', (_req, _res, next) => next(new HttpError(404, 'Diese Adresse gibt es nicht.'))); app.use(express.static(dist, { index: false, maxAge: '1h' })); app.get('/{*spa}', (_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 ZodError) return res.status(422).json({ error: error.issues[0]?.message || 'Prüfe die eingegebenen Werte.' }); if (error.code === 'LIMIT_FILE_SIZE') return res.status(413).json({ error: 'Dateien dürfen bis zu 100 MB groß sein.' }); const status = error instanceof HttpError || [400, 404, 413, 416].includes(error.status) ? error.status : 500; if (status === 500) console.error(error); res.status(status).json({ error: status === 500 ? 'Der Server konnte die Anfrage nicht verarbeiten.' : error.message }); }); await setup(); await seed(); const stopPublishing = startPublishing(); const server = app.listen(port, '0.0.0.0', () => console.log(`Syncova. Folio auf Port ${port}`)); function stop() { stopPublishing(); server.close(() => void pool.end()); } process.once('SIGTERM', stop); process.once('SIGINT', stop);