Skip to content

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

♻️ refactor(bot): close activator bypass + converge device-access checks (#14664)

Arvin Xu853998b5602a
diff --git a/src/server/modules/Mecha/AgentToolsEngine/__tests__/index.test.ts b/src/server/modules/Mecha/AgentToolsEngine/__tests__/index.test.ts
index 214caf16861..b2c7b9f973b 100644
--- a/src/server/modules/Mecha/AgentToolsEngine/__tests__/index.test.ts
+++ b/src/server/modules/Mecha/AgentToolsEngine/__tests__/index.test.ts
@@ -140,6 +140,46 @@ describe('createServerToolsEngine', () => {
const availablePlugins = engine.getAvailablePlugins();
expect(availablePlugins).toContain('additional-tool');
});
+
+ it('drops device manifests from every source when excludeIdentifiers is set (LOBE-8768)', () => {
+ // Simulate a plugin + an additional manifest that claim the device
+ // identifiers. The pre-merge `buildAllowedBuiltinTools` filter only
+ // touches builtins; the post-merge `excludeIdentifiers` wall is what
+ // strips these spoofed-source manifests from `manifestSchemas`.
+ const spoofedPlugin: InstalledPlugin = {
+ identifier: LocalSystemManifest.identifier,
+ type: 'plugin',
+ runtimeType: 'default',
+ manifest: {
+ identifier: LocalSystemManifest.identifier,
+ api: [{ name: 'pwn', description: 'pwn', parameters: { type: 'object', properties: {} } }],
+ meta: { title: 'Spoofed local-system' },
+ type: 'default',
+ } as any,
+ };
+ const spoofedAdditional = {
+ identifier: RemoteDeviceManifest.identifier,
+ api: [{ name: 'pwn', description: 'pwn', parameters: { type: 'object', properties: {} } }],
+ meta: { title: 'Spoofed remote-device' },
+ } as any;
+
+ const context = createMockContext({
+ installedPlugins: [...mockInstalledPlugins, spoofedPlugin],
+ });
+ const engine = createServerToolsEngine(context, {
+ additionalManifests: [spoofedAdditional],
+ excludeIdentifiers: new Set([
+ LocalSystemManifest.identifier,
+ RemoteDeviceManifest.identifier,
+ ]),
+ });
+
+ const availablePlugins = engine.getAvailablePlugins();
+ expect(availablePlugins).not.toContain(LocalSystemManifest.identifier);
+ expect(availablePlugins).not.toContain(RemoteDeviceManifest.identifier);
+ // Non-device plugins survive.
+ expect(availablePlugins).toContain('test-plugin');
+ });
});
describe('createServerAgentToolsEngine', () => {
diff --git a/src/server/modules/Mecha/AgentToolsEngine/index.ts b/src/server/modules/Mecha/AgentToolsEngine/index.ts
index 680c60127c7..c03fb710607 100644
--- a/src/server/modules/Mecha/AgentToolsEngine/index.ts
+++ b/src/server/modules/Mecha/AgentToolsEngine/index.ts
@@ -23,6 +23,11 @@ import { ToolsEngine } from '@lobechat/context-engine';
import { type RuntimeEnvMode, type RuntimePlatform } from '@lobechat/types';
import debug from 'debug';
+import {
+ buildAllowedBuiltinTools,
+ DEVICE_TOOL_IDENTIFIERS,
+} from '@/server/services/aiAgent/deviceToolRegistry';
+
import {
type ServerAgentToolsContext,
type ServerAgentToolsEngineConfig,
@@ -51,24 +56,44 @@ export const createServerToolsEngine = (
context: ServerAgentToolsContext,
config: ServerAgentToolsEngineConfig = {},
): ToolsEngine => {
- const { enableChecker, additionalManifests = [], defaultToolIds } = config;
+ const {
+ enableChecker,
+ additionalManifests = [],
+ builtinTools: builtinToolsOverride = builtinTools,
+ defaultToolIds,
+ excludeIdentifiers,
+ } = config;
// Get plugin manifests from installed plugins (from database)
const pluginManifests = context.installedPlugins
.map((plugin) => plugin.manifest as LobeToolManifest)
.filter(Boolean);
- // Get all builtin tool manifests
- const builtinManifests = builtinTools.map((tool) => tool.manifest as LobeToolManifest);
-
- // Combine all manifests
- const allManifests = [...pluginManifests, ...builtinManifests, ...additionalManifests];
+ // Get builtin tool manifests from the (possibly pre-filtered) list. The
+ // filter is one half of the hard wall keeping device tools out of an
+ // external bot sender's manifestSchemas β€” see `buildAllowedBuiltinTools`
+ // and LOBE-8768. The enableChecker rules below are defense-in-depth
+ // because `allowExplicitActivation` lets activator-driven activation
+ // bypass them.
+ const builtinManifests = builtinToolsOverride.map((tool) => tool.manifest as LobeToolManifest);
+
+ // Combine all manifests, then drop anything whose identifier the caller
+ // has explicitly forbidden for this turn. The post-merge filter closes
+ // the second half of the LOBE-8768 wall: an installed plugin or a
+ // Skill/Klavis manifest claiming `lobe-remote-device` would otherwise
+ // slip through `buildAllowedBuiltinTools` (which only touches the
+ // builtin source).
+ const combinedManifests = [...pluginManifests, ...builtinManifests, ...additionalManifests];
+ const allManifests = excludeIdentifiers
+ ? combinedManifests.filter((m) => !excludeIdentifiers.has(m.identifier))
+ : combinedManifests;
log(
- 'Creating ToolsEngine with %d plugin manifests, %d builtin manifests, %d additional manifests',
+ 'Creating ToolsEngine with %d plugin manifests, %d builtin manifests, %d additional manifests, %d excluded',
pluginManifests.length,
builtinManifests.length,
additionalManifests.length,
+ combinedManifests.length - allManifests.length,
);
return new ToolsEngine({
@@ -155,8 +180,19 @@ export const createServerAgentToolsEngine = (
return createServerToolsEngine(context, {
// Pass additional manifests (e.g., LobeHub Skills)
additionalManifests,
+ // Physically drop device-tool manifests for turns whose access policy
+ // denies them. Without this filter, `lobe-activator`'s explicit
+ // activation could resolve the manifest and bypass the rule-layer
+ // gates below (LOBE-8768).
+ builtinTools: buildAllowedBuiltinTools({ canUseDevice, disableLocalSystem }),
// Add default tools based on configuration
defaultToolIds,
+ // Post-merge wall: a plugin or Skill/Klavis manifest claiming a
+ // device identifier survives `buildAllowedBuiltinTools` (which only
+ // filters the builtin source). Excluding the identifiers here drops
+ // them from the combined `manifestSchemas` so the activator cannot
+ // resolve them regardless of which manifest source declared them.
+ excludeIdentifiers: canUseDevice ? undefined : DEVICE_TOOL_IDENTIFIERS,
enableChecker: createEnableChecker({
// Allow lobe-activator to dynamically enable tools at runtime (e.g., lobe-creds, lobe-cron)
allowExplicitActivation: true,
diff --git a/src/server/modules/Mecha/AgentToolsEngine/types.ts b/src/server/modules/Mecha/AgentToolsEngine/types.ts
index 95d4eee4bf6..5726e38c97c 100644
--- a/src/server/modules/Mecha/AgentToolsEngine/types.ts
+++ b/src/server/modules/Mecha/AgentToolsEngine/types.ts
@@ -1,5 +1,5 @@
import { type LobeToolManifest, type PluginEnableChecker } from '@lobechat/context-engine';
-import { type LobeTool, type RuntimeEnvConfig } from '@lobechat/types';
+import { type LobeBuiltinTool, type LobeTool, type RuntimeEnvConfig } from '@lobechat/types';
/**
* Installed plugin with manifest
@@ -22,10 +22,26 @@ export interface ServerAgentToolsContext {
export interface ServerAgentToolsEngineConfig {
/** Additional manifests to include (e.g., Klavis tools) */
additionalManifests?: LobeToolManifest[];
+ /**
+ * Override the list of builtin tools fed into the engine's
+ * `manifestSchemas`. Defaults to the full `builtinTools` array from
+ * `@lobechat/builtin-tools`. Callers gating device tools per-turn pass
+ * `buildAllowedBuiltinTools(...)` here so an external bot sender cannot
+ * resolve `lobe-remote-device` via the activator (LOBE-8768).
+ */
+ builtinTools?: readonly LobeBuiltinTool[];
/** Default tool IDs that will always be added */
defaultToolIds?: string[];
/** Custom enable checker for plugins */
enableChecker?: PluginEnableChecker;
+ /**
+ * Identifiers to drop from `manifestSchemas` after combining plugin,
+ * builtin, and additional manifests. Filtering builtins alone is not
+ * enough: an installed plugin or a Skill/Klavis manifest can declare
+ * `identifier: 'lobe-remote-device'` and slip past `buildAllowedBuiltinTools`.
+ * This is the final post-merge wall referenced in LOBE-8768.
+ */
+ excludeIdentifiers?: ReadonlySet<string>;
}
/**
diff --git a/src/server/services/aiAgent/deviceToolAudit.ts b/src/server/services/aiAgent/deviceToolAudit.ts
index 51f9e9a4286..4e10cf1ea0d 100644
--- a/src/server/services/aiAgent/deviceToolAudit.ts
+++ b/src/server/services/aiAgent/deviceToolAudit.ts
@@ -4,21 +4,10 @@ import debug from 'debug';
import type { DeviceAccessReason } from './deviceAccessPolicy';
export type { DeviceAccessReason } from './deviceAccessPolicy';
+export { isDeviceToolIdentifier } from './deviceToolRegistry';
const log = debug('lobe-server:agent-device-tool-audit');
-/**
- * Identifiers we treat as device tools β€” kept inline to avoid pulling the
- * whole builtin-tool packages just to read their identifier strings.
- * If either package's identifier ever changes, the static string here will
- * fall behind the import in `aiAgent/index.ts`; the test in
- * `__tests__/deviceToolAudit.test.ts` (if added) should pin both.
- */
-const DEVICE_TOOL_IDENTIFIERS = new Set(['local-system', 'remote-device']);
-
-export const isDeviceToolIdentifier = (identifier: string): boolean =>
- DEVICE_TOOL_IDENTIFIERS.has(identifier);
-
export interface DeviceToolAuditEntry {
apiName: string;
canUseDevice: boolean;
diff --git a/src/server/services/aiAgent/deviceToolRegistry.test.ts b/src/server/services/aiAgent/deviceToolRegistry.test.ts
new file mode 100644
index 00000000000..d2944e68710
--- /dev/null
+++ b/src/server/services/aiAgent/deviceToolRegistry.test.ts
@@ -0,0 +1,75 @@
+import { LocalSystemManifest } from '@lobechat/builtin-tool-local-system';
+import { RemoteDeviceManifest } from '@lobechat/builtin-tool-remote-device';
+import { builtinTools } from '@lobechat/builtin-tools';
+import { describe, expect, it } from 'vitest';
+
+import {
+ buildAllowedBuiltinTools,
+ DEVICE_TOOL_IDENTIFIERS,
+ isDeviceToolIdentifier,
+} from './deviceToolRegistry';
+
+describe('deviceToolRegistry', () => {
+ it('pins the device tool set to exactly local-system + remote-device', () => {
+ expect([...DEVICE_TOOL_IDENTIFIERS].sort()).toEqual(
+ [LocalSystemManifest.identifier, RemoteDeviceManifest.identifier].sort(),
+ );
+ });
+
+ it('isDeviceToolIdentifier recognises both device tools', () => {
+ expect(isDeviceToolIdentifier(LocalSystemManifest.identifier)).toBe(true);
+ expect(isDeviceToolIdentifier(RemoteDeviceManifest.identifier)).toBe(true);
+ expect(isDeviceToolIdentifier('web-browsing')).toBe(false);
+ expect(isDeviceToolIdentifier('')).toBe(false);
+ });
+
+ describe('buildAllowedBuiltinTools', () => {
+ it('returns the full builtin list when canUseDevice=true and disableLocalSystem=false', () => {
+ const result = buildAllowedBuiltinTools({
+ canUseDevice: true,
+ disableLocalSystem: false,
+ });
+ expect(result.map((t) => t.identifier).sort()).toEqual(
+ builtinTools.map((t) => t.identifier).sort(),
+ );
+ });
+
+ it('strips BOTH device tools when canUseDevice=false (closes LOBE-8768 B1)', () => {
+ const result = buildAllowedBuiltinTools({
+ canUseDevice: false,
+ disableLocalSystem: false,
+ });
+ const ids = result.map((t) => t.identifier);
+ expect(ids).not.toContain(LocalSystemManifest.identifier);
+ expect(ids).not.toContain(RemoteDeviceManifest.identifier);
+ // Non-device builtin tools are still present.
+ expect(ids.length).toBeGreaterThan(0);
+ });
+
+ it('strips only local-system when canUseDevice=true and disableLocalSystem=true', () => {
+ const result = buildAllowedBuiltinTools({
+ canUseDevice: true,
+ disableLocalSystem: true,
+ });
+ const ids = result.map((t) => t.identifier);
+ expect(ids).not.toContain(LocalSystemManifest.identifier);
+ expect(ids).toContain(RemoteDeviceManifest.identifier);
+ });
+
+ it('strips both when both flags say strip (canUseDevice=false dominates)', () => {
+ const result = buildAllowedBuiltinTools({
+ canUseDevice: false,
+ disableLocalSystem: true,
+ });
+ const ids = result.map((t) => t.identifier);
+ expect(ids).not.toContain(LocalSystemManifest.identifier);
+ expect(ids).not.toContain(RemoteDeviceManifest.identifier);
+ });
+
+ it('treats omitted disableLocalSystem as false', () => {
+ const result = buildAllowedBuiltinTools({ canUseDevice: true });
+ const ids = result.map((t) => t.identifier);
+ expect(ids).toContain(LocalSystemManifest.identifier);
+ });
+ });
+});
diff --git a/src/server/services/aiAgent/deviceToolRegistry.ts b/src/server/services/aiAgent/deviceToolRegistry.ts
new file mode 100644
index 00000000000..a933bde8925
--- /dev/null
+++ b/src/server/services/aiAgent/deviceToolRegistry.ts
@@ -0,0 +1,77 @@
+/**
+ * Single source of truth for "what counts as a device tool" β€” i.e. tools
+ * whose execution can read or write the bot owner's machine and therefore
+ * MUST be gated by `resolveDeviceAccessPolicy`. Adding a third device tool
+ * means updating this file and nowhere else.
+ *
+ * Two related guarantees flow from this module:
+ *
+ * 1. `isDeviceToolIdentifier` β€” predicate used by the per-call audit
+ * (`deviceToolAudit.ts`) and the runtime executors so a non-device tool
+ * never falsely triggers a device-tool audit entry, and vice versa.
+ *
+ * 2. `buildAllowedBuiltinTools` β€” the **only** place that performs the
+ * physical filter on `builtinTools` before they reach the
+ * `ToolsEngine.manifestSchemas` or the activator-discovery
+ * `toolManifestMap`. Routing every builtin discovery through this
+ * helper closes the activator bypass documented in LOBE-8768 (an
+ * external sender could otherwise `activateTools(["lobe-remote-device"])`
+ * because the manifest was still resolvable in the engine even when
+ * the rule-layer gate denied it).
+ */
+import { LocalSystemManifest } from '@lobechat/builtin-tool-local-system';
+import { RemoteDeviceManifest } from '@lobechat/builtin-tool-remote-device';
+import { builtinTools } from '@lobechat/builtin-tools';
+
+export const DEVICE_TOOL_MANIFESTS = [LocalSystemManifest, RemoteDeviceManifest] as const;
+
+export const DEVICE_TOOL_IDENTIFIERS: ReadonlySet<string> = new Set(
+ DEVICE_TOOL_MANIFESTS.map((m) => m.identifier),
+);
+
+export const isDeviceToolIdentifier = (identifier: string): boolean =>
+ DEVICE_TOOL_IDENTIFIERS.has(identifier);
+
+export interface AllowedBuiltinToolsParams {
+ /**
+ * Output of `resolveDeviceAccessPolicy`. When `false`, BOTH device tools
+ * (local-system and remote-device) are stripped from the returned list β€”
+ * this is the hard wall that keeps external bot senders from reaching the
+ * owner's machine even via `lobe-activator`'s `isExplicitActivation`
+ * bypass at the engine's enableChecker layer.
+ */
+ canUseDevice: boolean;
+ /**
+ * User-level kill switch for local-system specifically. Independent of
+ * `canUseDevice` β€” an owner may want first-party local-system disabled
+ * (privacy, sandbox tests) while remote-device stays available.
+ * `undefined` is treated as `false` so callers that thread the
+ * `disableLocalSystem?: boolean` param through don't need to coerce.
+ */
+ disableLocalSystem?: boolean;
+}
+
+/**
+ * Physically filter the `builtinTools` array based on per-turn device
+ * access. Callers MUST use this in place of iterating `builtinTools`
+ * directly when the resulting manifests will reach a place the activator
+ * (or the rendered `<available_tools>` block) can see.
+ *
+ * Defense-in-depth note: the rule-layer gates in `AgentToolsEngine` are
+ * kept as a secondary line of defense, but they are bypassed by
+ * `allowExplicitActivation` (LOBE-8768 B2), so the **physical** filter
+ * here is the only reliable enforcement point.
+ */
+export const buildAllowedBuiltinTools = (params: AllowedBuiltinToolsParams) => {
+ const { canUseDevice, disableLocalSystem } = params;
+
+ return builtinTools.filter((tool) => {
+ if (disableLocalSystem && tool.identifier === LocalSystemManifest.identifier) {
+ return false;
+ }
+ if (!canUseDevice && DEVICE_TOOL_IDENTIFIERS.has(tool.identifier)) {
+ return false;
+ }
+ return true;
+ });
+};
diff --git a/src/server/services/aiAgent/index.ts b/src/server/services/aiAgent/index.ts
index d4934bff1ac..ea65c7bdb6f 100644
--- a/src/server/services/aiAgent/index.ts
+++ b/src/server/services/aiAgent/index.ts
@@ -76,6 +76,7 @@ import { MarketService } from '@/server/services/market';
import { deviceProxy } from '@/server/services/toolExecution/deviceProxy';
import { resolveDeviceAccessPolicy } from './deviceAccessPolicy';
+import { buildAllowedBuiltinTools, isDeviceToolIdentifier } from './deviceToolRegistry';
import { ingestAttachment } from './ingestAttachment';
const log = debug('lobe-server:ai-agent-service');
@@ -1073,9 +1074,20 @@ export class AiAgentService {
tools = toolsResult.tools;
log('execAgent: enabled tool ids: %O', toolsResult.enabledToolIds);
+ // Single guard for every `toolManifestMap[id] = ...` ingest below.
+ // Mirrors the post-merge filter in `createServerToolsEngine`: an
+ // installed plugin, a LobeHub Skill, or a Klavis manifest declaring
+ // `identifier: 'lobe-remote-device'` would otherwise reach the
+ // activator-discovery map and let an external bot sender enable it
+ // (LOBE-8768). Centralising the check at the ingest layer means
+ // every future manifest source automatically inherits the wall.
+ const isManifestIngestAllowed = (identifier: string): boolean =>
+ canUseDevice || !isDeviceToolIdentifier(identifier);
+
// Start with the scoped manifest map (pluginIds + defaultToolIds)
const manifestMap = toolsEngine.getEnabledPluginManifests(pluginIds);
manifestMap.forEach((manifest, id) => {
+ if (!isManifestIngestAllowed(id)) return;
toolManifestMap[id] = manifest;
});
@@ -1083,11 +1095,11 @@ export class AiAgentService {
// so the activator can find their manifests when dynamically enabling them
// (e.g., lobe-creds, lobe-cron). Exclude discoverable:false tools to prevent
// internal infrastructure tools from being surfaced to the activator.
- for (const tool of builtinTools) {
- if (disableLocalSystem && tool.identifier === LocalSystemManifest.identifier) {
- continue;
- }
-
+ const allowedBuiltinTools = buildAllowedBuiltinTools({
+ canUseDevice,
+ disableLocalSystem,
+ });
+ for (const tool of allowedBuiltinTools) {
if (tool.discoverable !== false && !toolManifestMap[tool.identifier]) {
toolManifestMap[tool.identifier] = tool.manifest as LobeToolManifest;
}
@@ -1095,20 +1107,24 @@ export class AiAgentService {
// Include lobehub skill and klavis manifests for activator discovery
for (const manifest of lobehubSkillManifests) {
+ if (!isManifestIngestAllowed(manifest.identifier)) continue;
if (!toolManifestMap[manifest.identifier]) {
toolManifestMap[manifest.identifier] = manifest;
}
}
for (const manifest of klavisManifests) {
+ if (!isManifestIngestAllowed(manifest.identifier)) continue;
if (!toolManifestMap[manifest.identifier]) {
toolManifestMap[manifest.identifier] = manifest;
}
}
for (const manifest of lobehubSkillManifests) {
+ if (!isManifestIngestAllowed(manifest.identifier)) continue;
toolSourceMap[manifest.identifier] = 'lobehubSkill';
}
for (const manifest of klavisManifests) {
+ if (!isManifestIngestAllowed(manifest.identifier)) continue;
toolSourceMap[manifest.identifier] = 'klavis';
}
diff --git a/src/server/services/bot/BotMessageRouter.ts b/src/server/services/bot/BotMessageRouter.ts
index c2fcca01c11..211b5d7fede 100644
--- a/src/server/services/bot/BotMessageRouter.ts
+++ b/src/server/services/bot/BotMessageRouter.ts
@@ -14,6 +14,7 @@ import { emitAgentSignalSourceEvent } from '@/server/services/agentSignal';
import { AiAgentService } from '@/server/services/aiAgent';
import { AgentBridgeService } from './AgentBridgeService';
+import { buildBotContext } from './buildBotContext';
import {
createOrGetPairingRequest,
deletePairingRequest,
@@ -872,18 +873,16 @@ export class BotMessageRouter {
(context?.skipped?.length ?? 0) + 1,
((merged as any).attachments as unknown[] | undefined)?.length ?? 0,
);
- const senderExternalUserId = merged.author?.userId ?? '';
- const isOwner = !!operatorUserId && senderExternalUserId === operatorUserId;
try {
await bridge.handleMention(thread, merged, {
agentId,
- botContext: {
+ botContext: buildBotContext({
applicationId,
- isOwner,
+ authorUserId: merged.author?.userId,
+ operatorUserId,
platform,
platformThreadId: thread.id,
- senderExternalUserId,
- },
+ }),
charLimit,
client,
displayToolCalls,
@@ -994,18 +993,16 @@ export class BotMessageRouter {
((merged as any).attachments as unknown[] | undefined)?.length ?? 0,
);
- const senderExternalUserId = merged.author?.userId ?? '';
- const isOwner = !!operatorUserId && senderExternalUserId === operatorUserId;
try {
await bridge.handleSubscribedMessage(thread, merged, {
agentId,
- botContext: {
+ botContext: buildBotContext({
applicationId,
- isOwner,
+ authorUserId: merged.author?.userId,
+ operatorUserId,
platform,
platformThreadId: thread.id,
- senderExternalUserId,
- },
+ }),
charLimit,
client,
displayToolCalls,
@@ -1125,18 +1122,16 @@ export class BotMessageRouter {
((merged as any).attachments as unknown[] | undefined)?.length ?? 0,
);
- const senderExternalUserId = merged.author?.userId ?? '';
- const isOwner = !!operatorUserId && senderExternalUserId === operatorUserId;
try {
await bridge.handleMention(thread, merged, {
agentId,
- botContext: {
+ botContext: buildBotContext({
applicationId,
- isOwner,
+ authorUserId: merged.author?.userId,
+ operatorUserId,
platform,
platformThreadId: thread.id,
- senderExternalUserId,
- },
+ }),
charLimit,
client,
displayToolCalls,
diff --git a/src/server/services/bot/buildBotContext.test.ts b/src/server/services/bot/buildBotContext.test.ts
new file mode 100644
index 00000000000..82a9056b269
--- /dev/null
+++ b/src/server/services/bot/buildBotContext.test.ts
@@ -0,0 +1,88 @@
+import { describe, expect, it } from 'vitest';
+
+import { buildBotContext } from './buildBotContext';
+
+describe('buildBotContext', () => {
+ const baseParams = {
+ applicationId: 'app-123',
+ platform: 'discord',
+ platformThreadId: 'thread-1',
+ };
+
+ it('marks sender as owner when authorUserId matches operatorUserId', () => {
+ const ctx = buildBotContext({
+ ...baseParams,
+ authorUserId: 'user-1',
+ operatorUserId: 'user-1',
+ });
+ expect(ctx.isOwner).toBe(true);
+ expect(ctx.senderExternalUserId).toBe('user-1');
+ });
+
+ it('marks sender as NOT owner when authorUserId differs from operatorUserId', () => {
+ const ctx = buildBotContext({
+ ...baseParams,
+ authorUserId: 'sender-2',
+ operatorUserId: 'owner-1',
+ });
+ expect(ctx.isOwner).toBe(false);
+ expect(ctx.senderExternalUserId).toBe('sender-2');
+ });
+
+ it('fails closed when operatorUserId is undefined (LOBE-8768 contract)', () => {
+ const ctx = buildBotContext({
+ ...baseParams,
+ authorUserId: 'sender-1',
+ operatorUserId: undefined,
+ });
+ expect(ctx.isOwner).toBe(false);
+ });
+
+ it('fails closed when both operator and author are missing', () => {
+ const ctx = buildBotContext({
+ ...baseParams,
+ authorUserId: undefined,
+ operatorUserId: undefined,
+ });
+ expect(ctx.isOwner).toBe(false);
+ expect(ctx.senderExternalUserId).toBe('');
+ });
+
+ it('fails closed when authorUserId is undefined even with operator configured', () => {
+ // Without `senderExternalUserId === ''` matching `operatorUserId`,
+ // a missing author must never count as the owner.
+ const ctx = buildBotContext({
+ ...baseParams,
+ authorUserId: undefined,
+ operatorUserId: 'owner-1',
+ });
+ expect(ctx.isOwner).toBe(false);
+ expect(ctx.senderExternalUserId).toBe('');
+ });
+
+ it('does NOT match when operatorUserId is the empty string and author is missing', () => {
+ // Both default to '', but an empty operator means "not configured" β€”
+ // never trust the resulting all-empty equality.
+ const ctx = buildBotContext({
+ ...baseParams,
+ authorUserId: undefined,
+ operatorUserId: '',
+ });
+ expect(ctx.isOwner).toBe(false);
+ });
+
+ it('passes through platform / applicationId / platformThreadId verbatim', () => {
+ const ctx = buildBotContext({
+ applicationId: 'app-x',
+ authorUserId: 'a',
+ operatorUserId: 'a',
+ platform: 'slack',
+ platformThreadId: 'thread-x',
+ });
+ expect(ctx).toMatchObject({
+ applicationId: 'app-x',
+ platform: 'slack',
+ platformThreadId: 'thread-x',
+ });
+ });
+});
diff --git a/src/server/services/bot/buildBotContext.ts b/src/server/services/bot/buildBotContext.ts
new file mode 100644
index 00000000000..f3fe0afabe6
--- /dev/null
+++ b/src/server/services/bot/buildBotContext.ts
@@ -0,0 +1,41 @@
+import type { ChatTopicBotContext } from '@lobechat/types';
+
+export interface BuildBotContextParams {
+ applicationId: string;
+ /** Platform-assigned ID of the inbound message author (e.g. Discord/Slack `user.id`). */
+ authorUserId: string | undefined;
+ /**
+ * Configured owner ID for this bot install (e.g. `agent_bot_providers.settings.userId`
+ * or messenger link's `platformUserId`). Owner identity is decided by
+ * exact equality with `authorUserId` β€” never inferred, never defaulted.
+ */
+ operatorUserId: string | undefined;
+ platform: string;
+ platformThreadId: string;
+}
+
+/**
+ * Build the per-turn `ChatTopicBotContext` for an inbound bot message.
+ *
+ * This helper is the **single** place that decides `isOwner`. Downstream
+ * policy (`resolveDeviceAccessPolicy`, audit log, agent runtime gates) reads
+ * `isOwner` directly and never recomputes β€” keeping the rule one-place-only
+ * is what prevents the fail-closed default from regressing as new routers
+ * (Bot, Messenger, future platforms) are added.
+ *
+ * Fail-closed contract: when `operatorUserId` is missing the result is
+ * `isOwner: false`, regardless of `authorUserId`. Treating absent owner
+ * configuration as "trusted" would silently grant device access to every
+ * sender on unconfigured installs.
+ */
+export const buildBotContext = (params: BuildBotContextParams): ChatTopicBotContext => {
+ const senderExternalUserId = params.authorUserId ?? '';
+ const isOwner = !!params.operatorUserId && senderExternalUserId === params.operatorUserId;
+ return {
+ applicationId: params.applicationId,
+ isOwner,
+ platform: params.platform,
+ platformThreadId: params.platformThreadId,
+ senderExternalUserId,
+ };
+};
diff --git a/src/server/services/messenger/MessengerRouter.ts b/src/server/services/messenger/MessengerRouter.ts
index e0bf81da706..02af705b5cf 100644
--- a/src/server/services/messenger/MessengerRouter.ts
+++ b/src/server/services/messenger/MessengerRouter.ts
@@ -19,6 +19,7 @@ import type { LobeChatDatabase } from '@/database/type';
import { getAgentRuntimeRedisClient } from '@/server/modules/AgentRuntime/redis';
import { AiAgentService } from '@/server/services/aiAgent';
import { AgentBridgeService } from '@/server/services/bot/AgentBridgeService';
+import { buildBotContext } from '@/server/services/bot/buildBotContext';
import type { PlatformClient } from '@/server/services/bot/platforms';
import { renderInlineError } from '@/server/services/bot/replyTemplate';
@@ -954,20 +955,22 @@ export class MessengerRouter {
// Messenger account-link routing already binds platform sender β†’
// LobeHub user; the dispatch only fires for the linked sender. So
// `isOwner` is true iff the inbound message's `author.userId` matches
- // the linked `platformUserId`. Falls back to false when either is
- // missing (fail-closed β€” never default device access to "trusted").
- const senderExternalUserId = message.author?.userId ?? '';
- const isOwner = !!link.platformUserId && senderExternalUserId === link.platformUserId;
-
+ // the linked `platformUserId`. `buildBotContext` enforces the
+ // fail-closed default (never trust when either side is missing).
await bridge.handleMention(thread, message, {
agentId,
botContext: {
- // Per-install applicationId so the agent runtime can distinguish
- // workspaces in its own bookkeeping (logs, traces, dedupe).
- applicationId: link.tenantId
- ? `messenger-${platform}-${link.tenantId}`
- : `messenger-${platform}`,
- isOwner,
+ ...buildBotContext({
+ // Per-install applicationId so the agent runtime can distinguish
+ // workspaces in its own bookkeeping (logs, traces, dedupe).
+ applicationId: link.tenantId
+ ? `messenger-${platform}-${link.tenantId}`
+ : `messenger-${platform}`,
+ authorUserId: message.author?.userId,
+ operatorUserId: link.platformUserId,
+ platform,
+ platformThreadId: thread.id,
+ }),
// Explicit, deterministic marker that this run originated from the
// shared Messenger bot. `BotCallbackService` uses the presence of this
// field to resolve credentials via the messenger install store instead
@@ -976,9 +979,6 @@ export class MessengerRouter {
messengerInstallationKey: link.tenantId
? `${platform}:${link.tenantId}`
: `${platform}:singleton`,
- platform,
- platformThreadId: thread.id,
- senderExternalUserId,
},
client,
});