import { compare, compareSync, hashSync } from "bcryptjs";
export const DAEMON_PASSWORD_BCRYPT_COST = 12;
export function isBearerTokenValid(input) {
    return isBearerTokenValidSync(input);
}
export async function isBearerTokenValidAsync(input) {
    if (!input.password) {
        return true;
    }
    if (input.token === null) {
        return false;
    }
    return compare(input.token, input.password);
}
export function isBearerTokenValidSync(input) {
    if (!input.password) {
        return true;
    }
    if (input.token === null) {
        return false;
    }
    return compareSync(input.token, input.password);
}
export function hashDaemonPassword(password) {
    return hashSync(password, DAEMON_PASSWORD_BCRYPT_COST);
}
export function extractHttpBearerToken(value) {
    if (!value) {
        return null;
    }
    const [scheme, ...tokenParts] = value.trim().split(/\s+/);
    if (scheme !== "Bearer" || tokenParts.length !== 1) {
        return null;
    }
    return tokenParts[0] ?? null;
}
export function extractWsBearerProtocol(value) {
    if (!value) {
        return null;
    }
    for (const protocol of value.split(",")) {
        const trimmed = protocol.trim();
        const segments = trimmed.split(".");
        if (segments[0] === "paseo" && segments[1] === "bearer" && segments.length >= 3) {
            return trimmed;
        }
    }
    return null;
}
export function extractWsBearerToken(protocol) {
    if (!protocol) {
        return null;
    }
    const segments = protocol.split(".");
    if (segments[0] !== "paseo" || segments[1] !== "bearer" || segments.length < 3) {
        return null;
    }
    return segments.slice(2).join(".");
}
export function createRequireBearerMiddleware(auth, onReject) {
    const password = auth?.password;
    return (req, res, next) => {
        if (!password || shouldBypassBearerAuth(req.method, req.path)) {
            next();
            return;
        }
        void (async () => {
            try {
                const token = extractHttpBearerToken(req.header("authorization"));
                if (!(await isBearerTokenValidAsync({ password, token }))) {
                    onReject?.({
                        path: req.path,
                        method: req.method,
                        hasToken: token !== null,
                    });
                    res.status(401).json({ error: "Unauthorized" });
                    return;
                }
                next();
            }
            catch (error) {
                next(error);
            }
        })();
    };
}
export function shouldBypassBearerAuth(method, path) {
    if (method === "OPTIONS") {
        return true;
    }
    return path === "/api/health";
}
//# sourceMappingURL=auth.js.map