| 1 | #!/usr/bin/env node |
| 2 | |
| 3 | const crypto = require("crypto"); |
| 4 | const fs = require("fs"); |
| 5 | const fsp = require("fs/promises"); |
| 6 | const https = require("https"); |
| 7 | const os = require("os"); |
| 8 | const path = require("path"); |
| 9 | const { spawn } = require("child_process"); |
| 10 | |
| 11 | const repoRoot = path.resolve(__dirname, "..", ".."); |
| 12 | const packageDir = path.join(repoRoot, "npm", "codewhale"); |
| 13 | const prepareAssetsScript = path.join( |
| 14 | repoRoot, |
| 15 | "scripts", |
| 16 | "release", |
| 17 | "prepare-local-release-assets.js", |
| 18 | ); |
| 19 | const CLEANUP_MAX_RETRIES = 8; |
| 20 | const CLEANUP_RETRY_DELAY_MS = 250; |
| 21 | |
| 22 | function shellQuote(value) { |
| 23 | return /\s/.test(value) ? JSON.stringify(value) : value; |
| 24 | } |
| 25 | |
| 26 | function usesWindowsCommandShim(command) { |
| 27 | return process.platform === "win32" && (command === "npm" || command === "npx"); |
| 28 | } |
| 29 | |
| 30 | function runCommand(command, args, options = {}) { |
| 31 | const cwd = options.cwd || repoRoot; |
| 32 | console.log(`$ ${[command, ...args].map(shellQuote).join(" ")}`); |
| 33 | const child = spawn(command, args, { |
| 34 | cwd, |
| 35 | env: { |
| 36 | ...process.env, |
| 37 | ...(options.env || {}), |
| 38 | }, |
| 39 | encoding: "utf8", |
| 40 | shell: usesWindowsCommandShim(command), |
| 41 | stdio: options.capture ? ["ignore", "pipe", "pipe"] : "inherit", |
| 42 | windowsHide: true, |
| 43 | }); |
| 44 | |
| 45 | if (!options.capture) { |
| 46 | return new Promise((resolve, reject) => { |
| 47 | child.once("error", reject); |
| 48 | child.once("close", (status) => { |
| 49 | if (status === 0) { |
| 50 | resolve({ stdout: "", stderr: "" }); |
| 51 | } else { |
| 52 | reject(new Error(`${command} exited with status ${status}`)); |
| 53 | } |
| 54 | }); |
| 55 | }); |
| 56 | } |
| 57 | |
| 58 | let stdout = ""; |
| 59 | let stderr = ""; |
| 60 | child.stdout.setEncoding("utf8"); |
| 61 | child.stderr.setEncoding("utf8"); |
| 62 | child.stdout.on("data", (chunk) => { |
| 63 | stdout += chunk; |
| 64 | }); |
| 65 | child.stderr.on("data", (chunk) => { |
| 66 | stderr += chunk; |
| 67 | }); |
| 68 | return new Promise((resolve, reject) => { |
| 69 | child.once("error", reject); |
| 70 | child.once("close", (status) => { |
| 71 | if (status === 0) { |
| 72 | resolve({ stdout, stderr }); |
| 73 | return; |
| 74 | } |
| 75 | process.stdout.write(stdout); |
| 76 | process.stderr.write(stderr); |
| 77 | reject(new Error(`${command} exited with status ${status}`)); |
| 78 | }); |
| 79 | }); |
| 80 | } |
| 81 | |
| 82 | function derLen(length) { |
| 83 | if (length < 0x80) return Buffer.from([length]); |
| 84 | const bytes = []; |
| 85 | let n = length; |
| 86 | while (n > 0) { |
| 87 | bytes.unshift(n & 0xff); |
| 88 | n >>= 8; |
| 89 | } |
| 90 | return Buffer.from([0x80 | bytes.length, ...bytes]); |
| 91 | } |
| 92 | |
| 93 | function derTag(tag, content) { |
| 94 | return Buffer.concat([Buffer.from([tag]), derLen(content.length), content]); |
| 95 | } |
| 96 | |
| 97 | function derSeq(...items) { |
| 98 | return derTag(0x30, Buffer.concat(items)); |
| 99 | } |
| 100 | |
| 101 | function derSet(...items) { |
| 102 | return derTag(0x31, Buffer.concat(items)); |
| 103 | } |
| 104 | |
| 105 | function derOid(bytes) { |
| 106 | return derTag(0x06, Buffer.from(bytes)); |
| 107 | } |
| 108 | |
| 109 | function derInt(bytes) { |
| 110 | let buf = Buffer.from(bytes); |
| 111 | let start = 0; |
| 112 | while (start < buf.length - 1 && buf[start] === 0) { |
| 113 | start += 1; |
| 114 | } |
| 115 | buf = buf.subarray(start); |
| 116 | return derTag(0x02, buf[0] & 0x80 ? Buffer.concat([Buffer.from([0]), buf]) : buf); |
| 117 | } |
| 118 | |
| 119 | function derBitString(bytes) { |
| 120 | return derTag(0x03, Buffer.concat([Buffer.from([0x00]), bytes])); |
| 121 | } |
| 122 | |
| 123 | function derUtcTime(date) { |
| 124 | const pad = (n) => String(n).padStart(2, "0"); |
| 125 | const s = |
| 126 | String(date.getUTCFullYear()).slice(-2) + |
| 127 | pad(date.getUTCMonth() + 1) + |
| 128 | pad(date.getUTCDate()) + |
| 129 | pad(date.getUTCHours()) + |
| 130 | pad(date.getUTCMinutes()) + |
| 131 | pad(date.getUTCSeconds()) + |
| 132 | "Z"; |
| 133 | return derTag(0x17, Buffer.from(s, "ascii")); |
| 134 | } |
| 135 | |
| 136 | async function createLoopbackCertificate(certDir) { |
| 137 | const { privateKey, publicKey } = crypto.generateKeyPairSync("ec", { namedCurve: "prime256v1" }); |
| 138 | const spki = publicKey.export({ type: "spki", format: "der" }); |
| 139 | const sigAlg = derSeq(derOid([0x2a, 0x86, 0x48, 0xce, 0x3d, 0x04, 0x03, 0x02])); |
| 140 | const name = derSeq( |
| 141 | derSet(derSeq(derOid([0x55, 0x04, 0x03]), derTag(0x0c, Buffer.from("127.0.0.1", "utf8")))), |
| 142 | ); |
| 143 | const now = new Date(); |
| 144 | const later = new Date(now.getTime() + 24 * 60 * 60 * 1000); |
| 145 | const basicConstraints = derSeq( |
| 146 | derOid([0x55, 0x1d, 0x13]), |
| 147 | Buffer.from([0x01, 0x01, 0xff]), |
| 148 | derTag(0x04, derSeq(Buffer.from([0x01, 0x01, 0xff]))), |
| 149 | ); |
| 150 | const subjectAltName = derSeq( |
| 151 | derOid([0x55, 0x1d, 0x11]), |
| 152 | derTag(0x04, derSeq(derTag(0x87, Buffer.from([127, 0, 0, 1])))), |
| 153 | ); |
| 154 | const tbs = derSeq( |
| 155 | derTag(0xa0, derInt([0x02])), |
| 156 | derInt(crypto.randomBytes(8)), |
| 157 | sigAlg, |
| 158 | name, |
| 159 | derSeq(derUtcTime(now), derUtcTime(later)), |
| 160 | name, |
| 161 | spki, |
| 162 | derTag(0xa3, derSeq(basicConstraints, subjectAltName)), |
| 163 | ); |
| 164 | const sig = crypto.sign("sha256", tbs, privateKey); |
| 165 | const certDer = derSeq(tbs, sigAlg, derBitString(sig)); |
| 166 | const b64 = certDer.toString("base64").match(/.{1,64}/g).join("\n"); |
| 167 | const certPem = `-----BEGIN CERTIFICATE-----\n${b64}\n-----END CERTIFICATE-----\n`; |
| 168 | const keyPem = privateKey.export({ type: "pkcs8", format: "pem" }); |
| 169 | const caPath = path.join(certDir, "smoke-ca.pem"); |
| 170 | await fsp.writeFile(caPath, certPem, "utf8"); |
| 171 | return { cert: certPem, key: keyPem, caPath }; |
| 172 | } |
| 173 | |
| 174 | async function serveDirectory(root, certDir) { |
| 175 | const tls = await createLoopbackCertificate(certDir); |
| 176 | const server = https.createServer({ key: tls.key, cert: tls.cert }, async (request, response) => { |
| 177 | try { |
| 178 | const requestUrl = new URL(request.url || "/", "https://127.0.0.1"); |
| 179 | const decodedPath = decodeURIComponent(requestUrl.pathname); |
| 180 | const filePath = path.resolve(root, `.${decodedPath}`); |
| 181 | const relative = path.relative(root, filePath); |
| 182 | if (relative.startsWith("..") || path.isAbsolute(relative)) { |
| 183 | response.writeHead(403); |
| 184 | response.end("forbidden"); |
| 185 | return; |
| 186 | } |
| 187 | |
| 188 | const fileStat = await fsp.stat(filePath); |
| 189 | if (!fileStat.isFile()) { |
| 190 | response.writeHead(404); |
| 191 | response.end("not found"); |
| 192 | return; |
| 193 | } |
| 194 | |
| 195 | response.writeHead(200, { |
| 196 | "Content-Length": fileStat.size, |
| 197 | "Content-Type": "application/octet-stream", |
| 198 | }); |
| 199 | fs.createReadStream(filePath).pipe(response); |
| 200 | } catch (error) { |
| 201 | response.writeHead(error && error.code === "ENOENT" ? 404 : 500); |
| 202 | response.end(error && error.message ? error.message : "not found"); |
| 203 | } |
| 204 | }); |
| 205 | |
| 206 | return new Promise((resolve, reject) => { |
| 207 | server.once("error", reject); |
| 208 | server.listen(0, "127.0.0.1", () => { |
| 209 | const address = server.address(); |
| 210 | resolve({ |
| 211 | baseUrl: `https://127.0.0.1:${address.port}/`, |
| 212 | caPath: tls.caPath, |
| 213 | server, |
| 214 | }); |
| 215 | }); |
| 216 | }); |
| 217 | } |
| 218 | |
| 219 | function parsePackJson(stdout) { |
| 220 | const trimmed = stdout.trim(); |
| 221 | if (!trimmed) { |
| 222 | throw new Error("npm pack did not return package metadata"); |
| 223 | } |
| 224 | const parsed = JSON.parse(trimmed); |
| 225 | const first = Array.isArray(parsed) ? parsed[0] : parsed; |
| 226 | if (!first || !first.filename) { |
| 227 | throw new Error(`npm pack metadata did not include a filename: ${trimmed}`); |
| 228 | } |
| 229 | return first.filename; |
| 230 | } |
| 231 | |
| 232 | async function removeSmokeWorkspace(tempRoot, remove = fsp.rm) { |
| 233 | await remove(tempRoot, { |
| 234 | force: true, |
| 235 | recursive: true, |
| 236 | // Windows can report ENOTEMPTY briefly while completed binary downloads |
| 237 | // are still being released by the filesystem. fs.rm retries ENOTEMPTY |
| 238 | // (and the other documented transient removal errors) with linear |
| 239 | // backoff; the finite cap still surfaces a persistent cleanup failure. |
| 240 | maxRetries: CLEANUP_MAX_RETRIES, |
| 241 | retryDelay: CLEANUP_RETRY_DELAY_MS, |
| 242 | }); |
| 243 | } |
| 244 | |
| 245 | async function main() { |
| 246 | const tempRoot = await fsp.mkdtemp(path.join(os.tmpdir(), "codewhale-npm-smoke-")); |
| 247 | const suppliedAssetsDir = String( |
| 248 | process.env.CODEWHALE_SMOKE_ASSETS_DIR || "", |
| 249 | ).trim(); |
| 250 | const releaseAssetsDir = suppliedAssetsDir |
| 251 | ? path.resolve(suppliedAssetsDir) |
| 252 | : path.join(tempRoot, "release-assets"); |
| 253 | const packDir = path.join(tempRoot, "pack"); |
| 254 | const installDir = path.join(tempRoot, "install"); |
| 255 | let keepTemp = |
| 256 | process.env.CODEWHALE_KEEP_SMOKE_DIR === "1" || |
| 257 | process.env.DEEPSEEK_TUI_KEEP_SMOKE_DIR === "1"; |
| 258 | let server; |
| 259 | |
| 260 | try { |
| 261 | await fsp.mkdir(packDir, { recursive: true }); |
| 262 | await fsp.mkdir(installDir, { recursive: true }); |
| 263 | |
| 264 | if (suppliedAssetsDir) { |
| 265 | const assetDirectoryStat = await fsp.stat(releaseAssetsDir); |
| 266 | if (!assetDirectoryStat.isDirectory()) { |
| 267 | throw new Error(`CODEWHALE_SMOKE_ASSETS_DIR is not a directory: ${releaseAssetsDir}`); |
| 268 | } |
| 269 | console.log(`Using preassembled release assets from ${releaseAssetsDir}`); |
| 270 | } else { |
| 271 | const prepareArgs = [prepareAssetsScript, releaseAssetsDir]; |
| 272 | const cargoTargetDir = String(process.env.CARGO_TARGET_DIR || "").trim(); |
| 273 | if (cargoTargetDir) { |
| 274 | prepareArgs.push( |
| 275 | path.join(path.resolve(repoRoot, cargoTargetDir), "release"), |
| 276 | ); |
| 277 | } |
| 278 | await runCommand(process.execPath, prepareArgs); |
| 279 | } |
| 280 | const served = await serveDirectory(releaseAssetsDir, tempRoot); |
| 281 | server = served.server; |
| 282 | |
| 283 | const env = { |
| 284 | CODEWHALE_FORCE_DOWNLOAD: "1", |
| 285 | CODEWHALE_RELEASE_BASE_URL: served.baseUrl, |
| 286 | NODE_EXTRA_CA_CERTS: served.caPath, |
| 287 | }; |
| 288 | const pack = await runCommand( |
| 289 | "npm", |
| 290 | ["pack", "--json", "--pack-destination", packDir], |
| 291 | { |
| 292 | capture: true, |
| 293 | cwd: packageDir, |
| 294 | env, |
| 295 | }, |
| 296 | ); |
| 297 | const tarball = path.join(packDir, parsePackJson(pack.stdout)); |
| 298 | |
| 299 | await runCommand("npm", ["init", "-y"], { cwd: installDir }); |
| 300 | await runCommand("npm", ["install", tarball], { cwd: installDir, env }); |
| 301 | await runCommand("npx", ["--no-install", "codewhale", "doctor", "--help"], { |
| 302 | cwd: installDir, |
| 303 | env, |
| 304 | }); |
| 305 | await runCommand("npx", ["--no-install", "codew", "--version"], { |
| 306 | cwd: installDir, |
| 307 | env, |
| 308 | }); |
| 309 | |
| 310 | console.log(`npm wrapper smoke passed with local assets from ${served.baseUrl}`); |
| 311 | } catch (error) { |
| 312 | keepTemp = true; |
| 313 | console.error(`npm wrapper smoke failed: ${error.message}`); |
| 314 | console.error(`Smoke workspace retained at ${tempRoot}`); |
| 315 | process.exitCode = 1; |
| 316 | } finally { |
| 317 | if (server) { |
| 318 | await new Promise((resolve) => server.close(resolve)); |
| 319 | } |
| 320 | if (!keepTemp) { |
| 321 | await removeSmokeWorkspace(tempRoot); |
| 322 | } |
| 323 | } |
| 324 | } |
| 325 | |
| 326 | if (require.main === module) { |
| 327 | main(); |
| 328 | } |
| 329 | |
| 330 | module.exports = { |
| 331 | CLEANUP_MAX_RETRIES, |
| 332 | CLEANUP_RETRY_DELAY_MS, |
| 333 | removeSmokeWorkspace, |
| 334 | serveDirectory, |
| 335 | }; |
| 336 |