fix(apps): document Railway SSH setup and sync with master

Register the board-only SSH setup operation with its shared request schema and error responses. Resolve current catalog and branding metadata conflicts.

Co-Authored-By: Paperclip <noreply@paperclip.ing>
This commit is contained in:
Devin FoleyandPaperclip committed 2026-09-15 17:16:15 -07:00
commit 303340f190
488 files changed
+116005 -2175

No files matched your search

+13 -19
View File
@@ -25,19 +25,15 @@ function runShard(args) {
return result.stdout.trim().split(/\s+/).filter(Boolean);
}
function readPinnedTrustedPrWorkflow() {
function readTrustedPrWorkflow() {
const caller = readFileSync(prCallerWorkflow, "utf8");
const pin = caller.match(
/uses: paperclipai\/paperclip\/\.github\/workflows\/pr-trusted\.yml@([0-9a-f]{40})/,
assert.match(
caller,
/^\s+uses: paperclipai\/paperclip\/\.github\/workflows\/pr-trusted\.yml@master\s*$/m,
"pr.yml must call the trusted workflow from CODEOWNERS-protected master",
);
assert.ok(pin, "pr.yml must call the trusted workflow at a full commit SHA");
const result = spawnSync("git", ["show", `${pin[1]}:${trustedPrWorkflowPath}`], {
cwd: repoRoot,
encoding: "utf8",
});
assert.equal(result.status, 0, `cannot read the pinned trusted workflow: ${result.stderr}`);
return result.stdout;
// Validate proposed workflow changes locally; CI executes the merged master version.
return readFileSync(trustedPrWorkflow, "utf8");
}
function readWorkflowJobs(workflow) {
@@ -161,15 +157,15 @@ test("shard arguments are validated", () => {
}
});
test("pr.yml calls the trusted PR workflow at an immutable SHA", () => {
assert.ok(readPinnedTrustedPrWorkflow().length > 0);
test("pr.yml calls the trusted PR workflow from master", () => {
assert.ok(readTrustedPrWorkflow().length > 0);
});
test("the trusted PR workflow keeps a stable aggregate check named e2e over the shard matrix", () => {
// Branch protection requires a check literally named `e2e`. The shards run
// as `e2e shard (n/3)`, so the aggregate job below is what keeps the
// required-check contract intact — same pattern as the `verify` aggregate.
const workflow = readPinnedTrustedPrWorkflow();
const workflow = readTrustedPrWorkflow();
const jobs = readWorkflowJobs(workflow);
const aggregate = jobs.get("e2e");
@@ -293,7 +289,7 @@ test("the stacked PR scope selector runs full CI only where intended", () => {
test("the trusted PR workflow passes the shard's spec filter to Playwright without a literal --", () => {
// `pnpm run test:e2e -- $specs` forwards the literal separator to Playwright,
// so the specs after it are not applied as file filters.
const workflow = readPinnedTrustedPrWorkflow();
const workflow = readTrustedPrWorkflow();
assert.ok(
!/pnpm run test:e2e --\s/.test(workflow),
"pr-trusted.yml must not insert a literal `--` between `pnpm run test:e2e` and the spec filter",
@@ -306,10 +302,8 @@ test("the trusted PR workflow passes the shard's spec filter to Playwright witho
});
test("the trusted PR workflow regenerates stale stacked lockfiles", () => {
// Implementation PRs validate the workflow under development here. The
// caller remains pinned to the last merged trusted SHA until a separate
// activation PR advances it, so unmerged PR code never runs on trusted
// infrastructure.
// Validate the proposed workflow here. The caller executes the merged master
// workflow; edits to this workflow take effect after code-owner review and merge.
const workflow = readFileSync(trustedPrWorkflow, "utf8");
assert.match(
workflow,
+47
View File
@@ -0,0 +1,47 @@
export const assetPathPattern = /^\/brands\/apps\/[a-z0-9-]+\.(svg|png)$/;
export const normalizeBrandKey = (value) => value.trim().toLowerCase().replace(/&/g, "and").replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
// Conservative structural rejection, not a general-purpose SVG sanitizer.
// Original accepted artwork is copied byte-for-byte, never rewritten here.
export function validateArtwork(bytes, filename) {
if (filename.endsWith(".png")) {
if (bytes.length < 45 || !bytes.subarray(0, 8).equals(Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]))
|| bytes.toString("ascii", 12, 16) !== "IHDR" || bytes.readUInt32BE(16) === 0 || bytes.readUInt32BE(20) === 0
|| bytes.toString("ascii", bytes.length - 8, bytes.length - 4) !== "IEND") {
throw new Error(`${filename}: invalid PNG signature`);
}
return;
}
const svg = bytes.toString("utf8");
if (!filename.endsWith(".svg") || (!/<svg\b[^>]*\bviewBox\s*=\s*["'][^"']+["']/i.test(svg) && !(/<svg\b[^>]*\bwidth\s*=\s*["'][0-9.]+(?:px)?["']/i.test(svg) && /<svg\b[^>]*\bheight\s*=\s*["'][0-9.]+(?:px)?["']/i.test(svg)))) {
throw new Error(`${filename}: SVG requires a viewBox or intrinsic width and height`);
}
if (/<!DOCTYPE|<!ENTITY|<\?xml-stylesheet|&#|<\s*(?:[\w-]+:)?(?:script|foreignObject|image|feImage|iframe|object|embed|animate\w*|set|a)\b|\bon[\w-]+\s*=/i.test(svg)
|| /\b(?:[\w-]+:)?href\s*=\s*["'](?!#)/i.test(svg)
|| /@import|@media|url\(\s*["']?(?!#)[^)]*\)|(?:javascript|data|https?):|\\/i.test(svg.replace(/xmlns(?::[\w-]+)?\s*=\s*["'][^"']*["']/gi, ""))) {
throw new Error(`${filename}: unsafe SVG feature, external resource, theme media query, or embedded raster wrapper`);
}
}
export function validateManifest(manifest, readAsset) {
if (manifest.schemaVersion !== 1 || !Array.isArray(manifest.providers)) throw new Error("Invalid brand manifest");
const keys = new Map();
const slugs = new Set();
for (const row of manifest.providers) {
if (!/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(row.slug) || slugs.has(row.slug)) throw new Error(`Duplicate or invalid slug: ${row.slug}`);
slugs.add(row.slug);
if (typeof row.provider !== "string" || !row.provider.trim()) throw new Error(`${row.slug}: missing provider name`);
const aliases = row.aliases ?? [];
if (!Array.isArray(aliases) || aliases.some((alias) => typeof alias !== "string" || !alias.trim())) throw new Error(`${row.slug}: invalid aliases`);
for (const name of [row.slug, row.provider, ...aliases]) {
const key = normalizeBrandKey(name);
if (keys.has(key) && keys.get(key) !== row.slug) throw new Error(`${row.slug}: ambiguous brand alias ${name}`);
keys.set(key, row.slug);
}
for (const asset of new Set([row.localAsset, ...(row.darkAsset === undefined ? [] : [row.darkAsset])])) {
if (typeof asset !== "string" || !assetPathPattern.test(asset)) throw new Error(`${row.slug}: invalid asset path`);
validateArtwork(readAsset(asset), asset);
}
}
return manifest.providers.length;
}
+34
View File
@@ -0,0 +1,34 @@
import { test } from "node:test";
import assert from "node:assert/strict";
import { validateArtwork, validateManifest } from "./app-brand-validation.mjs";
const svg = Buffer.from('<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path fill="white" d="M0 0h24v24H0z"/></svg>');
const record = () => ({
slug: "example", provider: "Example", aliases: [], localAsset: "/brands/apps/example.svg", darkAsset: "/brands/apps/example.svg",
});
const check = (row, read = () => svg) => validateManifest({ schemaVersion: 1, providers: [row] }, read);
test("accepts authentic vector artwork, native gradients and actual PNG bytes", () => {
assert.equal(check(record()), 1);
validateArtwork(Buffer.from('<svg viewBox="0 0 24 24"><defs><linearGradient id="g"/></defs><path fill="url(#g)"/></svg>'), "gradient.svg");
validateArtwork(Buffer.from("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+jRZkAAAAASUVORK5CYII=", "base64"), "native.png");
assert.throws(() => validateArtwork(Buffer.from("89504e470d0a1a0a", "hex"), "truncated.png"), /PNG/);
assert.throws(() => validateArtwork(svg, "fake.png"), /PNG/);
});
for (const payload of ['<script/>', '<foreignObject/>', '<image href="data:image/png;base64,abc"/>', '<path onload="x()"/>', '<use href="https://example.com/a.svg#x"/>', '<style>@import "x"</style>', '<path fill="url(https://example.com/x)"/>', '<animate attributeName="href"/>', '<style>@media(prefers-color-scheme:dark){}</style>', '<use href="&#35;x"/>']) {
test(`rejects unsupported SVG features: ${payload}`, () => assert.throws(() => validateArtwork(Buffer.from(`<svg viewBox="0 0 24 24">${payload}</svg>`), "unsafe.svg"), /unsafe/));
}
test("rejects missing files and unsafe asset paths in either theme", () => {
assert.throws(() => check(record(), () => { throw new Error("ENOENT"); }), /ENOENT/);
const same = record(); delete same.darkAsset; assert.equal(check(same), 1);
for (const field of ["localAsset", "darkAsset"]) {
for (const value of ["/brands/apps/../x.svg", "https://example.com/a.svg", null]) {
assert.throws(() => check({ ...record(), [field]: value }), /asset path/);
}
}
});
test("rejects ambiguous aliases, permits shared art for separate identities", () => {
const a = record(); const b = { ...record(), slug: "second", provider: "Second", aliases: ["Example"] };
assert.throws(() => validateManifest({ schemaVersion: 1, providers: [a, b] }, () => svg), /ambiguous/);
b.aliases = []; assert.equal(validateManifest({ schemaVersion: 1, providers: [a, b] }, () => svg), 2);
});
+12 -2
View File
@@ -64,8 +64,18 @@ echo " [5/6] Generating publishable package.json..."
cp "$CLI_DIR/package.json" "$CLI_DIR/package.dev.json"
node "$REPO_ROOT/scripts/generate-npm-package-json.mjs"
# Copy root README so npm shows the repo README on the package page
cp "$REPO_ROOT/README.md" "$CLI_DIR/README.md"
# Copy the root README so npm shows the repo README on the package page, but
# rewrite repository-relative image assets because npm resolves README links
# under the package's `repository.directory` (`cli`), not the repository root.
README_ASSET_REF="${PAPERCLIP_README_ASSET_REF:-}"
if [ -z "$README_ASSET_REF" ]; then
README_ASSET_REF="$(git -C "$REPO_ROOT" rev-parse HEAD 2>/dev/null || true)"
fi
README_ASSET_REF="${README_ASSET_REF:-master}"
node "$REPO_ROOT/scripts/prepare-npm-readme.mjs" \
"$REPO_ROOT/README.md" \
"$CLI_DIR/README.md" \
"$README_ASSET_REF"
# ── Step 6: Summary ───────────────────────────────────────────────────────────
BUNDLE_SIZE=$(wc -c < "$DIST_DIR/index.js" | xargs)
+8
View File
@@ -0,0 +1,8 @@
import fs from "node:fs";
import path from "node:path";
import { validateManifest } from "./app-brand-validation.mjs";
const root = process.cwd();
const manifest = JSON.parse(fs.readFileSync(path.join(root, "ui/public/brands/apps/manifest.json"), "utf8"));
const count = validateManifest(manifest, (asset) => fs.readFileSync(path.join(root, "ui/public", asset)));
console.log(`Validated ${count} brand identities: local paths, aliases and artwork safety.`);
+210
View File
@@ -0,0 +1,210 @@
#!/usr/bin/env node
// The build job has no publish credential. The publisher only validates and
// uploads fixed data files; it never installs or executes package code.
import { createHash } from "node:crypto";
import { execFileSync } from "node:child_process";
import { copyFileSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import os from "node:os";
import path from "node:path";
import { pathToFileURL } from "node:url";
import { assertMetadata, tarManifest, versionFor } from "./preview-artifacts.mjs";
export const artifactBase = "https://d1p6rlowie26tp.cloudfront.net/cloud-migrators/v1";
export const artifactBucket = "paperclipai-runner-e2e-history-078455283791-us-east-1";
const prefix = "cloud-migrators/v1/";
const names = ["db", "shared"];
const maximumBytes = 32 * 1024 * 1024;
const integrityFor = (bytes) => `sha512-${createHash("sha512").update(bytes).digest("base64")}`;
export function descriptor(bytes, extension) {
const hash = createHash("sha512").update(bytes).digest("hex");
return { url: `${artifactBase}/blobs/${hash}.${extension}`, integrity: integrityFor(bytes), size: bytes.length };
}
function assertDescriptor(pin, extension) {
if (!pin || typeof pin.integrity !== "string" || !/^sha512-[A-Za-z0-9+/]{86}==$/.test(pin.integrity) ||
!Number.isSafeInteger(pin.size) || pin.size <= 0 || pin.size > maximumBytes) throw new Error("Invalid artifact integrity or size.");
const digest = Buffer.from(pin.integrity.slice(7), "base64");
if (digest.toString("base64") !== pin.integrity.slice(7) || pin.url !== `${artifactBase}/blobs/${digest.toString("hex")}.${extension}`) {
throw new Error("Artifact URL does not match its content hash and trusted origin.");
}
}
export function assertManifest(manifest, sha) {
if (manifest?.version !== 1 || manifest.sourceSha !== sha || manifest.packageVersion !== versionFor(sha)) throw new Error("Artifact source identity mismatch.");
for (const name of names) assertDescriptor(manifest.packages?.[name], "tgz");
assertDescriptor(manifest.lockfile, "json");
}
export function assertLockfile(lock, manifest) {
const version = manifest.packageVersion;
if (lock?.lockfileVersion !== 3 || !lock.packages || Array.isArray(lock.packages) ||
JSON.stringify(lock.packages[""]?.dependencies) !== JSON.stringify({ "@paperclipai/db": version })) throw new Error("Invalid migrator lockfile root.");
for (const name of names) {
const pin = lock.packages[`node_modules/@paperclipai/${name}`];
const expected = manifest.packages[name];
if (pin?.version !== version || pin.integrity !== expected.integrity || pin.resolved !== expected.url || pin.link || pin.inBundle) throw new Error("Migrator lockfile package pin mismatch.");
}
if (lock.packages["node_modules/@paperclipai/db"].dependencies?.["@paperclipai/shared"] !== version) throw new Error("Migrator shared dependency mismatch.");
for (const [key, entry] of Object.entries(lock.packages)) {
if (key === "") continue;
if (!entry || typeof entry !== "object" || entry.link) throw new Error("Invalid migrator lockfile entry.");
if (/(?:^|\/)node_modules\/@paperclipai\/[^/]+$/.test(key) && !names.some((name) => key === `node_modules/@paperclipai/${name}`)) throw new Error("Unexpected internal migrator dependency.");
if (entry.inBundle === true) {
if (!key.startsWith("node_modules/@paperclipai/db/node_modules/")) throw new Error("Unexpected bundled dependency.");
continue;
}
if (!/^sha512-[A-Za-z0-9+/]{86}==$/.test(entry.integrity ?? "")) throw new Error("Migrator dependency has no strong integrity pin.");
if (names.some((name) => key === `node_modules/@paperclipai/${name}`)) continue;
const url = new URL(entry.resolved);
if (url.origin !== "https://registry.npmjs.org" || url.username || url.password || url.search || url.hash) throw new Error("Migrator dependency must resolve to npm.");
}
}
export function buildBundle(directory, sha, { exec = execFileSync } = {}) {
versionFor(sha);
directory = path.resolve(directory);
const packages = {};
for (const name of names) {
const bytes = readFileSync(path.join(directory, `${name}.tgz`));
assertMetadata(tarManifest(bytes), `@paperclipai/${name}`, sha);
packages[name] = descriptor(bytes, "tgz");
}
const scratch = mkdtempSync(path.join(os.tmpdir(), "cloud-migrator-lock-"));
try {
for (const name of names) copyFileSync(path.join(directory, `${name}.tgz`), path.join(scratch, `${name}.tgz`));
const root = { name: "paperclip-migrator-install-root", version: "0.0.0", private: true,
dependencies: { "@paperclipai/db": "file:db.tgz", "@paperclipai/shared": "file:shared.tgz" } };
writeFileSync(path.join(scratch, "package.json"), JSON.stringify(root));
exec("npm", ["install", "--package-lock-only", "--ignore-scripts", "--no-audit", "--no-fund", "--registry=https://registry.npmjs.org"], { cwd: scratch, stdio: "inherit", timeout: 180_000 });
const lock = JSON.parse(readFileSync(path.join(scratch, "package-lock.json"), "utf8"));
// Both new packages are local during resolution. npm ci subsequently uses
// these immutable URLs, without looking up the new npm versions.
lock.packages[""].dependencies = { "@paperclipai/db": versionFor(sha) };
for (const name of names) lock.packages[`node_modules/@paperclipai/${name}`].resolved = packages[name].url;
const lockBytes = Buffer.from(JSON.stringify(lock) + "\n");
const manifest = { version: 1, sourceSha: sha, packageVersion: versionFor(sha), packages, lockfile: descriptor(lockBytes, "json") };
assertManifest(manifest, sha);
assertLockfile(lock, manifest);
writeFileSync(path.join(directory, "package-lock.json"), lockBytes);
writeFileSync(path.join(directory, "manifest.json"), JSON.stringify(manifest) + "\n");
return manifest;
} finally { rmSync(scratch, { recursive: true, force: true }); }
}
function verifyBytes(bytes, pin) {
if (bytes.length !== pin.size || integrityFor(bytes) !== pin.integrity) throw new Error("Artifact bytes do not match their immutable pin.");
}
export function validateBundle(directory, sha) {
const manifest = JSON.parse(readFileSync(path.join(directory, "manifest.json"), "utf8"));
assertManifest(manifest, sha);
for (const name of names) {
const bytes = readFileSync(path.join(directory, `${name}.tgz`));
verifyBytes(bytes, manifest.packages[name]);
assertMetadata(tarManifest(bytes), `@paperclipai/${name}`, sha);
}
const bytes = readFileSync(path.join(directory, "package-lock.json"));
verifyBytes(bytes, manifest.lockfile);
assertLockfile(JSON.parse(bytes), manifest);
return manifest;
}
/** Exercise the real dependency graph before publishing, with no new npm versions. */
export function verifyInstall(directory, sha, { exec = execFileSync } = {}) {
const manifest = validateBundle(directory, sha);
const scratch = mkdtempSync(path.join(os.tmpdir(), "cloud-migrator-install-"));
try {
const lock = JSON.parse(readFileSync(path.join(directory, "package-lock.json"), "utf8"));
for (const name of names) {
copyFileSync(path.join(directory, `${name}.tgz`), path.join(scratch, `${name}.tgz`));
// The public objects do not exist yet. Only transport changes for this
// smoke install; exact versions, integrity, root and transitive pins stay.
lock.packages[`node_modules/@paperclipai/${name}`].resolved = `file:${name}.tgz`;
}
writeFileSync(path.join(scratch, "package.json"), JSON.stringify({ name: "paperclip-migrator-install-root", version: "0.0.0", private: true,
dependencies: { "@paperclipai/db": manifest.packageVersion } }));
writeFileSync(path.join(scratch, "package-lock.json"), JSON.stringify(lock));
exec("npm", ["ci", "--ignore-scripts", "--no-audit", "--no-fund", "--update-notifier=false", "--cache", path.join(scratch, "empty-cache"),
"--registry=https://registry.npmjs.org"], { cwd: scratch, stdio: "inherit", timeout: 180_000 });
for (const name of names) assertMetadata(JSON.parse(readFileSync(path.join(scratch, "node_modules", "@paperclipai", name, "package.json"), "utf8")), `@paperclipai/${name}`, sha);
exec(process.execPath, ["--input-type=module", "--eval", "await import('@paperclipai/db'); await import('@paperclipai/shared');"], { cwd: scratch, stdio: "inherit", timeout: 30_000 });
} finally { rmSync(scratch, { recursive: true, force: true }); }
}
async function download(url, fetchImpl) {
const response = await fetchImpl(url, { redirect: "error", signal: AbortSignal.timeout(60_000) });
if (!response.ok) throw new Error(`Artifact download failed: HTTP ${response.status}`, { cause: { status: response.status } });
const reader = response.body.getReader();
const chunks = [];
let size = 0;
try {
while (true) {
const { done, value } = await reader.read();
if (done) break;
size += value.length;
if (size > maximumBytes) throw new Error("Artifact exceeds size limit.");
chunks.push(value);
}
} finally { await reader.cancel(); }
return Buffer.concat(chunks);
}
export async function verifyPublished(sha, fetchImpl = fetch, { verifyProvenance } = {}) {
versionFor(sha);
const bytes = await download(`${artifactBase}/${sha}/manifest.json`, fetchImpl);
const manifest = JSON.parse(bytes);
assertManifest(manifest, sha);
if (verifyProvenance) await verifyProvenance(bytes, sha);
await Promise.all(names.map(async (name) => {
const bytes = await download(manifest.packages[name].url, fetchImpl);
verifyBytes(bytes, manifest.packages[name]);
assertMetadata(tarManifest(bytes), `@paperclipai/${name}`, sha);
}));
const lock = await download(manifest.lockfile.url, fetchImpl);
verifyBytes(lock, manifest.lockfile);
assertLockfile(JSON.parse(lock), manifest);
return manifest;
}
export async function publishBundle(directory, sha, { exec = execFileSync, fetchImpl = fetch, sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)) } = {}) {
const manifest = validateBundle(directory, sha);
const key = `${prefix}${sha}/manifest.json`;
const verifyVisible = async () => {
for (let attempt = 0; ; attempt++) {
try { return await verifyPublished(sha, fetchImpl); }
catch (error) {
// A consumer may have cached a missing-object response just before
// publication. Wait through the CDN error TTL, never through bad bytes.
if (attempt >= 6 || ![403, 404].includes(error.cause?.status)) throw error;
await sleep(2_000);
}
}
};
const aws = (args) => exec("aws", ["s3api", ...args, "--bucket", artifactBucket, "--region", "us-east-1"], { encoding: "utf8", maxBuffer: 1024 * 1024 });
// Exact prefix listing distinguishes missing objects from permission errors.
const exists = (objectKey) => JSON.parse(aws(["list-objects-v2", "--prefix", objectKey, "--max-keys", "1"])).Contents?.some((object) => object.Key === objectKey);
if (exists(key)) return verifyVisible();
const upload = (file, objectKey, contentType) => {
if (exists(objectKey)) return;
aws(["put-object", "--key", objectKey, "--body", path.resolve(directory, file), "--content-type", contentType,
"--cache-control", "public,max-age=31536000,immutable", "--if-none-match", "*"]);
};
for (const name of names) upload(`${name}.tgz`, prefix + manifest.packages[name].url.slice(`${artifactBase}/`.length), "application/gzip");
upload("package-lock.json", prefix + manifest.lockfile.url.slice(`${artifactBase}/`.length), "application/json");
// Publish the commit marker last; readers can never observe a partial bundle.
upload("manifest.json", key, "application/json");
return verifyVisible();
}
if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
const [command, directory, sha] = process.argv.slice(2);
try {
if (command === "build") buildBundle(directory, sha);
else if (command === "validate") validateBundle(directory, sha);
else if (command === "verify-install") verifyInstall(directory, sha);
else if (command === "publish") await publishBundle(directory, sha);
else if (command === "verify") await verifyPublished(directory);
else throw new Error("Expected build, validate, verify-install, publish, or verify.");
} catch (error) { console.error(error.message); process.exitCode = 1; }
}
+144
View File
@@ -0,0 +1,144 @@
import test from "node:test";
import assert from "node:assert/strict";
import { execFile } from "node:child_process";
import { promisify } from "node:util";
import { createServer } from "node:http";
import { mkdtempSync, readFileSync, writeFileSync, rmSync } from "node:fs";
import os from "node:os";
import path from "node:path";
import { gzipSync } from "node:zlib";
import { artifactBase, assertManifest, assertLockfile, buildBundle, descriptor, validateBundle, verifyPublished, publishBundle } from "./cloud-migrator-artifacts.mjs";
import { previewManifest, versionFor } from "./preview-artifacts.mjs";
const sha = "a".repeat(40);
function fixture(t) {
const dir = mkdtempSync(path.join(os.tmpdir(), "migrator-artifact-test-"));
t.after(() => rmSync(dir, { recursive: true, force: true }));
for (const name of ["db", "shared"]) {
const bytes = Buffer.from(JSON.stringify(previewManifest({ name: `@paperclipai/${name}`, dependencies: {} }, sha)));
const header = Buffer.alloc(512);
header.write("package/package.json"); header.write(bytes.length.toString(8).padStart(11, "0"), 124, 11); header[156] = 48;
// A real tar header, so npm can install this fixture as well as inspect it.
header.fill(32, 148, 156);
const sum = header.reduce((a, b) => a + b, 0);
header.write(sum.toString(8).padStart(6, "0") + "\0 ", 148, 8);
const padded = Buffer.alloc(Math.ceil(bytes.length / 512) * 512); bytes.copy(padded);
writeFileSync(path.join(dir, `${name}.tgz`), gzipSync(Buffer.concat([header, padded, Buffer.alloc(1024)])));
}
const manifest = buildBundle(dir, sha, { exec: (cmd, args, options) => {
assert.equal(cmd, "npm"); assert.ok(args.includes("--ignore-scripts"));
const localRoot = JSON.parse(readFileSync(path.join(options.cwd, "package.json")));
assert.deepEqual(localRoot.dependencies, { "@paperclipai/db": "file:db.tgz", "@paperclipai/shared": "file:shared.tgz" });
const packages = { "": localRoot };
for (const name of ["db", "shared"]) packages[`node_modules/@paperclipai/${name}`] = {
version: versionFor(sha), integrity: descriptor(readFileSync(path.join(dir, `${name}.tgz`)), "tgz").integrity,
resolved: `file:${name}.tgz`, ...(name === "db" ? { dependencies: { "@paperclipai/shared": versionFor(sha) } } : {}),
};
writeFileSync(path.join(options.cwd, "package-lock.json"), JSON.stringify({ lockfileVersion: 3, packages }));
} });
const files = new Map([[`${artifactBase}/${sha}/manifest.json`, readFileSync(path.join(dir, "manifest.json"))]]);
for (const name of ["db", "shared"]) files.set(manifest.packages[name].url, readFileSync(path.join(dir, `${name}.tgz`)));
files.set(manifest.lockfile.url, readFileSync(path.join(dir, "package-lock.json")));
const fetchImpl = async (url, options) => {
assert.equal(options.redirect, "error"); assert.ok(options.signal);
assert.ok(files.has(url), `unexpected download: ${url}`);
return new Response(files.get(url));
};
return { dir, manifest, files, fetchImpl };
}
test("bundle pins the exact source pair and complete lockfile without new npm lookups", async (t) => {
const { dir, manifest, fetchImpl } = fixture(t);
assert.deepEqual(validateBundle(dir, sha), manifest);
assert.deepEqual(await verifyPublished(sha, fetchImpl), manifest);
});
test("source identity, content hashes, size, and origin fail closed", async (t) => {
const { dir, manifest, files, fetchImpl } = fixture(t);
for (const mutate of [
(m) => { m.sourceSha = "b".repeat(40); },
(m) => { m.packages.db.url = "https://evil.invalid/db.tgz"; },
(m) => { m.packages.shared.size = 0; },
(m) => { m.lockfile.integrity = "sha1-weak"; },
]) {
const bad = structuredClone(manifest); mutate(bad); assert.throws(() => assertManifest(bad, sha));
}
files.set(manifest.packages.db.url, Buffer.from("corrupt"));
await assert.rejects(verifyPublished(sha, fetchImpl), /immutable pin/);
writeFileSync(path.join(dir, "db.tgz"), "corrupt");
await assert.rejects(publishBundle(dir, sha, { exec: () => assert.fail("no upload before pair validation") }));
});
test("lockfile rejects mutable, foreign, linked, and mismatched dependencies", (t) => {
const { dir, manifest } = fixture(t);
const lock = JSON.parse(readFileSync(path.join(dir, "package-lock.json")));
for (const mutate of [
(l) => { l.packages[""].dependencies["@paperclipai/db"] = "latest"; },
(l) => { l.packages["node_modules/@paperclipai/shared"].version = "0.0.0"; },
(l) => { l.packages["node_modules/@paperclipai/db"].link = true; },
(l) => { l.packages["node_modules/evil"] = { inBundle: true }; },
(l) => { l.packages["node_modules/evil"] = { integrity: manifest.packages.db.integrity, resolved: "https://evil.invalid/pkg.tgz" }; },
(l) => { l.packages["node_modules/evil"] = { integrity: "sha1-weak", resolved: "https://registry.npmjs.org/pkg.tgz" }; },
(l) => { l.packages["node_modules/a/node_modules/@paperclipai/shared"] = l.packages["node_modules/@paperclipai/shared"]; },
]) {
const bad = structuredClone(lock); mutate(bad); assert.throws(() => assertLockfile(bad, manifest));
}
});
test("publisher writes blobs first, marker last, and never overwrites existing objects", async (t) => {
const { dir, fetchImpl } = fixture(t);
const objects = new Set(); const uploads = [];
const exec = (cmd, args) => {
assert.equal(cmd, "aws");
const arg = (key) => args[args.indexOf(key) + 1];
if (args[1] === "list-objects-v2") return JSON.stringify({ Contents: objects.has(arg("--prefix")) ? [{ Key: arg("--prefix") }] : [] });
assert.equal(args[1], "put-object"); assert.equal(arg("--if-none-match"), "*");
objects.add(arg("--key")); uploads.push(arg("--key")); return "{}";
};
await publishBundle(dir, sha, { exec, fetchImpl });
assert.equal(uploads.length, 4); assert.equal(uploads.at(-1), `cloud-migrators/v1/${sha}/manifest.json`);
await publishBundle(dir, sha, { exec, fetchImpl }); assert.equal(uploads.length, 4);
});
test("download failures and oversized objects never count as available", async (t) => {
fixture(t);
for (const status of [403, 404, 500]) await assert.rejects(verifyPublished(sha, async () => new Response(null, { status })), /download failed/);
await assert.rejects(verifyPublished(sha, async () => new Response(Buffer.alloc(32 * 1024 * 1024 + 1))), /size limit/);
});
test("real npm ci installs the new pair from pinned archives with an empty cache", async (t) => {
const { dir } = fixture(t);
// Real npm resolution uses local archives; neither package version exists on npm.
const manifest = buildBundle(dir, sha);
const lock = JSON.parse(readFileSync(path.join(dir, "package-lock.json")));
const requests = [];
const server = createServer((req, res) => {
requests.push(req.url);
if (!["/db.tgz", "/shared.tgz"].includes(req.url)) { res.writeHead(500); res.end(); return; }
res.end(readFileSync(path.join(dir, req.url.slice(1))));
});
await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
t.after(() => new Promise((resolve) => server.close(resolve)));
const base = `http://127.0.0.1:${server.address().port}`;
for (const name of ["db", "shared"]) lock.packages[`node_modules/@paperclipai/${name}`].resolved = `${base}/${name}.tgz`;
writeFileSync(path.join(dir, "package.json"), JSON.stringify({ name: "paperclip-migrator-install-root", version: "0.0.0", private: true, dependencies: { "@paperclipai/db": versionFor(sha) } }));
writeFileSync(path.join(dir, "package-lock.json"), JSON.stringify(lock));
await promisify(execFile)("npm", ["ci", "--update-notifier=false", "--ignore-scripts", "--no-audit", "--no-fund", "--registry", base, "--cache", path.join(dir, "empty-cache")], { cwd: dir, timeout: 60_000 });
assert.deepEqual(requests.sort(), ["/db.tgz", "/shared.tgz"]);
for (const name of ["db", "shared"]) assert.equal(JSON.parse(readFileSync(path.join(dir, `node_modules/@paperclipai/${name}/package.json`))).version, manifest.packageVersion);
});
test("AWS trust is master-only and publication policy cannot overwrite objects", () => {
const read = (name) => JSON.parse(readFileSync(new URL(`../.github/cloud-migrator-deploy/${name}.json`, import.meta.url)));
assert.equal(read("trust-policy").Statement[0].Condition.StringEquals["token.actions.githubusercontent.com:sub"], "repo:paperclipai/paperclip:ref:refs/heads/master");
const policy = read("upload-policy").Statement;
assert.deepEqual(policy.map((s) => s.Action), ["s3:PutObject", "s3:ListBucket"]);
assert.equal(policy[0].Condition.StringEquals["s3:if-none-match"], "*");
const workflow = readFileSync(new URL("../.github/workflows/cloud-migrator-artifacts.yml", import.meta.url), "utf8");
assert.ok(!workflow.includes("pull_request") && !workflow.includes("self-hosted") && !workflow.includes("runs-on/fleet="));
assert.equal((workflow.match(/id-token: write/g) ?? []).length, 1);
assert.equal((workflow.match(/attestations: write/g) ?? []).length, 1);
assert.ok(workflow.indexOf(" validate migrator-artifacts") < workflow.indexOf("uses: actions/attest@"));
assert.ok(workflow.indexOf("uses: actions/attest@") < workflow.indexOf(" publish migrator-artifacts"));
assert.ok(workflow.indexOf(" verify-install migrator-artifacts") < workflow.indexOf("actions/upload-artifact@"), "the real dependency smoke must pass before artifact upload");
});
+63 -7
View File
@@ -1,10 +1,64 @@
#!/usr/bin/env node
import { pathToFileURL } from "node:url";
import { imageExists, packageExists, versionFor } from "./preview-artifacts.mjs";
import { execFileSync } from "node:child_process";
import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
import os from "node:os";
import path from "node:path";
import { imageExists, versionFor } from "./preview-artifacts.mjs";
import { verifyPublished } from "./cloud-migrator-artifacts.mjs";
const repository = "paperclipai/paperclip";
const workflow = ".github/workflows/cloud-migrator-artifacts.yml";
export async function migratorPublished(sha, fetchImpl, token) {
let pending = false;
const failures = [];
for (let page = 1; page <= 10; page++) {
const response = await fetchImpl(`https://api.github.com/repos/${repository}/actions/workflows/cloud-migrator-artifacts.yml/runs?branch=master&head_sha=${sha}&per_page=100&page=${page}`, {
headers: { Accept: "application/vnd.github+json", ...(token ? { Authorization: `Bearer ${token}` } : {}) },
redirect: "error", signal: AbortSignal.timeout(30_000),
});
if (!response.ok) throw new Error(`Migrator producer lookup failed: HTTP ${response.status}`);
const body = await response.json();
if (!Array.isArray(body.workflow_runs) || !Number.isSafeInteger(body.total_count) || body.total_count < 0 ||
(page === 1 && (body.total_count === 0) !== (body.workflow_runs.length === 0))) throw new Error("Invalid migrator producer response.");
if (body.total_count === 0) return false;
for (const run of body.workflow_runs) {
if (run.head_sha !== sha || run.head_branch !== "master" || run.path !== workflow ||
run.head_repository?.id !== 1170821064 || run.head_repository.full_name !== repository ||
!["push", "workflow_dispatch"].includes(run.event)) throw new Error("Migrator producer identity mismatch.");
// Publication is immutable. A later failed manual run must not hide a
// successful exact-source publisher; the signed bundle is checked next.
if (run.status === "completed" && run.conclusion === "success") return true;
if (run.status !== "completed") pending = true;
else failures.push(`${run.id}: ${run.conclusion}`);
}
if (page * 100 >= body.total_count) {
if (pending) return false;
throw new Error(`Migrator producers failed: ${failures.join(", ")}.`);
}
}
throw new Error("Too many migrator producer runs to establish publication.");
}
export function verifyManifestProvenance(bytes, sha, { exec = execFileSync } = {}) {
versionFor(sha);
const scratch = mkdtempSync(path.join(os.tmpdir(), "cloud-readiness-attestation-"));
try {
const file = path.join(scratch, "manifest.json");
writeFileSync(file, bytes);
exec("gh", ["attestation", "verify", file, "--repo", repository,
"--source-digest", sha, "--source-ref", "refs/heads/master",
"--cert-identity", `https://github.com/${repository}/${workflow}@refs/heads/master`,
"--deny-self-hosted-runners"], { stdio: "inherit", timeout: 60_000 });
} finally { rmSync(scratch, { recursive: true, force: true }); }
}
/** Read-only availability gate. Deployment still resolves and pins artifacts. */
export async function waitForCloudArtifacts(sha, {
fetchImpl = fetch,
token = process.env.GH_TOKEN,
verifyProvenance = verifyManifestProvenance,
now = () => performance.now(),
sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)),
timeoutMs = 30 * 60_000,
@@ -17,17 +71,19 @@ export async function waitForCloudArtifacts(sha, {
}
const deadline = now() + timeoutMs;
let previous;
let missing = ["image", "shared", "db"];
let missing = ["image", "migrator"];
while (now() < deadline) {
// Recheck every artifact on the successful poll. Only an explicit 404
// means publication is pending; identity errors and upstream outages fail.
// Recheck the image and exact-source publisher on the successful poll.
// Only a missing/pending producer waits; failed publication fails closed.
const results = await Promise.all([
imageExists(sha, fetchImpl),
packageExists("@paperclipai/shared", sha, fetchImpl),
packageExists("@paperclipai/db", sha, fetchImpl),
migratorPublished(sha, fetchImpl, token),
]);
missing = ["image", "shared", "db"].filter((_, index) => !results[index]);
missing = ["image", "migrator"].filter((_, index) => !results[index]);
if (missing.length === 0) {
// Verify the exact signed bytes and all pinned downloads after the
// publisher succeeds. An inaccessible or corrupt artifact cannot pass.
await verifyPublished(sha, fetchImpl, { verifyProvenance });
log(`Cloud artifacts available for ${sha}: verified image and exact-source migrator ${version}.`);
return { version: 1, sha, packageVersion: version };
}
+80 -9
View File
@@ -61,6 +61,80 @@ export async function readSourceVerification(sha, api) {
return undefined;
}
// Statuses that say "ask again", not "the answer is no". A release must not be
// blocked because GitHub returned a gateway error during a 45-minute poll.
const TRANSIENT_READ_STATUSES = new Set([408, 425, 429, 500, 502, 503, 504]);
// A rate-limited read also says "ask again", and GitHub reports both primary
// and secondary rate limits as 403. Only the headers separate that from a
// token that may not read Actions, which must still fail at once.
function rateLimited(response) {
if (response.status !== 403) return false;
const header = (name) => response.headers?.get?.(name) ?? null;
return header("retry-after") !== null || header("x-ratelimit-remaining") === "0";
}
/** Milliseconds from a Retry-After header, when it carries a sane delay. */
function retryAfterMs(response, capMs) {
const value = Number(response?.headers?.get?.("retry-after"));
if (!Number.isFinite(value) || value <= 0) return null;
return Math.min(value * 1_000, capMs);
}
/**
* The GitHub Actions read used by the polling below, with transient transport
* failures retried: network errors, the statuses above, rate-limited 403s, and
* a body that fails while it is being read. Any other non-OK status throws on
* the first response, because waiting out a wrong token only delays the news.
*
* `deadlineAt` bounds retries by the caller's own polling deadline, so a read
* cannot extend the wait past the timeout it belongs to.
*/
export function createActionsReader({
token, fetchImpl = fetch, sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)),
attempts = 4, backoffMs = 1_000, log = console.log,
now = Date.now, deadlineAt = () => Infinity, maxRetryAfterMs = 60_000,
} = {}) {
return async (path) => {
for (let attempt = 1; ; attempt += 1) {
// Retry only while both the attempt budget and the caller's deadline
// leave room for the wait this attempt would cost.
const waitMs = backoffMs * attempt;
const retryable = attempt < attempts && now() + waitMs < deadlineAt();
const pause = (response) => sleep(retryAfterMs(response, maxRetryAfterMs) ?? waitMs);
let response;
try {
response = await fetchImpl(`https://api.github.com${path}`, {
headers: { Authorization: `Bearer ${token}`, Accept: "application/vnd.github+json", "X-GitHub-Api-Version": "2022-11-28" },
signal: AbortSignal.timeout(30_000), redirect: "error",
});
} catch (cause) {
if (!retryable) throw new Error(`GitHub Actions read failed: ${cause.message}`);
log(`GitHub Actions read failed (${cause.message}); retrying (${attempt}/${attempts - 1}).`);
await pause();
continue;
}
if (response.ok) {
try {
// A 200 whose body is truncated or undecodable is a transport
// failure like any other, so it belongs inside the retry.
return await response.json();
} catch (cause) {
if (!retryable) throw new Error(`GitHub Actions read failed: ${cause.message}`);
log(`GitHub Actions read body failed (${cause.message}); retrying (${attempt}/${attempts - 1}).`);
await pause();
continue;
}
}
if (!retryable || !(TRANSIENT_READ_STATUSES.has(response.status) || rateLimited(response))) {
throw new Error(`GitHub Actions read failed (HTTP ${response.status}).`);
}
log(`GitHub Actions read failed (HTTP ${response.status}); retrying (${attempt}/${attempts - 1}).`);
await pause(response);
}
};
}
export async function waitForSourceVerification(sha, {
api, now = Date.now, sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)),
timeoutMs = 45 * 60_000, intervalMs = 30_000, log = console.log,
@@ -80,15 +154,12 @@ export async function waitForSourceVerification(sha, {
if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
try {
if (!process.env.GITHUB_TOKEN) throw new Error("GITHUB_TOKEN with Actions read access is required.");
const api = async (path) => {
const response = await fetch(`https://api.github.com${path}`, {
headers: { Authorization: `Bearer ${process.env.GITHUB_TOKEN}`, Accept: "application/vnd.github+json", "X-GitHub-Api-Version": "2022-11-28" },
signal: AbortSignal.timeout(30_000), redirect: "error",
});
if (!response.ok) throw new Error(`GitHub Actions read failed (HTTP ${response.status}).`);
return response.json();
};
const proof = await waitForSourceVerification(process.argv[2], { api });
// One deadline for both layers: the reader stops retrying when the poll it
// serves is out of time, instead of extending the wait past its timeout.
const timeoutMs = 45 * 60_000;
const deadline = Date.now() + timeoutMs;
const api = createActionsReader({ token: process.env.GITHUB_TOKEN, deadlineAt: () => deadline });
const proof = await waitForSourceVerification(process.argv[2], { api, timeoutMs });
const message = `Source verification passed for ${proof.sha}: https://github.com/${repository}/actions/runs/${proof.runId}/attempts/${proof.attempt} (job ${proof.jobId}).`;
console.log(message);
if (process.env.GITHUB_STEP_SUMMARY) await appendFile(process.env.GITHUB_STEP_SUMMARY, `${message}\n`);
+109 -1
View File
@@ -1,6 +1,6 @@
import assert from "node:assert/strict";
import test from "node:test";
import { readSourceVerification, sourceVerificationJob, waitForSourceVerification } from "./cloud-source-verification.mjs";
import { createActionsReader, readSourceVerification, sourceVerificationJob, waitForSourceVerification } from "./cloud-source-verification.mjs";
const sha = "a".repeat(40);
const workflow = { id: 123, path: ".github/workflows/cloud-readiness.yml" };
@@ -123,3 +123,111 @@ test("malformed source refs are rejected before any request", async () => {
await assert.rejects(readSourceVerification(ref, () => assert.fail("must not request")), /full lowercase/);
}
});
// A gateway error during the poll must not decide the release. These cover the
// reader's transport only; the verification semantics above are unchanged.
function reader({ responses, attempts = 4, ...options }) {
const seen = [];
const waits = [];
const fetchImpl = async () => {
const next = responses[seen.length];
seen.push(next);
if (next instanceof Error) throw next;
return {
ok: next.status >= 200 && next.status < 300,
status: next.status,
headers: { get: (name) => next.headers?.[name.toLowerCase()] ?? null },
json: async () => {
if (next.bodyError) throw next.bodyError;
return next.body ?? { ok: true };
},
};
};
const api = createActionsReader({
token: "t", fetchImpl, attempts, backoffMs: 10,
sleep: async (ms) => { waits.push(ms); }, log: () => {}, ...options,
});
return { api, seen, waits };
}
test("a transient gateway error is retried instead of failing the release", async () => {
const { api, seen, waits } = reader({ responses: [{ status: 502 }, { status: 200, body: { id: 1 } }] });
assert.deepEqual(await api("/repos/x"), { id: 1 });
assert.equal(seen.length, 2);
assert.deepEqual(waits, [10]);
});
test("every transient status is retried, and the backoff grows", async () => {
for (const status of [408, 425, 429, 500, 502, 503, 504]) {
const { api, seen, waits } = reader({ responses: [{ status }, { status }, { status: 200, body: { ok: true } }] });
await api("/repos/x");
assert.equal(seen.length, 3, `status ${status} should be retried`);
assert.deepEqual(waits, [10, 20]);
}
});
test("a rate-limited 403 is retried, and a forbidden 403 is not", async () => {
// GitHub reports both primary and secondary rate limits as 403; only the
// headers tell them apart from a token that may not read Actions.
for (const headers of [{ "retry-after": "1" }, { "x-ratelimit-remaining": "0" }]) {
const { api, seen } = reader({ responses: [{ status: 403, headers }, { status: 200, body: { ok: true } }] });
await api("/repos/x");
assert.equal(seen.length, 2, `403 with ${JSON.stringify(headers)} should be retried`);
}
for (const headers of [undefined, { "x-ratelimit-remaining": "4999" }]) {
const { api, seen } = reader({ responses: [{ status: 403, headers }, { status: 200 }] });
await assert.rejects(api("/repos/x"), /HTTP 403/);
assert.equal(seen.length, 1, "a forbidden 403 must fail on the first response");
}
});
test("Retry-After sets the wait, capped so one header cannot stall the poll", async () => {
const { api, waits } = reader({ responses: [{ status: 429, headers: { "retry-after": "5" } }, { status: 200 }] });
await api("/repos/x");
assert.deepEqual(waits, [5_000]);
const capped = reader({ responses: [{ status: 429, headers: { "retry-after": "86400" } }, { status: 200 }], maxRetryAfterMs: 60_000 });
await capped.api("/repos/x");
assert.deepEqual(capped.waits, [60_000]);
});
test("a body that fails while being read is retried", async () => {
const { api, seen } = reader({
responses: [{ status: 200, bodyError: new Error("terminated") }, { status: 200, body: { id: 7 } }],
});
assert.deepEqual(await api("/repos/x"), { id: 7 });
assert.equal(seen.length, 2);
});
test("a network failure is retried, and its message survives exhaustion", async () => {
const { api, seen } = reader({ responses: Array.from({ length: 4 }, () => new Error("fetch failed")) });
await assert.rejects(api("/repos/x"), /GitHub Actions read failed: fetch failed/);
assert.equal(seen.length, 4);
});
test("an authorization failure is not retried", async () => {
for (const status of [401, 404, 422]) {
const { api, seen } = reader({ responses: [{ status }, { status: 200 }] });
await assert.rejects(api("/repos/x"), new RegExp(`HTTP ${status}`));
assert.equal(seen.length, 1, `status ${status} must fail on the first response`);
}
});
test("a transient status that never clears fails after its attempt budget", async () => {
const { api, seen } = reader({ responses: Array.from({ length: 4 }, () => ({ status: 502 })) });
await assert.rejects(api("/repos/x"), /HTTP 502/);
assert.equal(seen.length, 4);
});
test("retries stop at the caller's deadline rather than outliving the poll", async () => {
// The wait this attempt would cost does not fit before the deadline, so the
// read reports the failure instead of sleeping past the timeout it serves.
let clock = 0;
const { api, seen, waits } = reader({
responses: [{ status: 502 }, { status: 200 }],
now: () => clock, deadlineAt: () => 5,
});
await assert.rejects(api("/repos/x"), /HTTP 502/);
assert.equal(seen.length, 1);
assert.deepEqual(waits, []);
});
+2 -1
View File
@@ -68,7 +68,8 @@ if corepack pnpm install --frozen-lockfile > "$HOME/e2e-bootstrap-install.log" 2
else
tail -40 "$HOME/e2e-bootstrap-install.log"; fail_ "1b bootstrap pnpm install"; exit 1
fi
if bash scripts/build-npm.sh --skip-checks --skip-typecheck > "$HOME/e2e-bootstrap-build.log" 2>&1; then
if PAPERCLIP_README_ASSET_REF="$E2E_REF" \
bash scripts/build-npm.sh --skip-checks --skip-typecheck > "$HOME/e2e-bootstrap-build.log" 2>&1; then
pass "1c bootstrap build-npm.sh"
else
tail -40 "$HOME/e2e-bootstrap-build.log"; fail_ "1c bootstrap build-npm.sh"; exit 1
+1 -1
View File
@@ -97,7 +97,7 @@ else
| tar -xz --strip-components=1 -C "$BOOT" || { fail_ "1a bootstrap tarball"; exit 1; }
( cd "$BOOT" \
&& corepack pnpm install --frozen-lockfile > "$HOME/e2e-upd-bootstrap-install.log" 2>&1 \
&& bash scripts/build-npm.sh --skip-checks --skip-typecheck > "$HOME/e2e-upd-bootstrap-build.log" 2>&1 ) \
&& PAPERCLIP_README_ASSET_REF="$BASE_REF" bash scripts/build-npm.sh --skip-checks --skip-typecheck > "$HOME/e2e-upd-bootstrap-build.log" 2>&1 ) \
|| { tail -40 "$HOME"/e2e-upd-bootstrap-*.log; fail_ "1b bootstrap build"; exit 1; }
TARBALL="$(cd "$BOOT/cli" && npm pack --silent 2>/dev/null | tail -1)"
mkdir -p "$HOME/e2e-upd-bootstrap-cli"
+38
View File
@@ -0,0 +1,38 @@
import { readFileSync, writeFileSync } from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
export function prepareNpmReadme(readme, assetRef) {
if (!assetRef) {
throw new Error("an immutable README asset ref is required");
}
const assetBaseUrl =
`https://raw.githubusercontent.com/paperclipai/paperclip/${assetRef}/doc/assets/`;
return readme.replace(
/((?:src|srcset)=["'])([^"']*)(["'])/g,
(_match, prefix, value, suffix) =>
`${prefix}${value.replace(
/(^|,\s*)doc\/assets\//g,
`$1${assetBaseUrl}`,
)}${suffix}`,
);
}
const isDirectRun =
process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url);
if (isDirectRun) {
const [sourcePath, destinationPath, assetRef] = process.argv.slice(2);
if (!sourcePath || !destinationPath || !assetRef) {
throw new Error(
"usage: prepare-npm-readme.mjs <source> <destination> <asset-ref>",
);
}
writeFileSync(
destinationPath,
prepareNpmReadme(readFileSync(sourcePath, "utf8"), assetRef),
);
}
+48
View File
@@ -0,0 +1,48 @@
import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import test from "node:test";
import { prepareNpmReadme } from "./prepare-npm-readme.mjs";
const assetBase =
"https://raw.githubusercontent.com/paperclipai/paperclip/master/doc/assets/";
const releaseAssetBase =
"https://raw.githubusercontent.com/paperclipai/paperclip/abc123/doc/assets/";
test("rewrites repository-relative image sources for npm", () => {
const readme = [
'<img src="doc/assets/banner.jpg">',
'<source srcset="doc/assets/light.png, doc/assets/dark.png">',
'[docs](doc/assets/not-an-image.md)',
'<img src="https://example.com/already-absolute.png">',
'<img src="https://example.com/doc/assets/already-absolute.png">',
].join("\n");
assert.equal(
prepareNpmReadme(readme, "master"),
[
`<img src="${assetBase}banner.jpg">`,
`<source srcset="${assetBase}light.png, ${assetBase}dark.png">`,
"[docs](doc/assets/not-an-image.md)",
'<img src="https://example.com/already-absolute.png">',
'<img src="https://example.com/doc/assets/already-absolute.png">',
].join("\n"),
);
});
test("prepares the repository README without package-relative image sources", () => {
const readme = readFileSync(new URL("../README.md", import.meta.url), "utf8");
const npmReadme = prepareNpmReadme(readme, "master");
assert.doesNotMatch(
npmReadme,
/(?:src|srcset)=["'](?:doc\/assets\/|[^"']*,\s*doc\/assets\/)/,
);
});
test("supports immutable release refs for generated asset URLs", () => {
assert.equal(
prepareNpmReadme('<img src="doc/assets/banner.jpg">', "abc123"),
`<img src="${releaseAssetBase}banner.jpg">`,
);
});
+20 -7
View File
@@ -165,22 +165,35 @@ export function packPreview(source, output, sha, { exec = execFileSync } = {}) {
}
export async function publishPreview(dir, sha, { fetchImpl = fetch, exec = execFileSync, sleep = (ms) => new Promise((r) => setTimeout(r, ms)) } = {}) {
for (const short of ["shared", "db"]) {
// Validate the entire pair before publishing either immutable package.
const packages = ["shared", "db"].map((short) => {
const name = `@paperclipai/${short}`;
const file = path.resolve(dir, `${short}.tgz`);
const bytes = readFileSync(file);
assertMetadata(tarManifest(bytes), name, sha);
return { name, file, bytes };
});
const pending = new Set();
for (const { name, file, bytes } of packages) {
if (await packageExists(name, sha, fetchImpl)) { console.log(`Reusing ${name}@${versionFor(sha)}`); continue; }
console.log(`Publishing ${name}@${versionFor(sha)} (${createHash("sha256").update(bytes).digest("hex").slice(0, 12)})`);
// No package checkout, lifecycle scripts, npmrc, or branch code runs here.
exec("npm", ["publish", file, "--tag", "preview", "--access", "public", "--ignore-scripts", "--provenance", "--registry", "https://registry.npmjs.org"], { stdio: "inherit" });
let published = false;
for (let attempt = 0; attempt < 60; attempt++) {
if (await packageExists(name, sha, fetchImpl)) { published = true; break; }
await sleep(10_000);
}
if (!published) throw new Error("npm accepted the preview but it is not yet visible. Retry reuses published packages.");
pending.add(name);
}
// npm accepts a package without resolving its dependencies. Submit both
// packages before waiting so their registry propagation can overlap.
for (let attempt = 0; pending.size && attempt < 60; attempt++) {
const checks = await Promise.all([...pending].map(async (name) => ({ name, visible: await packageExists(name, sha, fetchImpl) })));
for (const { name, visible } of checks) {
if (visible) {
pending.delete(name);
console.log(`Visible ${name}@${versionFor(sha)}`);
}
}
if (pending.size) await sleep(10_000);
}
if (pending.size) throw new Error(`npm accepted the preview but it is not yet visible: ${[...pending].join(", ")}. Retry reuses published packages.`);
}
if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
+54 -8
View File
@@ -97,6 +97,59 @@ test("publishing reuses existing previews and never executes package lifecycle h
} finally { rmSync(dir, { recursive: true, force: true }); }
});
test("publishing submits both packages before waiting for either to propagate", async () => {
const dir = mkdtempSync(path.join(tmpdir(), "preview-publish-overlap-"));
const submitted = [];
let polls = 0;
try {
for (const short of ["shared", "db"]) writeFileSync(path.join(dir, `${short}.tgz`), pack(manifest(`@paperclipai/${short}`)));
await publishPreview(dir, sha, {
exec: (_command, args) => submitted.push(path.basename(args[1], ".tgz")),
fetchImpl: async (url) => {
const name = decodeURIComponent(new URL(url).pathname.split("/")[1]);
// Both packages become visible after the first shared visibility wait.
return submitted.length === 2 && polls > 0
? json({ ...manifest(name), dist: { integrity: "test-integrity", tarball: "https://registry.npmjs.org/package.tgz" } })
: json({}, 404);
},
sleep: async () => { assert.deepEqual(submitted, ["shared", "db"]); polls++; },
});
assert.deepEqual(submitted, ["shared", "db"]);
assert.equal(polls, 1);
} finally { rmSync(dir, { recursive: true, force: true }); }
});
test("a visibility timeout identifies the missing package after both were submitted", async () => {
const dir = mkdtempSync(path.join(tmpdir(), "preview-publish-timeout-"));
const submitted = [];
try {
for (const short of ["shared", "db"]) writeFileSync(path.join(dir, `${short}.tgz`), pack(manifest(`@paperclipai/${short}`)));
await assert.rejects(publishPreview(dir, sha, {
exec: (_command, args) => submitted.push(path.basename(args[1], ".tgz")),
fetchImpl: async (url) => {
const name = decodeURIComponent(new URL(url).pathname.split("/")[1]);
return name === "@paperclipai/db" && submitted.includes("db")
? json({ ...manifest(name), dist: { integrity: "test-integrity", tarball: "https://registry.npmjs.org/package.tgz" } })
: json({}, 404);
},
sleep: async () => {},
}), /not yet visible: @paperclipai\/shared\./);
assert.deepEqual(submitted, ["shared", "db"]);
} finally { rmSync(dir, { recursive: true, force: true }); }
});
test("invalid DB package metadata prevents publication of either package", async () => {
const dir = mkdtempSync(path.join(tmpdir(), "preview-publish-invalid-"));
try {
writeFileSync(path.join(dir, "shared.tgz"), pack(manifest("@paperclipai/shared")));
writeFileSync(path.join(dir, "db.tgz"), pack({ ...manifest("@paperclipai/db"), gitHead: "b".repeat(40) }));
await assert.rejects(publishPreview(dir, sha, {
exec: () => assert.fail("Invalid package pairs must not be published"),
fetchImpl: async () => assert.fail("Validate the pair before registry requests"),
}), /identity or dependency pin mismatch/);
} finally { rmSync(dir, { recursive: true, force: true }); }
});
test("preview workflow separates branch compilation from trusted publishing", () => {
const workflow = readFileSync(new URL("../.github/workflows/release.yml", import.meta.url), "utf8");
const builder = workflow.split(" package_preview:")[1].split(" publish_preview:")[0];
@@ -117,15 +170,8 @@ test("preview workflow separates branch compilation from trusted publishing", ()
assert.match(workflow, /Stack deploy \{0\} build/);
});
test("merge dispatch uses the existing publisher outside full-release concurrency without claiming image readiness", () => {
const dispatcher = readFileSync(new URL("../.github/workflows/cloud-artifacts.yml", import.meta.url), "utf8");
test("manual migrator and branch preview retain their npm publisher and concurrency", () => {
const release = readFileSync(new URL("../.github/workflows/release.yml", import.meta.url), "utf8");
assert.match(dispatcher, /branches: \[master\]/);
assert.match(dispatcher, /github.ref == 'refs\/heads\/master'/);
assert.match(dispatcher, /SOURCE_SHA: \$\{\{ github.sha \}\}/);
assert.match(dispatcher, /gh workflow run release.yml .*--ref master/);
assert.match(dispatcher, /--field channel=cloud-migrator/);
assert.doesNotMatch(dispatcher, /actions\/checkout|id-token: write|packages: write|secrets\./);
assert.match(release, /\(inputs.channel == 'preview' \|\| inputs.channel == 'cloud-migrator'\) && format\('\{0\}-\{1\}', inputs.channel, inputs.source_ref\)/);
const publisher = release.split(" publish_preview:")[1].split(" image_preview:")[0];
assert.match(publisher, /group: preview-package-publish-\$\{\{ inputs.source_ref \}\}/);
+133
View File
@@ -0,0 +1,133 @@
#!/usr/bin/env -S node --import tsx
import { execFileSync } from "node:child_process";
import { createHash } from "node:crypto";
import { lstat, readFile } from "node:fs/promises";
import path from "node:path";
import { fileURLToPath } from "node:url";
import { ANNOUNCEMENT_ANIMATION_MAX_BYTES, ANNOUNCEMENT_IMAGE_MAX_BYTES, ANNOUNCEMENT_MANIFEST_MAX_BYTES, announcementIdSchema, announcementManifestSchema } from "../packages/shared/src/announcements.js";
import { validateAnnouncementAnimation } from "../server/src/services/announcement-animation.js";
export function announcementPublishPrefix(staging?: string, hostPrefix?: string) {
if (hostPrefix !== undefined && !/^[a-z0-9-]+(?:\/[a-z0-9-]+)*$/.test(hostPrefix)) {
throw new Error("Invalid PAPERCLIP_PAGE_DEFAULT_PREFIX: use lowercase path segments without leading or trailing slashes");
}
const prefix = staging === undefined ? "announcements/v1" : `announcements/staging/${announcementIdSchema.parse(staging)}/v1`;
return hostPrefix ? `${hostPrefix}/${prefix}` : prefix;
}
export function parseAnnouncementPublishArgs(args: string[]) {
let sourceDirectory: string | undefined;
let staging: string | undefined;
let mode: "publish" | "dry-run" | undefined;
const usage = "Usage: publish-announcements.ts [directory] [--staging name] [--dry-run | --publish]";
for (let index = 0; index < args.length; index++) {
const arg = args[index];
if (arg === "--publish" || arg === "--dry-run") {
if (mode) throw new Error(usage);
mode = arg === "--publish" ? "publish" : "dry-run";
} else if (arg === "--staging") {
if (staging !== undefined || !args[index + 1]) throw new Error(usage);
staging = announcementIdSchema.parse(args[++index]);
} else if (arg.startsWith("--") || sourceDirectory !== undefined) {
throw new Error(usage);
} else {
sourceDirectory = arg;
}
}
return { sourceDirectory: sourceDirectory ?? (staging ? "announcements/examples/staging" : "announcements"), staging, publish: mode === "publish" };
}
export async function prepareAnnouncementPublish(sourceDirectory: string, staging?: string, hostPrefix?: string) {
const prefix = announcementPublishPrefix(staging, hostPrefix);
const source = path.resolve(sourceDirectory);
if (!(await lstat(source)).isDirectory()) throw new Error("Source must be a real directory");
const manifestPath = path.join(source, "current.json");
const stat = await lstat(manifestPath);
if (!stat.isFile() || stat.size > ANNOUNCEMENT_MANIFEST_MAX_BYTES) throw new Error("Invalid or oversized current.json");
const manifest = announcementManifestSchema.parse(JSON.parse(await readFile(manifestPath, "utf8")));
const files: Array<{ file: string; key: string; contentType: string; cacheControl: string }> = [];
for (const kind of ["image", "animation"] as const) {
const asset = manifest.announcement?.[kind];
if (!asset) continue;
if (!(await lstat(path.join(source, "assets"))).isDirectory()) throw new Error("Assets must be a real directory");
const assetPath = asset.path;
const file = path.join(source, assetPath);
const assetStat = await lstat(file);
const maximum = kind === "animation" ? ANNOUNCEMENT_ANIMATION_MAX_BYTES : ANNOUNCEMENT_IMAGE_MAX_BYTES;
if (!assetStat.isFile() || assetStat.size > maximum) throw new Error(`Invalid or oversized ${kind}`);
const bytes = await readFile(file);
const digest = createHash("sha256").update(bytes).digest("hex");
if (!assetPath.startsWith(`assets/${digest}.`)) throw new Error("Asset filename must match its SHA-256 digest");
if (kind === "animation") validateAnnouncementAnimation(bytes);
files.push({ file, key: `${prefix}/${assetPath}`, contentType: kind === "animation" ? "text/html" : assetPath.endsWith(".png") ? "image/png" : assetPath.endsWith(".jpg") ? "image/jpeg" : "image/webp", cacheControl: "public,max-age=31536000,immutable" });
}
files.push({ file: manifestPath, key: `${prefix}/current.json`, contentType: "application/json", cacheControl: "public,max-age=300" });
return { manifest, files };
}
export function announcementUploadArgs(bucket: string, file: Awaited<ReturnType<typeof prepareAnnouncementPublish>>["files"][number]) {
return ["s3api", "put-object", "--bucket", bucket, "--key", file.key, "--body", file.file,
"--content-type", file.contentType, "--cache-control", file.cacheControl];
}
async function main() {
const { sourceDirectory, staging, publish } = parseAnnouncementPublishArgs(process.argv.slice(2));
const hostPrefix = process.env.PAPERCLIP_PAGE_DEFAULT_PREFIX;
const prepared = await prepareAnnouncementPublish(sourceDirectory, staging, hostPrefix);
const bucket = process.env.PAPERCLIP_PAGE_BUCKET;
const baseUrl = process.env.PAPERCLIP_PAGE_BASE_URL?.replace(/\/+$/, "") ?? "https://pages.paperclip.ing";
const url = `${baseUrl}/${announcementPublishPrefix(staging, hostPrefix)}/current.json`;
const parsed = new URL(url);
if (parsed.protocol !== "https:" || parsed.username || parsed.password || parsed.search || parsed.hash) throw new Error("Invalid public base URL");
console.log(JSON.stringify({ mode: publish ? "publish" : "dry-run", target: staging ? `staging/${staging}` : "production", bucket: bucket ?? "(unset)", url, announcementId: prepared.manifest.announcement?.id ?? null, files: prepared.files }, null, 2));
if (!publish) return;
if (!bucket) throw new Error("Set PAPERCLIP_PAGE_BUCKET before publishing");
const env = { ...process.env };
const key = env.PAPERCLIP_PAGE_AWS_ACCESS_KEY_ID;
const secret = env.PAPERCLIP_PAGE_AWS_SECRET_ACCESS_KEY;
if (Boolean(key) !== Boolean(secret)) throw new Error("Set both namespaced page uploader credential variables");
if (key && secret) {
env.AWS_ACCESS_KEY_ID = key;
env.AWS_SECRET_ACCESS_KEY = secret;
delete env.AWS_SESSION_TOKEN;
if (env.PAPERCLIP_PAGE_AWS_SESSION_TOKEN) env.AWS_SESSION_TOKEN = env.PAPERCLIP_PAGE_AWS_SESSION_TOKEN;
} else if (env.PAPERCLIP_PAGE_AWS_PROFILE) {
delete env.AWS_ACCESS_KEY_ID;
delete env.AWS_SECRET_ACCESS_KEY;
delete env.AWS_SESSION_TOKEN;
env.AWS_PROFILE = env.PAPERCLIP_PAGE_AWS_PROFILE;
}
// Only validated files, assets before manifest; credentials are scoped to AWS.
for (const file of prepared.files) execFileSync("aws", announcementUploadArgs(bucket, file), { env, stdio: "pipe" });
console.log("Uploaded. Checking the public manifest (CDN propagation can take five minutes)…");
for (let attempt = 0; attempt < 23; attempt++) {
try {
const response = await fetch(url, { signal: AbortSignal.timeout(10_000), credentials: "omit", redirect: "error" });
const body = announcementManifestSchema.parse(await response.json());
if (response.ok && JSON.stringify(body) === JSON.stringify(prepared.manifest)
&& /(?:^|,)\s*max-age=300(?:\s*,|$)/i.test(response.headers.get("cache-control") ?? "")) {
for (const asset of prepared.files.slice(0, -1)) {
const image = await fetch(`${baseUrl}/${asset.key}`, { method: "HEAD", signal: AbortSignal.timeout(10_000), credentials: "omit", redirect: "error" });
const caching = image.headers.get("cache-control") ?? "";
if (!image.ok || image.headers.get("content-type") !== asset.contentType
|| !/(?:^|,)\s*max-age=31536000(?:\s*,|$)/i.test(caching)
|| !/(?:^|,)\s*immutable(?:\s*,|$)/i.test(caching)) {
throw new Error("Public announcement asset headers are not ready");
}
}
console.log(`Published and verified: ${url}`);
return;
}
} catch { /* Retry edge propagation; uploads have already completed. */ }
if (attempt < 22) await new Promise((resolve) => setTimeout(resolve, 15_000));
}
throw new Error(`Uploaded, but public verification did not finish. Check ${url} and the CloudFront cache policy (minimum TTL must not exceed 300 seconds).`);
}
if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
main().catch((error) => {
console.error(error instanceof Error ? error.message : "Announcement publish failed");
process.exitCode = 1;
});
}
+71 -13
View File
@@ -410,22 +410,80 @@ publish_package_to_npm() {
return 1
}
publish_package_to_npm_and_wait() {
local dist_tag="$1"
local package_name="$2"
local package_version="$3"
local publish_tool="${4:-pnpm}"
local attempts="${5:-12}"
local delay_seconds="${6:-5}"
# Wait for every already-published package to become registry-visible,
# polling all of them concurrently. npm accepts a publish in seconds, but
# packument propagation through the registry CDN can lag minutes per package;
# waiting on each package before publishing the next made the total wait the
# SUM of every package's lag (~2 hours on a bad day for the full set). Every
# publish has already been accepted by the time this runs, so the polls can
# race: the wall-clock cost becomes the single slowest package's lag. Each
# package keeps its own attempts x delay budget, and a package that never
# becomes visible still fails the release, naming every straggler.
#
# $3 is the list_public_package_info tuple list (pkg_dir<TAB>name<TAB>version
# lines); the directory field is ignored.
wait_for_npm_package_versions() {
local attempts="${1:-12}"
local delay_seconds="${2:-5}"
local package_info="$3"
publish_package_to_npm "$dist_tag" "$package_name" "$package_version" "$publish_tool" || return 1
# The polling phase runs in a subshell that owns its own EXIT trap: a
# cancelled or signalled release reaps every in-flight poller and the
# scratch directory instead of leaking one npm poll per package for the
# rest of its budget. The subshell also keeps this trap from clobbering
# the caller's cleanup trap.
(
local status_dir
local pids=()
local specs=()
local failures=()
local index=0
local pkg_name
local pkg_version
local i
if wait_for_npm_package_version "$package_name" "$package_version" "$attempts" "$delay_seconds"; then
return 0
fi
status_dir="$(mktemp -d "${TMPDIR:-/tmp}/paperclip-release-visibility.XXXXXX")"
release_warn "npm accepted ${package_name}@${package_version}, but the version did not become registry-visible."
return 1
# shellcheck disable=SC2329 # invoked via the trap below
reap_visibility_pollers() {
local pid
for pid in ${pids[@]+"${pids[@]}"}; do
kill "$pid" 2>/dev/null || true
done
rm -rf "$status_dir"
}
trap reap_visibility_pollers EXIT INT TERM
while IFS=$'\t' read -r _pkg_dir pkg_name pkg_version; do
[ -z "$pkg_name" ] && continue
(
if wait_for_npm_package_version "$pkg_name" "$pkg_version" "$attempts" "$delay_seconds"; then
: > "$status_dir/$index.ok"
fi
) &
pids+=("$!")
specs+=("${pkg_name}@${pkg_version}")
index=$((index + 1))
done <<< "$package_info"
if [ "${#pids[@]}" -gt 0 ]; then
for i in "${!pids[@]}"; do
wait "${pids[$i]}" || true
if [ -e "$status_dir/$i.ok" ]; then
release_info " ✓ ${specs[$i]} is registry-visible"
else
failures+=("${specs[$i]}")
fi
done
fi
if [ "${#failures[@]}" -gt 0 ]; then
release_warn "npm accepted every publish, but these versions did not become registry-visible: ${failures[*]}"
exit 1
fi
exit 0
)
}
verify_npm_installable() {
+150 -8
View File
@@ -6,6 +6,14 @@ import { join } from "node:path";
import test from "node:test";
const repoRoot = new URL("..", import.meta.url).pathname.replace(/\/$/, "");
const releaseWorkflow = readFileSync(new URL("../.github/workflows/release.yml", import.meta.url), "utf8");
function workflowVerifyBudget() {
return {
verifyAttempts: Number(releaseWorkflow.match(/^ NPM_PUBLISH_VERIFY_ATTEMPTS: "(\d+)"$/m)?.[1]),
verifyDelaySeconds: Number(releaseWorkflow.match(/^ NPM_PUBLISH_VERIFY_DELAY_SECONDS: "(\d+)"$/m)?.[1]),
};
}
function writeExecutable(path, body) {
writeFileSync(path, body, { mode: 0o755 });
@@ -18,6 +26,10 @@ function runPublishHelper({
callerPipefail = true,
publishTool = "pnpm",
waitForRegistry = false,
npmVersionExistsAfterChecks = 0,
verifyAttempts = 1,
verifyDelaySeconds = 0,
visibilityPackages = null,
}) {
const fixtureDir = mkdtempSync(join(tmpdir(), "paperclip-release-lib-"));
const binDir = join(fixtureDir, "bin");
@@ -74,9 +86,38 @@ exit 1
`#!/usr/bin/env bash
set -euo pipefail
printf 'npm %s\\n' "$*" >> "$FAKE_CALL_LOG"
if [ "$1" = "view" ] && [ "$NPM_VERSION_EXISTS" = "true" ]; then
echo "1.2.3"
exit 0
if [ "$1" = "view" ]; then
if [ "\${NPM_VIEW_CROSS:-}" = "true" ]; then
# Cross-visibility mode: a package resolves only after every OTHER
# package has been polled at least once. Mutually dependent visibility
# can only converge when the polls run concurrently.
spec="$2"
name="\${spec%@*}"
safe="$(printf '%s' "$name" | tr '/@' '__')"
touch "$FAKE_STATE_DIR/seen-$safe"
all_seen=true
for other in $CROSS_PACKAGES; do
osafe="$(printf '%s' "$other" | tr '/@' '__')"
[ "$osafe" = "$safe" ] && continue
[ -f "$FAKE_STATE_DIR/seen-$osafe" ] || all_seen=false
done
if [ "$all_seen" = "true" ]; then
echo "1.2.3"
exit 0
fi
exit 1
fi
checks=0
if [ -f "$FAKE_STATE_DIR/view-checks" ]; then
read -r checks < "$FAKE_STATE_DIR/view-checks"
fi
checks=$((checks + 1))
echo "$checks" > "$FAKE_STATE_DIR/view-checks"
if [ "$NPM_VERSION_EXISTS" = "true" ] ||
{ [ "$NPM_VERSION_EXISTS_AFTER_CHECKS" -gt 0 ] && [ "$checks" -ge "$NPM_VERSION_EXISTS_AFTER_CHECKS" ]; }; then
echo "1.2.3"
exit 0
fi
fi
if [ "$1" = "publish" ]; then
case "$PNPM_MODE" in
@@ -127,13 +168,30 @@ exec npm "$@"
);
const shellOptions = callerPipefail ? "set -euo pipefail" : "set -eu";
// The cross-visibility concurrency test needs real (fractional-second)
// sleeps so slower-starting sibling polls get a chance to run; every other
// test records virtual waiting so registry-delay tests stay fast/offline.
const sleepStub = visibilityPackages
? ""
: `sleep() { printf 'sleep %s\\n' "$*" >> "$FAKE_CALL_LOG"; }`;
const packageInfo = (
visibilityPackages ?? ["@paperclipai/example"]
)
.map((name) => `packages/example\\t${name}\\t1.2.3`)
.join("\\n");
const script = `
${shellOptions}
source "${repoRoot}/scripts/release-lib.sh"
${sleepStub}
${
waitForRegistry
? `publish_package_to_npm_and_wait ${distTag} @paperclipai/example 1.2.3 ${publishTool} 1 0`
: `publish_package_to_npm ${distTag} @paperclipai/example 1.2.3 ${publishTool}`
visibilityPackages
? `PACKAGE_INFO="$(printf '${packageInfo}')"
wait_for_npm_package_versions "$VERIFY_ATTEMPTS" "$VERIFY_DELAY_SECONDS" "$PACKAGE_INFO"`
: waitForRegistry
? `publish_package_to_npm ${distTag} @paperclipai/example 1.2.3 ${publishTool}
PACKAGE_INFO="$(printf '${packageInfo}')"
wait_for_npm_package_versions "$VERIFY_ATTEMPTS" "$VERIFY_DELAY_SECONDS" "$PACKAGE_INFO"`
: `publish_package_to_npm ${distTag} @paperclipai/example 1.2.3 ${publishTool}`
}
`;
@@ -149,6 +207,11 @@ ${
FAKE_CALL_LOG: callLog,
FAKE_STATE_DIR: stateDir,
NPM_VERSION_EXISTS: npmVersionExists ? "true" : "false",
NPM_VERSION_EXISTS_AFTER_CHECKS: String(npmVersionExistsAfterChecks),
VERIFY_ATTEMPTS: String(verifyAttempts),
VERIFY_DELAY_SECONDS: String(verifyDelaySeconds),
NPM_VIEW_CROSS: visibilityPackages ? "true" : "false",
CROSS_PACKAGES: (visibilityPackages ?? []).join(" "),
PNPM_MODE: pnpmMode,
REPO_ROOT: fixtureDir,
},
@@ -245,7 +308,7 @@ test("publish_package_to_npm does not retry stable publishes without provenance"
assert.doesNotMatch(result.calls, /--provenance=false/);
});
test("publish_package_to_npm_and_wait confirms registry visibility before returning", () => {
test("wait_for_npm_package_versions confirms registry visibility after a publish", () => {
const result = runPublishHelper({
pnpmMode: "success",
npmVersionExists: true,
@@ -257,10 +320,89 @@ test("publish_package_to_npm_and_wait confirms registry visibility before return
assert.match(result.calls, /^npm view @paperclipai\/example@1\.2\.3 version$/m);
});
test("publish_package_to_npm_and_wait blocks the release when registry visibility lags", () => {
test("wait_for_npm_package_versions blocks the release and names the straggler", () => {
const result = runPublishHelper({ pnpmMode: "success", waitForRegistry: true });
assert.notEqual(result.status, 0);
assert.match(result.calls, /^npm view @paperclipai\/example@1\.2\.3 version$/m);
assert.match(result.output, /did not become registry-visible: @paperclipai\/example@1\.2\.3/);
});
test("wait_for_npm_package_versions polls every package concurrently", () => {
// In cross-visibility mode each fake package resolves only after the OTHER
// package has been polled at least once. Waiting out one package's full
// budget before polling the next can never satisfy the first package;
// only concurrent polling converges.
const result = runPublishHelper({
pnpmMode: "success",
visibilityPackages: ["@paperclipai/alpha", "@paperclipai/beta"],
verifyAttempts: 50,
verifyDelaySeconds: 0.2,
});
assert.equal(result.status, 0, result.output);
assert.match(result.output, /@paperclipai\/alpha@1\.2\.3 is registry-visible/);
assert.match(result.output, /@paperclipai\/beta@1\.2\.3 is registry-visible/);
});
test("the workflow budget tolerates the observed 15-minute 20-second registry delay", () => {
const budget = workflowVerifyBudget();
assert.ok(budget.verifyDelaySeconds > 0);
const delayedCheck = Math.ceil((15 * 60 + 20) / budget.verifyDelaySeconds) + 1;
const result = runPublishHelper({
pnpmMode: "success",
waitForRegistry: true,
npmVersionExistsAfterChecks: delayedCheck,
...budget,
});
assert.equal(result.status, 0, result.output);
assert.equal(result.calls.match(/^pnpm publish /gm)?.length, 1);
assert.equal(result.calls.match(/^npm view /gm)?.length, delayedCheck);
assert.deepEqual(
result.calls.split("\n").filter((call) => call.startsWith("sleep ")),
Array(delayedCheck - 1).fill(`sleep ${budget.verifyDelaySeconds}`),
);
});
test("the workflow budget does not delay an immediately visible publish", () => {
const result = runPublishHelper({
pnpmMode: "success",
npmVersionExists: true,
waitForRegistry: true,
...workflowVerifyBudget(),
});
assert.equal(result.status, 0, result.output);
assert.equal(result.calls.match(/^npm view /gm)?.length, 1);
assert.doesNotMatch(result.calls, /^sleep /m);
});
test("the workflow budget fails closed after the last registry check", () => {
const budget = workflowVerifyBudget();
assert.ok(budget.verifyAttempts > 0);
const result = runPublishHelper({
pnpmMode: "success",
waitForRegistry: true,
npmVersionExistsAfterChecks: budget.verifyAttempts + 1,
...budget,
});
assert.notEqual(result.status, 0);
assert.match(result.output, /did not become registry-visible/);
assert.equal(result.calls.match(/^pnpm publish /gm)?.length, 1);
assert.equal(result.calls.match(/^npm view /gm)?.length, budget.verifyAttempts);
assert.equal(result.calls.match(/^sleep /gm)?.length, budget.verifyAttempts - 1);
});
test("every publish job budgets for build time and four delayed packages", () => {
const { verifyAttempts, verifyDelaySeconds } = workflowVerifyBudget();
const pollingSeconds = (verifyAttempts - 1) * verifyDelaySeconds;
const requiredSeconds = 30 * 60 + 4 * pollingSeconds;
for (const job of ["publish_canary", "publish_nightly", "publish_beta", "publish_stable"]) {
const body = releaseWorkflow.split(`\n ${job}:\n`)[1]?.split(/\n [a-z_]+:\n/)[0] ?? "";
const timeoutMinutes = Number(body.match(/^ timeout-minutes: (\d+)$/m)?.[1]);
assert.ok(timeoutMinutes * 60 > requiredSeconds, `${job} must leave time beyond build and polling`);
}
});
+5
View File
@@ -129,6 +129,11 @@
"name": "@paperclipai/plugin-cloudflare-sandbox",
"publishFromCi": true
},
{
"dir": "packages/plugins/sandbox-providers/createos",
"name": "@paperclipai/plugin-createos",
"publishFromCi": false
},
{
"dir": "packages/plugins/sandbox-providers/daytona",
"name": "@paperclipai/plugin-daytona",
+13 -7
View File
@@ -342,23 +342,29 @@ else
node "$REPO_ROOT/scripts/prepare-bundled-package.mjs" "$REPO_ROOT/$pkg_dir" "$publish_dir"
cd "$publish_dir"
fi
if ! publish_package_to_npm_and_wait \
if ! publish_package_to_npm \
"$DIST_TAG" \
"$pkg_name" \
"$pkg_version" \
"$publish_tool" \
"$VERIFY_ATTEMPTS" \
"$VERIFY_DELAY_SECONDS"; then
"$publish_tool"; then
if [ "$publish_tool" = "npm" ]; then
rm -rf "$publish_dir"
fi
release_fail "stopping release: npm did not publish and expose ${pkg_name}@${pkg_version}"
release_fail "stopping release: npm did not accept the publish of ${pkg_name}@${pkg_version}"
fi
if [ "$publish_tool" = "npm" ]; then
rm -rf "$publish_dir"
fi
release_info " ✓ Published version is registry-visible"
release_info " ✓ npm accepted the publish"
done <<< "$VERSIONED_PACKAGE_INFO"
release_info " ✓ npm accepted every package publish under dist-tag $DIST_TAG"
release_info " Waiting for registry visibility of all packages concurrently..."
if ! wait_for_npm_package_versions \
"$VERIFY_ATTEMPTS" \
"$VERIFY_DELAY_SECONDS" \
"$VERSIONED_PACKAGE_INFO"; then
release_fail "stopping release: npm did not expose every published version under dist-tag $DIST_TAG"
fi
release_info " ✓ Published the full package set under dist-tag $DIST_TAG"
fi
@@ -369,7 +375,7 @@ else
release_info "==> Step 6/7: Confirming npm package availability and dist-tag integrity..."
REGISTRY_STATE_VERIFY_ATTEMPTS="${NPM_REGISTRY_STATE_VERIFY_ATTEMPTS:-12}"
REGISTRY_STATE_VERIFY_DELAY_SECONDS="${NPM_REGISTRY_STATE_VERIFY_DELAY_SECONDS:-5}"
release_info " ✓ Every version was registry-visible before the next package publish"
release_info " ✓ Every version was registry-visible before tagging began"
verify_args=(
--channel "$channel"