feat(notifications): let a plugin register a notification channel

TREK's four channels (in-app, email, webhook, ntfy) were a closed set:
notificationService.send() dispatched with four copy-pasted `if` blocks and no
provider abstraction, so a fifth channel meant editing eight files by hand. A
plugin could produce a notification via ctx.notify.send(), but never deliver
one.

A plugin now registers a channel with `hooks.notificationChannel` +
`hook:notification-channel` on a plain `type: 'integration'` — not a new manifest
type, so the TREK-Plugins registry schema and both its CI gates are untouched.

Core refactor
- New channel registry (services/notifications/): email/webhook/ntfy become
  ExternalChannel providers wrapping the EXISTING send functions — no delivery
  logic is rewritten, only relocated. In-app deliberately stays out: it writes
  typed rows with scope/target/callbacks, not a rendered title+body, the same
  line shared/ already draws with i18n/externalNotifications.
- The event text is now rendered once per recipient instead of once per channel.
- The channel set is open: NotifChannel becomes a string, the matrix is
  registry-derived, and the UI columns are server-driven. The DB column was
  already bare TEXT and the Zod contract already a string record — only the
  TypeScript and the two UIs were ever closed.

The hook runs USERLESS. Every other hook is user-initiated, so actingUserId falls
out of the request; a notification is host-initiated for an ARBITRARY recipient,
so ctx.settings.get() would return undefined. The host resolves the recipient's
decrypted scope:'user' settings itself and passes them as an argument. That is
what lets a channel plugin be handed someone's push token WITHOUT being handed
the right to read their trips as them.

Enabling the plugin is the opt-in: a plugin channel is not gated on the admin's
`notification_channels` list. A built-in always exists in code and needs an
explicit switch; a plugin channel only exists because an admin enabled that
plugin. (Nothing could write a `plugin:` id into that CSV anyway, and the admin
toggle rebuilt it from three booleans, silently dropping anything else — so
requiring a second opt-in meant the channel could never be turned on at all.)

Also fixed, found while building this:
- Plugin settings keys were unvalidated, so a field named `__proto__` or
  `constructor` resolved off Object.prototype: a REQUIRED field with such a name
  reported as configured for every user who had configured nothing — enough, for
  a channel, to be dispatched to everyone with no credentials. Keys are now
  constrained at install and the config blob is parsed null-prototype, so it is
  impossible even for an already-installed plugin.
- A `select` field's options were cast straight through, so the obvious
  `["1","5"]` form rendered every dropdown entry BLANK (the client reads
  value/label). Now coerced, and malformed options are rejected.

Also adds: operator-supplied egress hosts (a plugin talking to a self-hosted
service can't name the operator's host at publish time, so an admin adds it
post-install and the runtime re-spawns the child with the widened allow-list —
only for a plugin that DECLARED operatorEgress, and only an admin, never a user);
settings-page actions (a "Test connection" button, user-initiated so
ctx.settings.get() returns the clicking user's own value); and a Gotify-shaped
notification-channel template in the SDK.

Verified end to end against a real Gotify container, not just in tests.
This commit is contained in:
jubnl
2026-07-11 19:26:53 +02:00
parent 2899465dac
commit c9627af239
95 changed files with 4757 additions and 830 deletions
+3 -1
View File
@@ -27,9 +27,11 @@ beforeEach(() => {
db = new Database(':memory:');
db.exec(`
CREATE TABLE plugins (id TEXT PRIMARY KEY, name TEXT, description TEXT, type TEXT, icon TEXT, version TEXT,
api_version INTEGER, min_trek_version TEXT, permissions TEXT, capabilities TEXT DEFAULT '{}', dependencies TEXT DEFAULT '{}', granted_permissions TEXT, status TEXT, config TEXT, updated_at TEXT);
api_version INTEGER, min_trek_version TEXT, permissions TEXT, capabilities TEXT DEFAULT '{}', dependencies TEXT DEFAULT '{}', operator_egress INTEGER DEFAULT 0, granted_permissions TEXT, status TEXT, config TEXT, updated_at TEXT);
CREATE TABLE plugin_settings_fields (plugin_id TEXT, field_key TEXT, label TEXT, input_type TEXT, placeholder TEXT, hint TEXT,
required INTEGER, secret INTEGER, scope TEXT, options TEXT, oauth_config TEXT, sort_order INTEGER);
CREATE TABLE plugin_actions (plugin_id TEXT, action_key TEXT, label TEXT, hint TEXT, danger INTEGER, sort_order INTEGER,
PRIMARY KEY (plugin_id, action_key));
CREATE TABLE plugin_error_log (id INTEGER PRIMARY KEY AUTOINCREMENT, plugin_id TEXT, level TEXT, message TEXT, ts TEXT);`);
});
afterEach(() => {
@@ -141,3 +141,99 @@ describe('parseManifest dependencies', () => {
expect(() => parseManifest({ ...base, pluginDependencies: [{ id: 'koffi', version: '*' }, { id: 'koffi', version: '^1' }] })).toThrow(/duplicate/);
});
});
describe('capabilities.notificationChannel', () => {
const base = {
id: 'my-gotify',
name: 'My Gotify',
version: '1.0.0',
apiVersion: 1,
type: 'integration',
nativeModules: false,
permissions: ['hook:notification-channel', 'http:outbound:gotify.example.com'],
egress: ['gotify.example.com'],
};
it('accepts what the SDK notification-channel template scaffolds', () => {
const m = parseManifest({
...base,
capabilities: { notificationChannel: { title: 'My Gotify' } },
settings: [{ key: 'appToken', label: 'App token', required: true, secret: true, scope: 'user' }],
});
expect(m.capabilities.notificationChannel?.title).toBe('My Gotify');
// scope:'user' + secret is what lets the host hand the decrypted value to the hook.
expect(m.settings[0].scope).toBe('user');
expect(m.settings[0].secret).toBe(true);
});
it('accepts a narrowed event list', () => {
const m = parseManifest({ ...base, capabilities: { notificationChannel: { events: ['trip_invite', 'booking_change'] } } });
expect(m.capabilities.notificationChannel?.events).toEqual(['trip_invite', 'booking_change']);
});
it('rejects an admin-scoped event — a plugin channel can never carry one', () => {
expect(() => parseManifest({ ...base, capabilities: { notificationChannel: { events: ['version_available'] } } }))
.toThrow(/not a plugin-deliverable event/);
});
it('rejects a non-array events field', () => {
expect(() => parseManifest({ ...base, capabilities: { notificationChannel: { events: 'trip_invite' } } }))
.toThrow(ManifestError);
});
});
describe('select field options', () => {
const base = { id: 'sel', name: 'Sel', version: '1.0.0', apiVersion: 1, type: 'integration', nativeModules: false, permissions: [] };
const opts = (options: unknown) => parseManifest({ ...base, settings: [{ key: 'priority', input_type: 'select', scope: 'user', options }] }).settings[0].options;
it('keeps a proper { value, label } list', () => {
expect(opts([{ value: '5', label: 'Normal' }])).toEqual([{ value: '5', label: 'Normal' }]);
});
it('coerces a bare string/number list instead of rendering blank options', () => {
// The obvious thing to write — and it used to be cast straight through, so the
// client read o.value/o.label as undefined and every dropdown entry was EMPTY.
expect(opts(['1', '5'])).toEqual([{ value: '1', label: '1' }, { value: '5', label: '5' }]);
expect(opts([1, 5])).toEqual([{ value: '1', label: '1' }, { value: '5', label: '5' }]);
});
it('defaults a missing label to the value rather than leaving it blank', () => {
expect(opts([{ value: '5' }])).toEqual([{ value: '5', label: '5' }]);
});
it('rejects an option with no value, and a non-array list', () => {
expect(() => opts([{ label: 'Normal' }])).toThrow(/non-empty "value"/);
expect(() => opts([null])).toThrow(ManifestError);
expect(() => opts('nope')).toThrow(/must be an array/);
});
});
describe('settings-page actions', () => {
const base = { id: 'act', name: 'Act', version: '1.0.0', apiVersion: 1, type: 'integration', nativeModules: false, permissions: [] };
it('parses actions with label/hint/danger', () => {
const m = parseManifest({ ...base, actions: [{ key: 'testConnection', label: 'Test connection', hint: 'Pings the API.' }, { key: 'purge', label: 'Purge', danger: true }] });
expect(m.actions).toEqual([
{ key: 'testConnection', label: 'Test connection', hint: 'Pings the API.', danger: false },
{ key: 'purge', label: 'Purge', hint: undefined, danger: true },
]);
});
it('defaults the label to the key, and bounds label/hint', () => {
const m = parseManifest({ ...base, actions: [{ key: 'sync', label: 'L'.repeat(200), hint: 'H'.repeat(500) }] });
expect(m.actions[0].label.length).toBe(60);
expect(m.actions[0].hint!.length).toBe(200);
expect(parseManifest({ ...base, actions: [{ key: 'sync' }] }).actions[0].label).toBe('sync');
});
it('rejects a prototype-chain key, a duplicate, a non-array and too many', () => {
expect(() => parseManifest({ ...base, actions: [{ key: '__proto__' }] })).toThrow(ManifestError);
expect(() => parseManifest({ ...base, actions: [{ key: 'a' }, { key: 'a' }] })).toThrow(/duplicate action/);
expect(() => parseManifest({ ...base, actions: 'nope' })).toThrow(/must be an array/);
expect(() => parseManifest({ ...base, actions: Array.from({ length: 9 }, (_, i) => ({ key: `a${i}` })) })).toThrow(/at most 8/);
});
it('defaults to no actions', () => {
expect(parseManifest(base).actions).toEqual([]);
});
});
@@ -0,0 +1,149 @@
/**
* Operator-supplied egress hosts.
*
* A plugin's egress allow-list is fixed in its manifest at publish time, but a plugin that
* talks to a SELF-HOSTED service (Gotify, ntfy, …) cannot know the operator's hostname —
* so a community plugin would serve nobody. An ADMIN adds the hosts post-install and the
* runtime unions them into the child's allow-list at spawn.
*
* The invariants that keep this from becoming an egress bypass:
* - only a plugin that DECLARED operatorEgress may have hosts (install-time consent);
* - hosts are validated like manifest egress (no bare `*`, no scheme, no whole-TLD);
* - it is always the ADMIN, never an end user, who widens it;
* - changing the set RE-SPAWNS the plugin, because the child's guard is install-once.
*/
import { describe, it, expect, vi, beforeAll, beforeEach } from 'vitest';
const { testDb, dbMock } = vi.hoisted(() => {
const Database = require('better-sqlite3');
const db = new Database(':memory:');
return { testDb: db, dbMock: { db, closeDb: () => {}, reinitialize: () => {}, canAccessTrip: () => null } };
});
vi.mock('../../../src/db/database', () => dbMock);
vi.mock('../../../src/config', () => ({ JWT_SECRET: 'x'.repeat(40), ENCRYPTION_KEY: 'a'.repeat(64), updateJwtSecret: () => {} }));
import { createTables } from '../../../src/db/schema';
import { runMigrations } from '../../../src/db/migrations';
import { PluginRuntimeService } from '../../../src/nest/plugins/plugin-runtime.service';
import { parseManifest, ManifestError } from '../../../src/nest/plugins/install/manifest';
function install(id: string, operatorEgress: boolean, perms: string[] = ['http:outbound:gotify.net']) {
testDb.prepare(
`INSERT OR REPLACE INTO plugins (id, name, status, enabled, version, permissions, granted_permissions, capabilities, config, operator_egress)
VALUES (?, ?, 'inactive', 0, '1.0.0', ?, ?, '{}', '{}', ?)`,
).run(id, id, JSON.stringify(perms), JSON.stringify(perms), operatorEgress ? 1 : 0);
}
let rt: PluginRuntimeService;
beforeAll(() => { createTables(testDb); runMigrations(testDb); });
beforeEach(() => {
testDb.prepare('DELETE FROM plugins').run();
testDb.prepare('DELETE FROM plugin_egress_hosts').run();
testDb.prepare('DELETE FROM plugin_actions').run();
rt = new PluginRuntimeService();
});
describe('operator-supplied egress hosts', () => {
it('OEG-001 — an admin can add hosts to a plugin that declared operatorEgress', async () => {
install('gotify', true);
expect(rt.wantsOperatorEgress('gotify')).toBe(true);
expect(await rt.setOperatorEgressHosts('gotify', ['gotify.mydomain.com'])).toEqual(['gotify.mydomain.com']);
expect(rt.operatorEgressHosts('gotify')).toEqual(['gotify.mydomain.com']);
});
it('OEG-002 — a plugin that did NOT declare it can never have hosts added', async () => {
install('sneaky', false);
expect(rt.wantsOperatorEgress('sneaky')).toBe(false);
// This is the load-bearing check: without it an admin could silently widen egress for
// ANY plugin, and the install-time consent would stop bounding what's possible.
await expect(rt.setOperatorEgressHosts('sneaky', ['evil.example.com'])).rejects.toThrow(/did not declare operatorEgress/);
expect(rt.operatorEgressHosts('sneaky')).toEqual([]);
});
it('OEG-003 — hosts are validated exactly like manifest egress', async () => {
install('gotify', true);
for (const bad of ['*', '*.com', 'https://gotify.example.com', 'has space', 'a/b']) {
await expect(rt.setOperatorEgressHosts('gotify', [bad])).rejects.toThrow(/invalid host/);
}
// A legitimate wildcard with a real multi-label suffix is fine.
expect(await rt.setOperatorEgressHosts('gotify', ['*.mydomain.com'])).toEqual(['*.mydomain.com']);
});
it('OEG-004 — hosts are normalized and de-duplicated', async () => {
install('gotify', true);
expect(await rt.setOperatorEgressHosts('gotify', ['Gotify.MyDomain.com', 'gotify.mydomain.com.', ' ', ''])).toEqual([
'gotify.mydomain.com',
]);
});
it('OEG-005 — setting the list replaces it (a removed host is really gone)', async () => {
install('gotify', true);
await rt.setOperatorEgressHosts('gotify', ['a.example.com', 'b.example.com']);
await rt.setOperatorEgressHosts('gotify', ['b.example.com']);
expect(rt.operatorEgressHosts('gotify')).toEqual(['b.example.com']);
});
it('OEG-006 — the manifest rejects operatorEgress without an outbound permission', () => {
const base = { id: 'chan', name: 'Chan', version: '1.0.0', apiVersion: 1, type: 'integration', nativeModules: false };
expect(() => parseManifest({ ...base, permissions: ['db:own'], operatorEgress: true })).toThrow(/requires an http:outbound/);
expect(() => parseManifest({ ...base, permissions: [], operatorEgress: 'yes' })).toThrow(ManifestError);
// …and accepts the real thing.
const m = parseManifest({ ...base, permissions: ['http:outbound:gotify.net'], egress: ['gotify.net'], operatorEgress: true });
expect(m.operatorEgress).toBe(true);
});
it('OEG-007 — uninstalling drops the admin’s host consent with the plugin', async () => {
install('gotify', true);
await rt.setOperatorEgressHosts('gotify', ['gotify.mydomain.com']);
await rt.uninstall('gotify', false);
// A LATER plugin reusing this id must not silently inherit hosts approved for another.
expect(rt.operatorEgressHosts('gotify')).toEqual([]);
});
});
describe('settings-page actions (runtime)', () => {
function declareAction(id: string, key: string) {
testDb.prepare('INSERT OR REPLACE INTO plugin_actions (plugin_id, action_key, label, hint, danger, sort_order) VALUES (?, ?, ?, NULL, 0, 0)')
.run(id, key, key);
}
it('ACT-001 — actionsOf returns the declared descriptors', () => {
install('p', false);
declareAction('p', 'testConnection');
expect(rt.actionsOf('p')).toEqual([{ key: 'testConnection', label: 'testConnection', hint: undefined, danger: false }]);
});
it('ACT-002 — invoking an action the plugin never declared is REFUSED', async () => {
install('p', false);
declareAction('p', 'testConnection');
// The key is caller-supplied (it comes off the URL), so the host must check it
// against the manifest rather than forwarding whatever it is handed to the child.
await expect(rt.invokeAction('p', 'somethingElse', 1)).rejects.toThrow(/did not declare action/);
await expect(rt.invokeAction('p', '__proto__', 1)).rejects.toThrow(/did not declare action/);
});
it('ACT-003 — a plugin with no actions can never be invoked', async () => {
install('p', false);
await expect(rt.invokeAction('p', 'testConnection', 1)).rejects.toThrow(/did not declare action/);
});
});
describe('the admin list surfaces operator egress (so the chip can be shown)', () => {
it('OEG-008 — reports operatorEgress + the host count', async () => {
const { PluginsService } = await import('../../../src/nest/plugins/plugins.service');
process.env.TREK_PLUGINS_ENABLED = 'true';
install('gotify', true);
install('plain', false);
const before = new PluginsService().list().plugins;
expect(before.find(p => p.id === 'gotify')).toMatchObject({ operatorEgress: true, egressHostCount: 0 });
// A plugin that never asked for it must never invite the admin to add hosts.
expect(before.find(p => p.id === 'plain')).toMatchObject({ operatorEgress: false, egressHostCount: 0 });
await rt.setOperatorEgressHosts('gotify', ['a.example.com', 'b.example.com']);
const after = new PluginsService().list().plugins;
expect(after.find(p => p.id === 'gotify')!.egressHostCount).toBe(2);
delete process.env.TREK_PLUGINS_ENABLED;
});
});
@@ -13,6 +13,7 @@ vi.mock('../../../src/nest/plugins/kill-switch', () => ({ pluginsEnabled }));
vi.mock('../../../src/db/database', () => ({ db: { prepare: () => ({ get: getMock }) } }));
import { PluginUserSettingsController } from '../../../src/nest/plugins/plugin-user-settings.controller';
import type { PluginRuntimeService } from '../../../src/nest/plugins/plugin-runtime.service';
import type { PluginsService } from '../../../src/nest/plugins/plugins.service';
// eslint-disable-next-line @typescript-eslint/no-explicit-any
@@ -23,7 +24,9 @@ function ctrl() {
getUserConfig: vi.fn(() => ({ apiKey: '••••••••' })),
updateUserConfig: vi.fn((_id: string, _uid: number, patch: Record<string, unknown>) => ({ ...patch, apiKey: '••••••••' })),
} as unknown as PluginsService;
return { c: new PluginUserSettingsController(svc), svc };
// The controller now also takes the runtime (for settings-page actions).
const runtime = { actionsOf: () => [], invokeAction: vi.fn() } as unknown as PluginRuntimeService;
return { c: new PluginUserSettingsController(svc, runtime), svc, runtime };
}
describe('PluginUserSettingsController', () => {
@@ -31,13 +34,13 @@ describe('PluginUserSettingsController', () => {
it('GET returns fields + masked config for a bound user; empty when gated', () => {
const { c } = ctrl();
expect(c.get('p', req(5))).toEqual({ fields: [{ key: 'apiKey', secret: true }], config: { apiKey: '••••••••' } });
expect(c.get('p', req(5))).toEqual({ fields: [{ key: 'apiKey', secret: true }], config: { apiKey: '••••••••' }, actions: [] });
pluginsEnabled.mockReturnValue(false);
expect(c.get('p', req(5))).toEqual({ fields: [], config: {} });
expect(c.get('p', req(5))).toEqual({ fields: [], config: {}, actions: [] });
pluginsEnabled.mockReturnValue(true);
expect(c.get('p', req(undefined))).toEqual({ fields: [], config: {} });
expect(c.get('p', req(undefined))).toEqual({ fields: [], config: {}, actions: [] });
getMock.mockReturnValue(undefined as never);
expect(c.get('p', req(5))).toEqual({ fields: [], config: {} });
expect(c.get('p', req(5))).toEqual({ fields: [], config: {}, actions: [] });
});
it('POST delegates the patch for a bound user; empty when gated', () => {
@@ -9,7 +9,7 @@ const { testDb } = vi.hoisted(() => {
const db = new Database(':memory:');
db.exec(`CREATE TABLE plugins (
id TEXT PRIMARY KEY, name TEXT, description TEXT, type TEXT, icon TEXT, version TEXT,
status TEXT, enabled INTEGER DEFAULT 0, last_error TEXT, reviewed_at TEXT, source_repo TEXT, config TEXT DEFAULT '{}', permissions TEXT DEFAULT '[]', capabilities TEXT DEFAULT '{}', dependencies TEXT DEFAULT '{}', updated_at TEXT,
status TEXT, enabled INTEGER DEFAULT 0, last_error TEXT, reviewed_at TEXT, source_repo TEXT, config TEXT DEFAULT '{}', permissions TEXT DEFAULT '[]', capabilities TEXT DEFAULT '{}', dependencies TEXT DEFAULT '{}', operator_egress INTEGER DEFAULT 0, updated_at TEXT,
sort_order INTEGER DEFAULT 0);
CREATE TABLE plugin_settings_fields (plugin_id TEXT, field_key TEXT, scope TEXT, secret INTEGER);
CREATE TABLE plugin_error_log (id INTEGER PRIMARY KEY AUTOINCREMENT, plugin_id TEXT, level TEXT, message TEXT, ts TEXT DEFAULT '2026-01-01');`);
@@ -49,6 +49,16 @@ describe('providersOf enforces the hook:* grant', () => {
expect(s.providersOf('atlasLayerProvider')).toEqual(['atlas']);
expect(s.providersOf('journalEntryProvider')).toEqual(['journal']);
});
it('maps notificationChannel to hook:notification-channel', () => {
const s = makeSupervisor();
put(s, 'gotify', 'active', ['notificationChannel'], ['hook:notification-channel']);
// Implements the hook but was never granted it — must not become a channel.
put(s, 'sneaky', 'active', ['notificationChannel'], ['notify:send', 'http:outbound']);
// Granted, but disabled — a channel must not survive being turned off.
put(s, 'off', 'stopped', ['notificationChannel'], ['hook:notification-channel']);
expect(s.providersOf('notificationChannel')).toEqual(['gotify']);
});
});
describe('runtime.invokeHook defense-in-depth', () => {
@@ -0,0 +1,135 @@
/**
* Plugin settings isolation.
*
* A plugin's settings live in its OWN storage — instance config in `plugins.config`,
* per-user config in `plugin_user_config` keyed by (plugin_id, user_id). Plugin code
* never writes the core `settings` table, and every read helper is host-bound to one
* plugin id. These tests pin that, plus the settings-key constraint: an unconstrained
* key (`__proto__`, `constructor`) used to resolve off Object.prototype, so a REQUIRED
* field with such a name reported as configured for a user who had configured nothing —
* which for a notification channel meant being dispatched to everyone with no credentials.
*/
import { describe, it, expect, vi, beforeAll, beforeEach } from 'vitest';
const { testDb, dbMock } = vi.hoisted(() => {
const Database = require('better-sqlite3');
const db = new Database(':memory:');
return { testDb: db, dbMock: { db, closeDb: () => {}, reinitialize: () => {}, canAccessTrip: () => null } };
});
vi.mock('../../../src/db/database', () => dbMock);
vi.mock('../../../src/config', () => ({ JWT_SECRET: 'x'.repeat(40), ENCRYPTION_KEY: 'a'.repeat(64), updateJwtSecret: () => {} }));
import { createTables } from '../../../src/db/schema';
import { runMigrations } from '../../../src/db/migrations';
import { createUser } from '../../helpers/factories';
import { readUserSettingsDecrypted, hasRequiredUserSettings, readUserSettingDecrypted } from '../../../src/nest/plugins/plugins.service';
import { parseManifest, ManifestError } from '../../../src/nest/plugins/install/manifest';
let uid: number;
function declareField(pluginId: string, key: string, opts: { required?: boolean; secret?: boolean } = {}) {
testDb.prepare(
`INSERT INTO plugin_settings_fields (plugin_id, field_key, label, input_type, required, secret, scope, sort_order)
VALUES (?, ?, ?, 'text', ?, ?, 'user', 0)`,
).run(pluginId, key, key, opts.required ? 1 : 0, opts.secret ? 1 : 0);
}
function setUserConfig(pluginId: string, config: Record<string, unknown>) {
testDb.prepare('INSERT OR REPLACE INTO plugin_user_config (plugin_id, user_id, config) VALUES (?, ?, ?)').run(pluginId, uid, JSON.stringify(config));
}
beforeAll(() => { createTables(testDb); runMigrations(testDb); });
beforeEach(() => {
testDb.prepare('DELETE FROM plugin_settings_fields').run();
testDb.prepare('DELETE FROM plugin_user_config').run();
testDb.prepare('DELETE FROM settings').run();
testDb.prepare('DELETE FROM users').run();
uid = createUser(testDb).user.id;
});
describe('plugin settings are isolated from core and from each other', () => {
it('PSET-001 — a plugin declaring "webhook_url" cannot touch the CORE settings row', () => {
testDb.prepare("INSERT INTO settings (user_id, key, value) VALUES (?, 'webhook_url', 'https://core.example.com/real')").run(uid);
declareField('evil', 'webhook_url');
setUserConfig('evil', { webhook_url: 'https://attacker.example.com' });
// The user's REAL notification webhook is untouched — the plugin's value lives in
// its own blob, in its own table. The namespacing is structural, not by key naming.
const core = testDb.prepare("SELECT value FROM settings WHERE user_id = ? AND key = 'webhook_url'").get(uid) as { value: string };
expect(core.value).toBe('https://core.example.com/real');
expect(readUserSettingsDecrypted('evil', uid)).toEqual({ webhook_url: 'https://attacker.example.com' });
});
it('PSET-002 — plugin A cannot read plugin B’s config, even with the same key name', () => {
declareField('a', 'token', { secret: true });
declareField('b', 'token', { secret: true });
setUserConfig('b', { token: 'B-SECRET' });
expect(readUserSettingsDecrypted('a', uid)).toEqual({});
expect(readUserSettingDecrypted('a', uid, 'token')).toBeUndefined();
expect(readUserSettingDecrypted('b', uid, 'token')).toBe('B-SECRET');
});
it('PSET-003 — a plugin only ever sees its own DECLARED keys', () => {
declareField('p', 'declared');
// An undeclared key that somehow reached the blob is not handed to the plugin.
setUserConfig('p', { declared: 'yes', sneaked: 'no' });
expect(readUserSettingsDecrypted('p', uid)).toEqual({ declared: 'yes' });
});
});
describe('settings keys cannot resolve off the prototype chain', () => {
it.each(['__proto__', 'constructor', 'prototype'])(
'PSET-004 — a REQUIRED field named "%s" is NOT reported as configured',
(key) => {
declareField('evil', key, { required: true });
// The user has configured nothing at all.
expect(hasRequiredUserSettings('evil', uid)).toBe(false);
expect(readUserSettingsDecrypted('evil', uid)).toEqual({});
},
);
it('PSET-005 — a genuinely configured required field still reports configured', () => {
declareField('good', 'appToken', { required: true, secret: true });
expect(hasRequiredUserSettings('good', uid)).toBe(false);
setUserConfig('good', { appToken: 'T' });
expect(hasRequiredUserSettings('good', uid)).toBe(true);
});
it('PSET-006 — the manifest rejects such a key at install', () => {
const base = { id: 'evil', name: 'Evil', version: '1.0.0', apiVersion: 1, type: 'integration', nativeModules: false, permissions: [] };
for (const key of ['__proto__', 'constructor', 'prototype', 'has space', '1leading', 'a'.repeat(65)]) {
expect(() => parseManifest({ ...base, settings: [{ key, scope: 'user' }] })).toThrow(ManifestError);
}
// …and still accepts an ordinary one.
expect(parseManifest({ ...base, settings: [{ key: 'appToken', scope: 'user', secret: true, required: true }] }).settings[0].key).toBe('appToken');
});
});
/**
* The channel label is a plugin-supplied string that becomes a column header in the
* user's notification preferences matrix, so the host bounds it like every other
* plugin string it renders (cf. cap()/stripEmoji in the calendar + photo controllers).
*/
describe('a plugin channel label is bounded by the host', () => {
it('PSET-007 — an oversized, emoji-laden capabilities.title is capped and stripped', async () => {
const { PluginRuntimeService } = await import('../../../src/nest/plugins/plugin-runtime.service');
process.env.TREK_PLUGINS_ENABLED = 'true';
testDb.prepare(
`INSERT OR REPLACE INTO plugins (id, name, status, enabled, version, permissions, granted_permissions, capabilities, config)
VALUES ('loud', 'Loud', 'active', 1, '1.0.0', '[]', '[]', ?, '{}')`,
).run(JSON.stringify({ notificationChannel: { title: '🎉'.repeat(5) + 'A'.repeat(500) } }));
const rt = new PluginRuntimeService();
// Stand the plugin up as a granted, active notificationChannel provider.
(rt as unknown as { supervisor: { running: Map<string, unknown> } }).supervisor.running.set('loud', {
id: 'loud', status: 'active', hooks: ['notificationChannel'], granted: new Set(['hook:notification-channel']),
});
const [channel] = rt.notificationChannels();
expect(channel.id).toBe('plugin:loud');
expect(channel.label!.length).toBeLessThanOrEqual(40);
expect(channel.label).not.toMatch(/\p{Extended_Pictographic}/u);
delete process.env.TREK_PLUGINS_ENABLED;
});
});