-
Notifications
You must be signed in to change notification settings - Fork 0
Fail closed on npm publication state (v1.2.3) #66
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,105 @@ | ||
| #!/usr/bin/env node | ||
|
|
||
| import { pathToFileURL } from "node:url"; | ||
|
|
||
| const REGISTRY_BASE = "https://registry.npmjs.org"; | ||
|
|
||
| function requireExpectedString(value, label) { | ||
| if (typeof value !== "string" || value.length === 0) { | ||
| throw new Error(`${label} is required`); | ||
| } | ||
| return value; | ||
| } | ||
|
|
||
| function requireIntegrity(value) { | ||
| const integrity = requireExpectedString(value, "expected npm integrity"); | ||
| if (!/^sha512-[A-Za-z0-9+/]+={0,2}$/.test(integrity)) { | ||
| throw new Error("expected npm integrity must be SHA-512 SRI"); | ||
| } | ||
| const digest = Buffer.from(integrity.slice("sha512-".length), "base64"); | ||
| if (digest.length !== 64) { | ||
| throw new Error("expected npm integrity must contain a 512-bit digest"); | ||
| } | ||
| return integrity; | ||
| } | ||
|
|
||
| export async function resolveNpmPublicationState({ | ||
| expectedName, | ||
| expectedVersion, | ||
| expectedIntegrity, | ||
| selector = expectedVersion, | ||
| timeoutMs = 10_000, | ||
| fetchImpl = fetch, | ||
| }) { | ||
| const name = requireExpectedString(expectedName, "expected npm package name"); | ||
| const version = requireExpectedString(expectedVersion, "expected npm package version"); | ||
| const integrity = requireIntegrity(expectedIntegrity); | ||
| if (selector !== version && selector !== "latest") { | ||
| throw new Error("npm registry selector must be the exact version or latest"); | ||
| } | ||
| if (!Number.isInteger(timeoutMs) || timeoutMs < 1) { | ||
| throw new Error("npm registry timeout must be a positive integer"); | ||
| } | ||
|
|
||
| const response = await fetchImpl( | ||
| `${REGISTRY_BASE}/${encodeURIComponent(name)}/${encodeURIComponent(selector)}`, | ||
| { | ||
| headers: { Accept: "application/json" }, | ||
| cache: "no-store", | ||
| signal: AbortSignal.timeout(timeoutMs), | ||
| }, | ||
| ); | ||
|
|
||
| if (response.status === 404) return "absent"; | ||
| if (!response.ok) { | ||
| throw new Error(`npm publication-state readback returned HTTP ${response.status}`); | ||
| } | ||
|
|
||
| let document; | ||
| try { | ||
| document = await response.json(); | ||
| } catch (error) { | ||
| throw new Error("npm publication-state response was not valid JSON", { cause: error }); | ||
| } | ||
| if ( | ||
| document === null || | ||
| typeof document !== "object" || | ||
| Array.isArray(document) || | ||
| document.dist === null || | ||
| typeof document.dist !== "object" || | ||
| Array.isArray(document.dist) || | ||
| document.name !== name || | ||
| document.version !== version || | ||
| document.dist.integrity !== integrity | ||
| ) { | ||
| throw new Error("npm publication-state metadata did not match the verified tarball"); | ||
| } | ||
|
|
||
| return "present"; | ||
| } | ||
|
|
||
| async function main() { | ||
| const mode = process.env.NPM_PUBLICATION_MODE; | ||
| if (mode !== "publication-state" && mode !== "require-present") { | ||
| throw new Error("NPM_PUBLICATION_MODE must be publication-state or require-present"); | ||
| } | ||
| const timeoutMs = Number(process.env.NPM_PUBLICATION_TIMEOUT_MS || 10_000); | ||
| const state = await resolveNpmPublicationState({ | ||
| expectedName: process.env.NPM_PUBLICATION_EXPECTED_NAME, | ||
| expectedVersion: process.env.NPM_PUBLICATION_EXPECTED_VERSION, | ||
| expectedIntegrity: process.env.NPM_PUBLICATION_EXPECTED_INTEGRITY, | ||
| selector: process.env.NPM_PUBLICATION_SELECTOR || process.env.NPM_PUBLICATION_EXPECTED_VERSION, | ||
| timeoutMs, | ||
| }); | ||
| if (mode === "require-present" && state !== "present") { | ||
| throw new Error("verified npm release is not publicly present"); | ||
| } | ||
| process.stdout.write(`${state}\n`); | ||
| } | ||
|
|
||
| if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) { | ||
| main().catch((error) => { | ||
| process.stderr.write(`${error instanceof Error ? error.message : String(error)}\n`); | ||
| process.exitCode = 1; | ||
| }); | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,110 @@ | ||
| import { describe, expect, it, vi } from "vitest"; | ||
| import { resolveNpmPublicationState } from "../scripts/resolve-npm-publication.mjs"; | ||
|
|
||
| const expected = { | ||
| expectedName: "oilpriceapi", | ||
| expectedVersion: "1.2.3", | ||
| expectedIntegrity: `sha512-${Buffer.alloc(64, 0x5a).toString("base64")}`, | ||
| }; | ||
|
|
||
| function registryResponse(status: number, payload: unknown) { | ||
| return { | ||
| ok: status >= 200 && status < 300, | ||
| status, | ||
| json: vi.fn().mockResolvedValue(payload), | ||
| }; | ||
| } | ||
|
|
||
| describe("npm publication state", () => { | ||
| it("treats only an exact HTTP 404 as absent", async () => { | ||
| const fetchImpl = vi.fn().mockResolvedValue(registryResponse(404, { error: "Not found" })); | ||
|
|
||
| await expect(resolveNpmPublicationState({ ...expected, fetchImpl })).resolves.toBe("absent"); | ||
| expect(fetchImpl).toHaveBeenCalledWith( | ||
| "https://registry.npmjs.org/oilpriceapi/1.2.3", | ||
| expect.objectContaining({ cache: "no-store" }), | ||
| ); | ||
| }); | ||
|
|
||
| it("accepts an exact name, version, and integrity document as present", async () => { | ||
| const fetchImpl = vi.fn().mockResolvedValue( | ||
| registryResponse(200, { | ||
| name: expected.expectedName, | ||
| version: expected.expectedVersion, | ||
| dist: { integrity: expected.expectedIntegrity }, | ||
| }), | ||
| ); | ||
|
|
||
| await expect(resolveNpmPublicationState({ ...expected, fetchImpl })).resolves.toBe("present"); | ||
| }); | ||
|
|
||
| it("rejects an SRI-shaped value whose digest is not 512 bits", async () => { | ||
| const fetchImpl = vi.fn().mockResolvedValue(registryResponse(404, { error: "Not found" })); | ||
|
|
||
| await expect( | ||
| resolveNpmPublicationState({ | ||
| ...expected, | ||
| expectedIntegrity: "sha512-dGVzdA==", | ||
| fetchImpl, | ||
| }), | ||
| ).rejects.toThrow("512-bit"); | ||
| expect(fetchImpl).not.toHaveBeenCalled(); | ||
| }); | ||
|
|
||
| it("validates the latest selector against the same exact release", async () => { | ||
| const fetchImpl = vi.fn().mockResolvedValue( | ||
| registryResponse(200, { | ||
| name: expected.expectedName, | ||
| version: expected.expectedVersion, | ||
| dist: { integrity: expected.expectedIntegrity }, | ||
| }), | ||
| ); | ||
|
|
||
| await expect( | ||
| resolveNpmPublicationState({ ...expected, selector: "latest", fetchImpl }), | ||
| ).resolves.toBe("present"); | ||
| expect(fetchImpl).toHaveBeenCalledWith( | ||
| "https://registry.npmjs.org/oilpriceapi/latest", | ||
| expect.any(Object), | ||
| ); | ||
| }); | ||
|
|
||
| it.each([ | ||
| ["wrong integrity", { name: "oilpriceapi", version: "1.2.3", dist: { integrity: "sha512-wrong" } }], | ||
| ["wrong name", { name: "other", version: "1.2.3", dist: { integrity: expected.expectedIntegrity } }], | ||
| ["wrong version", { name: "oilpriceapi", version: "9.9.9", dist: { integrity: expected.expectedIntegrity } }], | ||
| ["malformed document", { error: "not package metadata" }], | ||
| ])("rejects a 200 response with %s", async (_label, payload) => { | ||
| const fetchImpl = vi.fn().mockResolvedValue(registryResponse(200, payload)); | ||
|
|
||
| await expect(resolveNpmPublicationState({ ...expected, fetchImpl })).rejects.toThrow( | ||
| /verified tarball/, | ||
| ); | ||
| }); | ||
|
|
||
| it("fails closed on non-404 registry errors", async () => { | ||
| const fetchImpl = vi.fn().mockResolvedValue(registryResponse(503, { error: "unavailable" })); | ||
|
|
||
| await expect(resolveNpmPublicationState({ ...expected, fetchImpl })).rejects.toThrow("HTTP 503"); | ||
| }); | ||
|
|
||
| it("fails closed when a successful response is not valid JSON", async () => { | ||
| const fetchImpl = vi.fn().mockResolvedValue({ | ||
| ok: true, | ||
| status: 200, | ||
| json: vi.fn().mockRejectedValue(new SyntaxError("bad JSON")), | ||
| }); | ||
|
|
||
| await expect(resolveNpmPublicationState({ ...expected, fetchImpl })).rejects.toThrow( | ||
| "not valid JSON", | ||
| ); | ||
| }); | ||
|
|
||
| it("fails closed on network errors", async () => { | ||
| const fetchImpl = vi.fn().mockRejectedValue(new Error("network unavailable")); | ||
|
|
||
| await expect(resolveNpmPublicationState({ ...expected, fetchImpl })).rejects.toThrow( | ||
| "network unavailable", | ||
| ); | ||
| }); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.