session.js (21231B)
1 import crypto from 'node:crypto'; 2 import { parseCookie, stringifySetCookie } from 'cookie'; 3 import { findUserById, getMembership, getUserRoles } from './users.js'; 4 5 export const SHORT_SESSION_TTL = 12 * 60 * 60; 6 export const LONG_SESSION_TTL = 7 * 24 * 60 * 60; 7 export const SESSION_COOKIE = 'auth_session'; 8 const TOUCH_INTERVAL_MS = 60 * 1000; 9 10 function isSecureRequest(req) { 11 if (req.socket?.encrypted) return true; 12 const proto = String(req.headers['x-forwarded-proto'] || '').split(',')[0].trim().toLowerCase(); 13 return proto === 'https'; 14 } 15 16 function appendSetCookie(res, value) { 17 const existing = res.getHeader('Set-Cookie'); 18 if (!existing) { 19 res.setHeader('Set-Cookie', value); 20 return; 21 } 22 const values = Array.isArray(existing) ? existing : [existing]; 23 res.setHeader('Set-Cookie', [...values, value]); 24 } 25 26 export function setSessionCookie(res, req, token, ttl) { 27 appendSetCookie( 28 res, 29 stringifySetCookie({ 30 name: SESSION_COOKIE, 31 value: token, 32 httpOnly: true, 33 sameSite: 'lax', 34 path: '/', 35 maxAge: ttl, 36 secure: isSecureRequest(req), 37 }) 38 ); 39 } 40 41 export function clearSessionCookie(res, req) { 42 appendSetCookie( 43 res, 44 stringifySetCookie({ 45 name: SESSION_COOKIE, 46 value: '', 47 httpOnly: true, 48 sameSite: 'lax', 49 path: '/', 50 maxAge: 0, 51 secure: isSecureRequest(req), 52 }) 53 ); 54 } 55 56 export function requestToken(req) { 57 const cookies = parseCookie(req.headers.cookie || ''); 58 return cookies[SESSION_COOKIE] || null; 59 } 60 61 export function requestIp(req) { 62 const forwarded = String(req.headers['x-forwarded-for'] || '') 63 .split(',')[0] 64 .trim(); 65 return forwarded || req.socket?.remoteAddress || null; 66 } 67 68 function hashToken(token) { 69 return crypto.createHash('sha256').update(token).digest('hex'); 70 } 71 72 function scopeForContext(context) { 73 if (context.mode === 'canonical') { 74 return { scopeType: 'global', realmId: null, clientId: null }; 75 } 76 if (context.mode === 'realm') { 77 return { scopeType: 'realm', realmId: context.realm.id, clientId: null }; 78 } 79 return { 80 scopeType: 'client', 81 realmId: context.realm.id, 82 clientId: context.clientId, 83 }; 84 } 85 86 function scopeMatches(session, context) { 87 if (session.scope_host !== context.host) return false; 88 if (context.mode === 'canonical') return session.scope_type === 'global'; 89 if (context.mode === 'realm') { 90 return session.scope_type === 'realm' && session.realm_id === context.realm.id; 91 } 92 return ( 93 session.scope_type === 'client' && 94 session.realm_id === context.realm.id && 95 session.client_id === context.clientId 96 ); 97 } 98 99 export function sessionMatchesContext(session, context) { 100 return scopeMatches(session, context); 101 } 102 103 export async function findActiveSessionById(systemDb, sessionId, now = Date.now()) { 104 return systemDb.get( 105 `SELECT id, public_id, group_id, user_id, scope_type, scope_host, realm_id, 106 client_id, ttl, auth_time, created_at, expires_at, last_seen_at, 107 user_agent, ip 108 FROM sessions 109 WHERE id = {id} AND expires_at > {now}`, 110 { id: sessionId, now } 111 ); 112 } 113 114 async function findGroupByToken(systemDb, token) { 115 if (!token) return null; 116 return systemDb.get( 117 `SELECT id, host, active_session_id, created_at, last_seen_at 118 FROM session_groups 119 WHERE id = {id}`, 120 { id: hashToken(token) } 121 ); 122 } 123 124 async function findActiveSession(systemDb, group) { 125 if (!group?.active_session_id) return null; 126 return systemDb.get( 127 `SELECT id, public_id, group_id, user_id, scope_type, scope_host, realm_id, 128 client_id, ttl, auth_time, created_at, expires_at, last_seen_at, 129 user_agent, ip 130 FROM sessions 131 WHERE id = {id} AND group_id = {groupId}`, 132 { id: group.active_session_id, groupId: group.id } 133 ); 134 } 135 136 export async function getSessionByToken(systemDb, token, now = Date.now()) { 137 const group = await findGroupByToken(systemDb, token); 138 if (!group) return null; 139 const session = await findActiveSession(systemDb, group); 140 if (!session || session.expires_at <= now) return null; 141 return { group, session }; 142 } 143 144 async function deleteGroup(systemDb, groupId) { 145 await systemDb.run('DELETE FROM session_groups WHERE id = {id}', { id: groupId }); 146 } 147 148 async function nextActiveSession(systemDb, groupId, now) { 149 return systemDb.get( 150 `SELECT id 151 FROM sessions 152 WHERE group_id = {groupId} AND expires_at > {now} 153 ORDER BY created_at DESC 154 LIMIT 1`, 155 { groupId, now } 156 ); 157 } 158 159 export async function purgeExpiredSessions(systemDb, now = Date.now()) { 160 await systemDb.transaction(async (tx) => { 161 await tx.run('DELETE FROM sessions WHERE expires_at <= {now}', { now }); 162 await tx.run( 163 'DELETE FROM session_groups WHERE id NOT IN (SELECT group_id FROM sessions)' 164 ); 165 }); 166 } 167 168 async function insertSession(tx, { 169 groupId, 170 userId, 171 scope, 172 scopeHost, 173 ttl, 174 userAgent, 175 ip, 176 now, 177 }) { 178 const id = crypto.randomUUID(); 179 const publicId = crypto.randomUUID(); 180 const expiresAt = now + ttl * 1000; 181 const authTime = Math.floor(now / 1000); 182 183 await tx.run( 184 `INSERT INTO sessions 185 (id, public_id, group_id, user_id, scope_type, scope_host, realm_id, 186 client_id, ttl, auth_time, created_at, expires_at, last_seen_at, 187 user_agent, ip) 188 VALUES 189 ({id}, {publicId}, {groupId}, {userId}, {scopeType}, {scopeHost}, {realmId}, 190 {clientId}, {ttl}, {authTime}, {createdAt}, {expiresAt}, {lastSeenAt}, 191 {userAgent}, {ip})`, 192 { 193 id, 194 publicId, 195 groupId, 196 userId, 197 scopeType: scope.scopeType, 198 scopeHost, 199 realmId: scope.realmId, 200 clientId: scope.clientId, 201 ttl, 202 authTime, 203 createdAt: now, 204 expiresAt, 205 lastSeenAt: now, 206 userAgent, 207 ip, 208 } 209 ); 210 211 return { 212 id, 213 public_id: publicId, 214 group_id: groupId, 215 user_id: userId, 216 scope_type: scope.scopeType, 217 scope_host: scopeHost, 218 realm_id: scope.realmId, 219 client_id: scope.clientId, 220 ttl, 221 auth_time: authTime, 222 created_at: now, 223 expires_at: expiresAt, 224 last_seen_at: now, 225 user_agent: userAgent, 226 ip, 227 }; 228 } 229 230 export async function createHostSession( 231 systemDb, 232 { context, token = null, userId, ttl, userAgent = null, ip = null }, 233 now = Date.now() 234 ) { 235 const scope = scopeForContext(context); 236 237 return systemDb.transaction(async (tx) => { 238 let group = await findGroupByToken(tx, token); 239 if (group && group.host !== context.host) group = null; 240 241 if (group) { 242 const existing = await tx.get( 243 `SELECT id, public_id, group_id, user_id, scope_type, scope_host, realm_id, 244 client_id, ttl, auth_time, created_at, expires_at, last_seen_at, 245 user_agent, ip 246 FROM sessions 247 WHERE group_id = {groupId} AND user_id = {userId}`, 248 { groupId: group.id, userId } 249 ); 250 251 if ( 252 existing && 253 existing.expires_at > now && 254 existing.scope_type === scope.scopeType && 255 existing.scope_host === context.host && 256 existing.realm_id === scope.realmId && 257 existing.client_id === scope.clientId 258 ) { 259 const sessionTtl = Math.max(existing.ttl, ttl); 260 const expiresAt = Math.max(existing.expires_at, now + sessionTtl * 1000); 261 await tx.run( 262 `UPDATE sessions 263 SET ttl = {ttl}, expires_at = {expiresAt}, last_seen_at = {now}, 264 user_agent = {userAgent}, ip = {ip} 265 WHERE id = {id}`, 266 { ttl: sessionTtl, expiresAt, now, userAgent, ip, id: existing.id } 267 ); 268 await tx.run( 269 `UPDATE session_groups 270 SET active_session_id = {sessionId}, last_seen_at = {now} 271 WHERE id = {groupId}`, 272 { sessionId: existing.id, now, groupId: group.id } 273 ); 274 return { 275 token, 276 group: { ...group, active_session_id: existing.id, last_seen_at: now }, 277 session: { 278 ...existing, 279 ttl: sessionTtl, 280 expires_at: expiresAt, 281 last_seen_at: now, 282 user_agent: userAgent, 283 ip, 284 }, 285 }; 286 } 287 288 if (existing) { 289 await tx.run('DELETE FROM sessions WHERE id = {id}', { id: existing.id }); 290 } 291 292 const session = await insertSession(tx, { 293 groupId: group.id, 294 userId, 295 scope, 296 scopeHost: context.host, 297 ttl, 298 userAgent, 299 ip, 300 now, 301 }); 302 await tx.run( 303 `UPDATE session_groups 304 SET active_session_id = {sessionId}, last_seen_at = {now} 305 WHERE id = {groupId}`, 306 { sessionId: session.id, now, groupId: group.id } 307 ); 308 309 return { 310 token, 311 group: { ...group, active_session_id: session.id, last_seen_at: now }, 312 session, 313 }; 314 } 315 316 const nextToken = crypto.randomBytes(32).toString('base64url'); 317 const groupId = hashToken(nextToken); 318 const createdAt = now; 319 320 await tx.run( 321 `INSERT INTO session_groups 322 (id, host, active_session_id, created_at, last_seen_at) 323 VALUES 324 ({id}, {host}, NULL, {createdAt}, {lastSeenAt})`, 325 { id: groupId, host: context.host, createdAt, lastSeenAt: now } 326 ); 327 328 const session = await insertSession(tx, { 329 groupId, 330 userId, 331 scope, 332 scopeHost: context.host, 333 ttl, 334 userAgent, 335 ip, 336 now, 337 }); 338 339 await tx.run( 340 'UPDATE session_groups SET active_session_id = {sessionId} WHERE id = {id}', 341 { sessionId: session.id, id: groupId } 342 ); 343 344 return { 345 token: nextToken, 346 group: { 347 id: groupId, 348 host: context.host, 349 active_session_id: session.id, 350 created_at: createdAt, 351 last_seen_at: now, 352 }, 353 session, 354 }; 355 }); 356 } 357 358 export async function listSessionAccounts(systemDb, group, now = Date.now()) { 359 if (!group) return []; 360 361 const rows = await systemDb.all( 362 `SELECT s.id, s.public_id, s.user_id, s.created_at, s.expires_at, 363 u.username, u.display_name 364 FROM sessions s 365 JOIN users u ON u.id = s.user_id 366 WHERE s.group_id = {groupId} 367 AND s.expires_at > {now} 368 AND u.status = 'active' 369 ORDER BY s.created_at ASC`, 370 { groupId: group.id, now } 371 ); 372 373 return rows.map((row) => ({ 374 public_id: row.public_id, 375 active: row.id === group.active_session_id, 376 user: { 377 id: row.user_id, 378 username: row.username, 379 display_name: row.display_name, 380 }, 381 created_at: row.created_at, 382 expires_at: row.expires_at, 383 })); 384 } 385 386 export async function selectSessionAccount( 387 systemDb, 388 { token, context, publicId }, 389 now = Date.now() 390 ) { 391 if (!token || !publicId) return null; 392 393 return systemDb.transaction(async (tx) => { 394 const group = await findGroupByToken(tx, token); 395 if (!group || group.host !== context.host) return null; 396 397 const session = await tx.get( 398 `SELECT id, public_id, group_id, user_id, scope_type, scope_host, realm_id, 399 client_id, ttl, auth_time, created_at, expires_at, last_seen_at, 400 user_agent, ip 401 FROM sessions 402 WHERE group_id = {groupId} AND public_id = {publicId}`, 403 { groupId: group.id, publicId } 404 ); 405 if (!session || session.expires_at <= now || !scopeMatches(session, context)) { 406 return null; 407 } 408 409 const user = await findUserById(tx, session.user_id); 410 if (!user || user.status !== 'active') return null; 411 412 const expiresAt = now + session.ttl * 1000; 413 await tx.run( 414 `UPDATE sessions 415 SET last_seen_at = {now}, expires_at = {expiresAt} 416 WHERE id = {id}`, 417 { now, expiresAt, id: session.id } 418 ); 419 await tx.run( 420 `UPDATE session_groups 421 SET active_session_id = {sessionId}, last_seen_at = {now} 422 WHERE id = {id}`, 423 { sessionId: session.id, now, id: group.id } 424 ); 425 426 return { 427 group: { ...group, active_session_id: session.id, last_seen_at: now }, 428 session: { ...session, last_seen_at: now, expires_at: expiresAt }, 429 user, 430 }; 431 }); 432 } 433 434 export async function authenticateRequest({ 435 systemDb, 436 realmDb = null, 437 req, 438 res, 439 context, 440 now = Date.now(), 441 }) { 442 const token = requestToken(req); 443 if (!token) return null; 444 445 const group = await findGroupByToken(systemDb, token); 446 if (!group || group.host !== context.host) { 447 clearSessionCookie(res, req); 448 return null; 449 } 450 451 const session = await findActiveSession(systemDb, group); 452 if (!session || session.expires_at <= now) { 453 if (session) { 454 await systemDb.run('DELETE FROM sessions WHERE id = {id}', { id: session.id }); 455 } 456 const next = await nextActiveSession(systemDb, group.id, now); 457 if (next) { 458 await systemDb.run( 459 'UPDATE session_groups SET active_session_id = {sessionId} WHERE id = {id}', 460 { sessionId: next.id, id: group.id } 461 ); 462 } else { 463 await deleteGroup(systemDb, group.id); 464 clearSessionCookie(res, req); 465 } 466 return null; 467 } 468 469 if (!scopeMatches(session, context)) { 470 clearSessionCookie(res, req); 471 return null; 472 } 473 474 const user = await findUserById(systemDb, session.user_id); 475 if (!user || user.status !== 'active') { 476 const groupDeleted = await systemDb.transaction(async (tx) => { 477 await tx.run('DELETE FROM sessions WHERE id = {id}', { id: session.id }); 478 const next = await nextActiveSession(tx, group.id, now); 479 if (next) { 480 await tx.run( 481 'UPDATE session_groups SET active_session_id = {sessionId} WHERE id = {id}', 482 { sessionId: next.id, id: group.id } 483 ); 484 return false; 485 } 486 await deleteGroup(tx, group.id); 487 return true; 488 }); 489 if (groupDeleted) clearSessionCookie(res, req); 490 return null; 491 } 492 493 const membership = realmDb ? await getMembership(realmDb, user.id) : null; 494 const roles = realmDb ? await getUserRoles(realmDb, user.id) : []; 495 496 if (now - session.last_seen_at >= TOUCH_INTERVAL_MS) { 497 const expiresAt = now + session.ttl * 1000; 498 await systemDb.transaction(async (tx) => { 499 await tx.run( 500 `UPDATE sessions 501 SET last_seen_at = {now}, expires_at = {expiresAt} 502 WHERE id = {id}`, 503 { now, expiresAt, id: session.id } 504 ); 505 await tx.run( 506 'UPDATE session_groups SET last_seen_at = {now} WHERE id = {id}', 507 { now, id: group.id } 508 ); 509 }); 510 session.last_seen_at = now; 511 session.expires_at = expiresAt; 512 setSessionCookie(res, req, token, session.ttl); 513 } 514 515 return { group, session, user, membership, roles }; 516 } 517 518 async function removeSession(tx, session, now) { 519 const group = await tx.get( 520 'SELECT active_session_id FROM session_groups WHERE id = {id}', 521 { id: session.group_id } 522 ); 523 await tx.run('DELETE FROM sessions WHERE id = {id}', { id: session.id }); 524 if (!group) return { groupDeleted: true }; 525 if (group.active_session_id !== session.id) return { groupDeleted: false }; 526 527 const next = await nextActiveSession(tx, session.group_id, now); 528 if (next) { 529 await tx.run( 530 'UPDATE session_groups SET active_session_id = {sessionId} WHERE id = {id}', 531 { sessionId: next.id, id: session.group_id } 532 ); 533 return { groupDeleted: false }; 534 } 535 536 await deleteGroup(tx, session.group_id); 537 return { groupDeleted: true }; 538 } 539 540 export async function destroySession(systemDb, token) { 541 if (!token) return { groupDeleted: true }; 542 543 return systemDb.transaction(async (tx) => { 544 const group = await findGroupByToken(tx, token); 545 if (!group) return { groupDeleted: true }; 546 547 const session = await findActiveSession(tx, group); 548 if (session) return removeSession(tx, session, Date.now()); 549 550 const next = await nextActiveSession(tx, group.id, Date.now()); 551 if (next) { 552 await tx.run( 553 'UPDATE session_groups SET active_session_id = {sessionId} WHERE id = {id}', 554 { sessionId: next.id, id: group.id } 555 ); 556 return { groupDeleted: false }; 557 } 558 559 await deleteGroup(tx, group.id); 560 return { groupDeleted: true }; 561 }); 562 } 563 564 export async function destroySessionById(systemDb, sessionId, now = Date.now()) { 565 return systemDb.transaction(async (tx) => { 566 const session = await tx.get( 567 'SELECT id, group_id FROM sessions WHERE id = {id}', 568 { id: sessionId } 569 ); 570 if (!session) return { deleted: false, groupDeleted: false }; 571 572 const result = await removeSession(tx, session, now); 573 return { deleted: true, ...result }; 574 }); 575 } 576 577 export async function destroyClientHostSessions( 578 systemDb, 579 { realmId, clientId, host, now = Date.now() } 580 ) { 581 return systemDb.transaction(async (tx) => { 582 const sessions = await tx.all( 583 `SELECT id, group_id FROM sessions 584 WHERE scope_type = 'client' AND realm_id = {realmId} 585 AND client_id = {clientId} AND scope_host = {host}`, 586 { realmId, clientId, host } 587 ); 588 for (const session of sessions) { 589 await removeSession(tx, session, now); 590 } 591 return { destroyed: sessions.length }; 592 }); 593 } 594 595 export async function destroyUserSessions(systemDb, { userId, now = Date.now() }) { 596 return systemDb.transaction(async (tx) => { 597 // Expired rows are included so stale refresh tokens cascade too. 598 const sessions = await tx.all( 599 'SELECT id, group_id FROM sessions WHERE user_id = {userId}', 600 { userId } 601 ); 602 for (const session of sessions) { 603 await removeSession(tx, session, now); 604 } 605 return { destroyed: sessions.length }; 606 }); 607 } 608 609 export async function getSessionRealmBinding(systemDb, sessionId, realmId) { 610 return systemDb.get( 611 `SELECT session_id, realm_id, created_at, last_seen_at, revoked_at, revoked_by 612 FROM session_realms 613 WHERE session_id = {sessionId} AND realm_id = {realmId}`, 614 { sessionId, realmId } 615 ); 616 } 617 618 export async function revokeSessionRealm( 619 systemDb, 620 { sessionId, realmId, revokedBy = null, now = Date.now() } 621 ) { 622 return systemDb.transaction(async (tx) => { 623 const existing = await getSessionRealmBinding(tx, sessionId, realmId); 624 if (existing) { 625 if (!existing.revoked_at) { 626 await tx.run( 627 `UPDATE session_realms 628 SET revoked_at = {now}, revoked_by = {revokedBy} 629 WHERE session_id = {sessionId} AND realm_id = {realmId}`, 630 { now, revokedBy, sessionId, realmId } 631 ); 632 existing.revoked_at = now; 633 existing.revoked_by = revokedBy; 634 } 635 return existing; 636 } 637 638 await tx.run( 639 `INSERT INTO session_realms 640 (session_id, realm_id, created_at, last_seen_at, revoked_at, revoked_by) 641 VALUES 642 ({sessionId}, {realmId}, {now}, {now}, {now}, {revokedBy})`, 643 { sessionId, realmId, now, revokedBy } 644 ); 645 return { 646 session_id: sessionId, 647 realm_id: realmId, 648 created_at: now, 649 last_seen_at: now, 650 revoked_at: now, 651 revoked_by: revokedBy, 652 }; 653 }); 654 } 655 656 export async function revokeRealmSessions( 657 systemDb, 658 { realmId, revokedBy = null, now = Date.now() } 659 ) { 660 const result = await systemDb.run( 661 `UPDATE session_realms 662 SET revoked_at = {now}, revoked_by = {revokedBy} 663 WHERE realm_id = {realmId} AND revoked_at IS NULL`, 664 { realmId, revokedBy, now } 665 ); 666 return result.changes; 667 } 668 669 export async function revokeUserRealmSessions( 670 systemDb, 671 { userId, realmId, revokedBy = null, now = Date.now() } 672 ) { 673 const result = await systemDb.run( 674 `UPDATE session_realms 675 SET revoked_at = {now}, revoked_by = {revokedBy} 676 WHERE realm_id = {realmId} 677 AND revoked_at IS NULL 678 AND session_id IN (SELECT id FROM sessions WHERE user_id = {userId})`, 679 { now, revokedBy, realmId, userId } 680 ); 681 return result.changes; 682 } 683 684 export async function reauthenticateSession( 685 systemDb, 686 { sessionId, realmId, now = Date.now() } 687 ) { 688 const authTime = Math.floor(now / 1000); 689 690 return systemDb.transaction(async (tx) => { 691 await tx.run( 692 `UPDATE sessions 693 SET auth_time = {authTime}, last_seen_at = {now} 694 WHERE id = {id}`, 695 { authTime, now, id: sessionId } 696 ); 697 await tx.run( 698 `UPDATE session_realms 699 SET revoked_at = NULL, revoked_by = NULL, last_seen_at = {now} 700 WHERE session_id = {sessionId} AND realm_id = {realmId}`, 701 { now, sessionId, realmId } 702 ); 703 return authTime; 704 }); 705 } 706 707 export async function bindSessionRealm(systemDb, sessionId, realmId, now = Date.now()) { 708 const existing = await systemDb.get( 709 `SELECT session_id, realm_id, revoked_at 710 FROM session_realms 711 WHERE session_id = {sessionId} AND realm_id = {realmId}`, 712 { sessionId, realmId } 713 ); 714 715 if (existing) { 716 if (!existing.revoked_at) { 717 await systemDb.run( 718 `UPDATE session_realms 719 SET last_seen_at = {now} 720 WHERE session_id = {sessionId} AND realm_id = {realmId}`, 721 { now, sessionId, realmId } 722 ); 723 } 724 return; 725 } 726 727 await systemDb.run( 728 `INSERT INTO session_realms 729 (session_id, realm_id, created_at, last_seen_at, revoked_at, revoked_by) 730 VALUES 731 ({sessionId}, {realmId}, {now}, {now}, NULL, NULL)`, 732 { sessionId, realmId, now } 733 ); 734 }