// engine/auth/middleware.ts — Auth middleware for hosted MCP requests (SPEC-161)
// Is a no-op when auth is not configured (local stdio mode).
// Never logs token values.
import { loadAuthConfig } from './config.js';
import { validateToken, extractBearerToken } from './token-validator.js';
import { resolveAllowedTools } from './scope-mapper.js';
/** Unauthenticated context returned when auth is disabled (stdio mode). */
const DISABLED_CONTEXT = {
    enabled: false,
    allowedTools: [],
};
/**
 * Evaluate an incoming Authorization header against the current auth config.
 *
 * Behavior:
 * - No auth config → returns disabled context (all tools allowed, no enforcement).
 * - Auth config present but no token → returns invalid context.
 * - Auth config present and token provided → validates and maps scopes to tools.
 *
 * This function is async because it loads config from disk on first call
 * (cached thereafter) and may call the introspection endpoint.
 */
export async function evaluateAuthContext(authorizationHeader) {
    const config = await loadAuthConfig();
    if (config === null) {
        return DISABLED_CONTEXT;
    }
    const token = extractBearerToken(authorizationHeader);
    if (!token) {
        return buildInvalidContext(config, 'Missing or malformed Authorization: Bearer <token> header');
    }
    const validation = await validateToken(token, config);
    if (!validation.valid) {
        return buildInvalidContext(config, validation.reason ?? 'Token validation failed');
    }
    const allowedTools = resolveAllowedTools(validation.scopes, config.scopeMappings);
    return {
        enabled: true,
        validation,
        allowedTools,
    };
}
/**
 * Check whether the caller is authorized to invoke a specific tool.
 * When auth is disabled (stdio mode), all tools are accessible.
 */
export function authorizeToolCall(toolName, context) {
    if (!context.enabled) {
        return true;
    }
    if (!context.validation?.valid) {
        return false;
    }
    return context.allowedTools.includes(toolName);
}
function buildInvalidContext(config, reason) {
    void config; // Config is loaded but only used to mark auth as enabled
    return {
        enabled: true,
        validation: { valid: false, scopes: [], reason },
        allowedTools: [],
    };
}
//# sourceMappingURL=middleware.js.map