Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
392 changes: 356 additions & 36 deletions .github/workflows/publish.yml

Large diffs are not rendered by default.

28 changes: 17 additions & 11 deletions docs/RELEASING.md
Original file line number Diff line number Diff line change
Expand Up @@ -38,19 +38,25 @@ The release workflow verifies that the tag:

- is a stable annotated `vX.Y.Z` tag signed by an allowed signer;
- matches the package version;
- points to the checkout and the GitHub release-event commit; and
- points to the GitHub release-event commit; and
- is contained in `origin/main`.

Its preparation job has no OIDC permission. It installs dependencies with
the pinned pnpm, installs the reviewed npm version without dependency
caching, runs the full gate, builds and packs once,
smoke-tests the tarball from a clean consumer, records its SHA-1 and SHA-512
integrity, and uploads the exact prepared artifact.

Only the `npm-publish` job receives `id-token: write`. It installs no
dependencies and does not download pnpm. It invokes the publish helper with
`node`, verifies the prepared manifest and tarball hashes against the
release commit, and publishes that tarball with npm provenance.
The preparation job authenticates the tag in a temporary bare repository
before checkout or dependency installation. It then checks out the immutable
release-event commit without retained credentials, installs dependencies with
the pinned pnpm, installs the reviewed npm bytes, runs the full gate, and
builds and packs once. The packed manifest is checked against the reviewed
source manifest, and the output is sealed as exactly one manifest and one
tarball before upload. A separate job downloads that sealed artifact and
imports it from a clean consumer without OIDC permission.

Only the `npm-publish` job receives `id-token: write`. It performs no checkout,
installs no project dependencies, and does not download pnpm. It authenticates
the tag again in a fresh bare repository, installs the reviewed npm bytes,
downloads the prepared artifact by its upload id, and verifies the preparation
manifest digest, exact two-file inventory, release commit, and tarball SHA-256
and SHA-512. Registry lookup and publication run from a fresh empty directory
with empty npm configuration files and a minimal environment.

## Safe retry

Expand Down
103 changes: 102 additions & 1 deletion packages/audit/src/index.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { createMemoryStore, defineCollection } from "@pegma/storage-core";
import { runInNewContext } from "node:vm";
import { describe, expect, it } from "vitest";

import {
Expand Down Expand Up @@ -98,6 +99,21 @@ const event = (overrides: Partial<AuditEvent> = {}): AuditEvent =>
...overrides,
});

const rawEvent = (overrides: Partial<AuditEvent> = {}): AuditEvent => ({
id: "evt_1",
occurredAt: "2026-07-26T12:00:00.000Z",
actor: { kind: "principal", principalId: "prn_admin" },
action: "account.member.added",
subject: "mem_1",
...overrides,
});

const nullPrototypeDetails = (): AuditDetails => {
const details = Object.create(null) as AuditDetails;
(details as Record<string, string>)["role"] = "support";
return details;
};

describe("the event shape", () => {
it("survives a round trip through a flat record", () => {
const original = event({
Expand Down Expand Up @@ -129,6 +145,89 @@ describe("the event shape", () => {
).toThrow(/details.nested/);
});

it.each([
["null", null],
["array", []],
["string", "support"],
["number", 2],
["boolean", true],
["function", () => undefined],
["symbol", Symbol("detail")],
["date", new Date("2026-07-26T12:00:00.000Z")],
["regular expression", /detail/u],
["map", new Map()],
["set", new Set()],
])(
"rejects a %s details container at every write entry point",
async (_, value) => {
const collection = records();
const candidate = rawEvent({
id: `evt_invalid_${String(_)}`,
details: value as unknown as AuditDetails,
});

expect(() => auditEvent(candidate)).toThrow(
/details must be a plain object/,
);
expect(() => encodeAuditEvent(candidate)).toThrow(
/details must be a plain object/,
);
expect(() => audit.action(candidate)).toThrow(
/details must be a plain object/,
);
await expect(audit.append(collection, candidate)).rejects.toThrow(
/details must be a plain object/,
);
expect(await audit.history(collection, PARTITION)).toEqual([]);
},
);

it("accepts a null-prototype details bag at every write entry point", async () => {
const collection = records();
const direct = rawEvent({
id: "evt_null_prototype_direct",
details: nullPrototypeDetails(),
});
const encoded = encodeAuditEvent(
rawEvent({
id: "evt_null_prototype_encoded",
details: nullPrototypeDetails(),
}),
);

expect(auditEvent(rawEvent({ details: {} })).details).toEqual({});
expect(auditEvent(direct).details).toEqual({ role: "support" });
expect(encoded["auditDetails"]).toBe('{"role":"support"}');
await expect(
collection.transact(PARTITION, [
audit.action(
rawEvent({
id: "evt_null_prototype_action",
details: nullPrototypeDetails(),
}),
),
]),
).resolves.toMatchObject({ committed: true });
await expect(
audit.append(
collection,
rawEvent({
id: "evt_null_prototype_append",
details: nullPrototypeDetails(),
}),
),
).resolves.toMatchObject({ appended: true });
expect(await audit.history(collection, PARTITION)).toHaveLength(2);
});

it("accepts an ordinary details bag from another realm", () => {
const details = runInNewContext('({ role: "support" })') as AuditDetails;

expect(auditEvent(rawEvent({ details })).details).toEqual({
role: "support",
});
});

it("rejects a timestamp only Date.parse would accept", () => {
// `Date.parse` accepts implementation-defined formats, so it cannot be the
// whole check: the value is kept forever exactly as it was submitted, and
Expand Down Expand Up @@ -250,7 +349,9 @@ describe("an audit action inside the caller's transaction", () => {
// action is perfectly valid on its own, and must still not land.
const outcome = await collection.transact(PARTITION, [
{ action: "insert", value: member },
audit.action(event({ id: "evt_orphan" })),
audit.action(
rawEvent({ id: "evt_orphan", details: nullPrototypeDetails() }),
),
]);

expect(outcome).toMatchObject({ committed: false, reason: "exists" });
Expand Down
24 changes: 24 additions & 0 deletions packages/audit/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -224,7 +224,31 @@ function requireSequence(value: number): number {
return value;
}

const OBJECT_CONSTRUCTOR_SOURCE = Function.prototype.toString.call(Object);

function isPlainDetailsContainer(value: unknown): value is AuditDetails {
if (value === null || typeof value !== "object" || Array.isArray(value)) {
return false;
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟠 Null-prototype details bypass for exotic objects (risk)

An attacker who can control the details value can bypass the "details must be a plain object" check by nulling the prototype of a non-plain object.

isPlainDetailsContainer returns true immediately when Object.getPrototypeOf(value) === null without inspecting internal slots or constructor. Object.setPrototypeOf(new Date(), null) or Object.setPrototypeOf(new Map(), null) therefore passes as a plain container, while new Date() and new Map() are correctly rejected. The subsequent Object.keys(details) then sees no enumerable keys, so the exotic is accepted as an empty details bag instead of being rejected, silently losing data and violating the test's intent to reject date/map/set at every write entry point.

Concrete trigger: auditEvent({..., details: Object.setPrototypeOf(new Date('2026-07-26T12:00:00.000Z'), null) as any }) is accepted and encodes to {"auditDetails": "{}"} rather than throwing /details must be a plain object/.

Evidence: packages/audit/src/index.ts:229-247 early if (prototype === null) return true;. Checked current callers in requireDetails and tests in packages/audit/src/index.test.ts:145-170 which only test direct new Date/Map/Set without nulled prototype; no test covers the setPrototypeOf variant.

const prototype = Object.getPrototypeOf(value);
if (prototype === null) return true;
if (
Object.getPrototypeOf(prototype) !== null ||
!Object.prototype.hasOwnProperty.call(prototype, "constructor")
) {
return false;
}
const constructor = (prototype as { constructor: unknown }).constructor;
return (
typeof constructor === "function" &&
Function.prototype.toString.call(constructor) === OBJECT_CONSTRUCTOR_SOURCE
);
}

function requireDetails(details: AuditDetails): AuditDetails {
if (!isPlainDetailsContainer(details)) {
throw new AuditError("details must be a plain object");
}
const copied: Record<string, AuditDetail> = {};
for (const key of Object.keys(details).sort()) {
const value = details[key];
Expand Down
38 changes: 37 additions & 1 deletion scripts/release-packages.d.mts
Original file line number Diff line number Diff line change
Expand Up @@ -22,9 +22,26 @@ export interface ReleaseCommandOptions extends ValidationOptions {
export interface PublicPackageManifest {
readonly name: string;
readonly version: string;
readonly dependencies?: Readonly<Record<string, string>>;
readonly publishConfig?: Readonly<Record<string, unknown>>;
readonly [key: string]: unknown;
}

export interface PreparedReleaseManifest {
readonly schemaVersion: 1;
readonly gitCommit: string;
readonly releaseTag: string | null;
readonly package: {
readonly name: string;
readonly version: string;
readonly tarball: string;
readonly integrity: string;
readonly sha256: string;
readonly shasum: string;
readonly files: readonly { readonly path: string; readonly size: number }[];
};
}

export interface ValidationResult {
readonly root: string;
readonly manifest: PublicPackageManifest;
Expand Down Expand Up @@ -76,6 +93,25 @@ export function findInstallTimeScript(

export function verifyReviewedNpmTarball(bytes: Uint8Array | string): string;

export function validatePackageManifest(
manifest: PublicPackageManifest,
options?: {
readonly label?: string;
readonly expectedName?: string;
readonly expectedVersion?: string;
},
): PublicPackageManifest;

export function comparePackedManifest(
source: PublicPackageManifest,
packed: PublicPackageManifest,
): void;

export function validateReleaseInventory(
directory: string,
expectedTarball: string,
): Promise<void>;

export function parseArguments(
arguments_: readonly string[],
): ReleaseCommandOptions;
Expand All @@ -97,7 +133,7 @@ export function decidePublication(

export function prepareRelease(
options?: ReleaseCommandOptions,
): Promise<{ manifestPath: string; manifest: unknown }>;
): Promise<{ manifestPath: string; manifest: PreparedReleaseManifest }>;

export function publishPreparedRelease(
options?: ReleaseCommandOptions,
Expand Down
Loading
Loading