From 1b531ed039db9ebe88b1b93ed26658dfc3be7e6d Mon Sep 17 00:00:00 2001 From: Dr_rOot Date: Mon, 12 Oct 2026 12:03:26 +0800 Subject: [PATCH] fix(release): wait for npm publication verification --- docs/releasing.md | 27 +++++- docs/releasing.zh-CN.md | 12 ++- scripts/release.mjs | 147 +++++++++++++++++++++++------ scripts/release.test.mjs | 195 ++++++++++++++++++++++++++++++++++++++- 4 files changed, 346 insertions(+), 35 deletions(-) diff --git a/docs/releasing.md b/docs/releasing.md index 1cf5ce7..01cea99 100644 --- a/docs/releasing.md +++ b/docs/releasing.md @@ -68,9 +68,17 @@ After the version/tooling PRs are merged, use a clean, current `main` checkout a run this command yourself: ```bash +pnpm whoami --registry=https://registry.npmjs.org +# If this fails, log in with the package manager used for publication: +pnpm login --registry=https://registry.npmjs.org +# Continue only after pnpm whoami returns the intended publisher account. pnpm run release -- --publish ``` +An authenticated `npm whoami` does not prove that pnpm's selected credentials +are valid. Complete any browser/2FA challenge from pnpm promptly; an expired +challenge requires rerunning the command to obtain a fresh link. + This reruns the complete preparation pipeline. Publish mode rejects CI and non-interactive terminals before running the pipeline. There is no `--yes`, `--force` or validation-skip option. @@ -100,8 +108,19 @@ The script rechecks Git state and archive integrity after confirmation and befor each upload. It invokes pnpm with the verified tarball, explicit public registry, public access and `latest` tag, preserving Git checks and interactive OTP support. Each package must become visible with the matching integrity before the next is -published. Missing metadata is polled up to 15 times at two-second intervals; -each HTTP request has a 15-second timeout. Other registry errors stop immediately. +published. Once the upload command succeeds, its status becomes `verifying`. +Verification waits up to five minutes using a monotonic deadline, with delays +growing from two to ten seconds and a request timeout of at most 15 seconds +(bounded by the remaining deadline). Each metadata read uses a fresh query key +and requests cache revalidation so a preflight 404 is not reused. + +Only verification reads are retried: missing metadata, network failures, +timeouts, HTTP 429 and HTTP 5xx. `Retry-After` can extend the polling delay within +the deadline; progress is printed at least every 30 seconds while waiting. +Authentication/authorization errors, malformed metadata and integrity conflicts +stop immediately. Preflight registry errors still stop before uploads. The +script never retries an upload automatically or advances past an unverified +package. ## Failure and partial-release recovery @@ -110,6 +129,10 @@ fails, later packages are not attempted, and nothing is unpublished or retried automatically. Preserve the run directory and inspect `release.json` and npm. A `publishing` status is uncertain: the server may have accepted an upload even if the client failed or metadata was not yet visible. +A `verifying` status means the upload command succeeded but registry verification +has not finished. A verification timeout does not mean the upload failed; the +report preserves the attempt count and latest verification message. Check npm +before retrying, and keep the original artifacts. Once the cause is resolved, rerun from the same reviewed source with the pinned build tools. The script rebuilds and compares exact published integrity values; diff --git a/docs/releasing.zh-CN.md b/docs/releasing.zh-CN.md index fa8faf8..05d9e25 100644 --- a/docs/releasing.zh-CN.md +++ b/docs/releasing.zh-CN.md @@ -41,9 +41,15 @@ pnpm run release -- --dry-run 版本和工具 PR 合并后,在干净且已同步的 `main` 上,由维护者本人执行: ```bash +pnpm whoami --registry=https://registry.npmjs.org +# 如果失败,使用发布时实际调用的包管理器登录: +pnpm login --registry=https://registry.npmjs.org +# 确认 pnpm whoami 返回预期发布账号后再继续。 pnpm run release -- --publish ``` +`npm whoami` 成功不代表 pnpm 当前选用的凭据有效。pnpm 弹出浏览器或 2FA 验证时请及时完成;验证链接过期后,需要重新运行命令获取新链接。 + 该命令会重新完成整个准备流程。发布模式会在运行流程前拒绝 CI 和非交互式终端,没有 `--yes`、`--force` 或跳过校验选项。 上传前先核对 npm 上四个精确版本。404 表示尚未发布;认证、限流、网络或其他 registry 错误都会使流程停止。仅当已有版本的 SHA-512 integrity 与本次归档一致时才会跳过。任一版本冲突都会在首次上传前阻止整个批次。 @@ -59,12 +65,16 @@ pnpm run release -- --publish create-motrix-plugin ``` -确认后及每次上传前,脚本都会重新核对 Git 状态和归档摘要。发布时向 pnpm 传入已验证 tarball、明确的公共 registry、public access 和 `latest` tag,保留 Git 检查及交互式 OTP 支持。每个包必须在 npm 上可查询且摘要一致,才会继续下一个。元数据缺失时最多查询 15 次,间隔两秒;单次 HTTP 请求超时为 15 秒。其他 registry 错误立即停止。 +确认后及每次上传前,脚本都会重新核对 Git 状态和归档摘要。发布时向 pnpm 传入已验证 tarball、明确的公共 registry、public access 和 `latest` tag,保留 Git 检查及交互式 OTP 支持。每个包必须在 npm 上可查询且摘要一致,才会继续下一个。上传命令成功后,状态变为 `verifying`。核验使用单调时钟,最多等待 5 分钟;查询间隔从 2 秒逐步增加到 10 秒,单次请求最多 15 秒,且不能超出剩余等待时间。每次读取元数据都使用新的查询参数并要求缓存重新验证,避免复用上传前预检查到的 404。 + +只重试核验读取:元数据暂不可见、网络失败、超时、HTTP 429 和 HTTP 5xx。`Retry-After` 可以在总时限内延长查询间隔,等待时至少每 30 秒输出一次进度。认证或权限错误、元数据格式错误、摘要冲突立即停止。上传前的 registry 预检遇错仍直接停止。脚本不会自动重试上传,也不会越过尚未核验的包。 ## 失败与部分发布恢复 四个 npm 包的发布不具备原子性。上传或发布后校验失败时,后续包不再尝试,不自动撤销已发布包,也不自动重试上传。请保留运行目录,检查 `release.json` 和 npm 实际状态。报告中的 `publishing` 属于不确定状态:即使客户端失败或元数据尚不可见,服务端也可能已接收包。 +`verifying` 表示上传命令已成功,但 registry 核验尚未完成。核验超时不等于上传失败;报告保留查询次数及最后一条核验信息。重试前先检查 npm,并保留原始产物。 + 解决原因后,使用同一份经过评审的源码和固定构建工具重新运行。脚本重新构建并核对已发布包的精确 integrity;完全一致的包会跳过,只对缺少的包请求确认并上传。不会覆盖不可变版本。如果重建结果与已发布版本不同,应停止并查明原因,不能强制上传或静默忽略冲突。需要调整版本时,提交新的评审 PR,并保持 schema/CLI 版本一致。 在整个 SDK 批次核验完成前,消费者仍保持阻塞。完成后再更新 Motrix 和官方插件的依赖及锁文件,并复跑干净 CI。SDK 发布不代表兼容的宿主或插件也已发布,二者仍需独立核验。 diff --git a/scripts/release.mjs b/scripts/release.mjs index ad13cdb..b6a2a15 100644 --- a/scripts/release.mjs +++ b/scripts/release.mjs @@ -1,6 +1,6 @@ #!/usr/bin/env node import { execFile, spawn } from 'node:child_process' -import { createHash } from 'node:crypto' +import { createHash, randomUUID } from 'node:crypto' import { mkdir, mkdtemp, readFile, writeFile } from 'node:fs/promises' import path from 'node:path' import { createInterface } from 'node:readline/promises' @@ -18,6 +18,16 @@ export const PACKAGES = [ ] const CONFIRMATION = 'publish SDK packages to npm' const STABLE_VERSION = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/ +const REQUEST_TIMEOUT_MS = 15_000 +const VERIFICATION_TIMEOUT_MS = 5 * 60_000 + +export class RegistryLookupError extends Error { + constructor(message, { retryable = false, retryAfterMs = 0 } = {}) { + super(message) + this.retryable = retryable + this.retryAfterMs = retryAfterMs + } +} export function parseArgs(args) { const flags = args.filter((arg) => arg !== '--') @@ -69,21 +79,114 @@ async function execute(command, args, { cwd, capture = false }) { return '' } -async function readVersion(name, version) { - const response = await fetch( - new URL( - `${encodeURIComponent(name)}/${encodeURIComponent(version)}`, - REGISTRY - ), - { redirect: 'error', signal: AbortSignal.timeout(15_000) } +export async function readVersion( + name, + version, + { fetch: request = fetch, timeoutMs = REQUEST_TIMEOUT_MS } = {} +) { + const url = new URL( + `${encodeURIComponent(name)}/${encodeURIComponent(version)}`, + REGISTRY ) - if (response.status === 404) return null - if (!response.ok) { - throw new Error( - `Registry lookup failed for ${name}@${version}: HTTP ${response.status}.` + // Preflight may have cached a 404 before the version was uploaded. + url.searchParams.set('release-check', randomUUID()) + const signal = AbortSignal.timeout(timeoutMs) + try { + const response = await request(url, { + redirect: 'error', + cache: 'no-store', + headers: { Accept: 'application/json', 'Cache-Control': 'no-cache' }, + signal, + }) + if (response.ok) { + const metadata = await response.json() + if (!metadata || typeof metadata !== 'object' || Array.isArray(metadata)) + throw new Error(`Malformed registry metadata for ${name}@${version}.`) + return metadata + } + await response.body?.cancel() + if (response.status === 404) return null + const retryAfter = response.headers.get('retry-after') + const retryAfterMs = /^\d+$/.test(retryAfter ?? '') + ? Number(retryAfter) * 1000 + : Math.max(0, Date.parse(retryAfter) - Date.now()) || 0 + throw new RegistryLookupError( + `Registry lookup failed for ${name}@${version}: HTTP ${response.status}.`, + { + retryable: response.status === 429 || response.status >= 500, + retryAfterMs, + } + ) + } catch (error) { + if (signal.aborted || error instanceof TypeError) + throw new RegistryLookupError( + `Registry lookup for ${name}@${version} timed out or lost its connection.`, + { retryable: true } + ) + throw error + } +} + +async function verifyPublication(pkg, { lookup, wait, now, log, save }) { + const started = now() + const deadline = started + VERIFICATION_TIMEOUT_MS + let delay = 2000 + pkg.status = 'verifying' + pkg.verificationAttempts = 0 + await save() + log( + `Uploaded ${pkg.name}@${pkg.version}; verifying npm visibility and integrity (up to 5 minutes).` + ) + while (now() < deadline) { + pkg.verificationAttempts++ + let reason = 'version metadata is not visible yet' + let retryAfterMs = 0 + try { + const metadata = await lookup(pkg.name, pkg.version, { + timeoutMs: Math.max( + 1, + Math.ceil(Math.min(REQUEST_TIMEOUT_MS, deadline - now())) + ), + }) + if (metadata) { + matchesPublished(pkg, metadata) + pkg.status = 'published' + delete pkg.verificationMessage + await save() + log(`Verified ${pkg.name}@${pkg.version}.`) + return + } + } catch (error) { + if (!(error instanceof RegistryLookupError) || !error.retryable) + throw error + reason = error.message + retryAfterMs = error.retryAfterMs + } + pkg.verificationMessage = reason + await save() + const remaining = Math.max(0, deadline - now()) + if (!remaining) break + const next = Math.min(remaining, Math.max(delay, retryAfterMs)) + log( + `Waiting for ${pkg.name}@${pkg.version}: ${reason}; ${Math.round((now() - started) / 1000)}s elapsed, next check in ${Math.ceil(next / 1000)}s.` ) + // Long Retry-After values still produce a heartbeat at least every 30s. + const resumeAt = now() + next + while (now() < resumeAt && now() < deadline) { + const interval = Math.min(30_000, resumeAt - now(), deadline - now()) + if (interval <= 0) break + await wait(interval) + const remainingWait = Math.min(resumeAt, deadline) - now() + if (remainingWait > 0) + log( + `Still waiting for ${pkg.name}@${pkg.version}; next check in ${Math.ceil(remainingWait / 1000)}s.` + ) + } + delay = Math.min(delay * 2, 10_000) } - return response.json() + throw new Error( + `Upload completed for ${pkg.name}@${pkg.version}, but npm verification timed out after 5 minutes. No upload was retried. Preserve this report and rerun the release command after npm becomes visible; identical published packages will be skipped.` + ) } async function confirm(message) { @@ -285,6 +388,7 @@ export async function runRelease( dependencies.wait ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms))) const log = dependencies.log ?? console.log + const now = dependencies.now ?? (() => performance.now()) const env = dependencies.env ?? process.env const interactive = dependencies.interactive ?? @@ -427,22 +531,7 @@ export async function runRelease( ], { cwd: root } ) - let verified = false - for (let attempt = 0; attempt < 15; attempt++) { - const metadata = await lookup(pkg.name, pkg.version) - if (metadata) { - matchesPublished(pkg, metadata) - verified = true - break - } - if (attempt < 14) await wait(2000) - } - if (!verified) - throw new Error( - `Publication of ${pkg.name}@${pkg.version} is not yet verifiable. Check npm before retrying.` - ) - pkg.status = 'published' - await save() + await verifyPublication(pkg, { lookup, wait, now, log, save }) } report.phase = 'complete' await save() diff --git a/scripts/release.test.mjs b/scripts/release.test.mjs index 27b044f..9031c65 100644 --- a/scripts/release.test.mjs +++ b/scripts/release.test.mjs @@ -19,6 +19,8 @@ import { PACKAGES, parseArgs, REGISTRY, + RegistryLookupError, + readVersion, runRelease, } from './release.mjs' @@ -65,6 +67,9 @@ async function fixture(t) { fail: null, packMutation: null, onPublish: null, + elapsed: 0, + waits: [], + logs: [], } const metadata = (name) => { const entry = [...state.archives.values()].find( @@ -134,8 +139,12 @@ async function fixture(t) { execute, env: {}, interactive: true, - log: () => {}, - wait: async () => {}, + log: (message) => state.logs.push(message), + now: () => state.elapsed, + wait: async (ms) => { + state.waits.push(ms) + state.elapsed += ms + }, readVersion: async (name) => { state.lookups++ return state.published.get(name) ?? null @@ -474,9 +483,189 @@ test('unverifiable publication stops without retrying the upload or later packag f.state.onPublish = async () => {} await assert.rejects( runRelease({ publish: true, root: f.root }, f.dependencies), - /not yet verifiable/ + /verification timed out after 5 minutes/ ) assert.deepEqual(f.state.uploads, [PACKAGES[0][1]]) + assert.equal(f.state.elapsed, 300_000) + assert.equal((await f.report()).packages[0].status, 'verifying') + assert.ok(f.state.logs.some((line) => line.includes('next check in'))) +}) + +test('delayed visibility beyond the old polling limit completes without another upload', async (t) => { + const f = await fixture(t) + let attempts = 0 + const lookup = async (name) => { + if (!f.state.published.has(name)) return null + if (name === PACKAGES[0][1] && ++attempts <= 17) { + assert.deepEqual(f.state.uploads, [name]) + return null + } + return f.metadata(name) + } + const result = await runRelease( + { publish: true, root: f.root }, + { ...f.dependencies, readVersion: lookup } + ) + assert.equal(result.phase, 'complete') + assert.equal(result.packages[0].verificationAttempts, 18) + assert.ok(f.state.elapsed > 28_000) + assert.deepEqual( + f.state.uploads, + PACKAGES.map(([, name]) => name) + ) +}) + +test('verification retries transient reads, observes Retry-After and reports progress', async (t) => { + const f = await fixture(t) + let attempts = 0 + const lookup = async (name) => { + if (!f.state.published.has(name)) return null + if (name === PACKAGES[0][1] && ++attempts <= 2) + throw new RegistryLookupError('HTTP 429', { + retryable: true, + retryAfterMs: 45_000, + }) + return f.metadata(name) + } + await runRelease( + { publish: true, root: f.root }, + { ...f.dependencies, readVersion: lookup } + ) + assert.equal(f.state.elapsed, 90_000) + assert.ok(f.state.waits.every((ms) => ms <= 30_000)) + assert.ok(f.state.logs.some((line) => line.includes('Still waiting'))) + assert.deepEqual( + f.state.uploads, + PACKAGES.map(([, name]) => name) + ) +}) + +test('verification caps a long Retry-After at its deadline', async (t) => { + const f = await fixture(t) + const lookup = async (name) => { + if (!f.state.published.has(name)) return null + throw new RegistryLookupError('HTTP 503', { + retryable: true, + retryAfterMs: 600_000, + }) + } + await assert.rejects( + runRelease( + { publish: true, root: f.root }, + { ...f.dependencies, readVersion: lookup } + ), + /verification timed out/ + ) + assert.equal(f.state.elapsed, 300_000) + assert.deepEqual(f.state.uploads, [PACKAGES[0][1]]) +}) + +test('verification stops at its deadline after an unexpectedly long timer delay', async (t) => { + const f = await fixture(t) + let waits = 0 + await assert.rejects( + runRelease( + { publish: true, root: f.root }, + { + ...f.dependencies, + wait: async () => { + waits++ + f.state.elapsed += 600_000 + }, + readVersion: async (name) => { + if (!f.state.published.has(name)) return null + throw new RegistryLookupError('HTTP 429', { + retryable: true, + retryAfterMs: 120_000, + }) + }, + } + ), + /verification timed out/ + ) + assert.equal(waits, 1) + assert.deepEqual(f.state.uploads, [PACKAGES[0][1]]) +}) + +for (const failure of ['authorization', 'integrity']) { + test(`verification fails immediately on ${failure} without later uploads`, async (t) => { + const f = await fixture(t) + const lookup = async (name) => { + if (!f.state.published.has(name)) return null + if (failure === 'authorization') throw new RegistryLookupError('HTTP 403') + return { ...f.metadata(name), dist: { integrity: 'sha512-wrong' } } + } + await assert.rejects( + runRelease( + { publish: true, root: f.root }, + { ...f.dependencies, readVersion: lookup } + ), + /HTTP 403|will not be overwritten/ + ) + assert.equal(f.state.elapsed, 0) + assert.deepEqual(f.state.uploads, [PACKAGES[0][1]]) + }) +} + +test('version lookups request fresh metadata and never reuse a preflight cache key', async () => { + const requests = [] + const request = async (url, options) => { + requests.push({ url, options }) + return new Response(null, { status: 404 }) + } + assert.equal( + await readVersion('@motrix/plugin-api', '2.2.0', { fetch: request }), + null + ) + await readVersion('@motrix/plugin-api', '2.2.0', { fetch: request }) + assert.notEqual(requests[0].url.href, requests[1].url.href) + for (const { url, options } of requests) { + assert.equal(url.origin, 'https://registry.npmjs.org') + assert.equal(decodeURIComponent(url.pathname), '/@motrix/plugin-api/2.2.0') + assert.equal(options.cache, 'no-store') + assert.equal(options.headers['Cache-Control'], 'no-cache') + assert.equal(options.redirect, 'error') + } +}) + +for (const status of [401, 403, 429, 500, 503]) { + test(`version lookup classifies HTTP ${status} without treating it as absent`, async () => { + await assert.rejects( + readVersion('@motrix/plugin-api', '2.2.0', { + fetch: async () => + new Response(null, { status, headers: { 'Retry-After': '17' } }), + }), + (error) => { + assert.ok(error instanceof RegistryLookupError) + assert.equal(error.retryable, status === 429 || status >= 500) + assert.equal(error.retryAfterMs, 17_000) + return true + } + ) + }) +} + +test('a network failure is retryable but malformed registry data is not', async () => { + await assert.rejects( + readVersion('sample', '2.2.0', { + fetch: async () => { + throw new TypeError('fetch failed') + }, + }), + (error) => error instanceof RegistryLookupError && error.retryable + ) + await assert.rejects( + readVersion('sample', '2.2.0', { + fetch: async () => new Response('not json'), + }), + SyntaxError + ) + await assert.rejects( + readVersion('sample', '2.2.0', { + fetch: async () => new Response('null'), + }), + /Malformed registry metadata/ + ) }) test('real gzip tar archives are inspected without extracting files to disk', async (t) => {