fix(auth): a native app hand-off code redeems only while the session that minted it stands

The browser side of the native sign-in mints a one-time code from its
cookie session, and the app redeems it within a minute for a session of
its own. The code was bound to the account alone, so one minted before a
password reset, a sign-out or a revoked session still redeemed afterwards
into a fresh session, carrying access across the point where the account
took it back.

The code now carries the session it came from: its password version and,
for a tracked session, its id. Redeeming it mints a session only while the
password is unchanged and that session is still active, checked in the
same transaction that mints the new one.
This commit is contained in:
Maurice
2026-11-26 22:14:12 +01:00
parent 10d95a39ac
commit c88d3abc5e
7 changed files with 163 additions and 29 deletions
+28 -7
View File
@@ -1,11 +1,23 @@
import { Users } from '../../db/entities/Users.entity';
import type { UsersRepository } from '../../db/repositories/Users.repository';
import { dbNow } from '../../db/types/db-timestamp.type';
import { UnitOfWork } from '../database/unit-of-work';
import type { SessionClient } from '../sessions/sessions.service';
import { SessionsService, type SessionClient } from '../sessions/sessions.service';
import { AuthService } from './auth.service';
import { InjectRepository } from '@mikro-orm/nestjs';
import { Injectable } from '@nestjs/common';
/**
* The signed-in session a new one is carried on from: its account, the
* password version it was issued under, and its id (null on a token from
* before sessions were tracked).
*/
export interface SessionOrigin {
userId: number;
passwordVersion: number;
sessionId: string | null;
}
/**
* Signs in an account whose identity another way in has already proven: the
* login is recorded on the account and the session minted in one transaction.
@@ -18,16 +30,25 @@ export class LoginSessionService {
constructor(
private readonly auth: AuthService,
private readonly uow: UnitOfWork,
private readonly sessions: SessionsService,
@InjectRepository(Users) private readonly users: UsersRepository,
) {}
/** The session token, or null when the account no longer exists. */
async signIn(userId: number, remember: boolean | undefined, client?: SessionClient): Promise<string | null> {
/**
* The session token, or null when the session it is carried on from no
* longer stands: the account is gone, the password changed since, or that
* session ended (a sign-out, a revocation, a password reset). A credential
* the account took back cannot mint a new one this way.
*/
async signIn(origin: SessionOrigin, remember: boolean | undefined, client?: SessionClient): Promise<string | null> {
return this.uow.transactional(async () => {
const passwordVersion = await this.users.getPasswordVersion(userId);
if (passwordVersion === null) return null;
await this.users.touchLastLogin(userId);
return this.auth.generateToken({ id: userId, password_version: passwordVersion }, remember, client);
const passwordVersion = await this.users.getPasswordVersion(origin.userId);
if (passwordVersion === null || passwordVersion !== origin.passwordVersion) return null;
if (origin.sessionId !== null && !(await this.sessions.findActive(origin.sessionId, origin.userId, dbNow()))) {
return null;
}
await this.users.touchLastLogin(origin.userId);
return this.auth.generateToken({ id: origin.userId, password_version: passwordVersion }, remember, client);
});
}
}
@@ -3,6 +3,7 @@ import { AuditService } from '../audit/audit.service';
import { getClientIp } from '../audit/client-ip';
import { CookieAuthGuard } from '../auth-core/cookie-auth.guard';
import { CurrentUser } from '../auth-core/current-user.decorator';
import { verifiedSessionClaims } from '../auth-core/jwt-verify';
import { Public } from '../auth-core/public.decorator';
import { setAuthCookie } from '../common/cookie';
import { RateLimitService } from '../common/rate-limit.service';
@@ -67,14 +68,25 @@ export class NativeAuthController {
/**
* Cookie only: an API or MCP bearer token must not be able to mint itself a
* full browser session this way.
* full browser session this way. The code is bound to the cookie's session,
* which the guard has just verified, so it redeems only while that stands.
*/
@Post('handoff')
@UseGuards(CookieAuthGuard)
@HttpCode(200)
@ResponseContract(nativeHandoffResponseSchema)
async handoff(@Body() body: NativeHandoffDto, @CurrentUser() user: User): Promise<NativeHandoffResponse> {
return { code: await this.nativeAuth.issueCode(user.id, body.challenge) };
async handoff(
@Body() body: NativeHandoffDto,
@CurrentUser() user: User,
@Req() req: Request,
): Promise<NativeHandoffResponse> {
const claims = verifiedSessionClaims((req.cookies as Record<string, string> | undefined)?.trek_session);
const origin = {
userId: user.id,
passwordVersion: claims?.pv ?? 0,
sessionId: typeof claims?.jti === 'string' ? claims.jti : null,
};
return { code: await this.nativeAuth.issueCode(origin, body.challenge) };
}
/**
@@ -1,4 +1,4 @@
import { LoginSessionService } from '../auth/login-session.service';
import { LoginSessionService, type SessionOrigin } from '../auth/login-session.service';
import { DomainError } from '../common/domain-error';
import type { SessionClient } from '../sessions/sessions.service';
import { NATIVE_HANDOFF_CODE_TTL_MS, NativeHandoffStore } from './native-handoff.store';
@@ -30,10 +30,10 @@ export class NativeAuthService {
private readonly handoffs: NativeHandoffStore,
) {}
async issueCode(userId: number, challenge: string): Promise<string> {
async issueCode(origin: SessionOrigin, challenge: string): Promise<string> {
const code = randomBytes(32).toString('base64url');
const stored = await this.handoffs.put(code, {
userId,
origin,
challenge,
expiresAt: Date.now() + NATIVE_HANDOFF_CODE_TTL_MS,
});
@@ -45,13 +45,15 @@ export class NativeAuthService {
* Burns the code on every attempt, right or wrong, so a code that leaked
* through the URL scheme gets exactly one guess. The session is always the
* long one: an app that forgets its login whenever the system unloads it
* would be useless on the road.
* would be useless on the road. It is carried on from the browser session
* that handed it off, so a code minted before that session ended (a
* password reset above all) mints nothing afterwards.
*/
async redeem(code: string, verifier: string, client: SessionClient): Promise<{ token: string; userId: number }> {
const entry = await this.handoffs.take(code);
if (!entry || !verifierMatches(entry.challenge, verifier)) throw new DomainError(400, INVALID_CODE);
const token = await this.logins.signIn(entry.userId, true, client);
const token = await this.logins.signIn(entry.origin, true, client);
if (!token) throw new DomainError(400, INVALID_CODE);
return { token, userId: entry.userId };
return { token, userId: entry.origin.userId };
}
}
@@ -1,6 +1,9 @@
import type { SessionOrigin } from '../auth/login-session.service';
/** A sign-in the system browser handed off and the app has not redeemed yet. */
export interface NativeHandoff {
userId: number;
/** The browser session that handed it off; the app's session stands only while that one does. */
origin: SessionOrigin;
/** Hex sha256 of the verifier the app kept to itself. */
challenge: string;
expiresAt: number;
+78
View File
@@ -143,3 +143,81 @@ describe('Native sign-in hand-off e2e', () => {
expect((await request(server).get('/api/auth/native/start?challenge=nope')).status).toBe(400);
});
});
describe('a hand-off code outlives no end of the session that minted it', () => {
const sessionFrom = (response: request.Response): string =>
(response.headers['set-cookie'] as unknown as string[] | undefined)
?.find((c) => c.startsWith('trek_session='))
?.split(';')[0] ?? '';
/** A tracked browser session of a fresh account, as a sign-in leaves one. */
async function signedIn(name: string): Promise<{ email: string; cookie: string }> {
const email = `${name}@example.test`;
const { user } = await makeUser(orm, { username: name, email });
const minted = await handoff(sessionCookie(user.id));
const cookie = sessionFrom(await exchange({ code: minted.body.code, verifier }));
expect(cookie).not.toBe('');
return { email, cookie };
}
async function resetPassword(email: string): Promise<void> {
const mailer = app.get(MailerService) as unknown as { sendPasswordResetEmail: ReturnType<typeof vi.fn> };
mailer.sendPasswordResetEmail.mockClear();
mailer.sendPasswordResetEmail.mockResolvedValue({ delivered: 'test' });
expect((await request(server).post('/api/auth/forgot-password').send({ email })).status).toBe(200);
const url = String(mailer.sendPasswordResetEmail.mock.calls.at(-1)?.[1]);
const token = new URL(url).searchParams.get('token');
const reset = await request(server)
.post('/api/auth/reset-password')
.send({ token, new_password: 'Native-Reset-Check!2026' });
expect(reset.status).toBe(200);
}
async function refused(code: string): Promise<void> {
const late = await exchange({ code, verifier });
expect(late.status).toBe(400);
expect(late.body).toEqual({ error: 'Invalid or expired code' });
expect(late.headers['set-cookie']).toBeUndefined();
}
it('NATIVE-E2E-007: a code minted before a password reset mints no session after it', async () => {
const account = await signedIn('native-reset-tracked');
const minted = await handoff(account.cookie);
expect(minted.status).toBe(200);
await resetPassword(account.email);
await refused(minted.body.code);
});
it('NATIVE-E2E-008: a code minted from a session from before tracking is refused after a reset too', async () => {
const email = 'native-reset-untracked@example.test';
const { user } = await makeUser(orm, { username: 'native-reset-untracked', email });
const minted = await handoff(sessionCookie(user.id));
expect(minted.status).toBe(200);
await resetPassword(email);
await refused(minted.body.code);
});
it('NATIVE-E2E-009: a code minted before its session signed out mints no session after it', async () => {
const account = await signedIn('native-logout');
const minted = await handoff(account.cookie);
expect((await request(server).post('/api/auth/logout').set('Cookie', account.cookie)).status).toBe(200);
await refused(minted.body.code);
});
it('NATIVE-E2E-010: a code redeemed before the reset gives a session the reset then ends', async () => {
const account = await signedIn('native-reset-before');
const minted = await handoff(account.cookie);
const appSession = sessionFrom(await exchange({ code: minted.body.code, verifier }));
expect((await request(server).get('/api/auth/me').set('Cookie', appSession)).status).toBe(200);
await resetPassword(account.email);
expect((await request(server).get('/api/auth/me').set('Cookie', appSession)).status).toBe(401);
});
});
@@ -4,6 +4,7 @@
* service; the exchange route is rate-limited per ip before the code is
* touched, sets the remembered session cookie and writes the login row.
*/
import { JWT_SECRET } from '../../../src/config';
import type { AuditService } from '../../../src/nest/audit/audit.service';
import { DomainError } from '../../../src/nest/common/domain-error';
import type { RateLimitService } from '../../../src/nest/common/rate-limit.service';
@@ -14,6 +15,7 @@ import type { User } from '../../../src/types';
import { nativeHandoffResponseSchema, successResponseSchema } from '@trek/shared';
import type { Request, Response } from 'express';
import jwt from 'jsonwebtoken';
import { beforeEach, describe, expect, it, vi } from 'vitest';
const challenge = 'a'.repeat(64);
@@ -43,11 +45,25 @@ function makeRes() {
beforeEach(() => vi.clearAllMocks());
describe('NativeAuthController.handoff', () => {
it('NATIVE-CTL-001: issues a code for the signed-in user and the given challenge', async () => {
it('NATIVE-CTL-001: issues a code bound to the cookie session it was asked from', async () => {
const { controller, nativeAuth } = build();
const tracked = jwt.sign({ id: 7, pv: 3, jti: 'sess-1' }, JWT_SECRET, { algorithm: 'HS256' });
const asked = { ...req, cookies: { trek_session: tracked } } as unknown as Request;
expect(await controller.handoff({ challenge }, { id: 7 } as User)).toEqual({ code: 'code-1' });
expect(nativeAuth.issueCode).toHaveBeenCalledWith(7, challenge);
expect(await controller.handoff({ challenge }, { id: 7 } as User, asked)).toEqual({ code: 'code-1' });
expect(nativeAuth.issueCode).toHaveBeenCalledWith(
{ userId: 7, passwordVersion: 3, sessionId: 'sess-1' },
challenge,
);
});
it('NATIVE-CTL-001b: a session from before tracking binds the code to its password version alone', async () => {
const { controller, nativeAuth } = build();
const untracked = jwt.sign({ id: 7 }, JWT_SECRET, { algorithm: 'HS256' });
const asked = { ...req, cookies: { trek_session: untracked } } as unknown as Request;
await controller.handoff({ challenge }, { id: 7 } as User, asked);
expect(nativeAuth.issueCode).toHaveBeenCalledWith({ userId: 7, passwordVersion: 0, sessionId: null }, challenge);
});
});
@@ -29,6 +29,8 @@ import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from 'vitest
const verifier = 'v'.repeat(43);
const challenge = createHash('sha256').update(verifier).digest('hex');
const client = { userAgent: 'TREK iOS' };
/** A browser session from before sessions were tracked, on a password never changed. */
const origin = (userId: number) => ({ userId, passwordVersion: 0, sessionId: null });
const db = createSnapshotTestDb();
let t: TestModule;
@@ -60,7 +62,7 @@ describe('NativeAuthService', () => {
it('NATIVE-SVC-001: redeems a code with the matching verifier into a remembered, tracked session', async () => {
const { user } = await makeUser(orm());
const before = await readUser(orm(), user.id);
const code = await service.issueCode(user.id, challenge);
const code = await service.issueCode(origin(user.id), challenge);
const session = await service.redeem(code, verifier, client);
@@ -78,7 +80,7 @@ describe('NativeAuthService', () => {
it('NATIVE-SVC-002: a wrong verifier is refused and burns the code with it', async () => {
const { user } = await makeUser(orm());
const code = await service.issueCode(user.id, challenge);
const code = await service.issueCode(origin(user.id), challenge);
await expect(service.redeem(code, 'w'.repeat(43), client)).rejects.toEqual(refused);
await expect(service.redeem(code, verifier, client)).rejects.toEqual(refused);
@@ -86,7 +88,7 @@ describe('NativeAuthService', () => {
it('NATIVE-SVC-003: a code is single use', async () => {
const { user } = await makeUser(orm());
const code = await service.issueCode(user.id, challenge);
const code = await service.issueCode(origin(user.id), challenge);
await service.redeem(code, verifier, client);
await expect(service.redeem(code, verifier, client)).rejects.toEqual(refused);
@@ -99,7 +101,7 @@ describe('NativeAuthService', () => {
it('NATIVE-SVC-005: a code older than its ttl is refused', async () => {
const { user } = await makeUser(orm());
vi.useFakeTimers({ toFake: ['Date'] });
const code = await service.issueCode(user.id, challenge);
const code = await service.issueCode(origin(user.id), challenge);
vi.setSystemTime(Date.now() + NATIVE_HANDOFF_CODE_TTL_MS + 1);
await expect(service.redeem(code, verifier, client)).rejects.toEqual(refused);
@@ -107,7 +109,7 @@ describe('NativeAuthService', () => {
it('NATIVE-SVC-006: a code whose account is gone mints no session', async () => {
const sessions = await countRows(orm(), UserSessions);
const code = await service.issueCode(987654, challenge);
const code = await service.issueCode(origin(987654), challenge);
await expect(service.redeem(code, verifier, client)).rejects.toEqual(refused);
expect(await countRows(orm(), UserSessions)).toBe(sessions);
@@ -116,16 +118,16 @@ describe('NativeAuthService', () => {
it('NATIVE-SVC-007: a full store refuses to mint another code', async () => {
vi.spyOn(t.get(NativeHandoffStore), 'put').mockResolvedValueOnce(false);
await expect(service.issueCode(1, challenge)).rejects.toEqual(expect.objectContaining({ status: 503 }));
await expect(service.issueCode(origin(1), challenge)).rejects.toEqual(expect.objectContaining({ status: 503 }));
});
it('NATIVE-SVC-008: LoginSessionService answers null for an account that does not exist', async () => {
expect(await t.get(LoginSessionService).signIn(987654, true, client)).toBeNull();
expect(await t.get(LoginSessionService).signIn(origin(987654), true, client)).toBeNull();
});
});
describe('InMemoryNativeHandoffStore', () => {
const entry = (expiresAt: number): NativeHandoff => ({ userId: 1, challenge, expiresAt });
const entry = (expiresAt: number): NativeHandoff => ({ origin: origin(1), challenge, expiresAt });
it('NATIVE-STORE-001: holds at most its cap of live codes', async () => {
const store = new InMemoryNativeHandoffStore();
@@ -144,7 +146,7 @@ describe('InMemoryNativeHandoffStore', () => {
expect(await store.put('fresh', entry(Date.now() + 60_000))).toBe(true);
expect(await store.take('c0')).toBeNull();
expect(await store.take('fresh')).toEqual(expect.objectContaining({ userId: 1 }));
expect(await store.take('fresh')).toEqual(expect.objectContaining({ origin: origin(1) }));
});
it('NATIVE-STORE-003: take removes the entry, expired or not', async () => {