mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-12-03 09:38:54 +00:00
fix(sessions): renew a token from before tracking into one session
A token without a jti past half its life is renewed on every request its cookie authenticates, and each renewal minted a session with a random id. A first page load sends many requests at once, so one browser ended up with several active sessions; only the last cookie survived, and the rest showed up in GET /api/auth/sessions as separate devices until they expired, up to 30 days for remember me. The interceptor now hands the token to SessionsService.renew, which derives the session id from it (a SHA-256 of the token, laid out as a version 8 UUID so it passes the same id check) and inserts the row only if it is not there yet. Every renewal of the same token lands on the same session; if that session was ended in the meantime nothing is renewed, just as for a tracked token. A caller that passes no token gets the old behaviour.
This commit is contained in:
@@ -56,6 +56,25 @@ export class UserSessionsRepository extends TrekRepository<UserSessions> {
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* `INSERT INTO user_sessions (id, user_id, created_at, last_seen_at, expires_at, user_agent)
|
||||
* VALUES (?, ?, ?, ?, ?, ?) ON CONFLICT (id) DO NOTHING`: a row that is
|
||||
* already there, ended or not, is left exactly as it is.
|
||||
*/
|
||||
async insertSessionIfAbsent(row: NewUserSessionRow): Promise<void> {
|
||||
await this.upsertMany(
|
||||
[{
|
||||
id: row.id,
|
||||
user: row.user_id,
|
||||
created_at: row.created_at,
|
||||
last_seen_at: row.created_at,
|
||||
expires_at: row.expires_at,
|
||||
user_agent: row.user_agent,
|
||||
}],
|
||||
{ onConflictFields: ['id'], onConflictAction: 'ignore' },
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* The check behind every session token that carries an id:
|
||||
* `SELECT id, last_seen_at FROM user_sessions WHERE id = ? AND user_id = ?
|
||||
|
||||
@@ -20,7 +20,9 @@ import { setAuthCookie } from '../common/cookie';
|
||||
* 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. If the session ended in between, nothing is renewed.
|
||||
* 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
|
||||
@@ -58,7 +60,7 @@ export class SessionRenewalInterceptor implements NestInterceptor {
|
||||
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 },
|
||||
{ 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);
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { randomUUID } from 'crypto';
|
||||
import { createHash, randomUUID } from 'crypto';
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { InjectRepository } from '@mikro-orm/nestjs';
|
||||
import type { Request } from 'express';
|
||||
@@ -23,6 +23,24 @@ export interface RenewableSessionClaims {
|
||||
pv?: number;
|
||||
remember?: boolean;
|
||||
jti?: string;
|
||||
/**
|
||||
* The token itself. A token from before sessions were tracked has no `jti`,
|
||||
* and its session id is derived from it, so every renewal of that one token
|
||||
* lands on the same session.
|
||||
*/
|
||||
token?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* The session id a token from before sessions were tracked is renewed into:
|
||||
* a SHA-256 of the token, laid out as a version 8 UUID (RFC 9562), so it
|
||||
* passes the same id check a random one does. The same token always gives the
|
||||
* same id; any other token, which differs at least in its signature, another.
|
||||
*/
|
||||
export function legacySessionId(token: string): string {
|
||||
const h = createHash('sha256').update(token).digest('hex');
|
||||
const variant = ((parseInt(h.charAt(16), 16) & 0x3) | 0x8).toString(16);
|
||||
return `${h.slice(0, 8)}-${h.slice(8, 12)}-8${h.slice(13, 16)}-${variant}${h.slice(17, 20)}-${h.slice(20, 32)}`;
|
||||
}
|
||||
|
||||
/** The device description of a request: its User-Agent header, when it sent one. */
|
||||
@@ -84,14 +102,41 @@ export class SessionsService {
|
||||
* the old token keeps working until its own expiry whatever happens next.
|
||||
*/
|
||||
async renew(claims: RenewableSessionClaims, client: SessionClient = {}): Promise<string | null> {
|
||||
const user = { id: claims.id, pv: claims.pv ?? 0 };
|
||||
if (claims.jti === undefined) return this.issue(user, claims.remember, client);
|
||||
const token = this.sign(user, claims.remember, claims.jti);
|
||||
if (claims.jti === undefined) return this.renewUntracked(claims, client);
|
||||
const token = this.sign({ id: claims.id, pv: claims.pv ?? 0 }, claims.remember, claims.jti);
|
||||
const { exp } = this.lifetimeOf(token);
|
||||
const extended = await this.sessions.extendActive(claims.jti, claims.id, dbNow(), dbNow(new Date(exp * 1000)));
|
||||
return extended ? token : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* A token from before sessions were tracked, renewed into a tracked one.
|
||||
*
|
||||
* A page load sends many requests at once, and each of them past the token's
|
||||
* half life renews it. With a random id every one of them would add a
|
||||
* session, and the list would show one browser several times until they
|
||||
* expired. The id is derived from the token instead and the row inserted
|
||||
* only if it is not there yet, so all of them land on one session. If that
|
||||
* session was ended in the meantime, nothing is renewed.
|
||||
*
|
||||
* @txStandalone one statement, standing on its own like `renew`.
|
||||
*/
|
||||
private async renewUntracked(claims: RenewableSessionClaims, client: SessionClient): Promise<string | null> {
|
||||
const user = { id: claims.id, pv: claims.pv ?? 0 };
|
||||
if (claims.token === undefined) return this.issue(user, claims.remember, client);
|
||||
const jti = legacySessionId(claims.token);
|
||||
const token = this.sign(user, claims.remember, jti);
|
||||
const { iat, exp } = this.lifetimeOf(token);
|
||||
await this.sessions.insertSessionIfAbsent({
|
||||
id: jti,
|
||||
user_id: user.id,
|
||||
created_at: dbNow(new Date(iat * 1000)),
|
||||
expires_at: dbNow(new Date(exp * 1000)),
|
||||
user_agent: clipUserAgent(client.userAgent),
|
||||
});
|
||||
return (await this.sessions.findActive(jti, user.id, dbNow())) ? token : null;
|
||||
}
|
||||
|
||||
/** The user's active sessions, most recently used first, the one in `currentId` flagged. */
|
||||
async list(userId: number, currentId?: string): Promise<UserSession[]> {
|
||||
const rows = await this.sessions.listActiveForUser(userId, dbNow());
|
||||
|
||||
Reference in New Issue
Block a user