File size: 10,380 Bytes
3d01305
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4ebb914
3d01305
 
 
 
4ebb914
3d01305
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4779e44
 
 
 
3d01305
4779e44
 
3d01305
4779e44
3d01305
4779e44
 
 
 
 
 
 
 
 
3d01305
4779e44
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3d01305
 
 
 
 
 
 
 
 
 
 
 
 
 
45525c6
 
 
 
 
 
 
3d01305
 
 
 
 
 
 
 
6c928c9
3d01305
 
 
 
 
 
 
 
 
 
 
4ebb914
3d01305
 
 
4ebb914
3d01305
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4ebb914
3d01305
 
 
4ebb914
3d01305
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6c928c9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3d01305
 
 
 
 
 
 
 
 
6c928c9
 
 
 
 
 
 
3d01305
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4ebb914
 
 
 
 
 
 
 
 
 
3d01305
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4779e44
 
 
 
 
 
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
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
/**
 * CurlCliTransport β€” TLS transport using curl CLI subprocess.
 *
 * Extracted from codex-api.ts (curlPost) and curl-fetch.ts (execCurl).
 * Supports both streaming POST (SSE) and simple GET/POST.
 *
 * Used on macOS/Linux (curl-impersonate CLI) and as fallback on Windows (system curl).
 */

import { spawn, execFile } from "child_process";
import { resolveCurlBinary, getChromeTlsArgs, getProxyArgs, isImpersonate as curlIsImpersonate } from "./curl-binary.js";
import type { TlsTransport, TlsTransportResponse } from "./transport.js";

const STATUS_SEPARATOR = "\n__CURL_HTTP_STATUS__";
const HEADER_TIMEOUT_MS = 30_000;

export class CurlCliTransport implements TlsTransport {
  /**
   * Streaming POST β€” spawns curl with -i to capture headers + stream body.
   * Used for SSE requests to Codex Responses API.
   */
  post(
    url: string,
    headers: Record<string, string>,
    body: string,
    signal?: AbortSignal,
    timeoutSec?: number,
    proxyUrl?: string | null,
  ): Promise<TlsTransportResponse> {
    return new Promise((resolve, reject) => {
      const args = [
        ...getChromeTlsArgs(),
        ...resolveProxyArgs(proxyUrl),
        "-s", "-S",
        "--compressed",
        "-N",            // no output buffering (SSE)
        "-i",            // include response headers in stdout
        "-X", "POST",
        "--data-binary", "@-",  // read body from stdin
      ];

      if (timeoutSec) {
        args.push("--max-time", String(timeoutSec));
      }

      for (const [key, value] of Object.entries(headers)) {
        args.push("-H", `${key}: ${value}`);
      }
      // Suppress curl's auto Expect: 100-continue (Chromium never sends it)
      args.push("-H", "Expect:");
      args.push(url);

      const child = spawn(resolveCurlBinary(), args, {
        stdio: ["pipe", "pipe", "pipe"],
      });

      // Abort handling
      const onAbort = () => {
        child.kill("SIGTERM");
      };
      if (signal) {
        if (signal.aborted) {
          child.kill("SIGTERM");
          reject(new Error("Aborted"));
          return;
        }
        signal.addEventListener("abort", onAbort, { once: true });
      }

      // Write body to stdin then close
      child.stdin.write(body);
      child.stdin.end();

      let headerBuf = Buffer.alloc(0);
      let headersParsed = false;
      let bodyController: ReadableStreamDefaultController<Uint8Array> | null = null;

      // Header parse timeout β€” kill curl if headers aren't received
      const headerTimer = setTimeout(() => {
        if (!headersParsed) {
          child.kill("SIGTERM");
          reject(new Error(`curl header parse timeout after ${HEADER_TIMEOUT_MS}ms`));
        }
      }, HEADER_TIMEOUT_MS);
      if (headerTimer.unref) headerTimer.unref();

      const bodyStream = new ReadableStream<Uint8Array>({
        start(c) {
          bodyController = c;
        },
        cancel() {
          child.kill("SIGTERM");
        },
      });

      child.stdout.on("data", (chunk: Buffer) => {
        if (headersParsed) {
          bodyController?.enqueue(new Uint8Array(chunk));
          return;
        }

        // Accumulate until we find \r\n\r\n header separator
        headerBuf = Buffer.concat([headerBuf, chunk]);

        // Loop to skip intermediate header blocks (CONNECT tunnel 200, 100 Continue, etc.)
        while (!headersParsed) {
          const separatorIdx = headerBuf.indexOf("\r\n\r\n");
          if (separatorIdx === -1) return; // wait for more data

          const headerBlock = headerBuf.subarray(0, separatorIdx).toString("utf-8");
          const remainder = headerBuf.subarray(separatorIdx + 4);

          const parsed = parseHeaderDump(headerBlock);

          // Skip intermediate responses: CONNECT tunnel, 1xx informational
          if (parsed.status < 200 || isConnectResponse(headerBlock)) {
            headerBuf = remainder;
            continue;
          }

          // Real response found
          headersParsed = true;
          clearTimeout(headerTimer);

          if (remainder.length > 0) {
            bodyController?.enqueue(new Uint8Array(remainder));
          }

          if (signal) {
            signal.removeEventListener("abort", onAbort);
          }

          resolve({
            status: parsed.status,
            headers: parsed.headers,
            body: bodyStream,
            setCookieHeaders: parsed.setCookieHeaders,
          });
        }
      });

      let stderrBuf = "";
      child.stderr.on("data", (chunk: Buffer) => {
        stderrBuf += chunk.toString();
      });

      child.on("close", (code) => {
        clearTimeout(headerTimer);
        if (signal) {
          signal.removeEventListener("abort", onAbort);
        }
        if (!headersParsed) {
          reject(new Error(`curl exited with code ${code}: ${stderrBuf}`));
        } else if (code !== 0 && code !== null) {
          // curl died mid-stream (e.g. connection reset, SIGPIPE) β€” signal error to reader
          try {
            bodyController?.error(new Error(`curl exited with code ${code} mid-stream: ${stderrBuf.trim() || "connection lost"}`));
          } catch { /* stream already closed */ }
        } else {
          bodyController?.close();
        }
      });

      child.on("error", (err) => {
        clearTimeout(headerTimer);
        if (signal) {
          signal.removeEventListener("abort", onAbort);
        }
        reject(new Error(formatSpawnError(err)));
      });
    });
  }

  /**
   * Simple GET β€” execFile curl, returns full body as string.
   */
  get(
    url: string,
    headers: Record<string, string>,
    timeoutSec = 30,
    proxyUrl?: string | null,
  ): Promise<{ status: number; body: string }> {
    const args = [
      ...getChromeTlsArgs(),
      ...resolveProxyArgs(proxyUrl),
      "-s", "-S",
      "--compressed",
      "--max-time", String(timeoutSec),
    ];

    for (const [key, value] of Object.entries(headers)) {
      args.push("-H", `${key}: ${value}`);
    }
    args.push("-H", "Expect:");
    args.push("-w", STATUS_SEPARATOR + "%{http_code}");
    args.push(url);

    return execCurl(args);
  }

  /**
   * Simple (non-streaming) POST β€” execFile curl, returns full body as string.
   * Used for OAuth token exchange, device code requests, etc.
   */
  simplePost(
    url: string,
    headers: Record<string, string>,
    body: string,
    timeoutSec = 30,
    proxyUrl?: string | null,
  ): Promise<{ status: number; body: string }> {
    const args = [
      ...getChromeTlsArgs(),
      ...resolveProxyArgs(proxyUrl),
      "-s", "-S",
      "--compressed",
      "--max-time", String(timeoutSec),
      "-X", "POST",
    ];

    for (const [key, value] of Object.entries(headers)) {
      args.push("-H", `${key}: ${value}`);
    }
    args.push("-H", "Expect:");
    args.push("-d", body);
    args.push("-w", STATUS_SEPARATOR + "%{http_code}");
    args.push(url);

    return execCurl(args);
  }

  isImpersonate(): boolean {
    return curlIsImpersonate();
  }
}

/**
 * Format a spawn error with architecture hint for EBADARCH (-86) on macOS.
 * This commonly happens when curl-impersonate binary doesn't match the CPU arch.
 */
export function formatSpawnError(err: Error & { errno?: number; code?: string }): string {
  // errno -86 = EBADARCH (Bad CPU type in executable) on macOS
  if (err.errno === -86 || err.message.includes("-86")) {
    const binary = resolveCurlBinary();
    return (
      `curl-impersonate binary has wrong CPU architecture for this system. ` +
      `Binary: ${binary}, Host arch: ${process.arch}. ` +
      `Fix: run "npm run setup -- --force" to download the correct binary, ` +
      `or delete bin/curl-impersonate to fall back to system curl.`
    );
  }
  return `curl spawn error: ${err.message}`;
}

/** Execute curl via execFile and parse the status code from the output. */
function execCurl(args: string[]): Promise<{ status: number; body: string }> {
  return new Promise((resolve, reject) => {
    execFile(
      resolveCurlBinary(),
      args,
      { maxBuffer: 2 * 1024 * 1024 },
      (err, stdout, stderr) => {
        if (err) {
          const castErr = err as Error & { errno?: number };
          // Check for EBADARCH first (architecture mismatch)
          if (castErr.errno === -86 || err.message.includes("-86")) {
            reject(new Error(formatSpawnError(castErr)));
          } else {
            reject(new Error(`curl failed: ${err.message} ${stderr}`));
          }
          return;
        }

        const sepIdx = stdout.lastIndexOf(STATUS_SEPARATOR);
        if (sepIdx === -1) {
          reject(new Error("curl: missing status separator in output"));
          return;
        }

        const body = stdout.slice(0, sepIdx);
        const status = parseInt(stdout.slice(sepIdx + STATUS_SEPARATOR.length), 10);

        resolve({ status, body });
      },
    );
  });
}

/**
 * Resolve proxy args for curl CLI.
 * undefined β†’ global default | null β†’ no proxy | string β†’ specific proxy
 */
function resolveProxyArgs(proxyUrl: string | null | undefined): string[] {
  if (proxyUrl === null) return [];
  if (proxyUrl !== undefined) return ["-x", proxyUrl];
  return getProxyArgs();
}

/** Parse HTTP response header block from curl -i output. */
function parseHeaderDump(headerBlock: string): {
  status: number;
  headers: Headers;
  setCookieHeaders: string[];
} {
  const lines = headerBlock.split("\r\n");
  let status = 0;
  const headers = new Headers();
  const setCookieHeaders: string[] = [];

  for (let i = 0; i < lines.length; i++) {
    const line = lines[i];
    if (i === 0) {
      const match = line.match(/^HTTP\/[\d.]+ (\d+)/);
      if (match) status = parseInt(match[1], 10);
      continue;
    }
    const colonIdx = line.indexOf(":");
    if (colonIdx === -1) continue;
    const key = line.slice(0, colonIdx).trim();
    const value = line.slice(colonIdx + 1).trim();
    if (key.toLowerCase() === "set-cookie") {
      setCookieHeaders.push(value);
    }
    headers.append(key, value);
  }

  return { status, headers, setCookieHeaders };
}

/** Detect CONNECT tunnel responses (e.g. "HTTP/1.1 200 Connection established"). */
function isConnectResponse(headerBlock: string): boolean {
  const firstLine = headerBlock.split("\r\n")[0] ?? "";
  return /connection\s+established/i.test(firstLine);
}