All files / src/utils fetch.ts

80% Statements 68/85
66.03% Branches 35/53
100% Functions 8/8
80% Lines 68/85

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 20722x 22x 22x 22x 22x 22x 22x                             33x 27x     6x 6x 5x   5x 19x 19x   8x 8x 3x 3x 3x         5x   1x 1x                       35x 35x 35x                               35x 34x     1x 1x 1x 1x                   22x           22x 3x           22x         35x     35x 35x           35x                             35x 35x 1x 1x           35x                     22x 33x 33x     33x         33x 7x 2x 3x     5x         33x 2x       33x 33x 1x       33x             33x 33x 30x 30x   3x 3x 1x   2x      
import * as https from "https";
import * as fs from "fs";
import { HttpProxyAgent } from "http-proxy-agent";
import { HttpsProxyAgent } from "https-proxy-agent";
import { SocksProxyAgent } from "socks-proxy-agent";
import { logger } from "../logger";
import {
  SKIP_TLS_VERIFY,
  GITLAB_AUTH_COOKIE_PATH,
  GITLAB_CA_CERT_PATH,
  HTTP_PROXY,
  HTTPS_PROXY,
  NODE_TLS_REJECT_UNAUTHORIZED,
  GITLAB_TOKEN,
  API_TIMEOUT_MS,
} from "../config";
 
/**
 * Cookie handling - parse cookies from file and format for HTTP Cookie header
 */
function loadCookieHeader(): string | null {
  if (!GITLAB_AUTH_COOKIE_PATH) {
    return null;
  }
 
  try {
    const cookieString = fs.readFileSync(GITLAB_AUTH_COOKIE_PATH, "utf-8");
    const cookies: string[] = [];
 
    cookieString.split("\n").forEach(line => {
      const trimmed = line.trim();
      if (trimmed && !trimmed.startsWith("#")) {
        // Parse cookie line format: domain flag path secure expiration name value
        const parts = trimmed.split("\t");
        if (parts.length >= 7) {
          const name = parts[5];
          const value = parts[6];
          cookies.push(`${name}=${value}`);
        }
      }
    });
 
    return cookies.length > 0 ? cookies.join("; ") : null;
  } catch (error: unknown) {
    logger.warn({ err: error }, "Failed to load GitLab authentication cookies");
    return null;
  }
}
 
/**
 * Get proxy agent based on URL protocol
 */
function getProxyAgent():
  | HttpProxyAgent<string>
  | HttpsProxyAgent<string>
  | SocksProxyAgent
  | undefined {
  const proxyUrl = HTTPS_PROXY ?? HTTP_PROXY;
  Eif (!proxyUrl) {
    return undefined;
  }
 
  if (proxyUrl.startsWith("socks4://") || proxyUrl.startsWith("socks5://")) {
    return new SocksProxyAgent(proxyUrl);
  } else if (proxyUrl.startsWith("https://")) {
    return new HttpsProxyAgent(proxyUrl);
  } else {
    return new HttpProxyAgent(proxyUrl);
  }
}
 
/**
 * Load custom CA certificate
 */
function loadCACertificate(): Buffer | undefined {
  if (!GITLAB_CA_CERT_PATH) {
    return undefined;
  }
 
  try {
    const ca = fs.readFileSync(GITLAB_CA_CERT_PATH);
    logger.info(`Custom CA certificate loaded from ${GITLAB_CA_CERT_PATH}`);
    return ca;
  } catch (error: unknown) {
    logger.error({ err: error }, `Failed to load CA certificate from ${GITLAB_CA_CERT_PATH}`);
    return undefined;
  }
}
 
/**
 * HTTP headers and configuration
 */
export const DEFAULT_HEADERS: Record<string, string> = {
  "User-Agent": "GitLab MCP Server",
  "Content-Type": "application/json",
  Accept: "application/json",
};
 
if (GITLAB_TOKEN) {
  DEFAULT_HEADERS.Authorization = `Bearer ${GITLAB_TOKEN}`;
}
 
/**
 * Create fetch options with all features: TLS, proxy, cookies, CA certs
 */
export function createFetchOptions(): RequestInit & {
  agent?: HttpProxyAgent<string> | HttpsProxyAgent<string> | SocksProxyAgent | https.Agent;
} {
  const options: RequestInit & {
    agent?: HttpProxyAgent<string> | HttpsProxyAgent<string> | SocksProxyAgent | https.Agent;
  } = {};
 
  // Proxy agent
  const proxyAgent = getProxyAgent();
  Iif (proxyAgent) {
    options.agent = proxyAgent;
    logger.info(`Using proxy: ${HTTPS_PROXY ?? HTTP_PROXY}`);
  }
 
  // TLS configuration
  Iif (SKIP_TLS_VERIFY || NODE_TLS_REJECT_UNAUTHORIZED === "0") {
    const agent = new https.Agent({
      rejectUnauthorized: false,
    });
    options.agent = agent;
 
    if (SKIP_TLS_VERIFY) {
      logger.warn("TLS certificate verification disabled via SKIP_TLS_VERIFY");
    }
    if (NODE_TLS_REJECT_UNAUTHORIZED === "0") {
      logger.warn("TLS certificate verification disabled via NODE_TLS_REJECT_UNAUTHORIZED");
    }
  }
 
  // CA certificate
  const ca = loadCACertificate();
  if (ca) {
    if (!options.agent) {
      options.agent = new https.Agent({ ca });
    } else Eif (options.agent instanceof https.Agent) {
      options.agent.options.ca = ca;
    }
  }
 
  return options;
}
 
/**
 * Enhanced fetch function with full GitLab support:
 * - TLS verification bypass
 * - Cookie authentication
 * - Proxy support
 * - Custom CA certificates
 * - Configurable timeout handling
 */
export async function enhancedFetch(url: string, options: RequestInit = {}): Promise<Response> {
  const fetchOptions = createFetchOptions();
  const cookieHeader = loadCookieHeader();
 
  // Prepare headers
  const headers: Record<string, string> = {
    ...DEFAULT_HEADERS,
  };
 
  // Safely merge headers from options
  if (options.headers) {
    if (options.headers instanceof Headers) {
      options.headers.forEach((value, key) => {
        headers[key] = value;
      });
    } else {
      Object.assign(headers, options.headers);
    }
  }
 
  // Add cookies if available
  if (cookieHeader) {
    headers.Cookie = cookieHeader;
  }
 
  // Create timeout controller
  const controller = new AbortController();
  const timeoutId = setTimeout(() => {
    controller.abort();
  }, API_TIMEOUT_MS);
 
  // Merge all options with timeout signal
  const mergedOptions: RequestInit = {
    ...fetchOptions,
    ...options,
    headers,
    signal: controller.signal,
  };
 
  try {
    const response = await fetch(url, mergedOptions);
    clearTimeout(timeoutId);
    return response;
  } catch (error) {
    clearTimeout(timeoutId);
    if (error instanceof Error && error.name === "AbortError") {
      throw new Error(`GitLab API timeout after ${API_TIMEOUT_MS}ms`);
    }
    throw error;
  }
}