From 402b5b6810a66f5852dec6351782d2792afd4cf1 Mon Sep 17 00:00:00 2001 From: Ho Ngoc Hai Date: Wed, 8 Apr 2026 04:01:21 +0700 Subject: [PATCH] =?UTF-8?q?fix(auth):=20remove=20hardcoded=20JWT=20fallbac?= =?UTF-8?q?k=20secret=20=E2=80=94=20fail=20fast=20on=20missing=20env=20var?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The auth module fell back to a publicly-known secret string when JWT_SECRET was unset, creating a critical authentication bypass risk. Both jwt.strategy.ts and auth.module.ts now throw at startup if JWT_SECRET is missing. Co-Authored-By: Paperclip --- .env.example | 2 +- apps/api/src/modules/auth/auth.module.ts | 8 +++++++- .../auth/infrastructure/strategies/jwt.strategy.ts | 7 ++++++- 3 files changed, 14 insertions(+), 3 deletions(-) diff --git a/.env.example b/.env.example index c2ca01e..23d9d9c 100644 --- a/.env.example +++ b/.env.example @@ -46,7 +46,7 @@ API_PORT=3000 NODE_ENV=development # ----------------------------------------------------------------------------- -# JWT / Auth +# JWT / Auth (REQUIRED — app will not start without JWT_SECRET) # ----------------------------------------------------------------------------- JWT_SECRET=your_jwt_secret_change_me JWT_EXPIRES_IN=15m diff --git a/apps/api/src/modules/auth/auth.module.ts b/apps/api/src/modules/auth/auth.module.ts index ed45c0e..843eea5 100644 --- a/apps/api/src/modules/auth/auth.module.ts +++ b/apps/api/src/modules/auth/auth.module.ts @@ -39,7 +39,13 @@ const QueryHandlers = [GetProfileHandler, GetAgentByUserIdHandler]; CqrsModule, PassportModule, JwtModule.register({ - secret: process.env['JWT_SECRET'] || 'goodgo-jwt-secret-change-in-production', + secret: (() => { + const secret = process.env['JWT_SECRET']; + if (!secret) { + throw new Error('JWT_SECRET environment variable is required'); + } + return secret; + })(), signOptions: { expiresIn: '15m' }, }), ], diff --git a/apps/api/src/modules/auth/infrastructure/strategies/jwt.strategy.ts b/apps/api/src/modules/auth/infrastructure/strategies/jwt.strategy.ts index ac3a810..621a06a 100644 --- a/apps/api/src/modules/auth/infrastructure/strategies/jwt.strategy.ts +++ b/apps/api/src/modules/auth/infrastructure/strategies/jwt.strategy.ts @@ -6,10 +6,15 @@ import { type JwtPayload } from '../services/token.service'; @Injectable() export class JwtStrategy extends PassportStrategy(Strategy) { constructor() { + const jwtSecret = process.env['JWT_SECRET']; + if (!jwtSecret) { + throw new Error('JWT_SECRET environment variable is required'); + } + super({ jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(), ignoreExpiration: false, - secretOrKey: process.env['JWT_SECRET'] || 'goodgo-jwt-secret-change-in-production', + secretOrKey: jwtSecret, }); }