:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(cli): pass windows unzip paths through env and verify the binary (#109313)
posthog[bot]51c5ffa72f75
diff --git a/.github/scripts/patch-cli-npm-installer.mjs b/.github/scripts/patch-cli-npm-installer.mjsindex 7eceb77d234f..6daedb61ae06 100644--- a/.github/scripts/patch-cli-npm-installer.mjs+++ b/.github/scripts/patch-cli-npm-installer.mjs@@ -62,6 +62,27 @@ ${sleep.toString()}${downloadWithRetry.toString()}`+// Windows PowerShell joins every argument after -Command into one script, so a positional path+// that contains a space splits in two. The env passes each path to Expand-Archive as one value.+const WINDOWS_EXPAND_ARCHIVE_ANCHOR =+ /`& \{\s*param\(\[string\]\$LiteralPath, \[string\]\$DestinationPath\)\s*Expand-Archive -LiteralPath \$LiteralPath -DestinationPath \$DestinationPath -Force\s*\}`,\s*tempFile,\s*this\.installDirectory,\s*\]\);/+const WINDOWS_EXPAND_ARCHIVE_SOURCE = `"$ErrorActionPreference = 'Stop'; Expand-Archive -LiteralPath $env:POSTHOG_CLI_ZIP -DestinationPath $env:POSTHOG_CLI_DEST -Force",+ ], {+ env: {+ ...process.env,+ POSTHOG_CLI_ZIP: tempFile,+ POSTHOG_CLI_DEST: this.installDirectory,+ },+ });`++const INSTALLED_ANCHOR =+ /\.then\(\(\) => \{(\s*)if \(!suppressLogs\) \{\s*console\.error\(`\$\{this\.name\} has been installed!`\);/+const INSTALLED_CHECK_SOURCE = `if (!this.exists()) {+ throw new Error(+ \`The archive extracted, but \${this.name} is missing from \${this.installDirectory}\`,+ );+ }`+export function patchBinaryInstaller(source) {const importAnchor = 'const http = require("node:http");'const downloadAnchor = 'return download(this.url)'@@ -72,12 +93,23 @@ export function patchBinaryInstaller(source) {if (!source.includes(downloadAnchor)) {throw new Error(`Could not find the artifact download call in cargo-dist's binary-install.js`)}+ if (!WINDOWS_EXPAND_ARCHIVE_ANCHOR.test(source)) {+ throw new Error(`Could not find the Windows Expand-Archive call in cargo-dist's binary-install.js`)+ }+ if (!INSTALLED_ANCHOR.test(source)) {+ throw new Error(`Could not find the install success log in cargo-dist's binary-install.js`)+ }if (source.includes('downloadWithRetry(() => download(this.url)')) {throw new Error(`cargo-dist's binary-install.js is already patched`)}return source.replace(importAnchor, `${importAnchor}\n${RETRY_HELPER_SOURCE}`)+ .replace(WINDOWS_EXPAND_ARCHIVE_ANCHOR, () => WINDOWS_EXPAND_ARCHIVE_SOURCE)+ .replace(+ INSTALLED_ANCHOR,+ (match, indent) => `.then(() => {${indent}${INSTALLED_CHECK_SOURCE}${match.slice('.then(() => {'.length)}`+ ).replace(downloadAnchor,`return downloadWithRetry(() => download(this.url), {\n onRetry: (error, attempt, delayMs) => {\n console.error(\n \`Download attempt \${attempt} failed (\${error.message}); retrying in \${delayMs}ms...\`,\n );\n },\n })`@@ -134,5 +166,5 @@ export function patchCliNpmInstaller(distributionDirectory, manifestPath) {if (process.argv[1] && fileURLToPath(import.meta.url) === process.argv[1]) {const [distributionDirectory = 'target/distrib', manifestPath = 'dist-manifest.json'] = process.argv.slice(2)patchCliNpmInstaller(distributionDirectory, manifestPath)- console.log('Added retries with exponential backoff to the generated posthog-cli npm installer')+ console.log('Patched the generated posthog-cli npm installer with download retries and safe Windows extraction')}diff --git a/.github/scripts/patch-cli-npm-installer.test.mjs b/.github/scripts/patch-cli-npm-installer.test.mjsindex d6164158615d..ae5188afaf44 100644--- a/.github/scripts/patch-cli-npm-installer.test.mjs+++ b/.github/scripts/patch-cli-npm-installer.test.mjs@@ -16,13 +16,52 @@ import {const GENERATED_INSTALLER = `const http = require("node:http");class Package {- install() {+ install(suppressLogs = false) {return download(this.url)- .then(() => {});+ .then(() => {+ const tempFile = this.tempFile;+ const result = spawnSync("powershell.exe", [+ "-NoProfile",+ "-NonInteractive",+ "-Command",+ \`& {+ param([string]$LiteralPath, [string]$DestinationPath)+ Expand-Archive -LiteralPath $LiteralPath -DestinationPath $DestinationPath -Force+ }\`,+ tempFile,+ this.installDirectory,+ ]);+ })+ .then(() => {+ if (!suppressLogs) {+ console.error(\`\${this.name} has been installed!\`);+ }+ });}}`+function loadPatchedPackage({ binaryExists }) {+ const calls = []+ const Package = new Function(+ 'require',+ 'download',+ 'spawnSync',+ `${patchBinaryInstaller(GENERATED_INSTALLER)}\nreturn Package`+ )(+ () => ({}),+ async () => {},+ (command, args, options) => calls.push({ command, args, options })+ )+ const pkg = Object.assign(new Package(), {+ name: 'posthog-cli',+ tempFile: 'C:\\Users\\First Last\\AppData\\Local\\Temp\\cli.zip',+ installDirectory: 'C:\\Users\\First Last\\project\\node_modules\\.bin_real',+ exists: () => binaryExists,+ })+ return { pkg, calls }+}+test('classifies only transient download failures as retryable', () => {for (const message of ['HTTP 408 from URL', 'HTTP 429 from URL', 'HTTP 500 from URL', 'socket hang up']) {assert.equal(isTransientDownloadError(new Error(message)), true, message)@@ -77,6 +116,26 @@ test('patches the cargo-dist download call', () => {assert.match(patched, /DOWNLOAD_RETRY_BASE_DELAY_MS = 1000/)})+test('passes the Windows unzip paths through the env, not as PowerShell arguments', async () => {+ const { pkg, calls } = loadPatchedPackage({ binaryExists: true })++ await pkg.install(true)++ assert.equal(calls.length, 1)+ for (const arg of calls[0].args) {+ assert.doesNotMatch(arg, /First Last/)+ }+ assert.match(calls[0].args.at(-1), /-LiteralPath \$env:POSTHOG_CLI_ZIP -DestinationPath \$env:POSTHOG_CLI_DEST/)+ assert.equal(calls[0].options.env.POSTHOG_CLI_ZIP, pkg.tempFile)+ assert.equal(calls[0].options.env.POSTHOG_CLI_DEST, pkg.installDirectory)+})++test('fails the install when the binary is missing after extraction', async () => {+ const { pkg } = loadPatchedPackage({ binaryExists: false })++ await assert.rejects(pkg.install(true), /posthog-cli is missing from/)+})+test('patches the npm archive and refreshes release checksums', () => {const root = mkdtempSync(join(tmpdir(), 'posthog-cli-patcher-test-'))