mirror of
https://github.com/danny-avila/LibreChat.git
synced 2026-03-12 11:02:37 +01:00
* feat: Implement System Grants for Role-Based Capabilities
- Added a new `systemGrant` model and associated methods to manage role-based capabilities within the application.
- Introduced middleware functions `hasCapability` and `requireCapability` to check user permissions based on their roles.
- Updated the database seeding process to include system grants for the ADMIN role, ensuring all necessary capabilities are assigned on startup.
- Enhanced type definitions and schemas to support the new system grant functionality, improving overall type safety and clarity in the codebase.
* test: Add unit tests for capabilities middleware and system grant methods
- Introduced comprehensive unit tests for the capabilities middleware, including `hasCapability` and `requireCapability`, ensuring proper permission checks based on user roles.
- Added tests for the `SystemGrant` methods, verifying the seeding of system grants, capability granting, and revocation processes.
- Enhanced test coverage for edge cases, including idempotency of grant operations and handling of unexpected errors in middleware.
- Utilized mocks for database interactions to isolate tests and improve reliability.
* refactor: Transition to Capability-Based Access Control
- Replaced role-based access checks with capability-based checks across various middleware and routes, enhancing permission management.
- Introduced `hasCapability` and `requireCapability` functions to streamline capability verification for user actions.
- Updated relevant routes and middleware to utilize the new capability system, ensuring consistent permission enforcement.
- Enhanced type definitions and added tests for the new capability functions, improving overall code reliability and maintainability.
* test: Enhance capability-based access tests for ADMIN role
- Updated tests to reflect the new capability-based access control, specifically for the ADMIN role.
- Modified test descriptions to clarify that users with the MANAGE_AGENTS capability can bypass permission checks.
- Seeded capabilities for the ADMIN role in multiple test files to ensure consistent permission checks across different routes and middleware.
- Improved overall test coverage for capability verification, ensuring robust permission management.
* test: Update capability tests for MCP server access
- Renamed test to reflect the correct capability for bypassing permission checks, changing from MANAGE_AGENTS to MANAGE_MCP_SERVERS.
- Updated seeding of capabilities for the ADMIN role to align with the new capability structure.
- Ensured consistency in capability definitions across tests and middleware for improved permission management.
* feat: Add hasConfigCapability for enhanced config access control
- Introduced `hasConfigCapability` function to check user permissions for managing or reading specific config sections.
- Updated middleware to export the new capability function, ensuring consistent access control across the application.
- Enhanced unit tests to cover various scenarios for the new capability, improving overall test coverage and reliability.
* fix: Update tenantId filter in createSystemGrantMethods
- Added a condition to set tenantId filter to { $exists: false } when tenantId is null, ensuring proper handling of cases where tenantId is not provided.
- This change improves the robustness of the system grant methods by explicitly managing the absence of tenantId in the filter logic.
* fix: account deletion capability check
- Updated the `canDeleteAccount` middleware to ensure that the `hasManageUsers` capability check only occurs if a user is present, preventing potential errors when the user object is undefined.
- This change improves the robustness of the account deletion logic by ensuring proper handling of user permissions.
* refactor: Optimize seeding of system grants for ADMIN role
- Replaced sequential capability granting with parallel execution using Promise.all in the seedSystemGrants function.
- This change improves performance and efficiency during the initialization of system grants, ensuring all capabilities are granted concurrently.
* refactor: Simplify systemGrantSchema index definition
- Removed the sparse option from the unique index on principalType, principalId, capability, and tenantId in the systemGrantSchema.
- This change streamlines the index definition, potentially improving query performance and clarity in the schema design.
* refactor: Reorganize role capability check in roles route
- Moved the capability check for reading roles to occur after parsing the roleName, improving code clarity and structure.
- This change ensures that the authorization logic is consistently applied before fetching role details, enhancing overall permission management.
* refactor: Remove unused ISystemGrant interface from systemCapabilities.ts
- Deleted the ISystemGrant interface as it was no longer needed, streamlining the code and improving clarity.
- This change helps reduce clutter in the file and focuses on relevant capabilities for the system.
* refactor: Migrate SystemCapabilities to data-schemas
- Replaced imports of SystemCapabilities from 'librechat-data-provider' with imports from '@librechat/data-schemas' across multiple files.
- This change centralizes the management of system capabilities, improving code organization and maintainability.
* refactor: Update account deletion middleware and capability checks
- Modified the `canDeleteAccount` middleware to ensure that the account deletion permission is only granted to users with the `MANAGE_USERS` capability, improving security and clarity in permission management.
- Enhanced error logging for unauthorized account deletion attempts, providing better insights into permission issues.
- Updated the `capabilities.ts` file to ensure consistent handling of user authentication checks, improving robustness in capability verification.
- Refined type definitions in `systemGrant.ts` and `systemGrantMethods.ts` to utilize the `PrincipalType` enum, enhancing type safety and code clarity.
* refactor: Extract principal ID normalization into a separate function
- Introduced `normalizePrincipalId` function to streamline the normalization of principal IDs based on their type, enhancing code clarity and reusability.
- Updated references in `createSystemGrantMethods` to utilize the new normalization function, improving maintainability and reducing code duplication.
* test: Add unit tests for principalId normalization in systemGrant
- Introduced tests for the `grantCapability`, `revokeCapability`, and `getCapabilitiesForPrincipal` methods to verify correct handling of principalId normalization between string and ObjectId formats.
- Enhanced the `capabilities.ts` middleware to utilize the `PrincipalType` enum for improved type safety.
- Added a new utility function `normalizePrincipalId` to streamline principal ID normalization logic, ensuring consistent behavior across the application.
* feat: Introduce capability implications and enhance system grant methods
- Added `CapabilityImplications` to define relationships between broader and implied capabilities, allowing for more intuitive permission checks.
- Updated `createSystemGrantMethods` to expand capability queries to include implied capabilities, improving authorization logic.
- Enhanced `systemGrantSchema` to include an `expiresAt` field for future TTL enforcement of grants, and added validation to ensure `tenantId` is not set to null.
- Documented authorization requirements for prompt group and prompt deletion methods to clarify access control expectations.
* test: Add unit tests for canDeleteAccount middleware
- Introduced unit tests for the `canDeleteAccount` middleware to verify account deletion permissions based on user roles and capabilities.
- Covered scenarios for both allowed and blocked account deletions, including checks for ADMIN users with the `MANAGE_USERS` capability and handling of undefined user cases.
- Enhanced test structure to ensure clarity and maintainability of permission checks in the middleware.
* fix: Add principalType enum validation to SystemGrant schema
Without enum validation, any string value was accepted for principalType
and silently stored. Invalid documents would never match capability
queries, creating phantom grants impossible to diagnose without raw DB
inspection. All other ACL models in the codebase validate this field.
* fix: Replace seedSystemGrants Promise.all with bulkWrite for concurrency safety
When two server instances start simultaneously (K8s rolling deploy, PM2
cluster), both call seedSystemGrants. With Promise.all + findOneAndUpdate
upsert, both instances may attempt to insert the same documents, causing
E11000 duplicate key errors that crash server startup.
bulkWrite with ordered:false handles concurrent upserts gracefully and
reduces 17 individual round trips to a single network call. The returned
documents (previously discarded) are no longer fetched.
* perf: Add AsyncLocalStorage per-request cache for capability checks
Every hasCapability call previously required 2 DB round trips
(getUserPrincipals + SystemGrant.exists) — replacing what were O(1)
string comparisons. Routes like patchPromptGroup triggered this twice,
and hasConfigCapability's fallback path resolved principals twice.
This adds a per-request AsyncLocalStorage cache that:
- Caches resolved principals (same for all checks within one request)
- Caches capability check results (same user+cap = same answer)
- Automatically scoped to request lifetime (no stale grants)
- Falls through to DB when no store exists (background jobs, tests)
- Requires no signature changes to hasCapability
The capabilityContextMiddleware is registered at the app level before
all routes, initializing a fresh store per request.
* fix: Add error handling for inline hasCapability calls
canDeleteAccount, fetchAssistants, and validateAuthor all call
hasCapability without try-catch. These were previously O(1) string
comparisons that could never throw. Now they hit the database and can
fail on connection timeout or transient errors.
Wrap each call in try-catch, defaulting to deny (false) on error.
This ensures a DB hiccup returns a clean 403 instead of an unhandled
500 with a stack trace.
* test: Add canDeleteAccount DB-error resilience test
Tests that hasCapability rejection (e.g., DB timeout) results in a clean
403 rather than an unhandled exception. Validates the error handling
added in the previous commit.
* refactor: Use barrel import for hasCapability in validateAuthor
Import from ~/server/middleware barrel instead of directly from
~/server/middleware/roles/capabilities for consistency with other
non-middleware consumers. Files within the middleware barrel itself
must continue using direct imports to avoid circular requires.
* refactor: Remove misleading pre('save') hook from SystemGrant schema
The pre('save') hook normalized principalId for USER/GROUP principals,
but the primary write path (grantCapability) uses findOneAndUpdate —
which does not trigger save hooks. The normalization was already handled
explicitly in grantCapability itself. The hook created a false impression
of schema-level enforcement that only covered save()/create() paths.
Replace with a comment documenting that all writes must go through
grantCapability.
* feat: Add READ_ASSISTANTS capability to complete manage/read pair
Every other managed resource had a paired READ_X / MANAGE_X capability
except assistants. This adds READ_ASSISTANTS and registers the
MANAGE_ASSISTANTS → READ_ASSISTANTS implication in CapabilityImplications,
enabling future read-only assistant visibility grants.
* chore: Reorder systemGrant methods for clarity
Moved hasCapabilityForPrincipals to a more logical position in the returned object of createSystemGrantMethods, improving code readability. This change also maintains the inclusion of seedSystemGrants in the export, ensuring all necessary methods are available.
* fix: Wrap seedSystemGrants in try-catch to avoid blocking startup
Seeding capabilities is idempotent and will succeed on the next restart.
A transient DB error during seeding should not prevent the server from
starting — log the error and continue.
* refactor: Improve capability check efficiency and add audit logging
Move hasCapability calls after cheap early-exits in validateAuthor and
fetchAssistants so the DB check only runs when its result matters. Add
logger.debug on every capability bypass grant across all 7 call sites
for auditability, and log errors in catch blocks instead of silently
swallowing them.
* test: Add integration tests for AsyncLocalStorage capability caching
Exercises the full vertical — ALS context, generateCapabilityCheck,
real getUserPrincipals, real hasCapabilityForPrincipals, real MongoDB
via MongoMemoryServer. Covers per-request caching, cross-context
isolation, concurrent request isolation, negative caching, capability
implications, tenant scoping, group-based grants, and requireCapability
middleware.
* test: Add systemGrant data-layer and ALS edge-case integration tests
systemGrant.spec.ts (51 tests): Full integration tests for all
systemGrant methods against real MongoDB — grant/revoke lifecycle,
principalId normalization (string→ObjectId for USER/GROUP, string for
ROLE), capability implications (both directions), tenant scoping,
schema validation (null tenantId, invalid enum, required fields,
unique compound index).
capabilities.integration.spec.ts (27 tests): Adds ALS edge cases —
missing context degrades gracefully with no caching (background jobs,
child processes), nested middleware creates independent inner context,
optional-chaining safety when store is undefined, mid-request grant
changes are invisible due to result caching, requireCapability works
without ALS, and interleaved concurrent contexts maintain isolation.
* fix: Add worker thread guards to capability ALS usage
Detect when hasCapability or capabilityContextMiddleware is called from
a worker thread (where ALS context does not propagate from the parent).
hasCapability logs a warn-once per factory instance; the middleware logs
an error since mounting Express middleware in a worker is likely a
misconfiguration. Both continue to function correctly — the guard is
observability, not a hard block.
* fix: Include tenantId in ALS principal cache key for tenant isolation
The principal cache key was user.id:user.role, which would reuse
cached principals across tenants for the same user within a request.
When getUserPrincipals gains tenant-scoped group resolution, principals
from tenant-a would incorrectly serve tenant-b checks. Changed to
user.id:user.role:user.tenantId to prevent cross-tenant cache hits.
Adds integration test proving separate principal lookups per tenantId.
* test: Remove redundant mocked capabilities.spec.js
The JS wrapper test (7 tests, all mocked) is a strict subset of
capabilities.integration.spec.ts (28 tests, real MongoDB). Every
scenario it covered — hasCapability true/false, tenantId passthrough,
requireCapability 403/500, error handling — is tested with higher
fidelity in the integration suite.
* test: Replace mocked canDeleteAccount tests with real MongoDB integration
Remove hasCapability mock — tests now exercise the full capability
chain against real MongoDB (getUserPrincipals, hasCapabilityForPrincipals,
SystemGrant collection). Only mocks remaining are logger and cache.
Adds new coverage: admin role without grant is blocked, user-level
grant bypasses deletion restriction, null user handling.
* test: Add comprehensive tests for ACL entry management and user group methods
Introduces new tests for `deleteAclEntries`, `bulkWriteAclEntries`, and `findPublicResourceIds` in `aclEntry.spec.ts`, ensuring proper functionality for deleting and bulk managing ACL entries. Additionally, enhances `userGroup.spec.ts` with tests for finding groups by ID and name pattern, including external ID matching and source filtering. These changes improve coverage and validate the integrity of ACL and user group operations against real MongoDB interactions.
* refactor: Update capability checks and logging for better clarity and error handling
Replaced `MANAGE_USERS` with `ACCESS_ADMIN` in the `canDeleteAccount` middleware and related tests to align with updated permission structure. Enhanced logging in various middleware functions to use `logger.warn` for capability check failures, providing clearer error messages. Additionally, refactored capability checks in the `patchPromptGroup` and `validateAuthor` functions to improve readability and maintainability. This commit also includes adjustments to the `systemGrant` methods to implement retry logic for transient failures during capability seeding, ensuring robustness in the face of database errors.
* refactor: Enhance logging and retry logic in seedSystemGrants method
Updated the logging format in the seedSystemGrants method to include error messages for better clarity. Improved the retry mechanism by explicitly mocking multiple failures in tests, ensuring robust error handling during transient database issues. Additionally, refined imports in the systemGrant schema for better type management.
* refactor: Consolidate imports in canDeleteAccount middleware
Merged logger and SystemCapabilities imports from the data-schemas module into a single line for improved readability and maintainability of the code. This change streamlines the import statements in the canDeleteAccount middleware.
* test: Enhance systemGrant tests for error handling and capability validation
Added tests to the systemGrant methods to handle various error scenarios, including E11000 race conditions, invalid ObjectId strings for USER and GROUP principals, and invalid capability strings. These enhancements improve the robustness of the capability granting and revoking logic, ensuring proper error propagation and validation of inputs.
* fix: Wrap hasCapability calls in deny-by-default try-catch at remaining sites
canAccessResource, files.js, and roles.js all had hasCapability inside
outer try-catch blocks that returned 500 on DB failure instead of
falling through to the regular ACL check. This contradicts the
deny-by-default pattern used everywhere else.
Also removes raw error.message from the roles.js 500 response to
prevent internal host/connection info leaking to clients.
* fix: Normalize user ID in canDeleteAccount before passing to hasCapability
requireCapability normalizes req.user.id via _id?.toString() fallback,
but canDeleteAccount passed raw req.user directly. If req.user.id is
absent (some auth layers only populate _id), getUserPrincipals received
undefined, silently returning empty principals and blocking the bypass.
* fix: Harden systemGrant schema and type safety
- Reject empty string tenantId in schema validator (was only blocking
null; empty string silently orphaned documents)
- Fix reverseImplications to use BaseSystemCapability[] instead of
string[], preserving the narrow discriminated type
- Document READ_ASSISTANTS as reserved/unenforced
* test: Use fake timers for seedSystemGrants retry tests and add tenantId validation
- Switch retry tests to jest.useFakeTimers() to eliminate 3+ seconds
of real setTimeout delays per test run
- Add regression test for empty-string tenantId rejection
* docs: Add TODO(#12091) comments for tenant-scoped capability gaps
In multi-tenant mode, platform-level grants (no tenantId) won't match
tenant-scoped queries, breaking admin access. getUserPrincipals also
returns cross-tenant group memberships. Both need fixes in #12091.
647 lines
20 KiB
TypeScript
647 lines
20 KiB
TypeScript
import type { Model, Types } from 'mongoose';
|
|
import { ResourceType, SystemCategories } from 'librechat-data-provider';
|
|
import type { IPrompt, IPromptGroup, IPromptGroupDocument } from '~/types';
|
|
import { escapeRegExp } from '~/utils/string';
|
|
import logger from '~/config/winston';
|
|
|
|
export interface PromptDeps {
|
|
/** Removes all ACL permissions for a resource. Injected from PermissionService. */
|
|
removeAllPermissions: (params: { resourceType: string; resourceId: unknown }) => Promise<void>;
|
|
}
|
|
|
|
export function createPromptMethods(mongoose: typeof import('mongoose'), deps: PromptDeps) {
|
|
const { ObjectId } = mongoose.Types;
|
|
|
|
/**
|
|
* Batch-fetches production prompts for an array of prompt groups
|
|
* and attaches them as `productionPrompt` field.
|
|
*/
|
|
async function attachProductionPrompts(
|
|
groups: Array<Record<string, unknown>>,
|
|
): Promise<Array<Record<string, unknown>>> {
|
|
const Prompt = mongoose.models.Prompt as Model<IPrompt>;
|
|
const uniqueIds = [
|
|
...new Set(groups.map((g) => (g.productionId as Types.ObjectId)?.toString()).filter(Boolean)),
|
|
];
|
|
if (uniqueIds.length === 0) {
|
|
return groups.map((g) => ({ ...g, productionPrompt: null }));
|
|
}
|
|
|
|
const prompts = await Prompt.find({ _id: { $in: uniqueIds } })
|
|
.select('prompt')
|
|
.lean();
|
|
const promptMap = new Map(prompts.map((p) => [p._id.toString(), p]));
|
|
|
|
return groups.map((g) => ({
|
|
...g,
|
|
productionPrompt: g.productionId
|
|
? (promptMap.get((g.productionId as Types.ObjectId).toString()) ?? null)
|
|
: null,
|
|
}));
|
|
}
|
|
|
|
/**
|
|
* Get all prompt groups with filters (no pagination).
|
|
*/
|
|
async function getAllPromptGroups(filter: Record<string, unknown>) {
|
|
try {
|
|
const PromptGroup = mongoose.models.PromptGroup as Model<IPromptGroupDocument>;
|
|
const { name, ...query } = filter as {
|
|
name?: string;
|
|
category?: string;
|
|
[key: string]: unknown;
|
|
};
|
|
|
|
if (name) {
|
|
(query as Record<string, unknown>).name = new RegExp(escapeRegExp(name), 'i');
|
|
}
|
|
if (!query.category) {
|
|
delete query.category;
|
|
} else if (query.category === SystemCategories.MY_PROMPTS) {
|
|
delete query.category;
|
|
} else if (query.category === SystemCategories.NO_CATEGORY) {
|
|
query.category = '';
|
|
} else if (query.category === SystemCategories.SHARED_PROMPTS) {
|
|
delete query.category;
|
|
}
|
|
|
|
const groups = await PromptGroup.find(query)
|
|
.sort({ createdAt: -1 })
|
|
.select('name oneliner category author authorName createdAt updatedAt command productionId')
|
|
.lean();
|
|
return await attachProductionPrompts(groups as unknown as Array<Record<string, unknown>>);
|
|
} catch (error) {
|
|
console.error('Error getting all prompt groups', error);
|
|
return { message: 'Error getting all prompt groups' };
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Get prompt groups with pagination and filters.
|
|
*/
|
|
async function getPromptGroups(filter: Record<string, unknown>) {
|
|
try {
|
|
const PromptGroup = mongoose.models.PromptGroup as Model<IPromptGroupDocument>;
|
|
const {
|
|
pageNumber = 1,
|
|
pageSize = 10,
|
|
name,
|
|
...query
|
|
} = filter as {
|
|
pageNumber?: number | string;
|
|
pageSize?: number | string;
|
|
name?: string;
|
|
category?: string;
|
|
[key: string]: unknown;
|
|
};
|
|
|
|
const validatedPageNumber = Math.max(parseInt(String(pageNumber), 10), 1);
|
|
const validatedPageSize = Math.max(parseInt(String(pageSize), 10), 1);
|
|
|
|
if (name) {
|
|
(query as Record<string, unknown>).name = new RegExp(escapeRegExp(name), 'i');
|
|
}
|
|
if (!query.category) {
|
|
delete query.category;
|
|
} else if (query.category === SystemCategories.MY_PROMPTS) {
|
|
delete query.category;
|
|
} else if (query.category === SystemCategories.NO_CATEGORY) {
|
|
query.category = '';
|
|
} else if (query.category === SystemCategories.SHARED_PROMPTS) {
|
|
delete query.category;
|
|
}
|
|
|
|
const skip = (validatedPageNumber - 1) * validatedPageSize;
|
|
const limit = validatedPageSize;
|
|
|
|
const [groups, totalPromptGroups] = await Promise.all([
|
|
PromptGroup.find(query)
|
|
.sort({ createdAt: -1 })
|
|
.skip(skip)
|
|
.limit(limit)
|
|
.select(
|
|
'name numberOfGenerations oneliner category productionId author authorName createdAt updatedAt',
|
|
)
|
|
.lean(),
|
|
PromptGroup.countDocuments(query),
|
|
]);
|
|
|
|
const promptGroups = await attachProductionPrompts(
|
|
groups as unknown as Array<Record<string, unknown>>,
|
|
);
|
|
|
|
return {
|
|
promptGroups,
|
|
pageNumber: validatedPageNumber.toString(),
|
|
pageSize: validatedPageSize.toString(),
|
|
pages: Math.ceil(totalPromptGroups / validatedPageSize).toString(),
|
|
};
|
|
} catch (error) {
|
|
console.error('Error getting prompt groups', error);
|
|
return { message: 'Error getting prompt groups' };
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Delete a prompt group and its prompts, cleaning up ACL permissions.
|
|
*
|
|
* **Authorization is enforced upstream.** This method performs no ownership
|
|
* check — it deletes any group by ID. Callers must gate access via
|
|
* `canAccessPromptGroupResource` middleware before invoking this.
|
|
*/
|
|
async function deletePromptGroup({ _id }: { _id: string }) {
|
|
const PromptGroup = mongoose.models.PromptGroup as Model<IPromptGroupDocument>;
|
|
const Prompt = mongoose.models.Prompt as Model<IPrompt>;
|
|
|
|
const query: Record<string, unknown> = { _id };
|
|
const groupQuery: Record<string, unknown> = { groupId: new ObjectId(_id) };
|
|
|
|
const response = await PromptGroup.deleteOne(query);
|
|
|
|
if (!response || response.deletedCount === 0) {
|
|
throw new Error('Prompt group not found');
|
|
}
|
|
|
|
await Prompt.deleteMany(groupQuery);
|
|
|
|
try {
|
|
await deps.removeAllPermissions({
|
|
resourceType: ResourceType.PROMPTGROUP,
|
|
resourceId: _id,
|
|
});
|
|
} catch (error) {
|
|
logger.error('Error removing promptGroup permissions:', error);
|
|
}
|
|
|
|
return { message: 'Prompt group deleted successfully' };
|
|
}
|
|
|
|
/**
|
|
* Get prompt groups by accessible IDs with optional cursor-based pagination.
|
|
*/
|
|
async function getListPromptGroupsByAccess({
|
|
accessibleIds = [],
|
|
otherParams = {},
|
|
limit = null,
|
|
after = null,
|
|
}: {
|
|
accessibleIds?: Types.ObjectId[];
|
|
otherParams?: Record<string, unknown>;
|
|
limit?: number | null;
|
|
after?: string | null;
|
|
}) {
|
|
const PromptGroup = mongoose.models.PromptGroup as Model<IPromptGroupDocument>;
|
|
const isPaginated = limit !== null && limit !== undefined;
|
|
const normalizedLimit = isPaginated
|
|
? Math.min(Math.max(1, parseInt(String(limit)) || 20), 100)
|
|
: null;
|
|
|
|
const baseQuery: Record<string, unknown> = {
|
|
...otherParams,
|
|
_id: { $in: accessibleIds },
|
|
};
|
|
|
|
if (after && typeof after === 'string' && after !== 'undefined' && after !== 'null') {
|
|
try {
|
|
const cursor = JSON.parse(Buffer.from(after, 'base64').toString('utf8'));
|
|
const { updatedAt, _id } = cursor;
|
|
|
|
const cursorCondition = {
|
|
$or: [
|
|
{ updatedAt: { $lt: new Date(updatedAt) } },
|
|
{ updatedAt: new Date(updatedAt), _id: { $gt: new ObjectId(_id) } },
|
|
],
|
|
};
|
|
|
|
if (Object.keys(baseQuery).length > 0) {
|
|
baseQuery.$and = [{ ...baseQuery }, cursorCondition];
|
|
Object.keys(baseQuery).forEach((key) => {
|
|
if (key !== '$and') {
|
|
delete baseQuery[key];
|
|
}
|
|
});
|
|
} else {
|
|
Object.assign(baseQuery, cursorCondition);
|
|
}
|
|
} catch (error) {
|
|
logger.warn('Invalid cursor:', (error as Error).message);
|
|
}
|
|
}
|
|
|
|
const findQuery = PromptGroup.find(baseQuery)
|
|
.sort({ updatedAt: -1, _id: 1 })
|
|
.select(
|
|
'name numberOfGenerations oneliner category productionId author authorName createdAt updatedAt',
|
|
);
|
|
|
|
if (isPaginated && normalizedLimit) {
|
|
findQuery.limit(normalizedLimit + 1);
|
|
}
|
|
|
|
const groups = await findQuery.lean();
|
|
const promptGroups = await attachProductionPrompts(
|
|
groups as unknown as Array<Record<string, unknown>>,
|
|
);
|
|
|
|
const hasMore = isPaginated && normalizedLimit ? promptGroups.length > normalizedLimit : false;
|
|
const data = (
|
|
isPaginated && normalizedLimit ? promptGroups.slice(0, normalizedLimit) : promptGroups
|
|
).map((group) => {
|
|
if (group.author) {
|
|
group.author = (group.author as Types.ObjectId).toString();
|
|
}
|
|
return group;
|
|
});
|
|
|
|
let nextCursor: string | null = null;
|
|
if (isPaginated && hasMore && data.length > 0 && normalizedLimit) {
|
|
const lastGroup = promptGroups[normalizedLimit - 1] as Record<string, unknown>;
|
|
nextCursor = Buffer.from(
|
|
JSON.stringify({
|
|
updatedAt: (lastGroup.updatedAt as Date).toISOString(),
|
|
_id: (lastGroup._id as Types.ObjectId).toString(),
|
|
}),
|
|
).toString('base64');
|
|
}
|
|
|
|
return {
|
|
object: 'list' as const,
|
|
data,
|
|
first_id: data.length > 0 ? (data[0]._id as Types.ObjectId).toString() : null,
|
|
last_id: data.length > 0 ? (data[data.length - 1]._id as Types.ObjectId).toString() : null,
|
|
has_more: hasMore,
|
|
after: nextCursor,
|
|
};
|
|
}
|
|
|
|
/**
|
|
* Create a prompt and its respective group.
|
|
*/
|
|
async function createPromptGroup(saveData: {
|
|
prompt: Record<string, unknown>;
|
|
group: Record<string, unknown>;
|
|
author: string;
|
|
authorName: string;
|
|
}) {
|
|
try {
|
|
const PromptGroup = mongoose.models.PromptGroup as Model<IPromptGroupDocument>;
|
|
const Prompt = mongoose.models.Prompt as Model<IPrompt>;
|
|
const { prompt, group, author, authorName } = saveData;
|
|
|
|
let newPromptGroup = await PromptGroup.findOneAndUpdate(
|
|
{ ...group, author, authorName, productionId: null },
|
|
{ $setOnInsert: { ...group, author, authorName, productionId: null } },
|
|
{ new: true, upsert: true },
|
|
)
|
|
.lean()
|
|
.select('-__v')
|
|
.exec();
|
|
|
|
const newPrompt = await Prompt.findOneAndUpdate(
|
|
{ ...prompt, author, groupId: newPromptGroup!._id },
|
|
{ $setOnInsert: { ...prompt, author, groupId: newPromptGroup!._id } },
|
|
{ new: true, upsert: true },
|
|
)
|
|
.lean()
|
|
.select('-__v')
|
|
.exec();
|
|
|
|
newPromptGroup = (await PromptGroup.findByIdAndUpdate(
|
|
newPromptGroup!._id,
|
|
{ productionId: newPrompt!._id },
|
|
{ new: true },
|
|
)
|
|
.lean()
|
|
.select('-__v')
|
|
.exec())!;
|
|
|
|
return {
|
|
prompt: newPrompt,
|
|
group: {
|
|
...newPromptGroup,
|
|
productionPrompt: { prompt: (newPrompt as unknown as IPrompt).prompt },
|
|
},
|
|
};
|
|
} catch (error) {
|
|
logger.error('Error saving prompt group', error);
|
|
throw new Error('Error saving prompt group');
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Save a prompt.
|
|
*/
|
|
async function savePrompt(saveData: {
|
|
prompt: Record<string, unknown>;
|
|
author: string | Types.ObjectId;
|
|
}) {
|
|
try {
|
|
const Prompt = mongoose.models.Prompt as Model<IPrompt>;
|
|
const { prompt, author } = saveData;
|
|
const newPromptData = { ...prompt, author };
|
|
|
|
let newPrompt;
|
|
try {
|
|
newPrompt = await Prompt.create(newPromptData);
|
|
} catch (error: unknown) {
|
|
if ((error as Error)?.message?.includes('groupId_1_version_1')) {
|
|
await Prompt.db.collection('prompts').dropIndex('groupId_1_version_1');
|
|
} else {
|
|
throw error;
|
|
}
|
|
newPrompt = await Prompt.create(newPromptData);
|
|
}
|
|
|
|
return { prompt: newPrompt };
|
|
} catch (error) {
|
|
logger.error('Error saving prompt', error);
|
|
return { message: 'Error saving prompt' };
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Get prompts by filter.
|
|
*/
|
|
async function getPrompts(filter: Record<string, unknown>) {
|
|
try {
|
|
const Prompt = mongoose.models.Prompt as Model<IPrompt>;
|
|
return await Prompt.find(filter).sort({ createdAt: -1 }).lean();
|
|
} catch (error) {
|
|
logger.error('Error getting prompts', error);
|
|
return { message: 'Error getting prompts' };
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Get a single prompt by filter.
|
|
*/
|
|
async function getPrompt(filter: Record<string, unknown>) {
|
|
try {
|
|
const Prompt = mongoose.models.Prompt as Model<IPrompt>;
|
|
if (filter.groupId) {
|
|
filter.groupId = new ObjectId(filter.groupId as string);
|
|
}
|
|
return await Prompt.findOne(filter).lean();
|
|
} catch (error) {
|
|
logger.error('Error getting prompt', error);
|
|
return { message: 'Error getting prompt' };
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Get random prompt groups from distinct categories.
|
|
*/
|
|
async function getRandomPromptGroups(filter: { skip: number | string; limit: number | string }) {
|
|
try {
|
|
const PromptGroup = mongoose.models.PromptGroup as Model<IPromptGroupDocument>;
|
|
const categories = await PromptGroup.distinct('category', { category: { $ne: '' } });
|
|
|
|
for (let i = categories.length - 1; i > 0; i--) {
|
|
const j = Math.floor(Math.random() * (i + 1));
|
|
[categories[i], categories[j]] = [categories[j], categories[i]];
|
|
}
|
|
|
|
const skip = +filter.skip;
|
|
const limit = +filter.limit;
|
|
const selectedCategories = categories.slice(skip, skip + limit);
|
|
|
|
if (selectedCategories.length === 0) {
|
|
return { prompts: [] };
|
|
}
|
|
|
|
const groups = await PromptGroup.find({ category: { $in: selectedCategories } }).lean();
|
|
|
|
const groupByCategory = new Map<string, unknown>();
|
|
for (const group of groups) {
|
|
if (!groupByCategory.has(group.category)) {
|
|
groupByCategory.set(group.category, group);
|
|
}
|
|
}
|
|
|
|
const prompts = selectedCategories
|
|
.map((cat: string) => groupByCategory.get(cat))
|
|
.filter(Boolean);
|
|
|
|
return { prompts };
|
|
} catch (error) {
|
|
logger.error('Error getting prompt groups', error);
|
|
return { message: 'Error getting prompt groups' };
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Get prompt groups with populated prompts.
|
|
*/
|
|
async function getPromptGroupsWithPrompts(filter: Record<string, unknown>) {
|
|
try {
|
|
const PromptGroup = mongoose.models.PromptGroup as Model<IPromptGroupDocument>;
|
|
return await PromptGroup.findOne(filter)
|
|
.populate({
|
|
path: 'prompts',
|
|
select: '-_id -__v -user',
|
|
})
|
|
.select('-_id -__v -user')
|
|
.lean();
|
|
} catch (error) {
|
|
logger.error('Error getting prompt groups', error);
|
|
return { message: 'Error getting prompt groups' };
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Get a single prompt group by filter.
|
|
*/
|
|
async function getPromptGroup(filter: Record<string, unknown>) {
|
|
try {
|
|
const PromptGroup = mongoose.models.PromptGroup as Model<IPromptGroupDocument>;
|
|
return await PromptGroup.findOne(filter).lean();
|
|
} catch (error) {
|
|
logger.error('Error getting prompt group', error);
|
|
return { message: 'Error getting prompt group' };
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Delete a prompt, potentially removing the group if it's the last prompt.
|
|
*
|
|
* **Authorization is enforced upstream.** This method performs no ownership
|
|
* check — it deletes any prompt by ID. Callers must gate access via
|
|
* `canAccessPromptViaGroup` middleware before invoking this.
|
|
*/
|
|
async function deletePrompt({
|
|
promptId,
|
|
groupId,
|
|
}: {
|
|
promptId: string | Types.ObjectId;
|
|
groupId: string | Types.ObjectId;
|
|
}) {
|
|
const Prompt = mongoose.models.Prompt as Model<IPrompt>;
|
|
const PromptGroup = mongoose.models.PromptGroup as Model<IPromptGroupDocument>;
|
|
|
|
const query: Record<string, unknown> = { _id: promptId, groupId };
|
|
const { deletedCount } = await Prompt.deleteOne(query);
|
|
if (deletedCount === 0) {
|
|
throw new Error('Failed to delete the prompt');
|
|
}
|
|
|
|
const remainingPrompts = await Prompt.find({ groupId })
|
|
.select('_id')
|
|
.sort({ createdAt: 1 })
|
|
.lean();
|
|
|
|
if (remainingPrompts.length === 0) {
|
|
try {
|
|
await deps.removeAllPermissions({
|
|
resourceType: ResourceType.PROMPTGROUP,
|
|
resourceId: groupId,
|
|
});
|
|
} catch (error) {
|
|
logger.error('Error removing promptGroup permissions:', error);
|
|
}
|
|
|
|
await PromptGroup.deleteOne({ _id: groupId });
|
|
|
|
return {
|
|
prompt: 'Prompt deleted successfully',
|
|
promptGroup: {
|
|
message: 'Prompt group deleted successfully',
|
|
id: groupId,
|
|
},
|
|
};
|
|
} else {
|
|
const promptGroup = (await PromptGroup.findById(
|
|
groupId,
|
|
).lean()) as unknown as IPromptGroup | null;
|
|
if (promptGroup && promptGroup.productionId?.toString() === promptId.toString()) {
|
|
await PromptGroup.updateOne(
|
|
{ _id: groupId },
|
|
{ productionId: remainingPrompts[remainingPrompts.length - 1]._id },
|
|
);
|
|
}
|
|
|
|
return { prompt: 'Prompt deleted successfully' };
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Delete all prompts and prompt groups created by a specific user.
|
|
*/
|
|
async function deleteUserPrompts(userId: string) {
|
|
try {
|
|
const PromptGroup = mongoose.models.PromptGroup as Model<IPromptGroupDocument>;
|
|
const Prompt = mongoose.models.Prompt as Model<IPrompt>;
|
|
const AclEntry = mongoose.models.AclEntry;
|
|
|
|
const promptGroups = (await getAllPromptGroups({ author: new ObjectId(userId) })) as Array<
|
|
Record<string, unknown>
|
|
>;
|
|
|
|
if (!Array.isArray(promptGroups) || promptGroups.length === 0) {
|
|
return;
|
|
}
|
|
|
|
const groupIds = promptGroups.map((group) => group._id as Types.ObjectId);
|
|
|
|
await AclEntry.deleteMany({
|
|
resourceType: ResourceType.PROMPTGROUP,
|
|
resourceId: { $in: groupIds },
|
|
});
|
|
|
|
await PromptGroup.deleteMany({ author: new ObjectId(userId) });
|
|
await Prompt.deleteMany({ author: new ObjectId(userId) });
|
|
} catch (error) {
|
|
logger.error('[deleteUserPrompts] General error:', error);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Update a prompt group.
|
|
*/
|
|
async function updatePromptGroup(filter: Record<string, unknown>, data: Record<string, unknown>) {
|
|
try {
|
|
const PromptGroup = mongoose.models.PromptGroup as Model<IPromptGroupDocument>;
|
|
const updateOps = {};
|
|
const updateData = { ...data, ...updateOps };
|
|
const updatedDoc = await PromptGroup.findOneAndUpdate(filter, updateData, {
|
|
new: true,
|
|
upsert: false,
|
|
});
|
|
|
|
if (!updatedDoc) {
|
|
throw new Error('Prompt group not found');
|
|
}
|
|
|
|
return updatedDoc;
|
|
} catch (error) {
|
|
logger.error('Error updating prompt group', error);
|
|
return { message: 'Error updating prompt group' };
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Make a prompt the production prompt for its group.
|
|
*/
|
|
async function makePromptProduction(promptId: string) {
|
|
try {
|
|
const Prompt = mongoose.models.Prompt as Model<IPrompt>;
|
|
const PromptGroup = mongoose.models.PromptGroup as Model<IPromptGroupDocument>;
|
|
|
|
const prompt = await Prompt.findById(promptId).lean();
|
|
|
|
if (!prompt) {
|
|
throw new Error('Prompt not found');
|
|
}
|
|
|
|
await PromptGroup.findByIdAndUpdate(
|
|
prompt.groupId,
|
|
{ productionId: prompt._id },
|
|
{ new: true },
|
|
)
|
|
.lean()
|
|
.exec();
|
|
|
|
return { message: 'Prompt production made successfully' };
|
|
} catch (error) {
|
|
logger.error('Error making prompt production', error);
|
|
return { message: 'Error making prompt production' };
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Update prompt labels.
|
|
*/
|
|
async function updatePromptLabels(_id: string, labels: unknown) {
|
|
try {
|
|
const Prompt = mongoose.models.Prompt as Model<IPrompt>;
|
|
const response = await Prompt.updateOne({ _id }, { $set: { labels } });
|
|
if (response.matchedCount === 0) {
|
|
return { message: 'Prompt not found' };
|
|
}
|
|
return { message: 'Prompt labels updated successfully' };
|
|
} catch (error) {
|
|
logger.error('Error updating prompt labels', error);
|
|
return { message: 'Error updating prompt labels' };
|
|
}
|
|
}
|
|
|
|
return {
|
|
getPromptGroups,
|
|
deletePromptGroup,
|
|
getAllPromptGroups,
|
|
getListPromptGroupsByAccess,
|
|
createPromptGroup,
|
|
savePrompt,
|
|
getPrompts,
|
|
getPrompt,
|
|
getRandomPromptGroups,
|
|
getPromptGroupsWithPrompts,
|
|
getPromptGroup,
|
|
deletePrompt,
|
|
deleteUserPrompts,
|
|
updatePromptGroup,
|
|
makePromptProduction,
|
|
updatePromptLabels,
|
|
};
|
|
}
|
|
|
|
export type PromptMethods = ReturnType<typeof createPromptMethods>;
|