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
8 changes: 7 additions & 1 deletion CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,13 @@ in [ecosystem-reporting-validation.md](docs/ecosystem-reporting-validation.md).

Use Node.js `24.21.0` and pnpm `12.6.0`. Configure GitHub Packages authentication as described below, enable Corepack, then run `pnpm install --frozen-lockfile`.

Run `pnpm format`, `pnpm lint`, `pnpm typecheck`, `pnpm schema:check`, `pnpm test`, `pnpm test:coverage`, `pnpm audit`, and `pnpm bundle`. Review contract changes and provider payload fixtures carefully. Update `dist/index.js` with source changes. Use only synthetic fixtures; normal CI must never call real webhooks. PRs should explain contract/security effects and include focused tests.
Run `pnpm format`, `pnpm lint`, `pnpm typecheck`, `pnpm schema:check`, `pnpm test`, `pnpm test:coverage`, `pnpm audit`, and `pnpm bundle`. Review contract changes and provider payload fixtures carefully. Regenerate and commit all `dist` artifacts with source changes. Use only synthetic fixtures; normal CI must never call real webhooks. PRs should explain contract/security effects and include focused tests.

`pnpm bundle:check` builds in a temporary directory and compares the complete
artifact inventory and bytes, including `index.js`, `package.json`, and
`licenses.txt`, against committed `dist`. It fails for missing, obsolete or stale
files and never rewrites committed output. Standalone tests execute the packaged
`index.js` with its actual `package.json`, preserving the Action's module mode.

## GitHub Packages access

Expand Down
72 changes: 66 additions & 6 deletions scripts/check-bundle.mjs
Original file line number Diff line number Diff line change
@@ -1,6 +1,66 @@
import { execFileSync } from 'node:child_process';
import { readFileSync } from 'node:fs';
const before = readFileSync('dist/index.js', 'utf8');
execFileSync('pnpm', ['bundle'], { stdio: 'inherit' });
const after = readFileSync('dist/index.js', 'utf8');
if (before !== after) throw new Error('dist/index.js is stale; run pnpm bundle and commit the result.');
import { spawnSync } from 'node:child_process';
import { mkdtemp, readFile, readdir, rm } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join, resolve } from 'node:path';
import { pathToFileURL } from 'node:url';

async function files(directory, prefix = '') {
const result = [];
for (const entry of await readdir(join(directory, prefix), { withFileTypes: true })) {
const path = join(prefix, entry.name);
if (entry.isDirectory()) result.push(...(await files(directory, path)));
else if (entry.isFile()) result.push(path);
else throw new Error(`Unsupported bundle artifact: ${path}`);
}
return result.sort();
}

function buildBundle(root, output) {
const result = spawnSync(
process.execPath,
[
join(root, 'node_modules/@vercel/ncc/dist/ncc/cli.js'),
'build',
'src/main.ts',
'--minify',
'--license',
'licenses.txt',
'-o',
output,
],
{ cwd: root, stdio: 'inherit' },
);
if (result.error) throw result.error;
if (result.status !== 0) throw new Error(`Bundle generation failed (${result.status ?? result.signal}).`);
}

/** Check every generated artifact without repairing the committed bundle. */
export async function checkBundle({
root = resolve(import.meta.dirname, '..'),
build = (output) => buildBundle(root, output),
} = {}) {
const output = await mkdtemp(join(tmpdir(), 'commercekit-notify-bundle-'));
try {
await build(output);
const generated = await files(output);
for (const required of ['index.js', 'package.json', 'licenses.txt']) {
if (!generated.includes(required)) throw new Error(`Generated bundle is missing ${required}.`);
}
const committed = await files(join(root, 'dist'));
const missing = generated.filter((file) => !committed.includes(file));
const obsolete = committed.filter((file) => !generated.includes(file));
if (missing.length || obsolete.length) {
throw new Error(
`Bundle file inventory differs. Missing: ${missing.join(', ') || 'none'}; obsolete: ${obsolete.join(', ') || 'none'}. Run pnpm bundle and commit dist.`,
);
}
for (const file of generated) {
if (!(await readFile(join(output, file))).equals(await readFile(join(root, 'dist', file))))
throw new Error(`Stale dist/${file}; run pnpm bundle and commit dist.`);
}
} finally {
await rm(output, { recursive: true, force: true });
}
}

if (process.argv[1] && import.meta.url === pathToFileURL(resolve(process.argv[1])).href) await checkBundle();
131 changes: 131 additions & 0 deletions tests/bundle-verification.test.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,131 @@
import { afterEach, describe, expect, it } from 'vitest';
import { spawnSync } from 'node:child_process';
import { copyFile, mkdir, mkdtemp, readFile, rm, stat, writeFile } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { dirname, join } from 'node:path';
import { checkBundle } from '../scripts/check-bundle.mjs';

const roots = [];
const artifacts = {
'index.js': 'export const synthetic = true;\n',
'package.json': '{"type":"module"}\n',
'licenses.txt': 'Synthetic license notice\n',
[join('assets', 'runtime.bin')]: Buffer.from([0, 1, 128, 255]),
};

afterEach(async () => {
await Promise.all(roots.splice(0).map((root) => rm(root, { recursive: true, force: true })));
});

async function writeArtifacts(directory, values = artifacts) {
for (const [file, value] of Object.entries(values)) {
await mkdir(dirname(join(directory, file)), { recursive: true });
await writeFile(join(directory, file), value);
}
}

async function fixture() {
const root = await mkdtemp(join(tmpdir(), 'notify-bundle-verification-'));
roots.push(root);
await writeArtifacts(join(root, 'dist'));
return root;
}

describe('complete committed bundle verification', () => {
it('compares nested binary artifacts and leaves committed files untouched', async () => {
const root = await fixture();
let temporary;
await checkBundle({
root,
build: async (output) => {
temporary = output;
expect(output).not.toBe(join(root, 'dist'));
await writeArtifacts(output);
},
});
await expect(stat(temporary)).rejects.toMatchObject({ code: 'ENOENT' });
for (const [file, value] of Object.entries(artifacts))
expect(await readFile(join(root, 'dist', file))).toEqual(Buffer.from(value));
});

it('rejects license-only drift without repairing the committed license', async () => {
const root = await fixture();
await writeFile(join(root, 'dist/licenses.txt'), 'Obsolete notice');
let temporary;
await expect(
checkBundle({
root,
build: async (output) => {
temporary = output;
await writeArtifacts(output);
},
}),
).rejects.toThrow('Stale dist/licenses.txt');
expect(await readFile(join(root, 'dist/licenses.txt'), 'utf8')).toBe('Obsolete notice');
await expect(stat(temporary)).rejects.toMatchObject({ code: 'ENOENT' });
});

it.each(['index.js', 'package.json', 'licenses.txt'])('rejects missing committed %s', async (file) => {
const root = await fixture();
await rm(join(root, 'dist', file));
await expect(checkBundle({ root, build: writeArtifacts })).rejects.toThrow(`Missing: ${file}`);
});

it.each(['index.js', 'package.json', 'licenses.txt'])(
'rejects incomplete generated output without %s',
async (file) => {
const root = await fixture();
await expect(
checkBundle({
root,
build: (output) =>
writeArtifacts(output, Object.fromEntries(Object.entries(artifacts).filter(([name]) => name !== file))),
}),
).rejects.toThrow(`Generated bundle is missing ${file}`);
},
);

it('rejects obsolete files left in committed output', async () => {
const root = await fixture();
await writeFile(join(root, 'dist/previous.js'), 'obsolete');
await expect(checkBundle({ root, build: writeArtifacts })).rejects.toThrow('obsolete: previous.js');
});

it.each(['package.json', join('assets', 'runtime.bin')])('compares the bytes of %s', async (file) => {
const root = await fixture();
await writeFile(join(root, 'dist', file), 'different');
await expect(checkBundle({ root, build: writeArtifacts })).rejects.toThrow(`Stale dist/${file}`);
});

it('propagates bundle failures and cleans partial output', async () => {
const root = await fixture();
const failure = new Error('Synthetic compiler failure');
let temporary;
await expect(
checkBundle({
root,
build: async (output) => {
temporary = output;
await writeFile(join(output, 'partial.js'), 'partial');
throw failure;
},
}),
).rejects.toBe(failure);
await expect(stat(temporary)).rejects.toMatchObject({ code: 'ENOENT' });
});

it('requires the packaged module mode for the actual JavaScript entry', async () => {
const root = await fixture();
const entry = join(root, 'dist/index.js');
await copyFile(new URL('../dist/index.js', import.meta.url), entry);
await copyFile(new URL('../dist/package.json', import.meta.url), join(root, 'dist/package.json'));
const check = () =>
spawnSync(process.execPath, ['--check', entry], { encoding: 'utf8', maxBuffer: 2 * 1024 * 1024 });
expect(check().status).toBe(0);
await writeFile(join(root, 'dist/package.json'), '{"type":"commonjs"}\n');
const invalid = check();
expect(invalid.error).toBeUndefined();
expect(invalid.status).not.toBe(0);
expect(invalid.stderr).toContain('SyntaxError');
});
});
5 changes: 3 additions & 2 deletions tests/bundle.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,8 @@ async function bundleRun(
? 'https://hooks.slack.com/services/synthetic/fake/private'
: 'https://public.example.test/private/synthetic-hook';
try {
await copyFile(new URL('../dist/index.js', import.meta.url), join(dir, 'index.mjs'));
await copyFile(new URL('../dist/index.js', import.meta.url), join(dir, 'index.js'));
await copyFile(new URL('../dist/package.json', import.meta.url), join(dir, 'package.json'));
await writeFile(join(dir, 'output'), '');
await writeFile(join(dir, 'summary'), '');
if (options.useFile) await writeFile(join(dir, 'event.json'), event);
Expand All @@ -45,7 +46,7 @@ async function bundleRun(
return new Response('', {status: ${options.httpStatus ?? 200}});
};`,
);
const result = spawnSync(process.execPath, ['--import', join(dir, 'preload.mjs'), join(dir, 'index.mjs')], {
const result = spawnSync(process.execPath, ['--import', join(dir, 'preload.mjs'), join(dir, 'index.js')], {
cwd: dir,
env: {
INPUT_PROVIDER: provider,
Expand Down