"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.otpExpiryDate = exports.verifyAuthToken = exports.signAuthToken = exports.signAccessToken = exports.refreshTokenExpiryDate = exports.hashRefreshToken = exports.generateRefreshToken = exports.hashOtpCode = exports.generateOtpCode = exports.getJwtSecret = exports.REFRESH_TOKEN_EXPIRES_IN_DAYS = exports.ACCESS_TOKEN_EXPIRES_IN = exports.OTP_EXPIRES_IN_MINUTES = void 0;
const crypto_1 = __importDefault(require("crypto"));
const jsonwebtoken_1 = __importDefault(require("jsonwebtoken"));
const OTP_LENGTH = 6;
exports.OTP_EXPIRES_IN_MINUTES = Number(process.env.OTP_EXPIRES_IN_MINUTES || 10);
exports.ACCESS_TOKEN_EXPIRES_IN = (process.env.ACCESS_TOKEN_EXPIRES_IN ||
    process.env.JWT_EXPIRES_IN ||
    "15m");
exports.REFRESH_TOKEN_EXPIRES_IN_DAYS = Number(process.env.REFRESH_TOKEN_EXPIRES_IN_DAYS || 30);
const getJwtSecret = () => {
    const secret = process.env.JWT_SECRET;
    if (secret)
        return secret;
    if (process.env.NODE_ENV === "production") {
        throw new Error("JWT_SECRET is required in production.");
    }
    return "dev-only-change-this-jwt-secret";
};
exports.getJwtSecret = getJwtSecret;
const generateOtpCode = () => {
    const max = 10 ** OTP_LENGTH;
    return crypto_1.default.randomInt(0, max).toString().padStart(OTP_LENGTH, "0");
};
exports.generateOtpCode = generateOtpCode;
const hashOtpCode = (code) => {
    return crypto_1.default.createHash("sha256").update(code).digest("hex");
};
exports.hashOtpCode = hashOtpCode;
const generateRefreshToken = () => crypto_1.default.randomBytes(64).toString("hex");
exports.generateRefreshToken = generateRefreshToken;
const hashRefreshToken = (token) => {
    return crypto_1.default.createHash("sha256").update(token).digest("hex");
};
exports.hashRefreshToken = hashRefreshToken;
const refreshTokenExpiryDate = () => {
    return new Date(Date.now() + exports.REFRESH_TOKEN_EXPIRES_IN_DAYS * 24 * 60 * 60 * 1000);
};
exports.refreshTokenExpiryDate = refreshTokenExpiryDate;
const signAccessToken = (payload) => {
    return jsonwebtoken_1.default.sign(payload, (0, exports.getJwtSecret)(), {
        expiresIn: exports.ACCESS_TOKEN_EXPIRES_IN,
    });
};
exports.signAccessToken = signAccessToken;
exports.signAuthToken = exports.signAccessToken;
const verifyAuthToken = (token) => {
    return jsonwebtoken_1.default.verify(token, (0, exports.getJwtSecret)());
};
exports.verifyAuthToken = verifyAuthToken;
const otpExpiryDate = () => new Date(Date.now() + exports.OTP_EXPIRES_IN_MINUTES * 60 * 1000);
exports.otpExpiryDate = otpExpiryDate;
//# sourceMappingURL=authSecurity.js.map