LibreChat/config/migrate-agent-permissions.js

312 lines
9.9 KiB
JavaScript
Raw Normal View History

const path = require('path');
const { logger } = require('@librechat/data-schemas');
const { AccessRoleIds, ResourceType, PrincipalType } = require('librechat-data-provider');
const { GLOBAL_PROJECT_NAME } = require('librechat-data-provider').Constants;
require('module-alias')({ base: path.resolve(__dirname, '..', 'api') });
const connect = require('./connect');
const { grantPermission } = require('~/server/services/PermissionService');
const { getProjectByName } = require('~/models/Project');
const { findRoleByIdentifier } = require('~/models');
const { Agent } = require('~/db/models');
async function migrateAgentPermissionsEnhanced({ dryRun = true, batchSize = 100 } = {}) {
await connect();
logger.info('Starting Enhanced Agent Permissions Migration', { dryRun, batchSize });
/** Ensurse `aclentries` collection exists for DocumentDB compatibility
* @param {import('mongoose').mongo.Db} db
* @param {string} collectionName
*/
async function ensureCollectionExists(db, collectionName) {
try {
const collections = await db.listCollections({ name: collectionName }).toArray();
if (collections.length === 0) {
await db.createCollection(collectionName);
logger.info(`Created collection: ${collectionName}`);
} else {
logger.info(`Collection already exists: ${collectionName}`);
}
} catch (error) {
logger.error(`'Failed to check/create "${collectionName}" collection:`, error);
// If listCollections fails, try alternative approach
try {
// Try to access the collection directly - this will create it in MongoDB if it doesn't exist
await db.collection(collectionName).findOne({}, { projection: { _id: 1 } });
} catch (createError) {
logger.error(`Could not ensure collection ${collectionName} exists:`, createError);
}
}
}
const mongoose = require('mongoose');
/** @type {import('mongoose').mongo.Db | undefined} */
const db = mongoose.connection.db;
if (db) {
await ensureCollectionExists(db, 'aclentries');
}
// Verify required roles exist
const ownerRole = await findRoleByIdentifier(AccessRoleIds.AGENT_OWNER);
const viewerRole = await findRoleByIdentifier(AccessRoleIds.AGENT_VIEWER);
const editorRole = await findRoleByIdentifier(AccessRoleIds.AGENT_EDITOR);
if (!ownerRole || !viewerRole || !editorRole) {
throw new Error('Required roles not found. Run role seeding first.');
}
// Get global project agent IDs (stores agent.id, not agent._id)
const globalProject = await getProjectByName(GLOBAL_PROJECT_NAME, ['agentIds']);
const globalAgentIds = new Set(globalProject?.agentIds || []);
logger.info(`Found ${globalAgentIds.size} agents in global project`);
// Find agents without ACL entries using DocumentDB-compatible approach
const agentsToMigrate = await Agent.aggregate([
{
$lookup: {
from: 'aclentries',
localField: '_id',
foreignField: 'resourceId',
as: 'aclEntries',
},
},
{
$addFields: {
userAclEntries: {
$filter: {
input: '$aclEntries',
as: 'aclEntry',
cond: {
$and: [
{ $eq: ['$$aclEntry.resourceType', ResourceType.AGENT] },
{ $eq: ['$$aclEntry.principalType', PrincipalType.USER] },
],
},
},
},
},
},
{
$match: {
author: { $exists: true, $ne: null },
userAclEntries: { $size: 0 },
},
},
{
$project: {
_id: 1,
id: 1,
name: 1,
author: 1,
isCollaborative: 1,
},
},
]);
const categories = {
globalEditAccess: [], // Global project + collaborative -> Public EDIT
globalViewAccess: [], // Global project + not collaborative -> Public VIEW
privateAgents: [], // Not in global project -> Private (owner only)
};
agentsToMigrate.forEach((agent) => {
const isGlobal = globalAgentIds.has(agent.id);
const isCollab = agent.isCollaborative;
if (isGlobal && isCollab) {
categories.globalEditAccess.push(agent);
} else if (isGlobal && !isCollab) {
categories.globalViewAccess.push(agent);
} else {
categories.privateAgents.push(agent);
// Log warning if private agent claims to be collaborative
if (isCollab) {
logger.warn(
`Agent "${agent.name}" (${agent.id}) has isCollaborative=true but is not in global project`,
);
}
}
});
logger.info(
'Agent categorization:\n' +
JSON.stringify(
{
globalEditAccess: categories.globalEditAccess.length,
globalViewAccess: categories.globalViewAccess.length,
privateAgents: categories.privateAgents.length,
total: agentsToMigrate.length,
},
null,
2,
),
);
if (dryRun) {
return {
migrated: 0,
errors: 0,
dryRun: true,
summary: {
globalEditAccess: categories.globalEditAccess.length,
globalViewAccess: categories.globalViewAccess.length,
privateAgents: categories.privateAgents.length,
total: agentsToMigrate.length,
},
details: {
globalEditAccess: categories.globalEditAccess.map((a) => ({
name: a.name,
id: a.id,
permissions: 'Owner + Public EDIT',
})),
globalViewAccess: categories.globalViewAccess.map((a) => ({
name: a.name,
id: a.id,
permissions: 'Owner + Public VIEW',
})),
privateAgents: categories.privateAgents.map((a) => ({
name: a.name,
id: a.id,
permissions: 'Owner only',
})),
},
};
}
const results = {
migrated: 0,
errors: 0,
publicViewGrants: 0,
publicEditGrants: 0,
ownerGrants: 0,
};
// Process in batches
for (let i = 0; i < agentsToMigrate.length; i += batchSize) {
const batch = agentsToMigrate.slice(i, i + batchSize);
logger.info(
`Processing batch ${Math.floor(i / batchSize) + 1}/${Math.ceil(agentsToMigrate.length / batchSize)}`,
);
for (const agent of batch) {
try {
const isGlobal = globalAgentIds.has(agent.id);
const isCollab = agent.isCollaborative;
// Always grant owner permission to author
await grantPermission({
principalType: PrincipalType.USER,
principalId: agent.author,
🔧 refactor: Organize Sharing/Agent Components and Improve Type Safety refactor: organize Sharing/Agent components, improve type safety for resource types and access role ids, rename enums to PascalCase refactor: organize Sharing/Agent components, improve type safety for resource types and access role ids chore: move sharing related components to dedicated "Sharing" directory chore: remove PublicSharingToggle component and update index exports chore: move non-sidepanel agent components to `~/components/Agents` chore: move AgentCategoryDisplay component with tests chore: remove commented out code refactor: change PERMISSION_BITS from const to enum for better type safety refactor: reorganize imports in GenericGrantAccessDialog and update index exports for hooks refactor: update type definitions to use ACCESS_ROLE_IDS for improved type safety refactor: remove unused canAccessPromptResource middleware and related code refactor: remove unused prompt access roles from createAccessRoleMethods refactor: update resourceType in AclEntry type definition to remove unused 'prompt' value refactor: introduce ResourceType enum and update resourceType usage across data provider files for improved type safety refactor: update resourceType usage to ResourceType enum across sharing and permissions components for improved type safety refactor: standardize resourceType usage to ResourceType enum across agent and prompt models, permissions controller, and middleware for enhanced type safety refactor: update resourceType references from PROMPT_GROUP to PROMPTGROUP for consistency across models, middleware, and components refactor: standardize access role IDs and resource type usage across agent, file, and prompt models for improved type safety and consistency chore: add typedefs for TUpdateResourcePermissionsRequest and TUpdateResourcePermissionsResponse to enhance type definitions chore: move SearchPicker to PeoplePicker dir refactor: implement debouncing for query changes in SearchPicker for improved performance chore: fix typing, import order for agent admin settings fix: agent admin settings, prevent agent form submission refactor: rename `ACCESS_ROLE_IDS` to `AccessRoleIds` refactor: replace PermissionBits with PERMISSION_BITS refactor: replace PERMISSION_BITS with PermissionBits
2025-07-28 17:52:36 -04:00
resourceType: ResourceType.AGENT,
resourceId: agent._id,
🔧 refactor: Organize Sharing/Agent Components and Improve Type Safety refactor: organize Sharing/Agent components, improve type safety for resource types and access role ids, rename enums to PascalCase refactor: organize Sharing/Agent components, improve type safety for resource types and access role ids chore: move sharing related components to dedicated "Sharing" directory chore: remove PublicSharingToggle component and update index exports chore: move non-sidepanel agent components to `~/components/Agents` chore: move AgentCategoryDisplay component with tests chore: remove commented out code refactor: change PERMISSION_BITS from const to enum for better type safety refactor: reorganize imports in GenericGrantAccessDialog and update index exports for hooks refactor: update type definitions to use ACCESS_ROLE_IDS for improved type safety refactor: remove unused canAccessPromptResource middleware and related code refactor: remove unused prompt access roles from createAccessRoleMethods refactor: update resourceType in AclEntry type definition to remove unused 'prompt' value refactor: introduce ResourceType enum and update resourceType usage across data provider files for improved type safety refactor: update resourceType usage to ResourceType enum across sharing and permissions components for improved type safety refactor: standardize resourceType usage to ResourceType enum across agent and prompt models, permissions controller, and middleware for enhanced type safety refactor: update resourceType references from PROMPT_GROUP to PROMPTGROUP for consistency across models, middleware, and components refactor: standardize access role IDs and resource type usage across agent, file, and prompt models for improved type safety and consistency chore: add typedefs for TUpdateResourcePermissionsRequest and TUpdateResourcePermissionsResponse to enhance type definitions chore: move SearchPicker to PeoplePicker dir refactor: implement debouncing for query changes in SearchPicker for improved performance chore: fix typing, import order for agent admin settings fix: agent admin settings, prevent agent form submission refactor: rename `ACCESS_ROLE_IDS` to `AccessRoleIds` refactor: replace PermissionBits with PERMISSION_BITS refactor: replace PERMISSION_BITS with PermissionBits
2025-07-28 17:52:36 -04:00
accessRoleId: AccessRoleIds.AGENT_OWNER,
grantedBy: agent.author,
});
results.ownerGrants++;
// Determine public permissions for global project agents only
let publicRoleId = null;
let description = 'Private';
if (isGlobal) {
if (isCollab) {
// Global project + collaborative = Public EDIT access
🔧 refactor: Organize Sharing/Agent Components and Improve Type Safety refactor: organize Sharing/Agent components, improve type safety for resource types and access role ids, rename enums to PascalCase refactor: organize Sharing/Agent components, improve type safety for resource types and access role ids chore: move sharing related components to dedicated "Sharing" directory chore: remove PublicSharingToggle component and update index exports chore: move non-sidepanel agent components to `~/components/Agents` chore: move AgentCategoryDisplay component with tests chore: remove commented out code refactor: change PERMISSION_BITS from const to enum for better type safety refactor: reorganize imports in GenericGrantAccessDialog and update index exports for hooks refactor: update type definitions to use ACCESS_ROLE_IDS for improved type safety refactor: remove unused canAccessPromptResource middleware and related code refactor: remove unused prompt access roles from createAccessRoleMethods refactor: update resourceType in AclEntry type definition to remove unused 'prompt' value refactor: introduce ResourceType enum and update resourceType usage across data provider files for improved type safety refactor: update resourceType usage to ResourceType enum across sharing and permissions components for improved type safety refactor: standardize resourceType usage to ResourceType enum across agent and prompt models, permissions controller, and middleware for enhanced type safety refactor: update resourceType references from PROMPT_GROUP to PROMPTGROUP for consistency across models, middleware, and components refactor: standardize access role IDs and resource type usage across agent, file, and prompt models for improved type safety and consistency chore: add typedefs for TUpdateResourcePermissionsRequest and TUpdateResourcePermissionsResponse to enhance type definitions chore: move SearchPicker to PeoplePicker dir refactor: implement debouncing for query changes in SearchPicker for improved performance chore: fix typing, import order for agent admin settings fix: agent admin settings, prevent agent form submission refactor: rename `ACCESS_ROLE_IDS` to `AccessRoleIds` refactor: replace PermissionBits with PERMISSION_BITS refactor: replace PERMISSION_BITS with PermissionBits
2025-07-28 17:52:36 -04:00
publicRoleId = AccessRoleIds.AGENT_EDITOR;
description = 'Global Edit';
results.publicEditGrants++;
} else {
// Global project + not collaborative = Public VIEW access
🔧 refactor: Organize Sharing/Agent Components and Improve Type Safety refactor: organize Sharing/Agent components, improve type safety for resource types and access role ids, rename enums to PascalCase refactor: organize Sharing/Agent components, improve type safety for resource types and access role ids chore: move sharing related components to dedicated "Sharing" directory chore: remove PublicSharingToggle component and update index exports chore: move non-sidepanel agent components to `~/components/Agents` chore: move AgentCategoryDisplay component with tests chore: remove commented out code refactor: change PERMISSION_BITS from const to enum for better type safety refactor: reorganize imports in GenericGrantAccessDialog and update index exports for hooks refactor: update type definitions to use ACCESS_ROLE_IDS for improved type safety refactor: remove unused canAccessPromptResource middleware and related code refactor: remove unused prompt access roles from createAccessRoleMethods refactor: update resourceType in AclEntry type definition to remove unused 'prompt' value refactor: introduce ResourceType enum and update resourceType usage across data provider files for improved type safety refactor: update resourceType usage to ResourceType enum across sharing and permissions components for improved type safety refactor: standardize resourceType usage to ResourceType enum across agent and prompt models, permissions controller, and middleware for enhanced type safety refactor: update resourceType references from PROMPT_GROUP to PROMPTGROUP for consistency across models, middleware, and components refactor: standardize access role IDs and resource type usage across agent, file, and prompt models for improved type safety and consistency chore: add typedefs for TUpdateResourcePermissionsRequest and TUpdateResourcePermissionsResponse to enhance type definitions chore: move SearchPicker to PeoplePicker dir refactor: implement debouncing for query changes in SearchPicker for improved performance chore: fix typing, import order for agent admin settings fix: agent admin settings, prevent agent form submission refactor: rename `ACCESS_ROLE_IDS` to `AccessRoleIds` refactor: replace PermissionBits with PERMISSION_BITS refactor: replace PERMISSION_BITS with PermissionBits
2025-07-28 17:52:36 -04:00
publicRoleId = AccessRoleIds.AGENT_VIEWER;
description = 'Global View';
results.publicViewGrants++;
}
// Grant public permission
await grantPermission({
principalType: PrincipalType.PUBLIC,
principalId: null,
🔧 refactor: Organize Sharing/Agent Components and Improve Type Safety refactor: organize Sharing/Agent components, improve type safety for resource types and access role ids, rename enums to PascalCase refactor: organize Sharing/Agent components, improve type safety for resource types and access role ids chore: move sharing related components to dedicated "Sharing" directory chore: remove PublicSharingToggle component and update index exports chore: move non-sidepanel agent components to `~/components/Agents` chore: move AgentCategoryDisplay component with tests chore: remove commented out code refactor: change PERMISSION_BITS from const to enum for better type safety refactor: reorganize imports in GenericGrantAccessDialog and update index exports for hooks refactor: update type definitions to use ACCESS_ROLE_IDS for improved type safety refactor: remove unused canAccessPromptResource middleware and related code refactor: remove unused prompt access roles from createAccessRoleMethods refactor: update resourceType in AclEntry type definition to remove unused 'prompt' value refactor: introduce ResourceType enum and update resourceType usage across data provider files for improved type safety refactor: update resourceType usage to ResourceType enum across sharing and permissions components for improved type safety refactor: standardize resourceType usage to ResourceType enum across agent and prompt models, permissions controller, and middleware for enhanced type safety refactor: update resourceType references from PROMPT_GROUP to PROMPTGROUP for consistency across models, middleware, and components refactor: standardize access role IDs and resource type usage across agent, file, and prompt models for improved type safety and consistency chore: add typedefs for TUpdateResourcePermissionsRequest and TUpdateResourcePermissionsResponse to enhance type definitions chore: move SearchPicker to PeoplePicker dir refactor: implement debouncing for query changes in SearchPicker for improved performance chore: fix typing, import order for agent admin settings fix: agent admin settings, prevent agent form submission refactor: rename `ACCESS_ROLE_IDS` to `AccessRoleIds` refactor: replace PermissionBits with PERMISSION_BITS refactor: replace PERMISSION_BITS with PermissionBits
2025-07-28 17:52:36 -04:00
resourceType: ResourceType.AGENT,
resourceId: agent._id,
accessRoleId: publicRoleId,
grantedBy: agent.author,
});
}
results.migrated++;
logger.debug(`Migrated agent "${agent.name}" [${description}]`, {
agentId: agent.id,
author: agent.author,
isGlobal,
isCollab,
publicRole: publicRoleId,
});
} catch (error) {
results.errors++;
logger.error(`Failed to migrate agent "${agent.name}"`, {
agentId: agent.id,
author: agent.author,
error: error.message,
});
}
}
// Brief pause between batches
await new Promise((resolve) => setTimeout(resolve, 100));
}
logger.info('Enhanced migration completed', results);
return results;
}
if (require.main === module) {
const dryRun = process.argv.includes('--dry-run');
const batchSize =
parseInt(process.argv.find((arg) => arg.startsWith('--batch-size='))?.split('=')[1]) || 100;
migrateAgentPermissionsEnhanced({ dryRun, batchSize })
.then((result) => {
if (dryRun) {
console.log('\n=== DRY RUN RESULTS ===');
console.log(`Total agents to migrate: ${result.summary.total}`);
console.log(`- Global Edit Access: ${result.summary.globalEditAccess} agents`);
console.log(`- Global View Access: ${result.summary.globalViewAccess} agents`);
console.log(`- Private Agents: ${result.summary.privateAgents} agents`);
if (result.details.globalEditAccess.length > 0) {
console.log('\nGlobal Edit Access agents:');
result.details.globalEditAccess.forEach((agent, i) => {
console.log(` ${i + 1}. "${agent.name}" (${agent.id})`);
});
}
if (result.details.globalViewAccess.length > 0) {
console.log('\nGlobal View Access agents:');
result.details.globalViewAccess.forEach((agent, i) => {
console.log(` ${i + 1}. "${agent.name}" (${agent.id})`);
});
}
if (result.details.privateAgents.length > 0) {
console.log('\nPrivate agents:');
result.details.privateAgents.forEach((agent, i) => {
console.log(` ${i + 1}. "${agent.name}" (${agent.id})`);
});
}
} else {
console.log('\nMigration Results:', JSON.stringify(result, null, 2));
}
process.exit(0);
})
.catch((error) => {
console.error('Enhanced migration failed:', error);
process.exit(1);
});
}
module.exports = { migrateAgentPermissionsEnhanced };