mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-12-04 01:44:13 +00:00
@@ -241,6 +241,24 @@ describe('README helpers mirror the registry exactly', () => {
|
||||
expect(missingSections('## What it does')).toEqual(['Screenshots', 'Permissions', 'Setup']);
|
||||
});
|
||||
|
||||
it('still ignores the trailing anchor comment authors hide on a heading', () => {
|
||||
const md = '## What it does <!-- #what -->\n## Screenshots<!--x-->\n##\tPermissions \n## Setup <!-- unterminated';
|
||||
expect(missingSections(md)).toEqual([]);
|
||||
// A heading that is nothing but a comment names no section.
|
||||
expect(missingSections('# <!-- only -->')).toEqual(['What it does', 'Screenshots', 'Permissions', 'Setup']);
|
||||
});
|
||||
|
||||
it('does not stall on a heading padded with spaces', () => {
|
||||
// The old `(.+?)\s*(?:<!--.*)?$` was quadratic: ~12s at 80k spaces, ~75s at 200k.
|
||||
// READMEs reach this gate from the registry's submission CI, so the padding is
|
||||
// attacker-supplied. The bound is 1000x the real cost, so it fails on the shape
|
||||
// of the regression, not on a slow machine.
|
||||
const md = `## What it does${' '.repeat(200_000)}x\n## Screenshots\n## Permissions\n## Setup`;
|
||||
const started = performance.now();
|
||||
expect(missingSections(md)).toEqual([]);
|
||||
expect(performance.now() - started).toBeLessThan(1000);
|
||||
});
|
||||
|
||||
it('ignores data: URIs when looking for a screenshot, like the registry does', () => {
|
||||
expect(images('')).toEqual([]);
|
||||
expect(images('<img src="shot.png">')).toEqual(['shot.png']);
|
||||
|
||||
@@ -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();
|
||||
});
|
||||
});
|
||||
@@ -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);
|
||||
});
|
||||
});
|
||||
@@ -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)',
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -1,5 +1,7 @@
|
||||
/**
|
||||
* The SDK hand-mirrors two things the server owns: the hook→permission map, and the
|
||||
* The hook->permission map is no longer hand-mirrored: gen-plugin-facts.ts generates
|
||||
* src/generated/host-facts.ts from the server's protocol/envelope.ts, and that
|
||||
* generator's --check mode is a CI gate. What is still hand-vendored here is the
|
||||
* pure egress-policy helpers. trek-plugin-sdk ships standalone and cannot import across
|
||||
* the package boundary, so the copies are real copies — and a silent drift here is the
|
||||
* worst possible bug in this module: `dev` would confidently green-light a plugin that
|
||||
@@ -13,26 +15,33 @@ 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, 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');
|
||||
const supervisor = path.join(serverPlugins, 'supervisor/plugin-supervisor.ts');
|
||||
const envelopeFile = path.join(serverPlugins, 'protocol/envelope.ts');
|
||||
const serverEgress = path.join(serverPlugins, 'runtime/egress-policy.ts');
|
||||
const inMonorepo = fs.existsSync(supervisor) && fs.existsSync(serverEgress);
|
||||
const inMonorepo = fs.existsSync(envelopeFile) && fs.existsSync(serverEgress);
|
||||
const hostFrame = path.resolve(here, '../../client/src/components/Plugins/PluginFrame.tsx');
|
||||
|
||||
describe.skipIf(!inMonorepo)('parity with the host', () => {
|
||||
it('HOOK_PERMISSION matches the supervisor\'s map exactly', () => {
|
||||
const src = fs.readFileSync(supervisor, 'utf8');
|
||||
const block = src.match(/const HOOK_PERMISSION[^{]*\{([\s\S]*?)\n\};/);
|
||||
expect(block, 'could not find HOOK_PERMISSION in plugin-supervisor.ts').toBeTruthy();
|
||||
it("the generated host facts match the server's envelope.ts", () => {
|
||||
// Not a regex scrape any more: server/scripts/gen-plugin-facts.ts imports envelope.ts
|
||||
// and writes src/generated/host-facts.ts, and its --check mode is a CI gate. This
|
||||
// asserts the checked-in artefact is the one the host would produce, so a standalone
|
||||
// publish (which has no server present) still ships the right list.
|
||||
//
|
||||
// Compared as whole maps, both ways round: asserting the artefact merely CONTAINS
|
||||
// each entry passed when the host grew a hook the artefact never learned about,
|
||||
// which is the drift that actually ships a wrong permission list.
|
||||
const envelope = fs.readFileSync(envelopeFile, 'utf8');
|
||||
const block = envelope.match(/HOOK_PERMISSION[^{]*\{([\s\S]*?)\n\}/);
|
||||
expect(block, 'HOOK_PERMISSION not found in envelope.ts').toBeTruthy();
|
||||
const theirs: Record<string, string> = {};
|
||||
for (const m of block![1].matchAll(/^\s*(\w+):\s*'([^']+)'/gm)) theirs[m[1]] = m[2];
|
||||
|
||||
const host: Record<string, string> = {};
|
||||
for (const [, key, perm] of block![1].matchAll(/^\s*(\w+):\s*'([^']+)'/gm)) host[key] = perm;
|
||||
|
||||
// Both directions: a hook the host gates that we don't know about means dev fires it
|
||||
// when TREK never would; one we gate that the host doesn't means dev refuses for nothing.
|
||||
expect(Object.keys(host).length).toBeGreaterThan(0);
|
||||
expect(HOOK_PERMISSION).toEqual(host);
|
||||
expect(theirs).toEqual({ ...HOOK_PERMISSION });
|
||||
expect(Object.keys(HOOK_PERMISSION).length).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
it('the vendored egress-policy helpers are byte-identical to the server\'s', () => {
|
||||
@@ -52,3 +61,38 @@ describe.skipIf(!inMonorepo)('parity with the host', () => {
|
||||
for (const fn of fns) expect(body(ours, fn), `${fn} has drifted from the server`).toBe(body(theirs, fn));
|
||||
});
|
||||
});
|
||||
|
||||
describe.skipIf(!fs.existsSync(hostFrame))('parity with the host frame', () => {
|
||||
it('the session storage contract is one contract in all three copies', () => {
|
||||
// Nothing generates these: the limits are written out by hand in the SDK export
|
||||
// authors import, in the dev preview's inlined host, and in the real frame, because
|
||||
// the SDK ships standalone and cannot import across the package boundary. Bump one
|
||||
// and the preview happily stores what production then rejects.
|
||||
const frame = fs.readFileSync(hostFrame, 'utf8');
|
||||
const devServer = fs.readFileSync(path.resolve(here, '../src/cli/dev.ts'), 'utf8');
|
||||
|
||||
expect(frame).toContain(`const PLUGIN_SESSION_MAX_KEYS = ${PLUGIN_SESSION_MAX_KEYS}`);
|
||||
expect(frame).toContain(`const PLUGIN_SESSION_MAX_KEY_LENGTH = ${PLUGIN_SESSION_MAX_KEY_LENGTH}`);
|
||||
expect(frame).toContain(`const PLUGIN_SESSION_MAX_VALUE_BYTES = ${PLUGIN_SESSION_MAX_VALUE_BYTES}`);
|
||||
expect(devServer).toContain(
|
||||
`SESSION_MAX_KEYS=${PLUGIN_SESSION_MAX_KEYS},SESSION_MAX_KEY_LENGTH=${PLUGIN_SESSION_MAX_KEY_LENGTH},SESSION_MAX_VALUE_BYTES=${PLUGIN_SESSION_MAX_VALUE_BYTES}`,
|
||||
);
|
||||
|
||||
// Same for the codes a plugin branches on — a rename in one copy is a silent
|
||||
// behaviour change for anyone who developed against the other.
|
||||
for (const code of ['SESSION_INVALID_KEY', 'SESSION_INVALID_VALUE', 'SESSION_VALUE_TOO_LARGE', 'SESSION_KEY_LIMIT', 'NO_TRIP_CONTEXT', 'SESSION_STORAGE_ERROR']) {
|
||||
expect(frame, `${code} missing from the host frame`).toContain(`'${code}'`);
|
||||
expect(devServer, `${code} missing from the dev preview`).toContain(`"${code}"`);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
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);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
});
|
||||
@@ -86,6 +86,29 @@ describe('validateManifest', () => {
|
||||
expect(r.manifest?.permissions).toEqual(permissions);
|
||||
});
|
||||
|
||||
it('accepts hook:map-layer-provider, hook:day-schedule-provider, hook:day-tint-provider and geolocation:read', () => {
|
||||
const r = validateManifest({ ...base, permissions: ['hook:map-layer-provider', 'hook:day-schedule-provider', 'hook:day-tint-provider', 'geolocation:read'] });
|
||||
expect(r.errors).toEqual([]);
|
||||
expect(r.ok).toBe(true);
|
||||
});
|
||||
|
||||
it('validates capabilities.routeProfiles and ties it to hook:route-provider', () => {
|
||||
const profiles = [{ id: 'ev', label: 'EV' }];
|
||||
const ok = validateManifest({ ...base, permissions: ['hook:route-provider'], capabilities: { routeProfiles: profiles } });
|
||||
expect(ok.errors).toEqual([]);
|
||||
expect(ok.ok).toBe(true);
|
||||
// profiles without the grant are dead buttons — rejected at validate time
|
||||
expect(validateManifest({ ...base, capabilities: { routeProfiles: profiles } }).ok).toBe(false);
|
||||
// id shape, label cap, count cap, duplicates
|
||||
const bad = (routeProfiles: unknown) => validateManifest({ ...base, permissions: ['hook:route-provider'], capabilities: { routeProfiles } }).ok;
|
||||
expect(bad([{ id: 'EV', label: 'x' }])).toBe(false);
|
||||
expect(bad([{ id: 'ev' }])).toBe(false);
|
||||
expect(bad([{ id: 'ev', label: 'L'.repeat(41) }])).toBe(false);
|
||||
expect(bad([{ id: 'ev', label: 'a' }, { id: 'ev', label: 'b' }])).toBe(false);
|
||||
expect(bad([1, 2, 3, 4].map(i => ({ id: `p${i}`, label: 'x' })))).toBe(false);
|
||||
expect(bad('ev')).toBe(false);
|
||||
});
|
||||
|
||||
it('accepts the read-symmetry + broker permissions (collab, file content, trip create, rates)', () => {
|
||||
const permissions = ['db:read:collab', 'db:create:trips', 'rates:read', 'db:read:files:content'];
|
||||
const r = validateManifest({ ...base, permissions });
|
||||
@@ -108,6 +131,30 @@ describe('validateManifest', () => {
|
||||
});
|
||||
|
||||
describe('createMockHost', () => {
|
||||
it('mocks plugin UI session storage with scope isolation and production limits', async () => {
|
||||
const host = createMockHost({ sessionTripId: 42 });
|
||||
await host.session.set('filters', ['hotel']);
|
||||
await host.session.set('filters', ['flight'], { scope: 'trip' });
|
||||
await expect(host.session.get('filters')).resolves.toEqual(['hotel']);
|
||||
await expect(host.session.get('filters', { scope: 'trip' })).resolves.toEqual(['flight']);
|
||||
|
||||
await expect(host.session.set('x'.repeat(65), true)).rejects.toThrow(/SESSION_INVALID_KEY/);
|
||||
await expect(host.session.set('large', 'x'.repeat(1024))).rejects.toThrow(/SESSION_VALUE_TOO_LARGE/);
|
||||
await expect(host.session.set('x'.repeat(64), 'x'.repeat(1022))).resolves.toBeUndefined();
|
||||
|
||||
await host.session.clear();
|
||||
await host.session.clear({ scope: 'trip' });
|
||||
for (let index = 0; index < 32; index += 1) await host.session.set(`key-${index}`, index);
|
||||
await expect(host.session.set('key-32', 32)).rejects.toThrow(/SESSION_KEY_LIMIT/);
|
||||
await expect(host.session.set('trip-key', true, { scope: 'trip' })).resolves.toBeUndefined();
|
||||
|
||||
});
|
||||
|
||||
it('requires a trip context for trip-scoped mock session storage', async () => {
|
||||
const { session } = createMockHost();
|
||||
await expect(session.get('filters', { scope: 'trip' })).rejects.toThrow(/NO_TRIP_CONTEXT/);
|
||||
});
|
||||
|
||||
it('enforces the granted permission set', async () => {
|
||||
const { ctx } = createMockHost({ grants: ['db:own'] });
|
||||
await expect(ctx.db.migrate('1', 'CREATE TABLE t (x)')).resolves.toEqual({ applied: true });
|
||||
@@ -622,6 +669,21 @@ describe('dev-server SDK injection', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('dev-server preview', () => {
|
||||
// The preview plays the host, so it has to refuse what the host refuses. A preview
|
||||
// that answered trek:geolocation without the grant green-lights a plugin production
|
||||
// then breaks — the one drift direction this package cannot afford.
|
||||
it('gates the geolocation bridge on geolocation:read, like PluginFrame', async () => {
|
||||
const { preview } = await import('../src/cli/dev.js');
|
||||
const without = preview('demo', 'widget', 1, {});
|
||||
expect(without).toContain('var GEO_ALLOWED=false;');
|
||||
expect(without).toContain('if(!GEO_ALLOWED){');
|
||||
expect(without).toContain('error:"forbidden"');
|
||||
|
||||
expect(preview('demo', 'widget', 1, { geoAllowed: true })).toContain('var GEO_ALLOWED=true;');
|
||||
});
|
||||
});
|
||||
|
||||
describe('dev db bind shapes', () => {
|
||||
let tmp: string;
|
||||
beforeEach(() => { tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'devdb-')); });
|
||||
|
||||
@@ -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/);
|
||||
});
|
||||
});
|
||||
@@ -27,6 +27,9 @@ describe('design kit', () => {
|
||||
expect(TREK_THEME_JS).toContain('trek:resize');
|
||||
// Trusts only the real parent window (opaque frame has a 'null' origin).
|
||||
expect(TREK_THEME_JS).toContain('ev.source !== window.parent');
|
||||
// Host-managed tab state uses the same request/response channel.
|
||||
expect(TREK_THEME_JS).toContain("trek:session:get");
|
||||
expect(TREK_THEME_JS).toContain('session: session');
|
||||
});
|
||||
|
||||
it('never contains a closing tag that would break <style>/<script> inlining', () => {
|
||||
@@ -67,3 +70,55 @@ describe('design kit', () => {
|
||||
expect(out.match(/<style data-trek-ui>/g)?.length).toBe(2);
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* Boot the kit bootstrap against a stub window, so the bridge's promise handling can be
|
||||
* exercised without a DOM. `document.readyState` stays 'loading', which parks boot() on
|
||||
* DOMContentLoaded and leaves only the message plumbing live. The stub's postMessage runs
|
||||
* structuredClone first, exactly like the browser's — a value it cannot carry throws.
|
||||
*/
|
||||
function bootBridge() {
|
||||
const sent: Record<string, unknown>[] = [];
|
||||
const parent = { postMessage: (msg: Record<string, unknown>) => { structuredClone(msg); sent.push(msg); } };
|
||||
let onMessage: ((ev: { source: unknown; data: unknown }) => void) | null = null;
|
||||
const win: Record<string, unknown> = {
|
||||
parent,
|
||||
addEventListener: (type: string, cb: (ev: { source: unknown; data: unknown }) => void) => { if (type === 'message') onMessage = cb; },
|
||||
};
|
||||
const docEl = { setAttribute: () => {}, removeAttribute: () => {}, style: { setProperty: () => {} } };
|
||||
const doc = { documentElement: docEl, readyState: 'loading', addEventListener: () => {}, body: null };
|
||||
new Function('window', 'document', TREK_THEME_JS)(win, doc);
|
||||
return {
|
||||
trek: win.trek as {
|
||||
session: { set: (k: string, v: unknown) => Promise<unknown>; get: (k: string) => Promise<unknown> };
|
||||
invoke: (sub: string, opts?: { body?: unknown }) => Promise<unknown>;
|
||||
confirm: (opts: unknown) => Promise<boolean>;
|
||||
},
|
||||
sent,
|
||||
deliver: (data: unknown) => onMessage?.({ source: parent, data }),
|
||||
};
|
||||
}
|
||||
|
||||
describe('bridge requests never hang', () => {
|
||||
it('rejects session.set with a value the frame cannot post, instead of pending forever', async () => {
|
||||
const { trek, sent } = bootBridge();
|
||||
// A function can't be structured-cloned: postMessage throws synchronously and the
|
||||
// request never reaches the host, so the promise has to settle here.
|
||||
await expect(trek.session.set('k', () => 1)).rejects.toMatchObject({ code: 'SESSION_INVALID_VALUE' });
|
||||
expect(sent).toEqual([]);
|
||||
});
|
||||
|
||||
it('rejects invoke with an unpostable body and resolves confirm as declined', async () => {
|
||||
const { trek } = bootBridge();
|
||||
await expect(trek.invoke('/x', { body: { cb: () => 1 } })).rejects.toMatchObject({ code: 'error' });
|
||||
await expect(trek.confirm({ message: 'ok?', title: () => 'x' })).resolves.toBe(false);
|
||||
});
|
||||
|
||||
it('still settles a normal request from the host response', async () => {
|
||||
const { trek, sent, deliver } = bootBridge();
|
||||
const p = trek.session.get('k');
|
||||
expect(sent).toHaveLength(1);
|
||||
deliver({ type: 'trek:response', requestId: sent[0].requestId, data: 'v' });
|
||||
await expect(p).resolves.toBe('v');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -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']);
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user