From b7ca29b4865e90bffd8f69594926b76f2f16e253 Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Thu, 19 Nov 2026 16:58:39 +0000 Subject: [PATCH] feat(cli-docs): Serve /install.ps1/ with SENTRY_HANDOFF set Windows gets the same one-liner as bash: irm https://cli.sentry.dev/install.ps1/ | iex The handoff function now serves both install scripts. Because iex runs in the caller's session, the PowerShell variant clears SENTRY_HANDOFF in a finally block once the install ends. Co-Authored-By: Evan Purkhiser <1421724+evanpurkhiser@users.noreply.github.com> --- apps/cli-docs/test/install-handoff.test.mjs | 123 ++++++++++++++++---- apps/cli-docs/vercel/build-output.mjs | 16 ++- apps/cli-docs/vercel/install-handoff.mjs | 61 ++++++---- docs/cli/README.md | 5 +- 4 files changed, 151 insertions(+), 54 deletions(-) diff --git a/apps/cli-docs/test/install-handoff.test.mjs b/apps/cli-docs/test/install-handoff.test.mjs index 589573b1e..090396be7 100644 --- a/apps/cli-docs/test/install-handoff.test.mjs +++ b/apps/cli-docs/test/install-handoff.test.mjs @@ -9,7 +9,13 @@ import { buildOutput } from "../vercel/build-output.mjs"; import { createHandler } from "../vercel/install-handoff.mjs"; const code = `sntryh_${"a1_-".repeat(10)}xyz`; -const echoHandoff = createHandler(`#!/bin/bash\nprintf '%s' "\${SENTRY_HANDOFF:-unset}"\n`); +const echoHandoff = createHandler({ + install: `#!/bin/bash\nprintf '%s' "\${SENTRY_HANDOFF:-unset}"\n`, + // A failing install must still clear the variable, so this one can throw. + "install.ps1": `[Console]::Out.Write("$env:SENTRY_HANDOFF")\nif ($env:SENTRY_TEST_THROW) { throw 'install failed' }\n`, +}); +const hasPwsh = + spawnSync("pwsh", ["-NoProfile", "-Command", "exit 0"], { stdio: "ignore" }).status === 0; async function pipeToBash(response) { return spawnSync("bash", [], { @@ -19,9 +25,31 @@ async function pipeToBash(response) { }); } +// Runs the response the way `irm | iex` does, then prints whether +// SENTRY_HANDOFF is still set in the session. +async function pipeToIex(response, env = {}) { + const dir = mkdtempSync(join(tmpdir(), "cli-docs-iex-")); + const script = join(dir, "install.ps1"); + writeFileSync(script, await response.text()); + try { + return spawnSync( + "pwsh", + [ + "-NoProfile", + "-NonInteractive", + "-Command", + `try { Get-Content -Raw -LiteralPath '${script}' | Invoke-Expression } catch { [Console]::Out.Write("|threw") }; [Console]::Out.Write("|after=$env:SENTRY_HANDOFF")`, + ], + { encoding: "utf8", env: { PATH: process.env.PATH, HOME: process.env.HOME, ...env } }, + ); + } finally { + rmSync(dir, { recursive: true, force: true }); + } +} + test("piping /install/ to bash runs the script with SENTRY_HANDOFF set", async () => { for (const url of [ - `https://cli.sentry.dev/install-handoff?code=${code}`, + `https://cli.sentry.dev/install-handoff?script=install&code=${code}`, `https://cli.sentry.dev/install/${code}`, ]) { const response = echoHandoff(new Request(url)); @@ -33,39 +61,75 @@ test("piping /install/ to bash runs the script with SENTRY_HANDOFF set", a } }); -test("anything but a well-formed handoff code is not found", async () => { - for (const bad of [ - "", - "sntryh_short", - `sntryh_${"a".repeat(42)}'`, - `sntryh_${"a".repeat(40)}';id`, - `${code}a`, - `sntryx_${"a".repeat(43)}`, - ]) { +test( + "piping /install.ps1/ to iex runs the script with SENTRY_HANDOFF set, then clears it", + { skip: !hasPwsh && "pwsh is not installed" }, + async () => { + for (const url of [ + `https://cli.sentry.dev/install-handoff?script=install.ps1&code=${code}`, + `https://cli.sentry.dev/install.ps1/${code}`, + ]) { + const response = echoHandoff(new Request(url)); + assert.equal(response.status, 200); + assert.equal(response.headers.get("cache-control"), "no-store"); + const result = await pipeToIex(response); + assert.equal(result.status, 0, result.stderr); + assert.equal(result.stdout, `${code}|after=`); + } + + const failed = await pipeToIex( + echoHandoff(new Request(`https://cli.sentry.dev/install.ps1/${code}`)), + { SENTRY_TEST_THROW: "1" }, + ); + assert.equal(failed.stdout, `${code}|threw|after=`); + }, +); + +test("anything but a known script and a well-formed handoff code is not found", async () => { + const bad = [ + ["install", ""], + ["install", "sntryh_short"], + ["install", `sntryh_${"a".repeat(42)}'`], + ["install", `sntryh_${"a".repeat(40)}';id`], + ["install.ps1", `sntryh_${"a".repeat(40)}';id`], + ["install", `${code}a`], + ["install", `sntryx_${"a".repeat(43)}`], + ["", code], + ["install.sh", code], + ["constructor", code], + ]; + for (const [script, badCode] of bad) { const response = echoHandoff( - new Request(`https://cli.sentry.dev/install-handoff?code=${encodeURIComponent(bad)}`), + new Request( + `https://cli.sentry.dev/install-handoff?script=${encodeURIComponent(script)}&code=${encodeURIComponent(badCode)}`, + ), ); - assert.equal(response.status, 404, bad); + assert.equal(response.status, 404, `${script} ${badCode}`); assert.equal(await response.text(), "Not found\n"); } }); -test("the packaged site routes /install/ to a function serving the install script", async () => { +test("the packaged site routes /install/ and /install.ps1/ to a function serving the install scripts", async () => { const dir = mkdtempSync(join(tmpdir(), "cli-docs-vercel-")); try { const dist = join(dir, "dist"); const output = join(dir, "output"); - const script = readFileSync(new URL("../public/install", import.meta.url), "utf8"); + const bash = readFileSync(new URL("../public/install", import.meta.url), "utf8"); + const powershell = readFileSync(new URL("../public/install.ps1", import.meta.url), "utf8"); mkdirSync(dist); - writeFileSync(join(dist, "install"), script); + writeFileSync(join(dist, "install"), bash); + writeFileSync(join(dist, "install.ps1"), powershell); buildOutput(dist, output); const config = JSON.parse(readFileSync(join(output, "config.json"), "utf8")); const route = config.routes.find((r) => r.dest?.startsWith("/install-handoff")); - const match = `/install/${code}`.match(new RegExp(route.src)); - assert.equal(match?.[1], code); - assert.equal(new RegExp(route.src).test(`/install/${code}x`), false); - assert.equal(readFileSync(join(output, "static", "install"), "utf8"), script); + const src = new RegExp(route.src); + assert.deepEqual(`/install/${code}`.match(src)?.slice(1), ["install", code]); + assert.deepEqual(`/install.ps1/${code}`.match(src)?.slice(1), ["install.ps1", code]); + assert.equal(src.test(`/install/${code}x`), false); + assert.equal(src.test(`/installxps1/${code}`), false); + assert.equal(readFileSync(join(output, "static", "install"), "utf8"), bash); + assert.equal(readFileSync(join(output, "static", "install.ps1"), "utf8"), powershell); const fn = join(output, "functions", "install-handoff.func"); assert.deepEqual(JSON.parse(readFileSync(join(fn, ".vc-config.json"), "utf8")), { @@ -73,11 +137,20 @@ test("the packaged site routes /install/ to a function serving the install entrypoint: "index.js", }); const { default: handler } = await import(pathToFileURL(join(fn, "index.js")).href); - const body = await handler( - new Request(`https://cli.sentry.dev${route.dest.replace("$1", code)}`), - ).text(); - const [shebang, ...rest] = script.split("\n"); - assert.equal(body, [shebang, `export SENTRY_HANDOFF='${code}'`, ...rest].join("\n")); + const serve = (script) => + handler( + new Request( + `https://cli.sentry.dev${route.dest.replace("$1", script).replace("$2", code)}`, + ), + ).text(); + + const [shebang, ...rest] = bash.split("\n"); + assert.equal( + await serve("install"), + [shebang, `export SENTRY_HANDOFF='${code}'`, ...rest].join("\n"), + ); + const ps1 = await serve("install.ps1"); + assert.ok(ps1.startsWith(`$env:SENTRY_HANDOFF = '${code}'\ntry {\n${powershell}`)); } finally { rmSync(dir, { recursive: true, force: true }); } diff --git a/apps/cli-docs/vercel/build-output.mjs b/apps/cli-docs/vercel/build-output.mjs index 2d3902a5e..e2aadaa52 100644 --- a/apps/cli-docs/vercel/build-output.mjs +++ b/apps/cli-docs/vercel/build-output.mjs @@ -1,6 +1,7 @@ // Packages the built site (apps/cli-docs/dist) as Vercel Build Output API v3: -// the static files, the routes below, and the /install/ Edge -// Function. Usage: node build-output.mjs +// the static files, the routes below, and the Edge Function behind +// /install/ and /install.ps1/. +// Usage: node build-output.mjs import { cpSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs"; import { join } from "node:path"; import { fileURLToPath } from "node:url"; @@ -26,8 +27,8 @@ const routes = [ continue: true, }, { - src: `^/install/(${HANDOFF_CODE.source.slice(1, -1)})$`, - dest: `/${HANDOFF_FUNCTION}?code=$1`, + src: `^/(install|install\\.ps1)/(${HANDOFF_CODE.source.slice(1, -1)})$`, + dest: `/${HANDOFF_FUNCTION}?script=$1&code=$2`, }, ]; @@ -46,10 +47,13 @@ export function buildOutput(distDir, outputDir) { `${JSON.stringify({ runtime: "edge", entrypoint: "index.js" })}\n`, ); const handler = readFileSync(new URL("./install-handoff.mjs", import.meta.url), "utf8"); - const installScript = readFileSync(join(distDir, "install"), "utf8"); + const scripts = { + install: readFileSync(join(distDir, "install"), "utf8"), + "install.ps1": readFileSync(join(distDir, "install.ps1"), "utf8"), + }; writeFileSync( join(functionDir, "index.js"), - `${handler}\nexport default createHandler(${JSON.stringify(installScript)});\n`, + `${handler}\nexport default createHandler(${JSON.stringify(scripts)});\n`, ); } diff --git a/apps/cli-docs/vercel/install-handoff.mjs b/apps/cli-docs/vercel/install-handoff.mjs index e226b39c6..f5935034d 100644 --- a/apps/cli-docs/vercel/install-handoff.mjs +++ b/apps/cli-docs/vercel/install-handoff.mjs @@ -1,11 +1,13 @@ -// Serves cli.sentry.dev/install/: the install script with -// SENTRY_HANDOFF set, so `curl -fsSL https://cli.sentry.dev/install/ | bash` -// claims the Sentry agent handoff during `sentry cli setup`. build-output.mjs -// bundles this module with the install script as a Vercel Edge Function. +// Serves cli.sentry.dev/install/ and /install.ps1/: +// the install script with SENTRY_HANDOFF set, so +// curl -fsSL https://cli.sentry.dev/install/ | bash +// irm https://cli.sentry.dev/install.ps1/ | iex +// claim the Sentry agent handoff during `sentry cli setup`. build-output.mjs +// bundles this module with both install scripts as a Vercel Edge Function. // Matches the codes Sentry issues (`sntryh_` + 32 random bytes, base64url). -// The code is written into a shell script, so nothing outside this character -// set may ever reach the response. +// The code is written into a script, so nothing outside this character set +// may ever reach the response. export const HANDOFF_CODE = /^sntryh_[A-Za-z0-9_-]{43}$/; const HEADERS = { @@ -15,27 +17,44 @@ const HEADERS = { "X-Robots-Tag": "noindex", }; -export function createHandler(installScript) { - const firstLineEnd = installScript.indexOf("\n") + 1; - if (!installScript.startsWith("#!") || firstLineEnd === 0) { +// bash runs the piped script in its own process, so an export after the +// shebang is enough. +function withBashHandoff(script) { + const firstLineEnd = script.indexOf("\n") + 1; + if (!script.startsWith("#!") || firstLineEnd === 0) { throw new Error("install script must start with a shebang line"); } - const shebang = installScript.slice(0, firstLineEnd); - const body = installScript.slice(firstLineEnd); + const shebang = script.slice(0, firstLineEnd); + const body = script.slice(firstLineEnd); + return (code) => `${shebang}export SENTRY_HANDOFF='${code}'\n${body}`; +} + +// iex runs the script in the caller's session, where $env: changes outlive +// the install. Remove the variable afterwards, even when the install throws, +// so the code does not stay in the user's session. +function withPowerShellHandoff(script) { + return (code) => + `$env:SENTRY_HANDOFF = '${code}'\ntry {\n${script}\n} finally {\n Remove-Item Env:SENTRY_HANDOFF -ErrorAction SilentlyContinue\n}\n`; +} + +// `scripts` holds the raw `install` (bash) and `install.ps1` scripts. +export function createHandler(scripts) { + const render = { + install: withBashHandoff(scripts.install), + "install.ps1": withPowerShellHandoff(scripts["install.ps1"]), + }; return function handler(request) { const url = new URL(request.url); - // The route rewrites /install/ to ?code=. Read the original - // path too, in case the function sees the URL before the rewrite. - const code = - url.searchParams.get("code") ?? - url.pathname.match(/^\/install\/([^/]+)$/)?.[1] ?? - ""; - if (!HANDOFF_CODE.test(code)) { + // The route rewrites /