"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.SecurityService = void 0;
const api_locale_1 = require("@hed-hog/api-locale");
const common_1 = require("@nestjs/common");
const config_1 = require("@nestjs/config");
const argon2 = __importStar(require("argon2"));
const crypto_1 = require("crypto");
let SecurityService = class SecurityService {
    constructor(configService) {
        this.configService = configService;
    }
    getJwtSecret() {
        return this.configService.get('JWT_SECRET');
    }
    getValueWithPepper(value, pepper) {
        return value + (pepper || this.configService.get('PEPPER'));
    }
    hashWithPepper(value) {
        return this.hashSha256(this.getValueWithPepper(value));
    }
    randomOpaque(size = 32) {
        return (0, crypto_1.randomBytes)(size).toString('base64url');
    }
    hashSha256(value) {
        return (0, crypto_1.createHash)('sha256').update(value).digest('base64url');
    }
    hashArgon2(value, pepper) {
        return argon2.hash(this.getValueWithPepper(value, pepper));
    }
    async validatePassword(locale, credentials, password) {
        try {
            const peppered = this.getValueWithPepper(password);
            for (const { hash } of credentials) {
                if (await argon2.verify(hash, peppered))
                    return true;
            }
            return false;
        }
        catch (error) {
            throw new common_1.BadRequestException((0, api_locale_1.getLocaleText)('accessDenied', locale, 'Access denied.'));
        }
    }
    async verifyArgon2(value, hash, pepper) {
        try {
            const peppered = this.getValueWithPepper(value, pepper);
            return await argon2.verify(hash, peppered);
        }
        catch (error) {
            return false;
        }
    }
    encrypt(value, secret) {
        const encryptionSecret = this.resolveEncryptionSecret(secret);
        const salt = (0, crypto_1.randomBytes)(16);
        const key = (0, crypto_1.scryptSync)(encryptionSecret, salt, 32);
        const iv = (0, crypto_1.randomBytes)(12);
        const cipher = (0, crypto_1.createCipheriv)('aes-256-gcm', key, iv);
        const encrypted = Buffer.concat([cipher.update(value, 'utf8'), cipher.final()]);
        const authTag = cipher.getAuthTag();
        return [
            salt.toString('hex'),
            iv.toString('hex'),
            authTag.toString('hex'),
            encrypted.toString('hex')
        ].join(':');
    }
    decrypt(encryptedValue, secret) {
        try {
            const encryptionSecret = this.resolveEncryptionSecret(secret);
            const parts = encryptedValue.split(':');
            if (parts.length !== 4) {
                throw new Error(`Invalid encrypted format: expected 4 parts separated by ':', got ${parts.length} parts. Value: ${encryptedValue.substring(0, 50)}...`);
            }
            const salt = Buffer.from(parts[0], 'hex');
            const iv = Buffer.from(parts[1], 'hex');
            const authTag = Buffer.from(parts[2], 'hex');
            const ciphertext = Buffer.from(parts[3], 'hex');
            const key = (0, crypto_1.scryptSync)(encryptionSecret, salt, 32);
            const decipher = (0, crypto_1.createDecipheriv)('aes-256-gcm', key, iv);
            decipher.setAuthTag(authTag);
            const decrypted = Buffer.concat([decipher.update(ciphertext), decipher.final()]);
            return decrypted.toString('utf8');
        }
        catch (err) {
            throw new Error(`Failed to decrypt value: ${err.message}`);
        }
    }
    resolveEncryptionSecret(secret) {
        const encryptionSecret = secret || this.configService.get('ENCRYPTION_SECRET');
        if (!encryptionSecret || !String(encryptionSecret).trim()) {
            throw new Error('ENCRYPTION_SECRET is not configured.');
        }
        return encryptionSecret;
    }
    generateCode(length) {
        return Array.from(crypto.getRandomValues(new Uint8Array(length || 6)))
            .map(n => (n % 10).toString())
            .join('');
    }
};
exports.SecurityService = SecurityService;
exports.SecurityService = SecurityService = __decorate([
    (0, common_1.Injectable)(),
    __metadata("design:paramtypes", [config_1.ConfigService])
], SecurityService);
//# sourceMappingURL=security.service.js.map