50 lines
2.0 KiB
JavaScript
50 lines
2.0 KiB
JavaScript
import { createHash, randomBytes, scrypt, timingSafeEqual } from 'node:crypto'
|
|
import { promisify } from 'node:util'
|
|
|
|
const derive = promisify(scrypt)
|
|
const scryptOptions = { N: 32768, r: 8, p: 1, maxmem: 64 * 1024 * 1024 }
|
|
const dummyHash = '98a236bb22addb8f79d9780e7e1f85d0:' + '0'.repeat(128)
|
|
export const sessionHash = token => createHash('sha256').update(token).digest('hex')
|
|
export const makeSession = () => randomBytes(32).toString('base64url')
|
|
export const sessionCookie = 'syncova_session'
|
|
export const sessionOptions = {
|
|
httpOnly: true, sameSite: 'strict', secure: process.env.COOKIE_SECURE === 'true', path: '/',
|
|
}
|
|
export const sessionLifetime = 7 * 24 * 60 * 60 * 1000
|
|
|
|
export async function hashPassword(password) {
|
|
const salt = randomBytes(16).toString('hex')
|
|
const hash = await derive(password, salt, 64, scryptOptions)
|
|
return `${salt}:${hash.toString('hex')}`
|
|
}
|
|
|
|
export async function verifyPassword(password, stored = dummyHash) {
|
|
const [salt, hash] = stored.split(':')
|
|
const candidate = await derive(password, salt, 64, scryptOptions)
|
|
return timingSafeEqual(candidate, Buffer.from(hash, 'hex'))
|
|
}
|
|
|
|
export function getSession(req) {
|
|
return req.headers.cookie?.match(/(?:^|;\s*)syncova_session=([\w-]{43})(?:;|$)/)?.[1]
|
|
}
|
|
|
|
const loginAttempts = new Map()
|
|
export function limitLogin(req, res, next) {
|
|
const now = Date.now()
|
|
if (loginAttempts.size >= 1000) {
|
|
for (const [key, value] of loginAttempts) if (value.until <= now) loginAttempts.delete(key)
|
|
}
|
|
const key = req.ip
|
|
let attempt = loginAttempts.get(key)
|
|
if (!attempt || attempt.until <= now) {
|
|
if (loginAttempts.size >= 10_000) return res.status(429).json({ error: 'Bitte versuche es in einigen Minuten erneut.' })
|
|
attempt = { count: 0, until: now + 10 * 60 * 1000 }
|
|
loginAttempts.set(key, attempt)
|
|
}
|
|
if (++attempt.count > 12) {
|
|
res.set('Retry-After', String(Math.ceil((attempt.until - now) / 1000)))
|
|
return res.status(429).json({ error: 'Zu viele Anmeldeversuche. Bitte warte einige Minuten.' })
|
|
}
|
|
next()
|
|
}
|