Skip to content
7 changes: 5 additions & 2 deletions docs/docs/commands/registry.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,9 @@ nf publish [options]
| `--dry-run` | boolean | `false` | List the files to publish, and publish nothing. |

Before uploading, `nf publish` prints every file it packed, with its size, then their count and
total size. With `--dry-run` it stops there: check the list before your first publish.
total size. With `--dry-run` it stops there: check the list before your first publish. The size
limits below are checked while packing, so a package over them fails before anything is uploaded,
`--dry-run` included.

The archive holds only what the manifest names, with the manifest at its root:

Expand All @@ -138,7 +140,8 @@ Inside those, secrets and installed folders stay out, in any subfolder and whate
A file the manifest doesn't name, such as `notes.txt` next to it, is not sent: list your code and
assets in `contents`. `.gitignore` is not read. For an editor plugin, publish its build:
`nf publish -d dist`, the folder with the built manifest and its entry files. The registry refuses
archives over 20 MiB, or that unpack to more than 256 MiB or 20,000 files.
archives over 20 MiB, or that unpack to more than 256 MiB or 20,000 files: `nf publish` stops at
these limits before uploading.

```bash
nf publish --dry-run
Expand Down
1 change: 1 addition & 0 deletions libs/registry/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@ await registry.publish("@acme/kit", await zipFolder("kit", { ignore: (path) => p
await registry.unpublish("@acme/kit", "1.2.0");
```

- `zipFolder` stops before reading a folder past 256 MiB or 20,000 files (what an install accepts). `packFolder` does the same and also returns the packed files with their sizes; with `maxBytes: MAX_PUBLISH_BYTES` (20 MiB, the registry's limit) it zips one file at a time and stops as soon as the archive passes it, so a package the registry would refuse is never read in full nor uploaded. Its archives then have other bytes than `zipFolder`'s for the same files. `onFiles` gets that list once the folder is walked, before any file is read.
- `RegistryClient` only talks to the origin of `baseUrl`, redirects included: a `dist.tarball` or a redirect elsewhere is refused (`INVALID`). A registry that keeps its archives on another host lists it in `archiveOrigins`. Give `baseUrl` the exact origin the API writes its archive addresses with (its `API_BASE_URL`): `http://localhost:3000` and `http://127.0.0.1:3000` are two origins.
- `@nanoforge-dev/registry/types` holds the schemas and types only (no Node code), for browser code.
- `@nanoforge-dev/registry/tsconfig-paths` edits the `paths` of a `tsconfig.json`.
Expand Down
109 changes: 97 additions & 12 deletions libs/registry/src/archive/archive.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { strFromU8, unzipSync, zipSync } from "fflate";
import { Zip, ZipDeflate, strFromU8, unzipSync, zipSync } from "fflate";
import { createHash, randomBytes } from "node:crypto";
import { existsSync } from "node:fs";
import { mkdir, readFile, readdir, rename, rm, writeFile } from "node:fs/promises";
import { mkdir, readFile, readdir, rename, rm, stat, writeFile } from "node:fs/promises";
import { dirname, join } from "node:path";

import { ItemManifest, MANIFEST_FILE } from "../item/item.schema";
Expand All @@ -12,6 +12,8 @@ export const sha256 = (bytes: Uint8Array): string =>

/** Size of an archive, packed: a download past it is stopped. */
export const MAX_ARCHIVE_BYTES = 64 * 1024 * 1024;
/** Size of an archive, packed, the registry takes at publication (the API's `ARCHIVE_MAX_BYTES`). */
export const MAX_PUBLISH_BYTES = 20 * 1024 * 1024;
/** What an archive may unpack to, in all and in files. */
const MAX_UNPACKED_BYTES = 256 * 1024 * 1024;
const MAX_FILES = 20_000;
Expand Down Expand Up @@ -119,25 +121,108 @@ export interface ZipFolderOptions {
readonly ignore?: (path: string, isDirectory: boolean) => boolean;
}

export interface PackFolderOptions extends ZipFolderOptions {
/**
* Size the archive may reach, packed: files are then zipped one at a time, and packing stops as
* soon as the archive passes it.
*/
readonly maxBytes?: number;
/** Called with the files to pack once they are listed, before any of them is read. */
readonly onFiles?: (files: readonly PackedFile[]) => void;
}

/** A file of a packed folder: its path in the archive and its size, unpacked. */
export interface PackedFile {
readonly path: string;
readonly size: number;
}

/** No dates in archives, so their hash only follows their content (1980-01-01, zip's first day). */
const ZIP_MTIME = new Date(315532800000);

const TRIM_HINT = "Name fewer files in the manifest's contents, or make large assets smaller.";

/**
* Zips a folder with stable bytes (sorted paths, no dates), so its hash only follows its content.
* Symbolic links are left out.
* Zips the files one at a time, and stops as soon as the archive passes `maxBytes`. Its entries
* have data descriptors, so its bytes differ from `zipSync`'s for the same files.
*/
export const zipFolder = async (
folder: string,
{ ignore }: ZipFolderOptions = {},
const streamZip = async (
found: readonly { path: string; file: string }[],
maxBytes: number,
): Promise<Uint8Array> => {
const files: Record<string, [Uint8Array, { mtime: Date }]> = {};
const chunks: Uint8Array[] = [];
let packed = 0;
let failure: Error | undefined;
const zip = new Zip((error, chunk) => {
if (error) failure = error;
else {
chunks.push(chunk);
packed += chunk.length;
}
});
const check = () => {
if (failure) throw failure;
if (packed > maxBytes)
throw new RegistryError(
"INVALID",
`The archive is too large: over ${maxBytes / 1024 / 1024} MiB packed, the most the registry takes. ${TRIM_HINT}`,
);
};
for (const { path, file } of found) {
const entry = new ZipDeflate(path, { level: 6 });
entry.mtime = ZIP_MTIME;
zip.add(entry);
entry.push(await readFile(file), true);
check();
}
zip.end();
check();
const archive = new Uint8Array(packed);
let offset = 0;
for (const chunk of chunks) archive.set(chunk, (offset += chunk.length) - chunk.length);
return archive;
};

/**
* Zips a folder with stable bytes (sorted paths, no dates), so its hash only follows its content,
* and lists the files it packed. Symbolic links are left out. Sizes are added up while walking,
* before any file is read: past 256 MiB or 20,000 files, which `readArchive` would refuse, it
* stops. With `maxBytes`, it also stops as soon as the archive passes that size, packed.
*/
export const packFolder = async (
folder: string,
{ ignore, maxBytes, onFiles }: PackFolderOptions = {},
): Promise<{ archive: Uint8Array; files: PackedFile[] }> => {
const found: (PackedFile & { file: string })[] = [];
let unpacked = 0;
const walk = async (dir: string, prefix: string) => {
const entries = await readdir(dir, { withFileTypes: true });
for (const entry of entries.sort((a, b) => a.name.localeCompare(b.name))) {
const path = prefix ? `${prefix}/${entry.name}` : entry.name;
if (ignore?.(path, entry.isDirectory())) continue;
if (entry.isDirectory()) await walk(join(dir, entry.name), path);
else if (entry.isFile())
files[path] = [await readFile(join(dir, entry.name)), { mtime: new Date(315532800000) }];
const file = join(dir, entry.name);
if (entry.isDirectory()) await walk(file, path);
else if (entry.isFile()) {
const { size } = await stat(file);
unpacked += size;
if (found.push({ path, size, file }) > MAX_FILES || unpacked > MAX_UNPACKED_BYTES)
throw new RegistryError(
"INVALID",
`The folder is too large to pack: over 256 MiB or 20,000 files. ${TRIM_HINT}`,
);
}
}
};
await walk(folder, "");
return zipSync(files, { level: 6 });
const files = found.map(({ path, size }) => ({ path, size }));
onFiles?.(files);
if (maxBytes !== undefined) return { archive: await streamZip(found, maxBytes), files };
// Without a limit, zipSync keeps the bytes (and hashes) archives always had.
const entries: Record<string, [Uint8Array, { mtime: Date }]> = {};
for (const { path, file } of found) entries[path] = [await readFile(file), { mtime: ZIP_MTIME }];
return { archive: zipSync(entries, { level: 6 }), files };
};

/** The archive of `packFolder`, alone. */
export const zipFolder = async (folder: string, options?: ZipFolderOptions): Promise<Uint8Array> =>
(await packFolder(folder, options)).archive;
79 changes: 77 additions & 2 deletions libs/registry/test/archive/archive.spec.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
import { strToU8, zipSync } from "fflate";
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { randomBytes } from "node:crypto";
import { chmodSync, mkdirSync, mkdtempSync, rmSync, truncateSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { describe, expect, it } from "vitest";

import { readArchive, zipFolder } from "../../src/archive/archive";
import { packFolder, readArchive, zipFolder } from "../../src/archive/archive";

const CENTRAL_ENTRY = 0x02014b50;

Expand Down Expand Up @@ -66,3 +67,77 @@ describe("zipFolder", () => {
}
});
});

describe("packFolder", () => {
it("lists the files it packed, with their sizes", async () => {
const folder = mkdtempSync(join(tmpdir(), "nf-zip-"));
try {
mkdirSync(join(folder, "src"));
writeFileSync(join(folder, "a.txt"), "hello");
writeFileSync(join(folder, "src/b.ts"), "b");

const { archive, files } = await packFolder(folder);
expect(files).toEqual([
{ path: "a.txt", size: 5 },
{ path: "src/b.ts", size: 1 },
]);
expect([...readArchive(archive).keys()]).toEqual(["a.txt", "src/b.ts"]);
} finally {
rmSync(folder, { recursive: true, force: true });
}
});

it("stops before reading a folder past 256 MiB, naming the limit", async () => {
const folder = mkdtempSync(join(tmpdir(), "nf-zip-"));
try {
// A sparse file: 257 MiB on paper, nothing on disk.
writeFileSync(join(folder, "big.bin"), "");
truncateSync(join(folder, "big.bin"), 257 * 1024 * 1024);

await expect(zipFolder(folder)).rejects.toThrow(
/too large to pack: over 256 MiB or 20,000 files\. Name fewer files/,
);
} finally {
rmSync(folder, { recursive: true, force: true });
}
});

it("with maxBytes, zips the same files with stable bytes", async () => {
const folder = mkdtempSync(join(tmpdir(), "nf-zip-"));
try {
mkdirSync(join(folder, "src"));
writeFileSync(join(folder, "a.txt"), "hello");
writeFileSync(join(folder, "src/b.ts"), "b");

const first = await packFolder(folder, { maxBytes: 1024 * 1024 });
const second = await packFolder(folder, { maxBytes: 1024 * 1024 });
expect(first.archive).toEqual(second.archive);
expect(first.files).toEqual([
{ path: "a.txt", size: 5 },
{ path: "src/b.ts", size: 1 },
]);
const files = readArchive(first.archive);
expect(new TextDecoder().decode(files.get("a.txt"))).toBe("hello");
expect([...files.keys()]).toEqual(["a.txt", "src/b.ts"]);
} finally {
rmSync(folder, { recursive: true, force: true });
}
});

it("with maxBytes, stops packing as soon as the archive passes it, naming the limit", async () => {
const folder = mkdtempSync(join(tmpdir(), "nf-zip-"));
try {
// Random bytes do not compress: a.bin alone passes the limit.
writeFileSync(join(folder, "a.bin"), randomBytes(1024 * 1024 + 1));
// Unreadable: reading it would fail with EACCES rather than "too large".
writeFileSync(join(folder, "b.bin"), "b");
chmodSync(join(folder, "b.bin"), 0);

await expect(packFolder(folder, { maxBytes: 1024 * 1024 })).rejects.toThrow(
/too large: over 1 MiB packed, the most the registry takes\. Name fewer files/,
);
} finally {
rmSync(folder, { recursive: true, force: true });
}
});
});
54 changes: 54 additions & 0 deletions src/action/actions/publish.action.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
import { randomBytes } from "node:crypto";
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";

import { type Input } from "@lib/input";

import { PublishAction } from "./publish.action";

const input = (entries: Record<string, unknown>): Input =>
new Map(Object.entries(entries).map(([key, value]) => [key, { value }])) as Input;

let dir: string;

beforeEach(() => {
dir = mkdtempSync(join(tmpdir(), "nf-publish-action-"));
writeFileSync(
join(dir, "nanoforge.manifest.json"),
JSON.stringify({
name: "@acme/kit",
version: "1.2.0",
type: "package",
contents: [{ kind: "asset", path: "assets/" }],
}),
);
writeFileSync(join(dir, ".nanoforgerc"), "apiKey=secret-key\n");
});

afterEach(() => {
vi.restoreAllMocks();
vi.unstubAllGlobals();
rmSync(dir, { recursive: true, force: true });
});

describe("PublishAction", () => {
it("refuses an archive past the registry's 20 MiB before uploading it", async () => {
mkdirSync(join(dir, "assets"));
// Random bytes do not compress: the archive is over 20 MiB too.
writeFileSync(join(dir, "assets/noise.bin"), randomBytes(21 * 1024 * 1024));
const fetch = vi.fn();
vi.stubGlobal("fetch", fetch);
const info = vi.spyOn(console, "info").mockImplementation(() => undefined);

await expect(new PublishAction().handle(new Map(), input({ directory: dir }))).rejects.toThrow(
/too large: over 20 MiB packed, the most the registry takes\. Name fewer files/,
);
expect(fetch).not.toHaveBeenCalled();
// The list is still printed, to see what to leave out.
expect(info.mock.calls.map(([line]) => String(line))).toContain(
" assets/noise.bin (21.0 MiB)",
);
});
});
18 changes: 11 additions & 7 deletions src/action/actions/publish.action.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { readArchive, zipFolder } from "@nanoforge-dev/registry";
import { MAX_PUBLISH_BYTES, packFolder } from "@nanoforge-dev/registry";

import { type Input, getDirectoryInput, getDryRunInput } from "@lib/input";
import { loadManifest } from "@lib/manifest";
Expand Down Expand Up @@ -31,12 +31,16 @@ export class PublishAction extends AbstractAction {
const manifest = loadManifest(directory);
const subject = `${manifest.name}@${manifest.version}`;
const root = getCwd(directory);
const archive = await zipFolder(root, { ignore: await publishIgnore(root, manifest) });

const files = [...readArchive(archive)];
for (const [path, content] of files) console.info(` ${path} (${formatSize(content.length)})`);
const unpacked = files.reduce((total, [, content]) => total + content.length, 0);
console.info(Messages.PUBLISH_FILES(subject, files.length, formatSize(unpacked)));
// The list is printed before zipping, so it is there when the archive is too large.
const { archive } = await packFolder(root, {
ignore: await publishIgnore(root, manifest),
maxBytes: MAX_PUBLISH_BYTES,
onFiles: (files) => {
for (const { path, size } of files) console.info(` ${path} (${formatSize(size)})`);
const unpacked = files.reduce((total, { size }) => total + size, 0);
console.info(Messages.PUBLISH_FILES(subject, files.length, formatSize(unpacked)));
},
});

if (getDryRunInput(options)) {
this.successMessage = Messages.PUBLISH_DRY_RUN_SUCCESS;
Expand Down
Loading