syncova-links/server/auth.js
jf 27924e55e9
All checks were successful
Docker-Image veröffentlichen / publish (push) Successful in 1m44s
Initial import with Gitea Docker publishing
2026-11-16 15:14:43 +01:00

83 lines
3.3 KiB
JavaScript

import { createHash, randomBytes, scrypt, timingSafeEqual } from 'node:crypto'
import { promisify } from 'node:util'
export const passwordOptions = { N: 32768, r: 8, p: 1, maxmem: 64 * 1024 * 1024 }
const derive = promisify(scrypt)
const digest = (value) => createHash('sha256').update(value).digest()
const duration = 12 * 60 * 60 * 1000
const windowMs = 60_000
export function createAuth({ username, passwordHash, secure }) {
const match = /^scrypt:([a-f\d]{32}):([a-f\d]{128})$/.exec(passwordHash ?? '')
if (!username?.trim() || !match) {
throw new Error('ADMIN_USERNAME und ADMIN_PASSWORD_HASH müssen gültig konfiguriert sein.')
}
const expectedUser = digest(username)
const salt = Buffer.from(match[1], 'hex')
const expected = Buffer.from(match[2], 'hex')
const sessions = new Map()
const attempts = new Map()
let inFlight = 0
const cookie = {
httpOnly: true, secure, sameSite: 'strict', path: '/',
}
const cookieName = secure ? '__Host-syncova_session' : 'syncova_session'
const token = (req) => {
const match = req.headers.cookie?.split(';').map((item) => item.trim())
.find((item) => item.startsWith(cookieName + '='))
return match?.slice(cookieName.length + 1)
}
const active = (req) => {
const value = token(req)
return Boolean(value && (sessions.get(value) ?? 0) > Date.now())
}
setInterval(() => {
const now = Date.now()
for (const [value, expiry] of sessions) if (expiry <= now) sessions.delete(value)
for (const [ip, entry] of attempts) if (entry.until <= now) attempts.delete(ip)
}, windowMs).unref()
return {
active,
requireAdmin(req, res, next) {
if (!active(req)) return res.status(401).json({ error: 'Bitte zuerst anmelden.' })
next()
},
async login(req, res) {
const { username, password } = req.body ?? {}
if (typeof username !== 'string' || username.length > 256 ||
typeof password !== 'string' || password.length > 1024) {
return res.status(400).json({ error: 'Bitte Benutzername und Passwort eingeben.' })
}
const now = Date.now()
let entry = attempts.get(req.ip)
if (!entry || entry.until <= now) entry = { count: 0, until: now + windowMs }
if (entry.count >= 8 || inFlight >= 2 || (!attempts.has(req.ip) && attempts.size >= 4096)) {
return res.status(429).json({ error: 'Zu viele Anmeldeversuche. Bitte kurz warten.' })
}
entry.count += 1
attempts.set(req.ip, entry)
inFlight++
let result
try {
result = await derive(password, salt, expected.length, passwordOptions)
} finally {
inFlight--
}
if (!timingSafeEqual(digest(username), expectedUser) || !timingSafeEqual(result, expected)) {
return res.status(401).json({ error: 'Benutzername oder Passwort ist falsch.' })
}
attempts.delete(req.ip)
sessions.delete(token(req))
if (sessions.size >= 1024) sessions.delete(sessions.keys().next().value)
const value = randomBytes(32).toString('hex')
sessions.set(value, Date.now() + duration)
res.cookie(cookieName, value, { ...cookie, maxAge: duration }).json({ admin: true })
},
logout(req, res) {
sessions.delete(token(req))
res.clearCookie(cookieName, cookie).status(204).end()
},
}
}