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
+43
View File
@@ -3583,6 +3583,49 @@ function runMigrations(db: Database.Database): void {
`);
db.exec('CREATE INDEX IF NOT EXISTS idx_hidden_countries_user ON hidden_countries (user_id);');
},
// Operator-supplied egress hosts for a plugin (#plugins).
// 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 could serve nobody. These rows let the ADMIN add
// hosts post-install; the runtime unions them into the child's allow-list at spawn.
// Consent stays with the admin (never the end user), exactly as for manifest egress.
() => {
db.exec(`
CREATE TABLE IF NOT EXISTS plugin_egress_hosts (
id INTEGER PRIMARY KEY AUTOINCREMENT,
plugin_id TEXT NOT NULL,
host TEXT NOT NULL,
created_at TEXT NOT NULL DEFAULT (datetime('now')),
UNIQUE (plugin_id, host)
);
`);
db.exec('CREATE INDEX IF NOT EXISTS idx_plugin_egress_hosts_plugin ON plugin_egress_hosts (plugin_id);');
// Whether the plugin DECLARED that it needs operator-supplied hosts. Only such a
// plugin may have hosts added — an admin can never widen egress for a plugin that
// never asked for it, so the install-time consent still bounds what's possible.
const columns = db.prepare("PRAGMA table_info('plugins')").all() as Array<{ name: string }>;
if (!columns.some((c) => c.name === 'operator_egress')) {
db.exec('ALTER TABLE plugins ADD COLUMN operator_egress INTEGER NOT NULL DEFAULT 0;');
}
},
// Settings-page action buttons a plugin contributes ("Test connection", "Sync now").
// Descriptors only — the handler lives in the plugin's code and is invoked host-side
// with the CLICKING user bound, so it can read that user's own settings.
() => {
db.exec(`
CREATE TABLE IF NOT EXISTS plugin_actions (
plugin_id TEXT NOT NULL,
action_key TEXT NOT NULL,
label TEXT NOT NULL,
hint TEXT,
danger INTEGER NOT NULL DEFAULT 0,
sort_order INTEGER NOT NULL DEFAULT 0,
PRIMARY KEY (plugin_id, action_key)
);
`);
},
];
if (currentVersion < migrations.length) {
@@ -103,6 +103,18 @@ export class NotificationsController {
return this.notifications.testNtfy({ topic: resolvedTopic, server: resolvedServer ?? null, token: resolvedToken });
}
/**
* Generic channel test, dispatched through the registry — this is how a plugin
* channel's "Send test" button works. The three routes above stay as they are:
* they carry bespoke masked-secret and admin-fallback resolution whose exact
* error bodies the client depends on, and folding them in here would risk that.
*/
@Post('test/:channelId')
@HttpCode(200)
async testChannel(@CurrentUser() user: User, @Param('channelId') channelId: string): Promise<ChannelTestResult> {
return this.notifications.testChannel(user.id, channelId);
}
@Get('in-app')
listInApp(
@CurrentUser() user: User,
@@ -20,6 +20,7 @@ import {
respondToBoolean,
} from '../../services/inAppNotifications';
import { getPreferencesMatrix, setPreferences } from '../../services/notificationPreferencesService';
import { getChannel } from '../../services/notifications/channelRegistry';
type NtfyConfig = ReturnType<typeof getAdminNtfyConfig>;
type RespondResult = Awaited<ReturnType<typeof respondToBoolean>>;
@@ -39,6 +40,19 @@ export class NotificationsService {
return getPreferencesMatrix(userId, role, 'user');
}
/** Send a test notification over any registered channel (built-in or plugin). */
async testChannel(userId: number, channelId: string): Promise<ChannelTestResult> {
const channel = getChannel(channelId);
if (!channel) return { success: false, error: 'Unknown channel' };
if (!channel.test) return { success: false, error: 'This channel does not support test sends' };
if (!channel.isConfiguredFor(userId)) return { success: false, error: 'Channel is not configured for this user' };
try {
return await channel.test(userId);
} catch (e) {
return { success: false, error: e instanceof Error ? e.message : 'Unknown error' };
}
}
setPreferences(userId: number, body: Parameters<typeof setPreferences>[1]): void {
setPreferences(userId, body);
}
+12 -5
View File
@@ -67,17 +67,24 @@ function upsert(db: BetterSqlite3.Database, m: PluginManifest): void {
if (existing) {
db.prepare(
`UPDATE plugins SET name = ?, description = ?, type = ?, icon = ?, version = ?, api_version = ?,
min_trek_version = ?, permissions = ?, capabilities = ?, dependencies = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?`,
).run(m.name, m.description ?? null, m.type, m.icon ?? 'Blocks', m.version, m.apiVersion, m.minTrekVersion ?? null, JSON.stringify(m.permissions), JSON.stringify(m.capabilities), dependencies, m.id);
min_trek_version = ?, permissions = ?, capabilities = ?, dependencies = ?, operator_egress = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?`,
).run(m.name, m.description ?? null, m.type, m.icon ?? 'Blocks', m.version, m.apiVersion, m.minTrekVersion ?? null, JSON.stringify(m.permissions), JSON.stringify(m.capabilities), dependencies, m.operatorEgress ? 1 : 0, m.id);
} else {
db.prepare(
// granted_permissions '' (empty, not '[]') marks "never consented" so the
// first activation is distinguishable from a plugin consented to zero perms.
`INSERT INTO plugins (id, name, description, type, icon, version, api_version, min_trek_version, permissions, capabilities, dependencies, granted_permissions, status)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, '', 'inactive')`,
).run(m.id, m.name, m.description ?? null, m.type, m.icon ?? 'Blocks', m.version, m.apiVersion, m.minTrekVersion ?? null, JSON.stringify(m.permissions), JSON.stringify(m.capabilities), dependencies);
`INSERT INTO plugins (id, name, description, type, icon, version, api_version, min_trek_version, permissions, capabilities, dependencies, operator_egress, granted_permissions, status)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, '', 'inactive')`,
).run(m.id, m.name, m.description ?? null, m.type, m.icon ?? 'Blocks', m.version, m.apiVersion, m.minTrekVersion ?? null, JSON.stringify(m.permissions), JSON.stringify(m.capabilities), dependencies, m.operatorEgress ? 1 : 0);
}
// Refresh the settings-page action descriptors from the manifest.
db.prepare('DELETE FROM plugin_actions WHERE plugin_id = ?').run(m.id);
const insertAction = db.prepare(
'INSERT INTO plugin_actions (plugin_id, action_key, label, hint, danger, sort_order) VALUES (?, ?, ?, ?, ?, ?)',
);
m.actions.forEach((a, i) => insertAction.run(m.id, a.key, a.label, a.hint ?? null, a.danger ? 1 : 0, i));
// Refresh the settings-field descriptors from the manifest.
db.prepare('DELETE FROM plugin_settings_fields WHERE plugin_id = ?').run(m.id);
const insert = db.prepare(
+158 -2
View File
@@ -1,5 +1,6 @@
import semver from 'semver';
import { isKnownPermission } from '../protocol/envelope';
import type { NotifEventType } from '../../../services/notificationPreferencesService';
/**
* Parse + validate a plugin's trek-plugin.json (#plugins, M4). Kept deliberately
@@ -38,9 +39,32 @@ export interface TripPageCapability {
position?: number;
}
/** Config for a plugin that implements the `notificationChannel` hook. */
export interface NotificationChannelCapability {
/** Column name in the notification preferences matrix. Defaults to the plugin's name. */
title?: string;
/** Narrow which events this channel carries. Defaults to every non-admin event. */
events?: string[];
}
/**
* A button the plugin contributes to its own settings page ("Test connection",
* "Sync now"). Unlike the notification-channel hook, an action is USER-INITIATED — the
* acting user is whoever clicked — so `ctx.settings.get()` and trip reads work normally
* inside it, which is exactly what a "test my credentials" button needs.
*/
export interface ManifestAction {
key: string;
label: string;
hint?: string;
/** Render as destructive and ask for confirmation before running. */
danger?: boolean;
}
export interface PluginCapabilities {
widget?: WidgetCapability;
tripPage?: TripPageCapability;
notificationChannel?: NotificationChannelCapability;
/** Function names this plugin exposes to its dependents via ctx.plugins.call. */
provides?: string[];
/** Event names this plugin publishes to its dependents via ctx.events.emit. */
@@ -68,7 +92,15 @@ export interface PluginManifest {
nativeModules: boolean;
permissions: string[];
egress: string[];
/**
* The plugin talks to a service whose hostname only the OPERATOR knows (a self-hosted
* Gotify, ntfy, Uptime Kuma…). Its manifest `egress` can never cover that, so an admin
* may add hosts post-install and the runtime unions them into the child's allow-list.
* Consent stays with the admin — an end user can never widen egress.
*/
operatorEgress: boolean;
settings: ManifestSettingField[];
actions: ManifestAction[];
capabilities: PluginCapabilities;
/** Addon ids that must be enabled for this plugin to activate (format-only here). */
requiredAddons: string[];
@@ -129,6 +161,12 @@ export function parseManifest(raw: unknown): PluginManifest {
if (badOutbound !== undefined) throw new ManifestError(`invalid http:outbound host "${badOutbound}"`);
const egress = arr(m.egress).map(String);
if (m.operatorEgress !== undefined && typeof m.operatorEgress !== 'boolean') {
throw new ManifestError('operatorEgress must be a boolean');
}
if (m.operatorEgress === true && !permissions.some((p) => p === 'http:outbound' || p.startsWith('http:outbound:'))) {
throw new ManifestError('operatorEgress requires an http:outbound permission');
}
if (permissions.some((p) => p === 'http:outbound' || p.startsWith('http:outbound:')) && egress.length === 0) {
throw new ManifestError('http:outbound declared but egress[] is empty');
}
@@ -152,7 +190,9 @@ export function parseManifest(raw: unknown): PluginManifest {
nativeModules: false,
permissions,
egress,
operatorEgress: m.operatorEgress === true,
settings: parseSettings(m.settings),
actions: parseActions(m.actions),
capabilities: parseCapabilities(m.capabilities),
requiredAddons: parseRequiredAddons(m.requiredAddons),
pluginDependencies: parsePluginDependencies(m.pluginDependencies, id),
@@ -231,6 +271,26 @@ function parseCapabilities(raw: unknown): PluginCapabilities {
}
if (Object.keys(page).length) out.tripPage = page;
}
if (c.notificationChannel && typeof c.notificationChannel === 'object') {
const nc = c.notificationChannel as Record<string, unknown>;
const channel: NotificationChannelCapability = {};
const title = optStr(nc.title);
if (title) channel.title = title;
if (nc.events !== undefined) {
if (!Array.isArray(nc.events)) throw new ManifestError('capabilities.notificationChannel.events must be an array');
const events: string[] = [];
for (const v of nc.events) {
if (typeof v !== 'string' || !(PLUGIN_CHANNEL_EVENTS as readonly string[]).includes(v)) {
throw new ManifestError(
`capabilities.notificationChannel.events: "${String(v)}" is not a plugin-deliverable event (${PLUGIN_CHANNEL_EVENTS.join(', ')})`,
);
}
if (!events.includes(v)) events.push(v);
}
if (events.length) channel.events = events;
}
out.notificationChannel = channel;
}
const provides = parseCapabilityNames(c.provides, 'provides');
if (provides.length) out.provides = provides;
const emits = parseCapabilityNames(c.emits, 'emits');
@@ -238,6 +298,35 @@ function parseCapabilities(raw: unknown): PluginCapabilities {
return out;
}
/**
* Events a plugin notification channel may carry. Two exclusions, both deliberate:
* `version_available` is admin-scoped (it goes out over the admin's own global
* credentials, and a community plugin is never a recipient of one), and
* `synology_session_cleared` is in-app only.
*
* Spelled out rather than derived from the notification service, so the plugin
* installer carries no runtime dependency on it. The guard below is what keeps the
* two in step — same trick as `_eventKeyDriftGuard` in services/notifications.ts.
*/
export const PLUGIN_CHANNEL_EVENTS = [
'trip_invite',
'booking_change',
'trip_reminder',
'todo_due',
'vacay_invite',
'collection_invite',
'photos_shared',
'collab_message',
'packing_tagged',
'plugin_notification',
] as const;
// Compile-time guard: every id above must still be a real notification event.
// If one is renamed or dropped, this stops compiling.
type _ChannelEventsAreReal = (typeof PLUGIN_CHANNEL_EVENTS)[number] extends NotifEventType ? true : never;
const _channelEventDriftGuard: _ChannelEventsAreReal = true;
void _channelEventDriftGuard;
// Core planner tabs a trip-page plugin may replace while it is active. 'plan' is
// deliberately NOT in this list — a trip always keeps its planner view, so a
// plugin can take over bookings/transports/…, never the whole trip.
@@ -255,12 +344,24 @@ function parseCapabilityNames(raw: unknown, field: string): string[] {
return out;
}
/**
* A settings field key. Constrained because the key is used as a JSON object key in
* the plugin's stored config: an unconstrained one (`__proto__`, `constructor`) resolves
* off Object.prototype on read, so a *required* field with such a name would look
* "configured" for every user who had configured nothing — enough, for a notification
* channel, to be dispatched to everyone without anyone entering credentials.
* (safeParse in plugins.service.ts now uses a null-prototype object too; this is the
* front door, that is the backstop.)
*/
const SETTING_KEY_RE = /^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/;
const RESERVED_SETTING_KEYS = new Set(['constructor', 'prototype', '__proto__']);
function parseSettings(raw: unknown): ManifestSettingField[] {
if (!Array.isArray(raw)) return [];
return raw
.filter((s): s is Record<string, unknown> => !!s && typeof s === 'object')
.map((s): ManifestSettingField => ({
key: String(s.key ?? ''),
key: assertSettingKey(String(s.key ?? '')),
label: optStr(s.label),
input_type: optStr(s.input_type) ?? 'text',
placeholder: optStr(s.placeholder),
@@ -268,12 +369,67 @@ function parseSettings(raw: unknown): ManifestSettingField[] {
required: !!s.required,
secret: !!s.secret,
scope: s.scope === 'user' ? 'user' : 'instance',
options: Array.isArray(s.options) ? (s.options as Array<{ value: string; label: string }>) : undefined,
options: parseSettingOptions(s.options),
oauth: s.oauth && typeof s.oauth === 'object' ? (s.oauth as { initPath?: string; callbackPath?: string }) : undefined,
}))
.filter((s) => s.key);
}
/**
* A `select` field's options. The client renders `{value, label}`, so a bare string list —
* the obvious thing to write, and what a manifest was silently allowed to carry — rendered
* every option BLANK (value/label both undefined). Coerce the string form instead of
* failing on it, and reject anything that is neither.
*/
function parseSettingOptions(raw: unknown): Array<{ value: string; label: string }> | undefined {
if (raw === undefined) return undefined;
if (!Array.isArray(raw)) throw new ManifestError('settings option list must be an array');
return raw.map((o) => {
if (typeof o === 'string' || typeof o === 'number') return { value: String(o), label: String(o) };
if (o && typeof o === 'object') {
const { value, label } = o as { value?: unknown; label?: unknown };
if (value === undefined || value === null || String(value) === '') {
throw new ManifestError('settings option must have a non-empty "value"');
}
return { value: String(value), label: String(label ?? value) };
}
throw new ManifestError(`invalid settings option ${JSON.stringify(o)} (expected a string or { value, label })`);
});
}
/** Settings-page action buttons. Bounded: the host renders the label itself. */
function parseActions(raw: unknown): ManifestAction[] {
if (raw === undefined) return [];
if (!Array.isArray(raw)) throw new ManifestError('actions must be an array');
if (raw.length > 8) throw new ManifestError('at most 8 actions');
const out: ManifestAction[] = [];
for (const a of raw) {
if (!a || typeof a !== 'object') throw new ManifestError('each action must be an object');
const { key, label, hint, danger } = a as Record<string, unknown>;
const k = assertSettingKey(String(key ?? ''));
if (!k) throw new ManifestError('action must have a "key"');
if (out.some((x) => x.key === k)) throw new ManifestError(`duplicate action "${k}"`);
out.push({
key: k,
label: String(label ?? k).slice(0, 60),
hint: hint === undefined ? undefined : String(hint).slice(0, 200),
danger: danger === true,
});
}
return out;
}
function assertSettingKey(key: string): string {
// An empty key is dropped by the .filter below (a manifest may legitimately omit a
// field), but a PRESENT key that is malformed is a hard reject — silently ignoring it
// would leave the plugin expecting a setting the host will never store.
if (!key) return key;
if (!SETTING_KEY_RE.test(key) || RESERVED_SETTING_KEYS.has(key)) {
throw new ManifestError(`invalid settings key "${key}" (letters, digits, . _ - ; must start with a letter; 1–64 chars)`);
}
return key;
}
function str(v: unknown, name: string): string {
if (typeof v !== 'string' || !v) throw new ManifestError(`missing/invalid "${name}"`);
return v;
@@ -4,6 +4,10 @@ import { db } from '../../db/database';
import { pluginsEnabled } from './kill-switch';
import { setPluginEventSink } from '../../plugin-event-sink';
import { setUserDeletedSink } from '../../plugin-user-lifecycle';
import { setPluginChannelSource, pluginChannelId, type ChannelMessage, type ExternalChannel } from '../../services/notifications/channelRegistry';
import { readUserSettingsDecrypted, hasRequiredUserSettings } from './plugins.service';
import { PLUGIN_CHANNEL_EVENTS } from './install/manifest';
import { stripEmoji } from './text-sanitize';
import { applyStagedPluginTrees, setStagedRestoreApplier } from './plugin-backup';
import { decrypt_api_key } from '../../services/apiKeyCrypto';
import { PluginSupervisor, type PluginRouteInfo } from './supervisor/plugin-supervisor';
@@ -26,6 +30,21 @@ import { parseDependencies, disabledRequiredAddons, resolveDependencyState, enab
const HTTP_OUTBOUND = 'http:outbound:';
// Mirrors HOST_RE in install/manifest.ts: an exact hostname or a `*.`-prefixed wildcard
// with a real multi-label suffix. Rejects a bare `*`, a whole-TLD wildcard, a scheme and
// any embedded space — the string is interpolated into the egress guard and the CSP.
const EGRESS_HOST_RE = /^(\*\.[a-z0-9-]+(\.[a-z0-9-]+)+|[a-z0-9-]+(\.[a-z0-9-]+)*)$/i;
/** Hosts an admin added post-install for a plugin that declared `operatorEgress`. */
function operatorEgressHosts(id: string): string[] {
try {
return (db.prepare('SELECT host FROM plugin_egress_hosts WHERE plugin_id = ? ORDER BY host').all(id) as Array<{ host: string }>)
.map((r) => r.host);
} catch {
return []; // table absent (a slimmed test app) — never block activation
}
}
/**
* Remove `<plugins>/<id>` whether it is a real directory, a POSIX symlink or a
* Windows junction — WITHOUT ever following a dev-link into (and deleting) the
@@ -151,6 +170,10 @@ export class PluginRuntimeService implements OnModuleInit, OnModuleDestroy {
// Forward core trip events to plugins that subscribed (events:subscribe). The
// sink is name-only + fire-and-forget, so it can never block a core broadcast.
setPluginEventSink((tripId, event, meta) => this.supervisor.deliverEvent(tripId, event, meta));
// Expose plugin notification channels to the (plain, non-Nest) notification
// service. Pull-based: it calls this on every dispatch, so enabling or removing
// a plugin takes effect immediately with nothing to invalidate.
setPluginChannelSource(() => this.notificationChannels());
// Fan a deleted account out to plugins so they can erase their own per-user data.
// Enqueued durably (survives restart), so nothing is lost if a plugin is offline.
setUserDeletedSink((userId) => this.enqueueUserErasure(userId));
@@ -461,10 +484,60 @@ export class PluginRuntimeService implements OnModuleInit, OnModuleDestroy {
// Mark it enabled (admin intent) so it reboots after restarts/crashes.
db.prepare('UPDATE plugins SET granted_permissions = ?, enabled = 1 WHERE id = ?').run(JSON.stringify(declared), id);
const config = decryptConfig(parseObject(row.config));
const egress = declared.filter((p) => p.startsWith(HTTP_OUTBOUND)).map((p) => p.slice(HTTP_OUTBOUND.length));
const manifestHosts = declared.filter((p) => p.startsWith(HTTP_OUTBOUND)).map((p) => p.slice(HTTP_OUTBOUND.length));
// Union in the hosts the ADMIN added post-install. A plugin that talks to a
// self-hosted service can't name the operator's hostname in its manifest, so without
// this a community plugin (a Gotify channel, an ntfy channel) serves nobody. Only a
// plugin that DECLARED operatorEgress can have hosts, so the install-time consent
// still bounds what is possible — and it is always the admin, never an end user,
// who widens it. The egress list is spawn-time only, which is why changing it
// re-spawns the plugin (see setOperatorEgressHosts).
const egress = [...new Set([...manifestHosts, ...operatorEgressHosts(id)])];
await this.supervisor.activate(id, new Set(declared), config, egress);
}
/** Hosts an admin added for this plugin (empty unless it declared `operatorEgress`). */
operatorEgressHosts(id: string): string[] {
return operatorEgressHosts(id);
}
/** Does this plugin's manifest declare that it needs operator-supplied hosts? */
wantsOperatorEgress(id: string): boolean {
const row = db.prepare('SELECT operator_egress FROM plugins WHERE id = ?').get(id) as { operator_egress: number } | undefined;
return row?.operator_egress === 1;
}
/**
* Replace the admin-supplied egress hosts for a plugin, then RE-SPAWN it so the child's
* guard picks the new list up — `installEgressGuard` runs once at init and a second
* `init` is deliberately refused, so there is no way to widen a live child's allow-list.
*/
async setOperatorEgressHosts(id: string, hosts: string[]): Promise<string[]> {
if (!this.wantsOperatorEgress(id)) {
throw new ForbiddenResource(`plugin ${id} did not declare operatorEgress`);
}
const clean: string[] = [];
for (const raw of hosts) {
const host = String(raw ?? '').trim().toLowerCase().replace(/\.$/, '');
if (!host) continue;
// Same shape the manifest enforces — this string is interpolated into the egress
// guard AND the iframe CSP connect-src, so a bare `*` or a scheme must never land.
if (host === '*' || !EGRESS_HOST_RE.test(host)) throw new ForbiddenResource(`invalid host "${raw}"`);
if (!clean.includes(host)) clean.push(host);
}
db.transaction(() => {
db.prepare('DELETE FROM plugin_egress_hosts WHERE plugin_id = ?').run(id);
const ins = db.prepare('INSERT OR IGNORE INTO plugin_egress_hosts (plugin_id, host) VALUES (?, ?)');
for (const h of clean) ins.run(id, h);
})();
// Re-spawn so a live child actually gets the new allow-list.
if (this.isActive(id)) {
await this.supervisor.disable(id);
await this.activate(id);
}
return clean;
}
async deactivate(id: string): Promise<void> {
await this.supervisor.disable(id);
closePluginDataDb(id);
@@ -653,9 +726,19 @@ export class PluginRuntimeService implements OnModuleInit, OnModuleDestroy {
removePluginCodeEntry(pluginCodeDir(id));
db.prepare('DELETE FROM plugins WHERE id = ?').run(id);
db.prepare('DELETE FROM plugin_settings_fields WHERE plugin_id = ?').run(id);
try { db.prepare('DELETE FROM plugin_actions WHERE plugin_id = ?').run(id); } catch { /* table absent */ }
// The admin's egress consent dies with the plugin. Unconditional: leaving it would
// silently grant a LATER plugin that reuses this id the hosts the admin approved for
// a different one.
try { db.prepare('DELETE FROM plugin_egress_hosts WHERE plugin_id = ?').run(id); } catch { /* table absent */ }
// Scheduled tasks are operational (not user data), so they go unconditionally —
// a scheduled callback for a plugin that no longer exists must never fire.
db.prepare('DELETE FROM plugin_scheduled_tasks WHERE plugin_id = ?').run(id);
// If it was a notification channel, retire the channel too. Unconditional, for the
// same reason as the settings fields: these are TREK's config ABOUT the plugin, and
// leaving them means a later plugin that reuses this id silently inherits every
// user's opt-outs and the admin's enablement.
this.retireNotificationChannel(id);
if (deleteData) {
removePluginData(id);
db.prepare('DELETE FROM plugin_error_log WHERE plugin_id = ?').run(id);
@@ -770,6 +853,121 @@ export class PluginRuntimeService implements OnModuleInit, OnModuleDestroy {
return semver.satisfies(target.version ?? '0.0.0', dep.version, { includePrerelease: true });
}
/**
* Drop every trace of a plugin's notification channel: the per-user event opt-outs
* and the id in the admin's `notification_channels` list.
*/
private retireNotificationChannel(id: string): void {
// Drop the users' per-event opt-outs for this channel. A plugin channel is never
// listed in the admin's `notification_channels` CSV (it is active by virtue of the
// plugin being enabled), so there is nothing to scrub there.
//
// Defensive, like the boot path above: an uninstall must still complete in a context
// without the notification tables (a slimmed test app that imports only the plugin
// module).
try {
db.prepare('DELETE FROM notification_channel_preferences WHERE channel = ?').run(pluginChannelId(id));
} catch { /* no notifications schema here — nothing to retire */ }
}
/**
* Every active, granted `notificationChannel` provider, as an ExternalChannel the
* notification service can dispatch to. Rebuilt on every read (the registry pulls
* through setPluginChannelSource), so a plugin that is disabled or uninstalled
* simply stops being a channel — no cache to invalidate.
*
* The label, the event set and the configured-check are all answered from the
* manifest and the DB, with no IPC: the child is only ever woken to actually send.
*/
notificationChannels(): ExternalChannel[] {
if (!pluginsEnabled()) return [];
return this.supervisor.providersOf('notificationChannel').map((id) => {
const row = db.prepare('SELECT name, capabilities FROM plugins WHERE id = ?').get(id) as
| { name: string; capabilities: string }
| undefined;
let cap: { title?: string; events?: string[] } = {};
try {
cap = ((JSON.parse(row?.capabilities || '{}') as Record<string, unknown>).notificationChannel ?? {}) as typeof cap;
} catch { /* a malformed capabilities blob just means "no overrides" */ }
const allowed = new Set(cap.events?.length ? cap.events : PLUGIN_CHANNEL_EVENTS);
return {
id: pluginChannelId(id),
source: 'plugin' as const,
// A plugin-supplied display string, bounded and emoji-stripped like every other
// one the host renders (cf. the calendar/photo controllers) — it becomes a column
// header in the notification preferences matrix.
label: stripEmoji(String(cap.title || row?.name || id)).slice(0, 40) || id,
// Where the user actually configures this channel. Settings is ONE page with a
// tab, not a route per plugin — a `/settings/plugins/<id>` path would 404.
settingsPath: '/settings?tab=plugins',
// Admin-scoped events never reach a plugin channel — PLUGIN_CHANNEL_EVENTS
// excludes them, and a manifest can only narrow that set, never widen it.
supportsEvent: (event: string) => allowed.has(event),
isConfiguredFor: (userId: number) => hasRequiredUserSettings(id, userId),
sendToUser: (userId: number, msg: ChannelMessage) =>
this.invokeHook(
id,
'notificationChannel',
'send',
[{ event: msg.event, title: msg.title, body: msg.body, url: msg.url, tripName: msg.tripName }, readUserSettingsDecrypted(id, userId)],
// No acting user: a notification is host-initiated for an arbitrary
// recipient, so the hook gets the recipient's config as an argument
// rather than the right to read anything AS them.
undefined,
8000,
),
test: async (userId: number) => {
try {
await this.invokeHook(id, 'notificationChannel', 'test', [readUserSettingsDecrypted(id, userId)], undefined, 8000);
return { success: true };
} catch (e) {
return { success: false, error: e instanceof Error ? e.message : String(e) };
}
},
};
});
}
/** The settings-page action buttons a plugin declared (descriptors, from the DB). */
actionsOf(id: string): Array<{ key: string; label: string; hint?: string; danger: boolean }> {
try {
return (
db.prepare('SELECT action_key, label, hint, danger FROM plugin_actions WHERE plugin_id = ? ORDER BY sort_order').all(id) as Array<{
action_key: string; label: string; hint: string | null; danger: number;
}>
).map((r) => ({ key: r.action_key, label: r.label, hint: r.hint ?? undefined, danger: r.danger === 1 }));
} catch {
return []; // table absent (a slimmed test app)
}
}
/**
* Run a settings-page action for the user who clicked it. The acting user is bound
* host-side (never named by the plugin), so the action reads THAT user's settings and
* any trip read it makes is membership-checked against them.
*/
async invokeAction(id: string, key: string, actingUserId: number): Promise<{ ok: boolean; message?: string }> {
if (!this.actionsOf(id).some((a) => a.key === key)) {
throw new ForbiddenResource(`plugin ${id} did not declare action "${key}"`);
}
const cap = (v: unknown) => stripEmoji(String(v)).slice(0, 200);
try {
const raw = (await this.supervisor.invoke(id, 'invoke.action', { key }, { actingUserId, timeoutMs: 15_000 })) as
| { ok?: unknown; message?: unknown }
| undefined;
// The message is plugin-supplied and rendered to the user — bound it like every
// other plugin string the host displays.
return { ok: raw?.ok !== false, message: raw?.message === undefined ? undefined : cap(raw.message) };
} catch (e) {
// A plugin that throws is reporting a FAILED action, not a server fault — that is
// the documented contract ("throwing == { ok: false }"), and it is the normal path
// for "your credentials don't work". Surface the reason to the user.
return { ok: false, message: cap(e instanceof Error ? e.message : 'Action failed') };
}
}
/** A plugin's declared `capabilities.provides`/`capabilities.emits` (from the DB). */
private capabilityList(id: string, field: 'provides' | 'emits'): string[] {
const row = db.prepare('SELECT capabilities FROM plugins WHERE id = ?').get(id) as { capabilities: string } | undefined;
@@ -1,8 +1,9 @@
import { Body, Controller, Get, Param, Post, Req, UseGuards } from '@nestjs/common';
import { Body, Controller, Get, HttpCode, HttpException, Param, Post, Req, UseGuards } from '@nestjs/common';
import type { Request } from 'express';
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
import { pluginsEnabled } from './kill-switch';
import { PluginsService } from './plugins.service';
import { PluginRuntimeService } from './plugin-runtime.service';
import { db } from '../../db/database';
/**
@@ -19,7 +20,10 @@ import { db } from '../../db/database';
@Controller('api/plugin-settings')
@UseGuards(JwtAuthGuard)
export class PluginUserSettingsController {
constructor(private readonly plugins: PluginsService) {}
constructor(
private readonly plugins: PluginsService,
private readonly runtime: PluginRuntimeService,
) {}
private activeWithUserFields(id: string): boolean {
const row = db.prepare("SELECT 1 FROM plugins WHERE id = ? AND status = 'active'").get(id);
@@ -27,10 +31,43 @@ export class PluginUserSettingsController {
}
@Get(':id')
get(@Param('id') id: string, @Req() req: Request & { user?: { id: number } }): { fields: unknown[]; config: Record<string, unknown> } {
get(@Param('id') id: string, @Req() req: Request & { user?: { id: number } }): {
fields: unknown[];
config: Record<string, unknown>;
actions: Array<{ key: string; label: string; hint?: string; danger: boolean }>;
} {
const userId = req.user?.id;
if (!pluginsEnabled() || userId == null || !this.activeWithUserFields(id)) return { fields: [], config: {} };
return { fields: this.plugins.userSettingsFields(id), config: this.plugins.getUserConfig(id, userId) };
if (!pluginsEnabled() || userId == null || !this.activeWithUserFields(id)) return { fields: [], config: {}, actions: [] };
return {
fields: this.plugins.userSettingsFields(id),
config: this.plugins.getUserConfig(id, userId),
actions: this.runtime.actionsOf(id),
};
}
/**
* Run one of the plugin's declared settings-page actions ("Test connection").
* USER-INITIATED: the acting user is the caller, bound host-side — so the action reads
* the CALLER's own settings and any trip read it makes is checked against them. It can
* never act as anyone else, and a key the plugin didn't declare is refused.
*/
@Post(':id/actions/:key')
@HttpCode(200)
async runAction(
@Param('id') id: string,
@Param('key') key: string,
@Req() req: Request & { user?: { id: number } },
): Promise<{ ok: boolean; message?: string }> {
const userId = req.user?.id;
if (!pluginsEnabled() || userId == null || !this.activeWithUserFields(id)) {
throw new HttpException({ error: 'Plugin is not active' }, 404);
}
try {
return await this.runtime.invokeAction(id, key, userId);
} catch (e) {
// A failing action is a RESULT, not a server error — show the user why.
return { ok: false, message: (e instanceof Error ? e.message : 'Action failed').slice(0, 200) };
}
}
@Post(':id')
@@ -103,6 +103,28 @@ export class PluginsController {
return { config: this.plugins.updateInstanceConfig(id, body || {}) };
}
/**
* Operator-supplied egress hosts. A plugin that talks to a SELF-HOSTED service can't
* name the operator's hostname in its manifest, so an admin adds it here — and the
* runtime re-spawns the plugin with the widened allow-list. Admin-only (this controller
* is admin-guarded): an end user can never widen a plugin's egress.
*/
@Get(':id/egress-hosts')
egressHosts(@Param('id') id: string) {
return { supported: this.runtime.wantsOperatorEgress(id), hosts: this.runtime.operatorEgressHosts(id) };
}
@Put(':id/egress-hosts')
async setEgressHosts(@Param('id') id: string, @Body() body: { hosts?: unknown } = {}) {
if (!pluginsEnabled()) throw new HttpException({ error: 'Plugins are disabled by server configuration' }, 503);
const hosts = Array.isArray(body.hosts) ? body.hosts.map(String) : [];
try {
return { hosts: await this.runtime.setOperatorEgressHosts(id, hosts) };
} catch (e) {
throw new HttpException({ error: e instanceof Error ? e.message : 'Invalid hosts' }, 400);
}
}
@Post(':id/activate')
@HttpCode(200)
async activate(@Param('id') id: string, @Body() body: { consent?: boolean } = {}) {
+77 -4
View File
@@ -37,6 +37,15 @@ interface PluginRawRow {
dependencies: string | null;
}
/** Hosts an admin has added for a plugin (0 unless it declared operatorEgress). */
function egressHostCount(id: string): number {
try {
return (db.prepare('SELECT COUNT(*) AS n FROM plugin_egress_hosts WHERE plugin_id = ?').get(id) as { n: number }).n;
} catch {
return 0; // table absent (a slimmed test app)
}
}
export interface PluginListItem {
id: string;
name: string;
@@ -53,6 +62,10 @@ export interface PluginListItem {
permissions: string;
/** Declared capabilities (JSON string) — e.g. widget slot. */
capabilities: string;
/** The plugin declared it needs OPERATOR-supplied egress hosts (a self-hosted target). */
operatorEgress: boolean;
/** How many hosts an admin has actually added — so the card can nudge when it's 0. */
egressHostCount: number;
/** Declared dependencies (parsed) — required addons + plugin deps. */
dependencies: PluginDependencies;
/** Whether this plugin can currently activate, and why not if it can't. */
@@ -67,7 +80,7 @@ export class PluginsService {
const rows = db
.prepare(
`SELECT id, name, description, type, icon, version, status, enabled, last_error, reviewed_at, source_repo,
permissions, capabilities, dependencies
permissions, capabilities, dependencies, operator_egress
FROM plugins
ORDER BY sort_order, name`,
)
@@ -84,9 +97,11 @@ export class PluginsService {
: state.missing.length || state.versionMismatch.length
? 'missingPlugin'
: 'ok';
const { dependencies: _raw, ...rest } = r;
const { dependencies: _raw, operator_egress: _oe, ...rest } = r as PluginRawRow & { operator_egress?: number };
return {
...rest,
operatorEgress: _oe === 1,
egressHostCount: egressHostCount(r.id),
dependencies: deps,
dependencyStatus,
dependencyIssues: { disabledAddons, missing: state.missing, versionMismatch: state.versionMismatch },
@@ -244,12 +259,28 @@ export class PluginsService {
}
}
/**
* Parse a stored plugin config blob into a NULL-PROTOTYPE object.
*
* The prototype matters: a settings key of `__proto__` or `constructor` would otherwise
* resolve off Object.prototype on read, so `config[key]` comes back truthy for a user who
* has configured nothing — and a *required* field with such a name would report as
* configured for everyone. The manifest now rejects those keys at install
* (SETTING_KEY_RE); this makes it impossible regardless, including for a plugin that was
* installed before that check existed.
*/
function safeParse(json: string): Record<string, unknown> {
const empty = () => Object.create(null) as Record<string, unknown>;
try {
const v = JSON.parse(json || '{}');
return v && typeof v === 'object' && !Array.isArray(v) ? (v as Record<string, unknown>) : {};
if (!v || typeof v !== 'object' || Array.isArray(v)) return empty();
const out = empty();
// JSON.parse creates `__proto__` as an OWN property (it never invokes the setter), so
// copy own keys across onto the null-prototype object rather than trusting the parse.
for (const [k, val] of Object.entries(v as Record<string, unknown>)) out[k] = val;
return out;
} catch {
return {};
return empty();
}
}
function safeArray(json: string): unknown[] | undefined {
@@ -275,6 +306,48 @@ export function readUserSettingDecrypted(pluginId: string, userId: number, key:
if (v == null) return undefined;
return isSecret ? decrypt_api_key(v) : v;
}
/** Host-only: ALL of a plugin's per-user settings for one user, decrypted.
* This is how a notification-channel hook reaches the recipient's credentials —
* that dispatch is host-initiated with no acting user, so `ctx.settings.get()`
* (which resolves against the acting user) would return undefined there. Never
* send this to a client. */
export function readUserSettingsDecrypted(pluginId: string, userId: number): Record<string, unknown> {
const fields = db
.prepare("SELECT field_key, secret FROM plugin_settings_fields WHERE plugin_id = ? AND scope = 'user'")
.all(pluginId) as Array<{ field_key: string; secret: number }>;
const row = db.prepare('SELECT config FROM plugin_user_config WHERE plugin_id = ? AND user_id = ?').get(pluginId, userId) as
| { config: string }
| undefined;
const stored = safeParse(row?.config ?? '{}');
// Null-prototype for the same reason as safeParse: never let a field key write through
// to Object.prototype on the way out to the plugin.
const out: Record<string, unknown> = Object.create(null);
for (const f of fields) {
const v = stored[f.field_key];
if (v == null) continue;
out[f.field_key] = f.secret === 1 ? decrypt_api_key(v) : v;
}
return out;
}
/** Has this user filled in every `required`, `scope:'user'` field the plugin declares?
* A plugin with no required user fields is configured for everyone (an instance-wide
* channel, e.g. a shared workspace webhook). */
export function hasRequiredUserSettings(pluginId: string, userId: number): boolean {
const required = db
.prepare("SELECT field_key FROM plugin_settings_fields WHERE plugin_id = ? AND scope = 'user' AND required = 1")
.all(pluginId) as Array<{ field_key: string }>;
if (required.length === 0) return true;
const row = db.prepare('SELECT config FROM plugin_user_config WHERE plugin_id = ? AND user_id = ?').get(pluginId, userId) as
| { config: string }
| undefined;
const stored = safeParse(row?.config ?? '{}');
return required.every(f => {
const v = stored[f.field_key];
return v != null && String(v) !== '';
});
}
function maskSecrets(config: Record<string, unknown>, secretKeys: Set<string>): Record<string, unknown> {
const out: Record<string, unknown> = {};
for (const [k, v] of Object.entries(config)) {
@@ -328,6 +328,7 @@ export const KNOWN_PERMISSIONS = [
'hook:atlas-layer-provider',
'hook:journal-entry-provider',
'hook:trip-card-provider',
'hook:notification-channel',
// Data-subject-rights hook: the host calls the plugin's deleteUserData /
// exportUserData when a TREK account is erased or its data is exported. Userless
// (the plugin only receives a userId and acts on its OWN db), so it grants no
@@ -74,6 +74,13 @@ interface Registry {
export interface ManifestPreview {
permissions: string[];
egress: string[];
/**
* The plugin talks to a service only the OPERATOR can name (a self-hosted Gotify/ntfy),
* so its `egress` can't be the whole story — an admin adds the real hosts after install.
* Surfaced pre-install so the reviewer knows the network reach is not fully described by
* the hosts listed above.
*/
operatorEgress: boolean;
settings: Array<{ key: string; label: string; inputType: string; scope: string; required: boolean }>;
license: string | null;
icon: string | null;
@@ -390,6 +397,7 @@ function hostCompatible(v: RegistryVersion, host: string): boolean {
*/
function previewManifest(raw: unknown): ManifestPreview {
const m = (raw && typeof raw === 'object' ? raw : {}) as Record<string, unknown>;
const operatorEgress = m.operatorEgress === true;
const strings = (v: unknown): string[] =>
Array.isArray(v) ? v.filter((x): x is string => typeof x === 'string') : [];
const settings = Array.isArray(m.settings)
@@ -413,6 +421,7 @@ function previewManifest(raw: unknown): ManifestPreview {
return {
permissions: strings(m.permissions),
egress: strings(m.egress),
operatorEgress,
settings,
license: typeof m.license === 'string' ? m.license : null,
icon: typeof m.icon === 'string' ? m.icon : null,
@@ -177,6 +177,16 @@ async function handleInvoke(req: { id: string; method: string; params: Record<st
if (!impl || typeof impl[fnName] !== 'function') throw new Error(`no hook ${hookName}.${fnName}`);
const result = await impl[fnName](...args, invCtx);
respond(true, result);
} else if (req.method === 'invoke.action') {
// A settings-page button the user clicked. USER-INITIATED: invCtx carries the
// clicking user, so ctx.settings.get() returns THEIR value and trip reads are
// membership-checked against them (unlike a job or the notificationChannel hook).
const key = req.params.key as string;
const actions = def.actions as Record<string, ((c: PluginContext) => unknown) | undefined> | undefined;
const fn = actions?.[key];
if (typeof fn !== 'function') throw new Error(`no action ${key}`);
const result = await fn(invCtx);
respond(true, result ?? { ok: true });
} else if (req.method === 'invoke.event') {
// A core event fired for a trip. Run every matching subscription. invCtx carries
// NO user (delivered like a job), so trip reads are refused — the handler reacts
@@ -347,6 +347,46 @@ export interface PhotoProvider {
search(query: string, opts: { page: number; limit: number }, ctx: PluginContext): Promise<{ photos: Photo[]; total: number; hasMore: boolean }>;
getById(id: string, ctx: PluginContext): Promise<Photo | null>;
}
/**
* A notification, already rendered by the host into the recipient's language.
* A channel plugin never touches i18n — it only delivers.
*/
export interface NotificationMessage {
/** The TREK event that produced this, e.g. `trip_invite`. */
event: string;
title: string;
body: string;
/** Absolute deep link back into TREK, when the event has one. */
url?: string;
tripName?: string;
}
/**
* Deliver TREK notifications over a channel TREK doesn't ship (Gotify, Pushover, …).
* Needs `hook:notification-channel`.
*
* Unlike every other hook, this one is HOST-initiated for an arbitrary recipient, so
* it runs WITHOUT an acting user: `ctx.settings.get()` returns undefined here and trip
* reads are refused. The recipient's own `scope:'user'` settings are decrypted by the
* host and handed to you as `config` instead — that is the only way to reach them, and
* it is why a channel plugin cannot enumerate the recipient's trips.
*/
export interface NotificationChannel {
send(msg: NotificationMessage, config: Record<string, unknown>, ctx: PluginContext): Promise<void>;
/** Backs the "Send test" button in the user's notification settings. */
test?(config: Record<string, unknown>, ctx: PluginContext): Promise<void>;
}
/**
* Result of a settings-page action. `message` is shown to the user beside the button
* (bounded + emoji-stripped host-side); throwing is equivalent to `{ ok: false }` with
* the error message.
*/
export interface PluginActionResult {
ok?: boolean;
message?: string;
}
export interface CalendarEvent { id: string; title: string; start: string; end: string; allDay: boolean; }
export interface CalendarSource {
getName(ctx: PluginContext): string;
@@ -504,6 +544,16 @@ export interface PluginDefinition {
/** GDPR portability: return the data you hold about a user (own db only), as a
* JSON-serialisable value the host aggregates. Userless. Needs `hook:user-data`. */
exportUserData?(input: { userId: number }, ctx: PluginContext): Promise<unknown> | unknown;
/**
* Buttons on the plugin's own settings page ("Test connection", "Sync now"). The key
* must match an entry in the manifest's `actions`.
*
* USER-INITIATED, so unlike the notificationChannel hook there IS an acting user — the
* person who clicked. `ctx.settings.get()` returns THEIR value and trip reads are
* membership-checked against them, which is what makes a "test my credentials" button
* possible at all.
*/
actions?: Record<string, (ctx: PluginContext) => Promise<PluginActionResult | void> | PluginActionResult | void>;
events?: PluginEventSubscription[];
hooks?: {
photoProvider?: PhotoProvider;
@@ -516,6 +566,7 @@ export interface PluginDefinition {
atlasLayerProvider?: AtlasLayerProvider;
journalEntryProvider?: JournalEntryProvider;
tripCardProvider?: TripCardProvider;
notificationChannel?: NotificationChannel;
};
/** Functions exposed to dependents (names must match manifest capabilities.provides). */
exports?: Record<string, PluginExport>;
@@ -105,6 +105,7 @@ const HOOK_PERMISSION: Readonly<Record<string, string>> = {
atlasLayerProvider: 'hook:atlas-layer-provider',
journalEntryProvider: 'hook:journal-entry-provider',
tripCardProvider: 'hook:trip-card-provider',
notificationChannel: 'hook:notification-channel',
};
export class PluginSupervisor {
@@ -1,10 +1,23 @@
import type Database from 'better-sqlite3';
import { db } from '../db/database';
import { decrypt_api_key } from './apiKeyCrypto';
import { isSmtpConfigured } from './notifications';
import { listChannels, type ExternalChannel } from './notifications/channelRegistry';
// Side-effect import: populates the registry with email/webhook/ntfy. Safe from
// here — builtins only reaches ../notifications, which imports this module's
// types with `import type`, so there is no runtime cycle.
import './notifications/builtins';
// ── Types ──────────────────────────────────────────────────────────────────
export type NotifChannel = 'email' | 'webhook' | 'inapp' | 'ntfy';
/**
* A channel id. Open by design: the built-ins below plus `plugin:<id>` for any
* plugin implementing the `notificationChannel` hook. The DB column is a bare
* TEXT with no CHECK constraint and the Zod contract is already a string record,
* so the set was only ever closed in TypeScript.
*/
export type NotifChannel = string;
export const INAPP_CHANNEL = 'inapp';
export type NotifEventType =
| 'trip_invite'
@@ -20,29 +33,51 @@ export type NotifEventType =
| 'synology_session_cleared'
| 'plugin_notification';
export interface AvailableChannels {
email: boolean;
webhook: boolean;
inapp: boolean;
ntfy: boolean;
/** Every event, in the order the preferences UI lists them. */
export const ALL_EVENT_TYPES: NotifEventType[] = [
'trip_invite',
'booking_change',
'trip_reminder',
'todo_due',
'vacay_invite',
'collection_invite',
'photos_shared',
'collab_message',
'packing_tagged',
'version_available',
'synology_session_cleared',
'plugin_notification',
];
/** One channel column in the preferences matrix. */
export interface ChannelDescriptor {
id: string;
source: 'builtin' | 'plugin';
/** Built-ins: an i18n key. */
labelKey?: string;
/** Plugin channels: a literal display name. */
label?: string;
/** Where the user sets their credentials for this channel, if anywhere. */
settingsPath?: string;
/** The admin has enabled this channel (in-app is always on). */
active: boolean;
/** This user has credentials for it. */
configured: boolean;
}
// Which channels are implemented for each event type.
// Only implemented combos show toggles in the user preferences UI.
const IMPLEMENTED_COMBOS: Record<NotifEventType, NotifChannel[]> = {
trip_invite: ['inapp', 'email', 'webhook', 'ntfy'],
booking_change: ['inapp', 'email', 'webhook', 'ntfy'],
trip_reminder: ['inapp', 'email', 'webhook', 'ntfy'],
todo_due: ['inapp', 'email', 'webhook', 'ntfy'],
vacay_invite: ['inapp', 'email', 'webhook', 'ntfy'],
collection_invite: ['inapp', 'email', 'webhook', 'ntfy'],
photos_shared: ['inapp', 'email', 'webhook', 'ntfy'],
collab_message: ['inapp', 'email', 'webhook', 'ntfy'],
packing_tagged: ['inapp', 'email', 'webhook', 'ntfy'],
version_available: ['inapp', 'email', 'webhook', 'ntfy'],
synology_session_cleared: ['inapp'],
plugin_notification: ['inapp', 'email', 'webhook', 'ntfy'],
};
/**
* Channels implemented for an event. In-app takes everything; external channels
* decide for themselves (today: everything except `synology_session_cleared`).
*/
export function combosFor(event: NotifEventType): NotifChannel[] {
return [INAPP_CHANNEL, ...listChannels().filter(c => c.supportsEvent(event)).map(c => c.id)];
}
function allCombos(): Record<string, NotifChannel[]> {
const out: Record<string, NotifChannel[]> = {};
for (const event of ALL_EVENT_TYPES) out[event] = combosFor(event);
return out;
}
/** Events that target admins only (shown in admin panel, not in user settings). */
export const ADMIN_SCOPED_EVENTS = new Set<NotifEventType>(['version_available']);
@@ -56,24 +91,26 @@ function getAppSetting(key: string): string | null {
// ── Active channels (admin-configured) ────────────────────────────────────
/**
* Returns which channels the admin has enabled (email and/or webhook).
* Which channels the admin has enabled, as ids.
* Reads `notification_channels` (plural) with fallback to `notification_channel` (singular).
* In-app is always considered active at the service level.
*
* BUILT-INS ONLY. A plugin channel is NOT gated on this list: a built-in always exists in
* the code and so needs an explicit switch, but a plugin channel only exists because an
* admin installed and enabled that plugin — that IS the opt-in. Requiring a second one
* meant a plugin channel could never be turned on at all (nothing writes a `plugin:` id
* into this CSV, and the admin toggle rebuilds it from the three built-in booleans, which
* would silently drop any that were).
*/
export function getActiveChannels(): NotifChannel[] {
const raw = getAppSetting('notification_channels') || getAppSetting('notification_channel') || 'none';
if (raw === 'none') return [];
return raw.split(',').map(c => c.trim()).filter((c): c is NotifChannel => c === 'email' || c === 'webhook' || c === 'ntfy');
const builtins = new Set(listChannels().filter(c => c.source === 'builtin').map(c => c.id));
return raw.split(',').map(c => c.trim()).filter(c => builtins.has(c));
}
/**
* Returns which channels are configured (have valid credentials/URLs set).
* In-app is always available. Email/webhook depend on configuration.
*/
export function getAvailableChannels(): AvailableChannels {
const hasSmtp = !!(process.env.SMTP_HOST || getAppSetting('smtp_host'));
const activeChannels = getActiveChannels();
return { email: hasSmtp, webhook: activeChannels.includes('webhook'), ntfy: activeChannels.includes('ntfy'), inapp: true };
/** Is this channel switched on? Plugin channels are on by virtue of being live. */
export function isChannelActive(channel: ExternalChannel): boolean {
return channel.source === 'plugin' || getActiveChannels().includes(channel.id);
}
// ── Per-user preference checks ─────────────────────────────────────────────
@@ -93,12 +130,71 @@ export function isEnabledForEvent(userId: number, eventType: NotifEventType, cha
export interface PreferencesMatrix {
preferences: Partial<Record<NotifEventType, Partial<Record<NotifChannel, boolean>>>>;
available_channels: AvailableChannels;
/** The columns to render, in order. Replaces the old fixed-shape available_channels. */
channels: ChannelDescriptor[];
event_types: NotifEventType[];
implemented_combos: Record<NotifEventType, NotifChannel[]>;
implemented_combos: Record<string, NotifChannel[]>;
defaults?: { ntfyServer: string | null };
}
/** The in-app pseudo-channel — always active, never configurable. */
function inAppDescriptor(): ChannelDescriptor {
return {
id: INAPP_CHANNEL,
source: 'builtin',
labelKey: 'settings.notificationPreferences.inapp',
active: true,
configured: true,
};
}
/**
* The channel columns for a scope.
* scope='user' — a column per channel the admin turned on in `notification_channels`.
* scope='admin' — a column per channel that has admin-global credentials.
*/
function describeChannels(userId: number, scope: 'user' | 'admin'): ChannelDescriptor[] {
const out: ChannelDescriptor[] = [inAppDescriptor()];
if (scope === 'admin') {
// Admin-scoped events go out over the admin's own global credentials, which
// are independent of the per-user `notification_channels` toggle.
const hasSmtp = isSmtpConfigured();
const hasAdminWebhook = !!getAppSetting('admin_webhook_url');
const hasAdminNtfy = !!getAppSetting('admin_ntfy_topic');
const adminActive: Record<string, boolean> = { email: hasSmtp, webhook: hasAdminWebhook, ntfy: hasAdminNtfy };
for (const channel of listChannels()) {
// Plugin channels are user-scoped only — they never carry admin-global events.
if (channel.source !== 'builtin') continue;
const active = adminActive[channel.id] ?? false;
out.push({
id: channel.id,
source: channel.source,
labelKey: channel.labelKey,
label: channel.label,
active,
configured: active,
});
}
return out;
}
for (const channel of listChannels()) {
out.push({
id: channel.id,
source: channel.source,
labelKey: channel.labelKey,
label: channel.label,
settingsPath: channel.settingsPath,
// A live plugin channel is always a column. `configured` tells the user whether
// they still need to enter credentials — it does not hide the channel from them.
active: isChannelActive(channel),
configured: channel.isConfiguredFor(userId),
});
}
return out;
}
/**
* Returns the preferences matrix for a user.
* scope='user' — excludes admin-scoped events (for user settings page)
@@ -116,16 +212,16 @@ export function getPreferencesMatrix(userId: number, userRole: string, scope: 'u
stored[row.event_type]![row.channel] = row.enabled === 1;
}
const implemented_combos = allCombos();
// Build the full matrix with defaults (true when no row exists)
const preferences: Partial<Record<NotifEventType, Partial<Record<NotifChannel, boolean>>>> = {};
const allEvents = Object.keys(IMPLEMENTED_COMBOS) as NotifEventType[];
for (const eventType of allEvents) {
const channels = IMPLEMENTED_COMBOS[eventType];
for (const eventType of ALL_EVENT_TYPES) {
preferences[eventType] = {};
for (const channel of channels) {
// Admin-scoped events use global settings for email/webhook/ntfy
if (scope === 'admin' && ADMIN_SCOPED_EVENTS.has(eventType) && (channel === 'email' || channel === 'webhook' || channel === 'ntfy')) {
for (const channel of implemented_combos[eventType]) {
// Admin-scoped events use global settings for the built-in external channels
if (scope === 'admin' && ADMIN_SCOPED_EVENTS.has(eventType) && isAdminGlobalChannel(channel)) {
preferences[eventType]![channel] = getAdminGlobalPref(eventType, channel);
} else {
preferences[eventType]![channel] = stored[eventType]?.[channel] ?? true;
@@ -135,50 +231,43 @@ export function getPreferencesMatrix(userId: number, userRole: string, scope: 'u
// Filter event types by scope
const event_types = scope === 'admin'
? allEvents.filter(e => ADMIN_SCOPED_EVENTS.has(e))
: allEvents.filter(e => !ADMIN_SCOPED_EVENTS.has(e));
// Available channels depend on scope
let available_channels: AvailableChannels;
if (scope === 'admin') {
const hasSmtp = !!(process.env.SMTP_HOST || getAppSetting('smtp_host'));
const hasAdminWebhook = !!(getAppSetting('admin_webhook_url'));
const hasAdminNtfy = !!(getAppSetting('admin_ntfy_topic'));
available_channels = { email: hasSmtp, webhook: hasAdminWebhook, ntfy: hasAdminNtfy, inapp: true };
} else {
const activeChannels = getActiveChannels();
available_channels = {
email: activeChannels.includes('email'),
webhook: activeChannels.includes('webhook'),
ntfy: activeChannels.includes('ntfy'),
inapp: true,
};
}
? ALL_EVENT_TYPES.filter(e => ADMIN_SCOPED_EVENTS.has(e))
: ALL_EVENT_TYPES.filter(e => !ADMIN_SCOPED_EVENTS.has(e));
return {
preferences,
available_channels,
channels: describeChannels(userId, scope),
event_types,
implemented_combos: IMPLEMENTED_COMBOS,
implemented_combos,
...(scope === 'user' && { defaults: { ntfyServer: getAppSetting('admin_ntfy_server') || null } }),
};
}
// ── Admin global preferences (stored in app_settings) ─────────────────────
const ADMIN_GLOBAL_CHANNELS: NotifChannel[] = ['email', 'webhook', 'ntfy'];
/**
* Channels whose admin-scoped preference is global (app_settings) rather than
* per-user. Built-ins only: plugin channels are user-scoped and never carry
* admin-scoped events.
*/
const ADMIN_GLOBAL_CHANNELS = ['email', 'webhook', 'ntfy'] as const;
export type AdminGlobalChannel = (typeof ADMIN_GLOBAL_CHANNELS)[number];
export function isAdminGlobalChannel(channel: string): channel is AdminGlobalChannel {
return (ADMIN_GLOBAL_CHANNELS as readonly string[]).includes(channel);
}
/**
* Returns the global admin preference for an event+channel.
* Stored in app_settings as `admin_notif_pref_{event}_{channel}`.
* Defaults to true (enabled) when no row exists.
*/
export function getAdminGlobalPref(event: NotifEventType, channel: 'email' | 'webhook' | 'ntfy'): boolean {
export function getAdminGlobalPref(event: NotifEventType, channel: AdminGlobalChannel): boolean {
const val = getAppSetting(`admin_notif_pref_${event}_${channel}`);
return val !== '0';
}
function setAdminGlobalPref(event: NotifEventType, channel: 'email' | 'webhook' | 'ntfy', enabled: boolean): void {
function setAdminGlobalPref(event: NotifEventType, channel: AdminGlobalChannel, enabled: boolean): void {
db.prepare('INSERT OR REPLACE INTO app_settings (key, value) VALUES (?, ?)').run(
`admin_notif_pref_${event}_${channel}`,
enabled ? '1' : '0'
@@ -248,7 +337,7 @@ export function setAdminPreferences(
for (const [eventType, channels] of Object.entries(prefs)) {
if (!channels) continue;
for (const [channel, enabled] of Object.entries(channels)) {
if (ADMIN_GLOBAL_CHANNELS.includes(channel as NotifChannel)) {
if (isAdminGlobalChannel(channel)) {
if (!globalPrefs[eventType]) globalPrefs[eventType] = {};
globalPrefs[eventType]![channel] = enabled;
} else {
@@ -262,7 +351,8 @@ export function setAdminPreferences(
for (const [eventType, channels] of Object.entries(globalPrefs)) {
if (!channels) continue;
for (const [channel, enabled] of Object.entries(channels)) {
setAdminGlobalPref(eventType as NotifEventType, channel as 'email' | 'webhook' | 'ntfy', enabled);
if (!isAdminGlobalChannel(channel)) continue;
setAdminGlobalPref(eventType as NotifEventType, channel, enabled);
}
}
@@ -271,10 +361,10 @@ export function setAdminPreferences(
}
// ── SMTP availability helper (for authService) ─────────────────────────────
// Lives in ./notifications now (the module that owns SMTP config); re-exported
// here so existing importers keep working.
export function isSmtpConfigured(): boolean {
return !!(process.env.SMTP_HOST || getAppSetting('smtp_host'));
}
export { isSmtpConfigured };
export function isWebhookConfigured(): boolean {
return getActiveChannels().includes('webhook');
+71 -72
View File
@@ -4,25 +4,12 @@ import {
getActiveChannels,
isEnabledForEvent,
getAdminGlobalPref,
isSmtpConfigured,
isAdminGlobalChannel,
ADMIN_SCOPED_EVENTS,
type NotifEventType,
type NotifChannel,
} from './notificationPreferencesService';
import {
getEventText,
sendEmail,
sendWebhook,
sendNtfy,
getUserEmail,
getUserLanguage,
getUserWebhookUrl,
getAdminWebhookUrl,
getUserNtfyConfig,
getAdminNtfyConfig,
resolveNtfyUrl,
getAppUrl,
} from './notifications';
import { getEventText, getUserLanguage, getAppUrl } from './notifications';
import { listChannels, type ChannelMessage, type ExternalChannel } from './notifications/channelRegistry';
import {
resolveRecipients,
createNotificationForRecipient,
@@ -177,6 +164,40 @@ export interface NotificationPayload {
};
}
/**
* Should this channel deliver this event to this recipient?
*
* Encodes, unchanged, the gating the four hand-written dispatch blocks used to do:
* - admin-scoped events (version_available) reach recipients only over a channel
* that bypasses the `notification_channels` toggle (email), gated by the admin
* global pref rather than the per-user opt-out. Their webhook/ntfy copies go out
* once, globally, via sendGlobal() below — not per recipient.
* - everything else: the admin enabled the channel, the user didn't opt out of this
* event on it, and the user has credentials for it.
*/
function shouldSendToUser(
channel: ExternalChannel,
event: NotifEventType,
recipientId: number,
activeChannels: string[],
): boolean {
if (!channel.supportsEvent(event)) return false;
if (channel.isInstanceConfigured && !channel.isInstanceConfigured()) return false;
if (ADMIN_SCOPED_EVENTS.has(event)) {
if (!channel.bypassesActiveToggleForAdminEvents) return false;
if (!isAdminGlobalChannel(channel.id)) return false;
if (!getAdminGlobalPref(event, channel.id)) return false;
} else {
// A built-in needs the admin's explicit switch; a plugin channel is on because the
// admin enabled the plugin — that IS the opt-in (see getActiveChannels).
if (channel.source === 'builtin' && !activeChannels.includes(channel.id)) return false;
if (!isEnabledForEvent(recipientId, event, channel.id)) return false;
}
return channel.isConfiguredFor(recipientId);
}
export async function send(payload: NotificationPayload): Promise<void> {
const { event, actorId, params, scope, targetId, inApp } = payload;
@@ -202,6 +223,7 @@ export async function send(payload: NotificationPayload): Promise<void> {
}
const config = configEntry ?? FALLBACK_EVENT_CONFIG;
const activeChannels = getActiveChannels();
const channels = listChannels();
const appUrl = getAppUrl();
// Build navigate target (used by email/webhook CTA and in-app navigate)
@@ -273,43 +295,23 @@ export async function send(payload: NotificationPayload): Promise<void> {
);
}
// ── Email ────────────────────────────────────────────────────────────
// Admin-scoped events: use global pref + SMTP check (bypass notification_channels toggle)
// Regular events: use active channels + per-user pref
const emailEnabled = ADMIN_SCOPED_EVENTS.has(event)
? isSmtpConfigured() && getAdminGlobalPref(event, 'email')
: activeChannels.includes('email') && isEnabledForEvent(recipientId, event, 'email');
if (emailEnabled) {
const email = getUserEmail(recipientId);
if (email) {
const lang = getUserLanguage(recipientId);
const { title, body } = getEventText(lang, event, params);
promises.push(sendEmail(email, title, body, recipientId, navigateTarget ?? undefined));
}
}
// ── Webhook (per-user) — skip for admin-scoped events (handled globally below) ──
if (!ADMIN_SCOPED_EVENTS.has(event) && activeChannels.includes('webhook') && isEnabledForEvent(recipientId, event, 'webhook')) {
const webhookUrl = getUserWebhookUrl(recipientId);
if (webhookUrl) {
const lang = getUserLanguage(recipientId);
const { title, body } = getEventText(lang, event, params);
promises.push(sendWebhook(webhookUrl, { event, title, body, tripName: params.trip, link: fullLink }));
}
}
// ── Ntfy (per-user) — skip for admin-scoped events (handled globally below) ──
if (!ADMIN_SCOPED_EVENTS.has(event) && activeChannels.includes('ntfy') && isEnabledForEvent(recipientId, event, 'ntfy' as NotifChannel)) {
const userNtfyCfg = getUserNtfyConfig(recipientId);
const adminNtfyCfg = getAdminNtfyConfig();
const ntfyUrl = resolveNtfyUrl(adminNtfyCfg, userNtfyCfg);
if (ntfyUrl) {
const lang = getUserLanguage(recipientId);
const { title, body } = getEventText(lang, event, params);
const token = userNtfyCfg?.token ?? adminNtfyCfg.token;
promises.push(sendNtfy(ntfyUrl, token, { event, title, body, link: fullLink }));
}
// ── External channels (email, webhook, ntfy, plugin:*) ───────────────
// One loop over the registry. The message is rendered once per recipient, in
// their language, and handed to every channel that wants it — so a plugin
// channel never touches i18n.
const deliverable = channels.filter(ch => shouldSendToUser(ch, event, recipientId, activeChannels));
if (deliverable.length > 0) {
const lang = getUserLanguage(recipientId);
const { title, body } = getEventText(lang, event, params);
const msg: ChannelMessage = {
event,
title,
body,
navigateTarget: navigateTarget ?? undefined,
url: fullLink,
tripName: params.trip,
};
for (const ch of deliverable) promises.push(ch.sendToUser(recipientId, msg));
}
const results = await Promise.allSettled(promises);
@@ -320,26 +322,23 @@ export async function send(payload: NotificationPayload): Promise<void> {
}
}));
// ── Admin webhook (scope: admin) — global, respects global pref ──────
if (scope === 'admin' && getAdminGlobalPref(event, 'webhook')) {
const adminWebhookUrl = getAdminWebhookUrl();
if (adminWebhookUrl) {
// ── Admin-global copies (scope: admin) ───────────────────────────────
// One send per channel, over the admin's own credentials, not per-recipient.
// Always rendered in English — there is no single recipient to take a language from.
if (scope === 'admin') {
const globalChannels = channels.filter(
ch => ch.sendGlobal && ch.supportsEvent(event) && isAdminGlobalChannel(ch.id) && getAdminGlobalPref(event, ch.id),
);
if (globalChannels.length > 0) {
const { title, body } = getEventText('en', event, params);
await sendWebhook(adminWebhookUrl, { event, title, body, link: fullLink }).catch((err: unknown) => {
logError(`notificationService.send admin webhook failed event=${event}: ${err instanceof Error ? err.message : err}`);
});
}
}
// ── Admin ntfy (scope: admin) — global, respects global pref ─────────
if (scope === 'admin' && getAdminGlobalPref(event, 'ntfy')) {
const adminNtfyCfg = getAdminNtfyConfig();
const adminNtfyUrl = resolveNtfyUrl(adminNtfyCfg, null);
if (adminNtfyUrl) {
const { title, body } = getEventText('en', event, params);
await sendNtfy(adminNtfyUrl, adminNtfyCfg.token, { event, title, body, link: fullLink }).catch((err: unknown) => {
logError(`notificationService.send admin ntfy failed event=${event}: ${err instanceof Error ? err.message : err}`);
});
const msg: ChannelMessage = { event, title, body, navigateTarget: navigateTarget ?? undefined, url: fullLink };
await Promise.all(
globalChannels.map(ch =>
ch.sendGlobal!(msg).catch((err: unknown) => {
logError(`notificationService.send admin ${ch.id} failed event=${event}: ${err instanceof Error ? err.message : err}`);
}),
),
);
}
}
}
+5
View File
@@ -92,6 +92,11 @@ export function getMcpSafeUrl(): string {
return `http://localhost:${port}`;
}
/** Is SMTP configured at the instance level? (Independent of any one user's address.) */
export function isSmtpConfigured(): boolean {
return !!(process.env.SMTP_HOST || getAppSetting('smtp_host'));
}
export function getUserEmail(userId: number): string | null {
// Defense-in-depth (#1362): a guest's synthetic email must never be emailed.
return (db.prepare('SELECT email FROM users WHERE id = ? AND COALESCE(is_guest, 0) = 0').get(userId) as { email: string } | undefined)?.email || null;
@@ -0,0 +1,117 @@
import {
sendEmail,
sendWebhook,
sendNtfy,
testSmtp,
testWebhook,
testNtfy,
isSmtpConfigured,
getUserEmail,
getUserWebhookUrl,
getAdminWebhookUrl,
getUserNtfyConfig,
getAdminNtfyConfig,
resolveNtfyUrl,
} from '../notifications';
import { registerChannel, type ChannelMessage, type ExternalChannel } from './channelRegistry';
// The three built-in external channels, wrapping the send functions and config
// resolvers that already live in ../notifications.ts. No delivery logic is
// rewritten here — it is only relocated behind the ExternalChannel interface so
// notificationService.send() can iterate instead of branching.
/**
* Every event except `synology_session_cleared` is deliverable externally.
* This is the pre-registry IMPLEMENTED_COMBOS table, transposed: it listed
* ['inapp','email','webhook','ntfy'] for every event and ['inapp'] for that one.
*/
function supportsAllButSynology(event: string): boolean {
return event !== 'synology_session_cleared';
}
const emailChannel: ExternalChannel = {
id: 'email',
source: 'builtin',
labelKey: 'settings.notificationPreferences.email',
// Admin-scoped events (version_available) reach admins by email even when the
// admin has not put `email` in notification_channels — the admin global pref
// gates it instead. Verbatim from the pre-registry dispatch.
bypassesActiveToggleForAdminEvents: true,
supportsEvent: supportsAllButSynology,
isInstanceConfigured: isSmtpConfigured,
isConfiguredFor: (userId) => !!getUserEmail(userId),
async sendToUser(userId, msg) {
const email = getUserEmail(userId);
if (!email) return false;
return sendEmail(email, msg.title, msg.body, userId, msg.navigateTarget);
},
async test(userId) {
const email = getUserEmail(userId);
if (!email) return { success: false, error: 'No email address on file' };
return testSmtp(email);
},
};
const webhookChannel: ExternalChannel = {
id: 'webhook',
source: 'builtin',
labelKey: 'settings.notificationPreferences.webhook',
supportsAdminGlobal: true,
supportsEvent: supportsAllButSynology,
isConfiguredFor: (userId) => !!getUserWebhookUrl(userId),
async sendToUser(userId, msg) {
const url = getUserWebhookUrl(userId);
if (!url) return false;
return sendWebhook(url, { event: msg.event, title: msg.title, body: msg.body, tripName: msg.tripName, link: msg.url });
},
async sendGlobal(msg: ChannelMessage) {
const url = getAdminWebhookUrl();
if (!url) return false;
return sendWebhook(url, { event: msg.event, title: msg.title, body: msg.body, link: msg.url });
},
async test(userId, override) {
const url = (typeof override?.url === 'string' && override.url) || getUserWebhookUrl(userId);
if (!url) return { success: false, error: 'No webhook URL configured' };
return testWebhook(url);
},
};
const ntfyChannel: ExternalChannel = {
id: 'ntfy',
source: 'builtin',
labelKey: 'settings.notificationPreferences.ntfy',
supportsAdminGlobal: true,
supportsEvent: supportsAllButSynology,
isConfiguredFor: (userId) => !!resolveNtfyUrl(getAdminNtfyConfig(), getUserNtfyConfig(userId)),
async sendToUser(userId, msg) {
const userCfg = getUserNtfyConfig(userId);
const adminCfg = getAdminNtfyConfig();
const url = resolveNtfyUrl(adminCfg, userCfg);
if (!url) return false;
return sendNtfy(url, userCfg?.token ?? adminCfg.token, { event: msg.event, title: msg.title, body: msg.body, link: msg.url });
},
async sendGlobal(msg: ChannelMessage) {
const adminCfg = getAdminNtfyConfig();
const url = resolveNtfyUrl(adminCfg, null);
if (!url) return false;
return sendNtfy(url, adminCfg.token, { event: msg.event, title: msg.title, body: msg.body, link: msg.url });
},
async test(userId, override) {
const topic = typeof override?.topic === 'string' ? override.topic : getUserNtfyConfig(userId)?.topic;
if (!topic) return { success: false, error: 'Could not resolve ntfy URL — missing topic' };
return testNtfy({
topic,
server: typeof override?.server === 'string' ? override.server : null,
token: typeof override?.token === 'string' ? override.token : null,
});
},
};
export const BUILTIN_CHANNELS = [emailChannel, webhookChannel, ntfyChannel];
/** Idempotent — safe to call from every entry point that needs the registry populated. */
export function registerBuiltinChannels(): void {
for (const channel of BUILTIN_CHANNELS) registerChannel(channel);
}
registerBuiltinChannels();
@@ -0,0 +1,164 @@
import type { NotifEventType } from '../notificationPreferencesService';
// ── External notification channels ─────────────────────────────────────────
//
// A channel is anything that delivers a *rendered* notification out of TREK:
// email, webhook, ntfy, and any plugin that implements the `notificationChannel`
// hook. In-app is deliberately NOT a channel — it writes typed rows with
// scope/target/callback payloads rather than a title+body, so it keeps its own
// path in notificationService.send(). The split mirrors the one shared/ already
// draws in i18n/<locale>/externalNotifications.ts.
//
// Channels are declarative: they say what they support and whether a given user
// has credentials, and they send. They do NOT consult preferences — the admin
// toggle (`notification_channels`) and the per-user event opt-outs are applied by
// the dispatch loop. That keeps this module free of any runtime dependency on
// notificationPreferencesService, which in turn imports listChannels() from here.
/** A notification already rendered into the recipient's language. */
export interface ChannelMessage {
event: NotifEventType;
title: string;
body: string;
/** Relative navigate target (e.g. `/trips/12`) — what the email CTA builder takes. */
navigateTarget?: string;
/** Absolute link (appUrl + navigateTarget) — what webhook/ntfy/plugin payloads carry. */
url?: string;
tripName?: string;
}
export interface ExternalChannel {
readonly id: string;
readonly source: 'builtin' | 'plugin';
/** Built-ins: an i18n key the client resolves. */
readonly labelKey?: string;
/** Plugin channels: a literal display name (the host has no i18n for it). */
readonly label?: string;
/** Where the user configures their credentials, if anywhere. */
readonly settingsPath?: string;
/**
* Admin-scoped events (`version_available`) bypass the `notification_channels`
* toggle for this channel and are gated by the admin global pref instead.
* Only email does this today; preserved verbatim from the pre-registry dispatch.
*/
readonly bypassesActiveToggleForAdminEvents?: boolean;
/** Delivers the one admin-scoped global copy (not per-recipient). */
readonly supportsAdminGlobal?: boolean;
supportsEvent(event: NotifEventType): boolean;
/**
* Instance-level readiness, independent of any one recipient (email: is SMTP set
* up at all?). Absent means "always ready".
*/
isInstanceConfigured?(): boolean;
/** Does this recipient have credentials for this channel? */
isConfiguredFor(userId: number): boolean;
sendToUser(userId: number, msg: ChannelMessage): Promise<unknown>;
sendGlobal?(msg: ChannelMessage): Promise<unknown>;
test?(userId: number, override?: Record<string, unknown>): Promise<{ success: boolean; error?: string }>;
}
/** Namespace for plugin channel ids, so a plugin can never claim `email`. */
export const PLUGIN_CHANNEL_PREFIX = 'plugin:';
export function pluginChannelId(pluginId: string): string {
return `${PLUGIN_CHANNEL_PREFIX}${pluginId}`;
}
export function isPluginChannelId(id: string): boolean {
return id.startsWith(PLUGIN_CHANNEL_PREFIX);
}
// ── Registry ───────────────────────────────────────────────────────────────
const builtins = new Map<string, ExternalChannel>();
/** Register a built-in channel. Called at import of ./builtins. */
export function registerChannel(channel: ExternalChannel): void {
// The `plugin:` namespace belongs to plugins; a built-in claiming it would make
// getChannel() resolve inconsistently (it routes namespaced ids past this map).
if (isPluginChannelId(channel.id)) throw new Error(`built-in channel cannot claim the plugin namespace: ${channel.id}`);
builtins.set(channel.id, channel);
}
/**
* Plugin channels cross a trust boundary, so re-establish their invariants HERE
* rather than trusting whoever produced them.
*
* The runtime mints ids with pluginChannelId() and leaves the built-in-only privileges
* off — but nothing structural stopped a bug (or a future caller) from handing us a
* channel that claims `email`. Such a channel would be dispatched to off the user's
* EMAIL opt-in, without them ever enabling a plugin channel, and — because
* isAdminGlobalChannel('email') is true — would also receive admin-scoped events and
* the admin-global copy. Same reasoning as providersOf()/invokeHook re-checking the
* hook grant host-side even though the child reports its own hooks.
*/
function sanitizePluginChannels(raw: readonly ExternalChannel[]): ExternalChannel[] {
const out: ExternalChannel[] = [];
const seen = new Set<string>();
for (const c of raw) {
if (!c || typeof c.id !== 'string') continue;
if (!isPluginChannelId(c.id)) continue; // must be namespaced …
if (builtins.has(c.id)) continue; // … and can never shadow a built-in
if (seen.has(c.id)) continue; // no duplicate columns / double sends
seen.add(c.id);
out.push({
id: c.id,
source: 'plugin',
label: c.label,
settingsPath: c.settingsPath,
// Built-in-only privileges, stripped unconditionally. A plugin channel is
// user-scoped: it never bypasses the admin's channel toggle, and never carries an
// admin-scoped or admin-global notification. (With these off, notificationService
// refuses it an ADMIN_SCOPED_EVENT and the admin-global loop skips it — so this
// holds even if the channel lies in supportsEvent().)
bypassesActiveToggleForAdminEvents: false,
supportsAdminGlobal: false,
// Bound, so a producer that used a class keeps its `this`.
supportsEvent: (e) => c.supportsEvent(e),
isConfiguredFor: (u) => c.isConfiguredFor(u),
sendToUser: (u, m) => c.sendToUser(u, m),
...(c.isInstanceConfigured ? { isInstanceConfigured: () => c.isInstanceConfigured!() } : {}),
...(c.test ? { test: (u: number, o?: Record<string, unknown>) => c.test!(u, o) } : {}),
// NB: sendGlobal is deliberately NOT carried over.
});
}
return out;
}
// Plugin channels are supplied by the plugin runtime, which lives in the Nest
// graph and cannot be imported from a plain service. Same seam as
// setPluginEventSink() in plugin-runtime.service.ts: the runtime pushes a getter
// in at onModuleInit, and we pull from it on every read so a plugin that is
// disabled or uninstalled simply stops appearing.
let pluginChannelSource: (() => ExternalChannel[]) | null = null;
export function setPluginChannelSource(source: (() => ExternalChannel[]) | null): void {
pluginChannelSource = source;
}
/** Every channel that currently exists: built-ins plus live, sanitized plugin channels. */
export function listChannels(): ExternalChannel[] {
const plugins = (() => {
try {
return pluginChannelSource?.() ?? [];
} catch {
// A broken plugin runtime must never take notifications down with it.
return [];
}
})();
// Built-ins first, and they always win: a plugin channel can only ever be an
// addition, never an override.
return [...builtins.values(), ...sanitizePluginChannels(plugins)];
}
export function getChannel(id: string): ExternalChannel | undefined {
if (isPluginChannelId(id)) return listChannels().find((c) => c.id === id);
return builtins.get(id);
}
/** Test seam — drops registered built-ins. */
export function __resetChannelsForTest(): void {
builtins.clear();
pluginChannelSource = null;
}