Fix/plugin audit findings (#2031)

* fix(plugins): enforce manifest apiVersion at install and activation

* test(plugins): exercise the absent-apiVersion default

* feat(plugins): generate the core-event catalog into host-facts

* docs(plugins): explain the packing.listBags write-permission binding

* test(plugins): cover apiVersion upload refusal; tidy docblocks and generator header

* fix(plugin-sdk): validate settings options and oauth like the host

* fix(plugin-sdk): model the full manifest shape and stop dropping fields

* fix(plugin-sdk): drop non-string routeProfiles icons like the host

* docs(plugin-sdk): document host limits, oauth contract, and ignored asUserId

* feat(plugin-sdk): enforce daily budgets and meta quotas in the mock host

* feat(plugin-sdk): expose the generated core-event catalog

* feat(plugin-sdk): scaffold trek range >=3.4.0 <5.0.0 ahead of TREK 4.0

* feat(plugin-sdk): scaffold the oauth broker settings for oauth:client plugins

* chore(plugin-sdk): fix stale mirror docs and the colliding permissions export

* docs(plugin-sdk): add the rate-limit string; restore trek docblock; match host meta sizing

* feat(plugin-sdk): raise the scaffold trek floor to 4.0.0

* docs(wiki): bring the plugin pages in line with the current runtime

* docs: bring the workspace CLAUDE.md guides up to date and make them committable

* feat(plugin-sdk): roll back failed publishes, add unrelease, sync the fork, retro-sign updates

* docs(wiki): document the publish rollback, unrelease, fork sync, and retro-signing

* chore(plugin-sdk): 1.6.0
This commit is contained in:
jubnl
2026-08-24 23:48:36 +02:00
committed by GitHub
parent 4bac447ac8
commit d110b3bb6d
48 changed files with 1895 additions and 169 deletions
+36 -3
View File
@@ -4,7 +4,7 @@ import os from 'node:os';
import path from 'node:path';
import { validateManifest } from '../src/index.js';
import { scaffold } from '../src/cli/create.js';
import { PERMISSION_CATALOG, PERMISSION_FAMILIES, KNOWN_PERMISSIONS, isInteractive, missingArgs } from '../src/cli/ui.js';
import { PERMISSION_CATALOG, PERMISSION_FAMILIES, PICKER_PERMISSIONS, isInteractive, missingArgs } from '../src/cli/ui.js';
// The authoritative set — what the HOST accepts at activation. The picker must match it.
import { KNOWN_PERMISSIONS as MANIFEST_PERMISSIONS } from '../src/manifest.js';
import { resolveMenuChoice, PRIMARY_MENU, ADVANCED_MENU } from '../src/cli/menu.js';
@@ -47,7 +47,7 @@ describe('permission catalog', () => {
// list the host actually honours — so a new TREK permission fails here until `create`
// can offer it.
it('offers every permission the host accepts — no more, no less', () => {
expect([...KNOWN_PERMISSIONS].sort()).toEqual([...MANIFEST_PERMISSIONS].sort());
expect([...PICKER_PERMISSIONS].sort()).toEqual([...MANIFEST_PERMISSIONS].sort());
});
it('describes every permission, and files it in exactly one family', () => {
@@ -57,7 +57,7 @@ describe('permission catalog', () => {
.toHaveLength(1);
}
// No duplicates across families — a permission listed twice would render twice.
expect(new Set(KNOWN_PERMISSIONS).size).toBe(KNOWN_PERMISSIONS.length);
expect(new Set(PICKER_PERMISSIONS).size).toBe(PICKER_PERMISSIONS.length);
});
it('every family is non-empty and described (an empty one is a dead prompt entry)', () => {
@@ -245,3 +245,36 @@ describe('capabilities.notificationChannel validation', () => {
expect(r.errors!.join(' ')).toMatch(/requires the "hook:notification-channel" permission/);
});
});
describe('scaffold oauth:client settings', () => {
let tmp: string;
beforeEach(() => { tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'oauth-')); });
afterEach(() => { fs.rmSync(tmp, { recursive: true, force: true }); });
const OAUTH_KEYS = ['oauth_authorize_url', 'oauth_token_url', 'oauth_scopes', 'oauth_client_id', 'oauth_client_secret'];
it('scaffolds the five instance-scoped broker settings when oauth:client is granted', () => {
scaffold('oauth-plug', 'integration', tmp, { permissions: ['db:own', 'oauth:client'] });
const m = JSON.parse(fs.readFileSync(path.join(tmp, 'oauth-plug', 'trek-plugin.json'), 'utf8'));
const settings = m.settings as Array<{ key: string; secret?: boolean; scope?: string }>;
for (const key of OAUTH_KEYS) {
expect(settings.some((s) => s.key === key), `missing setting "${key}"`).toBe(true);
}
const secret = settings.find((s) => s.key === 'oauth_client_secret')!;
expect(secret.secret).toBe(true);
for (const key of OAUTH_KEYS) {
const s = settings.find((x) => x.key === key)!;
expect(s.scope, `${key}.scope`).toBe('instance');
}
expect(validateManifest(m).ok).toBe(true);
});
it('scaffolds none of the broker settings without oauth:client', () => {
scaffold('plain-oauth-plug', 'integration', tmp, { permissions: ['db:own'] });
const m = JSON.parse(fs.readFileSync(path.join(tmp, 'plain-oauth-plug', 'trek-plugin.json'), 'utf8'));
const settings = (m.settings ?? []) as Array<{ key: string }>;
for (const key of OAUTH_KEYS) {
expect(settings.some((s) => s.key === key), `unexpected setting "${key}"`).toBe(false);
}
});
});
@@ -0,0 +1,44 @@
import { describe, it, expect } from 'vitest';
import { validateManifest } from '../src/manifest.js';
describe('validateManifest normalized output', () => {
it('normalized manifest keeps every recognized field', () => {
const input = {
id: 'my-plugin', name: 'My Plugin', version: '1.0.0', type: 'widget', trek: '>=4.0.0 <5.0.0',
permissions: ['db:own'], operatorEgress: false, icon: 'Bell', author: 'A', description: 'Does things.',
homepage: 'https://example.com', tags: ['fun'], license: 'MIT',
capabilities: { widget: { title: 'W', slot: 'hero' }, provides: ['getState'] },
settings: [{ key: 'mode', scope: 'user', options: ['a', 'b'] }],
actions: [{ key: 'ping', label: 'Ping' }],
};
const r = validateManifest(input);
expect(r.ok).toBe(true);
const m = r.manifest!;
expect(m.capabilities?.widget?.slot).toBe('hero');
expect(m.settings?.[0].options).toEqual(['a', 'b']);
expect(m.actions?.[0]).toEqual({ key: 'ping', label: 'Ping' });
expect(m.icon).toBe('Bell');
expect(m.operatorEgress).toBe(false);
expect(m.nativeModules).toBe(false); // still forced
expect(m.apiVersion).toBe(1); // still defaulted
expect(m.requiredAddons).toEqual([]);
});
it('accepts routeProfiles icon', () => {
const r = validateManifest({
id: 'rt-plug', name: 'R', version: '1.0.0', type: 'integration', trek: '>=4.0.0 <5.0.0',
permissions: ['hook:route-provider'], capabilities: { routeProfiles: [{ id: 'hike', label: 'Hiking', icon: 'Mountain' }] },
});
expect(r.ok).toBe(true);
expect(r.manifest!.capabilities?.routeProfiles?.[0].icon).toBe('Mountain');
});
it('drops a non-string routeProfiles icon instead of rejecting the manifest', () => {
const r = validateManifest({
id: 'rt-plug', name: 'R', version: '1.0.0', type: 'integration', trek: '>=4.0.0 <5.0.0',
permissions: ['hook:route-provider'], capabilities: { routeProfiles: [{ id: 'hike', label: 'Hiking', icon: 42 }] },
});
expect(r.ok).toBe(true);
expect(r.manifest!.capabilities?.routeProfiles?.[0].icon).toBeUndefined();
});
});
+35
View File
@@ -0,0 +1,35 @@
import { describe, it, expect } from 'vitest';
import { validateManifest } from '../src/manifest.js';
const base = () => ({ id: 'my-plugin', name: 'My Plugin', version: '1.0.0', type: 'integration', trek: '>=4.0.0 <5.0.0' });
const withSetting = (extra: object) => ({ ...base(), settings: [{ key: 'mode', ...extra }] });
describe('validateManifest settings[].options / settings[].oauth', () => {
it('accepts string/number option lists', () => {
expect(validateManifest(withSetting({ options: ['a', 'b'] })).ok).toBe(true);
expect(validateManifest(withSetting({ options: [1, 2] })).ok).toBe(true);
});
it('accepts {value,label} options incl. value 0', () => {
expect(validateManifest(withSetting({ options: [{ value: 0, label: 'Zero' }] })).ok).toBe(true);
});
it('rejects a non-array options', () => {
const r = validateManifest(withSetting({ options: 'a,b' }));
expect(r.ok).toBe(false);
expect(r.errors).toContain('settings option list must be an array');
});
it('rejects an option with empty value', () => {
const r = validateManifest(withSetting({ options: [{ value: '', label: 'x' }] }));
expect(r.errors).toContain('settings option must have a non-empty "value"');
});
it('rejects a garbage option entry', () => {
const r = validateManifest(withSetting({ options: [true] }));
expect(r.errors).toContain('invalid settings option true (expected a string or { value, label })');
});
it('rejects a non-object oauth', () => {
expect(validateManifest(withSetting({ oauth: 'x' })).errors).toContain('settings oauth must be an object');
});
it('rejects non-string oauth paths, accepts valid oauth', () => {
expect(validateManifest(withSetting({ oauth: { initPath: 3 } })).errors).toContain('settings oauth.initPath must be a string');
expect(validateManifest(withSetting({ oauth: { initPath: '/oauth/init' } })).ok).toBe(true);
});
});
+134
View File
@@ -0,0 +1,134 @@
import { describe, it, expect } from 'vitest';
import { createMockHost } from '../src/index.js';
/**
* Mock-host fidelity for the two host-mediated daily budgets (ai.complete/extract and
* notify.send, daily-budget.ts) and the ctx.meta quotas (meta.rpc.ts). Error strings
* and check order are copied verbatim from the server so a plugin author sees the
* exact same failure locally that production would give them.
*/
describe('daily budgets', () => {
it('exhausts the AI budget', async () => {
const host = createMockHost({ grants: ['ai:invoke'], actingUserId: 1, aiPerDay: 2 });
await host.ctx.ai.complete('hi');
await host.ctx.ai.complete('hi');
await expect(host.ctx.ai.complete('hi')).rejects.toThrow('daily AI budget exhausted (resets at UTC midnight)');
});
it('ai.extract shares the same per-host AI budget as ai.complete', async () => {
const host = createMockHost({ grants: ['ai:invoke'], actingUserId: 1, aiPerDay: 1 });
await host.ctx.ai.complete('hi');
await expect(host.ctx.ai.extract('text', {})).rejects.toThrow('daily AI budget exhausted (resets at UTC midnight)');
});
it('aiPerDay: 0 disables the broker — the first call fails', async () => {
const host = createMockHost({ grants: ['ai:invoke'], actingUserId: 1, aiPerDay: 0 });
await expect(host.ctx.ai.complete('hi')).rejects.toThrow('daily AI budget exhausted (resets at UTC midnight)');
});
it('defaults to 200/day for ai, far above what a normal test suite calls', async () => {
const host = createMockHost({ grants: ['ai:invoke'], actingUserId: 1 });
for (let i = 0; i < 200; i++) await host.ctx.ai.complete('hi');
await expect(host.ctx.ai.complete('hi')).rejects.toThrow('daily AI budget exhausted (resets at UTC midnight)');
});
it('exhausts the notify budget', async () => {
const host = createMockHost({
grants: ['notify:send'],
actingUserId: 1,
trips: { 1: { members: [1] } },
notifyPerDay: 1,
});
await host.ctx.notify.send({ title: 't', body: 'b', scope: 'user', targetId: 1 });
await expect(host.ctx.notify.send({ title: 't', body: 'b', scope: 'user', targetId: 1 })).rejects.toThrow(
'daily notification budget exhausted (resets at UTC midnight)',
);
});
it('notifyPerDay: 0 disables the broker — the first call fails', async () => {
const host = createMockHost({
grants: ['notify:send'],
actingUserId: 1,
trips: { 1: { members: [1] } },
notifyPerDay: 0,
});
await expect(host.ctx.notify.send({ title: 't', body: 'b', scope: 'user', targetId: 1 })).rejects.toThrow(
'daily notification budget exhausted (resets at UTC midnight)',
);
});
it('defaults to 100/day for notify, far above what a normal test suite calls', async () => {
const host = createMockHost({ grants: ['notify:send'], actingUserId: 1, trips: { 1: { members: [1] } } });
for (let i = 0; i < 100; i++) await host.ctx.notify.send({ title: 't', body: 'b', scope: 'user', targetId: 1 });
await expect(host.ctx.notify.send({ title: 't', body: 'b', scope: 'user', targetId: 1 })).rejects.toThrow(
'daily notification budget exhausted (resets at UTC midnight)',
);
});
});
describe('ctx.meta quotas', () => {
const fixture = () =>
createMockHost({ grants: ['db:meta'], actingUserId: 1, trips: { 1: { members: [1] } } });
it('meta value quota: 65536 bytes passes, 65537 rejects', async () => {
const { ctx } = fixture();
// Size the payload via Buffer.byteLength(JSON.stringify(v)), same as the server's
// notion of "serialized JSON bytes" — a bare string serializes with 2 quote bytes,
// so budget those into the repeat count.
const okValue = 'x'.repeat(65536 - 2);
expect(Buffer.byteLength(JSON.stringify(okValue), 'utf8')).toBe(65536);
await expect(ctx.meta.set('trip', 1, 'k', okValue)).resolves.toEqual({ key: 'k', value: okValue });
const tooBig = 'x'.repeat(65537 - 2);
expect(Buffer.byteLength(JSON.stringify(tooBig), 'utf8')).toBe(65537);
await expect(ctx.meta.set('trip', 1, 'k2', tooBig)).rejects.toThrow('metadata value too large (>65536 bytes)');
});
it('meta key length: 256 chars passes, 257 rejects', async () => {
const { ctx } = fixture();
const okKey = 'k'.repeat(256);
await expect(ctx.meta.set('trip', 1, okKey, 'v')).resolves.toEqual({ key: okKey, value: 'v' });
const tooLongKey = 'k'.repeat(257);
await expect(ctx.meta.set('trip', 1, tooLongKey, 'v')).rejects.toThrow('metadata key too long (>256 chars)');
});
it('meta key count: 100 keys per (plugin, entity) passes, the 101st rejects', async () => {
const { ctx } = fixture();
for (let i = 0; i < 100; i++) {
await ctx.meta.set('trip', 1, `key-${i}`, i);
}
await expect(ctx.meta.set('trip', 1, 'key-100', 100)).rejects.toThrow(
'too many metadata keys on this trip (max 100)',
);
});
it('overwriting an existing key never counts against the 100-key cap', async () => {
const { ctx } = fixture();
for (let i = 0; i < 100; i++) {
await ctx.meta.set('trip', 1, `key-${i}`, i);
}
// The entity already has 100 keys; updating one of them must still succeed.
await expect(ctx.meta.set('trip', 1, 'key-0', 'updated')).resolves.toEqual({ key: 'key-0', value: 'updated' });
});
it('checks in server order: key length before value size before key count', async () => {
const { ctx } = fixture();
// A key that is simultaneously too long AND paired with an oversized value must
// fail on the key-length check first.
const tooLongKey = 'k'.repeat(257);
const tooBigValue = 'x'.repeat(70000);
await expect(ctx.meta.set('trip', 1, tooLongKey, tooBigValue)).rejects.toThrow('metadata key too long (>256 chars)');
// Fill the entity to the cap, then a value that is ALSO too large must fail on
// the value-size check (raised before the key-count check ever runs).
const full = fixture();
for (let i = 0; i < 100; i++) {
await full.ctx.meta.set('trip', 1, `key-${i}`, i);
}
await expect(full.ctx.meta.set('trip', 1, 'new-key', tooBigValue)).rejects.toThrow(
'metadata value too large (>65536 bytes)',
);
});
});
+11 -1
View File
@@ -15,7 +15,7 @@ import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { HOOK_PERMISSION } from '../src/permissions.js';
import { PLUGIN_SESSION_MAX_KEYS, PLUGIN_SESSION_MAX_KEY_LENGTH, PLUGIN_SESSION_MAX_VALUE_BYTES } from '../src/index.js';
import { PLUGIN_SESSION_MAX_KEYS, PLUGIN_SESSION_MAX_KEY_LENGTH, PLUGIN_SESSION_MAX_VALUE_BYTES, EVENT_FAMILIES, EVENT_SNAPSHOT_GRANT, KNOWN_PERMISSIONS } from '../src/index.js';
const here = path.dirname(fileURLToPath(import.meta.url));
const serverPlugins = path.resolve(here, '../../server/src/nest/plugins');
@@ -86,3 +86,13 @@ describe.skipIf(!fs.existsSync(hostFrame))('parity with the host frame', () => {
}
});
});
describe.skipIf(!inMonorepo)('core event catalog', () => {
it('event snapshot grants are known read permissions on known families', () => {
expect(EVENT_FAMILIES.length).toBeGreaterThan(0);
for (const [family, perm] of Object.entries(EVENT_SNAPSHOT_GRANT)) {
expect(EVENT_FAMILIES).toContain(family);
expect(KNOWN_PERMISSIONS).toContain(perm);
}
});
});
+128 -2
View File
@@ -6,6 +6,11 @@ import path from 'node:path';
// publish shells out to git + gh; drive those from here so we can assert what it WOULD run.
const calls: Array<{ bin: string; args: string[] }> = [];
let releaseExistsOnRemote = false;
/** The commit the local tag points at; null = no local tag. `git tag` mutates it like git would. */
let localTagSha: string | null = null;
let remoteTagOnOrigin = false;
let failPrCreate = false;
const HEAD_SHA = 'headfeedheadfeedheadfeedheadfeedheadfeed';
vi.mock('node:child_process', () => ({
execFileSync: (bin: string, args: string[]) => {
@@ -14,8 +19,24 @@ vi.mock('node:child_process', () => ({
if (!releaseExistsOnRemote) throw new Error('release not found');
return Buffer.from('');
}
// `git rev-parse <tag>^{commit}` — pretend the tag does not exist yet.
if (bin === 'git' && args.includes('rev-parse')) throw new Error('unknown revision');
if (bin === 'gh' && args[0] === 'pr' && args[1] === 'create' && failPrCreate) throw new Error('pr create exploded');
if (bin === 'gh' && args[0] === 'api') return Buffer.from('someone');
if (bin === 'git' && args.includes('ls-remote')) {
return Buffer.from(remoteTagOnOrigin ? `${HEAD_SHA}\trefs/tags/v1.0.0` : '');
}
if (bin === 'git' && args.includes('tag')) {
// Mirror git's behaviour so later rev-parses see what the run did.
const i = args.indexOf('tag');
if (args[i + 1] === '-d') localTagSha = null;
else localTagSha = HEAD_SHA; // `git tag <t>` and `git tag -f <t>` both land on HEAD
return Buffer.from('');
}
if (bin === 'git' && args.includes('rev-parse')) {
const target = args[args.indexOf('rev-parse') + 1];
if (target === 'HEAD') return Buffer.from(HEAD_SHA);
if (localTagSha === null) throw new Error('unknown revision');
return Buffer.from(localTagSha);
}
return Buffer.from('');
},
}));
@@ -24,6 +45,12 @@ const { publishPlugin } = await import('../src/cli/publish.js');
const { scaffold } = await import('../src/cli/create.js');
const { makePublishable } = await import('./helpers.js');
beforeEach(() => {
localTagSha = null;
remoteTagOnOrigin = false;
failPrCreate = false;
});
describe('publish — a released artifact is immutable', () => {
let tmp: string;
let dir: string;
@@ -139,6 +166,105 @@ describe('publish — the local gates run before anything is cut', () => {
* cut at step 3 — so the author learned it with their tag already burned, for a fact that was
* knowable before a single byte was packed. The check belongs in step 1, and this pins it there.
*/
/**
* The cleanup half of the immutability story. Step 3 creates a local tag, pushes it, and cuts
* the release; when step 4/5 then failed, all three were stranded and the author had to delete
* them by hand before re-running. A failed publish now rolls back exactly what IT created —
* and only that: anything that existed before the run (a merged release, a pre-pushed tag) is
* never touched.
*/
describe('publish — a failed run rolls back what it created', () => {
let tmp: string;
let dir: string;
beforeEach(() => {
calls.length = 0;
releaseExistsOnRemote = false;
tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'publish-rollback-'));
scaffold('rollback-plug', 'integration', tmp);
dir = path.join(tmp, 'rollback-plug');
makePublishable(dir);
});
afterEach(() => { fs.rmSync(tmp, { recursive: true, force: true }); });
const run = (opts: { force?: boolean; keepRelease?: boolean } = {}) => publishPlugin({
dir, repo: 'someone/trek-plugin-rollback-plug', tag: 'v1.0.0',
now: '2026-01-01T00:00:00Z', skipPreflight: true, log: () => {}, ...opts,
});
it('deletes the release, remote tag, and local tag this run created', async () => {
failPrCreate = true;
await expect(run()).rejects.toThrow(/rolled back/i);
expect(calls.some((c) => c.bin === 'gh' && c.args[0] === 'release' && c.args[1] === 'delete' && c.args.includes('v1.0.0'))).toBe(true);
expect(calls.some((c) => c.bin === 'git' && c.args.includes(':refs/tags/v1.0.0'))).toBe(true);
expect(calls.some((c) => c.bin === 'git' && c.args.includes('tag') && c.args.includes('-d'))).toBe(true);
});
it('--keep-release leaves everything in place and prints the manual cleanup', async () => {
failPrCreate = true;
await expect(run({ keepRelease: true })).rejects.toThrow(/gh release delete/);
expect(calls.some((c) => c.bin === 'gh' && c.args[1] === 'delete')).toBe(false);
expect(calls.some((c) => c.args.includes(':refs/tags/v1.0.0'))).toBe(false);
});
it('never deletes a release or remote tag that existed BEFORE the run', async () => {
releaseExistsOnRemote = true;
remoteTagOnOrigin = true;
failPrCreate = true;
await run({ force: true }).catch(() => {});
expect(calls.some((c) => c.bin === 'gh' && c.args[1] === 'delete')).toBe(false);
expect(calls.some((c) => c.args.includes(':refs/tags/v1.0.0'))).toBe(false);
// the local tag WAS created by this run, so that one goes
expect(calls.some((c) => c.bin === 'git' && c.args.includes('tag') && c.args.includes('-d'))).toBe(true);
});
});
/**
* The stale-tag trap: a failed publish leaves a tag; the author commits a fix and re-runs; the
* old flow silently reused the stale tag and released the UNFIXED code. A tag that does not
* point at HEAD and has no release is debris — move it. One that HAS a release is immutable.
*/
describe('publish — a stale tag from a failed run is moved, not reused', () => {
let tmp: string;
let dir: string;
beforeEach(() => {
calls.length = 0;
releaseExistsOnRemote = false;
tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'publish-stale-'));
scaffold('stale-plug', 'integration', tmp);
dir = path.join(tmp, 'stale-plug');
makePublishable(dir);
});
afterEach(() => { fs.rmSync(tmp, { recursive: true, force: true }); });
const run = () => publishPlugin({
dir, repo: 'someone/trek-plugin-stale-plug', tag: 'v1.0.0',
now: '2026-01-01T00:00:00Z', skipPreflight: true, log: () => {},
});
it('re-points a debris tag (no release) at HEAD and force-pushes it', async () => {
localTagSha = 'stalestalestalestalestalestalestalestale';
await run().catch(() => {});
expect(calls.some((c) => c.bin === 'git' && c.args.includes('tag') && c.args.includes('-f'))).toBe(true);
const push = calls.find((c) => c.bin === 'git' && c.args.includes('push') && c.args.includes('v1.0.0'));
expect(push?.args).toContain('--force');
});
it('refuses a mismatched tag whose release already exists', async () => {
localTagSha = 'stalestalestalestalestalestalestalestale';
releaseExistsOnRemote = true;
await expect(run()).rejects.toThrow(/points at/i);
expect(calls.some((c) => c.bin === 'git' && c.args.includes('-f'))).toBe(false);
});
it('reuses a tag already on HEAD without touching it', async () => {
localTagSha = HEAD_SHA;
await run().catch(() => {});
expect(calls.some((c) => c.bin === 'git' && c.args.includes('tag') && !c.args.includes('-d'))).toBe(false);
});
});
describe('publish — a signed plugin cannot quietly go unsigned', () => {
let tmp: string;
let dir: string;
+77
View File
@@ -0,0 +1,77 @@
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { createHash } from 'node:crypto';
import { generateKeypair, loadPrivateKey, publicKeyBase64, verifyArtifact } from '../src/cli/sign.js';
import { retroSignVersions } from '../src/cli/retro-sign.js';
const V1_BYTES = Buffer.from('the exact bytes of the v1.0.0 release asset');
const sha = (b: Buffer) => createHash('sha256').update(b).digest('hex');
describe('retro-sign — first signed update signs the older versions too', () => {
let tmp: string;
let keyPath: string;
let publicKey: string;
beforeEach(() => {
tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'retro-sign-'));
keyPath = path.join(tmp, 'signing.key');
publicKey = generateKeypair(keyPath).publicKey;
vi.stubGlobal('fetch', async (url: string) => {
if (String(url).includes('v1.0.0')) return { ok: true, arrayBuffer: async () => V1_BYTES } as unknown as Response;
return { ok: false, status: 404 } as Response;
});
});
afterEach(() => {
fs.rmSync(tmp, { recursive: true, force: true });
vi.unstubAllGlobals();
});
const entry = (v1: Partial<{ sha256: string; signature: string }> = {}) => ({
id: 'retro-plug',
authorPublicKey: publicKey,
versions: [
{ version: '1.1.0', downloadUrl: 'https://github.com/x/y/releases/download/v1.1.0/plugin.zip', sha256: 'deadbeef', signature: 'already-signed' },
{ version: '1.0.0', downloadUrl: 'https://github.com/x/y/releases/download/v1.0.0/plugin.zip', sha256: sha(V1_BYTES), ...v1 },
],
});
it('downloads, verifies, and signs each unsigned older version', async () => {
const e = entry();
const signed = await retroSignVersions(e, keyPath, () => {});
expect(signed).toEqual(['1.0.0']);
const sig = e.versions[1].signature!;
expect(verifyArtifact(V1_BYTES, sig, publicKey)).toBe(true);
expect(e.versions[0].signature).toBe('already-signed'); // untouched
});
it('REFUSES when the downloaded bytes no longer hash to the pinned sha256', async () => {
const e = entry({ sha256: 'not-the-real-hash' });
await expect(retroSignVersions(e, keyPath, () => {})).rejects.toThrow(/1\.0\.0.*sha256/is);
expect(e.versions[1].signature).toBeUndefined();
});
it('REFUSES a key that does not match the entry authorPublicKey', async () => {
const otherKey = path.join(tmp, 'other.key');
generateKeypair(otherKey);
await expect(retroSignVersions(entry(), otherKey, () => {})).rejects.toThrow(/key/i);
});
it('is a no-op for an unsigned entry or one with nothing to sign', async () => {
const unsignedEntry = { id: 'x', versions: [{ version: '1.0.0', downloadUrl: 'u', sha256: 'h' }] };
expect(await retroSignVersions(unsignedEntry, keyPath, () => {})).toEqual([]);
const fullySigned = entry({ signature: 'sig' });
expect(await retroSignVersions(fullySigned, keyPath, () => {})).toEqual([]);
});
it('names every version whose artifact could not be fetched', async () => {
const e = entry();
e.versions[1].downloadUrl = 'https://github.com/x/y/releases/download/v9.9.9/plugin.zip'; // 404s
await expect(retroSignVersions(e, keyPath, () => {})).rejects.toThrow(/1\.0\.0/);
});
it('key sanity: publicKeyBase64 round-trips through loadPrivateKey', () => {
expect(publicKeyBase64(loadPrivateKey(keyPath))).toBe(publicKey);
});
});
+110
View File
@@ -0,0 +1,110 @@
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { createHash } from 'node:crypto';
const calls: Array<{ bin: string; args: string[] }> = [];
let failSync = false;
/** Seeded into the fake fork clone as the plugin's existing registry entry (update case). */
let existingEntry: unknown = null;
let lastCloneDir = '';
// submit's git()/gh() run execFileSync with encoding:'utf8', which returns STRINGS — the
// mock must too, or `.trim()` explodes on a Buffer.
vi.mock('node:child_process', () => ({
execFileSync: (bin: string, args: string[]) => {
calls.push({ bin, args });
if (bin === 'gh' && args[0] === 'api') return 'someone';
if (bin === 'gh' && args[0] === 'repo' && args[1] === 'sync' && failSync) throw new Error('fork has diverged');
if (bin === 'gh' && args[0] === 'repo' && args[1] === 'clone') {
lastCloneDir = args[3];
if (existingEntry !== null) {
const p = path.join(lastCloneDir, 'registry', 'plugins', `${(existingEntry as { id: string }).id}.json`);
fs.mkdirSync(path.dirname(p), { recursive: true });
fs.writeFileSync(p, JSON.stringify(existingEntry, null, 2));
}
return '';
}
if (bin === 'gh' && args[0] === 'pr' && args[1] === 'create') return 'https://github.com/liketrek/TREK-Plugins/pull/999';
return '';
},
}));
const { submitEntry } = await import('../src/cli/submit.js');
const { generateKeypair } = await import('../src/cli/sign.js');
const { verifyArtifact } = await import('../src/cli/sign.js');
const V1_BYTES = Buffer.from('old release asset bytes');
const sha = (b: Buffer) => createHash('sha256').update(b).digest('hex');
describe('submit — fork sync and retro-signing', () => {
let tmp: string;
let keyPath: string;
let publicKey: string;
beforeEach(() => {
calls.length = 0;
failSync = false;
existingEntry = null;
lastCloneDir = '';
tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'submit-'));
keyPath = path.join(tmp, 'signing.key');
publicKey = generateKeypair(keyPath).publicKey;
vi.stubGlobal('fetch', async (url: string) => {
if (String(url).includes('v1.0.0')) return { ok: true, arrayBuffer: async () => V1_BYTES } as unknown as Response;
return { ok: false, status: 404 } as Response;
});
});
afterEach(() => {
fs.rmSync(tmp, { recursive: true, force: true });
vi.unstubAllGlobals();
});
const freshEntry = (signed = false) => ({
id: 'sync-plug',
name: 'Sync Plug',
...(signed ? { authorPublicKey: publicKey } : {}),
versions: [{
version: '1.1.0', downloadUrl: 'https://github.com/x/y/releases/download/v1.1.0/plugin.zip',
sha256: 'deadbeef', ...(signed ? { signature: 'fresh-sig' } : {}),
}],
});
it('fast-forwards the fork from the registry before branching', async () => {
await submitEntry(freshEntry(), {});
const sync = calls.find((c) => c.bin === 'gh' && c.args[0] === 'repo' && c.args[1] === 'sync');
expect(sync?.args).toContain('someone/TREK-Plugins');
expect(sync?.args).toContain('--source');
expect(sync?.args).toContain('liketrek/TREK-Plugins');
});
it('a diverged fork warns but does not stop the submit', async () => {
failSync = true;
const { prUrl } = await submitEntry(freshEntry(), {});
expect(prUrl).toContain('/pull/999');
});
it('retro-signs unsigned older versions on the first signed update', async () => {
existingEntry = {
id: 'sync-plug', name: 'Sync Plug',
versions: [{ version: '1.0.0', downloadUrl: 'https://github.com/x/y/releases/download/v1.0.0/plugin.zip', sha256: sha(V1_BYTES) }],
};
await submitEntry(freshEntry(true), { signKeyPath: keyPath, keep: true });
const written = JSON.parse(fs.readFileSync(path.join(lastCloneDir, 'registry', 'plugins', 'sync-plug.json'), 'utf8')) as {
versions: Array<{ version: string; signature?: string }>;
};
const v1 = written.versions.find((v) => v.version === '1.0.0')!;
expect(v1.signature).toBeDefined();
expect(verifyArtifact(V1_BYTES, v1.signature!, publicKey)).toBe(true);
fs.rmSync(lastCloneDir, { recursive: true, force: true });
});
it('refuses a first signed update when no key is available to retro-sign the older versions', async () => {
existingEntry = {
id: 'sync-plug', name: 'Sync Plug',
versions: [{ version: '1.0.0', downloadUrl: 'https://github.com/x/y/releases/download/v1.0.0/plugin.zip', sha256: sha(V1_BYTES) }],
};
await expect(submitEntry(freshEntry(true), {})).rejects.toThrow(/--sign/);
});
});
+99
View File
@@ -0,0 +1,99 @@
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
// unrelease shells out to git + gh; drive those from here so we can assert what it deletes.
const calls: Array<{ bin: string; args: string[] }> = [];
let releaseExistsOnRemote = false;
let remoteTagOnOrigin = false;
let localTagExists = false;
vi.mock('node:child_process', () => ({
execFileSync: (bin: string, args: string[]) => {
calls.push({ bin, args });
if (bin === 'gh' && args[0] === 'release' && args[1] === 'view') {
if (!releaseExistsOnRemote) throw new Error('release not found');
return Buffer.from('');
}
if (bin === 'git' && args.includes('ls-remote')) {
return Buffer.from(remoteTagOnOrigin ? 'abc\trefs/tags/v1.0.0' : '');
}
if (bin === 'git' && args.includes('rev-parse')) {
if (!localTagExists) throw new Error('unknown revision');
return Buffer.from('abc');
}
return Buffer.from('');
},
}));
const { unrelease } = await import('../src/cli/unrelease.js');
/** The published registry index the immutability guard consults. */
let indexBody: unknown = { plugins: [] };
let indexFails = false;
describe('unrelease — delete a stranded tag + release safely', () => {
let tmp: string;
beforeEach(() => {
calls.length = 0;
releaseExistsOnRemote = false;
remoteTagOnOrigin = false;
localTagExists = false;
indexBody = { plugins: [] };
indexFails = false;
tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'unrelease-'));
fs.writeFileSync(path.join(tmp, 'trek-plugin.json'), JSON.stringify({ id: 'doomed-plug', version: '1.0.0' }));
vi.stubGlobal('fetch', async () => {
if (indexFails) throw new Error('offline');
return { ok: true, json: async () => indexBody } as Response;
});
});
afterEach(() => {
fs.rmSync(tmp, { recursive: true, force: true });
vi.unstubAllGlobals();
});
const run = (yes?: boolean) => unrelease({
dir: tmp, tag: 'v1.0.0', repo: 'someone/trek-plugin-doomed-plug', yes, log: () => {},
});
it('REFUSES when that version is published in the registry — those artifacts are immutable', async () => {
indexBody = { plugins: [{ id: 'doomed-plug', versions: [{ version: '1.0.0' }] }] };
releaseExistsOnRemote = true;
await expect(run(true)).rejects.toThrow(/published in the registry/i);
expect(calls.some((c) => c.bin === 'gh' && c.args[1] === 'delete')).toBe(false);
});
it('deletes the release, remote tag, and local tag when they exist', async () => {
releaseExistsOnRemote = true;
remoteTagOnOrigin = true;
localTagExists = true;
const { deleted } = await run();
expect(deleted).toEqual(['release', 'remote tag', 'local tag']);
expect(calls.some((c) => c.bin === 'gh' && c.args[0] === 'release' && c.args[1] === 'delete' && c.args.includes('--yes'))).toBe(true);
expect(calls.some((c) => c.bin === 'git' && c.args.includes(':refs/tags/v1.0.0'))).toBe(true);
expect(calls.some((c) => c.bin === 'git' && c.args.includes('tag') && c.args.includes('-d'))).toBe(true);
});
it('reports what was already absent without failing', async () => {
const { deleted } = await run();
expect(deleted).toEqual([]);
});
it('when the registry cannot be checked, refuses without --yes and proceeds with it', async () => {
indexFails = true;
localTagExists = true;
await expect(run()).rejects.toThrow(/--yes/);
const { deleted } = await run(true);
expect(deleted).toEqual(['local tag']);
});
it('a different published version of the same plugin does not block this tag', async () => {
indexBody = { plugins: [{ id: 'doomed-plug', versions: [{ version: '0.9.0' }] }] };
localTagExists = true;
const { deleted } = await run();
expect(deleted).toEqual(['local tag']);
});
});