(req: Request, res: Response, next: NextFunction)
| 1488 | * Supports both cookie-based auth (web) and Authorization header (native apps) |
| 1489 | */ |
| 1490 | export async function optionalAuth(req: Request, res: Response, next: NextFunction) { |
| 1491 | // Dev mode: set dev user if logged in via dev-session cookie |
| 1492 | if (DEV_MODE_ENABLED) { |
| 1493 | const devUser = createDevUser(req); |
| 1494 | if (devUser) { |
| 1495 | req.user = devUser; |
| 1496 | req.accessToken = 'dev-mode-token'; |
| 1497 | // Carry over dev config flags (isMember, isAdmin) so enrichUserWithMembership skips DB lookup |
| 1498 | const devConfig = getDevUser(req); |
| 1499 | if (devConfig) { |
| 1500 | (req.user as unknown as Record<string, unknown>).isMember = devConfig.isMember; |
| 1501 | } |
| 1502 | } |
| 1503 | // No dev session = not logged in (which is fine for optional auth) |
| 1504 | return next(); |
| 1505 | } |
| 1506 | |
| 1507 | const sessionCookie = extractSealedSession(req); |
| 1508 | |
| 1509 | if (!sessionCookie) { |
| 1510 | return next(); |
| 1511 | } |
| 1512 | |
| 1513 | try { |
| 1514 | // Check session cache first to avoid repeated WorkOS API calls |
| 1515 | const cacheKey = hashSessionCookie(sessionCookie); |
| 1516 | const cached = sessionCache.get(cacheKey); |
| 1517 | const now = Date.now(); |
| 1518 | |
| 1519 | // Fast-reject sessions already known to be dead |
| 1520 | const deadAt = deadSessionCache.get(cacheKey); |
| 1521 | if (deadAt) { |
| 1522 | if (now - deadAt < DEAD_SESSION_TTL_MS) { |
| 1523 | return next(); // optional auth: just proceed without user |
| 1524 | } |
| 1525 | deadSessionCache.delete(cacheKey); |
| 1526 | } |
| 1527 | |
| 1528 | if (cached && cached.expiresAt > now) { |
| 1529 | // Cache hit - use cached session data |
| 1530 | logger.debug({ userId: cached.user.id }, 'Using cached session (optional auth)'); |
| 1531 | req.user = cached.user; |
| 1532 | req.accessToken = cached.accessToken; |
| 1533 | |
| 1534 | // If session was refreshed, update the cookie |
| 1535 | if (cached.newSealedSession) { |
| 1536 | setSessionCookie(res, cached.newSealedSession); |
| 1537 | } |
| 1538 | |
| 1539 | return next(); |
| 1540 | } |
| 1541 | |
| 1542 | // Cache miss or expired - validate with WorkOS |
| 1543 | // Load the sealed session to get access to both authenticate and refresh methods |
| 1544 | const session = workos.userManagement.loadSealedSession({ |
| 1545 | sessionData: sessionCookie, |
| 1546 | cookiePassword: WORKOS_COOKIE_PASSWORD, |
| 1547 | }); |
nothing calls this directly
no test coverage detected