File size: 2,390 Bytes
1034ef4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3ee84f3
 
 
 
 
1034ef4
 
3ee84f3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1034ef4
3ee84f3
1034ef4
3ee84f3
1034ef4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
import type { Request, Response } from 'express'
import type { DbSchema, DbSession, SessionKind } from './db.js'
import { newId, nowIso, pruneExpiredSessions } from './db.js'

export const COOKIE_FULL = 'sid'
export const COOKIE_PENDING = 'psid'

function addMinutes(date: Date, minutes: number) {
  return new Date(date.getTime() + minutes * 60_000)
}

function addDays(date: Date, days: number) {
  return new Date(date.getTime() + days * 86_400_000)
}

export function createSession(db: DbSchema, userId: string, kind: SessionKind): DbSession {
  pruneExpiredSessions(db)
  const now = new Date()
  const expires = kind === 'mfa_pending' ? addMinutes(now, 10) : addDays(now, 7)

  const s: DbSession = {
    id: newId(),
    user_id: userId,
    kind,
    created_at: nowIso(),
    expires_at: expires.toISOString(),
  }
  db.sessions.push(s)
  return s
}

function isSecureRequest(req: Request) {
  if (req.secure) return true
  const xfp = req.headers['x-forwarded-proto']
  if (typeof xfp === 'string') return xfp.split(',')[0]?.trim() === 'https'
  return false
}

function cookieBaseOptions(req: Request) {
  return {
    httpOnly: true,
    sameSite: 'lax' as const,
    secure: isSecureRequest(req),
  }
}

export function clearSessionCookies(req: Request, res: Response) {
  const base = cookieBaseOptions(req)
  res.clearCookie(COOKIE_FULL, base)
  res.clearCookie(COOKIE_PENDING, base)
}

export function setSessionCookie(req: Request, res: Response, session: DbSession) {
  const name = session.kind === 'mfa_pending' ? COOKIE_PENDING : COOKIE_FULL
  const base = cookieBaseOptions(req)
  res.cookie(name, session.id, {
    ...base,
    expires: new Date(session.expires_at),
  })
}

export function getSessionFromRequest(req: Request, kind: SessionKind) {
  const cookies = (req as unknown as { cookies?: Record<string, unknown> }).cookies
  const raw = cookies?.[kind === 'mfa_pending' ? COOKIE_PENDING : COOKIE_FULL]
  return typeof raw === 'string' ? raw : null
}

export function removeSessionsByIds(db: DbSchema, ids: string[]) {
  if (ids.length === 0) return
  const set = new Set(ids)
  db.sessions = db.sessions.filter((s) => !set.has(s.id))
}

export function removeOtherUserSessions(db: DbSchema, userId: string, keepSessionIds: string[]) {
  const keep = new Set(keepSessionIds)
  db.sessions = db.sessions.filter((s) => s.user_id !== userId || keep.has(s.id))
}