Skip to content

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

7.7 KB
Raw Blame
import type { PermissionResourceType } from '@/database/schemas';
import type { LobeChatDatabase } from '@/database/type';
import {
  canPerformResourceAction,
  getResourceMeta,
  isCollaborativeBuiltinAgent,
  type ResourceMeta,
} from '@/server/services/resourcePermission';

import { getWorkspaceAgentParentGroupIds } from './workspaceAgentGuard';

interface ResourceConfigGuardCtx {
  db: LobeChatDatabase;
  grantedPermissions?: readonly string[];
  userId: string;
  workspaceId?: string | null;
}

export type ResourceConfigAccess = 'full' | 'none' | 'profile';

const ACCESS_RANK: Record<ResourceConfigAccess, number> = {
  full: 2,
  none: 0,
  profile: 1,
};

const getSingleResourceConfigAccess = async (
  ctx: ResourceConfigGuardCtx,
  resourceType: PermissionResourceType,
  resourceId: string,
  knownMeta?: ResourceMeta,
): Promise<ResourceConfigAccess> => {
  const workspaceId = ctx.workspaceId!;
  const meta = knownMeta ?? (await getResourceMeta(ctx.db, resourceType, resourceId));
  if (!meta || meta.workspaceId !== workspaceId) return 'none';

  const permissionParams = {
    db: ctx.db,
    grantedPermissions: ctx.grantedPermissions,
    meta,
    resourceId,
    resourceType,
    userId: ctx.userId,
    workspaceId,
  };

  if (await canPerformResourceAction({ ...permissionParams, action: 'edit' })) return 'full';
  if (await canPerformResourceAction({ ...permissionParams, action: 'view' })) return 'profile';
  return 'none';
};

/**
 * Full configuration is an edit-level capability. Members with only view/use
 * access still need public profile data to render shared conversations, but
 * must not receive prompts, tools, model parameters, or other editable config.
 */
export const getResourceConfigAccess = async (
  ctx: ResourceConfigGuardCtx,
  resourceType: PermissionResourceType,
  resourceId: string,
  knownMeta?: ResourceMeta,
): Promise<ResourceConfigAccess> => {
  const workspaceId = ctx.workspaceId ?? undefined;
  if (!workspaceId) return 'full';

  // Resolved once and threaded through: both the access evaluation and the
  // builtin exemption below need it. Callers may hand over a partial meta β€”
  // `protectGroupMemberConfigs` passes only userId/visibility/workspaceId β€” so the
  // builtin markers are completed here, otherwise a linked builtin would fail the
  // classification below and stay capped by its group.
  // A meta we fetch ourselves already carries the builtin markers; a caller-supplied
  // one may not (`protectGroupMemberConfigs` passes only userId / visibility /
  // workspaceId), and classifying on that would leave a linked builtin capped by its
  // group. Complete it with exactly one extra read, and none in the common cases.
  const needsBuiltinMarkers =
    !!knownMeta &&
    resourceType === 'agent' &&
    (knownMeta.slug === undefined || knownMeta.virtual === undefined);
  const meta =
    !knownMeta || needsBuiltinMarkers
      ? ((await getResourceMeta(ctx.db, resourceType, resourceId)) ?? knownMeta)
      : knownMeta;
  if (!meta) return 'none';

  const ownAccess = await getSingleResourceConfigAccess(
    { ...ctx, workspaceId },
    resourceType,
    resourceId,
    meta,
  );
  if (resourceType !== 'agent' || ownAccess === 'none') return ownAccess;

  // Collaborative builtins (Lobe AI, the builders, the page agent) are workspace
  // infrastructure that happens to be `virtual: true`, so linking one into a group
  // would otherwise cap its config access at that group's level β€” reinstating the
  // lockout this whole change removes. They are not group-owned
  // content, so the parent cap does not apply to them.
  if (isCollaborativeBuiltinAgent(resourceType, meta)) return ownAccess;

  // A virtual member's effective config access cannot exceed any parent
  // group's access. This closes the direct agent-id path around a restricted
  // group while still allowing standalone agents to use their own ACL.
  const parentGroupIds = await getWorkspaceAgentParentGroupIds({
    agentId: resourceId,
    db: ctx.db,
    workspaceId,
  });
  if (parentGroupIds.length === 0) return ownAccess;

  const parentAccess = await Promise.all(
    parentGroupIds.map((groupId) =>
      getSingleResourceConfigAccess({ ...ctx, workspaceId }, 'agentGroup', groupId),
    ),
  );

  return [ownAccess, ...parentAccess].reduce((minimum, access) =>
    ACCESS_RANK[access] < ACCESS_RANK[minimum] ? access : minimum,
  );
};

const pick = <T extends Record<string, any>>(source: T, keys: readonly string[]): T => {
  const result: Record<string, any> = {};
  for (const key of keys) {
    if (key in source) result[key] = source[key];
  }
  return result as T;
};

const AGENT_PROFILE_KEYS = [
  'avatar',
  'backgroundColor',
  'createdAt',
  'description',
  'id',
  'isSupervisor',
  'marketIdentifier',
  'model',
  'name',
  'openingMessage',
  'openingQuestions',
  'provider',
  'slug',
  'title',
  'updatedAt',
  'userId',
  'virtual',
  'visibility',
  'workspaceId',
] as const;

/** Return only identity/display fields and a safe runtime summary; deliberately use a whitelist. */
export const redactAgentConfig = <T extends Record<string, any>>(agent: T): T => {
  const result = pick(agent, AGENT_PROFILE_KEYS) as Record<string, any>;
  const agencyConfig = agent.agencyConfig as Record<string, any> | null | undefined;

  // Selection policies are authorization metadata, not executable Agent
  // config. Use/view members need them so the chat controls cannot mistake a
  // redacted fixed Agent for the legacy `member` default β€” same for
  // `topicSharePolicy`, without which the share button would offer a member a
  // link the server then refuses. The execution target is a safe semantic
  // summary shown by use-only members; keep every other agency field (device
  // ids, provider args/env, working directories, etc.) behind edit-level
  // config access.
  if (agencyConfig) {
    const safeAgencySummary = pick(agencyConfig, [
      'executionTarget',
      'executionTargetSelectionPolicy',
      'modelSelectionPolicy',
      'topicSharePolicy',
    ]);
    // The hetero marker is identity, not executable config: without it,
    // use/view members render an external-CLI agent as a plain runtime agent
    // (wrong model selector, wrong composer). Expose the type only β€” args,
    // env and device bindings stay behind edit-level access.
    const heteroType = agencyConfig.heterogeneousProvider?.type;
    if (heteroType) safeAgencySummary.heterogeneousProvider = { type: heteroType };
    if (Object.keys(safeAgencySummary).length > 0) result.agencyConfig = safeAgencySummary;
  }
  const chatConfig = agent.chatConfig as Record<string, any> | null | undefined;
  if (chatConfig?.enableAgentMode !== undefined) {
    result.chatConfig = { enableAgentMode: chatConfig.enableAgentMode };
  }

  return result as T;
};

const GROUP_PROFILE_KEYS = [
  'avatar',
  'backgroundColor',
  'clientId',
  'createdAt',
  'description',
  'groupId',
  'id',
  'marketIdentifier',
  'pinned',
  'supervisorAgentId',
  'title',
  'updatedAt',
  'userId',
  'visibility',
  'workspaceId',
] as const;

/**
 * Preserve group/member display metadata and welcome copy for chat surfaces,
 * while removing the group system prompt and every member's executable config.
 */
export const redactGroupConfig = <T extends Record<string, any>>(group: T): T => {
  const result = pick(group, GROUP_PROFILE_KEYS) as Record<string, any>;
  const config = group.config as Record<string, any> | null | undefined;

  if (config) {
    result.config = pick(config, ['openingMessage', 'openingQuestions']);
  } else if ('config' in group) {
    result.config = config;
  }

  if (Array.isArray(group.agents)) {
    result.agents = group.agents.map((agent: Record<string, any>) => redactAgentConfig(agent));
  }

  return result as T;
};