"use strict";
/**
 * Auth Types and Configurations
 *
 * Type definitions and OAuth configurations for CLIProxy authentication.
 */
Object.defineProperty(exports, "__esModule", { value: true });
exports.getOAuthConfig = exports.getManagementOAuthCallbackPath = exports.getPasteCallbackStartPath = exports.getManagementAuthUrlPath = exports.CLIPROXY_AUTH_URL_PROVIDER_MAP = exports.CLIPROXY_CALLBACK_PROVIDER_MAP = exports.PROVIDER_TYPE_VALUES = exports.PROVIDER_AUTH_PREFIXES = exports.OAUTH_CONFIGS = exports.OAUTH_CALLBACK_PORTS = exports.toKiroManagementMethod = exports.getKiroCLIAuthArgs = exports.getKiroCLIAuthFlag = exports.getKiroCallbackPort = exports.isKiroDeviceCodeMethod = exports.normalizeKiroIDCFlow = exports.normalizeKiroAuthMethod = exports.isKiroIDCFlow = exports.isKiroCLIAuthMethod = exports.isKiroAuthMethod = exports.DEFAULT_KIRO_AUTH_METHOD = exports.DEFAULT_KIRO_IDC_FLOW = exports.KIRO_IDC_FLOWS = exports.KIRO_CLI_AUTH_METHODS = exports.KIRO_AUTH_METHODS = void 0;
const provider_capabilities_1 = require("../provider-capabilities");
/**
 * Kiro authentication methods supported by CLIProxyAPIPlus.
 * - aws: AWS Builder ID via Device Code flow
 * - aws-authcode: AWS Builder ID via Authorization Code flow (CLI flag only)
 * - google: Social OAuth via Google
 * - github: Social OAuth via GitHub (management API only)
 * - idc: IAM Identity Center (IDC) via CLI flags with start URL + region
 */
exports.KIRO_AUTH_METHODS = ['aws', 'aws-authcode', 'google', 'github', 'idc'];
/** CLI binary supports these Kiro methods directly via flags. */
exports.KIRO_CLI_AUTH_METHODS = ['aws', 'aws-authcode', 'google', 'idc'];
exports.KIRO_IDC_FLOWS = ['authcode', 'device'];
exports.DEFAULT_KIRO_IDC_FLOW = 'authcode';
/** Default Kiro method for CCS UX and AWS Organization support. */
exports.DEFAULT_KIRO_AUTH_METHOD = 'aws';
function isKiroAuthMethod(value) {
    return exports.KIRO_AUTH_METHODS.includes(value);
}
exports.isKiroAuthMethod = isKiroAuthMethod;
function isKiroCLIAuthMethod(value) {
    return exports.KIRO_CLI_AUTH_METHODS.includes(value);
}
exports.isKiroCLIAuthMethod = isKiroCLIAuthMethod;
function isKiroIDCFlow(value) {
    return exports.KIRO_IDC_FLOWS.includes(value);
}
exports.isKiroIDCFlow = isKiroIDCFlow;
function normalizeKiroAuthMethod(value) {
    if (!value)
        return exports.DEFAULT_KIRO_AUTH_METHOD;
    const normalized = value.trim().toLowerCase();
    return isKiroAuthMethod(normalized) ? normalized : exports.DEFAULT_KIRO_AUTH_METHOD;
}
exports.normalizeKiroAuthMethod = normalizeKiroAuthMethod;
function normalizeKiroIDCFlow(value) {
    if (!value)
        return exports.DEFAULT_KIRO_IDC_FLOW;
    const normalized = value.trim().toLowerCase();
    return isKiroIDCFlow(normalized) ? normalized : exports.DEFAULT_KIRO_IDC_FLOW;
}
exports.normalizeKiroIDCFlow = normalizeKiroIDCFlow;
function isKiroDeviceCodeMethod(method, options) {
    if (method === 'aws') {
        return true;
    }
    if (method === 'idc') {
        return normalizeKiroIDCFlow(options?.idcFlow) === 'device';
    }
    return false;
}
exports.isKiroDeviceCodeMethod = isKiroDeviceCodeMethod;
function getKiroCallbackPort(method, options) {
    return isKiroDeviceCodeMethod(method, options) ? null : 9876;
}
exports.getKiroCallbackPort = getKiroCallbackPort;
function getKiroCLIAuthFlag(method) {
    switch (method) {
        case 'aws':
            return '--kiro-aws-login';
        case 'aws-authcode':
            return '--kiro-aws-authcode';
        case 'google':
            return '--kiro-google-login';
        case 'idc':
            return '--kiro-idc-login';
    }
}
exports.getKiroCLIAuthFlag = getKiroCLIAuthFlag;
function getKiroCLIAuthArgs(method, options) {
    if (method !== 'idc') {
        return [getKiroCLIAuthFlag(method)];
    }
    const startUrl = options?.idcStartUrl?.trim();
    if (!startUrl) {
        throw new Error('Kiro IDC login requires --kiro-idc-start-url');
    }
    const args = [getKiroCLIAuthFlag('idc'), '--kiro-idc-start-url', startUrl];
    const region = options?.idcRegion?.trim();
    if (region) {
        args.push('--kiro-idc-region', region);
    }
    args.push('--kiro-idc-flow', normalizeKiroIDCFlow(options?.idcFlow));
    return args;
}
exports.getKiroCLIAuthArgs = getKiroCLIAuthArgs;
/**
 * Kiro method for CLIProxyAPI management endpoint:
 * GET /v0/management/kiro-auth-url?method=<value>
 */
function toKiroManagementMethod(method) {
    switch (method) {
        case 'google':
            return 'google';
        case 'github':
            return 'github';
        case 'idc':
            return null;
        case 'aws-authcode':
            return 'aws';
        case 'aws':
        default:
            return 'aws';
    }
}
exports.toKiroManagementMethod = toKiroManagementMethod;
/**
 * OAuth callback ports used by CLIProxyAPI (hardcoded in binary)
 * See: https://github.com/router-for-me/CLIProxyAPI/tree/main/internal/auth
 *
 * OAuth flow types per provider:
 * - Gemini: Authorization Code Flow with local callback server on port 8085
 * - Codex:  Authorization Code Flow with local callback server on port 1455
 * - Agy:    Authorization Code Flow with local callback server on port 51121
 * - iFlow:  Authorization Code Flow with local callback server on port 11451
 * - Claude: Authorization Code Flow with local callback server on port 54545 (Anthropic OAuth)
 * - Kiro:   Device Code Flow (polling-based, NO callback port needed)
 * - Qwen:   Device Code Flow (polling-based, NO callback port needed)
 * - GHCP:   Device Code Flow (polling-based, NO callback port needed)
 * - Kimi:   Device Code Flow (polling-based, NO callback port needed)
 * - Cursor: Device-style browser polling (NO callback port needed)
 * - GitLab: Authorization Code Flow with callback server on port 17171
 * - CodeBuddy: Device-style browser polling (NO callback port needed)
 * - Kilo: Device Code Flow (polling-based, NO callback port needed)
 */
exports.OAUTH_CALLBACK_PORTS = provider_capabilities_1.CLIPROXY_PROVIDER_IDS.reduce((acc, provider) => {
    const callbackPort = (0, provider_capabilities_1.getOAuthCallbackPort)(provider);
    if (callbackPort !== null) {
        acc[provider] = callbackPort;
    }
    return acc;
}, {});
/**
 * OAuth configurations per provider
 * Note: CLIProxyAPI handles actual OAuth - these are for display/manual flow
 */
exports.OAUTH_CONFIGS = {
    gemini: {
        provider: 'gemini',
        displayName: 'Google Gemini',
        authUrl: 'https://accounts.google.com/o/oauth2/v2/auth',
        scopes: ['https://www.googleapis.com/auth/generative-language'],
        authFlag: '--login',
    },
    codex: {
        provider: 'codex',
        displayName: 'Codex',
        authUrl: 'https://auth.openai.com/authorize',
        scopes: ['openid', 'profile'],
        authFlag: '--codex-login',
    },
    agy: {
        provider: 'agy',
        displayName: 'Antigravity',
        authUrl: 'https://antigravity.ai/oauth/authorize',
        scopes: ['api'],
        authFlag: '--antigravity-login',
    },
    qwen: {
        provider: 'qwen',
        displayName: 'Qwen Code',
        authUrl: 'https://chat.qwen.ai/api/v1/oauth2/device/code',
        scopes: ['openid', 'profile', 'email', 'model.completion'],
        authFlag: '--qwen-login',
    },
    iflow: {
        provider: 'iflow',
        displayName: 'iFlow',
        authUrl: 'https://iflow.cn/oauth',
        scopes: ['phone', 'profile', 'email'],
        authFlag: '--iflow-login',
    },
    kiro: {
        provider: 'kiro',
        displayName: 'Kiro (AWS)',
        authUrl: 'https://oidc.us-east-1.amazonaws.com',
        scopes: ['codewhisperer:completions', 'codewhisperer:conversations'],
        // Default to AWS Builder ID device code flow for better compatibility.
        // Other Kiro methods are selected at runtime via OAuthOptions.kiroMethod.
        authFlag: '--kiro-aws-login',
    },
    ghcp: {
        provider: 'ghcp',
        displayName: 'GitHub Copilot (OAuth)',
        authUrl: 'https://github.com/login/device/code',
        scopes: ['copilot'],
        authFlag: '--github-copilot-login',
    },
    claude: {
        provider: 'claude',
        displayName: 'Claude (Anthropic)',
        authUrl: 'https://console.anthropic.com/oauth/authorize',
        scopes: ['user:inference', 'user:profile'],
        authFlag: '--claude-login',
    },
    kimi: {
        provider: 'kimi',
        displayName: 'Kimi (Moonshot)',
        authUrl: 'https://auth.kimi.com/api/oauth/device_authorization',
        scopes: ['api'],
        authFlag: '--kimi-login',
    },
    cursor: {
        provider: 'cursor',
        displayName: 'Cursor',
        authUrl: 'https://cursor.com/loginDeepControl',
        scopes: [],
        authFlag: '--cursor-login',
    },
    gitlab: {
        provider: 'gitlab',
        displayName: 'GitLab Duo',
        authUrl: 'https://gitlab.com/oauth/authorize',
        scopes: ['api', 'read_user'],
        authFlag: '--gitlab-login',
    },
    codebuddy: {
        provider: 'codebuddy',
        displayName: 'CodeBuddy (Tencent)',
        authUrl: 'https://copilot.tencent.com/v2/plugin/auth/state',
        scopes: [],
        authFlag: '--codebuddy-login',
    },
    kilo: {
        provider: 'kilo',
        displayName: 'Kilo AI',
        authUrl: 'https://api.kilo.ai/api/device-auth/codes',
        scopes: [],
        authFlag: '--kilo-login',
    },
};
/**
 * Provider-specific auth file prefixes (fallback detection)
 * CLIProxyAPI names auth files with provider prefix (e.g., "antigravity-user@email.json")
 * Note: Gemini tokens may NOT have prefix - CLIProxyAPI uses {email}-{projectID}.json format
 */
exports.PROVIDER_AUTH_PREFIXES = (0, provider_capabilities_1.buildProviderMap)((provider) => [...(0, provider_capabilities_1.getProviderAuthFilePrefixes)(provider)]);
/**
 * Provider type values inside token JSON files
 * CLIProxyAPI sets "type" field in token JSON (e.g., {"type": "gemini"})
 */
exports.PROVIDER_TYPE_VALUES = (0, provider_capabilities_1.buildProviderMap)((provider) => [...(0, provider_capabilities_1.getProviderTokenTypeValues)(provider)]);
/**
 * Maps CCS provider names to CLIProxyAPI callback provider names
 * Used when submitting OAuth callbacks to CLIProxyAPI management endpoint
 */
exports.CLIPROXY_CALLBACK_PROVIDER_MAP = (0, provider_capabilities_1.buildProviderMap)((provider) => (0, provider_capabilities_1.getCLIProxyCallbackProviderName)(provider));
/**
 * Maps CCS provider names to CLIProxyAPI auth-url endpoint prefixes.
 * Used for GET /v0/management/${prefix}-auth-url endpoints.
 * These differ from callback names for some providers (e.g., gemini-cli vs gemini).
 */
exports.CLIPROXY_AUTH_URL_PROVIDER_MAP = (0, provider_capabilities_1.buildProviderMap)((provider) => (0, provider_capabilities_1.getCLIProxyAuthUrlProviderName)(provider));
function getManagementAuthUrlPath(provider) {
    const authUrlProvider = exports.CLIPROXY_AUTH_URL_PROVIDER_MAP[provider] || provider;
    return `/v0/management/${authUrlProvider}-auth-url?is_webui=true`;
}
exports.getManagementAuthUrlPath = getManagementAuthUrlPath;
function getPasteCallbackStartPath(provider, options) {
    if (provider === 'kiro') {
        const kiroMethod = options?.kiroMethod ?? normalizeKiroAuthMethod();
        if (kiroMethod === 'aws-authcode' || kiroMethod === 'idc') {
            return null;
        }
        const managementMethod = toKiroManagementMethod(kiroMethod);
        if (!managementMethod) {
            return null;
        }
        return `${getManagementAuthUrlPath(provider)}&method=${encodeURIComponent(managementMethod)}`;
    }
    return getManagementAuthUrlPath(provider);
}
exports.getPasteCallbackStartPath = getPasteCallbackStartPath;
function getManagementOAuthCallbackPath() {
    return '/v0/management/oauth-callback';
}
exports.getManagementOAuthCallbackPath = getManagementOAuthCallbackPath;
/**
 * Get OAuth config for provider
 */
function getOAuthConfig(provider) {
    const config = exports.OAUTH_CONFIGS[provider];
    if (!config) {
        throw new Error(`Unknown provider: ${provider}`);
    }
    return config;
}
exports.getOAuthConfig = getOAuthConfig;
//# sourceMappingURL=auth-types.js.map