feat(security): add phase8 hardening with rate limits, audit logs, and auth-first simulator flow
This commit is contained in:
31
Backend/middleware/security.ts
Normal file
31
Backend/middleware/security.ts
Normal file
@@ -0,0 +1,31 @@
|
||||
import type { NextFunction, Request, Response } from 'express';
|
||||
|
||||
type Bucket = {
|
||||
count: number;
|
||||
windowStart: number;
|
||||
};
|
||||
|
||||
const buckets = new Map<string, Bucket>();
|
||||
|
||||
export const rateLimit = (options: { keyPrefix: string; windowMs: number; max: number }) => {
|
||||
return (req: Request, res: Response, next: NextFunction): void => {
|
||||
const key = `${options.keyPrefix}:${req.ip ?? 'unknown'}`;
|
||||
const now = Date.now();
|
||||
const current = buckets.get(key);
|
||||
|
||||
if (!current || now - current.windowStart > options.windowMs) {
|
||||
buckets.set(key, { count: 1, windowStart: now });
|
||||
next();
|
||||
return;
|
||||
}
|
||||
|
||||
if (current.count >= options.max) {
|
||||
res.status(429).json({ message: 'Rate limit exceeded. Try again later.' });
|
||||
return;
|
||||
}
|
||||
|
||||
current.count += 1;
|
||||
buckets.set(key, current);
|
||||
next();
|
||||
};
|
||||
};
|
||||
Reference in New Issue
Block a user