From db7160565bd4bf4ac1852fd9fe8e2880de3afd85 Mon Sep 17 00:00:00 2001 From: Nick Vigilante Date: Wed, 21 Oct 2026 17:46:17 +0000 Subject: [PATCH 1/4] fix(apps): parse csp-check scripts with jsdom and scan dist tarballs with gitleaks csp-check found script tags with a regex, which misses an unterminated script src tag and wrongly reads script text inside a comment. It now parses the page with jsdom, as a browser does. The dist-release pack now unpacks each finished tarball and runs gitleaks over it, as the release design requires. A finding names the rule, file and line but not the matched text. With --release, or when CI is set, a missing gitleaks fails the pack instead of skipping the scan. Assisted-by: AI --- apps/dist-release/README.md | 2 + apps/dist-release/src/cli.mjs | 4 +- apps/dist-release/src/pack.mjs | 8 ++- apps/dist-release/src/pack.test.mjs | 38 +++++++++++- apps/dist-release/src/secrets.mjs | 37 ++++++++++++ apps/dist-release/src/secrets.test.mjs | 60 +++++++++++++++++++ .../offlinedocs/scripts/csp-check-helpers.mjs | 26 ++++---- .../scripts/csp-check-helpers.test.mjs | 22 +++++++ 8 files changed, 178 insertions(+), 19 deletions(-) create mode 100644 apps/dist-release/src/secrets.mjs create mode 100644 apps/dist-release/src/secrets.test.mjs diff --git a/apps/dist-release/README.md b/apps/dist-release/README.md index c0204deb..c1b817d0 100644 --- a/apps/dist-release/README.md +++ b/apps/dist-release/README.md @@ -19,6 +19,8 @@ Bytes such as gzip's OS field differ between toolchains, so the release workflow Each package tarball may hold only `package.json`, `README.md`, `LICENSE` and the paths that `PACKAGE_ALLOW` in `src/config.mjs` names for that package, whatever the package's own `files` field says. TypeScript source files other than declarations fail the pack wherever they are, as do `.map` files, `sourceMappingURL` comments, and entries that are not regular files or directories. Any comment left in a shipped `.js`, `.mjs`, `.cjs` or `.d.ts` file fails the pack too; the files are parsed, so `//` inside a string is not a comment. +Each finished tarball is unpacked and scanned with [gitleaks](https://github.com/gitleaks/gitleaks), and any finding fails the pack; findings name the rule, file and line, never the matched text. +With `--release`, or when `CI` is set, a missing `gitleaks` on `PATH` fails the pack too; otherwise the scan is skipped. The package READMEs ship as written, because they are written for consumers. The tarball's own `package.json` is read back and must be private, with this release's version and license, every `@coder` dependency a published package pinned to this release's URL, and every other dependency a plain registry range or tag. A `workspace:`, `catalog:`, `file:`, `link:` or `npm:` specifier, a git or GitHub spec, a URL, a path (including one that starts with `.`) or a `.tgz`, `.tar` or `.tar.gz` file fails the pack. diff --git a/apps/dist-release/src/cli.mjs b/apps/dist-release/src/cli.mjs index b9726aa1..1da4d309 100644 --- a/apps/dist-release/src/cli.mjs +++ b/apps/dist-release/src/cli.mjs @@ -36,10 +36,12 @@ if ((await readdir(outDir)).length) { console.error(`refusing to build: ${outDir} is not empty`); process.exit(1); } +// A release, or any CI run, fails when gitleaks is missing rather than skipping the scan. +const secretScan = { required: values.release || Boolean(process.env.CI) }; await buildPackagesForRelease(repoRoot); for (const pkg of PUBLISHED_PACKAGES) { console.log( - `packed ${path.basename(await packPackage({ repoRoot, pkg, version, license, outDir }))}`, + `packed ${path.basename(await packPackage({ repoRoot, pkg, version, license, outDir, secretScan }))}`, ); } console.log(`wrote ${await writeSha256Sums(outDir, releaseTarballNames(version))}`); diff --git a/apps/dist-release/src/pack.mjs b/apps/dist-release/src/pack.mjs index 6a4005a4..37fceaf7 100644 --- a/apps/dist-release/src/pack.mjs +++ b/apps/dist-release/src/pack.mjs @@ -13,6 +13,7 @@ import { readTarballEntry, } from "./contents.mjs"; import { assertReleaseDependencies, rewriteManifest } from "./manifest.mjs"; +import { findSecrets } from "./secrets.mjs"; const run = promisify(execFile); @@ -81,7 +82,7 @@ export async function checkTarball(pkg, file, { version, license }) { return problems; } -export async function packPackage({ repoRoot, pkg, version, license, outDir }) { +export async function packPackage({ repoRoot, pkg, version, license, outDir, secretScan = {} }) { if (!license.text?.trim()) throw new Error(`${pkg}: no license text to write as LICENSE`); const work = await mkdtemp(path.join(tmpdir(), `pack-${pkg}-`)); try { @@ -102,6 +103,11 @@ export async function packPackage({ repoRoot, pkg, version, license, outDir }) { ...(await findComments(packageDir)), ...(await checkTarball(pkg, file, { version, license })), ]; + // Scan what the tarball holds, not the directory it was packed from. + const unpacked = path.join(work, "unpacked"); + await mkdir(unpacked); + await run("tar", ["-xzf", file, "-C", unpacked]); + problems.push(...(await findSecrets(unpacked, secretScan))); if (problems.length) throw new Error(`${pkg}:\n ${problems.join("\n ")}`); const out = path.join(outDir, packageTarballName(pkg, version)); await copyFile(file, out); diff --git a/apps/dist-release/src/pack.test.mjs b/apps/dist-release/src/pack.test.mjs index 21d5e65f..a0ad1b2f 100644 --- a/apps/dist-release/src/pack.test.mjs +++ b/apps/dist-release/src/pack.test.mjs @@ -1,5 +1,5 @@ import assert from "node:assert/strict"; -import { execFileSync } from "node:child_process"; +import { execFileSync, spawnSync } from "node:child_process"; import { createHash } from "node:crypto"; import { existsSync, @@ -121,6 +121,42 @@ test("adding src to a package's files fails the pack and leaves no tarball", asy assert.deepEqual(readdirSync(outDir), []); }); +const hasGitleaks = spawnSync("gitleaks", ["version"]).status === 0; + +test( + "a secret in dist fails the pack and leaves no tarball", + { skip: hasGitleaks ? false : "gitleaks is not on PATH" }, + async () => { + const outDir = newOutDir(); + // Built at run time so no secret-shaped string is committed. + const key = ["AKIA", "ABCDEFGHIJKLMNOP"].join(""); + await assert.rejects( + packFake( + fakeRepo(["dist"], { extra: { "dist/leak.env": `AWS_ACCESS_KEY_ID=${key}\n` } }), + outDir, + ), + (error) => error.message.includes("secret (aws-access-token): package/dist/leak.env"), + ); + assert.deepEqual(readdirSync(outDir), []); + }, +); + +test("a required secret scan fails the pack when gitleaks is missing", async () => { + const outDir = newOutDir(); + await assert.rejects( + packPackage({ + repoRoot: fakeRepo(["dist"]), + pkg: "docs-ui", + version: "0.1.0", + license: apache, + outDir, + secretScan: { command: "gitleaks-is-not-installed", required: true }, + }), + /gitleaks is required but was not found/, + ); + assert.deepEqual(readdirSync(outDir), []); +}); + test("a source map in dist fails the pack and leaves no tarball", async () => { const outDir = newOutDir(); await assert.rejects( diff --git a/apps/dist-release/src/secrets.mjs b/apps/dist-release/src/secrets.mjs new file mode 100644 index 00000000..e24bae97 --- /dev/null +++ b/apps/dist-release/src/secrets.mjs @@ -0,0 +1,37 @@ +import { execFile } from "node:child_process"; +import { mkdtemp, readFile, rm } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { promisify } from "node:util"; + +const run = promisify(execFile); +// gitleaks exits 1 when it finds a leak, and 2 or more when it fails to run. +const LEAKS_FOUND = 1; + +/** + * Scan an unpacked package with gitleaks. A finding names the rule, file and line but never the + * matched text. Without gitleaks on PATH, a required scan fails and an optional one is skipped. + */ +export async function findSecrets(dir, { command = "gitleaks", required = false } = {}) { + const work = await mkdtemp(path.join(tmpdir(), "gitleaks-")); + const report = path.join(work, "report.json"); + try { + await run( + command, + ["dir", "--no-banner", "--redact", "--report-format", "json", "--report-path", report, dir], + { maxBuffer: 16 * 1024 * 1024 }, + ); + return []; + } catch (error) { + if (error.code === "ENOENT") { + return required ? [`gitleaks is required but was not found on PATH (${command})`] : []; + } + if (error.code !== LEAKS_FOUND) throw error; + const findings = JSON.parse(await readFile(report, "utf8")); + return findings.map( + (f) => `secret (${f.RuleID}): ${path.relative(dir, f.File)}:${f.StartLine}`, + ); + } finally { + await rm(work, { recursive: true, force: true }); + } +} diff --git a/apps/dist-release/src/secrets.test.mjs b/apps/dist-release/src/secrets.test.mjs new file mode 100644 index 00000000..b4abcc7d --- /dev/null +++ b/apps/dist-release/src/secrets.test.mjs @@ -0,0 +1,60 @@ +import assert from "node:assert/strict"; +import { execFileSync } from "node:child_process"; +import { mkdirSync, writeFileSync } from "node:fs"; +import path from "node:path"; +import test from "node:test"; +import { findSecrets } from "./secrets.mjs"; +import { tempDir } from "./temp-dir.mjs"; + +const hasGitleaks = (() => { + try { + execFileSync("gitleaks", ["version"], { stdio: "ignore" }); + return true; + } catch { + return false; + } +})(); +const needsGitleaks = hasGitleaks ? {} : { skip: "gitleaks is not on PATH" }; + +// Built at run time so no secret-shaped string is committed. +const plantedKey = () => `AWS_ACCESS_KEY_ID=${["AKIA", "ABCDEFGHIJKLMNOP"].join("")}\n`; + +function packageWith(name, body) { + const dir = tempDir("secrets-"); + mkdirSync(path.join(dir, "dist"), { recursive: true }); + writeFileSync(path.join(dir, "dist", name), body); + return dir; +} + +test("a missing gitleaks fails closed when it is required", async () => { + const problems = await findSecrets(tempDir("secrets-"), { + command: "gitleaks-is-not-installed", + required: true, + }); + assert.equal(problems.length, 1); + assert.match(problems[0], /gitleaks is required but was not found/); +}); + +test("a missing gitleaks is skipped when it is not required", async () => { + const problems = await findSecrets(tempDir("secrets-"), { + command: "gitleaks-is-not-installed", + required: false, + }); + assert.deepEqual(problems, []); +}); + +test("a clean package has no findings", needsGitleaks, async () => { + assert.deepEqual(await findSecrets(packageWith("index.js", "export {};\n"), {}), []); +}); + +test("a planted secret is reported by rule and file without its value", needsGitleaks, async () => { + const problems = await findSecrets(packageWith("config.env", plantedKey()), {}); + assert.equal(problems.length, 1); + assert.match(problems[0], /aws-access-token/); + assert.match(problems[0], /config\.env/); + assert.doesNotMatch(problems[0], /ABCDEFGHIJKLMNOP/); +}); + +test("a gitleaks run that errors is a problem, not a pass", needsGitleaks, async () => { + await assert.rejects(() => findSecrets(path.join(tempDir("secrets-"), "missing"), {})); +}); diff --git a/apps/offlinedocs/scripts/csp-check-helpers.mjs b/apps/offlinedocs/scripts/csp-check-helpers.mjs index 91d2f4cc..40a9f15f 100644 --- a/apps/offlinedocs/scripts/csp-check-helpers.mjs +++ b/apps/offlinedocs/scripts/csp-check-helpers.mjs @@ -1,6 +1,7 @@ // Pure helpers for scripts/csp-check.mjs, split out so the parsing and // per-script policy checks can be unit tested without a built export. import { createHash } from "node:crypto"; +import { JSDOM } from "jsdom"; /** * Parse a `Content-Security-Policy` header value into a directive -> token @@ -69,28 +70,21 @@ export function isJavaScriptScriptType(type) { * JavaScript MIME type (`application/json`, `importmap`, * `speculationrules`, ...) is a data block, not code — browsers never apply * script-src to it, so it is skipped. - * Matching is a plain regex over the serialized HTML, not a full parse: it - * is only asked to find `` tags, which Next always - * emits well-formed and un-nested. + * The document is parsed as a browser would, so an unterminated tag, a + * script inside a comment, and a script inside raw text are read as the + * browser reads them. * * @param {string} html * @returns {Array<{ type: "inline", body: string } | { type: "src", src: string }>} */ export function extractScripts(html) { const scripts = []; - const scriptTag = /]*)>([\s\S]*?)<\/script\b[^>]*>/gi; - let match = scriptTag.exec(html); - while (match !== null) { - const [, attrs, body] = match; - const typeMatch = attrs.match(/\btype\s*=\s*(?:"([^"]*)"|'([^']*)')/i); - const scriptType = typeMatch ? (typeMatch[1] ?? typeMatch[2]) : undefined; - if (isJavaScriptScriptType(scriptType)) { - const srcMatch = attrs.match(/\bsrc\s*=\s*(?:"([^"]*)"|'([^']*)')/i); - scripts.push( - srcMatch ? { type: "src", src: srcMatch[1] ?? srcMatch[2] } : { type: "inline", body }, - ); - } - match = scriptTag.exec(html); + for (const el of new JSDOM(html).window.document.querySelectorAll("script")) { + if (!isJavaScriptScriptType(el.getAttribute("type") ?? undefined)) continue; + const src = el.getAttribute("src"); + scripts.push( + src === null ? { type: "inline", body: el.textContent ?? "" } : { type: "src", src }, + ); } return scripts; } diff --git a/apps/offlinedocs/scripts/csp-check-helpers.test.mjs b/apps/offlinedocs/scripts/csp-check-helpers.test.mjs index b3715252..04bef9f6 100644 --- a/apps/offlinedocs/scripts/csp-check-helpers.test.mjs +++ b/apps/offlinedocs/scripts/csp-check-helpers.test.mjs @@ -55,6 +55,28 @@ test("extractScripts accepts single-quoted src attributes", () => { assert.deepEqual(extractScripts(html), [{ type: "src", src: "/a.js" }]); }); +test("extractScripts finds a src script that is never closed", () => { + assert.deepEqual(extractScripts(''; + assert.deepEqual(extractScripts(html), []); +}); + +test("extractScripts reads an unquoted src and the first of a repeated attribute", () => { + assert.deepEqual(extractScripts(""), [ + { type: "src", src: "/a.js" }, + ]); +}); + test("extractScripts returns nothing for HTML with no script tags", () => { assert.deepEqual(extractScripts("hi"), []); }); From d60ab8f8e2191fa335f65c374d24e9d7701a065f Mon Sep 17 00:00:00 2001 From: Nick Vigilante Date: Wed, 21 Oct 2026 13:36:47 -0700 Subject: [PATCH 2/4] fix(dist-release): fail closed on gitleaks errors and require the scan by default gitleaks exits 1 on fatal errors as well as on leaks, so a run that wrote an empty report and then failed (a timeout, for one) passed the pack. Leaks now get their own exit code, 3; any other non-zero exit throws with gitleaks' stderr, and the leak code with no findings throws too. A missing scan directory is an error rather than a clean scan of nothing. The scan was optional unless the caller asked otherwise, so a new caller or a local run skipped it silently. It is now required by default; the CLI's --allow-missing-gitleaks opts out for local dry runs only, is refused with --release or in CI, and a skipped scan prints "secret scan skipped". The scan now passes an explicit config and ignore path and ignores inline gitleaks:allow markers, so GITLEAKS_CONFIG, GITLEAKS_CONFIG_TOML and a .gitleaksignore in the working directory can't change it; a .gitleaksignore in the scanned directory fails it. The default config's path allowlist still skips .svg and other image, font and archive files, which the README now says. The CI test job installs a pinned, sha256-checked gitleaks for this package, and with CI set the secret-scan tests fail instead of skipping when it is missing, so the planted-secret checks run on every PR. Both test files share one gitleaks probe. Tarballs with symlinks or hardlinks are refused before they are extracted. Assisted-by: AI --- .github/workflows/ci.yml | 16 ++++ apps/dist-release/README.md | 8 +- apps/dist-release/src/cli.mjs | 13 ++- apps/dist-release/src/contents.mjs | 6 ++ apps/dist-release/src/contents.test.mjs | 21 +++- apps/dist-release/src/gitleaks-probe.mjs | 8 ++ apps/dist-release/src/pack.mjs | 9 +- apps/dist-release/src/pack.test.mjs | 50 +++++----- apps/dist-release/src/secrets.mjs | 53 ++++++++--- apps/dist-release/src/secrets.test.mjs | 116 +++++++++++++++++++---- 10 files changed, 236 insertions(+), 64 deletions(-) create mode 100644 apps/dist-release/src/gitleaks-probe.mjs diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 690e6c66..5f6ec7e0 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -126,9 +126,25 @@ jobs: - "@coder/docs-transforms" - "@coder/docs-ui" - "@coder/offlinedocs" + env: + GITLEAKS_VERSION: 8.30.1 + GITLEAKS_SHA256: 551f6fc83ea457d62a0d98237cbad105af8d557003051f41f3e7ca7b3f2470eb steps: - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 - uses: ./.github/actions/setup + # Pinned like actionlint below; with CI set, the secret-scan tests fail without it. + - name: Install gitleaks + if: matrix.package == '@coder/dist-release' + run: | + set -euo pipefail + base="https://github.com/gitleaks/gitleaks/releases/download/v${GITLEAKS_VERSION}" + tarball="gitleaks_${GITLEAKS_VERSION}_linux_x64.tar.gz" + cd "$RUNNER_TEMP" + curl -fsSLO "$base/$tarball" + echo "$GITLEAKS_SHA256 $tarball" | sha256sum -c - + mkdir -p gitleaks-bin + tar -xzf "$tarball" -C gitleaks-bin gitleaks + echo "$RUNNER_TEMP/gitleaks-bin" >> "$GITHUB_PATH" - name: Test run: pnpm turbo run test --filter=${{ matrix.package }} diff --git a/apps/dist-release/README.md b/apps/dist-release/README.md index c1b817d0..0feff451 100644 --- a/apps/dist-release/README.md +++ b/apps/dist-release/README.md @@ -19,8 +19,12 @@ Bytes such as gzip's OS field differ between toolchains, so the release workflow Each package tarball may hold only `package.json`, `README.md`, `LICENSE` and the paths that `PACKAGE_ALLOW` in `src/config.mjs` names for that package, whatever the package's own `files` field says. TypeScript source files other than declarations fail the pack wherever they are, as do `.map` files, `sourceMappingURL` comments, and entries that are not regular files or directories. Any comment left in a shipped `.js`, `.mjs`, `.cjs` or `.d.ts` file fails the pack too; the files are parsed, so `//` inside a string is not a comment. -Each finished tarball is unpacked and scanned with [gitleaks](https://github.com/gitleaks/gitleaks), and any finding fails the pack; findings name the rule, file and line, never the matched text. -With `--release`, or when `CI` is set, a missing `gitleaks` on `PATH` fails the pack too; otherwise the scan is skipped. +Each finished tarball is unpacked and scanned with [gitleaks](https://github.com/gitleaks/gitleaks) 8.19 or later (CI pins 8.30.1), and any finding fails the pack; findings name the rule, file and line, never the matched text. +A missing `gitleaks` on `PATH` fails the pack too. +For a local dry run only, `--allow-missing-gitleaks` skips the scan instead and prints `secret scan skipped`; it is refused with `--release` or when `CI` is set. +The scan uses gitleaks' built-in rules through an explicit config and ignore path, so `GITLEAKS_CONFIG`, `GITLEAKS_CONFIG_TOML` and a `.gitleaksignore` in the working directory don't change it, and a `.gitleaksignore` in the scanned directory fails it. +Inline `gitleaks:allow` markers are ignored, and an exit status other than 0 or gitleaks' leak status fails the pack with gitleaks' own error. +The built-in config skips image, font and archive extensions, including `.svg`, so a secret in a shipped `.svg` (such as `docs-theme`'s `assets/favicons/*.svg`) is not found; dropping that path allowlist would mean vendoring the whole default config. The package READMEs ship as written, because they are written for consumers. The tarball's own `package.json` is read back and must be private, with this release's version and license, every `@coder` dependency a published package pinned to this release's URL, and every other dependency a plain registry range or tag. A `workspace:`, `catalog:`, `file:`, `link:` or `npm:` specifier, a git or GitHub spec, a URL, a path (including one that starts with `.`) or a `.tgz`, `.tar` or `.tar.gz` file fails the pack. diff --git a/apps/dist-release/src/cli.mjs b/apps/dist-release/src/cli.mjs index 1da4d309..e5338414 100644 --- a/apps/dist-release/src/cli.mjs +++ b/apps/dist-release/src/cli.mjs @@ -15,11 +15,19 @@ const { positionals, values } = parseArgs({ tag: { type: "string" }, out: { type: "string" }, release: { type: "boolean", default: false }, + "allow-missing-gitleaks": { type: "boolean", default: false }, }, }); if (positionals[0] !== "build" || !values.tag || !values.out) { - console.error("usage: cli.mjs build --tag vX.Y.Z --out [--release]"); + console.error( + "usage: cli.mjs build --tag vX.Y.Z --out [--release | --allow-missing-gitleaks]", + ); + process.exit(2); +} +const allowMissingGitleaks = values["allow-missing-gitleaks"]; +if (allowMissingGitleaks && (values.release || process.env.CI)) { + console.error("--allow-missing-gitleaks is for local dry runs, not releases or CI"); process.exit(2); } let license, version; @@ -36,8 +44,7 @@ if ((await readdir(outDir)).length) { console.error(`refusing to build: ${outDir} is not empty`); process.exit(1); } -// A release, or any CI run, fails when gitleaks is missing rather than skipping the scan. -const secretScan = { required: values.release || Boolean(process.env.CI) }; +const secretScan = { required: !allowMissingGitleaks }; await buildPackagesForRelease(repoRoot); for (const pkg of PUBLISHED_PACKAGES) { console.log( diff --git a/apps/dist-release/src/contents.mjs b/apps/dist-release/src/contents.mjs index bfa48706..03b62030 100644 --- a/apps/dist-release/src/contents.mjs +++ b/apps/dist-release/src/contents.mjs @@ -66,6 +66,12 @@ export async function checkEntryTypes(file) { .map((line) => `not a regular file or directory: ${line}`); } +export async function extractTarball(file, dest) { + const problems = await checkEntryTypes(file); + if (problems.length) throw new Error(`${file}:\n ${problems.join("\n ")}`); + await run("tar", ["-xzf", file, "-C", dest]); +} + export async function findSourceMapReferences(dir) { const problems = []; for (const entry of await readdir(dir, { recursive: true, withFileTypes: true })) { diff --git a/apps/dist-release/src/contents.test.mjs b/apps/dist-release/src/contents.test.mjs index c255d296..1736a934 100644 --- a/apps/dist-release/src/contents.test.mjs +++ b/apps/dist-release/src/contents.test.mjs @@ -1,6 +1,6 @@ import assert from "node:assert/strict"; import { execFileSync } from "node:child_process"; -import { linkSync, mkdirSync, symlinkSync, writeFileSync } from "node:fs"; +import { linkSync, mkdirSync, readdirSync, symlinkSync, writeFileSync } from "node:fs"; import path from "node:path"; import test from "node:test"; import { @@ -8,6 +8,7 @@ import { checkEntries, checkEntryTypes, checkPackageEntries, + extractTarball, findComments, findSourceMapReferences, listTarball, @@ -135,6 +136,24 @@ test("a symlink or hardlink entry fails, naming it", async () => { assert.deepEqual(await checkEntryTypes(tarballOf({ "package/dist/index.js": "" })), []); }); +test("a tarball with a symlink is refused before anything is extracted", async () => { + const dir = tempDir("contents-"); + mkdirSync(path.join(dir, "package", "dist"), { recursive: true }); + writeFileSync(path.join(dir, "package", "dist", "index.js"), "export {};\n"); + symlinkSync("/etc/hosts", path.join(dir, "package", "dist", "hosts.js")); + const file = path.join(dir, "p.tgz"); + execFileSync("tar", ["-czf", file, "-C", dir, "package"]); + const dest = tempDir("contents-out-"); + await assert.rejects(extractTarball(file, dest), /not a regular file or directory: .*hosts\.js/); + assert.deepEqual(readdirSync(dest), []); +}); + +test("a tarball of regular files is extracted", async () => { + const dest = tempDir("contents-out-"); + await extractTarball(tarballOf({ "package/dist/index.js": "" }), dest); + assert.deepEqual(readdirSync(path.join(dest, "package", "dist")), ["index.js"]); +}); + test("a sourceMappingURL comment fails even with no .map file beside it", async () => { const dir = tempDir("contents-"); mkdirSync(path.join(dir, "dist", "nested"), { recursive: true }); diff --git a/apps/dist-release/src/gitleaks-probe.mjs b/apps/dist-release/src/gitleaks-probe.mjs new file mode 100644 index 00000000..74060eb1 --- /dev/null +++ b/apps/dist-release/src/gitleaks-probe.mjs @@ -0,0 +1,8 @@ +import { spawnSync } from "node:child_process"; + +const hasGitleaks = spawnSync("gitleaks", ["version"]).status === 0; + +// In CI a missing gitleaks fails these tests rather than skipping them. +export const needsGitleaks = { + skip: hasGitleaks || process.env.CI ? false : "gitleaks is not on PATH", +}; diff --git a/apps/dist-release/src/pack.mjs b/apps/dist-release/src/pack.mjs index 37fceaf7..62aad417 100644 --- a/apps/dist-release/src/pack.mjs +++ b/apps/dist-release/src/pack.mjs @@ -7,6 +7,7 @@ import { PUBLISHED_PACKAGES, packageTarballName } from "./config.mjs"; import { checkEntryTypes, checkPackageEntries, + extractTarball, findComments, findSourceMapReferences, listTarball, @@ -87,7 +88,7 @@ export async function packPackage({ repoRoot, pkg, version, license, outDir, sec const work = await mkdtemp(path.join(tmpdir(), `pack-${pkg}-`)); try { const first = await pnpmPack(path.join(repoRoot, "packages", pkg), path.join(work, "first")); - await run("tar", ["-xzf", first, "-C", work]); + await extractTarball(first, work); const packageDir = path.join(work, "package"); const manifestPath = path.join(packageDir, "package.json"); const manifest = rewriteManifest(JSON.parse(await readFile(manifestPath, "utf8")), { @@ -103,12 +104,14 @@ export async function packPackage({ repoRoot, pkg, version, license, outDir, sec ...(await findComments(packageDir)), ...(await checkTarball(pkg, file, { version, license })), ]; + const fail = () => new Error(`${pkg}:\n ${problems.join("\n ")}`); + if (problems.length) throw fail(); // Scan what the tarball holds, not the directory it was packed from. const unpacked = path.join(work, "unpacked"); await mkdir(unpacked); - await run("tar", ["-xzf", file, "-C", unpacked]); + await extractTarball(file, unpacked); problems.push(...(await findSecrets(unpacked, secretScan))); - if (problems.length) throw new Error(`${pkg}:\n ${problems.join("\n ")}`); + if (problems.length) throw fail(); const out = path.join(outDir, packageTarballName(pkg, version)); await copyFile(file, out); return out; diff --git a/apps/dist-release/src/pack.test.mjs b/apps/dist-release/src/pack.test.mjs index a0ad1b2f..980a88f6 100644 --- a/apps/dist-release/src/pack.test.mjs +++ b/apps/dist-release/src/pack.test.mjs @@ -1,5 +1,5 @@ import assert from "node:assert/strict"; -import { execFileSync, spawnSync } from "node:child_process"; +import { execFileSync } from "node:child_process"; import { createHash } from "node:crypto"; import { existsSync, @@ -12,6 +12,7 @@ import { import path from "node:path"; import test from "node:test"; import { listTarball, readTarballEntry } from "./contents.mjs"; +import { needsGitleaks } from "./gitleaks-probe.mjs"; import { checkTarball, packPackage, removePublishedDist } from "./pack.mjs"; import { tempDir } from "./temp-dir.mjs"; @@ -66,7 +67,14 @@ function fakeRepo( } const packFake = (repo, outDir = newOutDir(), license = apache) => - packPackage({ repoRoot: repo, pkg: "docs-ui", version: "0.1.0", license, outDir }); + packPackage({ + repoRoot: repo, + pkg: "docs-ui", + version: "0.1.0", + license, + outDir, + secretScan: { required: false }, + }); test("packs a workspace package with release URLs, catalog versions and the version", async () => { const file = await packFake( @@ -121,27 +129,21 @@ test("adding src to a package's files fails the pack and leaves no tarball", asy assert.deepEqual(readdirSync(outDir), []); }); -const hasGitleaks = spawnSync("gitleaks", ["version"]).status === 0; - -test( - "a secret in dist fails the pack and leaves no tarball", - { skip: hasGitleaks ? false : "gitleaks is not on PATH" }, - async () => { - const outDir = newOutDir(); - // Built at run time so no secret-shaped string is committed. - const key = ["AKIA", "ABCDEFGHIJKLMNOP"].join(""); - await assert.rejects( - packFake( - fakeRepo(["dist"], { extra: { "dist/leak.env": `AWS_ACCESS_KEY_ID=${key}\n` } }), - outDir, - ), - (error) => error.message.includes("secret (aws-access-token): package/dist/leak.env"), - ); - assert.deepEqual(readdirSync(outDir), []); - }, -); - -test("a required secret scan fails the pack when gitleaks is missing", async () => { +test("a secret in dist fails the pack and leaves no tarball", needsGitleaks, async () => { + const outDir = newOutDir(); + // Built at run time so no secret-shaped string is committed. + const key = ["AKIA", "ABCDEFGHIJKLMNOP"].join(""); + await assert.rejects( + packFake( + fakeRepo(["dist"], { extra: { "dist/leak.env": `AWS_ACCESS_KEY_ID=${key}\n` } }), + outDir, + ), + (error) => error.message.includes("secret (aws-access-token): package/dist/leak.env"), + ); + assert.deepEqual(readdirSync(outDir), []); +}); + +test("the secret scan is required by default, so a missing gitleaks fails the pack", async () => { const outDir = newOutDir(); await assert.rejects( packPackage({ @@ -150,7 +152,7 @@ test("a required secret scan fails the pack when gitleaks is missing", async () version: "0.1.0", license: apache, outDir, - secretScan: { command: "gitleaks-is-not-installed", required: true }, + secretScan: { command: "gitleaks-is-not-installed" }, }), /gitleaks is required but was not found/, ); diff --git a/apps/dist-release/src/secrets.mjs b/apps/dist-release/src/secrets.mjs index e24bae97..14b96c6a 100644 --- a/apps/dist-release/src/secrets.mjs +++ b/apps/dist-release/src/secrets.mjs @@ -1,33 +1,62 @@ import { execFile } from "node:child_process"; -import { mkdtemp, readFile, rm } from "node:fs/promises"; +import { mkdtemp, readFile, readdir, rm, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import path from "node:path"; -import { promisify } from "node:util"; +import { promisify, stripVTControlCharacters } from "node:util"; const run = promisify(execFile); -// gitleaks exits 1 when it finds a leak, and 2 or more when it fails to run. -const LEAKS_FOUND = 1; +// gitleaks exits 1 on fatal errors as well as on leaks, so leaks get a code of their own. +const LEAKS_FOUND = 3; +const CONFIG = "[extend]\nuseDefault = true\n"; /** - * Scan an unpacked package with gitleaks. A finding names the rule, file and line but never the - * matched text. Without gitleaks on PATH, a required scan fails and an optional one is skipped. + * Scan an unpacked package with gitleaks' built-in rules only. A finding names the rule, file and + * line, never the matched text. A missing gitleaks fails the scan unless `required` is false. */ -export async function findSecrets(dir, { command = "gitleaks", required = false } = {}) { +export async function findSecrets(dir, { command = "gitleaks", required = true } = {}) { + const entries = await readdir(dir); + if (entries.includes(".gitleaksignore")) { + return [".gitleaksignore would suppress findings: .gitleaksignore"]; + } const work = await mkdtemp(path.join(tmpdir(), "gitleaks-")); const report = path.join(work, "report.json"); + const config = path.join(work, "gitleaks.toml"); try { + await writeFile(config, CONFIG); await run( command, - ["dir", "--no-banner", "--redact", "--report-format", "json", "--report-path", report, dir], - { maxBuffer: 16 * 1024 * 1024 }, + [ + "dir", + "--no-banner", + "--redact", + "--ignore-gitleaks-allow", + "--config", + config, + "--gitleaks-ignore-path", + work, + "--exit-code", + String(LEAKS_FOUND), + "--report-format", + "json", + "--report-path", + report, + dir, + ], + { cwd: work, maxBuffer: 16 * 1024 * 1024 }, ); return []; } catch (error) { - if (error.code === "ENOENT") { - return required ? [`gitleaks is required but was not found on PATH (${command})`] : []; + if (error.code === "ENOENT" && error.path === command) { + if (required) return [`gitleaks is required but was not found on PATH (${command})`]; + console.warn(`secret scan skipped: gitleaks was not found on PATH (${command})`); + return []; + } + if (error.code !== LEAKS_FOUND) { + const stderr = stripVTControlCharacters(String(error.stderr ?? "")).trim(); + throw new Error(`gitleaks exited ${error.code}: ${stderr}`, { cause: error }); } - if (error.code !== LEAKS_FOUND) throw error; const findings = JSON.parse(await readFile(report, "utf8")); + if (!findings.length) throw new Error("gitleaks reported leaks but wrote no findings"); return findings.map( (f) => `secret (${f.RuleID}): ${path.relative(dir, f.File)}:${f.StartLine}`, ); diff --git a/apps/dist-release/src/secrets.test.mjs b/apps/dist-release/src/secrets.test.mjs index b4abcc7d..89cfcb30 100644 --- a/apps/dist-release/src/secrets.test.mjs +++ b/apps/dist-release/src/secrets.test.mjs @@ -1,21 +1,11 @@ import assert from "node:assert/strict"; -import { execFileSync } from "node:child_process"; -import { mkdirSync, writeFileSync } from "node:fs"; +import { chmodSync, mkdirSync, writeFileSync } from "node:fs"; import path from "node:path"; import test from "node:test"; +import { needsGitleaks } from "./gitleaks-probe.mjs"; import { findSecrets } from "./secrets.mjs"; import { tempDir } from "./temp-dir.mjs"; -const hasGitleaks = (() => { - try { - execFileSync("gitleaks", ["version"], { stdio: "ignore" }); - return true; - } catch { - return false; - } -})(); -const needsGitleaks = hasGitleaks ? {} : { skip: "gitleaks is not on PATH" }; - // Built at run time so no secret-shaped string is committed. const plantedKey = () => `AWS_ACCESS_KEY_ID=${["AKIA", "ABCDEFGHIJKLMNOP"].join("")}\n`; @@ -26,35 +16,123 @@ function packageWith(name, body) { return dir; } -test("a missing gitleaks fails closed when it is required", async () => { +// A stand-in for gitleaks that writes `report` to --report-path, prints `stderr` and exits `code`. +function fakeGitleaks({ code, report, stderr = "" }) { + const file = path.join(tempDir("fake-gitleaks-"), "gitleaks"); + writeFileSync( + file, + [ + "#!/bin/sh", + 'while [ $# -gt 0 ]; do [ "$1" = --report-path ] && printf %s ' + + `'${report}' > "$2"; shift; done`, + `printf %s '${stderr}' >&2`, + `exit ${code}`, + "", + ].join("\n"), + ); + chmodSync(file, 0o755); + return file; +} + +// Runs the real gitleaks with extra arguments after ours. +function gitleaksWith(...extra) { + const file = path.join(tempDir("gitleaks-wrapper-"), "gitleaks"); + writeFileSync(file, `#!/bin/sh\nexec gitleaks "$@" ${extra.join(" ")}\n`); + chmodSync(file, 0o755); + return file; +} + +test("a missing gitleaks fails closed by default", async () => { const problems = await findSecrets(tempDir("secrets-"), { command: "gitleaks-is-not-installed", - required: true, }); assert.equal(problems.length, 1); assert.match(problems[0], /gitleaks is required but was not found/); }); -test("a missing gitleaks is skipped when it is not required", async () => { +test("a missing gitleaks is skipped, with a warning, only when the scan is optional", async (t) => { + const warn = t.mock.method(console, "warn", () => {}); const problems = await findSecrets(tempDir("secrets-"), { command: "gitleaks-is-not-installed", required: false, }); assert.deepEqual(problems, []); + assert.equal(warn.mock.callCount(), 1); + assert.match(warn.mock.calls[0].arguments[0], /secret scan skipped/); +}); + +test("a gitleaks failure that writes an empty report is an error, with its stderr", async () => { + await assert.rejects( + findSecrets(tempDir("secrets-"), { + command: fakeGitleaks({ code: 1, report: "[]", stderr: "FTL timed out" }), + }), + /exited 1.*FTL timed out/s, + ); +}); + +test("the leaks exit code with no findings is an error, not a pass", async () => { + await assert.rejects( + findSecrets(tempDir("secrets-"), { command: fakeGitleaks({ code: 3, report: "[]" }) }), + /no findings/, + ); +}); + +test("a directory that does not exist is an error, not a clean scan", async () => { + await assert.rejects( + findSecrets(path.join(tempDir("secrets-"), "missing"), { + command: fakeGitleaks({ code: 0, report: "[]" }), + }), + /ENOENT/, + ); }); test("a clean package has no findings", needsGitleaks, async () => { - assert.deepEqual(await findSecrets(packageWith("index.js", "export {};\n"), {}), []); + assert.deepEqual(await findSecrets(packageWith("index.js", "export {};\n")), []); }); test("a planted secret is reported by rule and file without its value", needsGitleaks, async () => { - const problems = await findSecrets(packageWith("config.env", plantedKey()), {}); + const problems = await findSecrets(packageWith("config.env", plantedKey())); assert.equal(problems.length, 1); assert.match(problems[0], /aws-access-token/); assert.match(problems[0], /config\.env/); assert.doesNotMatch(problems[0], /ABCDEFGHIJKLMNOP/); }); -test("a gitleaks run that errors is a problem, not a pass", needsGitleaks, async () => { - await assert.rejects(() => findSecrets(path.join(tempDir("secrets-"), "missing"), {})); +test("a fatal gitleaks error is thrown with gitleaks' own message", needsGitleaks, async () => { + await assert.rejects( + findSecrets(packageWith("index.js", "export {};\n"), { + command: gitleaksWith("--config", "/nonexistent/gitleaks.toml"), + }), + /unable to load gitleaks config/, + ); +}); + +test("an inline gitleaks:allow marker does not hide a secret", needsGitleaks, async () => { + const body = plantedKey().replace("\n", " # gitleaks:allow\n"); + assert.deepEqual(await findSecrets(packageWith("config.env", body)), [ + "secret (aws-access-token): dist/config.env:1", + ]); +}); + +test("a config named in the environment does not change the scan", needsGitleaks, async (t) => { + const config = path.join(tempDir("secrets-"), "allow-all.toml"); + writeFileSync(config, "[allowlist]\npaths = ['''.*''']\n"); + for (const name of ["GITLEAKS_CONFIG", "GITLEAKS_CONFIG_TOML"]) { + const saved = process.env[name]; + process.env[name] = name === "GITLEAKS_CONFIG" ? config : "[allowlist]\npaths = ['''.*''']\n"; + t.after(() => { + if (saved === undefined) delete process.env[name]; + else process.env[name] = saved; + }); + } + assert.deepEqual(await findSecrets(packageWith("config.env", plantedKey())), [ + "secret (aws-access-token): dist/config.env:1", + ]); +}); + +test("a .gitleaksignore in the scanned directory fails the scan", async () => { + const dir = packageWith("index.js", "export {};\n"); + writeFileSync(path.join(dir, ".gitleaksignore"), ""); + const problems = await findSecrets(dir, { command: fakeGitleaks({ code: 0, report: "[]" }) }); + assert.deepEqual(problems, [".gitleaksignore would suppress findings: .gitleaksignore"]); }); From 6f845fac03cc4f8c76aad471275910f052d0fd0f Mon Sep 17 00:00:00 2001 From: Nick Vigilante Date: Wed, 21 Oct 2026 13:36:47 -0700 Subject: [PATCH 3/4] fix(offlinedocs): check scripts in template content and SVG script hrefs querySelectorAll does not enter template content, so a script inside a "; + assert.deepEqual(extractScripts(html), [ + { type: "src", src: "https://evil.example/t.js" }, + { type: "inline", body: "nested()" }, + { type: "inline", body: "after()" }, + ]); +}); + +test("extractScripts reads an SVG script's href and xlink:href as its src", () => { + const html = + '' + + ''; + assert.deepEqual(extractScripts(html), [ + { type: "src", src: "https://evil.example/x.js" }, + { type: "src", src: "https://evil.example/y.js" }, + { type: "inline", body: "inline()" }, + ]); +}); + test("extractScripts reads an unquoted src and the first of a repeated attribute", () => { assert.deepEqual(extractScripts(""), [ { type: "src", src: "/a.js" }, From 3d85a37cb0f28d946662c3141d1f67b4bd8845df Mon Sep 17 00:00:00 2001 From: Nick Vigilante Date: Wed, 21 Oct 2026 14:01:38 -0700 Subject: [PATCH 4/4] test(dist-release): build the allow-marker fixture without a single replace CodeQL read the one-off replace of the first newline as an incomplete sanitization. Splitting the planted key into lines and marking only the first says outright that one line carries the gitleaks:allow marker, and the test still fails if the scan honours it. Assisted-by: AI --- apps/dist-release/src/secrets.test.mjs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/apps/dist-release/src/secrets.test.mjs b/apps/dist-release/src/secrets.test.mjs index 89cfcb30..7beea617 100644 --- a/apps/dist-release/src/secrets.test.mjs +++ b/apps/dist-release/src/secrets.test.mjs @@ -108,7 +108,8 @@ test("a fatal gitleaks error is thrown with gitleaks' own message", needsGitleak }); test("an inline gitleaks:allow marker does not hide a secret", needsGitleaks, async () => { - const body = plantedKey().replace("\n", " # gitleaks:allow\n"); + const [first, ...rest] = plantedKey().split("\n"); + const body = [`${first} # gitleaks:allow`, ...rest].join("\n"); assert.deepEqual(await findSecrets(packageWith("config.env", body)), [ "secret (aws-access-token): dist/config.env:1", ]);