π€― 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.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
β»οΈ refactor(server): split the 1209-line messenger router into sub-domain modules (#21104)
Arvin Xu160876a9e869
diff --git a/apps/server/src/routers/lambda/messenger.ts b/apps/server/src/routers/lambda/messenger.tsdeleted file mode 100644index 358e83baa8a..00000000000--- a/apps/server/src/routers/lambda/messenger.ts+++ /dev/null@@ -1,1209 +0,0 @@-import { buildLinqDeepLink, createLinqLinkCode } from '@lobechat/agent-address-linq';-import { MESSENGER_PUSH_CONTENT_MAX_LENGTH } from '@lobechat/builtin-tool-message';-import { fetchQrCode, pollQrStatus } from '@lobechat/chat-adapter-wechat';-import { INBOX_SESSION_ID } from '@lobechat/const';-import { TRPCError } from '@trpc/server';-import { and, eq } from 'drizzle-orm';-import { z } from 'zod';--import {- assertBotFeatureAccess,- withBotPlatformAccessMeta,-} from '@/business/server/bot/featureAccess';-import { withScopedPermission } from '@/business/server/trpc-middlewares/rbacPermission';-import {- getEnabledMessengerPlatforms,- getMessengerDiscordConfig,- getMessengerLinqConfig,- getMessengerSlackConfig,- getMessengerTelegramConfig,- isMessengerPlatformEnabled,- type MessengerPlatform,-} from '@/config/messenger';-import { AgentModel } from '@/database/models/agent';-import { FileModel } from '@/database/models/file';-import type { SafeMessengerAccountLink } from '@/database/models/messengerAccountLink';-import {- MessengerAccountLinkConflictError,- MessengerAccountLinkModel,- MessengerAccountLinkRelinkRequiredError,-} from '@/database/models/messengerAccountLink';-import type { DecryptedMessengerInstallation } from '@/database/models/messengerInstallation';-import { MessengerInstallationModel } from '@/database/models/messengerInstallation';-import { RbacModel } from '@/database/models/rbac';-import { WorkspaceModel } from '@/database/models/workspace';-import { agents, users } from '@/database/schemas';-import type { LobeChatDatabase } from '@/database/type';-import { notTrashed } from '@/database/utils/softDelete';-import { authedProcedure, publicProcedure, router } from '@/libs/trpc/lambda';-import { serverDatabase } from '@/libs/trpc/lambda/middleware';-import { getServerFeatureFlagsStateFromRuntimeConfig } from '@/server/featureFlags';-import { getAgentRuntimeRedisClient } from '@/server/modules/AgentRuntime/redis';-import { KeyVaultsGateKeeper } from '@/server/modules/KeyVaultsEncrypt';-import { SlackApi } from '@/server/services/bot/platforms/slack/api';-import type { BotMessageAttachment } from '@/server/services/bot/platforms/types';-import {- wechatLegacyTokenKey,- wechatPendingPushKey,- wechatWindowKey,-} from '@/server/services/bot/platforms/wechat/contextWindow';-import { FileService } from '@/server/services/file';-import { GatewayService } from '@/server/services/gateway';-import { getBotRuntimeStatus } from '@/server/services/gateway/runtimeStatus';-import {- acquireWechatQrFinalizeLock,- consumeLinkToken,- consumeWechatQrSession,- getMessengerRouter,- issueWechatQrSession,- MessengerDiscordBinder,- messengerPlatformRegistry,- MessengerSlackBinder,- MessengerTelegramBinder,- peekConsumedLinkToken,- peekLinkToken,- peekWechatQrSession,- releaseWechatQrFinalizeLock,-} from '@/server/services/messenger';-import { wechatInstallationKey } from '@/server/services/messenger/installations';-import { issueLinkCode, peekLinkCodeStatus } from '@/server/services/messenger/linkTokenStore';-import { pickLinqPoolNumber } from '@/server/services/messenger/platforms/linq/pool';-import {- getMessengerPushWindow,- MESSENGER_PUSH_PLATFORMS,- sendMessengerPush,-} from '@/server/services/messenger/push';--const platformEnum = z.enum([- 'telegram',- 'slack',- 'discord',- 'wechat',- 'linq',-]) satisfies z.ZodType<MessengerPlatform>;--const REVOKED_SLACK_AUTH_ERRORS = new Set([- 'account_inactive',- 'invalid_auth',- 'not_authed',- 'token_revoked',-]);--const extractSlackAuthErrorCode = (error: unknown): string | null => {- if (!(error instanceof Error)) return null;-- const match = error.message.match(/Slack API auth\.test failed: ([a-z_]+)/);- return match?.[1] ?? null;-};--const WORKSPACE_FEATURE_DISABLED_MESSAGE = 'Workspace feature is not enabled for this user';--const isWorkspaceFeatureEnabledForUser = async (userId: string): Promise<boolean> => {- const featureFlags = await getServerFeatureFlagsStateFromRuntimeConfig(userId);- return featureFlags.enableWorkspace === true;-};--const assertWorkspaceFeatureEnabledForUser = async (userId: string): Promise<void> => {- if (await isWorkspaceFeatureEnabledForUser(userId)) return;-- throw new TRPCError({- code: 'FORBIDDEN',- message: WORKSPACE_FEATURE_DISABLED_MESSAGE,- });-};--const reconcileSlackInstallation = async (- serverDB: LobeChatDatabase,- row: DecryptedMessengerInstallation,-): Promise<DecryptedMessengerInstallation | null> => {- if (row.platform !== 'slack') return row;-- const botToken = (row.credentials as { botToken?: string })?.botToken;- if (!botToken) return row;-- try {- await new SlackApi(botToken).authTest();- return row;- } catch (error) {- const errorCode = extractSlackAuthErrorCode(error);-- if (errorCode && REVOKED_SLACK_AUTH_ERRORS.has(errorCode)) {- await MessengerInstallationModel.markRevoked(serverDB, row.id);- return null;- }-- console.error('[messenger:listMyInstallations] failed to verify Slack installation', error);- return row;- }-};--const disconnectWechatAccountLink = async (- link: SafeMessengerAccountLink,- userId: string,-): Promise<void> => {- const installationKey = wechatInstallationKey(link.tenantId);- await new GatewayService().disconnectUserMessenger({- installationKey,- platform: 'wechat',- userId,- });- // A rescan replaces the QR-issued token/baseUrl under the same installation- // key β drop the cached Chat SDK bot so webhooks rebuild it from the new- // credentials instead of replying through the stale client.- getMessengerRouter().invalidateBot(installationKey);-- if (!link.applicationId) return;- const redis = getAgentRuntimeRedisClient();- if (redis) {- await redis.del(- wechatLegacyTokenKey(link.applicationId, link.tenantId),- wechatWindowKey(link.applicationId, link.tenantId),- wechatPendingPushKey(link.applicationId, link.tenantId),- );- }-};--/**- * Reveal enough of the email so a legitimate owner recognizes the account- * without exposing the full address to anyone with Slack-side access to- * the IM identity.- */-const maskEmail = (email: string): string => {- const [local, domain] = email.split('@');- if (!domain) return email;- const head = local.slice(0, Math.min(2, local.length));- return `${head}***@${domain}`;-};--const messengerProcedure = authedProcedure.use(serverDatabase).use(async (opts) => {- const { ctx } = opts;- return opts.next({- ctx: {- // The System Bot is a single shared bot; the workspace a conversation- // runs in is derived from the *active agent*, not the ambient- // `X-Workspace-Id` header. So the link model is identity-scoped (by- // userId), and per-agent authorization happens in-handler via- // `resolveAuthorizedAgentScope`.- messengerLinkModel: new MessengerAccountLinkModel(ctx.serverDB, ctx.userId),- // The bindable-agents scope is request-driven β the cascading scope- // picker passes the workspace via input, not the ambient header β so- // expose a workspace-parameterized AgentModel factory rather than a- // single pre-scoped instance.- getAgentModel: (workspaceId?: string | null) =>- new AgentModel(ctx.serverDB, ctx.userId, workspaceId ?? undefined),- },- });-});-const messengerWriteProcedure = messengerProcedure.use(withScopedPermission('agent:update'));--/**- * Resolve the workspace scope of an agent the user wants to route the System- * Bot to, authorizing access along the way. Because the bot is shared and- * which LobeHub context a conversation runs in is derived from the *active- * agent*, every place that sets the active agent must re-authorize against- * that agent's own workspace:- *- * - personal agent (`workspace_id IS NULL`): must be owned by the caller.- * - workspace agent: caller must be a member AND hold `agent:update` in that- * workspace (mirrors `withScopedPermission('agent:update')`).- *- * Returns the derived `workspaceId` (null for personal) + the agent title.- * Throws `NOT_FOUND` / `FORBIDDEN`.- */-const resolveAuthorizedAgentScope = async (- serverDB: LobeChatDatabase,- userId: string,- agentId: string,-): Promise<{ title: string | null; workspaceId: string | null }> => {- const [agentRow] = await serverDB- .select({ title: agents.title, userId: agents.userId, workspaceId: agents.workspaceId })- .from(agents)- .where(and(eq(agents.id, agentId), notTrashed(agents.isDeleted)))- .limit(1);- if (!agentRow) {- throw new TRPCError({ code: 'NOT_FOUND', message: 'messenger.error.agentNotFound' });- }-- // Personal agent β only the owner may route the bot to it.- if (!agentRow.workspaceId) {- if (agentRow.userId !== userId) {- throw new TRPCError({ code: 'NOT_FOUND', message: 'messenger.error.agentNotFound' });- }- return { title: agentRow.title, workspaceId: null };- }-- // Workspace agent β caller must be a member with `agent:update`.- await assertWorkspaceFeatureEnabledForUser(userId);-- const userWorkspaces = await new WorkspaceModel(serverDB, userId).listUserWorkspaces();- const isMember = userWorkspaces.some((w) => w.id === agentRow.workspaceId);- if (!isMember) {- throw new TRPCError({ code: 'FORBIDDEN', message: 'messenger.error.agentNotFound' });- }- const allowed = await new RbacModel(serverDB, userId).hasAnyPermission(- ['agent:update:all', 'agent:update:owner'],- { workspaceId: agentRow.workspaceId },- );- if (!allowed) {- throw new TRPCError({ code: 'FORBIDDEN', message: 'messenger.error.agentNotFound' });- }- return { title: agentRow.title, workspaceId: agentRow.workspaceId };-};--export const messengerRouter = router({- /**- * Surface available platforms + bot deep-link metadata to the UI.- *- * The static per-platform fields (`id`, `name`, ...) come from the- * registry's serialized definitions β same pattern as- * `agentBotProvider.listPlatforms` for bot channels. Per-deployment- * fields (`appId`, `botUsername`) layer on top from each platform's- * DB-backed config:- *- * - Slack `appId` powers the verify-im success state's- * `slack://app?team=β¦&id=β¦` deep link straight into the bot DM.- * - Discord `applicationId` doubles as the bot user id and feeds the- * LinkModal's OAuth2 install URL.- */- availablePlatforms: messengerProcedure.query(async ({ ctx }) => {- const enabled = await getEnabledMessengerPlatforms();- const enabledSet = new Set<string>(enabled);- const definitions = messengerPlatformRegistry- .listSerializedPlatforms()- .filter((def) => enabledSet.has(def.id));-- const [discordConfig, slackConfig, telegramConfig] = await Promise.all([- enabledSet.has('discord') ? getMessengerDiscordConfig() : Promise.resolve(null),- enabledSet.has('slack') ? getMessengerSlackConfig() : Promise.resolve(null),- enabledSet.has('telegram') ? getMessengerTelegramConfig() : Promise.resolve(null),- ]);-- return Promise.all(- definitions.map(async (def) => {- const serialized = {- ...def,- appId:- def.id === 'slack'- ? slackConfig?.appId- : def.id === 'discord'- ? discordConfig?.applicationId- : undefined,- // Telegram-only: deep-link target (`https://t.me/<botUsername>`) β no- // direct equivalent on Slack/Discord, both of which use App/Application- // IDs to deep-link to the bot.- botUsername: def.id === 'telegram' ? telegramConfig?.botUsername : undefined,- enabled: true,- // Legacy field β older callers index by `.platform` rather than `.id`.- // Keep until those callers migrate; safe alias of the registry id.- platform: def.id,- };-- return withBotPlatformAccessMeta(serialized, { userId: ctx.userId });- }),- );- }),-- /** Start a user-bound, one-shot WeChat iLink QR session. */- createWechatQrSession: messengerProcedure.mutation(async ({ ctx }) => {- if (!(await isMessengerPlatformEnabled('wechat'))) {- throw new TRPCError({- code: 'BAD_REQUEST',- message: 'messenger.error.platformNotConfigured',- });- }- await assertBotFeatureAccess({- action: 'manage',- platform: 'wechat',- userId: ctx.userId,- });-- try {- const qr = await fetchQrCode();- if (!qr.qrcode || !qr.qrcode_img_content) {- throw new Error('WeChat QR response is incomplete');- }- const session = await issueWechatQrSession({- qrcode: qr.qrcode,- userId: ctx.userId,- });- return {- ...session,- qrCodePayload: qr.qrcode_img_content,- status: 'wait' as const,- };- } catch (error) {- if (error instanceof TRPCError) throw error;- throw new TRPCError({- cause: error,- code: 'BAD_GATEWAY',- message: 'messenger.wechat.error.qrUnavailable',- });- }- }),-- /**- * Poll a QR session and finalize the user-owned account connection exactly- * once when WeChat confirms it. The browser never receives the raw QR token- * or bot credential bundle.- */- pollWechatQrSession: messengerProcedure- .input(z.object({ sessionId: z.string().min(8) }))- .mutation(async ({ ctx, input }) => {- if (!(await isMessengerPlatformEnabled('wechat'))) {- throw new TRPCError({- code: 'BAD_REQUEST',- message: 'messenger.error.platformNotConfigured',- });- }- await assertBotFeatureAccess({- action: 'manage',- platform: 'wechat',- userId: ctx.userId,- });-- const session = await peekWechatQrSession(input.sessionId, ctx.userId);- if (!session) return { status: 'expired' as const };-- let qrStatus;- try {- qrStatus = await pollQrStatus(session.qrcode);- } catch (error) {- throw new TRPCError({- cause: error,- code: 'BAD_GATEWAY',- message: 'messenger.wechat.error.pollFailed',- });- }-- if (qrStatus.status === 'wait' || qrStatus.status === 'scaned') {- return { status: qrStatus.status };- }- if (qrStatus.status === 'expired') {- await consumeWechatQrSession(input.sessionId);- return { status: 'expired' as const };- }- if (- !qrStatus.bot_token ||- !qrStatus.ilink_bot_id ||- !qrStatus.ilink_user_id ||- !qrStatus.baseurl- ) {- throw new TRPCError({- code: 'BAD_GATEWAY',- message: 'messenger.wechat.error.incompleteConfirmation',- });- }-- const lockToken = await acquireWechatQrFinalizeLock(input.sessionId);- if (!lockToken) return { status: 'scaned' as const };-- try {- const platformUserId = qrStatus.ilink_user_id;- const botId = qrStatus.ilink_bot_id;- const botToken = qrStatus.bot_token;- const baseUrl = qrStatus.baseurl;- const existingIdentity = await MessengerAccountLinkModel.findByPlatformUser(- ctx.serverDB,- 'wechat',- platformUserId,- platformUserId,- );- if (existingIdentity && existingIdentity.userId !== ctx.userId) {- throw new TRPCError({- code: 'CONFLICT',- message: 'messenger.wechat.error.alreadyLinkedToOther',- });- }-- const existingUserLink = await ctx.messengerLinkModel.findByPlatform('wechat');- if (existingUserLink && existingUserLink.platformUserId !== platformUserId) {- throw new TRPCError({- code: 'CONFLICT',- message: 'messenger.wechat.error.unlinkBeforeRelink',- });- }-- // A first scan should be immediately usable, so route it to the user's- // personal inbox (LobeAI). A rescan preserves an authorized Agent- // choice, but repairs stale/deauthorized links with the same fallback.- const inboxAgentId =- (await ctx.getAgentModel().getBuiltinAgent(INBOX_SESSION_ID))?.id ?? null;- let activeAgentId = existingUserLink?.activeAgentId ?? inboxAgentId;- let workspaceId: string | null = null;-- if (activeAgentId) {- try {- workspaceId = (- await resolveAuthorizedAgentScope(ctx.serverDB, ctx.userId, activeAgentId)- ).workspaceId;- } catch (error) {- const isStaleAgent =- error instanceof TRPCError &&- (error.code === 'NOT_FOUND' || error.code === 'FORBIDDEN');- if (!isStaleAgent || activeAgentId === inboxAgentId) throw error;-- activeAgentId = inboxAgentId;- workspaceId = activeAgentId- ? (await resolveAuthorizedAgentScope(ctx.serverDB, ctx.userId, activeAgentId))- .workspaceId- : null;- }- }- const gateKeeper = await KeyVaultsGateKeeper.initWithEnvKey();- const previousWechatLink = existingUserLink- ? await ctx.messengerLinkModel.findByIdWithCredentials(- existingUserLink.id,- 'wechat',- gateKeeper,- )- : undefined;- const link = await ctx.serverDB.transaction(async (tx) => {- const txDB = tx as LobeChatDatabase;- return new MessengerAccountLinkModel(txDB, ctx.userId).upsertForPlatform(- {- activeAgentId,- applicationId: botId,- credentials: { baseUrl, botId, botToken },- platform: 'wechat',- platformUserId,- platformUsername: null,- tenantId: platformUserId,- workspaceId,- },- gateKeeper,- );- });-- if (existingUserLink) await disconnectWechatAccountLink(existingUserLink, ctx.userId);- const gateway = new GatewayService();- const connectionId = await gateway.ensureUserMessengerConnected({- installationKey: wechatInstallationKey(platformUserId),- platform: 'wechat',- userId: ctx.userId,- });- if (!connectionId) {- // The gateway resolves credentials from the committed account link.- // Compensate a failed first connection by deleting it; on a rescan,- // restore the previous credential bundle so a failed replacement- // never destroys a working user-owned connection.- const previousApplicationId = previousWechatLink?.applicationId;- if (previousWechatLink && previousApplicationId) {- await ctx.serverDB.transaction(async (tx) => {- const txDB = tx as LobeChatDatabase;- await new MessengerAccountLinkModel(txDB, ctx.userId).upsertForPlatform(- {- activeAgentId: previousWechatLink.activeAgentId,- applicationId: previousApplicationId,- credentials: previousWechatLink.credentials,- platform: 'wechat',- platformUserId: previousWechatLink.platformUserId,- platformUsername: previousWechatLink.platformUsername,- tenantId: previousWechatLink.tenantId,- workspaceId: previousWechatLink.workspaceId,- },- gateKeeper,- );- });- await gateway.ensureUserMessengerConnected({- installationKey: wechatInstallationKey(previousWechatLink.tenantId),- platform: 'wechat',- userId: ctx.userId,- });- } else {- await ctx.serverDB.transaction(async (tx) => {- const txDB = tx as LobeChatDatabase;- await new MessengerAccountLinkModel(txDB, ctx.userId).deleteByPlatform(- 'wechat',- platformUserId,- );- });- }- throw new TRPCError({- code: 'BAD_GATEWAY',- message: 'messenger.wechat.error.connectionFailed',- });- }-- const runtime = await getBotRuntimeStatus('wechat', botId);- await consumeWechatQrSession(input.sessionId);-- return {- installation: {- applicationId: botId,- id: link.id,- installedAt: link.createdAt,- platform: link.platform,- tenantId: link.tenantId,- tenantName: 'WeChat',- },- link,- runtime,- status: 'confirmed' as const,- };- } catch (error) {- await releaseWechatQrFinalizeLock(input.sessionId, lockToken);- if (error instanceof MessengerAccountLinkConflictError) {- throw new TRPCError({- code: 'CONFLICT',- message: 'messenger.wechat.error.alreadyLinkedToOther',- });- }- if (error instanceof MessengerAccountLinkRelinkRequiredError) {- throw new TRPCError({- code: 'CONFLICT',- message: 'messenger.wechat.error.unlinkBeforeRelink',- });- }- throw error;- }- }),-- /**- * Start an iMessage / SMS link on the shared Linq pool. The signed-in user- * gets a one-time code plus `sms:` / `imessage:` deep links prefilled with- * it; texting that code from their phone to the pool is what binds the- * sender's handle to this account (see `MessengerLinqBinder`). The pool- * number is only a destination β any number in the pool would route the- * same way, because inbound is matched by sender, never by number.- */- createLinqLink: messengerProcedure.mutation(async ({ ctx }) => {- const config = await getMessengerLinqConfig();- if (!config) {- throw new TRPCError({- code: 'BAD_REQUEST',- message: 'messenger.error.platformNotConfigured',- });- }- await assertBotFeatureAccess({ action: 'manage', platform: 'linq', userId: ctx.userId });-- const existing = await ctx.messengerLinkModel.findByPlatform('linq', '');- if (existing) {- throw new TRPCError({ code: 'CONFLICT', message: 'verify.error.unlinkBeforeRelink' });- }-- // Same default as a first WeChat scan: land on the personal inbox agent so- // the first message after linking already has somewhere to go.- const activeAgentId = (await ctx.getAgentModel().getBuiltinAgent(INBOX_SESSION_ID))?.id ?? null;- const workspaceId = activeAgentId- ? (await resolveAuthorizedAgentScope(ctx.serverDB, ctx.userId, activeAgentId)).workspaceId- : null;-- const { code, expiresAt, pollId } = await issueLinkCode({- activeAgentId,- mintCode: createLinqLinkCode,- platform: 'linq',- userId: ctx.userId,- workspaceId,- });-- const deepLink = buildLinqDeepLink({- code,- number: pickLinqPoolNumber(config.numbers, ctx.userId),- });- if (!deepLink) {- throw new TRPCError({- code: 'INTERNAL_SERVER_ERROR',- message: 'messenger.error.platformNotConfigured',- });- }-- return { code, deepLink, expiresAt, pollId };- }),-- /** Poll a Linq link started by `createLinqLink` until the code arrives. */- pollLinqLink: messengerProcedure- .input(z.object({ pollId: z.string().min(8) }))- .query(async ({ ctx, input }) => {- const result = await peekLinkCodeStatus(input.pollId, ctx.userId);- if (result.status !== 'linked') return result;-- const link = await ctx.messengerLinkModel.findByPlatform('linq', '');- return { ...result, link: link ?? null };- }),-- /**- * Public peek used by the verify-im page to render the IM identity preview- * before the user confirms. Does NOT consume the token.- *- * Also surfaces `linkedToEmail` when the IM identity is already bound to- * a LobeHub account β the page uses it to warn the user before they create- * a duplicate that would either fail the unique index or shadow another- * account's binding. Email is partially masked for privacy.- *- * Returns a discriminated union by `status`:- * - `active`: token is live; payload + linkedToEmail accompany it.- * - `consumed`: token was already consumed by a successful `confirmLink`.- * The page can show "binding succeeded" instead of a misleading- * "expired" error when the user refreshes after confirming.- * - `expired`: no live token and no consumed marker β TTL ran out before- * the user finished binding.- *- * This procedure intentionally does NOT throw for the `consumed` /- * `expired` cases β both are routine user states (post-confirm refresh,- * stale tab) and shouldn't be logged as tRPC handler errors.- */- peekLinkToken: publicProcedure- .use(serverDatabase)- .input(z.object({ randomId: z.string().min(8) }))- .query(async ({ input, ctx }) => {- const payload = await peekLinkToken(input.randomId);- if (!payload) {- const consumed = await peekConsumedLinkToken(input.randomId);- if (consumed) {- return {- platform: consumed.platform,- status: 'consumed' as const,- tenantId: consumed.tenantId,- };- }- return { status: 'expired' as const };- }-- const existingLink = await MessengerAccountLinkModel.findByPlatformUser(- ctx.serverDB,- payload.platform,- payload.platformUserId,- payload.tenantId ?? '',- );-- let linkedToEmail: string | null = null;- if (existingLink) {- const [owner] = await ctx.serverDB- .select({ email: users.email })- .from(users)- .where(eq(users.id, existingLink.userId))- .limit(1);- if (owner?.email) linkedToEmail = maskEmail(owner.email);- }-- return {- // Set when the IM identity is already linked to some LobeHub account.- // The verify-im page compares against the current session email and- // shows a warning when they don't match.- linkedToEmail,- platform: payload.platform,- platformUserId: payload.platformUserId,- platformUsername: payload.platformUsername,- status: 'active' as const,- // Tenant fields are populated by the binder for per-tenant platforms- // (Slack workspace name) and absent for global-bot platforms; the- // verify-im page conditionally renders the workspace blurb.- tenantId: payload.tenantId,- tenantName: payload.tenantName,- };- }),-- /**- * Confirm the account link. Account-level: creates (or overwrites) a single- * `messenger_account_links` row for `(userId, platform)`. `initialAgentId` is- * required so the user's first IM message has somewhere to land β they can- * always change it later via `/agents` (tap to switch) or the per-agent UI.- */- confirmLink: messengerProcedure- .input(- z.object({- initialAgentId: z.string().min(1, 'messenger.error.pickDefaultAgent'),- randomId: z.string().min(8),- }),- )- .mutation(async ({ input, ctx }) => {- // Peek first so a cross-user conflict / missing agent doesn't burn the- // one-shot token β the user can fix the issue (re-login, pick another- // agent) without going back to the bot for a fresh /start.- const peeked = await peekLinkToken(input.randomId);- if (!peeked) {- throw new TRPCError({- code: 'NOT_FOUND',- message: 'verify.error.expired',- });- }-- // Cross-user conflict: the (platform, tenant, platformUserId) tuple is- // already bound to a different LobeHub account. The DB unique index- // would surface this as an opaque "duplicate key" β replace with a- // user-facing 409 carrying the masked email of the existing owner.- const existingLink = await MessengerAccountLinkModel.findByPlatformUser(- ctx.serverDB,- peeked.platform,- peeked.platformUserId,- peeked.tenantId ?? '',- );- if (existingLink && existingLink.userId !== ctx.userId) {- // The verify-im page surfaces the same conflict (with the masked- // email of the existing owner) via peekLinkToken's `linkedToEmail`- // before the user even clicks confirm β this throw is the defensive- // backstop for the rare race / direct-API caller.- throw new TRPCError({- code: 'CONFLICT',- message: 'verify.error.alreadyLinkedToOther',- });- }-- // The verify-im flow should never silently replace an existing binding- // for the same scope. For Slack the scope is one workspace (tenantId);- // for Discord/Telegram it is the whole platform. Require an explicit- // unlink first so account switches stay deliberate.- const existingUserLink = await ctx.messengerLinkModel.findByPlatform(- peeked.platform,- peeked.tenantId ?? '',- );- if (existingUserLink && existingUserLink.platformUserId !== peeked.platformUserId) {- throw new TRPCError({- code: 'CONFLICT',- message: 'verify.error.unlinkBeforeRelink',- });- }-- // Authorize the chosen initial agent against its own workspace (personal- // or a workspace the user can access) and derive the active scope.- const agentScope = await resolveAuthorizedAgentScope(- ctx.serverDB,- ctx.userId,- input.initialAgentId,- );-- // Now safe to consume β token is single-use; do this last so any error- // above leaves the token available for retry.- const payload = await consumeLinkToken(input.randomId);- if (!payload) {- // Lost a race with another consumer (or the token expired during the- // checks above). Treat the same as the initial peek-miss.- throw new TRPCError({- code: 'NOT_FOUND',- message: 'verify.error.expired',- });- }-- let link;- try {- link = await ctx.messengerLinkModel.upsertForPlatform({- activeAgentId: input.initialAgentId,- platform: payload.platform,- platformUserId: payload.platformUserId,- platformUsername: payload.platformUsername ?? null,- tenantId: payload.tenantId ?? '',- workspaceId: agentScope.workspaceId,- });- } catch (error) {- // Race backstop: the IM identity got bound to another LobeHub user- // between the pre-check above and the upsert. Re-surface as the same- // friendly 409 the verify-im UI already knows how to render.- if (error instanceof MessengerAccountLinkConflictError) {- throw new TRPCError({- code: 'CONFLICT',- message: 'verify.error.alreadyLinkedToOther',- });- }- if (error instanceof MessengerAccountLinkRelinkRequiredError) {- throw new TRPCError({- code: 'CONFLICT',- message: 'verify.error.unlinkBeforeRelink',- });- }- throw error;- }-- // Best-effort confirmation back to the IM platform.- void notifyLinkSuccess(payload.platform, {- activeAgentName: agentScope.title ?? undefined,- platformUserId: payload.platformUserId,- tenantId: payload.tenantId,- });-- return { data: link, success: true };- }),-- /**- * Agent list for the verify-im UI's "pick an initial agent" dropdown.- *- * Excludes virtual agents (page-copilot, etc.) but explicitly keeps the- * inbox/LobeAI agent β historical inbox sessions get migrated with- * `virtual=true`, so a plain virtual filter would hide LobeAI even though- * the home sidebar shows it (sidebar fetches it separately via- * `agent.getBuiltinAgent`).- *- * Order matches the home sidebar (`updatedAt DESC`). Title fallback for the- * inbox agent resolves to `"LobeAI"` + default avatar; everything else falls- * back on the client via `common.defaultSession`.- */- listAgentsForBinding: messengerProcedure- .input(z.object({ workspaceId: z.string().nullish() }).optional())- .query(async ({ ctx, input }) => {- const { serverDB, userId } = ctx;- // Cascading scope: the caller picks a scope (personal or one of the- // workspaces they belong to) and we return just that scope's agents.- // Omitting `workspaceId` (or `null`) means personal.- const workspaceId = input?.workspaceId ?? null;-- // Authorize the requested scope. Personal is always the caller's own; a- // workspace scope requires membership, otherwise the caller could- // enumerate another workspace's agents.- if (workspaceId) {- await assertWorkspaceFeatureEnabledForUser(userId);-- const userWorkspaces = await new WorkspaceModel(serverDB, userId).listUserWorkspaces();- if (!userWorkspaces.some((w) => w.id === workspaceId)) {- throw new TRPCError({ code: 'FORBIDDEN', message: 'messenger.error.agentNotFound' });- }- }-- // Inbox meta fallback, the virtual-or-inbox filter, inbox pinning, and the- // `isInbox` flag all live in the model. Blank non-inbox titles stay null- // here so the web picker can apply its own i18n default.- return ctx.getAgentModel(workspaceId).listMessengerBindableAgents();- }),-- /**- * List the scopes the user can route the System Bot to: their personal space- * plus every workspace they belong to. Drives the connection card's- * first-level "scope" selector; the second level then calls- * `listAgentsForBinding({ workspaceId })` for the picked scope. Personal scope- * is implicit (the client prepends it) β this only returns workspaces, so in- * OSS / personal-only deployments it's simply an empty array.- */- listBindingScopes: messengerProcedure.query(async ({ ctx }) => {- if (!(await isWorkspaceFeatureEnabledForUser(ctx.userId))) return [];-- const workspaces = await new WorkspaceModel(ctx.serverDB, ctx.userId).listUserWorkspaces();- return workspaces.map((w) => ({ avatar: w.avatar, id: w.id, name: w.name }));- }),-- /**- * Get the current user's link for one platform (or null). `tenantId`- * narrows to a specific Slack workspace; omit for Telegram (global bot).- */- getMyLink: messengerProcedure- .input(z.object({ platform: platformEnum, tenantId: z.string().optional() }))- .query(async ({ input, ctx }) => {- return (await ctx.messengerLinkModel.findByPlatform(input.platform, input.tenantId)) ?? null;- }),-- /** List all the current user's links across platforms (and tenants). */- listMyLinks: messengerProcedure.query(async ({ ctx }) => {- return ctx.messengerLinkModel.list();- }),-- /**- * Proactive-push window status for the caller's link on a platform:- * deliverability mode, remaining quota, expiry, and queued messages.- * Read-only; used by the messenger settings UI.- */- getMessengerPushWindow: messengerProcedure- .input(- z.object({- platform: z.enum(MESSENGER_PUSH_PLATFORMS),- tenantId: z.string().optional(),- }),- )- .query(async ({ input, ctx }) => {- return getMessengerPushWindow({- platform: input.platform,- serverDB: ctx.serverDB,- tenantId: input.tenantId,- userId: ctx.userId,- });- }),-- /**- * Proactively push a message to the caller's linked messenger account.- *- * Platform-agnostic entry (see services/messenger/push): windowed platforms- * like WeChat deliver inside the current send window and queue outside it β- * the caller gets `queued`, never a silent drop. This is the low-level- * capability the notification-channel integration will build on.- */- sendMessengerPush: messengerProcedure- .input(- z- .object({- // Attachments are referenced by `fileId` only β deliberately NOT the- // `attachmentsInputSchema` shape from botMessage.ts, which also- // accepts `data` / `fetchUrl`. The platform senders materialize- // `fetchUrl` with a server-side `fetch`, so accepting one here would- // let any authenticated caller aim that fetch at an internal address- // and have the response uploaded into their own DM. Every field the- // senders need is read from the owned file row below instead.- attachments: z- .array(- z.object({- fileId: z.string().min(1),- type: z.enum(['image', 'file', 'video', 'audio']),- }),- )- .max(10)- .optional(),- content: z.string().trim().max(MESSENGER_PUSH_CONTENT_MAX_LENGTH).optional(),- // What to do with an image the platform will not take at full size.- // Absent means `compress` β the behavior before the choice existed.- oversizeImageStrategy: z.enum(['compress', 'link']).optional(),- platform: z.enum(MESSENGER_PUSH_PLATFORMS),- tenantId: z.string().optional(),- })- .refine((value) => !!value.content || !!value.attachments?.length, {- message: 'Either content or attachments is required',- }),- )- .mutation(async ({ input, ctx }) => {- let attachments: BotMessageAttachment[] | undefined;-- // Resolve each `fileId` server-side. Two reasons the URL is not taken- // from the client: a client-held storage URL is a presigned snapshot- // that expires (typically 2h), so by the time the platform sender- // fetches it the download can 403 and the attachment silently degrades- // to a text-only message; and an arbitrary caller-supplied URL would- // turn the sender's `fetch` into an SSRF primitive. `getFileAccessUrl`- // returns the stable anonymous file-proxy URL in production (storage URL- // in dev), and the ownership-scoped lookup keeps callers from attaching- // other users' files. Name and MIME type come from the same owned row.- if (input.attachments?.length) {- const workspaceId = ctx.workspaceId ?? undefined;- const fileModel = new FileModel(ctx.serverDB, ctx.userId, workspaceId);- const fileService = new FileService(ctx.serverDB, ctx.userId, workspaceId);-- attachments = await Promise.all(- input.attachments.map(async (attachment) => {- const file = await fileModel.findById(attachment.fileId);- if (!file) {- throw new TRPCError({ code: 'NOT_FOUND', message: 'File not found' });- }-- return {- fetchUrl: await fileService.getFileAccessUrl({ id: file.id, url: file.url }),- // Built here from a row this caller was checked to own, so the- // outbound guard may accept our own configured origins for it β- // which self-hosted storage and dev (localhost storage URL) need.- trustedUrl: true,- mimeType: file.fileType,- name: file.name,- // Byte size from the owned row β the send path uses it to apply- // per-platform budgets (compress / degrade-to-link) without- // having to download URL-sourced attachments first.- size: file.size,- type: attachment.type,- };- }),- );- }-- return sendMessengerPush({- attachments,- content: input.content,- oversizeImageStrategy: input.oversizeImageStrategy,- platform: input.platform,- serverDB: ctx.serverDB,- tenantId: input.tenantId,- userId: ctx.userId,- });- }),-- /**- * Set which agent the IM session routes to. Pass `agentId: null` to clear- * the active agent (next inbound message will get the "/agents to pick"- * prompt). Pass `tenantId` to scope to a specific Slack workspace.- */- setActiveAgent: messengerProcedure- .input(- z.object({- agentId: z.string().nullable(),- platform: platformEnum,- tenantId: z.string().optional(),- }),- )- .mutation(async ({ input, ctx }) => {- // Authorize the target agent against its own workspace and derive the- // active scope (personal β null). Clearing (`agentId: null`) resets to- // personal scope.- let workspaceId: string | null = null;- if (input.agentId !== null) {- const scope = await resolveAuthorizedAgentScope(ctx.serverDB, ctx.userId, input.agentId);- workspaceId = scope.workspaceId;- }-- const updated = await ctx.messengerLinkModel.setActiveAgent(- input.platform,- input.agentId,- workspaceId,- input.tenantId,- );- if (!updated) {- throw new TRPCError({- code: 'NOT_FOUND',- message: 'messenger.error.linkRequired',- });- }- return { data: updated, success: true };- }),-- /** Remove the user's account link for a platform (optionally scoped to one tenant). */- unlink: messengerWriteProcedure- .input(z.object({ platform: platformEnum, tenantId: z.string().optional() }))- .mutation(async ({ input, ctx }) => {- if (input.platform !== 'wechat' && !(await isMessengerPlatformEnabled(input.platform))) {- throw new TRPCError({- code: 'BAD_REQUEST',- message: 'messenger.error.platformNotConfigured',- });- }-- if (input.platform === 'wechat') {- const links = (await ctx.messengerLinkModel.list()).filter(- (link) =>- link.platform === 'wechat' &&- (input.tenantId === undefined || link.tenantId === input.tenantId),- );-- await ctx.messengerLinkModel.deleteByPlatform('wechat', input.tenantId);- await Promise.all(links.map((link) => disconnectWechatAccountLink(link, ctx.userId)));- return { success: true };- }-- await ctx.messengerLinkModel.deleteByPlatform(input.platform, input.tenantId);- return { success: true };- }),-- /** List the current user's System Bot connections without credential data. */- listMyInstallations: messengerProcedure.query(async ({ ctx }) => {- const gateKeeper = await KeyVaultsGateKeeper.initWithEnvKey().catch(() => undefined);- const [rows, links] = await Promise.all([- MessengerInstallationModel.listByInstallerUserId(ctx.serverDB, ctx.userId, gateKeeper),- ctx.messengerLinkModel.list(),- ]);- const activeRows = (- await Promise.all(- rows- .filter((row) => row.platform !== 'wechat')- .map((row) => reconcileSlackInstallation(ctx.serverDB, row)),- )- ).filter((row): row is DecryptedMessengerInstallation => row !== null);-- const installationViews = activeRows.map((row) => ({- applicationId: row.applicationId,- enterpriseId: (row.metadata as Record<string, unknown> | null)?.enterpriseId ?? null,- id: row.id,- installedAt: row.createdAt,- isEnterpriseInstall:- (row.metadata as Record<string, unknown> | null)?.isEnterpriseInstall === true,- platform: row.platform,- runtime: undefined,- scope: ((row.metadata as Record<string, unknown> | null)?.scope as string) ?? '',- tenantId: row.tenantId,- tenantName: ((row.metadata as Record<string, unknown> | null)?.tenantName as string) ?? '',- }));- const wechatViews = await Promise.all(- links- .filter(- (link): link is SafeMessengerAccountLink & { applicationId: string } =>- link.platform === 'wechat' && typeof link.applicationId === 'string',- )- .map(async (link) => ({- applicationId: link.applicationId,- enterpriseId: null,- id: link.id,- installedAt: link.createdAt,- isEnterpriseInstall: false,- platform: 'wechat',- runtime: await getBotRuntimeStatus('wechat', link.applicationId),- scope: '',- tenantId: link.tenantId,- tenantName: 'WeChat',- })),- );-- // Telegram is deliberately absent here even though the account link makes it- // reachable. This list doubles as send-target discovery for the client tool- // adapter, which resolves a per-agent `botId` from `platform` and ignores- // `messengerInstallationId` β the client adapter cannot route sends through a System Bot installation. Surfacing the synthetic- // singleton would turn a clean "I can't reach Telegram" into a confusing- // `No enabled bot found for platform "telegram"` for anyone who linked the- // System Bot but has no per-agent Telegram provider. Reaching the user- // themselves does not need this list at all β that is `sendMessengerPush`,- // which routes through the account link directly.- return [...installationViews, ...wechatViews];- }),-- /**- * Disconnect a System Bot connection. WeChat owns its credentials on the- * account link, so disconnecting deletes that user-owned aggregate. Other- * tenant platforms revoke their shared installation row.- *- * Semantics differ per platform: for Slack, revoking the row freezes the- * workspace's bot since dispatch is gated on the install token. For Discord,- * the runtime still uses the global env-side bot token, so revoking only- * removes the audit/listing entry β the bot itself remains in the guild- * until an admin removes it. UI copy is responsible for surfacing this.- *- * Cascading effect on `messenger_account_links` rows for that tenant is- * intentional: link rows persist so re-installing later restores the- * binding without re-running verify-im. To wipe a user's link, call `unlink`- * with `tenantId`.- *- * Slack's `auth.revoke` to invalidate the token server-side is a- * nice-to-have (frees a workspace bot slot), deferred to PR3.- */- uninstallInstallation: messengerWriteProcedure- .input(z.object({ installationId: z.string().min(1) }))- .mutation(async ({ input, ctx }) => {- const gateKeeper = await KeyVaultsGateKeeper.initWithEnvKey().catch(() => undefined);- const wechatLink = await ctx.messengerLinkModel.findById(input.installationId, 'wechat');- if (wechatLink) {- await ctx.messengerLinkModel.delete(wechatLink.id);- await disconnectWechatAccountLink(wechatLink, ctx.userId);- return { success: true };- }-- const row = await MessengerInstallationModel.findById(- ctx.serverDB,- input.installationId,- gateKeeper,- );- if (!row) {- throw new TRPCError({- code: 'NOT_FOUND',- message: 'messenger.error.installationNotFound',- });- }- // Authorization: only the user who initiated the install can disconnect- // it. Workspace admins who installed via a different LobeHub account- // can disconnect through their own settings page.- if (row.installedByUserId !== ctx.userId) {- throw new TRPCError({- code: 'FORBIDDEN',- message: 'messenger.error.disconnectNotAllowed',- });- }- await MessengerInstallationModel.markRevoked(ctx.serverDB, row.id);- return { success: true };- }),-});--/**- * Best-effort confirmation back to the IM platform after a successful link.- * Slack needs `tenantId` to resolve the right per-workspace bot token; Telegram- * is a global bot and ignores it. PR2.4 () rewires the Slack binder- * to receive `InstallationCredentials` via the router's installation store β- * until then this entry point falls back to no-op for Slack (binder.createClient- * returns null in PR1's intermediate state).- */-const notifyLinkSuccess = async (- platform: MessengerPlatform,- params: { activeAgentName?: string; platformUserId: string; tenantId?: string },-) => {- try {- switch (platform) {- case 'telegram': {- await new MessengerTelegramBinder().notifyLinkSuccess(params);- break;- }- case 'slack': {- await new MessengerSlackBinder().notifyLinkSuccess(params);- break;- }- case 'discord': {- await new MessengerDiscordBinder().notifyLinkSuccess(params);- break;- }- }- } catch (error) {- console.error('[messenger:notifyLinkSuccess]', error);- }-};diff --git a/apps/server/src/routers/lambda/messenger/agentScope.ts b/apps/server/src/routers/lambda/messenger/agentScope.tsnew file mode 100644index 00000000000..1ef50e633fa--- /dev/null+++ b/apps/server/src/routers/lambda/messenger/agentScope.ts@@ -0,0 +1,79 @@+import { TRPCError } from '@trpc/server';+import { and, eq } from 'drizzle-orm';++import { RbacModel } from '@/database/models/rbac';+import { WorkspaceModel } from '@/database/models/workspace';+import { agents } from '@/database/schemas';+import type { LobeChatDatabase } from '@/database/type';+import { notTrashed } from '@/database/utils/softDelete';+import { getServerFeatureFlagsStateFromRuntimeConfig } from '@/server/featureFlags';++const WORKSPACE_FEATURE_DISABLED_MESSAGE = 'Workspace feature is not enabled for this user';++export const isWorkspaceFeatureEnabledForUser = async (userId: string): Promise<boolean> => {+ const featureFlags = await getServerFeatureFlagsStateFromRuntimeConfig(userId);+ return featureFlags.enableWorkspace === true;+};++export const assertWorkspaceFeatureEnabledForUser = async (userId: string): Promise<void> => {+ if (await isWorkspaceFeatureEnabledForUser(userId)) return;++ throw new TRPCError({+ code: 'FORBIDDEN',+ message: WORKSPACE_FEATURE_DISABLED_MESSAGE,+ });+};++/**+ * Resolve the workspace scope of an agent the user wants to route the System+ * Bot to, authorizing access along the way. Because the bot is shared and+ * which LobeHub context a conversation runs in is derived from the *active+ * agent*, every place that sets the active agent must re-authorize against+ * that agent's own workspace:+ *+ * - personal agent (`workspace_id IS NULL`): must be owned by the caller.+ * - workspace agent: caller must be a member AND hold `agent:update` in that+ * workspace (mirrors `withScopedPermission('agent:update')`).+ *+ * Returns the derived `workspaceId` (null for personal) + the agent title.+ * Throws `NOT_FOUND` / `FORBIDDEN`.+ */+export const resolveAuthorizedAgentScope = async (+ serverDB: LobeChatDatabase,+ userId: string,+ agentId: string,+): Promise<{ title: string | null; workspaceId: string | null }> => {+ const [agentRow] = await serverDB+ .select({ title: agents.title, userId: agents.userId, workspaceId: agents.workspaceId })+ .from(agents)+ .where(and(eq(agents.id, agentId), notTrashed(agents.isDeleted)))+ .limit(1);+ if (!agentRow) {+ throw new TRPCError({ code: 'NOT_FOUND', message: 'messenger.error.agentNotFound' });+ }++ // Personal agent β only the owner may route the bot to it.+ if (!agentRow.workspaceId) {+ if (agentRow.userId !== userId) {+ throw new TRPCError({ code: 'NOT_FOUND', message: 'messenger.error.agentNotFound' });+ }+ return { title: agentRow.title, workspaceId: null };+ }++ // Workspace agent β caller must be a member with `agent:update`.+ await assertWorkspaceFeatureEnabledForUser(userId);++ const userWorkspaces = await new WorkspaceModel(serverDB, userId).listUserWorkspaces();+ const isMember = userWorkspaces.some((w) => w.id === agentRow.workspaceId);+ if (!isMember) {+ throw new TRPCError({ code: 'FORBIDDEN', message: 'messenger.error.agentNotFound' });+ }+ const allowed = await new RbacModel(serverDB, userId).hasAnyPermission(+ ['agent:update:all', 'agent:update:owner'],+ { workspaceId: agentRow.workspaceId },+ );+ if (!allowed) {+ throw new TRPCError({ code: 'FORBIDDEN', message: 'messenger.error.agentNotFound' });+ }+ return { title: agentRow.title, workspaceId: agentRow.workspaceId };+};diff --git a/apps/server/src/routers/lambda/messenger/bindingOptions.ts b/apps/server/src/routers/lambda/messenger/bindingOptions.tsnew file mode 100644index 00000000000..98714a96d30--- /dev/null+++ b/apps/server/src/routers/lambda/messenger/bindingOptions.ts@@ -0,0 +1,132 @@+import { TRPCError } from '@trpc/server';+import pMap from 'p-map';+import { z } from 'zod';++import { withBotPlatformAccessMeta } from '@/business/server/bot/featureAccess';+import {+ getEnabledMessengerPlatforms,+ getMessengerDiscordConfig,+ getMessengerSlackConfig,+ getMessengerTelegramConfig,+} from '@/config/messenger';+import { WorkspaceModel } from '@/database/models/workspace';+import { router } from '@/libs/trpc/lambda';+import { messengerPlatformRegistry } from '@/server/services/messenger';++import {+ assertWorkspaceFeatureEnabledForUser,+ isWorkspaceFeatureEnabledForUser,+} from './agentScope';+import { messengerProcedure } from './procedures';++/** `withBotPlatformAccessMeta` may read access state per platform; keep the fan-out bounded. */+const PLATFORM_ACCESS_META_CONCURRENCY = 5;++export const bindingOptionsRouter = router({+ /**+ * Surface available platforms + bot deep-link metadata to the UI.+ *+ * The static per-platform fields (`id`, `name`, ...) come from the+ * registry's serialized definitions β same pattern as+ * `agentBotProvider.listPlatforms` for bot channels. Per-deployment+ * fields (`appId`, `botUsername`) layer on top from each platform's+ * DB-backed config:+ *+ * - Slack `appId` powers the verify-im success state's+ * `slack://app?team=β¦&id=β¦` deep link straight into the bot DM.+ * - Discord `applicationId` doubles as the bot user id and feeds the+ * LinkModal's OAuth2 install URL.+ */+ availablePlatforms: messengerProcedure.query(async ({ ctx }) => {+ const enabled = await getEnabledMessengerPlatforms();+ const enabledSet = new Set<string>(enabled);+ const definitions = messengerPlatformRegistry+ .listSerializedPlatforms()+ .filter((def) => enabledSet.has(def.id));++ const [discordConfig, slackConfig, telegramConfig] = await Promise.all([+ enabledSet.has('discord') ? getMessengerDiscordConfig() : Promise.resolve(null),+ enabledSet.has('slack') ? getMessengerSlackConfig() : Promise.resolve(null),+ enabledSet.has('telegram') ? getMessengerTelegramConfig() : Promise.resolve(null),+ ]);++ return pMap(+ definitions,+ async (def) => {+ const serialized = {+ ...def,+ appId:+ def.id === 'slack'+ ? slackConfig?.appId+ : def.id === 'discord'+ ? discordConfig?.applicationId+ : undefined,+ // Telegram-only: deep-link target (`https://t.me/<botUsername>`) β no+ // direct equivalent on Slack/Discord, both of which use App/Application+ // IDs to deep-link to the bot.+ botUsername: def.id === 'telegram' ? telegramConfig?.botUsername : undefined,+ enabled: true,+ // Legacy field β older callers index by `.platform` rather than `.id`.+ // Keep until those callers migrate; safe alias of the registry id.+ platform: def.id,+ };++ return withBotPlatformAccessMeta(serialized, { userId: ctx.userId });+ },+ { concurrency: PLATFORM_ACCESS_META_CONCURRENCY },+ );+ }),+ /**+ * Agent list for the verify-im UI's "pick an initial agent" dropdown.+ *+ * Excludes virtual agents (page-copilot, etc.) but explicitly keeps the+ * inbox/LobeAI agent β historical inbox sessions get migrated with+ * `virtual=true`, so a plain virtual filter would hide LobeAI even though+ * the home sidebar shows it (sidebar fetches it separately via+ * `agent.getBuiltinAgent`).+ *+ * Order matches the home sidebar (`updatedAt DESC`). Title fallback for the+ * inbox agent resolves to `"LobeAI"` + default avatar; everything else falls+ * back on the client via `common.defaultSession`.+ */+ listAgentsForBinding: messengerProcedure+ .input(z.object({ workspaceId: z.string().nullish() }).optional())+ .query(async ({ ctx, input }) => {+ const { serverDB, userId } = ctx;+ // Cascading scope: the caller picks a scope (personal or one of the+ // workspaces they belong to) and we return just that scope's agents.+ // Omitting `workspaceId` (or `null`) means personal.+ const workspaceId = input?.workspaceId ?? null;++ // Authorize the requested scope. Personal is always the caller's own; a+ // workspace scope requires membership, otherwise the caller could+ // enumerate another workspace's agents.+ if (workspaceId) {+ await assertWorkspaceFeatureEnabledForUser(userId);++ const userWorkspaces = await new WorkspaceModel(serverDB, userId).listUserWorkspaces();+ if (!userWorkspaces.some((w) => w.id === workspaceId)) {+ throw new TRPCError({ code: 'FORBIDDEN', message: 'messenger.error.agentNotFound' });+ }+ }++ // Inbox meta fallback, the virtual-or-inbox filter, inbox pinning, and the+ // `isInbox` flag all live in the model. Blank non-inbox titles stay null+ // here so the web picker can apply its own i18n default.+ return ctx.getAgentModel(workspaceId).listMessengerBindableAgents();+ }),+ /**+ * List the scopes the user can route the System Bot to: their personal space+ * plus every workspace they belong to. Drives the connection card's+ * first-level "scope" selector; the second level then calls+ * `listAgentsForBinding({ workspaceId })` for the picked scope. Personal scope+ * is implicit (the client prepends it) β this only returns workspaces, so in+ * OSS / personal-only deployments it's simply an empty array.+ */+ listBindingScopes: messengerProcedure.query(async ({ ctx }) => {+ if (!(await isWorkspaceFeatureEnabledForUser(ctx.userId))) return [];++ const workspaces = await new WorkspaceModel(ctx.serverDB, ctx.userId).listUserWorkspaces();+ return workspaces.map((w) => ({ avatar: w.avatar, id: w.id, name: w.name }));+ }),+});diff --git a/apps/server/src/routers/lambda/messenger/index.procedures.test.ts b/apps/server/src/routers/lambda/messenger/index.procedures.test.tsnew file mode 100644index 00000000000..d842a0039cd--- /dev/null+++ b/apps/server/src/routers/lambda/messenger/index.procedures.test.ts@@ -0,0 +1,46 @@+// @vitest-environment node+import { describe, expect, it } from 'vitest';++import { messengerRouter } from './index';++/**+ * Pins the router's public surface: every procedure path, its kind, and its+ * middleware chain length (which encodes the procedure builder and its input+ * parsers). Splitting the router across files must keep all three.+ */+describe('messengerRouter procedures', () => {+ const procedures = (messengerRouter as any)._def.procedures as Record<string, any>;++ it('exposes exactly the expected procedure paths', () => {+ expect(Object.keys(procedures).sort()).toEqual(expected().map(([name]) => name));+ });++ it.each(expected())('%s is a %s with %i middlewares', (name, type, middlewares) => {+ expect(procedures[name]._def.type).toBe(type);+ expect(procedures[name]._def.middlewares).toHaveLength(middlewares);+ });+});++function expected(): Array<+ [name: string, type: 'mutation' | 'query' | 'subscription', middlewares: number]+> {+ return [+ ['availablePlatforms', 'query', 10],+ ['confirmLink', 'mutation', 11],+ ['createLinqLink', 'mutation', 10],+ ['createWechatQrSession', 'mutation', 10],+ ['getMessengerPushWindow', 'query', 11],+ ['getMyLink', 'query', 11],+ ['listAgentsForBinding', 'query', 11],+ ['listBindingScopes', 'query', 10],+ ['listMyInstallations', 'query', 10],+ ['listMyLinks', 'query', 10],+ ['peekLinkToken', 'query', 7],+ ['pollLinqLink', 'query', 11],+ ['pollWechatQrSession', 'mutation', 11],+ ['sendMessengerPush', 'mutation', 11],+ ['setActiveAgent', 'mutation', 11],+ ['uninstallInstallation', 'mutation', 12],+ ['unlink', 'mutation', 12],+ ];+}diff --git a/apps/server/src/routers/lambda/messenger/index.ts b/apps/server/src/routers/lambda/messenger/index.tsnew file mode 100644index 00000000000..c97b32ecf7f--- /dev/null+++ b/apps/server/src/routers/lambda/messenger/index.ts@@ -0,0 +1,19 @@+import { mergeRouters } from '@/libs/trpc/lambda';++import { bindingOptionsRouter } from './bindingOptions';+import { installationsRouter } from './installations';+import { linksRouter } from './links';+import { linkTokenRouter } from './linkToken';+import { linqRouter } from './linq';+import { pushRouter } from './push';+import { wechatRouter } from './wechat';++export const messengerRouter = mergeRouters(+ bindingOptionsRouter,+ wechatRouter,+ linqRouter,+ linkTokenRouter,+ linksRouter,+ pushRouter,+ installationsRouter,+);diff --git a/apps/server/src/routers/lambda/messenger/installations.fanout.test.ts b/apps/server/src/routers/lambda/messenger/installations.fanout.test.tsnew file mode 100644index 00000000000..61e50881c79--- /dev/null+++ b/apps/server/src/routers/lambda/messenger/installations.fanout.test.ts@@ -0,0 +1,129 @@+// @vitest-environment node+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { createCallerFactory } from '@/libs/trpc/lambda';+import { createContextInner } from '@/libs/trpc/lambda/context';++import { installationsRouter } from './installations';+import {+ FANOUT_CAP,+ FANOUT_COUNT,+ fanoutRange,+ slackInstall,+ trackInFlight,+ wechatLink,+} from './testUtils';++const {+ mockGetBotRuntimeStatus,+ mockGetServerDB,+ mockListAccountLinks,+ mockListByInstallerUserId,+ mockSlackAuthTest,+} = vi.hoisted(() => ({+ mockGetBotRuntimeStatus: vi.fn(),+ mockGetServerDB: vi.fn(),+ mockListAccountLinks: vi.fn(),+ mockListByInstallerUserId: vi.fn(),+ mockSlackAuthTest: vi.fn(),+}));++vi.mock('@lobechat/chat-adapter-wechat', () => ({+ fetchQrCode: vi.fn(),+ getWechatTextSendCount: () => 1,+ pollQrStatus: vi.fn(),+}));+vi.mock('@/config/messenger', () => ({+ getEnabledMessengerPlatforms: vi.fn().mockResolvedValue([]),+ getMessengerDiscordConfig: vi.fn(),+ getMessengerSlackConfig: vi.fn(),+ getMessengerTelegramConfig: vi.fn(),+ isMessengerPlatformEnabled: vi.fn().mockResolvedValue(true),+}));+vi.mock('@/database/core/db-adaptor', () => ({ getServerDB: mockGetServerDB }));+vi.mock('@/database/models/messengerInstallation', () => ({+ MessengerInstallationModel: {+ findById: vi.fn(),+ listByInstallerUserId: mockListByInstallerUserId,+ markRevoked: vi.fn(),+ },+}));+vi.mock('@/database/models/messengerAccountLink', () => ({+ MessengerAccountLinkConflictError: class extends Error {},+ MessengerAccountLinkRelinkRequiredError: class extends Error {},+ MessengerAccountLinkModel: class {+ deleteByPlatform = vi.fn();+ list = mockListAccountLinks;+ },+}));+vi.mock('@/server/modules/KeyVaultsEncrypt', () => ({+ KeyVaultsGateKeeper: { initWithEnvKey: vi.fn().mockResolvedValue({ kind: 'gatekeeper' }) },+}));+vi.mock('@/server/modules/AgentRuntime/redis', () => ({+ getAgentRuntimeRedisClient: () => null,+}));+vi.mock('@/server/services/messenger', () => ({+ getMessengerRouter: () => ({ invalidateBot: vi.fn() }),+ messengerPlatformRegistry: { listSerializedPlatforms: vi.fn().mockReturnValue([]) },+}));+vi.mock('@/server/services/gateway', () => ({+ GatewayService: class {+ disconnectUserMessenger = vi.fn();+ },+}));+vi.mock('@/server/services/gateway/runtimeStatus', () => ({+ getBotRuntimeStatus: mockGetBotRuntimeStatus,+}));+vi.mock('@/server/services/messenger/installations', () => ({+ wechatInstallationKey: (tenantId: string) => `wechat:${tenantId}`,+}));+vi.mock('@/server/services/bot/platforms/slack/api', () => ({+ SlackApi: vi.fn().mockImplementation(function () {+ return { authTest: mockSlackAuthTest };+ }),+}));++const createCaller = createCallerFactory(installationsRouter);+const caller = async () => createCaller(await createContextInner({ userId: 'user-1' }));++describe('messenger installations fan-outs', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ mockGetServerDB.mockResolvedValue({ kind: 'server-db' });+ mockListAccountLinks.mockResolvedValue([]);+ mockListByInstallerUserId.mockResolvedValue([]);+ });++ it('listMyInstallations bounds Slack reconciles and keeps their order', async () => {+ const tracker = trackInFlight(() => ({ ok: true }));+ mockSlackAuthTest.mockImplementation(tracker.fn);+ mockListByInstallerUserId.mockResolvedValue(fanoutRange.map(slackInstall));++ const result = await (await caller()).listMyInstallations();++ expect(result.map((view) => view.id)).toEqual(fanoutRange.map((i) => `install-${i}`));+ expect(mockSlackAuthTest).toHaveBeenCalledTimes(FANOUT_COUNT);+ expect(tracker.state.peak).toBeGreaterThan(1);+ expect(tracker.state.peak).toBeLessThanOrEqual(FANOUT_CAP);+ });++ it('listMyInstallations bounds WeChat runtime lookups and keeps their order', async () => {+ const tracker = trackInFlight((_platform: string, applicationId: string) => ({+ applicationId,+ status: 'connected',+ }));+ mockGetBotRuntimeStatus.mockImplementation(tracker.fn);+ mockListAccountLinks.mockResolvedValue(fanoutRange.map(wechatLink));++ const result = await (await caller()).listMyInstallations();++ expect(result.map((view) => [view.id, view.runtime])).toEqual(+ fanoutRange.map((i) => [+ `wechat-link-${i}`,+ { applicationId: `wechat-bot-${i}`, status: 'connected' },+ ]),+ );+ expect(tracker.state.peak).toBeGreaterThan(1);+ expect(tracker.state.peak).toBeLessThanOrEqual(FANOUT_CAP);+ });+});diff --git a/apps/server/src/routers/lambda/messenger/installations.ts b/apps/server/src/routers/lambda/messenger/installations.tsnew file mode 100644index 00000000000..218e44fcb15--- /dev/null+++ b/apps/server/src/routers/lambda/messenger/installations.ts@@ -0,0 +1,174 @@+import { TRPCError } from '@trpc/server';+import pMap from 'p-map';+import { z } from 'zod';++import type { SafeMessengerAccountLink } from '@/database/models/messengerAccountLink';+import type { DecryptedMessengerInstallation } from '@/database/models/messengerInstallation';+import { MessengerInstallationModel } from '@/database/models/messengerInstallation';+import type { LobeChatDatabase } from '@/database/type';+import { router } from '@/libs/trpc/lambda';+import { KeyVaultsGateKeeper } from '@/server/modules/KeyVaultsEncrypt';+import { SlackApi } from '@/server/services/bot/platforms/slack/api';+import { getBotRuntimeStatus } from '@/server/services/gateway/runtimeStatus';++import { messengerProcedure, messengerWriteProcedure } from './procedures';+import { disconnectWechatAccountLink } from './wechat';++// Each Slack reconcile is an `auth.test` call (plus a DB write on revocation).+const SLACK_RECONCILE_CONCURRENCY = 5;+// Each WeChat view awaits a gateway runtime-status lookup.+const WECHAT_RUNTIME_STATUS_CONCURRENCY = 5;++const REVOKED_SLACK_AUTH_ERRORS = new Set([+ 'account_inactive',+ 'invalid_auth',+ 'not_authed',+ 'token_revoked',+]);++const extractSlackAuthErrorCode = (error: unknown): string | null => {+ if (!(error instanceof Error)) return null;++ const match = error.message.match(/Slack API auth\.test failed: ([a-z_]+)/);+ return match?.[1] ?? null;+};++const reconcileSlackInstallation = async (+ serverDB: LobeChatDatabase,+ row: DecryptedMessengerInstallation,+): Promise<DecryptedMessengerInstallation | null> => {+ if (row.platform !== 'slack') return row;++ const botToken = (row.credentials as { botToken?: string })?.botToken;+ if (!botToken) return row;++ try {+ await new SlackApi(botToken).authTest();+ return row;+ } catch (error) {+ const errorCode = extractSlackAuthErrorCode(error);++ if (errorCode && REVOKED_SLACK_AUTH_ERRORS.has(errorCode)) {+ await MessengerInstallationModel.markRevoked(serverDB, row.id);+ return null;+ }++ console.error('[messenger:listMyInstallations] failed to verify Slack installation', error);+ return row;+ }+};++export const installationsRouter = router({+ /** List the current user's System Bot connections without credential data. */+ listMyInstallations: messengerProcedure.query(async ({ ctx }) => {+ const gateKeeper = await KeyVaultsGateKeeper.initWithEnvKey().catch(() => undefined);+ const [rows, links] = await Promise.all([+ MessengerInstallationModel.listByInstallerUserId(ctx.serverDB, ctx.userId, gateKeeper),+ ctx.messengerLinkModel.list(),+ ]);+ const activeRows = (+ await pMap(+ rows.filter((row) => row.platform !== 'wechat'),+ (row) => reconcileSlackInstallation(ctx.serverDB, row),+ { concurrency: SLACK_RECONCILE_CONCURRENCY },+ )+ ).filter((row): row is DecryptedMessengerInstallation => row !== null);++ const installationViews = activeRows.map((row) => ({+ applicationId: row.applicationId,+ enterpriseId: (row.metadata as Record<string, unknown> | null)?.enterpriseId ?? null,+ id: row.id,+ installedAt: row.createdAt,+ isEnterpriseInstall:+ (row.metadata as Record<string, unknown> | null)?.isEnterpriseInstall === true,+ platform: row.platform,+ runtime: undefined,+ scope: ((row.metadata as Record<string, unknown> | null)?.scope as string) ?? '',+ tenantId: row.tenantId,+ tenantName: ((row.metadata as Record<string, unknown> | null)?.tenantName as string) ?? '',+ }));+ const wechatViews = await pMap(+ links.filter(+ (link): link is SafeMessengerAccountLink & { applicationId: string } =>+ link.platform === 'wechat' && typeof link.applicationId === 'string',+ ),+ async (link) => ({+ applicationId: link.applicationId,+ enterpriseId: null,+ id: link.id,+ installedAt: link.createdAt,+ isEnterpriseInstall: false,+ platform: 'wechat',+ runtime: await getBotRuntimeStatus('wechat', link.applicationId),+ scope: '',+ tenantId: link.tenantId,+ tenantName: 'WeChat',+ }),+ { concurrency: WECHAT_RUNTIME_STATUS_CONCURRENCY },+ );++ // Telegram is deliberately absent here even though the account link makes it+ // reachable. This list doubles as send-target discovery for the client tool+ // adapter, which resolves a per-agent `botId` from `platform` and ignores+ // `messengerInstallationId` β the client adapter cannot route sends through a System Bot installation. Surfacing the synthetic+ // singleton would turn a clean "I can't reach Telegram" into a confusing+ // `No enabled bot found for platform "telegram"` for anyone who linked the+ // System Bot but has no per-agent Telegram provider. Reaching the user+ // themselves does not need this list at all β that is `sendMessengerPush`,+ // which routes through the account link directly.+ return [...installationViews, ...wechatViews];+ }),+ /**+ * Disconnect a System Bot connection. WeChat owns its credentials on the+ * account link, so disconnecting deletes that user-owned aggregate. Other+ * tenant platforms revoke their shared installation row.+ *+ * Semantics differ per platform: for Slack, revoking the row freezes the+ * workspace's bot since dispatch is gated on the install token. For Discord,+ * the runtime still uses the global env-side bot token, so revoking only+ * removes the audit/listing entry β the bot itself remains in the guild+ * until an admin removes it. UI copy is responsible for surfacing this.+ *+ * Cascading effect on `messenger_account_links` rows for that tenant is+ * intentional: link rows persist so re-installing later restores the+ * binding without re-running verify-im. To wipe a user's link, call `unlink`+ * with `tenantId`.+ *+ * Slack's `auth.revoke` to invalidate the token server-side is a+ * nice-to-have (frees a workspace bot slot), deferred to PR3.+ */+ uninstallInstallation: messengerWriteProcedure+ .input(z.object({ installationId: z.string().min(1) }))+ .mutation(async ({ input, ctx }) => {+ const gateKeeper = await KeyVaultsGateKeeper.initWithEnvKey().catch(() => undefined);+ const wechatLink = await ctx.messengerLinkModel.findById(input.installationId, 'wechat');+ if (wechatLink) {+ await ctx.messengerLinkModel.delete(wechatLink.id);+ await disconnectWechatAccountLink(wechatLink, ctx.userId);+ return { success: true };+ }++ const row = await MessengerInstallationModel.findById(+ ctx.serverDB,+ input.installationId,+ gateKeeper,+ );+ if (!row) {+ throw new TRPCError({+ code: 'NOT_FOUND',+ message: 'messenger.error.installationNotFound',+ });+ }+ // Authorization: only the user who initiated the install can disconnect+ // it. Workspace admins who installed via a different LobeHub account+ // can disconnect through their own settings page.+ if (row.installedByUserId !== ctx.userId) {+ throw new TRPCError({+ code: 'FORBIDDEN',+ message: 'messenger.error.disconnectNotAllowed',+ });+ }+ await MessengerInstallationModel.markRevoked(ctx.serverDB, row.id);+ return { success: true };+ }),+});diff --git a/apps/server/src/routers/lambda/messenger/linkToken.ts b/apps/server/src/routers/lambda/messenger/linkToken.tsnew file mode 100644index 00000000000..aa0260ae5b6--- /dev/null+++ b/apps/server/src/routers/lambda/messenger/linkToken.ts@@ -0,0 +1,261 @@+import { TRPCError } from '@trpc/server';+import { eq } from 'drizzle-orm';+import { z } from 'zod';++import { type MessengerPlatform } from '@/config/messenger';+import {+ MessengerAccountLinkConflictError,+ MessengerAccountLinkModel,+ MessengerAccountLinkRelinkRequiredError,+} from '@/database/models/messengerAccountLink';+import { users } from '@/database/schemas';+import { publicProcedure, router } from '@/libs/trpc/lambda';+import { serverDatabase } from '@/libs/trpc/lambda/middleware';+import {+ consumeLinkToken,+ MessengerDiscordBinder,+ MessengerSlackBinder,+ MessengerTelegramBinder,+ peekConsumedLinkToken,+ peekLinkToken,+} from '@/server/services/messenger';++import { resolveAuthorizedAgentScope } from './agentScope';+import { messengerProcedure } from './procedures';++/**+ * Reveal enough of the email so a legitimate owner recognizes the account+ * without exposing the full address to anyone with Slack-side access to+ * the IM identity.+ */+const maskEmail = (email: string): string => {+ const [local, domain] = email.split('@');+ if (!domain) return email;+ const head = local.slice(0, Math.min(2, local.length));+ return `${head}***@${domain}`;+};++/**+ * Best-effort confirmation back to the IM platform after a successful link.+ * Slack needs `tenantId` to resolve the right per-workspace bot token; Telegram+ * is a global bot and ignores it. PR2.4 () rewires the Slack binder+ * to receive `InstallationCredentials` via the router's installation store β+ * until then this entry point falls back to no-op for Slack (binder.createClient+ * returns null in PR1's intermediate state).+ */+const notifyLinkSuccess = async (+ platform: MessengerPlatform,+ params: { activeAgentName?: string; platformUserId: string; tenantId?: string },+) => {+ try {+ switch (platform) {+ case 'telegram': {+ await new MessengerTelegramBinder().notifyLinkSuccess(params);+ break;+ }+ case 'slack': {+ await new MessengerSlackBinder().notifyLinkSuccess(params);+ break;+ }+ case 'discord': {+ await new MessengerDiscordBinder().notifyLinkSuccess(params);+ break;+ }+ }+ } catch (error) {+ console.error('[messenger:notifyLinkSuccess]', error);+ }+};++export const linkTokenRouter = router({+ /**+ * Public peek used by the verify-im page to render the IM identity preview+ * before the user confirms. Does NOT consume the token.+ *+ * Also surfaces `linkedToEmail` when the IM identity is already bound to+ * a LobeHub account β the page uses it to warn the user before they create+ * a duplicate that would either fail the unique index or shadow another+ * account's binding. Email is partially masked for privacy.+ *+ * Returns a discriminated union by `status`:+ * - `active`: token is live; payload + linkedToEmail accompany it.+ * - `consumed`: token was already consumed by a successful `confirmLink`.+ * The page can show "binding succeeded" instead of a misleading+ * "expired" error when the user refreshes after confirming.+ * - `expired`: no live token and no consumed marker β TTL ran out before+ * the user finished binding.+ *+ * This procedure intentionally does NOT throw for the `consumed` /+ * `expired` cases β both are routine user states (post-confirm refresh,+ * stale tab) and shouldn't be logged as tRPC handler errors.+ */+ peekLinkToken: publicProcedure+ .use(serverDatabase)+ .input(z.object({ randomId: z.string().min(8) }))+ .query(async ({ input, ctx }) => {+ const payload = await peekLinkToken(input.randomId);+ if (!payload) {+ const consumed = await peekConsumedLinkToken(input.randomId);+ if (consumed) {+ return {+ platform: consumed.platform,+ status: 'consumed' as const,+ tenantId: consumed.tenantId,+ };+ }+ return { status: 'expired' as const };+ }++ const existingLink = await MessengerAccountLinkModel.findByPlatformUser(+ ctx.serverDB,+ payload.platform,+ payload.platformUserId,+ payload.tenantId ?? '',+ );++ let linkedToEmail: string | null = null;+ if (existingLink) {+ const [owner] = await ctx.serverDB+ .select({ email: users.email })+ .from(users)+ .where(eq(users.id, existingLink.userId))+ .limit(1);+ if (owner?.email) linkedToEmail = maskEmail(owner.email);+ }++ return {+ // Set when the IM identity is already linked to some LobeHub account.+ // The verify-im page compares against the current session email and+ // shows a warning when they don't match.+ linkedToEmail,+ platform: payload.platform,+ platformUserId: payload.platformUserId,+ platformUsername: payload.platformUsername,+ status: 'active' as const,+ // Tenant fields are populated by the binder for per-tenant platforms+ // (Slack workspace name) and absent for global-bot platforms; the+ // verify-im page conditionally renders the workspace blurb.+ tenantId: payload.tenantId,+ tenantName: payload.tenantName,+ };+ }),+ /**+ * Confirm the account link. Account-level: creates (or overwrites) a single+ * `messenger_account_links` row for `(userId, platform)`. `initialAgentId` is+ * required so the user's first IM message has somewhere to land β they can+ * always change it later via `/agents` (tap to switch) or the per-agent UI.+ */+ confirmLink: messengerProcedure+ .input(+ z.object({+ initialAgentId: z.string().min(1, 'messenger.error.pickDefaultAgent'),+ randomId: z.string().min(8),+ }),+ )+ .mutation(async ({ input, ctx }) => {+ // Peek first so a cross-user conflict / missing agent doesn't burn the+ // one-shot token β the user can fix the issue (re-login, pick another+ // agent) without going back to the bot for a fresh /start.+ const peeked = await peekLinkToken(input.randomId);+ if (!peeked) {+ throw new TRPCError({+ code: 'NOT_FOUND',+ message: 'verify.error.expired',+ });+ }++ // Cross-user conflict: the (platform, tenant, platformUserId) tuple is+ // already bound to a different LobeHub account. The DB unique index+ // would surface this as an opaque "duplicate key" β replace with a+ // user-facing 409 carrying the masked email of the existing owner.+ const existingLink = await MessengerAccountLinkModel.findByPlatformUser(+ ctx.serverDB,+ peeked.platform,+ peeked.platformUserId,+ peeked.tenantId ?? '',+ );+ if (existingLink && existingLink.userId !== ctx.userId) {+ // The verify-im page surfaces the same conflict (with the masked+ // email of the existing owner) via peekLinkToken's `linkedToEmail`+ // before the user even clicks confirm β this throw is the defensive+ // backstop for the rare race / direct-API caller.+ throw new TRPCError({+ code: 'CONFLICT',+ message: 'verify.error.alreadyLinkedToOther',+ });+ }++ // The verify-im flow should never silently replace an existing binding+ // for the same scope. For Slack the scope is one workspace (tenantId);+ // for Discord/Telegram it is the whole platform. Require an explicit+ // unlink first so account switches stay deliberate.+ const existingUserLink = await ctx.messengerLinkModel.findByPlatform(+ peeked.platform,+ peeked.tenantId ?? '',+ );+ if (existingUserLink && existingUserLink.platformUserId !== peeked.platformUserId) {+ throw new TRPCError({+ code: 'CONFLICT',+ message: 'verify.error.unlinkBeforeRelink',+ });+ }++ // Authorize the chosen initial agent against its own workspace (personal+ // or a workspace the user can access) and derive the active scope.+ const agentScope = await resolveAuthorizedAgentScope(+ ctx.serverDB,+ ctx.userId,+ input.initialAgentId,+ );++ // Now safe to consume β token is single-use; do this last so any error+ // above leaves the token available for retry.+ const payload = await consumeLinkToken(input.randomId);+ if (!payload) {+ // Lost a race with another consumer (or the token expired during the+ // checks above). Treat the same as the initial peek-miss.+ throw new TRPCError({+ code: 'NOT_FOUND',+ message: 'verify.error.expired',+ });+ }++ let link;+ try {+ link = await ctx.messengerLinkModel.upsertForPlatform({+ activeAgentId: input.initialAgentId,+ platform: payload.platform,+ platformUserId: payload.platformUserId,+ platformUsername: payload.platformUsername ?? null,+ tenantId: payload.tenantId ?? '',+ workspaceId: agentScope.workspaceId,+ });+ } catch (error) {+ // Race backstop: the IM identity got bound to another LobeHub user+ // between the pre-check above and the upsert. Re-surface as the same+ // friendly 409 the verify-im UI already knows how to render.+ if (error instanceof MessengerAccountLinkConflictError) {+ throw new TRPCError({+ code: 'CONFLICT',+ message: 'verify.error.alreadyLinkedToOther',+ });+ }+ if (error instanceof MessengerAccountLinkRelinkRequiredError) {+ throw new TRPCError({+ code: 'CONFLICT',+ message: 'verify.error.unlinkBeforeRelink',+ });+ }+ throw error;+ }++ // Best-effort confirmation back to the IM platform.+ void notifyLinkSuccess(payload.platform, {+ activeAgentName: agentScope.title ?? undefined,+ platformUserId: payload.platformUserId,+ tenantId: payload.tenantId,+ });++ return { data: link, success: true };+ }),+});diff --git a/apps/server/src/routers/lambda/messenger/links.fanout.test.ts b/apps/server/src/routers/lambda/messenger/links.fanout.test.tsnew file mode 100644index 00000000000..5f5c90672b0--- /dev/null+++ b/apps/server/src/routers/lambda/messenger/links.fanout.test.ts@@ -0,0 +1,104 @@+// @vitest-environment node+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { createCallerFactory } from '@/libs/trpc/lambda';+import { createContextInner } from '@/libs/trpc/lambda/context';++import { linksRouter } from './links';+import { FANOUT_CAP, fanoutRange, trackInFlight, wechatLink } from './testUtils';++const { mockDeleteByPlatform, mockDisconnectUserMessenger, mockGetServerDB, mockListAccountLinks } =+ vi.hoisted(() => ({+ mockDeleteByPlatform: vi.fn(),+ mockDisconnectUserMessenger: vi.fn(),+ mockGetServerDB: vi.fn(),+ mockListAccountLinks: vi.fn(),+ }));++vi.mock('@lobechat/chat-adapter-wechat', () => ({+ fetchQrCode: vi.fn(),+ getWechatTextSendCount: () => 1,+ pollQrStatus: vi.fn(),+}));+vi.mock('@/config/messenger', () => ({+ getEnabledMessengerPlatforms: vi.fn().mockResolvedValue([]),+ getMessengerDiscordConfig: vi.fn(),+ getMessengerSlackConfig: vi.fn(),+ getMessengerTelegramConfig: vi.fn(),+ isMessengerPlatformEnabled: vi.fn().mockResolvedValue(true),+}));+vi.mock('@/database/core/db-adaptor', () => ({ getServerDB: mockGetServerDB }));+vi.mock('@/database/models/messengerAccountLink', () => ({+ MessengerAccountLinkConflictError: class extends Error {},+ MessengerAccountLinkRelinkRequiredError: class extends Error {},+ MessengerAccountLinkModel: class {+ deleteByPlatform = mockDeleteByPlatform;+ list = mockListAccountLinks;+ },+}));+vi.mock('@/server/modules/KeyVaultsEncrypt', () => ({+ KeyVaultsGateKeeper: { initWithEnvKey: vi.fn().mockResolvedValue({ kind: 'gatekeeper' }) },+}));+vi.mock('@/server/modules/AgentRuntime/redis', () => ({+ getAgentRuntimeRedisClient: () => null,+}));+vi.mock('@/server/services/messenger', () => ({+ getMessengerRouter: () => ({ invalidateBot: vi.fn() }),+ messengerPlatformRegistry: { listSerializedPlatforms: vi.fn().mockReturnValue([]) },+}));+vi.mock('@/server/services/gateway', () => ({+ GatewayService: class {+ disconnectUserMessenger = mockDisconnectUserMessenger;+ },+}));+vi.mock('@/server/services/gateway/runtimeStatus', () => ({+ getBotRuntimeStatus: vi.fn(),+}));+vi.mock('@/server/services/messenger/installations', () => ({+ wechatInstallationKey: (tenantId: string) => `wechat:${tenantId}`,+}));++const createCaller = createCallerFactory(linksRouter);+const caller = async () => createCaller(await createContextInner({ userId: 'user-1' }));++describe('messenger links fan-outs', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ mockGetServerDB.mockResolvedValue({ kind: 'server-db' });+ mockListAccountLinks.mockResolvedValue([]);+ });++ it('unlink bounds WeChat disconnects and disconnects every link', async () => {+ const tracker = trackInFlight(() => undefined);+ mockDisconnectUserMessenger.mockImplementation(tracker.fn);+ mockListAccountLinks.mockResolvedValue(fanoutRange.map(wechatLink));++ await expect((await caller()).unlink({ platform: 'wechat' })).resolves.toEqual({+ success: true,+ });++ expect(mockDeleteByPlatform).toHaveBeenCalledWith('wechat', undefined);+ expect(mockDisconnectUserMessenger.mock.calls.map(([arg]) => arg.installationKey)).toEqual(+ fanoutRange.map((i) => `wechat:wechat-user-${i}`),+ );+ expect(tracker.state.peak).toBeGreaterThan(1);+ expect(tracker.state.peak).toBeLessThanOrEqual(FANOUT_CAP);+ });++ it('unlink still attempts every WeChat disconnect when an early one rejects', async () => {+ const failure = new Error('gateway unavailable');+ const tracker = trackInFlight(({ installationKey }: { installationKey: string }) => {+ if (installationKey === 'wechat:wechat-user-0') throw failure;+ });+ mockDisconnectUserMessenger.mockImplementation(tracker.fn);+ mockListAccountLinks.mockResolvedValue(fanoutRange.map(wechatLink));++ await expect((await caller()).unlink({ platform: 'wechat' })).rejects.toThrow(+ 'gateway unavailable',+ );++ expect(mockDeleteByPlatform).toHaveBeenCalledWith('wechat', undefined);+ expect(mockDisconnectUserMessenger).toHaveBeenCalledTimes(fanoutRange.length);+ expect(tracker.state.peak).toBeLessThanOrEqual(FANOUT_CAP);+ });+});diff --git a/apps/server/src/routers/lambda/messenger/links.ts b/apps/server/src/routers/lambda/messenger/links.tsnew file mode 100644index 00000000000..4a454e3fab4--- /dev/null+++ b/apps/server/src/routers/lambda/messenger/links.ts@@ -0,0 +1,111 @@+import { TRPCError } from '@trpc/server';+import pMap from 'p-map';+import { z } from 'zod';++import { isMessengerPlatformEnabled, type MessengerPlatform } from '@/config/messenger';+import { router } from '@/libs/trpc/lambda';++import { resolveAuthorizedAgentScope } from './agentScope';+import { messengerProcedure, messengerWriteProcedure } from './procedures';+import { disconnectWechatAccountLink } from './wechat';++// Each WeChat disconnect tears down a gateway connection and Redis state.+const WECHAT_DISCONNECT_CONCURRENCY = 5;++const platformEnum = z.enum([+ 'telegram',+ 'slack',+ 'discord',+ 'wechat',+ 'linq',+]) satisfies z.ZodType<MessengerPlatform>;++export const linksRouter = router({+ /**+ * Get the current user's link for one platform (or null). `tenantId`+ * narrows to a specific Slack workspace; omit for Telegram (global bot).+ */+ getMyLink: messengerProcedure+ .input(z.object({ platform: platformEnum, tenantId: z.string().optional() }))+ .query(async ({ input, ctx }) => {+ return (await ctx.messengerLinkModel.findByPlatform(input.platform, input.tenantId)) ?? null;+ }),+ /** List all the current user's links across platforms (and tenants). */+ listMyLinks: messengerProcedure.query(async ({ ctx }) => {+ return ctx.messengerLinkModel.list();+ }),+ /**+ * Set which agent the IM session routes to. Pass `agentId: null` to clear+ * the active agent (next inbound message will get the "/agents to pick"+ * prompt). Pass `tenantId` to scope to a specific Slack workspace.+ */+ setActiveAgent: messengerProcedure+ .input(+ z.object({+ agentId: z.string().nullable(),+ platform: platformEnum,+ tenantId: z.string().optional(),+ }),+ )+ .mutation(async ({ input, ctx }) => {+ // Authorize the target agent against its own workspace and derive the+ // active scope (personal β null). Clearing (`agentId: null`) resets to+ // personal scope.+ let workspaceId: string | null = null;+ if (input.agentId !== null) {+ const scope = await resolveAuthorizedAgentScope(ctx.serverDB, ctx.userId, input.agentId);+ workspaceId = scope.workspaceId;+ }++ const updated = await ctx.messengerLinkModel.setActiveAgent(+ input.platform,+ input.agentId,+ workspaceId,+ input.tenantId,+ );+ if (!updated) {+ throw new TRPCError({+ code: 'NOT_FOUND',+ message: 'messenger.error.linkRequired',+ });+ }+ return { data: updated, success: true };+ }),+ /** Remove the user's account link for a platform (optionally scoped to one tenant). */+ unlink: messengerWriteProcedure+ .input(z.object({ platform: platformEnum, tenantId: z.string().optional() }))+ .mutation(async ({ input, ctx }) => {+ if (input.platform !== 'wechat' && !(await isMessengerPlatformEnabled(input.platform))) {+ throw new TRPCError({+ code: 'BAD_REQUEST',+ message: 'messenger.error.platformNotConfigured',+ });+ }++ if (input.platform === 'wechat') {+ const links = (await ctx.messengerLinkModel.list()).filter(+ (link) =>+ link.platform === 'wechat' &&+ (input.tenantId === undefined || link.tenantId === input.tenantId),+ );++ await ctx.messengerLinkModel.deleteByPlatform('wechat', input.tenantId);+ // The rows are already gone, so a retry cannot rediscover a skipped+ // link: attempt every disconnect, then surface the first failure.+ const errors: unknown[] = [];+ await pMap(+ links,+ (link) =>+ disconnectWechatAccountLink(link, ctx.userId).catch((error: unknown) => {+ errors.push(error);+ }),+ { concurrency: WECHAT_DISCONNECT_CONCURRENCY },+ );+ if (errors.length > 0) throw errors[0];+ return { success: true };+ }++ await ctx.messengerLinkModel.deleteByPlatform(input.platform, input.tenantId);+ return { success: true };+ }),+});diff --git a/apps/server/src/routers/lambda/messenger/linq.ts b/apps/server/src/routers/lambda/messenger/linq.tsnew file mode 100644index 00000000000..37143601fcf--- /dev/null+++ b/apps/server/src/routers/lambda/messenger/linq.ts@@ -0,0 +1,77 @@+import { buildLinqDeepLink, createLinqLinkCode } from '@lobechat/agent-address-linq';+import { INBOX_SESSION_ID } from '@lobechat/const';+import { TRPCError } from '@trpc/server';+import { z } from 'zod';++import { assertBotFeatureAccess } from '@/business/server/bot/featureAccess';+import { getMessengerLinqConfig } from '@/config/messenger';+import { router } from '@/libs/trpc/lambda';+import { issueLinkCode, peekLinkCodeStatus } from '@/server/services/messenger/linkTokenStore';+import { pickLinqPoolNumber } from '@/server/services/messenger/platforms/linq/pool';++import { resolveAuthorizedAgentScope } from './agentScope';+import { messengerProcedure } from './procedures';++export const linqRouter = router({+ /**+ * Start an iMessage / SMS link on the shared Linq pool. The signed-in user+ * gets a one-time code plus `sms:` / `imessage:` deep links prefilled with+ * it; texting that code from their phone to the pool is what binds the+ * sender's handle to this account (see `MessengerLinqBinder`). The pool+ * number is only a destination β any number in the pool would route the+ * same way, because inbound is matched by sender, never by number.+ */+ createLinqLink: messengerProcedure.mutation(async ({ ctx }) => {+ const config = await getMessengerLinqConfig();+ if (!config) {+ throw new TRPCError({+ code: 'BAD_REQUEST',+ message: 'messenger.error.platformNotConfigured',+ });+ }+ await assertBotFeatureAccess({ action: 'manage', platform: 'linq', userId: ctx.userId });++ const existing = await ctx.messengerLinkModel.findByPlatform('linq', '');+ if (existing) {+ throw new TRPCError({ code: 'CONFLICT', message: 'verify.error.unlinkBeforeRelink' });+ }++ // Same default as a first WeChat scan: land on the personal inbox agent so+ // the first message after linking already has somewhere to go.+ const activeAgentId = (await ctx.getAgentModel().getBuiltinAgent(INBOX_SESSION_ID))?.id ?? null;+ const workspaceId = activeAgentId+ ? (await resolveAuthorizedAgentScope(ctx.serverDB, ctx.userId, activeAgentId)).workspaceId+ : null;++ const { code, expiresAt, pollId } = await issueLinkCode({+ activeAgentId,+ mintCode: createLinqLinkCode,+ platform: 'linq',+ userId: ctx.userId,+ workspaceId,+ });++ const deepLink = buildLinqDeepLink({+ code,+ number: pickLinqPoolNumber(config.numbers, ctx.userId),+ });+ if (!deepLink) {+ throw new TRPCError({+ code: 'INTERNAL_SERVER_ERROR',+ message: 'messenger.error.platformNotConfigured',+ });+ }++ return { code, deepLink, expiresAt, pollId };+ }),+ /** Poll a Linq link started by `createLinqLink` until the code arrives. */+ pollLinqLink: messengerProcedure+ .input(z.object({ pollId: z.string().min(8) }))+ .query(async ({ ctx, input }) => {+ const result = await peekLinkCodeStatus(input.pollId, ctx.userId);+ if (result.status !== 'linked') return result;++ const link = await ctx.messengerLinkModel.findByPlatform('linq', '');+ return { ...result, link: link ?? null };+ }),+});diff --git a/apps/server/src/routers/lambda/messenger/procedures.ts b/apps/server/src/routers/lambda/messenger/procedures.tsnew file mode 100644index 00000000000..ccbcf319050--- /dev/null+++ b/apps/server/src/routers/lambda/messenger/procedures.ts@@ -0,0 +1,27 @@+import { withScopedPermission } from '@/business/server/trpc-middlewares/rbacPermission';+import { AgentModel } from '@/database/models/agent';+import { MessengerAccountLinkModel } from '@/database/models/messengerAccountLink';+import { authedProcedure } from '@/libs/trpc/lambda';+import { serverDatabase } from '@/libs/trpc/lambda/middleware';++export const messengerProcedure = authedProcedure.use(serverDatabase).use(async (opts) => {+ const { ctx } = opts;+ return opts.next({+ ctx: {+ // The System Bot is a single shared bot; the workspace a conversation+ // runs in is derived from the *active agent*, not the ambient+ // `X-Workspace-Id` header. So the link model is identity-scoped (by+ // userId), and per-agent authorization happens in-handler via+ // `resolveAuthorizedAgentScope`.+ messengerLinkModel: new MessengerAccountLinkModel(ctx.serverDB, ctx.userId),+ // The bindable-agents scope is request-driven β the cascading scope+ // picker passes the workspace via input, not the ambient header β so+ // expose a workspace-parameterized AgentModel factory rather than a+ // single pre-scoped instance.+ getAgentModel: (workspaceId?: string | null) =>+ new AgentModel(ctx.serverDB, ctx.userId, workspaceId ?? undefined),+ },+ });+});++export const messengerWriteProcedure = messengerProcedure.use(withScopedPermission('agent:update'));diff --git a/apps/server/src/routers/lambda/messenger/push.fanout.test.ts b/apps/server/src/routers/lambda/messenger/push.fanout.test.tsnew file mode 100644index 00000000000..d7f4c69f84e--- /dev/null+++ b/apps/server/src/routers/lambda/messenger/push.fanout.test.ts@@ -0,0 +1,79 @@+// @vitest-environment node+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { createCallerFactory } from '@/libs/trpc/lambda';+import { createContextInner } from '@/libs/trpc/lambda/context';++import { pushRouter } from './push';+import { FANOUT_CAP, trackInFlight } from './testUtils';++const { mockFindFileById, mockGetFileAccessUrl, mockGetServerDB, mockSendMessengerPush } =+ vi.hoisted(() => ({+ mockFindFileById: vi.fn(),+ mockGetFileAccessUrl: vi.fn(),+ mockGetServerDB: vi.fn(),+ mockSendMessengerPush: vi.fn(),+ }));++vi.mock('@/database/core/db-adaptor', () => ({ getServerDB: mockGetServerDB }));+vi.mock('@/database/models/messengerAccountLink', () => ({+ MessengerAccountLinkModel: class {+ list = vi.fn().mockResolvedValue([]);+ },+}));+vi.mock('@/database/models/file', () => ({+ FileModel: class {+ findById = mockFindFileById;+ },+}));+vi.mock('@/server/services/file', () => ({+ FileService: class {+ getFileAccessUrl = mockGetFileAccessUrl;+ },+}));+vi.mock('@/server/services/messenger/push', () => ({+ getMessengerPushWindow: vi.fn(),+ MESSENGER_PUSH_PLATFORMS: ['telegram', 'slack', 'discord', 'wechat'],+ sendMessengerPush: mockSendMessengerPush,+}));++const createCaller = createCallerFactory(pushRouter);+const caller = async () => createCaller(await createContextInner({ userId: 'user-1' }));++describe('messenger push fan-outs', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ mockGetServerDB.mockResolvedValue({ kind: 'server-db' });+ });++ it('sendMessengerPush bounds attachment resolution and keeps attachment order', async () => {+ const attachmentCount = 10;+ const tracker = trackInFlight((id: string) => ({+ fileType: 'image/png',+ id,+ name: `${id}.png`,+ size: 1,+ url: `s3://bucket/${id}.png`,+ }));+ mockFindFileById.mockImplementation(tracker.fn);+ mockGetFileAccessUrl.mockImplementation(async ({ id }: { id: string }) => `https://f/${id}`);+ mockSendMessengerPush.mockResolvedValue({ status: 'sent' });++ await (+ await caller()+ ).sendMessengerPush({+ attachments: Array.from({ length: attachmentCount }, (_, i) => ({+ fileId: `file-${i}`,+ type: 'image' as const,+ })),+ platform: 'telegram',+ });++ const [{ attachments }] = mockSendMessengerPush.mock.calls[0];+ expect(attachments.map((a: { fetchUrl: string }) => a.fetchUrl)).toEqual(+ Array.from({ length: attachmentCount }, (_, i) => `https://f/file-${i}`),+ );+ expect(tracker.state.peak).toBeGreaterThan(1);+ expect(tracker.state.peak).toBeLessThanOrEqual(FANOUT_CAP);+ });+});diff --git a/apps/server/src/routers/lambda/messenger/push.ts b/apps/server/src/routers/lambda/messenger/push.tsnew file mode 100644index 00000000000..d6d357b9703--- /dev/null+++ b/apps/server/src/routers/lambda/messenger/push.ts@@ -0,0 +1,135 @@+import { MESSENGER_PUSH_CONTENT_MAX_LENGTH } from '@lobechat/builtin-tool-message';+import { TRPCError } from '@trpc/server';+import pMap from 'p-map';+import { z } from 'zod';++import { FileModel } from '@/database/models/file';+import { router } from '@/libs/trpc/lambda';+import type { BotMessageAttachment } from '@/server/services/bot/platforms/types';+import { FileService } from '@/server/services/file';+import {+ getMessengerPushWindow,+ MESSENGER_PUSH_PLATFORMS,+ sendMessengerPush,+} from '@/server/services/messenger/push';++import { messengerProcedure } from './procedures';++// Each attachment is a file-row read plus a file access URL resolution.+const ATTACHMENT_RESOLVE_CONCURRENCY = 5;++export const pushRouter = router({+ /**+ * Proactive-push window status for the caller's link on a platform:+ * deliverability mode, remaining quota, expiry, and queued messages.+ * Read-only; used by the messenger settings UI.+ */+ getMessengerPushWindow: messengerProcedure+ .input(+ z.object({+ platform: z.enum(MESSENGER_PUSH_PLATFORMS),+ tenantId: z.string().optional(),+ }),+ )+ .query(async ({ input, ctx }) => {+ return getMessengerPushWindow({+ platform: input.platform,+ serverDB: ctx.serverDB,+ tenantId: input.tenantId,+ userId: ctx.userId,+ });+ }),+ /**+ * Proactively push a message to the caller's linked messenger account.+ *+ * Platform-agnostic entry (see services/messenger/push): windowed platforms+ * like WeChat deliver inside the current send window and queue outside it β+ * the caller gets `queued`, never a silent drop. This is the low-level+ * capability the notification-channel integration will build on.+ */+ sendMessengerPush: messengerProcedure+ .input(+ z+ .object({+ // Attachments are referenced by `fileId` only β deliberately NOT the+ // `attachmentsInputSchema` shape from botMessage.ts, which also+ // accepts `data` / `fetchUrl`. The platform senders materialize+ // `fetchUrl` with a server-side `fetch`, so accepting one here would+ // let any authenticated caller aim that fetch at an internal address+ // and have the response uploaded into their own DM. Every field the+ // senders need is read from the owned file row below instead.+ attachments: z+ .array(+ z.object({+ fileId: z.string().min(1),+ type: z.enum(['image', 'file', 'video', 'audio']),+ }),+ )+ .max(10)+ .optional(),+ content: z.string().trim().max(MESSENGER_PUSH_CONTENT_MAX_LENGTH).optional(),+ // What to do with an image the platform will not take at full size.+ // Absent means `compress` β the behavior before the choice existed.+ oversizeImageStrategy: z.enum(['compress', 'link']).optional(),+ platform: z.enum(MESSENGER_PUSH_PLATFORMS),+ tenantId: z.string().optional(),+ })+ .refine((value) => !!value.content || !!value.attachments?.length, {+ message: 'Either content or attachments is required',+ }),+ )+ .mutation(async ({ input, ctx }) => {+ let attachments: BotMessageAttachment[] | undefined;++ // Resolve each `fileId` server-side. Two reasons the URL is not taken+ // from the client: a client-held storage URL is a presigned snapshot+ // that expires (typically 2h), so by the time the platform sender+ // fetches it the download can 403 and the attachment silently degrades+ // to a text-only message; and an arbitrary caller-supplied URL would+ // turn the sender's `fetch` into an SSRF primitive. `getFileAccessUrl`+ // returns the stable anonymous file-proxy URL in production (storage URL+ // in dev), and the ownership-scoped lookup keeps callers from attaching+ // other users' files. Name and MIME type come from the same owned row.+ if (input.attachments?.length) {+ const workspaceId = ctx.workspaceId ?? undefined;+ const fileModel = new FileModel(ctx.serverDB, ctx.userId, workspaceId);+ const fileService = new FileService(ctx.serverDB, ctx.userId, workspaceId);++ attachments = await pMap(+ input.attachments,+ async (attachment) => {+ const file = await fileModel.findById(attachment.fileId);+ if (!file) {+ throw new TRPCError({ code: 'NOT_FOUND', message: 'File not found' });+ }++ return {+ fetchUrl: await fileService.getFileAccessUrl({ id: file.id, url: file.url }),+ // Built here from a row this caller was checked to own, so the+ // outbound guard may accept our own configured origins for it β+ // which self-hosted storage and dev (localhost storage URL) need.+ trustedUrl: true,+ mimeType: file.fileType,+ name: file.name,+ // Byte size from the owned row β the send path uses it to apply+ // per-platform budgets (compress / degrade-to-link) without+ // having to download URL-sourced attachments first.+ size: file.size,+ type: attachment.type,+ };+ },+ { concurrency: ATTACHMENT_RESOLVE_CONCURRENCY },+ );+ }++ return sendMessengerPush({+ attachments,+ content: input.content,+ oversizeImageStrategy: input.oversizeImageStrategy,+ platform: input.platform,+ serverDB: ctx.serverDB,+ tenantId: input.tenantId,+ userId: ctx.userId,+ });+ }),+});diff --git a/apps/server/src/routers/lambda/messenger/testUtils.ts b/apps/server/src/routers/lambda/messenger/testUtils.tsnew file mode 100644index 00000000000..624b78cd742--- /dev/null+++ b/apps/server/src/routers/lambda/messenger/testUtils.ts@@ -0,0 +1,46 @@+/** The router fan-outs cap concurrent per-item I/O at this many calls. */+export const FANOUT_CAP = 5;++/** Item count used by fan-out tests β comfortably above {@link FANOUT_CAP}. */+export const FANOUT_COUNT = 12;++export const fanoutRange = Array.from({ length: FANOUT_COUNT }, (_, i) => i);++/**+ * Wraps an async implementation so it records the peak number of overlapping+ * calls. Each call yields across a macrotask so unbounded fan-outs overlap.+ */+export const trackInFlight = <A extends unknown[], R>(impl: (...args: A) => R) => {+ const state = { inFlight: 0, peak: 0 };+ const fn = async (...args: A) => {+ state.inFlight += 1;+ state.peak = Math.max(state.peak, state.inFlight);+ await new Promise((resolve) => setTimeout(resolve, 1));+ state.inFlight -= 1;+ return impl(...args);+ };+ return { fn, state };+};++export const wechatLink = (i: number) => ({+ activeAgentId: null,+ applicationId: `wechat-bot-${i}`,+ createdAt: new Date('2026-07-17T00:00:00.000Z'),+ id: `wechat-link-${i}`,+ platform: 'wechat',+ platformUserId: `wechat-user-${i}`,+ tenantId: `wechat-user-${i}`,+ userId: 'user-1',+ workspaceId: null,+});++export const slackInstall = (i: number) => ({+ applicationId: `A_${i}`,+ createdAt: new Date('2026-05-06T00:00:00.000Z'),+ credentials: { botToken: `xoxb-${i}` },+ id: `install-${i}`,+ installedByUserId: 'user-1',+ metadata: { scope: 'chat:write', tenantName: `Team ${i}` },+ platform: 'slack',+ tenantId: `T_${i}`,+});diff --git a/apps/server/src/routers/lambda/messenger/wechat.ts b/apps/server/src/routers/lambda/messenger/wechat.tsnew file mode 100644index 00000000000..c8aa60ec71d--- /dev/null+++ b/apps/server/src/routers/lambda/messenger/wechat.ts@@ -0,0 +1,318 @@+import { fetchQrCode, pollQrStatus } from '@lobechat/chat-adapter-wechat';+import { INBOX_SESSION_ID } from '@lobechat/const';+import { TRPCError } from '@trpc/server';+import { z } from 'zod';++import { assertBotFeatureAccess } from '@/business/server/bot/featureAccess';+import { isMessengerPlatformEnabled } from '@/config/messenger';+import type { SafeMessengerAccountLink } from '@/database/models/messengerAccountLink';+import {+ MessengerAccountLinkConflictError,+ MessengerAccountLinkModel,+ MessengerAccountLinkRelinkRequiredError,+} from '@/database/models/messengerAccountLink';+import type { LobeChatDatabase } from '@/database/type';+import { router } from '@/libs/trpc/lambda';+import { getAgentRuntimeRedisClient } from '@/server/modules/AgentRuntime/redis';+import { KeyVaultsGateKeeper } from '@/server/modules/KeyVaultsEncrypt';+import {+ wechatLegacyTokenKey,+ wechatPendingPushKey,+ wechatWindowKey,+} from '@/server/services/bot/platforms/wechat/contextWindow';+import { GatewayService } from '@/server/services/gateway';+import { getBotRuntimeStatus } from '@/server/services/gateway/runtimeStatus';+import {+ acquireWechatQrFinalizeLock,+ consumeWechatQrSession,+ getMessengerRouter,+ issueWechatQrSession,+ peekWechatQrSession,+ releaseWechatQrFinalizeLock,+} from '@/server/services/messenger';+import { wechatInstallationKey } from '@/server/services/messenger/installations';++import { resolveAuthorizedAgentScope } from './agentScope';+import { messengerProcedure } from './procedures';++export const disconnectWechatAccountLink = async (+ link: SafeMessengerAccountLink,+ userId: string,+): Promise<void> => {+ const installationKey = wechatInstallationKey(link.tenantId);+ await new GatewayService().disconnectUserMessenger({+ installationKey,+ platform: 'wechat',+ userId,+ });+ // A rescan replaces the QR-issued token/baseUrl under the same installation+ // key β drop the cached Chat SDK bot so webhooks rebuild it from the new+ // credentials instead of replying through the stale client.+ getMessengerRouter().invalidateBot(installationKey);++ if (!link.applicationId) return;+ const redis = getAgentRuntimeRedisClient();+ if (redis) {+ await redis.del(+ wechatLegacyTokenKey(link.applicationId, link.tenantId),+ wechatWindowKey(link.applicationId, link.tenantId),+ wechatPendingPushKey(link.applicationId, link.tenantId),+ );+ }+};++export const wechatRouter = router({+ /** Start a user-bound, one-shot WeChat iLink QR session. */+ createWechatQrSession: messengerProcedure.mutation(async ({ ctx }) => {+ if (!(await isMessengerPlatformEnabled('wechat'))) {+ throw new TRPCError({+ code: 'BAD_REQUEST',+ message: 'messenger.error.platformNotConfigured',+ });+ }+ await assertBotFeatureAccess({+ action: 'manage',+ platform: 'wechat',+ userId: ctx.userId,+ });++ try {+ const qr = await fetchQrCode();+ if (!qr.qrcode || !qr.qrcode_img_content) {+ throw new Error('WeChat QR response is incomplete');+ }+ const session = await issueWechatQrSession({+ qrcode: qr.qrcode,+ userId: ctx.userId,+ });+ return {+ ...session,+ qrCodePayload: qr.qrcode_img_content,+ status: 'wait' as const,+ };+ } catch (error) {+ if (error instanceof TRPCError) throw error;+ throw new TRPCError({+ cause: error,+ code: 'BAD_GATEWAY',+ message: 'messenger.wechat.error.qrUnavailable',+ });+ }+ }),+ /**+ * Poll a QR session and finalize the user-owned account connection exactly+ * once when WeChat confirms it. The browser never receives the raw QR token+ * or bot credential bundle.+ */+ pollWechatQrSession: messengerProcedure+ .input(z.object({ sessionId: z.string().min(8) }))+ .mutation(async ({ ctx, input }) => {+ if (!(await isMessengerPlatformEnabled('wechat'))) {+ throw new TRPCError({+ code: 'BAD_REQUEST',+ message: 'messenger.error.platformNotConfigured',+ });+ }+ await assertBotFeatureAccess({+ action: 'manage',+ platform: 'wechat',+ userId: ctx.userId,+ });++ const session = await peekWechatQrSession(input.sessionId, ctx.userId);+ if (!session) return { status: 'expired' as const };++ let qrStatus;+ try {+ qrStatus = await pollQrStatus(session.qrcode);+ } catch (error) {+ throw new TRPCError({+ cause: error,+ code: 'BAD_GATEWAY',+ message: 'messenger.wechat.error.pollFailed',+ });+ }++ if (qrStatus.status === 'wait' || qrStatus.status === 'scaned') {+ return { status: qrStatus.status };+ }+ if (qrStatus.status === 'expired') {+ await consumeWechatQrSession(input.sessionId);+ return { status: 'expired' as const };+ }+ if (+ !qrStatus.bot_token ||+ !qrStatus.ilink_bot_id ||+ !qrStatus.ilink_user_id ||+ !qrStatus.baseurl+ ) {+ throw new TRPCError({+ code: 'BAD_GATEWAY',+ message: 'messenger.wechat.error.incompleteConfirmation',+ });+ }++ const lockToken = await acquireWechatQrFinalizeLock(input.sessionId);+ if (!lockToken) return { status: 'scaned' as const };++ try {+ const platformUserId = qrStatus.ilink_user_id;+ const botId = qrStatus.ilink_bot_id;+ const botToken = qrStatus.bot_token;+ const baseUrl = qrStatus.baseurl;+ const existingIdentity = await MessengerAccountLinkModel.findByPlatformUser(+ ctx.serverDB,+ 'wechat',+ platformUserId,+ platformUserId,+ );+ if (existingIdentity && existingIdentity.userId !== ctx.userId) {+ throw new TRPCError({+ code: 'CONFLICT',+ message: 'messenger.wechat.error.alreadyLinkedToOther',+ });+ }++ const existingUserLink = await ctx.messengerLinkModel.findByPlatform('wechat');+ if (existingUserLink && existingUserLink.platformUserId !== platformUserId) {+ throw new TRPCError({+ code: 'CONFLICT',+ message: 'messenger.wechat.error.unlinkBeforeRelink',+ });+ }++ // A first scan should be immediately usable, so route it to the user's+ // personal inbox (LobeAI). A rescan preserves an authorized Agent+ // choice, but repairs stale/deauthorized links with the same fallback.+ const inboxAgentId =+ (await ctx.getAgentModel().getBuiltinAgent(INBOX_SESSION_ID))?.id ?? null;+ let activeAgentId = existingUserLink?.activeAgentId ?? inboxAgentId;+ let workspaceId: string | null = null;++ if (activeAgentId) {+ try {+ workspaceId = (+ await resolveAuthorizedAgentScope(ctx.serverDB, ctx.userId, activeAgentId)+ ).workspaceId;+ } catch (error) {+ const isStaleAgent =+ error instanceof TRPCError &&+ (error.code === 'NOT_FOUND' || error.code === 'FORBIDDEN');+ if (!isStaleAgent || activeAgentId === inboxAgentId) throw error;++ activeAgentId = inboxAgentId;+ workspaceId = activeAgentId+ ? (await resolveAuthorizedAgentScope(ctx.serverDB, ctx.userId, activeAgentId))+ .workspaceId+ : null;+ }+ }+ const gateKeeper = await KeyVaultsGateKeeper.initWithEnvKey();+ const previousWechatLink = existingUserLink+ ? await ctx.messengerLinkModel.findByIdWithCredentials(+ existingUserLink.id,+ 'wechat',+ gateKeeper,+ )+ : undefined;+ const link = await ctx.serverDB.transaction(async (tx) => {+ const txDB = tx as LobeChatDatabase;+ return new MessengerAccountLinkModel(txDB, ctx.userId).upsertForPlatform(+ {+ activeAgentId,+ applicationId: botId,+ credentials: { baseUrl, botId, botToken },+ platform: 'wechat',+ platformUserId,+ platformUsername: null,+ tenantId: platformUserId,+ workspaceId,+ },+ gateKeeper,+ );+ });++ if (existingUserLink) await disconnectWechatAccountLink(existingUserLink, ctx.userId);+ const gateway = new GatewayService();+ const connectionId = await gateway.ensureUserMessengerConnected({+ installationKey: wechatInstallationKey(platformUserId),+ platform: 'wechat',+ userId: ctx.userId,+ });+ if (!connectionId) {+ // The gateway resolves credentials from the committed account link.+ // Compensate a failed first connection by deleting it; on a rescan,+ // restore the previous credential bundle so a failed replacement+ // never destroys a working user-owned connection.+ const previousApplicationId = previousWechatLink?.applicationId;+ if (previousWechatLink && previousApplicationId) {+ await ctx.serverDB.transaction(async (tx) => {+ const txDB = tx as LobeChatDatabase;+ await new MessengerAccountLinkModel(txDB, ctx.userId).upsertForPlatform(+ {+ activeAgentId: previousWechatLink.activeAgentId,+ applicationId: previousApplicationId,+ credentials: previousWechatLink.credentials,+ platform: 'wechat',+ platformUserId: previousWechatLink.platformUserId,+ platformUsername: previousWechatLink.platformUsername,+ tenantId: previousWechatLink.tenantId,+ workspaceId: previousWechatLink.workspaceId,+ },+ gateKeeper,+ );+ });+ await gateway.ensureUserMessengerConnected({+ installationKey: wechatInstallationKey(previousWechatLink.tenantId),+ platform: 'wechat',+ userId: ctx.userId,+ });+ } else {+ await ctx.serverDB.transaction(async (tx) => {+ const txDB = tx as LobeChatDatabase;+ await new MessengerAccountLinkModel(txDB, ctx.userId).deleteByPlatform(+ 'wechat',+ platformUserId,+ );+ });+ }+ throw new TRPCError({+ code: 'BAD_GATEWAY',+ message: 'messenger.wechat.error.connectionFailed',+ });+ }++ const runtime = await getBotRuntimeStatus('wechat', botId);+ await consumeWechatQrSession(input.sessionId);++ return {+ installation: {+ applicationId: botId,+ id: link.id,+ installedAt: link.createdAt,+ platform: link.platform,+ tenantId: link.tenantId,+ tenantName: 'WeChat',+ },+ link,+ runtime,+ status: 'confirmed' as const,+ };+ } catch (error) {+ await releaseWechatQrFinalizeLock(input.sessionId, lockToken);+ if (error instanceof MessengerAccountLinkConflictError) {+ throw new TRPCError({+ code: 'CONFLICT',+ message: 'messenger.wechat.error.alreadyLinkedToOther',+ });+ }+ if (error instanceof MessengerAccountLinkRelinkRequiredError) {+ throw new TRPCError({+ code: 'CONFLICT',+ message: 'messenger.wechat.error.unlinkBeforeRelink',+ });+ }+ throw error;+ }+ }),+});diff --git a/eslint.config.mjs b/eslint.config.mjsindex 4c5f5183048..1b026eb5c66 100644--- a/eslint.config.mjs+++ b/eslint.config.mjs@@ -213,7 +213,7 @@ const legacyRawRedisClientConsumers = ['apps/server/src/router-hono/agent/handlers/llmRelay.ts','apps/server/src/router-hono/agent/handlers/toolResult.ts','apps/server/src/router-hono/webhooks/handlers/github.ts',- 'apps/server/src/routers/lambda/messenger.ts',+ 'apps/server/src/routers/lambda/messenger/wechat.ts','apps/server/src/services/agentRuntime/opportunisticSweep.ts','apps/server/src/services/agentSignal/store/adapters/redis/shared.ts','apps/server/src/services/bot/BotCallbackService.ts',