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.

7.3 KB
Raw Blame
import { registerChannel } from '../channel-registry';
import type { MailerService } from '../mailer/mailer.service';
import { ADMIN_SCOPED_EVENTS, type ChannelMessage, type ExternalChannel } from '../notification-events';
import { resolveAdminNtfyUrl, resolveNtfyToken, resolveNtfyUrl, type NtfyService } from '../transports/ntfy.service';
import type { WebPushService } from '../transports/web-push.service';
import type { WebhookService } from '../transports/webhook.service';
import { WEB_PUSH_CHANNEL_ID } from '@trek/shared';

// The built-in external channels. Email, webhook and ntfy wrap the transports
// that were free functions in services/notifications.ts before the fold; no
// delivery logic is rewritten here, it is only relocated behind the
// ExternalChannel interface so NotificationsService.send() can iterate instead
// of branching. Web Push (#894) joined later on the same terms.

function supportsAllButSynology(event: string): boolean {
  return event !== 'synology_session_cleared';
}

export interface BuiltinChannelDeps {
  mailer: MailerService;
  webhook: WebhookService;
  ntfy: NtfyService;
  push: WebPushService;
}

/**
 * Build the built-in channels over the given transports.
 *
 * They take their dependencies as an argument rather than importing them,
 * because the registry they land in is a module singleton while the transports
 * are providers. Every NotificationsService instance - the container singleton
 * and any separately-constructed one - registers from its
 * constructor, so the registry is populated on every path that can dispatch.
 * It used to happen through a side-effect import in the preferences service,
 * which meant the built-ins existed only because somebody happened to import
 * preferences; dropping that import would have silenced email, webhook and ntfy
 * without a single error.
 */
export function buildBuiltinChannels({ mailer, webhook, ntfy, push }: BuiltinChannelDeps): ExternalChannel[] {
  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: () => mailer.isSmtpConfigured(),
    isConfiguredFor: async (userId) => !!(await mailer.getUserEmail(userId)),
    async sendToUser(userId, msg) {
      const email = await mailer.getUserEmail(userId);
      if (!email) return false;
      const manageTarget = ADMIN_SCOPED_EVENTS.has(msg.event) ? '/admin?tab=notifications' : undefined;
      return mailer.sendEmail(email, msg.title, msg.body, userId, msg.navigateTarget, manageTarget);
    },
    async test(userId) {
      const email = await mailer.getUserEmail(userId);
      if (!email) return { success: false, error: 'No email address on file' };
      return mailer.testSmtp(email);
    },
  };

  const webhookChannel: ExternalChannel = {
    id: 'webhook',
    source: 'builtin',
    labelKey: 'settings.notificationPreferences.webhook',
    supportsAdminGlobal: true,
    supportsEvent: supportsAllButSynology,
    isConfiguredFor: async (userId) => !!(await webhook.getUserWebhookUrl(userId)),
    async sendToUser(userId, msg) {
      const url = await webhook.getUserWebhookUrl(userId);
      if (!url) return false;
      return webhook.sendWebhook(url, {
        event: msg.event,
        title: msg.title,
        body: msg.body,
        tripName: msg.tripName,
        link: msg.url,
      });
    },
    async sendGlobal(msg: ChannelMessage) {
      const url = await webhook.getAdminWebhookUrl();
      if (!url) return false;
      return webhook.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) || (await webhook.getUserWebhookUrl(userId));
      if (!url) return { success: false, error: 'No webhook URL configured' };
      return webhook.testWebhook(url);
    },
  };

  const ntfyChannel: ExternalChannel = {
    id: 'ntfy',
    source: 'builtin',
    labelKey: 'settings.notificationPreferences.ntfy',
    supportsAdminGlobal: true,
    supportsEvent: supportsAllButSynology,
    isConfiguredFor: async (userId) =>
      !!resolveNtfyUrl(await ntfy.getAdminNtfyConfig(), await ntfy.getUserNtfyConfig(userId)),
    async sendToUser(userId, msg) {
      const userCfg = await ntfy.getUserNtfyConfig(userId);
      const adminCfg = await ntfy.getAdminNtfyConfig();
      const url = resolveNtfyUrl(adminCfg, userCfg);
      if (!url) return false;
      // Not `?? adminCfg.token`: the user picks their own ntfy_server, so that
      // handed the operator's decrypted token to whatever host they named, on
      // every ordinary send and with no test route involved (GHSA-7pqc-fj3c-9346).
      return ntfy.sendNtfy(url, resolveNtfyToken(adminCfg, userCfg), {
        event: msg.event,
        title: msg.title,
        body: msg.body,
        link: msg.url,
      });
    },
    async sendGlobal(msg: ChannelMessage) {
      const adminCfg = await ntfy.getAdminNtfyConfig();
      const url = resolveAdminNtfyUrl(adminCfg);
      if (!url) return false;
      return ntfy.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 : (await ntfy.getUserNtfyConfig(userId))?.topic;
      if (!topic) return { success: false, error: 'Could not resolve ntfy URL — missing topic' };
      return ntfy.testNtfy({
        topic,
        server: typeof override?.server === 'string' ? override.server : null,
        token: typeof override?.token === 'string' ? override.token : null,
      });
    },
  };

  // Per user and per browser. It carries no admin-scoped events: those have
  // their own admin-global copy on the channels above, and a push column in
  // the admin matrix could never be switched on. There is no sendGlobal for the
  // same reason, and no credentials to check beyond the user having turned it
  // on in at least one browser. Subscribing is a browser-only act, so there is
  // no MCP twin for the routes behind it. While the server's key pair cannot be
  // used, push is not sent and not offered, and every device stays subscribed.
  const pushChannel: ExternalChannel = {
    id: WEB_PUSH_CHANNEL_ID,
    source: 'builtin',
    labelKey: 'settings.notificationPreferences.push',
    hiddenWhileInstanceUnconfigured: true,
    supportsEvent: (event) => supportsAllButSynology(event) && !ADMIN_SCOPED_EVENTS.has(event),
    isInstanceConfigured: () => push.isAvailable(),
    isConfiguredFor: (userId) => push.hasDevices(userId),
    sendToUser: (userId, msg) => push.sendToUser(userId, msg),
    test: (userId) => push.sendTest(userId),
  };

  return [emailChannel, webhookChannel, ntfyChannel, pushChannel];
}

/** Idempotent - safe to call from every entry point that needs the registry populated. */
export function registerBuiltinChannels(deps: BuiltinChannelDeps): void {
  for (const channel of buildBuiltinChannels(deps)) registerChannel(channel);
}