Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions server/src/db/session-refresh-db.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,9 +40,12 @@ export async function storeRefreshedSession(
/**
* Look up a refreshed session by the hash of the old cookie.
* Returns the new sealed session if found and not expired, undefined otherwise.
* Lookup failures also return undefined unless `throwOnError` is set, for
* callers that must not mistake an outage for "nothing stored".
*/
export async function getRefreshedSession(
oldCookieHash: string,
{ throwOnError = false }: { throwOnError?: boolean } = {},
): Promise<string | undefined> {
if (!isDatabaseInitialized()) return undefined;
try {
Expand All @@ -56,6 +59,7 @@ export async function getRefreshedSession(
}
} catch (err) {
logger.warn({ err }, 'Failed to look up refreshed session');
if (throwOnError) throw err;
}
return undefined;
}
Expand Down
103 changes: 38 additions & 65 deletions server/src/http.ts
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ import { resolveUserNameWithFallbacks, sanitizeName } from "./utils/resolve-user
import { scrubCommunityAuthorizedAgents } from "./utils/community-adagents.js";
import { formatPerspectiveUrlAsMarkdownDestination, normalizePerspectiveExternalUrl } from "./utils/perspective-url.js";
import { decodeHtmlEntities } from "./utils/html-entities.js";
import { requireAuth, requireAdmin, requireGlobalAdmin, optionalAuth, invalidateSessionCache, switchSessionOrganization, isDevModeEnabled, getDevUser, getAvailableDevUsers, getDevSessionCookieName, encodeDevSessionCookie, DEV_USERS, type DevUserConfig } from "./middleware/auth.js";
import { requireAuth, requireAdmin, requireGlobalAdmin, optionalAuth, invalidateSessionCache, resolvePageSession, type PageSession, type PageSessionUser, switchSessionOrganization, isDevModeEnabled, getDevUser, getAvailableDevUsers, getDevSessionCookieName, encodeDevSessionCookie, DEV_USERS, type DevUserConfig } from "./middleware/auth.js";
import { invitationRateLimiter, brandCreationRateLimiter, notificationRateLimiter, emailPrefsRateLimiter, adminContentWriteRateLimiter, newsletterSubscribeRateLimiter, newsletterConfirmRateLimiter, agentCardValidationRateLimiter } from "./middleware/rate-limit.js";
import { findOrCreateUserByEmail } from "./auth/workos-client.js";
import { sendNewsletterConfirmation } from "./notifications/email.js";
Expand Down Expand Up @@ -1151,75 +1151,29 @@ function getCsrfScriptVersion(): string {
}

/**
* Get user info from request for HTML config injection.
* Checks dev mode first, then WorkOS session.
* If session is refreshed, updates the cookie in the response.
* Resolve the page session for HTML config injection.
* Checks dev mode first, then WorkOS session. Refreshed sessions update the
* cookie; a cookie WorkOS definitively rejects is cleared.
*/
async function getUserFromRequest(
req: express.Request,
res?: express.Response
): Promise<{ id?: string; email: string; firstName?: string | null; lastName?: string | null } | null> {
async function getPageSession(req: express.Request, res: express.Response): Promise<PageSession> {
// Check dev mode first
if (isDevModeEnabled()) {
const devUser = getDevUser(req);
if (devUser) {
return devUser;
return { user: devUser, cleared: false };
}
}

// Then check WorkOS session
const sessionCookie = req.cookies?.['wos-session'];
// codeql[js/user-controlled-bypass] - session cookie is verified cryptographically by WorkOS sealed session
if (sessionCookie && AUTH_ENABLED && workos) {
try {
const session = workos.userManagement.loadSealedSession({
sessionData: sessionCookie,
cookiePassword: WORKOS_COOKIE_PASSWORD,
});

// Try to authenticate with the current session
let authResult = await session.authenticate();

// If authentication failed (e.g., expired token), try to refresh
if (!authResult.authenticated || !authResult.user) {
try {
const refreshResult = await session.refresh({
cookiePassword: WORKOS_COOKIE_PASSWORD,
});

if (refreshResult.authenticated && refreshResult.sealedSession) {
// Update the cookie with the refreshed session
if (res) {
res.cookie('wos-session', refreshResult.sealedSession, {
httpOnly: true,
secure: process.env.NODE_ENV === 'production',
sameSite: 'lax',
path: '/',
maxAge: 7 * 24 * 60 * 60 * 1000, // 7 days
});
}

// Re-authenticate with the new session
const newSession = workos.userManagement.loadSealedSession({
sessionData: refreshResult.sealedSession,
cookiePassword: WORKOS_COOKIE_PASSWORD,
});
authResult = await newSession.authenticate();
}
} catch {
// Refresh failed - continue without user
}
}

if (authResult.authenticated && authResult.user) {
return authResult.user;
}
} catch {
// Session invalid or expired - continue without user
}
}
if (!AUTH_ENABLED) return { user: null, cleared: false };
return resolvePageSession(req, res);
}

return null;
/** Get user info from request for HTML config injection. */
async function getUserFromRequest(
req: express.Request,
res: express.Response
): Promise<PageSessionUser | null> {
return (await getPageSession(req, res)).user;
}

function stripLegacyBrandContext(manifest: Record<string, unknown>): Record<string, unknown> {
Expand Down Expand Up @@ -1544,7 +1498,9 @@ export class HTTPServer {
html = await this.injectHomepageMemberCount(html);

// Get user from session (if authenticated), passing res to update cookie if session is refreshed
const user = await getUserFromRequest(req, res);
const session = await getPageSession(req, res);
if (this.rebridgeIfSessionCleared(req, res, session)) return;
const user = session.user;
await enrichUserWithMembership(user);
await enrichUserWithAdmin(user);

Expand Down Expand Up @@ -1696,13 +1652,28 @@ export class HTTPServer {
if (!req.headers.cookie && !isTopLevelDocumentNavigation) return false;

if (this.isAdcpDomain(req) && !req.cookies?.['wos-session'] && !req.cookies?.['bridge-checked']) {
const currentUrl = `https://${req.hostname}${req.originalUrl}`;
res.redirect(`https://agenticadvertising.org/auth/bridge?return_to=${encodeURIComponent(currentUrl)}`);
this.redirectThroughBridge(req, res);
return true;
}
return false;
}

// The AdCP cookie is a copy of the AAO session, and either copy can rotate
// the shared refresh token. When WorkOS rejects the AdCP copy, bridge once
// more to pick up the current AAO session. The return marker stops a loop
// when the AAO session is dead too.
private rebridgeIfSessionCleared(req: express.Request, res: express.Response, session: PageSession): boolean {
if (!session.cleared || !this.isAdcpDomain(req)) return false;
if (req.query?.[HTTPServer.BRIDGE_CHECK_PARAM] === '1') return false;
this.redirectThroughBridge(req, res);
return true;
}

private redirectThroughBridge(req: express.Request, res: express.Response): void {
const currentUrl = `https://${req.hostname}${req.originalUrl}`;
res.redirect(`https://agenticadvertising.org/auth/bridge?return_to=${encodeURIComponent(currentUrl)}`);
}

private async injectHomepageMemberCount(html: string, memberDb = new MemberDatabase()): Promise<string> {
if (!html.includes('{{PUBLIC_MEMBER_COUNT_PLUS}}')) {
return html;
Expand Down Expand Up @@ -1733,7 +1704,9 @@ export class HTTPServer {
if (this.bridgeIfNeeded(req, res)) return;

// Get user from session (if authenticated), passing res to update cookie if session is refreshed
const user = await getUserFromRequest(req, res);
const session = await getPageSession(req, res);
if (this.rebridgeIfSessionCleared(req, res, session)) return;
const user = session.user;
await enrichUserWithMembership(user);
await enrichUserWithAdmin(user);

Expand Down
168 changes: 148 additions & 20 deletions server/src/middleware/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1197,11 +1197,7 @@ async function requireAuthWithSnapshot(
// hasn't written its refreshed session to the DB yet.
if (refreshFailed) {
try {
let sharedSession = await getRefreshedSession(cacheKey);
if (!sharedSession) {
await new Promise(resolve => setTimeout(resolve, 200));
sharedSession = await getRefreshedSession(cacheKey);
}
const sharedSession = await findSharedRefreshedSession(cacheKey);
if (sharedSession) {
logger.info({ path: req.path }, 'Found shared refreshed session from another machine');

Expand Down Expand Up @@ -1267,13 +1263,7 @@ async function requireAuthWithSnapshot(

// Remove any stale positive cache entry and mark session as dead
// so subsequent requests skip the expensive WorkOS refresh + DB fallback
sessionCache.delete(cacheKey);
// LRU eviction: delete oldest entry when at capacity
if (deadSessionCache.size >= DEAD_SESSION_MAX_SIZE) {
const oldest = deadSessionCache.keys().next().value;
if (oldest) deadSessionCache.delete(oldest);
}
deadSessionCache.set(cacheKey, Date.now());
markSessionDead(cacheKey);
if (isHtmlRequest) {
return res.redirect(`/auth/login?return_to=${encodeURIComponent(req.originalUrl)}`);
}
Expand Down Expand Up @@ -1982,6 +1972,150 @@ function extractSealedSession(req: Request): string | undefined {
return typeof sessionCookie === 'string' && sessionCookie ? sessionCookie : undefined;
}

/**
* Look up a session another request already rotated. That request may not
* have stored its result yet, so retry after each delay before giving up.
*/
async function findSharedRefreshedSession(
cacheKey: string,
{ retryDelaysMs = [200], throwOnError = false }: { retryDelaysMs?: number[]; throwOnError?: boolean } = {},
): Promise<string | undefined> {
const lookup = () => throwOnError ? getRefreshedSession(cacheKey, { throwOnError }) : getRefreshedSession(cacheKey);
let shared = await lookup();
for (const delay of retryDelaysMs) {
if (shared) break;
await new Promise(resolve => setTimeout(resolve, delay));
shared = await lookup();
}
return shared;
}

function markSessionDead(cacheKey: string): void {
sessionCache.delete(cacheKey);
// LRU eviction: delete oldest entry when at capacity
if (deadSessionCache.size >= DEAD_SESSION_MAX_SIZE) {
const oldest = deadSessionCache.keys().next().value;
if (oldest) deadSessionCache.delete(oldest);
}
deadSessionCache.set(cacheKey, Date.now());
}

function clearSessionCookie(res: Response): void {
res.clearCookie('wos-session', {
httpOnly: true,
secure: process.env.NODE_ENV === 'production' && !ALLOW_INSECURE_COOKIES,
sameSite: 'lax',
path: '/',
});
}

class PageSessionUnavailableError extends Error {
constructor() {
super('Session refresh temporarily unavailable');
this.name = 'PageSessionUnavailableError';
}
}

export interface PageSessionUser {
id: string;
email: string;
firstName?: string | null;
lastName?: string | null;
}

export interface PageSession {
user: PageSessionUser | null;
/** WorkOS definitively rejected the cookie, and the response now clears it. */
cleared: boolean;
}

async function pageSessionUser(sealedSession: string): Promise<PageSessionUser | null> {
const result = await workos.userManagement.loadSealedSession({
sessionData: sealedSession,
cookiePassword: WORKOS_COOKIE_PASSWORD,
}).authenticate();
return result.authenticated && result.user ? result.user : null;
}

/** Null only for a terminal WorkOS refresh failure; anything else throws. */
async function refreshPageSession(sealedSession: string): Promise<string | null> {
const result = await workos.userManagement.loadSealedSession({
sessionData: sealedSession,
cookiePassword: WORKOS_COOKIE_PASSWORD,
}).refresh({ cookiePassword: WORKOS_COOKIE_PASSWORD });
if (result.authenticated && result.sealedSession) return result.sealedSession;
if (!result.authenticated && 'retryable' in result && result.retryable === false) return null;
throw new PageSessionUnavailableError();
}

async function authenticatePageSession(
sessionCookie: string, cacheKey: string, res: Response,
): Promise<PageSessionUser | null> {
const user = await pageSessionUser(sessionCookie);
if (user) return user;

let refreshed = await refreshPageSession(sessionCookie);
if (!refreshed) {
// The refresh token is single-use; another request (or the other domain's
// copy of this cookie) may already have rotated it. WorkOS answers a lost
// race with the same invalid_grant as a dead session, and a null here
// clears the cookie, so wait longer than the API middleware and treat a
// failed lookup as unavailable rather than as "nothing stored".
const shared = await findSharedRefreshedSession(cacheKey, {
retryDelaysMs: [200, 800],
throwOnError: true,
});
if (!shared) return null;
const sharedUser = await pageSessionUser(shared);
if (sharedUser) {
setSessionCookie(res, shared);
return sharedUser;
}
refreshed = await refreshPageSession(shared);
if (!refreshed) return null;
}

setSessionCookie(res, refreshed);
// Await so concurrent requests holding the old cookie can find the rotation.
await storeRefreshedSession(cacheKey, refreshed);
return pageSessionUser(refreshed);
}

/**
* Resolve the browser session for a server-rendered page. Pages never reject:
* an unusable session renders logged out. Refreshes are shared like the API
* middleware's so other copies of the cookie can recover. A cookie WorkOS
* definitively rejects is cleared; otherwise optional-auth API calls from the
* page would answer 401 for as long as the browser keeps it. Provider outages
* and unknown failures keep the cookie.
*/
export async function resolvePageSession(req: Request, res: Response): Promise<PageSession> {
const sessionCookie = req.cookies?.['wos-session'];
// codeql[js/user-controlled-bypass] - session cookie is verified cryptographically by WorkOS sealed session
if (typeof sessionCookie !== 'string' || !sessionCookie) return { user: null, cleared: false };

const cacheKey = hashSessionCookie(sessionCookie);
const cached = sessionCache.get(cacheKey);
if (cached && cached.expiresAt > Date.now()) {
if (cached.newSealedSession) setSessionCookie(res, cached.newSealedSession);
// Callers enrich the page user in place; the cached user is frozen.
return { user: { ...cached.user }, cleared: false };
}

try {
const user = await authenticatePageSession(sessionCookie, cacheKey, res);
if (user) return { user, cleared: false };
} catch (error) {
logger.debug({ err: error }, 'Page session unavailable');
return { user: null, cleared: false };
}

logger.debug('Clearing session cookie rejected by WorkOS');
markSessionDead(cacheKey);
clearSessionCookie(res);
return { user: null, cleared: true };
}

/**
* Optional auth permits anonymous requests only when no credential is supplied.
* Invalid presented credentials return 401; verification or authorization
Expand Down Expand Up @@ -2142,7 +2276,7 @@ export async function optionalAuth(req: Request, res: Response, next: NextFuncti
// If refresh failed, check DB for a shared refresh from another machine
if (refreshFailed) {
try {
const sharedSession = await getRefreshedSession(cacheKey);
const sharedSession = await findSharedRefreshedSession(cacheKey);
if (sharedSession) {
logger.debug('Found shared refreshed session (optional auth)');
const sharedSessionObj = workos.userManagement.loadSealedSession({
Expand Down Expand Up @@ -2190,13 +2324,7 @@ export async function optionalAuth(req: Request, res: Response, next: NextFuncti
if (!result.authenticated || !('user' in result) || !result.user) {
// All refresh attempts failed — mark session as dead to avoid
// expensive retries on every subsequent request
// LRU eviction: delete oldest entry when at capacity
if (deadSessionCache.size >= DEAD_SESSION_MAX_SIZE) {
const oldest = deadSessionCache.keys().next().value;
if (oldest) deadSessionCache.delete(oldest);
}
deadSessionCache.set(cacheKey, Date.now());
sessionCache.delete(cacheKey);
markSessionDead(cacheKey);
return res.status(401).json({ error: 'Invalid session', login_url: '/auth/login' });
}

Expand Down
Loading
Loading