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 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 | 22x 22x 22x 22x 22x 33x 27x 6x 6x 5x 5x 19x 19x 8x 8x 3x 3x 3x 5x 1x 1x 8x 7x 1x 1x 1x 1x 8x 8x 8x 8x 8x 1x 8x 8x 8x 8x 1x 7x 22x 35x 8x 8x 35x 22x 33x 33x 22x 33x 33x 22x 2x 2x 22x 33x 33x 33x 33x 33x 33x 33x 17x 33x 7x 2x 3x 5x 2x 4x 3x 33x 2x 33x 33x 33x 33x 1x 33x 33x 30x 30x 3x 3x 1x 2x 22x | /**
* Enhanced fetch utilities for GitLab MCP Server
*
* Node.js v24 compatible implementation using Undici's dispatcher pattern.
* Supports:
* - TLS verification bypass (SKIP_TLS_VERIFY)
* - Custom CA certificates (GITLAB_CA_CERT_PATH)
* - HTTP/HTTPS proxy support (HTTP_PROXY, HTTPS_PROXY)
* - Cookie authentication (GITLAB_AUTH_COOKIE_PATH)
* - OAuth per-request token context
* - Configurable timeout handling
*/
import * as fs from "fs";
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";
import { isOAuthEnabled, getTokenContext } from "../oauth/index";
// Dynamic require to avoid TypeScript analyzing complex undici types at compile time
/* eslint-disable no-undef, no-unused-vars */
const undici = require("undici") as {
Agent: new (opts?: Record<string, unknown>) => unknown;
ProxyAgent: new (opts: string | Record<string, unknown>) => unknown;
};
/* eslint-enable no-undef, no-unused-vars */
/**
* 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("#")) {
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;
}
}
/**
* 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;
}
}
/**
* Check if URL is a SOCKS proxy
*/
function isSocksProxy(url: string): boolean {
return url.startsWith("socks4://") || url.startsWith("socks5://") || url.startsWith("socks://");
}
/**
* Create Undici dispatcher for fetch requests
*/
function createDispatcher(): unknown {
const proxyUrl = HTTPS_PROXY ?? HTTP_PROXY;
// Build TLS options
const tlsOptions: Record<string, unknown> = {};
Iif (SKIP_TLS_VERIFY || NODE_TLS_REJECT_UNAUTHORIZED === "0") {
tlsOptions.rejectUnauthorized = false;
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");
}
}
const ca = loadCACertificate();
if (ca) {
tlsOptions.ca = ca;
}
const hasTlsConfig = Object.keys(tlsOptions).length > 0;
// SOCKS proxy not supported with native fetch
Iif (proxyUrl && isSocksProxy(proxyUrl)) {
logger.info(`Using SOCKS proxy: ${proxyUrl}`);
logger.warn("SOCKS proxy not supported with native fetch. Consider HTTP/HTTPS proxy.");
return undefined;
}
// HTTP/HTTPS proxy
Iif (proxyUrl) {
logger.info(`Using proxy: ${proxyUrl}`);
return new undici.ProxyAgent({
uri: proxyUrl,
requestTls: hasTlsConfig ? tlsOptions : undefined,
});
}
// Custom TLS config without proxy
if (hasTlsConfig) {
return new undici.Agent({ connect: tlsOptions });
}
return undefined;
}
/** Cached dispatcher */
let cachedDispatcher: unknown;
let dispatcherInitialized = false;
function getDispatcher(): unknown {
if (!dispatcherInitialized) {
cachedDispatcher = createDispatcher();
dispatcherInitialized = true;
}
return cachedDispatcher;
}
/**
* Base HTTP headers
*/
export const DEFAULT_HEADERS: Record<string, string> = {
"User-Agent": "GitLab MCP Server",
"Content-Type": "application/json",
Accept: "application/json",
};
function getGitLabToken(): string | undefined {
Iif (isOAuthEnabled()) {
const context = getTokenContext();
return context?.gitlabToken;
}
return GITLAB_TOKEN;
}
export function getAuthorizationHeader(): string | undefined {
const token = getGitLabToken();
return token ? `Bearer ${token}` : undefined;
}
/** @deprecated Use enhancedFetch() directly */
export function createFetchOptions(): Record<string, unknown> {
const dispatcher = getDispatcher();
return dispatcher ? { dispatcher } : {};
}
/**
* Enhanced fetch with GitLab support and Node.js v24 compatibility
*/
export async function enhancedFetch(url: string, options: RequestInit = {}): Promise<Response> {
const dispatcher = getDispatcher();
const cookieHeader = loadCookieHeader();
// For FormData, don't set Content-Type - let fetch set it with proper boundary
const isFormData = options.body instanceof FormData;
const baseHeaders = isFormData
? { "User-Agent": DEFAULT_HEADERS["User-Agent"], Accept: DEFAULT_HEADERS.Accept }
: { ...DEFAULT_HEADERS };
const headers: Record<string, string> = { ...baseHeaders };
const authHeader = getAuthorizationHeader();
if (authHeader) {
headers.Authorization = authHeader;
}
if (options.headers) {
if (options.headers instanceof Headers) {
options.headers.forEach((value, key) => {
headers[key] = value;
});
} else if (Array.isArray(options.headers)) {
for (const [key, value] of options.headers) {
headers[key] = value;
}
} else {
Object.assign(headers, options.headers);
}
}
if (cookieHeader) {
headers.Cookie = cookieHeader;
}
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), API_TIMEOUT_MS);
const fetchOptions: Record<string, unknown> = {
...options,
headers,
signal: controller.signal,
};
if (dispatcher) {
fetchOptions.dispatcher = dispatcher;
}
try {
const response = await fetch(url, fetchOptions as RequestInit);
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;
}
}
export function resetDispatcherCache(): void {
cachedDispatcher = undefined;
dispatcherInitialized = false;
}
|