Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 4 additions & 7 deletions .github/workflows/cli-build.yml
Original file line number Diff line number Diff line change
Expand Up @@ -382,13 +382,10 @@ jobs:
- name: Remove sourcemaps
run: find apps/cli-docs/dist -name '*.map' -delete
- name: Package docs
run: |
output_dir="$RUNNER_TEMP/vercel-output"
rm -rf "$output_dir"
mkdir -p "$output_dir/.vercel/output/static"
cp -R apps/cli-docs/dist/. "$output_dir/.vercel/output/static/"
printf '%s\n' '{"version":3,"routes":[{"src":"^/install(\\.ps1)?$","headers":{"Vary":"Accept"},"continue":true},{"src":"^/install(\\.ps1)?$","has":[{"type":"header","key":"accept","value":{"re":".*text/html.*"}}],"dest":"/install-source/install$1/index.html","check":true},{"src":"^/install$","headers":{"Content-Type":"text/plain; charset=utf-8"},"continue":true}]}' > "$output_dir/.vercel/output/config.json"
(cd "$output_dir" && zip -qr "$GITHUB_WORKSPACE/vercel.zip" .vercel)
run: node apps/cli-docs/vercel/build-output.mjs "$RUNNER_TEMP/vercel-output/.vercel/output"
- name: Zip docs
working-directory: ${{ runner.temp }}/vercel-output
run: zip -qr "$GITHUB_WORKSPACE/vercel.zip" .vercel
- name: Upload docs artifact
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
with:
Expand Down
2 changes: 1 addition & 1 deletion apps/cli-docs/src/pages/install-source/[script].astro
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
---
// Browsers that open /install or /install.ps1 are rewritten here (see the
// Vercel config in .github/workflows/cli-build.yml); curl, wget, and irm still
// routes in apps/cli-docs/vercel/build-output.mjs); curl, wget, and irm still
// get the raw script. The markup copies Chrome's text/plain viewer, with color.
import { codeToHtml } from "shiki";
import bash from "../../../public/install?raw";
Expand Down
84 changes: 84 additions & 0 deletions apps/cli-docs/test/install-handoff.test.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
import assert from "node:assert/strict";
import { spawnSync } from "node:child_process";
import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { pathToFileURL } from "node:url";
import test from "node:test";
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`);

async function pipeToBash(response) {
return spawnSync("bash", [], {
input: await response.text(),
encoding: "utf8",
env: { PATH: process.env.PATH },
});
}

test("piping /install/<code> 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/${code}`,
]) {
const response = echoHandoff(new Request(url));
assert.equal(response.status, 200);
assert.equal(response.headers.get("cache-control"), "no-store");
const result = await pipeToBash(response);
assert.equal(result.status, 0, result.stderr);
assert.equal(result.stdout, code);
}
});

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)}`,
]) {
const response = echoHandoff(
new Request(`https://cli.sentry.dev/install-handoff?code=${encodeURIComponent(bad)}`),
);
assert.equal(response.status, 404, bad);
assert.equal(await response.text(), "Not found\n");
}
});

test("the packaged site routes /install/<code> to a function serving the install script", 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");
mkdirSync(dist);
writeFileSync(join(dist, "install"), script);
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 fn = join(output, "functions", "install-handoff.func");
assert.deepEqual(JSON.parse(readFileSync(join(fn, ".vc-config.json"), "utf8")), {
runtime: "edge",
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"));
} finally {
rmSync(dir, { recursive: true, force: true });
}
});
61 changes: 61 additions & 0 deletions apps/cli-docs/vercel/build-output.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
// Packages the built site (apps/cli-docs/dist) as Vercel Build Output API v3:
// the static files, the routes below, and the /install/<handoff code> Edge
// Function. Usage: node build-output.mjs <output dir, e.g. .vercel/output>
import { cpSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { join } from "node:path";
import { fileURLToPath } from "node:url";
import { HANDOFF_CODE } from "./install-handoff.mjs";

const HANDOFF_FUNCTION = "install-handoff";

const routes = [
// Browsers that open /install or /install.ps1 get the highlighted source
// page; curl, wget, and irm still get the raw script.
{ src: "^/install(\\.ps1)?$", headers: { Vary: "Accept" }, continue: true },
{
src: "^/install(\\.ps1)?$",
has: [{ type: "header", key: "accept", value: { re: ".*text/html.*" } }],
dest: "/install-source/install$1/index.html",
check: true,
},
{
src: "^/install$",
headers: { "Content-Type": "text/plain; charset=utf-8" },
continue: true,
},
{
src: `^/install/(${HANDOFF_CODE.source.slice(1, -1)})$`,
dest: `/${HANDOFF_FUNCTION}?code=$1`,
},
];

export function buildOutput(distDir, outputDir) {
rmSync(outputDir, { recursive: true, force: true });
cpSync(distDir, join(outputDir, "static"), { recursive: true });
writeFileSync(
join(outputDir, "config.json"),
`${JSON.stringify({ version: 3, routes })}\n`,
);

const functionDir = join(outputDir, "functions", `${HANDOFF_FUNCTION}.func`);
mkdirSync(functionDir, { recursive: true });
writeFileSync(
join(functionDir, ".vc-config.json"),
`${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");
writeFileSync(
join(functionDir, "index.js"),
`${handler}\nexport default createHandler(${JSON.stringify(installScript)});\n`,
);
}

if (process.argv[1] === fileURLToPath(import.meta.url)) {
const outputDir = process.argv[2];
if (!outputDir) {
console.error("usage: node build-output.mjs <output dir>");
process.exit(2);
}
buildOutput(fileURLToPath(new URL("../dist", import.meta.url)), outputDir);
}
41 changes: 41 additions & 0 deletions apps/cli-docs/vercel/install-handoff.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
// Serves cli.sentry.dev/install/<handoff code>: the install script with
// SENTRY_HANDOFF set, so `curl -fsSL https://cli.sentry.dev/install/<code> | 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.

// 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.
export const HANDOFF_CODE = /^sntryh_[A-Za-z0-9_-]{43}$/;

const HEADERS = {
"Content-Type": "text/plain; charset=utf-8",
// The response carries a credential: never cache or index it.
"Cache-Control": "no-store",
"X-Robots-Tag": "noindex",
};

export function createHandler(installScript) {
const firstLineEnd = installScript.indexOf("\n") + 1;
if (!installScript.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);

return function handler(request) {
const url = new URL(request.url);
// The route rewrites /install/<code> to ?code=<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)) {
return new Response("Not found\n", { status: 404, headers: HEADERS });
}
return new Response(`${shebang}export SENTRY_HANDOFF='${code}'\n${body}`, {
headers: HEADERS,
});
};
}
3 changes: 3 additions & 0 deletions docs/cli/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,9 @@ CLI releases build it from that workspace. Start here for repository guides:
- [CLI build workflow](../../.github/workflows/cli-build.yml) and
[release configuration](../../.craft.yml) — binaries, npm packaging, and
release-gated website artifacts.
- [Website packaging](../../apps/cli-docs/vercel/build-output.mjs) — the
Vercel routes for `/install`, and the `/install/<handoff code>` function that
serves the install script with `SENTRY_HANDOFF` set.
- [CLI nightly watchdog](../../.github/workflows/cli-nightly-watchdog.yml) —
hourly and after each main Build, checks for stuck or failed Build runs and a
GHCR `nightly` that lags main. It keeps one open alert issue while unhealthy,
Expand Down
Loading