From dcd23fcfca54b315ba27d80d1e07e8c6666ec278 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Miguel=20=C3=81ngel?= Date: Sun, 23 Aug 2026 20:40:48 +0000 Subject: [PATCH] fix(release): preserve recovery and publish diagnostics --- docs/contributing/release-channels.mdx | 5 +++ scripts/publish-packages.test.ts | 37 +++++++++++++++++- scripts/publish-packages.ts | 44 ++++++++++++++++++--- scripts/publish-workflow.test.mjs | 2 + scripts/release-packages.test.ts | 5 +++ scripts/release-packages.ts | 7 ++++ scripts/stable-release-guard.mjs | 6 +-- scripts/stable-release-guard.test.mjs | 54 ++++++++++++++++++++++++++ 8 files changed, 151 insertions(+), 9 deletions(-) diff --git a/docs/contributing/release-channels.mdx b/docs/contributing/release-channels.mdx index 7ec1f79cfd..6ad65063dd 100644 --- a/docs/contributing/release-channels.mdx +++ b/docs/contributing/release-channels.mdx @@ -80,3 +80,8 @@ fully covers it; never soften the unknown-rule failure into a warning. After updating and reviewing the guard, rerun the original merged-PR workflow for recovery. Do not push a stable tag, select a different SHA, or introduce a manual publish path. + +Bypass rejection is intentional: a ruleset result of `bypass` permanently blocks that merge SHA +from publishing. Release PRs must merge normally with their required approval and checks. If a +release PR was bypass-merged, prepare a fresh release PR and merge it normally; rerunning the +bypassed event cannot turn its historical rule-suite result into `pass`. diff --git a/scripts/publish-packages.test.ts b/scripts/publish-packages.test.ts index 734c676208..9eb91b2d64 100644 --- a/scripts/publish-packages.test.ts +++ b/scripts/publish-packages.test.ts @@ -3,7 +3,11 @@ import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "nod import { tmpdir } from "node:os"; import { join } from "node:path"; import { describe, it } from "node:test"; -import { runPublishPackages, type PublishCommand } from "./publish-packages.ts"; +import { + runPublishPackages, + sanitizePublishError, + type PublishCommand, +} from "./publish-packages.ts"; import { type PublishablePackage } from "./release-packages.ts"; const normal: PublishablePackage = { @@ -93,6 +97,37 @@ describe("shared package publisher", () => { } }); + it("preserves useful publish output while redacting secrets and user paths", async () => { + const root = fixture(); + const logs: string[] = []; + const error = Object.assign(new Error("npm publish failed for /home/private-user/project"), { + stdout: "uploaded package metadata\n", + stderr: + "npm ERR! code E403\n//registry.npmjs.org/:_authToken=super-secret\naccess_token=also-secret\n", + }); + try { + assert.match(sanitizePublishError(error), /E403/); + assert.doesNotMatch(sanitizePublishError(error), /super-secret|also-secret|private-user/); + await assert.rejects( + runPublishPackages( + { root, version: "1.2.3", distTag: "latest", roster: [normal, cli] }, + { + packageExists: async () => false, + command: async () => { + throw error; + }, + log: (message) => logs.push(message), + }, + ), + /E403/, + ); + assert.match(logs.join("\n"), /uploaded package metadata|E403/); + assert.doesNotMatch(logs.join("\n"), /super-secret|also-secret|private-user/); + } finally { + rmSync(root, { recursive: true, force: true }); + } + }); + it("fails reconciliation before any npm boundary when a public workspace is omitted", async () => { const root = fixture(); let calls = 0; diff --git a/scripts/publish-packages.ts b/scripts/publish-packages.ts index e57071d2ed..3cddb95fb3 100644 --- a/scripts/publish-packages.ts +++ b/scripts/publish-packages.ts @@ -30,6 +30,32 @@ type PublishInput = { }; type PublishResult = { published: string[]; skipped: string[]; failed: string[] }; +function outputText(value: unknown): string { + if (typeof value === "string") return value; + if (Buffer.isBuffer(value)) return value.toString("utf8"); + return ""; +} + +// Keep all credential/path redaction in one boundary before diagnostics reach logs or errors. +// fallow-ignore-next-line complexity +export function sanitizePublishError(error: unknown): string { + const record = error && typeof error === "object" ? error : {}; + const parts = [ + error instanceof Error ? error.message : String(error), + outputText("stdout" in record ? record.stdout : undefined), + outputText("stderr" in record ? record.stderr : undefined), + ]; + return parts + .filter(Boolean) + .join("\n") + .replace(/(authorization:\s*bearer\s+)\S+/gi, "$1[redacted]") + .replace(/((?:_authToken|access_token|token|password|secret)\s*[=:]\s*)\S+/gi, "$1[redacted]") + .replace(/\/home\/[^/\s]+/g, "$HOME") + .replace(/[A-Za-z]:\\Users\\[^\\\s]+/g, "$HOME") + .trim() + .slice(0, 8_000); +} + // The two allowed publish modes converge here so CLI restoration cannot be bypassed. // fallow-ignore-next-line complexity async function publishEntry( @@ -80,6 +106,7 @@ export async function runPublishPackages( ): Promise { const roster = validatePublishablePackages(input.root, input.roster ?? PUBLISHABLE_PACKAGES); const result: PublishResult = { published: [], skipped: [], failed: [] }; + const failedDetails: string[] = []; for (const entry of roster) { if (await dependencies.packageExists(entry.npmName, input.version)) { dependencies.log(`⏭️ ${entry.npmName}@${input.version} already published — skipping`); @@ -91,13 +118,20 @@ export async function runPublishPackages( await publishEntry(input.root, entry, input.distTag, dependencies.command); dependencies.log(`✅ ${entry.npmName}@${input.version} published`); result.published.push(entry.npmName); - } catch { - dependencies.log(`❌ ${entry.npmName}@${input.version} failed to publish`); + } catch (error) { + const diagnostic = sanitizePublishError(error); + dependencies.log( + `❌ ${entry.npmName}@${input.version} failed to publish${diagnostic ? `:\n${diagnostic}` : ""}`, + ); result.failed.push(entry.npmName); + failedDetails.push(`${entry.npmName}: ${diagnostic || "unknown publish failure"}`); } } - if (result.failed.length > 0) - throw new Error(`Packages failed to publish: ${result.failed.join(", ")}`); + if (result.failed.length > 0) { + throw new Error( + `Packages failed to publish: ${result.failed.join(", ")}\n${failedDetails.join("\n")}`, + ); + } return result; } @@ -111,7 +145,7 @@ const defaultDependencies: PublishDependencies = { } }, command: async (executable, args, cwd) => { - await execFileAsync(executable, [...args], { cwd }); + await execFileAsync(executable, [...args], { cwd, maxBuffer: 16 * 1024 * 1024 }); }, log: console.log, }; diff --git a/scripts/publish-workflow.test.mjs b/scripts/publish-workflow.test.mjs index ce130efd5c..76b3c42451 100644 --- a/scripts/publish-workflow.test.mjs +++ b/scripts/publish-workflow.test.mjs @@ -128,6 +128,8 @@ test("effective non-check rule enforcement and maintenance are explicit", () => assert.match(releaseRunbook, /NON_CHECK_RULES/); assert.match(releaseRunbook, /GitHub adds.*rule type/i); assert.match(releaseRunbook, /rerun the original merged-PR workflow/i); + assert.match(releaseRunbook, /bypass rejection is intentional/i); + assert.match(releaseRunbook, /merge.*normally/i); }); test("the workflow invokes one shared publisher and owns no package roster", () => { diff --git a/scripts/release-packages.test.ts b/scripts/release-packages.test.ts index a824cfb53e..b4dc7cc6d2 100644 --- a/scripts/release-packages.test.ts +++ b/scripts/release-packages.test.ts @@ -6,6 +6,7 @@ import { describe, it } from "node:test"; import { PUBLISHABLE_PACKAGES, discoverWorkspacePackages, + validateRepositoryPublishablePackages, validatePublishablePackages, type PublishablePackage, } from "./release-packages.ts"; @@ -35,6 +36,10 @@ function fixture(): string { // One fixture-backed matrix documents the complete reconciliation contract. // fallow-ignore-next-line unit-size describe("publishable package roster", () => { + it("directly reconciles the actual repository packages tree", () => { + assert.deepEqual(validateRepositoryPublishablePackages(), PUBLISHABLE_PACKAGES); + }); + it("covers every public workspace exactly once and excludes private workspaces", () => { const root = fixture(); try { diff --git a/scripts/release-packages.ts b/scripts/release-packages.ts index 8dd8f11a8b..1c0b2a61b5 100644 --- a/scripts/release-packages.ts +++ b/scripts/release-packages.ts @@ -1,6 +1,8 @@ import { existsSync, readFileSync, readdirSync } from "node:fs"; import { join } from "node:path"; +const REPOSITORY_ROOT = join(import.meta.dirname, ".."); + export type PublishMode = "workspace" | "manifest-name-override"; export type PublishablePackage = { @@ -172,3 +174,8 @@ export function validatePublishablePackages( } return roster; } + +/** CI-facing contract that directly reconciles the checked-out repository tree. */ +export function validateRepositoryPublishablePackages(): readonly PublishablePackage[] { + return validatePublishablePackages(REPOSITORY_ROOT); +} diff --git a/scripts/stable-release-guard.mjs b/scripts/stable-release-guard.mjs index ead3723a92..0241016afe 100644 --- a/scripts/stable-release-guard.mjs +++ b/scripts/stable-release-guard.mjs @@ -384,9 +384,9 @@ export async function runStableReleaseGuard({ } } -function createGitHubClient({ repository, token }) { +export function createGitHubClient({ repository, token, fetchImpl = fetch }) { const request = async (path, requestBudgetMs) => { - const response = await fetch(`https://api.github.com${path}`, { + const response = await fetchImpl(`https://api.github.com${path}`, { headers: { Accept: "application/vnd.github+json", Authorization: `Bearer ${token}`, @@ -420,7 +420,7 @@ function createGitHubClient({ repository, token }) { paginate(`/repos/${repository}/pulls/${number}/reviews`, null, requestBudgetMs), getRuleSuite: async (sha, requestBudgetMs) => { const suites = await paginate( - `/repos/${repository}/rulesets/rule-suites?ref=${encodeURIComponent("refs/heads/main")}`, + `/repos/${repository}/rulesets/rule-suites?ref=${encodeURIComponent("refs/heads/main")}&time_period=month`, null, requestBudgetMs, ); diff --git a/scripts/stable-release-guard.test.mjs b/scripts/stable-release-guard.test.mjs index f251006232..8e07e3a879 100644 --- a/scripts/stable-release-guard.test.mjs +++ b/scripts/stable-release-guard.test.mjs @@ -3,6 +3,7 @@ import { describe, it } from "node:test"; import { assertImmutableRelease, collectEffectiveApprovals, + createGitHubClient, evaluateRequiredChecks, extractEffectiveRules, parseGuardTimeoutMs, @@ -475,3 +476,56 @@ describe("stable release guard timeout configuration", () => { } }); }); + +describe("rule-suite recovery lookback", () => { + function clientForSuites(suites, requests) { + return createGitHubClient({ + repository: "heygen-com/hyperframes", + token: "test-token", + fetchImpl: async (url) => { + requests.push(String(url)); + return new Response(JSON.stringify(suites), { + status: 200, + headers: { "content-type": "application/json" }, + }); + }, + }); + } + + it("finds an exact passing merge suite older than the default day within the month", async () => { + const requests = []; + const client = clientForSuites( + [ + { + id: 1, + after_sha: mergeSha, + ref: "refs/heads/main", + result: "pass", + pushed_at: "2026-08-16T00:00:00Z", + }, + ], + requests, + ); + assert.deepEqual(await client.getRuleSuite(mergeSha, 1_000), { + afterSha: mergeSha, + ref: "refs/heads/main", + result: "pass", + }); + assert.match(requests[0], /time_period=month/); + }); + + it("fails closed when the month response is absent or ambiguous", async () => { + for (const suites of [ + [], + [ + { after_sha: mergeSha, ref: "refs/heads/main", result: "pass" }, + { after_sha: mergeSha, ref: "refs/heads/main", result: "pass" }, + ], + ]) { + await assert.rejects( + clientForSuites(suites, []).getRuleSuite(mergeSha, 1_000), + /Expected one rule suite/, + ); + } + }); +});