|
| 1 | +'use strict'; |
| 2 | + |
| 3 | +/** |
| 4 | + * Shared HTTP + archive helpers used by both binary resolvers |
| 5 | + * (`lib/binary/index.js` for `agent-analyzer`, `lib/embed/binary.js` |
| 6 | + * for `agent-analyzer-embed`). |
| 7 | + * |
| 8 | + * Extracted to keep the two resolvers from drifting on HTTP redirect |
| 9 | + * handling, GitHub auth, and archive extraction details — a single |
| 10 | + * fix to e.g. the timeout policy or the redirect cap lands once and |
| 11 | + * applies to both binaries. |
| 12 | + * |
| 13 | + * @module lib/binary/shared-helpers |
| 14 | + */ |
| 15 | + |
| 16 | +const fs = require('fs'); |
| 17 | +const path = require('path'); |
| 18 | +const os = require('os'); |
| 19 | +const https = require('https'); |
| 20 | +const cp = require('child_process'); |
| 21 | + |
| 22 | +const DEFAULT_DOWNLOAD_TIMEOUT_MS = 30000; |
| 23 | +const MAX_REDIRECTS = 5; |
| 24 | + |
| 25 | +/** |
| 26 | + * Fetch a URL into an in-memory Buffer following up to 5 redirects. |
| 27 | + * |
| 28 | + * Honors `GITHUB_TOKEN` / `GH_TOKEN` for authenticated requests |
| 29 | + * (raises rate limit, lets private-repo asset URLs work). Stalled |
| 30 | + * connections are killed by the per-request timeout — without this |
| 31 | + * a stuck socket would hang the process indefinitely. |
| 32 | + * |
| 33 | + * @param {string} url |
| 34 | + * @param {Object} [options] |
| 35 | + * @param {string} [options.userAgent='agent-sh/binary-resolver'] |
| 36 | + * @param {number} [options.timeoutMs=30000] - per-request timeout |
| 37 | + * @returns {Promise<Buffer>} |
| 38 | + */ |
| 39 | +function downloadToBuffer(url, options) { |
| 40 | + const opts = options || {}; |
| 41 | + const userAgent = opts.userAgent || 'agent-sh/binary-resolver'; |
| 42 | + const timeoutMs = opts.timeoutMs || DEFAULT_DOWNLOAD_TIMEOUT_MS; |
| 43 | + |
| 44 | + return new Promise(function (resolve, reject) { |
| 45 | + const ghToken = process.env.GITHUB_TOKEN || process.env.GH_TOKEN; |
| 46 | + |
| 47 | + function request(reqUrl, redirectCount) { |
| 48 | + if (redirectCount > MAX_REDIRECTS) { |
| 49 | + reject(new Error('Too many redirects fetching from ' + url)); |
| 50 | + return; |
| 51 | + } |
| 52 | + const headers = { |
| 53 | + 'User-Agent': userAgent, |
| 54 | + 'Accept': 'application/octet-stream' |
| 55 | + }; |
| 56 | + if (ghToken) headers['Authorization'] = 'Bearer ' + ghToken; |
| 57 | + |
| 58 | + const req = https.get(reqUrl, { headers: headers, timeout: timeoutMs }, function (res) { |
| 59 | + const sc = res.statusCode; |
| 60 | + if (sc === 301 || sc === 302 || sc === 307 || sc === 308) { |
| 61 | + res.resume(); |
| 62 | + var loc = res.headers.location; |
| 63 | + if (loc && !loc.startsWith('https://')) { |
| 64 | + reject(new Error('Refusing non-HTTPS redirect to ' + loc)); |
| 65 | + return; |
| 66 | + } |
| 67 | + request(loc, redirectCount + 1); |
| 68 | + return; |
| 69 | + } |
| 70 | + if (sc !== 200) { |
| 71 | + res.resume(); |
| 72 | + const hint = sc === 403 ? ' (rate limited - set GITHUB_TOKEN env var)' : ''; |
| 73 | + reject(new Error('HTTP ' + sc + hint + ' fetching ' + reqUrl)); |
| 74 | + return; |
| 75 | + } |
| 76 | + const chunks = []; |
| 77 | + res.on('data', function (chunk) { chunks.push(chunk); }); |
| 78 | + res.on('end', function () { resolve(Buffer.concat(chunks)); }); |
| 79 | + res.on('error', reject); |
| 80 | + }); |
| 81 | + req.on('error', reject); |
| 82 | + req.on('timeout', function () { |
| 83 | + req.destroy(); |
| 84 | + reject(new Error('Timeout (' + timeoutMs + 'ms) fetching ' + reqUrl)); |
| 85 | + }); |
| 86 | + } |
| 87 | + |
| 88 | + request(url, 0); |
| 89 | + }); |
| 90 | +} |
| 91 | + |
| 92 | +/** |
| 93 | + * Extract a `.tar.gz` Buffer into `destDir` using the system `tar`. |
| 94 | + * Available on Linux, macOS, and Windows (built into recent Win10/11). |
| 95 | + * |
| 96 | + * @param {Buffer} buf |
| 97 | + * @param {string} destDir |
| 98 | + * @returns {Promise<void>} |
| 99 | + */ |
| 100 | +function extractTarGz(buf, destDir) { |
| 101 | + return new Promise(function (resolve, reject) { |
| 102 | + const tarDest = process.platform === 'win32' ? destDir.replace(/\\/g, '/') : destDir; |
| 103 | + const tar = cp.spawn('tar', ['xz', '-C', tarDest], { |
| 104 | + stdio: ['pipe', 'pipe', 'pipe'] |
| 105 | + }); |
| 106 | + let stderr = ''; |
| 107 | + tar.stderr.on('data', function (d) { stderr += d; }); |
| 108 | + tar.stdin.write(buf); |
| 109 | + tar.stdin.end(); |
| 110 | + tar.on('close', function (code) { |
| 111 | + if (code !== 0) { |
| 112 | + reject(new Error('tar extraction failed (code ' + code + '): ' + stderr)); |
| 113 | + } else { |
| 114 | + resolve(); |
| 115 | + } |
| 116 | + }); |
| 117 | + tar.on('error', reject); |
| 118 | + }); |
| 119 | +} |
| 120 | + |
| 121 | +/** |
| 122 | + * Extract a `.zip` Buffer into `destDir` using PowerShell's |
| 123 | + * `Expand-Archive` (Windows-only). |
| 124 | + * |
| 125 | + * @param {Buffer} buf |
| 126 | + * @param {string} destDir |
| 127 | + * @param {string} binaryName - used as the temp-dir prefix |
| 128 | + * @returns {Promise<void>} |
| 129 | + */ |
| 130 | +function extractZip(buf, destDir, binaryName) { |
| 131 | + return new Promise(function (resolve, reject) { |
| 132 | + var tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), binaryName + '-')); |
| 133 | + var tmpZip = path.join(tmpDir, 'archive.zip'); |
| 134 | + fs.writeFileSync(tmpZip, buf); |
| 135 | + var ps = cp.spawn( |
| 136 | + 'powershell', |
| 137 | + ['-NoProfile', '-NonInteractive', '-Command', |
| 138 | + 'Expand-Archive', '-Path', tmpZip, '-DestinationPath', destDir, '-Force'], |
| 139 | + { stdio: ['ignore', 'pipe', 'pipe'] } |
| 140 | + ); |
| 141 | + var stderr = ''; |
| 142 | + ps.stderr.on('data', function (d) { stderr += d; }); |
| 143 | + ps.on('close', function (code) { |
| 144 | + try { fs.rmSync(tmpDir, { recursive: true, force: true }); } catch (e) { /* ignore */ } |
| 145 | + if (code !== 0) { |
| 146 | + reject(new Error('zip extraction failed (code ' + code + '): ' + stderr)); |
| 147 | + } else { |
| 148 | + resolve(); |
| 149 | + } |
| 150 | + }); |
| 151 | + ps.on('error', reject); |
| 152 | + }); |
| 153 | +} |
| 154 | + |
| 155 | +module.exports = { |
| 156 | + downloadToBuffer, |
| 157 | + extractTarGz, |
| 158 | + extractZip, |
| 159 | + DEFAULT_DOWNLOAD_TIMEOUT_MS |
| 160 | +}; |
0 commit comments