π€― 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(agent-share): block owner-machine MCP servers in visitor runs (#20586)
YuTengjing0c83660567b2
diff --git a/apps/server/src/modules/AgentRuntime/context.ts b/apps/server/src/modules/AgentRuntime/context.tsindex 854a40cb0ff..037d5f4cb52 100644--- a/apps/server/src/modules/AgentRuntime/context.ts+++ b/apps/server/src/modules/AgentRuntime/context.ts@@ -30,7 +30,7 @@ export interface RuntimeExecutorContext {* its presence alone is the signal every per-step consumer keys off. Forwarded* into `ToolExecutionContext.agentShareVisitor` so* `BuiltinToolsExecutor.execute` can re-check the visitor's grants right- * before dispatch β see `isShareBlockedDataToolCall` in `shareGate.ts`.+ * before dispatch β see `isShareBlockedDataToolCall` in `shareGate/dispatch.ts`.*/agentShareVisitor?: AgentShareVisitorContext;/**diff --git a/apps/server/src/services/aiAgent/pipeline/startOperation.ts b/apps/server/src/services/aiAgent/pipeline/startOperation.tsindex 9e9f99d2a57..a1a3878047f 100644--- a/apps/server/src/services/aiAgent/pipeline/startOperation.ts+++ b/apps/server/src/services/aiAgent/pipeline/startOperation.ts@@ -195,7 +195,7 @@ export const startOperation = async (// Mirrors `shareConfig.allowReadMemory` so `BuiltinToolsExecutor`// can re-check the memory tool's grant at dispatch time (the// actual chokepoint) via `isShareBlockedDataToolCall` β see- // `shareGate.ts`.+ // `shareGate/dispatch.ts`.allowReadMemory: shareGate.shareConfig.allowReadMemory,// Mirrors `shareConfig.toolGrants` so tool runtimes resolved// outside `toolManifestMap` (e.g. `activateSkill`, which queriesdiff --git a/apps/server/src/services/aiAgent/shareGate.ts b/apps/server/src/services/aiAgent/shareGate.tsdeleted file mode 100644index 3c44c8ed9d6..00000000000--- a/apps/server/src/services/aiAgent/shareGate.ts+++ /dev/null@@ -1,1013 +0,0 @@-import {- AGENT_SHARE_DOCUMENT_API_NAMES,- AgentDocumentsApiName,- AgentDocumentsIdentifier,-} from '@lobechat/builtin-tool-agent-documents';-import { CloudSandboxManifest } from '@lobechat/builtin-tool-cloud-sandbox';-import {- KnowledgeBaseApiName,- KnowledgeBaseIdentifier,-} from '@lobechat/builtin-tool-knowledge-base';-import {- LobeAgentApiName,- LobeAgentIdentifier,- systemPromptWithoutSubAgent,-} from '@lobechat/builtin-tool-lobe-agent';-import { MEMORY_WRITE_API_NAMES, MemoryIdentifier } from '@lobechat/builtin-tool-memory';-import {- AGENT_SHARE_SKILL_API_NAMES,- SkillsIdentifier,- SkillsManifest,-} from '@lobechat/builtin-tool-skills';-import {- AGENT_SHARE_ALLOWED_BUILTIN_IDENTIFIERS,- isBuiltinToolIdentifier,-} from '@lobechat/builtin-tools';-import {- hasShareToolGrant,- isShareToolApiGranted,- PLUGIN_SCHEMA_SEPARATOR,- resolveShareAllowedSkillIds,- resolveShareToolGrants,- type ShareToolGrant,-} from '@lobechat/const';-import type { LobeToolManifest, ToolExecutor, ToolSource } from '@lobechat/context-engine';-import { generateToolsFromManifest, ToolNameResolver } from '@lobechat/context-engine';-import type { AgentShareToolGrant } from '@lobechat/types';--import type { AgentShareConfig } from '@/database/schemas';--import { resolveShareToolManifest } from './shareToolManifest';--/**- * Single shared resolver instance for regenerating function-calling names- * from a manifest's identifier/api/type β same class `ToolsEngine` used to- * build `toolSet.tools` in the first place. Stateless (no per-call config),- * so one instance is safe to reuse across every gate pass.- */-const toolNameResolver = new ToolNameResolver();--/**- * Server-side gate for shared-agent visitor conversations.- *- * Built exclusively by the shareChat router after the share access check β- * never from client input. The gate is applied at operation-build time inside- * `AiAgentService.execAgent`, so the restricted tool/memory/file surface is- * snapshotted into the operation state and every later step inherits it- * without the context engine knowing about shares.- */-export interface AgentShareGate {- agentId: string;- shareConfig: AgentShareConfig;- /**- * The `agentShares.id` this run was authorized against β read together with- * `shareConfig` in the SAME `AgentShareModel.findByShareIdWithAccessCheck`- * call.- *- * "The share row for this agent still exists AND its id still equals- * `shareId` AND its visibility is still `link`" is exactly the condition- * "this run's authorization has not been revoked". Every re-validation in- * the visitor chain (`shareVisitorAbuseGuards`, the per-step runtime- * re-check) is that one comparison.- *- * The visibility half carries the ordinary case: turning sharing off flips- * the row to `private` and keeps it, so the owner can resume the same link- * later (`AgentShareModel.updateVisibility`). The id half covers a row that- * genuinely went away and came back as a different instance β a hard delete- * (`AgentShareModel.deleteByAgentId`) or an agent delete + recreate.- */- shareId: string;- /**- * The signed-in visitor driving this run. Recorded on `topics.senderId` and- * spend-log metadata; the run itself executes as the creator.- */- visitorUserId: string;-}--/**- * Intersect a run's candidate plugin/skill ids with the share whitelist.- * The whitelist defaults to empty, so an unconfigured share exposes no tools.- *- * Identifier-level only: an entry granting just one API- * (`{ identifier: 'lobe-agent', apis: ['analyzeMedia'] }`) still counts as- * "this identifier is a- * candidate" here β narrowing the offer down to that specific API happens- * later, in {@link applyShareGateToToolSet}, once the real manifest is known.- */-export const filterPluginsByShareGate = (pluginIds: string[], gate: AgentShareGate): string[] => {- const grants = resolveShareToolGrants(gate.shareConfig.toolGrants);-- return pluginIds.filter((id) => hasShareToolGrant(grants, id));-};--/**- * Intersect a run's candidate SKILL ids with the share's skill grants.- *- * Skills are governed by `shareConfig.skillGrants`, not `toolGrants`: a skill- * grant also authorizes the no-tool path (a pinned skill's body is injected- * straight into context), so it cannot be expressed as a grant on the- * `lobe-skills` tool entry. See {@link resolveShareAllowedSkillIds} for the- * default-closed semantics.- *- * Kept next to {@link filterPluginsByShareGate} so the two read as the pair- * they are; callers must not use the plugin filter for skill ids.- */-export const filterSkillsByShareGate = (skillIds: string[], gate: AgentShareGate): string[] =>- resolveShareAllowedSkillIds(skillIds, gate.shareConfig);--/**- * Builtins whose Share grant is also their runtime opt-in.- *- * Agent Documents is a default activatable builtin rather than a profile- * plugin, so creators have no separate profile switch that could place it in- * `agentConfig.plugins`. Adding it here only after an explicit Share grant- * lets the picker act as that opt-in for visitor runs while keeping the- * default-closed behavior. The final tool-set gate still narrows its APIs.- */-export const getShareGrantActivatedPluginIds = (gate: AgentShareGate): string[] => {- const grants = resolveShareToolGrants(gate.shareConfig.toolGrants);-- return hasShareToolGrant(grants, AgentDocumentsIdentifier) ? [AgentDocumentsIdentifier] : [];-};--/**- * Whether the share grants `lobe-cloud-sandbox` (at any API scope). Drives- * `resolveExecutionPlan`'s `sandboxFallback`: a visitor can never reach the- * creator's device, so this grant is only meaningful if the plan resolves to- * the sandbox instead of collapsing to `none`.- */-export const shareGateGrantsCloudSandbox = (gate: AgentShareGate): boolean =>- hasShareToolGrant(- resolveShareToolGrants(gate.shareConfig.toolGrants),- CloudSandboxManifest.identifier,- );--/**- * Strip agent files / knowledge bases from a share visitor's resolved agent- * config. Mutates in place β `agentConfig` is threaded through the whole- * orchestration by reference (tool discovery, knowledge flags, context builder- * snapshot), so a filtered copy would silently diverge.- *- * ADAPTATION vs the original design: the share config no longer carries a- * `filePermissionConfig` field, so there is no grant a creator could set that- * would expose their agent files or knowledge bases to a visitor. The gate is- * therefore unconditional rather than conditional β the fail-closed reading of- * "no configured permission". Re-introducing a file grant means restoring the- * config field AND relaxing this function together.- */-export const applyShareGateToAgentConfig = (agentConfig: {- files?: unknown[] | null;- knowledgeBases?: unknown[] | null;-}): void => {- agentConfig.files = [];- agentConfig.knowledgeBases = [];-};--/**- * Minimal shape a `DataToolAccessRule.grant` needs β either the full share- * gate's `shareConfig`, or the trimmed `agentShare` marker threaded through- * `RuntimeExecutorContext` / `ToolExecutionContext` for tool calls resolved- * outside this module (see {@link isShareBlockedDataToolCall}).- */-export interface ShareDataToolPermissions {- allowReadMemory?: boolean;- /**- * Agent's own persisted, `enabled` knowledge-base ids (never- * visitor-supplied). Currently always empty for a share run β see- * {@link applyShareGateToAgentConfig} β but kept so the id-scoping rule- * below stays wired should a knowledge-base grant return.- */- knowledgeBaseIds?: string[];- /**- * The share's `skillGrants`. Read here only to answer "does this share- * authorize any skill at all", which is what turns the `lobe-skills` TOOL on;- * which individual skills it may load is decided by- * {@link filterSkillsByShareGate} at assembly and re-checked at load time in- * the skill runtime.- */- skillGrants?: string[];- toolGrants?: AgentShareToolGrant[];-}--/**- * Whether this share authorizes any skill at all β the condition under which- * the `lobe-skills` tool itself becomes available to a visitor.- *- * Skills are NOT picked in the tool picker, so no creator ever writes a- * `lobe-skills` entry into `toolGrants`; the skill list IS the opt-in, the same- * way {@link getShareGrantActivatedPluginIds} lets the Documents grant double as- * that tool's runtime opt-in. Without this, a share could list skills the- * visitor's model has no tool to load.- */-const hasShareSkillAuthorization = (permissions: ShareDataToolPermissions): boolean =>- (permissions.skillGrants?.length ?? 0) > 0;--/**- * `resolveShareToolGrants` plus the grants that are implied rather than picked.- *- * Today that is only `lobe-skills`, whose opt-in lives in `skillGrants` (see- * {@link hasShareSkillAuthorization}). The synthetic grant is toolset-level- * (`'all'`) on purpose: narrowing the Skills tool down to its two visitor-safe- * APIs is {@link DATA_TOOL_ACCESS_RULES}' job, and expressing it twice would- * let the two lists drift.- *- * Every gate that asks "did the creator grant this identifier" must go through- * here, or the tool passes one layer and is rejected by the next.- */-const resolveEffectiveShareToolGrants = (- permissions: ShareDataToolPermissions,-): Map<string, ShareToolGrant> => {- const grants = resolveShareToolGrants(permissions.toolGrants);-- if (hasShareSkillAuthorization(permissions)) grants.set(SkillsIdentifier, 'all');-- return grants;-};--/**- * See `AGENT_SHARE_ALLOWED_BUILTIN_IDENTIFIERS`'s JSDoc in- * `@lobechat/builtin-tools` for the full per-identifier evidence. Aliased here- * so the two enforcement points below read as one local rule.- */-const SHARE_VISITOR_ALLOWED_IDENTIFIERS = AGENT_SHARE_ALLOWED_BUILTIN_IDENTIFIERS;--/**- * Whether `identifier` belongs to the population this allowlist governs β the- * real builtin tool registry (`@lobechat/builtin-tools`), the same source- * `BuiltinToolsExecutor`/`hasServerRuntime` resolve against. MCP servers,- * market plugins, and custom plugins never appear in this registry, so they- * fall outside this allowlist's jurisdiction entirely and are left to- * {@link filterPluginsByShareGate} / `shareConfig.toolGrants` β the- * pre-existing (and unaffected) gate for that population.- */-const isGovernedByBuiltinAllowlist = isBuiltinToolIdentifier;--type DataToolGrant = 'none' | 'read';--/**- * Read/write surface of a builtin tool whose APIs act directly on the- * creator's private data store (memory, knowledge bases, agent documents).- *- * These tools are gated by three independent axes: whether the share grants- * ANY access at all (`grant`) β share grants are `none` | `read` only, there- * is no write grant to honor; whether a given API is a write regardless of- * grant (`writeApiNames`); and whether a "read" API can even be scoped to what- * the share actually grants at all (`alwaysBlockedApiNames`,- * `isArgsOutOfScope`) β some reads act on the caller's ENTIRE personal data- * store with no id parameter tying them to the agent's own assignment, so a- * `read` grant must not enable them.- */-interface DataToolAccessRule {- /**- * API names that read across the creator's whole personal store- * (independent of what this specific agent is assigned) with no id argument- * that could scope the call. Always blocked for a share visitor, even when- * `grant` is `read` β unlike `writeApiNames`, these ARE reads, but a read- * grant only ever means "read what this agent is assigned," never "read- * everything the creator owns."- */- alwaysBlockedApiNames?: string[];- /** Resolve this share's grant for the tool from its permission fields. */- grant: (permissions: ShareDataToolPermissions) => DataToolGrant;- /**- * For an API that DOES take an id scoping it to a specific resource (e.g.- * `viewKnowledgeBase`'s `id`): whether the id(s) `args` references fall- * outside what this share's permissions actually allow. Must fail closed β- * an id that cannot be verified (missing, wrong type, or the allowlist- * itself is empty/absent) is out of scope.- */- isArgsOutOfScope?: (permissions: ShareDataToolPermissions, apiName: string, args: any) => boolean;- /** API names that mutate creator data; stripped/blocked unconditionally. */- writeApiNames: string[];-}--/**- * Registry of data-bearing builtin tools a share visitor can be whitelisted- * into (`shareConfig.toolGrants`) without the whitelist itself implying- * read OR write access to the underlying store. `filterPluginsByShareGate` /- * `applyShareGateToToolSet`'s allowlist intersection only answers "is this- * tool id enabled for the share" β it says nothing about `allowReadMemory`,- * which is why a whitelisted memory/knowledge-base/agent-documents tool would- * otherwise execute read-write under the creator's own permissions no matter- * what the share granted.- *- * Adding a new write API to one of these packages must add it here too β- * `shareGate.test.ts` asserts against the REAL exported manifests, so a rename- * or omission fails that test instead of silently reopening the hole.- */-const DATA_TOOL_ACCESS_RULES: Record<string, DataToolAccessRule> = {- [AgentDocumentsIdentifier]: {- // The tool grant opts into a separately scoped authoring store. It never- // exposes the creator's ordinary Agent Documents: the runtime and database- // both constrain reads and writes to (shareId, visitorUserId, topicId).- grant: (permissions) =>- hasShareToolGrant(resolveShareToolGrants(permissions.toolGrants), AgentDocumentsIdentifier)- ? 'read'- : 'none',- writeApiNames: Object.values(AgentDocumentsApiName).filter(- (apiName) => !AGENT_SHARE_DOCUMENT_API_NAMES.has(apiName),- ),- },- [KnowledgeBaseIdentifier]: {- // `listFiles` / `getFileDetail` browse the creator's whole resource- // library (files not yet in any knowledge base) β that library has no- // per-agent assignment concept at all, so no grant can scope it to "what- // this agent is assigned." `listKnowledgeBases` lists every knowledge base- // the creator owns, not just the ones mounted on this agent, and takes no- // id to scope it either. `readKnowledge` accepts arbitrary- // `file_*`/`docs_*` ids read straight from the creator's file/document- // store with no knowledge-base-membership check of its own. Blocking them- // is the fail-closed choice: `searchKnowledgeBase` (already agent/task-id- // scoped server-side) still returns real chunk/document text, so a `read`- // grant would remain useful without this hole.- alwaysBlockedApiNames: [- KnowledgeBaseApiName.listFiles,- KnowledgeBaseApiName.getFileDetail,- KnowledgeBaseApiName.listKnowledgeBases,- KnowledgeBaseApiName.readKnowledge,- ],- // Same adaptation as `AgentDocumentsIdentifier` above: no knowledge-base- // grant exists in the current `AgentShareConfig`.- grant: () => 'none',- // `viewKnowledgeBase` DOES take an `id`, and the agent's own assignment- // would be known (`ShareDataToolPermissions.knowledgeBaseIds`) β kept- // wired so restoring a knowledge-base grant only needs the `grant` line- // above changed, not this scoping rule re-derived.- isArgsOutOfScope: (permissions, apiName, args) => {- if (apiName !== KnowledgeBaseApiName.viewKnowledgeBase) return false;- const id = args?.id;- if (typeof id !== 'string' || !id) return true;- const allowed = permissions.knowledgeBaseIds;- return !allowed || !allowed.includes(id);- },- writeApiNames: [- KnowledgeBaseApiName.createKnowledgeBase,- KnowledgeBaseApiName.deleteKnowledgeBase,- KnowledgeBaseApiName.createDocument,- KnowledgeBaseApiName.addFiles,- KnowledgeBaseApiName.removeFiles,- ],- },- [MemoryIdentifier]: {- grant: (permissions) => (permissions.allowReadMemory ? 'read' : 'none'),- // Shared with the share settings picker so the owner is never offered a- // write API the gate strips anyway.- writeApiNames: [...MEMORY_WRITE_API_NAMES],- },- [SkillsIdentifier]: {- // The grant is the creator's skill list, not a tool-picker entry β see- // `hasShareSkillAuthorization`. `'read'` is the widest a share can reach:- // the two surviving APIs only read skill content, and WHICH skills they may- // read is enforced separately (`filterSkillsByShareGate` at assembly, the- // skill runtime's own check at load time β the latter is the real gate,- // since `activateSkill` resolves a model-supplied name).- grant: (permissions) => (hasShareSkillAuthorization(permissions) ? 'read' : 'none'),- // Derived as "everything outside the visitor-safe set" rather than listed,- // so a skill API added later is denied by default. Today that resolves to- // `runCommand` / `execScript` / `exportFile`. Share runs now honor the- // visitor's approval flow, so `humanIntervention: 'required'` no longer- // strips the first two β this list is what keeps them closed until- // opening skill script execution to visitors is decided on its own- writeApiNames: SkillsManifest.api- .map((api) => api.name)- .filter((apiName) => !AGENT_SHARE_SKILL_API_NAMES.has(apiName)),- },-};--/**- * Whether a specific `identifier`/`apiName` tool call must be blocked for a- * share visitor run. This is the enforcement counterpart of- * `applyShareGateToDataToolAccess` below, reusable from the actual dispatch- * chokepoint (`BuiltinToolsExecutor.execute`, which invokes- * `runtime[apiName](...)` directly and never re-consults the possibly- * already-trimmed manifest β the trimmed manifest only changes what the model- * is OFFERED via function-calling schema, not what the executor is willing to- * run if the model calls it anyway).- *- * DEFAULT-DENY for the builtin population: an `identifier` that resolves- * against the real `@lobechat/builtin-tools` registry- * (`isGovernedByBuiltinAllowlist`) but is NOT in- * `SHARE_VISITOR_ALLOWED_IDENTIFIERS` is blocked outright, with no- * `apiName`-level distinction. A non-builtin identifier (MCP server, market- * plugin, custom plugin) is NOT this function's concern at all β it falls- * through to `false` untouched, left entirely to- * {@link filterPluginsByShareGate} / `shareConfig.toolGrants`.- *- * `args` is the tool call's parsed arguments, needed only for- * `isArgsOutOfScope` rules. Omit it for call sites that only need the- * identifier/apiName-level check (grant / write / always-blocked).- */-export const isShareBlockedDataToolCall = (- permissions: ShareDataToolPermissions,- identifier: string,- apiName: string,- args?: any,-): boolean => {- // Outside this gate's jurisdiction entirely β MCP/market/custom plugin- // identifiers are governed by the toolGrants picker, not this allowlist.- if (!isGovernedByBuiltinAllowlist(identifier)) return false;-- // Default-deny: a known builtin identifier not on the allowlist is blocked- // unconditionally, including any tool registered after this allowlist was- // written β the whole point of inverting a denylist.- if (!SHARE_VISITOR_ALLOWED_IDENTIFIERS.has(identifier)) return true;-- const rule = DATA_TOOL_ACCESS_RULES[identifier];- if (!rule) return false;-- const grant = rule.grant(permissions);- if (grant === 'none') return true;-- if (rule.writeApiNames.includes(apiName)) return true;- if (rule.alwaysBlockedApiNames?.includes(apiName)) return true;- if (args !== undefined && rule.isArgsOutOfScope?.(permissions, apiName, args)) return true;-- return false;-};--/**- * FULL dispatch-time gate for a share-visitor builtin tool call β the check- * `BuiltinToolsExecutor.execute` runs on every call that reaches it. Strictly- * wider than {@link isShareBlockedDataToolCall}: a call that bypassed- * assembly (resume path, recovery hint, model-fabricated call to a tool it- * was never offered) must clear ALL the same gates the assembled tool set- * enforced, not only the data-tool rules:- *- * 1. master default-deny allowlist (`SHARE_VISITOR_ALLOWED_IDENTIFIERS`);- * 2. the owner's own `toolGrants` picker β being on the master allowlist- * is necessary but NOT sufficient; a tool the creator never enabled for- * this share (e.g. image generation spending the creator's quota) must not- * run just because a call reached the executor;- * 3. the per-API data-tool rules ({@link isShareBlockedDataToolCall}).- *- * Non-builtin identifiers (MCP/market/custom plugins, LobeHub skills) pass- * through untouched: their id namespace does not reliably match- * `toolGrants` identifiers, so they remain governed by the assembly-time- * `filterPluginsByShareGate` intersection only.- */-export const isShareBlockedBuiltinDispatch = (- agentShare: ShareDataToolPermissions & { toolGrants?: AgentShareToolGrant[] },- identifier: string,- apiName: string,- args?: any,-): boolean => {- if (!isGovernedByBuiltinAllowlist(identifier)) return false;-- if (!SHARE_VISITOR_ALLOWED_IDENTIFIERS.has(identifier)) return true;- // The owner's picker must grant this identifier at all (toolset-level or- // naming this specific `apiName`) β a grant scoped to a DIFFERENT api on- // the same identifier does not authorize this call.- if (!isShareToolApiGranted(resolveEffectiveShareToolGrants(agentShare), identifier, apiName))- return true;-- // Sub-agent dispatch has no humanIntervention config to catch it, and the- // server sub-agent runner spawns the child via a plain `execAgent` call- // that does NOT thread the parent's shareGate β the child would run with- // the creator's full, unrestricted tool surface. Assembly strips the API- // (`stripSubAgentDispatchApis`); this is its dispatch-time counterpart.- if (SUB_AGENT_DISPATCH_APIS[identifier]?.apiName === apiName) return true;-- // `humanIntervention` is deliberately NOT re-checked here: share runs keep- // the manifest's intervention config and honor the visitor's own approval- // mode, so an intervention-gated call reaches this executor only after the- // visitor approved it (or chose auto-run). Granting a tool grants its normal- // approval flow.- return isShareBlockedDataToolCall(agentShare, identifier, apiName, args);-};--/**- * The assembled operation-level tool set, right before it is handed to- * `AgentRuntimeService.createOperation` as `toolSet`.- */-export interface ShareGateToolSet {- activatableToolIds: string[];- enabledToolIds: string[];- executorMap: Record<string, ToolExecutor>;- manifestMap: Record<string, LobeToolManifest>;- sourceMap: Record<string, ToolSource>;- tools: any[] | undefined;-}--/**- * Apply {@link DATA_TOOL_ACCESS_RULES} to the assembled tool set: drop a data- * tool entirely when its grant is `none`, or strip its write APIs (from both- * the manifest and the function-calling `tools` schema) when the grant is- * `read`. Runs as part of {@link applyShareGateToToolSet} β after that pass's- * allowlist intersection has already decided which identifiers survive at all- * β so this only needs to further restrict, never re-add.- *- * This is UX/defense-in-depth (the model is never offered the disallowed- * function); the actual unbypassable enforcement is- * {@link isShareBlockedDataToolCall} at the `BuiltinToolsExecutor` dispatch- * site.- */-const applyShareGateToDataToolAccess = (toolSet: ShareGateToolSet, gate: AgentShareGate): void => {- for (const [identifier, rule] of Object.entries(DATA_TOOL_ACCESS_RULES)) {- if (!toolSet.manifestMap[identifier]) continue;-- const grant = rule.grant(gate.shareConfig);-- if (grant === 'none') {- dropToolFromSet(toolSet, identifier);- continue;- }-- // Under a `read` grant, strip both mutations (`writeApiNames`) AND the- // creator-wide reads that no grant can honestly scope to this agent- // (`alwaysBlockedApiNames`) β same treatment, since both are never offered- // to the model regardless of grant. `isArgsOutOfScope`-covered APIs are- // NOT stripped here: they stay offered because they CAN be in scope- // depending on the id the model picks, and that per-call id check only- // runs at dispatch time, not against a static manifest.- const blockedApiNames = new Set([...rule.writeApiNames, ...(rule.alwaysBlockedApiNames ?? [])]);-- stripApisFromTool(toolSet, identifier, blockedApiNames);- }-};--/**- * Final allowlist enforcement for a share visitor's fully-assembled tool set.- *- * `shareConfig.toolGrants` is the single source of truth for what a share- * visitor can see or run. This pass mutates `toolSet` in place and must run- * once, after every manifest/default/dynamic-activation source has been merged- * in, immediately before the operation's `toolSet` is persisted. An- * empty/missing whitelist collapses the set to nothing (no built-in tool is- * exempted; a share with no configured tools is a plain-chat run).- */-export const applyShareGateToToolSet = (toolSet: ShareGateToolSet, gate: AgentShareGate): void => {- const grants = resolveEffectiveShareToolGrants(gate.shareConfig);-- // A tool must clear BOTH gates: the owner's own `toolGrants` picker- // (`grants` β toolset-level OR scoped to at least one API), AND β for- // builtin identifiers only β the default-deny master allowlist- // (`SHARE_VISITOR_ALLOWED_IDENTIFIERS`). Non-builtin identifiers (MCP/market/- // custom plugins) are outside `isGovernedByBuiltinAllowlist`'s population, so- // they pass straight through to the owner-picker check unaffected β this- // allowlist must never decide their fate, in either direction.- const isAllowed = (id: string) => {- if (!hasShareToolGrant(grants, id)) return false;- if (!isGovernedByBuiltinAllowlist(id)) return true;- return SHARE_VISITOR_ALLOWED_IDENTIFIERS.has(id);- };-- // Prune arrays in place (`splice`, not reassignment) so this works whether- // the caller's binding for `enabledToolIds` / `activatableToolIds` / `tools`- // is a `const` array reference β callers only need to pass the array they- // already hold, not receive a new one back.- pruneArrayInPlace(toolSet.enabledToolIds, isAllowed);- pruneArrayInPlace(toolSet.activatableToolIds, isAllowed);-- // Regenerate every allowed manifest's tool-call names BEFORE the manifests- // are pruned: `ToolNameResolver.generate` MD5-hashes an identifier segment- // that is non-ASCII or oversized, so the `tools[]` entry of such a tool does- // not start with its literal identifier and a prefix-only check would drop- // a granted MCP tool along with everything else (fail-closed, but breaks- // the grant). See `pruneToolsForIdentifier` for the mirror-image, fail-OPEN- // hazard on the per-API path.- const allowedToolNames = new Set<string>();- for (const [id, manifest] of Object.entries(toolSet.manifestMap)) {- if (!isAllowed(id)) continue;- for (const name of generateOwnedToolNames(id, manifest)) allowedToolNames.add(name);- }-- for (const id of Object.keys(toolSet.manifestMap)) {- if (!isAllowed(id)) delete toolSet.manifestMap[id];- }- for (const id of Object.keys(toolSet.sourceMap)) {- if (!isAllowed(id)) delete toolSet.sourceMap[id];- }- for (const id of Object.keys(toolSet.executorMap)) {- if (!isAllowed(id)) delete toolSet.executorMap[id];- }-- if (toolSet.tools) {- pruneArrayInPlace(toolSet.tools, (tool) => {- const name: string | undefined = tool?.function?.name;- if (!name) return false;- if (allowedToolNames.has(name)) return true;- // Fallback for an entry with no manifest to regenerate from β only its- // literal identifier prefix can vouch for it.- const identifier = name.split(PLUGIN_SCHEMA_SEPARATOR)[0];- return !!identifier && isAllowed(identifier);- });- }-- stripSubAgentDispatchApis(toolSet);- applyShareGateToDataToolAccess(toolSet, gate);- applyShareGateToPerApiGrants(toolSet, grants);-};--/**- * Narrow each surviving tool's offered APIs down to what the owner's picker- * actually granted for it. Runs LAST in {@link applyShareGateToToolSet}, after- * every other strip (data-tool write/always-blocked APIs, sub-agent dispatch)- * has already trimmed `manifest.api` β so a per-API grant- * naming an API another rule already removed is simply a no-op here, never an- * unstrip.- *- * A toolset-level entry (`grant === 'all'`) leaves the tool's remaining APIs- * untouched. A per-API entry (`grant` is a `Set`) drops every remaining API- * not named in it; if that empties the API list entirely, the tool is dropped- * outright β the same treatment `applyShareGateToDataToolAccess` gives a- * `'none'` grant, since an identifier with zero callable APIs offers a share- * visitor's model nothing.- *- * Matches on the manifest's real `api[].name` list (via `stripApisFromTool`)- * rather than parsing generated tool-call names directly:- * `ToolNameResolver.generate` MD5-hashes an oversized or invalid-character API- * segment, so the manifest is the only reliable source for which entries in- * `toolSet.tools` belong to which granted API.- */-const applyShareGateToPerApiGrants = (- toolSet: ShareGateToolSet,- grants: Map<string, ShareToolGrant>,-): void => {- for (const identifier of Object.keys(toolSet.manifestMap)) {- const grant = grants.get(identifier);- if (!grant || grant === 'all') continue;-- const manifest = toolSet.manifestMap[identifier];- if (!Array.isArray(manifest.api) || manifest.api.length === 0) continue;-- const blockedApiNames = new Set(- manifest.api.filter((api) => !grant.has(api.name)).map((api) => api.name),- );- if (blockedApiNames.size === 0) continue;-- if (blockedApiNames.size === manifest.api.length) {- dropToolFromSet(toolSet, identifier);- continue;- }-- stripApisFromTool(toolSet, identifier, blockedApiNames);- }-};--/**- * Rationale for every registered builtin identifier that is DENIED β i.e.- * absent from `AGENT_SHARE_ALLOWED_BUILTIN_IDENTIFIERS`. Under a denylist an- * identifier had to be explicitly proven dangerous to be blocked; under the- * allowlist an identifier has to be explicitly proven safe to be exposed, so- * this block exists purely to record the evidence trail for reviewers β the- * denial itself needs no code beyond "not in the Set".- *- * Confirmed leak paths (a concrete visitorβcreator-data route was found):- *- * - `lobe-agent-management`: `agentManagementRuntime` is scoped by `userId`- * (the creator β the run executes as the creator), but `agentId` is a- * free-form model argument on nearly every API. `searchAgent` enumerates the- * creator's whole workspace; `getAgentDetail` returns any creator-owned- * agent's full config (system prompt included) for an arbitrary id;- * `createAgent` / `updateAgent` / `updatePrompt` / `duplicateAgent` /- * `installPlugin` persistently mutate the creator's agent collection.- *- * - `agent-signal-review`: `listManagedSkills` / `getManagedSkill` prefer an- * optional model-supplied `agentId` over the context-bound one, letting a- * visitor read ANY other agent's private managed-skill catalog under the- * same creator. `writeMemory` / `createSkillIfAbsent` /- * `replaceSkillContentCAS` are unconditional creator-scoped mutations, and- * share grants are `none`/`read` only.- *- * - `lobe-skill-maintainer` / `agent-signal-skill-management`: hidden,- * system-only tools whose every API WRITES agent-document rows under the- * creator's account. No write grant exists to honor.- *- * - `lobe-task` / `lobe-goal`: `TaskModel`/`taskRouter` are scoped only by- * `userId`/`workspaceId` β the CREATOR's. Every mutating and single-task-read- * API takes a model-supplied identifier resolved with no topic/conversation- * check, letting a visitor read, edit, delete, reschedule or RUN (spending- * the creator's budget) any task in the workspace. `listTasks`'s `scope:- * 'allAgents'` makes the breadth explicit.- *- * - `lobe-creds`: `injectCreds` takes a free-form `keys: string[]` and decrypts- * matching entries out of the creator's ENTIRE saved credential store.- *- * - `lobe-message`: every bot-management API resolves `botId` straight from- * model args with no check against `context.agentId`; the messenger APIs act- * on the creator's whole personal messenger account.- *- * - `lobe-skill-store`: the `importFrom*` family fetches attacker-chosen- * remote code/zip content and persists it into the creator's skill catalog.- *- * - `lobe-agent-builder`: `updateConfig`/`updatePrompt` overwrite the shared- * agent's own `systemRole`/config wholesale β a visitor rewriting the- * creator's live agent. `installPlugin` installs an arbitrary market MCP- * plugin onto it as the creator, with no consent step.- *- * - `lobe-brief`: `createBrief` unconditionally persists a row via- * `BriefModel.create` under `context.userId` (the creator) from- * model-supplied content, with no intervention marker to gate it.- *- * - `lobe-group-agent-builder` / `lobe-group-management`: group-orchestration- * tools operating on the creator's group-agent collection and membership,- * with no share-run scoping designed in β same risk class as- * `lobe-agent-management`.- *- * - `lobe-topic-reference`: `topicReferenceRuntime.getTopicContext`- * (`apps/server/src/services/toolExecution/serverRuntimes/topicReference.ts`)- * resolves a free-form model-supplied `topicId` via- * `TopicModel.findOwnTopicById`, scoped only to the creator's `userId` β not- * to this share or agent β letting a visitor's model read the summary or- * recent messages of ANY other topic the creator owns by guessing/enumerating- * ids. `DATA_TOOL_ACCESS_RULES` has no entry for it (it isn't a- * memory/knowledge-base/agent-documents style store), so nothing narrows the- * allowlist grant. The automatic `<refer_topic>` injection path- * (`serverCallLlmContextBuilder.ts`) is separately share-scoped via- * `isTopicVisibleToRun` and is unaffected by this denial β only the- * model-invokable tool-call path is unsafe.- *- * Denied for lack of positive safety evidence (no confirmed exploit was- * required to withhold access β the point of default-deny is that an unproven- * tool does not ship):- *- * - `lobe-local-system` / `lobe-browser` / `lobe-remote-device`: these proxy- * through `deviceGateway` to the creator's own registered physical- * device(s). A visitor executing arbitrary commands or driving a live- * browser session on the CREATOR's own machine is a far larger blast radius- * than any single data store.- *- * - `lobe-web-onboarding`: reads and WRITES the creator's own onboarding- * `SOUL.md` document and persona.- *- * - `lobe-self-feedback-intent` / `agent-signal-reflection` /- * `agent-signal-feedback-intent`: hidden, system-only self-iteration tools- * whose write paths were never audited for share safety.- *- * - `lobe-page-agent`: not unsafe β genuinely unreachable for a share- * visitor's run (`execAgent` strips it whenever `appContext?.scope !==- * 'page'`, and the share visitor path never sets `scope`), so allowlisting- * it would only let the owner-facing tool picker confirm a grant no visitor- * conversation can ever exercise.- *- * - `lobe-user-interaction` / `lobe-activator`: originally denied because- * share runs were forced headless, so neither could ever honestly complete.- * Share runs now honor the visitor's approval flow, but both stay denied- * until audited on their own: `lobe-activator` can widen the run's tool- * surface at runtime, which must be proven not to escape the share grant.- */--/**- * Positive evidence for builtin identifiers that WERE added to- * `AGENT_SHARE_ALLOWED_BUILTIN_IDENTIFIERS` despite reaching outside a single- * data store β recorded here, rather than left implicit, because their- * general-purpose reach needs an explicit safety argument instead of just the- * absence of a known exploit.- *- * - `lobe-cloud-sandbox`: general-purpose shell/script execution, but a share- * visitor's run gets a fresh, isolated per-topic sandbox session β never- * the creator's own sandbox state. The `lh` CLI's JWT credential shim- * (`preprocessLhCommand.ts`) that would otherwise mint a creator-scoped- * token inside a shell the visitor controls is skipped entirely for- * `agentShareVisitor` runs (`serverRuntimes/cloudSandbox.ts`), and- * `lobe-creds` stays denied above so nothing ever writes `~/.creds/env`- * into that session either. No creator credential or JWT is therefore- * reachable from inside a visitor's sandbox command.- *- * - `lobe-skills`: the tool DOES resolve skills out of the creator's personal- * catalog β that is what it is for, and it was denied for exactly that reason- * until the catalog stopped being the unit of authorization. What changed is- * that the creator now names individual skills (`shareConfig.skillGrants`),- * so the reachable set is an explicit allowlist instead of "everything the- * creator owns minus an opt-out `disabledSkillIds` set". Three things make- * that allowlist the real boundary rather than a UI suggestion:- *- * 1. the operation's skill pool is intersected with it at assembly- * ({@link filterSkillsByShareGate}, applied in `operationPrep`);- * 2. `activateSkill` resolves a MODEL-SUPPLIED name, so assembly alone would- * be bypassable β the skill runtime re-checks the allowlist at load time,- * on every path that opens skill content (name/id resolution AND the- * archive/resource loads that `execScript` and `readReference` reach- * through). A name outside the grant fails there even if the model- * invents it;- * 3. only `activateSkill` / `readReference` survive at all- * (`AGENT_SHARE_SKILL_API_NAMES`, enforced by the rule above): both are- * pure reads of granted skill content. The exec-class APIs, which are what- * would turn a granted skill into arbitrary code running as the creator,- * stay blocked.- *- * The grant deliberately carries whatever the granted skill itself does β- * a creator who opens a skill opens that skill's instructions, and that is- * the premise of Agent Share, not a hole in it. The gate's job is to execute- * the grant exactly, not to second-guess which skills a creator should share.- */--/**- * Sub-agent dispatch is not available in shared visitor runs. This strip runs- * unconditionally on `lobe-agent`, independent of whether the manifest was- * resolved through the normal context-aware path, so a whitelisted entry can- * never surface `callSubAgent` β nor a `systemRole` that instructs the model- * to call it β to a share visitor's model or the activator. `lobe-agent`- * already ships a precise systemRole variant without the dispatch section- * (`systemPromptWithoutSubAgent`, also used by its own context-aware- * `resolveManifest`).- *- * `lobe-agent-management`'s dispatch API (`callAgent`) does NOT need an entry- * here: the whole tool β dispatch included β is simply absent from- * `SHARE_VISITOR_ALLOWED_IDENTIFIERS`, so it never survives that gate.- */-const SUB_AGENT_DISPATCH_APIS: Record<- string,- { apiName: string; systemRoleWithoutDispatch: string }-> = {- [LobeAgentIdentifier]: {- apiName: LobeAgentApiName.callSubAgent,- systemRoleWithoutDispatch: systemPromptWithoutSubAgent,- },-};--const stripSubAgentDispatchApis = (toolSet: ShareGateToolSet): void => {- for (const [identifier, { apiName, systemRoleWithoutDispatch }] of Object.entries(- SUB_AGENT_DISPATCH_APIS,- )) {- const manifest = toolSet.manifestMap[identifier];- if (manifest) {- // Always pin the sanitized `systemRole`, not only when `api` still- // carries the dispatch entry β an already context-aware-trimmed manifest- // (api filtered upstream) could otherwise keep a stale `systemRole` that- // still instructs the model to call the removed tool.- toolSet.manifestMap[identifier] = {- ...manifest,- api: manifest.api.filter((api) => api.name !== apiName),- systemRole: systemRoleWithoutDispatch,- };- }-- if (toolSet.tools) {- const dispatchToolName = `${identifier}${PLUGIN_SCHEMA_SEPARATOR}${apiName}`;- pruneArrayInPlace(toolSet.tools, (tool) => tool?.function?.name !== dispatchToolName);- }- }-};--/**- * Regenerate the exact function-calling name `ToolsEngine` would have used- * for each of `apiNames`, via the SAME `ToolNameResolver.generate` it used to- * build `toolSet.tools` originally.- *- * A naive `` `${identifier}${SEP}${apiName}` `` string only matches what is- * actually in `toolSet.tools` when neither segment needed normalizing.- * `generate` (1) MD5-hashes an api/identifier segment that contains- * characters strict providers reject or that pushes the name past the- * provider length cap, and (2) appends a third `${SEP}<type>` segment for any- * manifest whose `type` isn't `builtin`/`default` β MCP/connector manifests- * are `type: 'mcp'` (see `buildConnectorManifests.ts`). Both are common for- * MCP tools (server-controlled, often long/non-ASCII api names), so skipping- * this and slicing the raw string instead silently fails OPEN: the manifest- * loses the API but its generated tool-call name survives in `tools[]` and- * stays callable.- */-const generateToolNames = (- identifier: string,- apiNames: Iterable<string>,- type: LobeToolManifest['type'],-): Set<string> => {- const names = new Set<string>();- for (const apiName of apiNames) names.add(toolNameResolver.generate(identifier, apiName, type));- return names;-};--/**- * Drop every `toolSet.tools` entry that belongs to `identifier` and is not in- * `allowedNames`. Pass an empty `allowedNames` to drop every entry for the- * identifier.- *- * "Belongs to `identifier`" is decided by `ownedNames` β the full set of- * generated names for every API on the identifier's manifest, produced by- * the SAME `ToolNameResolver.generate` that built `toolSet.tools`. A raw- * first-segment comparison against `identifier` is NOT enough on its own:- * `generate` MD5-hashes the identifier segment whenever it contains- * characters strict providers reject (non-ASCII, punctuation) or whenever- * the assembled name is still over the provider length cap after hashing- * the api segment, so for such identifiers no entry ever starts with the- * literal identifier text and a prefix-only match keeps everything β- * silently failing OPEN. The prefix check is kept only as a fallback for- * entries that survived without a manifest (nothing to regenerate from).- */-const pruneToolsForIdentifier = (- toolSet: ShareGateToolSet,- identifier: string,- ownedNames: ReadonlySet<string>,- allowedNames: ReadonlySet<string>,-): void => {- if (!toolSet.tools) return;- pruneArrayInPlace(toolSet.tools, (tool) => {- const name: string | undefined = tool?.function?.name;- if (!name) return true;- const owned = ownedNames.has(name) || name.split(PLUGIN_SCHEMA_SEPARATOR)[0] === identifier;- if (!owned) return true;- return allowedNames.has(name);- });-};--/**- * Replace surviving function schemas with a builtin-owned restricted- * projection while preserving which tools the upstream engine activated.- */-const replaceToolsForIdentifier = (- toolSet: ShareGateToolSet,- identifier: string,- ownedNames: ReadonlySet<string>,- manifest: LobeToolManifest,-): void => {- if (!toolSet.tools) return;-- const replacements = new Map(- generateToolsFromManifest(manifest).map((tool) => [tool.function.name, tool]),- );-- for (let i = 0; i < toolSet.tools.length; i += 1) {- const name: string | undefined = toolSet.tools[i]?.function?.name;- if (!name) continue;-- const owned = ownedNames.has(name) || name.split(PLUGIN_SCHEMA_SEPARATOR)[0] === identifier;- const replacement = replacements.get(name);- if (owned && replacement) toolSet.tools[i] = replacement;- }-};--/** Every generated tool-call name the manifest can currently produce. */-const generateOwnedToolNames = (- identifier: string,- manifest: LobeToolManifest | undefined,-): Set<string> =>- manifest- ? generateToolNames(- identifier,- manifest.api.map((api) => api.name),- manifest.type,- )- : new Set();--const EMPTY_TOOL_NAME_SET: ReadonlySet<string> = new Set();--/** Remove one tool identifier from every parallel structure of the tool set. */-const dropToolFromSet = (toolSet: ShareGateToolSet, identifier: string): void => {- // Regenerate the owned names BEFORE the manifest is gone β it is the only- // source that can reproduce a hashed identifier segment.- const ownedNames = generateOwnedToolNames(identifier, toolSet.manifestMap[identifier]);- delete toolSet.manifestMap[identifier];- delete toolSet.sourceMap[identifier];- delete toolSet.executorMap[identifier];- pruneArrayInPlace(toolSet.enabledToolIds, (id) => id !== identifier);- pruneArrayInPlace(toolSet.activatableToolIds, (id) => id !== identifier);- pruneToolsForIdentifier(toolSet, identifier, ownedNames, EMPTY_TOOL_NAME_SET);-};--/** Drop `blockedApiNames` from one tool's manifest AND its function-calling schema. */-const stripApisFromTool = (- toolSet: ShareGateToolSet,- identifier: string,- blockedApiNames: Set<string>,-): void => {- const manifest = toolSet.manifestMap[identifier];- if (!manifest) return;-- const survivingApi = manifest.api.filter((api) => !blockedApiNames.has(api.name));- const wasTrimmed = survivingApi.length < manifest.api.length;- const ownedNames = generateOwnedToolNames(identifier, manifest);- const restrictedManifest = wasTrimmed- ? resolveShareToolManifest({- allowedApiNames: survivingApi.map((api) => api.name),- identifier,- })- : undefined;- const restrictedApiMap = new Map(restrictedManifest?.api.map((api) => [api.name, api]) ?? []);-- // A manifest-level system role commonly documents its complete API surface.- // Keeping it after a partial strip lets the model infer and advertise APIs- // that are no longer callable, even though the function schemas are safe.- // ToolResolver applies the same invariant for per-step tool-name filtering.- toolSet.manifestMap[identifier] = {- ...manifest,- api: survivingApi.map((api) => restrictedApiMap.get(api.name) ?? api),- meta: restrictedManifest?.meta ?? manifest.meta,- ...(wasTrimmed && {- systemRole: restrictedManifest?.systemRole,- }),- };-- // Fail-closed: only keep `tools[]` entries this file can PROVE still- // belong to a surviving API, by regenerating their exact names rather than- // reverse-parsing whatever is already in `tools[]`.- pruneToolsForIdentifier(- toolSet,- identifier,- ownedNames,- generateToolNames(- identifier,- survivingApi.map((api) => api.name),- manifest.type,- ),- );-- if (restrictedManifest) {- replaceToolsForIdentifier(toolSet, identifier, ownedNames, toolSet.manifestMap[identifier]);- }-};--const pruneArrayInPlace = <T>(array: T[], keep: (item: T) => boolean): void => {- for (let i = array.length - 1; i >= 0; i -= 1) {- if (!keep(array[i])) array.splice(i, 1);- }-};diff --git a/apps/server/src/services/aiAgent/shareGate/README.md b/apps/server/src/services/aiAgent/shareGate/README.mdnew file mode 100644index 00000000000..538f3ec0353--- /dev/null+++ b/apps/server/src/services/aiAgent/shareGate/README.md@@ -0,0 +1,159 @@+# Agent Share gate: builtin allowlist evidence++Reviewer record for `AGENT_SHARE_ALLOWED_BUILTIN_IDENTIFIERS` (`@lobechat/builtin-tools`). Update it whenever an identifier is added to or kept out of that allowlist.++## Denied builtins++Rationale for every registered builtin identifier that is DENIED β i.e.+absent from `AGENT_SHARE_ALLOWED_BUILTIN_IDENTIFIERS`. Under a denylist an+identifier had to be explicitly proven dangerous to be blocked; under the+allowlist an identifier has to be explicitly proven safe to be exposed, so+this block exists purely to record the evidence trail for reviewers β the+denial itself needs no code beyond "not in the Set".++Confirmed leak paths (a concrete visitorβcreator-data route was found):++- `lobe-agent-management`: `agentManagementRuntime` is scoped by `userId`+ (the creator β the run executes as the creator), but `agentId` is a+ free-form model argument on nearly every API. `searchAgent` enumerates the+ creator's whole workspace; `getAgentDetail` returns any creator-owned+ agent's full config (system prompt included) for an arbitrary id;+ `createAgent` / `updateAgent` / `updatePrompt` / `duplicateAgent` /+ `installPlugin` persistently mutate the creator's agent collection.++- `agent-signal-review`: `listManagedSkills` / `getManagedSkill` prefer an+ optional model-supplied `agentId` over the context-bound one, letting a+ visitor read ANY other agent's private managed-skill catalog under the+ same creator. `writeMemory` / `createSkillIfAbsent` /+ `replaceSkillContentCAS` are unconditional creator-scoped mutations, and+ share grants are `none`/`read` only.++- `lobe-skill-maintainer` / `agent-signal-skill-management`: hidden,+ system-only tools whose every API WRITES agent-document rows under the+ creator's account. No write grant exists to honor.++- `lobe-task` / `lobe-goal`: `TaskModel`/`taskRouter` are scoped only by+ `userId`/`workspaceId` β the CREATOR's. Every mutating and single-task-read+ API takes a model-supplied identifier resolved with no topic/conversation+ check, letting a visitor read, edit, delete, reschedule or RUN (spending+ the creator's budget) any task in the workspace. `listTasks`'s `scope:+'allAgents'` makes the breadth explicit.++- `lobe-creds`: `injectCreds` takes a free-form `keys: string[]` and decrypts+ matching entries out of the creator's ENTIRE saved credential store.++- `lobe-message`: every bot-management API resolves `botId` straight from+ model args with no check against `context.agentId`; the messenger APIs act+ on the creator's whole personal messenger account.++- `lobe-skill-store`: the `importFrom*` family fetches attacker-chosen+ remote code/zip content and persists it into the creator's skill catalog.++- `lobe-agent-builder`: `updateConfig`/`updatePrompt` overwrite the shared+ agent's own `systemRole`/config wholesale β a visitor rewriting the+ creator's live agent. `installPlugin` installs an arbitrary market MCP+ plugin onto it as the creator, with no consent step.++- `lobe-brief`: `createBrief` unconditionally persists a row via+ `BriefModel.create` under `context.userId` (the creator) from+ model-supplied content, with no intervention marker to gate it.++- `lobe-group-agent-builder` / `lobe-group-management`: group-orchestration+ tools operating on the creator's group-agent collection and membership,+ with no share-run scoping designed in β same risk class as+ `lobe-agent-management`.++- `lobe-topic-reference`: `topicReferenceRuntime.getTopicContext`+ (`apps/server/src/services/toolExecution/serverRuntimes/topicReference.ts`)+ resolves a free-form model-supplied `topicId` via+ `TopicModel.findOwnTopicById`, scoped only to the creator's `userId` β not+ to this share or agent β letting a visitor's model read the summary or+ recent messages of ANY other topic the creator owns by guessing/enumerating+ ids. `DATA_TOOL_ACCESS_RULES` has no entry for it (it isn't a+ memory/knowledge-base/agent-documents style store), so nothing narrows the+ allowlist grant. The automatic `<refer_topic>` injection path+ (`serverCallLlmContextBuilder.ts`) is separately share-scoped via+ `isTopicVisibleToRun` and is unaffected by this denial β only the+ model-invokable tool-call path is unsafe.++Denied for lack of positive safety evidence (no confirmed exploit was+required to withhold access β the point of default-deny is that an unproven+tool does not ship):++- `lobe-local-system` / `lobe-browser` / `lobe-remote-device`: these proxy+ through `deviceGateway` to the creator's own registered physical+ device(s). A visitor executing arbitrary commands or driving a live+ browser session on the CREATOR's own machine is a far larger blast radius+ than any single data store.++- `lobe-web-onboarding`: reads and WRITES the creator's own onboarding+ `SOUL.md` document and persona.++- `lobe-self-feedback-intent` / `agent-signal-reflection` /+ `agent-signal-feedback-intent`: hidden, system-only self-iteration tools+ whose write paths were never audited for share safety.++- `lobe-page-agent`: not unsafe β genuinely unreachable for a share+ visitor's run (`execAgent` strips it whenever `appContext?.scope !==+'page'`, and the share visitor path never sets `scope`), so allowlisting+ it would only let the owner-facing tool picker confirm a grant no visitor+ conversation can ever exercise.++- `lobe-user-interaction` / `lobe-activator`: originally denied because+ share runs were forced headless, so neither could ever honestly complete.+ Share runs now honor the visitor's approval flow, but both stay denied+ until audited on their own: `lobe-activator` can widen the run's tool+ surface at runtime, which must be proven not to escape the share grant.++- Device-only MCP servers (stdio, or an HTTP endpoint on localhost / a+ private network): not builtin identifiers, so the allowlist above never+ sees them, but a visitor run must still never reach them β the server can+ only call them by tunneling to the creator's online desktop app (or, with+ no device gateway, by spawning the binary on the server itself).+ `applyShareGateToToolSet` drops them regardless of `toolGrants`, and+ `ToolExecutionService.executeMCPTool` refuses the dispatch.++## Allowed builtins with general reach++Positive evidence for builtin identifiers that WERE added to+`AGENT_SHARE_ALLOWED_BUILTIN_IDENTIFIERS` despite reaching outside a single+data store β recorded here, rather than left implicit, because their+general-purpose reach needs an explicit safety argument instead of just the+absence of a known exploit.++- `lobe-cloud-sandbox`: general-purpose shell/script execution, but a share+ visitor's run gets a fresh, isolated per-topic sandbox session β never+ the creator's own sandbox state. The `lh` CLI's JWT credential shim+ (`preprocessLhCommand.ts`) that would otherwise mint a creator-scoped+ token inside a shell the visitor controls is skipped entirely for+ `agentShareVisitor` runs (`serverRuntimes/cloudSandbox.ts`), and+ `lobe-creds` stays denied above so nothing ever writes `~/.creds/env`+ into that session either. No creator credential or JWT is therefore+ reachable from inside a visitor's sandbox command.++- `lobe-skills`: the tool DOES resolve skills out of the creator's personal+ catalog β that is what it is for, and it was denied for exactly that reason+ until the catalog stopped being the unit of authorization. What changed is+ that the creator now names individual skills (`shareConfig.skillGrants`),+ so the reachable set is an explicit allowlist instead of "everything the+ creator owns minus an opt-out `disabledSkillIds` set". Three things make+ that allowlist the real boundary rather than a UI suggestion:++ 1. the operation's skill pool is intersected with it at assembly+ (`filterSkillsByShareGate`, applied in `operationPrep`);+ 2. `activateSkill` resolves a MODEL-SUPPLIED name, so assembly alone would+ be bypassable β the skill runtime re-checks the allowlist at load time,+ on every path that opens skill content (name/id resolution AND the+ archive/resource loads that `execScript` and `readReference` reach+ through). A name outside the grant fails there even if the model+ invents it;+ 3. only `activateSkill` / `readReference` survive at all+ (`AGENT_SHARE_SKILL_API_NAMES`, enforced by the rule above): both are+ pure reads of granted skill content. The exec-class APIs, which are what+ would turn a granted skill into arbitrary code running as the creator,+ stay blocked.++ The grant deliberately carries whatever the granted skill itself does β+ a creator who opens a skill opens that skill's instructions, and that is+ the premise of Agent Share, not a hole in it. The gate's job is to execute+ the grant exactly, not to second-guess which skills a creator should share.diff --git a/apps/server/src/services/aiAgent/shareGate/allowlist.ts b/apps/server/src/services/aiAgent/shareGate/allowlist.tsnew file mode 100644index 00000000000..4216b940644--- /dev/null+++ b/apps/server/src/services/aiAgent/shareGate/allowlist.ts@@ -0,0 +1,22 @@+import {+ AGENT_SHARE_ALLOWED_BUILTIN_IDENTIFIERS,+ isBuiltinToolIdentifier,+} from '@lobechat/builtin-tools';++/**+ * See `AGENT_SHARE_ALLOWED_BUILTIN_IDENTIFIERS`'s JSDoc in+ * `@lobechat/builtin-tools` for the full per-identifier evidence. Aliased here+ * so the two enforcement points below read as one local rule.+ */+export const SHARE_VISITOR_ALLOWED_IDENTIFIERS = AGENT_SHARE_ALLOWED_BUILTIN_IDENTIFIERS;++/**+ * Whether `identifier` belongs to the population this allowlist governs β the+ * real builtin tool registry (`@lobechat/builtin-tools`), the same source+ * `BuiltinToolsExecutor`/`hasServerRuntime` resolve against. MCP servers,+ * market plugins, and custom plugins never appear in this registry, so they+ * fall outside this allowlist's jurisdiction entirely and are left to+ * {@link filterPluginsByShareGate} / `shareConfig.toolGrants` β the+ * pre-existing (and unaffected) gate for that population.+ */+export const isGovernedByBuiltinAllowlist = isBuiltinToolIdentifier;diff --git a/apps/server/src/services/aiAgent/shareGate/dataToolRules.ts b/apps/server/src/services/aiAgent/shareGate/dataToolRules.tsnew file mode 100644index 00000000000..c08735a483d--- /dev/null+++ b/apps/server/src/services/aiAgent/shareGate/dataToolRules.ts@@ -0,0 +1,151 @@+import {+ AGENT_SHARE_DOCUMENT_API_NAMES,+ AgentDocumentsApiName,+ AgentDocumentsIdentifier,+} from '@lobechat/builtin-tool-agent-documents';+import {+ KnowledgeBaseApiName,+ KnowledgeBaseIdentifier,+} from '@lobechat/builtin-tool-knowledge-base';+import { MEMORY_WRITE_API_NAMES, MemoryIdentifier } from '@lobechat/builtin-tool-memory';+import {+ AGENT_SHARE_SKILL_API_NAMES,+ SkillsIdentifier,+ SkillsManifest,+} from '@lobechat/builtin-tool-skills';+import { hasShareToolGrant, resolveShareToolGrants } from '@lobechat/const';++import { hasShareSkillAuthorization } from './grants';+import type { ShareDataToolPermissions } from './types';++type DataToolGrant = 'none' | 'read';++/**+ * Read/write surface of a builtin tool whose APIs act directly on the+ * creator's private data store (memory, knowledge bases, agent documents).+ *+ * These tools are gated by three independent axes: whether the share grants+ * ANY access at all (`grant`) β share grants are `none` | `read` only, there+ * is no write grant to honor; whether a given API is a write regardless of+ * grant (`writeApiNames`); and whether a "read" API can even be scoped to what+ * the share actually grants at all (`alwaysBlockedApiNames`,+ * `isArgsOutOfScope`) β some reads act on the caller's ENTIRE personal data+ * store with no id parameter tying them to the agent's own assignment, so a+ * `read` grant must not enable them.+ */+interface DataToolAccessRule {+ /**+ * API names that read across the creator's whole personal store+ * (independent of what this specific agent is assigned) with no id argument+ * that could scope the call. Always blocked for a share visitor, even when+ * `grant` is `read` β unlike `writeApiNames`, these ARE reads, but a read+ * grant only ever means "read what this agent is assigned," never "read+ * everything the creator owns."+ */+ alwaysBlockedApiNames?: string[];+ /** Resolve this share's grant for the tool from its permission fields. */+ grant: (permissions: ShareDataToolPermissions) => DataToolGrant;+ /**+ * For an API that DOES take an id scoping it to a specific resource (e.g.+ * `viewKnowledgeBase`'s `id`): whether the id(s) `args` references fall+ * outside what this share's permissions actually allow. Must fail closed β+ * an id that cannot be verified (missing, wrong type, or the allowlist+ * itself is empty/absent) is out of scope.+ */+ isArgsOutOfScope?: (permissions: ShareDataToolPermissions, apiName: string, args: any) => boolean;+ /** API names that mutate creator data; stripped/blocked unconditionally. */+ writeApiNames: string[];+}++/**+ * Registry of data-bearing builtin tools a share visitor can be whitelisted+ * into (`shareConfig.toolGrants`) without the whitelist itself implying+ * read OR write access to the underlying store. `filterPluginsByShareGate` /+ * `applyShareGateToToolSet`'s allowlist intersection only answers "is this+ * tool id enabled for the share" β it says nothing about `allowReadMemory`,+ * which is why a whitelisted memory/knowledge-base/agent-documents tool would+ * otherwise execute read-write under the creator's own permissions no matter+ * what the share granted.+ *+ * Adding a new write API to one of these packages must add it here too β+ * `dispatch.test.ts` asserts against the REAL exported manifests, so a rename+ * or omission fails that test instead of silently reopening the hole.+ */+export const DATA_TOOL_ACCESS_RULES: Record<string, DataToolAccessRule> = {+ [AgentDocumentsIdentifier]: {+ // The tool grant opts into a separately scoped authoring store. It never+ // exposes the creator's ordinary Agent Documents: the runtime and database+ // both constrain reads and writes to (shareId, visitorUserId, topicId).+ grant: (permissions) =>+ hasShareToolGrant(resolveShareToolGrants(permissions.toolGrants), AgentDocumentsIdentifier)+ ? 'read'+ : 'none',+ writeApiNames: Object.values(AgentDocumentsApiName).filter(+ (apiName) => !AGENT_SHARE_DOCUMENT_API_NAMES.has(apiName),+ ),+ },+ [KnowledgeBaseIdentifier]: {+ // `listFiles` / `getFileDetail` browse the creator's whole resource+ // library (files not yet in any knowledge base) β that library has no+ // per-agent assignment concept at all, so no grant can scope it to "what+ // this agent is assigned." `listKnowledgeBases` lists every knowledge base+ // the creator owns, not just the ones mounted on this agent, and takes no+ // id to scope it either. `readKnowledge` accepts arbitrary+ // `file_*`/`docs_*` ids read straight from the creator's file/document+ // store with no knowledge-base-membership check of its own. Blocking them+ // is the fail-closed choice: `searchKnowledgeBase` (already agent/task-id+ // scoped server-side) still returns real chunk/document text, so a `read`+ // grant would remain useful without this hole.+ alwaysBlockedApiNames: [+ KnowledgeBaseApiName.listFiles,+ KnowledgeBaseApiName.getFileDetail,+ KnowledgeBaseApiName.listKnowledgeBases,+ KnowledgeBaseApiName.readKnowledge,+ ],+ // Same adaptation as `AgentDocumentsIdentifier` above: no knowledge-base+ // grant exists in the current `AgentShareConfig`.+ grant: () => 'none',+ // `viewKnowledgeBase` DOES take an `id`, and the agent's own assignment+ // would be known (`ShareDataToolPermissions.knowledgeBaseIds`) β kept+ // wired so restoring a knowledge-base grant only needs the `grant` line+ // above changed, not this scoping rule re-derived.+ isArgsOutOfScope: (permissions, apiName, args) => {+ if (apiName !== KnowledgeBaseApiName.viewKnowledgeBase) return false;+ const id = args?.id;+ if (typeof id !== 'string' || !id) return true;+ const allowed = permissions.knowledgeBaseIds;+ return !allowed || !allowed.includes(id);+ },+ writeApiNames: [+ KnowledgeBaseApiName.createKnowledgeBase,+ KnowledgeBaseApiName.deleteKnowledgeBase,+ KnowledgeBaseApiName.createDocument,+ KnowledgeBaseApiName.addFiles,+ KnowledgeBaseApiName.removeFiles,+ ],+ },+ [MemoryIdentifier]: {+ grant: (permissions) => (permissions.allowReadMemory ? 'read' : 'none'),+ // Shared with the share settings picker so the owner is never offered a+ // write API the gate strips anyway.+ writeApiNames: [...MEMORY_WRITE_API_NAMES],+ },+ [SkillsIdentifier]: {+ // The grant is the creator's skill list, not a tool-picker entry β see+ // `hasShareSkillAuthorization`. `'read'` is the widest a share can reach:+ // the two surviving APIs only read skill content, and WHICH skills they may+ // read is enforced separately (`filterSkillsByShareGate` at assembly, the+ // skill runtime's own check at load time β the latter is the real gate,+ // since `activateSkill` resolves a model-supplied name).+ grant: (permissions) => (hasShareSkillAuthorization(permissions) ? 'read' : 'none'),+ // Derived as "everything outside the visitor-safe set" rather than listed,+ // so a skill API added later is denied by default. Today that resolves to+ // `runCommand` / `execScript` / `exportFile`. Share runs now honor the+ // visitor's approval flow, so `humanIntervention: 'required'` no longer+ // strips the first two β this list is what keeps them closed until+ // opening skill script execution to visitors is decided on its own+ writeApiNames: SkillsManifest.api+ .map((api) => api.name)+ .filter((apiName) => !AGENT_SHARE_SKILL_API_NAMES.has(apiName)),+ },+};diff --git a/apps/server/src/services/aiAgent/shareGate/dispatch.test.ts b/apps/server/src/services/aiAgent/shareGate/dispatch.test.tsnew file mode 100644index 00000000000..669d767689c--- /dev/null+++ b/apps/server/src/services/aiAgent/shareGate/dispatch.test.ts@@ -0,0 +1,338 @@+import {+ AgentDocumentsApiName,+ AgentDocumentsIdentifier,+} from '@lobechat/builtin-tool-agent-documents';+import { AgentManagementIdentifier } from '@lobechat/builtin-tool-agent-management';+import { CalculatorIdentifier } from '@lobechat/builtin-tool-calculator';+import {+ KnowledgeBaseApiName,+ KnowledgeBaseIdentifier,+} from '@lobechat/builtin-tool-knowledge-base';+import { LobeAgentApiName, LobeAgentIdentifier } from '@lobechat/builtin-tool-lobe-agent';+import { MemoryApiName, MemoryIdentifier } from '@lobechat/builtin-tool-memory';+import { SkillsApiName, SkillsIdentifier } from '@lobechat/builtin-tool-skills';+import { TopicReferenceIdentifier } from '@lobechat/builtin-tool-topic-reference';+import {+ AGENT_SHARE_ALLOWED_BUILTIN_IDENTIFIERS,+ AGENT_SHARE_NO_DATA_GRANT_BUILTIN_IDENTIFIERS,+ builtinTools,+} from '@lobechat/builtin-tools';+import { describe, expect, it } from 'vitest';++import { isShareBlockedBuiltinDispatch, isShareBlockedDataToolCall } from '.';++describe('AGENT_SHARE_ALLOWED_BUILTIN_IDENTIFIERS', () => {+ it('only names identifiers that exist in the real builtin registry', () => {+ const registered = new Set(builtinTools.map((tool) => tool.identifier));++ for (const identifier of AGENT_SHARE_ALLOWED_BUILTIN_IDENTIFIERS) {+ expect(registered.has(identifier), `${identifier} is not a registered builtin`).toBe(true);+ }+ });++ it('does not allowlist the confirmed creator-data leak tools', () => {+ for (const identifier of [+ AgentManagementIdentifier,+ 'lobe-local-system',+ 'lobe-creds',+ 'lobe-task',+ TopicReferenceIdentifier,+ ]) {+ expect(AGENT_SHARE_ALLOWED_BUILTIN_IDENTIFIERS.has(identifier)).toBe(false);+ }+ });++ // `lobe-cloud-sandbox` is allowlisted despite its general-purpose reach: a+ // share visitor's run gets an isolated per-topic sandbox session with no+ // `lh` CLI JWT shim, so it cannot mint or exfiltrate the creator's+ // credentials β see the allowed-builtins section of `README.md`.+ it('allowlists lobe-cloud-sandbox now that visitor runs get a credential-free sandbox session', () => {+ expect(AGENT_SHARE_ALLOWED_BUILTIN_IDENTIFIERS.has('lobe-cloud-sandbox')).toBe(true);+ });++ it('allowlists video generation but still requires the owner grant to dispatch it', () => {+ expect(AGENT_SHARE_ALLOWED_BUILTIN_IDENTIFIERS.has('lobe-video-generation')).toBe(true);+ expect(isShareBlockedBuiltinDispatch({}, 'lobe-video-generation', 'generateVideo')).toBe(true);+ expect(+ isShareBlockedBuiltinDispatch(+ { toolGrants: [{ identifier: 'lobe-video-generation' }] },+ 'lobe-video-generation',+ 'generateVideo',+ ),+ ).toBe(false);+ });+});++/**+ * The owner-facing share settings tool picker renders this set as permanently+ * unavailable. If a grant here is ever relaxed server-side without updating+ * the exported set, the UI would start offering a toggle the gate still+ * ignores β so pin the two together.+ */+describe('AGENT_SHARE_NO_DATA_GRANT_BUILTIN_IDENTIFIERS', () => {+ const maximalPermissions = {+ allowReadMemory: true,+ knowledgeBaseIds: ['kb1'],+ // `lobe-skills` has its own opt-in β the skill list, not `toolGrants` β so+ // "maximal" has to name a skill or the tool reads as unconditionally+ // blocked and lands in this set by accident.+ skillGrants: ['pdf-report'],+ toolGrants: [{ identifier: AgentDocumentsIdentifier }],+ };++ it('names only allowlisted identifiers', () => {+ for (const identifier of AGENT_SHARE_NO_DATA_GRANT_BUILTIN_IDENTIFIERS) {+ expect(AGENT_SHARE_ALLOWED_BUILTIN_IDENTIFIERS.has(identifier)).toBe(true);+ }+ });++ it('matches exactly the allowlisted identifiers blocked under maximal permissions', () => {+ // `readOnlyApiName` stands in for any API: an unconditional `none` grant+ // blocks the identifier before the per-API rules are ever consulted.+ const blockedUnderMaximalPermissions = [...AGENT_SHARE_ALLOWED_BUILTIN_IDENTIFIERS].filter(+ (identifier) => isShareBlockedDataToolCall(maximalPermissions, identifier, 'readOnlyApiName'),+ );++ expect(new Set(blockedUnderMaximalPermissions)).toEqual(+ AGENT_SHARE_NO_DATA_GRANT_BUILTIN_IDENTIFIERS,+ );+ });++ it('excludes memory, whose grant is conditional on allowReadMemory', () => {+ expect(AGENT_SHARE_NO_DATA_GRANT_BUILTIN_IDENTIFIERS.has(MemoryIdentifier)).toBe(false);+ });++ it('excludes Agent Documents, whose grant enables only share-scoped authoring APIs', () => {+ expect(AGENT_SHARE_NO_DATA_GRANT_BUILTIN_IDENTIFIERS.has(AgentDocumentsIdentifier)).toBe(false);+ });+});++describe('isShareBlockedDataToolCall', () => {+ it('lets non-builtin identifiers through untouched', () => {+ expect(isShareBlockedDataToolCall({}, 'mcp-github', 'anything')).toBe(false);+ });++ it('default-denies any builtin outside the allowlist', () => {+ expect(isShareBlockedDataToolCall({}, AgentManagementIdentifier, 'searchAgent')).toBe(true);+ });++ it('allows an allowlisted builtin with no data rule', () => {+ expect(isShareBlockedDataToolCall({}, CalculatorIdentifier, 'calculate')).toBe(false);+ });++ describe('memory', () => {+ it('blocks every api without allowReadMemory', () => {+ expect(isShareBlockedDataToolCall({}, MemoryIdentifier, MemoryApiName.searchUserMemory)).toBe(+ true,+ );+ });++ it('allows reads but never writes with allowReadMemory', () => {+ const permissions = { allowReadMemory: true };++ expect(+ isShareBlockedDataToolCall(permissions, MemoryIdentifier, MemoryApiName.searchUserMemory),+ ).toBe(false);+ expect(+ isShareBlockedDataToolCall(permissions, MemoryIdentifier, MemoryApiName.addContextMemory),+ ).toBe(true);+ });+ });++ it('keeps Agent Documents closed by default, then allows only its scoped authoring APIs', () => {+ expect(+ isShareBlockedDataToolCall({}, AgentDocumentsIdentifier, AgentDocumentsApiName.listDocuments),+ ).toBe(true);++ const permissions = { toolGrants: [{ identifier: AgentDocumentsIdentifier }] };+ for (const apiName of [+ AgentDocumentsApiName.createDocument,+ AgentDocumentsApiName.readDocument,+ AgentDocumentsApiName.listDocuments,+ AgentDocumentsApiName.modifyNodes,+ AgentDocumentsApiName.replaceDocumentContent,+ AgentDocumentsApiName.renameDocument,+ ]) {+ expect(isShareBlockedDataToolCall(permissions, AgentDocumentsIdentifier, apiName)).toBe(+ false,+ );+ }+ for (const apiName of [+ AgentDocumentsApiName.copyDocument,+ AgentDocumentsApiName.removeDocument,+ AgentDocumentsApiName.updateLoadRule,+ ]) {+ expect(isShareBlockedDataToolCall(permissions, AgentDocumentsIdentifier, apiName)).toBe(true);+ }+ });++ it('blocks knowledge base outright (no grant exists)', () => {+ expect(+ isShareBlockedDataToolCall(+ { allowReadMemory: true, knowledgeBaseIds: ['kb1'] },+ KnowledgeBaseIdentifier,+ KnowledgeBaseApiName.viewKnowledgeBase,+ { id: 'kb1' },+ ),+ ).toBe(true);+ });+});++// Dispatch-time full gate, asserted against the REAL manifests: a call that+// bypassed assembly must clear the master allowlist, the owner's+// toolGrants picker, sub-agent dispatch, and the data-tool rules β in that+// order, all fail-closed. `humanIntervention` is not a dispatch rule: the+// runtime parks those calls for the visitor's approval first.+describe('isShareBlockedBuiltinDispatch', () => {+ it('blocks an allowlisted builtin the owner did not enable', () => {+ expect(isShareBlockedBuiltinDispatch({}, CalculatorIdentifier, 'evalExpression')).toBe(true);+ });++ it('passes an enabled builtin with no intervention semantics', () => {+ expect(+ isShareBlockedBuiltinDispatch(+ { toolGrants: [{ identifier: LobeAgentIdentifier }] },+ LobeAgentIdentifier,+ LobeAgentApiName.analyzeMedia,+ ),+ ).toBe(false);+ });++ it('passes an approved intervention-gated API on an enabled tool', () => {+ for (const apiName of [LobeAgentApiName.createPlan, LobeAgentApiName.askUserQuestion]) {+ expect(+ isShareBlockedBuiltinDispatch(+ { toolGrants: [{ identifier: LobeAgentIdentifier }] },+ LobeAgentIdentifier,+ apiName,+ ),+ ).toBe(false);+ }+ });++ it('blocks sub-agent dispatch even on an enabled tool with no intervention config', () => {+ // callSubAgent carries no humanIntervention, so neither the approval+ // flow nor the data-tool rules would catch it β and the child run it+ // spawns does not inherit the parent's shareGate. Must be blocked by its+ // dedicated dispatch rule.+ expect(+ isShareBlockedBuiltinDispatch(+ { toolGrants: [{ identifier: LobeAgentIdentifier }] },+ LobeAgentIdentifier,+ LobeAgentApiName.callSubAgent,+ ),+ ).toBe(true);+ });++ it('still applies the data-tool rules after the enable check', () => {+ const enabled = { toolGrants: [{ identifier: MemoryIdentifier }] };++ expect(+ isShareBlockedBuiltinDispatch(enabled, MemoryIdentifier, MemoryApiName.searchUserMemory),+ ).toBe(true);+ expect(+ isShareBlockedBuiltinDispatch(+ { ...enabled, allowReadMemory: true },+ MemoryIdentifier,+ MemoryApiName.searchUserMemory,+ ),+ ).toBe(false);+ expect(+ isShareBlockedBuiltinDispatch(+ { ...enabled, allowReadMemory: true },+ MemoryIdentifier,+ MemoryApiName.addContextMemory,+ ),+ ).toBe(true);+ });++ it('allows granted Agent Documents authoring APIs but blocks destructive and policy APIs', () => {+ const enabled = { toolGrants: [{ identifier: AgentDocumentsIdentifier }] };++ expect(+ isShareBlockedBuiltinDispatch(+ enabled,+ AgentDocumentsIdentifier,+ AgentDocumentsApiName.createDocument,+ ),+ ).toBe(false);+ expect(+ isShareBlockedBuiltinDispatch(+ enabled,+ AgentDocumentsIdentifier,+ AgentDocumentsApiName.renameDocument,+ ),+ ).toBe(false);+ expect(+ isShareBlockedBuiltinDispatch(+ enabled,+ AgentDocumentsIdentifier,+ AgentDocumentsApiName.removeDocument,+ ),+ ).toBe(true);+ expect(+ isShareBlockedBuiltinDispatch(+ enabled,+ AgentDocumentsIdentifier,+ AgentDocumentsApiName.updateLoadRule,+ ),+ ).toBe(true);+ });++ it('allows the two Skills read APIs but blocks the exec-class and export ones', () => {+ const enabled = { skillGrants: ['pdf-report'] };++ for (const apiName of [SkillsApiName.activateSkill, SkillsApiName.readReference]) {+ expect(isShareBlockedBuiltinDispatch(enabled, SkillsIdentifier, apiName)).toBe(false);+ }+ // runCommand/execScript run arbitrary code on the creator's account and+ // exportFile writes to the creator's file store β all three are phase-2+ // work, gated here rather than merely omitted from the assembled manifest.+ for (const apiName of [+ SkillsApiName.runCommand,+ SkillsApiName.execScript,+ SkillsApiName.exportFile,+ ]) {+ expect(isShareBlockedBuiltinDispatch(enabled, SkillsIdentifier, apiName)).toBe(true);+ }+ });++ it('blocks every Skills API when the owner revoked or never granted a skill', () => {+ // A tool grant is included on purpose: `toolGrants` never authorizes a+ // skill, so it cannot unblock these APIs either.+ for (const permissions of [{}, { skillGrants: [] }, { toolGrants: [{ identifier: 'x' }] }]) {+ expect(+ isShareBlockedBuiltinDispatch(permissions, SkillsIdentifier, SkillsApiName.activateSkill),+ ).toBe(true);+ }+ });++ it('ignores non-builtin identifiers entirely', () => {+ expect(isShareBlockedBuiltinDispatch({}, 'some-mcp-server', 'anything')).toBe(false);+ });++ it('blocks a builtin outside the master allowlist regardless of enablement', () => {+ expect(+ isShareBlockedBuiltinDispatch(+ { toolGrants: [{ identifier: AgentManagementIdentifier }] },+ AgentManagementIdentifier,+ 'searchAgent',+ ),+ ).toBe(true);+ });++ it('a per-API grant grants only the named API, not the whole identifier', () => {+ const enabled = {+ toolGrants: [{ apis: [LobeAgentApiName.analyzeMedia], identifier: LobeAgentIdentifier }],+ };++ expect(+ isShareBlockedBuiltinDispatch(enabled, LobeAgentIdentifier, LobeAgentApiName.analyzeMedia),+ ).toBe(false);+ // updatePlan carries no intervention config either, so only the picker's+ // per-API scoping is what blocks it here.+ expect(+ isShareBlockedBuiltinDispatch(enabled, LobeAgentIdentifier, LobeAgentApiName.updatePlan),+ ).toBe(true);+ });+});diff --git a/apps/server/src/services/aiAgent/shareGate/dispatch.ts b/apps/server/src/services/aiAgent/shareGate/dispatch.tsnew file mode 100644index 00000000000..31d6d5cab41--- /dev/null+++ b/apps/server/src/services/aiAgent/shareGate/dispatch.ts@@ -0,0 +1,109 @@+import { isShareToolApiGranted } from '@lobechat/const';+import type { AgentShareToolGrant } from '@lobechat/types';++import { isGovernedByBuiltinAllowlist, SHARE_VISITOR_ALLOWED_IDENTIFIERS } from './allowlist';+import { DATA_TOOL_ACCESS_RULES } from './dataToolRules';+import { resolveEffectiveShareToolGrants } from './grants';+import { SUB_AGENT_DISPATCH_APIS } from './subAgentDispatch';+import type { ShareDataToolPermissions } from './types';++/**+ * Whether a specific `identifier`/`apiName` tool call must be blocked for a+ * share visitor run. This is the enforcement counterpart of+ * `applyShareGateToDataToolAccess` below, reusable from the actual dispatch+ * chokepoint (`BuiltinToolsExecutor.execute`, which invokes+ * `runtime[apiName](...)` directly and never re-consults the possibly+ * already-trimmed manifest β the trimmed manifest only changes what the model+ * is OFFERED via function-calling schema, not what the executor is willing to+ * run if the model calls it anyway).+ *+ * DEFAULT-DENY for the builtin population: an `identifier` that resolves+ * against the real `@lobechat/builtin-tools` registry+ * (`isGovernedByBuiltinAllowlist`) but is NOT in+ * `SHARE_VISITOR_ALLOWED_IDENTIFIERS` is blocked outright, with no+ * `apiName`-level distinction. A non-builtin identifier (MCP server, market+ * plugin, custom plugin) is NOT this function's concern at all β it falls+ * through to `false` untouched, left entirely to+ * {@link filterPluginsByShareGate} / `shareConfig.toolGrants`.+ *+ * `args` is the tool call's parsed arguments, needed only for+ * `isArgsOutOfScope` rules. Omit it for call sites that only need the+ * identifier/apiName-level check (grant / write / always-blocked).+ */+export const isShareBlockedDataToolCall = (+ permissions: ShareDataToolPermissions,+ identifier: string,+ apiName: string,+ args?: any,+): boolean => {+ // Outside this gate's jurisdiction entirely β MCP/market/custom plugin+ // identifiers are governed by the toolGrants picker, not this allowlist.+ if (!isGovernedByBuiltinAllowlist(identifier)) return false;++ // Default-deny: a known builtin identifier not on the allowlist is blocked+ // unconditionally, including any tool registered after this allowlist was+ // written β the whole point of inverting a denylist.+ if (!SHARE_VISITOR_ALLOWED_IDENTIFIERS.has(identifier)) return true;++ const rule = DATA_TOOL_ACCESS_RULES[identifier];+ if (!rule) return false;++ const grant = rule.grant(permissions);+ if (grant === 'none') return true;++ if (rule.writeApiNames.includes(apiName)) return true;+ if (rule.alwaysBlockedApiNames?.includes(apiName)) return true;+ if (args !== undefined && rule.isArgsOutOfScope?.(permissions, apiName, args)) return true;++ return false;+};++/**+ * FULL dispatch-time gate for a share-visitor builtin tool call β the check+ * `BuiltinToolsExecutor.execute` runs on every call that reaches it. Strictly+ * wider than {@link isShareBlockedDataToolCall}: a call that bypassed+ * assembly (resume path, recovery hint, model-fabricated call to a tool it+ * was never offered) must clear ALL the same gates the assembled tool set+ * enforced, not only the data-tool rules:+ *+ * 1. master default-deny allowlist (`SHARE_VISITOR_ALLOWED_IDENTIFIERS`);+ * 2. the owner's own `toolGrants` picker β being on the master allowlist+ * is necessary but NOT sufficient; a tool the creator never enabled for+ * this share (e.g. image generation spending the creator's quota) must not+ * run just because a call reached the executor;+ * 3. the per-API data-tool rules ({@link isShareBlockedDataToolCall}).+ *+ * Non-builtin identifiers (MCP/market/custom plugins, LobeHub skills) pass+ * through untouched: their id namespace does not reliably match+ * `toolGrants` identifiers, so they remain governed by the assembly-time+ * `filterPluginsByShareGate` intersection only.+ */+export const isShareBlockedBuiltinDispatch = (+ agentShare: ShareDataToolPermissions & { toolGrants?: AgentShareToolGrant[] },+ identifier: string,+ apiName: string,+ args?: any,+): boolean => {+ if (!isGovernedByBuiltinAllowlist(identifier)) return false;++ if (!SHARE_VISITOR_ALLOWED_IDENTIFIERS.has(identifier)) return true;+ // The owner's picker must grant this identifier at all (toolset-level or+ // naming this specific `apiName`) β a grant scoped to a DIFFERENT api on+ // the same identifier does not authorize this call.+ if (!isShareToolApiGranted(resolveEffectiveShareToolGrants(agentShare), identifier, apiName))+ return true;++ // Sub-agent dispatch has no humanIntervention config to catch it, and the+ // server sub-agent runner spawns the child via a plain `execAgent` call+ // that does NOT thread the parent's shareGate β the child would run with+ // the creator's full, unrestricted tool surface. Assembly strips the API+ // (`stripSubAgentDispatchApis`); this is its dispatch-time counterpart.+ if (SUB_AGENT_DISPATCH_APIS[identifier]?.apiName === apiName) return true;++ // `humanIntervention` is deliberately NOT re-checked here: share runs keep+ // the manifest's intervention config and honor the visitor's own approval+ // mode, so an intervention-gated call reaches this executor only after the+ // visitor approved it (or chose auto-run). Granting a tool grants its normal+ // approval flow.+ return isShareBlockedDataToolCall(agentShare, identifier, apiName, args);+};diff --git a/apps/server/src/services/aiAgent/shareGate/grants.test.ts b/apps/server/src/services/aiAgent/shareGate/grants.test.tsnew file mode 100644index 00000000000..41dfed2c426--- /dev/null+++ b/apps/server/src/services/aiAgent/shareGate/grants.test.ts@@ -0,0 +1,123 @@+import { AgentDocumentsIdentifier } from '@lobechat/builtin-tool-agent-documents';+import { CloudSandboxManifest } from '@lobechat/builtin-tool-cloud-sandbox';+import { LobeAgentApiName, LobeAgentIdentifier } from '@lobechat/builtin-tool-lobe-agent';+import { describe, expect, it } from 'vitest';++import {+ applyShareGateToAgentConfig,+ filterPluginsByShareGate,+ filterSkillsByShareGate,+ getShareGrantActivatedPluginIds,+ shareGateGrantsCloudSandbox,+} from '.';+import { buildGate } from './testUtils';++describe('filterPluginsByShareGate', () => {+ it('keeps only allowlisted plugin ids', () => {+ const gate = buildGate({+ toolGrants: [{ identifier: 'web-search' }, { identifier: 'mcp-github' }],+ });++ expect(filterPluginsByShareGate(['web-search', 'local-system', 'mcp-github'], gate)).toEqual([+ 'web-search',+ 'mcp-github',+ ]);+ });++ it('exposes no tools when the allowlist is missing or empty', () => {+ expect(filterPluginsByShareGate(['web-search'], buildGate())).toEqual([]);+ expect(filterPluginsByShareGate(['web-search'], buildGate({ toolGrants: [] }))).toEqual([]);+ });++ it('treats a per-API grant as candidacy for the whole identifier', () => {+ // Narrowing down to the specific granted API happens later, in+ // `applyShareGateToToolSet`, once the real manifest is known β this pass+ // only decides whether the identifier is a candidate at all.+ const gate = buildGate({+ toolGrants: [{ apis: [LobeAgentApiName.analyzeMedia], identifier: LobeAgentIdentifier }],+ });++ expect(filterPluginsByShareGate([LobeAgentIdentifier, 'mcp-github'], gate)).toEqual([+ LobeAgentIdentifier,+ ]);+ });+});++describe('filterSkillsByShareGate', () => {+ it('keeps only the skills the creator named', () => {+ const gate = buildGate({ skillGrants: ['pdf-report', 'brand-voice'] });++ expect(filterSkillsByShareGate(['pdf-report', 'internal-audit', 'brand-voice'], gate)).toEqual([+ 'pdf-report',+ 'brand-voice',+ ]);+ });++ it('cannot turn an ordinary tool grant into a skill grant', () => {+ // `toolGrants` is never read as a skill list. Tool and skill ids share one+ // namespace, so a tool grant that happens to name a real skill id must not+ // widen the skill pool either.+ const gate = buildGate({ toolGrants: [{ identifier: 'pdf-report' }] });++ expect(filterSkillsByShareGate(['pdf-report'], gate)).toEqual([]);+ });++ it('exposes no skills when the share grants nothing at all', () => {+ expect(filterSkillsByShareGate(['pdf-report'], buildGate())).toEqual([]);+ expect(filterSkillsByShareGate(['pdf-report'], buildGate({ skillGrants: [] }))).toEqual([]);+ });+});++describe('getShareGrantActivatedPluginIds', () => {+ it('activates Agent Documents only after the owner grants it for this Share', () => {+ expect(getShareGrantActivatedPluginIds(buildGate())).toEqual([]);+ expect(+ getShareGrantActivatedPluginIds(+ buildGate({ toolGrants: [{ identifier: AgentDocumentsIdentifier }] }),+ ),+ ).toEqual([AgentDocumentsIdentifier]);+ });+});++describe('applyShareGateToAgentConfig', () => {+ it('always strips files and knowledge bases', () => {+ const agentConfig = {+ files: [{ enabled: true, id: 'f1' }],+ knowledgeBases: [{ enabled: true, id: 'kb1' }],+ };++ applyShareGateToAgentConfig(agentConfig);++ expect(agentConfig.files).toEqual([]);+ expect(agentConfig.knowledgeBases).toEqual([]);+ });+});++describe('shareGateGrantsCloudSandbox', () => {+ it('is false when the share does not grant lobe-cloud-sandbox', () => {+ expect(shareGateGrantsCloudSandbox(buildGate())).toBe(false);+ expect(+ shareGateGrantsCloudSandbox(buildGate({ toolGrants: [{ identifier: 'web-search' }] })),+ ).toBe(false);+ });++ it('is true for a whole-identifier grant', () => {+ expect(+ shareGateGrantsCloudSandbox(+ buildGate({ toolGrants: [{ identifier: CloudSandboxManifest.identifier }] }),+ ),+ ).toBe(true);+ });++ // The plan only needs to know the sandbox is in play at all β narrowing to+ // the granted APIs happens later in `applyShareGateToToolSet`.+ it('treats an apis-scoped grant as a grant of the identifier', () => {+ expect(+ shareGateGrantsCloudSandbox(+ buildGate({+ toolGrants: [{ apis: ['runCommand'], identifier: CloudSandboxManifest.identifier }],+ }),+ ),+ ).toBe(true);+ });+});diff --git a/apps/server/src/services/aiAgent/shareGate/grants.ts b/apps/server/src/services/aiAgent/shareGate/grants.tsnew file mode 100644index 00000000000..589e73227a0--- /dev/null+++ b/apps/server/src/services/aiAgent/shareGate/grants.ts@@ -0,0 +1,125 @@+import { AgentDocumentsIdentifier } from '@lobechat/builtin-tool-agent-documents';+import { CloudSandboxManifest } from '@lobechat/builtin-tool-cloud-sandbox';+import { SkillsIdentifier } from '@lobechat/builtin-tool-skills';+import {+ hasShareToolGrant,+ resolveShareAllowedSkillIds,+ resolveShareToolGrants,+ type ShareToolGrant,+} from '@lobechat/const';++import type { AgentShareGate, ShareDataToolPermissions } from './types';++/**+ * Intersect a run's candidate plugin/skill ids with the share whitelist.+ * The whitelist defaults to empty, so an unconfigured share exposes no tools.+ *+ * Identifier-level only: an entry granting just one API+ * (`{ identifier: 'lobe-agent', apis: ['analyzeMedia'] }`) still counts as+ * "this identifier is a+ * candidate" here β narrowing the offer down to that specific API happens+ * later, in {@link applyShareGateToToolSet}, once the real manifest is known.+ */+export const filterPluginsByShareGate = (pluginIds: string[], gate: AgentShareGate): string[] => {+ const grants = resolveShareToolGrants(gate.shareConfig.toolGrants);++ return pluginIds.filter((id) => hasShareToolGrant(grants, id));+};++/**+ * Intersect a run's candidate SKILL ids with the share's skill grants.+ *+ * Skills are governed by `shareConfig.skillGrants`, not `toolGrants`: a skill+ * grant also authorizes the no-tool path (a pinned skill's body is injected+ * straight into context), so it cannot be expressed as a grant on the+ * `lobe-skills` tool entry. See {@link resolveShareAllowedSkillIds} for the+ * default-closed semantics.+ *+ * Kept next to {@link filterPluginsByShareGate} so the two read as the pair+ * they are; callers must not use the plugin filter for skill ids.+ */+export const filterSkillsByShareGate = (skillIds: string[], gate: AgentShareGate): string[] =>+ resolveShareAllowedSkillIds(skillIds, gate.shareConfig);++/**+ * Builtins whose Share grant is also their runtime opt-in.+ *+ * Agent Documents is a default activatable builtin rather than a profile+ * plugin, so creators have no separate profile switch that could place it in+ * `agentConfig.plugins`. Adding it here only after an explicit Share grant+ * lets the picker act as that opt-in for visitor runs while keeping the+ * default-closed behavior. The final tool-set gate still narrows its APIs.+ */+export const getShareGrantActivatedPluginIds = (gate: AgentShareGate): string[] => {+ const grants = resolveShareToolGrants(gate.shareConfig.toolGrants);++ return hasShareToolGrant(grants, AgentDocumentsIdentifier) ? [AgentDocumentsIdentifier] : [];+};++/**+ * Whether the share grants `lobe-cloud-sandbox` (at any API scope). Drives+ * `resolveExecutionPlan`'s `sandboxFallback`: a visitor can never reach the+ * creator's device, so this grant is only meaningful if the plan resolves to+ * the sandbox instead of collapsing to `none`.+ */+export const shareGateGrantsCloudSandbox = (gate: AgentShareGate): boolean =>+ hasShareToolGrant(+ resolveShareToolGrants(gate.shareConfig.toolGrants),+ CloudSandboxManifest.identifier,+ );++/**+ * Strip agent files / knowledge bases from a share visitor's resolved agent+ * config. Mutates in place β `agentConfig` is threaded through the whole+ * orchestration by reference (tool discovery, knowledge flags, context builder+ * snapshot), so a filtered copy would silently diverge.+ *+ * ADAPTATION vs the original design: the share config no longer carries a+ * `filePermissionConfig` field, so there is no grant a creator could set that+ * would expose their agent files or knowledge bases to a visitor. The gate is+ * therefore unconditional rather than conditional β the fail-closed reading of+ * "no configured permission". Re-introducing a file grant means restoring the+ * config field AND relaxing this function together.+ */+export const applyShareGateToAgentConfig = (agentConfig: {+ files?: unknown[] | null;+ knowledgeBases?: unknown[] | null;+}): void => {+ agentConfig.files = [];+ agentConfig.knowledgeBases = [];+};++/**+ * Whether this share authorizes any skill at all β the condition under which+ * the `lobe-skills` tool itself becomes available to a visitor.+ *+ * Skills are NOT picked in the tool picker, so no creator ever writes a+ * `lobe-skills` entry into `toolGrants`; the skill list IS the opt-in, the same+ * way {@link getShareGrantActivatedPluginIds} lets the Documents grant double as+ * that tool's runtime opt-in. Without this, a share could list skills the+ * visitor's model has no tool to load.+ */+export const hasShareSkillAuthorization = (permissions: ShareDataToolPermissions): boolean =>+ (permissions.skillGrants?.length ?? 0) > 0;++/**+ * `resolveShareToolGrants` plus the grants that are implied rather than picked.+ *+ * Today that is only `lobe-skills`, whose opt-in lives in `skillGrants` (see+ * {@link hasShareSkillAuthorization}). The synthetic grant is toolset-level+ * (`'all'`) on purpose: narrowing the Skills tool down to its two visitor-safe+ * APIs is {@link DATA_TOOL_ACCESS_RULES}' job, and expressing it twice would+ * let the two lists drift.+ *+ * Every gate that asks "did the creator grant this identifier" must go through+ * here, or the tool passes one layer and is rejected by the next.+ */+export const resolveEffectiveShareToolGrants = (+ permissions: ShareDataToolPermissions,+): Map<string, ShareToolGrant> => {+ const grants = resolveShareToolGrants(permissions.toolGrants);++ if (hasShareSkillAuthorization(permissions)) grants.set(SkillsIdentifier, 'all');++ return grants;+};diff --git a/apps/server/src/services/aiAgent/shareGate/index.ts b/apps/server/src/services/aiAgent/shareGate/index.tsnew file mode 100644index 00000000000..165827da2d4--- /dev/null+++ b/apps/server/src/services/aiAgent/shareGate/index.ts@@ -0,0 +1,10 @@+export { isShareBlockedBuiltinDispatch, isShareBlockedDataToolCall } from './dispatch';+export {+ applyShareGateToAgentConfig,+ filterPluginsByShareGate,+ filterSkillsByShareGate,+ getShareGrantActivatedPluginIds,+ shareGateGrantsCloudSandbox,+} from './grants';+export { applyShareGateToToolSet } from './toolSet';+export type { AgentShareGate, ShareDataToolPermissions, ShareGateToolSet } from './types';diff --git a/apps/server/src/services/aiAgent/shareGate/subAgentDispatch.ts b/apps/server/src/services/aiAgent/shareGate/subAgentDispatch.tsnew file mode 100644index 00000000000..bb76ed50da8--- /dev/null+++ b/apps/server/src/services/aiAgent/shareGate/subAgentDispatch.ts@@ -0,0 +1,57 @@+import {+ LobeAgentApiName,+ LobeAgentIdentifier,+ systemPromptWithoutSubAgent,+} from '@lobechat/builtin-tool-lobe-agent';+import { PLUGIN_SCHEMA_SEPARATOR } from '@lobechat/const';++import { pruneArrayInPlace } from './toolSetMutation';+import type { ShareGateToolSet } from './types';++/**+ * Sub-agent dispatch is not available in shared visitor runs. This strip runs+ * unconditionally on `lobe-agent`, independent of whether the manifest was+ * resolved through the normal context-aware path, so a whitelisted entry can+ * never surface `callSubAgent` β nor a `systemRole` that instructs the model+ * to call it β to a share visitor's model or the activator. `lobe-agent`+ * already ships a precise systemRole variant without the dispatch section+ * (`systemPromptWithoutSubAgent`, also used by its own context-aware+ * `resolveManifest`).+ *+ * `lobe-agent-management`'s dispatch API (`callAgent`) does NOT need an entry+ * here: the whole tool β dispatch included β is simply absent from+ * `SHARE_VISITOR_ALLOWED_IDENTIFIERS`, so it never survives that gate.+ */+export const SUB_AGENT_DISPATCH_APIS: Record<+ string,+ { apiName: string; systemRoleWithoutDispatch: string }+> = {+ [LobeAgentIdentifier]: {+ apiName: LobeAgentApiName.callSubAgent,+ systemRoleWithoutDispatch: systemPromptWithoutSubAgent,+ },+};++export const stripSubAgentDispatchApis = (toolSet: ShareGateToolSet): void => {+ for (const [identifier, { apiName, systemRoleWithoutDispatch }] of Object.entries(+ SUB_AGENT_DISPATCH_APIS,+ )) {+ const manifest = toolSet.manifestMap[identifier];+ if (manifest) {+ // Always pin the sanitized `systemRole`, not only when `api` still+ // carries the dispatch entry β an already context-aware-trimmed manifest+ // (api filtered upstream) could otherwise keep a stale `systemRole` that+ // still instructs the model to call the removed tool.+ toolSet.manifestMap[identifier] = {+ ...manifest,+ api: manifest.api.filter((api) => api.name !== apiName),+ systemRole: systemRoleWithoutDispatch,+ };+ }++ if (toolSet.tools) {+ const dispatchToolName = `${identifier}${PLUGIN_SCHEMA_SEPARATOR}${apiName}`;+ pruneArrayInPlace(toolSet.tools, (tool) => tool?.function?.name !== dispatchToolName);+ }+ }+};diff --git a/apps/server/src/services/aiAgent/shareGate/testUtils.ts b/apps/server/src/services/aiAgent/shareGate/testUtils.tsnew file mode 100644index 00000000000..dfb4103436e--- /dev/null+++ b/apps/server/src/services/aiAgent/shareGate/testUtils.ts@@ -0,0 +1,74 @@+import { ToolNameResolver } from '@lobechat/context-engine';++import type { AgentShareGate, ShareGateToolSet } from '.';++export const buildGate = (config: Partial<AgentShareGate['shareConfig']> = {}): AgentShareGate => ({+ agentId: 'agent-1',+ shareConfig: {+ maxTopicsPerVisitor: 5,+ maxTurnsPerTopic: 20,+ ...config,+ },+ shareId: 'share-1',+ visitorUserId: 'visitor-1',+});++/**+ * Go through the REAL `ToolNameResolver` β the same class the share gate and+ * `ToolsEngine` use β instead of hand-concatenating `identifier____apiName`.+ * A hand-built string only matches what the resolver actually produces when+ * neither segment needs normalizing; it silently diverges for a `type` other+ * than `builtin`/`default` (an extra `____<type>` segment) or for an+ * api/identifier name the resolver MD5-hashes (invalid characters, or long+ * enough to hit the provider name-length cap). Using the real resolver here+ * is what makes the MCP-manifest and long-name tests below fail against a+ * naive slice-based strip instead of staying false-green.+ */+const toolNameResolver = new ToolNameResolver();+export const toolName = (identifier: string, apiName: string, type: string = 'builtin') =>+ toolNameResolver.generate(identifier, apiName, type);++/**+ * Build a tool set whose parallel structures (manifests, maps, id arrays and+ * the function-calling `tools` schema) are all consistent, so an assertion can+ * check that a strip touched EVERY structure rather than just the manifest.+ */+export const buildToolSet = (+ entries: Array<{+ apis: Array<{ humanIntervention?: unknown; name: string }>;+ identifier: string;+ type?: string;+ }>,+): ShareGateToolSet => {+ const toolSet: ShareGateToolSet = {+ activatableToolIds: entries.map((entry) => entry.identifier),+ enabledToolIds: entries.map((entry) => entry.identifier),+ executorMap: {},+ manifestMap: {},+ sourceMap: {},+ tools: [],+ };++ for (const { apis, identifier, type = 'builtin' } of entries) {+ toolSet.manifestMap[identifier] = {+ api: apis.map((api) => ({+ description: api.name,+ humanIntervention: api.humanIntervention,+ name: api.name,+ parameters: { properties: {}, type: 'object' },+ })),+ identifier,+ type,+ } as any;+ toolSet.sourceMap[identifier] = 'builtin' as any;+ toolSet.executorMap[identifier] = {} as any;+ for (const api of apis) {+ toolSet.tools!.push({+ function: { name: toolName(identifier, api.name, type) },+ type: 'function',+ });+ }+ }++ return toolSet;+};diff --git a/apps/server/src/services/aiAgent/shareGate.test.ts b/apps/server/src/services/aiAgent/shareGate/toolSet.test.tssimilarity index 55%rename from apps/server/src/services/aiAgent/shareGate.test.tsrename to apps/server/src/services/aiAgent/shareGate/toolSet.test.tsindex 789c84cf3c8..4e9e9e80332 100644--- a/apps/server/src/services/aiAgent/shareGate.test.ts+++ b/apps/server/src/services/aiAgent/shareGate/toolSet.test.ts@@ -6,11 +6,6 @@ import {} from '@lobechat/builtin-tool-agent-documents';import { AgentManagementIdentifier } from '@lobechat/builtin-tool-agent-management';import { CalculatorIdentifier } from '@lobechat/builtin-tool-calculator';-import { CloudSandboxManifest } from '@lobechat/builtin-tool-cloud-sandbox';-import {- KnowledgeBaseApiName,- KnowledgeBaseIdentifier,-} from '@lobechat/builtin-tool-knowledge-base';import {LobeAgentApiName,LobeAgentIdentifier,@@ -28,335 +23,11 @@ import {SkillsManifest,} from '@lobechat/builtin-tool-skills';import { TopicReferenceIdentifier } from '@lobechat/builtin-tool-topic-reference';-import {- AGENT_SHARE_ALLOWED_BUILTIN_IDENTIFIERS,- AGENT_SHARE_NO_DATA_GRANT_BUILTIN_IDENTIFIERS,- builtinTools,-} from '@lobechat/builtin-tools';-import { generateToolsFromManifest, ToolNameResolver } from '@lobechat/context-engine';+import { generateToolsFromManifest } from '@lobechat/context-engine';import { describe, expect, it } from 'vitest';-import type { AgentShareGate, ShareGateToolSet } from './shareGate';-import {- applyShareGateToAgentConfig,- applyShareGateToToolSet,- filterPluginsByShareGate,- filterSkillsByShareGate,- getShareGrantActivatedPluginIds,- isShareBlockedBuiltinDispatch,- isShareBlockedDataToolCall,- shareGateGrantsCloudSandbox,-} from './shareGate';--const buildGate = (config: Partial<AgentShareGate['shareConfig']> = {}): AgentShareGate => ({- agentId: 'agent-1',- shareConfig: {- maxTopicsPerVisitor: 5,- maxTurnsPerTopic: 20,- ...config,- },- shareId: 'share-1',- visitorUserId: 'visitor-1',-});--/**- * Go through the REAL `ToolNameResolver` β the same class `shareGate.ts` and- * `ToolsEngine` use β instead of hand-concatenating `identifier____apiName`.- * A hand-built string only matches what the resolver actually produces when- * neither segment needs normalizing; it silently diverges for a `type` other- * than `builtin`/`default` (an extra `____<type>` segment) or for an- * api/identifier name the resolver MD5-hashes (invalid characters, or long- * enough to hit the provider name-length cap). Using the real resolver here- * is what makes the MCP-manifest and long-name tests below fail against a- * naive slice-based strip instead of staying false-green.- */-const toolNameResolver = new ToolNameResolver();-const toolName = (identifier: string, apiName: string, type: string = 'builtin') =>- toolNameResolver.generate(identifier, apiName, type);--/**- * Build a tool set whose parallel structures (manifests, maps, id arrays and- * the function-calling `tools` schema) are all consistent, so an assertion can- * check that a strip touched EVERY structure rather than just the manifest.- */-const buildToolSet = (- entries: Array<{- apis: Array<{ humanIntervention?: unknown; name: string }>;- identifier: string;- type?: string;- }>,-): ShareGateToolSet => {- const toolSet: ShareGateToolSet = {- activatableToolIds: entries.map((entry) => entry.identifier),- enabledToolIds: entries.map((entry) => entry.identifier),- executorMap: {},- manifestMap: {},- sourceMap: {},- tools: [],- };-- for (const { apis, identifier, type = 'builtin' } of entries) {- toolSet.manifestMap[identifier] = {- api: apis.map((api) => ({- description: api.name,- humanIntervention: api.humanIntervention,- name: api.name,- parameters: { properties: {}, type: 'object' },- })),- identifier,- type,- } as any;- toolSet.sourceMap[identifier] = 'builtin' as any;- toolSet.executorMap[identifier] = {} as any;- for (const api of apis) {- toolSet.tools!.push({- function: { name: toolName(identifier, api.name, type) },- type: 'function',- });- }- }-- return toolSet;-};--describe('filterPluginsByShareGate', () => {- it('keeps only allowlisted plugin ids', () => {- const gate = buildGate({- toolGrants: [{ identifier: 'web-search' }, { identifier: 'mcp-github' }],- });-- expect(filterPluginsByShareGate(['web-search', 'local-system', 'mcp-github'], gate)).toEqual([- 'web-search',- 'mcp-github',- ]);- });-- it('exposes no tools when the allowlist is missing or empty', () => {- expect(filterPluginsByShareGate(['web-search'], buildGate())).toEqual([]);- expect(filterPluginsByShareGate(['web-search'], buildGate({ toolGrants: [] }))).toEqual([]);- });-- it('treats a per-API grant as candidacy for the whole identifier', () => {- // Narrowing down to the specific granted API happens later, in- // `applyShareGateToToolSet`, once the real manifest is known β this pass- // only decides whether the identifier is a candidate at all.- const gate = buildGate({- toolGrants: [{ apis: [LobeAgentApiName.analyzeMedia], identifier: LobeAgentIdentifier }],- });-- expect(filterPluginsByShareGate([LobeAgentIdentifier, 'mcp-github'], gate)).toEqual([- LobeAgentIdentifier,- ]);- });-});--describe('filterSkillsByShareGate', () => {- it('keeps only the skills the creator named', () => {- const gate = buildGate({ skillGrants: ['pdf-report', 'brand-voice'] });-- expect(filterSkillsByShareGate(['pdf-report', 'internal-audit', 'brand-voice'], gate)).toEqual([- 'pdf-report',- 'brand-voice',- ]);- });-- it('cannot turn an ordinary tool grant into a skill grant', () => {- // `toolGrants` is never read as a skill list. Tool and skill ids share one- // namespace, so a tool grant that happens to name a real skill id must not- // widen the skill pool either.- const gate = buildGate({ toolGrants: [{ identifier: 'pdf-report' }] });-- expect(filterSkillsByShareGate(['pdf-report'], gate)).toEqual([]);- });-- it('exposes no skills when the share grants nothing at all', () => {- expect(filterSkillsByShareGate(['pdf-report'], buildGate())).toEqual([]);- expect(filterSkillsByShareGate(['pdf-report'], buildGate({ skillGrants: [] }))).toEqual([]);- });-});--describe('getShareGrantActivatedPluginIds', () => {- it('activates Agent Documents only after the owner grants it for this Share', () => {- expect(getShareGrantActivatedPluginIds(buildGate())).toEqual([]);- expect(- getShareGrantActivatedPluginIds(- buildGate({ toolGrants: [{ identifier: AgentDocumentsIdentifier }] }),- ),- ).toEqual([AgentDocumentsIdentifier]);- });-});--describe('applyShareGateToAgentConfig', () => {- it('always strips files and knowledge bases', () => {- const agentConfig = {- files: [{ enabled: true, id: 'f1' }],- knowledgeBases: [{ enabled: true, id: 'kb1' }],- };-- applyShareGateToAgentConfig(agentConfig);-- expect(agentConfig.files).toEqual([]);- expect(agentConfig.knowledgeBases).toEqual([]);- });-});--describe('AGENT_SHARE_ALLOWED_BUILTIN_IDENTIFIERS', () => {- it('only names identifiers that exist in the real builtin registry', () => {- const registered = new Set(builtinTools.map((tool) => tool.identifier));-- for (const identifier of AGENT_SHARE_ALLOWED_BUILTIN_IDENTIFIERS) {- expect(registered.has(identifier), `${identifier} is not a registered builtin`).toBe(true);- }- });-- it('does not allowlist the confirmed creator-data leak tools', () => {- for (const identifier of [- AgentManagementIdentifier,- 'lobe-local-system',- 'lobe-creds',- 'lobe-task',- TopicReferenceIdentifier,- ]) {- expect(AGENT_SHARE_ALLOWED_BUILTIN_IDENTIFIERS.has(identifier)).toBe(false);- }- });-- // `lobe-cloud-sandbox` is allowlisted despite its general-purpose reach: a- // share visitor's run gets an isolated per-topic sandbox session with no- // `lh` CLI JWT shim, so it cannot mint or exfiltrate the creator's- // credentials β see the positive-evidence doc block above- // `AGENT_SHARE_ALLOWED_BUILTIN_IDENTIFIERS` in `shareGate.ts`.- it('allowlists lobe-cloud-sandbox now that visitor runs get a credential-free sandbox session', () => {- expect(AGENT_SHARE_ALLOWED_BUILTIN_IDENTIFIERS.has('lobe-cloud-sandbox')).toBe(true);- });-- it('allowlists video generation but still requires the owner grant to dispatch it', () => {- expect(AGENT_SHARE_ALLOWED_BUILTIN_IDENTIFIERS.has('lobe-video-generation')).toBe(true);- expect(isShareBlockedBuiltinDispatch({}, 'lobe-video-generation', 'generateVideo')).toBe(true);- expect(- isShareBlockedBuiltinDispatch(- { toolGrants: [{ identifier: 'lobe-video-generation' }] },- 'lobe-video-generation',- 'generateVideo',- ),- ).toBe(false);- });-});--/**- * The owner-facing share settings tool picker renders this set as permanently- * unavailable. If a grant here is ever relaxed server-side without updating- * the exported set, the UI would start offering a toggle the gate still- * ignores β so pin the two together.- */-describe('AGENT_SHARE_NO_DATA_GRANT_BUILTIN_IDENTIFIERS', () => {- const maximalPermissions = {- allowReadMemory: true,- knowledgeBaseIds: ['kb1'],- // `lobe-skills` has its own opt-in β the skill list, not `toolGrants` β so- // "maximal" has to name a skill or the tool reads as unconditionally- // blocked and lands in this set by accident.- skillGrants: ['pdf-report'],- toolGrants: [{ identifier: AgentDocumentsIdentifier }],- };-- it('names only allowlisted identifiers', () => {- for (const identifier of AGENT_SHARE_NO_DATA_GRANT_BUILTIN_IDENTIFIERS) {- expect(AGENT_SHARE_ALLOWED_BUILTIN_IDENTIFIERS.has(identifier)).toBe(true);- }- });-- it('matches exactly the allowlisted identifiers blocked under maximal permissions', () => {- // `readOnlyApiName` stands in for any API: an unconditional `none` grant- // blocks the identifier before the per-API rules are ever consulted.- const blockedUnderMaximalPermissions = [...AGENT_SHARE_ALLOWED_BUILTIN_IDENTIFIERS].filter(- (identifier) => isShareBlockedDataToolCall(maximalPermissions, identifier, 'readOnlyApiName'),- );-- expect(new Set(blockedUnderMaximalPermissions)).toEqual(- AGENT_SHARE_NO_DATA_GRANT_BUILTIN_IDENTIFIERS,- );- });-- it('excludes memory, whose grant is conditional on allowReadMemory', () => {- expect(AGENT_SHARE_NO_DATA_GRANT_BUILTIN_IDENTIFIERS.has(MemoryIdentifier)).toBe(false);- });-- it('excludes Agent Documents, whose grant enables only share-scoped authoring APIs', () => {- expect(AGENT_SHARE_NO_DATA_GRANT_BUILTIN_IDENTIFIERS.has(AgentDocumentsIdentifier)).toBe(false);- });-});--describe('isShareBlockedDataToolCall', () => {- it('lets non-builtin identifiers through untouched', () => {- expect(isShareBlockedDataToolCall({}, 'mcp-github', 'anything')).toBe(false);- });-- it('default-denies any builtin outside the allowlist', () => {- expect(isShareBlockedDataToolCall({}, AgentManagementIdentifier, 'searchAgent')).toBe(true);- });-- it('allows an allowlisted builtin with no data rule', () => {- expect(isShareBlockedDataToolCall({}, CalculatorIdentifier, 'calculate')).toBe(false);- });-- describe('memory', () => {- it('blocks every api without allowReadMemory', () => {- expect(isShareBlockedDataToolCall({}, MemoryIdentifier, MemoryApiName.searchUserMemory)).toBe(- true,- );- });-- it('allows reads but never writes with allowReadMemory', () => {- const permissions = { allowReadMemory: true };-- expect(- isShareBlockedDataToolCall(permissions, MemoryIdentifier, MemoryApiName.searchUserMemory),- ).toBe(false);- expect(- isShareBlockedDataToolCall(permissions, MemoryIdentifier, MemoryApiName.addContextMemory),- ).toBe(true);- });- });-- it('keeps Agent Documents closed by default, then allows only its scoped authoring APIs', () => {- expect(- isShareBlockedDataToolCall({}, AgentDocumentsIdentifier, AgentDocumentsApiName.listDocuments),- ).toBe(true);-- const permissions = { toolGrants: [{ identifier: AgentDocumentsIdentifier }] };- for (const apiName of [- AgentDocumentsApiName.createDocument,- AgentDocumentsApiName.readDocument,- AgentDocumentsApiName.listDocuments,- AgentDocumentsApiName.modifyNodes,- AgentDocumentsApiName.replaceDocumentContent,- AgentDocumentsApiName.renameDocument,- ]) {- expect(isShareBlockedDataToolCall(permissions, AgentDocumentsIdentifier, apiName)).toBe(- false,- );- }- for (const apiName of [- AgentDocumentsApiName.copyDocument,- AgentDocumentsApiName.removeDocument,- AgentDocumentsApiName.updateLoadRule,- ]) {- expect(isShareBlockedDataToolCall(permissions, AgentDocumentsIdentifier, apiName)).toBe(true);- }- });-- it('blocks knowledge base outright (no grant exists)', () => {- expect(- isShareBlockedDataToolCall(- { allowReadMemory: true, knowledgeBaseIds: ['kb1'] },- KnowledgeBaseIdentifier,- KnowledgeBaseApiName.viewKnowledgeBase,- { id: 'kb1' },- ),- ).toBe(true);- });-});+import { applyShareGateToToolSet } from '.';+import { buildGate, buildToolSet, toolName } from './testUtils';describe('applyShareGateToToolSet', () => {it('drops everything the owner picker did not enable', () => {@@ -423,6 +94,50 @@ describe('applyShareGateToToolSet', () => {expect(toolSet.manifestMap['mcp-github'].systemRole).toBe('Use run for repository operations.');});+ it('drops a granted MCP server that only the creator machine can reach', () => {+ const toolSet = buildToolSet([+ { apis: [{ name: 'read_file' }], identifier: 'mcp-fs', type: 'mcp' },+ { apis: [{ name: 'query' }], identifier: 'mcp-lan', type: 'mcp' },+ { apis: [{ name: 'run' }], identifier: 'mcp-remote', type: 'mcp' },+ ]);+ (toolSet.manifestMap['mcp-fs'] as any).mcpParams = {+ args: [],+ command: 'npx',+ name: 'mcp-fs',+ type: 'stdio',+ };+ (toolSet.manifestMap['mcp-lan'] as any).mcpParams = {+ name: 'mcp-lan',+ type: 'http',+ url: 'http://192.168.1.20:8000/mcp',+ };+ (toolSet.manifestMap['mcp-remote'] as any).mcpParams = {+ name: 'mcp-remote',+ type: 'http',+ url: 'https://mcp.example.com/mcp',+ };+ toolSet.executorMap['mcp-fs'] = 'client';++ applyShareGateToToolSet(+ toolSet,+ buildGate({+ toolGrants: [+ { identifier: 'mcp-fs' },+ { identifier: 'mcp-lan' },+ { identifier: 'mcp-remote' },+ ],+ }),+ );++ expect(toolSet.enabledToolIds).toEqual(['mcp-remote']);+ expect(toolSet.activatableToolIds).toEqual(['mcp-remote']);+ expect(Object.keys(toolSet.manifestMap)).toEqual(['mcp-remote']);+ expect(toolSet.executorMap).not.toHaveProperty('mcp-fs');+ expect(toolSet.tools!.map((tool) => tool.function.name)).toEqual([+ toolName('mcp-remote', 'run', 'mcp'),+ ]);+ });+it('collapses the whole set when no tools are enabled', () => {const toolSet = buildToolSet([{ apis: [{ name: 'calculate' }], identifier: CalculatorIdentifier },@@ -914,191 +629,3 @@ describe('applyShareGateToToolSet', () => {]);});});--// Dispatch-time full gate, asserted against the REAL manifests: a call that-// bypassed assembly must clear the master allowlist, the owner's-// toolGrants picker, sub-agent dispatch, and the data-tool rules β in that-// order, all fail-closed. `humanIntervention` is not a dispatch rule: the-// runtime parks those calls for the visitor's approval first.-describe('isShareBlockedBuiltinDispatch', () => {- it('blocks an allowlisted builtin the owner did not enable', () => {- expect(isShareBlockedBuiltinDispatch({}, CalculatorIdentifier, 'evalExpression')).toBe(true);- });-- it('passes an enabled builtin with no intervention semantics', () => {- expect(- isShareBlockedBuiltinDispatch(- { toolGrants: [{ identifier: LobeAgentIdentifier }] },- LobeAgentIdentifier,- LobeAgentApiName.analyzeMedia,- ),- ).toBe(false);- });-- it('passes an approved intervention-gated API on an enabled tool', () => {- for (const apiName of [LobeAgentApiName.createPlan, LobeAgentApiName.askUserQuestion]) {- expect(- isShareBlockedBuiltinDispatch(- { toolGrants: [{ identifier: LobeAgentIdentifier }] },- LobeAgentIdentifier,- apiName,- ),- ).toBe(false);- }- });-- it('blocks sub-agent dispatch even on an enabled tool with no intervention config', () => {- // callSubAgent carries no humanIntervention, so neither the approval- // flow nor the data-tool rules would catch it β and the child run it- // spawns does not inherit the parent's shareGate. Must be blocked by its- // dedicated dispatch rule.- expect(- isShareBlockedBuiltinDispatch(- { toolGrants: [{ identifier: LobeAgentIdentifier }] },- LobeAgentIdentifier,- LobeAgentApiName.callSubAgent,- ),- ).toBe(true);- });-- it('still applies the data-tool rules after the enable check', () => {- const enabled = { toolGrants: [{ identifier: MemoryIdentifier }] };-- expect(- isShareBlockedBuiltinDispatch(enabled, MemoryIdentifier, MemoryApiName.searchUserMemory),- ).toBe(true);- expect(- isShareBlockedBuiltinDispatch(- { ...enabled, allowReadMemory: true },- MemoryIdentifier,- MemoryApiName.searchUserMemory,- ),- ).toBe(false);- expect(- isShareBlockedBuiltinDispatch(- { ...enabled, allowReadMemory: true },- MemoryIdentifier,- MemoryApiName.addContextMemory,- ),- ).toBe(true);- });-- it('allows granted Agent Documents authoring APIs but blocks destructive and policy APIs', () => {- const enabled = { toolGrants: [{ identifier: AgentDocumentsIdentifier }] };-- expect(- isShareBlockedBuiltinDispatch(- enabled,- AgentDocumentsIdentifier,- AgentDocumentsApiName.createDocument,- ),- ).toBe(false);- expect(- isShareBlockedBuiltinDispatch(- enabled,- AgentDocumentsIdentifier,- AgentDocumentsApiName.renameDocument,- ),- ).toBe(false);- expect(- isShareBlockedBuiltinDispatch(- enabled,- AgentDocumentsIdentifier,- AgentDocumentsApiName.removeDocument,- ),- ).toBe(true);- expect(- isShareBlockedBuiltinDispatch(- enabled,- AgentDocumentsIdentifier,- AgentDocumentsApiName.updateLoadRule,- ),- ).toBe(true);- });-- it('allows the two Skills read APIs but blocks the exec-class and export ones', () => {- const enabled = { skillGrants: ['pdf-report'] };-- for (const apiName of [SkillsApiName.activateSkill, SkillsApiName.readReference]) {- expect(isShareBlockedBuiltinDispatch(enabled, SkillsIdentifier, apiName)).toBe(false);- }- // runCommand/execScript run arbitrary code on the creator's account and- // exportFile writes to the creator's file store β all three are phase-2- // work, gated here rather than merely omitted from the assembled manifest.- for (const apiName of [- SkillsApiName.runCommand,- SkillsApiName.execScript,- SkillsApiName.exportFile,- ]) {- expect(isShareBlockedBuiltinDispatch(enabled, SkillsIdentifier, apiName)).toBe(true);- }- });-- it('blocks every Skills API when the owner revoked or never granted a skill', () => {- // A tool grant is included on purpose: `toolGrants` never authorizes a- // skill, so it cannot unblock these APIs either.- for (const permissions of [{}, { skillGrants: [] }, { toolGrants: [{ identifier: 'x' }] }]) {- expect(- isShareBlockedBuiltinDispatch(permissions, SkillsIdentifier, SkillsApiName.activateSkill),- ).toBe(true);- }- });-- it('ignores non-builtin identifiers entirely', () => {- expect(isShareBlockedBuiltinDispatch({}, 'some-mcp-server', 'anything')).toBe(false);- });-- it('blocks a builtin outside the master allowlist regardless of enablement', () => {- expect(- isShareBlockedBuiltinDispatch(- { toolGrants: [{ identifier: AgentManagementIdentifier }] },- AgentManagementIdentifier,- 'searchAgent',- ),- ).toBe(true);- });-- it('a per-API grant grants only the named API, not the whole identifier', () => {- const enabled = {- toolGrants: [{ apis: [LobeAgentApiName.analyzeMedia], identifier: LobeAgentIdentifier }],- };-- expect(- isShareBlockedBuiltinDispatch(enabled, LobeAgentIdentifier, LobeAgentApiName.analyzeMedia),- ).toBe(false);- // updatePlan carries no intervention config either, so only the picker's- // per-API scoping is what blocks it here.- expect(- isShareBlockedBuiltinDispatch(enabled, LobeAgentIdentifier, LobeAgentApiName.updatePlan),- ).toBe(true);- });-});--describe('shareGateGrantsCloudSandbox', () => {- it('is false when the share does not grant lobe-cloud-sandbox', () => {- expect(shareGateGrantsCloudSandbox(buildGate())).toBe(false);- expect(- shareGateGrantsCloudSandbox(buildGate({ toolGrants: [{ identifier: 'web-search' }] })),- ).toBe(false);- });-- it('is true for a whole-identifier grant', () => {- expect(- shareGateGrantsCloudSandbox(- buildGate({ toolGrants: [{ identifier: CloudSandboxManifest.identifier }] }),- ),- ).toBe(true);- });-- // The plan only needs to know the sandbox is in play at all β narrowing to- // the granted APIs happens later in `applyShareGateToToolSet`.- it('treats an apis-scoped grant as a grant of the identifier', () => {- expect(- shareGateGrantsCloudSandbox(- buildGate({- toolGrants: [{ apis: ['runCommand'], identifier: CloudSandboxManifest.identifier }],- }),- ),- ).toBe(true);- });-});diff --git a/apps/server/src/services/aiAgent/shareGate/toolSet.ts b/apps/server/src/services/aiAgent/shareGate/toolSet.tsnew file mode 100644index 00000000000..18f131e0f67--- /dev/null+++ b/apps/server/src/services/aiAgent/shareGate/toolSet.ts@@ -0,0 +1,186 @@+import { hasShareToolGrant, PLUGIN_SCHEMA_SEPARATOR, type ShareToolGrant } from '@lobechat/const';+import { isDeviceOnlyMcpEndpoint } from '@lobechat/utils/mcpEndpoint';++import { isGovernedByBuiltinAllowlist, SHARE_VISITOR_ALLOWED_IDENTIFIERS } from './allowlist';+import { DATA_TOOL_ACCESS_RULES } from './dataToolRules';+import { resolveEffectiveShareToolGrants } from './grants';+import { stripSubAgentDispatchApis } from './subAgentDispatch';+import {+ dropToolFromSet,+ generateOwnedToolNames,+ pruneArrayInPlace,+ stripApisFromTool,+} from './toolSetMutation';+import type { AgentShareGate, ShareGateToolSet } from './types';++/**+ * Apply {@link DATA_TOOL_ACCESS_RULES} to the assembled tool set: drop a data+ * tool entirely when its grant is `none`, or strip its write APIs (from both+ * the manifest and the function-calling `tools` schema) when the grant is+ * `read`. Runs as part of {@link applyShareGateToToolSet} β after that pass's+ * allowlist intersection has already decided which identifiers survive at all+ * β so this only needs to further restrict, never re-add.+ *+ * This is UX/defense-in-depth (the model is never offered the disallowed+ * function); the actual unbypassable enforcement is+ * {@link isShareBlockedDataToolCall} at the `BuiltinToolsExecutor` dispatch+ * site.+ */+const applyShareGateToDataToolAccess = (toolSet: ShareGateToolSet, gate: AgentShareGate): void => {+ for (const [identifier, rule] of Object.entries(DATA_TOOL_ACCESS_RULES)) {+ if (!toolSet.manifestMap[identifier]) continue;++ const grant = rule.grant(gate.shareConfig);++ if (grant === 'none') {+ dropToolFromSet(toolSet, identifier);+ continue;+ }++ // Under a `read` grant, strip both mutations (`writeApiNames`) AND the+ // creator-wide reads that no grant can honestly scope to this agent+ // (`alwaysBlockedApiNames`) β same treatment, since both are never offered+ // to the model regardless of grant. `isArgsOutOfScope`-covered APIs are+ // NOT stripped here: they stay offered because they CAN be in scope+ // depending on the id the model picks, and that per-call id check only+ // runs at dispatch time, not against a static manifest.+ const blockedApiNames = new Set([...rule.writeApiNames, ...(rule.alwaysBlockedApiNames ?? [])]);++ stripApisFromTool(toolSet, identifier, blockedApiNames);+ }+};++/**+ * Final allowlist enforcement for a share visitor's fully-assembled tool set.+ *+ * `shareConfig.toolGrants` is the single source of truth for what a share+ * visitor can see or run. This pass mutates `toolSet` in place and must run+ * once, after every manifest/default/dynamic-activation source has been merged+ * in, immediately before the operation's `toolSet` is persisted. An+ * empty/missing whitelist collapses the set to nothing (no built-in tool is+ * exempted; a share with no configured tools is a plain-chat run).+ */+export const applyShareGateToToolSet = (toolSet: ShareGateToolSet, gate: AgentShareGate): void => {+ const grants = resolveEffectiveShareToolGrants(gate.shareConfig);++ // A tool must clear BOTH gates: the owner's own `toolGrants` picker+ // (`grants` β toolset-level OR scoped to at least one API), AND β for+ // builtin identifiers only β the default-deny master allowlist+ // (`SHARE_VISITOR_ALLOWED_IDENTIFIERS`). Non-builtin identifiers (MCP/market/+ // custom plugins) are outside `isGovernedByBuiltinAllowlist`'s population, so+ // they pass straight through to the owner-picker check unaffected β this+ // allowlist must never decide their fate, in either direction.+ // MCP servers only the creator's machine can reach (stdio / localhost / LAN)+ // never survive, grant or not: dispatching one tunnels to the creator's+ // device under the creator's identity. Decided from the manifest's runtime+ // `mcpParams` (set for connector manifests by `buildConnectorManifests`),+ // the same field `ToolExecutionService.executeMCPTool` dispatches on β which+ // also refuses these calls for visitor runs as the unbypassable backstop.+ const deviceOnlyMcpIds = new Set(+ Object.entries(toolSet.manifestMap)+ .filter(([, manifest]) => {+ const mcpParams = (manifest as { mcpParams?: { type?: string; url?: string } }).mcpParams;+ return !!mcpParams && isDeviceOnlyMcpEndpoint(mcpParams);+ })+ .map(([id]) => id),+ );++ const isAllowed = (id: string) => {+ if (deviceOnlyMcpIds.has(id)) return false;+ if (!hasShareToolGrant(grants, id)) return false;+ if (!isGovernedByBuiltinAllowlist(id)) return true;+ return SHARE_VISITOR_ALLOWED_IDENTIFIERS.has(id);+ };++ // Prune arrays in place (`splice`, not reassignment) so this works whether+ // the caller's binding for `enabledToolIds` / `activatableToolIds` / `tools`+ // is a `const` array reference β callers only need to pass the array they+ // already hold, not receive a new one back.+ pruneArrayInPlace(toolSet.enabledToolIds, isAllowed);+ pruneArrayInPlace(toolSet.activatableToolIds, isAllowed);++ // Regenerate every allowed manifest's tool-call names BEFORE the manifests+ // are pruned: `ToolNameResolver.generate` MD5-hashes an identifier segment+ // that is non-ASCII or oversized, so the `tools[]` entry of such a tool does+ // not start with its literal identifier and a prefix-only check would drop+ // a granted MCP tool along with everything else (fail-closed, but breaks+ // the grant). See `pruneToolsForIdentifier` for the mirror-image, fail-OPEN+ // hazard on the per-API path.+ const allowedToolNames = new Set<string>();+ for (const [id, manifest] of Object.entries(toolSet.manifestMap)) {+ if (!isAllowed(id)) continue;+ for (const name of generateOwnedToolNames(id, manifest)) allowedToolNames.add(name);+ }++ for (const id of Object.keys(toolSet.manifestMap)) {+ if (!isAllowed(id)) delete toolSet.manifestMap[id];+ }+ for (const id of Object.keys(toolSet.sourceMap)) {+ if (!isAllowed(id)) delete toolSet.sourceMap[id];+ }+ for (const id of Object.keys(toolSet.executorMap)) {+ if (!isAllowed(id)) delete toolSet.executorMap[id];+ }++ if (toolSet.tools) {+ pruneArrayInPlace(toolSet.tools, (tool) => {+ const name: string | undefined = tool?.function?.name;+ if (!name) return false;+ if (allowedToolNames.has(name)) return true;+ // Fallback for an entry with no manifest to regenerate from β only its+ // literal identifier prefix can vouch for it.+ const identifier = name.split(PLUGIN_SCHEMA_SEPARATOR)[0];+ return !!identifier && isAllowed(identifier);+ });+ }++ stripSubAgentDispatchApis(toolSet);+ applyShareGateToDataToolAccess(toolSet, gate);+ applyShareGateToPerApiGrants(toolSet, grants);+};++/**+ * Narrow each surviving tool's offered APIs down to what the owner's picker+ * actually granted for it. Runs LAST in {@link applyShareGateToToolSet}, after+ * every other strip (data-tool write/always-blocked APIs, sub-agent dispatch)+ * has already trimmed `manifest.api` β so a per-API grant+ * naming an API another rule already removed is simply a no-op here, never an+ * unstrip.+ *+ * A toolset-level entry (`grant === 'all'`) leaves the tool's remaining APIs+ * untouched. A per-API entry (`grant` is a `Set`) drops every remaining API+ * not named in it; if that empties the API list entirely, the tool is dropped+ * outright β the same treatment `applyShareGateToDataToolAccess` gives a+ * `'none'` grant, since an identifier with zero callable APIs offers a share+ * visitor's model nothing.+ *+ * Matches on the manifest's real `api[].name` list (via `stripApisFromTool`)+ * rather than parsing generated tool-call names directly:+ * `ToolNameResolver.generate` MD5-hashes an oversized or invalid-character API+ * segment, so the manifest is the only reliable source for which entries in+ * `toolSet.tools` belong to which granted API.+ */+const applyShareGateToPerApiGrants = (+ toolSet: ShareGateToolSet,+ grants: Map<string, ShareToolGrant>,+): void => {+ for (const identifier of Object.keys(toolSet.manifestMap)) {+ const grant = grants.get(identifier);+ if (!grant || grant === 'all') continue;++ const manifest = toolSet.manifestMap[identifier];+ if (!Array.isArray(manifest.api) || manifest.api.length === 0) continue;++ const blockedApiNames = new Set(+ manifest.api.filter((api) => !grant.has(api.name)).map((api) => api.name),+ );+ if (blockedApiNames.size === 0) continue;++ if (blockedApiNames.size === manifest.api.length) {+ dropToolFromSet(toolSet, identifier);+ continue;+ }++ stripApisFromTool(toolSet, identifier, blockedApiNames);+ }+};diff --git a/apps/server/src/services/aiAgent/shareGate/toolSetMutation.ts b/apps/server/src/services/aiAgent/shareGate/toolSetMutation.tsnew file mode 100644index 00000000000..f4a648038e1--- /dev/null+++ b/apps/server/src/services/aiAgent/shareGate/toolSetMutation.ts@@ -0,0 +1,186 @@+import { PLUGIN_SCHEMA_SEPARATOR } from '@lobechat/const';+import type { LobeToolManifest } from '@lobechat/context-engine';+import { generateToolsFromManifest, ToolNameResolver } from '@lobechat/context-engine';++import { resolveShareToolManifest } from '../shareToolManifest';+import type { ShareGateToolSet } from './types';++/**+ * Single shared resolver instance for regenerating function-calling names+ * from a manifest's identifier/api/type β same class `ToolsEngine` used to+ * build `toolSet.tools` in the first place. Stateless (no per-call config),+ * so one instance is safe to reuse across every gate pass.+ */+const toolNameResolver = new ToolNameResolver();++/**+ * Regenerate the exact function-calling name `ToolsEngine` would have used+ * for each of `apiNames`, via the SAME `ToolNameResolver.generate` it used to+ * build `toolSet.tools` originally.+ *+ * A naive `` `${identifier}${SEP}${apiName}` `` string only matches what is+ * actually in `toolSet.tools` when neither segment needed normalizing.+ * `generate` (1) MD5-hashes an api/identifier segment that contains+ * characters strict providers reject or that pushes the name past the+ * provider length cap, and (2) appends a third `${SEP}<type>` segment for any+ * manifest whose `type` isn't `builtin`/`default` β MCP/connector manifests+ * are `type: 'mcp'` (see `buildConnectorManifests.ts`). Both are common for+ * MCP tools (server-controlled, often long/non-ASCII api names), so skipping+ * this and slicing the raw string instead silently fails OPEN: the manifest+ * loses the API but its generated tool-call name survives in `tools[]` and+ * stays callable.+ */+const generateToolNames = (+ identifier: string,+ apiNames: Iterable<string>,+ type: LobeToolManifest['type'],+): Set<string> => {+ const names = new Set<string>();+ for (const apiName of apiNames) names.add(toolNameResolver.generate(identifier, apiName, type));+ return names;+};++/**+ * Drop every `toolSet.tools` entry that belongs to `identifier` and is not in+ * `allowedNames`. Pass an empty `allowedNames` to drop every entry for the+ * identifier.+ *+ * "Belongs to `identifier`" is decided by `ownedNames` β the full set of+ * generated names for every API on the identifier's manifest, produced by+ * the SAME `ToolNameResolver.generate` that built `toolSet.tools`. A raw+ * first-segment comparison against `identifier` is NOT enough on its own:+ * `generate` MD5-hashes the identifier segment whenever it contains+ * characters strict providers reject (non-ASCII, punctuation) or whenever+ * the assembled name is still over the provider length cap after hashing+ * the api segment, so for such identifiers no entry ever starts with the+ * literal identifier text and a prefix-only match keeps everything β+ * silently failing OPEN. The prefix check is kept only as a fallback for+ * entries that survived without a manifest (nothing to regenerate from).+ */+const pruneToolsForIdentifier = (+ toolSet: ShareGateToolSet,+ identifier: string,+ ownedNames: ReadonlySet<string>,+ allowedNames: ReadonlySet<string>,+): void => {+ if (!toolSet.tools) return;+ pruneArrayInPlace(toolSet.tools, (tool) => {+ const name: string | undefined = tool?.function?.name;+ if (!name) return true;+ const owned = ownedNames.has(name) || name.split(PLUGIN_SCHEMA_SEPARATOR)[0] === identifier;+ if (!owned) return true;+ return allowedNames.has(name);+ });+};++/**+ * Replace surviving function schemas with a builtin-owned restricted+ * projection while preserving which tools the upstream engine activated.+ */+const replaceToolsForIdentifier = (+ toolSet: ShareGateToolSet,+ identifier: string,+ ownedNames: ReadonlySet<string>,+ manifest: LobeToolManifest,+): void => {+ if (!toolSet.tools) return;++ const replacements = new Map(+ generateToolsFromManifest(manifest).map((tool) => [tool.function.name, tool]),+ );++ for (let i = 0; i < toolSet.tools.length; i += 1) {+ const name: string | undefined = toolSet.tools[i]?.function?.name;+ if (!name) continue;++ const owned = ownedNames.has(name) || name.split(PLUGIN_SCHEMA_SEPARATOR)[0] === identifier;+ const replacement = replacements.get(name);+ if (owned && replacement) toolSet.tools[i] = replacement;+ }+};++/** Every generated tool-call name the manifest can currently produce. */+export const generateOwnedToolNames = (+ identifier: string,+ manifest: LobeToolManifest | undefined,+): Set<string> =>+ manifest+ ? generateToolNames(+ identifier,+ manifest.api.map((api) => api.name),+ manifest.type,+ )+ : new Set();++const EMPTY_TOOL_NAME_SET: ReadonlySet<string> = new Set();++/** Remove one tool identifier from every parallel structure of the tool set. */+export const dropToolFromSet = (toolSet: ShareGateToolSet, identifier: string): void => {+ // Regenerate the owned names BEFORE the manifest is gone β it is the only+ // source that can reproduce a hashed identifier segment.+ const ownedNames = generateOwnedToolNames(identifier, toolSet.manifestMap[identifier]);+ delete toolSet.manifestMap[identifier];+ delete toolSet.sourceMap[identifier];+ delete toolSet.executorMap[identifier];+ pruneArrayInPlace(toolSet.enabledToolIds, (id) => id !== identifier);+ pruneArrayInPlace(toolSet.activatableToolIds, (id) => id !== identifier);+ pruneToolsForIdentifier(toolSet, identifier, ownedNames, EMPTY_TOOL_NAME_SET);+};++/** Drop `blockedApiNames` from one tool's manifest AND its function-calling schema. */+export const stripApisFromTool = (+ toolSet: ShareGateToolSet,+ identifier: string,+ blockedApiNames: Set<string>,+): void => {+ const manifest = toolSet.manifestMap[identifier];+ if (!manifest) return;++ const survivingApi = manifest.api.filter((api) => !blockedApiNames.has(api.name));+ const wasTrimmed = survivingApi.length < manifest.api.length;+ const ownedNames = generateOwnedToolNames(identifier, manifest);+ const restrictedManifest = wasTrimmed+ ? resolveShareToolManifest({+ allowedApiNames: survivingApi.map((api) => api.name),+ identifier,+ })+ : undefined;+ const restrictedApiMap = new Map(restrictedManifest?.api.map((api) => [api.name, api]) ?? []);++ // A manifest-level system role commonly documents its complete API surface.+ // Keeping it after a partial strip lets the model infer and advertise APIs+ // that are no longer callable, even though the function schemas are safe.+ // ToolResolver applies the same invariant for per-step tool-name filtering.+ toolSet.manifestMap[identifier] = {+ ...manifest,+ api: survivingApi.map((api) => restrictedApiMap.get(api.name) ?? api),+ meta: restrictedManifest?.meta ?? manifest.meta,+ ...(wasTrimmed && {+ systemRole: restrictedManifest?.systemRole,+ }),+ };++ // Fail-closed: only keep `tools[]` entries this file can PROVE still+ // belong to a surviving API, by regenerating their exact names rather than+ // reverse-parsing whatever is already in `tools[]`.+ pruneToolsForIdentifier(+ toolSet,+ identifier,+ ownedNames,+ generateToolNames(+ identifier,+ survivingApi.map((api) => api.name),+ manifest.type,+ ),+ );++ if (restrictedManifest) {+ replaceToolsForIdentifier(toolSet, identifier, ownedNames, toolSet.manifestMap[identifier]);+ }+};++export const pruneArrayInPlace = <T>(array: T[], keep: (item: T) => boolean): void => {+ for (let i = array.length - 1; i >= 0; i -= 1) {+ if (!keep(array[i])) array.splice(i, 1);+ }+};diff --git a/apps/server/src/services/aiAgent/shareGate/types.ts b/apps/server/src/services/aiAgent/shareGate/types.tsnew file mode 100644index 00000000000..b06a9deb5f9--- /dev/null+++ b/apps/server/src/services/aiAgent/shareGate/types.ts@@ -0,0 +1,80 @@+import type { LobeToolManifest, ToolExecutor, ToolSource } from '@lobechat/context-engine';+import type { AgentShareToolGrant } from '@lobechat/types';++import type { AgentShareConfig } from '@/database/schemas';++/**+ * Server-side gate for shared-agent visitor conversations.+ *+ * Built exclusively by the shareChat router after the share access check β+ * never from client input. The gate is applied at operation-build time inside+ * `AiAgentService.execAgent`, so the restricted tool/memory/file surface is+ * snapshotted into the operation state and every later step inherits it+ * without the context engine knowing about shares.+ */+export interface AgentShareGate {+ agentId: string;+ shareConfig: AgentShareConfig;+ /**+ * The `agentShares.id` this run was authorized against β read together with+ * `shareConfig` in the SAME `AgentShareModel.findByShareIdWithAccessCheck`+ * call.+ *+ * "The share row for this agent still exists AND its id still equals+ * `shareId` AND its visibility is still `link`" is exactly the condition+ * "this run's authorization has not been revoked". Every re-validation in+ * the visitor chain (`shareVisitorAbuseGuards`, the per-step runtime+ * re-check) is that one comparison.+ *+ * The visibility half carries the ordinary case: turning sharing off flips+ * the row to `private` and keeps it, so the owner can resume the same link+ * later (`AgentShareModel.updateVisibility`). The id half covers a row that+ * genuinely went away and came back as a different instance β a hard delete+ * (`AgentShareModel.deleteByAgentId`) or an agent delete + recreate.+ */+ shareId: string;+ /**+ * The signed-in visitor driving this run. Recorded on `topics.senderId` and+ * spend-log metadata; the run itself executes as the creator.+ */+ visitorUserId: string;+}++/**+ * Minimal shape a `DataToolAccessRule.grant` needs β either the full share+ * gate's `shareConfig`, or the trimmed `agentShare` marker threaded through+ * `RuntimeExecutorContext` / `ToolExecutionContext` for tool calls resolved+ * outside this module (see {@link isShareBlockedDataToolCall}).+ */+export interface ShareDataToolPermissions {+ allowReadMemory?: boolean;+ /**+ * Agent's own persisted, `enabled` knowledge-base ids (never+ * visitor-supplied). Currently always empty for a share run β see+ * {@link applyShareGateToAgentConfig} β but kept so the id-scoping rule+ * below stays wired should a knowledge-base grant return.+ */+ knowledgeBaseIds?: string[];+ /**+ * The share's `skillGrants`. Read here only to answer "does this share+ * authorize any skill at all", which is what turns the `lobe-skills` TOOL on;+ * which individual skills it may load is decided by+ * {@link filterSkillsByShareGate} at assembly and re-checked at load time in+ * the skill runtime.+ */+ skillGrants?: string[];+ toolGrants?: AgentShareToolGrant[];+}++/**+ * The assembled operation-level tool set, right before it is handed to+ * `AgentRuntimeService.createOperation` as `toolSet`.+ */+export interface ShareGateToolSet {+ activatableToolIds: string[];+ enabledToolIds: string[];+ executorMap: Record<string, ToolExecutor>;+ manifestMap: Record<string, LobeToolManifest>;+ sourceMap: Record<string, ToolSource>;+ tools: any[] | undefined;+}diff --git a/apps/server/src/services/aiAgent/shareToolManifest.ts b/apps/server/src/services/aiAgent/shareToolManifest.tsindex d3cea7b44dc..aa991ee8f7a 100644--- a/apps/server/src/services/aiAgent/shareToolManifest.ts+++ b/apps/server/src/services/aiAgent/shareToolManifest.ts@@ -19,7 +19,7 @@ const hasExactApiSet = (* Transitional bridge between Agent Share policy filtering and builtin-owned* restricted manifests.*- * Keep this adapter separate from `shareGate.ts`: a future shared tool+ * Keep this adapter separate from `shareGate/`: a future shared tool* finalization pipeline can move the same optional resolver without retaining* Agent Share-specific registry lookup or Documents/Memory knowledge in the* gate. The exact-set check prevents a tool-owned projection from widening thediff --git a/apps/server/src/services/toolExecution/__tests__/index.test.ts b/apps/server/src/services/toolExecution/__tests__/index.test.tsindex 0475a56026a..1bdf4b7d7ac 100644--- a/apps/server/src/services/toolExecution/__tests__/index.test.ts+++ b/apps/server/src/services/toolExecution/__tests__/index.test.ts@@ -772,6 +772,57 @@ describe('ToolExecutionService', () => {expect((result.error as any)?.code).toBe('MCP_DEVICE_UNAVAILABLE');});+ describe('Agent Share visitor runs', () => {+ const visitor = { agentShareVisitor: { shareId: 'share-1' } };++ it.each([+ ['stdio', { args: [], command: 'npx', name: 'my-mcp', type: 'stdio' }],+ ['local-network HTTP', { name: 'my-mcp', type: 'http', url: 'http://10.0.0.5:8000/mcp' }],+ ])(+ 'refuses a %s MCP call instead of tunneling to the creator device',+ async (_, mcpParams) => {+ vi.mocked(getScopedOnlineDevices).mockResolvedValue([+ { channels: [{ channel: 'desktop' }], deviceId: 'creator-desktop', online: true },+ ] as any);+ const callTool = vi.fn();+ const service = makeService({ callTool });++ const result = await service.executeTool(mcpPayload, contextWith(mcpParams, visitor));++ expect(result.success).toBe(false);+ expect((result.error as any)?.code).toBe('SHARE_GATE_BLOCKED');+ expect(deviceGateway.executeMcpCall).not.toHaveBeenCalled();+ expect(callTool).not.toHaveBeenCalled();+ },+ );++ it('refuses a stdio MCP call when no gateway is configured', async () => {+ (deviceGateway as any).isConfigured = false;+ const callTool = vi.fn();+ const service = makeService({ callTool });++ const result = await service.executeTool(+ mcpPayload,+ contextWith({ args: [], command: 'npx', name: 'my-mcp', type: 'stdio' }, visitor),+ );++ expect((result.error as any)?.code).toBe('SHARE_GATE_BLOCKED');+ expect(callTool).not.toHaveBeenCalled();+ });++ it('still calls a public HTTP MCP server', async () => {+ const callTool = vi.fn().mockResolvedValue({ ok: true });+ const service = makeService({ callTool });++ await service.executeTool(+ mcpPayload,+ contextWith({ name: 'my-mcp', type: 'http', url: 'https://mcp.example.com' }, visitor),+ );++ expect(callTool).toHaveBeenCalledTimes(1);+ });+ });+it('runs stdio in-process when no gateway is configured (standalone Electron)', async () => {(deviceGateway as any).isConfigured = false;const callTool = vi.fn().mockResolvedValue({ ok: true });diff --git a/apps/server/src/services/toolExecution/index.ts b/apps/server/src/services/toolExecution/index.tsindex cc2d743f821..33c9b0716bc 100644--- a/apps/server/src/services/toolExecution/index.ts+++ b/apps/server/src/services/toolExecution/index.ts@@ -1,6 +1,7 @@import { DEFAULT_TOOL_RESULT_MAX_LENGTH, truncateToolResult } from '@lobechat/prompts/toolResult';import { type ChatToolPayload } from '@lobechat/types';-import { isLocalOrPrivateUrl, safeParseJSON } from '@lobechat/utils';+import { safeParseJSON } from '@lobechat/utils';+import { isDeviceOnlyMcpEndpoint } from '@lobechat/utils/mcpEndpoint';import debug from 'debug';import { ConnectorToolPermission } from '@/database/schemas';@@ -283,6 +284,23 @@ export class ToolExecutionService {mcpParams.type,);+ const isDeviceOnlyMcp = isDeviceOnlyMcpEndpoint(mcpParams);++ // Agent Share visitor runs execute with the CREATOR's identity, so a+ // device-only MCP would tunnel to (or, without a gateway, spawn on) the+ // creator's machine on a visitor's behalf. The tool-set gate already drops+ // these manifests (`applyShareGateToToolSet`); this is the unbypassable+ // dispatch-site check, mirroring `isShareBlockedBuiltinDispatch`.+ if (context.agentShareVisitor && isDeviceOnlyMcp) {+ log('Share gate blocked device-only MCP dispatch: %s:%s', identifier, apiName);+ const message = `MCP server '${identifier}' runs on the agent owner's own machine and is not available in shared conversations.`;+ return {+ content: message,+ error: { code: 'SHARE_GATE_BLOCKED', message },+ success: false,+ };+ }+try {// Check if this is a cloud MCP endpointif (mcpParams.type === 'cloud') {@@ -299,9 +317,6 @@ export class ToolExecutionService {// classic-path guard in connector exec enforces). Standalone Electron /// self-host (no gateway) falls through to the in-process MCP service// below, which legitimately runs on the user's machine or LAN.- const isDeviceOnlyMcp =- mcpParams.type === 'stdio' ||- (mcpParams.type === 'http' && isLocalOrPrivateUrl(mcpParams.url));if (isDeviceOnlyMcp && deviceGateway.isConfigured) {const tunnelTarget = context.userId? await this.resolveMcpTunnelTarget(context)diff --git a/packages/builtin-tool-skills/src/types.ts b/packages/builtin-tool-skills/src/types.tsindex 1dadd581591..e36b06a1ab1 100644--- a/packages/builtin-tool-skills/src/types.ts+++ b/packages/builtin-tool-skills/src/types.ts@@ -20,7 +20,7 @@ export const SkillsApiName = {* those APIs would have started.** Shared with the server share gate (`DATA_TOOL_ACCESS_RULES` in- * `apps/server/src/services/aiAgent/shareGate.ts`), which derives its block+ * `apps/server/src/services/aiAgent/shareGate/dataToolRules.ts`), which derives its block* list as "every API of this tool that is NOT in this set" β so a newly added* skill API is denied to visitors by default rather than silently exposed.*/diff --git a/packages/builtin-tools/src/index.ts b/packages/builtin-tools/src/index.tsindex ab3da6edd82..8ecc0af63b3 100644--- a/packages/builtin-tools/src/index.ts+++ b/packages/builtin-tools/src/index.ts@@ -192,7 +192,7 @@ export const runtimeManagedToolIds = [* touch, at BOTH the tool-set-assembly layer (server* `applyShareGateToToolSet`) and the dispatch layer (server* `isShareBlockedDataToolCall`) β see- * `apps/server/src/services/aiAgent/shareGate.ts`. Also the single source of+ * `apps/server/src/services/aiAgent/shareGate/`. Also the single source of* truth for the agent-owner-facing share settings tool picker, which must* show a builtin tool as unavailable-to-visitors rather than let the owner* select (and the UI silently confirm) a grant the server gate can never@@ -229,8 +229,8 @@ export const runtimeManagedToolIds = [* `lobe-user-interaction`, `lobe-activator`,* `lobe-local-system`, `lobe-browser`, `lobe-remote-device`,* `lobe-topic-reference`, and the hidden system-only self-iteration tools),- * see the denied-bucket doc block at the bottom of- * `apps/server/src/services/aiAgent/shareGate.ts`.+ * see the denied-builtins section of+ * `apps/server/src/services/aiAgent/shareGate/README.md`.*/export const AGENT_SHARE_ALLOWED_BUILTIN_IDENTIFIERS = new Set<string>([CalculatorManifest.identifier,@@ -248,11 +248,11 @@ export const AGENT_SHARE_ALLOWED_BUILTIN_IDENTIFIERS = new Set<string>([// is skipped for visitor runs (see `cloudSandbox.ts` /// `preprocessLhCommand.ts`), and `lobe-creds` stays denied so// `~/.creds/env` is never written into that session either. See the- // positive-evidence doc block in `shareGate.ts` for the full rationale.+ // allowed-builtins section of `shareGate/README.md` for the full rationale.CloudSandboxManifest.identifier,// Data-bearing tools whose whole-identifier grant AND per-API write/always-// blocked surface is further narrowed server-side by- // `DATA_TOOL_ACCESS_RULES` in `shareGate.ts` β being on this allowlist only+ // `DATA_TOOL_ACCESS_RULES` in `shareGate/dataToolRules.ts` β being on this allowlist only// lets them survive to that narrower gate, it does not itself grant read or// write access.KnowledgeBaseManifest.identifier,@@ -264,8 +264,8 @@ export const AGENT_SHARE_ALLOWED_BUILTIN_IDENTIFIERS = new Set<string>([// `activateSkill` / `readReference` on skills the creator explicitly listed// in `shareConfig.skillGrants`, enforced again at load time in the server// runtime so the model cannot name a skill outside that list. Every other- // API of the tool is blocked. See the positive-evidence doc block in- // `shareGate.ts`.+ // API of the tool is blocked. See the allowed-builtins section of+ // `shareGate/README.md`.SkillsManifest.identifier,]);@@ -273,7 +273,7 @@ export const AGENT_SHARE_ALLOWED_BUILTIN_IDENTIFIERS = new Set<string>([* Subset of {@link AGENT_SHARE_ALLOWED_BUILTIN_IDENTIFIERS} whose server-side* data grant is UNCONDITIONALLY `none` β surviving the master allowlist only* to be blocked outright by `DATA_TOOL_ACCESS_RULES` in- * `apps/server/src/services/aiAgent/shareGate.ts`, for every API and no matter+ * `apps/server/src/services/aiAgent/shareGate/dataToolRules.ts`, for every API and no matter* what the share config says. There is no knowledge-base or agent-file grant* in `AgentShareConfig` at all (see `applyShareGateToAgentConfig`), so a* visitor run can never reach the knowledge-base store. Agent Documents is@@ -285,7 +285,7 @@ export const AGENT_SHARE_ALLOWED_BUILTIN_IDENTIFIERS = new Set<string>([** Exists so the owner-facing share settings tool picker can render these as* permanently unavailable instead of offering a toggle the server will always- * ignore. `shareGate.test.ts` asserts this set stays exactly the set of+ * ignore. `shareGate/dispatch.test.ts` asserts this set stays exactly the set of* identifiers `isShareBlockedDataToolCall` blocks under maximal permissions,* so relaxing a grant server-side without updating this list fails there* rather than silently lying in the UI.@@ -627,7 +627,7 @@ export const isBuiltinToolIdentifier = (identifier: string): boolean =>* governed builtin identifier, true only when it is explicitly listed in* {@link AGENT_SHARE_ALLOWED_BUILTIN_IDENTIFIERS}.*- * Shared by the server gate (`shareGate.ts`) and the owner-facing tool picker+ * Shared by the server gate (`apps/server/src/services/aiAgent/shareGate/`) and the owner-facing tool picker* so both sides agree on exactly which builtin tools a share visitor's run* can ever reach.*/diff --git a/packages/utils/src/mcpEndpoint.test.ts b/packages/utils/src/mcpEndpoint.test.tsnew file mode 100644index 00000000000..40e363a5b52--- /dev/null+++ b/packages/utils/src/mcpEndpoint.test.ts@@ -0,0 +1,21 @@+import { describe, expect, it } from 'vitest';++import { isDeviceOnlyMcpEndpoint } from './mcpEndpoint';++describe('isDeviceOnlyMcpEndpoint', () => {+ it('treats stdio as device-only', () => {+ expect(isDeviceOnlyMcpEndpoint({ type: 'stdio' })).toBe(true);+ });++ it('treats a localhost or private-network HTTP endpoint as device-only', () => {+ expect(isDeviceOnlyMcpEndpoint({ type: 'http', url: 'http://localhost:3000/mcp' })).toBe(true);+ expect(isDeviceOnlyMcpEndpoint({ type: 'http', url: 'http://192.168.1.8/mcp' })).toBe(true);+ expect(isDeviceOnlyMcpEndpoint({ type: null, url: 'http://127.0.0.1:8080' })).toBe(true);+ });++ it('allows a public HTTP endpoint and the cloud transport', () => {+ expect(isDeviceOnlyMcpEndpoint({ type: 'http', url: 'https://mcp.example.com' })).toBe(false);+ expect(isDeviceOnlyMcpEndpoint({ type: 'cloud', url: 'http://localhost:3000' })).toBe(false);+ expect(isDeviceOnlyMcpEndpoint({})).toBe(false);+ });+});diff --git a/packages/utils/src/mcpEndpoint.ts b/packages/utils/src/mcpEndpoint.tsnew file mode 100644index 00000000000..577ecbd0798--- /dev/null+++ b/packages/utils/src/mcpEndpoint.ts@@ -0,0 +1,18 @@+import { isLocalOrPrivateUrl } from './url';++export interface McpEndpointShape {+ /** MCP transport: `stdio`, `http`, `cloud`, ... (`mcpConnectionType` on connector rows). */+ type?: string | null;+ /** HTTP endpoint (`mcpServerUrl` on connector rows). */+ url?: string | null;+}++/**+ * Whether an MCP endpoint is reachable only from the user's own machine: a+ * stdio server (a local binary) or an HTTP endpoint on localhost / a private+ * network. A cloud server can only call such an endpoint by tunneling to the+ * user's device, so anything that must never touch that device (for example an+ * Agent Share visitor run) has to refuse it.+ */+export const isDeviceOnlyMcpEndpoint = ({ type, url }: McpEndpointShape): boolean =>+ type === 'stdio' || (type !== 'cloud' && !!url && isLocalOrPrivateUrl(url));diff --git a/src/libs/swr/keys.ts b/src/libs/swr/keys.tsindex 4cf315787b7..310702fc08f 100644--- a/src/libs/swr/keys.ts+++ b/src/libs/swr/keys.ts@@ -1176,6 +1176,11 @@ export const inboxKeys = {// ---- share (shared agent / topic / page) ---------------------------------export const shareKeys = {agentInfo: def('share:agentInfo', (slugOrId: string) => ['share:agentInfo', slugOrId]),+ /** Connector lists the creator-side AGENT share tool picker screens, keyed by agentId. */+ agentShareConnectors: def('share:agentShareConnectors', (agentId: string) => [+ 'share:agentShareConnectors',+ agentId,+ ]),/** Candidates for the creator-side AGENT share skill picker, keyed by agentId. */agentShareGrantableSkills: def('share:agentShareGrantableSkills', (agentId: string) => ['share:agentShareGrantableSkills',