/**
 * Token Service
 * Handles JWT token generation and verification
 */
import jwt from "jsonwebtoken";
/** Pinned JWT algorithm — prevents algorithm-confusion / alg:none attacks. */
const JWT_ALGORITHM = "HS256";
export function createTokenService(config) {
    const expiresIn = config.expiresIn ?? "7d";
    // Fail closed only on a MISSING secret. Secret strength is a recommendation
    // surfaced once at startup (validateAuthSecretAtStartup) — we don't hard-fail a
    // short secret here, so an existing deployment keeps running and can rotate on
    // its own schedule.
    if (!config.secret) {
        throw new Error("SECRET_KEY is not configured for the auth token service.");
    }
    return {
        generateToken(payload) {
            return jwt.sign(payload, config.secret, { expiresIn, algorithm: JWT_ALGORITHM });
        },
        verifyToken(token) {
            try {
                const decoded = jwt.verify(token, config.secret, { algorithms: [JWT_ALGORITHM] });
                return decoded;
            }
            catch (error) {
                return null;
            }
        },
        decodeToken(token) {
            try {
                const decoded = jwt.decode(token);
                return decoded;
            }
            catch (error) {
                return null;
            }
        },
        generateUserToken({ user, role, session, tenant }) {
            const payload = {
                id: user.id,
                role_Id: role.id,
                sessionToken: session.token,
            };
            if (tenant) {
                payload.tenant_Id = tenant.id;
            }
            return this.generateToken(payload);
        },
    };
}
export default createTokenService;
//# sourceMappingURL=token.js.map