auth.js 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  1. /**
  2. * 会话与 cookie
  3. * ============
  4. * Web 版没有 Electron 的 store,登录态只活在服务端内存里:
  5. *
  6. * 浏览器只拿到一个随机 sid(HttpOnly + SameSite=Lax),签名防止伪造;
  7. * 真正的 apiKey / 用户身份留在服务端 session 表里,从不写进 cookie。
  8. *
  9. * 这样做的代价是重启进程会掉登录(引擎进程和浏览器也一起没了,本来就要重来);
  10. * 换来的是 apiKey 不会被 XSS 读走,也不会出现在浏览器历史/日志里。
  11. */
  12. import crypto from 'node:crypto'
  13. import { config } from '../config.js'
  14. const sessions = new Map()
  15. let sweeper = null
  16. function sign (sid) {
  17. return crypto.createHmac('sha256', config.secret).update(sid).digest('base64url').slice(0, 32)
  18. }
  19. function safeEqual (a, b) {
  20. const x = Buffer.from(String(a))
  21. const y = Buffer.from(String(b))
  22. if (x.length !== y.length) return false
  23. try { return crypto.timingSafeEqual(x, y) } catch { return false }
  24. }
  25. export function create (user) {
  26. const sid = crypto.randomBytes(32).toString('base64url')
  27. const now = Date.now()
  28. const session = {
  29. sid,
  30. user,
  31. createdAt: now,
  32. lastSeen: now,
  33. expiresAt: now + config.sessionHours * 3600_000
  34. }
  35. sessions.set(sid, session)
  36. startSweeper()
  37. return session
  38. }
  39. export function get (sid) {
  40. if (!sid) return null
  41. const session = sessions.get(sid)
  42. if (!session) return null
  43. if (session.expiresAt < Date.now()) {
  44. sessions.delete(sid)
  45. return null
  46. }
  47. session.lastSeen = Date.now()
  48. return session
  49. }
  50. export function drop (sid) {
  51. sessions.delete(sid)
  52. }
  53. export function size () {
  54. return sessions.size
  55. }
  56. export function all () {
  57. return [...sessions.values()]
  58. }
  59. export function cookieOf (sid) {
  60. return `${config.cookieName}=${sid}.${sign(sid)}; Path=/; HttpOnly; SameSite=Lax; Max-Age=${config.sessionHours * 3600}`
  61. }
  62. export function clearCookie () {
  63. return `${config.cookieName}=; Path=/; HttpOnly; SameSite=Lax; Max-Age=0`
  64. }
  65. export function parseCookies (header) {
  66. const out = {}
  67. for (const part of String(header || '').split(';')) {
  68. const idx = part.indexOf('=')
  69. if (idx < 0) continue
  70. const key = part.slice(0, idx).trim()
  71. if (key) out[key] = decodeURIComponent(part.slice(idx + 1).trim())
  72. }
  73. return out
  74. }
  75. /** 从请求里恢复会话:签名不对、过期、或 sid 不在表里,都当没登录。 */
  76. export function fromRequest (req) {
  77. const cookies = parseCookies(req.headers.cookie)
  78. const raw = cookies[config.cookieName]
  79. if (!raw) return null
  80. const idx = raw.lastIndexOf('.')
  81. if (idx <= 0) return null
  82. const sid = raw.slice(0, idx)
  83. const mac = raw.slice(idx + 1)
  84. if (!safeEqual(mac, sign(sid))) return null
  85. return get(sid)
  86. }
  87. function startSweeper () {
  88. if (sweeper) return
  89. sweeper = setInterval(() => {
  90. const now = Date.now()
  91. for (const [sid, s] of sessions) {
  92. if (s.expiresAt < now) sessions.delete(sid)
  93. }
  94. }, 10 * 60_000)
  95. sweeper.unref?.()
  96. }