mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-11-29 08:00:06 +00:00
724c88c201
A mechanical prettier --write over server/src, server/tests, server/scripts and shared/src with the workspaces' .prettierrc; nothing but layout and import order changes, and every file keeps the same set of imports. shared is formatted throughout and its format baseline is empty. The server baseline keeps the 35 files that Prettier would grow past their lint:size limit (they need a split first, which is not a formatting change), and the generated entity files stay as their generator writes them.
70 lines
3.6 KiB
TypeScript
70 lines
3.6 KiB
TypeScript
import { decodeSessionClaims } from '../auth-core/jwt-verify';
|
|
import { setAuthCookie } from '../common/cookie';
|
|
import { SessionsService, sessionClientFrom } from '../sessions/sessions.service';
|
|
import { CallHandler, ExecutionContext, Injectable, NestInterceptor } from '@nestjs/common';
|
|
|
|
import type { Request, Response } from 'express';
|
|
import type { Observable } from 'rxjs';
|
|
|
|
/**
|
|
* Sliding session renewal (#1927): once a cookie-authenticated session token is
|
|
* past half of its lifetime, re-issue the trek_session cookie with a fresh
|
|
* token so an active user never hits the expiry cliff mid-use. Renewal
|
|
* preserves the login's remember semantics via the token's `remember` claim
|
|
* (true → long persistent cookie, false → browser-session cookie, absent → the
|
|
* historical default duration).
|
|
*
|
|
* Cheap by construction, one write per half-life at most:
|
|
* - `req.user` is only set after a guard ran verifyJwtAndLoadUser on this exact
|
|
* request, which already proved the token's `pv` matches the DB and its
|
|
* session is active, so the user id, pv and session id can be copied from
|
|
* the decoded (not re-verified) token.
|
|
* - A tracked token is re-signed under the same session id and the session's
|
|
* expiry moves with it; a token from before sessions were tracked comes back
|
|
* as a tracked session whose id is derived from that token, so the parallel
|
|
* requests of one page load renew it into one session, not several. If the
|
|
* session ended in between, nothing is renewed.
|
|
* - The cookie is only renewed when it is the verified credential: extractToken
|
|
* prefers the cookie over the Authorization header, so cookie-present +
|
|
* req.user set means the guard verified the cookie. Bearer-only callers
|
|
* (MCP, API clients) are never renewed.
|
|
*
|
|
* The cookie is written eagerly, before the handler runs: renewal doesn't
|
|
* depend on the handler's outcome, and this sidesteps @Res()/streaming routes
|
|
* whose headers are gone by the time the observable settles. When a handler
|
|
* later sets or clears trek_session itself (password change, logout), Express
|
|
* appends its Set-Cookie after this one and the browser keeps the last — the
|
|
* handler's cookie wins, which is the correct outcome.
|
|
*/
|
|
@Injectable()
|
|
export class SessionRenewalInterceptor implements NestInterceptor {
|
|
constructor(private readonly sessions: SessionsService) {}
|
|
|
|
async intercept(context: ExecutionContext, next: CallHandler): Promise<Observable<unknown>> {
|
|
if (context.getType() === 'http') {
|
|
const req = context.switchToHttp().getRequest<Request & { user?: { id: number } }>();
|
|
const res = context.switchToHttp().getResponse<Response>();
|
|
await this.maybeRenew(req, res);
|
|
}
|
|
return next.handle();
|
|
}
|
|
|
|
private async maybeRenew(req: Request & { user?: { id: number } }, res: Response): Promise<void> {
|
|
const cookieToken: string | undefined = (req as { cookies?: Record<string, string> }).cookies?.trek_session;
|
|
if (!req.user || !cookieToken || res.headersSent) return;
|
|
|
|
const claims = decodeSessionClaims(cookieToken);
|
|
if (!claims || claims.purpose || claims.id !== req.user.id) return;
|
|
if (typeof claims.iat !== 'number' || typeof claims.exp !== 'number' || claims.exp <= claims.iat) return;
|
|
|
|
const halfLife = claims.iat + (claims.exp - claims.iat) / 2;
|
|
if (Date.now() / 1000 < halfLife) return;
|
|
|
|
const token = await this.sessions.renew(
|
|
{ id: req.user.id, pv: claims.pv, remember: claims.remember, jti: claims.jti, token: cookieToken },
|
|
sessionClientFrom(req),
|
|
);
|
|
if (token) setAuthCookie(res, token, req, claims.remember);
|
|
}
|
|
}
|