From 0eadbc45b1304b5986ce1c324bfda1421faaabfe Mon Sep 17 00:00:00 2001 From: "lia-by-librechat[bot]" <328778573+lia-by-librechat[bot]@users.noreply.github.com> Date: Tue, 10 Nov 2026 15:44:13 -0500 Subject: [PATCH] =?UTF-8?q?=F0=9F=AA=B8=20refactor:=20Separate=20Shared-Li?= =?UTF-8?q?nk=20and=20Schedule=20Persistence=20(#18031)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Lia --- api/server/routes/__tests__/share.spec.js | 81 +++--------- api/server/routes/accessPermissions.js | 5 +- .../accessPermissions.sharePolicy.test.js | 34 +++-- api/server/routes/share.js | 17 +-- api/server/services/Schedules/access.js | 6 +- api/server/services/Schedules/index.js | 14 +-- api/server/services/Schedules/index.spec.js | 24 ++-- packages/api/src/schedules/access.ts | 5 +- .../authorization/enrollment.spec.ts | 2 +- packages/api/src/schedules/service.ts | 2 +- packages/api/src/shared-links/access.ts | 30 +---- packages/api/src/shared-links/service.test.ts | 47 +++++++ packages/api/src/shared-links/service.ts | 119 +++++++----------- packages/data-schemas/src/methods/aclEntry.ts | 24 ++++ .../src/methods/admission.spec.ts | 69 ++++++++++ packages/data-schemas/src/methods/agent.ts | 8 ++ packages/data-schemas/src/methods/share.ts | 104 +++++++++++++++ .../src/methods/transaction.spec.ts | 40 ++++++ .../data-schemas/src/methods/transaction.ts | 18 +++ packages/data-schemas/src/methods/user.ts | 20 +++ 20 files changed, 438 insertions(+), 231 deletions(-) create mode 100644 packages/data-schemas/src/methods/admission.spec.ts diff --git a/api/server/routes/__tests__/share.spec.js b/api/server/routes/__tests__/share.spec.js index 0d8bb9fb7f..bd38847081 100644 --- a/api/server/routes/__tests__/share.spec.js +++ b/api/server/routes/__tests__/share.spec.js @@ -1,6 +1,5 @@ const express = require('express'); const request = require('supertest'); -const mongoose = require('mongoose'); const mockGetSharedLinkExpiration = jest.fn(); const mockGrantCreationPermissions = jest.fn(); @@ -154,17 +153,6 @@ jest.mock('librechat-data-provider', () => { }; }); -jest.mock('mongoose', () => ({ - models: { - Conversation: { - findOne: jest.fn(), - }, - SharedLink: { - findOne: jest.fn(), - }, - }, -})); - jest.mock('~/models', () => ({ getFiles: jest.fn(), updateFile: jest.fn(), @@ -174,6 +162,8 @@ jest.mock('~/models', () => ({ deleteSharedLink: jest.fn(), getSharedLinks: jest.fn(), getSharedLink: jest.fn(), + findOwnedSharedLink: jest.fn(), + findShareConversationRetention: jest.fn(), getSharedLinkFile: jest.fn(), backfillSharedLinkFiles: jest.fn(), getMessages: jest.fn(), @@ -240,6 +230,8 @@ const { getSharedMessages, createSharedLink, updateSharedLink, + findOwnedSharedLink, + findShareConversationRetention, getSharedLinks, getSharedLinkFile, backfillSharedLinkFiles, @@ -259,10 +251,6 @@ const contentFilters = { }, }; -const lean = (value) => ({ - lean: jest.fn().mockResolvedValue(value), -}); - const buildApp = ({ retentionMode = RetentionMode.TEMPORARY, user = { id: 'user-123' }, @@ -799,12 +787,9 @@ describe('share routes', () => { }), ); const [, dependencies] = mockGetSharedLinkExpiration.mock.calls[0]; - mongoose.models.Conversation.findOne.mockReturnValue(lean({ expiredAt: activeExpiration })); + findShareConversationRetention.mockResolvedValue({ expiredAt: activeExpiration }); await dependencies.getConvo('user-123', 'convo-123'); - expect(mongoose.models.Conversation.findOne).toHaveBeenCalledWith( - { conversationId: 'convo-123', user: 'user-123' }, - 'isTemporary expiredAt', - ); + expect(findShareConversationRetention).toHaveBeenCalledWith('user-123', 'convo-123'); expect(createSharedLink).toHaveBeenCalledWith( 'user-123', 'convo-123', @@ -1068,9 +1053,7 @@ describe('share routes', () => { }); it('passes the snapshotFiles opt-out through on update', async () => { - mongoose.models.SharedLink.findOne.mockReturnValue( - lean({ _id: 'link-456', conversationId: 'convo-123' }), - ); + findOwnedSharedLink.mockResolvedValue({ _id: 'link-456', conversationId: 'convo-123' }); mockGetSharedLinkExpiration.mockResolvedValue(activeExpiration); mockUpdatedShare({ _id: 'link-456', shareId: 'share-456' }); @@ -1099,9 +1082,7 @@ describe('share routes', () => { }, }); const messages = [{ files: [{ file_id: 'file_PRIVATE-SENTINEL' }] }]; - mongoose.models.SharedLink.findOne.mockReturnValue( - lean({ _id: 'link-456', conversationId: 'convo-123' }), - ); + findOwnedSharedLink.mockResolvedValue({ _id: 'link-456', conversationId: 'convo-123' }); mockGetSharedLinkExpiration.mockResolvedValue(activeExpiration); mockAssertConversationContentAllowed.mockImplementationOnce(() => { throw error; @@ -1159,19 +1140,14 @@ describe('share routes', () => { }); it('expires updated shares for retained non-temporary conversations', async () => { - mongoose.models.SharedLink.findOne.mockReturnValue( - lean({ _id: 'link-456', conversationId: 'convo-123' }), - ); + findOwnedSharedLink.mockResolvedValue({ _id: 'link-456', conversationId: 'convo-123' }); mockGetSharedLinkExpiration.mockResolvedValue(activeExpiration); mockUpdatedShare({ _id: 'link-456', shareId: 'share-456' }); const response = await request(buildApp()).patch('/api/share/share-123'); expect(response.status).toBe(200); - expect(mongoose.models.SharedLink.findOne).toHaveBeenCalledWith( - { shareId: 'share-123', user: 'user-123' }, - 'conversationId', - ); + expect(findOwnedSharedLink).toHaveBeenCalledWith('user-123', 'share-123'); expect(mockGetSharedLinkExpiration).toHaveBeenCalledTimes(1); expect(mockGetSharedLinkExpiration).toHaveBeenCalledWith( expect.objectContaining({ @@ -1200,9 +1176,7 @@ describe('share routes', () => { }); it('does not re-publish content when re-scoping the grants fails', async () => { - mongoose.models.SharedLink.findOne.mockReturnValue( - lean({ _id: 'link-456', conversationId: 'convo-123' }), - ); + findOwnedSharedLink.mockResolvedValue({ _id: 'link-456', conversationId: 'convo-123' }); mockGetSharedLinkExpiration.mockResolvedValue(activeExpiration); mockUpdateSharedLinkPermissionsExpiration.mockRejectedValueOnce(new Error('acl down')); mockUpdatedShare({ _id: 'link-456', shareId: 'share-456' }); @@ -1216,9 +1190,7 @@ describe('share routes', () => { }); it('rejects updated shares when the retained conversation expired', async () => { - mongoose.models.SharedLink.findOne.mockReturnValue( - lean({ _id: 'link-456', conversationId: 'convo-123' }), - ); + findOwnedSharedLink.mockResolvedValue({ _id: 'link-456', conversationId: 'convo-123' }); mockGetSharedLinkExpiration.mockResolvedValue(expiredExpiration); updateSharedLink.mockResolvedValue({ shareId: 'share-456' }); @@ -1229,9 +1201,7 @@ describe('share routes', () => { }); it('rejects updated shares for expired conversations in all retention mode', async () => { - mongoose.models.SharedLink.findOne.mockReturnValue( - lean({ _id: 'link-456', conversationId: 'convo-123' }), - ); + findOwnedSharedLink.mockResolvedValue({ _id: 'link-456', conversationId: 'convo-123' }); mockGetSharedLinkExpiration.mockResolvedValue(expiredExpiration); updateSharedLink.mockResolvedValue({ shareId: 'share-456' }); @@ -1240,17 +1210,12 @@ describe('share routes', () => { ); expect(response.status).toBe(404); - expect(mongoose.models.SharedLink.findOne).toHaveBeenCalledWith( - { shareId: 'share-123', user: 'user-123' }, - 'conversationId', - ); + expect(findOwnedSharedLink).toHaveBeenCalledWith('user-123', 'share-123'); expect(updateSharedLink).not.toHaveBeenCalled(); }); it('clears updated share expiration when the conversation is no longer retained', async () => { - mongoose.models.SharedLink.findOne.mockReturnValue( - lean({ _id: 'link-456', conversationId: 'convo-123' }), - ); + findOwnedSharedLink.mockResolvedValue({ _id: 'link-456', conversationId: 'convo-123' }); mockGetSharedLinkExpiration.mockResolvedValue(null); mockUpdatedShare({ _id: 'link-456', shareId: 'share-456' }); @@ -1282,9 +1247,7 @@ describe('share routes', () => { }); it('preserves updated share expiration when the conversation cannot be found', async () => { - mongoose.models.SharedLink.findOne.mockReturnValue( - lean({ _id: 'link-456', conversationId: 'convo-123' }), - ); + findOwnedSharedLink.mockResolvedValue({ _id: 'link-456', conversationId: 'convo-123' }); mockGetSharedLinkExpiration.mockResolvedValue(undefined); mockUpdatedShare({ shareId: 'share-456' }); @@ -1305,9 +1268,7 @@ describe('share routes', () => { it('clears updated share expiration when creating a new expiration throws', async () => { const error = new Error('bad config'); - mongoose.models.SharedLink.findOne.mockReturnValue( - lean({ _id: 'link-456', conversationId: 'convo-123' }), - ); + findOwnedSharedLink.mockResolvedValue({ _id: 'link-456', conversationId: 'convo-123' }); mockGetSharedLinkExpiration.mockImplementationOnce(async (_input, dependencies) => { dependencies.logger.error('[getSharedLinkExpiration] Error creating expiration date:', error); return null; @@ -1334,9 +1295,7 @@ describe('share routes', () => { }); it('updates share target message while applying retention expiration', async () => { - mongoose.models.SharedLink.findOne.mockReturnValue( - lean({ _id: 'link-456', conversationId: 'convo-123' }), - ); + findOwnedSharedLink.mockResolvedValue({ _id: 'link-456', conversationId: 'convo-123' }); mockGetSharedLinkExpiration.mockResolvedValue(activeExpiration); mockUpdatedShare({ shareId: 'share-456', targetMessageId: 'msg-456' }); @@ -1375,7 +1334,7 @@ describe('share routes', () => { }); it('maps a missing-share update domain error to not found', async () => { - mongoose.models.SharedLink.findOne.mockReturnValue(lean(null)); + findOwnedSharedLink.mockResolvedValue(null); updateSharedLink.mockRejectedValue( Object.assign(new Error('Share not found'), { code: 'SHARE_NOT_FOUND' }), ); @@ -1387,7 +1346,7 @@ describe('share routes', () => { }); it('returns and records a missing-tail update rejection', async () => { - mongoose.models.SharedLink.findOne.mockReturnValue(lean({ conversationId: 'convo-123' })); + findOwnedSharedLink.mockResolvedValue({ conversationId: 'convo-123' }); mockGetSharedLinkExpiration.mockResolvedValue(activeExpiration); updateSharedLink.mockRejectedValue( Object.assign(new Error('Target message not found'), { diff --git a/api/server/routes/accessPermissions.js b/api/server/routes/accessPermissions.js index 4429f1e4b3..524016250b 100644 --- a/api/server/routes/accessPermissions.js +++ b/api/server/routes/accessPermissions.js @@ -1,4 +1,4 @@ -const mongoose = require('mongoose'); +const { findSharedLinkById } = require('~/models'); const express = require('express'); const { AccessRoleIds, @@ -158,8 +158,7 @@ const rejectSharedLinkOwnerPermissionChanges = async (req, res, next) => { } try { - const SharedLink = mongoose.models.SharedLink; - const link = await SharedLink.findById(req.params.resourceId, 'user').lean(); + const link = await findSharedLinkById(req.params.resourceId); const ownerId = link?.user?.toString(); const touchesOwner = ownerId ? userMutations.some((principal) => principal.id?.toString() === ownerId) diff --git a/api/server/routes/accessPermissions.sharePolicy.test.js b/api/server/routes/accessPermissions.sharePolicy.test.js index b00299da27..beb668c244 100644 --- a/api/server/routes/accessPermissions.sharePolicy.test.js +++ b/api/server/routes/accessPermissions.sharePolicy.test.js @@ -1,5 +1,6 @@ jest.mock('~/models', () => ({ getRoleByName: jest.fn(), + findSharedLinkById: jest.fn(), findMCPServerByObjectId: jest.fn(), getSkillById: jest.fn(), })); @@ -34,7 +35,6 @@ jest.mock('~/server/controllers/PermissionsController', () => ({ const express = require('express'); const request = require('supertest'); -const mongoose = require('mongoose'); const { SystemRoles, ResourceType, @@ -49,12 +49,11 @@ const { updateResourcePermissions } = require('~/server/controllers/PermissionsC const { hasCapability } = require('~/server/middleware/roles/capabilities'); const { canAccessResource } = require('~/server/middleware'); const accessPermissionsRouter = require('./accessPermissions'); -const { getRoleByName } = require('~/models'); +const { getRoleByName, findSharedLinkById } = require('~/models'); describe('Access permissions share policy', () => { let app; - const mockSharedLinkFindById = jest.fn(); - const originalSharedLinkModel = mongoose.models.SharedLink; + const mockSharedLinkFindById = findSharedLinkById; const resourceId = '507f1f77bcf86cd799439011'; const sharePolicyCases = [ @@ -135,18 +134,11 @@ describe('Access permissions share policy', () => { }; const mockSharedLinkOwner = (ownerId = 'owner-user') => { - mockSharedLinkFindById.mockReturnValue({ - lean: jest.fn().mockResolvedValue({ user: ownerId }), - }); + mockSharedLinkFindById.mockResolvedValue({ user: ownerId }); }; beforeEach(() => { jest.clearAllMocks(); - if (mongoose.models.SharedLink) { - mongoose.models.SharedLink.findById = mockSharedLinkFindById; - } else { - mongoose.models.SharedLink = { findById: mockSharedLinkFindById }; - } hasCapability.mockResolvedValue(false); app = express(); @@ -158,14 +150,6 @@ describe('Access permissions share policy', () => { app.use('/api/permissions', accessPermissionsRouter); }); - afterAll(() => { - if (originalSharedLinkModel) { - mongoose.models.SharedLink = originalSharedLinkModel; - } else { - delete mongoose.models.SharedLink; - } - }); - it.each(sharePolicyCases)( 'blocks non-public $label sharing when ACL SHARE passes but role SHARE is disabled', async ({ resourceType, permissionType, accessRoleId, middlewareOptions }) => { @@ -337,4 +321,14 @@ describe('Access permissions share policy', () => { expect(response.status).toBe(200); expect(updateResourcePermissions).toHaveBeenCalledTimes(1); }); + it('fails closed when the canonical owner query rejects', async () => { + allowSharedLinkSharing(); + findSharedLinkById.mockRejectedValueOnce(new Error('database secret')); + const response = await request(app) + .put(`/api/permissions/${ResourceType.SHARED_LINK}/${resourceId}`) + .send({ removed: [{ type: PrincipalType.USER, id: 'owner-user' }] }); + expect(response.status).toBe(500); + expect(response.body.message).toBe('Failed to validate shared link owner permissions'); + expect(updateResourcePermissions).not.toHaveBeenCalled(); + }); }); diff --git a/api/server/routes/share.js b/api/server/routes/share.js index ad09159a53..34430581d6 100644 --- a/api/server/routes/share.js +++ b/api/server/routes/share.js @@ -1,4 +1,3 @@ -const mongoose = require('mongoose'); const express = require('express'); const { assertModelBoundContent, @@ -43,6 +42,8 @@ const { updateSharedLink, getSharedLinks, getSharedLink, + findOwnedSharedLink, + findShareConversationRetention, getSharedLinkFile, backfillSharedLinkFiles, getMessages, @@ -117,13 +118,7 @@ const resolveSharedLinkExpiration = (req, conversationId) => getSharedLinkExpiration( { req, conversationId }, { - getConvo: async (userId, sourceConversationId) => { - const Conversation = mongoose.models.Conversation; - return Conversation.findOne( - { conversationId: sourceConversationId, user: userId }, - 'isTemporary expiredAt', - ).lean(); - }, + getConvo: findShareConversationRetention, createExpirationDate: createChatExpirationDate, logger, }, @@ -720,11 +715,7 @@ router.patch( } let expiredAt; - const SharedLink = mongoose.models.SharedLink; - const existing = await SharedLink.findOne( - { shareId: req.params.shareId, user: req.user.id }, - 'conversationId', - ).lean(); + const existing = await findOwnedSharedLink(req.user.id, req.params.shareId); if (existing?.conversationId) { expiredAt = await resolveSharedLinkExpiration(req, existing.conversationId); } diff --git a/api/server/services/Schedules/access.js b/api/server/services/Schedules/access.js index a278b4e339..06fb83a7ec 100644 --- a/api/server/services/Schedules/access.js +++ b/api/server/services/Schedules/access.js @@ -1,15 +1,13 @@ -const mongoose = require('mongoose'); const { createResolveAgentFireAccess } = require('@librechat/api'); const { checkPermission } = require('~/server/services/PermissionService'); const { hasCapability } = require('~/server/middleware/roles/capabilities'); -const { getRoleByName } = require('~/models'); +const { getRoleByName, findAgentIdentity } = require('~/models'); // Thin wiring over the TypeScript implementation in packages/api: inject the // api-layer lookups (agent id, role, capability, resource ACL); the authorization // logic itself lives in @librechat/api so it stays type-checked and in-boundary. const resolveAgentFireAccess = createResolveAgentFireAccess({ - findAgentObjectId: (agentId) => - mongoose.models.Agent.findOne({ id: agentId }).select('_id').lean(), + findAgentObjectId: findAgentIdentity, getRoleByName, hasCapability, checkPermission, diff --git a/api/server/services/Schedules/index.js b/api/server/services/Schedules/index.js index 9c9a404154..c3f2359839 100644 --- a/api/server/services/Schedules/index.js +++ b/api/server/services/Schedules/index.js @@ -10,7 +10,6 @@ function getService() { if (service != null) { return service; } - const mongoose = require('mongoose'); const { createSchedulesService } = require('@librechat/api'); const { getAppConfig } = require('~/server/services/Config/app'); const { @@ -25,21 +24,12 @@ function getService() { preflightMCP: require('./mcp'), methods, getAppConfig, - findUserById: (userId) => - mongoose.models.User.findById(userId).select('_id tenantId role termsAccepted').lean(), + findUserById: (userId) => methods.findScheduleOwner(userId.toString()), findBalance: (userId, options) => methods.findBalanceByUser(userId, { includeReservedCredits: true, ...options }), upsertBalance: (userId, { set, setOnInsert }) => methods.upsertBalanceFields(userId, set ?? {}, setOnInsert ?? {}), - // Compare-and-set: only initialize an existing record while its credit is still null. - // No upsert — a CAS miss must re-read the winner, not insert a fresh balance. `null` - // in the filter also matches a legacy record whose `tokenCredits` field is absent. - initializeNullBalance: (userId, { tokenCredits, sync }) => - mongoose.models.Balance.findOneAndUpdate( - { user: userId, tokenCredits: null }, - { $set: { tokenCredits, ...(sync && Object.keys(sync).length > 0 ? sync : {}) } }, - { new: true, sort: { _id: 1 } }, - ).lean(), + initializeNullBalance: methods.initializeNullBalance, enqueueAgentTrigger, // Reconciliation reads the durable delivery to tell a still-live admission (a // deferred Retry-After) or a dead-letter apart from a genuinely orphaned run. diff --git a/api/server/services/Schedules/index.spec.js b/api/server/services/Schedules/index.spec.js index f2bd037ba9..db1a138f44 100644 --- a/api/server/services/Schedules/index.spec.js +++ b/api/server/services/Schedules/index.spec.js @@ -6,12 +6,15 @@ const mockCreateSchedulesService = jest.fn(() => ({ jest.mock('@librechat/api', () => ({ createSchedulesService: (...args) => mockCreateSchedulesService(...args), })); -jest.mock('mongoose', () => ({ models: {} })); jest.mock('~/server/services/Config/app', () => ({ getAppConfig: jest.fn() })); jest.mock('~/server/services/Agents/triggers', () => ({ enqueueAgentTrigger: jest.fn() })); jest.mock('./mcp', () => jest.fn()); jest.mock('./access', () => ({ resolveAgentFireAccess: jest.fn() })); -jest.mock('~/models', () => ({ isAgentTriggerPrincipalActive: jest.fn() })); +jest.mock('~/models', () => ({ + isAgentTriggerPrincipalActive: jest.fn(), + findScheduleOwner: jest.fn(), + initializeNullBalance: jest.fn(), +})); const { recordExpiredScheduleApproval } = require('./index'); @@ -62,11 +65,9 @@ describe('recordExpiredScheduleApproval', () => { describe('schedule owner lookup', () => { it('selects the terms acceptance flag the fire-time terms check reads', async () => { - const mongoose = require('mongoose'); - const lean = jest.fn().mockResolvedValue({ _id: 'user-1', termsAccepted: false }); - const select = jest.fn(() => ({ lean })); - const findById = jest.fn(() => ({ select })); - mongoose.models.User = { findById }; + const methods = require('~/models'); + const owner = { _id: 'user-1', termsAccepted: false }; + methods.findScheduleOwner.mockResolvedValue(owner); mockRecordScheduleOutcome.mockResolvedValue(true); let facade; jest.isolateModules(() => { @@ -80,11 +81,10 @@ describe('schedule owner lookup', () => { scheduledFor: '2026-08-17T12:00:00.000Z', }); const { findUserById } = mockCreateSchedulesService.mock.calls.at(-1)[0]; - await findUserById('user-1'); - - expect(findById).toHaveBeenCalledWith('user-1'); - expect(select.mock.calls[0][0].split(' ')).toEqual( - expect.arrayContaining(['_id', 'tenantId', 'role', 'termsAccepted']), + await expect(findUserById('user-1')).resolves.toEqual(owner); + expect(methods.findScheduleOwner).toHaveBeenCalledWith('user-1'); + expect(mockCreateSchedulesService.mock.calls.at(-1)[0].initializeNullBalance).toBe( + methods.initializeNullBalance, ); }); }); diff --git a/packages/api/src/schedules/access.ts b/packages/api/src/schedules/access.ts index 83cb793124..29b83f18db 100644 --- a/packages/api/src/schedules/access.ts +++ b/packages/api/src/schedules/access.ts @@ -6,14 +6,13 @@ import { PermissionTypes, } from 'librechat-data-provider'; import type { SystemCapability } from '@librechat/data-schemas'; -import type { Types } from 'mongoose'; import type { ScheduleUserContext } from './types'; type AgentAccess = 'ok' | 'missing' | 'forbidden'; export interface AgentFireAccessDeps { /** Resolves an agent's internal `_id` by its custom id, or null when it doesn't exist. */ - findAgentObjectId: (agentId: string) => Promise<{ _id: Types.ObjectId } | null>; + findAgentObjectId: (agentId: string) => Promise<{ _id: string } | null>; /** Loads a role's permission map by name. */ getRoleByName: ( role?: string, @@ -25,7 +24,7 @@ export interface AgentFireAccessDeps { userId: string; role?: string; resourceType: ResourceType; - resourceId: Types.ObjectId; + resourceId: string; requiredPermission: PermissionBits; }) => Promise; } diff --git a/packages/api/src/schedules/authorization/enrollment.spec.ts b/packages/api/src/schedules/authorization/enrollment.spec.ts index fdfa475fbe..d4ef56e851 100644 --- a/packages/api/src/schedules/authorization/enrollment.spec.ts +++ b/packages/api/src/schedules/authorization/enrollment.spec.ts @@ -135,7 +135,7 @@ it('denies an owner/tenant mismatch and cancellation before resolving resources' it('honors capability-only root access without bypassing descendant VIEW checks', async () => { const { deps, resolve } = setup(); const rootAccess = createResolveAgentFireAccess({ - findAgentObjectId: async () => ({ _id: new Types.ObjectId() }), + findAgentObjectId: async () => ({ _id: new Types.ObjectId().toString() }), getRoleByName: async () => ({ permissions: { [PermissionTypes.AGENTS]: { [Permissions.USE]: true } }, }), diff --git a/packages/api/src/schedules/service.ts b/packages/api/src/schedules/service.ts index c7ef3597ca..1666062d15 100644 --- a/packages/api/src/schedules/service.ts +++ b/packages/api/src/schedules/service.ts @@ -167,7 +167,7 @@ export interface SchedulesServiceDeps { }; getAppConfig: (options?: GetAppConfigOptions) => Promise; findUserById: (userId: string | Types.ObjectId) => Promise<{ - _id: Types.ObjectId; + _id: string | Types.ObjectId; tenantId?: string; role?: string; termsAccepted?: boolean; diff --git a/packages/api/src/shared-links/access.ts b/packages/api/src/shared-links/access.ts index 1ae898035a..797659cdb9 100644 --- a/packages/api/src/shared-links/access.ts +++ b/packages/api/src/shared-links/access.ts @@ -1,28 +1,11 @@ import { ResourceType, PermissionBits } from 'librechat-data-provider'; -import { - getTenantId, - runAsSystem, - tenantStorage, - activeExpirationFilter, -} from '@librechat/data-schemas'; +import { getTenantId, runAsSystem, tenantStorage, createMethods } from '@librechat/data-schemas'; +import type { IUser, ShareMethods } from '@librechat/data-schemas'; import type { Request, Response, NextFunction } from 'express'; -import type { IUser } from '@librechat/data-schemas'; -import type { Types, Model } from 'mongoose'; import { AccessControlService } from '~/acl/accessControlService'; import { autoMigrateLegacyLink } from './service'; import { isEnabled } from '~/utils'; -interface RawSharedLink { - _id?: Types.ObjectId; - conversationId: string; - title?: string; - user?: string; - shareId?: string; - tenantId?: string; - isPublic?: boolean; - expiredAt?: Date; -} - interface SharedLinkAccessRequest extends Request { shareResourceId?: string; shareTenantId?: string; @@ -33,6 +16,7 @@ interface SharedLinkAccessRequest extends Request { export interface SharedLinkAccessDeps { mongoose: typeof import('mongoose'); aclService?: AccessControlService; + findActiveSharedLink?: ShareMethods['findActiveSharedLink']; } function isAutoMigrateEnabled(): boolean { @@ -44,6 +28,7 @@ function isAutoMigrateEnabled(): boolean { export function createSharedLinkAccessMiddleware(deps: SharedLinkAccessDeps) { const { mongoose: mg } = deps; const aclService = deps.aclService ?? new AccessControlService(mg); + const findActiveSharedLink = deps.findActiveSharedLink ?? createMethods(mg).findActiveSharedLink; async function hasPublicViewPermission(resourceId: string): Promise { return aclService.hasPublicAccess({ @@ -64,12 +49,7 @@ export function createSharedLinkAccessMiddleware(deps: SharedLinkAccessDeps) { } const viewerTenantId = getTenantId(); - const SharedLink = mg.models.SharedLink as Model; - const findShare = async () => - (await SharedLink.findOne({ - shareId, - ...activeExpirationFilter(), - }).lean()) as RawSharedLink | null; + const findShare = () => findActiveSharedLink(shareId); // Resolve by the (globally unique, secret) shareId under the viewer's tenant // first, then fall back to a system-wide lookup so a share owned by another // tenant — e.g. a public link opened by an authenticated user from a diff --git a/packages/api/src/shared-links/service.test.ts b/packages/api/src/shared-links/service.test.ts index e6050465eb..4511fbbab9 100644 --- a/packages/api/src/shared-links/service.test.ts +++ b/packages/api/src/shared-links/service.test.ts @@ -8,6 +8,7 @@ import { MongoMemoryServer } from 'mongodb-memory-server'; import { createModels, createMethods } from '@librechat/data-schemas'; import { PrincipalType, AccessRoleIds } from 'librechat-data-provider'; import type { IAclEntry, ISharedLink } from '@librechat/data-schemas'; +import { AccessControlService } from '~/acl/accessControlService'; import { autoMigrateLegacyLink, grantCreationPermissions, @@ -408,3 +409,49 @@ describe('deleteAllSharedLinksWithCleanup', () => { expect(await AclEntry.countDocuments({ resourceId: link._id })).toBe(0); }); }); + +describe('persistence failures', () => { + test.each([1, 2])( + 'compensates link and ACL after grant %s partially writes then fails', + async (failingGrant) => { + const link = await createTestLink(); + const original = AccessControlService.prototype.grantPermission; + let calls = 0; + const grant = jest + .spyOn(AccessControlService.prototype, 'grantPermission') + .mockImplementation(async function (this: AccessControlService, params) { + const result = await original.call(this, params); + if (++calls === failingGrant) { + throw new Error('grant failed'); + } + return result; + }); + try { + await expect(grantCreationPermissions(link._id, userId, true)).rejects.toThrow( + 'grant failed', + ); + expect(await SharedLink.findById(link._id)).toBeNull(); + expect(await AclEntry.countDocuments({ resourceId: link._id })).toBe(0); + } finally { + grant.mockRestore(); + } + }, + ); + + test('expiration update failures reject instead of reporting success', async () => { + const link = await createTestLink(); + const update = jest.spyOn(AclEntry, 'updateMany').mockRejectedValueOnce(new Error('acl down')); + await expect(updateSharedLinkPermissionsExpiration(link._id, null)).rejects.toThrow('acl down'); + update.mockRestore(); + }); + + test('ordinary deletion remains successful when ACL cleanup fails', async () => { + const link = await createTestLink(); + const cleanup = jest.spyOn(AclEntry, 'deleteMany').mockRejectedValueOnce(new Error('acl down')); + await expect(deleteSharedLinkWithCleanup(userId, link.shareId!)).resolves.toMatchObject({ + success: true, + }); + expect(await SharedLink.findById(link._id)).toBeNull(); + cleanup.mockRestore(); + }); +}); diff --git a/packages/api/src/shared-links/service.ts b/packages/api/src/shared-links/service.ts index 2dae3613c5..a6ab3e4d8a 100644 --- a/packages/api/src/shared-links/service.ts +++ b/packages/api/src/shared-links/service.ts @@ -1,15 +1,20 @@ import mongoose from 'mongoose'; -import { logger } from '@librechat/data-schemas'; +import { logger, createMethods } from '@librechat/data-schemas'; import { PrincipalType, ResourceType, AccessRoleIds, PermissionBits, } from 'librechat-data-provider'; -import type { Model, Types, DeleteResult, UpdateQuery } from 'mongoose'; -import type { IAclEntry, ISharedLink } from '@librechat/data-schemas'; +import type { AllMethods } from '@librechat/data-schemas'; +import type { Types } from 'mongoose'; import { AccessControlService } from '~/acl/accessControlService'; +let _methods: AllMethods | undefined; +function getMethods(): AllMethods { + return (_methods ??= createMethods(mongoose)); +} + let _aclService: AccessControlService | null = null; function getAclService(): AccessControlService { if (!_aclService) { @@ -19,7 +24,7 @@ function getAclService(): AccessControlService { } interface RawSharedLink { - _id?: Types.ObjectId; + _id?: string | Types.ObjectId; conversationId: string; title?: string; user?: string; @@ -110,9 +115,7 @@ export async function autoMigrateLegacyLink(share: RawSharedLink): Promise return; } - await mongoose.connection - .db!.collection('sharedlinks') - .updateOne({ _id: shareId }, { $unset: { isPublic: 1 } }); + await getMethods().clearSharedLinkLegacyVisibility(resourceId); logger.info('[autoMigrateLegacyLink] Migrated legacy shared link', { shareId: share.shareId, @@ -145,7 +148,10 @@ export async function grantCreationPermissions( resourceId, error: err instanceof Error ? err.message : String(err), }); - await mongoose.models.SharedLink.deleteOne({ _id: sharedLinkId }); + await Promise.all([ + getMethods().deleteSharedLinkById(resourceId), + cleanupSharedLinkPermissions(resourceId), + ]); throw err; } @@ -166,7 +172,7 @@ export async function grantCreationPermissions( error: err instanceof Error ? err.message : String(err), }); await Promise.all([ - mongoose.models.SharedLink.deleteOne({ _id: sharedLinkId }), + getMethods().deleteSharedLinkById(resourceId), getAclService().removeAllPermissions({ resourceType: ResourceType.SHARED_LINK, resourceId, @@ -181,8 +187,7 @@ export async function ensureLinkPermissions( sharedLinkId: string | Types.ObjectId, userId: string, ): Promise { - const SharedLink = mongoose.models.SharedLink as Model; - const rawDoc = await SharedLink.findById(sharedLinkId).lean(); + const rawDoc = await getMethods().findSharedLinkById(sharedLinkId.toString()); if (!rawDoc) { return; @@ -192,7 +197,7 @@ export async function ensureLinkPermissions( * back through the migration: the owner grant alone does not mean the public one was * ever created. `autoMigrateLegacyLink` skips the grants that are already in place. */ if ('isPublic' in rawDoc) { - await autoMigrateLegacyLink(rawDoc as Parameters[0]); + await autoMigrateLegacyLink(rawDoc); return; } @@ -231,117 +236,79 @@ export async function ensureLinkPermissions( export async function cleanupSharedLinkPermissions( resourceId: string | Types.ObjectId, -): Promise { - return getAclService().removeAllPermissions({ - resourceType: ResourceType.SHARED_LINK, - resourceId, - }); +): Promise<{ acknowledged: boolean; deletedCount: number }> { + return getMethods().deleteSharedLinkAclEntries([resourceId.toString()]); } export async function cleanupBulkSharedLinkPermissions( resourceIds: (string | Types.ObjectId)[], -): Promise { - const AclEntry = mongoose.models.AclEntry as Model; - return AclEntry.deleteMany({ - resourceType: ResourceType.SHARED_LINK, - resourceId: { $in: resourceIds }, - }); +): Promise<{ acknowledged: boolean; deletedCount: number }> { + return getMethods().deleteSharedLinkAclEntries(resourceIds.map((id) => id.toString())); } export async function updateSharedLinkPermissionsExpiration( resourceId: string | Types.ObjectId, expiredAt: Date | null, ): Promise { - const AclEntry = mongoose.models.AclEntry as Model; - const update: UpdateQuery = - expiredAt instanceof Date ? { $set: { expiredAt } } : { $unset: { expiredAt: 1 } }; - - await AclEntry.updateMany( - { - resourceType: ResourceType.SHARED_LINK, - resourceId, - }, - update, - ); + await getMethods().updateSharedLinkAclExpiration(resourceId.toString(), expiredAt); } export async function deleteSharedLinkWithCleanup( user: string, shareId: string, ): Promise<{ _id?: string; success: boolean; shareId: string; message: string } | null> { - const SharedLink = mongoose.models.SharedLink as Model; - const result = await SharedLink.findOneAndDelete({ shareId, user }).lean(); - + const result = await getMethods().deleteSharedLink(user, shareId); if (!result) { return null; } - - const resourceId = result._id; - if (resourceId) { - cleanupSharedLinkPermissions(resourceId).catch((err) => { + if (result._id) { + cleanupSharedLinkPermissions(result._id).catch((err) => { logger.error('[deleteSharedLinkWithCleanup] ACL cleanup failed', { shareId, error: err instanceof Error ? err.message : String(err), }); }); } - - return { - _id: resourceId?.toString(), - success: true, - shareId, - message: 'Share deleted successfully', - }; + return result; } export async function deleteConvoSharedLinksWithCleanup( user: string, conversationId: string, ): Promise<{ message: string; deletedCount: number }> { - const SharedLink = mongoose.models.SharedLink as Model; - const links = await SharedLink.find({ user, conversationId }).select('_id').lean(); - const ids = links.map((l) => l._id); - const result = await SharedLink.deleteMany({ user, conversationId }); - - if (ids.length > 0) { - cleanupBulkSharedLinkPermissions(ids).catch((err) => { + const { deletedIds, ...result } = await getMethods().deleteConvoSharedLink(user, conversationId); + if (deletedIds.length > 0) { + cleanupBulkSharedLinkPermissions(deletedIds).catch((err) => { logger.error('[deleteConvoSharedLinksWithCleanup] ACL cleanup failed', { conversationId, error: err instanceof Error ? err.message : String(err), }); }); } - - return { - message: 'Shared links deleted successfully', - deletedCount: result.deletedCount, - }; + return result; } export async function deleteAllSharedLinksWithCleanup( user: string, options: { awaitCleanup?: boolean } = {}, ): Promise<{ message: string; deletedCount: number }> { - const SharedLink = mongoose.models.SharedLink as Model; - const links = await SharedLink.find({ user }).select('_id').lean(); - const ids = links.map((l) => l._id); - if (options.awaitCleanup && ids.length > 0) { - /** The links identify the ACL resources, so they must outlive a failed cleanup for a retry. */ - await cleanupBulkSharedLinkPermissions(ids); - } - const result = await SharedLink.deleteMany({ user }); - - if (!options.awaitCleanup && ids.length > 0) { - cleanupBulkSharedLinkPermissions(ids).catch((err) => { + const { deletedIds, ...result } = await getMethods().deleteAllSharedLinks( + user, + options.awaitCleanup + ? async (ids) => { + if (ids.length > 0) { + await cleanupBulkSharedLinkPermissions(ids); + } + } + : undefined, + ); + if (!options.awaitCleanup && deletedIds.length > 0) { + cleanupBulkSharedLinkPermissions(deletedIds).catch((err) => { logger.error('[deleteAllSharedLinksWithCleanup] ACL cleanup failed', { user, error: err instanceof Error ? err.message : String(err), }); }); } - - return { - message: 'All shared links deleted successfully', - deletedCount: result.deletedCount, - }; + return result; } diff --git a/packages/data-schemas/src/methods/aclEntry.ts b/packages/data-schemas/src/methods/aclEntry.ts index 6efb23cf60..221091944b 100644 --- a/packages/data-schemas/src/methods/aclEntry.ts +++ b/packages/data-schemas/src/methods/aclEntry.ts @@ -1,5 +1,6 @@ import { Types } from 'mongoose'; import { + ResourceType, PrincipalType, PrincipalModel, PermissionBits, @@ -131,6 +132,8 @@ export const OWNER_ACL_PERMISSION_BIT_SUPERSETS: readonly number[] = const OBJECT_ID_HEX = /^[0-9a-fA-F]{24}$/; export function createAclEntryMethods(mongoose: typeof import('mongoose')): { + deleteSharedLinkAclEntries: (resourceIds: string[]) => Promise; + updateSharedLinkAclExpiration: (resourceId: string, expiredAt: Date | null) => Promise; findEntriesByResource: ( resourceType: string, resourceId: string | Types.ObjectId, @@ -907,7 +910,28 @@ export function createAclEntryMethods(mongoose: typeof import('mongoose')): { return ownedIds.filter((id) => !multiOwnerIds.has(id.toString())); } + async function deleteSharedLinkAclEntries(resourceIds: string[]): Promise { + const AclEntry = mongoose.models.AclEntry as Model; + return AclEntry.deleteMany({ + resourceType: ResourceType.SHARED_LINK, + resourceId: { $in: resourceIds }, + }); + } + + async function updateSharedLinkAclExpiration( + resourceId: string, + expiredAt: Date | null, + ): Promise { + const AclEntry = mongoose.models.AclEntry as Model; + await AclEntry.updateMany( + { resourceType: ResourceType.SHARED_LINK, resourceId }, + expiredAt instanceof Date ? { $set: { expiredAt } } : { $unset: { expiredAt: 1 } }, + ); + } + return { + deleteSharedLinkAclEntries, + updateSharedLinkAclExpiration, findEntriesByResource, findEntriesByPrincipalsAndResource, hasPermission, diff --git a/packages/data-schemas/src/methods/admission.spec.ts b/packages/data-schemas/src/methods/admission.spec.ts new file mode 100644 index 0000000000..045c8f83c1 --- /dev/null +++ b/packages/data-schemas/src/methods/admission.spec.ts @@ -0,0 +1,69 @@ +import mongoose from 'mongoose'; +import { MongoMemoryServer } from 'mongodb-memory-server'; +import { createModels } from '~/models'; +import { createMethods } from './index'; + +let mongo: MongoMemoryServer; +let methods: ReturnType; +beforeAll(async () => { + mongo = await MongoMemoryServer.create(); + await mongoose.connect(mongo.getUri()); + createModels(mongoose); + methods = createMethods(mongoose); +}); +afterAll(async () => { + await mongoose.disconnect(); + await mongo.stop(); +}); +afterEach(async () => { + await Promise.all( + ['User', 'Agent', 'SharedLink'].map((name) => mongoose.models[name].deleteMany({})), + ); +}); + +it('returns only live admission owner fields with a plain identity', async () => { + const _id = new mongoose.Types.ObjectId(); + await mongoose.models.User.collection.insertOne({ + _id, + role: 'USER', + termsAccepted: false, + email: 'private@example.test', + }); + expect(await methods.findScheduleOwner(_id.toString())).toEqual({ + _id: _id.toString(), + role: 'USER', + termsAccepted: false, + }); + expect(await methods.findScheduleOwner(new mongoose.Types.ObjectId().toString())).toBeNull(); +}); + +it('returns an agent identity without leaking its definition and propagates query rejection', async () => { + const _id = new mongoose.Types.ObjectId(); + await mongoose.models.Agent.collection.insertOne({ _id, id: 'agent', instructions: 'private' }); + expect(await methods.findAgentIdentity('agent')).toEqual({ _id: _id.toString() }); + expect(await methods.findAgentIdentity('missing')).toBeNull(); + const failure = jest.spyOn(mongoose.models.Agent, 'findOne').mockImplementationOnce(() => { + throw new Error('query failed'); + }); + await expect(methods.findAgentIdentity('agent')).rejects.toThrow('query failed'); + failure.mockRestore(); +}); + +it('discovers every user link before awaited cleanup, retaining rows when cleanup rejects', async () => { + const user = new mongoose.Types.ObjectId().toString(); + const rows = await mongoose.models.SharedLink.create([ + { user, conversationId: 'one', shareId: 'one', messages: [], expiredAt: new Date(0) }, + { user, conversationId: 'two', shareId: 'two', messages: [] }, + ]); + const ids = rows.map((row) => row._id.toString()).sort(); + const cleanup = jest.fn(async (found: string[]) => { + expect(found.sort()).toEqual(ids); + expect(await mongoose.models.SharedLink.countDocuments({ user })).toBe(2); + throw new Error('cleanup failed'); + }); + await expect(methods.deleteAllSharedLinks(user, cleanup)).rejects.toThrow('cleanup failed'); + expect(await mongoose.models.SharedLink.countDocuments({ user })).toBe(2); + expect(await methods.findActiveSharedLink('one')).toBeNull(); + expect((await methods.findActiveSharedLink('two'))?._id).toBe(rows[1]._id.toString()); + expect((await methods.deleteAllSharedLinks(user)).deletedIds.sort()).toEqual(ids); +}); diff --git a/packages/data-schemas/src/methods/agent.ts b/packages/data-schemas/src/methods/agent.ts index 822f6c6f7d..51ca6eafba 100644 --- a/packages/data-schemas/src/methods/agent.ts +++ b/packages/data-schemas/src/methods/agent.ts @@ -1077,6 +1077,7 @@ export function createAgentMethods( mongoose: typeof import('mongoose'), deps: AgentDeps, ): { + findAgentIdentity: (agentId: string) => Promise<{ _id: string } | null>; getAgent: GetAgent; getAgentName: (id: string, tenantId?: string) => Promise; getAgentVersions: (searchParameter: FilterQuery) => Promise; @@ -2836,7 +2837,14 @@ export function createAgentMethods( await evictAuthUserDocsForUsers(deps.getCache, userIds); } + async function findAgentIdentity(agentId: string): Promise<{ _id: string } | null> { + const Agent = mongoose.models.Agent as Model; + const agent = await Agent.findOne({ id: agentId }).select('_id').lean(); + return agent ? { _id: agent._id.toString() } : null; + } + return { + findAgentIdentity, getAgent, getAgentName, getAgentVersions, diff --git a/packages/data-schemas/src/methods/share.ts b/packages/data-schemas/src/methods/share.ts index bd8f7e0ddc..0e132650d6 100644 --- a/packages/data-schemas/src/methods/share.ts +++ b/packages/data-schemas/src/methods/share.ts @@ -898,8 +898,27 @@ function getMessagesUpToTarget(messages: t.IMessage[], targetMessageId: string): return Array.from(results); } +export interface SharedLinkAccessRecord { + _id: string; + conversationId: string; + user?: string; + shareId?: string; + tenantId?: string; + isPublic?: boolean; + expiredAt?: Date; +} + /** Factory function that takes mongoose instance and returns the methods */ export function createShareMethods(mongoose: typeof import('mongoose')): { + findShareConversationRetention: ( + user: string, + conversationId: string, + ) => Promise<{ isTemporary?: boolean; expiredAt?: Date } | null>; + findActiveSharedLink: (shareId: string) => Promise; + findSharedLinkById: (resourceId: string) => Promise; + findOwnedSharedLink: (user: string, shareId: string) => Promise; + clearSharedLinkLegacyVisibility: (resourceId: string) => Promise; + deleteSharedLinkById: (resourceId: string) => Promise; getSharedLink: (user: string, conversationId: string) => Promise; getSharedLinks: ( user: string, @@ -942,12 +961,80 @@ export function createShareMethods(mongoose: typeof import('mongoose')): { ) => Promise; deleteAllSharedLinks: ( user: string, + beforeDelete?: (resourceIds: string[]) => Promise, ) => Promise; deleteConvoSharedLink: ( user: string, conversationId: string, ) => Promise; } { + function accessRecord(share: t.ISharedLink | null): SharedLinkAccessRecord | null { + if (!share?._id) { + return null; + } + return { + _id: share._id.toString(), + conversationId: share.conversationId, + user: share.user?.toString(), + shareId: share.shareId, + tenantId: share.tenantId, + expiredAt: share.expiredAt, + ...('isPublic' in share + ? { isPublic: (share as t.ISharedLink & { isPublic?: boolean }).isPublic } + : {}), + }; + } + + async function findShareConversationRetention( + user: string, + conversationId: string, + ): Promise<{ isTemporary?: boolean; expiredAt?: Date } | null> { + const Conversation = mongoose.models.Conversation as Model; + return Conversation.findOne({ conversationId, user }) + .select('isTemporary expiredAt -_id') + .lean(); + } + + async function findActiveSharedLink(shareId: string): Promise { + const SharedLink = mongoose.models.SharedLink as Model; + return accessRecord( + await SharedLink.findOne({ shareId, ...activeExpirationFilter() }) + .select('_id conversationId user shareId tenantId expiredAt isPublic') + .lean(), + ); + } + + async function findSharedLinkById(resourceId: string): Promise { + const SharedLink = mongoose.models.SharedLink as Model; + return accessRecord( + await SharedLink.findById(resourceId) + .select('_id conversationId user shareId tenantId expiredAt isPublic') + .lean(), + ); + } + + async function findOwnedSharedLink( + user: string, + shareId: string, + ): Promise { + const SharedLink = mongoose.models.SharedLink as Model; + return accessRecord( + await SharedLink.findOne({ user, shareId }) + .select('_id conversationId user tenantId expiredAt') + .lean(), + ); + } + + async function clearSharedLinkLegacyVisibility(resourceId: string): Promise { + await mongoose.connection + .db!.collection('sharedlinks') + .updateOne({ _id: new Types.ObjectId(resourceId) }, { $unset: { isPublic: 1 } }); + } + + async function deleteSharedLinkById(resourceId: string): Promise { + await mongoose.models.SharedLink.deleteOne({ _id: resourceId }); + } + /** * Get shared messages for a share link */ @@ -1203,11 +1290,19 @@ export function createShareMethods(mongoose: typeof import('mongoose')): { */ async function deleteAllSharedLinks( user: string, + beforeDelete?: (resourceIds: string[]) => Promise, ): Promise { + let cleanupFailed = false; try { const SharedLink = mongoose.models.SharedLink as Model; const links = await SharedLink.find({ user }).select('_id').lean(); const ids = links.map((l) => l._id.toString()); + try { + await beforeDelete?.(ids); + } catch (error) { + cleanupFailed = true; + throw error; + } const result = await SharedLink.deleteMany({ user }); return { message: 'All shared links deleted successfully', @@ -1215,6 +1310,9 @@ export function createShareMethods(mongoose: typeof import('mongoose')): { deletedIds: ids, }; } catch (error) { + if (cleanupFailed) { + throw error; + } logger.error('[deleteAllSharedLinks] Error deleting shared links', { error: error instanceof Error ? error.message : 'Unknown error', user, @@ -1668,6 +1766,12 @@ export function createShareMethods(mongoose: typeof import('mongoose')): { // Return all methods return { + findShareConversationRetention, + findActiveSharedLink, + findSharedLinkById, + findOwnedSharedLink, + clearSharedLinkLegacyVisibility, + deleteSharedLinkById, getSharedLink, getSharedLinks, createSharedLink, diff --git a/packages/data-schemas/src/methods/transaction.spec.ts b/packages/data-schemas/src/methods/transaction.spec.ts index 2e1d93def8..5599010dd9 100644 --- a/packages/data-schemas/src/methods/transaction.spec.ts +++ b/packages/data-schemas/src/methods/transaction.spec.ts @@ -32,6 +32,7 @@ let releaseBalanceReservation: ReturnType< >['releaseBalanceReservation']; let findBalanceByUser: ReturnType['findBalanceByUser']; let upsertBalanceFields: ReturnType['upsertBalanceFields']; +let initializeNullBalance: ReturnType['initializeNullBalance']; let updateBalance: ReturnType['updateBalance']; let getMultiplier: ReturnType['getMultiplier']; let getCacheMultiplier: ReturnType['getCacheMultiplier']; @@ -64,6 +65,7 @@ beforeAll(async () => { findBalanceByUser = transactionMethods.findBalanceByUser; upsertBalanceFields = transactionMethods.upsertBalanceFields; updateBalance = transactionMethods.updateBalance; + initializeNullBalance = transactionMethods.initializeNullBalance; const spendMethods = createSpendTokensMethods(mongoose, { createTransaction: transactionMethods.createTransaction, @@ -1863,3 +1865,41 @@ describe('Balance Reservations', () => { }); }); }); + +describe('initializeNullBalance admission CAS', () => { + it.each([null, undefined])( + 'initializes legacy credit %s only once without upsert', + async (credit) => { + const user = new mongoose.Types.ObjectId().toString(); + await Balance.collection.insertOne({ + user: new mongoose.Types.ObjectId(user), + ...(credit === undefined ? {} : { tokenCredits: credit }), + }); + const initialized = await initializeNullBalance(user, { + tokenCredits: 100, + sync: { autoRefillEnabled: true }, + }); + expect(initialized?.tokenCredits).toBe(100); + expect(initialized?.autoRefillEnabled).toBe(true); + await Balance.updateOne({ user }, { $set: { tokenCredits: 7 } }); + expect(await initializeNullBalance(user, { tokenCredits: 100 })).toBeNull(); + expect((await findBalanceByUser(user))?.tokenCredits).toBe(7); + expect(await Balance.countDocuments({ user })).toBe(1); + }, + ); + + it('chooses the oldest eligible row and never creates a missing balance', async () => { + const user = new mongoose.Types.ObjectId().toString(); + expect(await initializeNullBalance(user, { tokenCredits: 100 })).toBeNull(); + const first = new mongoose.Types.ObjectId('000000000000000000000001'); + const second = new mongoose.Types.ObjectId('000000000000000000000002'); + await Balance.collection.insertMany([ + { _id: second, user: new mongoose.Types.ObjectId(user), tokenCredits: null }, + { _id: first, user: new mongoose.Types.ObjectId(user), tokenCredits: null }, + ]); + expect((await initializeNullBalance(user, { tokenCredits: 100 }))?._id.toString()).toBe( + first.toString(), + ); + expect((await Balance.findById(second).lean())?.tokenCredits).toBeNull(); + }); +}); diff --git a/packages/data-schemas/src/methods/transaction.ts b/packages/data-schemas/src/methods/transaction.ts index 50fca1e819..edcce34a1a 100644 --- a/packages/data-schemas/src/methods/transaction.ts +++ b/packages/data-schemas/src/methods/transaction.ts @@ -105,6 +105,10 @@ export function createTransactionMethods( user: string, options?: { includeReservedCredits?: boolean; applyReset?: boolean }, ) => Promise; + initializeNullBalance: ( + user: string, + input: { tokenCredits: number; sync?: IBalanceUpdate }, + ) => Promise; upsertBalanceFields: ( user: string, fields: IBalanceUpdate, @@ -795,7 +799,21 @@ export function createTransactionMethods( } } + /** Null also matches legacy missing credit; a miss must never upsert or restore spent credit. */ + async function initializeNullBalance( + user: string, + { tokenCredits, sync }: { tokenCredits: number; sync?: IBalanceUpdate }, + ): Promise { + const Balance = mongoose.models.Balance as Model; + return Balance.findOneAndUpdate( + { user, tokenCredits: null }, + { $set: { tokenCredits, ...(sync && Object.keys(sync).length > 0 ? sync : {}) } }, + { new: true, sort: oldestFirst }, + ).lean(); + } + return { + initializeNullBalance, updateBalance, bulkInsertTransactions, findBalanceByUser, diff --git a/packages/data-schemas/src/methods/user.ts b/packages/data-schemas/src/methods/user.ts index 4820a8827f..8d5d444c37 100644 --- a/packages/data-schemas/src/methods/user.ts +++ b/packages/data-schemas/src/methods/user.ts @@ -52,6 +52,9 @@ export function createUserMethods( mongoose: typeof import('mongoose'), deps: UserMethodDeps = {}, ): { + findScheduleOwner: ( + userId: string, + ) => Promise<{ _id: string; tenantId?: string; role?: string; termsAccepted?: boolean } | null>; findUser: ( searchCriteria: FilterQuery, fieldsToSelect?: string | string[] | null, @@ -1027,7 +1030,24 @@ export function createUserMethods( return updated; } + async function findScheduleOwner( + userId: string, + ): Promise<{ _id: string; tenantId?: string; role?: string; termsAccepted?: boolean } | null> { + const user = await mongoose.models.User.findById(userId) + .select('_id tenantId role termsAccepted') + .lean(); + return user + ? { + _id: user._id.toString(), + tenantId: user.tenantId, + role: user.role, + termsAccepted: user.termsAccepted, + } + : null; + } + return { + findScheduleOwner, findUser, findUsers, findOwnerContactUsers,