diff --git a/prisma/schema/admin-totp.prisma b/prisma/schema/admin-totp.prisma new file mode 100644 index 00000000..36935599 --- /dev/null +++ b/prisma/schema/admin-totp.prisma @@ -0,0 +1,11 @@ +model AdminTotp { + userId String @id + secretEnc String + enabledAt DateTime? + recoveryHashes String[] @default([]) + lastUsedStep Int? + createdAt DateTime @default(now()) + updatedAt DateTime @updatedAt + + @@map("admin_totp") +} diff --git a/prisma/schema/migrations/20261123000000_add_admin_totp/migration.sql b/prisma/schema/migrations/20261123000000_add_admin_totp/migration.sql new file mode 100644 index 00000000..ec0d6a8a --- /dev/null +++ b/prisma/schema/migrations/20261123000000_add_admin_totp/migration.sql @@ -0,0 +1,11 @@ +CREATE TABLE "admin_totp" ( + "userId" TEXT NOT NULL, + "secretEnc" TEXT NOT NULL, + "enabledAt" TIMESTAMP(3), + "recoveryHashes" TEXT[] NOT NULL DEFAULT ARRAY[]::TEXT[], + "lastUsedStep" INTEGER, + "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + "updatedAt" TIMESTAMP(3) NOT NULL, + + CONSTRAINT "admin_totp_pkey" PRIMARY KEY ("userId") +); diff --git a/src/app.ts b/src/app.ts index 3392d5b0..2b43b25b 100644 --- a/src/app.ts +++ b/src/app.ts @@ -48,6 +48,7 @@ import { routeBodySizeLimit } from './middlewares/body-size-limit.middleware'; import { envConfig } from './config'; import { v1RelatedKeysRouter } from './routes/keys.routes'; import { logger } from './utils/logger.utils'; +import admin2faRouter from './modules/admin/admin-2fa.routes'; import { sanctionedAddressMiddleware } from './middlewares/sanctioned-address.middleware'; const app: Express = express(); @@ -129,6 +130,7 @@ app.get('/', (_, res: Response) => { // Routes app.use('/v1', v1RelatedKeysRouter); +app.use('/v1/admin/2fa', routeBodySizeLimit('admin'), admin2faRouter); app.use('/status', routeBodySizeLimit('default'), statusRouter); app.use('/nonce', routeBodySizeLimit('default'), nonceRouter); app.use('/internal', routeBodySizeLimit('default'), internalRouter); diff --git a/src/middlewares/admin-guard.middleware.test.ts b/src/middlewares/admin-guard.middleware.test.ts index 72a789a1..4af2c292 100644 --- a/src/middlewares/admin-guard.middleware.test.ts +++ b/src/middlewares/admin-guard.middleware.test.ts @@ -1,5 +1,5 @@ import jwt from 'jsonwebtoken'; -import { adminGuard } from './admin-guard.middleware'; +import { adminGuard, pendingAdminGuard } from './admin-guard.middleware'; import { logger } from '../utils/logger.utils'; import { envConfig } from '../config'; @@ -57,3 +57,58 @@ describe('adminGuard — expired token logging (#733)', () => { expect(logger.warn).not.toHaveBeenCalled(); }); }); + +describe('adminGuard — TOTP session status (#1277)', () => { + beforeEach(() => jest.clearAllMocks()); + + it('rejects pending_2fa admin sessions with 401', () => { + const token = jwt.sign( + { sub: 'admin-2fa', role: 'admin', twoFactorStatus: 'pending_2fa' }, + envConfig.JWT_SECRET + ); + const req = makeReq(token); + const res = makeRes(); + const next = jest.fn(); + + adminGuard(req, res, next); + + expect(res.status).toHaveBeenCalledWith(401); + expect(res.json).toHaveBeenCalledWith( + expect.objectContaining({ success: false }) + ); + expect(next).not.toHaveBeenCalled(); + expect(req.adminId).toBeUndefined(); + }); + + it('accepts verified admin sessions', () => { + const token = jwt.sign( + { sub: 'admin-2fa', role: 'admin', twoFactorStatus: 'verified' }, + envConfig.JWT_SECRET + ); + const req = makeReq(token); + const res = makeRes(); + const next = jest.fn(); + + adminGuard(req, res, next); + + expect(next).toHaveBeenCalledTimes(1); + expect(req.adminId).toBe('admin-2fa'); + expect(res.status).not.toHaveBeenCalled(); + }); + + it('allows pending_2fa sessions on the 2FA endpoints', () => { + const token = jwt.sign( + { sub: 'admin-2fa', role: 'admin', twoFactorStatus: 'pending_2fa' }, + envConfig.JWT_SECRET + ); + const req = makeReq(token); + const res = makeRes(); + const next = jest.fn(); + + pendingAdminGuard(req, res, next); + + expect(next).toHaveBeenCalledTimes(1); + expect(req.adminId).toBe('admin-2fa'); + expect(res.status).not.toHaveBeenCalled(); + }); +}); diff --git a/src/middlewares/admin-guard.middleware.ts b/src/middlewares/admin-guard.middleware.ts index 9138fbb2..e779d6ba 100644 --- a/src/middlewares/admin-guard.middleware.ts +++ b/src/middlewares/admin-guard.middleware.ts @@ -1,17 +1,24 @@ import { Request, Response, NextFunction } from 'express'; import jwt from 'jsonwebtoken'; import { envConfig } from '../config'; +import type { AdminJwtPayload } from '../types/auth.types'; import { sendForbidden, sendUnauthorized } from '../utils/api-response.utils'; import { logExpiredTokenRejection } from '../utils/expired-token-log.utils'; +export const ADMIN_2FA_STATUS_PENDING = 'pending_2fa'; +export const ADMIN_2FA_STATUS_VERIFIED = 'verified'; + export interface AdminRequest extends Request { adminId?: string; + adminToken?: string; + adminClaims?: AdminJwtPayload; } -export function adminGuard( +function verifyAdminRequest( req: AdminRequest, res: Response, - next: NextFunction + next: NextFunction, + allowPending: boolean ): void { const authHeader = req.headers.authorization; if (!authHeader?.startsWith('Bearer ')) { @@ -21,17 +28,25 @@ export function adminGuard( const token = authHeader.slice(7); try { - const payload = jwt.verify(token, envConfig.JWT_SECRET) as { - sub?: string; - adminId?: string; - role?: string; - }; + const payload = jwt.verify(token, envConfig.JWT_SECRET) as AdminJwtPayload; const adminId = payload.adminId ?? payload.sub; if (payload.role !== 'admin' || !adminId) { sendForbidden(res, 'Admin authorization required'); return; } + + if ( + !allowPending && + payload.twoFactorStatus !== undefined && + payload.twoFactorStatus !== ADMIN_2FA_STATUS_VERIFIED + ) { + sendUnauthorized(res, 'Two-factor authentication required'); + return; + } + req.adminId = adminId; + req.adminToken = token; + req.adminClaims = payload; next(); } catch (error) { if (error instanceof jwt.TokenExpiredError) { @@ -40,3 +55,19 @@ export function adminGuard( sendUnauthorized(res, 'Invalid or expired token'); } } + +export function adminGuard( + req: AdminRequest, + res: Response, + next: NextFunction +): void { + verifyAdminRequest(req, res, next, false); +} + +export function pendingAdminGuard( + req: AdminRequest, + res: Response, + next: NextFunction +): void { + verifyAdminRequest(req, res, next, true); +} diff --git a/src/modules/admin/admin-2fa.controllers.ts b/src/modules/admin/admin-2fa.controllers.ts new file mode 100644 index 00000000..59f6eb7c --- /dev/null +++ b/src/modules/admin/admin-2fa.controllers.ts @@ -0,0 +1,105 @@ +import type { NextFunction, Response } from 'express'; +import { ErrorCode } from '../../constants/error.constants'; +import type { AdminJwtPayload } from '../../types/auth.types'; +import { + sendError, + sendSuccess, + sendUnauthorized, +} from '../../utils/api-response.utils'; +import { + AdminTotpServiceError, + AdminTotpLoginInput, + loginWithAdminTotp, + setupAdminTotp, + verifyAdminTotpSetup, +} from './admin-2fa.service'; +import type { AdminRequest } from '../../middlewares/admin-guard.middleware'; + +function handleTotpError( + res: Response, + error: unknown, + next: NextFunction +): void { + if (!(error instanceof AdminTotpServiceError)) { + next(error); + return; + } + + if (error.retryAfterSeconds) { + res.setHeader('Retry-After', String(error.retryAfterSeconds)); + } + + const code = + error.statusCode === 429 + ? ErrorCode.RATE_LIMIT + : error.statusCode === 409 + ? ErrorCode.CONFLICT + : ErrorCode.UNAUTHORIZED; + + sendError(res, error.statusCode, code, error.message); +} + +export async function httpAdminTotpSetup( + req: AdminRequest, + res: Response, + next: NextFunction +): Promise { + try { + if (!req.adminId) { + sendUnauthorized(res, 'Admin authorization required'); + return; + } + + sendSuccess( + res, + await setupAdminTotp(req.adminId), + 200, + 'Two-factor setup created' + ); + } catch (error) { + handleTotpError(res, error, next); + } +} + +export async function httpAdminTotpVerify( + req: AdminRequest, + res: Response, + next: NextFunction +): Promise { + try { + if (!req.adminId) { + sendUnauthorized(res, 'Admin authorization required'); + return; + } + + const { code } = req.body as { code: string }; + const enabledAt = await verifyAdminTotpSetup(req.adminId, code); + sendSuccess(res, { enabledAt }, 200, 'Two-factor authentication enabled'); + } catch (error) { + handleTotpError(res, error, next); + } +} + +export async function httpAdminTotpLogin( + req: AdminRequest, + res: Response, + next: NextFunction +): Promise { + try { + if (!req.adminId) { + sendUnauthorized(res, 'Admin authorization required'); + return; + } + + const claims: AdminJwtPayload = req.adminClaims ?? { + sub: req.adminId, + role: 'admin', + }; + const input = req.body as AdminTotpLoginInput; + const result = await loginWithAdminTotp(req.adminId, claims, input); + + sendSuccess(res, result, 200, 'Two-factor authentication verified'); + } catch (error) { + handleTotpError(res, error, next); + } +} diff --git a/src/modules/admin/admin-2fa.routes.ts b/src/modules/admin/admin-2fa.routes.ts new file mode 100644 index 00000000..de846614 --- /dev/null +++ b/src/modules/admin/admin-2fa.routes.ts @@ -0,0 +1,45 @@ +import { Router } from 'express'; +import { z } from 'zod'; +import { pendingAdminGuard } from '../../middlewares/admin-guard.middleware'; +import { validateBody } from '../../middlewares/validate-body.middleware'; +import { + httpAdminTotpLogin, + httpAdminTotpSetup, + httpAdminTotpVerify, +} from './admin-2fa.controllers'; + +const totpCodeSchema = z + .string() + .regex(/^\d{6}$/, 'Verification code must be 6 digits'); + +export const AdminTotpVerifySchema = z.object({ + code: totpCodeSchema, +}); + +export const AdminTotpLoginSchema = z + .object({ + code: totpCodeSchema.optional(), + recoveryCode: z.string().trim().min(8).max(32).optional(), + }) + .refine(value => Boolean(value.code || value.recoveryCode), { + message: 'A verification code or recovery code is required', + path: ['code'], + }); + +export const admin2faRouter = Router(); + +admin2faRouter.post('/setup', pendingAdminGuard, httpAdminTotpSetup); +admin2faRouter.post( + '/verify', + pendingAdminGuard, + validateBody(AdminTotpVerifySchema), + httpAdminTotpVerify +); +admin2faRouter.post( + '/login', + pendingAdminGuard, + validateBody(AdminTotpLoginSchema), + httpAdminTotpLogin +); + +export default admin2faRouter; diff --git a/src/modules/admin/admin-2fa.service.test.ts b/src/modules/admin/admin-2fa.service.test.ts new file mode 100644 index 00000000..f42e8091 --- /dev/null +++ b/src/modules/admin/admin-2fa.service.test.ts @@ -0,0 +1,358 @@ +import { createHmac } from 'crypto'; +import jwt from 'jsonwebtoken'; +import { envConfig } from '../../config'; +import { prisma } from '../../utils/prisma.utils'; +import { + AdminTotpInvalidCodeError, + AdminTotpRateLimitError, + loginWithAdminTotp, + resetAdminTotpRateLimit, + setupAdminTotp, + verifyAdminTotpSetup, +} from './admin-2fa.service'; + +jest.mock('../../utils/prisma.utils', () => ({ + prisma: { + adminTotp: { + findUnique: jest.fn(), + upsert: jest.fn(), + update: jest.fn(), + updateMany: jest.fn(), + }, + }, +})); + +const ADMIN_ID = 'admin-totp-test'; +const BASE32_ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'; +const START_TIME = new Date('2026-11-23T00:00:00.000Z'); + +interface StoredTotp { + userId: string; + secretEnc: string; + enabledAt: Date | null; + recoveryHashes: string[]; + lastUsedStep: number | null; + createdAt: Date; + updatedAt: Date; +} + +const adminTotp = prisma.adminTotp as unknown as { + findUnique: jest.Mock; + upsert: jest.Mock; + update: jest.Mock; + updateMany: jest.Mock; +}; + +let stored: StoredTotp | null = null; + +function cloneStored(): StoredTotp | null { + return stored + ? { + ...stored, + recoveryHashes: [...stored.recoveryHashes], + enabledAt: stored.enabledAt + ? new Date(stored.enabledAt.getTime()) + : null, + } + : null; +} + +function arraysEqual(left: string[], right: string[]): boolean { + return ( + left.length === right.length && + left.every((value, index) => value === right[index]) + ); +} + +function base32Decode(value: string): Buffer { + let bits = 0; + let buffer = 0; + const bytes: number[] = []; + + for (const character of value.toUpperCase().replace(/=+$/, '')) { + const index = BASE32_ALPHABET.indexOf(character); + if (index < 0) throw new Error(`Invalid base32 character: ${character}`); + buffer = (buffer << 5) | index; + bits += 5; + if (bits >= 8) { + bytes.push((buffer >>> (bits - 8)) & 0xff); + bits -= 8; + } + } + + return Buffer.from(bytes); +} + +function secretFromUri(uri: string): string { + const secret = new URL(uri).searchParams.get('secret'); + if (!secret) throw new Error('otpauth URI is missing the secret'); + return secret; +} + +function totpCode(uri: string, step: number): string { + const counter = Buffer.alloc(8); + counter.writeBigUInt64BE(BigInt(step)); + const digest = createHmac('sha1', base32Decode(secretFromUri(uri))) + .update(counter) + .digest(); + const offset = digest[digest.length - 1] & 0x0f; + const value = (digest.readUInt32BE(offset) & 0x7fffffff) % 1_000_000; + return value.toString().padStart(6, '0'); +} + +function stepNow(): number { + return Math.floor(Date.now() / 1000 / 30); +} + +function differentCode(uri: string, step: number): string { + const valid = totpCode(uri, step); + return valid === '000000' ? '000001' : '000000'; +} + +async function configureTotp(adminId = ADMIN_ID) { + const setup = await setupAdminTotp(adminId); + await verifyAdminTotpSetup(adminId, totpCode(setup.otpauthUri, stepNow())); + return setup; +} + +function pendingClaims(adminId = ADMIN_ID) { + return { + sub: adminId, + adminId, + role: 'admin', + twoFactorStatus: 'pending_2fa' as const, + }; +} + +beforeEach(() => { + jest.useFakeTimers(); + jest.setSystemTime(START_TIME); + stored = null; + resetAdminTotpRateLimit(); + jest.clearAllMocks(); + + adminTotp.findUnique.mockImplementation(async () => cloneStored()); + adminTotp.upsert.mockImplementation(async ({ create }) => { + stored = { ...create, createdAt: START_TIME, updatedAt: START_TIME }; + return cloneStored(); + }); + adminTotp.update.mockImplementation(async ({ data }) => { + stored = { ...stored!, ...data, updatedAt: new Date() }; + return cloneStored(); + }); + adminTotp.updateMany.mockImplementation(async ({ where, data }) => { + if (!stored) return { count: 0 }; + + if (where.recoveryHashes?.equals) { + if (!arraysEqual(stored.recoveryHashes, where.recoveryHashes.equals)) { + return { count: 0 }; + } + stored.recoveryHashes = [...data.recoveryHashes.set]; + } else if (where.lastUsedStep !== undefined || where.OR) { + const candidate = data.lastUsedStep as number; + if (stored.lastUsedStep !== null && stored.lastUsedStep >= candidate) { + return { count: 0 }; + } + stored.lastUsedStep = candidate; + } else { + return { count: 0 }; + } + + stored.updatedAt = new Date(); + return { count: 1 }; + }); +}); + +afterEach(() => { + jest.useRealTimers(); +}); + +describe('admin TOTP setup', () => { + it('returns an otpauth URI and stores an encrypted secret with hashed recovery codes', async () => { + const result = await setupAdminTotp(ADMIN_ID); + const uri = new URL(result.otpauthUri); + const secret = secretFromUri(result.otpauthUri); + + expect(uri.protocol).toBe('otpauth:'); + expect(uri.hostname).toBe('totp'); + expect(uri.searchParams.get('secret')).toBe(secret); + expect(uri.searchParams.get('algorithm')).toBe('SHA1'); + expect(uri.searchParams.get('digits')).toBe('6'); + expect(uri.searchParams.get('period')).toBe('30'); + + expect(result.recoveryCodes).toHaveLength(10); + expect(new Set(result.recoveryCodes).size).toBe(10); + result.recoveryCodes.forEach(code => { + expect(code).toMatch(/^[A-Z2-7]{4}-[A-Z2-7]{4}-[A-Z2-7]{2}$/); + }); + + expect(stored).not.toBeNull(); + expect(stored!.secretEnc).toMatch(/^v1\./); + expect(stored!.secretEnc).not.toContain(secret); + expect(stored!.enabledAt).toBeNull(); + expect(stored!.recoveryHashes).toHaveLength(10); + stored!.recoveryHashes.forEach(hash => expect(hash).toMatch(/^[0-9a-f]{64}$/)); + result.recoveryCodes.forEach(code => { + expect(stored!.recoveryHashes).not.toContain(code); + expect(stored!.recoveryHashes).not.toContain(code.replace(/-/g, '')); + }); + }); + + it('enables TOTP only with a valid code', async () => { + const setup = await setupAdminTotp(ADMIN_ID); + const step = stepNow(); + + await expect( + verifyAdminTotpSetup(ADMIN_ID, differentCode(setup.otpauthUri, step)) + ).rejects.toBeInstanceOf(AdminTotpInvalidCodeError); + expect(stored!.enabledAt).toBeNull(); + + resetAdminTotpRateLimit(ADMIN_ID); + const enabledAt = await verifyAdminTotpSetup( + ADMIN_ID, + totpCode(setup.otpauthUri, step) + ); + + expect(enabledAt).toBeInstanceOf(Date); + expect(stored!.enabledAt).toEqual(enabledAt); + }); +}); + +describe('admin TOTP login', () => { + it('issues a verified session for a valid code and rejects an invalid code', async () => { + const setup = await configureTotp(); + jest.setSystemTime(new Date(START_TIME.getTime() + 30_000)); + const step = stepNow(); + + await expect( + loginWithAdminTotp(ADMIN_ID, pendingClaims(), { + code: differentCode(setup.otpauthUri, step), + }) + ).rejects.toBeInstanceOf(AdminTotpInvalidCodeError); + + const result = await loginWithAdminTotp(ADMIN_ID, pendingClaims(), { + code: totpCode(setup.otpauthUri, step), + }); + const decoded = jwt.verify(result.accessToken, envConfig.JWT_SECRET) as jwt.JwtPayload; + + expect(result.tokenType).toBe('Bearer'); + expect(result.expiresIn).toBe(envConfig.JWT_ACCESS_TOKEN_TTL_SECONDS); + expect(decoded).toMatchObject({ + adminId: ADMIN_ID, + sub: ADMIN_ID, + role: 'admin', + twoFactorStatus: 'verified', + }); + }); + + it('rejects a code that was already used in the same step', async () => { + const setup = await configureTotp(); + jest.setSystemTime(new Date(START_TIME.getTime() + 30_000)); + const code = totpCode(setup.otpauthUri, stepNow()); + + await loginWithAdminTotp(ADMIN_ID, pendingClaims(), { code }); + + await expect( + loginWithAdminTotp(ADMIN_ID, pendingClaims(), { code }) + ).rejects.toBeInstanceOf(AdminTotpInvalidCodeError); + }); + + it('rejects a code consumed during setup when logging in during the same step', async () => { + const setup = await setupAdminTotp(ADMIN_ID); + const code = totpCode(setup.otpauthUri, stepNow()); + await verifyAdminTotpSetup(ADMIN_ID, code); + + await expect( + loginWithAdminTotp(ADMIN_ID, pendingClaims(), { code }) + ).rejects.toBeInstanceOf(AdminTotpInvalidCodeError); + }); + + it('accepts one step of clock skew in either direction but not two', async () => { + const previousStep = await setupAdminTotp('admin-skew-behind'); + await verifyAdminTotpSetup( + 'admin-skew-behind', + totpCode(previousStep.otpauthUri, stepNow() - 1) + ); + expect(stored!.enabledAt).toBeInstanceOf(Date); + + stored = null; + const aheadStep = await setupAdminTotp('admin-skew-ahead'); + await verifyAdminTotpSetup( + 'admin-skew-ahead', + totpCode(aheadStep.otpauthUri, stepNow() + 1) + ); + expect(stored!.enabledAt).toBeInstanceOf(Date); + + stored = null; + const tooOld = await setupAdminTotp('admin-skew-too-old'); + await expect( + verifyAdminTotpSetup( + 'admin-skew-too-old', + totpCode(tooOld.otpauthUri, stepNow() - 2) + ) + ).rejects.toBeInstanceOf(AdminTotpInvalidCodeError); + }); +}); + +describe('admin TOTP recovery codes', () => { + it('consumes a recovery code once', async () => { + const setup = await configureTotp(); + jest.setSystemTime(new Date(START_TIME.getTime() + 30_000)); + const recoveryCode = setup.recoveryCodes[0]; + + const result = await loginWithAdminTotp(ADMIN_ID, pendingClaims(), { + recoveryCode: recoveryCode.toLowerCase().replace(/-/g, ' '), + }); + expect(result.accessToken).toEqual(expect.any(String)); + expect(stored!.recoveryHashes).toHaveLength(9); + + await expect( + loginWithAdminTotp(ADMIN_ID, pendingClaims(), { + recoveryCode, + }) + ).rejects.toBeInstanceOf(AdminTotpInvalidCodeError); + expect(stored!.recoveryHashes).toHaveLength(9); + }); + + it('allows only one concurrent use of the same recovery code', async () => { + const setup = await configureTotp(); + jest.setSystemTime(new Date(START_TIME.getTime() + 30_000)); + const recoveryCode = setup.recoveryCodes[1]; + + const results = await Promise.allSettled([ + loginWithAdminTotp(ADMIN_ID, pendingClaims(), { recoveryCode }), + loginWithAdminTotp(ADMIN_ID, pendingClaims(), { recoveryCode }), + ]); + + expect(results.filter(result => result.status === 'fulfilled')).toHaveLength(1); + expect(results.filter(result => result.status === 'rejected')).toHaveLength(1); + expect(stored!.recoveryHashes).toHaveLength(9); + }); +}); + +describe('admin TOTP verification rate limit', () => { + it('returns 429 on the sixth failed attempt within 15 minutes', async () => { + const setup = await setupAdminTotp(ADMIN_ID); + const invalidCode = differentCode(setup.otpauthUri, stepNow()); + + for (let attempt = 0; attempt < 5; attempt++) { + await expect( + verifyAdminTotpSetup(ADMIN_ID, invalidCode) + ).rejects.toBeInstanceOf(AdminTotpInvalidCodeError); + } + + const rateLimitError = (await verifyAdminTotpSetup( + ADMIN_ID, + invalidCode + ).catch(error => error)) as AdminTotpRateLimitError; + + expect(rateLimitError).toBeInstanceOf(AdminTotpRateLimitError); + expect(rateLimitError.statusCode).toBe(429); + expect(rateLimitError.retryAfterSeconds).toBeGreaterThan(0); + + jest.setSystemTime(new Date(START_TIME.getTime() + 15 * 60 * 1000 + 1)); + await expect( + verifyAdminTotpSetup(ADMIN_ID, invalidCode) + ).rejects.toBeInstanceOf(AdminTotpInvalidCodeError); + }); +}); diff --git a/src/modules/admin/admin-2fa.service.ts b/src/modules/admin/admin-2fa.service.ts new file mode 100644 index 00000000..e1ca479c --- /dev/null +++ b/src/modules/admin/admin-2fa.service.ts @@ -0,0 +1,430 @@ +import { + createCipheriv, + createDecipheriv, + createHash, + createHmac, + randomBytes, + timingSafeEqual, +} from 'crypto'; +import { envConfig } from '../../config'; +import type { AdminJwtPayload } from '../../types/auth.types'; +import { signAdminSessionToken } from '../../utils/jwt.utils'; +import { prisma } from '../../utils/prisma.utils'; + +export const TOTP_STEP_SECONDS = 30; +export const TOTP_SKEW_STEPS = 1; +export const TOTP_DIGITS = 6; +export const TOTP_RECOVERY_CODE_COUNT = 10; +export const TOTP_MAX_ATTEMPTS = 5; +export const TOTP_RATE_LIMIT_WINDOW_MS = 15 * 60 * 1000; + +const BASE32_ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'; +const ENCRYPTION_VERSION = 'v1'; + +interface TotpRecord { + userId: string; + secretEnc: string; + enabledAt: Date | null; + recoveryHashes: string[]; + lastUsedStep: number | null; + updatedAt: Date; +} + +interface VerificationAttempt { + count: number; + resetAt: number; +} + +const verificationAttempts = new Map(); + +export class AdminTotpServiceError extends Error { + constructor( + message: string, + public readonly statusCode: number, + public readonly code: string, + public readonly retryAfterSeconds?: number + ) { + super(message); + this.name = new.target.name; + } +} + +export class AdminTotpNotConfiguredError extends AdminTotpServiceError { + constructor() { + super( + 'Two-factor authentication is not configured for this admin', + 409, + 'TOTP_NOT_CONFIGURED' + ); + } +} + +export class AdminTotpAlreadyEnabledError extends AdminTotpServiceError { + constructor() { + super( + 'Two-factor authentication is already enabled for this admin', + 409, + 'TOTP_ALREADY_ENABLED' + ); + } +} + +export class AdminTotpInvalidCodeError extends AdminTotpServiceError { + constructor() { + super( + 'Invalid or already used verification code', + 401, + 'INVALID_TOTP_CODE' + ); + } +} + +export class AdminTotpRateLimitError extends AdminTotpServiceError { + constructor(retryAfterSeconds: number) { + super( + 'Too many two-factor verification attempts', + 429, + 'RATE_LIMIT_EXCEEDED', + retryAfterSeconds + ); + } +} + +export interface AdminTotpSetupResult { + otpauthUri: string; + recoveryCodes: string[]; +} + +export interface AdminTotpLoginInput { + code?: string; + recoveryCode?: string; +} + +export interface AdminTotpLoginResult { + accessToken: string; + tokenType: 'Bearer'; + expiresIn: number; +} + +function base32Encode(buffer: Buffer): string { + let bits = 0; + let value = 0; + let encoded = ''; + + for (const byte of buffer) { + value = (value << 8) | byte; + bits += 8; + while (bits >= 5) { + encoded += BASE32_ALPHABET[(value >>> (bits - 5)) & 31]; + bits -= 5; + } + } + + if (bits > 0) { + encoded += BASE32_ALPHABET[(value << (5 - bits)) & 31]; + } + + return encoded; +} + +function encryptionKey(): Buffer { + return createHash('sha256').update(envConfig.APP_SECRET).digest(); +} + +function encryptSecret(secret: Buffer, userId: string): string { + const iv = randomBytes(12); + const cipher = createCipheriv('aes-256-gcm', encryptionKey(), iv); + cipher.setAAD(Buffer.from(userId, 'utf8')); + const ciphertext = Buffer.concat([cipher.update(secret), cipher.final()]); + + return [ + ENCRYPTION_VERSION, + iv.toString('base64url'), + cipher.getAuthTag().toString('base64url'), + ciphertext.toString('base64url'), + ].join('.'); +} + +function decryptSecret(secretEnc: string, userId: string): Buffer { + const [version, ivPart, tagPart, ciphertextPart] = secretEnc.split('.'); + if ( + version !== ENCRYPTION_VERSION || + !ivPart || + !tagPart || + !ciphertextPart + ) { + throw new Error('Invalid encrypted TOTP secret'); + } + + const decipher = createDecipheriv( + 'aes-256-gcm', + encryptionKey(), + Buffer.from(ivPart, 'base64url') + ); + decipher.setAAD(Buffer.from(userId, 'utf8')); + decipher.setAuthTag(Buffer.from(tagPart, 'base64url')); + + return Buffer.concat([ + decipher.update(Buffer.from(ciphertextPart, 'base64url')), + decipher.final(), + ]); +} + +function currentStep(now: number = Date.now()): number { + return Math.floor(now / 1000 / TOTP_STEP_SECONDS); +} + +function totpCode(secret: Buffer, step: number): string { + const counter = Buffer.alloc(8); + counter.writeBigUInt64BE(BigInt(step)); + + const digest = createHmac('sha1', secret).update(counter).digest(); + const offset = digest[digest.length - 1] & 0x0f; + const value = (digest.readUInt32BE(offset) & 0x7fffffff) % 1_000_000; + + return value.toString().padStart(TOTP_DIGITS, '0'); +} + +function codesEqual(expected: string, actual: string): boolean { + const expectedBuffer = Buffer.from(expected, 'utf8'); + const actualBuffer = Buffer.from(actual, 'utf8'); + return ( + expectedBuffer.length === actualBuffer.length && + timingSafeEqual(expectedBuffer, actualBuffer) + ); +} + +function otpauthUri(userId: string, secret: string): string { + const issuer = new URL(envConfig.BACKEND_URL).host; + const label = `${encodeURIComponent(issuer)}:${encodeURIComponent(userId)}`; + const params = new URLSearchParams({ + secret, + issuer, + algorithm: 'SHA1', + digits: String(TOTP_DIGITS), + period: String(TOTP_STEP_SECONDS), + }); + + return `otpauth://totp/${label}?${params.toString()}`; +} + +export function normalizeRecoveryCode(code: string): string { + return code.toUpperCase().replace(/[^A-Z0-9]/g, ''); +} + +function hashRecoveryCode(code: string): string { + return createHmac('sha256', encryptionKey()) + .update(normalizeRecoveryCode(code)) + .digest('hex'); +} + +function generateRecoveryCodes(): string[] { + return Array.from({ length: TOTP_RECOVERY_CODE_COUNT }, () => { + const raw = base32Encode(randomBytes(6)); + return `${raw.slice(0, 4)}-${raw.slice(4, 8)}-${raw.slice(8)}`; + }); +} + +function assertVerificationAllowed(adminId: string): void { + const now = Date.now(); + let attempt = verificationAttempts.get(adminId); + + if (!attempt || now >= attempt.resetAt) { + attempt = { + count: 0, + resetAt: now + TOTP_RATE_LIMIT_WINDOW_MS, + }; + verificationAttempts.set(adminId, attempt); + } + + if (attempt.count >= TOTP_MAX_ATTEMPTS) { + throw new AdminTotpRateLimitError( + Math.max(1, Math.ceil((attempt.resetAt - now) / 1000)) + ); + } + + attempt.count += 1; + + if (verificationAttempts.size > 1000) { + for (const [key, state] of verificationAttempts) { + if (now >= state.resetAt) { + verificationAttempts.delete(key); + } + } + } +} + +function clearVerificationAttempts(adminId: string): void { + verificationAttempts.delete(adminId); +} + +export function resetAdminTotpRateLimit(adminId?: string): void { + if (adminId) { + verificationAttempts.delete(adminId); + return; + } + verificationAttempts.clear(); +} + +async function loadTotp(adminId: string): Promise { + return (await prisma.adminTotp.findUnique({ + where: { userId: adminId }, + })) as TotpRecord | null; +} + +async function verifyTotpCode( + record: TotpRecord, + code: string +): Promise { + if (!/^\d{6}$/.test(code)) { + return false; + } + + const secret = decryptSecret(record.secretEnc, record.userId); + const step = currentStep(); + + for (const candidate of [step, step + TOTP_SKEW_STEPS, step - TOTP_SKEW_STEPS]) { + if (record.lastUsedStep !== null && candidate <= record.lastUsedStep) { + continue; + } + + if (!codesEqual(totpCode(secret, candidate), code)) { + continue; + } + + const consumed = await prisma.adminTotp.updateMany({ + where: { + userId: record.userId, + OR: [ + { lastUsedStep: null }, + { lastUsedStep: { lt: candidate } }, + ], + }, + data: { lastUsedStep: candidate }, + }); + + return consumed.count === 1; + } + + return false; +} + +async function consumeRecoveryCode( + record: TotpRecord, + recoveryCode: string +): Promise { + const hash = hashRecoveryCode(recoveryCode); + if (!record.recoveryHashes.includes(hash)) { + return false; + } + + const remainingHashes = record.recoveryHashes.filter( + value => value !== hash + ); + const consumed = await prisma.adminTotp.updateMany({ + where: { + userId: record.userId, + recoveryHashes: { equals: record.recoveryHashes }, + }, + data: { recoveryHashes: { set: remainingHashes } }, + }); + + return consumed.count === 1; +} + +export async function setupAdminTotp( + adminId: string +): Promise { + const existing = await loadTotp(adminId); + if (existing?.enabledAt) { + throw new AdminTotpAlreadyEnabledError(); + } + + const secret = randomBytes(20); + const secretBase32 = base32Encode(secret); + const recoveryCodes = generateRecoveryCodes(); + const secretEnc = encryptSecret(secret, adminId); + + await prisma.adminTotp.upsert({ + where: { userId: adminId }, + create: { + userId: adminId, + secretEnc, + enabledAt: null, + recoveryHashes: recoveryCodes.map(hashRecoveryCode), + lastUsedStep: null, + }, + update: { + secretEnc, + enabledAt: null, + recoveryHashes: recoveryCodes.map(hashRecoveryCode), + lastUsedStep: null, + }, + }); + + return { + otpauthUri: otpauthUri(adminId, secretBase32), + recoveryCodes, + }; +} + +export async function verifyAdminTotpSetup( + adminId: string, + code: string +): Promise { + assertVerificationAllowed(adminId); + + const record = await loadTotp(adminId); + if (!record) { + throw new AdminTotpNotConfiguredError(); + } + if (record.enabledAt) { + throw new AdminTotpAlreadyEnabledError(); + } + + if (!(await verifyTotpCode(record, code))) { + throw new AdminTotpInvalidCodeError(); + } + + const enabledAt = new Date(); + await prisma.adminTotp.update({ + where: { userId: adminId }, + data: { enabledAt }, + }); + clearVerificationAttempts(adminId); + + return enabledAt; +} + +export async function loginWithAdminTotp( + adminId: string, + claims: AdminJwtPayload, + input: AdminTotpLoginInput +): Promise { + assertVerificationAllowed(adminId); + + const record = await loadTotp(adminId); + if (!record?.enabledAt) { + throw new AdminTotpNotConfiguredError(); + } + + let verified = false; + if (input.code) { + verified = await verifyTotpCode(record, input.code); + } + if (!verified && input.recoveryCode) { + verified = await consumeRecoveryCode(record, input.recoveryCode); + } + + if (!verified) { + throw new AdminTotpInvalidCodeError(); + } + + clearVerificationAttempts(adminId); + + return { + accessToken: signAdminSessionToken(claims, 'verified'), + tokenType: 'Bearer', + expiresIn: envConfig.JWT_ACCESS_TOKEN_TTL_SECONDS, + }; +} diff --git a/src/modules/admin/admin.routes.ts b/src/modules/admin/admin.routes.ts index fbc53227..25fd93c5 100644 --- a/src/modules/admin/admin.routes.ts +++ b/src/modules/admin/admin.routes.ts @@ -51,6 +51,7 @@ import { prisma } from '../../utils/prisma.utils'; import { logger } from '../../utils/logger.utils'; import { invalidateKeyVestingCache } from '../vesting/vesting.service'; import { treasuryRouter } from '../treasury/treasury.routes'; +import admin2faRouter from './admin-2fa.routes'; import { adminFlagRouter } from '../flags/feature-flags.routes'; function isValidStellarAddress(address: string): boolean { @@ -124,6 +125,7 @@ function serializeTimelockAction(action: any) { const adminRouter = Router(); +adminRouter.use('/2fa', admin2faRouter); adminRouter.use(adminFlagRouter); adminRouter.patch('/creators/:id/metadata', httpUpdateCreatorMetadata); diff --git a/src/types/auth.types.ts b/src/types/auth.types.ts index 675efc66..f7aa2c36 100644 --- a/src/types/auth.types.ts +++ b/src/types/auth.types.ts @@ -1,5 +1,17 @@ // types/auth.types.ts - Add this to your backend types import { Request, Response, NextFunction } from 'express'; +import type { JwtPayload } from 'jsonwebtoken'; + +export type AdminTwoFactorStatus = 'pending_2fa' | 'verified'; + +export interface AdminJwtPayload extends JwtPayload { + sub?: string; + adminId?: string; + role?: string; + wallet?: string; + twoFactorStatus?: AdminTwoFactorStatus; +} + export interface GoogleCredentials { googleId: string; email: string; diff --git a/src/utils/jwt.utils.ts b/src/utils/jwt.utils.ts index d7a4c291..f6fd115b 100644 --- a/src/utils/jwt.utils.ts +++ b/src/utils/jwt.utils.ts @@ -8,6 +8,10 @@ import jwt, { JwtPayload, SignOptions } from 'jsonwebtoken'; import { envConfig } from '../config'; +import type { + AdminJwtPayload, + AdminTwoFactorStatus, +} from '../types/auth.types'; export interface WalletAccessTokenPayload extends JwtPayload { sub: string; @@ -105,3 +109,43 @@ export function signJwt( } export const JwtError = JwtVerifyError; + +export function signAdminSessionToken( + payload: AdminJwtPayload, + twoFactorStatus: AdminTwoFactorStatus = 'pending_2fa', + expiresInSeconds: number = envConfig.JWT_ACCESS_TOKEN_TTL_SECONDS +): string { + const adminId = payload.adminId ?? payload.sub; + if (!adminId) { + throw new Error('Admin session token requires an admin id'); + } + + const { + adminId: _adminId, + sub: _sub, + role: _role, + twoFactorStatus: _twoFactorStatus, + iat: _iat, + exp: _exp, + nbf: _nbf, + jti: _jti, + iss: _iss, + aud: _aud, + ...claims + } = payload; + + return jwt.sign( + { + ...claims, + adminId, + role: 'admin', + twoFactorStatus, + }, + envConfig.JWT_SECRET, + { + expiresIn: expiresInSeconds, + issuer: envConfig.JWT_ISSUER, + subject: adminId, + } + ); +}