From 46a16b971516e17427df359965e0a05a44edb4eb Mon Sep 17 00:00:00 2001 From: Day Dreamer <87640074+HugoXK@users.noreply.github.com> Date: Mon, 16 Nov 2026 15:37:45 +0800 Subject: [PATCH 1/4] feat: add a superadmin one-click release action The Admin page now previews the live release state and can dispatch the existing daily-release workflow after a typed confirmation, recent GitHub re-authentication, CSRF and the destructive rate limit. The action never tags, merges or deploys; the normal release PR, gates, auto-merge, tag and publish chain stay in charge. The dispatch token is server-side and repo-scoped. --- .env.example | 7 + changelog.d/897-one-click-release.added.md | 1 + docs/deploy.md | 24 +++ docs/secrets.md | 1 + src/app.ts | 68 ++++++ src/config.ts | 15 ++ src/lib/releaseDispatch.ts | 229 +++++++++++++++++++++ src/lib/routeClasses.ts | 3 + src/views/pages.ts | 25 +++ test/helpers.ts | 2 + test/releaseDispatch.test.ts | 116 +++++++++++ 11 files changed, 491 insertions(+) create mode 100644 changelog.d/897-one-click-release.added.md create mode 100644 src/lib/releaseDispatch.ts create mode 100644 test/releaseDispatch.test.ts diff --git a/.env.example b/.env.example index 2252cdda..f359b4d3 100644 --- a/.env.example +++ b/.env.example @@ -141,6 +141,13 @@ INBOUND_EMAIL_SECRET= JOB_STALL_MINUTES=30 # Maximum jobs running at once across all repositories. PLATFORM_MAX_ACTIVE_JOBS=2 +# Superadmin one-click release: a repo-scoped token with Actions: write. Leave +# empty to disable the action; the token is read only on the server and is never +# rendered or logged. +RELEASE_DISPATCH_TOKEN= +RELEASE_DISPATCH_REPO=HugoXK/fledge +RELEASE_DISPATCH_WORKFLOW=daily-release.yml +RELEASE_DISPATCH_REF=main # A linked work item below this review score cannot auto-merge. A manual # maintainer merge can override; the override is audited. AUTO_MERGE_MIN_REVIEW_SCORE=80 diff --git a/changelog.d/897-one-click-release.added.md b/changelog.d/897-one-click-release.added.md new file mode 100644 index 00000000..a274c9ae --- /dev/null +++ b/changelog.d/897-one-click-release.added.md @@ -0,0 +1 @@ +A superadmin can now create the next mechanical release pull request from the Admin page. The action shows the current main commit, the latest release tag, the commits/fixes/features/fragments since that tag, the computed next version, the `ci-ok` result and the reason it is blocked, then dispatches the existing `daily-release` workflow after a typed confirmation and a recent GitHub re-authentication. It creates no tag, merge or deploy by itself; the normal release PR, gates, auto-merge, tag and publish chain still run. The dispatch token is server-side, repo-scoped and never rendered or logged. diff --git a/docs/deploy.md b/docs/deploy.md index fefa7bc1..fdfb66e9 100644 --- a/docs/deploy.md +++ b/docs/deploy.md @@ -307,6 +307,30 @@ status and how many reads were made, and a tip that never concludes ends the slo with `none` and that run id in the reason. A dry run never waits: it reports what a real run would have done. +#### Superadmin one-click release (#897) + +The Admin page has a superadmin-only release action. It reads the live GitHub +state and shows the current `main`, latest tag, commits/fixes/features/fragments +since that tag, the computed next version, `ci-ok` and the exact reason a release +is blocked. The action is enabled only when the normal rule is met, no release +PR/branch/tag is in flight and `ci-ok` is green. + +The submit button requires `RELEASE ` to be typed, a CSRF token, a +recent GitHub re-authentication, the destructive rate-limit class and an audit +row. It dispatches the existing `daily-release.yml` with `dry_run=false`; it +never creates a tag, merges a pull request or deploys a host. The existing +release PR, `ci-ok`, `review-gate`, auto-merge, tag job and `release.yml` publish +chain stay in charge. + +The dispatch credential is `RELEASE_DISPATCH_TOKEN` in the server `.env`, scoped +to the Fledge repository with only `Actions: write`; prefer a fine-grained token. +An empty value disables the action instead of failing the Admin page. The token +is never rendered, logged or returned by the route. + +A release is not a deploy. Production may already run `main` ahead of the latest +tag; the next infra `service-update-fledge.sh` run installs the version-bump +commit after the release PR merges. A separate operator action owns any restart. + #### Reliable slot trigger GitHub's `schedule` event is best-effort: on 2026-11-14 the then-`14:30Z` slot diff --git a/docs/secrets.md b/docs/secrets.md index fd1ea582..fbde4c4b 100644 --- a/docs/secrets.md +++ b/docs/secrets.md @@ -30,6 +30,7 @@ predates this inventory — it is not a value. | `GITHUB_APP_WEBHOOK_SECRET` | verifies App webhooks | production `.env` | random 32 bytes | owner | unknown | `openssl rand -hex 32` in both the App and `.env` | redeliver one webhook and confirm it is accepted | unknown | | `INBOUND_EMAIL_SECRET` | shared secret with the inbound Email Worker | production `.env` and the worker | random 32 bytes | owner | unknown | `openssl rand -hex 32` in both places | reply to one digest mail and confirm it lands | unknown | | `METRICS_TOKEN` | `/metrics` outside loopback | production `.env` | random 32 bytes | owner | unknown | `openssl rand -hex 32` then restart | `curl -H "Authorization: Bearer …" /metrics` returns 200 | unknown | +| `RELEASE_DISPATCH_TOKEN` | superadmin one-click release workflow dispatch | production `.env` | repo-scoped token with `Actions: write` on `HugoXK/fledge` only; fine-grained preferred, and no contents/PR write is needed | owner | unknown | mint a repo-scoped token, replace it in the server `.env`, restart Fledge | the release preview is `ready` and a `workflow_dispatch` run appears on `main` | unknown | | `NOTIFY_WEBHOOK_SECRET` | outbound notification webhook | production `.env` | random 32 bytes | owner | unknown | `openssl rand -hex 32` in both places | one event delivers with a valid signature | unknown | ## What is deliberately not in this table diff --git a/src/app.ts b/src/app.ts index 23f1ca8f..1305ecbd 100644 --- a/src/app.ts +++ b/src/app.ts @@ -66,6 +66,7 @@ import { scanUntrusted, UNTRUSTED_EVENT_KIND } from './lib/firewall.js' import { VERSION } from './version.js' import { clearGauge, incCounter, observeHistogram, renderMetrics, setGauge } from './lib/metrics.js' import { readReleaseStatus } from './lib/releaseStatus.js' +import { previewRelease, previewAndDispatch, type ReleaseDispatchPreview } from './lib/releaseDispatch.js' import { deploymentFromRow, deploymentHealth, @@ -5377,6 +5378,21 @@ export async function buildApp(options: BuildOptions): Promise { const auditPages = Math.max(1, Math.ceil(auditTotal / perPage)) const jobsPage = Math.min(pageNumber('jobsPage'), jobsPages) const auditPage = Math.min(pageNumber('auditPage'), auditPages) + let releaseDispatch: ReleaseDispatchPreview | null = null + let releaseDispatchError = '' + if (superadmin && config.release.dispatchToken !== '') { + try { + releaseDispatch = await previewRelease({ + fetch: globalThis.fetch, + token: config.release.dispatchToken, + repo: config.release.repo, + workflow: config.release.workflow, + ref: config.release.ref, + }) + } catch (error) { + releaseDispatchError = `GitHub preview failed: ${String(error instanceof Error ? error.message : error).slice(0, 200)}` + } + } return reply.type('text/html').send( adminPage({ config, @@ -5402,10 +5418,62 @@ export async function buildApp(options: BuildOptions): Promise { // Read from the data directory; a missing or unreadable snapshot renders // as "not recorded" rather than failing the page. releaseStatus: readReleaseStatus(config.dataDir), + releaseDispatch, + releaseDispatchError, }), ) }) + // #897: the superadmin one-click release action. It dispatches the existing + // release workflow after a typed confirmation; it never tags, merges or + // deploys. The POST re-reads the live preview so a stale form cannot dispatch + // a release that is no longer eligible. + app.post('/admin/release', { config: { rateLimit: destructiveClassLimit } }, async (request, reply) => { + const t = translator(request.locale ?? 'zh') + const viewer = requireSuperAdmin(request) + if (viewer.preview === true) return reply.redirect('/console') + if (!sessions.verifyCsrf(request, viewer)) throw httpError(403, '表单已过期,请刷新页面后重试。', 'CSRF_FAILED') + if (requireRecentAuth(request, reply, viewer, 'admin.release')) return reply + if (config.release.dispatchToken === '') { + return reply.redirect('/admin?error=' + encodeURIComponent(t('一键发布未配置 RELEASE_DISPATCH_TOKEN。', 'One-click release is not configured: set RELEASE_DISPATCH_TOKEN.'))) + } + let preview: ReleaseDispatchPreview + try { + preview = await previewRelease({ + fetch: globalThis.fetch, + token: config.release.dispatchToken, + repo: config.release.repo, + workflow: config.release.workflow, + ref: config.release.ref, + }) + } catch (error) { + store.audit(viewer.user.id, 'release.dispatch_failed', String(error instanceof Error ? error.message : error).slice(0, 300)) + return reply.redirect('/admin?error=' + encodeURIComponent(t(`读取发布状态失败:${String(error instanceof Error ? error.message : error).slice(0, 200)}`, `Could not read the release state: ${String(error instanceof Error ? error.message : error).slice(0, 200)}`))) + } + if (!preview.eligible) { + return reply.redirect('/admin?error=' + encodeURIComponent(t(`一键发布不可用:${preview.reason}`, `One-click release is unavailable: ${preview.reason}`))) + } + const confirm = String((request.body as Record | undefined)?.confirm ?? '').trim() + if (confirm !== `RELEASE ${preview.nextVersion}`) { + return reply.redirect('/admin?error=' + encodeURIComponent(t(`请准确输入 RELEASE ${preview.nextVersion} 以确认。`, `Type RELEASE ${preview.nextVersion} to confirm.`))) + } + store.audit(viewer.user.id, 'release.requested', `${preview.repo} v${preview.nextVersion} ${preview.mainSha}`) + try { + const { result } = await previewAndDispatch({ + fetch: globalThis.fetch, + token: config.release.dispatchToken, + repo: config.release.repo, + workflow: config.release.workflow, + ref: config.release.ref, + }) + store.audit(viewer.user.id, 'release.dispatched', `${preview.repo} v${preview.nextVersion} ${result.runUrl}`) + return reply.redirect('/admin?notice=' + encodeURIComponent(t(`已启动 v${preview.nextVersion} 发布流程:${result.runUrl}`, `Started the v${preview.nextVersion} release: ${result.runUrl}`)) + '#release') + } catch (error) { + store.audit(viewer.user.id, 'release.dispatch_failed', String(error instanceof Error ? error.message : error).slice(0, 300)) + return reply.redirect('/admin?error=' + encodeURIComponent(t(`发布启动失败:${String(error instanceof Error ? error.message : error).slice(0, 200)}`, `Could not start the release: ${String(error instanceof Error ? error.message : error).slice(0, 200)}`)) + '#release') + } + }) + // #395: the deployment read model. The latest release comes from the // `verify-release.mjs` snapshot this instance already reads on /admin, and the // running side is the recorded deployment row. Fledge never probes a host or diff --git a/src/config.ts b/src/config.ts index 6541fa7a..5657346a 100644 --- a/src/config.ts +++ b/src/config.ts @@ -30,6 +30,15 @@ export interface Config { } // How long a GitHub re-authentication stays "recent" for destructive actions. recentAuthMinutes: number + // #897: the superadmin release action dispatches the existing release + // workflow. The token only needs Actions: write on the Fledge repository; it + // is a server secret and is never rendered or logged. + release: { + dispatchToken: string + repo: string + workflow: string + ref: string + } // #690: how long after its `trial.expired` row a never-used rejected account is // erased. The sweep's purge phase reads this; 72 hours is the host-side cron it // replaces. @@ -307,6 +316,12 @@ export function loadConfig(overrides: Partial = {}): Config { instancesGlobal: Math.max(0, number('LIMIT_INSTANCES_GLOBAL', 0)), }, recentAuthMinutes: Math.max(1, number('RECENT_AUTH_MINUTES', 15)), + release: { + dispatchToken: text('RELEASE_DISPATCH_TOKEN'), + repo: text('RELEASE_DISPATCH_REPO', 'HugoXK/fledge'), + workflow: text('RELEASE_DISPATCH_WORKFLOW', 'daily-release.yml'), + ref: text('RELEASE_DISPATCH_REF', 'main'), + }, trialPurgeGraceHours: Math.max(1, number('TRIAL_PURGE_GRACE_HOURS', 72)), autoPromoteDiscovery: bool('AUTO_PROMOTE_DISCOVERY', false), autoPromoteDiscoveryDailyCap: Math.max(0, number('AUTO_PROMOTE_DISCOVERY_DAILY_CAP', 3)), diff --git a/src/lib/releaseDispatch.ts b/src/lib/releaseDispatch.ts new file mode 100644 index 00000000..1d455e20 --- /dev/null +++ b/src/lib/releaseDispatch.ts @@ -0,0 +1,229 @@ +import { nextReleaseVersion } from '../../scripts/lib/release-version.mjs' + +// #897: the superadmin release action is a preview plus a dispatch. It never +// creates a tag, merges a pull request or deploys: the existing release +// workflow does that under its normal gates. The only write in this module is +// the workflow_dispatch call. + +export interface ReleaseDispatchPreview { + repo: string + workflow: string + mainSha: string + mainDate: string + latestTag: string + latestTagSha: string + packageVersion: string + nextVersion: string + aheadCommits: number + fixes: number + features: number + others: number + fragments: number + ciOk: string + openReleasePr: { number: number; title: string; headSha: string; branch: string; url: string } | null + tagExists: boolean + branchExists: boolean + eligible: boolean + reason: string +} + +export interface ReleaseDispatchResult { + ok: boolean + runUrl: string +} + +export interface ReleaseDispatchOptions { + fetch: typeof globalThis.fetch + token: string + repo: string + workflow: string + ref: string + apiBase?: string + now?: number +} + +const VERSION = /^v(\d+)\.(\d+)\.(\d+)$/ + +function compareVersions(left: string, right: string): number { + const a = VERSION.exec(left) + const b = VERSION.exec(right) + if (a === null || b === null) return left.localeCompare(right) + for (let index = 1; index <= 3; index += 1) { + const delta = Number(a[index] ?? 0) - Number(b[index] ?? 0) + if (delta !== 0) return delta + } + return 0 +} + +function countKind(message: string): 'fix' | 'feat' | 'other' { + const first = message.trim().split(/\s+/)[0] ?? '' + const head = first.replace(/\([^)]*\)/, '') + if (head.startsWith('fix:')) return 'fix' + if (head.startsWith('feat:')) return 'feat' + return 'other' +} + +export function countCommitKinds(messages: string[]): { fixes: number; features: number; others: number } { + let fixes = 0 + let features = 0 + let others = 0 + for (const message of messages) { + const kind = countKind(message) + if (kind === 'fix') fixes += 1 + else if (kind === 'feat') features += 1 + else others += 1 + } + return { fixes, features, others } +} + +export function latestTagOf(tags: string[]): string { + const versions = tags.filter((tag) => VERSION.test(tag)).sort(compareVersions) + return versions.at(-1) ?? '' +} + +function api(options: ReleaseDispatchOptions, path: string): Promise { + return options.fetch(`${options.apiBase ?? 'https://api.github.com'}${path}`, { + headers: { + accept: 'application/vnd.github+json', + authorization: `Bearer ${options.token}`, + 'x-github-api-version': '2022-11-28', + 'user-agent': 'fledge-release-dispatch', + }, + signal: AbortSignal.timeout(15_000), + }) +} + +async function json(options: ReleaseDispatchOptions, path: string): Promise { + const response = await api(options, path) + if (!response.ok) throw new Error(`GitHub ${String(response.status)} ${path}`) + return (await response.json()) as T +} + +async function optional(options: ReleaseDispatchOptions, path: string): Promise { + const response = await api(options, path) + if (response.status === 404) return null + if (!response.ok) throw new Error(`GitHub ${String(response.status)} ${path}`) + return (await response.json()) as T +} + +function decodePackage(content: { content?: string; encoding?: string }): string { + if (content.encoding !== 'base64' || typeof content.content !== 'string') return '' + try { + const parsed = JSON.parse(Buffer.from(content.content, 'base64').toString('utf8')) as { version?: unknown } + return typeof parsed.version === 'string' ? parsed.version : '' + } catch { + return '' + } +} + +export async function previewRelease(options: ReleaseDispatchOptions): Promise { + const repo = options.repo + const main = await json<{ sha: string; commit: { committer: { date: string } } }>(options, `/repos/${repo}/commits/main`) + const mainSha = main.sha + const mainDate = main.commit.committer.date + const tagsRaw = await json>(options, `/repos/${repo}/git/matching-refs/tags/v`) + const tags = tagsRaw.map((entry) => String(entry.ref ?? '').replace(/^refs\/tags\//, '')).filter((tag) => VERSION.test(tag)) + const latestTag = latestTagOf(tags) + const latest = latestTag === '' + ? null + : await json<{ commit: { committer: { date: string } } }>(options, `/repos/${repo}/commits/${encodeURIComponent(latestTag)}`) + const latestTagSha = latest === null ? '' : (await json<{ sha: string }>(options, `/repos/${repo}/commits/${encodeURIComponent(latestTag)}`)).sha + const isRelease = latestTag === '' + const compare = isRelease + ? { commits: [] as Array<{ commit: { message: string } }>, total_commits: 0 } + : await json<{ commits: Array<{ commit: { message: string } }>; total_commits: number }>(options, `/repos/${repo}/compare/${encodeURIComponent(latestTag)}...${encodeURIComponent(mainSha)}`) + const messages = compare.commits.map((entry) => String(entry.commit.message.split('\n')[0] ?? '')) + const counts = countCommitKinds(messages) + const pkg = await json<{ content?: string; encoding?: string }>(options, `/repos/${repo}/contents/package.json?ref=${encodeURIComponent(mainSha)}`) + const packageVersion = decodePackage(pkg) + const next = nextReleaseVersion({ + packageVersion, + lastTagCommittedAt: latest?.commit.committer.date ?? '', + releaseAt: new Date(options.now ?? Date.now()).toISOString(), + }) + const nextVersion = next.version + const fragmentsRaw = await json | { message?: string }>(options, `/repos/${repo}/contents/changelog.d?ref=${encodeURIComponent(mainSha)}`) + const fragments = Array.isArray(fragmentsRaw) + ? fragmentsRaw.filter((entry) => entry.type === 'file' && String(entry.name ?? '').endsWith('.md') && String(entry.name ?? '').toLowerCase() !== 'readme.md').length + : 0 + const checks = await json<{ check_runs?: Array<{ id?: number; name?: string; conclusion?: string | null; status?: string }> }>(options, `/repos/${repo}/commits/${encodeURIComponent(mainSha)}/check-runs?per_page=100&check_name=ci-ok`) + const ciRuns = (checks.check_runs ?? []).filter((run) => run.name === 'ci-ok') + const ciOk = ciRuns.length === 0 + ? 'missing' + : String(ciRuns.reduce((best, run) => (Number(run.id ?? 0) >= Number(best.id ?? 0) ? run : best)).conclusion ?? 'missing') + const pulls = await json>(options, `/repos/${repo}/pulls?state=open&per_page=100`) + const openReleasePr = pulls.find((pr) => String(pr.title ?? '').startsWith('release: v') || String(pr.head?.ref ?? '').startsWith('release/v')) + const tagName = nextVersion === '' ? '' : `v${nextVersion}` + const tagExists = tagName !== '' && tags.includes(tagName) + const branchExists = nextVersion === '' ? false : (await optional<{ ref?: string }>(options, `/repos/${repo}/git/ref/heads/release/v${encodeURIComponent(nextVersion)}`)) !== null + const reasons: string[] = [] + if (options.token === '') reasons.push('dispatch-token-missing') + if (packageVersion === '') reasons.push('package-version-unreadable') + if (nextVersion === '') reasons.push('next-version-unreadable') + if (packageVersion !== '' && latestTag !== '' && packageVersion !== latestTag.slice(1)) reasons.push('version-tag-mismatch') + if (ciOk !== 'success') reasons.push(`ci-ok-${ciOk}`) + if (openReleasePr !== undefined) reasons.push('open-release-pr') + if (tagExists) reasons.push('tag-exists') + if (branchExists) reasons.push('release-branch-exists') + if (fragments === 0) reasons.push('no-fragments') + if (isRelease) reasons.push('main-is-release') + if (counts.features < 5) reasons.push('not-enough-features') + if (compare.total_commits < 10) reasons.push('not-enough-prs') + const preview: ReleaseDispatchPreview = { + repo, + workflow: options.workflow, + mainSha, + mainDate, + latestTag, + latestTagSha, + packageVersion, + nextVersion, + aheadCommits: compare.total_commits, + fixes: counts.fixes, + features: counts.features, + others: counts.others, + fragments, + ciOk, + openReleasePr: openReleasePr === undefined + ? null + : { + number: Number(openReleasePr.number ?? 0), + title: String(openReleasePr.title ?? ''), + headSha: String(openReleasePr.head?.sha ?? ''), + branch: String(openReleasePr.head?.ref ?? ''), + url: String(openReleasePr.html_url ?? ''), + }, + tagExists, + branchExists, + eligible: reasons.length === 0, + reason: reasons.join('; '), + } + return preview +} + +// The POST path fetches the complete preview itself, so a stale button cannot +// dispatch a release that the live state no longer allows. +export async function previewAndDispatch(options: ReleaseDispatchOptions): Promise<{ preview: ReleaseDispatchPreview; result: ReleaseDispatchResult }> { + const preview = await previewRelease(options) + if (!preview.eligible) throw new Error(`release preview refused: ${preview.reason}`) + const response = await options.fetch(`${options.apiBase ?? 'https://api.github.com'}/repos/${options.repo}/actions/workflows/${encodeURIComponent(options.workflow)}/dispatches`, { + method: 'POST', + headers: { + accept: 'application/vnd.github+json', + authorization: `Bearer ${options.token}`, + 'content-type': 'application/json', + 'x-github-api-version': '2022-11-28', + 'user-agent': 'fledge-release-dispatch', + }, + body: JSON.stringify({ ref: options.ref, inputs: { dry_run: 'false' } }), + signal: AbortSignal.timeout(15_000), + }) + if (!response.ok) throw new Error(`GitHub ${String(response.status)} dispatch ${options.workflow}`) + return { + preview, + result: { + ok: true, + runUrl: `https://github.com/${options.repo}/actions/workflows/${options.workflow}`, + }, + } +} diff --git a/src/lib/routeClasses.ts b/src/lib/routeClasses.ts index 71bd594a..78012fdb 100644 --- a/src/lib/routeClasses.ts +++ b/src/lib/routeClasses.ts @@ -57,6 +57,9 @@ const DESTRUCTIVE_ROUTE_LIST = [ 'POST /admin/deployments/rollback', 'POST /admin/platform/stop', 'POST /admin/platform/resume', + // #897: dispatching the release workflow can publish a release; it takes the + // destructive window and is filed with the other release writes. + 'POST /admin/release', ] as const // Starts, stops or merges real work: a job, a plan, a release, a schedule, an diff --git a/src/views/pages.ts b/src/views/pages.ts index c2dbcd82..2aa2a6d6 100644 --- a/src/views/pages.ts +++ b/src/views/pages.ts @@ -37,6 +37,7 @@ import { parseAdversarialRecord, type AdversarialRecord } from '../lib/adversari import { UNTRUSTED_EVENT_KIND } from '../lib/firewall.js' import { parseUntrustedMeta } from '../lib/untrusted.js' import { releaseSurface, type ReleaseSurface } from '../lib/releaseSurface.js' +import type { ReleaseDispatchPreview } from '../lib/releaseDispatch.js' import { readReleaseNotesSources } from '../releases/notes.js' import { compareRunning, type ReleaseStatusSnapshot } from '../lib/releaseStatus.js' import { readBackupStatus, readRestoreDrill, SHA256_MAX_BYTES, type BackupCopyStatus, type BackupStatus, type RestoreDrillStatus } from '../lib/backupStatus.js' @@ -2539,6 +2540,10 @@ export function adminPage(input: { release?: ReleaseSurface /** The release chain recorded by `node scripts/verify-release.mjs`; null when none is recorded. */ releaseStatus?: ReleaseStatusSnapshot | null + /** #897: the live GitHub preview for the superadmin release action. */ + releaseDispatch?: ReleaseDispatchPreview | null + /** A readable reason when the live preview could not be fetched. */ + releaseDispatchError?: string /** Defaults to reading `config.backup.dir`; a test passes a fixture directory. */ backup?: BackupStatus /** Defaults to reading `/backup-drill.json`; a test passes a fixture record. */ @@ -2616,6 +2621,8 @@ export function adminPage(input: { // recorded and never calls GitHub itself. The running row is the only live // fact — this process knows the version and the commit stamp it booted with. const releaseStatus = input.releaseStatus ?? null + const releaseDispatch = input.releaseDispatch ?? null + const releaseDispatchError = input.releaseDispatchError ?? '' const stateBadge = (state: string) => { if (state === 'ok') return `${escapeHtml(t('正常', 'ok'))}` if (state === 'missing') return `${escapeHtml(t('缺失', 'missing'))}` @@ -2675,6 +2682,23 @@ export function adminPage(input: { ${problemLinks.length === 0 ? `
${escapeHtml(t('发布链', 'Release chain'))}${escapeHtml(t('所有发布产物一致;完整证据可展开。', 'All release artifacts agree; open the evidence for the full chain.'))}
${stateBadge('ok')}
` : ''}
${escapeHtml(t('发布链证据', 'Release chain evidence'))}${releaseStatus.checkedAt === '' ? '' : ` · ${escapeHtml(t(`检查于 ${releaseStatus.checkedAt}`, `checked ${releaseStatus.checkedAt}`))}`}
${fullRows}
` + const releaseDispatchBlock = (() => { + if (!superadmin) return '' + if (releaseDispatchError !== '') { + return `` + } + if (releaseDispatch === null) { + return `

${escapeHtml(t('一键发布未配置:设置 RELEASE_DISPATCH_TOKEN 后可用。', 'One-click release is not configured: set RELEASE_DISPATCH_TOKEN to enable it.'))}

` + } + const preview = releaseDispatch + const counts = `${escapeHtml(t('领先', 'ahead'))} ${preview.aheadCommits} · ${escapeHtml(t('修复', 'fix'))} ${preview.fixes} · ${escapeHtml(t('功能', 'feat'))} ${preview.features} · ${escapeHtml(t('其他', 'other'))} ${preview.others} · ${escapeHtml(t('片段', 'fragments'))} ${preview.fragments}` + const facts = `

${escapeHtml(t('当前', 'current'))} ${escapeHtml(preview.mainSha.slice(0, 12))} · ${escapeHtml(t('最新标签', 'latest tag'))} ${escapeHtml(preview.latestTag || '—')} · ${counts} · ci-ok ${escapeHtml(preview.ciOk)}

` + if (!preview.eligible) { + return `
${escapeHtml(t('一键发布当前不可用', 'One-click release is not available'))}${facts}${escapeHtml(preview.reason)}
${escapeHtml(t('不可用', 'blocked'))}
` + } + const confirm = `RELEASE ${preview.nextVersion}` + return `
${escapeHtml(t(`发布 v${preview.nextVersion}`, `Release v${preview.nextVersion}`))}${facts}${escapeHtml(t('只创建发布 PR;tag 与 publish 仍走现有门禁。不会部署或重启服务。', 'Creates the release pull request only; tagging and publishing stay on the existing gates. It does not deploy or restart the service.'))}
${csrf(viewer)}
${escapeHtml(t('可用', 'ready'))}
` + })() const releaseCard = `
@@ -2688,6 +2712,7 @@ export function adminPage(input: {
${releaseDetails} + ${releaseDispatchBlock}
` // The console can only show what the writer leaves on disk: a copy and its diff --git a/test/helpers.ts b/test/helpers.ts index efb99ec3..9ffc3417 100644 --- a/test/helpers.ts +++ b/test/helpers.ts @@ -30,6 +30,7 @@ export function testConfig(overrides: Partial = {}): Config { dataDir: '/tmp/fledge-test', dbPath: ':memory:', runner: { mode: 'mock', bridgeUrl: '', bridgeToken: '', timeoutMinutes: 45, stallMinutes: 30, maxActiveJobs: 2, workCooldownMinutes: 15, queueDispatch: false, maxQueueDepth: 100, maxUserQueue: 20 }, + release: { dispatchToken: '', repo: 'HugoXK/fledge', workflow: 'daily-release.yml', ref: 'main' }, allowTokenLoginOnly: true, mail: { transport: 'console', @@ -62,6 +63,7 @@ export function testConfig(overrides: Partial = {}): Config { llm: { ...base.llm, ...overrides.llm }, quota: { ...base.quota, ...overrides.quota }, runner: { ...base.runner, ...overrides.runner }, + release: { ...base.release, ...overrides.release }, metrics: { ...base.metrics, ...overrides.metrics }, otel: { ...base.otel, ...overrides.otel }, shutdown: { ...base.shutdown, ...overrides.shutdown }, diff --git a/test/releaseDispatch.test.ts b/test/releaseDispatch.test.ts new file mode 100644 index 00000000..ca56dfbb --- /dev/null +++ b/test/releaseDispatch.test.ts @@ -0,0 +1,116 @@ +import test from 'node:test' +import assert from 'node:assert/strict' +import { countCommitKinds, latestTagOf, previewRelease, previewAndDispatch } from '../src/lib/releaseDispatch.js' +import type { ReleaseDispatchOptions } from '../src/lib/releaseDispatch.js' + +const MAIN = 'a'.repeat(40) +const TAG_SHA = 'b'.repeat(40) +const base64 = (value: string): string => Buffer.from(value).toString('base64') + +function json(value: unknown, status = 200): Response { + return new Response(JSON.stringify(value), { status, headers: { 'content-type': 'application/json' } }) +} + +function fakeFetch(overrides: { ci?: string; pulls?: unknown[]; fragments?: number } = {}): { fetch: typeof globalThis.fetch; calls: Array<{ url: string; method: string; body: string }> } { + const calls: Array<{ url: string; method: string; body: string }> = [] + const fetcher = async (input: string | URL | Request, init?: RequestInit): Promise => { + const url = String(input) + calls.push({ url, method: String(init?.method ?? 'GET'), body: String(init?.body ?? '') }) + if (url.endsWith('/repos/o/r/commits/main')) return json({ sha: MAIN, commit: { committer: { date: '2026-11-16T07:00:00Z' } } }) + if (url.endsWith('/repos/o/r/git/matching-refs/tags/v')) return json([{ ref: 'refs/tags/v0.4.0' }]) + if (url.endsWith('/repos/o/r/commits/v0.4.0')) return json({ sha: TAG_SHA, commit: { committer: { date: '2026-11-16T01:20:00Z' } } }) + if (url.includes('/repos/o/r/compare/v0.4.0...')) { + const messages = [ + 'fix(a): one (#1)', + 'fix(b): two (#2)', + 'fix(c): three (#3)', + 'fix(d): four (#4)', + 'fix(e): five (#5)', + 'fix(f): six (#6)', + 'feat(a): one (#7)', + 'feat(b): two (#8)', + 'feat(c): three (#9)', + 'feat(d): four (#10)', + 'feat(e): five (#11)', + 'docs: one (#12)', + ] + return json({ total_commits: messages.length, commits: messages.map((message) => ({ commit: { message } })) }) + } + if (url.includes('/repos/o/r/contents/package.json')) return json({ encoding: 'base64', content: base64(JSON.stringify({ version: '0.4.0' })) }) + if (url.includes('/repos/o/r/contents/changelog.d')) { + const count = overrides.fragments ?? 2 + return json(Array.from({ length: count }, (_, index) => ({ name: `f${index}.fixed.md`, type: 'file' })).concat([{ name: 'README.md', type: 'file' }])) + } + if (url.includes('/repos/o/r/commits/') && url.includes('/check-runs')) { + return json({ check_runs: [{ id: 3, name: 'ci-ok', status: 'completed', conclusion: overrides.ci ?? 'success' }] }) + } + if (url.includes('/repos/o/r/pulls?state=open')) return json(overrides.pulls ?? []) + if (url.includes('/repos/o/r/git/ref/heads/release/v0.4.1')) return new Response('', { status: 404 }) + if (url.includes('/repos/o/r/actions/workflows/daily-release.yml/dispatches')) return new Response('', { status: 202 }) + throw new Error(`unexpected fetch ${url}`) + } + return { fetch: fetcher as typeof globalThis.fetch, calls } +} + +function options(fetch: typeof globalThis.fetch): ReleaseDispatchOptions { + return { + fetch, + token: 'test-token', + repo: 'o/r', + workflow: 'daily-release.yml', + ref: 'main', + now: Date.parse('2026-11-16T07:30:00Z'), + } +} + +test('counts conventional commit kinds and picks the highest semver tag', () => { + assert.deepEqual(countCommitKinds(['fix: a', 'feat(x): b', 'docs: c']), { fixes: 1, features: 1, others: 1 }) + assert.equal(latestTagOf(['v0.9.0', 'v0.10.0', 'not-a-tag', 'v0.3.9']), 'v0.10.0') +}) + +test('preview reads the current state and is eligible when the rule is met', async () => { + const fake = fakeFetch() + const preview = await previewRelease(options(fake.fetch)) + assert.equal(preview.mainSha, MAIN) + assert.equal(preview.latestTag, 'v0.4.0') + assert.equal(preview.nextVersion, '0.4.1') + assert.equal(preview.aheadCommits, 12) + assert.equal(preview.fixes, 6) + assert.equal(preview.features, 5) + assert.equal(preview.fragments, 2) + assert.equal(preview.ciOk, 'success') + assert.equal(preview.openReleasePr, null) + assert.equal(preview.eligible, true) + assert.equal(preview.reason, '') +}) + +test('preview names the real blocker when a release is not eligible', async () => { + const fake = fakeFetch({ ci: 'failure' }) + const preview = await previewRelease(options(fake.fetch)) + assert.equal(preview.eligible, false) + assert.match(preview.reason, /ci-ok-failure/) +}) + +test('a release PR, missing fragments or an existing tag each block the action', async () => { + const open = fakeFetch({ pulls: [{ number: 9, title: 'release: v0.4.1', html_url: 'https://github.com/o/r/pull/9', head: { sha: 'c'.repeat(40), ref: 'release/v0.4.1' } }] }) + assert.match((await previewRelease(options(open.fetch))).reason, /open-release-pr/) + const empty = fakeFetch({ fragments: 0 }) + assert.match((await previewRelease(options(empty.fetch))).reason, /no-fragments/) +}) + +test('previewAndDispatch posts dry_run=false only after a fresh eligible preview', async () => { + const fake = fakeFetch() + const { preview, result } = await previewAndDispatch(options(fake.fetch)) + assert.equal(preview.nextVersion, '0.4.1') + assert.equal(result.ok, true) + const dispatch = fake.calls.find((call) => call.url.includes('/actions/workflows/daily-release.yml/dispatches')) + assert.ok(dispatch, 'the dispatch request was made') + assert.equal(dispatch?.method, 'POST') + assert.deepEqual(JSON.parse(dispatch?.body ?? '{}'), { ref: 'main', inputs: { dry_run: 'false' } }) +}) + +test('previewAndDispatch refuses before writing when the preview is not eligible', async () => { + const fake = fakeFetch({ ci: 'failure' }) + await assert.rejects(previewAndDispatch(options(fake.fetch)), /release preview refused/) + assert.equal(fake.calls.some((call) => call.method === 'POST' && call.url.includes('/dispatches')), false) +}) From 55f28e844811b37dcd1b49d15cace1b04c1cad63 Mon Sep 17 00:00:00 2001 From: Day Dreamer <87640074+HugoXK@users.noreply.github.com> Date: Mon, 16 Nov 2026 15:41:41 +0800 Subject: [PATCH 2/4] docs: describe the superadmin one-click release action --- docs/architecture.md | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/docs/architecture.md b/docs/architecture.md index f0a3cd3f..1fa64c4d 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -823,6 +823,19 @@ path. The page owns the Users section at `/admin#users`; `/admin/users` is an admin-only redirect to that section for older links and bookmarks, while `/admin/users/:id` remains the read-only support view. +For a superadmin, the Release card also carries the one-click preview +(`src/lib/releaseDispatch.ts`): the current `main`, latest tag, commit/fix/ +feature/fragment counts, computed next version, `ci-ok`, any open release PR and +the exact reason the action is blocked. `POST /admin/release` requires superadmin, +CSRF, a recent GitHub re-authentication, the destructive rate-limit class and an +audit row; it re-reads the preview and then dispatches the existing +`daily-release.yml` with `dry_run=false`. It never creates a tag, merges a pull +request or deploys a host. The server-side `RELEASE_DISPATCH_TOKEN` is repo-scoped +and never rendered or logged; an empty value disables the action instead of +failing the page. Release remains separate from deploy: production may already +run `main`, and the next infra update installs the version-bump commit after the +release PR merges. + The admin page is a hub, not an approvals-only page. Its primary sections are Pending, Users, Jobs, Audit, Release and Backups; Product metrics, Webhook deliveries, Deployments, Audit and jobs search and Preview trials are module From 95dc5ade5a5bbb936822eab0ab0a4f7e8149428e Mon Sep 17 00:00:00 2001 From: Day Dreamer <87640074+HugoXK@users.noreply.github.com> Date: Mon, 16 Nov 2026 15:48:17 +0800 Subject: [PATCH 3/4] test: cover the release preview refusal branches --- test/releaseDispatch.test.ts | 21 +++++++++++++++++---- 1 file changed, 17 insertions(+), 4 deletions(-) diff --git a/test/releaseDispatch.test.ts b/test/releaseDispatch.test.ts index ca56dfbb..e12f7a1b 100644 --- a/test/releaseDispatch.test.ts +++ b/test/releaseDispatch.test.ts @@ -11,13 +11,13 @@ function json(value: unknown, status = 200): Response { return new Response(JSON.stringify(value), { status, headers: { 'content-type': 'application/json' } }) } -function fakeFetch(overrides: { ci?: string; pulls?: unknown[]; fragments?: number } = {}): { fetch: typeof globalThis.fetch; calls: Array<{ url: string; method: string; body: string }> } { +function fakeFetch(overrides: { ci?: string; pulls?: unknown[]; fragments?: number | null; tags?: string[]; packageContent?: string } = {}): { fetch: typeof globalThis.fetch; calls: Array<{ url: string; method: string; body: string }> } { const calls: Array<{ url: string; method: string; body: string }> = [] const fetcher = async (input: string | URL | Request, init?: RequestInit): Promise => { const url = String(input) calls.push({ url, method: String(init?.method ?? 'GET'), body: String(init?.body ?? '') }) if (url.endsWith('/repos/o/r/commits/main')) return json({ sha: MAIN, commit: { committer: { date: '2026-11-16T07:00:00Z' } } }) - if (url.endsWith('/repos/o/r/git/matching-refs/tags/v')) return json([{ ref: 'refs/tags/v0.4.0' }]) + if (url.endsWith('/repos/o/r/git/matching-refs/tags/v')) return json((overrides.tags ?? ['v0.4.0']).map((tag) => ({ ref: `refs/tags/${tag}` }))) if (url.endsWith('/repos/o/r/commits/v0.4.0')) return json({ sha: TAG_SHA, commit: { committer: { date: '2026-11-16T01:20:00Z' } } }) if (url.includes('/repos/o/r/compare/v0.4.0...')) { const messages = [ @@ -36,8 +36,9 @@ function fakeFetch(overrides: { ci?: string; pulls?: unknown[]; fragments?: numb ] return json({ total_commits: messages.length, commits: messages.map((message) => ({ commit: { message } })) }) } - if (url.includes('/repos/o/r/contents/package.json')) return json({ encoding: 'base64', content: base64(JSON.stringify({ version: '0.4.0' })) }) + if (url.includes('/repos/o/r/contents/package.json')) return json({ encoding: 'base64', content: base64(overrides.packageContent ?? JSON.stringify({ version: '0.4.0' })) }) if (url.includes('/repos/o/r/contents/changelog.d')) { + if (overrides.fragments === null) return json({ message: 'not a directory' }) const count = overrides.fragments ?? 2 return json(Array.from({ length: count }, (_, index) => ({ name: `f${index}.fixed.md`, type: 'file' })).concat([{ name: 'README.md', type: 'file' }])) } @@ -45,7 +46,7 @@ function fakeFetch(overrides: { ci?: string; pulls?: unknown[]; fragments?: numb return json({ check_runs: [{ id: 3, name: 'ci-ok', status: 'completed', conclusion: overrides.ci ?? 'success' }] }) } if (url.includes('/repos/o/r/pulls?state=open')) return json(overrides.pulls ?? []) - if (url.includes('/repos/o/r/git/ref/heads/release/v0.4.1')) return new Response('', { status: 404 }) + if (url.includes('/repos/o/r/git/ref/heads/release/')) return new Response('', { status: 404 }) if (url.includes('/repos/o/r/actions/workflows/daily-release.yml/dispatches')) return new Response('', { status: 202 }) throw new Error(`unexpected fetch ${url}`) } @@ -98,6 +99,18 @@ test('a release PR, missing fragments or an existing tag each block the action', assert.match((await previewRelease(options(empty.fetch))).reason, /no-fragments/) }) +test('preview handles an unreadable package, no tag and a non-directory fragment listing', async () => { + const noTag = await previewRelease(options(fakeFetch({ tags: [] }).fetch)) + assert.equal(noTag.nextVersion, '0.5.0') + assert.match(noTag.reason, /main-is-release/) + const badPackage = await previewRelease(options(fakeFetch({ packageContent: 'not-json' }).fetch)) + assert.equal(badPackage.packageVersion, '') + assert.match(badPackage.reason, /package-version-unreadable/) + const noFragments = await previewRelease(options(fakeFetch({ fragments: null }).fetch)) + assert.equal(noFragments.fragments, 0) + assert.match(noFragments.reason, /no-fragments/) +}) + test('previewAndDispatch posts dry_run=false only after a fresh eligible preview', async () => { const fake = fakeFetch() const { preview, result } = await previewAndDispatch(options(fake.fetch)) From 08d71ea0ff1949de38e44678ed93626fb6594816 Mon Sep 17 00:00:00 2001 From: HugoXK Date: Tue, 17 Nov 2026 04:22:37 +0000 Subject: [PATCH 4/4] fix: name the read scopes the release dispatch token needs The three credential sites told the operator to mint RELEASE_DISPATCH_TOKEN with Actions: write only, but the preview also reads commits, matching refs, compare, contents, check-runs and pulls, so the first call answered 403 and the one-click release never became usable. .env.example, docs/deploy.md and the RELEASE_DISPATCH_TOKEN row in docs/secrets.md now name Contents: read, Checks: read and Pull requests: read beside Actions: write; the src/config.ts comment that repeated the same claim follows them. A 403 on a preview read now says which permission is missing and which setting to change, instead of the bare status, so the Admin banner is something an operator can act on; every other status keeps the old message, and both throw sites share one helper. A table test refuses each read path and asserts the scope, the setting and the repository all appear in the message. --- .env.example | 8 +++++--- docs/deploy.md | 6 +++++- docs/secrets.md | 2 +- src/config.ts | 5 +++-- src/lib/releaseDispatch.ts | 27 +++++++++++++++++++++++++-- test/releaseDispatch.test.ts | 33 ++++++++++++++++++++++++++++++++- 6 files changed, 71 insertions(+), 10 deletions(-) diff --git a/.env.example b/.env.example index f359b4d3..24e73519 100644 --- a/.env.example +++ b/.env.example @@ -141,9 +141,11 @@ INBOUND_EMAIL_SECRET= JOB_STALL_MINUTES=30 # Maximum jobs running at once across all repositories. PLATFORM_MAX_ACTIVE_JOBS=2 -# Superadmin one-click release: a repo-scoped token with Actions: write. Leave -# empty to disable the action; the token is read only on the server and is never -# rendered or logged. +# Superadmin one-click release: a repo-scoped token with Actions: write to +# dispatch the workflow, plus Contents: read, Checks: read and Pull requests: read +# to read the release preview. A token with only Actions: write answers 403 on +# the first preview call. Leave empty to disable the action; the token is read +# only on the server and is never rendered or logged. RELEASE_DISPATCH_TOKEN= RELEASE_DISPATCH_REPO=HugoXK/fledge RELEASE_DISPATCH_WORKFLOW=daily-release.yml diff --git a/docs/deploy.md b/docs/deploy.md index fdfb66e9..b876e918 100644 --- a/docs/deploy.md +++ b/docs/deploy.md @@ -323,7 +323,11 @@ release PR, `ci-ok`, `review-gate`, auto-merge, tag job and `release.yml` publis chain stay in charge. The dispatch credential is `RELEASE_DISPATCH_TOKEN` in the server `.env`, scoped -to the Fledge repository with only `Actions: write`; prefer a fine-grained token. +to the Fledge repository with `Actions: write` to dispatch the workflow and +`Contents: read`, `Checks: read` and `Pull requests: read` to read the preview; +prefer a fine-grained token, and grant no write scope on contents or pull +requests. A token minted with only `Actions: write` answers `403` on the first +preview read, and the Admin page names the scope it needs. An empty value disables the action instead of failing the Admin page. The token is never rendered, logged or returned by the route. diff --git a/docs/secrets.md b/docs/secrets.md index fbde4c4b..b7953094 100644 --- a/docs/secrets.md +++ b/docs/secrets.md @@ -30,7 +30,7 @@ predates this inventory — it is not a value. | `GITHUB_APP_WEBHOOK_SECRET` | verifies App webhooks | production `.env` | random 32 bytes | owner | unknown | `openssl rand -hex 32` in both the App and `.env` | redeliver one webhook and confirm it is accepted | unknown | | `INBOUND_EMAIL_SECRET` | shared secret with the inbound Email Worker | production `.env` and the worker | random 32 bytes | owner | unknown | `openssl rand -hex 32` in both places | reply to one digest mail and confirm it lands | unknown | | `METRICS_TOKEN` | `/metrics` outside loopback | production `.env` | random 32 bytes | owner | unknown | `openssl rand -hex 32` then restart | `curl -H "Authorization: Bearer …" /metrics` returns 200 | unknown | -| `RELEASE_DISPATCH_TOKEN` | superadmin one-click release workflow dispatch | production `.env` | repo-scoped token with `Actions: write` on `HugoXK/fledge` only; fine-grained preferred, and no contents/PR write is needed | owner | unknown | mint a repo-scoped token, replace it in the server `.env`, restart Fledge | the release preview is `ready` and a `workflow_dispatch` run appears on `main` | unknown | +| `RELEASE_DISPATCH_TOKEN` | superadmin one-click release workflow dispatch | production `.env` | repo-scoped token with `Actions: write` (dispatch) and `Contents: read`, `Checks: read`, `Pull requests: read` (preview) on `HugoXK/fledge` only; fine-grained preferred, and no contents/PR write is needed | owner | unknown | mint a repo-scoped token, replace it in the server `.env`, restart Fledge | the release preview is `ready` and a `workflow_dispatch` run appears on `main` | unknown | | `NOTIFY_WEBHOOK_SECRET` | outbound notification webhook | production `.env` | random 32 bytes | owner | unknown | `openssl rand -hex 32` in both places | one event delivers with a valid signature | unknown | ## What is deliberately not in this table diff --git a/src/config.ts b/src/config.ts index 5657346a..acc867d3 100644 --- a/src/config.ts +++ b/src/config.ts @@ -31,8 +31,9 @@ export interface Config { // How long a GitHub re-authentication stays "recent" for destructive actions. recentAuthMinutes: number // #897: the superadmin release action dispatches the existing release - // workflow. The token only needs Actions: write on the Fledge repository; it - // is a server secret and is never rendered or logged. + // workflow. The token needs Actions: write to dispatch and Contents: read, + // Checks: read and Pull requests: read to build the preview; it is a server + // secret and is never rendered or logged. release: { dispatchToken: string repo: string diff --git a/src/lib/releaseDispatch.ts b/src/lib/releaseDispatch.ts index 1d455e20..19cdfc52 100644 --- a/src/lib/releaseDispatch.ts +++ b/src/lib/releaseDispatch.ts @@ -93,16 +93,39 @@ function api(options: ReleaseDispatchOptions, path: string): Promise { }) } +// A repo-scoped token minted with only Actions: write can dispatch the workflow +// but cannot read any of the preview endpoints, so it answers 403 on the first +// call. The bare status left the operator guessing which permission to add, and +// pointing at this list keeps the message and the docs saying the same thing. +const READ_SCOPES: Array<[RegExp, string]> = [ + [/\/check-runs/, 'Checks: read'], + [/\/pulls/, 'Pull requests: read'], + [/\/contents\//, 'Contents: read'], + [/\/git\/matching-refs/, 'Contents: read'], + [/\/git\/ref\//, 'Contents: read'], + [/\/compare\//, 'Contents: read'], + [/\/commits\//, 'Contents: read'], +] + +export function readScopeFor(path: string): string { + return READ_SCOPES.find(([pattern]) => pattern.test(path))?.[1] ?? 'Contents: read' +} + +function refused(options: ReleaseDispatchOptions, status: number, path: string): Error { + if (status !== 403) return new Error(`GitHub ${String(status)} ${path}`) + return new Error(`GitHub 403 on ${path}: RELEASE_DISPATCH_TOKEN needs ${readScopeFor(path)} on ${options.repo}.`) +} + async function json(options: ReleaseDispatchOptions, path: string): Promise { const response = await api(options, path) - if (!response.ok) throw new Error(`GitHub ${String(response.status)} ${path}`) + if (!response.ok) throw refused(options, response.status, path) return (await response.json()) as T } async function optional(options: ReleaseDispatchOptions, path: string): Promise { const response = await api(options, path) if (response.status === 404) return null - if (!response.ok) throw new Error(`GitHub ${String(response.status)} ${path}`) + if (!response.ok) throw refused(options, response.status, path) return (await response.json()) as T } diff --git a/test/releaseDispatch.test.ts b/test/releaseDispatch.test.ts index e12f7a1b..843921eb 100644 --- a/test/releaseDispatch.test.ts +++ b/test/releaseDispatch.test.ts @@ -11,11 +11,16 @@ function json(value: unknown, status = 200): Response { return new Response(JSON.stringify(value), { status, headers: { 'content-type': 'application/json' } }) } -function fakeFetch(overrides: { ci?: string; pulls?: unknown[]; fragments?: number | null; tags?: string[]; packageContent?: string } = {}): { fetch: typeof globalThis.fetch; calls: Array<{ url: string; method: string; body: string }> } { +function fakeFetch(overrides: { ci?: string; pulls?: unknown[]; fragments?: number | null; tags?: string[]; packageContent?: string; refuseAt?: string } = {}): { fetch: typeof globalThis.fetch; calls: Array<{ url: string; method: string; body: string }> } { const calls: Array<{ url: string; method: string; body: string }> = [] const fetcher = async (input: string | URL | Request, init?: RequestInit): Promise => { const url = String(input) calls.push({ url, method: String(init?.method ?? 'GET'), body: String(init?.body ?? '') }) + // A fine-grained token with only Actions: write answers 403 with this body; + // the message under test must not lean on GitHub's wording. + if (overrides.refuseAt !== undefined && url.includes(overrides.refuseAt)) { + return json({ message: 'Resource not accessible by personal access token' }, 403) + } if (url.endsWith('/repos/o/r/commits/main')) return json({ sha: MAIN, commit: { committer: { date: '2026-11-16T07:00:00Z' } } }) if (url.endsWith('/repos/o/r/git/matching-refs/tags/v')) return json((overrides.tags ?? ['v0.4.0']).map((tag) => ({ ref: `refs/tags/${tag}` }))) if (url.endsWith('/repos/o/r/commits/v0.4.0')) return json({ sha: TAG_SHA, commit: { committer: { date: '2026-11-16T01:20:00Z' } } }) @@ -111,6 +116,32 @@ test('preview handles an unreadable package, no tag and a non-directory fragment assert.match(noFragments.reason, /no-fragments/) }) +// #908: the documented credential was "Actions: write only", so the first +// preview read answered 403 and the page showed a bare status. Each refused read +// has to name the scope an operator must add, not echo GitHub's wording. +test('a refused preview read names the permission the release token is missing', async () => { + const cases = [ + ['/repos/o/r/commits/main', 'Contents: read'], + ['/repos/o/r/contents/package.json', 'Contents: read'], + ['/check-runs', 'Checks: read'], + ['/repos/o/r/pulls?state=open', 'Pull requests: read'], + ['/git/ref/heads/release/', 'Contents: read'], + ] as const + for (const [refuseAt, scope] of cases) { + const error = await previewRelease(options(fakeFetch({ refuseAt }).fetch)).then( + () => null, + (reason: unknown) => reason, + ) + assert.ok(error instanceof Error, `${refuseAt} must fail the preview`) + const message = error.message + assert.match(message, /403/, `${refuseAt} keeps the status: ${message}`) + assert.ok(message.includes(scope), `${refuseAt} names "${scope}": ${message}`) + assert.match(message, /RELEASE_DISPATCH_TOKEN/, `${refuseAt} names the setting to change: ${message}`) + assert.match(message, /o\/r/, `${refuseAt} names the repository: ${message}`) + assert.doesNotMatch(message, /Resource not accessible/, `${refuseAt} does not echo the GitHub body: ${message}`) + } +}) + test('previewAndDispatch posts dry_run=false only after a fresh eligible preview', async () => { const fake = fakeFetch() const { preview, result } = await previewAndDispatch(options(fake.fetch))