121 lines
3.5 KiB
JavaScript
121 lines
3.5 KiB
JavaScript
import { randomBytes, scryptSync, timingSafeEqual, createHash } from 'node:crypto'
|
||
|
||
const KEYLEN = 64
|
||
const SESSION_DAYS = 30
|
||
const ATTEMPT_WINDOW = 5 * 60 * 1000
|
||
const ATTEMPT_LIMIT = 10
|
||
|
||
export const SESSION_COOKIE = 'devbox_session'
|
||
|
||
export function hashPassword(password, salt = randomBytes(16).toString('hex')) {
|
||
const hash = scryptSync(password, salt, KEYLEN, { N: 16384, r: 8, p: 1 }).toString('hex')
|
||
return { salt, hash }
|
||
}
|
||
|
||
export function verifyPassword(password, salt, expectedHash) {
|
||
const actual = scryptSync(password, salt, KEYLEN, { N: 16384, r: 8, p: 1 })
|
||
const expected = Buffer.from(expectedHash, 'hex')
|
||
if (expected.length !== actual.length) return false
|
||
return timingSafeEqual(actual, expected)
|
||
}
|
||
|
||
export function randomId(bytes = 24) {
|
||
return randomBytes(bytes).toString('hex')
|
||
}
|
||
|
||
export function createSession(db, userId) {
|
||
const id = randomId(24)
|
||
const now = Date.now()
|
||
db.prepare('INSERT INTO sessions (id, user_id, created_at, expires_at) VALUES (?, ?, ?, ?)').run(
|
||
id,
|
||
userId,
|
||
now,
|
||
now + SESSION_DAYS * 24 * 60 * 60 * 1000
|
||
)
|
||
return id
|
||
}
|
||
|
||
export function sessionUser(db, sessionId) {
|
||
if (!sessionId) return null
|
||
const row = db
|
||
.prepare(
|
||
`SELECT u.* FROM sessions s JOIN users u ON u.id = s.user_id
|
||
WHERE s.id = ? AND s.expires_at > ? AND u.disabled = 0`
|
||
)
|
||
.get(sessionId, Date.now())
|
||
return row || null
|
||
}
|
||
|
||
export function destroySession(db, sessionId) {
|
||
if (sessionId) db.prepare('DELETE FROM sessions WHERE id = ?').run(sessionId)
|
||
}
|
||
|
||
export function destroyUserSessions(db, userId, keepSessionId = null) {
|
||
if (keepSessionId) db.prepare('DELETE FROM sessions WHERE user_id = ? AND id <> ?').run(userId, keepSessionId)
|
||
else db.prepare('DELETE FROM sessions WHERE user_id = ?').run(userId)
|
||
}
|
||
|
||
export function cleanExpired(db) {
|
||
db.prepare('DELETE FROM sessions WHERE expires_at <= ?').run(Date.now())
|
||
}
|
||
|
||
export function parseCookies(header = '') {
|
||
const out = {}
|
||
for (const part of String(header).split(';')) {
|
||
const idx = part.indexOf('=')
|
||
if (idx < 0) continue
|
||
const k = part.slice(0, idx).trim()
|
||
const v = part.slice(idx + 1).trim()
|
||
if (k) out[k] = decodeURIComponent(v)
|
||
}
|
||
return out
|
||
}
|
||
|
||
export function cookieHeader(id, maxAgeSeconds) {
|
||
const parts = [`${SESSION_COOKIE}=${encodeURIComponent(id)}`, 'Path=/', 'HttpOnly', 'SameSite=Lax', `Max-Age=${maxAgeSeconds}`]
|
||
return parts.join('; ')
|
||
}
|
||
|
||
export function clearCookieHeader() {
|
||
return `${SESSION_COOKIE}=; Path=/; HttpOnly; SameSite=Lax; Max-Age=0`
|
||
}
|
||
|
||
const attempts = new Map()
|
||
|
||
export function tooManyAttempts(key) {
|
||
const row = attempts.get(key)
|
||
if (!row) return false
|
||
if (Date.now() - row.first > ATTEMPT_WINDOW) {
|
||
attempts.delete(key)
|
||
return false
|
||
}
|
||
return row.count >= ATTEMPT_LIMIT
|
||
}
|
||
|
||
export function noteAttempt(key) {
|
||
const row = attempts.get(key)
|
||
const now = Date.now()
|
||
if (!row || now - row.first > ATTEMPT_WINDOW) attempts.set(key, { first: now, count: 1 })
|
||
else row.count += 1
|
||
}
|
||
|
||
export function resetAttempts(key) {
|
||
attempts.delete(key)
|
||
}
|
||
|
||
/** CDK:XXXX-XXXX-XXXX-XXXX,去掉容易看混的 0/O/1/I */
|
||
export function newCode() {
|
||
const alphabet = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789'
|
||
const pick = () => {
|
||
const bytes = randomBytes(4)
|
||
let out = ''
|
||
for (const b of bytes) out += alphabet[b % alphabet.length]
|
||
return out
|
||
}
|
||
return `${pick()}-${pick()}-${pick()}-${pick()}`
|
||
}
|
||
|
||
export function shortHash(text) {
|
||
return createHash('sha256').update(text).digest('hex').slice(0, 16)
|
||
}
|