Files
imgbed/lib/auth.mjs
T

98 lines
3.4 KiB
JavaScript

// 口令哈希、会话、Cookie —— 只用 node 自带的 crypto。
import { randomBytes, scryptSync, timingSafeEqual, createHash } from 'node:crypto'
const SESSION_DAYS = 30
const SCRYPT = { N: 16384, r: 8, p: 1, keylen: 64 }
export function hashPassword(password) {
const salt = randomBytes(16).toString('hex')
const hash = scryptSync(password, salt, SCRYPT.keylen, { N: SCRYPT.N, r: SCRYPT.r, p: SCRYPT.p }).toString('hex')
return { salt, hash }
}
export function verifyPassword(password, salt, expected) {
const actual = scryptSync(password, salt, SCRYPT.keylen, { N: SCRYPT.N, r: SCRYPT.r, p: SCRYPT.p })
const target = Buffer.from(expected, 'hex')
return actual.length === target.length && timingSafeEqual(actual, target)
}
export const randomId = (bytes = 24) => randomBytes(bytes).toString('hex')
export function createSession(db, userId, ua = '') {
const now = Date.now()
const id = randomId(24)
db.prepare('INSERT INTO sessions (id, user_id, created_at, expires_at, ua) VALUES (?, ?, ?, ?, ?)').run(
id, userId, new Date(now).toISOString(), new Date(now + SESSION_DAYS * 86400_000).toISOString(), String(ua).slice(0, 200)
)
return id
}
export function sessionUser(db, sessionId) {
if (!sessionId) return null
const row = db
.prepare('SELECT s.id AS sid, s.expires_at, u.* FROM sessions s JOIN users u ON u.id = s.user_id WHERE s.id = ?')
.get(sessionId)
if (!row) return null
if (new Date(row.expires_at).getTime() < Date.now()) {
db.prepare('DELETE FROM sessions WHERE id = ?').run(sessionId)
return null
}
if (row.disabled) return null
return row
}
export function destroySession(db, sessionId) {
if (sessionId) db.prepare('DELETE FROM sessions WHERE id = ?').run(sessionId)
}
export function parseCookies(header = '') {
const out = {}
for (const part of String(header).split(';')) {
const index = part.indexOf('=')
if (index < 0) continue
const key = part.slice(0, index).trim()
if (!key) continue
out[key] = decodeURIComponent(part.slice(index + 1).trim())
}
return out
}
export function cookieHeader(name, value, { maxAge = SESSION_DAYS * 86400, secure = false } = {}) {
const parts = [`${name}=${encodeURIComponent(value)}`, 'Path=/', 'HttpOnly', 'SameSite=Lax', `Max-Age=${maxAge}`]
if (secure) parts.push('Secure')
return parts.join('; ')
}
export const clearCookie = (name) => `${name}=; Path=/; HttpOnly; SameSite=Lax; Max-Age=0`
export function newApiKey() {
const key = 'imb_' + randomBytes(20).toString('hex')
return { key, hash: createHash('sha256').update(key).digest('hex'), hint: key.slice(0, 8) + '…' + key.slice(-4) }
}
export const hashApiKey = (key) => createHash('sha256').update(key).digest('hex')
// 登录失败限速:同一 IP + 用户名 5 分钟内最多 10 次
const attempts = new Map()
export function tooManyAttempts(ip, username) {
const key = `${ip}|${username.toLowerCase()}`
const record = attempts.get(key)
if (!record) return false
if (Date.now() - record.first > 5 * 60_000) {
attempts.delete(key)
return false
}
return record.count >= 10
}
export function noteAttempt(ip, username) {
const key = `${ip}|${username.toLowerCase()}`
const record = attempts.get(key) || { first: Date.now(), count: 0 }
record.count += 1
attempts.set(key, record)
}
export function resetAttempts(ip, username) {
attempts.delete(`${ip}|${username.toLowerCase()}`)
}