๐คฏ 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
๐ fix(bot): stop returning bot credentials from the channel list (#19452)
Arvin Xu689f8a39931f
diff --git a/apps/cli/src/commands/bot.ts b/apps/cli/src/commands/bot.tsindex 4d45e6b7ebd..0fa2362f63a 100644--- a/apps/cli/src/commands/bot.ts+++ b/apps/cli/src/commands/bot.ts@@ -57,11 +57,6 @@ function normalizeAllowList(raw: unknown): AllowEntry[] {return out;}-function maskValue(val: string): string {- if (val.length > 8) return val.slice(0, 4) + '****' + val.slice(-4);- return '****';-}-function camelToFlag(name: string): string {return '--' + name.replaceAll(/([A-Z])/g, '-$1').toLowerCase();}@@ -93,7 +88,13 @@ function extractCredentials(return { credentials, missing };}-/** Find a bot by ID from the user's bot list. */+/**+ * Find a bot by ID.+ *+ * The list is the only way to turn an id into a channel, but it deliberately+ * carries no credentials, so re-read the one we found through the per-agent+ * detail call to get the (masked) credential shape `view` renders.+ */async function findBot(client: TrpcClient, botId: string) {const bots = await client.agentBotProvider.list.query();const bot = (bots as any[]).find((b: any) => b.id === botId);@@ -101,7 +102,12 @@ async function findBot(client: TrpcClient, botId: string) {log.error(`Bot integration not found: ${botId}`);process.exit(1);}- return bot;++ const detailed = (await client.agentBotProvider.getByAgentId.query({+ agentId: bot.agentId,+ })) as any[];++ return detailed.find((b: any) => b.id === botId) ?? bot;}const STATUS_COLORS: Record<string, (s: string) => string> = {@@ -569,61 +575,55 @@ export function registerBotCommand(program: Command) {.command('view <botId>').description('View bot integration details').option('--json [fields]', 'Output JSON, optionally specify fields (comma-separated)')- .option('--show-credentials', 'Show full credential values (unmasked)')- .action(- async (botId: string, options: { json?: string | boolean; showCredentials?: boolean }) => {- const client = await getTrpcClient();- const b = await findBot(client, botId);+ .action(async (botId: string, options: { json?: string | boolean }) => {+ const client = await getTrpcClient();+ const b = await findBot(client, botId);- if (options.json !== undefined) {- const fields = typeof options.json === 'string' ? options.json : undefined;- outputJson(b, fields);- return;- }+ if (options.json !== undefined) {+ const fields = typeof options.json === 'string' ? options.json : undefined;+ outputJson(b, fields);+ return;+ }- const status = b.enabled ? (b.runtimeStatus ?? 'disconnected') : 'disabled';- const statusColorFn = STATUS_COLORS[status] ?? pc.dim;-- const credentialLines: string[] = [];- if (b.credentials && typeof b.credentials === 'object') {- for (const [key, value] of Object.entries(b.credentials)) {- const val = String(value);- const display = options.showCredentials ? val : maskValue(val);- credentialLines.push(`${pc.dim(key)}: ${display}`);- }+ const status = b.enabled ? (b.runtimeStatus ?? 'disconnected') : 'disabled';+ const statusColorFn = STATUS_COLORS[status] ?? pc.dim;++ const credentialLines: string[] = [];+ if (b.credentials && typeof b.credentials === 'object') {+ // Already masked by the server โ there is no unmasked form to opt into.+ for (const [key, value] of Object.entries(b.credentials)) {+ credentialLines.push(`${pc.dim(key)}: ${String(value)}`);}+ }- const settingsLines: string[] = [];- if (b.settings && typeof b.settings === 'object') {- for (const [key, value] of Object.entries(b.settings)) {- settingsLines.push(`${pc.dim(key)}: ${JSON.stringify(value)}`);- }+ const settingsLines: string[] = [];+ if (b.settings && typeof b.settings === 'object') {+ for (const [key, value] of Object.entries(b.settings)) {+ settingsLines.push(`${pc.dim(key)}: ${JSON.stringify(value)}`);}+ }- printBoxTable(- [- { header: 'Field', key: 'field' },- { header: 'Value', key: 'value' },- ],- [- { field: 'ID', value: b.id || '' },- { field: 'Platform', value: pc.cyan(b.platform || '') },- { field: 'Application ID', value: b.applicationId || '' },- { field: 'Agent ID', value: b.agentId || '' },- { field: 'Status', value: statusColorFn(status) },- ...(credentialLines.length > 0- ? [{ field: 'Credentials', value: credentialLines }]- : []),- ...(settingsLines.length > 0 ? [{ field: 'Settings', value: settingsLines }] : []),- ...(b.createdAt- ? [{ field: 'Created', value: new Date(b.createdAt).toLocaleString() }]- : []),- ...(b.updatedAt ? [{ field: 'Updated', value: timeAgo(b.updatedAt) }] : []),- ],- `${b.platform} bot`,- );- },- );+ printBoxTable(+ [+ { header: 'Field', key: 'field' },+ { header: 'Value', key: 'value' },+ ],+ [+ { field: 'ID', value: b.id || '' },+ { field: 'Platform', value: pc.cyan(b.platform || '') },+ { field: 'Application ID', value: b.applicationId || '' },+ { field: 'Agent ID', value: b.agentId || '' },+ { field: 'Status', value: statusColorFn(status) },+ ...(credentialLines.length > 0 ? [{ field: 'Credentials', value: credentialLines }] : []),+ ...(settingsLines.length > 0 ? [{ field: 'Settings', value: settingsLines }] : []),+ ...(b.createdAt+ ? [{ field: 'Created', value: new Date(b.createdAt).toLocaleString() }]+ : []),+ ...(b.updatedAt ? [{ field: 'Updated', value: timeAgo(b.updatedAt) }] : []),+ ],+ `${b.platform} bot`,+ );+ });// โโ add โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโdiff --git a/apps/server/src/routers/lambda/__tests__/agentBotProvider.scope.test.ts b/apps/server/src/routers/lambda/__tests__/agentBotProvider.scope.test.tsindex c67197e281b..0987d5eb51e 100644--- a/apps/server/src/routers/lambda/__tests__/agentBotProvider.scope.test.ts+++ b/apps/server/src/routers/lambda/__tests__/agentBotProvider.scope.test.ts@@ -31,7 +31,23 @@ vi.mock('@/server/services/bot/platforms', () => ({collectFieldFormatViolations: vi.fn(() => []),formatFieldFormatViolations: vi.fn(() => ''),mergeWithDefaults: vi.fn((_p: string, s: unknown) => s),- platformRegistry: { getPlatform: vi.fn(() => undefined) },+ // Shaped like the real feishu entry so the masking helper can tell the+ // secret apart from the identifier.+ platformRegistry: {+ getPlatform: vi.fn(() => ({+ schema: [+ {+ key: 'credentials',+ properties: [+ { key: 'appSecret', type: 'password' },+ { key: 'appId', type: 'string' },+ ],+ type: 'object',+ },+ ],+ })),+ },+ withResolvedConcurrencySettings: vi.fn((_p: string, s: unknown) => s),}));const mockStopClient = vi.fn(async () => {});@@ -62,6 +78,9 @@ vi.mock('@/database/models/workspaceMember', () => ({}));const mockCreate = vi.fn();+const mockQuery = vi.fn();+const mockFindByAgentId = vi.fn();+const mockUpdate = vi.fn();const mockFindById = vi.fn();const mockDelete = vi.fn();const mockFindByIdAcrossScopes = vi.fn();@@ -74,8 +93,11 @@ vi.mock('@/database/models/agentBotProvider', () => {create: mockCreate,delete: mockDelete,deleteAcrossScopes: mockDeleteAcrossScopes,+ findByAgentId: mockFindByAgentId,findById: mockFindById,findByIdAcrossScopes: mockFindByIdAcrossScopes,+ query: mockQuery,+ update: mockUpdate,};});AgentBotProviderModel.findByPlatformAndAppId = mockFindByPlatformAndAppId;@@ -83,6 +105,7 @@ vi.mock('@/database/models/agentBotProvider', () => {});const { agentBotProviderRouter } = await import('../agentBotProvider');+const { CREDENTIAL_MASK } = await import('@/server/services/bot/credentialMasking');/** Shaped like the driver error drizzle surfaces, nested behind `cause`. */const uniqueViolation = () => {@@ -113,6 +136,9 @@ beforeEach(() => {mockFindByIdAcrossScopes.mockResolvedValue(undefined);mockDeleteAcrossScopes.mockResolvedValue([{ id: BOT_ID }]);mockGetMember.mockResolvedValue({ role: 'member' });+ mockQuery.mockResolvedValue([]);+ mockFindByAgentId.mockResolvedValue([]);+ mockUpdate.mockResolvedValue([]);});describe('agentBotProviderRouter ยท bindings stranded outside the active scope', () => {@@ -246,3 +272,99 @@ describe('agentBotProviderRouter ยท bindings stranded outside the active scope',});});});++describe('agentBotProviderRouter ยท credentials never leave through a list', () => {+ const row = {+ agentId: 'agt_1',+ applicationId: 'cli_app',+ credentials: { appId: 'cli_app', appSecret: 'real-secret' },+ enabled: true,+ id: BOT_ID,+ platform: 'feishu',+ settings: {},+ userId: 'user-1',+ workspaceId: 'ws-1',+ };++ it('omits the credentials field from list entirely', async () => {+ mockQuery.mockResolvedValue([row]);+ const caller = agentBotProviderRouter.createCaller(ctx);++ const [entry] = await caller.list();++ expect(entry).not.toHaveProperty('credentials');+ expect(JSON.stringify(entry)).not.toContain('real-secret');+ });++ it('masks the secret but keeps the identifier on the detail read', async () => {+ mockFindByAgentId.mockResolvedValue([row]);+ const caller = agentBotProviderRouter.createCaller(ctx);++ const [entry] = await caller.getByAgentId({ agentId: 'agt_1' });++ expect(entry.credentials).toEqual({ appId: 'cli_app', appSecret: CREDENTIAL_MASK });+ });++ it('restores the stored secret when an edit hands the mask back', async () => {+ mockFindById.mockResolvedValue(row);+ const caller = agentBotProviderRouter.createCaller(ctx);++ await caller.update({+ credentials: { appId: 'cli_app', appSecret: CREDENTIAL_MASK },+ id: BOT_ID,+ });++ expect(mockUpdate).toHaveBeenCalledWith(+ BOT_ID,+ expect.objectContaining({ credentials: { appId: 'cli_app', appSecret: 'real-secret' } }),+ );+ });++ it('persists a genuinely rotated secret', async () => {+ mockFindById.mockResolvedValue(row);+ const caller = agentBotProviderRouter.createCaller(ctx);++ await caller.update({ credentials: { appSecret: 'rotated' }, id: BOT_ID });++ expect(mockUpdate).toHaveBeenCalledWith(+ BOT_ID,+ expect.objectContaining({ credentials: { appSecret: 'rotated' } }),+ );+ });++ it('hands back real credentials on the export read', async () => {+ // The one read that discloses, so a channel can be moved somewhere else.+ // It sits behind the write gate, which is what keeps viewers out.+ mockFindByAgentId.mockResolvedValue([row]);+ const caller = agentBotProviderRouter.createCaller(ctx);++ const [entry] = await caller.exportByAgentId({ agentId: 'agt_1' });++ expect(entry.credentials).toEqual({ appId: 'cli_app', appSecret: 'real-secret' });+ // Row identity stays out of the file: it is re-created on import.+ expect(entry).not.toHaveProperty('id');+ });++ it('will not export a workspace teammateโs channel to a non-owner', async () => {+ mockFindByAgentId.mockResolvedValue([{ ...row, userId: 'someone-else' }]);+ const caller = agentBotProviderRouter.createCaller({ ...ctx, workspaceRole: 'member' });++ await expect(caller.exportByAgentId({ agentId: 'agt_1' })).rejects.toMatchObject({+ code: 'FORBIDDEN',+ });+ });++ it('refuses to create a binding whose secret is the placeholder', async () => {+ const caller = agentBotProviderRouter.createCaller(ctx);++ await expect(+ caller.create({+ agentId: 'agt_1',+ applicationId: 'cli_app',+ credentials: { appSecret: CREDENTIAL_MASK },+ platform: 'feishu',+ }),+ ).rejects.toMatchObject({ code: 'BAD_REQUEST' });+ expect(mockCreate).not.toHaveBeenCalled();+ });+});diff --git a/apps/server/src/routers/lambda/agentBotProvider.ts b/apps/server/src/routers/lambda/agentBotProvider.tsindex 8d8dd35ff35..7d7c860fa55 100644--- a/apps/server/src/routers/lambda/agentBotProvider.ts+++ b/apps/server/src/routers/lambda/agentBotProvider.ts@@ -23,6 +23,11 @@ import {mergeBotSettingsForPersist,} from '@/server/services/bot/agentBotProviderSettings';import { getBotMessageRouter } from '@/server/services/bot/BotMessageRouter';+import {+ containsMaskedCredential,+ maskCredentials,+ resolveMaskedCredentials,+} from '@/server/services/bot/credentialMasking';import {type BotProviderFieldValues,collectFieldFormatViolations,@@ -188,6 +193,15 @@ export const agentBotProviderRouter = router({}),).mutation(async ({ input, ctx }) => {+ // A new binding has no stored secret for a mask to stand in for, so this+ // can only be a form that submitted what it read back.+ if (containsMaskedCredential(input.credentials)) {+ throw new TRPCError({+ code: 'BAD_REQUEST',+ message: 'Enter the real credential value โ the masked placeholder cannot be saved.',+ });+ }+await assertBotFeatureAccess({action: 'manage',applicationId: input.applicationId,@@ -286,6 +300,10 @@ export const agentBotProviderRouter = router({return providers.map((p, i) => ({...p,+ // The detail surface needs to show which credentials are configured,+ // never what they are. `update` resolves the mask back to the stored+ // secret, so an edit form can round-trip this safely.+ credentials: maskCredentials(p.platform, p.credentials),runtimeStatus: statuses[i].status,// Show the strategy the runtime will actually use. A channel created// before `burst` existed still stores `queue`, which its platform no@@ -298,6 +316,35 @@ export const agentBotProviderRouter = router({}));}),+ /**+ * The one read that returns credentials in the clear, for taking a channel+ * somewhere else.+ *+ * Everything else masks, because an ambient read handing out secrets to+ * anyone who can see the channel is what made a workspace's tokens+ * collectable. Export is not ambient: it is a deliberate act, it sits behind+ * the write gate so viewers cannot reach it, and each row still has to pass+ * the creator / workspace-owner check. The file it produces holds real+ * secrets โ the caller is told so.+ */+ exportByAgentId: agentBotProviderProcedureWrite+ .input(z.object({ agentId: z.string() }))+ .query(async ({ input, ctx }) => {+ const providers = await ctx.agentBotProviderModel.findByAgentId(input.agentId);++ for (const provider of providers) {+ assertWorkspaceRowManageable(ctx, provider.userId, 'bot provider');+ }++ return providers.map((p) => ({+ applicationId: p.applicationId,+ credentials: p.credentials,+ enabled: p.enabled,+ platform: p.platform,+ settings: p.settings,+ }));+ }),+getRuntimeStatus: authedProcedure.input(z.object({ applicationId: z.string(), platform: z.string() })).query(async ({ input }) => {@@ -335,8 +382,11 @@ export const agentBotProviderRouter = router({providers.map((p) => getBotRuntimeStatus(p.platform, p.applicationId)),);- return providers.map((p, i) => ({+ return providers.map(({ credentials: _credentials, ...p }, i) => ({...p,+ // A list is an inventory, not a place to hand out secrets โ not even+ // the caller's own. Read one channel through `getByAgentId` to see+ // which credentials are set.runtimeStatus: statuses[i].status,// Show the strategy the runtime will actually use. A channel created// before `burst` existed still stores `queue`, which its platform no@@ -536,6 +586,15 @@ export const agentBotProviderRouter = router({// Load existing record to get platform + applicationId for cache invalidationconst existing = await ctx.agentBotProviderModel.findById(id);if (existing) assertWorkspaceRowManageable(ctx, existing.userId, 'bot provider');+ // The detail surface hands out masks, so an untouched field comes back as+ // one. Resolve each mask to the secret it stood for before anything else+ // looks at the value: the model replaces the credential blob wholesale,+ // so dropping the masked keys would delete those secrets instead, and the+ // format check below would reject the mask outright.+ if (value.credentials) {+ value.credentials = resolveMaskedCredentials(value.credentials, existing?.credentials);+ }+const targetPlatform = value.platform ?? existing?.platform;const targetApplicationId = value.applicationId ?? existing?.applicationId;const isDisableOnly =diff --git a/apps/server/src/services/bot/__tests__/credentialMasking.test.ts b/apps/server/src/services/bot/__tests__/credentialMasking.test.tsnew file mode 100644index 00000000000..dfefbff1de4--- /dev/null+++ b/apps/server/src/services/bot/__tests__/credentialMasking.test.ts@@ -0,0 +1,116 @@+// @vitest-environment node+import { describe, expect, it } from 'vitest';++import {+ containsMaskedCredential,+ CREDENTIAL_MASK,+ maskCredentials,+ resolveMaskedCredentials,+} from '../credentialMasking';++describe('maskCredentials', () => {+ it('masks a secret but keeps the identifier beside it', () => {+ // Discord declares publicKey as `string` and botToken as `password`, which+ // is the distinction the mask reads.+ const masked = maskCredentials('discord', { botToken: 'real-token', publicKey: 'abc123' });++ expect(masked).toEqual({ botToken: CREDENTIAL_MASK, publicKey: 'abc123' });+ });++ it('masks every feishu secret', () => {+ const masked = maskCredentials('feishu', {+ appSecret: 's',+ encryptKey: 'e',+ verificationToken: 'v',+ });++ expect(Object.values(masked)).toEqual([CREDENTIAL_MASK, CREDENTIAL_MASK, CREDENTIAL_MASK]);+ });++ it('keeps the identifiers a QR-provisioned platform declares, and masks its token', () => {+ // WeChat has no credentials in its form schema, so the split comes from+ // `publicCredentialKeys` on the platform definition instead.+ const masked = maskCredentials('wechat', {+ botId: 'bot-1',+ botToken: 'real-token',+ userId: 'user-1',+ });++ expect(masked).toEqual({ botId: 'bot-1', botToken: CREDENTIAL_MASK, userId: 'user-1' });+ });++ it('leaves the iMessage bridge credentials readable', () => {+ // The desktop bridge holds `webhookSecret` as a shared secret and cannot+ // ask for it back; masking it would make the two sides disagree.+ const masked = maskCredentials('imessage', {+ desktopDeviceId: 'dev-1',+ webhookSecret: 'shared-secret',+ });++ expect(masked).toEqual({ desktopDeviceId: 'dev-1', webhookSecret: 'shared-secret' });+ });++ it('treats an unclassified key as a secret', () => {+ // Fail-closed: a platform that forgets to declare a field leaks nothing.+ expect(maskCredentials('discord', { somethingNew: 'value' })).toEqual({+ somethingNew: CREDENTIAL_MASK,+ });+ });++ it('leaves an empty value empty so "not configured" stays readable', () => {+ expect(maskCredentials('discord', { botToken: '' })).toEqual({ botToken: '' });+ });++ it('returns an empty object for a row with no credentials', () => {+ expect(maskCredentials('discord', null)).toEqual({});+ });+});++describe('resolveMaskedCredentials', () => {+ const stored = { botToken: 'real-token', publicKey: 'abc123' };++ it('restores the stored secret when the form hands back the mask untouched', () => {+ // The model replaces the blob wholesale, so this is what stops an untouched+ // save from either persisting the mask or deleting the secret.+ expect(resolveMaskedCredentials({ botToken: CREDENTIAL_MASK, publicKey: 'abc123' }, stored)) //+ .toEqual(stored);+ });++ it('takes a real edit over the stored value', () => {+ expect(resolveMaskedCredentials({ botToken: 'rotated', publicKey: 'abc123' }, stored)).toEqual({+ botToken: 'rotated',+ publicKey: 'abc123',+ });+ });++ it('restores the secret when the placeholder came back padded', () => {+ // The form accepts a padded placeholder as unchanged, so treating it as a+ // new secret here would persist dots over a live credential โ the damage+ // lands hardest on platforms whose fields carry no format pattern.+ expect(resolveMaskedCredentials({ botToken: ` ${CREDENTIAL_MASK} ` }, stored)).toEqual({+ botToken: 'real-token',+ });+ });++ it('drops a mask that stands for nothing', () => {+ expect(resolveMaskedCredentials({ botToken: CREDENTIAL_MASK }, {})).toEqual({});+ });++ it('does not resurrect a key the caller removed', () => {+ expect(resolveMaskedCredentials({ publicKey: 'abc123' }, stored)).toEqual({+ publicKey: 'abc123',+ });+ });+});++describe('containsMaskedCredential', () => {+ it.each([+ [{ botToken: CREDENTIAL_MASK }, true],+ [{ botToken: ` ${CREDENTIAL_MASK} ` }, true],+ [{ botToken: 'real' }, false],+ [{}, false],+ [undefined, false],+ ])('%o โ %s', (credentials, expected) => {+ expect(containsMaskedCredential(credentials as Record<string, string>)).toBe(expected);+ });+});diff --git a/apps/server/src/services/bot/credentialMasking.ts b/apps/server/src/services/bot/credentialMasking.tsnew file mode 100644index 00000000000..ebe4f84f62f--- /dev/null+++ b/apps/server/src/services/bot/credentialMasking.ts@@ -0,0 +1,91 @@+import { BOT_CREDENTIAL_MASK, isMaskedBotCredential } from '@lobechat/const';++import { platformRegistry } from './platforms';++/** Re-exported so server code has one import for the whole masking concern. */+export const CREDENTIAL_MASK = BOT_CREDENTIAL_MASK;++/**+ * Credential keys a platform publishes as identifiers rather than secrets.+ *+ * Derived from the form schema, where `type: 'password'` already marks what a+ * UI must not render in the clear โ Discord's `publicKey` is a public key,+ * its `botToken` is not. Platforms whose credentials never come from a form+ * (WeChat fills them from the QR handshake) declare the identifiers through+ * `publicCredentialKeys` instead, since they have no schema to read.+ *+ * Anything not named here is treated as secret. Fail-closed is the point: a new+ * platform that forgets to classify a field leaks nothing.+ */+const publicCredentialKeys = (platform: string): Set<string> => {+ const entry = platformRegistry.getPlatform(platform);+ const declared = entry?.schema?.find((field) => field.key === 'credentials');++ const fromSchema = (declared?.properties ?? [])+ .filter((field) => field.type !== 'password')+ .map((field) => field.key);++ return new Set([...fromSchema, ...(entry?.publicCredentialKeys ?? [])]);+};++/**+ * Replace every secret value with {@link CREDENTIAL_MASK}, keeping the keys.+ *+ * The shape has to survive: a reader still needs to see which credentials are+ * configured and which are blank, and that is exactly what an empty value+ * already communicates โ so empties are passed through untouched rather than+ * masked into looking set.+ */+export const maskCredentials = (+ platform: string,+ credentials: Record<string, string> | null | undefined,+): Record<string, string> => {+ if (!credentials) return {};++ const isPublic = publicCredentialKeys(platform);++ return Object.fromEntries(+ Object.entries(credentials).map(([key, value]) => {+ if (isPublic.has(key)) return [key, value];+ if (!value) return [key, value];+ return [key, CREDENTIAL_MASK];+ }),+ );+};++/**+ * Rebuild the credential blob a masked edit form sends back.+ *+ * The model replaces credentials wholesale, so a form that read masks and+ * submitted them unchanged would otherwise persist the mask as the secret, and+ * merely dropping the masked keys would delete the secrets instead. Each masked+ * entry therefore resolves to the stored value it was standing in for; a key+ * with no stored value behind it is dropped, because a mask is not a secret.+ */+export const resolveMaskedCredentials = (+ submitted: Record<string, string>,+ stored: Record<string, string> | null | undefined,+): Record<string, string> => {+ const result: Record<string, string> = {};++ for (const [key, value] of Object.entries(submitted)) {+ // Recognised through the shared predicate, which ignores surrounding+ // whitespace. An exact comparison here would disagree with the form, which+ // accepts a padded placeholder as unchanged โ and the half-millimetre+ // between those two readings is a real secret being overwritten by dots.+ if (!isMaskedBotCredential(value)) {+ result[key] = value;+ continue;+ }++ const previous = stored?.[key];+ if (previous !== undefined) result[key] = previous;+ }++ return result;+};++/** Whether the caller handed us a mask where a real secret was required. */+export const containsMaskedCredential = (+ credentials: Record<string, string> | null | undefined,+): boolean => Object.values(credentials ?? {}).some((value) => isMaskedBotCredential(value));diff --git a/apps/server/src/services/bot/platforms/imessage/definition.ts b/apps/server/src/services/bot/platforms/imessage/definition.tsindex 46992f5e3e6..2f95908a98f 100644--- a/apps/server/src/services/bot/platforms/imessage/definition.ts+++ b/apps/server/src/services/bot/platforms/imessage/definition.ts@@ -14,6 +14,12 @@ export const imessage: PlatformDefinition = {portalUrl: 'https://bluebubbles.app/',setupGuideUrl: channelDocUrl('imessage'),},+ // Both of these are written and read by the user's own desktop bridge, which+ // holds `webhookSecret` as a shared secret with the cloud side and has no way+ // to ask for it back. Masking it would make the bridge persist the+ // placeholder and stop matching the server, so iMessage opts out and its+ // credentials stay visible to whoever can already read the channel.+ publicCredentialKeys: ['desktopDeviceId', 'webhookSecret'],schema,showWebhookUrl: false,supportsMarkdown: false,diff --git a/apps/server/src/services/bot/platforms/types.ts b/apps/server/src/services/bot/platforms/types.tsindex 26bc8345b37..75ac8b8a1e6 100644--- a/apps/server/src/services/bot/platforms/types.ts+++ b/apps/server/src/services/bot/platforms/types.ts@@ -560,6 +560,15 @@ export interface PlatformDefinition {/** The name of the platform. */name: string;+ /**+ * Credential keys that are identifiers rather than secrets, for platforms+ * whose credentials never come from the form schema and so have no+ * `type: 'password'` marking to read. WeChat's QR handshake writes `botId`+ * and `userId` alongside the token; those two are safe to show, the token is+ * not. Everything unlisted is treated as secret.+ */+ publicCredentialKeys?: string[];+/** Field schema โ top-level objects `credentials` and `settings` map to DB columns. */schema: FieldSchema[];diff --git a/apps/server/src/services/bot/platforms/wechat/definition.ts b/apps/server/src/services/bot/platforms/wechat/definition.tsindex 1e8f8571804..d47a7143691 100644--- a/apps/server/src/services/bot/platforms/wechat/definition.ts+++ b/apps/server/src/services/bot/platforms/wechat/definition.ts@@ -13,6 +13,11 @@ export const wechat: PlatformDefinition = {documentation: {setupGuideUrl: channelDocUrl('wechat'),},+ // The QR handshake writes botId / userId / botToken together, and with no+ // credentials in `schema` there is no `type: 'password'` marking to separate+ // them. Name the two identifiers so the connected-account panel keeps showing+ // them; the token stays masked.+ publicCredentialKeys: ['botId', 'userId'],schema,supportsMessageEdit: false,unsupportedMessageApis: PLATFORM_UNSUPPORTED_MESSAGE_APIS.wechat,diff --git a/locales/en-US/agent.json b/locales/en-US/agent.jsonindex f373d06c95e..3cf53c3c094 100644--- a/locales/en-US/agent.json+++ b/locales/en-US/agent.json@@ -90,6 +90,7 @@"channel.endpointUrl": "Webhook URL","channel.endpointUrlHint": "Please copy this URL and paste it into the <bold>{{fieldName}}</bold> field in the {{name}} Developer Portal.","channel.exportConfig": "Export Configuration",+ "channel.exportContainsCredentials": "This file contains bot credentials in plain text โ store it somewhere safe.","channel.feishu.description": "Connect this agent to Feishu for private and group chats.","channel.feishu.fetchOwnerId": "Fetch from app info","channel.feishu.fetchOwnerIdAutoSuccess": "Filled in the app ownerโs Open ID โ check it is you, then save",diff --git a/locales/zh-CN/agent.json b/locales/zh-CN/agent.jsonindex 69ceba3ccaa..a1896267116 100644--- a/locales/zh-CN/agent.json+++ b/locales/zh-CN/agent.json@@ -90,6 +90,7 @@"channel.endpointUrl": "Webhook URL","channel.endpointUrlHint": "่ฏทๅคๅถๆญค URL ๅนถ็ฒ่ดดๅฐ {{name}} ๅผๅ่ ้จๆท็ <bold>{{fieldName}}</bold> ๅญๆฎตไธญใ","channel.exportConfig": "ๅฏผๅบๅนณๅฐ้ ็ฝฎ",+ "channel.exportContainsCredentials": "่ฟไธชๆไปถ้ๆฏๆๆ็ๆบๅจไบบๅญ่ฏ๏ผ่ฏทๅฆฅๅไฟ็ฎกใ","channel.feishu.description": "ๅฐๅฉๆ่ฟๆฅๅฐ้ฃไนฆ๏ผๆฏๆ็ง่ๅ็พค่ใ","channel.feishu.fetchOwnerId": "ไปๅบ็จไฟกๆฏ่ทๅ","channel.feishu.fetchOwnerIdAutoSuccess": "ๅทฒ่ชๅจๅกซๅ ฅๅบ็จๆๆ่ ็ Open ID๏ผ็กฎ่ฎคๆฏไฝ ๆฌไบบๅไฟๅญ",diff --git a/packages/const/src/bot.test.ts b/packages/const/src/bot.test.tsnew file mode 100644index 00000000000..32fe2f98a43--- /dev/null+++ b/packages/const/src/bot.test.ts@@ -0,0 +1,16 @@+import { describe, expect, it } from 'vitest';++import { BOT_CREDENTIAL_MASK, isMaskedBotCredential } from './bot';++describe('isMaskedBotCredential', () => {+ it.each([+ [BOT_CREDENTIAL_MASK, true],+ [` ${BOT_CREDENTIAL_MASK} `, true],+ ['a-real-secret', false],+ ['', false],+ [undefined, false],+ [null, false],+ ])('%o โ %s', (value, expected) => {+ expect(isMaskedBotCredential(value as string)).toBe(expected);+ });+});diff --git a/packages/const/src/bot.ts b/packages/const/src/bot.tsindex 76aa2ab8e87..4e50ae98593 100644--- a/packages/const/src/bot.ts+++ b/packages/const/src/bot.ts@@ -90,3 +90,28 @@ export const DEFAULT_OVERSIZE_IMAGE_STRATEGY: MessengerOversizeImageStrategy = '* compress, or the consequence it spells out is simply untrue.*/export const MESSENGER_MAX_COMPRESSION_SOURCE_BYTES = 100 * MB;++/**+ * Stand-in the server returns instead of a bot credential it will not disclose.+ *+ * Shared with the client because a form that reads a credential back cannot+ * tell a secret from a placeholder by looking: helper actions that spend the+ * value (LINE's bot-info fetch, Feishu's owner lookup) have to recognise it as+ * "not available" rather than send it upstream and fail authentication.+ *+ * One fixed sentinel rather than a partial reveal: surviving characters are+ * still entropy, and an exact value is the only thing the write path can+ * reliably match on the way back in.+ */+export const BOT_CREDENTIAL_MASK = 'โขโขโขโขโขโขโขโข';++/**+ * Whether a form field holds the placeholder rather than a usable credential.+ *+ * Anything that spends a credential โ a helper that calls the platform API, a+ * bridge that persists it locally โ must ask this before using the value, or it+ * sends the placeholder upstream and reads the resulting auth failure as a bad+ * secret.+ */+export const isMaskedBotCredential = (value: string | null | undefined): boolean =>+ value?.trim() === BOT_CREDENTIAL_MASK;diff --git a/packages/locales/src/default/agent.ts b/packages/locales/src/default/agent.tsindex 26756dde88b..4689d3fcd27 100644--- a/packages/locales/src/default/agent.ts+++ b/packages/locales/src/default/agent.ts@@ -86,6 +86,8 @@ export default {'channel.messengerPromo.dismiss': 'Dismiss','channel.messengerPromo.title': 'Skip the setup','channel.exportConfig': 'Export Configuration',+ 'channel.exportContainsCredentials':+ 'This file contains bot credentials in plain text โ store it somewhere safe.','channel.importConfig': 'Import Configuration','channel.importSuccess': 'Configuration imported successfully','channel.importFailed': 'Failed to import configuration',diff --git a/src/features/AgentSetting/AgentChannel/feishu/UserIdExtras.tsx b/src/features/AgentSetting/AgentChannel/feishu/UserIdExtras.tsxindex 5fe55067961..814372dde73 100644--- a/src/features/AgentSetting/AgentChannel/feishu/UserIdExtras.tsx+++ b/src/features/AgentSetting/AgentChannel/feishu/UserIdExtras.tsx@@ -1,5 +1,6 @@'use client';+import { isMaskedBotCredential } from '@lobechat/const';import { Button, toast } from '@lobehub/ui/base-ui';import { Form as AntdForm } from 'antd';import { Download } from 'lucide-react';@@ -51,7 +52,11 @@ export const FeishuUserIdExtras = ({const feishuFetchOwnerId = useAgentStore((s) => s.feishuFetchOwnerId);const appId = applicationId?.trim();- const secret = appSecret?.trim();+ const rawSecret = appSecret?.trim();+ // A masked secret is the server declining to hand the value back, not a+ // secret โ sending it to Feishu only earns an auth failure, so treat it the+ // same as an empty field and leave the lookup unavailable until it is typed.+ const secret = isMaskedBotCredential(rawSecret) ? undefined : rawSecret;useEffect(() => {setLoading(false);return () => {diff --git a/src/routes/(main)/agent/channel/Header.tsx b/src/routes/(main)/agent/channel/Header.tsxindex 2d7a4a8ba35..4b61f633927 100644--- a/src/routes/(main)/agent/channel/Header.tsx+++ b/src/routes/(main)/agent/channel/Header.tsx@@ -25,6 +25,7 @@ import { useAgentStore } from '@/store/agent';import type { BotProviderItem } from '@/store/agent/slices/bot/action';import { BOT_RUNTIME_STATUSES, type BotRuntimeStatus } from '../../../../types/botRuntimeStatus';+import { isImportableChannel, planChannelImport } from './importPlan';interface HeaderProps {agentId: string;@@ -55,12 +56,14 @@ const Header = memo<HeaderProps>(connectBot,createBotProvider,deleteAllBotProviders,+ exportBotProviders,refreshBotRuntimeStatus,updateBotProvider,] = useAgentStore((s) => [s.connectBot,s.createBotProvider,s.deleteAllBotProviders,+ s.exportBotProviders,s.refreshBotRuntimeStatus,s.updateBotProvider,]);@@ -77,11 +80,19 @@ const Header = memo<HeaderProps>(if (!currentConfig || pendingEnabled === currentConfig.enabled) setPendingEnabled(undefined);}, [currentConfig, pendingEnabled]);- const handleExport = useCallback(() => {+ const handleExport = useCallback(async () => {if (!providers?.length) return;- const exportData = providers.map(({ id: _, ...rest }) => rest);- exportJSONFile(exportData, `lobehub-channels-${agentId}.json`);- }, [agentId, providers]);+ try {+ // The cached providers carry masked credentials, so the file has to be+ // built from a fresh authorized read or it would export placeholders.+ const exportData = await exportBotProviders(agentId);+ exportJSONFile(exportData, `lobehub-channels-${agentId}.json`);+ // The file holds real tokens โ say so rather than let it look inert.+ toast.warning(t('channel.exportContainsCredentials'));+ } catch (error) {+ toast.error(error instanceof Error ? error.message : String(error));+ }+ }, [agentId, exportBotProviders, providers, t]);const handleImport = useCallback(() => {if (disabled) return;@@ -98,27 +109,25 @@ const Header = memo<HeaderProps>(try {const data = JSON.parse(await file.text());- if (- !Array.isArray(data) ||- data.some((item) => !item.platform || !item.applicationId || !item.credentials)- ) {+ if (!Array.isArray(data) || !data.every(isImportableChannel)) {toast.error(t('channel.importInvalidFormat'));return;}- for (const item of data) {+ for (const step of planChannelImport(data)) {await createBotProvider({agentId,- applicationId: item.applicationId,- credentials: item.credentials,- platform: item.platform,- settings: item.settings ?? undefined,+ applicationId: step.applicationId,+ credentials: step.credentials,+ enabled: step.enabled,+ platform: step.platform,+ settings: step.settings,});- if (item.enabled) {+ if (step.connect) {await connectBot({agentId,- applicationId: item.applicationId,- platform: item.platform,+ applicationId: step.applicationId,+ platform: step.platform,});}}diff --git a/src/routes/(main)/agent/channel/detail/Body.tsx b/src/routes/(main)/agent/channel/detail/Body.tsxindex 8b447e627eb..9bc7d663c4e 100644--- a/src/routes/(main)/agent/channel/detail/Body.tsx+++ b/src/routes/(main)/agent/channel/detail/Body.tsx@@ -1,5 +1,6 @@'use client';+import { isMaskedBotCredential } from '@lobechat/const';import { Block, Flexbox, Form, FormGroup, FormItem, Icon } from '@lobehub/ui';import type { SelectOption } from '@lobehub/ui/base-ui';import { Button, Select, Switch, Tag, Text } from '@lobehub/ui/base-ui';@@ -121,19 +122,28 @@ const styles = createStaticStyles(({ css, cssVar }) => ({// --------------- Validation rules builder ----------------function buildRules(field: FieldSchema, t: (key: string) => string) {+export function buildRules(field: FieldSchema, t: (key: string) => string) {const rules: any[] = [];if (field.required) {rules.push({ message: t(field.label), required: true });}- // Format constraint declared by the platform schema. antd's validator skips- // `pattern` on empty values, so an untouched optional field stays valid.+ // Format constraint declared by the platform schema. Empty stays valid, so an+ // untouched optional field does not trip it, and so does the placeholder the+ // server returns in place of a stored secret โ the save path swaps that back+ // for the real value, and holding it to the platform's format here would make+ // every unrelated edit demand the secret be retyped.if (field.pattern) {+ const pattern = new RegExp(field.pattern);+ const message = field.patternMessage ? t(field.patternMessage) : t(field.label);+rules.push({- message: field.patternMessage ? t(field.patternMessage) : t(field.label),- pattern: new RegExp(field.pattern),+ validator: (_: unknown, value: unknown) => {+ if (typeof value !== 'string' || !value) return Promise.resolve();+ if (isMaskedBotCredential(value)) return Promise.resolve();+ return pattern.test(value) ? Promise.resolve() : Promise.reject(new Error(message));+ },});}diff --git a/src/routes/(main)/agent/channel/detail/buildRules.test.ts b/src/routes/(main)/agent/channel/detail/buildRules.test.tsnew file mode 100644index 00000000000..0c77ff03db4--- /dev/null+++ b/src/routes/(main)/agent/channel/detail/buildRules.test.ts@@ -0,0 +1,44 @@+import { BOT_CREDENTIAL_MASK } from '@lobechat/const';+import { describe, expect, it } from 'vitest';++import { buildRules } from './Body';++/** Discord's real bot-token pattern, the one a masked value has to survive. */+const tokenField = {+ key: 'botToken',+ label: 'botToken',+ pattern: '^[\\w-]{20,}\\.[\\w-]{5,}\\.[\\w-]{20,}$',+ type: 'password' as const,+};++type FormRule = { validator?: (rule: unknown, value: unknown) => Promise<void> };++const validate = (value: unknown) => {+ const rules = buildRules(tokenField, (k: string) => k) as FormRule[];+ const validator = rules.find((rule) => rule.validator)?.validator;+ if (!validator) throw new Error('buildRules stopped emitting a validator for a patterned field');++ return validator(undefined, value);+};++describe('credential format rule', () => {+ it('accepts the placeholder a stored secret is read back as', async () => {+ // Otherwise saving any unrelated edit on an existing channel would demand+ // the secret be retyped, because the form submits what the server gave it.+ await expect(validate(BOT_CREDENTIAL_MASK)).resolves.toBeUndefined();+ });++ it('still accepts a real token', async () => {+ await expect(+ validate('MTIzNDU2Nzg5MDEyMzQ1Njc4.GhIjKl.SUPERSECRETTOKENVALUE123'),+ ).resolves.toBeUndefined();+ });++ it('still rejects a malformed token', async () => {+ await expect(validate('nope')).rejects.toThrow();+ });++ it('leaves an empty value to the required rule', async () => {+ await expect(validate('')).resolves.toBeUndefined();+ });+});diff --git a/src/routes/(main)/agent/channel/importPlan.test.ts b/src/routes/(main)/agent/channel/importPlan.test.tsnew file mode 100644index 00000000000..99dbf75818b--- /dev/null+++ b/src/routes/(main)/agent/channel/importPlan.test.ts@@ -0,0 +1,56 @@+import { describe, expect, it } from 'vitest';++import { isImportableChannel, planChannelImport } from './importPlan';++describe('planChannelImport', () => {+ it('lands an entry that carries credentials as the file asked', () => {+ const [step] = planChannelImport([+ {+ applicationId: 'app-1',+ credentials: { botToken: 't' },+ enabled: true,+ platform: 'discord',+ },+ ]);++ expect(step.enabled).toBeUndefined();+ expect(step.connect).toBe(true);+ });++ it('lands a credential-less entry switched off, and does not connect it', () => {+ // It cannot work without a secret, so it must not look like a live channel.+ const [step] = planChannelImport([+ { applicationId: 'app-1', enabled: true, platform: 'discord' },+ ]);++ expect(step.enabled).toBe(false);+ expect(step.connect).toBe(false);+ });++ it('treats an empty credentials object the same as none', () => {+ const [step] = planChannelImport([+ { applicationId: 'app-1', credentials: {}, enabled: true, platform: 'discord' },+ ]);++ expect(step.enabled).toBe(false);+ });++ it('leaves a disabled entry disabled even with credentials', () => {+ const [step] = planChannelImport([+ { applicationId: 'app-1', credentials: { botToken: 't' }, platform: 'discord' },+ ]);++ expect(step.connect).toBe(false);+ });+});++describe('isImportableChannel', () => {+ it.each([+ [{ applicationId: 'a', platform: 'discord' }, true],+ [{ applicationId: 'a' }, false],+ [{ platform: 'discord' }, false],+ [{}, false],+ ])('%o โ %s', (item, expected) => {+ expect(isImportableChannel(item)).toBe(expected);+ });+});diff --git a/src/routes/(main)/agent/channel/importPlan.ts b/src/routes/(main)/agent/channel/importPlan.tsnew file mode 100644index 00000000000..b44badd30a3--- /dev/null+++ b/src/routes/(main)/agent/channel/importPlan.ts@@ -0,0 +1,46 @@+/** One entry of a channel export file, as it arrives from disk. */+export interface ChannelImportItem {+ applicationId?: string;+ credentials?: Record<string, string>;+ enabled?: boolean;+ platform?: string;+ settings?: Record<string, unknown>;+}++export interface ChannelImportStep {+ applicationId: string;+ /** `undefined` leaves the server default; `false` lands an unusable draft. */+ connect: boolean;+ credentials: Record<string, string>;+ enabled: boolean | undefined;+ platform: string;+ settings: Record<string, unknown> | undefined;+}++/**+ * Decide what each entry of an import file should become.+ *+ * Exports carry credentials, but a hand-trimmed or legacy file may not, and+ * refusing the whole file over one such entry is worse than landing it. What a+ * credential-less entry must never become is a live channel: it cannot work, so+ * it arrives switched off, as a draft to finish rather than a broken+ * integration that looks connected.+ */+export const planChannelImport = (items: ChannelImportItem[]): ChannelImportStep[] =>+ items.map((item) => {+ const credentials = item.credentials ?? {};+ const hasCredentials = Object.keys(credentials).length > 0;++ return {+ applicationId: item.applicationId!,+ connect: Boolean(item.enabled) && hasCredentials,+ credentials,+ enabled: hasCredentials ? undefined : false,+ platform: item.platform!,+ settings: item.settings ?? undefined,+ };+ });++/** An entry without these cannot be created at all. */+export const isImportableChannel = (item: ChannelImportItem): boolean =>+ Boolean(item.platform && item.applicationId);diff --git a/src/routes/(main)/agent/channel/platform/line/CredentialExtras.tsx b/src/routes/(main)/agent/channel/platform/line/CredentialExtras.tsxindex 54bc83be143..ee9cf758117 100644--- a/src/routes/(main)/agent/channel/platform/line/CredentialExtras.tsx+++ b/src/routes/(main)/agent/channel/platform/line/CredentialExtras.tsx@@ -1,5 +1,6 @@'use client';+import { isMaskedBotCredential } from '@lobechat/const';import { Button, toast } from '@lobehub/ui/base-ui';import { Form as AntdForm } from 'antd';import { Download } from 'lucide-react';@@ -25,7 +26,9 @@ const CredentialExtras = memo<PlatformCredentialExtrasProps>(({ disabled }) => {if (disabled) return;const token = channelAccessToken?.trim();- if (!token) {+ // A masked token is the server telling us it will not hand the secret back,+ // not a token โ spending it here just fails authentication at LINE.+ if (!token || isMaskedBotCredential(token)) {toast.warning(t('channel.line.fetchBotInfoMissingToken'));return;}@@ -51,12 +54,14 @@ const CredentialExtras = memo<PlatformCredentialExtrasProps>(({ disabled }) => {return (<Button- disabled={disabled || !channelAccessToken?.trim()}icon={<Download size={14} />}loading={loading}size="small"style={{ alignSelf: 'flex-start', marginBlockStart: 4 }}type="default"+ disabled={+ disabled || !channelAccessToken?.trim() || isMaskedBotCredential(channelAccessToken)+ }onClick={handleFetch}>{t('channel.line.fetchBotInfo')}diff --git a/src/services/agentBotProvider.ts b/src/services/agentBotProvider.tsindex 5753cd433c1..4d7fb004d3b 100644--- a/src/services/agentBotProvider.ts+++ b/src/services/agentBotProvider.ts@@ -11,6 +11,15 @@ class AgentBotProviderService {return lambdaClient.agentBotProvider.getByAgentId.query({ agentId });};+ /**+ * Credentials in the clear, for writing an importable export file. Separate+ * from `getByAgentId` on purpose: that one masks, and the export is the only+ * place allowed to ask for the real values.+ */+ exportByAgentId = async (agentId: string) => {+ return lambdaClient.agentBotProvider.exportByAgentId.query({ agentId });+ };+getRuntimeStatus = async (params: {applicationId: string;platform: string;diff --git a/src/store/agent/slices/bot/action.ts b/src/store/agent/slices/bot/action.tsindex c7c025e107d..085233cb9b0 100644--- a/src/store/agent/slices/bot/action.ts+++ b/src/store/agent/slices/bot/action.ts@@ -36,6 +36,8 @@ export class BotSliceActionImpl {agentId: string;applicationId: string;credentials: Record<string, string>;+ /** Defaults to enabled server-side; pass false to land an unusable draft. */+ enabled?: boolean;platform: string;settings?: Record<string, unknown>;}) => {@@ -67,6 +69,15 @@ export class BotSliceActionImpl {return agentBotProviderService.feishuFetchOwnerId(params);};+ /**+ * Channel configs with their credentials in the clear, for an export file the+ * user can import elsewhere. The cached provider list is masked, so this has+ * to go back to the server rather than reuse it.+ */+ exportBotProviders = async (agentId: string) => {+ return agentBotProviderService.exportByAgentId(agentId);+ };+deleteAllBotProviders = async (agentId: string) => {const providers = await agentBotProviderService.getByAgentId(agentId);await Promise.all(providers.map((p) => agentBotProviderService.delete(p.id)));