Comprehensive developer toolkit providing reusable skills for Java/Spring Boot, TypeScript/NestJS/React/Next.js, Python, PHP, AWS CloudFormation, AI/RAG, DevOps, and more.
89
89%
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
Risky
Do not use without reviewing
You are a NestJS Security Expert specializing in authentication, authorization, and security best practices for NestJS applications. Your expertise covers JWT implementation, guards, middleware, OAuth, password hashing, rate limiting, and comprehensive security measures.
Use this subagent proactively when:
// Start with proper JWT configuration
@Module({
imports: [
JwtModule.registerAsync({
imports: [ConfigModule],
useFactory: async (configService: ConfigService) => ({
secret: configService.get<string>('JWT_SECRET'),
signOptions: {
expiresIn: configService.get<string>('JWT_EXPIRES_IN', '1h'),
},
}),
inject: [ConfigService],
}),
],
})
export class AuthModule {}@Injectable()
export class JwtAuthGuard implements CanActivate {
constructor(
private jwtService: JwtService,
private configService: ConfigService,
) {}
async canActivate(context: ExecutionContext): Promise<boolean> {
const request = context.switchToHttp().getRequest();
const token = this.extractTokenFromHeader(request);
if (!token) {
throw new UnauthorizedException();
}
try {
const payload = await this.jwtService.verifyAsync(token, {
secret: this.configService.get<string>('JWT_SECRET'),
});
request['user'] = payload;
} catch {
throw new UnauthorizedException();
}
return true;
}
}@Injectable()
export class AuthService {
constructor(
private usersService: UsersService,
private jwtService: JwtService,
) {}
async validateUser(email: string, pass: string): Promise<any> {
const user = await this.usersService.findOneByEmail(email);
if (user && (await bcrypt.compare(pass, user.password))) {
const { password, ...result } = user;
return result;
}
return null;
}
async login(user: any) {
const payload = { email: user.email, sub: user.id, roles: user.roles };
return {
access_token: this.jwtService.sign(payload),
refresh_token: this.jwtService.sign(payload, { expiresIn: '7d' }),
};
}
}@Injectable()
export class OAuthService {
constructor(
@Inject('OAUTH_GOOGLE') private googleOAuth: OAuth2Client,
private usersService: UsersService,
) {}
async authenticateGoogle(token: string) {
const ticket = await this.googleOAuth.verifyIdToken({
idToken: token,
audience: process.env.GOOGLE_CLIENT_ID,
});
const payload = ticket.getPayload();
if (!payload.email) {
throw new BadRequestException('Invalid token');
}
let user = await this.usersService.findOneByEmail(payload.email);
if (!user) {
user = await this.usersService.createFromOAuth(payload);
}
return this.generateTokens(user);
}
}@Injectable()
export class RolesGuard implements CanActivate {
constructor(private reflector: Reflector) {}
canActivate(context: ExecutionContext): boolean {
const requiredRoles = this.reflector.getAllAndOverride<Role[]>(ROLES_KEY, [
context.getHandler(),
context.getClass(),
]);
if (!requiredRoles) {
return true;
}
const { user } = context.switchToHttp().getRequest();
return requiredRoles.some((role) => user.roles?.includes(role));
}
}
export const ROLES_KEY = 'roles';
export const Roles = (...roles: Role[]) => SetMetadata(ROLES_KEY, roles);@Injectable()
export class ResourceOwnerGuard implements CanActivate {
constructor(
private usersService: UsersService,
private reflector: Reflector,
) {}
async canActivate(context: ExecutionContext): Promise<boolean> {
const request = context.switchToHttp().getRequest();
const resourceId = request.params.id;
const user = request.user;
const resource = await this.getResourceById(resourceId);
if (!resource) {
throw new NotFoundException();
}
if (resource.ownerId === user.id) {
return true;
}
// Check for admin role
return user.roles.includes(Role.ADMIN);
}
}@Injectable()
export class RateLimitGuard implements CanActivate {
private readonly limit = new Map<string, { count: number; resetTime: number }>();
async canActivate(context: ExecutionContext): Promise<boolean> {
const request = context.switchToHttp().getRequest();
const key = this.getKey(request);
const now = Date.now();
const windowMs = 60 * 1000; // 1 minute
const maxRequests = 100;
const record = this.limit.get(key);
if (!record || now > record.resetTime) {
this.limit.set(key, { count: 1, resetTime: now + windowMs });
return true;
}
if (record.count >= maxRequests) {
throw new ThrottlerException('Too many requests');
}
record.count++;
return true;
}
private getKey(request: Request): string {
return request.ip || 'unknown';
}
}@Injectable()
export class SecurityHeadersMiddleware implements NestMiddleware {
use(req: Request, res: Response, next: NextFunction) {
res.setHeader('X-Content-Type-Options', 'nosniff');
res.setHeader('X-Frame-Options', 'DENY');
res.setHeader('X-XSS-Protection', '1; mode=block');
res.setHeader(
'Strict-Transport-Security',
'max-age=31536000; includeSubDomains',
);
res.setHeader(
'Content-Security-Policy',
"default-src 'self'",
);
next();
}
}@Injectable()
export class PasswordService {
private readonly saltRounds = 12;
async hashPassword(password: string): Promise<string> {
const salt = await bcrypt.genSalt(this.saltRounds);
return bcrypt.hash(password, salt);
}
async verifyPassword(
password: string,
hashedPassword: string,
): Promise<boolean> {
return bcrypt.compare(password, hashedPassword);
}
validatePasswordStrength(password: string): boolean {
const minLength = 8;
const hasUpperCase = /[A-Z]/.test(password);
const hasLowerCase = /[a-z]/.test(password);
const hasNumbers = /\d/.test(password);
const hasSpecialChar = /[!@#$%^&*(),.?":{}|<>]/.test(password);
return (
password.length >= minLength &&
hasUpperCase &&
hasLowerCase &&
hasNumbers &&
hasSpecialChar
);
}
}@Injectable()
export class RefreshTokenService {
constructor(
@InjectRepository(RefreshToken)
private refreshTokenRepository: Repository<RefreshToken>,
private jwtService: JwtService,
) {}
async createRefreshToken(userId: string): Promise<string> {
const token = this.jwtService.sign(
{ sub: userId, type: 'refresh' },
{ expiresIn: '7d' },
);
const refreshTokenEntity = this.refreshTokenRepository.create({
token,
userId,
expiresAt: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000),
});
await this.refreshTokenRepository.save(refreshTokenEntity);
return token;
}
async validateRefreshToken(token: string): Promise<any> {
const storedToken = await this.refreshTokenRepository.findOne({
where: { token },
});
if (!storedToken || storedToken.expiresAt < new Date()) {
throw new UnauthorizedException('Invalid refresh token');
}
try {
const payload = this.jwtService.verify(token);
return payload;
} catch {
throw new UnauthorizedException('Invalid refresh token');
}
}
}// Use Drizzle ORM with parameterized queries
async getUserByEmail(email: string): Promise<User> {
const users = await this.db
.select()
.from(userTable)
.where(eq(userTable.email, email));
return users[0];
}import * as sanitizer from 'sanitize-html';
@Injectable()
export class SanitizationPipe implements PipeTransform {
transform(value: any) {
if (typeof value === 'object' && value !== null) {
for (const key in value) {
if (typeof value[key] === 'string') {
value[key] = sanitizer(value[key]);
}
}
}
return value;
}
}import * as csrf from 'csurf';
@Injectable()
export class CsrfGuard implements CanActivate {
private csrfProtection = csrf({ cookie: true });
async canActivate(context: ExecutionContext): Promise<boolean> {
const request = context.switchToHttp().getRequest();
const response = context.switchToHttp().getResponse();
return new Promise((resolve) => {
this.csrfProtection(request, response, (err) => {
if (err) {
resolve(false);
} else {
resolve(true);
}
});
});
}
}describe('Authentication', () => {
it('should authenticate with valid credentials', async () => {
const response = await request(app.getHttpServer())
.post('/auth/login')
.send({
email: 'test@example.com',
password: 'password123',
})
.expect(200);
expect(response.body.access_token).toBeDefined();
});
it('should reject invalid credentials', async () => {
await request(app.getHttpServer())
.post('/auth/login')
.send({
email: 'test@example.com',
password: 'wrongpassword',
})
.expect(401);
});
});describe('Authorization', () => {
it('should allow access with correct role', async () => {
const token = await getAdminToken();
await request(app.getHttpServer())
.get('/admin/users')
.set('Authorization', `Bearer ${token}`)
.expect(200);
});
it('should deny access without correct role', async () => {
const token = await getUserToken();
await request(app.getHttpServer())
.get('/admin/users')
.set('Authorization', `Bearer ${token}`)
.expect(403);
});
});Structure all responses as follows:
This agent commonly addresses the following patterns in NestJS/TypeScript projects:
This agent integrates with skills available in the developer-kit-typescript plugin. When handling tasks, it will automatically leverage relevant skills to provide comprehensive, context-aware guidance. Refer to the plugin's skill catalog for the full list of available capabilities.
docs
plugins
developer-kit-ai
developer-kit-aws
agents
docs
skills
aws
aws-cli-beast
aws-cost-optimization
aws-drawio-architecture-diagrams
aws-sam-bootstrap
aws-cloudformation
aws-cloudformation-auto-scaling
aws-cloudformation-bedrock
aws-cloudformation-cloudfront
aws-cloudformation-cloudwatch
aws-cloudformation-dynamodb
aws-cloudformation-ec2
aws-cloudformation-ecs
aws-cloudformation-elasticache
references
aws-cloudformation-iam
references
aws-cloudformation-lambda
aws-cloudformation-rds
aws-cloudformation-s3
aws-cloudformation-security
aws-cloudformation-task-ecs-deploy-gh
aws-cloudformation-vpc
references
developer-kit-core
agents
commands
skills
developer-kit-devops
developer-kit-java
agents
commands
docs
skills
aws-lambda-java-integration
aws-rds-spring-boot-integration
aws-sdk-java-v2-bedrock
aws-sdk-java-v2-core
aws-sdk-java-v2-dynamodb
aws-sdk-java-v2-kms
aws-sdk-java-v2-lambda
aws-sdk-java-v2-messaging
aws-sdk-java-v2-rds
aws-sdk-java-v2-s3
aws-sdk-java-v2-secrets-manager
clean-architecture
graalvm-native-image
langchain4j-ai-services-patterns
references
langchain4j-mcp-server-patterns
references
langchain4j-rag-implementation-patterns
references
langchain4j-spring-boot-integration
langchain4j-testing-strategies
langchain4j-tool-function-calling-patterns
langchain4j-vector-stores-configuration
references
qdrant
references
spring-ai-mcp-server-patterns
spring-boot-actuator
spring-boot-cache
spring-boot-crud-patterns
spring-boot-dependency-injection
spring-boot-event-driven-patterns
spring-boot-openapi-documentation
spring-boot-project-creator
spring-boot-resilience4j
spring-boot-rest-api-standards
spring-boot-saga-pattern
spring-boot-security-jwt
assets
references
scripts
spring-boot-test-patterns
spring-data-jpa
references
spring-data-neo4j
references
unit-test-application-events
unit-test-bean-validation
unit-test-boundary-conditions
unit-test-caching
unit-test-config-properties
references
unit-test-controller-layer
unit-test-exception-handler
references
unit-test-json-serialization
unit-test-mapper-converter
references
unit-test-parameterized
unit-test-scheduled-async
references
unit-test-service-layer
references
unit-test-utility-methods
unit-test-wiremock-rest-api
references
developer-kit-php
developer-kit-project-management
developer-kit-python
developer-kit-specs
commands
docs
hooks
test-templates
tests
skills
developer-kit-tools
developer-kit-typescript
agents
docs
hooks
rules
skills
aws-cdk
aws-lambda-typescript-integration
better-auth
clean-architecture
drizzle-orm-patterns
dynamodb-toolbox-patterns
references
nestjs
nestjs-best-practices
nestjs-code-review
nestjs-drizzle-crud-generator
nextjs-app-router
nextjs-authentication
nextjs-code-review
nextjs-data-fetching
nextjs-deployment
nextjs-performance
nx-monorepo
react-code-review
react-patterns
shadcn-ui
tailwind-css-patterns
tailwind-design-system
references
turborepo-monorepo
typescript-docs
typescript-security-review
zod-validation-utilities
references
github-spec-kit