Sync-in · Sovereign platform for file storage, sharing, synchronization, and collaboration.
TypeScript cloud-alternativecollaborationcollaborative-editingdropboxfile-serverfile-sharingfile-storagefile-syncfull-text-searchhomelabnextcloudon-premiseopen-sourceprivacy-firstprivate-cloudrealtimesecureself-hostedstorage-serverwebdav
fix(backend:files): preserve trash source during overwrite restore
johaven13fcae9ebbe4
diff --git a/backend/src/applications/files/services/files-manager.service.spec.ts b/backend/src/applications/files/services/files-manager.service.spec.tsindex 007e2d14..149097b6 100644--- a/backend/src/applications/files/services/files-manager.service.spec.ts+++ b/backend/src/applications/files/services/files-manager.service.spec.ts@@ -984,6 +984,61 @@ describe(FilesManager.name, () => {})describe('copyMove', () => {+ const prepareExternalRootOverwriteRestore = (task?: Record<string, any>) => {+ const trashDbScope = { ownerId: null, spaceId: 11, spaceExternalRootId: null, shareExternalId: null, inTrash: true }+ const src = makeSpace({+ id: 11,+ repository: 'trash',+ url: 'trash/project/documents/report.txt',+ inTrashRepository: true,+ inPersonalSpace: false,+ realPath: '/data/spaces/project/trash/documents/report.txt',+ realBasePath: '/data/spaces/project/trash',+ dbFile: { ...trashDbScope, path: 'documents/report.txt' },+ task+ })+ const dst = makeSpace({+ id: 11,+ url: 'files/project/archive/documents/report.txt',+ inPersonalSpace: false,+ realPath: '/mnt/archive/documents/report.txt',+ realBasePath: '/mnt/archive',+ dbFile: {+ ownerId: null,+ spaceId: 11,+ spaceExternalRootId: 22,+ shareExternalId: null,+ path: 'documents/report.txt',+ inTrash: false+ }+ })+ const datedTrashFile = '/data/spaces/project/trash/documents/report-2026.txt'+ vi.mocked(spacesPathUtils.trashTargetFromSpace).mockReturnValueOnce({+ dbScope: trashDbScope,+ mode: 'trash',+ path: '/data/spaces/project/trash',+ temporaryRoot: '/data/spaces/project/tmp/users/7'+ })+ setPathExists(+ {+ [src.realPath]: true,+ [path.dirname(src.realPath)]: true,+ [path.dirname(dst.realPath)]: true,+ [dst.realPath]: true,+ [datedTrashFile]: false+ },+ false+ )+ vi.mocked(filesUtils.isPathIsDir).mockResolvedValue(false)+ vi.mocked(filesUtils.uniqueDatedFilePath).mockResolvedValueOnce({ isDir: false, path: datedTrashFile })+ return {+ datedTrashDb: { ...trashDbScope, path: 'documents/report-2026.txt' },+ datedTrashFile,+ dst,+ src+ }+ }+it('should copy file and emit add event', async () => {const src = makeSpace({id: 10,@@ -1096,6 +1151,52 @@ describe(FilesManager.name, () => {expect(filesQueries.moveFiles).toHaveBeenCalledWith(src.dbFile, dst.dbFile, false)})+ it('should preserve the trash source while restoring over its occupied external-root destination', async () => {+ const { datedTrashDb, datedTrashFile, dst, src } = prepareExternalRootOverwriteRestore()++ await service.copyMove(user, src, dst, true, true)++ expect(filesUtils.uniqueDatedFilePath).toHaveBeenCalledWith(dst.realPath)+ expect(filesUtils.moveFiles).toHaveBeenCalledTimes(2)+ expect(filesUtils.moveFiles).toHaveBeenNthCalledWith(1, dst.realPath, datedTrashFile, true)+ expect(filesUtils.moveFiles).toHaveBeenNthCalledWith(2, src.realPath, dst.realPath, true)+ expect(filesQueries.moveFiles).toHaveBeenCalledTimes(2)+ expect(filesQueries.moveFiles).toHaveBeenNthCalledWith(1, dst.dbFile, datedTrashDb, false)+ expect(filesQueries.moveFiles).toHaveBeenNthCalledWith(2, src.dbFile, dst.dbFile, false)+ })++ it('should preserve the trash source while copying over its occupied external-root destination', async () => {+ const { datedTrashDb, datedTrashFile, dst, src } = prepareExternalRootOverwriteRestore()++ await service.copyMove(user, src, dst, false, true)++ expect(filesUtils.moveFiles).toHaveBeenCalledOnce()+ expect(filesUtils.moveFiles).toHaveBeenCalledWith(dst.realPath, datedTrashFile, true)+ expect(filesUtils.copyFiles).toHaveBeenCalledWith(src.realPath, dst.realPath, true, false)+ expect(filesQueries.moveFiles).toHaveBeenCalledOnce()+ expect(filesQueries.moveFiles).toHaveBeenCalledWith(dst.dbFile, datedTrashDb, false)+ })++ it('should preserve the trash source until an overwrite move task commits', async () => {+ const task = { id: 'task-restore', type: FILE_OPERATION.MOVE, cacheKey: 'task-restore', props: {} }+ const { datedTrashDb, datedTrashFile, dst, src } = prepareExternalRootOverwriteRestore(task)+ const signal = new AbortController().signal+ filesTasksTransfer.move.mockImplementationOnce(async (...args: any[]) => {+ const deleteDestination = args[6] as () => Promise<void>+ await deleteDestination()+ return undefined+ })++ await service.copyMove(user, src, dst, true, true, false, undefined, signal)++ expect(filesTasksTransfer.move).toHaveBeenCalledWith(user, src, dst, true, false, signal, expect.any(Function))+ expect(filesUtils.moveFiles).toHaveBeenCalledOnce()+ expect(filesUtils.moveFiles).toHaveBeenCalledWith(dst.realPath, datedTrashFile, true)+ expect(filesQueries.moveFiles).toHaveBeenCalledTimes(2)+ expect(filesQueries.moveFiles).toHaveBeenNthCalledWith(1, dst.dbFile, datedTrashDb, false)+ expect(filesQueries.moveFiles).toHaveBeenNthCalledWith(2, src.dbFile, dst.dbFile, false)+ })+it('should update the database before reporting an abortable move source cleanup failure', async () => {const src = makeSpace({url: 'files/source/src.txt',diff --git a/backend/src/applications/files/services/files-manager.service.ts b/backend/src/applications/files/services/files-manager.service.tsindex 8489c240..d6059890 100644--- a/backend/src/applications/files/services/files-manager.service.ts+++ b/backend/src/applications/files/services/files-manager.service.ts@@ -76,6 +76,10 @@ import { createTar } from '../utils/tar-file'import { createZip } from '../utils/zip-file'import { FILE_ERROR } from '../constants/errors'+interface DeleteOptions {+ protectedTrashPath?: string+}+@Injectable()export class FilesManager {// Spaces permissions are checked in the space guard, except for the copy/move destination@@ -510,16 +514,21 @@ export class FilesManager {// check destinationawait this.filesLockManager.checkConflicts(dstSpace.dbFile, depth, { userId: user.id, lockTokens: dav?.lockTokens })+ const deleteDestination = (): Promise<void> =>+ srcSpace.inTrashRepository+ ? this.delete(user, dstSpace, undefined, undefined, { protectedTrashPath: srcSpace.realPath })+ : this.delete(user, dstSpace)+// Task transfers defer overwrite handling until their staged content is ready to commit.if (!useTaskTransfer && overwrite && (await isPathExists(dstSpace.realPath))) {- await this.delete(user, dstSpace)+ await deleteDestination()}// doif (isMove) {let sourceCleanupError: SourceCleanupError | undefinedif (useTaskTransfer && signal) {- sourceCleanupError = await this.filesTasksTransfer.move(user, srcSpace, dstSpace, overwrite, isDir, signal, () => this.delete(user, dstSpace))+ sourceCleanupError = await this.filesTasksTransfer.move(user, srcSpace, dstSpace, overwrite, isDir, signal, deleteDestination)} else {await moveFiles(srcSpace.realPath, dstSpace.realPath, overwrite)}@@ -539,7 +548,7 @@ export class FilesManager {if (!signal) {throw new Error('An abort signal is required for a copy task')}- await this.filesTasksTransfer.copy(user, srcSpace, dstSpace, overwrite, recursive, isDir, signal, () => this.delete(user, dstSpace))+ await this.filesTasksTransfer.copy(user, srcSpace, dstSpace, overwrite, recursive, isDir, signal, deleteDestination)} else {await copyFiles(srcSpace.realPath, dstSpace.realPath, overwrite, recursive)}@@ -548,7 +557,7 @@ export class FilesManager {}}- async delete(user: UserModel, space: SpaceEnv, dav?: { lockTokens: string[] }, signal?: AbortSignal): Promise<void> {+ async delete(user: UserModel, space: SpaceEnv, dav?: { lockTokens: string[] }, signal?: AbortSignal, options?: DeleteOptions): Promise<void> {const isTaskContext = Boolean(space.task?.cacheKey)if (!(await isPathExists(space.realPath))) {throw new FileError(HttpStatus.NOT_FOUND, 'Location not found')@@ -569,14 +578,21 @@ export class FilesManager {} else {const trashTarget = trashTargetFromSpace(user, space)if (trashTarget?.mode === 'trash') {- const destinationDbFile: FileDBProps = { ...trashTarget.dbScope, path: space.dbFile.path }- trashDbFile = destinationDbFile+ let destinationDbFile: FileDBProps = { ...trashTarget.dbScope, path: space.dbFile.path }const name = fileName(space.realPath)const trashDir = path.join(trashTarget.path, dirName(space.dbFile.path))- const trashFile = path.join(trashDir, name)+ let trashFile = path.join(trashDir, name)if (!(await isPathExists(trashDir))) {await makeDir(trashDir, true)}+ // During an overwrite from trash, this path can be the active copy/move source.+ // Keep that source stable and archive the overwritten destination under a dated name instead.+ if (options?.protectedTrashPath && path.resolve(options.protectedTrashPath) === path.resolve(trashFile)) {+ const datedDestination = await uniqueDatedFilePath(space.realPath)+ trashFile = path.join(trashDir, fileName(datedDestination.path))+ destinationDbFile = { ...destinationDbFile, path: path.join(dirName(destinationDbFile.path), fileName(trashFile)) }+ }+ trashDbFile = destinationDbFileif (isTaskContext) {sourceCleanupError = await this.filesTasksTransfer.delete(space, trashFile, trashTarget.temporaryRoot, isDir, signal, () =>this.moveExistingTrashFile(trashFile, destinationDbFile)diff --git a/backend/src/applications/spaces/spaces.md b/backend/src/applications/spaces/spaces.mdindex 00c1dfe7..e7d95ba4 100644--- a/backend/src/applications/spaces/spaces.md+++ b/backend/src/applications/spaces/spaces.md@@ -87,6 +87,10 @@ Moving an entry into trash updates its existing database record rather than deletherefore preserved. A collision is resolved against the canonical destination scope before the incoming record is moved into it. In particular,entries from different external roots converge on the same native-space trash scope.+When a resource is restored with overwrite to the location from which it was deleted, its own trash path is protected for the duration of the+operation. The overwritten destination is archived under a dated name instead, so the active restore source keeps the same filesystem path and+database identity.+For an external share, deletion skips this lifecycle and removes the source directly from the filesystem and database.Deleting a resource that is already under `trash/...` removes it permanently from the filesystem and database. The trash itself is a protected virtual