Skip to content

Commit a50f695

Browse files
LudoLoopsLudoLoops
andauthored
fix(release): verify the exact published tarball before the consumer install (#628) (#629)
* fix(release): verify the exact published tarball before the consumer install (#628) `--wait-for-registry` polled only version metadata, so the 2.2.5 release passed the visibility gate while `svforge-2.2.5.tgz` still answered 404 and the consumer install failed on an already-published version. `tarballAvailable()` now resolves `dist.tarball` + `dist.integrity` from the registry metadata, fetches that exact URL, and verifies the gzip artifact and its sha512 integrity before anything is installed. It is composed into the availability probe (`registryReleaseConsumable`), so the existing bounded retry loop covers it: - retried: a verified 404/410 of the EXPECTED tarball (and E404/ETARGET metadata), with the same bounded delays; - fatal, never retried: checksum mismatch, non-gzip/invalid artifact, any other HTTP status, network/auth errors, and metadata without a tarball URL (the URL is never guessed). Covered by 12 new tests (retry-only-on-404, checksum mismatch, 503, ECONNRESET, HTML body, missing metadata, composed probe order, bounded waits) plus the existing suite; `bun run lint` and `bun run typecheck` are clean. Documented in docs/RELEASE.md; no changeset (root-only release tooling). * fix(release): require validated tarball integrity and gzip payload --------- Co-authored-by: LudoLoops <ludoloops@ik.me>
1 parent 583337a commit a50f695

3 files changed

Lines changed: 235 additions & 3 deletions

File tree

‎docs/RELEASE.md‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,14 @@ lag npm's publish acknowledgment: the visibility gate checks fresh npm metadata
3131
(with an isolated temporary cache for every probe) for up to approximately ten
3232
minutes. Only E404/ETARGET or a stale version response may be retried; unexpected
3333
npm/authentication/network/parsing failures still fail immediately. A timeout
34-
fails the workflow without claiming the release was not published. Recovery uses
34+
fails the workflow without claiming the release was not published.
35+
36+
The gate also fetches the **exact tarball** named by that metadata and verifies
37+
its mandatory sha512 `dist.integrity` and complete gzip structure before installing (#628): npm can expose
38+
version metadata while `<name>-<version>.tgz` still answers 404, which failed an
39+
already-published release. Only a verified 404/410 of the expected tarball URL is
40+
retried; a checksum mismatch, an invalid artifact, an unexpected HTTP status or a
41+
network/auth error fails immediately, and the URL is never guessed. Recovery uses
3542
the same approved, already-merged `Version Packages` PR, not a new version.
3643

3744
## Release policy: grouped stable releases, optional numbered canaries (#572)

‎scripts/npm-consumer-smoke.mjs‎

Lines changed: 86 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,8 @@
44
* imports for every package through its declared TypeScript entry point.
55
*/
66
import { execFileSync } from 'node:child_process';
7+
import { createHash } from 'node:crypto';
8+
import { gunzipSync } from 'node:zlib';
79
import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
810
import { join, resolve } from 'node:path';
911
import { tmpdir } from 'node:os';
@@ -117,6 +119,89 @@ export function registryVersionVisible(spec, npm = 'npm', run = execFileSync) {
117119
}
118120
}
119121

122+
/**
123+
* The exact published TARBALL must be fetchable, not just the version metadata
124+
* (#628): npm exposed `svforge@2.2.5` metadata while `svforge-2.2.5.tgz` still
125+
* answered 404, and the consumer gate failed on a release that was already
126+
* published.
127+
*
128+
* Retry ONLY a verified 404/410 of the EXPECTED tarball resolved from the
129+
* registry metadata. A checksum mismatch, a non-gzip artifact, an unexpected
130+
* HTTP status, or a network/auth error stays fatal: those mean the published
131+
* artifact is broken, not that propagation is still in flight.
132+
*/
133+
export async function tarballAvailable(spec, npm = 'npm', { run = execFileSync, fetchImpl = fetch } = {}) {
134+
const cacheDir = mkdtempSync(join(tmpdir(), 'svforge-tarball-probe-'));
135+
let metadata;
136+
try {
137+
const output = run(
138+
npm,
139+
['view', spec, 'dist.tarball', 'dist.integrity', '--json', '--prefer-online', '--cache', cacheDir],
140+
{ encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }
141+
);
142+
metadata = JSON.parse(String(output).trim());
143+
} catch (error) {
144+
const details = [error?.stderr, error?.stdout, error?.message].filter(Boolean).map(String).join('\n');
145+
if (/\b(?:E404|ETARGET)\b|404 Not Found|No matching version found|No match found for version/i.test(details)) {
146+
console.log(`Registry not ready for ${spec}: npm view reported E404/ETARGET`);
147+
return false;
148+
}
149+
throw new Error(`Registry lookup failed for ${spec}: ${details.slice(0, 700)}`, { cause: error });
150+
} finally {
151+
rmSync(cacheDir, { recursive: true, force: true });
152+
}
153+
154+
const url = metadata?.['dist.tarball'];
155+
const integrity = metadata?.['dist.integrity'];
156+
if (typeof url !== 'string' || !url) {
157+
throw new Error(`Registry metadata for ${spec} has no dist.tarball; refusing to guess a tarball URL.`);
158+
}
159+
if (typeof integrity !== 'string' || !/^sha512-[A-Za-z0-9+/]{86}==$/.test(integrity)) {
160+
throw new Error(`Registry metadata for ${spec} has no valid sha512 dist.integrity; refusing an unverified tarball.`);
161+
}
162+
163+
let response;
164+
try {
165+
response = await fetchImpl(url, { redirect: 'follow', signal: AbortSignal.timeout(30_000) });
166+
} catch (error) {
167+
throw new Error(`Tarball fetch failed for ${spec} (${url}): ${error?.message ?? error}`, { cause: error });
168+
}
169+
if (response.status === 404 || response.status === 410) {
170+
console.log(`Registry not ready for ${spec}: tarball ${url} returned HTTP ${response.status}`);
171+
return false;
172+
}
173+
if (!response.ok) {
174+
throw new Error(`Tarball fetch for ${spec} returned HTTP ${response.status} (${url})`);
175+
}
176+
177+
const bytes = Buffer.from(await response.arrayBuffer());
178+
if (bytes.length < 2 || bytes[0] !== 0x1f || bytes[1] !== 0x8b) {
179+
throw new Error(`Tarball for ${spec} is not a gzip artifact (${bytes.length} bytes from ${url}).`);
180+
}
181+
const digest = `sha512-${createHash('sha512').update(bytes).digest('base64')}`;
182+
if (digest !== integrity) {
183+
throw new Error(`Tarball integrity mismatch for ${spec}: registry ${integrity}, downloaded ${digest}.`);
184+
}
185+
try {
186+
gunzipSync(bytes);
187+
} catch (error) {
188+
throw new Error(`Tarball for ${spec} has an invalid gzip payload (${url}).`, { cause: error });
189+
}
190+
return true;
191+
}
192+
193+
/**
194+
* Version metadata AND its exact tarball must be consumable before installing.
195+
*
196+
* @param {string} spec
197+
* @param {string} [npm]
198+
* @param {{ run?: typeof execFileSync, fetchImpl?: typeof fetch }} [options]
199+
*/
200+
export async function registryReleaseConsumable(spec, npm = 'npm', options = {}) {
201+
if (!registryVersionVisible(spec, npm, options.run ?? execFileSync)) return false;
202+
return tarballAvailable(spec, npm, options);
203+
}
204+
120205
/**
121206
* @param {{packages: Array<{name: string, version: string, tarball?: string}>}} plan
122207
* @param {{
@@ -129,7 +214,7 @@ export async function waitForRegistryAvailability(plan, {
129214
registryOnly = false,
130215
maxAttempts = 60,
131216
intervalMs = 10000,
132-
probe = registryVersionVisible,
217+
probe = registryReleaseConsumable,
133218
pause = sleep
134219
} = {}) {
135220
if (!Number.isInteger(maxAttempts) || maxAttempts < 1) throw new Error('maxAttempts must be positive.');

‎tests/npm-consumer-smoke.test.ts‎

Lines changed: 141 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,11 @@
11
import { describe, expect, it, vi } from 'vitest';
2+
import { createHash } from 'node:crypto';
3+
import { gzipSync } from 'node:zlib';
24
import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
35
import { join } from 'node:path';
46
import { tmpdir } from 'node:os';
57

6-
const { consumerInstallSpecs, consumerSource, consumerTsConfig, packageTypePath, validateInstalledTypes, waitForRegistryAvailability, registryVersionVisible } = await import('../scripts/npm-consumer-smoke.mjs');
8+
const { consumerInstallSpecs, consumerSource, consumerTsConfig, packageTypePath, validateInstalledTypes, waitForRegistryAvailability, registryVersionVisible, tarballAvailable, registryReleaseConsumable } = await import('../scripts/npm-consumer-smoke.mjs');
79

810
describe('npm consumer smoke test (#330)', () => {
911
it('resolves the declared type entry for every exact package', () => {
@@ -181,4 +183,142 @@ describe('npm consumer smoke test (#330)', () => {
181183
expect(() => registryVersionVisible('@svforge/audit@2.2.0', 'npm',
182184
fake(Object.assign(new Error('access denied'), { stderr: 'npm error code E401' })))).toThrow(/Registry lookup failed/);
183185
});
186+
187+
describe('exact tarball availability (#628)', () => {
188+
const gzipBody = gzipSync(Buffer.from('test tarball payload'));
189+
const integrityOf = (body: Buffer) => `sha512-${createHash('sha512').update(body).digest('base64')}`;
190+
const tarballUrl = 'https://registry.npmjs.org/svforge/-/svforge-2.5.0.tgz';
191+
const metadata = (url = tarballUrl, integrity = integrityOf(gzipBody)) =>
192+
JSON.stringify({ 'dist.tarball': url, 'dist.integrity': integrity });
193+
const npmReturning = (payload: string) => (() => payload) as unknown as NonNullable<Parameters<typeof tarballAvailable>[2]>['run'];
194+
const fetchReturning = (status: number, body: Buffer = gzipBody) =>
195+
(async () => new Response(status === 200 ? new Uint8Array(body) : 'missing', { status })) as unknown as typeof fetch;
196+
197+
it('accepts the exact tarball when the registry metadata and bytes agree', async () => {
198+
expect(
199+
await tarballAvailable('svforge@2.5.0', 'npm', {
200+
run: npmReturning(metadata()),
201+
fetchImpl: fetchReturning(200)
202+
})
203+
).toBe(true);
204+
});
205+
206+
it('retries only a verified 404 of the expected tarball', async () => {
207+
const log = vi.spyOn(console, 'log').mockImplementation(() => {});
208+
try {
209+
expect(
210+
await tarballAvailable('svforge@2.5.0', 'npm', {
211+
run: npmReturning(metadata()),
212+
fetchImpl: fetchReturning(404)
213+
})
214+
).toBe(false);
215+
expect(log).toHaveBeenCalledWith(expect.stringContaining(`tarball ${tarballUrl} returned HTTP 404`));
216+
} finally {
217+
log.mockRestore();
218+
}
219+
});
220+
221+
it('treats a missing version (E404/ETARGET) as not-ready but never retries other npm failures', async () => {
222+
const log = vi.spyOn(console, 'log').mockImplementation(() => {});
223+
try {
224+
const notFound = (() => {
225+
throw Object.assign(new Error('missing'), { stderr: 'npm error code E404' });
226+
}) as unknown as NonNullable<Parameters<typeof tarballAvailable>[2]>['run'];
227+
expect(await tarballAvailable('svforge@2.5.0', 'npm', { run: notFound, fetchImpl: fetchReturning(200) })).toBe(false);
228+
229+
const denied = (() => {
230+
throw Object.assign(new Error('denied'), { stderr: 'npm error code E401' });
231+
}) as unknown as NonNullable<Parameters<typeof tarballAvailable>[2]>['run'];
232+
await expect(
233+
tarballAvailable('svforge@2.5.0', 'npm', { run: denied, fetchImpl: fetchReturning(200) })
234+
).rejects.toThrow(/Registry lookup failed/);
235+
} finally {
236+
log.mockRestore();
237+
}
238+
});
239+
240+
it('rejects missing or invalid sha512 metadata before accepting a tarball', async () => {
241+
for (const integrity of [undefined, 'sha1-test', 'sha512-invalid']) {
242+
const response = JSON.stringify({ 'dist.tarball': tarballUrl, ...(integrity === undefined ? {} : { 'dist.integrity': integrity }) });
243+
await expect(
244+
tarballAvailable('svforge@2.5.0', 'npm', {
245+
run: npmReturning(response),
246+
fetchImpl: fetchReturning(200)
247+
})
248+
).rejects.toThrow(/valid sha512 dist\.integrity/);
249+
}
250+
});
251+
252+
it('rejects truncated gzip data even when sha512 matches its bytes', async () => {
253+
const truncated = Buffer.from([0x1f, 0x8b, 0x08, 0, 0, 0, 0, 0]);
254+
await expect(
255+
tarballAvailable('svforge@2.5.0', 'npm', {
256+
run: npmReturning(metadata(tarballUrl, integrityOf(truncated))),
257+
fetchImpl: fetchReturning(200, truncated)
258+
})
259+
).rejects.toThrow(/invalid gzip payload/);
260+
});
261+
262+
it('fails hard on a checksum mismatch instead of retrying a broken artifact', async () => {
263+
await expect(
264+
tarballAvailable('svforge@2.5.0', 'npm', {
265+
run: npmReturning(metadata(tarballUrl, integrityOf(Buffer.from('other')))),
266+
fetchImpl: fetchReturning(200)
267+
})
268+
).rejects.toThrow(/integrity mismatch/);
269+
});
270+
271+
it('fails hard on unexpected HTTP statuses, network errors and non-gzip bodies', async () => {
272+
await expect(
273+
tarballAvailable('svforge@2.5.0', 'npm', { run: npmReturning(metadata()), fetchImpl: fetchReturning(503) })
274+
).rejects.toThrow(/HTTP 503/);
275+
276+
const networkError = (async () => {
277+
throw new Error('ECONNRESET');
278+
}) as unknown as typeof fetch;
279+
await expect(
280+
tarballAvailable('svforge@2.5.0', 'npm', { run: npmReturning(metadata()), fetchImpl: networkError })
281+
).rejects.toThrow(/Tarball fetch failed .*ECONNRESET/);
282+
283+
await expect(
284+
tarballAvailable('svforge@2.5.0', 'npm', {
285+
run: npmReturning(metadata()),
286+
fetchImpl: fetchReturning(200, Buffer.from('<!doctype html>'))
287+
})
288+
).rejects.toThrow(/not a gzip artifact/);
289+
});
290+
291+
it('refuses to guess a tarball URL from incomplete metadata', async () => {
292+
await expect(
293+
tarballAvailable('svforge@2.5.0', 'npm', { run: npmReturning('{}'), fetchImpl: fetchReturning(200) })
294+
).rejects.toThrow(/no dist\.tarball/);
295+
});
296+
297+
it('waits for a tarball 404 to clear and then installs', async () => {
298+
let probes = 0;
299+
let waits = 0;
300+
await waitForRegistryAvailability({ packages: [{ name: 'svforge', version: '2.5.0' }] }, {
301+
maxAttempts: 4,
302+
intervalMs: 1,
303+
probe: async () => ++probes > 2,
304+
pause: async () => {
305+
waits++;
306+
}
307+
});
308+
expect(probes).toBe(3);
309+
expect(waits).toBe(2);
310+
});
311+
312+
it('verifies metadata and bytes through the composed consumability probe', async () => {
313+
const fields: string[] = [];
314+
const run = ((_npm: string, args: string[]) => {
315+
fields.push(args[2]);
316+
return args[2] === 'version' ? '"2.5.0"' : JSON.stringify({ 'dist.tarball': tarballUrl, 'dist.integrity': integrityOf(gzipBody) });
317+
}) as unknown as NonNullable<Parameters<typeof registryReleaseConsumable>[2]>['run'];
318+
const fetchImpl = (async () => new Response('missing', { status: 404 })) as unknown as typeof fetch;
319+
320+
expect(await registryReleaseConsumable('svforge@2.5.0', 'npm', { run, fetchImpl })).toBe(false);
321+
expect(fields).toEqual(['version', 'dist.tarball']);
322+
});
323+
});
184324
});

0 commit comments

Comments
 (0)