Files
outline/server/utils/LogoutTokenStore.ts
T
Tom MoorandClaude Opus 5.5 00b124d03c chore: Rename APIContext to Context and flatten its fields (#14684)
* chore: Rename APIContext to Context and flatten its fields

Auth and transaction now live directly on the context instead of in
ctx.state and a nested ctx.context, and model helpers read them directly.
APIContext remains as a deprecated alias.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_016MJXFeUxvU46KyvKnP8sXf

* chore: Remove deprecated APIContext alias

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_016MJXFeUxvU46KyvKnP8sXf

* fix: Read auth from context in OAuth provider callbacks

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_016MJXFeUxvU46KyvKnP8sXf

* chore: Add withUser and withTransaction context helpers

Replaces manual createContext rebuilds that copy fields from an existing context.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_016MJXFeUxvU46KyvKnP8sXf

* chore: Remove arbitrary property access from Koa context types

AppContext and Context no longer inherit the any index signature from
Koa's DefaultContext, custom fields are declared explicitly, and importing
Koa's loose Context type is disallowed by lint.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_016MJXFeUxvU46KyvKnP8sXf

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-11-23 23:17:06 -05:00

119 lines
3.7 KiB
TypeScript

import crypto from "node:crypto";
import { addSeconds, subMinutes } from "date-fns";
import { toError } from "@shared/utils/error";
import { getCookieDomain } from "@shared/utils/domains";
import env from "@server/env";
import Logger from "@server/logging/Logger";
import Redis from "@server/storage/redis";
import { RedisPrefixHelper } from "./RedisPrefixHelper";
import type { AppContext } from "@server/types";
// ~3 months. Matches the default cookie lifetime so the hint is available for
// as long as the cookie referencing it can be sent back.
const DEFAULT_TTL_SECONDS = 90 * 24 * 60 * 60;
/**
* Persists a per-session logout hint (e.g. an OIDC `id_token`) for an auth
* provider that supports provider-initiated logout.
*
* The token is stored server-side keyed by a short random session identifier;
* only that identifier is placed in a cookie. Tokens can be large and storing
* one directly in the cookie inflates response headers enough to exceed reverse
* proxy buffers, resulting in a 502 on sign-in. Both operations are best-effort:
* a Redis failure never blocks sign-in or logout, it only causes the hint to be
* omitted.
*/
export class LogoutTokenStore {
/**
* @param provider The auth provider id, used to namespace the cookie, Redis
* key, and logout path (e.g. "oidc").
* @param ttlSeconds How long the token is retained, also the cookie lifetime.
*/
constructor(
private provider: string,
private ttlSeconds: number = DEFAULT_TTL_SECONDS
) {}
/**
* Persists a logout token for the current session and references it from a
* scoped cookie. Best-effort — never throws.
*
* @param ctx The Koa context of the sign-in request.
* @param token The provider token to persist as a later logout hint.
*/
public async persist(ctx: AppContext, token: string): Promise<void> {
try {
const sessionId = crypto.randomBytes(16).toString("hex");
await Redis.defaultClient.set(
RedisPrefixHelper.getLogoutTokenKey(this.provider, sessionId),
token,
"EX",
this.ttlSeconds
);
ctx.cookies.set(
this.cookieName,
sessionId,
this.cookieOptions(ctx, addSeconds(new Date(), this.ttlSeconds))
);
} catch (err) {
Logger.warn("Failed to persist logout token", {
provider: this.provider,
error: toError(err).message,
});
}
}
/**
* Consumes the logout token for the current session and clears its cookie.
* Best-effort — never throws.
*
* @param ctx The Koa context of the logout request.
* @returns The persisted token, or null if absent or unavailable.
*/
public async consume(ctx: AppContext): Promise<string | null> {
const sessionId = ctx.cookies.get(this.cookieName);
let token: string | null = null;
if (sessionId) {
try {
token = await Redis.defaultClient.getdel(
RedisPrefixHelper.getLogoutTokenKey(this.provider, sessionId)
);
} catch (err) {
Logger.warn("Failed to read logout token", {
provider: this.provider,
error: toError(err).message,
});
}
}
// Always discard the session identifier, regardless of the result.
ctx.cookies.set(
this.cookieName,
"",
this.cookieOptions(ctx, subMinutes(new Date(), 1))
);
return token;
}
private get cookieName(): string {
return `${this.provider}Session`;
}
private get cookiePath(): string {
return `/auth/${this.provider}.logout`;
}
private cookieOptions(ctx: AppContext, expires: Date) {
return {
httpOnly: true,
sameSite: "lax" as const,
secure: ctx.request.secure,
path: this.cookiePath,
domain: getCookieDomain(ctx.request.hostname, env.isCloudHosted),
expires,
};
}
}