Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions .github/workflows/release.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down Expand Up @@ -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 }}
4 changes: 4 additions & 0 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -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<version>`. 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.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
293 changes: 293 additions & 0 deletions scripts/mirror-github-packages.mjs
Original file line number Diff line number Diff line change
@@ -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;
}
}
Loading
Loading