"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.createStrictRateLimiter = exports.applySecurityMiddleware = void 0;
const helmet_1 = __importDefault(require("helmet"));
const cors_1 = __importDefault(require("cors"));
const express_rate_limit_1 = __importDefault(require("express-rate-limit"));
const env_1 = require("../../main/config/env");
const redis_rate_limit_store_1 = require("../../infrastructure/cache/redis-rate-limit-store");
const buildRateLimitStore = (windowMs, redis) => {
    if (!redis) {
        return undefined;
    }
    return new redis_rate_limit_store_1.RedisRateLimitStore(redis, windowMs);
};
const applySecurityMiddleware = (app, redis) => {
    app.use((0, helmet_1.default)({
        hsts: env_1.env.NODE_ENV === 'production'
            ? { maxAge: 31_536_000, includeSubDomains: true, preload: true }
            : false,
    }));
    const allowedOrigins = env_1.env.ALLOWED_ORIGINS.split(',').map((origin) => origin.trim());
    app.use((0, cors_1.default)({
        origin: (origin, callback) => {
            if (env_1.env.NODE_ENV === 'development' || !origin || allowedOrigins.includes(origin)) {
                callback(null, true);
                return;
            }
            callback(new Error('Not allowed by CORS'));
        },
        credentials: true,
    }));
    const defaultLimiter = (0, express_rate_limit_1.default)({
        windowMs: env_1.env.RATE_LIMIT_WINDOW_MS,
        max: env_1.env.RATE_LIMIT_MAX,
        standardHeaders: true,
        legacyHeaders: false,
        store: buildRateLimitStore(env_1.env.RATE_LIMIT_WINDOW_MS, redis),
        keyGenerator: (req) => req.ip ?? 'unknown',
    });
    app.use(defaultLimiter);
};
exports.applySecurityMiddleware = applySecurityMiddleware;
const createStrictRateLimiter = (windowMs, max, redis) => {
    return (0, express_rate_limit_1.default)({
        windowMs,
        max,
        standardHeaders: true,
        legacyHeaders: false,
        store: buildRateLimitStore(windowMs, redis),
        keyGenerator: (req) => req.ip ?? 'unknown',
    });
};
exports.createStrictRateLimiter = createStrictRateLimiter;
//# sourceMappingURL=security.middleware.js.map