mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-12-04 18:04:18 +00:00
refactor(server): make the state ports async and route every reader through the provided store
The process-state ports were meant to let a store shared between processes replace the in-memory one, but they could not. The readers outside the container (the broadcast functions, the backup restore's permissions-cache flush, the pending-code sweep, hand-built consumers) went straight to the module-level in-memory instances, so an overridden provider was used by the gateway and the services while the broadcasts and the restore flush kept using the old store. And every port was synchronous, while a store in the database or on the network is async, so plugging one in would have changed every signature anyway. RateLimitStore, PendingCodeStore, OidcFlowStore and PermissionsCacheStore now return promises, and RateLimitService, OauthService, OidcService, PermissionsService and their callers await them. The in-memory stores still decide synchronously, so who gets a 429, a code or a cached level is unchanged. RoomRegistry stays synchronous: membership holds live sockets and broadcast() is a synchronous call every domain makes, so several processes need a fan-out in front of broadcast(), not a different place for the sets. The process-wide ports get a ProcessStoreSlot. PermissionsModule, OauthModule and RealtimeGatewayModule install the store the container resolved and release it on shutdown, and the free functions, the sweep and hand-built consumers read the slot, so overriding the provider changes every reader. Tests provide fake stores and check that the broadcasts, the restore flush and the sweep use them. Two callers needed more than an await. The transit MCP tools counted in a RateLimitService of their own that no provider could reach; they now take the one RateLimitModule provides (their mcp_transit_* buckets never overlap the REST ones). The link preview claimed its in-flight slot only after the budget check, which now yields, so simultaneous askers would each have been charged; it now claims the slot first, and an asker that joined someone out of budget asks again on its own budget. The unused putPendingCode/takePendingCode helpers are gone.
This commit is contained in:
@@ -29,19 +29,20 @@ export interface OidcAuthCode {
|
||||
* In memory today, which ties a login to the process that started it; with
|
||||
* several processes behind one address the callback can land on another one.
|
||||
* A store shared between processes replaces InMemoryOidcFlowStore in
|
||||
* OidcModule without touching OidcService.
|
||||
* OidcModule without touching OidcService. Every method returns a promise,
|
||||
* because such a store lives in the database or on the network.
|
||||
*/
|
||||
export abstract class OidcFlowStore {
|
||||
abstract putState(state: string, entry: OidcPendingState): void;
|
||||
abstract putState(state: string, entry: OidcPendingState): Promise<void>;
|
||||
/** The entry, removed in the same step; null when unknown. */
|
||||
abstract takeState(state: string): OidcPendingState | null;
|
||||
abstract putCode(code: string, entry: OidcAuthCode): void;
|
||||
abstract takeState(state: string): Promise<OidcPendingState | null>;
|
||||
abstract putCode(code: string, entry: OidcAuthCode): Promise<void>;
|
||||
/** The entry, removed in the same step, expired or not (the caller decides); null when unknown. */
|
||||
abstract takeCode(code: string): OidcAuthCode | null;
|
||||
abstract takeCode(code: string): Promise<OidcAuthCode | null>;
|
||||
/** Drop states created more than `ttlMs` before `now`. */
|
||||
abstract sweepStates(now: number, ttlMs: number): void;
|
||||
abstract sweepStates(now: number, ttlMs: number): Promise<void>;
|
||||
/** Drop codes created more than `ttlMs` before `now`. */
|
||||
abstract sweepCodes(now: number, ttlMs: number): void;
|
||||
abstract sweepCodes(now: number, ttlMs: number): Promise<void>;
|
||||
}
|
||||
|
||||
/** The current behaviour: two maps in this process's memory. */
|
||||
@@ -49,37 +50,41 @@ export class InMemoryOidcFlowStore extends OidcFlowStore {
|
||||
private readonly states = new Map<string, OidcPendingState>();
|
||||
private readonly codes = new Map<string, OidcAuthCode>();
|
||||
|
||||
putState(state: string, entry: OidcPendingState): void {
|
||||
putState(state: string, entry: OidcPendingState): Promise<void> {
|
||||
this.states.set(state, entry);
|
||||
return Promise.resolve();
|
||||
}
|
||||
|
||||
takeState(state: string): OidcPendingState | null {
|
||||
takeState(state: string): Promise<OidcPendingState | null> {
|
||||
const entry = this.states.get(state);
|
||||
if (!entry) return null;
|
||||
if (!entry) return Promise.resolve(null);
|
||||
this.states.delete(state);
|
||||
return entry;
|
||||
return Promise.resolve(entry);
|
||||
}
|
||||
|
||||
putCode(code: string, entry: OidcAuthCode): void {
|
||||
putCode(code: string, entry: OidcAuthCode): Promise<void> {
|
||||
this.codes.set(code, entry);
|
||||
return Promise.resolve();
|
||||
}
|
||||
|
||||
takeCode(code: string): OidcAuthCode | null {
|
||||
takeCode(code: string): Promise<OidcAuthCode | null> {
|
||||
const entry = this.codes.get(code);
|
||||
if (!entry) return null;
|
||||
if (!entry) return Promise.resolve(null);
|
||||
this.codes.delete(code);
|
||||
return entry;
|
||||
return Promise.resolve(entry);
|
||||
}
|
||||
|
||||
sweepStates(now: number, ttlMs: number): void {
|
||||
sweepStates(now: number, ttlMs: number): Promise<void> {
|
||||
for (const [state, entry] of this.states) {
|
||||
if (now - entry.createdAt > ttlMs) this.states.delete(state);
|
||||
}
|
||||
return Promise.resolve();
|
||||
}
|
||||
|
||||
sweepCodes(now: number, ttlMs: number): void {
|
||||
sweepCodes(now: number, ttlMs: number): Promise<void> {
|
||||
for (const [code, entry] of this.codes) {
|
||||
if (now - entry.created > ttlMs) this.codes.delete(code);
|
||||
}
|
||||
return Promise.resolve();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -69,7 +69,7 @@ export class OidcController {
|
||||
const query = oidcLoginQuerySchema.safeParse(req.query);
|
||||
const inviteToken = query.success ? query.data.invite : (req.query.invite as string | undefined);
|
||||
const remember = query.success && query.data.remember !== undefined ? query.data.remember === '1' : undefined;
|
||||
const { state, codeChallenge } = this.oidc.createState(redirectUri, inviteToken, remember);
|
||||
const { state, codeChallenge } = await this.oidc.createState(redirectUri, inviteToken, remember);
|
||||
// Bind the state to THIS browser. The callback requires a matching cookie,
|
||||
// so an attacker-initiated login (whose callback URL carries a valid state
|
||||
// from the shared server map) cannot be replayed in a victim's browser to
|
||||
@@ -117,7 +117,7 @@ export class OidcController {
|
||||
// Require the callback to come from the browser that started the flow.
|
||||
if (!boundState || boundState !== state) return f('/login?oidc_error=invalid_state');
|
||||
|
||||
const pending = this.oidc.consumeState(state);
|
||||
const pending = await this.oidc.consumeState(state);
|
||||
if (!pending) return f('/login?oidc_error=invalid_state');
|
||||
|
||||
const config = await this.oidc.getOidcConfig();
|
||||
@@ -203,7 +203,7 @@ export class OidcController {
|
||||
// "absent", not `false`, or the sliding renewal would later downgrade the
|
||||
// default persistent cookie to a browser-session one (remember-me, #1927).
|
||||
const jwtToken = await this.oidc.generateToken(result.user, pending.remember);
|
||||
const { code: authCode, binding } = this.oidc.createAuthCode(jwtToken, pending.remember);
|
||||
const { code: authCode, binding } = await this.oidc.createAuthCode(jwtToken, pending.remember);
|
||||
// Bind the code to THIS browser, the way the state cookie binds the callback.
|
||||
// The code rides home in a URL, so it is readable from history, from a
|
||||
// referrer and from anything that logs URLs; without a second half nobody
|
||||
@@ -219,7 +219,7 @@ export class OidcController {
|
||||
}
|
||||
|
||||
@Get('exchange')
|
||||
exchange(@Query('code') code: string | undefined, @Req() req: Request, @Res() res: Response): void {
|
||||
async exchange(@Query('code') code: string | undefined, @Req() req: Request, @Res() res: Response): Promise<void> {
|
||||
// The binding cookie is single-use like the state cookie: one redemption
|
||||
// attempt per callback, whatever its outcome.
|
||||
const binding = (req.cookies as Record<string, string> | undefined)?.[OIDC_EXCHANGE_COOKIE];
|
||||
@@ -229,7 +229,7 @@ export class OidcController {
|
||||
res.status(400).json({ error: 'Code required' });
|
||||
return;
|
||||
}
|
||||
const result = this.oidc.consumeAuthCode(code, binding);
|
||||
const result = await this.oidc.consumeAuthCode(code, binding);
|
||||
if ('error' in result) {
|
||||
res.status(400).json({ error: result.error });
|
||||
return;
|
||||
|
||||
@@ -14,6 +14,7 @@ import { TripMembershipService } from '../trip-membership/trip-membership.servic
|
||||
import { setAuthCookie, RememberOption } from '../common/cookie';
|
||||
import { AuthService } from '../auth/auth.service';
|
||||
import { UnitOfWork } from '../database/unit-of-work';
|
||||
import { logError } from '../audit/audit-log.logger';
|
||||
import { safeFetchAdminConfigured } from '../../utils/ssrfGuard';
|
||||
import { Users } from '../../db/entities/Users.entity';
|
||||
import type { UsersRepository, UserRow } from '../../db/repositories/Users.repository';
|
||||
@@ -21,7 +22,7 @@ import { InviteTokens } from '../../db/entities/InviteTokens.entity';
|
||||
import type { InviteTokensRepository, InviteTokenRow } from '../../db/repositories/InviteTokens.repository';
|
||||
import { AppSettings } from '../../db/entities/AppSettings.entity';
|
||||
import type { AppSettingsRepository } from '../../db/repositories/AppSettings.repository';
|
||||
import { InMemoryOidcFlowStore, OidcFlowStore } from './oidc-flow.store';
|
||||
import { InMemoryOidcFlowStore, OidcFlowStore, type OidcPendingState } from './oidc-flow.store';
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Types
|
||||
@@ -247,8 +248,14 @@ export class OidcService implements OnModuleDestroy {
|
||||
@InjectRepository(AppSettings) private readonly appSettings: AppSettingsRepository,
|
||||
private readonly flows: OidcFlowStore = new InMemoryOidcFlowStore(),
|
||||
) {
|
||||
this.stateSweeper = setInterval(() => this.flows.sweepStates(Date.now(), STATE_TTL), STATE_CLEANUP);
|
||||
this.codeSweeper = setInterval(() => this.flows.sweepCodes(Date.now(), AUTH_CODE_TTL), AUTH_CODE_CLEANUP);
|
||||
const sweepFailed = (err: unknown) =>
|
||||
logError(`OIDC flow sweep failed: ${err instanceof Error ? err.message : String(err)}`);
|
||||
this.stateSweeper = setInterval(() => {
|
||||
this.flows.sweepStates(Date.now(), STATE_TTL).catch(sweepFailed);
|
||||
}, STATE_CLEANUP);
|
||||
this.codeSweeper = setInterval(() => {
|
||||
this.flows.sweepCodes(Date.now(), AUTH_CODE_TTL).catch(sweepFailed);
|
||||
}, AUTH_CODE_CLEANUP);
|
||||
}
|
||||
|
||||
onModuleDestroy(): void {
|
||||
@@ -265,15 +272,19 @@ export class OidcService implements OnModuleDestroy {
|
||||
// Creates the login state and a matching PKCE pair. The verifier stays server
|
||||
// side (in the flow store); the S256 challenge goes to the provider so PKCE-
|
||||
// required setups (e.g. Pocket ID with PKCE = required) work.
|
||||
createState(redirectUri: string, inviteToken?: string, remember?: boolean): { state: string; codeChallenge: string } {
|
||||
async createState(
|
||||
redirectUri: string,
|
||||
inviteToken?: string,
|
||||
remember?: boolean,
|
||||
): Promise<{ state: string; codeChallenge: string }> {
|
||||
const state = crypto.randomBytes(32).toString('hex');
|
||||
const codeVerifier = base64url(crypto.randomBytes(32));
|
||||
const codeChallenge = base64url(crypto.createHash('sha256').update(codeVerifier).digest());
|
||||
this.flows.putState(state, { createdAt: Date.now(), redirectUri, inviteToken, codeVerifier, remember });
|
||||
await this.flows.putState(state, { createdAt: Date.now(), redirectUri, inviteToken, codeVerifier, remember });
|
||||
return { state, codeChallenge };
|
||||
}
|
||||
|
||||
consumeState(state: string) {
|
||||
consumeState(state: string): Promise<OidcPendingState | null> {
|
||||
return this.flows.takeState(state);
|
||||
}
|
||||
|
||||
@@ -284,18 +295,21 @@ export class OidcService implements OnModuleDestroy {
|
||||
* cookie, so redeeming the code takes both halves and only the browser that
|
||||
* completed the provider handshake has both.
|
||||
*/
|
||||
createAuthCode(token: string, remember?: boolean): { code: string; binding: string } {
|
||||
async createAuthCode(token: string, remember?: boolean): Promise<{ code: string; binding: string }> {
|
||||
const authCode: string = uuidv4();
|
||||
const binding = crypto.randomBytes(32).toString('base64url');
|
||||
this.flows.putCode(authCode, { token, created: Date.now(), remember, bindingHash: sha256Hex(binding) });
|
||||
await this.flows.putCode(authCode, { token, created: Date.now(), remember, bindingHash: sha256Hex(binding) });
|
||||
return { code: authCode, binding };
|
||||
}
|
||||
|
||||
consumeAuthCode(code: string, binding?: string): { token: string; remember?: boolean } | { error: string } {
|
||||
async consumeAuthCode(
|
||||
code: string,
|
||||
binding?: string,
|
||||
): Promise<{ token: string; remember?: boolean } | { error: string }> {
|
||||
// Single use, burnt on every outcome: a code seen by someone else must not
|
||||
// survive their attempt for a second guess, and the browser that owns it can
|
||||
// simply log in again.
|
||||
const entry = this.flows.takeCode(code);
|
||||
const entry = await this.flows.takeCode(code);
|
||||
if (!entry) return { error: 'Invalid or expired code' };
|
||||
if (Date.now() - entry.created > AUTH_CODE_TTL) return { error: 'Code expired' };
|
||||
// Same wording as the unknown-code case on purpose — whoever presents a code
|
||||
|
||||
Reference in New Issue
Block a user