Skip to content

🀯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

9.8 KB
Raw Blame
import { createEnv } from '@t3-oss/env-nextjs';
import debug from 'debug';
import { z } from 'zod';

import { getServerDB } from '@/database/core/db-adaptor';
import {
  type DecryptedSystemBotProvider,
  SystemBotProviderModel,
} from '@/database/models/systemBotProvider';
import { gatewayEnv } from '@/envs/gateway';
import { redisEnv } from '@/envs/redis';
import { KeyVaultsGateKeeper } from '@/server/modules/KeyVaultsEncrypt';
import {
  isAnyMessageGatewayEnabled,
  isMessageGatewayHostConfigured,
  resolveMessageGatewayHost,
} from '@/server/services/gateway/MessageGatewayClient';

const log = debug('lobe-server:messenger:config');

/**
 * Messenger bot configuration β€” DB-backed.
 *
 * Replaces the env-only path. Credentials live in `system_bot_providers` and
 * are managed from develop-center. The only env knob left is the link-token
 * TTL (no secrets, just a tunable).
 *
 * Two distribution models still apply downstream:
 *
 * - **Global-token platforms (Telegram, Discord)**: a single LobeHub-owned
 *   bot serves every user. The full credential bundle for the bot lives in
 *   the row.
 *
 * - **Per-tenant OAuth platforms (Slack)**: the row carries App-level
 *   credentials (`appId` / `clientId` / `clientSecret` / `signingSecret`);
 *   each workspace bot token is acquired via OAuth on install and stored
 *   in `messenger_installations`.
 */
export const getMessengerConfig = () => {
  return createEnv({
    client: {},
    runtimeEnv: {
      LOBE_LINK_TOKEN_TTL_SECONDS: process.env.LOBE_LINK_TOKEN_TTL_SECONDS,
    },
    server: {
      LOBE_LINK_TOKEN_TTL_SECONDS: z.coerce.number().int().positive().default(1800),
    },
  });
};

export const messengerEnv = getMessengerConfig();

export type MessengerPlatform = 'telegram' | 'slack' | 'discord' | 'wechat' | 'linq';

export interface MessengerTelegramConfig {
  botToken: string;
  botUsername?: string;
  webhookSecret?: string;
}

export interface MessengerSlackConfig {
  appId: string;
  clientId: string;
  clientSecret: string;
  signingSecret: string;
}

export interface MessengerDiscordConfig {
  applicationId: string;
  botToken: string;
  /**
   * Discord OAuth client secret. Required only for the per-guild install flow
   * (`[platform]/install` β†’ `[platform]/oauth/callback`). The runtime bot
   * itself uses `botToken` only, so legacy deployments without OAuth wiring
   * keep working.
   */
  clientSecret?: string;
  publicKey: string;
}

/**
 * WeChat System Bot credentials are user-owned and acquired by QR scan, so
 * the deployment-level provider only acts as an availability switch.
 */
export interface MessengerWechatConfig {
  enabled: true;
}

/**
 * Linq (iMessage / SMS) β€” a pool of LobeHub-owned numbers shared by every
 * user. No number belongs to a user or an agent: inbound routes by the
 * sender's handle, and a person links their phone by texting a one-time code
 * to any pool number.
 */
export interface MessengerLinqConfig {
  /** REST base override; defaults to the Linq package's `https://api.linqapp.com/v3`. */
  apiBaseUrl?: string;
  apiKey: string;
  /** Shared pool numbers in E.164. Never empty. */
  numbers: string[];
  /** Standard Webhooks signing secret (`whsec_…`) of the account-level webhook. */
  webhookSecret: string;
}

/** Accept the pool as a JSON array or a comma / whitespace separated string. */
export const parseLinqNumberPool = (raw: unknown): string[] => {
  const values = Array.isArray(raw) ? raw : typeof raw === 'string' ? raw.split(/[\s,]+/) : [];
  const numbers = values
    .filter((value): value is string => typeof value === 'string')
    .map((value) => value.trim())
    .filter((value) => /^\+\d{8,15}$/.test(value));
  return [...new Set(numbers)];
};

// ---------------------------------------------------------------------------
// In-process cache.
//
// Webhooks fire frequently β€” every Discord MESSAGE_CREATE, every Slack event,
// every Telegram update would otherwise hit the DB to read the App config.
// 30s TTL keeps the round-trip out of the hot path while letting credential
// rotations from dc-center take effect within ~30s without a deploy.
// ---------------------------------------------------------------------------

const CACHE_TTL_MS = 30_000;

interface CacheEntry<T> {
  expiresAt: number;
  value: T | null;
}

const platformCache = new Map<MessengerPlatform, CacheEntry<unknown>>();

/** Drop the cached config for a platform (or all). Called by mutations after
 *  the dc-center admin saves new credentials. Best-effort: cross-process
 *  invalidation is not guaranteed (Vercel functions don't share memory), so
 *  the 30s TTL is the real backstop. */
export const invalidateMessengerConfigCache = (platform?: MessengerPlatform): void => {
  if (platform) {
    platformCache.delete(platform);
  } else {
    platformCache.clear();
  }
};

const fetchAndCache = async <T>(
  platform: MessengerPlatform,
  decode: (decrypted: DecryptedSystemBotProvider) => T | null,
): Promise<T | null> => {
  const cached = platformCache.get(platform) as CacheEntry<T> | undefined;
  if (cached && cached.expiresAt > Date.now()) return cached.value;

  let value: T | null = null;
  try {
    const db = await getServerDB();
    const gateKeeper = await KeyVaultsGateKeeper.initWithEnvKey().catch(() => undefined);
    const row = await SystemBotProviderModel.findEnabledByPlatform(db, platform, gateKeeper);
    if (row) value = decode(row);
  } catch (error) {
    log('fetchAndCache: lookup failed for platform=%s: %O', platform, error);
  }

  platformCache.set(platform, { expiresAt: Date.now() + CACHE_TTL_MS, value });
  return value;
};

export const getMessengerTelegramConfig = async (): Promise<MessengerTelegramConfig | null> => {
  return fetchAndCache<MessengerTelegramConfig>('telegram', (row) => {
    const c = row.credentials as Partial<MessengerTelegramConfig>;
    if (!c.botToken) return null;
    return {
      botToken: c.botToken,
      botUsername: c.botUsername,
      webhookSecret: c.webhookSecret,
    };
  });
};

export const getMessengerSlackConfig = async (): Promise<MessengerSlackConfig | null> => {
  return fetchAndCache<MessengerSlackConfig>('slack', (row) => {
    const c = row.credentials as Partial<Omit<MessengerSlackConfig, 'appId'>>;
    if (!row.applicationId || !c.clientId || !c.clientSecret || !c.signingSecret) return null;
    return {
      appId: row.applicationId,
      clientId: c.clientId,
      clientSecret: c.clientSecret,
      signingSecret: c.signingSecret,
    };
  });
};

export const getMessengerDiscordConfig = async (): Promise<MessengerDiscordConfig | null> => {
  return fetchAndCache<MessengerDiscordConfig>('discord', (row) => {
    const c = row.credentials as Partial<Omit<MessengerDiscordConfig, 'applicationId'>>;
    if (!row.applicationId || !c.botToken || !c.publicKey) return null;
    return {
      applicationId: row.applicationId,
      botToken: c.botToken,
      clientSecret: c.clientSecret,
      publicKey: c.publicKey,
    };
  });
};

export const getMessengerWechatConfig = async (): Promise<MessengerWechatConfig | null> => {
  // WeChat owns a long-polling connection in a message gateway, with Redis
  // backing its QR session and per-user connection state. Do not advertise an
  // enabled provider until the runtime can actually complete that lifecycle.
  //
  // Two conditions, and both are load-bearing: the runtime only enters gateway
  // mode when the default host is configured (`isAnyMessageGatewayEnabled`),
  // and WeChat's connection is only reachable if the host that OWNS WeChat is
  // configured β€” which is the Node host once it is routed there. Checking only
  // the second would advertise WeChat in a Node-only deployment, where the
  // runtime stays in-process and nothing ever serves those links.
  const gatewayReady =
    isAnyMessageGatewayEnabled() &&
    isMessageGatewayHostConfigured(resolveMessageGatewayHost('wechat'));
  if (
    gatewayEnv.MESSAGE_GATEWAY_ENABLED !== '1' ||
    !gatewayReady ||
    !redisEnv.REDIS_URL ||
    process.env.DISABLE_REDIS
  ) {
    return null;
  }

  return fetchAndCache<MessengerWechatConfig>('wechat', () => ({ enabled: true }));
};

export const getMessengerLinqConfig = async (): Promise<MessengerLinqConfig | null> => {
  // Link codes and webhook replay claims live in Redis; without it a person
  // could never complete a link, so the platform is not advertised.
  if (!redisEnv.REDIS_URL || process.env.DISABLE_REDIS) return null;

  return fetchAndCache<MessengerLinqConfig>('linq', (row) => {
    const c = row.credentials as Partial<
      Record<'apiBaseUrl' | 'apiKey' | 'webhookSecret', string>
    > & {
      numbers?: unknown;
    };
    const numbers = parseLinqNumberPool(c.numbers);
    if (!c.apiKey || !c.webhookSecret || numbers.length === 0) return null;
    return {
      apiBaseUrl: c.apiBaseUrl || undefined,
      apiKey: c.apiKey,
      numbers,
      webhookSecret: c.webhookSecret,
    };
  });
};

export const isMessengerPlatformEnabled = async (platform: MessengerPlatform): Promise<boolean> => {
  switch (platform) {
    case 'telegram': {
      return !!(await getMessengerTelegramConfig());
    }
    case 'slack': {
      return !!(await getMessengerSlackConfig());
    }
    case 'discord': {
      return !!(await getMessengerDiscordConfig());
    }
    case 'wechat': {
      return !!(await getMessengerWechatConfig());
    }
    case 'linq': {
      return !!(await getMessengerLinqConfig());
    }
    default: {
      return false;
    }
  }
};

export const getEnabledMessengerPlatforms = async (): Promise<MessengerPlatform[]> => {
  const platforms = ['telegram', 'slack', 'discord', 'wechat', 'linq'] as const;
  const checks = await Promise.all(
    platforms.map(async (p) => ((await isMessengerPlatformEnabled(p)) ? p : null)),
  );
  return checks.filter((p): p is MessengerPlatform => p !== null);
};

export const getMessengerLinkTokenTtl = (): number => messengerEnv.LOBE_LINK_TOKEN_TTL_SECONDS;