From d9788e823a24f5f44d81bc875c8dc70f4843561e Mon Sep 17 00:00:00 2001 From: aaltshuler Date: Sat, 28 Nov 2026 18:43:24 +0200 Subject: [PATCH] Mirror published Orbit packages to the GitHub registry --- .github/workflows/release.yml | 22 ++ CONTRIBUTING.md | 4 + package.json | 2 +- scripts/mirror-github-packages.mjs | 293 ++++++++++++++++++++++++ scripts/mirror-github-packages.test.mjs | 258 +++++++++++++++++++++ 5 files changed, 578 insertions(+), 1 deletion(-) create mode 100644 scripts/mirror-github-packages.mjs create mode 100644 scripts/mirror-github-packages.test.mjs diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index c6d1b86..e3c2742 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -28,6 +28,8 @@ permissions: jobs: release: runs-on: ubuntu-latest + outputs: + has-changesets: ${{ steps.changesets.outputs.has-changesets }} steps: - uses: actions/checkout@v7 with: @@ -60,3 +62,23 @@ jobs: GH_TOKEN: ${{ github.token }} BEFORE_SHA: ${{ github.event.before }} PUBLISHED: ${{ steps.changesets.outputs.published }} + + github-packages: + needs: release + if: needs.release.outputs.has-changesets == 'false' + runs-on: ubuntu-latest + permissions: + contents: read + packages: write + steps: + - uses: actions/checkout@v7 + - uses: actions/setup-node@v7 + with: + node-version: 24 + registry-url: https://npm.pkg.github.com + scope: '@modernrelay' + package-manager-cache: false + - name: Mirror the published npm tarballs to GitHub Packages + run: node scripts/mirror-github-packages.mjs + env: + NODE_AUTH_TOKEN: ${{ github.token }} diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index a7fef80..21be115 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -50,3 +50,7 @@ five packages release in lockstep. When the version PR merges, the release workflow publishes the packages to npm and creates one GitHub release tagged `v`. Its notes combine the package changelogs and link to each published npm version. +The same workflow mirrors those npm tarballs to GitHub Packages. On the +first publish of a new package, set its GitHub package visibility to Public +so readers can find it in the repository's Packages section. The install +commands in the README use the public npm registry. diff --git a/package.json b/package.json index 8d463f2..eda99d9 100644 --- a/package.json +++ b/package.json @@ -4,7 +4,7 @@ "type": "module", "scripts": { "build": "pnpm -r --filter \"./packages/*\" run build", - "test": "pnpm -r run test && node --test scripts/orbit-release-notes.test.mjs", + "test": "pnpm -r run test && node --test scripts/orbit-release-notes.test.mjs scripts/mirror-github-packages.test.mjs", "typecheck": "pnpm -r run typecheck", "lint": "eslint .", "boundaries": "node scripts/check-boundaries.mjs", diff --git a/scripts/mirror-github-packages.mjs b/scripts/mirror-github-packages.mjs new file mode 100644 index 0000000..fc70b68 --- /dev/null +++ b/scripts/mirror-github-packages.mjs @@ -0,0 +1,293 @@ +#!/usr/bin/env node +/** + * Mirror the fixed release group's exact public npm tarballs to GitHub Packages. + * Usage: NODE_AUTH_TOKEN=... node scripts/mirror-github-packages.mjs + * Read-only source verification: node scripts/mirror-github-packages.mjs --verify-source + * First publication is private on GitHub; package admins set visibility separately. + */ +import { execFile } from 'node:child_process'; +import { createHash } from 'node:crypto'; +import { mkdtemp, rm, writeFile } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import path from 'node:path'; +import { setTimeout as delay } from 'node:timers/promises'; +import { pathToFileURL } from 'node:url'; +import { promisify } from 'node:util'; + +import { readReleasePackages, RELEASE_VERSION } from './orbit-release-packages.mjs'; + +const exec = promisify(execFile); +const PUBLIC_REGISTRY = 'https://registry.npmjs.org'; +const GITHUB_REGISTRY = 'https://npm.pkg.github.com'; +const PUBLIC_WAIT_MS = 12 * 60_000; +const TARGET_WAIT_MS = 2 * 60_000; +const POLL_MS = 15_000; +const MAX_TARBALL_BYTES = 256 * 1024 * 1024; + +function identity(manifest, pkg, where) { + if (manifest?.name !== pkg.name || manifest?.version !== pkg.version) { + throw new Error(`${where}: expected ${pkg.name}@${pkg.version}, received ${manifest?.name}@${manifest?.version}`); + } +} + +function verifyDigest(dist, bytes, where, requireStrong = false) { + const tokens = typeof dist?.integrity === 'string' ? dist.integrity.split(/\s+/) : []; + const supported = tokens.map((token) => /^(sha512|sha384|sha256)-([A-Za-z0-9+/]+={0,2})$/.exec(token)).filter(Boolean); + if (requireStrong && !supported.length) throw new Error(`${where}: missing strong tarball integrity`); + if (!supported.length && !/^[a-f\d]{40}$/i.test(dist?.shasum ?? '')) { + throw new Error(`${where}: missing verifiable tarball digest`); + } + for (const [, algorithm, expected] of supported) { + if (createHash(algorithm).update(bytes).digest('base64') !== expected) { + throw new Error(`${where}: conflicting tarball integrity (${algorithm})`); + } + } + if (dist?.shasum && createHash('sha1').update(bytes).digest('hex') !== dist.shasum.toLowerCase()) { + throw new Error(`${where}: conflicting tarball integrity (sha1)`); + } +} + +async function readTarball(response, name) { + const chunks = []; + let size = 0; + for await (const chunk of response.body) { + size += chunk.length; + if (size >= MAX_TARBALL_BYTES) throw new Error(`${name}: tarball exceeds GitHub Packages' size limit`); + chunks.push(chunk); + } + return Buffer.concat(chunks); +} + +async function verifyTarget(existing, source, context) { + const { pkg, bytes } = source; + const where = `GitHub Packages ${pkg.name}@${pkg.version}`; + if (typeof existing.dist?.integrity === 'string' && /(?:^|\s)sha(?:512|384|256)-/.test(existing.dist.integrity)) { + verifyDigest(existing.dist, bytes, where, true); + return; + } + if (existing.dist?.shasum) verifyDigest(existing.dist, bytes, where); + // GitHub registry metadata need not contain a strong SRI digest. In that case + // compare the actual stored archive, not just its name/version or SHA-1. + let url = new URL(existing.dist?.tarball); + if (url.origin !== GITHUB_REGISTRY) throw new Error(`${where}: unexpected tarball host`); + for (let redirects = 0; redirects <= 5; redirects++) { + if (url.protocol !== 'https:' || url.username || url.password) throw new Error(`${where}: invalid tarball URL`); + const response = await context.fetchImpl(url.href, { + // Blob-storage redirects may use signed URLs. Never forward registry auth + // to those hosts (or npmjs), even if the metadata points there. + headers: url.origin === GITHUB_REGISTRY ? { authorization: `Bearer ${context.token}` } : {}, + redirect: 'manual', signal: AbortSignal.timeout(30_000), + }); + if ([301, 302, 303, 307, 308].includes(response.status)) { + await response.body?.cancel(); + const location = response.headers.get('location'); + if (!location) throw new Error(`${where}: missing tarball redirect location`); + url = new URL(location, url); + continue; + } + if (!response.ok) { + await response.body?.cancel(); + throw new Error(`${where}: tarball download failed (${response.status})`); + } + if (!bytes.equals(await readTarball(response, pkg.name))) throw new Error(`${where}: conflicting tarball bytes`); + return; + } + throw new Error(`${where}: too many tarball redirects`); +} + +async function fetchResponse(url, { fetchImpl, token } = {}) { + const parsed = new URL(url); + if (parsed.origin !== (token ? GITHUB_REGISTRY : PUBLIC_REGISTRY) || parsed.username || parsed.password) { + throw new Error(`Refusing unexpected registry URL: ${parsed.origin}`); + } + // Public npm reads never use npm configuration or any inherited credentials. + // Refuse redirects so the GitHub token cannot be forwarded to another host. + return fetchImpl(url, { + headers: token ? { authorization: `Bearer ${token}` } : {}, + redirect: 'error', + signal: AbortSignal.timeout(30_000), + }); +} + +async function publicResponse(url, context) { + while (true) { + const response = await fetchResponse(url, context); + if (response.ok) return response; + const retryable = response.status === 404 || response.status === 408 || response.status === 429 || response.status >= 500; + await response.body?.cancel(); + if (!retryable || context.now() >= context.deadline) { + throw new Error(`Public npm request failed (${response.status}): ${url}`); + } + context.log(`Waiting for public npm propagation (${response.status}): ${url}`); + await context.sleep(Math.min(POLL_MS, context.deadline - context.now())); + } +} + +async function targetVersion(pkg, context) { + const url = `${GITHUB_REGISTRY}/${encodeURIComponent(pkg.name)}`; + const response = await fetchResponse(url, { ...context, token: context.token }); + if (response.status === 404) { + await response.body?.cancel(); + return null; + } + if (!response.ok) { + await response.body?.cancel(); + throw new Error(`GitHub Packages lookup failed (${response.status}) for ${pkg.name}`); + } + const metadata = await response.json(); + if (metadata?.name !== pkg.name || !metadata.versions || typeof metadata.versions !== 'object' || Array.isArray(metadata.versions)) { + throw new Error(`Invalid GitHub Packages metadata for ${pkg.name}`); + } + // A valid existing package can lack this version. Authentication and server + // errors above must never be mistaken for an absent package/version. + if (!Object.hasOwn(metadata.versions, pkg.version)) return null; + const version = metadata.versions[pkg.version]; + identity(version, pkg, 'GitHub Packages version'); + return version; +} + +async function readSource(pkg, directory, context) { + const url = `${PUBLIC_REGISTRY}/${encodeURIComponent(pkg.name)}/${encodeURIComponent(pkg.version)}`; + const metadata = await (await publicResponse(url, context)).json(); + identity(metadata, pkg, 'Public npm metadata'); + if (typeof metadata.dist?.tarball !== 'string') throw new Error(`${pkg.name}: missing public npm tarball URL`); + const response = await publicResponse(metadata.dist.tarball, context); + const bytes = await readTarball(response, pkg.name); + verifyDigest(metadata.dist, bytes, `Public npm ${pkg.name}@${pkg.version}`, true); + const tarball = path.join(directory, `${pkg.name.slice(1).replaceAll('/', '-')}-${pkg.version}.tgz`); + await writeFile(tarball, bytes); + // Read the manifest without extracting files to disk or executing scripts. + const { stdout } = await exec('tar', ['-xOf', tarball, 'package/package.json'], { maxBuffer: 1024 * 1024, timeout: 30_000 }); + const manifest = JSON.parse(stdout); + identity(manifest, pkg, 'Packaged manifest'); + const repository = typeof manifest.repository === 'string' ? manifest.repository : manifest.repository?.url; + if (manifest.private || !/^(?:git\+)?https:\/\/github\.com\/ModernRelay\/orbit(?:\.git)?\/?$/i.test(repository ?? '')) { + throw new Error(`${pkg.name}: tarball must be public and linked to ModernRelay/orbit`); + } + if (manifest.publishConfig?.registry && manifest.publishConfig.registry.replace(/\/$/, '') !== GITHUB_REGISTRY) { + throw new Error(`${pkg.name}: tarball publishConfig.registry would redirect publication`); + } + const packument = await (await publicResponse(`${PUBLIC_REGISTRY}/${encodeURIComponent(pkg.name)}`, context)).json(); + if (packument.name !== pkg.name || !packument['dist-tags'] || typeof packument['dist-tags'] !== 'object' || Array.isArray(packument['dist-tags'])) { + throw new Error(`${pkg.name}: invalid public npm dist-tags`); + } + const tags = Object.entries(packument['dist-tags']).filter(([, version]) => version === pkg.version).map(([tag]) => tag).sort(); + const tag = tags.includes('latest') ? 'latest' : tags[0]; + return { pkg, bytes, tarball, tag }; +} + +/** Publish the existing archive, with isolated GitHub-only auth and no hooks. */ +export async function publishTarball(tarball, { token, directory, tag, execImpl = exec, env = process.env }) { + if (!tag || tag.startsWith('-')) throw new Error('An explicit public npm dist-tag is required'); + const userconfig = env.NPM_CONFIG_USERCONFIG ?? env.npm_config_userconfig ?? path.join(directory, 'github.npmrc'); + const globalconfig = path.join(directory, 'empty.npmrc'); + if (!env.NPM_CONFIG_USERCONFIG && !env.npm_config_userconfig) await writeFile(userconfig, [ + `registry=${GITHUB_REGISTRY}`, + `@modernrelay:registry=${GITHUB_REGISTRY}`, + '//npm.pkg.github.com/:_authToken=${NODE_AUTH_TOKEN}', + 'ignore-scripts=true', + 'provenance=false', + '', + ].join('\n'), { mode: 0o600 }); + await writeFile(globalconfig, ''); + try { + await execImpl('npm', ['publish', tarball, `--registry=${GITHUB_REGISTRY}`, `--tag=${tag}`, '--ignore-scripts', '--provenance=false'], { + cwd: directory, + timeout: 5 * 60_000, + maxBuffer: 4 * 1024 * 1024, + env: { + PATH: env.PATH, + HOME: env.HOME, + CI: 'true', + NODE_AUTH_TOKEN: token, + NPM_CONFIG_USERCONFIG: userconfig, + NPM_CONFIG_GLOBALCONFIG: globalconfig, + NPM_CONFIG_CACHE: path.join(directory, 'npm-cache'), + }, + }); + } catch (error) { + // npm normally redacts auth; do not rely on that for child error output. + const detail = String(error.stderr || error.message).replaceAll(token, '[redacted]').slice(-2000); + throw new Error(`GitHub Packages publish failed: ${detail}`); + } +} + +/** Injectable I/O keeps the release safety/retry tests entirely offline. */ +export async function mirrorPackages({ + packages = readReleasePackages(), token = process.env.NODE_AUTH_TOKEN, + verifySourceOnly = false, fetchImpl = fetch, publishImpl = publishTarball, + sleep = delay, now = Date.now, log = console.log, + publicWaitMs = PUBLIC_WAIT_MS, targetWaitMs = TARGET_WAIT_MS, +} = {}) { + if (!verifySourceOnly && !token) throw new Error('NODE_AUTH_TOKEN is required for GitHub Packages'); + for (const pkg of packages) { + if (!/^@modernrelay\/orbit-[a-z-]+$/.test(pkg.name) || !RELEASE_VERSION.test(pkg.version)) { + throw new Error('Expected exact scoped Orbit package names and versions'); + } + } + const directory = await mkdtemp(path.join(tmpdir(), 'orbit-github-packages-')); + try { + // Validate every source before making any registry mutation. + const publicContext = { fetchImpl, sleep, now, log, deadline: now() + publicWaitMs }; + const sources = []; + for (const pkg of packages) sources.push(await readSource(pkg, directory, publicContext)); + if (verifySourceOnly) { + for (const { pkg } of sources) log(`Verified public npm tarball: ${pkg.name}@${pkg.version}`); + return sources.map(({ pkg }) => ({ name: pkg.name, version: pkg.version, status: 'verified' })); + } + + const context = { fetchImpl, token }; + const targets = []; + for (const source of sources) { + const { pkg, tag } = source; + const existing = await targetVersion(pkg, context); + if (existing !== null) await verifyTarget(existing, source, context); + else if (!tag) throw new Error(`${pkg.name}@${pkg.version}: no public npm dist-tag points to this version; refusing to change GitHub latest`); + targets.push(existing); + } + const result = []; + for (const [index, source] of sources.entries()) { + const { pkg, tarball, tag } = source; + let existing = targets[index]; + const alreadyExists = existing !== null; + if (!alreadyExists) { + let publishError; + try { + await publishImpl(tarball, { token, directory, tag }); + } catch (error) { + // A registry write can succeed even if its response is lost. Verify + // exact content before considering such an ambiguous result success. + publishError = error; + } + const deadline = now() + targetWaitMs; + while (true) { + existing = await targetVersion(pkg, context); + if (existing !== null) break; + if (now() >= deadline) throw publishError ?? new Error(`${pkg.name}@${pkg.version}: publication not visible after waiting`); + await sleep(Math.min(POLL_MS, deadline - now())); + } + } + identity(existing, pkg, 'GitHub Packages version'); + if (!alreadyExists) await verifyTarget(existing, source, context); + const status = alreadyExists ? 'existing' : 'published'; + log(`${status === 'existing' ? 'Verified existing' : 'Mirrored'} GitHub package: ${pkg.name}@${pkg.version}`); + result.push({ name: pkg.name, version: pkg.version, status }); + } + return result; + } finally { + await rm(directory, { recursive: true, force: true }); + } +} + +if (process.argv[1] && import.meta.url === pathToFileURL(path.resolve(process.argv[1])).href) { + try { + const args = process.argv.slice(2); + if (args.length > 1 || (args.length === 1 && args[0] !== '--verify-source')) { + throw new Error('Usage: node scripts/mirror-github-packages.mjs [--verify-source]'); + } + await mirrorPackages({ verifySourceOnly: args[0] === '--verify-source' }); + } catch (error) { + console.error(`mirror-github-packages: ${error.message}`); + process.exitCode = 1; + } +} diff --git a/scripts/mirror-github-packages.test.mjs b/scripts/mirror-github-packages.test.mjs new file mode 100644 index 0000000..4562d6b --- /dev/null +++ b/scripts/mirror-github-packages.test.mjs @@ -0,0 +1,258 @@ +import assert from 'node:assert/strict'; +import { execFileSync } from 'node:child_process'; +import { createHash } from 'node:crypto'; +import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import path from 'node:path'; +import { test } from 'node:test'; + +import { mirrorPackages, publishTarball } from './mirror-github-packages.mjs'; + +const TOKEN = 'test-github-secret'; +const PUBLIC = 'https://registry.npmjs.org'; +const GITHUB = 'https://npm.pkg.github.com'; + +function source(t, overrides = {}) { + const dir = mkdtempSync(path.join(tmpdir(), 'orbit-mirror-test-')); + t.after(() => rmSync(dir, { recursive: true, force: true })); + mkdirSync(path.join(dir, 'package')); + const manifest = { + name: '@modernrelay/orbit-core', version: '1.2.3', + repository: { type: 'git', url: 'git+https://github.com/ModernRelay/orbit.git' }, + scripts: { prepublishOnly: 'exit 99', publish: 'exit 99', postpublish: 'exit 99' }, + ...overrides, + }; + writeFileSync(path.join(dir, 'package/package.json'), JSON.stringify(manifest)); + const tarball = path.join(dir, 'source.tgz'); + execFileSync('tar', ['-czf', tarball, '-C', dir, 'package']); + const bytes = readFileSync(tarball); + const dist = { + integrity: `sha512-${createHash('sha512').update(bytes).digest('base64')}`, + shasum: createHash('sha1').update(bytes).digest('hex'), + tarball: `${PUBLIC}/${manifest.name}/-/orbit-core-${manifest.version}.tgz`, + }; + return { dir, manifest, bytes, metadata: { ...manifest, dist }, pkg: { name: manifest.name, version: manifest.version, dir } }; +} + +function harness(src, { target = null, targetStatus = 200, publicMissing = 0, tags = { latest: src.pkg.version } } = {}) { + const calls = []; + const published = []; + let elapsed = 0; + let checks = 0; + let currentTarget = target; + const options = { + packages: [src.pkg], token: TOKEN, log: () => {}, + now: () => elapsed, + sleep: async (ms) => { elapsed += ms; }, + fetchImpl: async (url, options) => { + calls.push({ url, options }); + const origin = new URL(url).origin; + assert.equal(options.redirect, 'error'); + if (origin === PUBLIC) { + assert.deepEqual(options.headers, {}); + if (url === src.metadata.dist.tarball) return new Response(src.bytes); + if (url === `${PUBLIC}/${encodeURIComponent(src.pkg.name)}`) return Response.json({ name: src.pkg.name, 'dist-tags': tags }); + if (checks++ < publicMissing) return new Response('', { status: 404 }); + return Response.json(src.metadata); + } + assert.equal(origin, GITHUB); + assert.deepEqual(options.headers, { authorization: `Bearer ${TOKEN}` }); + if (targetStatus !== 200) return new Response('', { status: targetStatus }); + return currentTarget === null ? new Response('', { status: 404 }) + : Response.json({ name: src.pkg.name, versions: currentTarget }); + }, + publishImpl: async (tarball) => { + assert.deepEqual(readFileSync(tarball), src.bytes); + published.push(tarball); + currentTarget = { [src.pkg.version]: src.metadata }; + }, + }; + return { calls, published, options, elapsed: () => elapsed }; +} + +test('mirrors exact verified bytes, isolates credentials, and skips an identical version on retry', async (t) => { + const src = source(t); + const h = harness(src); + assert.deepEqual(await mirrorPackages(h.options), [{ name: src.pkg.name, version: '1.2.3', status: 'published' }]); + assert.equal(h.published.length, 1); + assert.ok(!existsSync(path.dirname(h.published[0])), 'temporary artifacts cleaned up'); + assert.deepEqual(await mirrorPackages(h.options), [{ name: src.pkg.name, version: '1.2.3', status: 'existing' }]); + assert.equal(h.published.length, 1, 'retry must not publish again'); + assert.ok(h.calls.some(({ url }) => new URL(url).origin === PUBLIC)); + assert.ok(h.calls.some(({ url }) => new URL(url).origin === GITHUB)); +}); + +test('allows a new version of an existing package and tolerates more than six minutes of public propagation', async (t) => { + const src = source(t); + const h = harness(src, { target: {}, publicMissing: 25 }); + await mirrorPackages(h.options); + assert.equal(h.elapsed(), 375_000); + assert.equal(h.published.length, 1); +}); + +test('fails on conflicting target content instead of overwriting an existing version', async (t) => { + const src = source(t); + const h = harness(src, { target: { '1.2.3': { ...src.metadata, dist: { shasum: '0'.repeat(40) } } } }); + await assert.rejects(mirrorPackages(h.options), /conflicting tarball integrity/); + assert.equal(h.published.length, 0); +}); + +test('401, 403, and 500 are failures, not absent GitHub packages', async (t) => { + const src = source(t); + for (const targetStatus of [401, 403, 500]) { + const h = harness(src, { targetStatus }); + await assert.rejects(mirrorPackages(h.options), new RegExp(`lookup failed \\(${targetStatus}\\)`)); + assert.equal(h.published.length, 0); + } +}); + +test('invalid existing version metadata is not treated as an absent version', async (t) => { + const src = source(t); + for (const version of [null, { ...src.metadata, version: '1.2.4' }]) { + const h = harness(src, { target: { '1.2.3': version } }); + await assert.rejects(mirrorPackages(h.options), /GitHub Packages version: expected/); + assert.equal(h.published.length, 0); + } +}); + +test('rejects corrupted public tarballs and wrong packaged identities before writing', async (t) => { + const src = source(t); + src.bytes = Buffer.from('corrupt archive'); + const h = harness(src); + await assert.rejects(mirrorPackages(h.options), /Public npm .*conflicting tarball integrity/); + assert.equal(h.published.length, 0); + + const other = source(t, { name: '@modernrelay/orbit-react' }); + other.pkg.name = '@modernrelay/orbit-core'; + other.metadata.name = other.pkg.name; + const mismatch = harness(other); + await assert.rejects(mirrorPackages(mismatch.options), /Packaged manifest: expected/); + assert.equal(mismatch.published.length, 0); +}); + +test('refuses tarball redirects to another registry and wrong repository links', async (t) => { + const src = source(t); + src.metadata.dist.tarball = 'https://example.com/package.tgz'; + const h = harness(src); + await assert.rejects(mirrorPackages(h.options), /Refusing unexpected registry URL/); + assert.equal(h.published.length, 0); + const wrongRepo = harness(source(t, { repository: 'https://github.com/other/repo' })); + await assert.rejects(mirrorPackages(wrongRepo.options), /linked to ModernRelay\/orbit/); + assert.equal(wrongRepo.published.length, 0); +}); + +test('accepts a lost publish response only after verifying the exact stored version', async (t) => { + const src = source(t); + const h = harness(src); + const publish = h.options.publishImpl; + h.options.publishImpl = async (...args) => { + await publish(...args); + throw new Error('connection lost after write'); + }; + assert.equal((await mirrorPackages(h.options))[0].status, 'published'); + assert.equal(h.published.length, 1); +}); + +test('bounds missing source and missing target propagation without repeating a publish', async (t) => { + const src = source(t); + const missingSource = harness(src, { publicMissing: Infinity }); + await assert.rejects(mirrorPackages({ ...missingSource.options, publicWaitMs: 30_000 }), /Public npm request failed \(404\)/); + assert.equal(missingSource.elapsed(), 30_000); + assert.equal(missingSource.published.length, 0); + const missingTarget = harness(src); + let writes = 0; + missingTarget.options.publishImpl = async () => { writes++; throw new Error('publish rejected'); }; + await assert.rejects(mirrorPackages({ ...missingTarget.options, targetWaitMs: 30_000 }), /publish rejected/); + assert.equal(missingTarget.elapsed(), 30_000); + assert.equal(writes, 1); +}); + +test('source-only verification needs no token and never contacts GitHub', async (t) => { + const src = source(t); + const h = harness(src); + assert.equal((await mirrorPackages({ ...h.options, token: undefined, verifySourceOnly: true }))[0].status, 'verified'); + assert.equal(h.published.length, 0); + assert.ok(h.calls.every(({ url }) => new URL(url).origin === PUBLIC)); +}); + +test('npm subprocess uses a GH-only isolated config and ignores all lifecycle scripts', async (t) => { + const src = source(t); + let calls = 0; + await publishTarball('/tmp/example.tgz', { + token: TOKEN, directory: src.dir, tag: 'latest', + env: { PATH: '/bin', HOME: '/original-home', NODE_AUTH_TOKEN: 'npm-secret', NPM_TOKEN: 'npm-secret', NPM_CONFIG_REGISTRY: PUBLIC, NODE_OPTIONS: '--require=evil.js' }, + execImpl: async (command, args, options) => { + calls++; + assert.equal(command, 'npm'); + assert.deepEqual(args, ['publish', '/tmp/example.tgz', `--registry=${GITHUB}`, '--tag=latest', '--ignore-scripts', '--provenance=false']); + assert.equal(options.cwd, src.dir); + assert.equal(options.env.NODE_AUTH_TOKEN, TOKEN); + assert.equal(options.env.HOME, '/original-home'); + assert.equal(options.env.NPM_TOKEN, undefined); + assert.equal(options.env.NODE_OPTIONS, undefined); + assert.equal(options.env.NPM_CONFIG_REGISTRY, undefined); + const config = readFileSync(options.env.NPM_CONFIG_USERCONFIG, 'utf8'); + assert.match(config, /\/\/npm\.pkg\.github\.com\/:_authToken=\$\{NODE_AUTH_TOKEN\}/); + assert.doesNotMatch(config, /npmjs|test-github-secret|npm-secret/); + assert.equal(readFileSync(options.env.NPM_CONFIG_GLOBALCONFIG, 'utf8'), ''); + }, + }); + assert.equal(calls, 1); +}); + +test('uses setup-node userconfig unchanged when provided', async (t) => { + const src = source(t); + const userconfig = path.join(src.dir, 'setup-node.npmrc'); + const content = '//npm.pkg.github.com/:_authToken=${NODE_AUTH_TOKEN}\n@modernrelay:registry=https://npm.pkg.github.com\n'; + writeFileSync(userconfig, content); + await publishTarball('/tmp/example.tgz', { + token: TOKEN, directory: src.dir, tag: 'latest', env: { PATH: '/bin', NPM_CONFIG_USERCONFIG: userconfig }, + execImpl: async (_command, _args, options) => { + assert.equal(options.env.NPM_CONFIG_USERCONFIG, userconfig); + assert.equal(readFileSync(userconfig, 'utf8'), content); + }, + }); +}); + +test('uses the authoritative prerelease tag and refuses untagged historical versions', async (t) => { + const src = source(t, { version: '1.3.0-beta.1', repository: 'https://github.com/ModernRelay/orbit' }); + const h = harness(src, { tags: { latest: '1.2.3', beta: '1.3.0-beta.1' } }); + const publish = h.options.publishImpl; + h.options.publishImpl = async (tarball, options) => { + assert.equal(options.tag, 'beta'); + await publish(tarball, options); + }; + await mirrorPackages(h.options); + assert.equal(h.published.length, 1); + const old = harness(src, { tags: { latest: '1.3.0' } }); + await assert.rejects(mirrorPackages(old.options), /no public npm dist-tag points to this version/); + assert.equal(old.published.length, 0); +}); + +test('compares target tarball bytes when GH metadata lacks strong integrity, stripping auth on redirects', async (t) => { + const src = source(t); + const ghTarball = `${GITHUB}/download/@modernrelay/orbit-core/1.2.3/archive`; + const h = harness(src, { target: { '1.2.3': { ...src.metadata, dist: { tarball: ghTarball } } } }); + const fetch = h.options.fetchImpl; + let downloads = 0; + h.options.fetchImpl = async (url, options) => { + if (url === ghTarball) { + assert.deepEqual(options.headers, { authorization: `Bearer ${TOKEN}` }); + assert.equal(options.redirect, 'manual'); + return new Response('', { status: 302, headers: { location: 'https://storage.example.com/signed-archive' } }); + } + if (url === 'https://storage.example.com/signed-archive') { + downloads++; + assert.deepEqual(options.headers, {}); + return new Response(src.bytes); + } + return fetch(url, options); + }; + assert.equal((await mirrorPackages(h.options))[0].status, 'existing'); + assert.equal(downloads, 1); + assert.equal(h.published.length, 0); + const validFetch = h.options.fetchImpl; + h.options.fetchImpl = (url, options) => url === 'https://storage.example.com/signed-archive' + ? Promise.resolve(new Response('different bytes')) : validFetch(url, options); + await assert.rejects(mirrorPackages(h.options), /conflicting tarball bytes/); +});