Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions prisma/schema/admin-totp.prisma
Original file line number Diff line number Diff line change
@@ -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")
}
Original file line number Diff line number Diff line change
@@ -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")
);
2 changes: 2 additions & 0 deletions src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down Expand Up @@ -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);
Expand Down
57 changes: 56 additions & 1 deletion src/middlewares/admin-guard.middleware.test.ts
Original file line number Diff line number Diff line change
@@ -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';

Expand Down Expand Up @@ -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();
});
});
45 changes: 38 additions & 7 deletions src/middlewares/admin-guard.middleware.ts
Original file line number Diff line number Diff line change
@@ -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 ')) {
Expand All @@ -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) {
Expand All @@ -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);
}
105 changes: 105 additions & 0 deletions src/modules/admin/admin-2fa.controllers.ts
Original file line number Diff line number Diff line change
@@ -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<void> {
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<void> {
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<void> {
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);
}
}
45 changes: 45 additions & 0 deletions src/modules/admin/admin-2fa.routes.ts
Original file line number Diff line number Diff line change
@@ -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;
Loading
Loading