Skip to content

armgit / TREK

Public Imported from GitHub
0

The most complete open-source travel planner: real-time collaboration, bookings, budgets, packing lists, journals, offline PWA, SSO and an AI-ready MCP server, with planet-wide place search and routing built in.

refactor(server): give the notification vocabulary its own module

Maurice712a33626a01
diff --git a/server/src/nest/notifications/notification-events.ts b/server/src/nest/notifications/notification-events.ts
new file mode 100644
index 000000000..edd9784ba
--- /dev/null
+++ b/server/src/nest/notifications/notification-events.ts
@@ -0,0 +1,156 @@
+import type { NotificationEventKey } from '@trek/shared/i18n/externalNotifications';
+
+/**
+ * The notification vocabulary: event names, channel ids, and the contract a
+ * channel implements. No database, no DI, and — deliberately — no imports from
+ * anywhere else in the domain.
+ *
+ * This module exists to keep the notification cluster a DAG. The preferences
+ * service, the channel registry and the transports all need these names, and
+ * before they lived here the cluster was only acyclic because two of those
+ * edges happened to be `import type` and compiled away. The first person to put
+ * `NotifEventType` or `ALL_EVENT_TYPES` in a value position would have turned
+ * that into a real runtime cycle, with the built-in channels as a third ring.
+ */
+
+// ── Channels ───────────────────────────────────────────────────────────────
+
+/**
+ * A channel id. Open by design: the built-ins 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';
+
+// ── Events ─────────────────────────────────────────────────────────────────
+
+export type NotifEventType =
+ | 'trip_invite'
+ | 'booking_change'
+ | 'trip_reminder'
+ | 'todo_due'
+ | 'vacay_invite'
+ | 'vacay_share'
+ | 'collection_invite'
+ | 'photos_shared'
+ | 'collab_message'
+ | 'packing_tagged'
+ | 'version_available'
+ | 'synology_session_cleared'
+ | 'plugin_notification';
+
+/** 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',
+ 'vacay_share',
+ 'collection_invite',
+ 'photos_shared',
+ 'collab_message',
+ 'packing_tagged',
+ 'version_available',
+ 'synology_session_cleared',
+ 'plugin_notification',
+];
+
+/** Events that target admins only (shown in admin panel, not in user settings). */
+export const ADMIN_SCOPED_EVENTS = new Set<NotifEventType>(['version_available']);
+
+// Compile-time guard: shared NotificationEventKey and server NotifEventType must
+// stay in sync. It sits next to the union it guards — it used to live in the
+// transports module, three files away from the type it was protecting.
+type _EvtFwd = NotifEventType extends NotificationEventKey ? true : never;
+type _EvtBwd = NotificationEventKey extends NotifEventType ? true : never;
+const _eventKeyDriftGuard: [_EvtFwd, _EvtBwd] = [true, true];
+void _eventKeyDriftGuard;
+
+/**
+ * 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);
+}
+
+// ── The channel contract ───────────────────────────────────────────────────
+//
+// 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 NotificationsService.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.
+
+/** 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 }>;
+}
+
+/** 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;
+}
diff --git a/server/src/nest/notifications/notifications.service.ts b/server/src/nest/notifications/notifications.service.ts
index b9058b707..5f7751fe6 100644
--- a/server/src/nest/notifications/notifications.service.ts
+++ b/server/src/nest/notifications/notifications.service.ts
@@ -19,11 +19,15 @@ import {
getActiveChannels,
isEnabledForEvent,
getAdminGlobalPref,
- isAdminGlobalChannel,
+} from '../../services/notificationPreferencesService';
+import {
ADMIN_SCOPED_EVENTS,
+ isAdminGlobalChannel,
+ type ChannelMessage,
+ type ExternalChannel,
type NotifEventType,
-} from '../../services/notificationPreferencesService';
-import { getChannel, listChannels, type ChannelMessage, type ExternalChannel } from '../../services/notifications/channelRegistry';
+} from './notification-events';
+import { getChannel, listChannels } from '../../services/notifications/channelRegistry';
import { getAction } from './in-app-actions';
import { avatarUrl } from '../common/avatarUrl';
import { DatabaseService } from '../database/database.service';
diff --git a/server/src/nest/plugins/install/manifest.ts b/server/src/nest/plugins/install/manifest.ts
index 7080a29f9..c6450ed4c 100644
--- a/server/src/nest/plugins/install/manifest.ts
+++ b/server/src/nest/plugins/install/manifest.ts
@@ -1,7 +1,7 @@
import semver from 'semver';
import { isKnownPermission } from '../protocol/envelope';
import { isValidTrekRange, minTrekOf } from './host-compat';
-import type { NotifEventType } from '../../../services/notificationPreferencesService';
+import type { NotifEventType } from '../../notifications/notification-events';
/**
* Parse + validate a plugin's trek-plugin.json (#plugins, M4). Kept deliberately
diff --git a/server/src/services/notificationPreferencesService.ts b/server/src/services/notificationPreferencesService.ts
index 24e0b9218..0a5f349b6 100644
--- a/server/src/services/notificationPreferencesService.ts
+++ b/server/src/services/notificationPreferencesService.ts
@@ -1,72 +1,23 @@
import type Database from 'better-sqlite3';
import { db } from '../db/database';
import { isSmtpConfigured } from './notifications';
-import { listChannels, type ExternalChannel } from './notifications/channelRegistry';
+import {
+ ADMIN_SCOPED_EVENTS,
+ ALL_EVENT_TYPES,
+ INAPP_CHANNEL,
+ isAdminGlobalChannel,
+ type AdminGlobalChannel,
+ type ChannelDescriptor,
+ type ExternalChannel,
+ type NotifChannel,
+ type NotifEventType,
+} from '../nest/notifications/notification-events';
+import { listChannels } 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 ──────────────────────────────────────────────────────────────────
-
-/**
- * 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'
- | 'booking_change'
- | 'trip_reminder'
- | 'todo_due'
- | 'vacay_invite'
- | 'vacay_share'
- | 'collection_invite'
- | 'photos_shared'
- | 'collab_message'
- | 'packing_tagged'
- | 'version_available'
- | 'synology_session_cleared'
- | 'plugin_notification';
-
-/** 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',
- 'vacay_share',
- '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;
-}
-
/**
* Channels implemented for an event. In-app takes everything; external channels
* decide for themselves (today: everything except `synology_session_cleared`).
@@ -81,9 +32,6 @@ function allCombos(): Record<string, NotifChannel[]> {
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']);
-
// ── Helpers ────────────────────────────────────────────────────────────────
function getAppSetting(key: string): string | null {
@@ -247,18 +195,6 @@ export function getPreferencesMatrix(userId: number, userRole: string, scope: 'u
// ── Admin global preferences (stored in app_settings) ─────────────────────
-/**
- * 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}`.
diff --git a/server/src/services/notifications.ts b/server/src/services/notifications.ts
index e0eb63fc8..d30121c1f 100644
--- a/server/src/services/notifications.ts
+++ b/server/src/services/notifications.ts
@@ -5,22 +5,16 @@ import { decrypt_api_key } from '../nest/common/crypto/apiKeyCrypto';
import { logInfo, logDebug, logError } from '../nest/audit/audit-log.logger';
// ── Types ──────────────────────────────────────────────────────────────────
-import type { NotifEventType } from './notificationPreferencesService';
+import type { NotifEventType } from '../nest/notifications/notification-events';
import { EMAIL_I18N as I18N, EVENT_TEXTS, PASSWORD_RESET_I18N } from '@trek/shared/i18n/externalNotifications';
import type {
EmailStrings,
EventText,
PasswordResetStrings,
- NotificationEventKey,
} from '@trek/shared/i18n/externalNotifications';
import nodemailer from 'nodemailer';
-// Compile-time guard: shared NotificationEventKey and server NotifEventType must stay in sync.
-type _EvtFwd = NotifEventType extends NotificationEventKey ? true : never;
-type _EvtBwd = NotificationEventKey extends NotifEventType ? true : never;
-const _eventKeyDriftGuard: [_EvtFwd, _EvtBwd] = [true, true];
-
interface SmtpConfig {
host: string;
port: number;
diff --git a/server/src/services/notifications/channelRegistry.ts b/server/src/services/notifications/channelRegistry.ts
index 9df12c6d5..5aae1caf5 100644
--- a/server/src/services/notifications/channelRegistry.ts
+++ b/server/src/services/notifications/channelRegistry.ts
@@ -1,62 +1,11 @@
-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 }>;
-}
+import type { ExternalChannel } from '../../nest/notifications/notification-events';
+
+// The channel contract itself (ChannelMessage, ExternalChannel) lives in
+// nest/notifications/notification-events.ts so that this registry, the
+// preferences service and the transports can all name it without importing each
+// other. Re-exported here for the consumers that reach the contract through the
+// registry.
+export type { ChannelMessage, ExternalChannel } from '../../nest/notifications/notification-events';
/** Namespace for plugin channel ids, so a plugin can never claim `email`. */
export const PLUGIN_CHANNEL_PREFIX = 'plugin:';