diff --git a/apps/api-e2e/src/api/auth.e2e.spec.ts b/apps/api-e2e/src/api/auth.e2e.spec.ts index 9158475..29fee26 100644 --- a/apps/api-e2e/src/api/auth.e2e.spec.ts +++ b/apps/api-e2e/src/api/auth.e2e.spec.ts @@ -1,4 +1,9 @@ -import { createTestApp, login, seedEmployee, type TestContext } from '../support/test-app'; +import { + createTestApp, + login, + seedEmployee, + type TestContext, +} from '../support/test-app'; describe('Auth — POST /api/auth/login', () => { let ctx: TestContext; @@ -33,6 +38,7 @@ describe('Auth — POST /api/auth/login', () => { firstName: 'Hannah', role: 'HRAdmin', }); + expect(await ctx.prisma.loginAttemptState.count()).toBe(0); }); it('rejects wrong password with 401', async () => { @@ -63,7 +69,10 @@ describe('Auth — POST /api/auth/login', () => { lastName: 'Roth', email: 'hannah@test.local', }); - await ctx.prisma.employee.update({ where: { id: e.id }, data: { isActive: false } }); + await ctx.prisma.employee.update({ + where: { id: e.id }, + data: { isActive: false }, + }); await ctx.http .post('/api/auth/login') @@ -71,6 +80,74 @@ describe('Auth — POST /api/auth/login', () => { .expect(401); }); + it('uses the same generic denial for unknown, inactive, wrong-password, and non-owner Solo accounts', async () => { + const owner = await seedEmployee(ctx.prisma, { + personalNo: 'OWNER', + firstName: 'Solo', + lastName: 'Owner', + email: 'owner@test.local', + }); + const inactive = await seedEmployee(ctx.prisma, { + personalNo: 'INACTIVE', + firstName: 'Inactive', + lastName: 'Employee', + email: 'inactive@test.local', + }); + await ctx.prisma.employee.update({ + where: { id: inactive.id }, + data: { isActive: false }, + }); + await seedEmployee(ctx.prisma, { + personalNo: 'OUTSIDER', + firstName: 'Team', + lastName: 'Outsider', + email: 'outsider@test.local', + }); + await ctx.prisma.installationSettings.create({ + data: { mode: 'Solo', ownerEmployeeId: owner.id }, + }); + + const attempts = [ + { email: owner.email, password: 'wrong-password' }, + { email: 'unknown@test.local', password: 'test1234' }, + { email: inactive.email, password: 'test1234' }, + { email: 'outsider@test.local', password: 'test1234' }, + ]; + let genericDenial: unknown; + for (const credentials of attempts) { + const response = await ctx.http + .post('/api/auth/login') + .send(credentials) + .expect(401); + genericDenial ??= response.body; + expect(response.body).toEqual(genericDenial); + expect(response.body.message).toBe('Invalid credentials'); + } + }); + + it('atomically rate-limits parallel attempts with Retry-After responses', async () => { + await seedEmployee(ctx.prisma, { + personalNo: '0001', + firstName: 'Hannah', + lastName: 'Roth', + email: 'hannah@test.local', + }); + + const responses = await Promise.all( + Array.from({ length: 10 }, () => + ctx.http + .post('/api/auth/login') + .send({ email: 'hannah@test.local', password: 'wrong-password' }), + ), + ); + expect(responses.filter(({ status }) => status === 401)).toHaveLength(5); + expect(responses.filter(({ status }) => status === 429)).toHaveLength(5); + const limited = responses.find(({ status }) => status === 429); + + expect(limited?.body.code).toBe('AUTH_LOGIN_RATE_LIMITED'); + expect(Number(limited?.headers['retry-after'])).toBeGreaterThan(0); + }); + it('GET /api/auth/me echoes the token subject', async () => { await seedEmployee(ctx.prisma, { personalNo: '0001', diff --git a/apps/api-e2e/src/api/refresh.e2e.spec.ts b/apps/api-e2e/src/api/refresh.e2e.spec.ts index 459d639..b2b9728 100644 --- a/apps/api-e2e/src/api/refresh.e2e.spec.ts +++ b/apps/api-e2e/src/api/refresh.e2e.spec.ts @@ -1,4 +1,8 @@ -import { createTestApp, seedEmployee, type TestContext } from '../support/test-app'; +import { + createTestApp, + seedEmployee, + type TestContext, +} from '../support/test-app'; describe('Auth — refresh tokens', () => { let ctx: TestContext; @@ -58,6 +62,66 @@ describe('Auth — refresh tokens', () => { .expect(200); }); + it('detects refresh-token replay and revokes the whole session family', async () => { + await seedEmployee(ctx.prisma, { + personalNo: '0001', + firstName: 'Hannah', + lastName: 'Roth', + email: 'hannah@test.local', + }); + const login = await ctx.http + .post('/api/auth/login') + .send({ email: 'hannah@test.local', password: 'test1234' }) + .expect(200); + const rotated = await ctx.http + .post('/api/auth/refresh') + .send({ refreshToken: login.body.refreshToken }) + .expect(200); + + // Reusing the consumed token is treated as family compromise. + await ctx.http + .post('/api/auth/refresh') + .send({ refreshToken: login.body.refreshToken }) + .expect(401); + await ctx.http + .post('/api/auth/refresh') + .send({ refreshToken: rotated.body.refreshToken }) + .expect(401); + await ctx.http + .get('/api/auth/me') + .set('Authorization', `Bearer ${rotated.body.accessToken}`) + .expect(401); + }); + + it('server logout revokes refresh and access tokens in Solo mode', async () => { + const employee = await seedEmployee(ctx.prisma, { + personalNo: '0001', + firstName: 'Hannah', + lastName: 'Roth', + email: 'hannah@test.local', + }); + await ctx.prisma.installationSettings.create({ + data: { mode: 'Solo', ownerEmployeeId: employee.id }, + }); + const login = await ctx.http + .post('/api/auth/login') + .send({ email: 'hannah@test.local', password: 'test1234' }) + .expect(200); + + await ctx.http + .post('/api/auth/logout') + .send({ refreshToken: login.body.refreshToken }) + .expect(204); + await ctx.http + .post('/api/auth/refresh') + .send({ refreshToken: login.body.refreshToken }) + .expect(401); + await ctx.http + .get('/api/auth/me') + .set('Authorization', `Bearer ${login.body.accessToken}`) + .expect(401); + }); + it('rejects garbage refresh token with 401', async () => { await ctx.http .post('/api/auth/refresh') @@ -110,7 +174,10 @@ describe('Auth — refresh tokens', () => { .post('/api/auth/login') .send({ email: 'hannah@test.local', password: 'test1234' }) .expect(200); - await ctx.prisma.employee.update({ where: { id: e.id }, data: { isActive: false } }); + await ctx.prisma.employee.update({ + where: { id: e.id }, + data: { isActive: false }, + }); await ctx.http .post('/api/auth/refresh') .send({ refreshToken: login.body.refreshToken }) diff --git a/apps/api-e2e/src/support/test-app.ts b/apps/api-e2e/src/support/test-app.ts index 4b83f0e..1d2850c 100644 --- a/apps/api-e2e/src/support/test-app.ts +++ b/apps/api-e2e/src/support/test-app.ts @@ -18,6 +18,8 @@ export interface TestContext { const RESET_SQL = ` TRUNCATE TABLE + "LoginAttemptState", + "AuthSession", "InstallationSettings", "InstallationEvent", "SoloPolicy", diff --git a/apps/api/openapi.json b/apps/api/openapi.json index 0feecdb..2c22dd6 100644 --- a/apps/api/openapi.json +++ b/apps/api/openapi.json @@ -690,7 +690,10 @@ }, "responses": { "200": { - "description": "" + "description": "Authentication succeeded." + }, + "429": { + "description": "The account or network source exceeded its login budget." } }, "tags": ["auth"] @@ -718,6 +721,28 @@ "tags": ["auth"] } }, + "/api/auth/logout": { + "post": { + "operationId": "AuthController_logout", + "parameters": [], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/LogoutDto" + } + } + } + }, + "responses": { + "204": { + "description": "The refresh session was revoked." + } + }, + "tags": ["auth"] + } + }, "/api/auth/me/preferences": { "patch": { "operationId": "AuthController_updatePreferences", @@ -6262,6 +6287,16 @@ }, "required": ["refreshToken"] }, + "LogoutDto": { + "type": "object", + "properties": { + "refreshToken": { + "type": "string", + "description": "The refresh token for the session family that should be revoked." + } + }, + "required": ["refreshToken"] + }, "ThemePreference": { "type": "string", "enum": ["Light", "Dark", "System"], diff --git a/apps/api/src/app/auth/auth.controller.ts b/apps/api/src/app/auth/auth.controller.ts index 4c56819..f89221f 100644 --- a/apps/api/src/app/auth/auth.controller.ts +++ b/apps/api/src/app/auth/auth.controller.ts @@ -2,17 +2,28 @@ import { Body, Controller, Get, + HttpException, HttpCode, HttpStatus, Patch, Post, + Req, + Res, UseGuards, } from '@nestjs/common'; -import { ApiBearerAuth, ApiTags } from '@nestjs/swagger'; +import { + ApiBearerAuth, + ApiNoContentResponse, + ApiOkResponse, + ApiTags, + ApiTooManyRequestsResponse, +} from '@nestjs/swagger'; +import type { Request, Response } from 'express'; import { CurrentUser } from './current-user.decorator'; import { AuthService } from './auth.service'; import { LoginDto, + LogoutDto, ChangePasswordDto, UpdateOwnProfileDto, RefreshDto, @@ -53,8 +64,35 @@ export class AuthController { @Post('login') @HttpCode(HttpStatus.OK) - login(@Body() dto: LoginDto): Promise { - return this.auth.login(dto.email, dto.password); + @ApiOkResponse({ description: 'Authentication succeeded.' }) + @ApiTooManyRequestsResponse({ + description: 'The account or network source exceeded its login budget.', + }) + async login( + @Body() dto: LoginDto, + @Req() request: Request, + @Res({ passthrough: true }) response: Response, + ): Promise { + try { + // Do not trust a caller-provided forwarding header. Express `ip` is the + // peer address unless the deployment explicitly configures trusted proxies. + const source = + request.ip ?? request.socket.remoteAddress ?? 'unknown-peer'; + return await this.auth.login(dto.email, dto.password, source); + } catch (error) { + if (error instanceof HttpException && error.getStatus() === 429) { + const body = error.getResponse(); + const retryAfterSeconds = + typeof body === 'object' && + body !== null && + 'retryAfterSeconds' in body && + typeof body.retryAfterSeconds === 'number' + ? body.retryAfterSeconds + : 60; + response.setHeader('Retry-After', String(retryAfterSeconds)); + } + throw error; + } } @Post('refresh') @@ -63,6 +101,13 @@ export class AuthController { return this.auth.refresh(dto.refreshToken); } + @Post('logout') + @HttpCode(HttpStatus.NO_CONTENT) + @ApiNoContentResponse({ description: 'The refresh session was revoked.' }) + logout(@Body() dto: LogoutDto): Promise { + return this.auth.logout(dto.refreshToken); + } + @Get('me') @ApiBearerAuth() @UseGuards(JwtAuthGuard) diff --git a/apps/api/src/app/auth/auth.dto.ts b/apps/api/src/app/auth/auth.dto.ts index a50c34a..a008775 100644 --- a/apps/api/src/app/auth/auth.dto.ts +++ b/apps/api/src/app/auth/auth.dto.ts @@ -29,6 +29,16 @@ export class RefreshDto { refreshToken!: string; } +export class LogoutDto { + @ApiProperty({ + description: + 'The refresh token for the session family that should be revoked.', + }) + @IsString() + @MinLength(1) + refreshToken!: string; +} + export class UpdatePreferencesDto { @ApiProperty({ enum: ThemePreference, diff --git a/apps/api/src/app/auth/auth.service.ts b/apps/api/src/app/auth/auth.service.ts index 72aac71..e77ea95 100644 --- a/apps/api/src/app/auth/auth.service.ts +++ b/apps/api/src/app/auth/auth.service.ts @@ -1,14 +1,16 @@ -import { randomUUID } from 'crypto'; +import { createHash, randomUUID } from 'node:crypto'; import { BadRequestException, ConflictException, + HttpException, + HttpStatus, Injectable, NotFoundException, UnauthorizedException, } from '@nestjs/common'; import { JwtService } from '@nestjs/jwt'; import * as bcrypt from 'bcrypt'; -import { ThemePreference } from '@prisma/client'; +import { ThemePreference, type Prisma } from '@prisma/client'; import { PrismaService } from '../prisma/prisma.service'; import { InstallationService } from '../installation/installation.service'; import type { JwtPayload } from './jwt.strategy'; @@ -21,6 +23,20 @@ import type { const ACCESS_TTL = '15m'; const ACCESS_TTL_SECONDS = 15 * 60; const REFRESH_TTL = '7d'; +const REFRESH_TTL_MS = 7 * 24 * 60 * 60 * 1000; +const LOGIN_WINDOW_MS = 15 * 60 * 1000; +const LOGIN_LOCK_MS = 15 * 60 * 1000; +const ACCOUNT_ATTEMPT_LIMIT = 5; +const SOURCE_ATTEMPT_LIMIT = 100; +// A fixed cost-10 bcrypt hash keeps unknown accounts on the same expensive +// password-verification path as production employee accounts. +const DUMMY_PASSWORD_HASH = + '$2b$10$N9qo8uLOickgx2ZMRZoMyeIjZAgcfl7p92ldGxad68LJZdL17lhWy'; + +interface LoginLimitKey { + key: string; + limit: number; +} @Injectable() export class AuthService { @@ -30,25 +46,50 @@ export class AuthService { private readonly installation: InstallationService, ) {} - async login(email: string, password: string): Promise { - const employee = await this.prisma.employee.findUnique({ - where: { email }, - }); - if (!employee || !employee.isActive) { + async login( + email: string, + password: string, + source: string, + ): Promise { + const normalizedEmail = email.trim().toLowerCase(); + const limitKeys = this.loginLimitKeys(normalizedEmail, source); + const retryAfterSeconds = await this.reserveLoginAttempt(limitKeys); + if (retryAfterSeconds !== null) { + throw this.loginRateLimited(retryAfterSeconds); + } + const [employee, settings] = await Promise.all([ + this.prisma.employee.findUnique({ where: { email: normalizedEmail } }), + this.installation.getSettings(), + ]); + const passwordMatches = await bcrypt.compare( + password, + employee?.passwordHash ?? DUMMY_PASSWORD_HASH, + ); + const actorAllowed = + employee?.isActive && + (settings.mode !== 'Solo' || settings.ownerEmployeeId === employee.id); + if (!actorAllowed || !passwordMatches) { throw new UnauthorizedException('Invalid credentials'); } - const ok = await bcrypt.compare(password, employee.passwordHash); - if (!ok) throw new UnauthorizedException('Invalid credentials'); - await this.installation.assertActorAccess(employee.id); + await this.completeSuccessfulLogin(limitKeys); - const tokens = await this.issueTokenPair({ + const sessionId = randomUUID(); + const issued = await this.issueTokenPair(sessionId, { sub: employee.id, email: employee.email, role: employee.role, ver: employee.authVersion, }); + await this.prisma.authSession.create({ + data: { + id: sessionId, + employeeId: employee.id, + refreshTokenHash: issued.refreshTokenHash, + expiresAt: issued.refreshExpiresAt, + }, + }); return { - ...tokens, + ...issued.tokens, employee: this.toProfile(employee), }; } @@ -77,9 +118,19 @@ export class AuthService { ) throw new UnauthorizedException('Current password is incorrect'); const passwordHash = await bcrypt.hash(newPassword, 10); - const changed = await this.prisma.employee.updateMany({ - where: { id: employeeId, passwordHash: employee.passwordHash }, - data: { passwordHash, authVersion: { increment: 1 } }, + const changed = await this.prisma.$transaction(async (tx) => { + await this.lockEmployeeAuth(tx, employeeId); + const result = await tx.employee.updateMany({ + where: { id: employeeId, passwordHash: employee.passwordHash }, + data: { passwordHash, authVersion: { increment: 1 } }, + }); + if (result.count) { + await tx.authSession.updateMany({ + where: { employeeId, revokedAt: null }, + data: { revokedAt: new Date() }, + }); + } + return result; }); if (!changed.count) throw new UnauthorizedException( @@ -151,25 +202,84 @@ export class AuthService { } catch { throw new UnauthorizedException('Invalid refresh token'); } - if (payload.typ !== 'refresh') { - throw new UnauthorizedException('Token is not a refresh token'); + if (payload.typ !== 'refresh' || !payload.sid || !payload.sub) { + throw new UnauthorizedException('Invalid refresh token'); } - // Re-check the employee exists and is still active — a deactivation - // between login and refresh must invalidate the session. - const employee = await this.prisma.employee.findUnique({ - where: { id: payload.sub }, + const employeeId = payload.sub; + const sessionId = payload.sid; + await this.installation.assertActorAccess(employeeId); + const presentedHash = this.hash(refreshToken); + const tokens = await this.prisma.$transaction(async (tx) => { + await this.lockEmployeeAuth(tx, employeeId); + await this.lockSession(tx, sessionId); + const [session, employee] = await Promise.all([ + tx.authSession.findUnique({ where: { id: sessionId } }), + tx.employee.findUnique({ where: { id: employeeId } }), + ]); + const now = new Date(); + const sessionMatches = + session?.employeeId === employeeId && + !session.revokedAt && + session.expiresAt > now && + session.refreshTokenHash === presentedHash; + const employeeMatches = + employee?.isActive && (payload.ver ?? 0) === employee.authVersion; + if (!sessionMatches || !employeeMatches) { + // A validly signed token for an existing family that is no longer the + // current token is a replay. Revoke the family so the token minted by + // the winning rotation cannot be used either. + if (session && !session.revokedAt) { + await tx.authSession.update({ + where: { id: session.id }, + data: { revokedAt: now }, + }); + } + return null; + } + const issued = await this.issueTokenPair(session.id, { + sub: employee.id, + email: employee.email, + role: employee.role, + ver: employee.authVersion, + }); + await tx.authSession.update({ + where: { id: session.id }, + data: { + refreshTokenHash: issued.refreshTokenHash, + expiresAt: issued.refreshExpiresAt, + lastRotatedAt: now, + }, + }); + return issued.tokens; }); - if (!employee || !employee.isActive) { - throw new UnauthorizedException('Account is no longer active'); + if (!tokens) throw new UnauthorizedException('Invalid refresh token'); + return tokens; + } + + async logout(refreshToken: string): Promise { + let payload: JwtPayload; + try { + // Logout remains useful when the short-lived access or refresh token has + // just expired. Signature verification is still mandatory. + payload = await this.jwt.verifyAsync(refreshToken, { + ignoreExpiration: true, + }); + } catch { + return; } - if ((payload.ver ?? 0) !== employee.authVersion) - throw new UnauthorizedException('Session no longer valid'); - await this.installation.assertActorAccess(employee.id); - return this.issueTokenPair({ - sub: employee.id, - email: employee.email, - role: employee.role, - ver: employee.authVersion, + if (payload.typ !== 'refresh' || !payload.sid || !payload.sub) return; + const employeeId = payload.sub; + const sessionId = payload.sid; + await this.prisma.$transaction(async (tx) => { + await this.lockSession(tx, sessionId); + await tx.authSession.updateMany({ + where: { + id: sessionId, + employeeId, + revokedAt: null, + }, + data: { revokedAt: new Date() }, + }); }); } @@ -180,19 +290,173 @@ export class AuthService { * pair has at most a 7-day window. */ private async issueTokenPair( - base: Omit, - ): Promise { + sessionId: string, + base: Omit, + ): Promise<{ + tokens: RefreshResponse; + refreshTokenHash: string; + refreshExpiresAt: Date; + }> { // `jwtid` ensures every token has a unique string even when signed at the // same second with the same payload (otherwise login + immediate refresh // would mint identical access tokens). const accessToken = await this.jwt.signAsync( - { ...base, typ: 'access' satisfies JwtPayload['typ'] }, + { ...base, sid: sessionId, typ: 'access' satisfies JwtPayload['typ'] }, { expiresIn: ACCESS_TTL, jwtid: randomUUID() }, ); const refreshToken = await this.jwt.signAsync( - { ...base, typ: 'refresh' satisfies JwtPayload['typ'] }, + { ...base, sid: sessionId, typ: 'refresh' satisfies JwtPayload['typ'] }, { expiresIn: REFRESH_TTL, jwtid: randomUUID() }, ); - return { accessToken, refreshToken, expiresIn: ACCESS_TTL_SECONDS }; + return { + tokens: { accessToken, refreshToken, expiresIn: ACCESS_TTL_SECONDS }, + refreshTokenHash: this.hash(refreshToken), + refreshExpiresAt: new Date(Date.now() + REFRESH_TTL_MS), + }; + } + + private hash(value: string): string { + return createHash('sha256').update(value).digest('hex'); + } + + private loginLimitKeys(email: string, source: string): LoginLimitKey[] { + return [ + { + key: this.hash(`account:${email}`), + limit: ACCOUNT_ATTEMPT_LIMIT, + }, + { + key: this.hash(`source:${source || 'unknown-peer'}`), + limit: SOURCE_ATTEMPT_LIMIT, + }, + ]; + } + + private async reserveLoginAttempt( + keys: LoginLimitKey[], + ): Promise { + return this.prisma.$transaction(async (tx) => { + await this.lockLoginKeys(tx, keys); + const now = new Date(); + await tx.loginAttemptState.deleteMany({ + where: { expiresAt: { lte: now } }, + }); + const rows = await tx.loginAttemptState.findMany({ + where: { key: { in: keys.map(({ key }) => key) } }, + }); + const rowsByKey = new Map(rows.map((row) => [row.key, row])); + const activeRetryAfter = rows.reduce((maximum, row) => { + const remaining = row.lockedUntil + ? row.lockedUntil.getTime() - now.getTime() + : 0; + return Math.max(maximum, remaining); + }, 0); + if (activeRetryAfter > 0) { + return Math.max(1, Math.ceil(activeRetryAfter / 1000)); + } + + let retryAfter = 0; + for (const { key, limit } of keys) { + const current = rowsByKey.get(key); + const reset = + !current || + now.getTime() - current.windowStartedAt.getTime() >= LOGIN_WINDOW_MS; + const attemptCount = reset ? 1 : current.attemptCount + 1; + const windowStartedAt = reset ? now : current.windowStartedAt; + const windowExpiresAt = windowStartedAt.getTime() + LOGIN_WINDOW_MS; + const lockedUntil = + attemptCount > limit + ? new Date(Math.max(windowExpiresAt, now.getTime() + LOGIN_LOCK_MS)) + : reset + ? null + : current.lockedUntil; + const expiresAt = new Date( + Math.max(windowExpiresAt, lockedUntil?.getTime() ?? 0), + ); + await tx.loginAttemptState.upsert({ + where: { key }, + create: { + key, + attemptCount, + windowStartedAt, + lockedUntil, + expiresAt, + }, + update: { + attemptCount, + windowStartedAt, + lockedUntil, + expiresAt, + }, + }); + if (lockedUntil) { + retryAfter = Math.max( + retryAfter, + lockedUntil.getTime() - now.getTime(), + ); + } + } + return retryAfter > 0 ? Math.max(1, Math.ceil(retryAfter / 1000)) : null; + }); + } + + private async completeSuccessfulLogin(keys: LoginLimitKey[]): Promise { + await this.prisma.$transaction(async (tx) => { + await this.lockLoginKeys(tx, keys); + await tx.loginAttemptState.deleteMany({ where: { key: keys[0].key } }); + const source = await tx.loginAttemptState.findUnique({ + where: { key: keys[1].key }, + }); + const now = new Date(); + // Remove only this successful request's reservation. If other parallel + // attempts already locked the source, preserving that lock takes priority. + if (source && (!source.lockedUntil || source.lockedUntil <= now)) { + if (source.attemptCount <= 1) { + await tx.loginAttemptState.delete({ where: { key: source.key } }); + } else { + await tx.loginAttemptState.update({ + where: { key: source.key }, + data: { + attemptCount: { decrement: 1 }, + lockedUntil: null, + }, + }); + } + } + }); + } + + private async lockLoginKeys( + tx: Prisma.TransactionClient, + keys: LoginLimitKey[], + ): Promise { + for (const key of keys.map(({ key }) => key).sort()) { + await tx.$executeRaw`SELECT pg_advisory_xact_lock(hashtextextended(${`auth-login:${key}`}, 0))`; + } + } + + private async lockEmployeeAuth( + tx: Prisma.TransactionClient, + employeeId: string, + ): Promise { + await tx.$executeRaw`SELECT pg_advisory_xact_lock(hashtextextended(${`auth-employee:${employeeId}`}, 0))`; + } + + private async lockSession( + tx: Prisma.TransactionClient, + sessionId: string, + ): Promise { + await tx.$executeRaw`SELECT pg_advisory_xact_lock(hashtextextended(${`auth-session:${sessionId}`}, 0))`; + } + + private loginRateLimited(retryAfterSeconds: number): HttpException { + return new HttpException( + { + code: 'AUTH_LOGIN_RATE_LIMITED', + message: 'Too many login attempts; try again later', + retryAfterSeconds, + }, + HttpStatus.TOO_MANY_REQUESTS, + ); } } diff --git a/apps/api/src/app/auth/jwt.strategy.ts b/apps/api/src/app/auth/jwt.strategy.ts index 2f098b6..85615d3 100644 --- a/apps/api/src/app/auth/jwt.strategy.ts +++ b/apps/api/src/app/auth/jwt.strategy.ts @@ -11,6 +11,8 @@ export interface JwtPayload { sub: string; email: string; role: Role; + /** Server-side session family for tokens issued after session rotation. */ + sid?: string; /** Token type — guards against using a refresh-token as an access-token. */ typ: TokenType; ver?: number; @@ -53,6 +55,18 @@ export class JwtStrategy extends PassportStrategy(Strategy) { }); if (!employee?.isActive || (payload.ver ?? 0) !== employee.authVersion) throw new UnauthorizedException('Session no longer valid'); + if (payload.sid) { + const session = await this.prisma.authSession.findFirst({ + where: { + id: payload.sid, + employeeId: employee.id, + revokedAt: null, + expiresAt: { gt: new Date() }, + }, + select: { id: true }, + }); + if (!session) throw new UnauthorizedException('Session no longer valid'); + } return { id: employee.id, email: employee.email, diff --git a/apps/api/src/app/installation/solo-access.guard.ts b/apps/api/src/app/installation/solo-access.guard.ts index 93aa1c3..6b2fb54 100644 --- a/apps/api/src/app/installation/solo-access.guard.ts +++ b/apps/api/src/app/installation/solo-access.guard.ts @@ -29,7 +29,7 @@ export class SoloAccessGuard extends AuthGuard('jwt') { ); if ( req.method === 'OPTIONS' || - ['/health', '/auth/login', '/auth/refresh'].includes(path) + ['/health', '/auth/login', '/auth/refresh', '/auth/logout'].includes(path) ) return true; await super.canActivate(context); diff --git a/apps/web/src/api/client.spec.ts b/apps/web/src/api/client.spec.ts new file mode 100644 index 0000000..a159869 --- /dev/null +++ b/apps/web/src/api/client.spec.ts @@ -0,0 +1,135 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { REFRESH_STORAGE_KEY, TOKEN_STORAGE_KEY, request } from './client'; + +describe('cross-tab refresh rotation', () => { + const originalLocks = Object.getOwnPropertyDescriptor(navigator, 'locks'); + const originalStorage = Object.getOwnPropertyDescriptor( + window, + 'localStorage', + ); + const storedValues = new Map(); + const storage: Storage = { + get length() { + return storedValues.size; + }, + clear: () => storedValues.clear(), + getItem: (key) => storedValues.get(key) ?? null, + key: (index) => Array.from(storedValues.keys())[index] ?? null, + removeItem: (key) => storedValues.delete(key), + setItem: (key, value) => storedValues.set(key, value), + }; + const token = (sub: string, sid: string, nonce: string) => { + const payload = btoa(JSON.stringify({ sub, sid, nonce })) + .replace(/\+/g, '-') + .replace(/\//g, '_') + .replace(/=+$/g, ''); + return `header.${payload}.signature`; + }; + + beforeEach(() => { + Object.defineProperty(window, 'localStorage', { + configurable: true, + value: storage, + }); + }); + + afterEach(() => { + storage.clear(); + vi.unstubAllGlobals(); + if (originalLocks) { + Object.defineProperty(navigator, 'locks', originalLocks); + } else { + Reflect.deleteProperty(navigator, 'locks'); + } + if (originalStorage) { + Object.defineProperty(window, 'localStorage', originalStorage); + } + }); + + it('reuses tokens rotated by another tab while waiting for the Web Lock', async () => { + const oldAccess = token('employee-1', 'session-1', 'old-access'); + const oldRefresh = token('employee-1', 'session-1', 'old-refresh'); + const newAccess = token('employee-1', 'session-1', 'new-access'); + const newRefresh = token('employee-1', 'session-1', 'new-refresh'); + storage.setItem(TOKEN_STORAGE_KEY, oldAccess); + storage.setItem(REFRESH_STORAGE_KEY, oldRefresh); + const fetchMock = vi + .fn() + .mockResolvedValueOnce( + new Response(JSON.stringify({ message: 'expired' }), { + status: 401, + headers: { 'Content-Type': 'application/json' }, + }), + ) + .mockResolvedValueOnce( + new Response(JSON.stringify({ ok: true }), { + status: 200, + headers: { 'Content-Type': 'application/json' }, + }), + ); + vi.stubGlobal('fetch', fetchMock); + const lockRequest = vi.fn( + async (_name: string, callback: () => Promise) => { + storage.setItem(TOKEN_STORAGE_KEY, newAccess); + storage.setItem(REFRESH_STORAGE_KEY, newRefresh); + return callback(); + }, + ); + Object.defineProperty(navigator, 'locks', { + configurable: true, + value: { request: lockRequest }, + }); + + await expect(request<{ ok: boolean }>('/api/protected')).resolves.toEqual({ + ok: true, + }); + + expect(lockRequest).toHaveBeenCalledWith( + 'openclockwork:refresh-token', + expect.any(Function), + ); + expect(fetchMock).toHaveBeenCalledTimes(2); + expect(fetchMock.mock.calls[0][0]).toBe('/api/protected'); + expect(fetchMock.mock.calls[1][0]).toBe('/api/protected'); + expect(fetchMock.mock.calls[1][1]?.headers).toMatchObject({ + Authorization: `Bearer ${newAccess}`, + }); + }); + + it('does not retry an old request under a different newly logged-in identity', async () => { + const oldAccess = token('employee-1', 'session-1', 'old-access'); + const oldRefresh = token('employee-1', 'session-1', 'old-refresh'); + const otherAccess = token('employee-2', 'session-2', 'new-access'); + const otherRefresh = token('employee-2', 'session-2', 'new-refresh'); + storage.setItem(TOKEN_STORAGE_KEY, oldAccess); + storage.setItem(REFRESH_STORAGE_KEY, oldRefresh); + const fetchMock = vi.fn().mockResolvedValue( + new Response(JSON.stringify({ message: 'expired' }), { + status: 401, + headers: { 'Content-Type': 'application/json' }, + }), + ); + vi.stubGlobal('fetch', fetchMock); + Object.defineProperty(navigator, 'locks', { + configurable: true, + value: { + request: async ( + _name: string, + callback: () => Promise, + ) => { + storage.setItem(TOKEN_STORAGE_KEY, otherAccess); + storage.setItem(REFRESH_STORAGE_KEY, otherRefresh); + return callback(); + }, + }, + }); + + await expect(request('/api/protected')).rejects.toMatchObject({ + status: 401, + }); + + expect(fetchMock).toHaveBeenCalledTimes(1); + expect(storage.getItem(TOKEN_STORAGE_KEY)).toBe(otherAccess); + expect(storage.getItem(REFRESH_STORAGE_KEY)).toBe(otherRefresh); + }); +}); diff --git a/apps/web/src/api/client.ts b/apps/web/src/api/client.ts index 0d9319e..c32555b 100644 --- a/apps/web/src/api/client.ts +++ b/apps/web/src/api/client.ts @@ -1012,6 +1012,10 @@ export interface RefreshResponse { expiresIn: number; } +export interface LogoutPayload { + refreshToken: string; +} + export const TOKEN_STORAGE_KEY = 'openclockwork.accessToken'; export const REFRESH_STORAGE_KEY = 'openclockwork.refreshToken'; export const AUTH_SESSION_EXPIRED_EVENT = 'openclockwork:auth-session-expired'; @@ -1059,35 +1063,112 @@ function storeTokens(access: string | null, refresh: string | null): void { * /auth/refresh. */ let refreshInFlight: Promise | null = null; +const AUTH_REFRESH_LOCK_NAME = 'openclockwork:refresh-token'; -async function tryRefreshOnce(): Promise { - if (refreshInFlight) return refreshInFlight; +interface TokenIdentity { + sub: string; + sid: string; +} + +/** Decode only enough unverified JWT payload to correlate browser storage. + * Authorization still relies exclusively on server-side signature checks. */ +function tokenIdentity(token: string): TokenIdentity | null { + try { + const payload = token.split('.')[1]; + if (!payload) return null; + const normalized = payload.replace(/-/g, '+').replace(/_/g, '/'); + const decoded = JSON.parse( + atob(normalized.padEnd(Math.ceil(normalized.length / 4) * 4, '=')), + ) as { sub?: unknown; sid?: unknown }; + return typeof decoded.sub === 'string' && typeof decoded.sid === 'string' + ? { sub: decoded.sub, sid: decoded.sid } + : null; + } catch { + return null; + } +} + +function sameSessionFamily(...tokens: string[]): boolean { + const identities = tokens.map(tokenIdentity); + const first = identities[0]; + return Boolean( + first && + identities.every( + (identity) => identity?.sub === first.sub && identity.sid === first.sid, + ), + ); +} + +async function refreshAfterLock( + expectedRefreshToken: string, +): Promise { const refreshToken = readRefreshToken(); if (!refreshToken) { notifySessionExpired(); return null; } + // Another tab may have completed rotation while this tab waited for the + // origin-wide Web Lock. Reuse its new access token instead of replaying the + // now-consumed refresh token. + if (refreshToken !== expectedRefreshToken) { + const accessToken = readToken(); + if ( + accessToken && + sameSessionFamily(expectedRefreshToken, refreshToken, accessToken) + ) { + return accessToken; + } + // Storage may instead contain a logout followed by a different user's + // login. Do not retry the old request under that new identity, and do not + // clear the unrelated session. + return null; + } + try { + const res = await fetch(`${baseUrl}/api/auth/refresh`, { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + Accept: 'application/json', + }, + body: JSON.stringify({ refreshToken }), + }); + if (!res.ok) { + // Refresh itself failed — clear the slate so the user is forced to log in. + storeTokens(null, null); + return null; + } + const body = (await res.json()) as RefreshResponse; + storeTokens(body.accessToken, body.refreshToken); + return body.accessToken; + } catch { + storeTokens(null, null); + return null; + } +} + +async function tryRefreshOnce(): Promise { + if (refreshInFlight) return refreshInFlight; + const expectedRefreshToken = readRefreshToken(); + if (!expectedRefreshToken) { + notifySessionExpired(); + return null; + } refreshInFlight = (async () => { try { - const res = await fetch(`${baseUrl}/api/auth/refresh`, { - method: 'POST', - headers: { - 'Content-Type': 'application/json', - Accept: 'application/json', - }, - body: JSON.stringify({ refreshToken }), - }); - if (!res.ok) { - // Refresh itself failed — clear the slate so the user is forced to log in. - storeTokens(null, null); - return null; + const locks = + typeof navigator !== 'undefined' ? navigator.locks : undefined; + if (locks) { + return await locks.request(AUTH_REFRESH_LOCK_NAME, () => + refreshAfterLock(expectedRefreshToken), + ); } - const body = (await res.json()) as RefreshResponse; - storeTokens(body.accessToken, body.refreshToken); - return body.accessToken; + // Older browsers retain the existing per-tab coalescing. The server's + // single-use rotation remains authoritative if two such tabs race. + return await refreshAfterLock(expectedRefreshToken); } catch { - storeTokens(null, null); - return null; + // A present-but-unusable LockManager must not make offline recovery + // worse; fall back to the same guarded refresh path. + return refreshAfterLock(expectedRefreshToken); } finally { refreshInFlight = null; } @@ -1242,6 +1323,11 @@ export const api = { method: 'POST', body: JSON.stringify(payload), }), + logout: (payload: LogoutPayload) => + request('/api/auth/logout', { + method: 'POST', + body: JSON.stringify(payload), + }), me: () => request('/api/auth/me'), updatePreferences: (themePreference: ThemePreference) => request('/api/auth/me/preferences', { diff --git a/apps/web/src/api/generated.ts b/apps/web/src/api/generated.ts index 7c8d548..d9ab305 100644 --- a/apps/web/src/api/generated.ts +++ b/apps/web/src/api/generated.ts @@ -276,6 +276,22 @@ export interface paths { patch?: never; trace?: never; }; + '/api/auth/logout': { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + post: operations['AuthController_logout']; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; '/api/auth/me/preferences': { parameters: { query?: never; @@ -2176,6 +2192,10 @@ export interface components { /** @description A refresh token previously returned from /auth/login or /auth/refresh. */ refreshToken: string; }; + LogoutDto: { + /** @description The refresh token for the session family that should be revoked. */ + refreshToken: string; + }; /** * @description Light / Dark / System. System follows the OS color-scheme media query in the browser. * @enum {string} @@ -4445,12 +4465,20 @@ export interface operations { }; }; responses: { + /** @description Authentication succeeded. */ 200: { headers: { [name: string]: unknown; }; content?: never; }; + /** @description The account or network source exceeded its login budget. */ + 429: { + headers: { + [name: string]: unknown; + }; + content?: never; + }; }; }; AuthController_refresh: { @@ -4474,6 +4502,28 @@ export interface operations { }; }; }; + AuthController_logout: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody: { + content: { + 'application/json': components['schemas']['LogoutDto']; + }; + }; + responses: { + /** @description The refresh session was revoked. */ + 204: { + headers: { + [name: string]: unknown; + }; + content?: never; + }; + }; + }; AuthController_updatePreferences: { parameters: { query?: never; diff --git a/apps/web/src/app/auth.spec.tsx b/apps/web/src/app/auth.spec.tsx index 79e0055..ae9d6e1 100644 --- a/apps/web/src/app/auth.spec.tsx +++ b/apps/web/src/app/auth.spec.tsx @@ -1,6 +1,6 @@ import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; -import { fireEvent, render, screen } from '@testing-library/react'; -import { beforeEach, describe, expect, it } from 'vitest'; +import { fireEvent, render, screen, waitFor } from '@testing-library/react'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { AUTH_SESSION_EXPIRED_EVENT, REFRESH_STORAGE_KEY, @@ -42,8 +42,13 @@ describe('AuthProvider', () => { beforeEach(() => { localStorageMock.clear(); }); + afterEach(() => vi.unstubAllGlobals()); - it('clears the employee session and cached profile synchronously on logout', () => { + it('clears locally first and best-effort revokes the server session on logout', async () => { + const fetchMock = vi + .fn() + .mockResolvedValue(new Response(null, { status: 204 })); + vi.stubGlobal('fetch', fetchMock); localStorageMock.setItem(TOKEN_STORAGE_KEY, 'access-token'); localStorageMock.setItem(REFRESH_STORAGE_KEY, 'refresh-token'); localStorageMock.setItem( @@ -74,6 +79,14 @@ describe('AuthProvider', () => { expect(localStorageMock.getItem(TOKEN_STORAGE_KEY)).toBeNull(); expect(localStorageMock.getItem(REFRESH_STORAGE_KEY)).toBeNull(); expect(localStorageMock.getItem(USER_STORAGE_KEY)).toBeNull(); + await waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(1)); + expect(fetchMock).toHaveBeenCalledWith( + '/api/auth/logout', + expect.objectContaining({ + method: 'POST', + body: JSON.stringify({ refreshToken: 'refresh-token' }), + }), + ); }); it('logs an admin tab out when a same-origin kiosk tab clears its access token', () => { diff --git a/apps/web/src/app/auth.tsx b/apps/web/src/app/auth.tsx index 229c258..4bcfe69 100644 --- a/apps/web/src/app/auth.tsx +++ b/apps/web/src/app/auth.tsx @@ -111,7 +111,20 @@ export function AuthProvider({ children }: { children: ReactNode }) { queryClient.clear(); }, [queryClient]); - const logout = clearSession; + const logout = useCallback(() => { + let refreshToken: string | null = null; + try { + refreshToken = window.localStorage?.getItem(REFRESH_STORAGE_KEY) ?? null; + } catch { + /* localStorage may be unavailable in hardened browser contexts */ + } + // Local logout is immediate; server revocation is deliberately best effort + // so an offline API cannot leave a shared browser visibly signed in. + clearSession(); + if (refreshToken) { + void api.logout({ refreshToken }).catch(() => undefined); + } + }, [clearSession]); useEffect(() => { const handleStorage = (event: StorageEvent) => { diff --git a/prisma/migrations/20261205120000_auth_sessions_and_login_limits/migration.sql b/prisma/migrations/20261205120000_auth_sessions_and_login_limits/migration.sql new file mode 100644 index 0000000..523941a --- /dev/null +++ b/prisma/migrations/20261205120000_auth_sessions_and_login_limits/migration.sql @@ -0,0 +1,36 @@ +-- Server-side refresh-token families make rotation and logout enforceable. +CREATE TABLE "AuthSession" ( + "id" UUID NOT NULL, + "employeeId" UUID NOT NULL, + "refreshTokenHash" CHAR(64) NOT NULL, + "expiresAt" TIMESTAMP(3) NOT NULL, + "revokedAt" TIMESTAMP(3), + "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + "lastRotatedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + "updatedAt" TIMESTAMP(3) NOT NULL, + + CONSTRAINT "AuthSession_pkey" PRIMARY KEY ("id") +); + +-- Login-attempt limits are durable and shared across API processes. The key is a +-- scoped SHA-256 digest; no email address or network address is stored here. +CREATE TABLE "LoginAttemptState" ( + "key" CHAR(64) NOT NULL, + "attemptCount" INTEGER NOT NULL DEFAULT 0, + "windowStartedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + "lockedUntil" TIMESTAMP(3), + "expiresAt" TIMESTAMP(3) NOT NULL, + "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + "updatedAt" TIMESTAMP(3) NOT NULL, + + CONSTRAINT "LoginAttemptState_pkey" PRIMARY KEY ("key") +); + +CREATE INDEX "AuthSession_employeeId_idx" ON "AuthSession"("employeeId"); +CREATE INDEX "AuthSession_expiresAt_idx" ON "AuthSession"("expiresAt"); +CREATE INDEX "LoginAttemptState_expiresAt_idx" ON "LoginAttemptState"("expiresAt"); + +ALTER TABLE "AuthSession" +ADD CONSTRAINT "AuthSession_employeeId_fkey" +FOREIGN KEY ("employeeId") REFERENCES "Employee"("id") +ON DELETE CASCADE ON UPDATE CASCADE; diff --git a/prisma/schema.prisma b/prisma/schema.prisma index 77d4c22..a4eca42 100644 --- a/prisma/schema.prisma +++ b/prisma/schema.prisma @@ -157,6 +157,7 @@ model Employee { projectAssignments ProjectAssignment[] terminalChallengeRedemptions TerminalChallengeRedemption[] terminalCredential TerminalCredential? + authSessions AuthSession[] lastTerminalActivityId String? @db.Uuid lastTerminalActivity Activity? @relation(fields: [lastTerminalActivityId], references: [id], onDelete: SetNull) ownedInstallation InstallationSettings? @@ -175,6 +176,37 @@ model Employee { @@index([lastTerminalActivityId]) } +/// A server-side refresh-token family. Only the hash of the currently valid +/// refresh token is stored; every successful refresh atomically replaces it. +model AuthSession { + id String @id @default(uuid()) @db.Uuid + employeeId String @db.Uuid + employee Employee @relation(fields: [employeeId], references: [id], onDelete: Cascade) + refreshTokenHash String @db.Char(64) + expiresAt DateTime + revokedAt DateTime? + createdAt DateTime @default(now()) + lastRotatedAt DateTime @default(now()) + updatedAt DateTime @updatedAt + + @@index([employeeId]) + @@index([expiresAt]) +} + +/// Durable login-attempt windows shared by every API process. Keys are +/// SHA-256 digests of a scoped account or peer identity, never raw PII. +model LoginAttemptState { + key String @id @db.Char(64) + attemptCount Int @default(0) + windowStartedAt DateTime @default(now()) + lockedUntil DateTime? + expiresAt DateTime + createdAt DateTime @default(now()) + updatedAt DateTime @updatedAt + + @@index([expiresAt]) +} + // Frame and core working hours. A schedule is assigned per Employee // (Employee.workScheduleId). Multiple core-time windows per schedule are // supported (e.g. 10:00–11:00 and 14:00–15:00). Times are stored as checked