import crypto from 'node:crypto';
export function requireAgentToken(config) {
    return async (request, reply) => {
        // Header-only for HTTP routes so the token never travels in a URL (logs/history).
        // The query-param fallback exists solely for the WebSocket route, which checks inline.
        const token = extractBearerHeader(request);
        if (!verifyAgentToken(config, token)) {
            await reply.code(401).send({ error: 'unauthorized' });
        }
    };
}
export function extractBearerHeader(request) {
    const auth = request.headers.authorization;
    return auth?.startsWith('Bearer ') ? auth.slice(7) : null;
}
export function verifyAgentToken(config, token) {
    if (!token || !config.agentToken) {
        return false;
    }
    const provided = Buffer.from(token);
    const expected = Buffer.from(config.agentToken);
    return provided.length === expected.length && crypto.timingSafeEqual(provided, expected);
}
export function extractBearerToken(request) {
    const auth = request.headers.authorization;
    if (auth?.startsWith('Bearer ')) {
        return auth.slice(7);
    }
    const query = request.query;
    if (typeof query.token === 'string') {
        return query.token;
    }
    return null;
}
//# sourceMappingURL=agentAuth.js.map