| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110 |
- /**
- * 会话与 cookie
- * ============
- * Web 版没有 Electron 的 store,登录态只活在服务端内存里:
- *
- * 浏览器只拿到一个随机 sid(HttpOnly + SameSite=Lax),签名防止伪造;
- * 真正的 apiKey / 用户身份留在服务端 session 表里,从不写进 cookie。
- *
- * 这样做的代价是重启进程会掉登录(引擎进程和浏览器也一起没了,本来就要重来);
- * 换来的是 apiKey 不会被 XSS 读走,也不会出现在浏览器历史/日志里。
- */
- import crypto from 'node:crypto'
- import { config } from '../config.js'
- const sessions = new Map()
- let sweeper = null
- function sign (sid) {
- return crypto.createHmac('sha256', config.secret).update(sid).digest('base64url').slice(0, 32)
- }
- function safeEqual (a, b) {
- const x = Buffer.from(String(a))
- const y = Buffer.from(String(b))
- if (x.length !== y.length) return false
- try { return crypto.timingSafeEqual(x, y) } catch { return false }
- }
- export function create (user) {
- const sid = crypto.randomBytes(32).toString('base64url')
- const now = Date.now()
- const session = {
- sid,
- user,
- createdAt: now,
- lastSeen: now,
- expiresAt: now + config.sessionHours * 3600_000
- }
- sessions.set(sid, session)
- startSweeper()
- return session
- }
- export function get (sid) {
- if (!sid) return null
- const session = sessions.get(sid)
- if (!session) return null
- if (session.expiresAt < Date.now()) {
- sessions.delete(sid)
- return null
- }
- session.lastSeen = Date.now()
- return session
- }
- export function drop (sid) {
- sessions.delete(sid)
- }
- export function size () {
- return sessions.size
- }
- export function all () {
- return [...sessions.values()]
- }
- export function cookieOf (sid) {
- return `${config.cookieName}=${sid}.${sign(sid)}; Path=/; HttpOnly; SameSite=Lax; Max-Age=${config.sessionHours * 3600}`
- }
- export function clearCookie () {
- return `${config.cookieName}=; Path=/; HttpOnly; SameSite=Lax; Max-Age=0`
- }
- export function parseCookies (header) {
- const out = {}
- for (const part of String(header || '').split(';')) {
- const idx = part.indexOf('=')
- if (idx < 0) continue
- const key = part.slice(0, idx).trim()
- if (key) out[key] = decodeURIComponent(part.slice(idx + 1).trim())
- }
- return out
- }
- /** 从请求里恢复会话:签名不对、过期、或 sid 不在表里,都当没登录。 */
- export function fromRequest (req) {
- const cookies = parseCookies(req.headers.cookie)
- const raw = cookies[config.cookieName]
- if (!raw) return null
- const idx = raw.lastIndexOf('.')
- if (idx <= 0) return null
- const sid = raw.slice(0, idx)
- const mac = raw.slice(idx + 1)
- if (!safeEqual(mac, sign(sid))) return null
- return get(sid)
- }
- function startSweeper () {
- if (sweeper) return
- sweeper = setInterval(() => {
- const now = Date.now()
- for (const [sid, s] of sessions) {
- if (s.expiresAt < now) sessions.delete(sid)
- }
- }, 10 * 60_000)
- sweeper.unref?.()
- }
|