diff --git a/.github/actions/standalone-release/action.yml b/.github/actions/standalone-release/action.yml new file mode 100644 index 0000000..52e3436 --- /dev/null +++ b/.github/actions/standalone-release/action.yml @@ -0,0 +1,145 @@ +name: Publish the standalone release asset +description: Build the exact tag and verify the uploaded HTML against its local SHA-256. +inputs: + tag: + description: Published stable release tag to build. + required: true + replace-standalone: + description: Allow an explicit maintenance rebuild to replace differing HTML. + required: false + default: 'false' + verify-only: + description: Check the existing SDK manifest before notes repair without uploading assets. + required: false + default: 'false' +outputs: + digest: + description: Verified SHA-256 of the uploaded HTML. + value: ${{ steps.standalone.outputs.digest }} +runs: + using: composite + steps: + - name: Verify the target release + shell: bash + env: + GH_TOKEN: ${{ github.token }} + RELEASE_TAG: ${{ inputs.tag }} + run: | + if [[ ! "$RELEASE_TAG" =~ ^v(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)$ || "$RELEASE_TAG" == v0.1.0 || "$RELEASE_TAG" == v0.1.1 ]]; then + echo "::error::Expected a stable vX.Y.Z tag after the two preserved releases." + exit 1 + fi + gh api "repos/$GITHUB_REPOSITORY/releases/tags/$RELEASE_TAG" | + jq -e --arg tag "$RELEASE_TAG" ' + .tag_name == $tag and .draft == false and (.published_at | fromdateiso8601 | type == "number")' + + - name: Check out the release tag + uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 + with: + ref: refs/tags/${{ inputs.tag }} + persist-credentials: false + path: released-source + fetch-depth: 0 + + - name: Confirm the tag belongs to the trusted main history + shell: bash + working-directory: released-source + env: + MAIN_SHA: ${{ github.sha }} + RELEASE_TAG: ${{ inputs.tag }} + run: | + [[ "$(git rev-parse HEAD)" == "$(git rev-parse "refs/tags/$RELEASE_TAG^{commit}")" ]] + git merge-base --is-ancestor HEAD "$MAIN_SHA" + + - name: Set up Node.js + uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 + with: + node-version: ${{ hashFiles('released-source/scripts/build-sdk.mjs') != '' && '24.18.0' || '22.23.5' }} + package-manager-cache: false + + - name: Build the standalone edition + id: build + if: inputs.verify-only != 'true' || hashFiles('released-source/scripts/build-sdk.mjs') != '' + shell: bash + working-directory: released-source + run: | + npm clean-install + # Vite embeds the current time. Use the tagged commit time for repeatable HTML. + SOURCE_DATE_EPOCH=$(git show -s --format=%ct HEAD) + export SOURCE_DATE_EPOCH + cat > "$RUNNER_TEMP/release-clock.cjs" <<'JS' + require('node:test').mock.timers.enable({ + apis: ['Date'], now: Number(process.env.SOURCE_DATE_EPOCH) * 1000, + }); + JS + NODE_OPTIONS="--require=$RUNNER_TEMP/release-clock.cjs" npm run build + if [[ -f scripts/build-sdk.mjs ]]; then + npm run check:sdk-dist + fi + + - name: Verify and publish the standalone HTML + id: standalone + if: success() && inputs.verify-only != 'true' && steps.build.outcome == 'success' + shell: bash + working-directory: released-source + env: + GH_TOKEN: ${{ github.token }} + GH_REPO: ${{ github.repository }} + RELEASE_TAG: ${{ inputs.tag }} + REPLACE_STANDALONE: ${{ inputs.replace-standalone }} + run: | + if [[ ! -f dist/decodebox.html || ! -s dist/decodebox.html ]]; then + echo "::error::The standalone build produced no HTML file." + exit 1 + fi + version=$(node -p "require('./package.json').version") + if [[ "$RELEASE_TAG" != "v$version" ]]; then + echo "::error::The package version does not match the release tag." + exit 1 + fi + name="OWASP-DecodeBox-Standalone-$RELEASE_TAG.html" + ASSET_PATH="$RUNNER_TEMP/$name" + cp dist/decodebox.html "$ASSET_PATH" + digest="sha256:$(sha256sum "$ASSET_PATH" | cut -d' ' -f1)" + existing=$(gh api "repos/$GITHUB_REPOSITORY/releases/tags/$RELEASE_TAG" | + jq -er --arg name "$name" '[.assets[] | select(.name == $name)] | + if length == 0 then "missing" elif length == 1 then (.[0].digest // "incomplete") + else error("duplicate standalone asset") end') + if [[ "$existing" == missing ]]; then + gh release upload "$RELEASE_TAG" "$ASSET_PATH" + elif [[ "$existing" != "$digest" ]]; then + [[ "$REPLACE_STANDALONE" == true ]] || { echo "::error::Existing HTML differs; review before rebuilding."; exit 1; } + gh release upload "$RELEASE_TAG" "$ASSET_PATH" --clobber + fi + gh api "repos/$GITHUB_REPOSITORY/releases/tags/$RELEASE_TAG" | \ + jq -e --arg tag "$RELEASE_TAG" --arg name "$name" --arg digest "$digest" ' + .tag_name == $tag and + any(.assets[]; .name == $name and .state == "uploaded" and .digest == $digest)' + echo "digest=$digest" >> "$GITHUB_OUTPUT" + + - name: Attach the verified SDK manifest for SDK-capable tags + id: manifest + if: >- + success() && steps.build.outcome == 'success' && hashFiles('released-source/scripts/build-sdk.mjs') != '' && + (steps.standalone.outcome == 'success' || inputs.verify-only == 'true') + working-directory: released-source + shell: bash + env: + GH_TOKEN: ${{ github.token }} + GH_REPO: ${{ github.repository }} + RELEASE_TAG: ${{ inputs.tag }} + VERIFY_ONLY: ${{ inputs.verify-only }} + run: | + manifest="dist/sdk/v1/${RELEASE_TAG#v}/SHA256SUMS" + asset="DecodeBox-SDK-$RELEASE_TAG-SHA256SUMS" + test -s "$manifest" + names=$(gh release view "$RELEASE_TAG" --json assets --jq '.assets[].name') + if ! grep -Fxq "$asset" <<< "$names"; then + if [[ "$VERIFY_ONLY" == true ]]; then + echo "::error::Missing SDK manifest. Run the release_tag rebuild first." + exit 1 + fi + cp "$manifest" "$RUNNER_TEMP/$asset" + gh release upload "$RELEASE_TAG" "$RUNNER_TEMP/$asset" + fi + gh release download "$RELEASE_TAG" --pattern "$asset" --output - | cmp - "$manifest" diff --git a/.github/scripts/fixtures/fake-gh.py b/.github/scripts/fixtures/fake-gh.py new file mode 100644 index 0000000..e3c5d29 --- /dev/null +++ b/.github/scripts/fixtures/fake-gh.py @@ -0,0 +1,98 @@ +#!/usr/bin/env python3 +"""Offline gh executable used only by the release CLI integration tests.""" +import hashlib +import json +import os +import sys +from pathlib import Path + +file = Path(os.environ["FAKE_GH_STATE"]) +# Check the process boundary before handling either publisher or workflow requests. +if (os.environ["PATH"] != str(file.parent / "bin") + or os.environ["HOME"] != str(file.parent) + or os.environ["GH_CONFIG_DIR"] != str(file.parent / "gh-config") + or any(key in os.environ for key in ( + "GH_TOKEN", "GITHUB_TOKEN", "GH_ENTERPRISE_TOKEN", "GITHUB_ENTERPRISE_TOKEN", + "GH_HOST", "XDG_CONFIG_HOME", "GIT_CONFIG_GLOBAL", "GH_TEST_CALLER_ONLY", + ))): + sys.exit("Expected the isolated, credential-free fixture environment.") +state = json.loads(file.read_text()) +release = state["release"] +args = sys.argv[1:] +repo = "repos/OWASP/DecodeBox/" +tag = release["tag_name"] +data = json.load(sys.stdin) if "--input" in args else None +state["calls"].append([args, data]) + + +def finish(value="", code=0): + file.write_text(json.dumps(state)) + if isinstance(value, bytes): + sys.stdout.buffer.write(value) + else: + print(value if isinstance(value, str) else json.dumps(value)) + sys.exit(code) + + +name = f"OWASP-DecodeBox-Standalone-{tag}.html" +manifest = f"DecodeBox-SDK-{tag}-SHA256SUMS" +if args == ["release", "view", tag, "--json", "assets", "--jq", ".assets[].name"]: + finish(manifest if "manifest" in state else "") +if args == ["release", "upload", tag, str(file.parent / manifest)]: + assert "manifest" not in state + state["manifest"] = (file.parent / manifest).read_text() + finish() +if args == ["release", "download", tag, "--pattern", manifest, "--output", "-"]: + finish(state["manifest"].encode()) +if args[:2] == ["release", "upload"]: + expected = ["release", "upload", tag, str(file.parent / name)] + assert args == (expected + ["--clobber"] if release["assets"] else expected) + if state.get("fault") == "upload": + finish(code=1) + blob = (file.parent / name).read_bytes() + digest = hashlib.sha256(blob).hexdigest() + if state.get("fault") == "digest": + digest = "0" * 64 + release["assets"] = [dict(id=73, name=name, state="uploaded", size=len(blob), digest="sha256:" + digest)] + finish() +if args == ["api", "-H", "Accept: application/octet-stream", repo + "releases/assets/73"]: + finish((file.parent / name).read_bytes()) +if args == ["api", repo + "releases/tags/" + tag]: + finish(release) +if args[:2] != ["api", "--method"]: + finish("Unexpected invocation", 2) +method, endpoint = args[2:4] +assert args[4:] == ([] if method == "GET" else ["--input", "-"]) +assert endpoint.startswith(repo) +route = endpoint[len(repo):] +if state.get("fault") == "invalid JSON": + finish("{") +if method == "GET" and state.get("fault") == "baseline edit" and route == f"releases/{release['id']}": + if sum(c[0] == args for c in state["calls"]) == 2: + release["body"] = "Maintainer edit before baseline." +if method == "GET" and route in (f"releases/{release['id']}", "releases/tags/" + tag): + if state.get("fault") == "concurrent edit" and route == f"releases/{release['id']}": + release["name"] = "Edited during contributor lookup" + finish(release) +if method == "POST" and route == "releases/generate-notes": + assert data == {"tag_name": tag, "previous_tag_name": "v0.1.1"} + if state.get("fault") == "contributors": + finish(code=1) + line = "* @alice made their first contribution in https://github.com/OWASP/DecodeBox/pull/31" + finish({"body": "## New Contributors\n" + line + "\n" + line}) +if method == "GET" and route == "pulls/31": + finish(dict(number=31, merge_commit_sha="a" * 40, user=dict(login="alice"), base=dict(ref="main", repo=dict(full_name="OWASP/DecodeBox")), + merged_at="2026-11-20T00:00:00Z")) +if method == "GET" and route == f"compare/v0.1.1...{tag}?per_page=100&page=1": + finish(dict(status="ahead", total_commits=1, commits=[dict(sha="a" * 40)])) +if method == "PATCH" and route == f"releases/{release['id']}": + assert set(data) in ({"body"}, {"name", "body"}) + if state.get("fault") == "reject PATCH": + finish(code=1) + release.update(data) + if state.get("fault") == "lose PATCH response": + finish(code=1) + if state.get("fault") == "invalid PATCH reply": + finish({}) + finish(release) +finish("Unexpected route", 2) diff --git a/.github/scripts/publish-release-notes.cjs b/.github/scripts/publish-release-notes.cjs new file mode 100644 index 0000000..5a6d707 --- /dev/null +++ b/.github/scripts/publish-release-notes.cjs @@ -0,0 +1,272 @@ +const { execFileSync, spawn } = require('node:child_process'); +const { createHash } = require('node:crypto'); +const { once } = require('node:events'); + +// GitHub supplies first-time status in generated Markdown, not in a structured field. +// Accept its contributor records only, then confirm the PR author and merge via the pulls API. +async function newContributors(repository, previousTag, tag, api, warn) { + let lines; + try { + const { body } = await api('POST', 'releases/generate-notes', { + tag_name: tag, previous_tag_name: previousTag, + }); + lines = body.split(/\r?\n/); + } catch { + warn('GitHub contributor metadata is unavailable. Omitting credits.'); + return []; + } + const heading = lines.indexOf('## New Contributors'); + if (heading < 0) return []; + if (heading !== lines.lastIndexOf('## New Contributors')) { + warn('Ambiguous GitHub contributor section. Omitting credits.'); + return []; + } + + const records = new Map(); + const authors = new Map(); + const ambiguous = new Set(); + for (const line of lines.slice(heading + 1)) { + if (/^#{1,6} |^\*\*Full Changelog/.test(line)) break; + if (!line.trim()) continue; + const match = /^[-*] @([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,37}[a-zA-Z0-9])?(?:\[bot\])?) made their first contribution in (?:https:\/\/github\.com\/([^/\s]+\/[^/\s]+)\/pull\/|#)([1-9]\d*)\.?$/.exec(line); + if (!match || (match[2] && match[2] !== repository)) { + warn('Unrecognized GitHub contributor record. Skipping it.'); + continue; + } + const [, login, , number] = match; + const author = login.toLowerCase(); + if (!Number.isSafeInteger(Number(number))) continue; + if (records.has(author) && records.get(author) !== number) ambiguous.add(author); + if (authors.has(number) && authors.get(number) !== author) { + ambiguous.add(author); + ambiguous.add(authors.get(number)); + } + records.set(author, number); + authors.set(number, author); + } + + const candidates = new Map(); + for (const [login, number] of records) { + if (ambiguous.has(login)) continue; + let pr; + try { + pr = await api('GET', `pulls/${number}`); + } catch { + warn(`Contributor metadata for PR #${number} is unavailable. Skipping it.`); + continue; + } + if (!Number.isFinite(Date.parse(pr?.merged_at)) || !/^[a-f0-9]{40}$/.test(pr?.merge_commit_sha) || + pr.base?.ref !== 'main' || pr.base.repo?.full_name !== repository || + typeof pr.user?.login !== 'string' || pr.user.login.toLowerCase() !== login || String(pr.number) !== number) { + warn(`Could not confirm the contributor on PR #${number}. Skipping it.`); + continue; + } + candidates.set(number, pr); + } + if (!candidates.size) return []; + + // A real merged PR for this repository may still belong to a different release. + const shas = new Set(); + const wanted = new Set([...candidates.values()].map(pr => pr.merge_commit_sha)); + try { + for (let page = 1; ; page++) { + const range = await api('GET', `compare/${previousTag}...${tag}?per_page=100&page=${page}`); + const remaining = range.total_commits - (page - 1) * 100; + if (range.status !== 'ahead' || !Number.isSafeInteger(range.total_commits) || + remaining < 1 || range.commits?.length !== Math.min(remaining, 100)) { + throw new Error('Incomplete release comparison.'); + } + for (const commit of range.commits) if (wanted.has(commit.sha)) shas.add(commit.sha); + if (shas.size === wanted.size || remaining <= 100) break; + } + } catch { + warn('Could not verify the release commit range. Omitting credits.'); + return []; + } + return [...candidates.values()].filter(pr => shas.has(pr.merge_commit_sha)).map(pr => + `- @${pr.user.login} made their first contribution in [#${pr.number}](https://github.com/${repository}/pull/${pr.number}).`); +} + +async function formatNotes(original, tag, repository, api, warn) { + const notes = original.replace(/\r\n/g, '\n').trim(); + const [header, ...lines] = notes.split('\n'); + const changes = lines.join('\n').trim(); + const match = /^## \[(?[\d.]+)\]\((?\S+\/compare\/(?v\d+\.\d+\.\d+)\.\.\.v[\d.]+)\) \((?\d{4}-\d{2}-\d{2})\)$/.exec(header); + if (!match || 'v' + match.groups.version !== tag || !changes || + match.groups.comparison !== `https://github.com/${repository}/compare/${match.groups.previousTag}...${tag}` || + /^## (?:What's Changed|New Contributors|Standalone Edition)$/m.test(changes)) { + throw new Error('Unrecognized Release Please notes. Leaving the published body intact.'); + } + const { comparison, previousTag, date } = match.groups; + const parsedDate = new Date(date); + const parts = value => value.slice(1).split('.').map(BigInt); + if (!/^v(0|[1-9]\d*)(\.(0|[1-9]\d*)){2}$/.test(previousTag) || + !Number.isFinite(parsedDate.getTime()) || parsedDate.toISOString().slice(0, 10) !== date) { + throw new Error('Invalid release comparison or calendar date.'); + } + const previous = parts(previousTag); + const current = parts(tag); + const difference = current.findIndex((v, i) => v !== previous[i]); + if (difference < 0 || current[difference] < previous[difference]) throw new Error('Invalid release version order.'); + const credits = await newContributors(repository, previousTag, tag, api, warn); + const title = `OWASP DecodeBox ${tag}`; + return [ + `# ${title}`, + `Changes since [${previousTag}](${comparison}) ยท ${date}`, + "## What's Changed", + changes, + ...(credits.length ? ['## New Contributors', credits.join('\n')] : []), + '## Standalone Edition', + `Download \`OWASP-DecodeBox-Standalone-${tag}.html\` from the release assets and open it in your browser.`, + 'Core encoding, decoding, and analysis work offline. Processing runs locally in your browser, ' + + 'with no installation or server required.', + 'Large inputs can pause the tab. Download a new copy for updates and security fixes.', + ].join('\n\n'); +} + +const marker = ''; +} + +function inspectMarker(release) { + const [visible, suffix, extra] = release.body.split('\n\n' + marker); + if (visible.includes(marker) || extra !== undefined) throw new Error('Malformed or duplicate integrity marker.'); + if (suffix === undefined) return null; + const fields = /^v2 (baseline|formatted) ([a-f0-9]{64}) ([a-f0-9]{64}) ([A-Za-z0-9+/]+={0,2}) [a-f0-9]{64} -->$/.exec(suffix); + if (!fields) throw new Error('Invalid release notes integrity marker.'); + const [, phase, originalHash, titleHash, archive] = fields; + const [title, original] = JSON.parse(Buffer.from(archive, 'base64').toString('utf8')); + if (typeof title !== 'string' || typeof original !== 'string' || + sha256(original) !== originalHash || sha256(title) !== titleHash || + markedBody(release, phase, visible, original, title) !== release.body || + (phase === 'baseline' && sha256(visible) !== originalHash)) { + throw new Error('Release body or integrity marker changed. Review the published notes.'); + } + const expectedTitle = 'OWASP DecodeBox ' + release.tag_name; + if (release.name !== expectedTitle && (phase === 'formatted' || sha256(release.name) !== titleHash)) { + throw new Error('The release title changed. Review the published title.'); + } + return { phase, visible, original, title, originalHash, titleHash }; +} + +function validateRelease(release, tag, id) { + if (!Number.isSafeInteger(release?.id) || release.id <= 0 || (id && String(release.id) !== id) || + release.tag_name !== tag || release.draft !== false || typeof release.published_at !== 'string' || + !Number.isFinite(Date.parse(release.published_at)) || + typeof release.name !== 'string' || typeof release.body !== 'string') { + throw new Error('Expected the requested published release, its ID, title and notes.'); + } +} + +function standaloneAsset(release) { + const name = 'OWASP-DecodeBox-Standalone-' + release.tag_name + '.html'; + const matches = release.assets?.filter(asset => asset.name === name) ?? []; + const [asset] = matches; + if (matches.length !== 1 || asset.state !== 'uploaded' || !Number.isSafeInteger(asset.id) || asset.id <= 0 || + !Number.isSafeInteger(asset.size) || asset.size <= 0 || !/^sha256:[a-f0-9]{64}$/.test(asset.digest)) { + throw new Error('Expected one uploaded ' + name + ' with a SHA-256 digest. Run the standalone rebuild first.'); + } + return asset; +} + +async function publishReleaseNotes({ mode, tag, id, original, title, version, digest, repository }, api, + warn = console.warn, downloadDigest = hashGitHubAsset) { + validateRepository(repository); + if (!['baseline', 'format', 'repair'].includes(mode)) throw new Error('Choose baseline, format or repair.'); + if (!/^v(0|[1-9]\d*)(\.(0|[1-9]\d*)){2}$/.test(tag) || ['v0.1.0', 'v0.1.1'].includes(tag)) { + throw new Error('Invalid or protected release tag.'); + } + if (mode !== 'repair' && !/^[1-9]\d*$/.test(id)) throw new Error('Missing release creation ID.'); + const current = await api('GET', mode === 'repair' ? 'releases/tags/' + tag : 'releases/' + id); + validateRelease(current, tag, mode === 'repair' ? undefined : id); + const endpoint = 'releases/' + current.id; + let payload; + if (mode === 'baseline') { + if ('v' + version !== tag || typeof original !== 'string' || !original || typeof title !== 'string' || !title) { + throw new Error('Incomplete Release Please creation response.'); + } + const state = inspectMarker(current); + if (state && state.originalHash === sha256(original) && state.titleHash === sha256(title)) return; + if (state || current.body !== original || current.name !== title) { + throw new Error('Title or body differs from the creation response. Refusing to record a baseline.'); + } + const latest = await api('GET', endpoint); + validateRelease(latest, tag, id); + if (latest.body !== original || latest.name !== title) throw new Error('Release changed before recording baseline.'); + payload = { body: markedBody(current, 'baseline', original, original, title) }; + } else { + const asset = standaloneAsset(current); + if (mode === 'repair') digest = await downloadDigest(repository, asset); + if (digest !== asset.digest) throw new Error('Standalone asset digest mismatch.'); + const state = inspectMarker(current); + if (!state) throw new Error('Missing creation baseline. Review the release manually.'); + if (state.phase === 'baseline') { + const formatted = await formatNotes(state.visible, tag, repository, api, warn); + payload = { body: markedBody(current, 'formatted', formatted, state.original, state.title) }; + const expectedTitle = 'OWASP DecodeBox ' + tag; + if (current.name !== expectedTitle) payload.name = expectedTitle; + } + + // Recheck after the download and contributor lookups, including on a no-op repair. + // GitHub documents no conditional PATCH for releases. + const latest = await api('GET', endpoint); + validateRelease(latest, tag, String(current.id)); + const latestAsset = standaloneAsset(latest); + if (latest.body !== current.body || latest.name !== current.name || + latestAsset.id !== asset.id || latestAsset.size !== asset.size || latestAsset.digest !== digest) { + throw new Error('Release metadata or asset changed while formatting. Retry after review.'); + } + if (state.phase === 'formatted') return; + } + const updated = await api('PATCH', endpoint, payload); + validateRelease(updated, tag, String(current.id)); + if (updated.body !== payload.body || updated.name !== (payload.name ?? current.name)) { + throw new Error('GitHub did not confirm the requested release metadata.'); + } + return updated.body; +} + +// Recovery has no local build. Stream the asset by its GitHub ID and hash the actual bytes. +async function hashGitHubAsset(repository, asset) { + const hash = createHash('sha256'); + let bytes = 0; + const child = spawn('gh', ['api', '-H', 'Accept: application/octet-stream', + 'repos/' + repository + '/releases/assets/' + asset.id], { shell: false, stdio: ['ignore', 'pipe', 'inherit'] }); + child.stdout.on('data', chunk => { + bytes += chunk.length; + hash.update(chunk); + }); + const [code] = await once(child, 'close'); + if (code !== 0 || bytes !== asset.size) throw new Error('Could not verify the complete standalone asset download.'); + return 'sha256:' + hash.digest('hex'); +} + +function validateRepository(repository) { + if (typeof repository !== 'string' || !/^[a-z0-9][a-z0-9-]*\/[a-z0-9_.-]+$/i.test(repository) || + ['.', '..'].includes(repository.split('/')[1])) throw new Error('Invalid GitHub repository.'); +} + +function githubApi(repository) { + validateRepository(repository); + return (method, path, payload) => JSON.parse(execFileSync('gh', [ + 'api', '--method', method, 'repos/' + repository + '/' + path, ...(payload ? ['--input', '-'] : []), + ], { shell: false, input: JSON.stringify(payload), encoding: 'utf8', maxBuffer: 4 * 1024 * 1024 })); +} + +module.exports = { publishReleaseNotes, githubApi }; +if (require.main === module) { + const { RELEASE_TAG: tag, RELEASE_ID: id, RELEASE_VERSION: version, ORIGINAL_TITLE: title, + ORIGINAL_NOTES: original, VERIFIED_DIGEST: digest, GITHUB_REPOSITORY: repository } = process.env; + publishReleaseNotes({ mode: process.argv[2], tag, id, version, title, original, digest, repository }, githubApi(repository)) + .catch(error => { console.error(error.message); process.exitCode = 1; }); +} diff --git a/.github/scripts/release-notes.cjs b/.github/scripts/release-notes.cjs index 327211d..d58bea1 100644 --- a/.github/scripts/release-notes.cjs +++ b/.github/scripts/release-notes.cjs @@ -1,5 +1,6 @@ const { GitHub, Manifest, registerChangelogNotes } = require('release-please'); const { DefaultChangelogNotes } = require('release-please/build/src/changelog-notes/default'); +const { githubApi } = require('./publish-release-notes.cjs'); const conventionalPreset = require('conventional-changelog-conventionalcommits'); // GitHub associates both the merge and its source commits with the same PR. @@ -20,7 +21,7 @@ function uniqueNotes(commits) { // Use the upstream renderer for scopes, issues, escaping and breaking notes. // Change its template punctuation, never the contributor's Markdown. -async function buildNotes(commits, options) { +async function buildNotes(commits, options, lookupPull) { const { writerOpts } = await conventionalPreset(); const renderer = new DefaultChangelogNotes({ mainTemplate: writerOpts.mainTemplate @@ -30,13 +31,59 @@ async function buildNotes(commits, options) { commitPartial: writerOpts.commitPartial.replace(/^\*/, '-') .replace('[{{shortHash}}]', '[`{{shortHash}}`]'), }); - return renderer.buildNotes(uniqueNotes(commits), options); + // An associated PR can belong to a different base. Confirm the association + // before it affects deduplication or adds a citation to the changelog. + const verified = []; + const pulls = new Map(); + const repository = `${options.owner}/${options.repository}`; + for (const commit of commits) { + const pr = commit.pullRequest; + let matches = false; + if (pr?.baseBranchName === 'main' && Number.isSafeInteger(pr.number) && pr.number > 0 && + /^[a-f0-9]{40}$/.test(pr.mergeCommitOid)) { + if (!pulls.has(pr.number)) { + try { pulls.set(pr.number, await lookupPull(pr.number)); } + catch { console.warn(`Could not verify PR #${pr.number}; keeping the commit citation.`); pulls.set(pr.number, null); } + } + const actual = pulls.get(pr.number); + matches = actual?.number === pr.number && Number.isFinite(Date.parse(actual.merged_at)) && + actual.base?.ref === 'main' && actual.base.repo?.full_name === repository && + actual.merge_commit_sha === pr.mergeCommitOid; + } + verified.push(matches || !pr ? commit : { ...commit, pullRequest: undefined }); + } + const changes = uniqueNotes(verified); + const notes = await renderer.buildNotes(changes, options); + const repo = `${options.host || 'https://github.com'}/${options.owner}/${options.repository}`; + const mergedPRs = new Map(changes + .filter(({ pullRequest: pr }) => pr?.mergeCommitOid && pr.baseBranchName === 'main') + .map(commit => [commit.sha, commit.pullRequest.number])); + + // Only annotate citations the renderer kept. A squash subject or issue footer + // can already contain a link to the same PR (GitHub also resolves /issues/N). + const numbers = new Set(mergedPRs.values()); + const linked = new Set(); + const withPRLinks = notes.replace(/\]\(([^\s)]+)\/(?:pull|issues)\/(\d+)\)/g, (link, host, id) => { + if (host !== repo || !numbers.has(Number(id))) return link; + linked.add(Number(id)); + return `](${repo}/pull/${id})`; + }); + return withPRLinks.replace(/\[`[0-9a-f]{7}`\]\(([^\s)]+)\/commit\/([0-9a-f]{40})\)/g, + (citation, host, sha) => { + const number = mergedPRs.get(sha); + if (host !== repo || !Number.isSafeInteger(number) || number <= 0 || linked.has(number)) return citation; + linked.add(number); + return `${citation}, [#${number}](${repo}/pull/${number})`; + }); } async function updateReleasePR() { const [owner, repo] = process.env.GITHUB_REPOSITORY.split('/'); const github = await GitHub.create({ owner, repo, token: process.env.GH_TOKEN }); - registerChangelogNotes('default', () => ({ buildNotes })); + const api = githubApi(process.env.GITHUB_REPOSITORY); + registerChangelogNotes('default', () => ({ + buildNotes: (commits, options) => buildNotes(commits, options, n => api('GET', 'pulls/' + n)), + })); const manifest = await Manifest.fromManifest(github, github.repository.defaultBranch, 'release-please-config.json', '.release-please-manifest.json', { skipLabeling: true }); await manifest.createPullRequests(); diff --git a/.github/scripts/verify-release-cli.cjs b/.github/scripts/verify-release-cli.cjs new file mode 100644 index 0000000..d3d12e4 --- /dev/null +++ b/.github/scripts/verify-release-cli.cjs @@ -0,0 +1,321 @@ +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const os = require('node:os'); +const path = require('node:path'); +const { spawnSync } = require('node:child_process'); +const { createHash } = require('node:crypto'); +const { test } = require('node:test'); +const YAML = require('yaml'); // From the pinned Release Please toolchain. + +const workflow = YAML.parse(fs.readFileSync('.github/workflows/release-please.yml', 'utf8')).jobs; +const action = YAML.parse(fs.readFileSync('.github/actions/standalone-release/action.yml', 'utf8')).runs.steps; +const upload = action.find(step => step.id === 'standalone'); +const tag = 'v0.1.2'; +const name = 'OWASP-DecodeBox-Standalone-' + tag + '.html'; +const title = 'v0.1.2'; +const notes = '## [0.1.2](https://github.com/OWASP/DecodeBox/compare/v0.1.1...v0.1.2) (2026-11-22)\n\n### Fixed\n\n- Restore a preference.'; + +function fixture(t) { + // PATH will contain this one directory. Ignore caller-controlled TMPDIR (it can contain ':'). + const dir = fs.mkdtempSync('/tmp/decodebox-release-'); + t.after(() => fs.rmSync(dir, { recursive: true, force: true })); + const bin = path.join(dir, 'bin'); + fs.mkdirSync(bin); + const gh = path.join(bin, 'gh'); + fs.symlinkSync(process.execPath, path.join(bin, 'node')); + // The workflow runs on Ubuntu. Expose only the utilities its tested steps need. + for (const tool of ['python3', 'jq', 'cp', 'cut', 'sha256sum', 'grep', 'cmp']) { + fs.symlinkSync('/usr/bin/' + tool, path.join(bin, tool)); + } + fs.copyFileSync(path.join(__dirname, 'fixtures/fake-gh.py'), gh); + fs.chmodSync(gh, 0o755); + fs.mkdirSync(path.join(dir, 'dist')); + fs.writeFileSync(path.join(dir, 'dist/decodebox.html'), 'offline'); + fs.writeFileSync(path.join(dir, 'package.json'), '{"version":"0.1.2"}'); + const file = path.join(dir, 'state.json'); + const read = () => JSON.parse(fs.readFileSync(file, 'utf8')); + const write = state => fs.writeFileSync(file, JSON.stringify(state)); + write({ calls: [], release: { tag_name: tag, id: 901, name: title, body: notes, draft: false, + published_at: '2026-11-22T00:00:00Z', assets: [] } }); + const config = path.join(dir, 'gh-config'); + fs.mkdirSync(config, { mode: 0o700 }); + const env = { PATH: bin, HOME: dir, GH_CONFIG_DIR: config, FAKE_GH_STATE: file, RUNNER_TEMP: dir, + GITHUB_OUTPUT: path.join(dir, 'output'), GITHUB_REPOSITORY: 'OWASP/DecodeBox', + REPLACE_STANDALONE: 'false', VERIFY_ONLY: 'false', RELEASE_TAG: tag, RELEASE_ID: '901', RELEASE_VERSION: '0.1.2', + ORIGINAL_TITLE: title, ORIGINAL_NOTES: notes }; + function check(r, success) { + assert.ifError(r.error); + assert.equal(r.status, success ? 0 : 1, r.stderr || r.stdout); + return r.stderr; + } + const cli = (mode, success = true, overrides = {}) => check( + spawnSync(process.execPath, ['publish-release-notes.cjs', mode], { + cwd: __dirname, env: { ...env, ...overrides }, shell: false, encoding: 'utf8', + }), success); + // Execute the checked-in workflow step on stdin. Its environment is data, never shell source. + const shell = (step, success = true) => check( + spawnSync('/bin/bash', ['-eu', '-o', 'pipefail', '-s'], { + input: step.run, cwd: dir, env, shell: false, encoding: 'utf8', + }), success); + function standalone(success = true) { + shell(action[0]); + shell(upload, success); + if (success) { + const receipt = fs.readFileSync(env.GITHUB_OUTPUT, 'utf8').trim(); + assert.match(receipt, /^digest=sha256:[a-f0-9]{64}$/); + env.VERIFIED_DIGEST = receipt.slice('digest='.length); + } else assert(!fs.existsSync(env.GITHUB_OUTPUT)); + } + const change = fn => { const state = read(); fn(state); write(state); }; + const fault = value => change(state => { state.fault = value; }); + const patchCount = () => read().calls.filter(([args]) => args[2] === 'PATCH').length; + return { cli, shell, standalone, read, change, fault, patchCount, env, dir }; +} + +test('publisher and workflow children use only the offline CLI and fixture configuration', t => { + // Use dummy caller values. The fake CLI checks its actual environment on every call. + const caller = fs.mkdtempSync(path.join(os.tmpdir(), 'decodebox-caller-')); + t.after(() => fs.rmSync(caller, { recursive: true, force: true })); + fs.symlinkSync('/bin/false', path.join(caller, 'gh')); + const sentinels = { + PATH: caller, HOME: caller, GH_CONFIG_DIR: caller, XDG_CONFIG_HOME: caller, + TMPDIR: caller + ':ignored', + GH_TOKEN: 'caller-only', GITHUB_TOKEN: 'caller-only', GH_ENTERPRISE_TOKEN: 'caller-only', + GITHUB_ENTERPRISE_TOKEN: 'caller-only', GH_HOST: 'caller.invalid', + GIT_CONFIG_GLOBAL: caller, GH_TEST_CALLER_ONLY: 'caller-only', + }; + for (const [key, value] of Object.entries(sentinels)) { + const original = process.env[key]; + t.after(() => { + if (original === undefined) delete process.env[key]; + else process.env[key] = original; + }); + process.env[key] = value; + } + const f = fixture(t); + f.cli('baseline'); + f.shell(action[0]); + assert.equal(f.patchCount(), 1); + // Ask Bash to resolve gh without executing it. Losing the shim must fail closed + // even on a runner with its own authenticated GitHub CLI installed. + fs.renameSync(path.join(f.dir, 'bin', 'gh'), path.join(f.dir, 'disabled-gh')); + f.shell({ run: 'if command -v gh; then exit 1; fi' }); + assert.match(f.cli('baseline', false), /spawnSync gh ENOENT/); + assert.equal(f.read().calls.at(-1)[0][1], 'repos/OWASP/DecodeBox/releases/tags/' + tag); +}); + +test('normal release records an idempotent baseline, verifies the build digest, then formats once', t => { + const f = fixture(t); + f.cli('baseline'); + assert(f.read().release.body.startsWith(notes + '\n\n$/)[1]; + assert.deepEqual(JSON.parse(Buffer.from(archive, 'base64')), [title, notes]); + f.cli('repair'); + assert.deepEqual(f.read().release, release); + assert.equal(f.patchCount(), 2); +}); + +test('only the creation response can establish a missing baseline after an interrupted write', t => { + const f = fixture(t); + f.fault('reject PATCH'); + f.cli('baseline', false); + assert.equal(f.read().release.body, notes); + f.standalone(); + f.fault(); + f.cli('repair', false); // Recovery cannot bless an unmarked body, even with a valid asset. + f.fault('lose PATCH response'); + f.cli('baseline', false); + f.fault(); + f.cli('baseline'); + assert.equal(f.patchCount(), 2); + f.cli('repair'); + assert.equal(f.patchCount(), 3); + f.fault('concurrent edit'); + f.cli('repair', false); // The no-op check also observes edits during asset verification. + assert.equal(f.patchCount(), 3); +}); + +for (const fault of ['upload', 'digest']) { + test(fault + ' failure preserves the original baseline and emits no verified digest', t => { + const f = fixture(t); + f.cli('baseline'); + const initial = f.read().release.body; + f.fault(fault); + f.standalone(false); + f.cli('repair', false); + assert.equal(f.read().release.body, initial); + assert.equal(f.patchCount(), 1); + f.fault(); + f.env.REPLACE_STANDALONE = 'true'; // Explicit maintenance rebuild can replace mismatched bytes. + f.standalone(); + f.cli('repair'); + assert.equal(f.patchCount(), 2); + }); +} + +for (const fault of ['reject PATCH', 'lose PATCH response', 'invalid PATCH reply']) { + test('recover after ' + fault + ' and repeat without a second applied update', t => { + const f = fixture(t); + f.cli('baseline'); + f.standalone(); + f.fault(fault); + f.cli('format', false); + f.fault(); + const before = f.patchCount(); + f.cli('repair'); + const saved = f.read().release; + f.cli('repair'); + assert.equal(f.patchCount(), before + Number(fault === 'reject PATCH')); + assert.deepEqual(f.read().release, saved); + assert.equal(saved.body.split("## What's Changed").length, 2); + }); +} + +test('unmarked, tampered, partial and manually edited releases fail closed', t => { + const f = fixture(t); + f.standalone(); + f.cli('repair', false); + f.cli('baseline', false, { ORIGINAL_TITLE: 'Different creation title' }); + assert.equal(f.patchCount(), 0); + f.cli('baseline'); + const baseline = f.read().release; + const wrongSeal = body => body.replace(/[a-f0-9]{64} -->$/, '0'.repeat(64) + ' -->'); + for (const body of [baseline.body + ' ', baseline.body.replace('preference.', 'preference!'), + wrongSeal(baseline.body), baseline.body.slice(0, -3), baseline.body + baseline.body, notes]) { + f.change(s => { s.release.body = body; }); + f.cli('repair', false); + assert.equal(f.read().release.body, body); + } + f.change(s => { s.release = { ...baseline, name: 'Maintainer title' }; }); + f.cli('repair', false); + f.change(s => { s.release = baseline; }); + f.fault('concurrent edit'); + f.cli('repair', false); + assert.equal(f.read().release.name, 'Edited during contributor lookup'); + assert.equal(f.patchCount(), 1); + f.fault('contributors'); + f.change(s => { s.release.name = 'OWASP DecodeBox ' + tag; }); + f.cli('repair'); + const formatted = f.read().release; + const [, payload] = f.read().calls.at(-1); + assert.deepEqual(Object.keys(payload), ['body']); // Expected title already present. + assert(!formatted.body.includes('## New Contributors')); + f.change(s => { s.release.name = title; }); + f.cli('repair', false); + f.change(s => { s.release = { ...formatted, body: wrongSeal(formatted.body) }; }); + f.cli('repair', false); + assert.equal(f.patchCount(), 2); +}); + +test('repair validates the release identity and the uploaded bytes before touching metadata', t => { + const f = fixture(t); + for (const value of ['v0.1.0', 'v0.1.1', 'v01.1.2', '0.1.2', 'v1.2.3-rc.1', '../main', '']) { + f.cli('repair', false, { RELEASE_TAG: value }); + } + assert.equal(f.read().calls.length, 0); + f.cli('baseline'); + f.standalone(); + const release = f.read().release; + for (const bad of [{ draft: true }, { published_at: null }, { tag_name: 'v0.3.5' }, { id: 0 }, + { assets: [] }, { assets: [{ ...release.assets[0], state: 'open' }] }, + { assets: [{ ...release.assets[0], name: 'wrong.html' }] }, { assets: [{ ...release.assets[0], digest: null }] }]) { + f.change(s => { s.release = { ...release, ...bad }; }); + f.cli('repair', false); + } + f.change(s => { s.release = release; }); + fs.appendFileSync(path.join(f.dir, name), 'modified'); + f.cli('repair', false); + f.fault('invalid JSON'); + f.cli('repair', false); + assert.equal(f.patchCount(), 1); +}); + +test('baseline rechecks the creation response before PATCH', t => { + const f = fixture(t); + f.fault('baseline edit'); + f.cli('baseline', false); + assert.equal(f.patchCount(), 0); + assert.equal(f.read().release.body, 'Maintainer edit before baseline.'); +}); + +test('invalid repository and protected tags make no CLI calls', t => { + const f = fixture(t); + for (const repo of ['', 'OWASP/..', 'a/b/c', 'OWASP/DecodeBox?other']) + f.cli('baseline', false, { GITHUB_REPOSITORY: repo }); + for (const value of ['v0.1.0', 'v0.1.1', 'main']) { + f.env.RELEASE_TAG = value; + f.shell(action[0], false); + } + assert.deepEqual(f.read().calls, []); +}); + +test('SDK manifest is immutable and repair can only verify it', t => { + const f = fixture(t); + const step = action.find(s => s.id === 'manifest'); + const node = action.find(s => s.uses?.startsWith('actions/setup-node@')); + assert.equal(node.with['node-version'], "$" + "{{ hashFiles('released-source/scripts/build-sdk.mjs') != '' && '24.18.0' || '22.23.5' }}"); + assert.match(action.find(s => s.id === 'build').run, /npm run check:sdk-dist/); + const directory = path.join(f.dir, 'dist/sdk/v1/0.1.2'); + fs.mkdirSync(directory, { recursive: true }); + fs.writeFileSync(path.join(directory, 'SHA256SUMS'), 'checksums\\n'); + f.env.VERIFY_ONLY = 'true'; + f.shell(step, false); + assert.equal(f.read().manifest, undefined); + f.env.VERIFY_ONLY = 'false'; + f.shell(step); + f.env.VERIFY_ONLY = 'true'; + f.shell(step); + f.change(s => { s.manifest = 'different bytes'; }); + f.shell(step, false); + f.env.VERIFY_ONLY = 'false'; + f.shell(step, false); + assert.equal(f.read().manifest, 'different bytes'); +}); + +test('workflow routes are exclusive and formatting requires the baseline and verified upload', t => { + const f = fixture(t); + const normal = workflow['release-please'], manual = workflow.maintenance; + assert.equal(normal.if, "github.ref == 'refs/heads/main' && inputs.release_tag == '' && inputs.repair_release_notes_tag == ''"); + assert.equal(manual.if, "github.ref == 'refs/heads/main' && (inputs.release_tag != '' || inputs.repair_release_notes_tag != '')"); + assert.deepEqual(manual.permissions, { contents: 'write', 'pull-requests': 'read' }); + const [conflict, checkout, rebuild, verify, repair] = manual.steps; + assert.equal(manual.steps.length, 5); + assert.equal(conflict.if, "inputs.release_tag != '' && inputs.repair_release_notes_tag != ''"); + f.shell(conflict, false); + assert(checkout.uses.startsWith('actions/checkout@')); + assert.equal(rebuild.if, "inputs.release_tag != '' && inputs.repair_release_notes_tag == ''"); + assert.equal(rebuild.uses, './.github/actions/standalone-release'); + assert.equal(repair.if, "inputs.repair_release_notes_tag != '' && inputs.release_tag == ''"); + assert.equal(rebuild.with['replace-standalone'], 'true'); + assert.equal(verify.if, repair.if); + assert.equal(verify.uses, rebuild.uses); + assert.equal(verify.with['verify-only'], 'true'); + assert.equal(repair.run, 'node .github/scripts/publish-release-notes.cjs repair'); + const tail = normal.steps.slice(normal.steps.findIndex(step => step.id === 'release')); + assert.deepEqual(tail.map(s => s.id || s.run), ['release', 'baseline', 'standalone', + 'node .github/scripts/publish-release-notes.cjs format', 'node .github/scripts/release-notes.cjs']); + assert.equal(tail[1].if, "steps.release.outputs.release_created == 'true'"); + assert.equal(tail[2].if, "success() && steps.baseline.outcome == 'success'"); + assert.equal(tail[3].if, "success() && steps.release.outputs.release_created == 'true' && steps.baseline.outcome == 'success' && steps.standalone.outcome == 'success'"); + assert.equal(upload.if, "success() && inputs.verify-only != 'true' && steps.build.outcome == 'success'"); + assert.equal(tail[3].env.VERIFIED_DIGEST, '$' + '{{ steps.standalone.outputs.digest }}'); + f.standalone(); + assert.equal(f.patchCount(), 0); + assert.equal(f.read().release.body, notes); + assert.equal(f.read().release.name, title); +}); diff --git a/.github/scripts/verify-release-notes.cjs b/.github/scripts/verify-release-notes.cjs index 36c1a6e..0619adf 100644 --- a/.github/scripts/verify-release-notes.cjs +++ b/.github/scripts/verify-release-notes.cjs @@ -3,14 +3,125 @@ const fs = require('node:fs'); const { parseConventionalCommits } = require('release-please/build/src/commit'); const { Changelog } = require('release-please/build/src/updaters/changelog'); const { PullRequestBody } = require('release-please/build/src/util/pull-request-body'); -const { buildNotes } = require('./release-notes.cjs'); +const { buildNotes: renderNotes } = require('./release-notes.cjs'); +const { publishReleaseNotes } = require('./publish-release-notes.cjs'); + +// Model the repository's merged PR records at the GitHub API boundary. +const mergeShas = { 25: 'f86d350b9a56f8e982140c2fc1a51eb606e34b39', 27: 'a'.repeat(40), + 31: 'a'.repeat(40), 32: 'c'.repeat(40), 33: 'd'.repeat(40), 34: 'e'.repeat(40), + 35: 'f'.repeat(40), 36: '1'.repeat(40) }; +const pull = number => ({ number, merged_at: '2026-11-20T00:00:00Z', + merge_commit_sha: mergeShas[number], base: { ref: 'main', repo: { full_name: 'OWASP/DecodeBox' } } }); +const buildNotes = (commits, options) => renderNotes(commits, options, pull); + +// Exercise the actual publication entry point. Only GitHub's HTTP boundary is mocked. +async function testPublication(options) { + const repository = 'OWASP/DecodeBox'; + const url = 'https://github.com/' + repository; + function change(message, number, digit) { + const sha = digit.repeat(40); + return { sha, message, pullRequest: { number, mergeCommitOid: mergeShas[number], baseBranchName: 'main', body: '' } }; + } + const optionsFor = version => ({ + ...options, version, previousTag: 'v0.1.1', currentTag: 'v' + version, + }); + const fix = change('fix(ui): restore the folder preference', 31, 'a'); + const fixes = await buildNotes(parseConventionalCommits([fix]), optionsFor('0.1.2')); + const changes = await buildNotes(parseConventionalCommits([ + fix, change('fix: preserve existing settings', 31, 'b'), + change('feat(data): accept another format\n\nBREAKING CHANGE: update the input format', 32, 'c'), + change('perf: reduce processing time (#33)', 33, 'd'), + change('security: validate imported recipes', 34, 'e'), + change('deps: update the parser', 35, 'f'), + change('docs: update an internal checklist', 36, '1'), + { sha: '2'.repeat(40), message: 'fix: handle empty files', pullRequest: { number: 39, baseBranchName: 'main', body: '' } }, + ]), optionsFor('0.2.0')); + const expected = "## What's Changed"; + const first = (login, number) => `* @${login} made their first contribution in ${url}/pull/${number}`; + const nativeChanges = `## What's Changed\n* An unrelated label-based title by @regular in ${url}/pull/31\n* Another by @regular in ${url}/pull/33`; + const native = [nativeChanges, '## New Contributors', first('new-user', 32), first('NEW-USER', 32), + first('incorrect', 31), first('new-user', 37).replace(repository, 'another/project'), + first('unavailable', 38), first('another-user', 34), '**Full Changelog**: ...'].join('\n'); + async function exercise(original, generated, settings = {}) { + const { releaseData } = PullRequestBody.parse('Proposed release.\n\n---\n\n' + original + '\n\n---\n\nRelease footer.'); + const tag = 'v' + releaseData[0].version.toString(); + const digest = 'sha256:' + 'a'.repeat(64); + const input = { repository, tag, version: tag.slice(1), id: '901', title: tag, + original: releaseData[0].notes, digest, ...settings }; + const release = { id: 901, tag_name: tag, name: tag, draft: false, published_at: '2026-11-20T01:00:00Z', + body: settings.liveBody ?? original, assets: [{ id: 22, name: 'OWASP-DecodeBox-Standalone-' + tag + '.html', + state: 'uploaded', size: 128, digest }] }; + const calls = [], warnings = []; + let saved; + const api = async (method, path, payload) => { + calls.push([method, path]); + if (method === 'POST' && path === 'releases/generate-notes') { + assert.deepEqual(payload, { previous_tag_name: 'v0.1.1', tag_name: tag }); + if (generated instanceof Error) throw generated; + return { body: generated }; + } + if (method === 'GET' && path.startsWith('pulls/')) { + const number = Number(path.slice(6)); + if (number === 38) throw new Error('unavailable'); + const login = { 31: 'regular', 32: 'new-user', 34: 'another-user' }[number]; + assert(login, 'unexpected PR lookup'); + return { number, merge_commit_sha: String(number).padStart(40, '0'), merged_at: '2026-11-20', base: { ref: 'main', repo: { full_name: repository } }, user: { login } }; + } + if (method === 'GET' && path === `compare/v0.1.1...${tag}?per_page=100&page=1`) + return { status: 'ahead', total_commits: 2, commits: [32, 34].map(n => ({ sha: String(n).padStart(40, '0') })) }; + assert.equal(path, 'releases/901'); + if (method === 'GET') return { ...release }; + assert.equal(method, 'PATCH'); + saved = payload; + return { ...Object.assign(release, payload) }; + }; + await publishReleaseNotes({ ...input, mode: 'baseline' }, api); + const body = await publishReleaseNotes({ ...input, mode: 'format' }, api, warning => warnings.push(warning)); + assert.deepEqual(saved, { name: 'OWASP DecodeBox ' + tag, body }); + return { body, calls, warnings }; + } + const full = await exercise(changes, native); + const [main, credits] = full.body.split('## New Contributors'); + for (const section of ['Added', 'Changed', 'Fixed', 'Security', 'Maintenance']) assert(main.includes('### ' + section)); + assert(main.includes('BREAKING CHANGES') && main.includes('update the input format') && main.includes('**data:**')); + assert(main.includes('v0.1.1...v0.2.0') && main.includes('handle empty files') && !main.includes('/pull/39')); + assert(!main.includes('internal checklist') && !main.includes('unrelated label-based title')); + assert.equal(main.split(url + '/pull/31)').length - 1, 1, 'one PR link for two distinct fixes'); + assert.equal((main.match(/\[#33\]/g) || []).length, 1, 'squash title already references its PR'); + assert(main.includes('[#33](' + url + '/pull/33)')); + assert(credits.includes('@new-user made their first contribution in [#32](' + url + '/pull/32)')); + assert(credits.includes('@another-user') && !credits.includes('@regular') && !credits.includes('@incorrect')); + assert.equal((credits.match(/made their first contribution/g) || []).length, 2); + assert.equal(full.calls.filter(([, path]) => path === 'pulls/32').length, 1); + assert(full.warnings.length > 0 && !full.calls.some(([, path]) => path === 'pulls/37')); + for (const text of [expected, '## New Contributors', '## Standalone Edition']) assert.equal(full.body.split(text).length, 2); + assert(full.body.includes('OWASP-DecodeBox-Standalone-v0.2.0.html') && full.body.includes('open it in your browser')); + assert(full.body.includes('offline') && full.body.includes('locally') && full.body.includes('no installation or server')); + for (const metadata of [ + nativeChanges, + '## New Contributors\n' + first('incorrect', 31), + '## New Contributors\n' + first('regular', 31), // Real author, merge outside the tag range. + ['## New Contributors', first('new-user', 32), first('new-user', 34)].join('\n'), + ['## New Contributors', first('new-user', 32), first('another-user', 32)].join('\n'), + ['## New Contributors', first('new-user', 32), '## New Contributors'].join('\n'), + new Error('rate limited'), null, + ]) { + const result = await exercise(fixes, metadata); + assert(result.body.includes('### Fixed') && !result.body.includes('### Added') && !result.body.includes('## New Contributors')); + assert(result.body.includes('OWASP-DecodeBox-Standalone-v0.1.2.html')); + if (typeof metadata !== 'string') assert(result.warnings.length); + } + for (const tag of ['v0.1.0', 'v0.1.1']) await assert.rejects(exercise(fixes, native, { tag }), /protected/); + await assert.rejects(exercise(fixes, nativeChanges, { liveBody: 'A maintainer edited these notes.' }), /creation response/); + return full.body; +} async function test() { // Both messages are from PR #25. The abbreviated source SHA also reproduces the Aspell error. const source = '25e50aee69509511979e2c53b622a6bb89bd0d29'; const merge = 'f86d350b9a56f8e982140c2fc1a51eb606e34b39'; const title = 'fix: improve sidebar quick-access defaults'; - const pullRequest = { number: 25, mergeCommitOid: merge, body: '' }; + const pullRequest = { number: 25, mergeCommitOid: merge, baseBranchName: 'main', body: '' }; const raw = [ { sha: merge, message: 'Merge pull request #25 from OWASP/fix/sidebar-quick-access-defaults\n\n' + title, pullRequest }, { sha: source, message: title, pullRequest }, @@ -23,8 +134,14 @@ async function test() { }; const first = await buildNotes(commits, options); assert.equal(first.split('improve sidebar quick-access defaults').length - 1, 1); + for (const patch of [{ merged_at: null }, { base: { ref: 'main', repo: { full_name: 'other/repo' } } }, + { base: { ref: 'next', repo: { full_name: 'OWASP/DecodeBox' } } }, { merge_commit_sha: source }]) { + const rejected = await renderNotes(commits, options, n => ({ ...pull(n), ...patch })); + assert(!rejected.includes('/pull/25)') && rejected.includes(source)); + } assert(first.includes('[`25e50ae`](https://github.com/OWASP/DecodeBox/commit/' + source + ')')); assert(!first.includes(merge)); + assert.equal(first.split('/pull/25)').length - 1, 1); const separatePR = { ...raw[1], sha: 'a'.repeat(40), pullRequest: { number: 27, body: '', mergeCommitOid: 'a'.repeat(40) } }; const scoped = await buildNotes(parseConventionalCommits([...raw, separatePR]), options); assert.equal(scoped.split('improve sidebar quick-access defaults').length - 1, 2, 'distinct PRs retain their notes'); @@ -50,6 +167,8 @@ async function test() { assert(changelog.endsWith(historical.slice(historical.indexOf('##')))); assert(!changelog.includes('\n\n\n') && !/^\* /m.test(changelog)); if (process.argv[2]) fs.writeFileSync(process.argv[2], changelog); + const release = await testPublication(options); + if (process.argv[3]) fs.writeFileSync(process.argv[3], release + '\n'); console.log('Release Please merge provenance, Markdown, release body and successive changelog updates passed.'); } diff --git a/.github/workflows/docs-quality.yml b/.github/workflows/docs-quality.yml index ec8b010..c15882e 100644 --- a/.github/workflows/docs-quality.yml +++ b/.github/workflows/docs-quality.yml @@ -11,6 +11,7 @@ on: - '.markdownlint-cli2.yaml' - '.github/scripts/**' - '.github/actions/release-please-tools/**' + - '.github/actions/standalone-release/**' - '.github/workflows/docs-quality.yml' - '.github/workflows/release-please.yml' - 'release-please-config.json' @@ -21,6 +22,7 @@ on: - '.markdownlint-cli2.yaml' - '.github/scripts/**' - '.github/actions/release-please-tools/**' + - '.github/actions/standalone-release/**' - '.github/workflows/docs-quality.yml' - '.github/workflows/release-please.yml' - 'release-please-config.json' @@ -60,14 +62,17 @@ jobs: env: NODE_PATH: ${{ runner.temp }}/release-please/node_modules run: | - mkdir docs-fixture + mkdir -p docs-fixture/release cp .markdownlint-cli2.yaml docs-fixture/ - node .github/scripts/verify-release-notes.cjs docs-fixture/CHANGELOG.md + cp .markdownlint-cli2.yaml docs-fixture/release/ + # Published notes contain the same long commit citations as the changelog. + node .github/scripts/verify-release-notes.cjs docs-fixture/CHANGELOG.md docs-fixture/release/CHANGELOG.md + node --test .github/scripts/verify-release-cli.cjs - - name: Lint the generated changelog with the project configuration + - name: Lint the generated changelog and final release body uses: DavidAnson/markdownlint-cli2-action@21c1be1b93ad9ed58fa840aacc3f279cde2a72ff # v24.2.0 with: - globs: docs-fixture/CHANGELOG.md + globs: docs-fixture/**/CHANGELOG.md # Link checking is advisory because external hosts may rate-limit CI runners. diff --git a/.github/workflows/release-please.yml b/.github/workflows/release-please.yml index ded32a9..8fc3fa4 100644 --- a/.github/workflows/release-please.yml +++ b/.github/workflows/release-please.yml @@ -11,6 +11,11 @@ on: required: false type: string + repair_release_notes_tag: + description: 'From main, repair the notes of an existing release with a verified standalone asset.' + required: false + type: string + permissions: contents: read @@ -21,7 +26,7 @@ concurrency: jobs: release-please: name: Manage release and standalone HTML - if: github.ref == 'refs/heads/main' + if: github.ref == 'refs/heads/main' && inputs.release_tag == '' && inputs.repair_release_notes_tag == '' runs-on: ubuntu-24.04 env: GH_REPO: ${{ github.repository }} @@ -35,19 +40,16 @@ jobs: steps: - name: Check out release tooling - if: inputs.release_tag == '' uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 with: persist-credentials: false - name: Prepare the pinned Release Please library - if: inputs.release_tag == '' uses: ./.github/actions/release-please-tools # The pinned action skips labeling new PRs, but requires its pending label # to update an open PR or publish a merged one. Reconcile its own root PR. - name: Recognize the pending Release Please PR - if: inputs.release_tag == '' env: GH_TOKEN: ${{ github.token }} run: | @@ -65,7 +67,6 @@ jobs: - name: Run Release Please id: release - if: inputs.release_tag == '' uses: googleapis/release-please-action@5c625bfb5d1ff62eadeeb3772007f7f66fdcf071 # v4 with: config-file: release-please-config.json @@ -73,107 +74,79 @@ jobs: skip-labeling: true skip-github-pull-request: true - - name: Verify the target release - id: target - if: steps.release.outputs.release_created == 'true' || inputs.release_tag != '' + - name: Record the original release title and notes + id: baseline + if: steps.release.outputs.release_created == 'true' env: GH_TOKEN: ${{ github.token }} - RELEASE_TAG: ${{ steps.release.outputs.tag_name || inputs.release_tag }} + RELEASE_TAG: ${{ steps.release.outputs.tag_name }} + RELEASE_ID: ${{ steps.release.outputs.id }} RELEASE_VERSION: ${{ steps.release.outputs.version }} + ORIGINAL_TITLE: ${{ steps.release.outputs.name }} + ORIGINAL_NOTES: ${{ steps.release.outputs.body }} + run: node .github/scripts/publish-release-notes.cjs baseline + + - name: Build, upload and verify the standalone HTML + id: standalone + if: success() && steps.baseline.outcome == 'success' + uses: ./.github/actions/standalone-release + with: + tag: ${{ steps.release.outputs.tag_name }} + + - name: Format the newly created GitHub Release + if: >- + success() && steps.release.outputs.release_created == 'true' && steps.baseline.outcome == 'success' && + steps.standalone.outcome == 'success' + env: + GH_TOKEN: ${{ github.token }} + RELEASE_TAG: ${{ steps.release.outputs.tag_name }} + RELEASE_ID: ${{ steps.release.outputs.id }} + VERIFIED_DIGEST: ${{ steps.standalone.outputs.digest }} + run: node .github/scripts/publish-release-notes.cjs format + + - name: Create or update the Release Please PR + env: + GH_TOKEN: ${{ github.token }} + NODE_PATH: ${{ runner.temp }}/release-please/node_modules + run: node .github/scripts/release-notes.cjs + + maintenance: + name: Repair a published release + if: github.ref == 'refs/heads/main' && (inputs.release_tag != '' || inputs.repair_release_notes_tag != '') + runs-on: ubuntu-24.04 + permissions: + contents: write + # Notes repair reads merged PR authors to verify contributor credits. + pull-requests: read + steps: + - name: Reject conflicting repair requests + if: inputs.release_tag != '' && inputs.repair_release_notes_tag != '' run: | - if [[ ! "$RELEASE_TAG" =~ ^v(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)$ || "$RELEASE_TAG" == v0.1.0 ]]; then - echo "::error::Expected a stable vX.Y.Z tag other than the preserved first release." - exit 1 - fi - if [[ -n "$RELEASE_VERSION" && "$RELEASE_TAG" != "v$RELEASE_VERSION" ]]; then - echo "::error::Release Please returned inconsistent tag and version outputs." - exit 1 - fi - actual_tag=$(gh release view "$RELEASE_TAG" --json tagName --jq .tagName) - [[ "$actual_tag" == "$RELEASE_TAG" ]] - echo "tag=$RELEASE_TAG" >> "$GITHUB_OUTPUT" + echo "::error::Choose either release_tag or repair_release_notes_tag, never both." + exit 1 - - name: Check out the release tag - if: steps.target.outputs.tag != '' + - name: Check out release tooling uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 with: - ref: refs/tags/${{ steps.target.outputs.tag }} persist-credentials: false - path: released-source - - name: Set up Node.js - if: steps.target.outputs.tag != '' - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 + - name: Rebuild the standalone HTML + if: inputs.release_tag != '' && inputs.repair_release_notes_tag == '' + uses: ./.github/actions/standalone-release with: - # Rebuild historical pre-SDK tags with their original toolchain. - node-version: ${{ hashFiles('released-source/scripts/build-sdk.mjs') != '' && '24.18.0' || '22.23.5' }} - package-manager-cache: false + tag: ${{ inputs.release_tag }} + replace-standalone: 'true' - - name: Build the standalone edition - if: steps.target.outputs.tag != '' - working-directory: released-source - run: | - npm clean-install - # Vite embeds the current time. Use the tagged commit time for repeatable HTML. - SOURCE_DATE_EPOCH=$(git show -s --format=%ct HEAD) - export SOURCE_DATE_EPOCH - cat > "$RUNNER_TEMP/release-clock.cjs" <<'JS' - require('node:test').mock.timers.enable({ - apis: ['Date'], now: Number(process.env.SOURCE_DATE_EPOCH) * 1000, - }); - JS - NODE_OPTIONS="--require=$RUNNER_TEMP/release-clock.cjs" npm run build - - - name: Verify and publish the standalone HTML - if: steps.target.outputs.tag != '' - working-directory: released-source - env: - GH_TOKEN: ${{ github.token }} - RELEASE_TAG: ${{ steps.target.outputs.tag }} - run: | - if [[ ! -f dist/decodebox.html || ! -s dist/decodebox.html ]]; then - echo "::error::The standalone build produced no HTML file." - exit 1 - fi - version=$(node -p "require('./package.json').version") - if [[ "$RELEASE_TAG" != "v$version" ]]; then - echo "::error::The package version does not match the release tag." - exit 1 - fi - name="OWASP-DecodeBox-Standalone-$RELEASE_TAG.html" - ASSET_PATH="$RUNNER_TEMP/$name" - cp dist/decodebox.html "$ASSET_PATH" - digest="sha256:$(sha256sum "$ASSET_PATH" | cut -d' ' -f1)" - gh release upload "$RELEASE_TAG" "$ASSET_PATH" --clobber - gh release edit "$RELEASE_TAG" --title "OWASP DecodeBox $RELEASE_TAG" - gh api "repos/$GH_REPO/releases/tags/$RELEASE_TAG" | \ - jq -e --arg tag "$RELEASE_TAG" --arg name "$name" --arg digest "$digest" ' - .tag_name == $tag and .name == ("OWASP DecodeBox " + $tag) and - any(.assets[]; .name == $name and .state == "uploaded" and .digest == $digest)' - - - name: Attach SDK integrity manifest to the tagged release - if: steps.target.outputs.tag != '' - working-directory: released-source - env: - GH_TOKEN: ${{ github.token }} - RELEASE_TAG: ${{ steps.target.outputs.tag }} - run: | - # Historical tags predate the SDK distribution. - if [[ -f scripts/check-sdk-dist.mjs ]]; then - npm run check:sdk-dist - manifest="dist/sdk/v1/${RELEASE_TAG#v}/SHA256SUMS" - asset="DecodeBox-SDK-$RELEASE_TAG-SHA256SUMS" - cp "$manifest" "$RUNNER_TEMP/$asset" - if gh release view "$RELEASE_TAG" --json assets --jq '.assets[].name' | grep -Fx "$asset"; then - gh release download "$RELEASE_TAG" --pattern "$asset" --output - | cmp - "$manifest" - else - gh release upload "$RELEASE_TAG" "$RUNNER_TEMP/$asset" - fi - fi + - name: Verify published assets for notes repair + if: inputs.repair_release_notes_tag != '' && inputs.release_tag == '' + uses: ./.github/actions/standalone-release + with: + tag: ${{ inputs.repair_release_notes_tag }} + verify-only: 'true' - - name: Create or update the Release Please PR - if: inputs.release_tag == '' + - name: Recover release notes + if: inputs.repair_release_notes_tag != '' && inputs.release_tag == '' env: GH_TOKEN: ${{ github.token }} - NODE_PATH: ${{ runner.temp }}/release-please/node_modules - run: node .github/scripts/release-notes.cjs + RELEASE_TAG: ${{ inputs.repair_release_notes_tag }} + run: node .github/scripts/publish-release-notes.cjs repair