Skip to content

Commit 83cb357

Browse files
committed
fix(release): publish validated artifact bytes
1 parent 40925fc commit 83cb357

4 files changed

Lines changed: 242 additions & 37 deletions

File tree

‎.github/workflows/release.yml‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -233,7 +233,7 @@ jobs:
233233
if: github.ref_protected
234234
needs: collect
235235
runs-on: ubuntu-latest
236-
timeout-minutes: 15
236+
timeout-minutes: 20
237237
permissions:
238238
contents: read
239239
id-token: write
@@ -256,7 +256,7 @@ jobs:
256256
name: release-package
257257
path: release-artifacts
258258

259-
- name: Publish or verify
259+
- name: Publish validated artifact or verify
260260
run: node scripts/publish-or-verify.mjs --package "@openclaw/fs-safe" --artifacts release-artifacts
261261

262262
release:

‎CHANGELOG.md‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,11 @@
11
# Changelog
22

3+
## Unreleased
4+
5+
### Docs and Tooling
6+
7+
- Publish only the validated release tarball after asserting its byte identity against the release manifest, and tolerate npm registry propagation with bounded exponential backoff.
8+
39
## 0.5.0 - 2026-07-27
410

511
### Highlights

‎scripts/publish-or-verify.mjs‎

Lines changed: 121 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -1,59 +1,145 @@
11
import { execFileSync, spawnSync } from "node:child_process";
2+
import { createHash } from "node:crypto";
23
import { readFileSync } from "node:fs";
3-
import { join, resolve } from "node:path";
4+
import { basename, dirname, join, resolve } from "node:path";
5+
import { pathToFileURL } from "node:url";
46

5-
const packageIndex = process.argv.indexOf("--package");
6-
const artifactsIndex = process.argv.indexOf("--artifacts");
7-
const packageName = packageIndex >= 0 ? process.argv[packageIndex + 1] : undefined;
8-
const artifactsDir = resolve(artifactsIndex >= 0 ? process.argv[artifactsIndex + 1] : "release-artifacts");
9-
if (!packageName) throw new Error("--package is required");
7+
export const REGISTRY_RETRY_DELAYS_MS = [
8+
5_000,
9+
10_000,
10+
20_000,
11+
30_000,
12+
45_000,
13+
60_000,
14+
60_000,
15+
60_000,
16+
60_000,
17+
60_000,
18+
60_000,
19+
60_000,
20+
];
1021

11-
const manifest = JSON.parse(readFileSync(join(artifactsDir, "manifest.json"), "utf8"));
12-
const artifact = manifest.find((entry) => entry.name === packageName);
13-
if (!artifact) throw new Error(`release manifest has no entry for ${packageName}`);
14-
const spec = `${artifact.name}@${artifact.version}`;
22+
function sha512Integrity(bytes) {
23+
return `sha512-${createHash("sha512").update(bytes).digest("base64")}`;
24+
}
25+
26+
export function loadReleaseArtifact(packageName, artifactsDirectory) {
27+
const artifactsDir = resolve(artifactsDirectory);
28+
const manifest = JSON.parse(readFileSync(join(artifactsDir, "manifest.json"), "utf8"));
29+
if (!Array.isArray(manifest)) throw new Error("release manifest must be an array");
30+
31+
const artifact = manifest.find((entry) => entry?.name === packageName);
32+
if (!artifact) throw new Error(`release manifest has no entry for ${packageName}`);
33+
if (
34+
typeof artifact.version !== "string" ||
35+
typeof artifact.filename !== "string" ||
36+
basename(artifact.filename) !== artifact.filename
37+
) {
38+
throw new Error(`release manifest has invalid artifact metadata for ${packageName}`);
39+
}
40+
41+
const artifactPath = resolve(artifactsDir, artifact.filename);
42+
if (dirname(artifactPath) !== artifactsDir) {
43+
throw new Error(`release artifact escapes artifacts directory: ${artifact.filename}`);
44+
}
1545

16-
function registryState() {
46+
const bytes = readFileSync(artifactPath);
47+
const integrity = sha512Integrity(bytes);
48+
if (integrity !== artifact.integrity) {
49+
throw new Error(`${packageName}@${artifact.version} artifact bytes do not match release manifest`);
50+
}
51+
if (Number.isSafeInteger(artifact.size) && bytes.length !== artifact.size) {
52+
throw new Error(`${packageName}@${artifact.version} artifact size does not match release manifest`);
53+
}
54+
55+
return { ...artifact, path: artifactPath, integrity };
56+
}
57+
58+
function registryState(artifact, execNpm) {
59+
const spec = `${artifact.name}@${artifact.version}`;
1760
try {
18-
const raw = execFileSync("npm", ["view", spec, "dist", "--json"], {
61+
const raw = execNpm("npm", ["view", spec, "dist", "--json", "--prefer-online"], {
1962
encoding: "utf8",
2063
stdio: ["ignore", "pipe", "pipe"],
2164
});
2265
const dist = JSON.parse(raw);
2366
if (dist.integrity !== artifact.integrity) {
24-
throw new Error(`${spec} exists with different package bytes`);
67+
return { state: "pending", reason: "registry reports different package bytes" };
2568
}
2669
if (!dist.attestations?.url) {
27-
throw new Error(`${spec} exists without npm provenance`);
70+
return { state: "pending", reason: "registry has not exposed npm provenance" };
2871
}
29-
return "verified";
72+
return { state: "verified" };
3073
} catch (error) {
3174
const stderr = String(error?.stderr ?? "");
32-
if (stderr.includes("E404")) return "missing";
33-
throw error;
75+
if (stderr.includes("E404")) return { state: "missing", reason: "version is not visible" };
76+
return { state: "pending", reason: error instanceof Error ? error.message : String(error) };
3477
}
3578
}
3679

37-
if (registryState() === "verified") {
38-
console.log(`verified ${spec} integrity and provenance`);
39-
process.exit(0);
80+
function sleep(milliseconds) {
81+
return new Promise((resolvePromise) => setTimeout(resolvePromise, milliseconds));
4082
}
4183

42-
const published = spawnSync(
43-
"npm",
44-
["publish", join(artifactsDir, artifact.filename), "--access", "public", "--provenance"],
45-
{ stdio: "inherit" },
46-
);
47-
for (let attempt = 1; attempt <= 12; attempt += 1) {
48-
try {
49-
if (registryState() === "verified") {
50-
console.log(`verified ${spec} integrity and provenance`);
51-
process.exit(0);
84+
export async function publishOrVerify({
85+
packageName,
86+
artifactsDir,
87+
execNpm = execFileSync,
88+
spawnNpm = spawnSync,
89+
retryDelaysMs = REGISTRY_RETRY_DELAYS_MS,
90+
wait = sleep,
91+
log = console.log,
92+
}) {
93+
if (!packageName) throw new Error("--package is required");
94+
const artifact = loadReleaseArtifact(packageName, artifactsDir);
95+
const spec = `${artifact.name}@${artifact.version}`;
96+
let publishResult;
97+
98+
for (let attempt = 0; attempt <= retryDelaysMs.length; attempt += 1) {
99+
const registry = registryState(artifact, execNpm);
100+
if (registry.state === "verified") {
101+
log(`verified ${spec} byte identity and provenance`);
102+
return;
52103
}
53-
} catch (error) {
54-
if (attempt === 12) throw error;
104+
105+
if (registry.state === "missing" && publishResult === undefined) {
106+
publishResult = spawnNpm(
107+
"npm",
108+
["publish", artifact.path, "--access", "public", "--provenance"],
109+
{ stdio: "inherit" },
110+
);
111+
if (publishResult.error) {
112+
log(`npm publish could not start: ${publishResult.error.message}`);
113+
} else if (publishResult.status !== 0) {
114+
log(`npm publish exited ${publishResult.status}; checking whether the registry committed it`);
115+
}
116+
}
117+
118+
if (attempt === retryDelaysMs.length) {
119+
const publishSummary =
120+
publishResult === undefined ? "npm publish was not attempted" : `npm publish exited ${publishResult.status}`;
121+
throw new Error(`${publishSummary}; registry never confirmed ${spec}: ${registry.reason}`);
122+
}
123+
124+
const delayMs = retryDelaysMs[attempt];
125+
log(
126+
`registry verification attempt ${attempt + 1}/${retryDelaysMs.length + 1} has not confirmed ${spec}` +
127+
` (${registry.reason}); retrying in ${delayMs / 1_000}s`,
128+
);
129+
await wait(delayMs);
55130
}
56-
console.log(`registry verification attempt ${attempt}/12 has not confirmed ${spec}`);
57-
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 5_000);
58131
}
59-
throw new Error(`npm publish exited ${published.status}; registry never confirmed ${spec}`);
132+
133+
function parseArguments(argv) {
134+
const packageIndex = argv.indexOf("--package");
135+
const artifactsIndex = argv.indexOf("--artifacts");
136+
return {
137+
packageName: packageIndex >= 0 ? argv[packageIndex + 1] : undefined,
138+
artifactsDir: resolve(artifactsIndex >= 0 ? argv[artifactsIndex + 1] : "release-artifacts"),
139+
};
140+
}
141+
142+
const entryPath = process.argv[1] ? pathToFileURL(resolve(process.argv[1])).href : undefined;
143+
if (entryPath === import.meta.url) {
144+
await publishOrVerify(parseArguments(process.argv.slice(2)));
145+
}

‎test/publish-or-verify.test.ts‎

Lines changed: 113 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,113 @@
1+
import { createHash } from "node:crypto";
2+
import { mkdtemp, rm, writeFile } from "node:fs/promises";
3+
import { tmpdir } from "node:os";
4+
import { join, resolve } from "node:path";
5+
import { afterEach, describe, expect, it, vi } from "vitest";
6+
import {
7+
REGISTRY_RETRY_DELAYS_MS,
8+
loadReleaseArtifact,
9+
publishOrVerify,
10+
} from "../scripts/publish-or-verify.mjs";
11+
12+
const temporaryDirectories: string[] = [];
13+
14+
async function releaseArtifact(bytes = Buffer.from("validated tarball bytes")) {
15+
const directory = await mkdtemp(join(tmpdir(), "fs-safe-publish-test-"));
16+
temporaryDirectories.push(directory);
17+
const filename = "openclaw-fs-safe-9.9.9.tgz";
18+
const integrity = `sha512-${createHash("sha512").update(bytes).digest("base64")}`;
19+
await writeFile(join(directory, filename), bytes);
20+
await writeFile(
21+
join(directory, "manifest.json"),
22+
`${JSON.stringify([
23+
{
24+
name: "@openclaw/fs-safe",
25+
version: "9.9.9",
26+
filename,
27+
integrity,
28+
size: bytes.length,
29+
},
30+
])}\n`,
31+
);
32+
return { directory, filename, integrity };
33+
}
34+
35+
afterEach(async () => {
36+
await Promise.all(
37+
temporaryDirectories.splice(0).map((directory) => rm(directory, { recursive: true, force: true })),
38+
);
39+
});
40+
41+
describe("publish-or-verify", () => {
42+
it("rejects artifact bytes that differ from the validated manifest", async () => {
43+
const artifact = await releaseArtifact();
44+
await writeFile(join(artifact.directory, artifact.filename), "repacked bytes");
45+
46+
expect(() => loadReleaseArtifact("@openclaw/fs-safe", artifact.directory)).toThrow(
47+
"artifact bytes do not match release manifest",
48+
);
49+
});
50+
51+
it("publishes the exact validated tarball path and verifies its registry identity", async () => {
52+
const artifact = await releaseArtifact();
53+
const registryResponses = [
54+
Object.assign(new Error("missing"), { stderr: "npm error code E404" }),
55+
JSON.stringify({ integrity: "sha512-stale", attestations: { url: "https://example.test/stale" } }),
56+
JSON.stringify({ integrity: artifact.integrity, attestations: { url: "https://example.test/provenance" } }),
57+
];
58+
const execNpm = vi.fn(() => {
59+
const response = registryResponses.shift();
60+
if (response instanceof Error) throw response;
61+
return response;
62+
});
63+
const spawnNpm = vi.fn(() => ({ status: 0 }));
64+
const wait = vi.fn(async () => undefined);
65+
66+
await publishOrVerify({
67+
packageName: "@openclaw/fs-safe",
68+
artifactsDir: artifact.directory,
69+
execNpm,
70+
spawnNpm,
71+
retryDelaysMs: [5_000, 10_000],
72+
wait,
73+
log: vi.fn(),
74+
});
75+
76+
expect(spawnNpm).toHaveBeenCalledOnce();
77+
expect(spawnNpm).toHaveBeenCalledWith(
78+
"npm",
79+
["publish", resolve(artifact.directory, artifact.filename), "--access", "public", "--provenance"],
80+
{ stdio: "inherit" },
81+
);
82+
expect(wait.mock.calls.map(([delay]) => delay)).toEqual([5_000, 10_000]);
83+
});
84+
85+
it("backs off through transient mismatches without republishing an existing version", async () => {
86+
const artifact = await releaseArtifact();
87+
const execNpm = vi
88+
.fn()
89+
.mockReturnValueOnce(JSON.stringify({ integrity: "sha512-stale", attestations: {} }))
90+
.mockReturnValueOnce(JSON.stringify({ integrity: "sha512-stale", attestations: {} }))
91+
.mockReturnValueOnce(
92+
JSON.stringify({ integrity: artifact.integrity, attestations: { url: "https://example.test/provenance" } }),
93+
);
94+
const spawnNpm = vi.fn(() => ({ status: 0 }));
95+
const wait = vi.fn(async () => undefined);
96+
97+
await publishOrVerify({
98+
packageName: "@openclaw/fs-safe",
99+
artifactsDir: artifact.directory,
100+
execNpm,
101+
spawnNpm,
102+
retryDelaysMs: [5_000, 10_000],
103+
wait,
104+
log: vi.fn(),
105+
});
106+
107+
expect(spawnNpm).not.toHaveBeenCalled();
108+
expect(wait.mock.calls.map(([delay]) => delay)).toEqual([5_000, 10_000]);
109+
expect(REGISTRY_RETRY_DELAYS_MS.reduce((total, delay) => total + delay, 0)).toBeGreaterThanOrEqual(
110+
8 * 60_000,
111+
);
112+
});
113+
});

0 commit comments

Comments
 (0)