All checks were successful
Docker-Image veröffentlichen / publish (push) Successful in 1m44s
108 lines
5.1 KiB
JavaScript
108 lines
5.1 KiB
JavaScript
import express from 'express'
|
|
import { fileURLToPath } from 'node:url'
|
|
import { join } from 'node:path'
|
|
import { createAuth } from './auth.js'
|
|
import { fetchFavicon, iconLimit, normalizeIcon } from './icons.js'
|
|
import { settings, update } from './model.js'
|
|
import { openStore, RequestError } from './store.js'
|
|
|
|
const { ADMIN_USERNAME, ADMIN_PASSWORD_HASH, COOKIE_SECURE, PORT, DATA_DIR } = process.env
|
|
const auth = createAuth({ username: ADMIN_USERNAME, passwordHash: ADMIN_PASSWORD_HASH, secure: COOKIE_SECURE === 'true' })
|
|
const store = openStore(DATA_DIR || './data')
|
|
const dist = fileURLToPath(new URL('../dist/', import.meta.url))
|
|
const app = express()
|
|
app.disable('x-powered-by')
|
|
app.use((req, res, next) => {
|
|
res.set({
|
|
'Content-Security-Policy': "default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self'; font-src 'self'; object-src 'none'; base-uri 'none'; frame-ancestors 'none'; form-action 'self'",
|
|
'X-Content-Type-Options': 'nosniff',
|
|
'Referrer-Policy': 'no-referrer',
|
|
})
|
|
next()
|
|
})
|
|
app.get('/healthz', (_req, res) => res.sendStatus(200))
|
|
app.use('/api', (_req, res, next) => {
|
|
res.set('Cache-Control', 'private, no-store')
|
|
next()
|
|
})
|
|
|
|
const json = express.json({ limit: '2mb' })
|
|
const binary = express.raw({ type: 'application/octet-stream', limit: iconLimit, inflate: false })
|
|
const write = (req, res, next) => {
|
|
if (req.get('x-syncova-request') !== '1' || ['cross-site', 'same-site'].includes(req.get('sec-fetch-site'))) {
|
|
throw new RequestError(403, 'Diese Anfrage ist nicht zulässig.')
|
|
}
|
|
next()
|
|
}
|
|
const adminWrite = [auth.requireAdmin, write]
|
|
|
|
function parse(schema, body) {
|
|
const result = schema.safeParse(body)
|
|
if (!result.success) {
|
|
const issue = result.error.issues[0]
|
|
const message = ['custom', 'invalid_format'].includes(issue.code) && !issue.message.startsWith('Invalid')
|
|
? issue.message
|
|
: 'Bitte prüfe die Pflichtfelder und die Länge deiner Eingaben.'
|
|
throw new RequestError(400, message)
|
|
}
|
|
return result.data
|
|
}
|
|
|
|
app.get('/api/session', (req, res) => res.json({ admin: auth.active(req) }))
|
|
app.post('/api/login', write, json, auth.login)
|
|
app.post('/api/logout', ...adminWrite, auth.logout)
|
|
app.get('/api/admin/pages', auth.requireAdmin, (_req, res) => res.json(store.list()))
|
|
app.get('/api/pages', (_req, res) => res.json(store.list().map(({ name, slug }) => ({ name, slug }))))
|
|
app.get('/api/pages/:slug', (req, res) => res.json(store.get(req.params.slug)))
|
|
app.post('/api/pages', ...adminWrite, json, (req, res) => res.status(201).json(store.create(parse(settings, req.body))))
|
|
app.put('/api/pages/:id', ...adminWrite, json, (req, res) => res.json(store.save(req.params.id, parse(update, req.body))))
|
|
app.delete('/api/pages/:id', ...adminWrite, (req, res) => {
|
|
store.remove(req.params.id)
|
|
res.status(204).end()
|
|
})
|
|
|
|
app.get('/api/icons/:id', (req, res) => {
|
|
const icon = store.icon(req.params.id)
|
|
if (!icon || (!icon.published && !auth.active(req))) return res.sendStatus(404)
|
|
res.type('png').send(Buffer.from(icon.png))
|
|
})
|
|
app.post('/api/icons/upload', ...adminWrite, binary, async (req, res) => {
|
|
if (!Buffer.isBuffer(req.body) || !req.body.length) throw new RequestError(400, 'Bitte wähle eine Bilddatei aus.')
|
|
let image
|
|
try { image = await normalizeIcon(req.body) } catch {
|
|
throw new RequestError(422, 'Das Icon muss ein gültiges PNG, JPEG, WebP, GIF oder ICO sein.')
|
|
}
|
|
res.status(201).json(store.addIcon(image))
|
|
})
|
|
let fetches = 0
|
|
app.post('/api/icons/favicon', ...adminWrite, json, async (req, res) => {
|
|
const url = req.body?.url
|
|
if (typeof url !== 'string' || url.length > 2048) throw new RequestError(400, 'Bitte gib eine gültige Link-Adresse ein.')
|
|
if (fetches >= 2) throw new RequestError(429, 'Zu viele laufende Abrufe. Bitte versuche es gleich erneut.')
|
|
fetches++
|
|
let image
|
|
try { image = await fetchFavicon(url) } catch {
|
|
throw new RequestError(422, 'Kein verwendbares Favicon gefunden. Der Link kann mit dem Standard-Icon gespeichert werden.')
|
|
} finally {
|
|
fetches--
|
|
}
|
|
res.status(201).json(store.addIcon(image))
|
|
})
|
|
app.use('/api', (_req, res) => res.status(404).json({ error: 'Diese Funktion wurde nicht gefunden.' }))
|
|
app.use('/assets', express.static(join(dist, 'assets'), { immutable: true, maxAge: '1y' }))
|
|
app.get(['/', '/:slug'], (_req, res) => res.sendFile(join(dist, 'index.html'), { maxAge: 0 }))
|
|
app.use((_req, res) => res.sendStatus(404))
|
|
app.use((error, _req, res, next) => {
|
|
if (res.headersSent) return next(error)
|
|
if (error instanceof RequestError) return res.status(error.status).json({ error: error.message })
|
|
if (error.status === 413) return res.status(413).json({ error: 'Die Datei oder Anfrage ist zu groß.' })
|
|
if (error.status >= 400 && error.status < 500) return res.status(error.status).json({ error: 'Ungültige Anfrage.' })
|
|
console.error(error)
|
|
res.status(500).json({ error: 'Die Anfrage konnte nicht verarbeitet werden.' })
|
|
})
|
|
const server = app.listen(Number(PORT || 3000), '0.0.0.0', () => {
|
|
console.log(`syncova-links hört auf Port ${server.address().port}`)
|
|
})
|
|
server.requestTimeout = 30_000
|
|
for (const signal of ['SIGTERM', 'SIGINT']) process.once(signal, () => server.close(() => process.exit(0)))
|