logigate/server/utils/auth.ts

110 lines
3.7 KiB
TypeScript

// Accounts: email + password (scrypt), sessions in an httpOnly cookie.
// Stored as JSON files: data/users, data/sessions, data/accounts.
import { createHash, randomBytes, scrypt, timingSafeEqual } from 'node:crypto'
import type { H3Event } from 'h3'
export interface User {
id: string
email: string
hash: string
salt: string
created: number
}
interface Session {
uid: string
created: number
expires: number
}
export const SESSION_COOKIE = 'lg_session'
const SESSION_DAYS = 180
const sha256 = (s: string) => createHash('sha256').update(s).digest('hex')
export const users = () => useStorage('users')
const sessions = () => useStorage<Session>('sessions')
export const emailKey = (email: string) => `email:${sha256(email.trim().toLowerCase())}`
export const publicUser = (u: User) => ({ id: u.id, email: u.email })
export function validEmail(email: unknown): email is string {
return typeof email === 'string' && email.length <= 200 && /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email.trim())
}
export function validPassword(pw: unknown): pw is string {
return typeof pw === 'string' && pw.length >= 8 && pw.length <= 200
}
function scryptHash(password: string, salt: string): Promise<Buffer> {
return new Promise((resolve, reject) =>
scrypt(password.normalize('NFKC'), salt, 64, { N: 16384, r: 8, p: 1 }, (err, key) => (err ? reject(err) : resolve(key))),
)
}
export async function hashPassword(password: string): Promise<{ hash: string; salt: string }> {
const salt = randomBytes(16).toString('hex')
return { hash: (await scryptHash(password, salt)).toString('hex'), salt }
}
export async function verifyPassword(password: string, user: User): Promise<boolean> {
const a = await scryptHash(password, user.salt)
const b = Buffer.from(user.hash, 'hex')
return a.length === b.length && timingSafeEqual(a, b)
}
export async function findUserByEmail(email: string): Promise<User | null> {
const ref = await users().getItem<{ uid: string }>(emailKey(email))
return ref ? users().getItem<User>(`user:${ref.uid}`) : null
}
export async function startSession(event: H3Event, uid: string) {
const token = randomBytes(32).toString('base64url')
const now = Date.now()
await sessions().setItem(sha256(token), { uid, created: now, expires: now + SESSION_DAYS * 86_400_000 })
setCookie(event, SESSION_COOKIE, token, {
httpOnly: true,
secure: process.env.NODE_ENV === 'production',
sameSite: 'lax',
path: '/',
maxAge: SESSION_DAYS * 86_400,
})
}
export async function endSession(event: H3Event) {
const token = getCookie(event, SESSION_COOKIE)
if (token) await sessions().removeItem(sha256(token))
deleteCookie(event, SESSION_COOKIE, { path: '/' })
}
/** Ends every session of a user (password change, account deletion). */
export async function endAllSessions(uid: string, keep?: H3Event) {
const keepKey = keep ? sha256(getCookie(keep, SESSION_COOKIE) ?? '') : ''
for (const key of await sessions().getKeys()) {
if (key === keepKey) continue
const s = await sessions().getItem(key)
if (s?.uid === uid) await sessions().removeItem(key)
}
}
export async function currentUser(event: H3Event): Promise<User | null> {
const token = getCookie(event, SESSION_COOKIE)
if (!token) return null
const key = sha256(token)
const s = await sessions().getItem(key)
if (!s) return null
if (s.expires < Date.now()) {
await sessions().removeItem(key)
return null
}
return users().getItem<User>(`user:${s.uid}`)
}
export async function requireUser(event: H3Event): Promise<User> {
const user = await currentUser(event)
if (!user) throw createError({ statusCode: 401, message: 'Please sign in' })
return user
}
export const newUserId = () => randomBytes(9).toString('base64url').replace(/[-_]/g, 'x')