Skip to content

Sync-in · Sovereign platform for file storage, sharing, synchronization, and collaboration.

refactor(backend): adopt Zod validation and strict typing (#294)

Johan Legrand02a062386c78
diff --git a/backend/package.json b/backend/package.json
index b24f633b..ceb8b179 100755
--- a/backend/package.json
+++ b/backend/package.json
@@ -54,8 +54,6 @@
"@socket.io/redis-adapter": "^8.3.0",
"@zip.js/zip.js": "^2.8.26",
"bcryptjs": "^3.0.3",
- "class-transformer": "^0.5.1",
- "class-validator": "^0.15.1",
"deepmerge": "^4.3.1",
"drizzle-kit": "^0.31.10",
"drizzle-orm": "^0.45.2",
@@ -88,7 +86,8 @@
"tesseract.js": "^7.0.0",
"text-to-svg": "^3.1.5",
"time2fa": "^1.4.2",
- "unpdf": "^1.8.1"
+ "unpdf": "^1.8.1",
+ "zod": "^4.6.5"
},
"devDependencies": {
"@eslint/js": "^9.18.0",
diff --git a/backend/src/app.bootstrap.ts b/backend/src/app.bootstrap.ts
index 98079c70..d34d8318 100644
--- a/backend/src/app.bootstrap.ts
+++ b/backend/src/app.bootstrap.ts
@@ -1,8 +1,8 @@
import fastifyCookie from '@fastify/cookie'
import fastifyHelmet from '@fastify/helmet'
import multipart from '@fastify/multipart'
-import { ClassSerializerInterceptor, ValidationPipe } from '@nestjs/common'
-import { NestFactory, Reflector } from '@nestjs/core'
+import { StandardSchemaValidationPipe } from '@nestjs/common'
+import { NestFactory } from '@nestjs/core'
import { FastifyAdapter, NestFastifyApplication } from '@nestjs/platform-fastify'
import { FastifyInstance, FastifyRequest } from 'fastify'
import { Logger, LoggerErrorInterceptor } from 'nestjs-pino'
@@ -49,15 +49,12 @@ export async function appBootstrap(): Promise<NestFastifyApplication> {
fastifyInstance.addContentTypeParser('*', (_req: FastifyRequest, _payload: FastifyRequest['raw'], done) => done(null))
/* INTERCEPTORS */
- app.useGlobalInterceptors(
- new LoggerErrorInterceptor(),
- new ClassSerializerInterceptor(app.get(Reflector), {
- excludePrefixes: ['_']
- })
- )
+ // UserModel owns its Zod-backed response serialization; its internal caches
+ // use ECMAScript private fields and therefore cannot leak into JSON responses.
+ app.useGlobalInterceptors(new LoggerErrorInterceptor())
/* VALIDATION */
- app.useGlobalPipes(new ValidationPipe({ transform: true, whitelist: true }))
+ app.useGlobalPipes(new StandardSchemaValidationPipe())
/* STATIC */
app.useStaticAssets({ root: STATIC_PATH, prefixAvoidTrailingSlash: true })
diff --git a/backend/src/app.constants.ts b/backend/src/app.constants.ts
index 4cae0916..89e0736d 100644
--- a/backend/src/app.constants.ts
+++ b/backend/src/app.constants.ts
@@ -2,7 +2,7 @@ import { loadVersion } from './app.functions.js'
export const VERSION = loadVersion()
export const USER_AGENT = `sync-in-server/${VERSION}`
-export const CONTENT_SECURITY_POLICY = (xOfficeServer: string, collaboraServer: string, drawioServer: string) => ({
+export const CONTENT_SECURITY_POLICY = (xOfficeServer: string | null, collaboraServer: string | null, drawioServer: string | null) => ({
useDefaults: false,
directives: {
defaultSrc: ["'self'"],
diff --git a/backend/src/app.functions.ts b/backend/src/app.functions.ts
index ccfecb4b..ac2bab26 100644
--- a/backend/src/app.functions.ts
+++ b/backend/src/app.functions.ts
@@ -1,3 +1,4 @@
+import { toErrorMessage } from './common/errors.js'
import { existsSync, readFileSync } from 'fs'
import { dirname, join, resolve } from 'node:path'
import { fileURLToPath } from 'node:url'
@@ -17,7 +18,7 @@ export function loadVersion(): string {
version = candidateVersion
break
} catch (e) {
- console.error(`unable to load version from: ${p} - ${e}`)
+ console.error(`unable to load version from: ${p} - ${toErrorMessage(e)}`)
}
}
diff --git a/backend/src/app.module.ts b/backend/src/app.module.ts
index 89dcf068..35ace947 100755
--- a/backend/src/app.module.ts
+++ b/backend/src/app.module.ts
@@ -5,6 +5,7 @@ import { USER_AGENT } from './app.constants.js'
import { AppService } from './app.service.js'
import { ApplicationsModule } from './applications/applications.module.js'
import { AuthModule } from './authentication/auth.module.js'
+import { IS_TEST_ENV } from './configuration/config.constants.js'
import { configuration } from './configuration/config.environment.js'
import { configLogger } from './configuration/config.logger.js'
import type { FastifyLoggerRequest } from './configuration/interfaces/logger.interface.js'
@@ -19,7 +20,7 @@ import { SchedulerModule } from './infrastructure/scheduler/scheduler.module.js'
imports: [
LoggerModule.forRootAsync<FastifyLoggerRequest>({
useFactory: async () => ({
- pinoHttp: configLogger(configuration.logger)
+ pinoHttp: IS_TEST_ENV ? { level: 'silent' } : configLogger(configuration.logger)
})
}),
AvailabilityModule,
diff --git a/backend/src/app.service.spec.ts b/backend/src/app.service.spec.ts
index a913995e..893685f3 100644
--- a/backend/src/app.service.spec.ts
+++ b/backend/src/app.service.spec.ts
@@ -43,7 +43,7 @@ describe(AppService.name, () => {
const processOnSpy = vi.spyOn(process, 'on')
const processExitSpy = vi.spyOn(process, 'exit').mockImplementation((() => undefined) as never)
- configuration.websocket.adapter = null
+ configuration.websocket.adapter = null as never
configuration.server.restartOnFailure = true
AppService.clusterize(vi.fn().mockResolvedValue(undefined))
@@ -120,7 +120,7 @@ describe(AppService.name, () => {
expect(vi.mocked(cluster.fork).mock.calls.length).toBe(forkCallsAfterTrue)
// --- MASTER again, adapter != 'cluster' -> covers the FALSE side of the adapter check
- configuration.websocket.adapter = null
+ configuration.websocket.adapter = null as never
expect(() => AppService.clusterize(bootstrap)).not.toThrow()
// setupPrimary should NOT be called again
expect(setupPrimary).toHaveBeenCalledTimes(1)
diff --git a/backend/src/app.service.ts b/backend/src/app.service.ts
index b6e44bf8..828b52b7 100755
--- a/backend/src/app.service.ts
+++ b/backend/src/app.service.ts
@@ -1,21 +1,24 @@
-import { Injectable, Logger } from '@nestjs/common'
+import { ConsoleLogger, Injectable } from '@nestjs/common'
import { setupPrimary } from '@socket.io/cluster-adapter'
import cluster, { Worker } from 'node:cluster'
import { cpus } from 'node:os'
import process from 'node:process'
import { configuration } from './configuration/config.environment.js'
+import { IS_TEST_ENV } from './configuration/config.constants.js'
import { SCHEDULER_ENV, SCHEDULER_STATE } from './infrastructure/scheduler/scheduler.constants.js'
import { SERVER_NAME } from './common/shared.js'
@Injectable()
export class AppService {
- static schedulerPID: number
- private static readonly logger = new Logger('SERVER')
+ static schedulerPID?: number
+ private static readonly logger = new ConsoleLogger('SERVER', {
+ prefix: SERVER_NAME,
+ logLevels: IS_TEST_ENV ? ['fatal'] : undefined
+ })
private static shuttingDown = false
private static shutdownHooksRegistered = false
static clusterize(bootstrap: () => Promise<void>) {
- AppService.logger.localInstance['options']['prefix'] = SERVER_NAME
if (cluster.isPrimary) {
if (configuration.websocket.adapter === 'cluster') {
// setup connections between the workers
diff --git a/backend/src/applications/admin/services/admin.service.ts b/backend/src/applications/admin/services/admin.service.ts
index 8c381f2e..7a4bf62f 100644
--- a/backend/src/applications/admin/services/admin.service.ts
+++ b/backend/src/applications/admin/services/admin.service.ts
@@ -1,3 +1,4 @@
+import { toErrorMessage } from '../../../common/errors.js'
import { HttpService } from '@nestjs/axios'
import { Injectable, Logger } from '@nestjs/common'
import type { AxiosResponse } from 'axios'
@@ -37,7 +38,7 @@ export class AdminService {
})
lastVersion = res.data?.tag_name || ''
} catch (e) {
- this.logger.warn({ tag: this.checkServerUpdateAndNotify.name, msg: `unable to check update: ${e}` })
+ this.logger.warn({ tag: this.checkServerUpdateAndNotify.name, msg: `unable to check update: ${toErrorMessage(e)}` })
return
}
if (!lastVersion.startsWith('v')) {
@@ -73,6 +74,6 @@ export class AdminService {
this.notificationsManager
.create(adminsToNotify, notification)
.then(() => this.cache.set(this.checkServerUpdateAndNotify.name, { version: lastVersion } satisfies ServerReleaseNotification, 0))
- .catch((e: Error) => this.logger.error({ tag: this.checkServerUpdateAndNotify.name, msg: `${e}` }))
+ .catch((e: Error) => this.logger.error({ tag: this.checkServerUpdateAndNotify.name, msg: toErrorMessage(e) }))
}
}
diff --git a/backend/src/applications/applications.config.ts b/backend/src/applications/applications.config.ts
index 0fa201dd..0e2ef669 100644
--- a/backend/src/applications/applications.config.ts
+++ b/backend/src/applications/applications.config.ts
@@ -1,28 +1,10 @@
-import { Type } from 'class-transformer'
-import { IsDefined, IsNotEmptyObject, IsObject, ValidateNested } from 'class-validator'
-import { FilesConfig } from './files/files.config.js'
-import { AppStoreConfig } from './sync/sync.config.js'
-import { UsersConfig } from './users/users.config.js'
+import { z } from 'zod'
+import { FilesConfigSchema } from './files/files.config.js'
+import { AppStoreConfigSchema } from './sync/sync.config.js'
+import { UsersConfigSchema } from './users/users.config.js'
-export class ApplicationsConfig {
- @IsDefined()
- @IsObject()
- @IsNotEmptyObject()
- @ValidateNested()
- @Type(() => FilesConfig)
- files: FilesConfig
-
- @IsDefined()
- @IsObject()
- @IsNotEmptyObject()
- @ValidateNested()
- @Type(() => UsersConfig)
- users: UsersConfig = new UsersConfig()
-
- @IsDefined()
- @IsObject()
- @IsNotEmptyObject()
- @ValidateNested()
- @Type(() => AppStoreConfig)
- appStore: AppStoreConfig = new AppStoreConfig()
-}
+export const ApplicationsConfigSchema = z.looseObject({
+ files: FilesConfigSchema,
+ users: UsersConfigSchema.prefault({}),
+ appStore: AppStoreConfigSchema.prefault({})
+})
diff --git a/backend/src/applications/comments/comments.controller.ts b/backend/src/applications/comments/comments.controller.ts
index 247ec976..0e1fa06f 100644
--- a/backend/src/applications/comments/comments.controller.ts
+++ b/backend/src/applications/comments/comments.controller.ts
@@ -1,4 +1,4 @@
-import { BadRequestException, Body, Controller, Delete, Get, ParseIntPipe, Patch, Post, Query, UseGuards } from '@nestjs/common'
+import { Body, Controller, Delete, Get, Patch, Post, Query, UseGuards } from '@nestjs/common'
import { SkipSpaceGuard } from '../spaces/decorators/space-skip-guard.decorator.js'
import { SkipSpacePermissionsCheck } from '../spaces/decorators/space-skip-permissions.decorator.js'
import { GetSpace } from '../spaces/decorators/space.decorator.js'
@@ -6,11 +6,12 @@ import { SpaceGuard } from '../spaces/guards/space.guard.js'
import { SpaceEnv } from '../spaces/models/space-env.model.js'
import { GetUser } from '../users/decorators/user.decorator.js'
import type { UserModel } from '../users/models/user.model.js'
+import { recentCommentsLimitQuerySchema } from './comments.schema.js'
import { COMMENTS_RECENTS_DEFAULT_LIMIT, COMMENTS_RECENTS_MAX_LIMIT } from './constants/recents.js'
import { COMMENTS_ROUTE } from './constants/routes.js'
-import { CreateOrUpdateCommentDto, DeleteCommentDto } from './dto/comment.dto.js'
+import { type CreateOrUpdateCommentDto, createOrUpdateCommentSchema, type DeleteCommentDto, deleteCommentSchema } from './dto/comment.dto.js'
import { CommentRecent } from './interfaces/comment-recent.interface.js'
-import { Comment } from './schemas/comment.interface.js'
+import type { Comment } from './schemas/comment.interface.js'
import { CommentsManager } from './services/comments-manager.service.js'
@Controller(COMMENTS_ROUTE.BASE)
@@ -25,17 +26,29 @@ export class CommentsController {
}
@Post(`${COMMENTS_ROUTE.SPACES}/*`)
- createFromSpace(@GetUser() user: UserModel, @GetSpace() space: SpaceEnv, @Body() createCommentDto: CreateOrUpdateCommentDto): Promise<Comment> {
+ createFromSpace(
+ @GetUser() user: UserModel,
+ @GetSpace() space: SpaceEnv,
+ @Body({ schema: createOrUpdateCommentSchema }) createCommentDto: CreateOrUpdateCommentDto
+ ): Promise<Comment> {
return this.commentsManager.createComment(user, space, createCommentDto)
}
@Patch(`${COMMENTS_ROUTE.SPACES}/*`)
- updateFromSpace(@GetUser() user: UserModel, @GetSpace() space: SpaceEnv, @Body() updateCommentDto: CreateOrUpdateCommentDto): Promise<Comment> {
+ updateFromSpace(
+ @GetUser() user: UserModel,
+ @GetSpace() space: SpaceEnv,
+ @Body({ schema: createOrUpdateCommentSchema }) updateCommentDto: CreateOrUpdateCommentDto
+ ): Promise<Comment> {
return this.commentsManager.updateComment(user, space, updateCommentDto)
}
@Delete(`${COMMENTS_ROUTE.SPACES}/*`)
- deleteFromSpace(@GetUser() user: UserModel, @GetSpace() space: SpaceEnv, @Body() deleteCommentDto: DeleteCommentDto): Promise<void> {
+ deleteFromSpace(
+ @GetUser() user: UserModel,
+ @GetSpace() space: SpaceEnv,
+ @Body({ schema: deleteCommentSchema }) deleteCommentDto: DeleteCommentDto
+ ): Promise<void> {
return this.commentsManager.deleteComment(user, space, deleteCommentDto)
}
@@ -43,9 +56,8 @@ export class CommentsController {
@SkipSpaceGuard()
getRecents(
@GetUser() user: UserModel,
- @Query('limit', new ParseIntPipe({ optional: true })) limit: number = COMMENTS_RECENTS_DEFAULT_LIMIT
+ @Query('limit', { schema: recentCommentsLimitQuerySchema }) limit: number = COMMENTS_RECENTS_DEFAULT_LIMIT
): Promise<CommentRecent[]> {
- if (!Number.isInteger(limit) || limit < 1) throw new BadRequestException('limit must be a positive integer')
return this.commentsManager.getRecents(user, Math.min(limit, COMMENTS_RECENTS_MAX_LIMIT))
}
}
diff --git a/backend/src/applications/comments/comments.schema.ts b/backend/src/applications/comments/comments.schema.ts
new file mode 100644
index 00000000..46c0cfcc
--- /dev/null
+++ b/backend/src/applications/comments/comments.schema.ts
@@ -0,0 +1,3 @@
+import { positiveIntegerFromStringSchema } from '../../configuration/config.schema.js'
+
+export const recentCommentsLimitQuerySchema = positiveIntegerFromStringSchema.optional()
diff --git a/backend/src/applications/comments/dto/comment.dto.spec.ts b/backend/src/applications/comments/dto/comment.dto.spec.ts
new file mode 100644
index 00000000..b47f2d97
--- /dev/null
+++ b/backend/src/applications/comments/dto/comment.dto.spec.ts
@@ -0,0 +1,22 @@
+import { createOrUpdateCommentSchema, deleteCommentSchema } from './comment.dto.js'
+
+describe('comment schemas', () => {
+ it('accepts a large temporary inode for the first comment', () => {
+ const fileId = -(2 ** 54)
+
+ expect(createOrUpdateCommentSchema.parse({ fileId, content: 'Comment' })).toEqual({ fileId, content: 'Comment' })
+ })
+
+ it('preserves large SQL file and comment identifiers for updates and deletions', () => {
+ const fileId = 2 ** 54
+ const commentId = 2 ** 53
+
+ expect(createOrUpdateCommentSchema.parse({ fileId, content: 'Updated', commentId })).toEqual({ fileId, content: 'Updated', commentId })
+ expect(deleteCommentSchema.parse({ fileId, commentId })).toEqual({ fileId, commentId })
+ })
+
+ it.each([1.5, -1.5, NaN, Infinity, -Infinity])('rejects a non-integer or non-finite file identifier %s', (fileId) => {
+ expect(createOrUpdateCommentSchema.safeParse({ fileId, content: 'Comment' }).success).toBe(false)
+ expect(deleteCommentSchema.safeParse({ fileId, commentId: 42 }).success).toBe(false)
+ })
+})
diff --git a/backend/src/applications/comments/dto/comment.dto.ts b/backend/src/applications/comments/dto/comment.dto.ts
index 8e394424..74b90f0d 100644
--- a/backend/src/applications/comments/dto/comment.dto.ts
+++ b/backend/src/applications/comments/dto/comment.dto.ts
@@ -1,24 +1,17 @@
-import { IsInt, IsNotEmpty, IsOptional, IsString } from 'class-validator'
+import { z } from 'zod'
+import { integerNumberSchema } from '../../../configuration/config.schema.js'
-export class CreateOrUpdateCommentDto {
- @IsNotEmpty()
- @IsInt()
- fileId: number
+export const createOrUpdateCommentSchema = z.object({
+ fileId: integerNumberSchema,
+ content: z.string().min(1),
+ commentId: integerNumberSchema.nullish()
+})
- @IsNotEmpty()
- @IsString()
- content: string
+export type CreateOrUpdateCommentDto = z.infer<typeof createOrUpdateCommentSchema>
- @IsOptional()
- @IsInt()
- commentId?: number
-}
+export const deleteCommentSchema = z.object({
+ fileId: integerNumberSchema,
+ commentId: integerNumberSchema
+})
-export class DeleteCommentDto {
- @IsNotEmpty()
- @IsInt()
- fileId: number
-
- @IsInt()
- commentId: number
-}
+export type DeleteCommentDto = z.infer<typeof deleteCommentSchema>
diff --git a/backend/src/applications/comments/schemas/comment.interface.ts b/backend/src/applications/comments/schemas/comment.interface.ts
index a24e10e4..8be08f3c 100644
--- a/backend/src/applications/comments/schemas/comment.interface.ts
+++ b/backend/src/applications/comments/schemas/comment.interface.ts
@@ -1,16 +1,9 @@
-import { Owner } from '../../users/interfaces/owner.interface.js'
+import type { Owner } from '../../users/interfaces/owner.interface.js'
import type { comments } from './comments.schema.js'
type CommentSchema = typeof comments.$inferSelect
-export class Comment implements CommentSchema {
- id: number
- userId: number
- fileId: number
- content: string
- createdAt: Date
- modifiedAt: Date
-
+export interface Comment extends CommentSchema {
// extra properties
author: Owner & { isAuthor: boolean }
isFileOwner: boolean
diff --git a/backend/src/applications/comments/services/comments-manager.service.spec.ts b/backend/src/applications/comments/services/comments-manager.service.spec.ts
index 622ef2b9..0a48797d 100644
--- a/backend/src/applications/comments/services/comments-manager.service.spec.ts
+++ b/backend/src/applications/comments/services/comments-manager.service.spec.ts
@@ -13,12 +13,16 @@ import { CommentsQueries } from './comments-queries.service.js'
import { Mock } from 'vitest'
// Mocks of the file utilities used by the service
-vi.mock('../../files/utils/files.js', () => ({
- isPathExists: vi.fn(),
- getProps: vi.fn(),
- dirName: vi.fn(),
- fileName: vi.fn()
-}))
+vi.mock('../../files/utils/files.js', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('../../files/utils/files.js')>()
+ return {
+ ...actual,
+ isPathExists: vi.fn(),
+ getProps: vi.fn(),
+ dirName: vi.fn(),
+ fileName: vi.fn()
+ }
+})
describe(CommentsManager.name, () => {
let commentsManager: CommentsManager
diff --git a/backend/src/applications/comments/services/comments-manager.service.ts b/backend/src/applications/comments/services/comments-manager.service.ts
index e06ae326..d2a7fea0 100644
--- a/backend/src/applications/comments/services/comments-manager.service.ts
+++ b/backend/src/applications/comments/services/comments-manager.service.ts
@@ -1,3 +1,4 @@
+import { toErrorMessage } from '../../../common/errors.js'
import { HttpException, HttpStatus, Injectable, Logger } from '@nestjs/common'
import type { FileProps } from '../../files/interfaces/file-props.interface.js'
import { FilesQueries } from '../../files/services/files-queries.service.js'
@@ -8,7 +9,7 @@ import { UserMailNotification } from '../../notifications/interfaces/user-mail-n
import { NotificationsManager } from '../../notifications/services/notifications-manager.service.js'
import { SpaceEnv } from '../../spaces/models/space-env.model.js'
import { UserModel } from '../../users/models/user.model.js'
-import { CreateOrUpdateCommentDto, DeleteCommentDto } from '../dto/comment.dto.js'
+import type { CreateOrUpdateCommentDto, DeleteCommentDto } from '../dto/comment.dto.js'
import { CommentRecent } from '../interfaces/comment-recent.interface.js'
import type { Comment } from '../schemas/comment.interface.js'
import { CommentsQueries } from './comments-queries.service.js'
@@ -40,7 +41,9 @@ export class CommentsManager {
}
const fileId = await this.getFileId(space, createCommentDto.fileId)
const commentId: number = await this.commentQueries.createComment(user.id, fileId, createCommentDto.content)
- this.notify(user, fileId, space, createCommentDto.content).catch((e: Error) => this.logger.error({ tag: this.createComment.name, msg: `${e}` }))
+ this.notify(user, fileId, space, createCommentDto.content).catch((e: Error) =>
+ this.logger.error({ tag: this.createComment.name, msg: toErrorMessage(e) })
+ )
return (await this.commentQueries.getComments(user.id, space.dbFile?.ownerId === user.id, null, commentId))[0]
}
@@ -53,7 +56,7 @@ export class CommentsManager {
if (fileId === undefined || updateCommentDto.fileId !== fileId || comment.fileId !== fileId) {
throw new HttpException('File id mismatch', HttpStatus.BAD_REQUEST)
}
- if (!(await this.commentQueries.updateComment(user.id, updateCommentDto.commentId, updateCommentDto.fileId, updateCommentDto.content))) {
+ if (!(await this.commentQueries.updateComment(user.id, updateCommentDto.commentId!, updateCommentDto.fileId, updateCommentDto.content))) {
throw new HttpException('Unable to update', HttpStatus.INTERNAL_SERVER_ERROR)
}
return (await this.commentQueries.getComments(user.id, space.dbFile?.ownerId === user.id, null, updateCommentDto.commentId))[0]
@@ -105,6 +108,6 @@ export class CommentsManager {
author: fromUser,
content: comment
})
- .catch((e: Error) => this.logger.error({ tag: this.notify.name, msg: `${e}` }))
+ .catch((e: Error) => this.logger.error({ tag: this.notify.name, msg: toErrorMessage(e) }))
}
}
diff --git a/backend/src/applications/comments/services/comments-queries.service.ts b/backend/src/applications/comments/services/comments-queries.service.ts
index 81514c5d..8ef6fe5d 100644
--- a/backend/src/applications/comments/services/comments-queries.service.ts
+++ b/backend/src/applications/comments/services/comments-queries.service.ts
@@ -1,5 +1,5 @@
import { Inject, Injectable } from '@nestjs/common'
-import { and, desc, eq, getTableColumns, inArray, isNotNull, isNull, ne, or, SelectedFields, SQL, sql } from 'drizzle-orm'
+import { and, desc, eq, getTableColumns, inArray, isNotNull, isNull, ne, or, SQL, sql } from 'drizzle-orm'
import { alias, union } from 'drizzle-orm/mysql-core'
import { DB_TOKEN_PROVIDER } from '../../../infrastructure/database/constants.js'
import type { DBSchema } from '../../../infrastructure/database/interfaces/database.interface.js'
@@ -18,7 +18,7 @@ import { UserModel } from '../../users/models/user.model.js'
import { userFullNameSQL, users } from '../../users/schemas/users.schema.js'
import { COMMENTS_RECENTS_MAX_LIMIT } from '../constants/recents.js'
import { CommentRecent } from '../interfaces/comment-recent.interface.js'
-import { Comment } from '../schemas/comment.interface.js'
+import type { Comment } from '../schemas/comment.interface.js'
import { comments } from '../schemas/comments.schema.js'
@Injectable()
@@ -29,27 +29,27 @@ export class CommentsQueries {
private readonly sharesQueries: SharesQueries
) {}
- getComments(userId: number, isFileOwner: boolean, fromFileId?: number, fromCommentId?: number, limit: number = undefined): Promise<Comment[]> {
+ getComments(userId: number, isFileOwner: boolean, fromFileId?: number | null, fromCommentId?: number | null): Promise<Comment[]> {
let where: SQL
if (fromFileId) {
where = eq(comments.fileId, fromFileId)
} else if (fromCommentId) {
where = eq(comments.id, fromCommentId)
- limit = 1
} else {
throw Error('fromFileId or fromCommentId must be provided')
}
- return this.db
+ const query = this.db
.select({
...getTableColumns(comments),
author: { login: users.login, fullName: userFullNameSQL(users), email: users.email, isAuthor: eq(users.id, userId).mapWith(Boolean) },
isFileOwner: sql`${+isFileOwner}`.mapWith(Boolean)
})
.from(comments)
- .leftJoin(users, eq(users.id, comments.userId))
+ .innerJoin(users, eq(users.id, comments.userId))
.where(where)
.orderBy(desc(comments.id))
- .limit(limit)
+
+ return fromCommentId ? query.limit(1) : query
}
async createComment(userId: number, fileId: number, content: string): Promise<Comment['id']> {
@@ -81,7 +81,7 @@ export class CommentsQueries {
membersToNotify(fromUserId: number, fileId: number): Promise<UserMailNotification[]> {
/* lists the owner of the file and the users who have commented on it */
- const select: UserMailNotification | SelectedFields<any, any> = {
+ const select: Record<keyof UserMailNotification, any> = {
id: users.id,
email: users.email,
language: users.language,
@@ -130,7 +130,7 @@ export class CommentsQueries {
fromShare: sql<number>`1`.as('fromShare'),
displayRootName: shares.name
}
- } satisfies CommentRecent | SelectedFields<any, any>)
+ } satisfies Record<keyof CommentRecent, any>)
.from(shares)
.leftJoin(shareFile, eq(shareFile.id, shares.fileId))
.leftJoin(spaces, eq(spaces.id, shareFile.spaceId))
@@ -185,7 +185,7 @@ export class CommentsQueries {
fromSpace: sql<number>`0`.as('fromSpace'),
fromShare: sql<number>`0`.as('fromShare')
}
- } satisfies CommentRecent | SelectedFields<any, any>)
+ } satisfies Record<keyof CommentRecent, any>)
.from(files)
.innerJoin(comments, and(eq(comments.fileId, files.id), ne(comments.userId, userId)))
.innerJoin(users, eq(users.id, comments.userId))
@@ -220,7 +220,7 @@ export class CommentsQueries {
fromShare: sql<number>`0`.as('fromShare'),
displayRootName: sql<string>`IF (${files.ownerId} = ${userId}, NULL, ${spaces.name})`.as('displayRootName')
}
- } satisfies CommentRecent | SelectedFields<any, any>)
+ } satisfies Record<keyof CommentRecent, any>)
.from(spaces)
.leftJoin(spacesRoots, eq(spacesRoots.spaceId, spaces.id))
.leftJoin(spaceRootFile, eq(spaceRootFile.id, spacesRoots.fileId))
@@ -268,7 +268,7 @@ export class CommentsQueries {
hasSpaces ? this.getRecentsFromSpaces(user.id, spaceIds, sourceLimit) : Promise.resolve([]),
hasShares ? this.getRecentsFromShares(user.id, shareIds, sourceLimit) : Promise.resolve([])
])
- const recents = sourceRecents.flat().sort((a, b) => b.id - a.id)
+ const recents = sourceRecents.flat().sort((a, b) => b.id - a.id) as CommentRecent[]
return Array.from(new Map(recents.map((r) => [r.id, r])).values()).slice(0, recentsLimit)
}
}
diff --git a/backend/src/applications/files/adapters/files-content-store-mysql.service.spec.ts b/backend/src/applications/files/adapters/files-content-store-mysql.service.spec.ts
index afd78e94..31532583 100644
--- a/backend/src/applications/files/adapters/files-content-store-mysql.service.spec.ts
+++ b/backend/src/applications/files/adapters/files-content-store-mysql.service.spec.ts
@@ -390,7 +390,7 @@ describe(FilesContentStoreMySQL.name, () => {
mockSingleSearchRecord(`${before} target ${after}.`)
const res = await filesIndexerMySQL.searchRecords(['files_content_u_1'], 'target', 10)
- const [match] = res[0].matches
+ const [match] = res[0]!.matches!
expect(match).toMatch(/^before2 /)
expect(match).toContain('<mark>target</mark>')
@@ -427,7 +427,7 @@ describe(FilesContentStoreMySQL.name, () => {
const res = await filesIndexerMySQL.searchRecords(['files_content_u_1'], 'खाते', 10)
- expect(res[0].matches[0]).toContain('<mark>खाते</mark>')
+ expect(res[0]!.matches![0]).toContain('<mark>खाते</mark>')
})
it.each([
@@ -437,7 +437,7 @@ describe(FilesContentStoreMySQL.name, () => {
mockSingleSearchRecord('A setting followed by a set value.')
const res = await filesIndexerMySQL.searchRecords(['files_content_u_1'], search, 10)
- const matches = res[0].matches.join(' ')
+ const matches = res[0]!.matches!.join(' ')
expect(matches).toContain(highlightedTerm)
if (rejectedHighlight) {
diff --git a/backend/src/applications/files/adapters/files-content-store-mysql.service.ts b/backend/src/applications/files/adapters/files-content-store-mysql.service.ts
index 81553d45..925c7474 100644
--- a/backend/src/applications/files/adapters/files-content-store-mysql.service.ts
+++ b/backend/src/applications/files/adapters/files-content-store-mysql.service.ts
@@ -1,3 +1,4 @@
+import { toErrorMessage } from '../../../common/errors.js'
import { Inject, Injectable, Logger } from '@nestjs/common'
import { SQL, sql } from 'drizzle-orm'
import { MySqlQueryResult } from 'drizzle-orm/mysql2'
@@ -69,7 +70,7 @@ export class FilesContentStoreMySQL implements FilesContentStore {
await this.ensureRunIdColumn(tableName)
return true
} catch (e) {
- this.logger.error({ tag: this.createIndex.name, msg: `${tableName} : ${e}` })
+ this.logger.error({ tag: this.createIndex.name, msg: `${tableName} : ${toErrorMessage(e)}` })
return false
}
}
@@ -83,7 +84,7 @@ export class FilesContentStoreMySQL implements FilesContentStore {
await this.db.execute(sql`DROP TABLE IF EXISTS ${sql.identifier(tableName)} `)
return true
} catch (e) {
- this.logger.error({ tag: this.dropIndex.name, msg: `${tableName} : ${e}` })
+ this.logger.error({ tag: this.dropIndex.name, msg: `${tableName} : ${toErrorMessage(e)}` })
return false
}
}
@@ -103,7 +104,7 @@ export class FilesContentStoreMySQL implements FilesContentStore {
`)
return true
} catch (e) {
- this.logger.error({ tag: this.insertRecord.name, msg: `${tableName} : ${e}` })
+ this.logger.error({ tag: this.insertRecord.name, msg: `${tableName} : ${toErrorMessage(e)}` })
}
return false
}
@@ -126,7 +127,7 @@ export class FilesContentStoreMySQL implements FilesContentStore {
await this.db.execute(sql`UPDATE ${sql.identifier(tableName)} SET seen_run_id = ${runId} WHERE id IN (${idsSqlList(ids)})`)
return true
} catch (e) {
- this.logger.error({ tag: this.markRecordsSeen.name, msg: `${tableName} : ${e}` })
+ this.logger.error({ tag: this.markRecordsSeen.name, msg: `${tableName} : ${toErrorMessage(e)}` })
}
return false
}
@@ -138,7 +139,7 @@ export class FilesContentStoreMySQL implements FilesContentStore {
this.logger.warn({ tag: this.deleteRecords.name, msg: `${tableName} - deleted : ${r.affectedRows}/${ids.length}` })
}
} catch (e) {
- this.logger.error({ tag: this.deleteRecords.name, msg: `${tableName} : ${e}` })
+ this.logger.error({ tag: this.deleteRecords.name, msg: `${tableName} : ${toErrorMessage(e)}` })
}
}
@@ -147,7 +148,7 @@ export class FilesContentStoreMySQL implements FilesContentStore {
const [r] = await this.db.execute(sql`DELETE FROM ${sql.identifier(tableName)} WHERE seen_run_id IS NULL OR seen_run_id <> ${runId}`)
return r.affectedRows ?? 0
} catch (e) {
- this.logger.error({ tag: this.deleteUnseenRecords.name, msg: `${tableName} : ${e}` })
+ this.logger.error({ tag: this.deleteUnseenRecords.name, msg: `${tableName} : ${toErrorMessage(e)}` })
}
return 0
}
@@ -227,7 +228,7 @@ export class FilesContentStoreMySQL implements FilesContentStore {
const termsHighlightRegexp = new RegExp(`(${FilesContentStoreMySQL.genFullTextHighlightPattern(positiveTerms)})`, 'giu')
for (const r of records) {
- r.matches = FilesContentStoreMySQL.extractHighlightedMatches(r.content, termsHighlightRegexp)
+ r.matches = FilesContentStoreMySQL.extractHighlightedMatches(r.content!, termsHighlightRegexp)
// Do not expose the full indexed content in search results.
r.content = undefined
}
@@ -421,7 +422,7 @@ export class FilesContentStoreMySQL implements FilesContentStore {
private async ensureRunIdColumn(tableName: string): Promise<void> {
// migration for old versions of the application
const [columns] = (await this.db.execute(sql`SHOW COLUMNS FROM ${sql.identifier(tableName)} LIKE 'seen_run_id'`)) as MySqlQueryResult
- if ((columns as unknown[]).length) {
+ if (Array.isArray(columns) && columns.length) {
return
}
await this.db.execute(sql`ALTER TABLE ${sql.identifier(tableName)} ADD COLUMN seen_run_id varchar(64), ADD INDEX seen_run_id (seen_run_id)`)
diff --git a/backend/src/applications/files/dto/file-favorite.dto.spec.ts b/backend/src/applications/files/dto/file-favorite.dto.spec.ts
new file mode 100644
index 00000000..cf863153
--- /dev/null
+++ b/backend/src/applications/files/dto/file-favorite.dto.spec.ts
@@ -0,0 +1,21 @@
+import { deleteFileFavoriteSchema, fileFavoriteSchema } from './file-favorite.dto.js'
+
+describe('file favorite schemas', () => {
+ it('accepts a large temporary inode when adding a favorite', () => {
+ const fileId = -(2 ** 54)
+
+ expect(fileFavoriteSchema.parse({ fileId })).toEqual({ fileId })
+ })
+
+ it.each([0, 2 ** 53, -1.5, Infinity, -Infinity])('rejects an invalid file reference: %s', (fileId) => {
+ expect(fileFavoriteSchema.safeParse({ fileId }).success).toBe(false)
+ })
+
+ it.each([1, 42, 2 ** 53, 2 ** 54])('accepts the positive SQL identifier %s for favorite deletion', (fileId) => {
+ expect(deleteFileFavoriteSchema.parse({ fileId })).toEqual({ fileId })
+ })
+
+ it.each([0, -(2 ** 54), 1.5, NaN, Infinity, -Infinity])('rejects an invalid identifier %s for favorite deletion', (fileId) => {
+ expect(deleteFileFavoriteSchema.safeParse({ fileId }).success).toBe(false)
+ })
+})
diff --git a/backend/src/applications/files/dto/file-favorite.dto.ts b/backend/src/applications/files/dto/file-favorite.dto.ts
index dbd8fdba..0852767d 100644
--- a/backend/src/applications/files/dto/file-favorite.dto.ts
+++ b/backend/src/applications/files/dto/file-favorite.dto.ts
@@ -1,14 +1,15 @@
-import { IsInt, IsNotEmpty, Min } from 'class-validator'
-
-export class FileFavoriteDto {
- @IsNotEmpty()
- @IsInt()
- fileId: number
-}
-
-export class DeleteFileFavoriteDto {
- @IsNotEmpty()
- @IsInt()
- @Min(1)
- fileId: number
-}
+import { z } from 'zod'
+import { integerNumberSchema } from '../../../configuration/config.schema.js'
+import { fileReferenceIdSchema } from '../files.schema.js'
+
+export const fileFavoriteSchema = z.object({
+ fileId: fileReferenceIdSchema
+})
+
+export type FileFavoriteDto = z.infer<typeof fileFavoriteSchema>
+
+export const deleteFileFavoriteSchema = z.object({
+ fileId: integerNumberSchema.min(1)
+})
+
+export type DeleteFileFavoriteDto = z.infer<typeof deleteFileFavoriteSchema>
diff --git a/backend/src/applications/files/dto/file-operations.dto.spec.ts b/backend/src/applications/files/dto/file-operations.dto.spec.ts
new file mode 100644
index 00000000..f0a9746a
--- /dev/null
+++ b/backend/src/applications/files/dto/file-operations.dto.spec.ts
@@ -0,0 +1,14 @@
+import { downloadFileSchema } from './file-operations.dto.js'
+
+describe('downloadFileSchema', () => {
+ it.each(['https://files.example.test/archive.zip', 'http://203.0.113.1/archive.zip'])('accepts an HTTP(S) URL: %s', (url) => {
+ expect(downloadFileSchema.parse({ url })).toEqual({ url })
+ })
+
+ it.each(['ftp://files.example.test/archive.zip', 'https://files_server.example.test/archive.zip', 'https://files.example.test./archive.zip'])(
+ 'rejects a URL outside the former IsUrl contract: %s',
+ (url) => {
+ expect(downloadFileSchema.safeParse({ url }).success).toBe(false)
+ }
+ )
+})
diff --git a/backend/src/applications/files/dto/file-operations.dto.ts b/backend/src/applications/files/dto/file-operations.dto.ts
index 8ba8f036..69c8e8d5 100644
--- a/backend/src/applications/files/dto/file-operations.dto.ts
+++ b/backend/src/applications/files/dto/file-operations.dto.ts
@@ -1,100 +1,53 @@
-import { Transform } from 'class-transformer'
-import {
- ArrayMinSize,
- IsArray,
- IsBoolean,
- IsDefined,
- IsIn,
- IsInt,
- IsNotEmpty,
- IsOptional,
- IsString,
- IsUrl,
- Max,
- MaxLength,
- Min
-} from 'class-validator'
-import { RejectIfMatch } from '../../../common/decorators.js'
+import { z } from 'zod'
import { regExpInvalidFileName } from '../../../common/shared.js'
+import { httpUrlSchema } from '../../../configuration/config.schema.js'
import { TAR_EXTENSION, ZIP_EXTENSION } from '../constants/compress.js'
import { SEARCH_FILES_DEFAULT_LIMIT, SEARCH_FILES_MAX_LIMIT, SEARCH_FILES_MAX_QUERY_LENGTH, SEARCH_FILES_MIN_LIMIT } from '../constants/search.js'
-export class CopyMoveFileDto {
- @IsNotEmpty()
- @IsString()
- dstDirectory: string
+const validFileNameSchema = z.string().refine((value) => !regExpInvalidFileName.test(value), { message: 'Forbidden characters' })
- @IsOptional()
- @IsString()
- @RejectIfMatch(regExpInvalidFileName, { message: 'Forbidden characters' })
- // Renaming scenario
- dstName?: string
-
- @IsOptional()
- @IsBoolean()
- overwrite? = false
-}
+const compressFileEntrySchema = z
+ .unknown()
+ .refine((value) => value !== '' && value !== null && value !== undefined)
+ .transform((value) => value as { name: string; rootAlias: string; path?: string })
-export class DownloadFileDto {
- @IsNotEmpty()
- @IsUrl({
- // only allow HTTP(S)
- protocols: ['http', 'https'],
- require_protocol: true,
- require_valid_protocol: true,
- // reject exotic schemes and underscores
- allow_underscores: false,
- allow_trailing_dot: false
- })
- url: string
-}
+export const copyMoveFileSchema = z.object({
+ dstDirectory: z.string().min(1),
+ // Renaming scenario
+ dstName: validFileNameSchema.nullish(),
+ overwrite: z.boolean().nullish().default(false)
+})
-export class MakeFileDto {
- @IsNotEmpty()
- @IsString()
- @IsIn(['file', 'directory'])
- type: 'file' | 'directory'
-}
+export type CopyMoveFileDto = z.input<typeof copyMoveFileSchema>
+export type ValidatedCopyMoveFileDto = z.output<typeof copyMoveFileSchema>
-export class CompressFileDto {
- @IsOptional()
- @IsString()
- @RejectIfMatch(regExpInvalidFileName, { message: 'Forbidden characters' })
- name?: string // only used on frontend
+export const downloadFileSchema = z.object({
+ url: httpUrlSchema
+})
- @IsDefined()
- @IsBoolean()
- compressInDirectory: boolean
+export type DownloadFileDto = z.infer<typeof downloadFileSchema>
- @IsDefined()
- @IsBoolean()
- compression: boolean
+export const makeFileSchema = z.object({
+ type: z.enum(['file', 'directory'])
+})
- @IsNotEmpty({ each: true })
- @IsArray()
- @ArrayMinSize(1)
- files: { name: string; rootAlias: string; path?: string }[]
+export type MakeFileDto = z.infer<typeof makeFileSchema>
- @IsNotEmpty()
- @IsString()
- @IsIn([TAR_EXTENSION, ZIP_EXTENSION])
- extension: typeof TAR_EXTENSION | typeof ZIP_EXTENSION
-}
+export const compressFileSchema = z.object({
+ name: validFileNameSchema.nullish(),
+ compressInDirectory: z.boolean(),
+ compression: z.boolean(),
+ files: z.array(compressFileEntrySchema).min(1),
+ extension: z.enum([TAR_EXTENSION, ZIP_EXTENSION])
+})
-export class SearchFilesDto {
- @IsNotEmpty()
- @IsString()
- @MaxLength(SEARCH_FILES_MAX_QUERY_LENGTH)
- @Transform(({ value }) => (value ? value.trim() : null))
- content: string
+export type CompressFileDto = z.infer<typeof compressFileSchema>
- @IsOptional()
- @IsBoolean()
- fullText?: boolean = false
+export const searchFilesSchema = z.object({
+ content: z.string().trim().min(1).max(SEARCH_FILES_MAX_QUERY_LENGTH),
+ fullText: z.boolean().nullish().default(false),
+ limit: z.number().int().min(SEARCH_FILES_MIN_LIMIT).max(SEARCH_FILES_MAX_LIMIT).nullish().default(SEARCH_FILES_DEFAULT_LIMIT)
+})
- @IsOptional()
- @IsInt()
- @Min(SEARCH_FILES_MIN_LIMIT)
- @Max(SEARCH_FILES_MAX_LIMIT)
- limit?: number = SEARCH_FILES_DEFAULT_LIMIT
-}
+export type SearchFilesDto = z.input<typeof searchFilesSchema>
+export type ValidatedSearchFilesDto = z.output<typeof searchFilesSchema>
diff --git a/backend/src/applications/files/dto/file-tasks.dto.ts b/backend/src/applications/files/dto/file-tasks.dto.ts
index 4fa8e157..33680070 100644
--- a/backend/src/applications/files/dto/file-tasks.dto.ts
+++ b/backend/src/applications/files/dto/file-tasks.dto.ts
@@ -1,14 +1,13 @@
-import { ArrayNotEmpty, IsArray, IsString } from 'class-validator'
-
-export class FileTasksDeleteDto {
- @ArrayNotEmpty()
- @IsArray()
- @IsString({ each: true })
- taskIds: string[]
-}
-
-export class FileTasksPollDto {
- @IsArray()
- @IsString({ each: true })
- trackedIds: string[]
-}
+import { z } from 'zod'
+
+export const fileTasksDeleteSchema = z.object({
+ taskIds: z.array(z.string()).min(1)
+})
+
+export type FileTasksDeleteDto = z.infer<typeof fileTasksDeleteSchema>
+
+export const fileTasksPollSchema = z.object({
+ trackedIds: z.array(z.string())
+})
+
+export type FileTasksPollDto = z.infer<typeof fileTasksPollSchema>
diff --git a/backend/src/applications/files/editors/collabora-online/collabora-online-manager.service.spec.ts b/backend/src/applications/files/editors/collabora-online/collabora-online-manager.service.spec.ts
index defbe870..228a7b88 100644
--- a/backend/src/applications/files/editors/collabora-online/collabora-online-manager.service.spec.ts
+++ b/backend/src/applications/files/editors/collabora-online/collabora-online-manager.service.spec.ts
@@ -13,6 +13,7 @@ import { ACTION } from '../../../../common/constants.js'
import { DEPTH, LOCK_SCOPE } from '../../../webdav/constants/webdav.js'
import { FILE_MODE } from '../../constants/operations.js'
import { FileEvent } from '../../events/file-events.js'
+import type { FileLock } from '../../interfaces/file-lock.interface.js'
import { FileLockProps } from '../../interfaces/file-props.interface.js'
import { FileError } from '../../models/file-error.js'
import { LockConflict } from '../../models/file-lock-error.js'
@@ -39,7 +40,7 @@ describe(CollaboraOnlineManager.name, () => {
language: 'en',
role: 1,
applications: []
- } as UserModel
+ } as unknown as UserModel
const mockSpace = {
realPath: '/path/to/document.docx',
@@ -156,7 +157,10 @@ describe(CollaboraOnlineManager.name, () => {
}
vi.spyOn(filesLockManager, 'checkConflicts').mockRejectedValue(new LockConflict(mockLock as any, 'conflict'))
- vi.spyOn(filesLockManager, 'convertLockToFileLockProps').mockReturnValue(mockFileLockProps)
+ vi.spyOn<{ convertLockToFileLockProps: (lock: FileLock) => FileLockProps }, 'convertLockToFileLockProps'>(
+ filesLockManager,
+ 'convertLockToFileLockProps'
+ ).mockReturnValue(mockFileLockProps)
const result = await service.getSettings(mockUser, spaceWithPermissions)
@@ -541,7 +545,7 @@ describe(CollaboraOnlineManager.name, () => {
const existingLock = { key: 'lock-key', options: { lockToken: 'lock-token-to-remove' } }
vi.spyOn(filesLockManager, 'isLockedWithToken').mockResolvedValue(existingLock as any)
- vi.spyOn(filesLockManager, 'removeLock').mockResolvedValue(undefined)
+ vi.spyOn(filesLockManager, 'removeLock').mockResolvedValue(undefined as never)
await service.manageLock(mockRequest, mockReply)
diff --git a/backend/src/applications/files/editors/collabora-online/collabora-online-manager.service.ts b/backend/src/applications/files/editors/collabora-online/collabora-online-manager.service.ts
index a2ee4d85..7a09ffeb 100644
--- a/backend/src/applications/files/editors/collabora-online/collabora-online-manager.service.ts
+++ b/backend/src/applications/files/editors/collabora-online/collabora-online-manager.service.ts
@@ -5,6 +5,7 @@ import fs from 'node:fs/promises'
import os from 'node:os'
import path from 'node:path'
import { TOKEN_TYPE } from '../../../../authentication/interfaces/token.interface.js'
+import { toErrorMessage } from '../../../../common/errors.js'
import { convertHumanTimeToSeconds } from '../../../../common/functions.js'
import { configuration } from '../../../../configuration/config.environment.js'
import { ContextManager } from '../../../../infrastructure/context/services/context-manager.service.js'
@@ -81,7 +82,7 @@ export class CollaboraOnlineManager {
hasLock = this.filesLockManager.convertLockToFileLockProps(e.lock)
mode = FILE_MODE.VIEW
} else {
- this.logger.error({ tag: this.getSettings.name, msg: `${e}` })
+ this.logger.error({ tag: this.getSettings.name, msg: toErrorMessage(e) })
throw new HttpException('Unable to check file lock', HttpStatus.INTERNAL_SERVER_ERROR)
}
}
@@ -132,7 +133,7 @@ export class CollaboraOnlineManager {
if (e instanceof FileError) {
throw new HttpException(e.message, e.httpCode)
}
- throw new Error(`unable to save document : ${e.message}`)
+ throw new Error(`unable to save document : ${toErrorMessage(e)}`)
}
// try to verify the downloaded size
if (contentLength !== undefined && contentLength !== 0) {
@@ -152,14 +153,14 @@ export class CollaboraOnlineManager {
const fStats = await fs.stat(req.space.realPath)
return { LastModifiedTime: fStats.mtime.toISOString() } satisfies CollaboraSaveDocumentDto
} catch (e) {
- this.logger.error({ tag: this.saveDocument.name, msg: `unable to save document: ${e}` })
+ this.logger.error({ tag: this.saveDocument.name, msg: `unable to save document: ${toErrorMessage(e)}` })
throw new HttpException('Unable to save document', HttpStatus.INTERNAL_SERVER_ERROR)
}
} finally {
try {
await removeFiles(tmpFilePath)
} catch (e) {
- this.logger.error({ tag: this.saveDocument.name, msg: `failed to remove temporary document ${tmpFilePath}: ${e.message}` })
+ this.logger.error({ tag: this.saveDocument.name, msg: `failed to remove temporary document ${tmpFilePath}: ${toErrorMessage(e)}` })
}
}
}
@@ -187,7 +188,7 @@ export class CollaboraOnlineManager {
this.expiration
)
if (!ok) {
- this.lockConflict(res, fileLock.options.lockToken)
+ this.lockConflict(res, fileLock.options!.lockToken)
return
}
break
@@ -205,7 +206,7 @@ export class CollaboraOnlineManager {
case COLLABORA_LOCK_ACTION.GET_LOCK: {
const lock = await this.filesLockManager.getLocksByPath(req.space.dbFile)
if (lock.length) {
- res.header(COLLABORA_HEADERS.LockToken, lock[0].options.lockToken)
+ res.header(COLLABORA_HEADERS.LockToken, lock[0].options!.lockToken)
}
break
}
@@ -275,8 +276,8 @@ export class CollaboraOnlineManager {
return lockToken
}
- private lockConflict(res: FastifyReply, currentLockToken: string) {
- res.header(COLLABORA_HEADERS.LockToken, currentLockToken)
+ private lockConflict(res: FastifyReply, currentLockToken?: string | null) {
+ res.header(COLLABORA_HEADERS.LockToken, currentLockToken as string)
throw new HttpException('The file is locked', HttpStatus.CONFLICT)
}
diff --git a/backend/src/applications/files/editors/collabora-online/collabora-online.config.ts b/backend/src/applications/files/editors/collabora-online/collabora-online.config.ts
index 0eee099d..39ef21c7 100644
--- a/backend/src/applications/files/editors/collabora-online/collabora-online.config.ts
+++ b/backend/src/applications/files/editors/collabora-online/collabora-online.config.ts
@@ -1,12 +1,7 @@
-import { Transform } from 'class-transformer'
-import { IsBoolean, IsOptional, IsUrl } from 'class-validator'
+import { z } from 'zod'
+import { optionalHttpBaseUrlSchema } from '../../../../configuration/config.schema.js'
-export class CollaboraOnlineConfig {
- @IsBoolean()
- enabled = false
-
- @Transform(({ value }) => (typeof value === 'string' ? value.trim() || null : value))
- @IsOptional()
- @IsUrl({ protocols: ['http', 'https'], require_protocol: true, require_tld: false, disallow_auth: true })
- externalServer: string = null
-}
+export const CollaboraOnlineConfigSchema = z.looseObject({
+ enabled: z.boolean().default(false),
+ externalServer: optionalHttpBaseUrlSchema.default(null)
+})
diff --git a/backend/src/applications/files/editors/drawio/drawio-manager.service.spec.ts b/backend/src/applications/files/editors/drawio/drawio-manager.service.spec.ts
index 48513deb..a3732b81 100644
--- a/backend/src/applications/files/editors/drawio/drawio-manager.service.spec.ts
+++ b/backend/src/applications/files/editors/drawio/drawio-manager.service.spec.ts
@@ -11,7 +11,7 @@ vi.mock('../../utils/files.js')
describe(DrawioManager.name, () => {
let service: DrawioManager
let contextManager: ContextManager
- let previousExternalServer: string
+ let previousExternalServer: string | null
const mockSpace = {
realPath: '/path/to/diagram.drawio'
diff --git a/backend/src/applications/files/editors/drawio/drawio.config.ts b/backend/src/applications/files/editors/drawio/drawio.config.ts
index 562e7dbf..344e1b34 100644
--- a/backend/src/applications/files/editors/drawio/drawio.config.ts
+++ b/backend/src/applications/files/editors/drawio/drawio.config.ts
@@ -1,12 +1,7 @@
-import { Transform } from 'class-transformer'
-import { IsBoolean, IsOptional, IsUrl } from 'class-validator'
+import { z } from 'zod'
+import { optionalHttpBaseUrlSchema } from '../../../../configuration/config.schema.js'
-export class DrawioConfig {
- @IsBoolean()
- enabled = false
-
- @Transform(({ value }) => (typeof value === 'string' ? value.trim() || null : value))
- @IsOptional()
- @IsUrl({ protocols: ['http', 'https'], require_protocol: true, require_tld: false, disallow_auth: true })
- externalServer: string = null
-}
+export const DrawioConfigSchema = z.looseObject({
+ enabled: z.boolean().default(false),
+ externalServer: optionalHttpBaseUrlSchema.default(null)
+})
diff --git a/backend/src/applications/files/editors/only-office/only-office-manager.service.spec.ts b/backend/src/applications/files/editors/only-office/only-office-manager.service.spec.ts
index d00cddcf..0a347b5a 100644
--- a/backend/src/applications/files/editors/only-office/only-office-manager.service.spec.ts
+++ b/backend/src/applications/files/editors/only-office/only-office-manager.service.spec.ts
@@ -34,7 +34,7 @@ describe(OnlyOfficeManager.name, () => {
let jwtService: Mocked<JwtService>
let filesLockManager: Mocked<FilesLockManager>
let onlyOfficeEnabled: boolean
- let onlyOfficeExternalServer: string
+ let onlyOfficeExternalServer: string | null
const mockUser = {
id: 1,
@@ -130,6 +130,13 @@ describe(OnlyOfficeManager.name, () => {
vi.clearAllMocks()
})
+ it('builds the conversion endpoint without a double slash', () => {
+ configuration.applications.files.editors.onlyoffice.externalServer = 'https://office.example.test/subpath/'
+ const configuredService = new OnlyOfficeManager(httpService, {} as ContextManager, cache, jwtService, filesLockManager)
+
+ expect((configuredService as any).convertUrl).toBe('https://office.example.test/subpath/ConvertService.ashx')
+ })
+
describe('getSettings', () => {
beforeEach(() => {
vi.mocked(filesUtils.isPathExists).mockResolvedValue(true)
@@ -137,7 +144,7 @@ describe(OnlyOfficeManager.name, () => {
filesLockManager.checkConflicts.mockResolvedValue(undefined)
jwtService.signAsync.mockResolvedValue('mock-token')
cache.get.mockResolvedValue(null)
- cache.set.mockResolvedValue(undefined)
+ cache.set.mockResolvedValue(undefined as never)
vi.mocked(filesUtils.genEtag).mockReturnValue('mock-etag')
})
@@ -146,8 +153,8 @@ describe(OnlyOfficeManager.name, () => {
expect(result).toBeDefined()
expect(result.config.documentType).toBe('word')
- expect(result.config.editorConfig.mode).toBe(FILE_MODE.EDIT)
- expect(result.config.document.permissions.edit).toBe(true)
+ expect(result.config.editorConfig!.mode).toBe(FILE_MODE.EDIT)
+ expect(result.config.document!.permissions!.edit).toBe(true)
expect(result.hasLock).toBe(false)
expect(jwtService.signAsync).toHaveBeenCalledWith(
expect.objectContaining({
@@ -198,8 +205,8 @@ describe(OnlyOfficeManager.name, () => {
const result = await service.getSettings(mockUser, mockSpaceEnv, mockRequest)
- expect(result.config.editorConfig.mode).toBe(FILE_MODE.VIEW)
- expect(result.config.document.permissions.edit).toBe(false)
+ expect(result.config.editorConfig!.mode).toBe(FILE_MODE.VIEW)
+ expect(result.config.document!.permissions!.edit).toBe(false)
expect(result.hasLock).toBeDefined()
})
@@ -212,8 +219,8 @@ describe(OnlyOfficeManager.name, () => {
const result = await service.getSettings(mockUser, viewOnlySpaceEnv, mockRequest)
- expect(result.config.editorConfig.mode).toBe(FILE_MODE.VIEW)
- expect(result.config.document.permissions.edit).toBe(false)
+ expect(result.config.editorConfig!.mode).toBe(FILE_MODE.VIEW)
+ expect(result.config.document!.permissions!.edit).toBe(false)
})
it('should set mode to VIEW when document is in trash repository', async () => {
@@ -224,8 +231,8 @@ describe(OnlyOfficeManager.name, () => {
const result = await service.getSettings(mockUser, trashSpaceEnv, mockRequest)
- expect(result.config.editorConfig.mode).toBe(FILE_MODE.VIEW)
- expect(result.config.document.permissions.edit).toBe(false)
+ expect(result.config.editorConfig!.mode).toBe(FILE_MODE.VIEW)
+ expect(result.config.document!.permissions!.edit).toBe(false)
expect(filesLockManager.checkConflicts).not.toHaveBeenCalled()
})
@@ -246,7 +253,7 @@ describe(OnlyOfficeManager.name, () => {
const result = await service.getSettings(mockUser, mockSpaceEnv, mockRequest)
- expect(result.config.document.key).toBe('cached-doc-key')
+ expect(result.config.document!.key).toBe('cached-doc-key')
expect(cache.set).not.toHaveBeenCalled()
})
})
@@ -256,7 +263,7 @@ describe(OnlyOfficeManager.name, () => {
const mockDocumentUrl = 'http://localhost:3000/onlyoffice/document.docx?md5=abc123&expires=1739400549&shardkey=-33120641&filename=document.docx'
beforeEach(() => {
- filesLockManager.removeLock.mockResolvedValue(undefined)
+ filesLockManager.removeLock.mockResolvedValue(undefined as never)
filesLockManager.getLocksByPath.mockResolvedValue([])
filesLockManager.isPathLocked.mockResolvedValue(false)
cache.del.mockResolvedValue(true)
@@ -467,7 +474,7 @@ describe(OnlyOfficeManager.name, () => {
actions: [{ type: 1, userid: '1' }],
users: ['1']
})
- filesLockManager.create.mockResolvedValue([false, null])
+ filesLockManager.create.mockResolvedValue([false, null as never])
const result = await service.callBack(mockUser, mockSpaceEnv, mockToken)
diff --git a/backend/src/applications/files/editors/only-office/only-office-manager.service.ts b/backend/src/applications/files/editors/only-office/only-office-manager.service.ts
index 85a1199a..d654d4b9 100644
--- a/backend/src/applications/files/editors/only-office/only-office-manager.service.ts
+++ b/backend/src/applications/files/editors/only-office/only-office-manager.service.ts
@@ -1,13 +1,14 @@
import { HttpService } from '@nestjs/axios'
import { HttpException, HttpStatus, Injectable, Logger } from '@nestjs/common'
import { JwtService } from '@nestjs/jwt'
-import { AxiosResponse } from 'axios'
+import { AxiosResponse, isAxiosError } from 'axios'
import https from 'https'
import crypto from 'node:crypto'
import os from 'node:os'
import path from 'node:path'
-import { JwtIdentityPayload } from '../../../../authentication/interfaces/jwt-payload.interface.js'
+import type { JwtIdentityPayload } from '../../../../authentication/interfaces/jwt-payload.interface.js'
import { TOKEN_TYPE } from '../../../../authentication/interfaces/token.interface.js'
+import { toErrorMessage } from '../../../../common/errors.js'
import { convertHumanTimeToSeconds } from '../../../../common/functions.js'
import { encodeUrl } from '../../../../common/shared.js'
import { configuration } from '../../../../configuration/config.environment.js'
@@ -65,7 +66,9 @@ export class OnlyOfficeManager {
private readonly officeAppLock = configuration.applications.files.editors.onlyoffice.enabled ? ONLY_OFFICE_APP_LOCK : EURO_OFFICE_APP_LOCK
private readonly externalOnlyOfficeServer = this.officeConfig.externalServer || null
private readonly rejectUnauthorized: boolean = this.officeConfig.verifySSL
- private readonly convertUrl = this.externalOnlyOfficeServer ? `${this.externalOnlyOfficeServer}/ConvertService.ashx` : null
+ private readonly convertUrl: string | null = this.externalOnlyOfficeServer
+ ? `${this.externalOnlyOfficeServer.replace(/\/+$/, '')}/ConvertService.ashx`
+ : null
private readonly expiration = convertHumanTimeToSeconds(configuration.auth.token.refresh.expiration)
private readonly mobileRegex: RegExp = /android|webos|iphone|ipad|ipod|blackberry|windows phone|opera mini|iemobile|mobile/i
@@ -103,17 +106,18 @@ export class OnlyOfficeManager {
hasLock = this.filesLockManager.convertLockToFileLockProps(e.lock)
mode = FILE_MODE.VIEW
} else {
- this.logger.error({ tag: this.getSettings.name, msg: `${e}` })
+ this.logger.error({ tag: this.getSettings.name, msg: toErrorMessage(e) })
throw new HttpException('Unable to check file lock', HttpStatus.INTERNAL_SERVER_ERROR)
}
}
}
- const isMobile: boolean = this.mobileRegex.test(req.headers['user-agent'])
+ const userAgent = req.headers['user-agent']
+ const isMobile = this.mobileRegex.test(typeof userAgent === 'string' ? userAgent : '')
const authToken: string = await this.genAuthToken(user)
const fileUrl = this.buildUrl(API_ONLY_OFFICE_DOCUMENT, encodeUrl(space.url), authToken)
const callBackUrl = this.buildUrl(API_ONLY_OFFICE_CALLBACK, encodeUrl(space.url), authToken)
const config: OnlyOfficeReqDto = await this.genConfiguration(user, space, mode, fileUrl, fileExtension, callBackUrl, isMobile, hasLock)
- config.config.editorConfig.customization.uiTheme = `theme-${theme ?? USER_THEME.LIGHT}`
+ config.config.editorConfig!.customization!.uiTheme = `theme-${theme ?? USER_THEME.LIGHT}`
config.config.token = await this.genPayloadToken(config.config)
return config
}
@@ -134,14 +138,14 @@ export class OnlyOfficeManager {
this.logger.debug({ tag: this.callBack.name, msg: `document was edited but closed with no changes : ${space.url}` })
} else {
this.logger.debug({ tag: this.callBack.name, msg: `document was edited and closed but not saved (let's do it) : ${space.url}` })
- await this.saveDocument(user, space, callBackData.url)
+ await this.saveDocument(user, space, callBackData.url!)
}
await this.removeFileLock(user.id, space)
await this.removeDocumentKey(space)
break
case 3:
this.logger.error({ tag: this.callBack.name, msg: `document cannot be saved, an error has occurred (try to save it) : ${space.url}` })
- await this.saveDocument(user, space, callBackData.url)
+ await this.saveDocument(user, space, callBackData.url!)
break
case 4:
// No active users on the document
@@ -151,18 +155,19 @@ export class OnlyOfficeManager {
break
case 6:
this.logger.debug({ tag: this.callBack.name, msg: `document is edited but save was requested : ${space.url}` })
- await this.saveDocument(user, space, callBackData.url)
+ await this.saveDocument(user, space, callBackData.url!)
break
case 7:
this.logger.error({ tag: this.callBack.name, msg: `document cannot be force saved, an error has occurred (try to save it) : ${space.url}` })
- await this.saveDocument(user, space, callBackData.url)
+ await this.saveDocument(user, space, callBackData.url!)
break
default:
this.logger.error({ tag: this.callBack.name, msg: 'unhandled case' })
}
} catch (e) {
- this.logger.error({ tag: this.callBack.name, msg: `${e.message} : ${space.url}` })
- return { error: e.message }
+ const errorMessage = toErrorMessage(e)
+ this.logger.error({ tag: this.callBack.name, msg: `${errorMessage} : ${space.url}` })
+ return { error: errorMessage }
}
return { error: 0 }
}
@@ -265,7 +270,7 @@ export class OnlyOfficeManager {
}
private async checkFileLock(user: UserModel, space: SpaceEnv, callBackData: OnlyOfficeCallBack) {
- for (const action of callBackData.actions) {
+ for (const action of callBackData.actions!) {
if (action.type === 0) {
// Disconnect
// Remove the lock if no other users are active on the document
@@ -347,7 +352,7 @@ export class OnlyOfficeManager {
let finalParsedDownloadUrl = callbackDownloadUrl
if (localExtension !== remoteExtension && !ONLY_OFFICE_CONVERT_EXTENSIONS.ALLOW_AUTO.has(localExtension)) {
if (ONLY_OFFICE_CONVERT_EXTENSIONS.FROM.has(remoteExtension) && ONLY_OFFICE_CONVERT_EXTENSIONS.TO.has(localExtension)) {
- finalDownloadUrl = await this.convertDocument(urlParams.get('shardkey'), url, remoteExtension, localExtension, space.url)
+ finalDownloadUrl = (await this.convertDocument(urlParams.get('shardkey')!, url, remoteExtension, localExtension, space.url))!
finalParsedDownloadUrl = this.parseDocumentServerDownloadUrl(finalDownloadUrl)
} else {
throw new Error(`document cannot be converted from ${remoteExtension} -> ${localExtension} : ${space.url}`)
@@ -376,9 +381,9 @@ export class OnlyOfficeManager {
downloadStream?.destroy?.()
this.logger.error({
tag: this.saveDocument.name,
- msg: `failed to download document from ${finalParsedDownloadUrl.origin}${finalParsedDownloadUrl.pathname} : ${space.url} - ${e.message}`
+ msg: `failed to download document from ${finalParsedDownloadUrl.origin}${finalParsedDownloadUrl.pathname} : ${space.url} - ${toErrorMessage(e)}`
})
- throw new Error(`unable to download document : ${e.message}`)
+ throw new Error(`unable to download document : ${toErrorMessage(e)}`)
}
// try to verify the downloaded size
@@ -396,13 +401,13 @@ export class OnlyOfficeManager {
// emit file event
FileEvent.emit('event', { user: user, space: space, action: ACTION.UPDATE, rPath: space.realPath, source: 'editor' })
} catch (e) {
- throw new Error(`unable to save document : ${e.message}`)
+ throw new Error(`unable to save document : ${toErrorMessage(e)}`)
}
} finally {
try {
await removeFiles(tmpFilePath)
} catch (e) {
- this.logger.error({ tag: this.saveDocument.name, msg: `failed to remove temporary document ${tmpFilePath} : ${e.message}` })
+ this.logger.error({ tag: this.saveDocument.name, msg: `failed to remove temporary document ${tmpFilePath} : ${toErrorMessage(e)}` })
}
}
}
@@ -440,7 +445,7 @@ export class OnlyOfficeManager {
return parsedUrl
}
- private async convertDocument(id: string, url: string, fileType: string, outputType: string, spaceUrl: string): Promise<string> {
+ private async convertDocument(id: string, url: string, fileType: string, outputType: string, spaceUrl: string): Promise<string | undefined> {
const key: string = `${id}-${crypto.randomBytes(20).toString('hex')}`.slice(0, 20).replace('-', '_')
const payload: OnlyOfficeConvertForm = {
key: key,
@@ -454,13 +459,14 @@ export class OnlyOfficeManager {
try {
const res: AxiosResponse = await this.http.axiosRef({
method: HTTP_METHOD.POST,
- url: this.convertUrl,
+ url: this.convertUrl as string,
data: payload,
httpsAgent: new https.Agent({ rejectUnauthorized: this.rejectUnauthorized })
})
result = res.data
} catch (e) {
- throw new Error(`convert failed with status : ${e.response.status}`)
+ const reason = isAxiosError(e) && e.response ? `status : ${e.response.status}` : `reason : ${toErrorMessage(e)}`
+ throw new Error(`convert failed with ${reason}`)
}
if (result.error) {
throw new Error(`convert failed with reason : ${ONLY_OFFICE_CONVERT_ERROR.get(result.error)}`)
diff --git a/backend/src/applications/files/editors/only-office/only-office.config.ts b/backend/src/applications/files/editors/only-office/only-office.config.ts
index c9c0c409..d45d012e 100644
--- a/backend/src/applications/files/editors/only-office/only-office.config.ts
+++ b/backend/src/applications/files/editors/only-office/only-office.config.ts
@@ -1,20 +1,21 @@
-import { Transform } from 'class-transformer'
-import { IsBoolean, IsNotEmpty, IsOptional, IsString, IsUrl, ValidateIf } from 'class-validator'
+import { z } from 'zod'
+import { nonEmptyStringSchema, optionalHttpBaseUrlSchema } from '../../../../configuration/config.schema.js'
-export class OnlyOfficeConfig {
- @IsBoolean()
- enabled = false
-
- @Transform(({ value }) => (typeof value === 'string' ? value.trim() || null : value))
- @IsOptional()
- @IsUrl({ protocols: ['http', 'https'], require_protocol: true, require_tld: false, disallow_auth: true })
- externalServer: string = null
-
- @ValidateIf((o: OnlyOfficeConfig) => o.enabled)
- @IsString()
- @IsNotEmpty()
- secret: string
-
- @IsBoolean()
- verifySSL: boolean = false
-}
+export const OnlyOfficeConfigSchema = z.discriminatedUnion('enabled', [
+ z.looseObject({
+ enabled: z.literal(false).default(false),
+ externalServer: optionalHttpBaseUrlSchema.default(null),
+ // Preserve the public type without validating an inactive editor secret.
+ secret: z
+ .custom<string>()
+ .optional()
+ .transform((value) => value as string),
+ verifySSL: z.boolean().default(false)
+ }),
+ z.looseObject({
+ enabled: z.literal(true),
+ externalServer: optionalHttpBaseUrlSchema.default(null),
+ secret: nonEmptyStringSchema,
+ verifySSL: z.boolean().default(false)
+ })
+])
diff --git a/backend/src/applications/files/editors/only-office/only-office.controller.ts b/backend/src/applications/files/editors/only-office/only-office.controller.ts
index ad6cc7f9..3601bc4d 100644
--- a/backend/src/applications/files/editors/only-office/only-office.controller.ts
+++ b/backend/src/applications/files/editors/only-office/only-office.controller.ts
@@ -1,18 +1,4 @@
-import {
- Body,
- Controller,
- Get,
- HttpCode,
- HttpStatus,
- ParseEnumPipe,
- Post,
- Query,
- Request,
- Res,
- StreamableFile,
- UseGuards,
- UseInterceptors
-} from '@nestjs/common'
+import { Body, Controller, Get, HttpCode, HttpStatus, Post, Query, Request, Res, StreamableFile, UseGuards, UseInterceptors } from '@nestjs/common'
import { type FastifyReply } from 'fastify'
import { ContextInterceptor } from '../../../../infrastructure/context/interceptors/context.interceptor.js'
import { SPACE_OPERATION } from '../../../spaces/constants/spaces.js'
@@ -21,7 +7,6 @@ import { GetSpace } from '../../../spaces/decorators/space.decorator.js'
import { SpaceGuard } from '../../../spaces/guards/space.guard.js'
import { type FastifySpaceRequest } from '../../../spaces/interfaces/space-request.interface.js'
import { SpaceEnv } from '../../../spaces/models/space-env.model.js'
-import { USER_THEME } from '../../../users/constants/user-preferences.js'
import { GetUser } from '../../../users/decorators/user.decorator.js'
import type { UserTheme } from '../../../users/interfaces/user-preferences.interface.js'
import { UserModel } from '../../../users/models/user.model.js'
@@ -30,6 +15,7 @@ import { OnlyOfficeEnvironment } from './only-office-environment.decorator.js'
import { OnlyOfficeManager } from './only-office-manager.service.js'
import type { OnlyOfficeReqDto } from './only-office.dtos.js'
import { API_ONLY_OFFICE, ONLY_OFFICE_ROUTE } from './only-office.routes.js'
+import { themeQueryParameterSchema } from './only-office.schema.js'
@Controller(API_ONLY_OFFICE)
export class OnlyOfficeController {
@@ -43,7 +29,7 @@ export class OnlyOfficeController {
@UseInterceptors(ContextInterceptor)
onlyOfficeSettings(
@Request() req: FastifySpaceRequest,
- @Query('theme', new ParseEnumPipe({ DARK: USER_THEME.DARK, LIGHT: USER_THEME.LIGHT }, { optional: true })) theme?: UserTheme
+ @Query('theme', { schema: themeQueryParameterSchema }) theme?: UserTheme
): Promise<OnlyOfficeReqDto> {
return this.filesOnlyOfficeManager.getSettings(req.user, req.space, req, theme)
}
diff --git a/backend/src/applications/files/editors/only-office/only-office.guard.spec.ts b/backend/src/applications/files/editors/only-office/only-office.guard.spec.ts
index e9eede5b..b2eec435 100644
--- a/backend/src/applications/files/editors/only-office/only-office.guard.spec.ts
+++ b/backend/src/applications/files/editors/only-office/only-office.guard.spec.ts
@@ -3,7 +3,7 @@ import { ExecutionContext } from '@nestjs/common'
import { JwtModule, JwtService } from '@nestjs/jwt'
import { Test, TestingModule } from '@nestjs/testing'
import { PinoLogger } from 'nestjs-pino'
-import { JwtPayload } from '../../../../authentication/interfaces/jwt-payload.interface.js'
+import type { JwtPayload } from '../../../../authentication/interfaces/jwt-payload.interface.js'
import { TOKEN_TYPE } from '../../../../authentication/interfaces/token.interface.js'
import { configuration } from '../../../../configuration/config.environment.js'
import { ONLY_OFFICE_TOKEN_QUERY_PARAM_NAME } from './only-office.constants.js'
diff --git a/backend/src/applications/files/editors/only-office/only-office.schema.ts b/backend/src/applications/files/editors/only-office/only-office.schema.ts
new file mode 100644
index 00000000..9fecc1ae
--- /dev/null
+++ b/backend/src/applications/files/editors/only-office/only-office.schema.ts
@@ -0,0 +1,4 @@
+import { z } from 'zod'
+import { USER_THEME } from '../../../users/constants/user-preferences.js'
+
+export const themeQueryParameterSchema = z.enum([USER_THEME.DARK, USER_THEME.LIGHT]).optional()
diff --git a/backend/src/applications/files/editors/only-office/only-office.strategy.ts b/backend/src/applications/files/editors/only-office/only-office.strategy.ts
index 3f4b5d2f..f4229d0e 100644
--- a/backend/src/applications/files/editors/only-office/only-office.strategy.ts
+++ b/backend/src/applications/files/editors/only-office/only-office.strategy.ts
@@ -2,7 +2,7 @@ import { Injectable, UnauthorizedException } from '@nestjs/common'
import { AbstractStrategy, PassportStrategy } from '@nestjs/passport'
import { PinoLogger } from 'nestjs-pino'
import { ExtractJwt, Strategy } from 'passport-jwt'
-import { JwtPayload } from '../../../../authentication/interfaces/jwt-payload.interface.js'
+import type { JwtPayload } from '../../../../authentication/interfaces/jwt-payload.interface.js'
import { TOKEN_TYPE } from '../../../../authentication/interfaces/token.interface.js'
import { configuration } from '../../../../configuration/config.environment.js'
import { UserModel } from '../../../users/models/user.model.js'
diff --git a/backend/src/applications/files/events/files-events.utils.ts b/backend/src/applications/files/events/files-events.utils.ts
index 2c6e4b88..0b6c4162 100644
--- a/backend/src/applications/files/events/files-events.utils.ts
+++ b/backend/src/applications/files/events/files-events.utils.ts
@@ -13,7 +13,7 @@ export function SpaceToFileRepository(userId: number, space: SpaceEnv): { id: nu
return { id: space.id, type: FILE_REPOSITORY.SPACE }
} else if (space.root?.file?.path && space.root.owner?.login) {
// Space root is linked to a user file
- return { id: space.root.owner.id, type: FILE_REPOSITORY.USER }
+ return { id: space.root.owner.id as number, type: FILE_REPOSITORY.USER }
} else if (space.root?.file?.space?.id) {
return { id: space.root.file.space.id, type: FILE_REPOSITORY.SPACE }
} else if (space.id) {
diff --git a/backend/src/applications/files/files-operations.controller.ts b/backend/src/applications/files/files-operations.controller.ts
index fe47e178..5782c7a1 100644
--- a/backend/src/applications/files/files-operations.controller.ts
+++ b/backend/src/applications/files/files-operations.controller.ts
@@ -8,8 +8,6 @@ import {
Lock,
Logger,
Move,
- ParseBoolPipe,
- ParseIntPipe,
Patch,
Post,
Put,
@@ -30,7 +28,17 @@ import { GetUser } from '../users/decorators/user.decorator.js'
import { UserModel } from '../users/models/user.model.js'
import { FILE_OPERATION, FORCE_AS_FILE_OWNER } from './constants/operations.js'
import { FILES_ROUTE } from './constants/routes.js'
-import { CompressFileDto, CopyMoveFileDto, DownloadFileDto, MakeFileDto } from './dto/file-operations.dto.js'
+import {
+ type CompressFileDto,
+ compressFileSchema,
+ copyMoveFileSchema,
+ type DownloadFileDto,
+ downloadFileSchema,
+ type MakeFileDto,
+ makeFileSchema,
+ type ValidatedCopyMoveFileDto
+} from './dto/file-operations.dto.js'
+import { forceAsFileOwnerQuerySchema, thumbnailSizeQuerySchema } from './files.schema.js'
import type { CopyMoveFileResponse } from './interfaces/copy-move-file.interface.js'
import { FileLockProps } from './interfaces/file-props.interface.js'
import { FileTask } from './models/file-task.js'
@@ -60,7 +68,7 @@ export class FilesOperationsController {
}
@Post(`${FILES_ROUTE.OPERATION}/${FILE_OPERATION.MAKE}/*`)
- async make(@GetUser() user: UserModel, @GetSpace() space: SpaceEnv, @Body() makeFileDto: MakeFileDto): Promise<void> {
+ async make(@GetUser() user: UserModel, @GetSpace() space: SpaceEnv, @Body({ schema: makeFileSchema }) makeFileDto: MakeFileDto): Promise<void> {
return this.filesMethods.make(user, space, makeFileDto)
}
@@ -80,12 +88,20 @@ export class FilesOperationsController {
}
@Copy(`${FILES_ROUTE.OPERATION}/*`)
- async copy(@GetUser() user: UserModel, @GetSpace() space: SpaceEnv, @Body() copyMoveFileDto: CopyMoveFileDto): Promise<CopyMoveFileResponse> {
+ async copy(
+ @GetUser() user: UserModel,
+ @GetSpace() space: SpaceEnv,
+ @Body({ schema: copyMoveFileSchema }) copyMoveFileDto: ValidatedCopyMoveFileDto
+ ): Promise<CopyMoveFileResponse> {
return this.filesMethods.copy(user, space, copyMoveFileDto)
}
@Move(`${FILES_ROUTE.OPERATION}/*`)
- async move(@GetUser() user: UserModel, @GetSpace() space: SpaceEnv, @Body() copyMoveFileDto: CopyMoveFileDto): Promise<CopyMoveFileResponse> {
+ async move(
+ @GetUser() user: UserModel,
+ @GetSpace() space: SpaceEnv,
+ @Body({ schema: copyMoveFileSchema }) copyMoveFileDto: ValidatedCopyMoveFileDto
+ ): Promise<CopyMoveFileResponse> {
return this.filesMethods.move(user, space, copyMoveFileDto)
}
@@ -95,7 +111,7 @@ export class FilesOperationsController {
}
@Get(`${FILES_ROUTE.OPERATION}/${FILE_OPERATION.THUMBNAIL}/*`)
- async genThumbnail(@GetSpace() space: SpaceEnv, @Query('size', new ParseIntPipe({ optional: true })) size = 256): Promise<StreamableFile> {
+ async genThumbnail(@GetSpace() space: SpaceEnv, @Query('size', { schema: thumbnailSizeQuerySchema }) size = 256): Promise<StreamableFile> {
if (size > 1024) size = 1024
const thumbnail = await this.filesMethods.genThumbnail(space, size)
return new StreamableFile(thumbnail.stream, { length: thumbnail.size, type: thumbnail.mimeType })
@@ -110,7 +126,7 @@ export class FilesOperationsController {
async unlock(
@GetUser() user: UserModel,
@GetSpace() space: SpaceEnv,
- @Query(FORCE_AS_FILE_OWNER, new ParseBoolPipe({ optional: true })) forceAsFileOwner?: boolean
+ @Query(FORCE_AS_FILE_OWNER, { schema: forceAsFileOwnerQuerySchema }) forceAsFileOwner?: boolean
): Promise<void> {
return this.filesMethods.unlock(user, space, forceAsFileOwner)
}
@@ -128,14 +144,18 @@ export class FilesOperationsController {
// TASKS OPERATIONS
@Post(`${FILES_ROUTE.TASK_OPERATION}/${FILE_OPERATION.DOWNLOAD}/*`)
- async downloadFromUrlAsTask(@GetUser() user: UserModel, @GetSpace() space: SpaceEnv, @Body() downloadFileDto: DownloadFileDto): Promise<FileTask> {
+ async downloadFromUrlAsTask(
+ @GetUser() user: UserModel,
+ @GetSpace() space: SpaceEnv,
+ @Body({ schema: downloadFileSchema }) downloadFileDto: DownloadFileDto
+ ): Promise<FileTask> {
return this.filesTasksManager.createTask(FILE_OPERATION.DOWNLOAD, user, space, downloadFileDto, this.filesMethods.downloadFromUrl.name)
}
@Post(`${FILES_ROUTE.TASK_OPERATION}/${FILE_OPERATION.COMPRESS}/*`)
@SkipSpacePermissionsCheck()
// Can be used to create or download an archive of files; permissions are checked later
- async compressAsTask(@Req() req: FastifySpaceRequest, @Body() compressFileDto: CompressFileDto): Promise<FileTask> {
+ async compressAsTask(@Req() req: FastifySpaceRequest, @Body({ schema: compressFileSchema }) compressFileDto: CompressFileDto): Promise<FileTask> {
if (compressFileDto.compressInDirectory) {
await SpaceGuard.checkPermissions(req, this.logger)
}
@@ -148,12 +168,20 @@ export class FilesOperationsController {
}
@Copy(`${FILES_ROUTE.TASK_OPERATION}/*`)
- async copyAsTask(@GetUser() user: UserModel, @GetSpace() space: SpaceEnv, @Body() copyMoveFileDto: CopyMoveFileDto): Promise<FileTask> {
+ async copyAsTask(
+ @GetUser() user: UserModel,
+ @GetSpace() space: SpaceEnv,
+ @Body({ schema: copyMoveFileSchema }) copyMoveFileDto: ValidatedCopyMoveFileDto
+ ): Promise<FileTask> {
return this.filesTasksManager.createTask(FILE_OPERATION.COPY, user, space, copyMoveFileDto, this.filesMethods.copy.name)
}
@Move(`${FILES_ROUTE.TASK_OPERATION}/*`)
- async moveAsTask(@GetUser() user: UserModel, @GetSpace() space: SpaceEnv, @Body() copyMoveFileDto: CopyMoveFileDto): Promise<FileTask> {
+ async moveAsTask(
+ @GetUser() user: UserModel,
+ @GetSpace() space: SpaceEnv,
+ @Body({ schema: copyMoveFileSchema }) copyMoveFileDto: ValidatedCopyMoveFileDto
+ ): Promise<FileTask> {
return this.filesTasksManager.createTask(FILE_OPERATION.MOVE, user, space, copyMoveFileDto, this.filesMethods.move.name)
}
diff --git a/backend/src/applications/files/files-tasks.controller.ts b/backend/src/applications/files/files-tasks.controller.ts
index 43acee14..2d880718 100644
--- a/backend/src/applications/files/files-tasks.controller.ts
+++ b/backend/src/applications/files/files-tasks.controller.ts
@@ -4,21 +4,22 @@ import { type FastifySpaceRequest } from '../spaces/interfaces/space-request.int
import { GetUser } from '../users/decorators/user.decorator.js'
import { UserModel } from '../users/models/user.model.js'
import { API_FILES_TASKS, FILES_ROUTE } from './constants/routes.js'
+import { type FileTasksDeleteDto, fileTasksDeleteSchema, type FileTasksPollDto, fileTasksPollSchema } from './dto/file-tasks.dto.js'
+import { optionalTaskIdParameterSchema, taskIdParameterSchema } from './files.schema.js'
import type { FileTasksPollResponse } from './interfaces/file-task.interface.js'
import { FilesTasksManager } from './services/tasks/files-tasks-manager.service.js'
-import { FileTasksDeleteDto, FileTasksPollDto } from './dto/file-tasks.dto.js'
@Controller(API_FILES_TASKS)
export class FilesTasksController {
constructor(private readonly filesTasksManager: FilesTasksManager) {}
@Get(':id?')
- getTasks(@GetUser() user: UserModel, @Param('id') taskId?: string) {
+ getTasks(@GetUser() user: UserModel, @Param('id', { schema: optionalTaskIdParameterSchema }) taskId?: string) {
return this.filesTasksManager.getTasks(user.id, taskId)
}
@Post(FILES_ROUTE.TASKS_POLL)
- pollTasks(@GetUser() user: UserModel, @Body() fileTasksPollDto: FileTasksPollDto): Promise<FileTasksPollResponse> {
+ pollTasks(@GetUser() user: UserModel, @Body({ schema: fileTasksPollSchema }) fileTasksPollDto: FileTasksPollDto): Promise<FileTasksPollResponse> {
return this.filesTasksManager.pollTasks(user.id, fileTasksPollDto.trackedIds)
}
@@ -28,19 +29,19 @@ export class FilesTasksController {
}
@Post(FILES_ROUTE.TASKS_DELETE)
- deleteSelectedTasks(@GetUser() user: UserModel, @Body() fileTasksDeleteDto: FileTasksDeleteDto) {
+ deleteSelectedTasks(@GetUser() user: UserModel, @Body({ schema: fileTasksDeleteSchema }) fileTasksDeleteDto: FileTasksDeleteDto) {
return this.filesTasksManager.deleteTasks(user, fileTasksDeleteDto.taskIds)
}
@Post(`${FILES_ROUTE.TASKS_CANCEL}/:id`)
- cancelTask(@GetUser() user: UserModel, @Param('id') taskId: string) {
+ cancelTask(@GetUser() user: UserModel, @Param('id', { schema: taskIdParameterSchema }) taskId: string) {
return this.filesTasksManager.cancelTask(user.id, taskId)
}
@Get(`${FILES_ROUTE.TASKS_DOWNLOAD}/:id`)
downloadTaskFile(
@GetUser() user: UserModel,
- @Param('id') taskId: string,
+ @Param('id', { schema: taskIdParameterSchema }) taskId: string,
@Req() req: FastifySpaceRequest,
@Res({ passthrough: true }) res: FastifyReply
): Promise<StreamableFile> {
diff --git a/backend/src/applications/files/files.config.spec.ts b/backend/src/applications/files/files.config.spec.ts
new file mode 100644
index 00000000..109184b5
--- /dev/null
+++ b/backend/src/applications/files/files.config.spec.ts
@@ -0,0 +1,15 @@
+import { FilesConfigSchema } from './files.config.js'
+
+describe('FilesConfigSchema', () => {
+ const paths = { dataPath: '/data', usersPath: '/data/users', spacesPath: '/data/spaces', linksPath: '/data/links' }
+
+ it('accepts a large upload ceiling without changing its value', () => {
+ const maxUploadSize = 2 ** 53
+
+ expect(FilesConfigSchema.parse({ ...paths, maxUploadSize }).maxUploadSize).toBe(maxUploadSize)
+ })
+
+ it.each([1.5, Infinity, -Infinity])('rejects a fractional or non-finite upload ceiling: %s', (maxUploadSize) => {
+ expect(FilesConfigSchema.safeParse({ ...paths, maxUploadSize }).success).toBe(false)
+ })
+})
diff --git a/backend/src/applications/files/files.config.ts b/backend/src/applications/files/files.config.ts
index 99f94d25..45ecd5ef 100644
--- a/backend/src/applications/files/files.config.ts
+++ b/backend/src/applications/files/files.config.ts
@@ -1,138 +1,83 @@
-import { Transform, Type } from 'class-transformer'
-import {
- ArrayNotEmpty,
- ArrayUnique,
- IsArray,
- IsBoolean,
- IsIn,
- IsInt,
- IsNotEmpty,
- IsNotEmptyObject,
- IsOptional,
- IsString,
- Min,
- ValidateIf,
- ValidateNested
-} from 'class-validator'
-import type { SampleDocumentGroup } from './constants/samples.js'
+import { z } from 'zod'
+import { hydrateConfigDefaults, integerNumberSchema, nonEmptyStringSchema } from '../../configuration/config.schema.js'
import { SAMPLE_DOCUMENT_GROUPS } from './constants/samples.js'
-import { CollaboraOnlineConfig } from './editors/collabora-online/collabora-online.config.js'
-import { DrawioConfig } from './editors/drawio/drawio.config.js'
-import { OnlyOfficeConfig } from './editors/only-office/only-office.config.js'
-
-export class FilesContentIndexingOCRConfig {
- @IsBoolean()
- enabled: boolean = true
-
- @ValidateIf((o: FilesContentIndexingOCRConfig) => o.enabled)
- @ArrayNotEmpty()
- @IsArray()
- @IsString({ each: true })
- languages: string[] = ['eng']
-
- @IsBoolean()
- offline: boolean = false
-
- @IsOptional()
- @IsString()
- languagesPath?: string
-}
-
-export class FilesContentIndexingConfig {
- @IsBoolean()
- enabled: boolean = true
-
- @ValidateIf((o: FilesContentIndexingConfig) => o.enabled)
- @IsNotEmptyObject()
- @ValidateNested()
- @Type(() => FilesContentIndexingOCRConfig)
- ocr: FilesContentIndexingOCRConfig = new FilesContentIndexingOCRConfig()
-}
-
-export class FilesTrashRetentionConfig {
- @Transform(({ value }) => (value === 0 ? false : value))
- @ValidateIf((o: FilesTrashRetentionConfig) => o.users !== false)
- @IsInt()
- @Min(1)
- users: number | false = false
-
- @Transform(({ value }) => (value === 0 ? false : value))
- @ValidateIf((o: FilesTrashRetentionConfig) => o.spaces !== false)
- @IsInt()
- @Min(1)
- spaces: number | false = false
-}
-
-export class FilesEditorsConfig {
- @IsNotEmptyObject()
- @ValidateNested()
- @Type(() => OnlyOfficeConfig)
- onlyoffice: OnlyOfficeConfig = new OnlyOfficeConfig()
-
- @IsNotEmptyObject()
- @ValidateNested()
- @Type(() => OnlyOfficeConfig)
- eurooffice: OnlyOfficeConfig = new OnlyOfficeConfig()
-
- @IsNotEmptyObject()
- @ValidateNested()
- @Type(() => CollaboraOnlineConfig)
- collabora: CollaboraOnlineConfig = new CollaboraOnlineConfig()
-
- @IsNotEmptyObject()
- @ValidateNested()
- @Type(() => DrawioConfig)
- drawio: DrawioConfig = new DrawioConfig()
-}
-
-export class FilesConfig {
- @IsNotEmpty()
- @IsString()
- dataPath: string
-
- @IsNotEmpty()
- @IsString()
- usersPath: string
-
- @IsNotEmpty()
- @IsString()
- spacesPath: string
-
- @IsNotEmpty()
- @IsString()
- linksPath: string
-
- @IsInt()
- maxUploadSize: number = 5368709120 // 5 GB
-
- @IsNotEmptyObject()
- @ValidateNested()
- @Type(() => FilesContentIndexingConfig)
- contentIndexing: FilesContentIndexingConfig = new FilesContentIndexingConfig()
-
- @IsNotEmptyObject()
- @ValidateNested()
- @Type(() => FilesTrashRetentionConfig)
- trashRetention: FilesTrashRetentionConfig = new FilesTrashRetentionConfig()
-
- @IsBoolean()
- showHiddenFiles: boolean = false
-
- @Transform(({ value }) =>
+import { CollaboraOnlineConfigSchema } from './editors/collabora-online/collabora-online.config.js'
+import { DrawioConfigSchema } from './editors/drawio/drawio.config.js'
+import { OnlyOfficeConfigSchema } from './editors/only-office/only-office.config.js'
+
+export type FilesContentIndexingOCRConfig = z.output<typeof FilesContentIndexingOCRConfigSchema>
+export type FilesTrashRetentionConfig = z.output<typeof FilesTrashRetentionConfigSchema>
+export type FilesConfig = z.output<typeof FilesConfigSchema>
+
+export const FilesContentIndexingOCRConfigSchema = z.discriminatedUnion('enabled', [
+ z.looseObject({
+ enabled: z.literal(true).default(true),
+ languages: z
+ .array(z.string())
+ .min(1)
+ .default(() => ['eng']),
+ offline: z.boolean().default(false),
+ languagesPath: z.string().nullish()
+ }),
+ z.looseObject({
+ enabled: z.literal(false),
+ // Disabled OCR retains its unchecked language configuration.
+ languages: z.custom<string[]>().default(() => ['eng']),
+ offline: z.boolean().default(false),
+ languagesPath: z.string().nullish()
+ })
+])
+
+const inactiveOCRConfigSchema = z
+ .custom<FilesContentIndexingOCRConfig>()
+ .transform((value) => hydrateConfigDefaults(FilesContentIndexingOCRConfigSchema.parse({}), value) as FilesContentIndexingOCRConfig)
+ .default(() => FilesContentIndexingOCRConfigSchema.parse({}))
+
+export const FilesContentIndexingConfigSchema = z.discriminatedUnion('enabled', [
+ z.looseObject({
+ enabled: z.literal(true).default(true),
+ ocr: FilesContentIndexingOCRConfigSchema.prefault({})
+ }),
+ z.looseObject({
+ enabled: z.literal(false),
+ ocr: inactiveOCRConfigSchema
+ })
+])
+
+const retentionPeriodSchema = z.preprocess((value) => (value === 0 ? false : value), z.union([z.literal(false), z.number().int().min(1)]))
+
+export const FilesTrashRetentionConfigSchema = z.looseObject({
+ users: retentionPeriodSchema.default(false),
+ spaces: retentionPeriodSchema.default(false)
+})
+
+export const FilesEditorsConfigSchema = z.looseObject({
+ onlyoffice: OnlyOfficeConfigSchema.default(() => OnlyOfficeConfigSchema.parse({})),
+ eurooffice: OnlyOfficeConfigSchema.default(() => OnlyOfficeConfigSchema.parse({})),
+ collabora: CollaboraOnlineConfigSchema.prefault({}),
+ drawio: DrawioConfigSchema.prefault({})
+})
+
+const sampleDocumentsSchema = z.preprocess(
+ (value) =>
typeof value === 'string'
? value
.split(',')
- .map((v: string) => v.trim())
+ .map((group) => group.trim())
.filter(Boolean)
- : value
- )
- @ArrayUnique()
- @IsArray()
- @IsIn(SAMPLE_DOCUMENT_GROUPS, { each: true })
- sampleDocuments: SampleDocumentGroup[] = [...SAMPLE_DOCUMENT_GROUPS]
-
- @IsNotEmptyObject()
- @ValidateNested()
- @Type(() => FilesEditorsConfig)
- editors: FilesEditorsConfig = new FilesEditorsConfig()
-}
+ : value,
+ z.array(z.enum(SAMPLE_DOCUMENT_GROUPS)).refine((groups) => new Set(groups).size === groups.length, { message: 'Array elements must be unique' })
+)
+
+export const FilesConfigSchema = z.looseObject({
+ dataPath: nonEmptyStringSchema,
+ usersPath: nonEmptyStringSchema,
+ spacesPath: nonEmptyStringSchema,
+ linksPath: nonEmptyStringSchema,
+ maxUploadSize: integerNumberSchema.default(5368709120), // 5 GB
+ contentIndexing: FilesContentIndexingConfigSchema.prefault({}),
+ trashRetention: FilesTrashRetentionConfigSchema.prefault({}),
+ showHiddenFiles: z.boolean().default(false),
+ sampleDocuments: sampleDocumentsSchema.default(() => [...SAMPLE_DOCUMENT_GROUPS]),
+ editors: FilesEditorsConfigSchema.prefault({})
+})
diff --git a/backend/src/applications/files/files.controller.ts b/backend/src/applications/files/files.controller.ts
index b2a2aa4e..4acd2960 100644
--- a/backend/src/applications/files/files.controller.ts
+++ b/backend/src/applications/files/files.controller.ts
@@ -1,4 +1,4 @@
-import { BadRequestException, Body, Controller, Delete, Get, ParseIntPipe, Post, Query, Search, UseGuards } from '@nestjs/common'
+import { Body, Controller, Delete, Get, Post, Query, Search, UseGuards } from '@nestjs/common'
import { SkipSpacePermissionsCheck } from '../spaces/decorators/space-skip-permissions.decorator.js'
import { GetSpace } from '../spaces/decorators/space.decorator.js'
import { SpaceGuard } from '../spaces/guards/space.guard.js'
@@ -10,12 +10,13 @@ import { UserRolesGuard } from '../users/guards/roles.guard.js'
import { UserModel } from '../users/models/user.model.js'
import { FILES_RECENTS_DEFAULT_LIMIT, FILES_RECENTS_MAX_LIMIT } from './constants/recents.js'
import { FILES_ROUTE } from './constants/routes.js'
-import { DeleteFileFavoriteDto, FileFavoriteDto } from './dto/file-favorite.dto.js'
-import { SearchFilesDto } from './dto/file-operations.dto.js'
+import { type DeleteFileFavoriteDto, deleteFileFavoriteSchema, type FileFavoriteDto, fileFavoriteSchema } from './dto/file-favorite.dto.js'
+import { searchFilesSchema, type ValidatedSearchFilesDto } from './dto/file-operations.dto.js'
+import { filesRecentsLimitQuerySchema } from './files.schema.js'
import { IndexingStatus } from './interfaces/indexing.interface.js'
import { FileContent } from './schemas/file-content.interface.js'
import type { FileFavorite, FileFavoriteIdentity } from './schemas/file-favorite.interface.js'
-import { FileRecent } from './schemas/file-recent.interface.js'
+import type { FileRecent } from './schemas/file-recent.interface.js'
import { FilesContentIndexer } from './services/files-content-indexer.service.js'
import { FilesFavoritesManager } from './services/files-favorites-manager.service.js'
import { FilesRecents } from './services/files-recents.service.js'
@@ -44,14 +45,18 @@ export class FilesController {
@SkipSpacePermissionsCheck()
@UserHaveRole(USER_ROLE.GUEST)
@UseGuards(SpaceGuard, UserRolesGuard)
- addFavorite(@GetUser() user: UserModel, @GetSpace() space: SpaceEnv, @Body() favoriteDto: FileFavoriteDto): Promise<FileFavoriteIdentity> {
+ addFavorite(
+ @GetUser() user: UserModel,
+ @GetSpace() space: SpaceEnv,
+ @Body({ schema: fileFavoriteSchema }) favoriteDto: FileFavoriteDto
+ ): Promise<FileFavoriteIdentity> {
return this.filesFavoritesManager.addFavorite(user, space, favoriteDto.fileId)
}
@Delete(FILES_ROUTE.FAVORITES)
@UserHaveRole(USER_ROLE.GUEST)
@UseGuards(UserRolesGuard)
- removeFavorite(@GetUser() user: UserModel, @Body() favoriteDto: DeleteFileFavoriteDto): Promise<void> {
+ removeFavorite(@GetUser() user: UserModel, @Body({ schema: deleteFileFavoriteSchema }) favoriteDto: DeleteFileFavoriteDto): Promise<void> {
return this.filesFavoritesManager.removeFavorite(user, favoriteDto.fileId)
}
@@ -60,16 +65,15 @@ export class FilesController {
@Get(FILES_ROUTE.RECENTS)
getRecents(
@GetUser() user: UserModel,
- @Query('limit', new ParseIntPipe({ optional: true })) limit: number = FILES_RECENTS_DEFAULT_LIMIT
+ @Query('limit', { schema: filesRecentsLimitQuerySchema }) limit: number = FILES_RECENTS_DEFAULT_LIMIT
): Promise<FileRecent[]> {
- if (!Number.isInteger(limit) || limit < 1) throw new BadRequestException('limit must be a positive integer')
return this.filesRecents.getRecents(user, Math.min(limit, FILES_RECENTS_MAX_LIMIT))
}
// SEARCH FILES
@Search(FILES_ROUTE.SEARCH)
- search(@GetUser() user: UserModel, @Body() search: SearchFilesDto): Promise<FileContent[]> {
+ search(@GetUser() user: UserModel, @Body({ schema: searchFilesSchema }) search: ValidatedSearchFilesDto): Promise<FileContent[]> {
return this.filesSearch.search(user, search)
}
diff --git a/backend/src/applications/files/files.schema.ts b/backend/src/applications/files/files.schema.ts
new file mode 100644
index 00000000..9bea06c7
--- /dev/null
+++ b/backend/src/applications/files/files.schema.ts
@@ -0,0 +1,10 @@
+import { z } from 'zod'
+import { booleanFromStringSchema, positiveIntegerFromStringSchema, safeIntegerFromStringSchema } from '../../configuration/config.schema.js'
+import { isValidFileReferenceId } from './utils/files.js'
+
+export const fileReferenceIdSchema = z.number().refine(isValidFileReferenceId, { message: 'Invalid file id' })
+export const filesRecentsLimitQuerySchema = positiveIntegerFromStringSchema.optional()
+export const thumbnailSizeQuerySchema = safeIntegerFromStringSchema.optional()
+export const forceAsFileOwnerQuerySchema = booleanFromStringSchema.optional()
+export const taskIdParameterSchema = z.string()
+export const optionalTaskIdParameterSchema = taskIdParameterSchema.optional()
diff --git a/backend/src/applications/files/interfaces/file-db-props.interface.ts b/backend/src/applications/files/interfaces/file-db-props.interface.ts
index 3327f174..6f802a0a 100644
--- a/backend/src/applications/files/interfaces/file-db-props.interface.ts
+++ b/backend/src/applications/files/interfaces/file-db-props.interface.ts
@@ -2,10 +2,10 @@ import type { File } from '../schemas/file.interface.js'
export interface FileDBProps extends Partial<Pick<File, 'ownerId' | 'spaceId' | 'spaceExternalRootId' | 'shareExternalId' | 'inTrash' | 'path'>> {
// warn: used during lock creation, new fields will be used in the lock key
- ownerId?: number
- spaceId?: number
- spaceExternalRootId?: number
- shareExternalId?: number
+ ownerId?: number | null
+ spaceId?: number | null
+ spaceExternalRootId?: number | null
+ shareExternalId?: number | null
inTrash: boolean
// full path with name
path: string
diff --git a/backend/src/applications/files/interfaces/file-lock.interface.ts b/backend/src/applications/files/interfaces/file-lock.interface.ts
index de59bde7..5e334f56 100644
--- a/backend/src/applications/files/interfaces/file-lock.interface.ts
+++ b/backend/src/applications/files/interfaces/file-lock.interface.ts
@@ -10,8 +10,8 @@ export type LOCK_APP =
// Optional lock parameters
export interface FileLockOptions {
// Only locktype write is currently implemented in RFC
- lockRoot: string // Used with webdav (uri)
- lockToken: string
+ lockRoot: string | null // Used with webdav (uri)
+ lockToken: string | null
lockScope: LOCK_SCOPE
lockInfo?: string // Provided by some WebDAV clients to identify the locking application.
}
diff --git a/backend/src/applications/files/interfaces/file-props.interface.ts b/backend/src/applications/files/interfaces/file-props.interface.ts
index 8e1fa3f8..d87bba9f 100644
--- a/backend/src/applications/files/interfaces/file-props.interface.ts
+++ b/backend/src/applications/files/interfaces/file-props.interface.ts
@@ -12,8 +12,8 @@ export interface FileLockProps {
isExclusive: boolean
}
-export interface FileProps extends Omit<File, 'ownerId' | 'spaceId' | 'spaceExternalRootId' | 'shareExternalId' | 'inTrash'> {
- id: number
+export interface FileProps extends Omit<File, 'id' | 'ownerId' | 'spaceId' | 'spaceExternalRootId' | 'shareExternalId' | 'inTrash'> {
+ id?: number
name: string
path: string
isDir: boolean
diff --git a/backend/src/applications/files/interfaces/file-space.interface.ts b/backend/src/applications/files/interfaces/file-space.interface.ts
index 546a66dc..b514f135 100644
--- a/backend/src/applications/files/interfaces/file-space.interface.ts
+++ b/backend/src/applications/files/interfaces/file-space.interface.ts
@@ -1,13 +1,7 @@
import type { File } from '../schemas/file.interface.js'
-export class FileSpace implements Pick<File, 'id' | 'ownerId' | 'path' | 'isDir' | 'inTrash' | 'mime'> {
- id: number
- ownerId: number
+export interface FileSpace extends Pick<File, 'id' | 'ownerId' | 'path' | 'isDir' | 'inTrash' | 'mime'> {
name: string
- path: string
- isDir: boolean
- inTrash: boolean
- mime: string
// permissions are inherited from the shared file (space and root permissions are intersected)
permissions?: string
space: {
diff --git a/backend/src/applications/files/interfaces/file-task-queue.interface.ts b/backend/src/applications/files/interfaces/file-task-queue.interface.ts
index 6ac077ca..3dcb8665 100644
--- a/backend/src/applications/files/interfaces/file-task-queue.interface.ts
+++ b/backend/src/applications/files/interfaces/file-task-queue.interface.ts
@@ -2,6 +2,8 @@ import type { SpaceEnv } from '../../spaces/models/space-env.model.js'
import type { UserModel } from '../../users/models/user.model.js'
import type { FileTask } from '../models/file-task.js'
+export type FileTaskMethod = (user: UserModel, space: SpaceEnv, dto: any, signal?: AbortSignal) => Promise<any>
+
export interface FileTaskQueueItem {
cacheKey: string
dto: any
diff --git a/backend/src/applications/files/models/file-task.ts b/backend/src/applications/files/models/file-task.ts
index f120ccf4..57701698 100644
--- a/backend/src/applications/files/models/file-task.ts
+++ b/backend/src/applications/files/models/file-task.ts
@@ -22,13 +22,13 @@ export class FileTask {
id: string
type: FILE_OPERATION
cancellable: boolean
- status: FileTaskStatus
+ status!: FileTaskStatus
path: string
name: string
props: FileTaskProps = {}
- result: string
- startedAt: number
- endedAt: number
+ result!: string
+ startedAt!: number
+ endedAt!: number
constructor(id: string, type: FILE_OPERATION, path: string, name: string, cancellable = false) {
this.id = id
diff --git a/backend/src/applications/files/schemas/file-content.interface.ts b/backend/src/applications/files/schemas/file-content.interface.ts
index 7c28a565..45726c31 100644
--- a/backend/src/applications/files/schemas/file-content.interface.ts
+++ b/backend/src/applications/files/schemas/file-content.interface.ts
@@ -6,7 +6,7 @@ export interface FileContent {
size: number
mtime: number
// used for inserts
- content?: string
+ content?: string | null
// used for search
matches?: string[]
// used for search
diff --git a/backend/src/applications/files/schemas/file-recent.interface.ts b/backend/src/applications/files/schemas/file-recent.interface.ts
index 4ca6dbed..f49b0d92 100644
--- a/backend/src/applications/files/schemas/file-recent.interface.ts
+++ b/backend/src/applications/files/schemas/file-recent.interface.ts
@@ -1,13 +1,9 @@
-import { filesRecents } from './files-recents.schema.js'
-
-type FileRecentSchema = typeof filesRecents.$inferSelect
-
-export class FileRecent implements FileRecentSchema {
+export interface FileRecent {
// Browser file identity: database id when available, otherwise negative inode.
id: number
- ownerId: number
- spaceId: number
- shareId: number
+ ownerId?: number | null
+ spaceId?: number | null
+ shareId?: number | null
path: string
name: string
mime: string
diff --git a/backend/src/applications/files/schemas/file.interface.ts b/backend/src/applications/files/schemas/file.interface.ts
index 82cee1b7..15e397e7 100644
--- a/backend/src/applications/files/schemas/file.interface.ts
+++ b/backend/src/applications/files/schemas/file.interface.ts
@@ -1,19 +1,3 @@
import type { files } from './files.schema.js'
-type FileSchema = typeof files.$inferSelect
-
-export class File implements FileSchema {
- id: number
- ownerId: number
- spaceId: number
- spaceExternalRootId: number
- shareExternalId: number
- path: string
- name: string
- isDir: boolean
- inTrash: boolean
- mime: string
- size: number
- mtime: number
- ctime: number
-}
+export type File = typeof files.$inferSelect
diff --git a/backend/src/applications/files/services/files-content-indexer.service.spec.ts b/backend/src/applications/files/services/files-content-indexer.service.spec.ts
index 8f4022a9..6c17eadf 100644
--- a/backend/src/applications/files/services/files-content-indexer.service.spec.ts
+++ b/backend/src/applications/files/services/files-content-indexer.service.spec.ts
@@ -456,13 +456,12 @@ describe(FilesContentIndexer.name, () => {
{ parentPath: '/root', name: 'a.txt', isDirectory: () => false }
] as any)
readdirSpy.mockResolvedValueOnce([{ parentPath: '/root/sub', name: 'b.txt', isDirectory: () => false }] as any)
- vi.spyOn(service as any, 'getFileMetadata').mockImplementation(async (realPath: string) =>
+ vi.spyOn(service as any, 'getFileMetadata').mockImplementation((async (realPath: string) =>
fileMetadata({
id: realPath.length,
name: path.basename(realPath),
realPath
- })
- )
+ })) as never)
const yielded: any[] = []
for await (const metadata of (service as any).parseFileMetadata('/root', contentContext({ regexBasePath: /^\/?root\/?/ }))) {
diff --git a/backend/src/applications/files/services/files-content-indexer.service.ts b/backend/src/applications/files/services/files-content-indexer.service.ts
index 2ea11ace..ea250577 100644
--- a/backend/src/applications/files/services/files-content-indexer.service.ts
+++ b/backend/src/applications/files/services/files-content-indexer.service.ts
@@ -1,3 +1,4 @@
+import { toErrorMessage } from '../../../common/errors.js'
import { Injectable, Logger } from '@nestjs/common'
import fs from 'fs/promises'
import { Stats } from 'node:fs'
@@ -89,7 +90,7 @@ export class FilesContentIndexer {
try {
status.indexesCount = await this.filesContentStore.indexesCount()
} catch (e) {
- this.logger.error({ tag: this.status.name, msg: `${e}` })
+ this.logger.error({ tag: this.status.name, msg: toErrorMessage(e) })
}
return status
}
@@ -110,7 +111,7 @@ export class FilesContentIndexer {
try {
await this.parseAndIndexAllFiles()
} catch (e) {
- this.logger.error({ tag: this.processIndexingQueue.name, msg: `${e}` })
+ this.logger.error({ tag: this.processIndexingQueue.name, msg: toErrorMessage(e) })
}
return
}
@@ -140,7 +141,7 @@ export class FilesContentIndexer {
await this.parseAndIndexAllFiles(userIds, spaceIds, shareIds)
await this.cache.set(CACHE_INDEXING_EVENT_LAST_RUN_KEY, Date.now(), 0)
} catch (e) {
- this.logger.error({ tag: this.processIndexingQueue.name, msg: `${e}` })
+ this.logger.error({ tag: this.processIndexingQueue.name, msg: toErrorMessage(e) })
}
}
}
@@ -148,7 +149,9 @@ export class FilesContentIndexer {
// Clean up event keys even if incremental indexing fails.
// Ignore cache deletion errors, the full reindex restores consistency.
for (const k of cacheKeys) {
- this.cache.del(k).catch((e) => this.logger.warn({ tag: this.processIndexingQueue.name, msg: `Unable to clean key: ${k} - ${e}` }))
+ this.cache
+ .del(k)
+ .catch((e) => this.logger.warn({ tag: this.processIndexingQueue.name, msg: `Unable to clean key: ${k} - ${toErrorMessage(e)}` }))
}
} finally {
await this.setRunning(false)
@@ -162,7 +165,7 @@ export class FilesContentIndexer {
try {
await this.ocrManager.start()
} catch (e) {
- this.logger.warn({ tag: this.parseAndIndexAllFiles.name, msg: `unable to initialize OCR worker: ${e}` })
+ this.logger.warn({ tag: this.parseAndIndexAllFiles.name, msg: `unable to initialize OCR worker: ${toErrorMessage(e)}` })
}
const indexSuffixes: string[] = []
let stopped = false
@@ -175,11 +178,13 @@ export class FilesContentIndexer {
try {
await this.indexFiles(indexSuffix, paths)
} catch (e) {
- this.logger.error({ tag: this.parseAndIndexAllFiles.name, msg: `${e}` })
+ this.logger.error({ tag: this.parseAndIndexAllFiles.name, msg: toErrorMessage(e) })
}
indexSuffixes.push(indexSuffix)
// renew the TTL after each indexed space to prevent expiration during long runs
- this.renewRunningTTL().catch((e) => this.logger.warn({ tag: this.parseAndIndexAllFiles.name, msg: `unable to refresh running TTL: ${e}` }))
+ this.renewRunningTTL().catch((e) =>
+ this.logger.warn({ tag: this.parseAndIndexAllFiles.name, msg: `unable to refresh running TTL: ${toErrorMessage(e)}` })
+ )
}
// clean up old tables only when all indexes have been indexed
if (!stopped && !userIds?.length && !spaceIds?.length && !shareIds?.length) {
@@ -265,7 +270,7 @@ export class FilesContentIndexer {
// case when no data
this.filesContentStore
.dropIndex(indexName)
- .catch((e: Error) => this.logger.error({ tag: this.indexFiles.name, msg: `${indexSuffix} - unable to drop index : ${e}` }))
+ .catch((e: Error) => this.logger.error({ tag: this.indexFiles.name, msg: `${indexSuffix} - unable to drop index : ${toErrorMessage(e)}` }))
this.logger.verbose({ tag: this.indexFiles.name, msg: `${indexSuffix} - no data: index not stored` })
} else if (indexedRecords === 0 && indexingErrors === 0 && deletedRecords === 0) {
this.logger.verbose({ tag: this.indexFiles.name, msg: `${indexSuffix} - no changes` })
@@ -333,7 +338,7 @@ export class FilesContentIndexer {
}
} catch (e) {
// skip unreadable directories, their unseen records will be cleaned later
- this.logger.warn({ tag: this.parseFileMetadata.name, msg: `${context.indexName} - unable to parse: ${dir} - ${e}` })
+ this.logger.warn({ tag: this.parseFileMetadata.name, msg: `${context.indexName} - unable to parse: ${dir} - ${toErrorMessage(e)}` })
}
}
@@ -350,7 +355,7 @@ export class FilesContentIndexer {
try {
stats = await fs.stat(realPath)
} catch (e) {
- this.logger.warn({ tag: this.getFileMetadata.name, msg: `unable to stats: ${realPath} - ${e}` })
+ this.logger.warn({ tag: this.getFileMetadata.name, msg: `unable to stats: ${realPath} - ${toErrorMessage(e)}` })
// unreadable or missing files are treated as unseen records
return null
}
@@ -385,7 +390,7 @@ export class FilesContentIndexer {
}
}
- private async parseContent(rPath: string, extension: string): Promise<string> {
+ private async parseContent(rPath: string, extension: string): Promise<string | null> {
try {
const content = await docTextify(
rPath,
@@ -401,7 +406,7 @@ export class FilesContentIndexer {
)
return content.length ? content : null
} catch (e) {
- this.logger.warn({ tag: this.parseContent.name, msg: `unable to index: ${rPath} - ${e}` })
+ this.logger.warn({ tag: this.parseContent.name, msg: `unable to index: ${rPath} - ${toErrorMessage(e)}` })
}
return null
}
diff --git a/backend/src/applications/files/services/files-event-manager.service.ts b/backend/src/applications/files/services/files-event-manager.service.ts
index fd1174b1..bba215c4 100644
--- a/backend/src/applications/files/services/files-event-manager.service.ts
+++ b/backend/src/applications/files/services/files-event-manager.service.ts
@@ -1,3 +1,4 @@
+import { toErrorMessage } from '../../../common/errors.js'
import { Injectable, Logger, OnModuleDestroy } from '@nestjs/common'
import { Cache } from '../../../infrastructure/cache/cache.service.js'
import { FileEvent } from '../events/file-events.js'
@@ -60,7 +61,7 @@ export class FilesEventManager implements OnModuleDestroy {
await this.filesRecents.updateRecentFromEditor(event.user, event.space, event.rPath)
} catch (e) {
if ((e as NodeJS.ErrnoException)?.code === 'ENOENT') return
- this.logger.warn({ tag: this.processRecentEditorUpdate.name, msg: `Could not update recent file ${event.space.url}: ${e}` })
+ this.logger.warn({ tag: this.processRecentEditorUpdate.name, msg: `Could not update recent file ${event.space.url}: ${toErrorMessage(e)}` })
}
}
@@ -93,7 +94,7 @@ export class FilesEventManager implements OnModuleDestroy {
try {
await this.processEvents(events)
} catch (e) {
- this.logger.error({ tag: this.flushEvents.name, msg: `Could not process buffered events: ${e}` })
+ this.logger.error({ tag: this.flushEvents.name, msg: `Could not process buffered events: ${toErrorMessage(e)}` })
this.eventsBuffer.unshift(...events)
} finally {
this.isFlushing = false
@@ -117,7 +118,7 @@ export class FilesEventManager implements OnModuleDestroy {
this.processIndexingEvent(event)
}
} catch (e) {
- this.logger.warn({ tag: this.processEvents.name, msg: `Could not process event: ${JSON.stringify(event)} - ${e}` })
+ this.logger.warn({ tag: this.processEvents.name, msg: `Could not process event: ${JSON.stringify(event)} - ${toErrorMessage(e)}` })
}
}
await Promise.all([this.storeEventsInCache(), this.processRecentEvents(fEvents)])
@@ -157,7 +158,7 @@ export class FilesEventManager implements OnModuleDestroy {
try {
await this.filesRecents.deleteRecents(deletions)
} catch (e) {
- this.logger.warn({ tag: this.processRecentDeletes.name, msg: `Could not delete recent files: ${e}` })
+ this.logger.warn({ tag: this.processRecentDeletes.name, msg: `Could not delete recent files: ${toErrorMessage(e)}` })
}
}
diff --git a/backend/src/applications/files/services/files-favorites-manager.service.spec.ts b/backend/src/applications/files/services/files-favorites-manager.service.spec.ts
index ba376610..6e1de225 100644
--- a/backend/src/applications/files/services/files-favorites-manager.service.spec.ts
+++ b/backend/src/applications/files/services/files-favorites-manager.service.spec.ts
@@ -12,10 +12,14 @@ import { FilesFavoritesQueries } from './files-favorites-queries.service.js'
import { FilesQueries } from './files-queries.service.js'
import type { Mock } from 'vitest'
-vi.mock('../utils/files.js', () => ({
- getProps: vi.fn(),
- isPathExists: vi.fn()
-}))
+vi.mock('../utils/files.js', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('../utils/files.js')>()
+ return {
+ ...actual,
+ getProps: vi.fn(),
+ isPathExists: vi.fn()
+ }
+})
describe(FilesFavoritesManager.name, () => {
let service: FilesFavoritesManager
diff --git a/backend/src/applications/files/services/files-favorites-queries.e2e-spec.ts b/backend/src/applications/files/services/files-favorites-queries.e2e-spec.ts
index 3f8a9806..a01aae2a 100644
--- a/backend/src/applications/files/services/files-favorites-queries.e2e-spec.ts
+++ b/backend/src/applications/files/services/files-favorites-queries.e2e-spec.ts
@@ -40,14 +40,14 @@ describe('Files favorites queries (e2e)', () => {
let commentsQueries: CommentsQueries
let spacesQueries: SpacesQueries
let sharesQueries: SharesQueries
- let ownerId: number | undefined
- let memberId: number | undefined
- let spaceId: number | undefined
- let shareId: number | undefined
- let rootFileId: number | undefined
- let activeFileId: number | undefined
- let trashedFileId: number | undefined
- let syncPathId: number | undefined
+ let ownerId: number
+ let memberId: number
+ let spaceId: number
+ let shareId: number
+ let rootFileId: number
+ let activeFileId: number
+ let trashedFileId: number
+ let syncPathId: number
const suffix = randomUUID().replaceAll('-', '').slice(0, 12)
const rootName = `favorite-root-${suffix}`
diff --git a/backend/src/applications/files/services/files-favorites-queries.service.ts b/backend/src/applications/files/services/files-favorites-queries.service.ts
index 9fe57da6..b337af23 100644
--- a/backend/src/applications/files/services/files-favorites-queries.service.ts
+++ b/backend/src/applications/files/services/files-favorites-queries.service.ts
@@ -1,5 +1,5 @@
import { Inject, Injectable } from '@nestjs/common'
-import { and, desc, eq, inArray, isNotNull, isNull, or, SelectedFields, sql } from 'drizzle-orm'
+import { and, desc, eq, inArray, isNotNull, isNull, or, sql } from 'drizzle-orm'
import { alias, unionAll } from 'drizzle-orm/mysql-core'
import { DB_TOKEN_PROVIDER } from '../../../infrastructure/database/constants.js'
import type { DBSchema } from '../../../infrastructure/database/interfaces/database.interface.js'
@@ -63,7 +63,7 @@ export class FilesFavoritesQueries {
hasComments: sql`${fileHasCommentsSubquerySQL(files.id)}`.mapWith(Boolean),
repository: sql<FileFavoriteRepository>`IF (${isPersonal}, ${SPACE_ALIAS.PERSONAL}, NULL)`.as('repository'),
displayRootName: sql<string>`NULL`.as('displayRootName')
- } satisfies FileFavorite | SelectedFields<any, any>)
+ } satisfies { [K in keyof FileFavorite]: any })
.from(filesFavorites)
.innerJoin(files, eq(files.id, filesFavorites.fileId))
.leftJoin(spacesRoots, and(isPersonal, eq(spacesRoots.fileId, files.id)))
@@ -76,7 +76,7 @@ export class FilesFavoritesQueries {
return q
.where(eq(filesFavorites.userId, userId))
.groupBy(files.id, filesFavorites.createdAt)
- .orderBy(desc(filesFavorites.createdAt), desc(filesFavorites.fileId))
+ .orderBy(desc(filesFavorites.createdAt), desc(filesFavorites.fileId)) as Promise<FileFavorite[]>
}
getFavoriteLocationsFromSpaces(userId: number, spaceIds: number[]): Promise<FileFavoriteLocation[]> {
@@ -113,7 +113,7 @@ export class FilesFavoritesQueries {
displayRootName: sql<string>`${spaces.name}`.as('displayRootName'),
contextId: sql<number>`${spaces.id}`.as('contextId'),
rootId: sql<number>`0`.as('rootId')
- } satisfies FileFavoriteLocation | SelectedFields<any, any>)
+ } satisfies Record<keyof FileFavoriteLocation, any>)
.from(filesFavorites)
.innerJoin(files, eq(files.id, filesFavorites.fileId))
.innerJoin(spaces, and(eq(spaces.id, files.spaceId), inArray(spaces.id, spaceIds), eq(spaces.enabled, true)))
@@ -138,7 +138,7 @@ export class FilesFavoritesQueries {
displayRootName: sql<string>`${spaces.name}`.as('displayRootName'),
contextId: sql<number>`${spaces.id}`.as('contextId'),
rootId: sql<number>`${anchoredSpaceRoot.id}`.as('rootId')
- } satisfies FileFavoriteLocation | SelectedFields<any, any>)
+ } satisfies Record<keyof FileFavoriteLocation, any>)
.from(filesFavorites)
.innerJoin(files, eq(files.id, filesFavorites.fileId))
.innerJoin(spaceRootFile, fileFromSpaceRoot)
@@ -187,7 +187,7 @@ export class FilesFavoritesQueries {
displayRootName: sql<string>`${shares.name}`.as('displayRootName'),
contextId: sql<number>`${shares.id}`.as('contextId'),
rootId: sql<number>`COALESCE(${spaceRoot.id}, 0)`.as('rootId')
- }) satisfies FileFavoriteLocation | SelectedFields<any, any>
+ }) satisfies Record<keyof FileFavoriteLocation, any>
const externalLocationSelect = (spaceRoot: any) =>
({
fileId: sql<number>`${files.id}`.as('fileId'),
@@ -203,7 +203,7 @@ export class FilesFavoritesQueries {
displayRootName: sql<string>`${shares.name}`.as('displayRootName'),
contextId: sql<number>`${shares.id}`.as('contextId'),
rootId: sql<number>`COALESCE(${spaceRoot.id}, 0)`.as('rootId')
- }) satisfies FileFavoriteLocation | SelectedFields<any, any>
+ }) satisfies Record<keyof FileFavoriteLocation, any>
const externalShareTargets = this.db
.select({ id: shares.id, parentId: shares.parentId, externalPath: shares.externalPath })
.from(shares)
diff --git a/backend/src/applications/files/services/files-lock-manager.service.spec.ts b/backend/src/applications/files/services/files-lock-manager.service.spec.ts
index 5e68f0d5..5a0f2994 100644
--- a/backend/src/applications/files/services/files-lock-manager.service.spec.ts
+++ b/backend/src/applications/files/services/files-lock-manager.service.spec.ts
@@ -167,7 +167,7 @@ describe(FilesLockManager.name, () => {
{ path: 'docs/file.txt', ownerId: 10, inTrash: false },
WEBDAV_APP_LOCK,
DEPTH.RESOURCE,
- null,
+ null as never,
55
)
expect(created).toBe(true)
diff --git a/backend/src/applications/files/services/files-lock-manager.service.ts b/backend/src/applications/files/services/files-lock-manager.service.ts
index 239640bb..18934b19 100644
--- a/backend/src/applications/files/services/files-lock-manager.service.ts
+++ b/backend/src/applications/files/services/files-lock-manager.service.ts
@@ -1,6 +1,7 @@
import { Injectable, Logger } from '@nestjs/common'
import crypto from 'node:crypto'
+import { toErrorMessage } from '../../../common/errors.js'
import { currentTimeStamp } from '../../../common/shared.js'
import { Cache } from '../../../infrastructure/cache/cache.service.js'
import { UserModel } from '../../users/models/user.model.js'
@@ -38,7 +39,7 @@ export class FilesLockManager {
dbFile: FileDBProps,
app: LOCK_APP,
depth: LOCK_DEPTH,
- options?: FileLockOptions,
+ options?: FileLockOptions | null,
ttl?: number
): Promise<[boolean, FileLock]> {
try {
@@ -47,7 +48,8 @@ export class FilesLockManager {
if (e instanceof LockConflict) {
return [false, e.lock]
}
- throw new Error(e)
+ if (e instanceof Error) throw e
+ throw new Error(toErrorMessage(e))
}
ttl ??= CACHE_LOCK_DEFAULT_TTL
const key = `${CACHE_LOCK_PREFIX}|${this.genSuffixKey(dbFile, { depth: depth, token: options?.lockToken })}`
@@ -59,7 +61,7 @@ export class FilesLockManager {
app: app,
depth: depth,
expiration: expiration,
- options: options
+ options: options ?? undefined
}
this.logger.verbose({ tag: this.create.name, msg: `${key}` })
await this.cache.set(key, lock, ttl)
@@ -77,7 +79,7 @@ export class FilesLockManager {
// Refresh if more than half of the TTL has passed
const mustRefresh = lock.expiration - currentTimeStamp() < ttl / 2
if (mustRefresh) {
- this.refreshLockTimeout(lock, ttl).catch((e: Error) => this.logger.error({ tag: this.createOrRefresh.name, msg: `${e}` }))
+ this.refreshLockTimeout(lock, ttl).catch((e: Error) => this.logger.error({ tag: this.createOrRefresh.name, msg: toErrorMessage(e) }))
}
} else {
throw new LockConflict(lock, 'Conflicting lock')
@@ -115,7 +117,7 @@ export class FilesLockManager {
}
}
- async isLockedWithToken(token: string, dbFilePath: string): Promise<FileLock> {
+ async isLockedWithToken(token: string, dbFilePath: string): Promise<FileLock | null> {
// check if the url (or any of its parents) is locked by the token
const lock = await this.getLockByToken(token)
return lock ? (dbFilePath.startsWith(lock.dbFilePath) ? lock : null) : null
@@ -144,10 +146,10 @@ export class FilesLockManager {
async refreshLockTimeout(lock: FileLock, ttl: number) {
lock.expiration = currentTimeStamp() + ttl
- this.cache.set(lock.key, lock, ttl).catch((e: Error) => this.logger.error({ tag: this.refreshLockTimeout.name, msg: `${e}` }))
+ this.cache.set(lock.key, lock, ttl).catch((e: Error) => this.logger.error({ tag: this.refreshLockTimeout.name, msg: toErrorMessage(e) }))
}
- async getLockByToken(token: string): Promise<FileLock> {
+ async getLockByToken(token: string): Promise<FileLock | null> {
const key = await this.searchKeyByToken(token)
return key ? (await this.cache.get(key)) || null : null
}
@@ -183,7 +185,10 @@ export class FilesLockManager {
// Only compatible with shared locks (with the same owner and the same application)
continue
}
- if (options?.userId === l.owner.id && (!l.options || (options?.lockTokens?.length && options.lockTokens.indexOf(l.options.lockToken) > -1))) {
+ if (
+ options?.userId === l.owner.id &&
+ (!l.options || (options?.lockTokens?.length && options.lockTokens.indexOf(l.options.lockToken as string) > -1))
+ ) {
// Owner owns this lock (no davLock if the lock was created from api)
continue
}
@@ -193,7 +198,10 @@ export class FilesLockManager {
}
if (depth === DEPTH.INFINITY) {
for await (const l of this.searchChildLocks(dbFile)) {
- if (options?.userId === l.owner.id && (!l.options || (options?.lockTokens?.length && options.lockTokens.indexOf(l.options.lockToken) > -1))) {
+ if (
+ options?.userId === l.owner.id &&
+ (!l.options || (options?.lockTokens?.length && options.lockTokens.indexOf(l.options.lockToken as string) > -1))
+ ) {
// Owner owns this lock (no davLock if the lock was created from api)
continue
}
@@ -217,7 +225,9 @@ export class FilesLockManager {
}
}
- convertLockToFileLockProps(lock: FileLock): FileLockProps {
+ convertLockToFileLockProps(lock: FileLock): FileLockProps
+ convertLockToFileLockProps(lock: null): null
+ convertLockToFileLockProps(lock: FileLock | null): FileLockProps | null {
if (!lock) return null
return {
owner: lock.owner,
@@ -253,7 +263,7 @@ export class FilesLockManager {
}
}
- private async searchKeyByToken(token: string): Promise<string> {
+ private async searchKeyByToken(token: string): Promise<string | null> {
const keys = await this.cache.keys(`${CACHE_LOCK_PREFIX}|token:${token}|*`)
if (!keys.length) {
return null
@@ -263,17 +273,15 @@ export class FilesLockManager {
return keys[0]
}
- private searchKeysByPath(path: string, props = '*', depth?: LOCK_DEPTH): Promise<string[]> {
+ private searchKeysByPath(path: string, props = '*', depth?: LOCK_DEPTH | null): Promise<string[]> {
return this.cache.keys(`${CACHE_LOCK_PREFIX}*${depth ? `|depth:${depth}` : ''}|path:${path}|${props}`)
}
- private genSuffixKey(dbFile: FileDBProps, options: { ignorePath?: boolean; depth?: LOCK_DEPTH; token?: string } = {}): string {
+ private genSuffixKey(dbFile: FileDBProps, options: { ignorePath?: boolean; depth?: LOCK_DEPTH; token?: string | null } = {}): string {
// return -> `depth:infinity|path:code/sync-in|spaceId:1` | `token:xxx|depth:0|path:code/sync-in.ts|ownerId:1`
// ignorePath -> `spaceId:1`
const suffixes = []
- for (const k of Object.keys(dbFile)
- .filter((k) => k !== files.inTrash.name && dbFile[k] !== null)
- .sort()) {
+ for (const k of (Object.keys(dbFile) as (keyof FileDBProps)[]).filter((k) => k !== files.inTrash.name && dbFile[k] !== null).sort()) {
if (k === files.path.name) {
if (options.ignorePath) {
continue
diff --git a/backend/src/applications/files/services/files-manager.service.spec.ts b/backend/src/applications/files/services/files-manager.service.spec.ts
index d6214974..1b9f94a4 100644
--- a/backend/src/applications/files/services/files-manager.service.spec.ts
+++ b/backend/src/applications/files/services/files-manager.service.spec.ts
@@ -5,7 +5,6 @@ import { lookup } from 'node:dns/promises'
import fs from 'node:fs/promises'
import path from 'node:path'
import { Readable } from 'node:stream'
-import { transformAndValidate } from '../../../common/functions.js'
import * as imageUtils from '../../../common/image.js'
import { configuration } from '../../../configuration/config.environment.js'
import { NotificationsManager } from '../../notifications/services/notifications-manager.service.js'
@@ -14,7 +13,7 @@ import * as spacesPathUtils from '../../spaces/utils/paths.js'
import * as spacesPermsUtils from '../../spaces/utils/permissions.js'
import { DEPTH } from '../../webdav/constants/webdav.js'
import { ACTION } from '../../../common/constants.js'
-import { DownloadFileDto } from '../dto/file-operations.dto.js'
+import { downloadFileSchema } from '../dto/file-operations.dto.js'
import { FileEvent, FileTaskEvent } from '../events/file-events.js'
import { FileError, SourceCleanupError } from '../models/file-error.js'
import { LockConflict } from '../models/file-lock-error.js'
@@ -1534,14 +1533,14 @@ describe(FilesManager.name, () => {
describe('downloadFromUrl', () => {
describe('dto validation', () => {
it('should accept http and https schemes', () => {
- expect(transformAndValidate(DownloadFileDto, { url: 'https://example.org/file.txt' }).url).toBe('https://example.org/file.txt')
- expect(transformAndValidate(DownloadFileDto, { url: 'http://example.org/file.txt' }).url).toBe('http://example.org/file.txt')
+ expect(downloadFileSchema.parse({ url: 'https://example.org/file.txt' }).url).toBe('https://example.org/file.txt')
+ expect(downloadFileSchema.parse({ url: 'http://example.org/file.txt' }).url).toBe('http://example.org/file.txt')
})
it('should reject non-http(s) schemes', () => {
const invalidUrls = ['ftp://example.org/file.txt', 'file:///tmp/file.txt', 'ws://example.org/file.txt']
for (const url of invalidUrls) {
- expect(() => transformAndValidate(DownloadFileDto, { url })).toThrow()
+ expect(() => downloadFileSchema.parse({ url })).toThrow()
}
})
})
diff --git a/backend/src/applications/files/services/files-manager.service.ts b/backend/src/applications/files/services/files-manager.service.ts
index bc0b6d46..a8e4c82d 100644
--- a/backend/src/applications/files/services/files-manager.service.ts
+++ b/backend/src/applications/files/services/files-manager.service.ts
@@ -1,3 +1,4 @@
+import { toErrorMessage } from '../../../common/errors.js'
import { HttpService } from '@nestjs/axios'
import { HttpStatus, Injectable, Logger } from '@nestjs/common'
import type { Dirent } from 'node:fs'
@@ -25,7 +26,7 @@ import { TAR_EXTENSION, TAR_GZ_EXTENSION, ZIP_EXTENSION } from '../constants/com
import { COMPRESSION_EXTENSION } from '../constants/files.js'
import { FILE_OPERATION } from '../constants/operations.js'
import { SAMPLE_DOCUMENT_EXTENSIONS, SAMPLE_PATH_WITHOUT_EXT } from '../constants/samples.js'
-import { CompressFileDto, DownloadFileDto } from '../dto/file-operations.dto.js'
+import type { CompressFileDto, DownloadFileDto } from '../dto/file-operations.dto.js'
import type { DeleteFileOptions } from '../interfaces/delete-file.interface.js'
import { FileDBProps } from '../interfaces/file-db-props.interface.js'
import { FileLock } from '../interfaces/file-lock.interface.js'
@@ -172,7 +173,7 @@ export class FilesManager {
try {
// todo: check file in db to update
// todo : versioning here
- let checksum: string
+ let checksum: string | undefined
if (options?.checksumAlg) {
checksum = await writeUploadFromStreamAndChecksum(options?.tmpPath || space.realPath, req.raw, options.checksumAlg, {
limiter: fileLimiter
@@ -193,14 +194,14 @@ export class FilesManager {
} catch (e) {
// cleanup tmp file
await removeFiles(options.tmpPath)
- this.logger.error({ tag: this.saveStream.name, msg: `unable to move ${options.tmpPath} -> ${space.realPath} : ${e}` })
+ this.logger.error({ tag: this.saveStream.name, msg: `unable to move ${options.tmpPath} -> ${space.realPath} : ${toErrorMessage(e)}` })
throw new FileError(HttpStatus.INTERNAL_SERVER_ERROR, 'Unable to move tmp file to dst file')
}
} else {
fileWritten = true
}
if (options?.checksumAlg) {
- return checksum
+ return checksum!
}
return fExists
} finally {
@@ -212,7 +213,7 @@ export class FilesManager {
try {
await this.filesLockManager.removeLock(fileLock.key)
} catch (e) {
- this.logger.warn({ tag: this.saveStream.name, msg: `Failed to remove lock ${fileLock.key}: ${e}` })
+ this.logger.warn({ tag: this.saveStream.name, msg: `Failed to remove lock ${fileLock.key}: ${toErrorMessage(e)}` })
}
}
}
@@ -270,8 +271,8 @@ export class FilesManager {
const dstDir = dirName(dstFile)
// For overwrite conflicts, defer destructive deletes until the upload stream is fully validated.
- let dstSpaceToDeleteBeforeMove: SpaceEnv | undefined
- let dstParentSpaceToDeleteBeforeMove: SpaceEnv | undefined
+ let dstSpaceToDeleteBeforeMove: SpaceEnv | null | undefined
+ let dstParentSpaceToDeleteBeforeMove: SpaceEnv | null | undefined
if (overwrite) {
// Prevent errors when an uploaded file would replace a directory with the same name
@@ -449,7 +450,10 @@ export class FilesManager {
try {
await makeDir(dirName(dstSpace.realPath), true)
} catch (e) {
- this.logger.error({ tag: this.copyMove.name, msg: `Cannot create parent directory for destination ${dstSpace.realPath} : ${e}` })
+ this.logger.error({
+ tag: this.copyMove.name,
+ msg: `Cannot create parent directory for destination ${dstSpace.realPath} : ${toErrorMessage(e)}`
+ })
throw new FileError(HttpStatus.INTERNAL_SERVER_ERROR, 'Cannot create parent directory for destination')
}
} else {
@@ -623,10 +627,12 @@ export class FilesManager {
}
// remove locks, these locks have already been checked in the `checkConflicts` function
if (isDir) {
- this.filesLockManager.removeChildLocks(user, space.dbFile).catch((e: Error) => this.logger.error({ tag: this.delete.name, msg: `${e}` }))
+ this.filesLockManager
+ .removeChildLocks(user, space.dbFile)
+ .catch((e: Error) => this.logger.error({ tag: this.delete.name, msg: toErrorMessage(e) }))
}
for (const lock of await this.filesLockManager.getLocksByPath(space.dbFile)) {
- this.filesLockManager.removeLock(lock.key).catch((e: Error) => this.logger.error({ tag: this.delete.name, msg: `${e}` }))
+ this.filesLockManager.removeLock(lock.key).catch((e: Error) => this.logger.error({ tag: this.delete.name, msg: toErrorMessage(e) }))
}
// Keep the database aligned with the completed filesystem operation before reporting a residual source.
if (trashDbFile) {
@@ -669,7 +675,7 @@ export class FilesManager {
await moveFiles(tmpPath, dstPath)
} catch (e) {
await removeFiles(tmpPath).catch((err: Error) =>
- this.logger.error({ tag: this.downloadFromUrl.name, msg: `unable to remove ${tmpPath} : ${err}` })
+ this.logger.error({ tag: this.downloadFromUrl.name, msg: `unable to remove ${tmpPath} : ${toErrorMessage(err)}` })
)
throw e
} finally {
@@ -691,8 +697,8 @@ export class FilesManager {
}
const srcPath = dirName(space.realPath)
const outputExtension = dto.extension === TAR_EXTENSION && dto.compression ? TAR_GZ_EXTENSION : dto.extension
- const archiveExt = dto.name.endsWith(`.${outputExtension}`) ? '' : `.${outputExtension}`
- const archiveName = `${dto.name}${archiveExt}`
+ const archiveExt = dto.name!.endsWith(`.${outputExtension}`) ? '' : `.${outputExtension}`
+ const archiveName = `${dto.name!}${archiveExt}`
const dstPath = dto.compressInDirectory ? await uniqueFilePathFromDir(path.join(srcPath, archiveName)) : path.join(user.tmpPath, archiveName)
const temporaryRoot = dto.compressInDirectory ? temporaryRootFromSpace(user, space) : user.tmpPath
const tmpPath = temporaryFilePath(temporaryRoot, archiveName, FILE_OPERATION.COMPRESS, space.task?.id)
@@ -727,7 +733,9 @@ export class FilesManager {
await moveFiles(tmpPath, dstPath)
}
} catch (e) {
- await removeFiles(tmpPath).catch((err: Error) => this.logger.error({ tag: this.compress.name, msg: `unable to remove ${tmpPath} : ${err}` }))
+ await removeFiles(tmpPath).catch((err: Error) =>
+ this.logger.error({ tag: this.compress.name, msg: `unable to remove ${tmpPath} : ${toErrorMessage(err)}` })
+ )
throw e
} finally {
if (fileLock) {
@@ -779,7 +787,9 @@ export class FilesManager {
}
await moveFiles(tmpPath, dstPath)
} catch (e) {
- await removeFiles(tmpPath).catch((err: Error) => this.logger.error({ tag: this.decompress.name, msg: `unable to remove ${tmpPath} : ${err}` }))
+ await removeFiles(tmpPath).catch((err: Error) =>
+ this.logger.error({ tag: this.decompress.name, msg: `unable to remove ${tmpPath} : ${toErrorMessage(err)}` })
+ )
throw e
} finally {
if (fileLock) await this.filesLockManager.removeLock(fileLock.key)
@@ -850,10 +860,10 @@ export class FilesManager {
url: dirName(space.url)
}
this.notificationsManager
- .create([lock.owner.id], notification, {
+ .create([lock.owner.id as number], notification, {
author: user
})
- .catch((e: Error) => this.logger.error({ tag: this.unlockRequest.name, msg: `${e}` }))
+ .catch((e: Error) => this.logger.error({ tag: this.unlockRequest.name, msg: toErrorMessage(e) }))
}
}
}
@@ -908,7 +918,7 @@ export class FilesManager {
if ((e as NodeJS.ErrnoException)?.code === 'ENOENT') continue
if (!continueOnError) throw e
failureCount++
- this.logger.warn({ tag: this.emptyTrash.name, msg: `unable to delete trash entry: ${e}` })
+ this.logger.warn({ tag: this.emptyTrash.name, msg: `unable to delete trash entry: ${toErrorMessage(e)}` })
}
}
diff --git a/backend/src/applications/files/services/files-methods.service.spec.ts b/backend/src/applications/files/services/files-methods.service.spec.ts
index 08430135..e22e2ed0 100644
--- a/backend/src/applications/files/services/files-methods.service.spec.ts
+++ b/backend/src/applications/files/services/files-methods.service.spec.ts
@@ -2,7 +2,6 @@ import { HttpException, HttpStatus } from '@nestjs/common'
import { Test, TestingModule } from '@nestjs/testing'
import path from 'node:path'
import type { Mock } from 'vitest'
-import { transformAndValidate } from '../../../common/functions.js'
import { Cache } from '../../../infrastructure/cache/cache.service.js'
import { DB_TOKEN_PROVIDER } from '../../../infrastructure/database/constants.js'
import { NotificationsManager } from '../../notifications/services/notifications-manager.service.js'
@@ -16,7 +15,7 @@ import { UserModel } from '../../users/models/user.model.js'
import { UsersQueries } from '../../users/services/users-queries.service.js'
import { generateUserTest } from '../../users/utils/test.js'
import { TAR_EXTENSION } from '../constants/compress.js'
-import { CompressFileDto, CopyMoveFileDto } from '../dto/file-operations.dto.js'
+import { type CompressFileDto, compressFileSchema, type CopyMoveFileDto, copyMoveFileSchema } from '../dto/file-operations.dto.js'
import { FilesManager } from './files-manager.service.js'
import { FilesMethods } from './files-methods.service.js'
import { FilesQuotaManager } from './files-quota-manager.service.js'
@@ -90,8 +89,8 @@ describe(FilesMethods.name, () => {
})
it('should avoid path traversal on CopyMove action', async () => {
- const copyMoveFileDto: CopyMoveFileDto = { dstDirectory: '../../../foo', dstName: '../bar/../' }
- expect(() => transformAndValidate(CopyMoveFileDto, copyMoveFileDto)).toThrow()
+ const copyMoveFileDto: CopyMoveFileDto = { dstDirectory: '../../../foo', dstName: '../bar/../', overwrite: false }
+ expect(() => copyMoveFileSchema.parse(copyMoveFileDto)).toThrow()
await expect((filesMethods as any).copyMove(userTest, spaceEnv, copyMoveFileDto, false)).rejects.toThrow(/is not valid/i)
})
@@ -100,10 +99,10 @@ describe(FilesMethods.name, () => {
name: '../../archive',
compressInDirectory: false,
compression: false,
- files: [{ name: '../../foo', rootAlias: undefined }],
+ files: [{ name: '../../foo', rootAlias: undefined } as any],
extension: TAR_EXTENSION
}
- expect(() => transformAndValidate(CompressFileDto, compressFileDto)).toThrow()
+ expect(() => compressFileSchema.parse(compressFileDto)).toThrow()
await expect(filesMethods.compress(userTest, spaceEnv, compressFileDto)).rejects.toThrow(/does not exist/i)
compressFileDto.files[0].path = '../../../bar/../'
await expect(filesMethods.compress(userTest, spaceEnv, compressFileDto)).rejects.toThrow(/is not valid/i)
diff --git a/backend/src/applications/files/services/files-methods.service.ts b/backend/src/applications/files/services/files-methods.service.ts
index 2da89290..efdf78b2 100644
--- a/backend/src/applications/files/services/files-methods.service.ts
+++ b/backend/src/applications/files/services/files-methods.service.ts
@@ -1,12 +1,13 @@
import { HttpException, HttpStatus, Injectable, Logger, StreamableFile } from '@nestjs/common'
import { FastifyReply } from 'fastify'
import path from 'node:path'
+import { toErrorMessage } from '../../../common/errors.js'
import { FastifySpaceRequest } from '../../spaces/interfaces/space-request.interface.js'
import { SpaceEnv } from '../../spaces/models/space-env.model.js'
import { SpacesManager } from '../../spaces/services/spaces-manager.service.js'
import { UserModel } from '../../users/models/user.model.js'
import { FILE_OPERATION } from '../constants/operations.js'
-import { CompressFileDto, CopyMoveFileDto, DownloadFileDto, MakeFileDto } from '../dto/file-operations.dto.js'
+import type { CompressFileDto, DownloadFileDto, MakeFileDto, ValidatedCopyMoveFileDto } from '../dto/file-operations.dto.js'
import type { CopyMoveFileResponse } from '../interfaces/copy-move-file.interface.js'
import { FileLockProps } from '../interfaces/file-props.interface.js'
import type { FileThumbnail } from '../interfaces/file-thumbnail.interface.js'
@@ -55,11 +56,11 @@ export class FilesMethods {
}
}
- copy(user: UserModel, space: SpaceEnv, copyMoveFileDto: CopyMoveFileDto, signal?: AbortSignal): Promise<CopyMoveFileResponse> {
+ copy(user: UserModel, space: SpaceEnv, copyMoveFileDto: ValidatedCopyMoveFileDto, signal?: AbortSignal): Promise<CopyMoveFileResponse> {
return this.copyMove(user, space, copyMoveFileDto, false, signal)
}
- move(user: UserModel, space: SpaceEnv, copyMoveFileDto: CopyMoveFileDto, signal?: AbortSignal): Promise<CopyMoveFileResponse> {
+ move(user: UserModel, space: SpaceEnv, copyMoveFileDto: ValidatedCopyMoveFileDto, signal?: AbortSignal): Promise<CopyMoveFileResponse> {
return this.copyMove(user, space, copyMoveFileDto, true, signal)
}
@@ -89,11 +90,11 @@ export class FilesMethods {
// handles the case where the file is an anchored file
let baseSpace: SpaceEnv
if (f.path) {
- baseSpace = await this.spacesManager.spaceEnv(user, f.path.split('/'))
+ baseSpace = (await this.spacesManager.spaceEnv(user, f.path.split('/')))!
f.path = baseSpace.realPath
} else {
if (f.rootAlias) {
- baseSpace = await this.spacesManager.spaceEnv(user, path.join(dirName(space.url), f.rootAlias).split('/'))
+ baseSpace = (await this.spacesManager.spaceEnv(user, path.join(dirName(space.url), f.rootAlias).split('/')))!
f.path = baseSpace.realPath
} else {
baseSpace = space
@@ -168,18 +169,21 @@ export class FilesMethods {
private async copyMove(
user: UserModel,
space: SpaceEnv,
- copyMoveFileDto: CopyMoveFileDto,
+ copyMoveFileDto: ValidatedCopyMoveFileDto,
isMove: boolean,
signal?: AbortSignal
): Promise<CopyMoveFileResponse> {
const dstUrl = path.join(copyMoveFileDto.dstDirectory, copyMoveFileDto.dstName || fileName(space.realPath))
- let dstSpace: SpaceEnv
+ let dstSpace: SpaceEnv | null | undefined
try {
dstSpace = await this.spacesManager.spaceEnv(user, dstUrl.split('/'))
- await this.filesManager.copyMove(user, space, dstSpace, isMove, copyMoveFileDto.overwrite, false, undefined, signal)
+ if (!dstSpace) {
+ throw new Error(`Destination space not found: ${dstUrl}`)
+ }
+ await this.filesManager.copyMove(user, space, dstSpace, isMove, copyMoveFileDto.overwrite ?? false, false, undefined, signal)
return { path: dirName(dstUrl), name: fileName(dstUrl), mime: getMimeType(dstSpace.realPath, await isPathIsDir(dstSpace.realPath)) }
} catch (e) {
- this.handleError(space, isMove ? FILE_OPERATION.MOVE : FILE_OPERATION.COPY, e, dstSpace, signal)
+ this.handleError(space, isMove ? FILE_OPERATION.MOVE : FILE_OPERATION.COPY, e, dstSpace ?? undefined, signal)
}
}
@@ -190,15 +194,15 @@ export class FilesMethods {
dstSpace?: SpaceEnv,
signal?: AbortSignal,
res?: FastifyReply
- ): void {
+ ): never {
if (signal && this.isCancellationError(error, signal)) {
throw signal.reason
}
this.logger.error({
tag: this.handleError.name,
- msg: `unable to ${action} ${space.url}${dstSpace?.url ? ` -> ${dstSpace.url}` : ''} : ${error}`
+ msg: `unable to ${action} ${space.url}${dstSpace?.url ? ` -> ${dstSpace.url}` : ''} : ${toErrorMessage(error)}`
})
- const normalizedError = error instanceof Error ? error : new Error(String(error))
+ const normalizedError = error instanceof Error ? error : new Error(toErrorMessage(error))
// Remove the last part to avoid exposing the path
const errorMsg = normalizedError.message.split(',')[0]
if (normalizedError instanceof LockConflict) {
diff --git a/backend/src/applications/files/services/files-queries.service.ts b/backend/src/applications/files/services/files-queries.service.ts
index d6655aa2..ae4088d0 100644
--- a/backend/src/applications/files/services/files-queries.service.ts
+++ b/backend/src/applications/files/services/files-queries.service.ts
@@ -1,5 +1,6 @@
+import { toErrorMessage } from '../../../common/errors.js'
import { HttpException, HttpStatus, Inject, Injectable, Logger } from '@nestjs/common'
-import { and, desc, eq, getTableColumns, inArray, isNotNull, isNull, or, SelectedFields, sql, SQL } from 'drizzle-orm'
+import { and, desc, eq, getTableColumns, inArray, isNotNull, isNull, or, sql, SQL } from 'drizzle-orm'
import { DB_TOKEN_PROVIDER } from '../../../infrastructure/database/constants.js'
import { type DBSchema } from '../../../infrastructure/database/interfaces/database.interface.js'
import { concatDistinctObjectsInArray, convertToWhere, dbCheckAffectedRows, dbGetInsertedId } from '../../../infrastructure/database/utils.js'
@@ -14,7 +15,7 @@ import { FILES_RECENTS_MAX_LIMIT } from '../constants/recents.js'
import { FileDBProps } from '../interfaces/file-db-props.interface.js'
import { FileProps } from '../interfaces/file-props.interface.js'
import type { FileRecent, FileRecentLocation, FileRecentUpdate } from '../schemas/file-recent.interface.js'
-import { File } from '../schemas/file.interface.js'
+import type { File } from '../schemas/file.interface.js'
import { filesFavorites } from '../schemas/files-favorites.schema.js'
import { filesRecents } from '../schemas/files-recents.schema.js'
import { childFilesMatch, childFilesReplacePath, childPathMatch, filePathSQL, files } from '../schemas/files.schema.js'
@@ -78,10 +79,10 @@ export class FilesQueries {
if (details?.favorites) {
q.leftJoin(filesFavorites, and(eq(filesFavorites.userId, userId), eq(filesFavorites.fileId, files.id)))
}
- return q
+ return q as Promise<FileProps[]>
}
- async getUserFile(userId: number, fileId: number): Promise<Pick<File, 'id' | 'path'>> {
+ async getUserFile(userId: number, fileId: number): Promise<Pick<File, 'id' | 'path'> | null> {
if (fileId > 0) {
const [fileInDB] = await this.db
.select({ id: files.id, path: filePathSQL(files) })
@@ -107,7 +108,8 @@ export class FilesQueries {
this.logger.warn({ tag: this.getOrCreateUserFile.name, msg: `file mismatch : ${JSON.stringify(searchFileInDB)} !== ${JSON.stringify(file)}` })
}
}
- return dbGetInsertedId(await this.db.insert(files).values({ ...file, id: undefined, ownerId: userId } as File))
+ const fileToInsert = { ...file, id: undefined, ownerId: userId } satisfies typeof files.$inferInsert
+ return dbGetInsertedId(await this.db.insert(files).values(fileToInsert))
}
async getOrCreateSpaceFile(fileId: number, file: FileProps, dbFile: FileDBProps, options: GetOrCreateSpaceFileOptions = {}): Promise<number> {
@@ -147,7 +149,8 @@ export class FilesQueries {
}
// `fileInDB` keeps the DB scope and uses the `FileProps` path/name.
- return dbGetInsertedId(await this.db.insert(files).values({ ...file, ...fileInDB, id: undefined } as File))
+ const fileToInsert = { ...file, ...fileInDB, id: undefined } satisfies typeof files.$inferInsert
+ return dbGetInsertedId(await this.db.insert(files).values(fileToInsert))
}
async getSpaceFileId(file: FileProps, dbFile: FileDBProps, options: { withDir?: boolean } = {}): Promise<number | undefined> {
@@ -169,7 +172,7 @@ export class FilesQueries {
try {
dbCheckAffectedRows(await this.db.update(files).set(file).where(eq(files.id, id)), 1)
} catch (e) {
- this.logger.error({ tag: this.updateFile.name, msg: `file (${id}) properties was not updated : ${e}` })
+ this.logger.error({ tag: this.updateFile.name, msg: `file (${id}) properties was not updated : ${toErrorMessage(e)}` })
}
}
@@ -274,7 +277,7 @@ export class FilesQueries {
dbFile.mime !== fsFile.mime
) {
this.logger.verbose({ tag: this.compareAndUpdateFileProps.name, msg: `${dbFile.path} (${dbFile.id})` })
- await this.updateFile(dbFile.id, {
+ await this.updateFile(dbFile.id!, {
isDir: fsFile.isDir,
size: fsFile.size,
ctime: fsFile.ctime,
@@ -305,14 +308,14 @@ export class FilesQueries {
mime: filesRecents.mime,
mtime: filesRecents.mtime,
displayRootName: sql<string>`COALESCE(${spaces.name}, ${shares.name})`.as('displayRootName')
- } satisfies FileRecent | SelectedFields<any, any>)
+ } satisfies Record<keyof FileRecent, any>)
.from(filesRecents)
.leftJoin(spaces, eq(spaces.id, filesRecents.spaceId))
.leftJoin(shares, eq(shares.id, filesRecents.shareId))
.where(or(...where))
.groupBy(filesRecents.id)
.orderBy(desc(filesRecents.mtime))
- .limit(recentsLimit)
+ .limit(recentsLimit) as Promise<FileRecent[]>
}
getRecentsFromLocation(location: FileRecentLocation): Promise<FileRecent[]> {
@@ -320,7 +323,7 @@ export class FilesQueries {
return this.db
.select(getTableColumns(filesRecents))
.from(filesRecents)
- .where(and(...where))
+ .where(and(...where)) as Promise<FileRecent[]>
}
async deleteRecents(locations: FileRecentLocation[]): Promise<void> {
@@ -349,7 +352,7 @@ export class FilesQueries {
.delete(filesRecents)
.where(and(...where, or(...batch.map((sourcePath) => childPathMatch(filePathSQL(filesRecents), sourcePath)))))
} catch (e) {
- this.logger.error({ tag: this.deleteRecents.name, msg: `${e}` })
+ this.logger.error({ tag: this.deleteRecents.name, msg: toErrorMessage(e) })
}
}
}
@@ -379,7 +382,7 @@ export class FilesQueries {
try {
await this.db.insert(filesRecents).values(add)
} catch (e) {
- this.logger.error({ tag: this.updateRecents.name, msg: `${e}` })
+ this.logger.error({ tag: this.updateRecents.name, msg: toErrorMessage(e) })
}
}
// update
@@ -391,7 +394,7 @@ export class FilesQueries {
.set(props)
.where(and(...where, eq(filesRecents.id, id)))
} catch (e) {
- this.logger.error({ tag: this.updateRecents.name, msg: `${e}` })
+ this.logger.error({ tag: this.updateRecents.name, msg: toErrorMessage(e) })
}
}
}
@@ -400,7 +403,7 @@ export class FilesQueries {
try {
await this.db.delete(filesRecents).where(and(...where, inArray(filesRecents.id, remove)))
} catch (e) {
- this.logger.error({ tag: this.updateRecents.name, msg: `${e}` })
+ this.logger.error({ tag: this.updateRecents.name, msg: toErrorMessage(e) })
}
}
}
diff --git a/backend/src/applications/files/services/files-quota-manager.service.spec.ts b/backend/src/applications/files/services/files-quota-manager.service.spec.ts
index 04bf8cb6..6cd15d8c 100644
--- a/backend/src/applications/files/services/files-quota-manager.service.spec.ts
+++ b/backend/src/applications/files/services/files-quota-manager.service.spec.ts
@@ -126,9 +126,9 @@ describe(FilesQuotaManager.name, () => {
'event-update-quota-share-3',
'event-update-quota-unknown-4'
])
- const userSpy = vi.spyOn(service, 'updatePersonalSpacesQuota').mockResolvedValueOnce(undefined)
- const spaceSpy = vi.spyOn(service, 'updateSpacesQuota').mockResolvedValueOnce(undefined)
- const shareSpy = vi.spyOn(service, 'updateSharesExternalPathQuota').mockResolvedValueOnce(undefined)
+ const userSpy = vi.spyOn(service, 'updatePersonalSpacesQuota').mockResolvedValueOnce(undefined as never)
+ const spaceSpy = vi.spyOn(service, 'updateSpacesQuota').mockResolvedValueOnce(undefined as never)
+ const shareSpy = vi.spyOn(service, 'updateSharesExternalPathQuota').mockResolvedValueOnce(undefined as never)
await service.updateStorageUsageEntries()
diff --git a/backend/src/applications/files/services/files-quota-manager.service.ts b/backend/src/applications/files/services/files-quota-manager.service.ts
index a5621623..3fb54875 100644
--- a/backend/src/applications/files/services/files-quota-manager.service.ts
+++ b/backend/src/applications/files/services/files-quota-manager.service.ts
@@ -1,8 +1,8 @@
+import { toErrorMessage } from '../../../common/errors.js'
import { Injectable, Logger } from '@nestjs/common'
import { SpacesQueries } from '../../spaces/services/spaces-queries.service.js'
import { UsersQueries } from '../../users/services/users-queries.service.js'
import type { StorageQuota } from '../../../common/interfaces.js'
-import type { User } from '../../users/schemas/user.interface.js'
import { eq, lte } from 'drizzle-orm'
import { users } from '../../users/schemas/users.schema.js'
import { USER_ROLE } from '../../users/constants/user.js'
@@ -72,35 +72,35 @@ export class FilesQuotaManager {
this.logger.warn({ tag: this.updateStorageUsageEntries.name, msg: `Unknown type: ${repository}` })
}
} catch (e) {
- this.logger.error({ tag: this.updateStorageUsageEntries.name, msg: `${e}` })
+ this.logger.error({ tag: this.updateStorageUsageEntries.name, msg: toErrorMessage(e) })
} finally {
this.spacesQueries.cache
.del(k)
- .catch((e) => this.logger.warn({ tag: this.updateStorageUsageEntries.name, msg: `Unable to clean key: ${k} - ${e}` }))
+ .catch((e) => this.logger.warn({ tag: this.updateStorageUsageEntries.name, msg: `Unable to clean key: ${k} - ${toErrorMessage(e)}` }))
}
}
}
- async updateStorageQuota(id: number, type: FILE_REPOSITORY, quota: number) {
+ async updateStorageQuota(id: number, type: FILE_REPOSITORY, quota: number | null) {
const cacheKey = genQuotaCacheKey(id, type)
const entryQuota: StorageQuota = await this.spacesQueries.cache.get(cacheKey)
if (entryQuota && entryQuota.storageUsage !== undefined) {
this.spacesQueries.cache
.set(cacheKey, { storageUsage: entryQuota.storageUsage, storageQuota: quota }, CACHE_QUOTA_TTL)
- .catch((e: Error) => this.logger.error({ tag: this.updateStorageQuota.name, msg: `type *${type}* (${id}) - ${e}` }))
+ .catch((e: Error) => this.logger.error({ tag: this.updateStorageQuota.name, msg: `type *${type}* (${id}) - ${toErrorMessage(e)}` }))
} else {
// store event update for later propagation
const updateCacheKey = genQuotaCacheKey(id, type, true)
this.spacesQueries.cache
.set(updateCacheKey, true, CACHE_QUOTA_TTL)
- .catch((e: Error) => this.logger.error({ tag: this.updateStorageQuota.name, msg: `type *${type}* (${id}) event - ${e}` }))
+ .catch((e: Error) => this.logger.error({ tag: this.updateStorageQuota.name, msg: `type *${type}* (${id}) event - ${toErrorMessage(e)}` }))
}
}
async updatePersonalSpacesQuota(): Promise<void>
async updatePersonalSpacesQuota(userId: number): Promise<StorageQuota>
async updatePersonalSpacesQuota(userId?: number): Promise<void | StorageQuota> {
- const props: (keyof User)[] = ['id', 'login', 'storageUsage', 'storageQuota']
+ const props: ('id' | 'login' | 'storageUsage' | 'storageQuota')[] = ['id', 'login', 'storageUsage', 'storageQuota']
for (const user of await this.usersQueries.selectUsers(props, [lte(users.role, USER_ROLE.USER), ...(userId ? [eq(users.id, userId)] : [])])) {
const userPath = UserModel.getHomePath(user.login)
if (!(await isPathExists(userPath))) {
@@ -109,12 +109,17 @@ export class FilesQuotaManager {
}
const [size, errors] = await dirSize(userPath)
for (const [path, error] of Object.entries(errors)) {
- this.logger.warn({ tag: this.updatePersonalSpacesQuota.name, msg: `unable to get size for *${user.login}* on ${path} : ${error}` })
+ this.logger.warn({
+ tag: this.updatePersonalSpacesQuota.name,
+ msg: `unable to get size for *${user.login}* on ${path} : ${toErrorMessage(error)}`
+ })
}
const spaceQuota: StorageQuota = { storageUsage: size, storageQuota: user.storageQuota }
this.spacesQueries.cache
.set(genQuotaCacheKey(user.id, FILE_REPOSITORY.USER), spaceQuota, CACHE_QUOTA_TTL)
- .catch((e: Error) => this.logger.error({ tag: this.updatePersonalSpacesQuota.name, msg: `user *${user.login}* (${user.id}) : ${e}` }))
+ .catch((e: Error) =>
+ this.logger.error({ tag: this.updatePersonalSpacesQuota.name, msg: `user *${user.login}* (${user.id}) : ${toErrorMessage(e)}` })
+ )
if (user.storageUsage !== spaceQuota.storageUsage) {
this.usersQueries.updateUserOrGuest(user.id, { storageUsage: spaceQuota.storageUsage }).then(
(updated: boolean) =>
@@ -145,13 +150,18 @@ export class FilesQuotaManager {
const [rPathSize, errors] = await dirSize(rPath)
size += rPathSize
for (const [path, error] of Object.entries(errors)) {
- this.logger.warn({ tag: this.updateSpacesQuota.name, msg: `unable to get size for *${space.alias}* on ${path} : ${error}` })
+ this.logger.warn({
+ tag: this.updateSpacesQuota.name,
+ msg: `unable to get size for *${space.alias}* on ${path} : ${toErrorMessage(error)}`
+ })
}
}
const spaceQuota: StorageQuota = { storageUsage: size, storageQuota: space.storageQuota }
this.spacesQueries.cache
.set(genQuotaCacheKey(space.id, FILE_REPOSITORY.SPACE), spaceQuota, CACHE_QUOTA_TTL)
- .catch((e: Error) => this.logger.error({ tag: this.updateSpacesQuota.name, msg: `space *${space.alias}* (${space.id}) : ${e}` }))
+ .catch((e: Error) =>
+ this.logger.error({ tag: this.updateSpacesQuota.name, msg: `space *${space.alias}* (${space.id}) : ${toErrorMessage(e)}` })
+ )
if (space.storageUsage !== spaceQuota.storageUsage) {
this.spacesQueries.updateSpace(space.id, { storageUsage: spaceQuota.storageUsage }).then(
(updated: boolean) =>
@@ -178,12 +188,17 @@ export class FilesQuotaManager {
}
const [size, errors] = await dirSize(share.externalPath)
for (const [path, error] of Object.entries(errors)) {
- this.logger.warn({ tag: this.updateSharesExternalPathQuota.name, msg: `unable to get size for *${share.alias}* on ${path} : ${error}` })
+ this.logger.warn({
+ tag: this.updateSharesExternalPathQuota.name,
+ msg: `unable to get size for *${share.alias}* on ${path} : ${toErrorMessage(error)}`
+ })
}
const shareQuota: StorageQuota = { storageUsage: size, storageQuota: share.storageQuota }
this.sharesQueries.cache
.set(genQuotaCacheKey(share.id, FILE_REPOSITORY.SHARE), shareQuota, CACHE_QUOTA_TTL)
- .catch((e: Error) => this.logger.error({ tag: this.updateSharesExternalPathQuota.name, msg: `share *${share.alias}* (${share.id}) : ${e}` }))
+ .catch((e: Error) =>
+ this.logger.error({ tag: this.updateSharesExternalPathQuota.name, msg: `share *${share.alias}* (${share.id}) : ${toErrorMessage(e)}` })
+ )
if (share.storageUsage !== shareQuota.storageUsage) {
this.sharesQueries.updateShare(share.id, { storageUsage: shareQuota.storageUsage }).then(
(updated: boolean) =>
diff --git a/backend/src/applications/files/services/files-recents.service.ts b/backend/src/applications/files/services/files-recents.service.ts
index 99e1d8e6..51b533b2 100644
--- a/backend/src/applications/files/services/files-recents.service.ts
+++ b/backend/src/applications/files/services/files-recents.service.ts
@@ -78,13 +78,13 @@ export class FilesRecents {
const recents = new Map<number, FileRecent>()
for (const file of files) {
if (!this.isRecentFile(file, minMtime)) continue
- recents.set(file.id, {
- id: file.id,
+ recents.set(file.id!, {
+ id: file.id!,
name: file.name,
mtime: file.mtime,
mime: file.mime,
...location,
- ...(space.inSharesList && { shareId: file.root.id })
+ ...(space.inSharesList && { shareId: file.root!.id })
} as FileRecent)
}
return [...recents.values()]
@@ -154,7 +154,7 @@ export class FilesRecents {
private getSnapshotLocation(user: UserModel, space: SpaceEnv, logicalPath: string, files: FileProps[]): FileRecentLocation {
if (space.inSharesList) {
- return { path: logicalPath, shareId: files.map((file) => file.root.id) }
+ return { path: logicalPath, shareId: files.map((file) => file.root!.id) }
}
return { ...this.getRepositoryLocation(user.id, space.id, space.inPersonalSpace, space.inSharesRepository), path: logicalPath }
}
diff --git a/backend/src/applications/files/services/files-scheduler.service.ts b/backend/src/applications/files/services/files-scheduler.service.ts
index 4741e68f..e08ec183 100644
--- a/backend/src/applications/files/services/files-scheduler.service.ts
+++ b/backend/src/applications/files/services/files-scheduler.service.ts
@@ -1,3 +1,4 @@
+import { toErrorMessage } from '../../../common/errors.js'
import { Inject, Injectable, Logger } from '@nestjs/common'
import { Cron, CronExpression, Timeout } from '@nestjs/schedule'
import { isNotNull, sql } from 'drizzle-orm'
@@ -58,7 +59,7 @@ export class FilesScheduler {
await this.updateQuotas()
await this.cleanupTrashFiles()
} catch (e) {
- this.logger.error({ tag: this.onStartup.name, msg: `${e}` })
+ this.logger.error({ tag: this.onStartup.name, msg: toErrorMessage(e) })
}
}
@@ -67,7 +68,7 @@ export class FilesScheduler {
try {
await this.indexContentFiles()
} catch (e) {
- this.logger.error({ tag: this.afterStartup.name, msg: `${e}` })
+ this.logger.error({ tag: this.afterStartup.name, msg: toErrorMessage(e) })
}
}
@@ -78,7 +79,7 @@ export class FilesScheduler {
try {
await this.filesQuotaManager.updateStorageUsageEntries()
} catch (e) {
- this.logger.error({ tag: this.updateStorageAndIndexing.name, msg: `update quota error: ${e}` })
+ this.logger.error({ tag: this.updateStorageAndIndexing.name, msg: `update quota error: ${toErrorMessage(e)}` })
} finally {
this.isQuotaUpdateEntriesIsRunning = false
}
@@ -86,7 +87,7 @@ export class FilesScheduler {
try {
await this.filesContentIndexer.processIndexingQueue()
} catch (e) {
- this.logger.error({ tag: this.updateStorageAndIndexing.name, msg: `update indexing error: ${e}` })
+ this.logger.error({ tag: this.updateStorageAndIndexing.name, msg: `update indexing error: ${toErrorMessage(e)}` })
}
}
@@ -97,7 +98,7 @@ export class FilesScheduler {
try {
await this.filesTrashRetention.indexAndCleanTrash()
} catch (e) {
- this.logger.error({ tag: this.cleanupTrashFiles.name, msg: `${e}` })
+ this.logger.error({ tag: this.cleanupTrashFiles.name, msg: toErrorMessage(e) })
} finally {
this.isTrashCleanupRunning = false
}
@@ -149,7 +150,7 @@ export class FilesScheduler {
await this.discoverTemporaryUsersRoot(path.join(externalRoot, TEMPORARY_PATH.STORAGE, TEMPORARY_PATH.ACTORS), temporaryDirectories)
}
} catch (e) {
- this.logger.error({ tag: this.cleanupUserTmpFiles.name, msg: `${e}` })
+ this.logger.error({ tag: this.cleanupUserTmpFiles.name, msg: toErrorMessage(e) })
}
for (const [userId, directories] of temporaryDirectories) {
await this.cleanupTemporaryDirectories(userId, [...directories.values()], expiration)
@@ -178,7 +179,7 @@ export class FilesScheduler {
nbCleared += r.affectedRows
}
} catch (e) {
- this.logger.error({ tag: this.clearRecentFiles.name, msg: `${e}` })
+ this.logger.error({ tag: this.clearRecentFiles.name, msg: toErrorMessage(e) })
}
this.logger.log({ tag: this.clearRecentFiles.name, msg: `${nbCleared} records cleared` })
}
@@ -224,7 +225,7 @@ export class FilesScheduler {
this.logger.log({ tag: this.deleteOrphanFiles.name, msg: `files: ${r.affectedRows}` })
})
} catch (e) {
- this.logger.log({ tag: this.deleteOrphanFiles.name, msg: `${e}` })
+ this.logger.log({ tag: this.deleteOrphanFiles.name, msg: toErrorMessage(e) })
}
this.logger.log({ tag: this.deleteOrphanFiles.name, msg: `END` })
}
@@ -237,21 +238,21 @@ export class FilesScheduler {
try {
await this.filesQuotaManager.updatePersonalSpacesQuota()
} catch (e) {
- this.logger.error({ tag: this.updateQuotas.name, msg: `Personals - ${e}` })
+ this.logger.error({ tag: this.updateQuotas.name, msg: `Personals - ${toErrorMessage(e)}` })
}
this.logger.log({ tag: this.updateQuotas.name, msg: 'Personals - END' })
this.logger.log({ tag: this.updateQuotas.name, msg: 'Spaces - START' })
try {
await this.filesQuotaManager.updateSpacesQuota()
} catch (e) {
- this.logger.error({ tag: this.updateQuotas.name, msg: `Spaces - ${e}` })
+ this.logger.error({ tag: this.updateQuotas.name, msg: `Spaces - ${toErrorMessage(e)}` })
}
this.logger.log({ tag: this.updateQuotas.name, msg: 'Spaces - END' })
this.logger.log({ tag: this.updateQuotas.name, msg: 'Share External Paths - START' })
try {
await this.filesQuotaManager.updateSharesExternalPathQuota()
} catch (e) {
- this.logger.error({ tag: this.updateQuotas.name, msg: `Share External Paths - ${e}` })
+ this.logger.error({ tag: this.updateQuotas.name, msg: `Share External Paths - ${toErrorMessage(e)}` })
}
this.logger.log({ tag: this.updateQuotas.name, msg: 'Share External Paths - END' })
this.isQuotaUpdateIsRunning = false
@@ -284,7 +285,7 @@ export class FilesScheduler {
this.registerTemporaryDirectory(temporaryDirectories, userId, path.join(usersTmpPath, entry.name))
}
} catch (e) {
- this.logger.error({ tag: this.cleanupUserTmpFiles.name, msg: `unable to browse ${usersTmpPath} : ${e}` })
+ this.logger.error({ tag: this.cleanupUserTmpFiles.name, msg: `unable to browse ${usersTmpPath} : ${toErrorMessage(e)}` })
}
}
@@ -295,7 +296,7 @@ export class FilesScheduler {
const candidates = directory.includeLegacyEntries ? fileNames : fileNames.filter((fileName) => fileName.startsWith(TEMPORARY_FILE_PREFIX))
return candidates.length === 0 ? undefined : { fileNames: candidates, path: directory.path }
} catch (e) {
- this.logger.error({ tag: this.cleanupUserTmpFiles.name, msg: `unable to browse ${directory.path} : ${e}` })
+ this.logger.error({ tag: this.cleanupUserTmpFiles.name, msg: `unable to browse ${directory.path} : ${toErrorMessage(e)}` })
}
}
@@ -313,7 +314,7 @@ export class FilesScheduler {
// snapshots guarantees that concurrent entries are either protected or left for the next pass.
protectedPrefixes = await this.taskPrefixes(userId)
} catch (e) {
- this.logger.error({ tag: this.cleanupUserTmpFiles.name, msg: `unable to resolve temporary files for user ${userId} : ${e}` })
+ this.logger.error({ tag: this.cleanupUserTmpFiles.name, msg: `unable to resolve temporary files for user ${userId} : ${toErrorMessage(e)}` })
return
}
for (const snapshot of snapshots) {
@@ -336,7 +337,7 @@ export class FilesScheduler {
await removeFiles(rPath)
}
} catch (e) {
- this.logger.error({ tag: this.cleanupUserTmpFiles.name, msg: `unable to remove ${rPath} : ${e}` })
+ this.logger.error({ tag: this.cleanupUserTmpFiles.name, msg: `unable to remove ${rPath} : ${toErrorMessage(e)}` })
}
}
@@ -375,7 +376,7 @@ export class FilesScheduler {
msg: `${nb} tasks cleaned, ${nbCancellationRequests} cancellation requests cleared, ${nbUserTaskCounters} user task counters cleared`
})
} catch (e) {
- this.logger.error({ tag: this.cleanupInterruptedTasks.name, msg: `${e}` })
+ this.logger.error({ tag: this.cleanupInterruptedTasks.name, msg: toErrorMessage(e) })
}
}
diff --git a/backend/src/applications/files/services/files-search-manager.service.ts b/backend/src/applications/files/services/files-search-manager.service.ts
index 480e4b0d..6f1e21fd 100644
--- a/backend/src/applications/files/services/files-search-manager.service.ts
+++ b/backend/src/applications/files/services/files-search-manager.service.ts
@@ -2,12 +2,14 @@ import { HttpException, HttpStatus, Injectable, Logger } from '@nestjs/common'
import fs from 'fs/promises'
import { Stats } from 'node:fs'
import path from 'node:path'
+import { toErrorMessage } from '../../../common/errors.js'
+import { escapePath } from '../../../common/functions.js'
import { configuration } from '../../../configuration/config.environment.js'
import { SharesQueries } from '../../shares/services/shares-queries.service.js'
import { SPACE_REPOSITORY } from '../../spaces/constants/spaces.js'
import { SpacesQueries } from '../../spaces/services/spaces-queries.service.js'
import { UserModel } from '../../users/models/user.model.js'
-import { SearchFilesDto } from '../dto/file-operations.dto.js'
+import type { ValidatedSearchFilesDto } from '../dto/file-operations.dto.js'
import { FilesContentStore } from '../models/files-content-store.js'
import { FileContent } from '../schemas/file-content.interface.js'
import { dirName, fileName, getMimeType, isInternalTemporaryEntry } from '../utils/files.js'
@@ -15,7 +17,6 @@ import { genRegexPositiveAndNegativeTerms, normalizeSearchLimit } from '../utils
import { FilesContentParser } from './files-content-parser.service.js'
import { FILE_REPOSITORY } from '../constants/operations.js'
import { genIndexingKey } from '../utils/indexing.js'
-import { escapePath } from '../../../common/functions.js'
@Injectable()
export class FilesSearchManager {
@@ -28,7 +29,7 @@ export class FilesSearchManager {
private readonly sharesQueries: SharesQueries
) {}
- async search(user: UserModel, search: SearchFilesDto): Promise<FileContent[]> {
+ async search(user: UserModel, search: ValidatedSearchFilesDto): Promise<FileContent[]> {
if (search.fullText && !configuration.applications.files.contentIndexing.enabled) {
throw new HttpException('Full-text search is disabled', HttpStatus.BAD_REQUEST)
}
@@ -57,7 +58,7 @@ export class FilesSearchManager {
try {
return await this.filesIndexer.searchRecords(indexNames, search, limit)
} catch (e) {
- const error = e instanceof Error ? e : new Error(`${e}`)
+ const error = e instanceof Error ? e : new Error(toErrorMessage(e))
this.logger.error({ tag: this.searchFullText.name, msg: `${JSON.stringify(indexNames)} - ${search}`, err: error })
let msg: string
if (/Invalid regular expression/.test(error.message)) {
@@ -109,11 +110,11 @@ export class FilesSearchManager {
}
}
} catch (e) {
- this.logger.warn({ tag: this.parseFileNames.name, msg: `unable to parse: ${dir} (${e})` })
+ this.logger.warn({ tag: this.parseFileNames.name, msg: `unable to parse: ${dir} (${toErrorMessage(e)})` })
}
}
- private async analyzeFile(realPath: string, pathPrefix: string, regexBasePath: RegExp, regexpTerms: RegExp): Promise<FileContent> {
+ private async analyzeFile(realPath: string, pathPrefix: string, regexBasePath: RegExp, regexpTerms: RegExp): Promise<FileContent | null> {
const filePath = realPath.replace(regexBasePath, '')
if (!regexpTerms.test(filePath)) return null
const stats: Stats = await fs.stat(realPath)
diff --git a/backend/src/applications/files/services/files-trash-retention.service.ts b/backend/src/applications/files/services/files-trash-retention.service.ts
index 8ef14392..f93b8b75 100644
--- a/backend/src/applications/files/services/files-trash-retention.service.ts
+++ b/backend/src/applications/files/services/files-trash-retention.service.ts
@@ -1,3 +1,4 @@
+import { toErrorMessage } from '../../../common/errors.js'
import { Inject, Injectable, Logger } from '@nestjs/common'
import { DB_TOKEN_PROVIDER } from '../../../infrastructure/database/constants.js'
import { type DBSchema } from '../../../infrastructure/database/interfaces/database.interface.js'
@@ -74,7 +75,7 @@ export class FilesTrashRetention {
if (scannedRecords === 0 && indexedRecords === 0 && deletedRecords === 0 && expiredRecords.deletedRecords === 0) {
this.dropTable(tableName).catch((e: Error) =>
- this.logger.error({ tag: this.indexAndCleanTrash.name, msg: `${tableName} - unable to drop table : ${e}` })
+ this.logger.error({ tag: this.indexAndCleanTrash.name, msg: `${tableName} - unable to drop table : ${toErrorMessage(e)}` })
)
this.logger.verbose({ tag: this.indexAndCleanTrash.name, msg: `${tableName} - no data: index not stored` })
} else if (indexedRecords === 0 && totalErrorRecords === 0 && deletedRecords === 0 && expiredRecords.deletedRecords === 0) {
@@ -189,7 +190,7 @@ export class FilesTrashRetention {
}
}
} catch (e) {
- this.logger.warn({ tag: this.parseFiles.name, msg: `${context.tableName} - unable to parse: ${dir} - ${e}` })
+ this.logger.warn({ tag: this.parseFiles.name, msg: `${context.tableName} - unable to parse: ${dir} - ${toErrorMessage(e)}` })
}
}
@@ -198,7 +199,7 @@ export class FilesTrashRetention {
try {
stats = await fs.lstat(realPath)
} catch (e) {
- this.logger.warn({ tag: this.analyzeFile.name, msg: `unable to stats: ${realPath} - ${e}` })
+ this.logger.warn({ tag: this.analyzeFile.name, msg: `unable to stats: ${realPath} - ${toErrorMessage(e)}` })
return null
}
const filePath = realPath.replace(context.regexBasePath, '')
@@ -219,7 +220,7 @@ export class FilesTrashRetention {
await this.db.execute(createTableFilesTrash(tableName))
return true
} catch (e) {
- this.logger.error({ tag: this.createTable.name, msg: `${tableName} : ${e}` })
+ this.logger.error({ tag: this.createTable.name, msg: `${tableName} : ${toErrorMessage(e)}` })
return false
}
}
@@ -229,7 +230,7 @@ export class FilesTrashRetention {
await this.db.execute(sql`DROP TABLE IF EXISTS ${sql.identifier(tableName)} `)
return true
} catch (e) {
- this.logger.error({ tag: this.dropTable.name, msg: `${tableName} : ${e}` })
+ this.logger.error({ tag: this.dropTable.name, msg: `${tableName} : ${toErrorMessage(e)}` })
return false
}
}
@@ -250,7 +251,7 @@ export class FilesTrashRetention {
await this.db.execute(sql`UPDATE ${sql.identifier(tableName)} SET seen_run_id = ${runId} WHERE id IN (${idsSqlList(ids)})`)
return true
} catch (e) {
- this.logger.error({ tag: this.markRecordsSeen.name, msg: `${tableName} : ${e}` })
+ this.logger.error({ tag: this.markRecordsSeen.name, msg: `${tableName} : ${toErrorMessage(e)}` })
}
return false
}
@@ -268,7 +269,7 @@ export class FilesTrashRetention {
`)
return true
} catch (e) {
- this.logger.error({ tag: this.insertRecord.name, msg: `${tableName} : ${e}` })
+ this.logger.error({ tag: this.insertRecord.name, msg: `${tableName} : ${toErrorMessage(e)}` })
}
return false
}
@@ -278,7 +279,7 @@ export class FilesTrashRetention {
const [r] = await this.db.execute(sql`DELETE FROM ${sql.identifier(tableName)} WHERE seen_run_id IS NULL OR seen_run_id <> ${runId}`)
return r.affectedRows ?? 0
} catch (e) {
- this.logger.error({ tag: this.deleteUnseenRecords.name, msg: `${tableName} : ${e}` })
+ this.logger.error({ tag: this.deleteUnseenRecords.name, msg: `${tableName} : ${toErrorMessage(e)}` })
}
return null
}
@@ -379,7 +380,7 @@ export class FilesTrashRetention {
}
return r.affectedRows ?? 0
} catch (e) {
- this.logger.error({ tag: this.deleteRecordsByIds.name, msg: `${tableName} : ${e}` })
+ this.logger.error({ tag: this.deleteRecordsByIds.name, msg: `${tableName} : ${toErrorMessage(e)}` })
}
return null
}
@@ -391,7 +392,7 @@ export class FilesTrashRetention {
await removeFiles(realPath)
return true
} catch (e) {
- this.logger.error({ tag: this.deleteTrashRecordFile.name, msg: `${realBasePath}/${ft.path} : ${e}` })
+ this.logger.error({ tag: this.deleteTrashRecordFile.name, msg: `${realBasePath}/${ft.path} : ${toErrorMessage(e)}` })
}
return false
}
diff --git a/backend/src/applications/files/services/tasks/files-tasks-manager.service.spec.ts b/backend/src/applications/files/services/tasks/files-tasks-manager.service.spec.ts
index b88dd4e6..33785487 100644
--- a/backend/src/applications/files/services/tasks/files-tasks-manager.service.spec.ts
+++ b/backend/src/applications/files/services/tasks/files-tasks-manager.service.spec.ts
@@ -8,6 +8,7 @@ import { FileTaskEvent } from '../../events/file-events.js'
import { SendFile } from '../../utils/send-file.js'
import { FILE_OPERATION } from '../../constants/operations.js'
import { CACHE_TASK_CANCEL_PREFIX, CACHE_TASK_PREFIX, CACHE_TASK_TTL, CACHE_TASK_USER_PREFIX } from '../../constants/cache.js'
+import { FileError } from '../../models/file-error.js'
import { FileTaskStatus } from '../../models/file-task.js'
import { FilesMethods } from '../files-methods.service.js'
import { FilesTasksManager } from './files-tasks-manager.service.js'
@@ -141,7 +142,7 @@ describe(FilesTasksManager.name, () => {
it('should not overlap watcher updates', async () => {
vi.useFakeTimers()
try {
- let finishUpdate: () => void
+ let finishUpdate!: () => void
const update = vi.fn(
() =>
new Promise<void>((resolve) => {
@@ -238,8 +239,8 @@ describe(FilesTasksManager.name, () => {
status: FileTaskStatus.PENDING,
props: { size: 10 }
})
- let releaseGet: () => void
- let notifyGetStarted: () => void
+ let releaseGet!: () => void
+ let notifyGetStarted!: () => void
const getStarted = new Promise<void>((resolve) => {
notifyGetStarted = resolve
})
@@ -653,7 +654,7 @@ describe(FilesTasksManager.name, () => {
status: FileTaskStatus.SUCCESS,
props: { compressInDirectory: false }
})
- vi.spyOn(SendFile.prototype, 'checks').mockRejectedValueOnce({ message: 'Location not found', httpCode: 404 } as any)
+ vi.spyOn(SendFile.prototype, 'checks').mockRejectedValueOnce(new FileError(HttpStatus.NOT_FOUND, 'Location not found'))
const downloadPromise = filesTasksManager.downloadArchive({ id: 50, tmpPath: '/tmp' } as any, 'task-ok', {} as any, {} as any)
await expect(downloadPromise).rejects.toThrow(HttpException)
diff --git a/backend/src/applications/files/services/tasks/files-tasks-manager.service.ts b/backend/src/applications/files/services/tasks/files-tasks-manager.service.ts
index 745e72c0..117fb2a2 100644
--- a/backend/src/applications/files/services/tasks/files-tasks-manager.service.ts
+++ b/backend/src/applications/files/services/tasks/files-tasks-manager.service.ts
@@ -3,6 +3,7 @@ import { FastifyReply } from 'fastify'
import crypto from 'node:crypto'
import path from 'node:path'
import { FastifyAuthenticatedRequest } from '../../../../authentication/interfaces/auth-request.interface.js'
+import { toErrorMessage } from '../../../../common/errors.js'
import { currentTimeStamp } from '../../../../common/shared.js'
import { Cache } from '../../../../infrastructure/cache/cache.service.js'
import { SpaceEnv } from '../../../spaces/models/space-env.model.js'
@@ -11,10 +12,11 @@ import { trashRelativePathFromSpace, trashTargetFromSpace } from '../../../space
import { UserModel } from '../../../users/models/user.model.js'
import { CACHE_TASK_CANCEL_PREFIX, CACHE_TASK_PREFIX, CACHE_TASK_TTL } from '../../constants/cache.js'
import { FILE_OPERATION } from '../../constants/operations.js'
-import { CopyMoveFileDto } from '../../dto/file-operations.dto.js'
-import type { FileTaskQueueItem } from '../../interfaces/file-task-queue.interface.js'
+import type { ValidatedCopyMoveFileDto } from '../../dto/file-operations.dto.js'
+import type { FileTaskMethod, FileTaskQueueItem } from '../../interfaces/file-task-queue.interface.js'
import type { FileTasksPollResponse } from '../../interfaces/file-task.interface.js'
import { FileTask, FileTaskProps, FileTaskStatus } from '../../models/file-task.js'
+import { FileError } from '../../models/file-error.js'
import { dirName, fileName, removeFiles, temporaryFilePath } from '../../utils/files.js'
import { SendFile } from '../../utils/send-file.js'
import { isTaskCancellable } from '../../utils/tasks.js'
@@ -139,7 +141,7 @@ export class FilesTasksManager implements OnModuleDestroy {
try {
await sendFile.checks()
} catch (e) {
- throw new HttpException(e.message, e.httpCode)
+ throw new HttpException(toErrorMessage(e), e instanceof FileError ? e.httpCode : HttpStatus.INTERNAL_SERVER_ERROR)
}
return await sendFile.stream(req, res)
}
@@ -147,7 +149,9 @@ export class FilesTasksManager implements OnModuleDestroy {
private async cleanupTask(user: UserModel, cacheKey: string, task: FileTask): Promise<void> {
this.filesTasksWatcher.stopWatch(cacheKey)
if (task.props.compressInDirectory === false) {
- await removeFiles(this.downloadableArchivePath(user, task)).catch((e: Error) => this.logger.error({ tag: this.deleteTasks.name, msg: `${e}` }))
+ await removeFiles(this.downloadableArchivePath(user, task)).catch((e: Error) =>
+ this.logger.error({ tag: this.deleteTasks.name, msg: toErrorMessage(e) })
+ )
}
}
@@ -161,7 +165,7 @@ export class FilesTasksManager implements OnModuleDestroy {
try {
await this.cache.set(cacheKey, task, CACHE_TASK_TTL)
} catch (e) {
- this.logger.error({ tag: this.storeTask.name, msg: `${e}` })
+ this.logger.error({ tag: this.storeTask.name, msg: toErrorMessage(e) })
}
}
@@ -187,7 +191,7 @@ export class FilesTasksManager implements OnModuleDestroy {
}
await this.cache
.del(cacheKey.replace(`${CACHE_TASK_PREFIX}-`, `${CACHE_TASK_CANCEL_PREFIX}-`))
- .catch((e: Error) => this.logger.error({ tag: this.setTaskDone.name, msg: `${e}` }))
+ .catch((e: Error) => this.logger.error({ tag: this.setTaskDone.name, msg: toErrorMessage(e) }))
} finally {
this.filesTasksWatcher.endFinalization(cacheKey)
}
@@ -208,25 +212,25 @@ export class FilesTasksManager implements OnModuleDestroy {
// Transfer-capable tasks receive a signal; successful native renames still stay atomic.
const controller = this.watchCancellation(task.task, task.user.id, task.cacheKey)
const taskPromise = controller
- ? this.filesMethods[task.method](task.user, task.space, task.dto, controller.signal)
- : this.filesMethods[task.method](task.user, task.space, task.dto)
+ ? (this.filesMethods[task.method as keyof FilesMethods] as FileTaskMethod)(task.user, task.space, task.dto, controller.signal)
+ : (this.filesMethods[task.method as keyof FilesMethods] as FileTaskMethod)(task.user, task.space, task.dto)
taskPromise
.then(async (data: any) => {
this.logger.debug({ tag: this.runTask.name, msg: `${task.task.name} : ${task.method} done` })
const finalProps = await this.getFinalTaskProps(task, data)
this.completeTask(task.user.id, task.cacheKey, FileTaskStatus.SUCCESS, data, finalProps).catch((e: Error) =>
- this.logger.warn({ tag: this.runTask.name, msg: `${e}` })
+ this.logger.warn({ tag: this.runTask.name, msg: toErrorMessage(e) })
)
})
.catch((e: HttpException | any) => {
- this.logger.warn({ tag: this.runTask.name, msg: `${task.task.name} : ${task.method} : ${e}` })
+ this.logger.warn({ tag: this.runTask.name, msg: `${task.task.name} : ${task.method} : ${toErrorMessage(e)}` })
const isCancellation = this.isCancellationError(e, controller)
this.completeTask(
task.user.id,
task.cacheKey,
isCancellation ? FileTaskStatus.CANCELLED : FileTaskStatus.ERROR,
isCancellation ? 'Cancelled' : e.message
- ).catch((e: Error) => this.logger.error({ tag: this.runTask.name, msg: `${e}` }))
+ ).catch((e: Error) => this.logger.error({ tag: this.runTask.name, msg: toErrorMessage(e) }))
})
}
@@ -255,10 +259,10 @@ export class FilesTasksManager implements OnModuleDestroy {
try {
const publishedUrl = path.join(result.path, result.name)
const publishedSpace = await this.spacesManager.spaceEnv(task.user, publishedUrl.split('/'))
- const props = await this.filesTasksWatcher.getPathProps(publishedSpace.realPath)
+ const props = await this.filesTasksWatcher.getPathProps(publishedSpace!.realPath)
return { ...props, progress: 100 }
} catch (e) {
- this.logger.warn({ tag: this.getFinalTaskProps.name, msg: `${e}` })
+ this.logger.warn({ tag: this.getFinalTaskProps.name, msg: toErrorMessage(e) })
}
}
@@ -273,9 +277,9 @@ export class FilesTasksManager implements OnModuleDestroy {
private async taskDestinationPath(type: FILE_OPERATION, user: UserModel, space: SpaceEnv, dto: unknown): Promise<string | undefined> {
try {
if (type === FILE_OPERATION.MOVE) {
- const copyMoveDto = dto as CopyMoveFileDto
+ const copyMoveDto = dto as ValidatedCopyMoveFileDto
const dstUrl = path.join(copyMoveDto.dstDirectory, copyMoveDto.dstName || fileName(space.realPath))
- return (await this.spacesManager.spaceEnv(user, dstUrl.split('/'))).realPath
+ return (await this.spacesManager.spaceEnv(user, dstUrl.split('/')))!.realPath
}
if (type === FILE_OPERATION.DELETE && !space.inTrashRepository) {
const trashTarget = trashTargetFromSpace(user, space)
@@ -307,7 +311,7 @@ export class FilesTasksManager implements OnModuleDestroy {
this.stopCancellationWatch(cacheKey)
await this.cache.del(cancellationCacheKey)
} catch (e) {
- this.logger.error({ tag: this.abortTaskIfRequested.name, msg: `${e}` })
+ this.logger.error({ tag: this.abortTaskIfRequested.name, msg: toErrorMessage(e) })
}
}
diff --git a/backend/src/applications/files/services/tasks/files-tasks-queue.service.spec.ts b/backend/src/applications/files/services/tasks/files-tasks-queue.service.spec.ts
index cb1f746d..c4ea6db7 100644
--- a/backend/src/applications/files/services/tasks/files-tasks-queue.service.spec.ts
+++ b/backend/src/applications/files/services/tasks/files-tasks-queue.service.spec.ts
@@ -108,7 +108,7 @@ describe(FilesTasksQueue.name, () => {
await queue.enqueue(userId, createTask('task-1'), startTask)
- expect(loggerSpy).toHaveBeenCalledWith({ tag: 'drain', msg: `${error}` })
+ expect(loggerSpy).toHaveBeenCalledWith({ tag: 'drain', msg: 'start failed' })
expect(counters.get(counterKey)).toBe(0)
})
diff --git a/backend/src/applications/files/services/tasks/files-tasks-queue.service.ts b/backend/src/applications/files/services/tasks/files-tasks-queue.service.ts
index 466635c2..4a45961a 100644
--- a/backend/src/applications/files/services/tasks/files-tasks-queue.service.ts
+++ b/backend/src/applications/files/services/tasks/files-tasks-queue.service.ts
@@ -1,3 +1,4 @@
+import { toErrorMessage } from '../../../../common/errors.js'
import { Injectable, Logger, OnModuleDestroy } from '@nestjs/common'
import { Cache } from '../../../../infrastructure/cache/cache.service.js'
import { CACHE_TASK_TTL, CACHE_TASK_USER_PREFIX } from '../../constants/cache.js'
@@ -67,7 +68,7 @@ export class FilesTasksQueue implements OnModuleDestroy {
try {
if (entry && (await entry.startTask(entry.task))) continue
} catch (e) {
- this.logger.error({ tag: this.drain.name, msg: `${e}` })
+ this.logger.error({ tag: this.drain.name, msg: toErrorMessage(e) })
}
await this.releaseUserRunningTaskSlot(userId)
}
@@ -98,7 +99,7 @@ export class FilesTasksQueue implements OnModuleDestroy {
private startQueueDrainInterval(): void {
if (this.queuedTasksDrainInterval) return
this.queuedTasksDrainInterval = setInterval(() => {
- this.drainAll().catch((e: Error) => this.logger.error({ tag: this.drainAll.name, msg: `${e}` }))
+ this.drainAll().catch((e: Error) => this.logger.error({ tag: this.drainAll.name, msg: toErrorMessage(e) }))
}, this.drainInterval)
this.queuedTasksDrainInterval.unref()
}
diff --git a/backend/src/applications/files/services/tasks/files-tasks-watcher.service.spec.ts b/backend/src/applications/files/services/tasks/files-tasks-watcher.service.spec.ts
index 2443e205..105a9244 100644
--- a/backend/src/applications/files/services/tasks/files-tasks-watcher.service.spec.ts
+++ b/backend/src/applications/files/services/tasks/files-tasks-watcher.service.spec.ts
@@ -64,7 +64,9 @@ describe(FilesTasksWatcher.name, () => {
it('starts a download watcher with the published task metadata', async () => {
const space = makeSpace()
const updateTask = vi.spyOn(service as any, 'updateTask').mockResolvedValue(undefined)
- const watchTask = vi.spyOn(service as any, 'watchTask').mockImplementation((_cacheKey: string, update: () => Promise<void>) => void update())
+ const watchTask = vi
+ .spyOn(service as any, 'watchTask')
+ .mockImplementation(((_cacheKey: string, update: () => Promise<void>) => void update()) as never)
FileTaskEvent.emit('startWatch', space, '/files/report.txt')
await flushPromises()
diff --git a/backend/src/applications/files/services/tasks/files-tasks-watcher.service.ts b/backend/src/applications/files/services/tasks/files-tasks-watcher.service.ts
index 021dfc73..3cff742c 100644
--- a/backend/src/applications/files/services/tasks/files-tasks-watcher.service.ts
+++ b/backend/src/applications/files/services/tasks/files-tasks-watcher.service.ts
@@ -1,3 +1,4 @@
+import { toErrorMessage } from '../../../../common/errors.js'
import { Injectable, Logger, OnModuleDestroy } from '@nestjs/common'
import { Cache } from '../../../../infrastructure/cache/cache.service.js'
import { SpaceEnv } from '../../../spaces/models/space-env.model.js'
@@ -29,7 +30,7 @@ export class FilesTasksWatcher implements OnModuleDestroy {
async beginFinalization(cacheKey: string): Promise<void> {
this.finalizingTasks.add(cacheKey)
this.stopWatch(cacheKey)
- await this.pendingTaskUpdates.get(cacheKey)?.catch((e: Error) => this.logger.error({ tag: this.beginFinalization.name, msg: `${e}` }))
+ await this.pendingTaskUpdates.get(cacheKey)?.catch((e: Error) => this.logger.error({ tag: this.beginFinalization.name, msg: toErrorMessage(e) }))
}
endFinalization(cacheKey: string): void {
@@ -57,8 +58,8 @@ export class FilesTasksWatcher implements OnModuleDestroy {
this.updateTask(cacheKey, props, {
name: fileName(rPath),
path: dirName(space.url)
- }).catch((e: Error) => this.logger.error({ tag: this.startWatch.name, msg: `${e}` }))
- this.watchTask(cacheKey, () => this.updateTask(cacheKey, space.task.props))
+ }).catch((e: Error) => this.logger.error({ tag: this.startWatch.name, msg: toErrorMessage(e) }))
+ this.watchTask(cacheKey, () => this.updateTask(cacheKey, space.task!.props))
}
private watchTask(cacheKey: string, update: () => Promise<void>): void {
@@ -68,7 +69,7 @@ export class FilesTasksWatcher implements OnModuleDestroy {
if (updateInProgress) return
updateInProgress = true
void update()
- .catch((e: Error) => this.logger.error({ tag: this.watchTask.name, msg: `${e}` }))
+ .catch((e: Error) => this.logger.error({ tag: this.watchTask.name, msg: toErrorMessage(e) }))
.finally(() => {
updateInProgress = false
})
diff --git a/backend/src/applications/files/utils/doc-textify/adapters/pdf.ts b/backend/src/applications/files/utils/doc-textify/adapters/pdf.ts
index a786fd93..cfd0ec52 100644
--- a/backend/src/applications/files/utils/doc-textify/adapters/pdf.ts
+++ b/backend/src/applications/files/utils/doc-textify/adapters/pdf.ts
@@ -62,7 +62,7 @@ function extractText(items: unknown[], newlineDelimiter: string): string {
async function extractTextFromImages(images: ExtractedImages, options: DocTextifyOptions, pageRotation = 0): Promise<string[]> {
const contents: string[] = []
- const worker: DocTextifyOCRWorkerLike | undefined = options.ocrWorker
+ const worker: DocTextifyOCRWorkerLike | null | undefined = options.ocrWorker
if (!worker) return contents
diff --git a/backend/src/applications/files/utils/doc-textify/doc-textify.ts b/backend/src/applications/files/utils/doc-textify/doc-textify.ts
index 9b520d3f..c6f0932b 100644
--- a/backend/src/applications/files/utils/doc-textify/doc-textify.ts
+++ b/backend/src/applications/files/utils/doc-textify/doc-textify.ts
@@ -1,4 +1,5 @@
import fs from 'node:fs/promises'
+import { toErrorMessage } from '../../../../common/errors.js'
import { parseExcel } from './adapters/excel.js'
import { parseHtml } from './adapters/html.js'
import { parseMarkdown } from './adapters/markdown.js'
@@ -15,10 +16,10 @@ import { getExtensionWithoutDot } from '../files.js'
/** Main: determine parser by extension and dispatch */
export async function docTextify(
filePath: string,
- options: DocTextifyOptions,
+ options: Partial<DocTextifyOptions> = {},
fileProperties?: { extension?: string; verified?: boolean }
): Promise<string> {
- options = {
+ const resolvedOptions: DocTextifyOptions = {
newlineDelimiter: '\n',
minCharsToExtract: 10,
...options
@@ -28,7 +29,7 @@ export async function docTextify(
try {
await fs.access(filePath)
} catch (e) {
- throw new Error(`file does not exist or not accessible : ${filePath} (${e})`)
+ throw new Error(`file does not exist or not accessible : ${filePath} (${toErrorMessage(e)})`, { cause: e })
}
}
@@ -40,24 +41,24 @@ export async function docTextify(
switch (ext) {
case 'docx':
- return cleanContent(await parseWord(filePath, options), options)
+ return cleanContent(await parseWord(filePath, resolvedOptions), resolvedOptions)
case 'pptx':
- return cleanContent(await parsePowerPoint(filePath, options), options)
+ return cleanContent(await parsePowerPoint(filePath, resolvedOptions), resolvedOptions)
case 'xlsx':
- return cleanContent(await parseExcel(filePath, options), options)
+ return cleanContent(await parseExcel(filePath, resolvedOptions), resolvedOptions)
case 'odt':
case 'odp':
case 'ods':
- return cleanContent(await parseOpenOffice(filePath, options), options)
+ return cleanContent(await parseOpenOffice(filePath, resolvedOptions), resolvedOptions)
case 'pdf':
- return cleanContent(await parsePdf(filePath, options), options)
+ return cleanContent(await parsePdf(filePath, resolvedOptions), resolvedOptions)
case 'txt':
- return cleanContent(await parseText(filePath), options)
+ return cleanContent(await parseText(filePath), resolvedOptions)
case 'md':
- return cleanContent(await parseMarkdown(filePath), options)
+ return cleanContent(await parseMarkdown(filePath), resolvedOptions)
case 'html':
case 'htm':
- return cleanContent(await parseHtml(filePath), options)
+ return cleanContent(await parseHtml(filePath), resolvedOptions)
default:
throw new Error(`no handler found for extension: ${ext}`)
}
diff --git a/backend/src/applications/files/utils/doc-textify/utils/ocr.ts b/backend/src/applications/files/utils/doc-textify/utils/ocr.ts
index a94c6490..359fefcc 100644
--- a/backend/src/applications/files/utils/doc-textify/utils/ocr.ts
+++ b/backend/src/applications/files/utils/doc-textify/utils/ocr.ts
@@ -1,3 +1,4 @@
+import { toErrorMessage } from '../../../../../common/errors.js'
import type { Logger } from '@nestjs/common'
import path from 'node:path'
import { fileURLToPath } from 'node:url'
@@ -61,7 +62,7 @@ export class OCRManager {
await this.workerInitializationPromise.catch((e) =>
this.logger.error({
tag: this.constructor.name,
- msg: `Initialization: ${e}`
+ msg: `Initialization: ${toErrorMessage(e)}`
})
)
}
@@ -77,7 +78,7 @@ export class OCRManager {
.catch((e) =>
this.logger.error({
tag: this.constructor.name,
- msg: `${e}`
+ msg: toErrorMessage(e)
})
)
}
@@ -88,7 +89,7 @@ export class OCRManager {
errorHandler: (e: unknown) =>
this.logger.error({
tag: this.constructor.name,
- msg: `${e}`
+ msg: toErrorMessage(e)
}),
logger: () => {
// intentionally disabled
@@ -109,7 +110,7 @@ export class OCRManager {
} catch (e) {
this.logger.error({
tag: this.constructor.name,
- msg: `unable to create languages directory: ${e}`
+ msg: `unable to create languages directory: ${toErrorMessage(e)}`
})
}
if (this.ocrConfig.offline) {
@@ -126,7 +127,7 @@ export class OCRManager {
} catch (error) {
this.logger.warn({
tag: this.constructor.name,
- msg: `unable to load offline OCR languages as ${this.ocrTrainedDataGzipExtension}, retrying with ${this.ocrTrainedDataExtension}: ${error}`
+ msg: `unable to load offline OCR languages as ${this.ocrTrainedDataGzipExtension}, retrying with ${this.ocrTrainedDataExtension}: ${toErrorMessage(error)}`
})
// Fallback for non-gz files: <lang>.traineddata
return this.createConfiguredWorker(this.ocrConfig.languages, {
diff --git a/backend/src/applications/files/utils/download-file.spec.ts b/backend/src/applications/files/utils/download-file.spec.ts
index 18cd7fa7..2b279379 100644
--- a/backend/src/applications/files/utils/download-file.spec.ts
+++ b/backend/src/applications/files/utils/download-file.spec.ts
@@ -9,9 +9,13 @@ import { DownloadFile } from './download-file.js'
import type { Mock } from 'vitest'
import { FILE_ERROR } from '../constants/errors.js'
-vi.mock('./files.js', () => ({
- writeUploadFromStream: vi.fn()
-}))
+vi.mock('./files.js', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('./files.js')>()
+ return {
+ ...actual,
+ writeUploadFromStream: vi.fn()
+ }
+})
vi.mock('node:dns/promises', () => ({
lookup: vi.fn()
}))
diff --git a/backend/src/applications/files/utils/download-file.ts b/backend/src/applications/files/utils/download-file.ts
index 2a933569..7fcbdd6d 100644
--- a/backend/src/applications/files/utils/download-file.ts
+++ b/backend/src/applications/files/utils/download-file.ts
@@ -1,3 +1,4 @@
+import { toErrorMessage } from '../../../common/errors.js'
import { lookup } from 'node:dns/promises'
import { Agent as HttpAgent } from 'node:http'
import { Agent as HttpsAgent } from 'node:https'
@@ -5,7 +6,7 @@ import type { LookupAddress } from 'node:dns'
import type { LookupFunction } from 'node:net'
import type { HttpService } from '@nestjs/axios'
import { HttpStatus, Logger } from '@nestjs/common'
-import { AxiosHeaders, type AxiosRequestConfig, type AxiosResponse } from 'axios'
+import { AxiosHeaders, type AxiosRequestConfig, type AxiosResponse, type RawAxiosHeaders } from 'axios'
import ipaddr from 'ipaddr.js'
import { HTTP_METHOD } from '../../applications.constants.js'
import type { SpaceEnv } from '../../spaces/models/space-env.model.js'
@@ -57,7 +58,7 @@ export class DownloadFile {
currentUrl = url
stage = 'validation'
- const headers = AxiosHeaders.from(headRes.headers)
+ const headers = AxiosHeaders.from(headRes.headers as RawAxiosHeaders)
contentLength = this.contentLength(headers)
if (options?.getContentInfo) {
return {
@@ -88,7 +89,7 @@ export class DownloadFile {
)
stage = 'stream'
try {
- const getContentLength = this.contentLength(AxiosHeaders.from(getRes.headers))
+ const getContentLength = this.contentLength(AxiosHeaders.from(getRes.headers as RawAxiosHeaders))
if (getContentLength !== null) {
fileLimiter.assertKnownSize(getContentLength)
}
@@ -112,7 +113,7 @@ export class DownloadFile {
const host = URL.canParse(url) ? new URL(url).hostname || 'unknown' : 'invalid'
const sizeContext =
stage === 'validation' || stage === 'stream' ? ` (contentLength=${contentLength ?? 'missing'}, maxSize=${maxSize ?? 'unset'})` : ''
- this.logger.warn({ tag: this.download.name, msg: `${stage} failed for host *${host}*${sizeContext}: ${error}` })
+ this.logger.warn({ tag: this.download.name, msg: `${stage} failed for host *${host}*${sizeContext}: ${toErrorMessage(error)}` })
}
private safeLookup(hostname: string, options: Parameters<LookupFunction>[1], cb: Parameters<LookupFunction>[2]): void {
diff --git a/backend/src/applications/files/utils/files-search.ts b/backend/src/applications/files/utils/files-search.ts
index 7a083581..5bc7d9ce 100644
--- a/backend/src/applications/files/utils/files-search.ts
+++ b/backend/src/applications/files/utils/files-search.ts
@@ -121,8 +121,8 @@ export function likeSearchTermStartPattern(): string {
return `(?=${LIKE_SEARCH_CHAR})`
}
-export function normalizeSearchLimit(limit?: number): number {
- if (!Number.isInteger(limit)) return SEARCH_FILES_DEFAULT_LIMIT
+export function normalizeSearchLimit(limit?: number | null): number {
+ if (typeof limit !== 'number' || !Number.isInteger(limit)) return SEARCH_FILES_DEFAULT_LIMIT
return Math.min(Math.max(limit, SEARCH_FILES_MIN_LIMIT), SEARCH_FILES_MAX_LIMIT)
}
diff --git a/backend/src/applications/files/utils/files.ts b/backend/src/applications/files/utils/files.ts
index 57d118c2..b9ea7e3d 100644
--- a/backend/src/applications/files/utils/files.ts
+++ b/backend/src/applications/files/utils/files.ts
@@ -8,6 +8,7 @@ import fs from 'node:fs/promises'
import path from 'node:path'
import { Readable, Transform } from 'node:stream'
import { pipeline } from 'node:stream/promises'
+import { toErrorMessage } from '../../../common/errors.js'
import { formatDateISOString } from '../../../common/functions.js'
import { currentTimeStamp, isValidFileName, regExpPreventPathTraversal } from '../../../common/shared.js'
import { DEFAULT_CHECKSUM_ALGORITHM, DEFAULT_HIGH_WATER_MARK, EXTRA_MIMES_TYPE, TEMPORARY_FILE_PREFIX, TEMPORARY_PATH } from '../constants/files.js'
@@ -50,11 +51,12 @@ export function sanitizeName(name: string): string {
.replace(/^\s+|[. ]+$/g, '') // trimStart + trimEnd + strip trailing dots
}
-export function assertValidFileReferenceId(fileId: number): void {
- const isTemporaryInode = Number.isInteger(fileId) && fileId < 0
- const isDatabaseId = Number.isSafeInteger(fileId) && fileId > 0
+export function isValidFileReferenceId(fileId: unknown): fileId is number {
+ return typeof fileId === 'number' && Number.isInteger(fileId) && (fileId < 0 || (fileId > 0 && Number.isSafeInteger(fileId)))
+}
- if (!isTemporaryInode && !isDatabaseId) {
+export function assertValidFileReferenceId(fileId: number | undefined): asserts fileId is number {
+ if (!isValidFileReferenceId(fileId)) {
throw new HttpException('Invalid file id', HttpStatus.BAD_REQUEST)
}
}
@@ -129,7 +131,7 @@ export function createEmptyFile(rPath: string): Promise<void> {
return fs.writeFile(rPath, '')
}
-export function makeDir(rPath: string, recursive?: boolean): Promise<string> {
+export function makeDir(rPath: string, recursive?: boolean): Promise<string | undefined> {
return fs.mkdir(rPath, { recursive: recursive })
}
@@ -192,8 +194,9 @@ export function getMimeType(fPath: string, isDir: boolean): string {
return 'directory'
}
const extName: string = path.extname(fPath)
- if (EXTRA_MIMES_TYPE.has(extName)) {
- return EXTRA_MIMES_TYPE.get(extName)
+ const extraMime = EXTRA_MIMES_TYPE.get(extName)
+ if (extraMime !== undefined) {
+ return extraMime
}
const m = mime.lookup(extName)
if (m) {
@@ -206,7 +209,7 @@ export function getExtensionWithoutDot(fPath: string): string {
return path.extname(fPath).slice(1).toLowerCase()
}
-export function genEtag(file?: Pick<FileProps, 'size' | 'mtime'>, rPath?: string, weakPrefix = true): string {
+export function genEtag(file?: Pick<FileProps, 'size' | 'mtime'> | null, rPath?: string, weakPrefix = true): string {
if (!file) {
if (!rPath) throw new Error('File or path are missing')
const stats = statSync(rPath)
@@ -221,7 +224,7 @@ export function genHash(str: string, algo = 'md5', encoding: crypto.BinaryToText
}
export function genUniqHashFromFileDBProps(dbFile: FileDBProps) {
- const dbFileString = `${Object.keys(dbFile)
+ const dbFileString = `${(Object.keys(dbFile) as (keyof FileDBProps)[])
.sort()
.map((k) => `${k}=${String(dbFile[k])}`)
.join('|')}`
@@ -360,7 +363,7 @@ export function createProgressTransform(
checkSize?.(chunk.length)
onProgress?.(chunk.length)
} catch (error) {
- callback(error as Error)
+ callback(error instanceof Error ? error : new Error(toErrorMessage(error)))
return
}
callback(null, chunk)
@@ -379,7 +382,7 @@ export function writeFromStream(rPath: string, stream: Readable, options: WriteF
try {
accountBytes(chunk.length)
} catch (error) {
- callback(error as Error)
+ callback(error instanceof Error ? error : new Error(toErrorMessage(error)))
return
}
callback(null, chunk)
@@ -453,9 +456,9 @@ export async function walkDir(
try {
entries = await fs.readdir(rPath, { withFileTypes: true })
- } catch (e: any) {
+ } catch (e) {
if (!errors) throw e
- errors[rPath] = e.message
+ errors[rPath] = toErrorMessage(e)
return
}
@@ -479,8 +482,8 @@ export async function dirSize(rPath: string): Promise<[number, any]> {
if (!entry.isFile()) return
try {
size += (await fs.stat(entryPath)).size
- } catch (e: any) {
- errors[entryPath] = e.message
+ } catch (e) {
+ errors[entryPath] = toErrorMessage(e)
}
},
errors
diff --git a/backend/src/applications/files/utils/indexing.ts b/backend/src/applications/files/utils/indexing.ts
index de257a3c..2cb71df2 100644
--- a/backend/src/applications/files/utils/indexing.ts
+++ b/backend/src/applications/files/utils/indexing.ts
@@ -13,14 +13,14 @@ export function genRunId(): string {
export function indexingUpdateCacheKeysFromSpace(userId: number, space: SpaceEnv): string[] {
const cacheKeys: string[] = []
- if (space.inSharesRepository && !space.root.externalPath) {
+ if (space.inSharesRepository && !space.root!.externalPath) {
// shares that are linked to a space must also be indexed
cacheKeys.push(`${CACHE_INDEXING_EVENT_PREFIX}-${genIndexingKey(space.id, FILE_REPOSITORY.SHARE, '-')}`)
} else if (space.inFilesRepository && space.root?.owner?.login) {
// space where the user’s root file is anchored
cacheKeys.push(`${CACHE_INDEXING_EVENT_PREFIX}-${genIndexingKey(space.id, FILE_REPOSITORY.SPACE, '-')}`)
}
- const repository: { id: number; type: FILE_REPOSITORY } = SpaceToFileRepository(userId, space)
+ const repository = SpaceToFileRepository(userId, space)
if (repository !== null) {
cacheKeys.push(`${CACHE_INDEXING_EVENT_PREFIX}-${genIndexingKey(repository.id, repository.type, '-')}`)
}
diff --git a/backend/src/applications/files/utils/quota.ts b/backend/src/applications/files/utils/quota.ts
index cdf901de..ab408b82 100644
--- a/backend/src/applications/files/utils/quota.ts
+++ b/backend/src/applications/files/utils/quota.ts
@@ -8,6 +8,6 @@ export function genQuotaCacheKey(id: number, type: FILE_REPOSITORY, isEventUpdat
}
export function quotaCacheKeyFromSpace(userId: number, space: SpaceEnv, isEventUpdate = false): string | null {
- const repository: { id: number; type: FILE_REPOSITORY } = SpaceToFileRepository(userId, space)
+ const repository = SpaceToFileRepository(userId, space)
return repository === null ? null : genQuotaCacheKey(repository.id, repository.type, isEventUpdate)
}
diff --git a/backend/src/applications/files/utils/send-file.ts b/backend/src/applications/files/utils/send-file.ts
index 077d468f..4dcdc980 100644
--- a/backend/src/applications/files/utils/send-file.ts
+++ b/backend/src/applications/files/utils/send-file.ts
@@ -12,7 +12,7 @@ export function makeContentDispositionAttachment(fileName: string) {
}
export class SendFile {
- private fileName: string
+ private fileName!: string
constructor(
private readonly filePath: string,
@@ -49,7 +49,7 @@ export class SendFile {
this.fileName = encodeURIComponent(this.downloadName ? this.downloadName : fileName(this.filePath))
const sendResult: SendResult = await send(req.raw, encodedFilePath, this.sendOptions)
// Check if the path was correctly validated
- if (sendResult.metadata['path'] === undefined) {
+ if ((sendResult as typeof sendResult & { metadata: Record<string, unknown> }).metadata['path'] === undefined) {
throw new FileError(HttpStatus.BAD_REQUEST, 'Location not found')
}
// Force file to be downloaded as an attachment
@@ -58,7 +58,6 @@ export class SendFile {
res.status(sendResult.statusCode)
// sendStream.once('stream', () => console.log(`Sending: ${this.fileName}`))
// sendStream.once('end', () => console.log(`Received: ${this.fileName}`))
- // sendStream.once('error', (e: Error) => console.error(`Transfer error : ${this.fileName} - ${e}`))
return new StreamableFile(sendResult.stream)
}
}
diff --git a/backend/src/applications/files/utils/untar-file.ts b/backend/src/applications/files/utils/untar-file.ts
index ab43b85c..bda613fa 100644
--- a/backend/src/applications/files/utils/untar-file.ts
+++ b/backend/src/applications/files/utils/untar-file.ts
@@ -1,6 +1,7 @@
import { createReadStream } from 'node:fs'
import { pipeline } from 'node:stream/promises'
import { extract, type ReadEntry, type Unpack } from 'tar'
+import { toErrorMessage } from '../../../common/errors.js'
import type { FileTaskExtractionEntry } from '../interfaces/file-task.interface.js'
import { storageQuotaExceededError } from './errors.js'
import { createProgressTransform, createSizeLimiter } from './files.js'
@@ -64,7 +65,7 @@ export async function extractTar(
onEntry?.({ path: entry.path, isDirectory: isTarDirectory(entry.type), size: 0 })
return true
} catch (e) {
- return abortExtraction(e as Error)
+ return abortExtraction(e instanceof Error ? e : new Error(toErrorMessage(e)))
}
}
})
diff --git a/backend/src/applications/files/utils/unzip-file.ts b/backend/src/applications/files/utils/unzip-file.ts
index 66c8e6cc..7bc9df2b 100644
--- a/backend/src/applications/files/utils/unzip-file.ts
+++ b/backend/src/applications/files/utils/unzip-file.ts
@@ -3,6 +3,7 @@ import { createWriteStream, openAsBlob } from 'node:fs'
import path from 'node:path'
import { Writable } from 'node:stream'
import { pipeline } from 'node:stream/promises'
+import { toErrorMessage } from '../../../common/errors.js'
import { DEFAULT_HIGH_WATER_MARK } from '../constants/files.js'
import type { FileTaskExtractionEntry } from '../interfaces/file-task.interface.js'
import { storageQuotaExceededError } from './errors.js'
@@ -84,7 +85,7 @@ export async function extractZip(
await fileEntry.getData(Writable.toWeb(entryOutput), { signal })
await outputPromise
} catch (error) {
- const reason = error instanceof Error ? error : new Error(String(error))
+ const reason = error instanceof Error ? error : new Error(toErrorMessage(error))
entryOutput.destroy(reason)
if (progressTransform) writeStream.destroy(reason)
await outputPromise?.catch(() => undefined)
diff --git a/backend/src/applications/files/utils/zip-file.ts b/backend/src/applications/files/utils/zip-file.ts
index 8f568dc7..caa8d00a 100644
--- a/backend/src/applications/files/utils/zip-file.ts
+++ b/backend/src/applications/files/utils/zip-file.ts
@@ -4,6 +4,7 @@ import { lstat, opendir } from 'node:fs/promises'
import path from 'node:path'
import { Writable } from 'node:stream'
import { pipeline } from 'node:stream/promises'
+import { toErrorMessage } from '../../../common/errors.js'
import { DEFAULT_HIGH_WATER_MARK } from '../constants/files.js'
import { storageQuotaExceededError } from './errors.js'
import { createProgressTransform, fileName, isInternalTemporaryEntry, isPathInside } from './files.js'
@@ -111,7 +112,7 @@ export async function createZip(
await outputPromise
signal?.throwIfAborted()
} catch (error) {
- const reason = error instanceof Error ? error : new Error(String(error))
+ const reason = error instanceof Error ? error : new Error(toErrorMessage(error))
archiveOutput.destroy(reason)
if (progressTransform) output.destroy(reason)
await outputPromise?.catch(() => undefined)
diff --git a/backend/src/applications/links/dto/create-or-update-link.dto.ts b/backend/src/applications/links/dto/create-or-update-link.dto.ts
index 337a1352..f52d566c 100644
--- a/backend/src/applications/links/dto/create-or-update-link.dto.ts
+++ b/backend/src/applications/links/dto/create-or-update-link.dto.ts
@@ -1,60 +1,24 @@
-import { Transform } from 'class-transformer'
-import { IsBoolean, IsDate, IsOptional, IsString, MinLength } from 'class-validator'
+import { z } from 'zod'
import { currentDate } from '../../../common/shared.js'
import { USER_PASSWORD_MIN_LENGTH } from '../../users/constants/user.js'
-export class CreateOrUpdateLinkDto {
- @IsOptional()
- @IsString()
- uuid?: string
-
- @IsOptional()
- @IsString()
- name?: string
-
- @IsOptional()
- @IsString()
- email?: string
-
- @IsOptional()
- @IsString()
- language?: string
-
- @IsOptional()
- @Transform(({ value }) => value || 0)
- limitAccess?: number
-
- @IsOptional()
- @Transform(({ value }) => (value ? currentDate(value) : null))
- @IsDate()
- expiresAt?: Date
-
- @IsOptional()
- @Transform(({ value }) => !!value)
- @IsBoolean()
- requireAuth?: boolean
-
- @IsOptional()
- @Transform(({ value }) => !!value)
- @IsBoolean()
- isActive?: boolean
-
- @IsOptional()
- @IsString()
- permissions?: string
-
- @IsOptional()
- @IsString()
- @MinLength(USER_PASSWORD_MIN_LENGTH)
- password?: string
-
+export const createOrUpdateLinkSchema = z.object({
+ uuid: z.string().nullish(),
+ name: z.string().nullish(),
+ email: z.string().nullish(),
+ language: z.string().nullish(),
+ limitAccess: z.coerce.number().optional(),
+ expiresAt: z
+ .preprocess((value) => (typeof value === 'string' ? (value ? currentDate(value) : null) : value ? value : null), z.date().nullable())
+ .optional(),
+ requireAuth: z.coerce.boolean().optional(),
+ isActive: z.coerce.boolean().optional(),
+ permissions: z.string().nullish(),
+ password: z.string().min(USER_PASSWORD_MIN_LENGTH).nullish(),
// used for update link from links component
- @IsOptional()
- @IsString()
- shareName?: string
-
+ shareName: z.string().nullish(),
// used for update link from links component
- @IsOptional()
- @IsString()
- shareDescription?: string
-}
+ shareDescription: z.string().nullish()
+})
+
+export type CreateOrUpdateLinkDto = z.infer<typeof createOrUpdateLinkSchema>
diff --git a/backend/src/applications/links/interfaces/link-env.interface.ts b/backend/src/applications/links/interfaces/link-env.interface.ts
new file mode 100644
index 00000000..3279d17b
--- /dev/null
+++ b/backend/src/applications/links/interfaces/link-env.interface.ts
@@ -0,0 +1,3 @@
+import type { LinkAsUser } from './link-guest.interface.js'
+
+export type LinkEnv = [link: LinkAsUser, check: true, ok: true] | [link: LinkAsUser | undefined, check: string, ok: false]
diff --git a/backend/src/applications/links/links.controller.ts b/backend/src/applications/links/links.controller.ts
index ada37a72..eb3aefa6 100644
--- a/backend/src/applications/links/links.controller.ts
+++ b/backend/src/applications/links/links.controller.ts
@@ -5,11 +5,12 @@ import { AuthTokenOptional } from '../../authentication/decorators/auth-token-op
import { LoginResponseDto } from '../../authentication/dto/login-response.dto.js'
import { AuthRateLimitGuard } from '../../authentication/guards/auth-rate-limit.guard.js'
import { GetUser } from '../users/decorators/user.decorator.js'
-import { UserPasswordDto } from '../users/dto/user-properties.dto.js'
+import { type UserPasswordDto, userPasswordSchema } from '../users/dto/user-properties.dto.js'
import { UserModel } from '../users/models/user.model.js'
import { LINK_DOWNLOAD_RATE_LIMIT_OPTIONS } from './constants/links.js'
import { PUBLIC_LINKS_ROUTE } from './constants/routes.js'
import { SpaceLink } from './interfaces/link-space.interface.js'
+import { publicLinkUuidParameterSchema } from './links.schema.js'
import { LinksManager } from './services/links-manager.service.js'
@Controller(PUBLIC_LINKS_ROUTE.BASE)
@@ -21,11 +22,11 @@ export class LinksController {
@UseGuards(AuthRateLimitGuard)
linkValidation(
@GetUser() user: UserModel,
- @Param('uuid') uuid: string
+ @Param('uuid', { schema: publicLinkUuidParameterSchema }) uuid: string
): Promise<{
- error: string | true
+ error: string | null
ok: boolean
- link: SpaceLink
+ link: SpaceLink | null
}> {
return this.linksManager.linkValidation(user, uuid)
}
@@ -35,7 +36,7 @@ export class LinksController {
@UseGuards(AuthRateLimitGuard)
linkAccess(
@GetUser() user: UserModel,
- @Param('uuid') uuid: string,
+ @Param('uuid', { schema: publicLinkUuidParameterSchema }) uuid: string,
@Req() req: FastifyRequest,
@Res({ passthrough: true }) res: FastifyReply
): Promise<LoginResponseDto | Omit<LoginResponseDto, 'token'>> {
@@ -47,7 +48,7 @@ export class LinksController {
@UseGuards(AuthRateLimitGuard)
linkDownload(
@GetUser() user: UserModel,
- @Param('uuid') uuid: string,
+ @Param('uuid', { schema: publicLinkUuidParameterSchema }) uuid: string,
@Req() req: FastifyRequest,
@Res({ passthrough: true }) res: FastifyReply
): Promise<StreamableFile> {
@@ -59,8 +60,8 @@ export class LinksController {
@UseGuards(AuthRateLimitGuard)
linkAuthentication(
@GetUser() user: UserModel,
- @Param('uuid') uuid: string,
- @Body() linkPasswordDto: UserPasswordDto,
+ @Param('uuid', { schema: publicLinkUuidParameterSchema }) uuid: string,
+ @Body({ schema: userPasswordSchema }) linkPasswordDto: UserPasswordDto,
@Req() req: FastifyRequest,
@Res({ passthrough: true }) res: FastifyReply
): Promise<LoginResponseDto> {
diff --git a/backend/src/applications/links/links.schema.ts b/backend/src/applications/links/links.schema.ts
new file mode 100644
index 00000000..ea3da406
--- /dev/null
+++ b/backend/src/applications/links/links.schema.ts
@@ -0,0 +1,3 @@
+import { z } from 'zod'
+
+export const publicLinkUuidParameterSchema = z.string()
diff --git a/backend/src/applications/links/schemas/link.interface.ts b/backend/src/applications/links/schemas/link.interface.ts
index 690e1e87..1a22ef12 100644
--- a/backend/src/applications/links/schemas/link.interface.ts
+++ b/backend/src/applications/links/schemas/link.interface.ts
@@ -1,16 +1,3 @@
import type { links } from './links.schema.js'
-type LinkSchema = typeof links.$inferSelect
-
-export class Link implements LinkSchema {
- id: number
- uuid: string
- userId: number
- name: string
- email: string
- requireAuth: boolean
- nbAccess: number
- limitAccess: number
- expiresAt: Date
- createdAt: Date
-}
+export type Link = typeof links.$inferSelect
diff --git a/backend/src/applications/links/services/links-manager.service.spec.ts b/backend/src/applications/links/services/links-manager.service.spec.ts
index 59bb2bb7..60f647c9 100644
--- a/backend/src/applications/links/services/links-manager.service.spec.ts
+++ b/backend/src/applications/links/services/links-manager.service.spec.ts
@@ -13,7 +13,6 @@ import { SharesManager } from '../../shares/services/shares-manager.service.js'
import { SharesQueries } from '../../shares/services/shares-queries.service.js'
import { SpacesManager } from '../../spaces/services/spaces-manager.service.js'
import { SpacesQueries } from '../../spaces/services/spaces-queries.service.js'
-import { UserModel } from '../../users/models/user.model.js'
import { AdminUsersManager } from '../../users/services/admin-users-manager.service.js'
import { AdminUsersQueries } from '../../users/services/admin-users-queries.service.js'
import { UsersManager } from '../../users/services/users-manager.service.js'
@@ -143,7 +142,7 @@ describe(LinksManager.name, () => {
})
it('returns error and null link when uuid is not found', async () => {
- linksQueriesMock.linkFromUUID.mockResolvedValueOnce(null)
+ linksQueriesMock.linkFromUUID.mockResolvedValueOnce(undefined)
const res = await service.linkValidation(identity, 'missing-uuid')
@@ -210,10 +209,6 @@ describe(LinksManager.name, () => {
it('authenticates and returns cookies when link targets a directory and user is different', async () => {
const link = { ...baseLink, requireAuth: false, user: { id: 7, login: 'john', isActive: true } }
linksQueriesMock.linkFromUUID.mockResolvedValueOnce(link)
- const spaceLink = {
- space: { alias: 'files', name: 'My Space' },
- share: { isDir: true, name: 'ignored', alias: 'ignored' }
- } as any
const loginDto: any = { token: 'jwt' }
authManagerMock.setCookies.mockResolvedValueOnce(loginDto)
@@ -228,10 +223,6 @@ describe(LinksManager.name, () => {
expect(linksQueriesMock.consumeLinkAccess).toHaveBeenCalledWith(link.uuid)
expect(usersManagerMock.updateAccesses).toHaveBeenCalledWith(expect.anything(), req.ip, true)
expect(authManagerMock.setCookies).toHaveBeenCalled()
- // additionally cover the "space truthy" branch by calling the private helper directly
- // should call spacesManager.spaceEnv with FILES and space alias when link.space is truthy
- await (service as any).spaceEnvFromLink(new UserModel(link.user as any), spaceLink as any)
- expect(spacesManagerMock.spaceEnv).toHaveBeenCalledWith(expect.anything(), ['files', 'files'])
// should log error when updateAccesses fails
expect(logErrorSpy).toHaveBeenCalled()
})
diff --git a/backend/src/applications/links/services/links-manager.service.ts b/backend/src/applications/links/services/links-manager.service.ts
index e029e479..2ecba9b3 100644
--- a/backend/src/applications/links/services/links-manager.service.ts
+++ b/backend/src/applications/links/services/links-manager.service.ts
@@ -1,19 +1,21 @@
+import { toErrorMessage } from '../../../common/errors.js'
import { HttpException, HttpStatus, Injectable, Logger, StreamableFile } from '@nestjs/common'
import { FastifyReply, FastifyRequest } from 'fastify'
import { AuthManager } from '../../../authentication/auth.service.js'
import { LoginResponseDto } from '../../../authentication/dto/login-response.dto.js'
-import { JwtIdentityPayload } from '../../../authentication/interfaces/jwt-payload.interface.js'
+import type { JwtIdentityPayload } from '../../../authentication/interfaces/jwt-payload.interface.js'
import { serverConfig } from '../../../configuration/config.environment.js'
import { FilesManager } from '../../files/services/files-manager.service.js'
import { SendFile } from '../../files/utils/send-file.js'
import { SPACE_REPOSITORY } from '../../spaces/constants/spaces.js'
import { SpaceEnv } from '../../spaces/models/space-env.model.js'
import { SpacesManager } from '../../spaces/services/spaces-manager.service.js'
-import { UserPasswordDto } from '../../users/dto/user-properties.dto.js'
+import type { UserPasswordDto } from '../../users/dto/user-properties.dto.js'
import { UserModel } from '../../users/models/user.model.js'
import { UsersManager } from '../../users/services/users-manager.service.js'
import { getAvatarBase64 } from '../../users/utils/avatar.js'
import { LINK_ERROR } from '../constants/links.js'
+import type { LinkEnv } from '../interfaces/link-env.interface.js'
import { LinkAsUser } from '../interfaces/link-guest.interface.js'
import { SpaceLink } from '../interfaces/link-space.interface.js'
import { LinksQueries } from './links-queries.service.js'
@@ -30,12 +32,12 @@ export class LinksManager {
private readonly linksQueries: LinksQueries
) {}
- async linkValidation(identity: JwtIdentityPayload, uuid: string): Promise<{ ok: boolean; error: string | true; link: SpaceLink }> {
+ async linkValidation(identity: JwtIdentityPayload, uuid: string): Promise<{ ok: boolean; error: string | null; link: SpaceLink | null }> {
const [_link, check, ok] = await this.linkEnv(identity, uuid)
if (!ok) {
this.logger.warn({ tag: this.linkValidation.name, msg: `${uuid} : ${check}` })
}
- const spaceLink: SpaceLink = ok ? await this.linksQueries.spaceLink(uuid) : null
+ const spaceLink = ok ? ((await this.linksQueries.spaceLink(uuid)) ?? null) : null
if (ok) {
if (spaceLink?.owner?.login) {
spaceLink.owner.avatar = await getAvatarBase64(spaceLink.owner.login)
@@ -58,15 +60,17 @@ export class LinksManager {
): Promise<LoginResponseDto | Omit<LoginResponseDto, 'token'>> {
const [link, check, ok] = await this.linkEnv(identity, uuid)
if (!ok) {
- this.logger.warn({ tag: this.linkAccess.name, msg: `*${link.user.login}* (${link.user.id}) : ${check}` })
- throw new HttpException(check as string, HttpStatus.BAD_REQUEST)
+ this.logger.warn({ tag: this.linkAccess.name, msg: `${link ? `*${link.user.login}* (${link.user.id})` : uuid} : ${check}` })
+ throw new HttpException(check, HttpStatus.BAD_REQUEST)
}
const user = new UserModel(link.user)
if (link.user.id !== identity.id) {
// Authenticate the link user for subsequent access
await this.consumeLinkAccess(link)
this.logger.log({ tag: this.linkAccess.name, msg: `*${user.login}* (${user.id}) is logged` })
- this.usersManager.updateAccesses(user, req.ip, true).catch((e: Error) => this.logger.error({ tag: this.linkAccess.name, msg: `${e}` }))
+ this.usersManager
+ .updateAccesses(user, req.ip, true)
+ .catch((e: Error) => this.logger.error({ tag: this.linkAccess.name, msg: toErrorMessage(e) }))
return this.authManager.setCookies(user, res)
}
// Already authenticated
@@ -76,11 +80,11 @@ export class LinksManager {
async linkDownload(identity: JwtIdentityPayload, uuid: string, req: FastifyRequest, res: FastifyReply): Promise<StreamableFile> {
const [link, check, ok] = await this.linkEnv(identity, uuid)
if (!ok) {
- this.logger.warn({ tag: this.linkDownload.name, msg: `*${link.user.login}* (${link.user.id}) : ${check}` })
- throw new HttpException(check as string, HttpStatus.BAD_REQUEST)
+ this.logger.warn({ tag: this.linkDownload.name, msg: `${link ? `*${link.user.login}* (${link.user.id})` : uuid} : ${check}` })
+ throw new HttpException(check, HttpStatus.BAD_REQUEST)
}
- const spaceLink: SpaceLink = await this.linksQueries.spaceLink(uuid)
- if (spaceLink.space || spaceLink.share?.isDir) {
+ const spaceLink = await this.linksQueries.spaceLink(uuid)
+ if (!spaceLink || spaceLink.space || !spaceLink.share || spaceLink.share.isDir) {
this.logger.error({ tag: this.linkDownload.name, msg: `the provided link does not reference a downloadable file` })
throw new HttpException('This link does not allow file download', HttpStatus.BAD_REQUEST)
}
@@ -90,13 +94,13 @@ export class LinksManager {
await this.consumeLinkAccess(link)
}
this.logger.log({ tag: this.linkDownload.name, msg: `*${user.login}* (${user.id}) downloading ${spaceLink.share.name}` })
- const spaceEnv: SpaceEnv = await this.spaceEnvFromLink(user, spaceLink)
+ const spaceEnv: SpaceEnv = await this.spaceEnvFromLink(user, spaceLink.share)
const sendFile: SendFile = this.filesManager.sendFileFromSpace(spaceEnv, spaceLink.share.name)
try {
await sendFile.checks()
return await sendFile.stream(req, res)
} catch (e) {
- this.logger.error({ tag: this.linkDownload.name, msg: `unable to send file : ${e}` })
+ this.logger.error({ tag: this.linkDownload.name, msg: `unable to send file : ${toErrorMessage(e)}` })
throw new HttpException('Unable to download file', HttpStatus.INTERNAL_SERVER_ERROR)
}
}
@@ -104,15 +108,15 @@ export class LinksManager {
async linkAuthentication(identity: JwtIdentityPayload, uuid: string, linkPasswordDto: UserPasswordDto, req: FastifyRequest, res: FastifyReply) {
const [link, check, ok] = await this.linkEnv(identity, uuid, true)
if (!ok) {
- this.logger.warn({ tag: this.linkAuthentication.name, msg: `*${link.user.login}* (${link.user.id}) : ${check}` })
- throw new HttpException(check as string, HttpStatus.BAD_REQUEST)
+ this.logger.warn({ tag: this.linkAuthentication.name, msg: `${link ? `*${link.user.login}* (${link.user.id})` : uuid} : ${check}` })
+ throw new HttpException(check, HttpStatus.BAD_REQUEST)
}
const user = new UserModel(link.user)
await this.usersManager.validatePasswordAttempts(user)
const authSuccess: boolean = await this.usersManager.compareUserPassword(link.user.id, linkPasswordDto.password)
this.usersManager
.updateAccesses(user, req.ip, authSuccess)
- .catch((e: Error) => this.logger.error({ tag: this.linkAuthentication.name, msg: `${e}` }))
+ .catch((e: Error) => this.logger.error({ tag: this.linkAuthentication.name, msg: toErrorMessage(e) }))
if (!authSuccess) {
this.logger.warn({ tag: this.linkAuthentication.name, msg: `*${user.login}* (${user.id}) : auth failed` })
throw new HttpException(LINK_ERROR.UNAUTHORIZED, HttpStatus.FORBIDDEN)
@@ -123,24 +127,24 @@ export class LinksManager {
return this.authManager.setCookies(user, res)
}
- private spaceEnvFromLink(user: UserModel, link: SpaceLink): Promise<SpaceEnv> {
- return this.spacesManager.spaceEnv(user, [
- link.space ? SPACE_REPOSITORY.FILES : SPACE_REPOSITORY.SHARES,
- link.space ? link.space.alias : link.share.alias
- ])
+ private async spaceEnvFromLink(user: UserModel, share: NonNullable<SpaceLink['share']>): Promise<SpaceEnv> {
+ const spaceEnv = await this.spacesManager.spaceEnv(user, [SPACE_REPOSITORY.SHARES, share.alias])
+ if (!spaceEnv) {
+ throw new HttpException(LINK_ERROR.NOT_FOUND, HttpStatus.BAD_REQUEST)
+ }
+ return spaceEnv
}
- private async linkEnv(identity: JwtIdentityPayload, uuid: string, ignoreAuth: boolean = false): Promise<[LinkAsUser, string | true, boolean]> {
- const link: LinkAsUser = await this.linksQueries.linkFromUUID(uuid)
- const check: string | true = this.checkLink(identity, link, ignoreAuth)
- const ok: boolean = check === true
- return [link, check, ok]
+ private async linkEnv(identity: JwtIdentityPayload, uuid: string, ignoreAuth: boolean = false): Promise<LinkEnv> {
+ const link = await this.linksQueries.linkFromUUID(uuid)
+ if (!link) {
+ return [link, LINK_ERROR.NOT_FOUND, false]
+ }
+ const check = this.checkLink(identity, link, ignoreAuth)
+ return check === true ? [link, true, true] : [link, check, false]
}
private checkLink(identity: JwtIdentityPayload, link: LinkAsUser, ignoreAuth: boolean = false): string | true {
- if (!link) {
- return LINK_ERROR.NOT_FOUND
- }
if (!link.user.isActive) {
return LINK_ERROR.DISABLED
}
diff --git a/backend/src/applications/links/services/links-queries.service.ts b/backend/src/applications/links/services/links-queries.service.ts
index 0e0910f1..d74b4660 100644
--- a/backend/src/applications/links/services/links-queries.service.ts
+++ b/backend/src/applications/links/services/links-queries.service.ts
@@ -21,6 +21,7 @@ import type { User } from '../../users/schemas/user.interface.js'
import { userFullNameSQL, users } from '../../users/schemas/users.schema.js'
import { CACHE_LINK_UUID_PREFIX, CACHE_LINK_UUID_TTL } from '../constants/cache.js'
import { LINK_TYPE } from '../constants/links.js'
+import type { CreateOrUpdateLinkDto } from '../dto/create-or-update-link.dto.js'
import type { LinkAsUser, LinkGuest } from '../interfaces/link-guest.interface.js'
import type { SpaceLink } from '../interfaces/link-space.interface.js'
import type { Link } from '../schemas/link.interface.js'
@@ -97,7 +98,12 @@ export class LinksQueries {
}
}
- async createLinkToSpaceOrShare(guestId: number, spaceOrShareId: number, type: LINK_TYPE, link: Partial<LinkGuest>): Promise<number> {
+ async createLinkToSpaceOrShare(
+ guestId: number,
+ spaceOrShareId: number,
+ type: LINK_TYPE,
+ link: CreateOrUpdateLinkDto & Pick<Link, 'uuid' | 'userId'>
+ ): Promise<number> {
const linkId = dbGetInsertedId(await this.db.insert(links).values(link as Link))
if (type === LINK_TYPE.SPACE) {
await this.db.insert(spacesMembers).values({
@@ -127,7 +133,7 @@ export class LinksQueries {
.where(and(eq(type == 'share' ? members.shareId : members.spaceId, spaceOrShareId), isNotNull(members.linkId)))
}
- async linkFromUUID(uuid: string): Promise<LinkAsUser> {
+ async linkFromUUID(uuid: string): Promise<LinkAsUser | undefined> {
const { password, ...userColumns } = getTableColumns(users)
const [r] = await this.db
.select({
@@ -138,13 +144,13 @@ export class LinksQueries {
.leftJoin(users, eq(users.id, links.userId))
.where(eq(links.uuid, uuid))
.limit(1)
- return r
+ return r as LinkAsUser | undefined
}
- async spaceLink(uuid: string): Promise<SpaceLink> {
+ async spaceLink(uuid: string): Promise<SpaceLink | undefined> {
const shareOwner: any = alias(users, 'shareOwner')
const shareSpaceRoot: any = alias(spacesRoots, 'shareSpaceRoot')
- const [r]: SpaceLink[] = await this.db
+ const [r] = await this.db
.select({
share: {
name: shares.name,
@@ -175,11 +181,14 @@ export class LinksQueries {
)
.where(eq(links.uuid, uuid))
.limit(1)
+ if (!r) {
+ return undefined
+ }
return {
...r,
space: r.space?.name ? r.space : null,
share: r.share?.name ? r.share : null
- }
+ } as SpaceLink
}
async consumeLinkAccess(uuid: string): Promise<boolean> {
diff --git a/backend/src/applications/notifications/i18n/index.ts b/backend/src/applications/notifications/i18n/index.ts
index 7fa7f88f..fbfe66fe 100644
--- a/backend/src/applications/notifications/i18n/index.ts
+++ b/backend/src/applications/notifications/i18n/index.ts
@@ -35,7 +35,7 @@ export const translations = new Map<i18nLocale, Record<string, string>>([
export function translateObject(language: i18nLocale, obj: Record<string, string>): Record<string, string> {
if (!language || !translations.has(language)) return obj
- const tr: Record<string, string> = translations.get(language)
+ const tr = translations.get(language)
if (!tr) return obj
for (const key in obj) {
const v = obj[key]
diff --git a/backend/src/applications/notifications/interfaces/notification-properties.interface.ts b/backend/src/applications/notifications/interfaces/notification-properties.interface.ts
index dc396568..67681244 100644
--- a/backend/src/applications/notifications/interfaces/notification-properties.interface.ts
+++ b/backend/src/applications/notifications/interfaces/notification-properties.interface.ts
@@ -4,14 +4,24 @@ import type { UserModel } from '../../users/models/user.model.js'
import type { NOTIFICATION_APP } from '../constants/notifications.js'
import type { Notification } from '../schemas/notification.interface.js'
-export interface NotificationContent {
- app: NOTIFICATION_APP
+interface NotificationContentBase {
event: string
element: string
- url: string
externalUrl?: string
}
+type NotificationAppWithoutUrl = NOTIFICATION_APP.LINKS | NOTIFICATION_APP.UPDATE_AVAILABLE
+
+export type NotificationContentFor<T extends NOTIFICATION_APP = NOTIFICATION_APP> = {
+ [App in T]: NotificationContentBase & {
+ app: App
+ url: App extends NotificationAppWithoutUrl ? null : string
+ }
+}[T]
+
+export type NotificationContent = NotificationContentFor
+export type NotificationContentWithUrl = NotificationContentFor<Exclude<NOTIFICATION_APP, NotificationAppWithoutUrl>>
+
export interface NotificationOptions {
author?: UserModel
content?: string
@@ -20,4 +30,30 @@ export interface NotificationOptions {
linkPassword?: string
}
-export type NotificationFromUser = Omit<Notification, 'fromUserId' | 'toUserId'> & { fromUser: Owner }
+type NotificationAppWithoutOptions = NOTIFICATION_APP.AUTH_2FA | NOTIFICATION_APP.AUTH_LOCKED | NOTIFICATION_APP.UPDATE_AVAILABLE
+
+type NotificationOptionsFor<App extends NOTIFICATION_APP> = NotificationOptions &
+ (App extends NOTIFICATION_APP.COMMENTS
+ ? { author: UserModel; content: string }
+ : App extends NOTIFICATION_APP.UNLOCK_REQUEST
+ ? { author: UserModel }
+ : App extends NOTIFICATION_APP.SPACE_ROOTS
+ ? { author: UserModel; action: ACTION }
+ : App extends NOTIFICATION_APP.LINKS
+ ? { action: ACTION; linkUUID: string }
+ : App extends NOTIFICATION_APP.SPACES | NOTIFICATION_APP.SHARES | NOTIFICATION_APP.SYNC
+ ? { action: ACTION }
+ : unknown)
+
+export type NotificationArguments = {
+ [App in NOTIFICATION_APP]: App extends NotificationAppWithoutOptions
+ ? [content: NotificationContentFor<App>, options?: NotificationOptionsFor<App>]
+ : [content: NotificationContentFor<App>, options: NotificationOptionsFor<App>]
+}[NOTIFICATION_APP]
+
+export type NotificationMail = {
+ [App in NOTIFICATION_APP]: NotificationContentFor<App> &
+ (App extends NotificationAppWithoutOptions ? { options?: NotificationOptionsFor<App> } : { options: NotificationOptionsFor<App> })
+}[NOTIFICATION_APP]
+
+export type NotificationFromUser = Omit<Notification, 'fromUserId' | 'toUserId'> & { fromUser: Owner | null }
diff --git a/backend/src/applications/notifications/interfaces/user-mail-notification.interface.ts b/backend/src/applications/notifications/interfaces/user-mail-notification.interface.ts
index eeea1590..5c05514a 100644
--- a/backend/src/applications/notifications/interfaces/user-mail-notification.interface.ts
+++ b/backend/src/applications/notifications/interfaces/user-mail-notification.interface.ts
@@ -3,6 +3,6 @@ import { USER_NOTIFICATION } from '../../users/constants/user.js'
export interface UserMailNotification {
id: number
email: string
- language: string
+ language: string | null
notification: USER_NOTIFICATION
}
diff --git a/backend/src/applications/notifications/mails/models.ts b/backend/src/applications/notifications/mails/models.ts
index 45326743..835ccb37 100644
--- a/backend/src/applications/notifications/mails/models.ts
+++ b/backend/src/applications/notifications/mails/models.ts
@@ -4,8 +4,9 @@ import { i18nLocale } from '../../../common/i18n.js'
import { capitalizeString, SERVER_NAME } from '../../../common/shared.js'
import { fileName } from '../../files/utils/files.js'
import { UserModel } from '../../users/models/user.model.js'
+import { NOTIFICATION_APP } from '../constants/notifications.js'
import { translateObject } from '../i18n/index.js'
-import { NotificationContent } from '../interfaces/notification-properties.interface.js'
+import type { NotificationContentFor } from '../interfaces/notification-properties.interface.js'
import { defaultFooter, mailAuthor, mailEventOnElement, mailItalicContent, mailTemplate } from './templates.js'
import { urlFromLink, urlFromSpace, urlFromSpaceFile, urlFromSync } from './urls.js'
@@ -15,7 +16,7 @@ function mailActionLink(urlText: string, url?: string): string {
export function commentMail(
language: i18nLocale,
- notification: NotificationContent,
+ notification: NotificationContentFor<NOTIFICATION_APP.COMMENTS>,
options: {
content: string
publicUrl?: string
@@ -40,7 +41,7 @@ export function commentMail(
export function spaceMail(
language: i18nLocale,
- notification: NotificationContent,
+ notification: NotificationContentFor<NOTIFICATION_APP.SPACES>,
options: {
publicUrl?: string
action: ACTION
@@ -64,7 +65,7 @@ export function spaceMail(
export function spaceRootMail(
language: i18nLocale,
- notification: NotificationContent,
+ notification: NotificationContentFor<NOTIFICATION_APP.SPACE_ROOTS>,
options: {
publicUrl?: string
author: UserModel
@@ -95,10 +96,10 @@ export function spaceRootMail(
export function shareMail(
language: i18nLocale,
- notification: NotificationContent,
+ notification: NotificationContentFor<NOTIFICATION_APP.SHARES>,
options: {
publicUrl?: string
- author: UserModel
+ author?: UserModel
action: ACTION
}
): [string, string] {
@@ -119,13 +120,13 @@ export function shareMail(
export function linkMail(
language: i18nLocale,
- notification: NotificationContent,
+ notification: NotificationContentFor<NOTIFICATION_APP.LINKS>,
options: {
publicUrl?: string
- author: UserModel
+ author?: UserModel
action: ACTION
linkUUID: string
- linkPassword: string
+ linkPassword?: string
}
): [string, string] {
const tr = translateObject(language, {
@@ -149,7 +150,7 @@ export function linkMail(
export function syncMail(
language: i18nLocale,
- notification: NotificationContent,
+ notification: NotificationContentFor<NOTIFICATION_APP.SYNC>,
options: {
publicUrl?: string
action: ACTION
@@ -171,7 +172,7 @@ export function syncMail(
return [`${tr.title}: ${capitalizeString(notification.element)}`, mailTemplate(content, footer)]
}
-export function auth2FaMail(language: i18nLocale, notification: NotificationContent): [string, string] {
+export function auth2FaMail(language: i18nLocale, notification: NotificationContentFor<NOTIFICATION_APP.AUTH_2FA>): [string, string] {
const tr = translateObject(language, {
title: 'Security notification',
footer:
@@ -188,7 +189,7 @@ export function auth2FaMail(language: i18nLocale, notification: NotificationCont
return [tr.title, mailTemplate(content, footer)]
}
-export function authLockedMail(language: i18nLocale, notification: NotificationContent): [string, string] {
+export function authLockedMail(language: i18nLocale, notification: NotificationContentFor<NOTIFICATION_APP.AUTH_LOCKED>): [string, string] {
const tr = translateObject(language, {
title: 'Security notification',
footer: 'You can try signing in again after 15 minutes. If you did not make these attempts, please contact your administrator.',
@@ -205,7 +206,7 @@ export function authLockedMail(language: i18nLocale, notification: NotificationC
export function requestUnlockMail(
language: i18nLocale,
- notification: NotificationContent,
+ notification: NotificationContentFor<NOTIFICATION_APP.UNLOCK_REQUEST>,
options: {
publicUrl?: string
author: UserModel
@@ -227,7 +228,10 @@ export function requestUnlockMail(
return [`${tr.title}: ${capitalizeString(notification.element)}`, mailTemplate(content, footer)]
}
-export function serverUpdateAvailableMail(language: i18nLocale, notification: NotificationContent): [string, string] {
+export function serverUpdateAvailableMail(
+ language: i18nLocale,
+ notification: NotificationContentFor<NOTIFICATION_APP.UPDATE_AVAILABLE>
+): [string, string] {
const tr = translateObject(language, {
title: 'New Version Available',
defaultFooter: defaultFooter,
diff --git a/backend/src/applications/notifications/mails/urls.ts b/backend/src/applications/notifications/mails/urls.ts
index e04fc6b6..a32206a5 100644
--- a/backend/src/applications/notifications/mails/urls.ts
+++ b/backend/src/applications/notifications/mails/urls.ts
@@ -1,7 +1,7 @@
import { PUBLIC_LINKS_ROUTE } from '../../links/constants/routes.js'
import { SPACES_BASE_ROUTE } from '../../spaces/constants/routes.js'
import { SYNC_BASE_ROUTE } from '../../sync/constants/routes.js'
-import { NotificationContent } from '../interfaces/notification-properties.interface.js'
+import type { NotificationContentWithUrl } from '../interfaces/notification-properties.interface.js'
function encodePath(path: string): string {
return path
@@ -14,7 +14,7 @@ export function urlSpaceBase(url: string): string {
return url ? `${url}/#/${SPACES_BASE_ROUTE}` : ''
}
-export function urlFromSpaceFile(url: string, notification: NotificationContent): string {
+export function urlFromSpaceFile(url: string, notification: NotificationContentWithUrl): string {
return `${urlSpaceBase(url)}/${encodePath(notification.url)}?select=${encodeURIComponent(notification.element)}`
}
diff --git a/backend/src/applications/notifications/notifications.controller.ts b/backend/src/applications/notifications/notifications.controller.ts
index 96a6f028..fc4927f2 100644
--- a/backend/src/applications/notifications/notifications.controller.ts
+++ b/backend/src/applications/notifications/notifications.controller.ts
@@ -1,4 +1,5 @@
-import { Controller, Delete, Get, Param, ParseIntPipe, Patch } from '@nestjs/common'
+import { Controller, Delete, Get, Param, Patch } from '@nestjs/common'
+import { integerFromStringSchema } from '../../configuration/config.schema.js'
import { GetUser } from '../users/decorators/user.decorator.js'
import type { UserModel } from '../users/models/user.model.js'
import { NOTIFICATIONS_ROUTE } from './constants/routes.js'
@@ -20,7 +21,7 @@ export class NotificationsController {
}
@Patch(':id')
- wasRead(@GetUser() user: UserModel, @Param('id', ParseIntPipe) notificationId: number): void {
+ wasRead(@GetUser() user: UserModel, @Param('id', { schema: integerFromStringSchema }) notificationId: number): void {
return this.notificationsManager.wasRead(user, notificationId)
}
@@ -30,7 +31,7 @@ export class NotificationsController {
}
@Delete(':id')
- delete(@GetUser() user: UserModel, @Param('id', ParseIntPipe) notificationId: number): Promise<void> {
+ delete(@GetUser() user: UserModel, @Param('id', { schema: integerFromStringSchema }) notificationId: number): Promise<void> {
return this.notificationsManager.delete(user, notificationId)
}
}
diff --git a/backend/src/applications/notifications/notifications.gateway.ts b/backend/src/applications/notifications/notifications.gateway.ts
index 5498ff4e..b9c42a0d 100644
--- a/backend/src/applications/notifications/notifications.gateway.ts
+++ b/backend/src/applications/notifications/notifications.gateway.ts
@@ -5,7 +5,7 @@ import { NOTIFICATIONS_WS } from './constants/websocket.js'
@WebSocketGateway({ namespace: NOTIFICATIONS_WS.NAME_SPACE })
export class WebSocketNotifications {
- @WebSocketServer() server: Server
+ @WebSocketServer() server!: Server
sendMessageToUsers(userIds: number[], eventName: string, body: any) {
if (userIds.length) {
diff --git a/backend/src/applications/notifications/schemas/notification.interface.ts b/backend/src/applications/notifications/schemas/notification.interface.ts
index 61aea98d..f1ad04bf 100644
--- a/backend/src/applications/notifications/schemas/notification.interface.ts
+++ b/backend/src/applications/notifications/schemas/notification.interface.ts
@@ -1,13 +1,3 @@
-import { NotificationContent } from '../interfaces/notification-properties.interface.js'
-import { notifications } from './notifications.schema.js'
+import type { notifications } from './notifications.schema.js'
-type NotificationSchema = typeof notifications.$inferSelect
-
-export class Notification implements NotificationSchema {
- id: number
- toUserId: number
- fromUserId: number
- content: NotificationContent
- wasRead: boolean
- createdAt: Date
-}
+export type Notification = typeof notifications.$inferSelect
diff --git a/backend/src/applications/notifications/services/notifications-manager.service.spec.ts b/backend/src/applications/notifications/services/notifications-manager.service.spec.ts
index 405f594c..239e9137 100644
--- a/backend/src/applications/notifications/services/notifications-manager.service.spec.ts
+++ b/backend/src/applications/notifications/services/notifications-manager.service.spec.ts
@@ -111,7 +111,7 @@ describe(NotificationsManager.name, () => {
expect(notificationsQueriesMock.create).toHaveBeenCalledWith(null, toUserIds, content)
expect(webSocketNotificationsMock.sendMessageToUsers).toHaveBeenCalledWith(toUserIds, NOTIFICATIONS_WS.EVENTS.NOTIFICATION, 'check')
expect(notificationsQueriesMock.usersNotifiedByEmail).toHaveBeenCalledWith(toUserIds)
- expect(sendEmailSpy).toHaveBeenCalledWith(emailUsers as any, content, undefined)
+ expect(sendEmailSpy).toHaveBeenCalledWith(emailUsers as any, content)
})
it('does not try email when mailer is unavailable', async () => {
@@ -159,7 +159,7 @@ describe(NotificationsManager.name, () => {
expect(notificationsQueriesMock.wasRead).toHaveBeenCalledWith(5, 123)
const loggerSpy = spyLogger()
notificationsQueriesMock.wasRead.mockRejectedValueOnce(new Error('fail'))
- service.wasRead({ id: 8 } as any, undefined)
+ service.wasRead({ id: 8 } as any, 456)
await flushPromises()
expect(loggerSpy).toHaveBeenCalled()
expect(loggerSpy.mock.calls[0]?.[0]).toMatchObject({ tag: 'wasRead' })
diff --git a/backend/src/applications/notifications/services/notifications-manager.service.ts b/backend/src/applications/notifications/services/notifications-manager.service.ts
index 19edb000..2e36da81 100644
--- a/backend/src/applications/notifications/services/notifications-manager.service.ts
+++ b/backend/src/applications/notifications/services/notifications-manager.service.ts
@@ -1,3 +1,4 @@
+import { toErrorMessage } from '../../../common/errors.js'
import { Injectable, Logger } from '@nestjs/common'
import { i18nLocale } from '../../../common/i18n.js'
import { configuration } from '../../../configuration/config.environment.js'
@@ -8,7 +9,12 @@ import { UserModel } from '../../users/models/user.model.js'
import { getAvatarBase64 } from '../../users/utils/avatar.js'
import { NOTIFICATION_APP } from '../constants/notifications.js'
import { NOTIFICATIONS_WS } from '../constants/websocket.js'
-import type { NotificationContent, NotificationFromUser, NotificationOptions } from '../interfaces/notification-properties.interface.js'
+import type {
+ NotificationArguments,
+ NotificationContent,
+ NotificationFromUser,
+ NotificationMail
+} from '../interfaces/notification-properties.interface.js'
import type { UserMailNotification } from '../interfaces/user-mail-notification.interface.js'
import {
auth2FaMail,
@@ -28,7 +34,7 @@ import { NotificationsQueries } from './notifications-queries.service.js'
@Injectable()
export class NotificationsManager {
private readonly logger = new Logger(NotificationsManager.name)
- private readonly publicUrl = configuration.server.publicUrl
+ private readonly publicUrl = configuration.server.publicUrl ?? undefined
constructor(
private readonly mailer: Mailer,
@@ -44,11 +50,14 @@ export class NotificationsManager {
return this.notificationsQueries.list(user.id, onlyUnread)
}
- async create(toUsers: UserMailNotification[] | number[], content: NotificationContent, options?: NotificationOptions): Promise<void> {
+ async create(toUsers: UserMailNotification[] | number[], ...notification: NotificationArguments): Promise<void> {
+ const [content, options] = notification
// store it in db
const isArrayOfUsers: boolean = typeof toUsers[0] === 'object'
const toUserIds = isArrayOfUsers ? (toUsers as UserMailNotification[]).map((m) => m.id) : (toUsers as number[])
- this.storeNotification(toUserIds, content, options?.author?.id).catch((e: Error) => this.logger.error({ tag: this.create.name, msg: `${e}` }))
+ this.storeNotification(toUserIds, content, options?.author?.id).catch((e: Error) =>
+ this.logger.error({ tag: this.create.name, msg: toErrorMessage(e) })
+ )
// send websocket notification
this.webSocketNotifications.sendMessageToUsers(toUserIds, NOTIFICATIONS_WS.EVENTS.NOTIFICATION, 'check')
@@ -61,41 +70,42 @@ export class NotificationsManager {
if (!usersNotifiedByEmail.length) {
return
}
- this.sendEmailNotification(usersNotifiedByEmail, content, options).catch((e: Error) =>
- this.logger.error({ tag: this.create.name, msg: `${e}` })
+ this.sendEmailNotification(usersNotifiedByEmail, ...notification).catch((e: Error) =>
+ this.logger.error({ tag: this.create.name, msg: toErrorMessage(e) })
)
}
}
- wasRead(user: UserModel, notificationId?: number): void {
- this.notificationsQueries.wasRead(user.id, notificationId).catch((e: Error) => this.logger.error({ tag: this.wasRead.name, msg: `${e}` }))
+ wasRead(user: UserModel, notificationId: number): void {
+ this.notificationsQueries
+ .wasRead(user.id, notificationId)
+ .catch((e: Error) => this.logger.error({ tag: this.wasRead.name, msg: toErrorMessage(e) }))
}
async delete(user: UserModel, notificationId?: number): Promise<void> {
return this.notificationsQueries.delete(user.id, notificationId)
}
- async sendEmailNotification(toUsers: UserMailNotification[], content: NotificationContent, options?: NotificationOptions): Promise<void> {
+ async sendEmailNotification(toUsers: UserMailNotification[], ...notification: NotificationArguments): Promise<void> {
if (!this.mailer.available) {
return
}
+ const [, options] = notification
if (options?.author) {
options.author.avatarBase64 = await getAvatarBase64(options.author.login)
}
this.mailer
.sendMails(
- await Promise.all(
- toUsers.map(async (m) => {
- const [title, html] = this.genMail(m.language as i18nLocale, content, options)
- return {
- to: m.email,
- subject: title,
- html: html
- } satisfies MailProps
- })
- )
+ toUsers.map((m) => {
+ const [title, html] = this.genMail(m.language as i18nLocale, ...notification)!
+ return {
+ to: m.email,
+ subject: title,
+ html: html
+ } satisfies MailProps
+ })
)
- .catch((e: Error) => this.logger.error({ tag: this.sendEmailNotification.name, msg: `${e}` }))
+ .catch((e: Error) => this.logger.error({ tag: this.sendEmailNotification.name, msg: toErrorMessage(e) }))
}
private async storeNotification(toUserIds: number[], content: NotificationContent, authorId?: number): Promise<void> {
@@ -103,40 +113,57 @@ export class NotificationsManager {
try {
await this.notificationsQueries.create(authorId || null, toUserIds, content)
} catch (e) {
- this.logger.error({ tag: this.storeNotification.name, msg: `${e}` })
+ this.logger.error({ tag: this.storeNotification.name, msg: toErrorMessage(e) })
}
}
- private genMail(language: i18nLocale, content: NotificationContent, options?: NotificationOptions): [string, string] {
- switch (content.app) {
+ private genMail(language: i18nLocale, ...[content, options]: NotificationArguments): [string, string] | undefined {
+ // The argument tuple enforces the correlation; grouping it lets the switch narrow the options too.
+ const notification = { ...content, options } as NotificationMail
+ switch (notification.app) {
case NOTIFICATION_APP.COMMENTS:
- return commentMail(language, content, { content: options.content, publicUrl: this.publicUrl, author: options.author })
+ return commentMail(language, notification, {
+ content: notification.options.content,
+ publicUrl: this.publicUrl,
+ author: notification.options.author
+ })
case NOTIFICATION_APP.SPACES:
- return spaceMail(language, content, { publicUrl: this.publicUrl, action: options.action })
+ return spaceMail(language, notification, { publicUrl: this.publicUrl, action: notification.options.action })
case NOTIFICATION_APP.SPACE_ROOTS:
- return spaceRootMail(language, content, { publicUrl: this.publicUrl, author: options.author, action: options.action })
+ return spaceRootMail(language, notification, {
+ publicUrl: this.publicUrl,
+ author: notification.options.author,
+ action: notification.options.action
+ })
case NOTIFICATION_APP.SHARES:
- return shareMail(language, content, { publicUrl: this.publicUrl, author: options.author, action: options.action })
+ return shareMail(language, notification, {
+ publicUrl: this.publicUrl,
+ author: notification.options.author,
+ action: notification.options.action
+ })
case NOTIFICATION_APP.LINKS:
- return linkMail(language, content, {
+ return linkMail(language, notification, {
publicUrl: this.publicUrl,
- author: options.author,
- linkUUID: options.linkUUID,
- linkPassword: options.linkPassword,
- action: options.action
+ author: notification.options.author,
+ linkUUID: notification.options.linkUUID,
+ linkPassword: notification.options.linkPassword,
+ action: notification.options.action
})
case NOTIFICATION_APP.SYNC:
- return syncMail(language, content, { publicUrl: this.publicUrl, action: options.action })
+ return syncMail(language, notification, { publicUrl: this.publicUrl, action: notification.options.action })
case NOTIFICATION_APP.AUTH_2FA:
- return auth2FaMail(language, content)
+ return auth2FaMail(language, notification)
case NOTIFICATION_APP.AUTH_LOCKED:
- return authLockedMail(language, content)
+ return authLockedMail(language, notification)
case NOTIFICATION_APP.UNLOCK_REQUEST:
- return requestUnlockMail(language, content, { publicUrl: this.publicUrl, author: options.author })
+ return requestUnlockMail(language, notification, {
+ publicUrl: this.publicUrl,
+ author: notification.options.author
+ })
case NOTIFICATION_APP.UPDATE_AVAILABLE:
- return serverUpdateAvailableMail(language, content)
+ return serverUpdateAvailableMail(language, notification)
default:
- this.logger.error({ tag: this.genMail.name, msg: `case not handled : ${content.app}` })
+ this.logger.error({ tag: this.genMail.name, msg: `case not handled: ${JSON.stringify(content)}` })
}
}
}
diff --git a/backend/src/applications/notifications/services/notifications-queries.service.ts b/backend/src/applications/notifications/services/notifications-queries.service.ts
index 863d35bc..dead607b 100644
--- a/backend/src/applications/notifications/services/notifications-queries.service.ts
+++ b/backend/src/applications/notifications/services/notifications-queries.service.ts
@@ -1,5 +1,5 @@
import { Inject, Injectable } from '@nestjs/common'
-import { and, desc, eq, inArray, SelectedFields, SQL } from 'drizzle-orm'
+import { and, desc, eq, inArray, SQL } from 'drizzle-orm'
import { DB_TOKEN_PROVIDER } from '../../../infrastructure/database/constants.js'
import { type DBSchema } from '../../../infrastructure/database/interfaces/database.interface.js'
import { dbCheckAffectedRows } from '../../../infrastructure/database/utils.js'
@@ -7,7 +7,7 @@ import { USER_NOTIFICATION } from '../../users/constants/user.js'
import { userFullNameSQL, users } from '../../users/schemas/users.schema.js'
import type { NotificationContent, NotificationFromUser } from '../interfaces/notification-properties.interface.js'
import type { UserMailNotification } from '../interfaces/user-mail-notification.interface.js'
-import { Notification } from '../schemas/notification.interface.js'
+import type { Notification } from '../schemas/notification.interface.js'
import { notifications } from '../schemas/notifications.schema.js'
@Injectable()
@@ -23,14 +23,14 @@ export class NotificationsQueries {
content: notifications.content,
wasRead: notifications.wasRead,
createdAt: notifications.createdAt
- } satisfies NotificationFromUser | SelectedFields<any, any>)
+ } satisfies Record<keyof NotificationFromUser, any>)
.from(notifications)
.leftJoin(users, eq(users.id, notifications.fromUserId))
.where(and(...where))
.orderBy(desc(notifications.id))
}
- async create(fromUserId: number, toUserIds: number[], content: NotificationContent): Promise<void> {
+ async create(fromUserId: number | null, toUserIds: number[], content: NotificationContent): Promise<void> {
dbCheckAffectedRows(
await this.db.insert(notifications).values(
toUserIds.map((toUserId: number) => ({
@@ -62,7 +62,7 @@ export class NotificationsQueries {
email: users.email,
language: users.language,
notification: users.notification
- } satisfies UserMailNotification | SelectedFields<any, any>)
+ } satisfies Record<keyof UserMailNotification, any>)
.from(users)
.where(and(inArray(users.id, userIds), eq(users.notification, USER_NOTIFICATION.APPLICATION_EMAIL)))
}
diff --git a/backend/src/applications/shares/dto/create-or-update-share.dto.spec.ts b/backend/src/applications/shares/dto/create-or-update-share.dto.spec.ts
new file mode 100644
index 00000000..90bca170
--- /dev/null
+++ b/backend/src/applications/shares/dto/create-or-update-share.dto.spec.ts
@@ -0,0 +1,125 @@
+import { MEMBER_TYPE } from '../../users/constants/member.js'
+import { createOrUpdateShareSchema } from './create-or-update-share.dto.js'
+
+describe('createOrUpdateShareSchema', () => {
+ const largeInteger = 2 ** 53
+
+ it.each([{ name: 'share' }, { name: 'share', members: null, links: null }])('normalizes missing or null member collections', (input) => {
+ expect(createOrUpdateShareSchema.parse(input)).toEqual(expect.objectContaining({ members: [], links: [], storageQuota: null }))
+ })
+
+ it('normalizes a null alias to an empty string', () => {
+ expect(createOrUpdateShareSchema.parse({ name: 'share', alias: null }).alias).toBe('')
+ })
+
+ it('accepts a child share without a file owner id', () => {
+ const file = { id: 42, path: 'folder' }
+ const input = { name: 'child', parent: { alias: 'parent' }, file }
+
+ expect(createOrUpdateShareSchema.parse(input).file).toEqual(file)
+ })
+
+ it('accepts an external space root when updating a share', () => {
+ const file = {
+ id: null,
+ ownerId: null,
+ path: '.',
+ space: { alias: 'team', name: 'Team', root: { alias: 'external-root', name: 'External root' } }
+ }
+
+ expect(createOrUpdateShareSchema.parse({ id: 843, name: 'renamed share', externalPath: null, file }).file).toEqual(file)
+ })
+
+ it.each([null, 42])('normalizes file properties before conditional validation for id %s', (id) => {
+ const file = {
+ id,
+ ownerId: null,
+ path: 'folder//file.txt',
+ space: { alias: ' team ', name: null, root: { alias: ' external/root.. ', name: null } }
+ }
+
+ expect(createOrUpdateShareSchema.parse({ name: 'share', file }).file).toEqual({
+ id,
+ ownerId: null,
+ path: 'folder/file.txt',
+ space: { alias: 'team', name: '', root: { alias: 'externalroot', name: '' } }
+ })
+ expect(file.space.alias).toBe(' team ')
+ expect(file.path).toBe('folder//file.txt')
+ })
+
+ it('preserves omitted names and extra file properties when validation is skipped', () => {
+ const file = { id: null, ownerId: null, path: '.', mime: 'inode/directory', space: { root: {} } }
+
+ expect(createOrUpdateShareSchema.parse({ name: 'share', file }).file).toEqual(file)
+ })
+
+ it('still validates files with an id', () => {
+ const input = { name: 'share', file: { id: 42, ownerId: null, path: '.' } }
+
+ expect(createOrUpdateShareSchema.safeParse(input).success).toBe(true)
+ const result = createOrUpdateShareSchema.safeParse({ ...input, file: { ...input.file, path: null } })
+
+ expect(result.success).toBe(false)
+ if (!result.success) {
+ expect(result.error.issues).toEqual(expect.arrayContaining([expect.objectContaining({ path: ['file', 'path'] })]))
+ }
+ })
+
+ it('rejects a path emptied by normalization for a file with an id', () => {
+ expect(createOrUpdateShareSchema.safeParse({ name: 'share', file: { id: 42, ownerId: null, path: '../' } }).success).toBe(false)
+ })
+
+ it('accepts large share, member and link ids and storage quotas', () => {
+ const member = { id: largeInteger, type: MEMBER_TYPE.USER, linkId: largeInteger }
+ const result = createOrUpdateShareSchema.parse({
+ id: largeInteger,
+ name: 'share',
+ storageQuota: largeInteger,
+ members: [member],
+ links: [member]
+ })
+
+ expect(result).toMatchObject({ id: largeInteger, storageQuota: largeInteger, members: [member], links: [member] })
+ })
+
+ it('accepts a large negative inode as a file reference', () => {
+ const file = { id: -largeInteger, ownerId: null, path: 'folder//file.txt' }
+
+ expect(createOrUpdateShareSchema.parse({ name: 'share', file }).file).toEqual({ ...file, path: 'folder/file.txt' })
+ })
+
+ it('accepts a large persisted file id when updating a share', () => {
+ const file = { id: largeInteger, ownerId: null, path: 'folder//file.txt' }
+
+ expect(createOrUpdateShareSchema.parse({ id: 42, name: 'renamed share', file }).file).toEqual({ ...file, path: 'folder/file.txt' })
+ })
+
+ it.each([1.5, -1.5, Infinity, -Infinity])('rejects an invalid file reference %s when file validation applies', (id) => {
+ const result = createOrUpdateShareSchema.safeParse({ name: 'share', file: { id, ownerId: null, path: 'folder' } })
+
+ expect(result.success).toBe(false)
+ if (!result.success) {
+ expect(result.error.issues).toEqual(expect.arrayContaining([expect.objectContaining({ path: ['file', 'id'] })]))
+ }
+ })
+
+ it.each(['id', 'storageQuota'])('still rejects a fractional %s', (field) => {
+ expect(createOrUpdateShareSchema.safeParse({ name: 'share', [field]: 1.5 }).success).toBe(false)
+ })
+
+ it.each(['id', 'linkId'])('still rejects a fractional member %s', (field) => {
+ expect(createOrUpdateShareSchema.safeParse({ name: 'share', members: [{ id: 1, type: MEMBER_TYPE.USER, [field]: 1.5 }] }).success).toBe(false)
+ })
+
+ it('preserves null ids, storage quotas and member link ids', () => {
+ const result = createOrUpdateShareSchema.parse({
+ name: 'share',
+ id: null,
+ storageQuota: null,
+ members: [{ id: 1, type: MEMBER_TYPE.USER, linkId: null }]
+ })
+
+ expect(result).toMatchObject({ id: null, storageQuota: null, members: [{ linkId: null }] })
+ })
+})
diff --git a/backend/src/applications/shares/dto/create-or-update-share.dto.ts b/backend/src/applications/shares/dto/create-or-update-share.dto.ts
index 20a059eb..dc4cfc12 100644
--- a/backend/src/applications/shares/dto/create-or-update-share.dto.ts
+++ b/backend/src/applications/shares/dto/create-or-update-share.dto.ts
@@ -1,156 +1,135 @@
-import { Transform, Type } from 'class-transformer'
-import { IsArray, IsBoolean, IsEnum, IsInt, IsNotEmpty, IsOptional, IsString, ValidateIf, ValidateNested } from 'class-validator'
-import { FileSpace } from '../../files/interfaces/file-space.interface.js'
+import { z } from 'zod'
+import { integerNumberSchema } from '../../../configuration/config.schema.js'
import { sanitizeName, sanitizePath } from '../../files/utils/files.js'
-import { CreateOrUpdateLinkDto } from '../../links/dto/create-or-update-link.dto.js'
+import { createOrUpdateLinkSchema } from '../../links/dto/create-or-update-link.dto.js'
import { MEMBER_TYPE, MEMBER_TYPE_REVERSE } from '../../users/constants/member.js'
+import type { Member } from '../../users/interfaces/member.interface.js'
import { SHARE_TYPE } from '../constants/shares.js'
-export class ShareMemberDto {
- @IsNotEmpty()
- @IsInt()
- id: number
-
- @IsNotEmpty()
- @IsString()
- @Transform(({ value }) => MEMBER_TYPE_REVERSE[value])
- type: MEMBER_TYPE
-
- @IsOptional()
- @IsString()
- permissions?: string = ''
-
- @IsOptional()
- @IsInt()
- linkId?: number
+const shareMemberTypeSchema = z.enum(MEMBER_TYPE).overwrite((value) => MEMBER_TYPE_REVERSE[value])
+export const shareMemberSchema = z.object({
+ id: integerNumberSchema,
+ type: shareMemberTypeSchema,
+ permissions: z.string().nullish().default(''),
+ linkId: integerNumberSchema.nullish(),
// used only to update the link
- @IsOptional()
- @ValidateNested()
- @Type(() => CreateOrUpdateLinkDto)
- linkSettings?: CreateOrUpdateLinkDto = null
-}
+ linkSettings: createOrUpdateLinkSchema.nullish().default(null)
+})
-export class ShareFileSpaceRootDto {
- @IsOptional()
- @IsString()
- @Transform(({ value }) => (value ? sanitizeName(value.trim()) : ''))
- alias: string
+export type ShareMemberDto = z.output<typeof shareMemberSchema>
- @IsOptional()
- @IsString()
- @Transform(({ value }) => (value ? sanitizeName(value.trim()) : ''))
- name: string
+export type ShareMemberInputDto = Pick<Member, 'id' | 'type'> & {
+ permissions?: string | null
+ linkId?: number | null
+ linkSettings?: Member['linkSettings'] | null
}
-export class ShareFileSpaceDto {
- @IsOptional()
- @IsString()
- @Transform(({ value }) => (value ? value.trim() : ''))
- alias: string
-
- @IsOptional()
- @IsString()
- @Transform(({ value }) => (value ? value.trim() : ''))
- name: string
-
- @IsOptional()
- @ValidateNested()
- @Type(() => ShareFileSpaceRootDto)
- root: ShareFileSpaceRootDto
-}
+// File properties are normalized by transformShareFile before these schemas validate them.
+const optionalFileNameSchema = z.string().optional()
-export class ShareParentDto {
- @IsNotEmpty()
- @IsString()
- @Transform(({ value }) => (value ? value.trim() : ''))
- alias: string
-}
+export const shareFileSpaceRootSchema = z.object({
+ alias: optionalFileNameSchema,
+ name: optionalFileNameSchema
+})
-export class ShareFileDto implements Omit<FileSpace, 'mime' | 'name' | 'inTrash' | 'isDir'> {
- @IsNotEmpty()
- @IsInt()
- id: number
+export const shareFileSpaceSchema = z.object({
+ alias: optionalFileNameSchema,
+ name: optionalFileNameSchema,
+ root: shareFileSpaceRootSchema.nullish()
+})
- @ValidateIf((_, ownerId) => ownerId === null || typeof ownerId === 'number')
- ownerId: number
+export const shareParentSchema = z.object({
+ alias: z.string().trim().min(1)
+})
- @IsNotEmpty()
- @IsString()
- @Transform(({ value }) => sanitizePath(value))
- path: string
+export type ShareParentDto = z.infer<typeof shareParentSchema>
- @IsOptional()
- @IsString()
- permissions?: string
+export const shareFileSchema = z.object({
+ id: integerNumberSchema,
+ ownerId: z.number().nullish(),
+ path: z.string().min(1),
+ permissions: z.string().nullish(),
+ space: shareFileSpaceSchema.nullish()
+})
- @IsOptional()
- @ValidateNested()
- @Type(() => ShareFileSpaceDto)
- space: ShareFileSpaceDto
-}
+export type ShareFileDto = z.infer<typeof shareFileSchema>
-export class CreateOrUpdateShareDto {
- @IsOptional()
- @IsInt()
- id?: number
+const sanitizedShareNameSchema = z.string().trim().overwrite(sanitizeName)
+const nullableSanitizedShareNameSchema = sanitizedShareNameSchema.nullable().transform((value) => value ?? '')
- @IsNotEmpty()
- @IsString()
- @Transform(({ value }) => (value ? sanitizeName(value.trim()) : ''))
- name: string
+const transformOptionalName = (value: unknown, sanitize: boolean): unknown => {
+ if (typeof value === 'string') return value ? (sanitize ? sanitizeName(value.trim()) : value.trim()) : ''
+ return value ? value : ''
+}
- @IsOptional()
- @IsString()
- @Transform(({ value }) => (value ? sanitizeName(value.trim()) : ''))
- alias?: string
+const transformShareFile = (value: unknown): unknown => {
+ if (value === null || typeof value !== 'object' || Array.isArray(value)) return value
+ const file = { ...value } as Record<string, unknown>
+ if ('path' in file && typeof file.path === 'string') file.path = sanitizePath(file.path)
+ if (file.space !== null && typeof file.space === 'object' && !Array.isArray(file.space)) {
+ const space = { ...file.space } as Record<string, unknown>
+ if ('alias' in space) space.alias = transformOptionalName(space.alias, false)
+ if ('name' in space) space.name = transformOptionalName(space.name, false)
+ if (space.root !== null && typeof space.root === 'object' && !Array.isArray(space.root)) {
+ const root = { ...space.root } as Record<string, unknown>
+ if ('alias' in root) root.alias = transformOptionalName(root.alias, true)
+ if ('name' in root) root.name = transformOptionalName(root.name, true)
+ space.root = root
+ }
+ file.space = space
+ }
+ return file
+}
- @IsOptional()
- @IsEnum(SHARE_TYPE)
- type?: SHARE_TYPE
-
- @IsOptional()
- @IsString()
- description?: string
-
- @IsOptional()
- @IsString()
- externalPath?: string = null
-
- @IsOptional()
- @IsBoolean()
- enabled?: boolean
-
- @IsOptional()
- @IsInt()
- storageQuota?: number = null
-
- @IsOptional()
- @IsBoolean()
- storageIndexing?: boolean
-
- @IsOptional()
- @ValidateNested()
- @Type(() => ShareParentDto)
- parent?: ShareParentDto
-
- @IsOptional()
- @ValidateIf((_, file) => !_.externalPath && file?.id)
- @ValidateNested()
- @Type(() => ShareFileDto)
- file?: ShareFileDto
-
- @IsOptional()
- @IsArray()
- @ValidateNested({ each: true })
- @Type(() => ShareMemberDto)
+const createOrUpdateShareBaseSchema = z.object({
+ id: integerNumberSchema.nullish(),
+ name: sanitizedShareNameSchema.min(1),
+ alias: nullableSanitizedShareNameSchema.optional(),
+ type: z.enum(SHARE_TYPE).nullish(),
+ description: z.string().nullish(),
+ externalPath: z.string().nullish().default(null),
+ enabled: z.boolean().nullish(),
+ storageQuota: integerNumberSchema.nullish().default(null),
+ storageIndexing: z.boolean().nullish(),
+ parent: shareParentSchema.nullish(),
+ // Validation is conditional to preserve the former ValidateIf semantics.
+ file: z.unknown().transform(transformShareFile).nullish(),
// contains members (users, guests, links, groups, personal groups)
- members?: ShareMemberDto[] = []
-
- @IsOptional()
- @IsArray()
- @ValidateNested({ each: true })
- @Type(() => ShareMemberDto)
+ members: z.preprocess((value) => value ?? [], z.array(shareMemberSchema)),
// contains links
- links?: ShareMemberDto[] = []
+ links: z.preprocess((value) => value ?? [], z.array(shareMemberSchema))
+})
+
+type CreateOrUpdateShareSchemaOutput = Omit<z.output<typeof createOrUpdateShareBaseSchema>, 'file'> & {
+ file?: ShareFileDto | null
}
+
+export const createOrUpdateShareSchema = createOrUpdateShareBaseSchema.transform((share, ctx): CreateOrUpdateShareSchemaOutput => {
+ const { externalPath, file, ...shareProps } = share
+ if (externalPath) return { ...shareProps, externalPath }
+ if (file === undefined) return { ...shareProps, externalPath: null }
+ if (file === null) return { ...shareProps, externalPath: null, file: null }
+
+ // External space roots have no file id; preserve the former ValidateIf(file?.id) behavior.
+ const shareFile = file as ShareFileDto
+ if (!shareFile.id) return { ...shareProps, externalPath: null, file: shareFile }
+
+ const result = shareFileSchema.safeParse(file)
+ if (!result.success) {
+ for (const issue of result.error.issues) {
+ ctx.addIssue({ code: 'custom', input: file, message: issue.message, path: ['file', ...issue.path] })
+ }
+ return z.NEVER
+ }
+ return { ...shareProps, externalPath: null, file: result.data }
+})
+
+export type CreateOrUpdateShareDto = Omit<z.input<typeof createOrUpdateShareSchema>, 'alias' | 'file' | 'members' | 'links'> & {
+ alias?: string
+ file?: ShareFileDto | null
+ members?: ShareMemberInputDto[] | null
+ links?: ShareMemberInputDto[] | null
+}
+
+export type ValidatedCreateOrUpdateShareDto = z.output<typeof createOrUpdateShareSchema>
diff --git a/backend/src/applications/shares/interfaces/share-child.interface.ts b/backend/src/applications/shares/interfaces/share-child.interface.ts
index cb054678..95e1cfd4 100644
--- a/backend/src/applications/shares/interfaces/share-child.interface.ts
+++ b/backend/src/applications/shares/interfaces/share-child.interface.ts
@@ -6,10 +6,10 @@ export interface ShareChildQuery extends Pick<Share, 'id' | 'parentId' | 'type'
type: number
alias: string
name: string
- ownerLogin: string
- ownerFullName: string
- ownerEmail: string
- fileMime: string
+ ownerLogin: string | null
+ ownerFullName: string | null
+ ownerEmail: string | null
+ fileMime: string | null
}
export interface ShareChildMember {
diff --git a/backend/src/applications/shares/interfaces/share-file.interface.ts b/backend/src/applications/shares/interfaces/share-file.interface.ts
index 13e864c7..e1d3334a 100644
--- a/backend/src/applications/shares/interfaces/share-file.interface.ts
+++ b/backend/src/applications/shares/interfaces/share-file.interface.ts
@@ -1,18 +1,12 @@
import type { FileSpace } from '../../files/interfaces/file-space.interface.js'
import type { Share } from '../schemas/share.interface.js'
-export class ShareFile implements Pick<Share, 'id' | 'name' | 'description' | 'alias' | 'createdAt' | 'modifiedAt'> {
- id: number
- name: string
- alias: string
+export interface ShareFile extends Pick<Share, 'id' | 'name' | 'description' | 'alias' | 'createdAt' | 'modifiedAt'> {
externalPath: boolean
- description: string
- enabled: boolean
- createdAt: Date
- modifiedAt: Date
+ enabled: Share['enabled']
parent: Pick<Share, 'id' | 'alias' | 'name'>
file: FileSpace
hasComments: boolean
counts: { users: number; groups: number; links: number; shares: number }
- syncs: { clientId: string; clientName: string; id: number }[] = []
+ syncs: { clientId: string; clientName: string; id: number }[]
}
diff --git a/backend/src/applications/shares/interfaces/share-identity.interface.ts b/backend/src/applications/shares/interfaces/share-identity.interface.ts
new file mode 100644
index 00000000..94537a98
--- /dev/null
+++ b/backend/src/applications/shares/interfaces/share-identity.interface.ts
@@ -0,0 +1,6 @@
+import type { Share } from '../schemas/share.interface.js'
+
+export type ShareIdentity = Pick<Share, 'id' | 'alias' | 'name'> & Partial<Omit<Share, 'id' | 'alias' | 'name'>>
+export type ShareDescriptor = Pick<Share, 'alias' | 'name'>
+export type ShareOwnerIdentity = Pick<Share, 'id' | 'ownerId'>
+export type ShareSelection = Pick<Share, 'id' | 'ownerId' | 'alias' | 'name'>
diff --git a/backend/src/applications/shares/interfaces/share-props.interface.ts b/backend/src/applications/shares/interfaces/share-props.interface.ts
index f1f167ca..62587f3f 100644
--- a/backend/src/applications/shares/interfaces/share-props.interface.ts
+++ b/backend/src/applications/shares/interfaces/share-props.interface.ts
@@ -2,7 +2,7 @@ import type { FileSpace } from '../../files/interfaces/file-space.interface.js'
import type { Member } from '../../users/interfaces/member.interface.js'
import type { Share } from '../schemas/share.interface.js'
-export class ShareProps implements Pick<
+export interface ShareProps extends Pick<
Share,
| 'id'
| 'ownerId'
@@ -18,22 +18,9 @@ export class ShareProps implements Pick<
| 'storageQuota'
| 'storageIndexing'
> {
- id: number
- ownerId: number
- alias: string
- name: string
- description: string
- enabled: boolean
- externalPath: string
- storageUsage: number
- storageQuota: number
- storageIndexing: boolean
- createdAt: Date
- modifiedAt: Date
- disabledAt: Date
parent: Pick<Share, 'id' | 'ownerId' | 'alias' | 'name'>
file: FileSpace
// Extra properties
- members: Member[] = []
+ members: Member[]
}
diff --git a/backend/src/applications/shares/models/share-child.model.ts b/backend/src/applications/shares/models/share-child.model.ts
index 9ebe4d91..eb0e38a2 100644
--- a/backend/src/applications/shares/models/share-child.model.ts
+++ b/backend/src/applications/shares/models/share-child.model.ts
@@ -4,13 +4,13 @@ import type { ShareChildQuery } from '../interfaces/share-child.interface.js'
import type { Share } from '../schemas/share.interface.js'
export class ShareChild implements Pick<Share, 'id' | 'parentId' | 'type' | 'name' | 'alias'> {
- id: number
- parentId: number
- type: number
- name: string
- alias: string
- owner: Owner
- file: { mime: string }
+ id!: number
+ parentId!: number
+ type!: number
+ name!: string
+ alias!: string
+ owner: Owner | null
+ file: { mime: string } | null
constructor(props: ShareChildQuery) {
this.owner = props.ownerLogin
diff --git a/backend/src/applications/shares/schemas/share-members.interface.ts b/backend/src/applications/shares/schemas/share-members.interface.ts
index a6b9f199..2fd0c897 100644
--- a/backend/src/applications/shares/schemas/share-members.interface.ts
+++ b/backend/src/applications/shares/schemas/share-members.interface.ts
@@ -1,14 +1,3 @@
import type { sharesMembers } from './shares-members.schema.js'
-type ShareMembersSchema = typeof sharesMembers.$inferSelect
-
-export class ShareMembers implements ShareMembersSchema {
- id: number
- shareId: number
- userId: number
- groupId: number
- linkId: number
- permissions: string
- createdAt: Date
- modifiedAt: Date
-}
+export type ShareMembers = typeof sharesMembers.$inferSelect
diff --git a/backend/src/applications/shares/schemas/share.interface.ts b/backend/src/applications/shares/schemas/share.interface.ts
index 1e9056e0..0fe041e3 100644
--- a/backend/src/applications/shares/schemas/share.interface.ts
+++ b/backend/src/applications/shares/schemas/share.interface.ts
@@ -1,24 +1,3 @@
import type { shares } from './shares.schema.js'
-type ShareSchema = typeof shares.$inferSelect
-
-export class Share implements ShareSchema {
- id: number
- ownerId: number
- parentId: number
- spaceId: number
- spaceRootId: number
- fileId: number
- externalPath: string
- type: number
- alias: string
- name: string
- enabled: boolean
- description: string
- storageUsage: number
- storageQuota: number
- storageIndexing: boolean
- createdAt: Date
- modifiedAt: Date
- disabledAt: Date
-}
+export type Share = typeof shares.$inferSelect
diff --git a/backend/src/applications/shares/services/shares-manager.service.spec.ts b/backend/src/applications/shares/services/shares-manager.service.spec.ts
index b8586d84..bf8e7108 100644
--- a/backend/src/applications/shares/services/shares-manager.service.spec.ts
+++ b/backend/src/applications/shares/services/shares-manager.service.spec.ts
@@ -587,7 +587,7 @@ describe(SharesManager.name, () => {
})
it('updates modified links and returns them along with unmodified ones', async () => {
- const updateLinkSpy = vi.spyOn(service, 'updateLinkFromSpaceOrShare').mockResolvedValue(void 0)
+ const updateLinkSpy = vi.spyOn(service, 'updateLinkFromSpaceOrShare').mockResolvedValue(void 0 as never)
const members = await service.createOrUpdateLinksAsMembers(user, { id: 1, name: 'S' } as any, LINK_TYPE.SHARE, [
{ id: 2, linkId: 2, permissions: 'p', linkSettings: { name: 'new' } },
diff --git a/backend/src/applications/shares/services/shares-manager.service.ts b/backend/src/applications/shares/services/shares-manager.service.ts
index 0928488c..9e80dc7e 100644
--- a/backend/src/applications/shares/services/shares-manager.service.ts
+++ b/backend/src/applications/shares/services/shares-manager.service.ts
@@ -1,6 +1,7 @@
import { HttpException, HttpStatus, Injectable, Logger } from '@nestjs/common'
import path from 'node:path'
import { ACTION } from '../../../common/constants.js'
+import { toErrorMessage } from '../../../common/errors.js'
import {
anonymizePassword,
convertDiffUpdate,
@@ -31,16 +32,17 @@ import { SpacesQueries } from '../../spaces/services/spaces-queries.service.js'
import { havePermission, haveSpacePermission, removePermissions } from '../../spaces/utils/permissions.js'
import { MEMBER_TYPE } from '../../users/constants/member.js'
import { GUEST_PERMISSION, USER_NOTIFICATION, USER_ROLE } from '../../users/constants/user.js'
-import { CreateUserDto } from '../../users/dto/create-or-update-user.dto.js'
+import type { CreateUserDto } from '../../users/dto/create-or-update-user.dto.js'
import { UserModel } from '../../users/models/user.model.js'
import type { User } from '../../users/schemas/user.interface.js'
import { UsersQueries } from '../../users/services/users-queries.service.js'
import { SHARE_ALL_OPERATIONS, SHARE_TYPE } from '../constants/shares.js'
-import type { CreateOrUpdateShareDto, ShareMemberDto } from '../dto/create-or-update-share.dto.js'
+import { type ShareMemberDto, shareMemberSchema, type ValidatedCreateOrUpdateShareDto } from '../dto/create-or-update-share.dto.js'
import type { ShareChildMember } from '../interfaces/share-child.interface.js'
import type { ShareEnv } from '../interfaces/share-env.interface.js'
import type { ShareFile } from '../interfaces/share-file.interface.js'
import type { ShareLink } from '../interfaces/share-link.interface.js'
+import type { ShareDescriptor, ShareIdentity } from '../interfaces/share-identity.interface.js'
import type { ShareProps } from '../interfaces/share-props.interface.js'
import type { ShareChild } from '../models/share-child.model.js'
import type { ShareMembers } from '../schemas/share-members.interface.js'
@@ -88,7 +90,7 @@ export class SharesManager {
share.file.ownerId = null
// retrieve space permissions (cached query)
const userId = asAdmin ? share.ownerId : user.id
- const spacePermissions: Partial<SpaceEnv> = await this.spacesQueries.permissions(userId, share.file.space.alias, share.file.space.root?.alias)
+ const spacePermissions = await this.spacesQueries.permissions(userId!, share.file.space.alias, share.file.space.root?.alias)
if (!spacePermissions) {
this.logger.warn({ tag: this.setAllowedPermissions.name, msg: `missing space permissions : ${JSON.stringify(share)}` })
throw new HttpException('Space not found', HttpStatus.NOT_FOUND)
@@ -101,7 +103,7 @@ export class SharesManager {
// retrieve parent share permissions (cached query)
// use current the user permissions on the share or the share owner permissions if we request the share as admin
const userId = asAdmin ? share.ownerId : user.id
- const sharePermissions: Partial<SpaceEnv> = await this.sharesQueries.permissions(userId, share.parent.alias, +user.isAdmin)
+ const sharePermissions = await this.sharesQueries.permissions(userId!, share.parent.alias, +user.isAdmin)
if (!sharePermissions) {
this.logger.warn({ tag: this.setAllowedPermissions.name, msg: `missing share permissions : ${JSON.stringify(share)}` })
throw new HttpException('Share not found', HttpStatus.NOT_FOUND)
@@ -115,7 +117,7 @@ export class SharesManager {
async getShareWithMembers(user: UserModel, shareId: number, asAdmin = false): Promise<ShareProps> {
// asAdmin: true if the user is the owner of the parent share or if the share is requested from the administration
- const share: ShareProps = await this.sharesQueries.getShareWithMembers(user, shareId, asAdmin)
+ const share = await this.sharesQueries.getShareWithMembers(user, shareId, asAdmin)
if (!share) {
throw new HttpException('Unauthorized', HttpStatus.FORBIDDEN)
}
@@ -123,15 +125,15 @@ export class SharesManager {
return share
}
- async createShare(user: UserModel, createOrUpdateShareDto: CreateOrUpdateShareDto): Promise<ShareProps> {
+ async createShare(user: UserModel, createOrUpdateShareDto: ValidatedCreateOrUpdateShareDto): Promise<ShareProps> {
const share: Partial<Share> = {
name: createOrUpdateShareDto.name,
alias: await this.uniqueShareAlias(createOrUpdateShareDto.name),
description: createOrUpdateShareDto.description,
externalPath: createOrUpdateShareDto.externalPath,
- enabled: createOrUpdateShareDto.enabled,
+ enabled: createOrUpdateShareDto.enabled ?? undefined,
storageQuota: createOrUpdateShareDto.storageQuota,
- storageIndexing: createOrUpdateShareDto.storageIndexing,
+ storageIndexing: createOrUpdateShareDto.storageIndexing ?? undefined,
disabledAt: createOrUpdateShareDto.enabled ? null : new Date(),
type: createOrUpdateShareDto.type || SHARE_TYPE.COMMON
}
@@ -142,36 +144,36 @@ export class SharesManager {
}
try {
await checkExternalPath(share.externalPath)
- } catch (e: any) {
- throw new HttpException(e.message, e instanceof FileError ? e.httpCode : HttpStatus.INTERNAL_SERVER_ERROR)
+ } catch (e) {
+ throw new HttpException(toErrorMessage(e), e instanceof FileError ? e.httpCode : HttpStatus.INTERNAL_SERVER_ERROR)
}
share.ownerId = null
} else {
/* SPACES CASE */
share.externalPath = null
share.ownerId = user.id
- if (createOrUpdateShareDto.file.ownerId) {
+ if (createOrUpdateShareDto.file!.ownerId) {
/* PERSONAL SPACE CASE */
// check file
- if (createOrUpdateShareDto.file.ownerId === user.id && createOrUpdateShareDto.file.id > 0) {
+ if (createOrUpdateShareDto.file!.ownerId === user.id && createOrUpdateShareDto.file!.id > 0) {
// When a user shares a root space they own, it is recommended to create the share from their personal space.
// `file.path` come from a root space with a custom name (invalid in the personal space context); if so, retrieve the original path.
- const f = await this.spacesQueries.getUserFile(user.id, createOrUpdateShareDto.file.id)
- if (f) createOrUpdateShareDto.file.path = f.path
+ const f = await this.spacesQueries.getUserFile(user.id, createOrUpdateShareDto.file!.id)
+ if (f) createOrUpdateShareDto.file!.path = f.path
}
- const realPath = path.join(user.filesPath, createOrUpdateShareDto.file.path)
+ const realPath = path.join(user.filesPath, createOrUpdateShareDto.file!.path)
if (!(await isPathExists(realPath))) {
this.logger.warn({ tag: this.createShare.name, msg: `location does not exist : ${realPath}` })
throw new HttpException('The location does not exist', HttpStatus.NOT_FOUND)
}
- const fileProps: FileProps = { ...(await getProps(realPath, createOrUpdateShareDto.file.path)), id: createOrUpdateShareDto.file.id }
+ const fileProps: FileProps = { ...(await getProps(realPath, createOrUpdateShareDto.file!.path)), id: createOrUpdateShareDto.file!.id }
share.fileId = await this.spacesQueries.getOrCreateUserFile(user.id, fileProps)
- } else if (createOrUpdateShareDto.file.space?.alias) {
+ } else if (createOrUpdateShareDto.file!.space?.alias) {
/* SPACE CASE */
- const spacePermissions: Partial<SpaceEnv> = await this.spacesQueries.permissions(
+ const spacePermissions = await this.spacesQueries.permissions(
user.id,
- createOrUpdateShareDto.file.space.alias,
- createOrUpdateShareDto.file.space.root.alias
+ createOrUpdateShareDto.file!.space.alias,
+ createOrUpdateShareDto.file!.space.root!.alias!
)
if (!spacePermissions) {
throw new HttpException('Space not found', HttpStatus.NOT_FOUND)
@@ -188,20 +190,24 @@ export class SharesManager {
}
// intersect space permissions for members
for (const m of createOrUpdateShareDto.members) {
- m.permissions = intersectPermissions(space.envPermissions, m.permissions)
+ m.permissions = intersectPermissions(space.envPermissions, m.permissions ?? '')
}
// intersect space permissions for links
for (const l of createOrUpdateShareDto.links) {
- l.permissions = intersectPermissions(space.envPermissions, l.permissions)
+ l.permissions = intersectPermissions(space.envPermissions, l.permissions ?? '')
}
// check file
try {
- space.setPaths(user, createOrUpdateShareDto.file.space.root.alias, createOrUpdateShareDto.file.path.split('/').slice(space.root.id ? 1 : 0))
+ space.setPaths(
+ user,
+ createOrUpdateShareDto.file!.space.root!.alias!,
+ createOrUpdateShareDto.file!.path.split('/').slice(space.root!.id ? 1 : 0)
+ )
} catch (e) {
if (e instanceof FileError) {
throw new HttpException(e.message, e.httpCode)
}
- throw new HttpException(e.message, HttpStatus.BAD_REQUEST)
+ throw new HttpException(toErrorMessage(e), HttpStatus.BAD_REQUEST)
}
if (!(await isPathExists(space.realPath))) {
this.logger.warn({ tag: this.createShare.name, msg: `space location does not exist : *${space.alias}* (${space.id}) : ${space.realPath}` })
@@ -212,15 +218,15 @@ export class SharesManager {
// define share.fileId
// if the file is the same as the space root, ignores share.fileId and only uses spaceId and spaceRootId
const isExternalSpaceRoot =
- createOrUpdateShareDto.file?.id < 0 &&
+ (createOrUpdateShareDto.file?.id as number) < 0 &&
createOrUpdateShareDto.file?.path === createOrUpdateShareDto.file?.space?.root?.alias &&
createOrUpdateShareDto.file?.space?.root?.alias === spacePermissions.root?.alias &&
createOrUpdateShareDto.file?.space?.root?.name === spacePermissions.root?.name
- const isSpaceRoot = Number(createOrUpdateShareDto.file.id) === Number(spacePermissions.root?.file?.id)
+ const isSpaceRoot = Number(createOrUpdateShareDto.file!.id) === Number(spacePermissions.root?.file?.id)
if (!isSpaceRoot && !isExternalSpaceRoot) {
const fileProps: FileProps = { ...(await getProps(space.realPath, space.dbFile.path)), id: undefined }
// get or create file id
- share.fileId = await this.spacesQueries.getOrCreateSpaceFile(createOrUpdateShareDto.file.id, fileProps, space.dbFile, {
+ share.fileId = await this.spacesQueries.getOrCreateSpaceFile(createOrUpdateShareDto.file!.id, fileProps, space.dbFile, {
rejectIdMismatch: true
})
}
@@ -232,24 +238,24 @@ export class SharesManager {
// create share
share.id = await this.sharesQueries.createShare(share)
// check and update members
- await this.createOrUpdateLinksAsMembers(user, share, LINK_TYPE.SHARE, createOrUpdateShareDto.links)
- await this.updateMembers(user, share, [], createOrUpdateShareDto.members)
+ await this.createOrUpdateLinksAsMembers(user, share as ShareIdentity, LINK_TYPE.SHARE, createOrUpdateShareDto.links)
+ await this.updateMembers(user, share as ShareIdentity, [], createOrUpdateShareDto.members)
return this.getShareWithMembers(user, share.id)
}
- async updateShare(user: UserModel, shareId: number, createOrUpdateShareDto: CreateOrUpdateShareDto, asAdmin = false): Promise<ShareProps> {
+ async updateShare(user: UserModel, shareId: number, createOrUpdateShareDto: ValidatedCreateOrUpdateShareDto, asAdmin = false): Promise<ShareProps> {
// asAdmin: true if the user is the owner of the parent share or if the share is requested from the administration
const share: ShareProps = await this.getShareWithMembers(user, shareId, asAdmin)
// check and update share info
- let renamedShareAlias: string
+ let renamedShareAlias: string | undefined
const shareDiffProps: Partial<ShareProps> = { modifiedAt: new Date() }
- const props: (keyof CreateOrUpdateShareDto)[] = ['name', 'description', 'enabled', 'storageQuota', 'storageIndexing']
+ const props = ['name', 'description', 'enabled', 'storageQuota', 'storageIndexing'] as const
for (const prop of props) {
if (createOrUpdateShareDto[prop] !== share[prop]) {
- shareDiffProps[prop] = createOrUpdateShareDto[prop]
+ ;(shareDiffProps as Record<string, unknown>)[prop] = createOrUpdateShareDto[prop]
if (prop === 'name') {
renamedShareAlias = share.alias
- shareDiffProps.alias = await this.uniqueShareAlias(shareDiffProps.name, shareId)
+ shareDiffProps.alias = await this.uniqueShareAlias(shareDiffProps.name!, shareId)
} else if (prop === 'enabled') {
shareDiffProps.disabledAt = shareDiffProps[prop] ? null : new Date()
}
@@ -264,17 +270,17 @@ export class SharesManager {
}
// update quota in cache
if ('storageQuota' in shareDiffProps) {
- void this.filesQuotaManager.updateStorageQuota(shareId, FILE_REPOSITORY.SHARE, shareDiffProps.storageQuota)
+ void this.filesQuotaManager.updateStorageQuota(shareId, FILE_REPOSITORY.SHARE, shareDiffProps.storageQuota as number | null)
}
// check & update members
const linkMembers: ShareMemberDto[] = await this.createOrUpdateLinksAsMembers(user, share, LINK_TYPE.SHARE, createOrUpdateShareDto.links)
// intersect share permissions for members
for (const m of createOrUpdateShareDto.members) {
- m.permissions = intersectPermissions(share.file.permissions, m.permissions)
+ m.permissions = intersectPermissions(share.file.permissions!, m.permissions ?? '')
}
// intersect share permissions for links
for (const l of linkMembers) {
- l.permissions = intersectPermissions(share.file.permissions, l.permissions)
+ l.permissions = intersectPermissions(share.file.permissions!, l.permissions ?? '')
}
await this.updateMembers(user, share, share.members, [...createOrUpdateShareDto.members, ...linkMembers])
return this.getShareWithMembers(user, share.id, asAdmin)
@@ -289,7 +295,7 @@ export class SharesManager {
await this.deleteAllLinkMembers(shareId, LINK_TYPE.SHARE)
await this.removeShareFromOwners(shareId, 'all', false, user.id)
} catch (e) {
- this.logger.error({ tag: this.deleteShare.name, msg: `unable to delete share (${shareId}) (asAdmin = ${asAdmin}) : ${e}` })
+ this.logger.error({ tag: this.deleteShare.name, msg: `unable to delete share (${shareId}) (asAdmin = ${asAdmin}) : ${toErrorMessage(e)}` })
throw new HttpException('Unable to delete share', HttpStatus.INTERNAL_SERVER_ERROR)
}
}
@@ -297,33 +303,35 @@ export class SharesManager {
async getChildShare(user: UserModel, shareId: number, childId: number, isLink?: false): Promise<ShareProps>
async getChildShare(user: UserModel, shareId: number, childId: number, isLink?: true): Promise<ShareLink>
async getChildShare(user: UserModel, shareId: number, childId: number, isLink?: boolean): Promise<ShareProps | ShareLink> {
- if (await this.checkChildSharePermissions(user, shareId, childId)) {
- if (isLink) {
- return this.getShareLink(user, childId, true)
- }
- return this.getShareWithMembers(user, childId, true)
+ await this.checkChildSharePermissions(user, shareId, childId)
+ if (isLink) {
+ return this.getShareLink(user, childId, true)
}
+ return this.getShareWithMembers(user, childId, true)
}
- async updateChildShare(user: UserModel, shareId: number, childId: number, createOrUpdateShareDto: CreateOrUpdateShareDto): Promise<ShareProps> {
- if (await this.checkChildSharePermissions(user, shareId, childId)) {
- return this.updateShare(user, childId, createOrUpdateShareDto, true)
- }
+ async updateChildShare(
+ user: UserModel,
+ shareId: number,
+ childId: number,
+ createOrUpdateShareDto: ValidatedCreateOrUpdateShareDto
+ ): Promise<ShareProps> {
+ await this.checkChildSharePermissions(user, shareId, childId)
+ return this.updateShare(user, childId, createOrUpdateShareDto, true)
}
async deleteChildShare(user: UserModel, shareId: number, childId: number): Promise<void> {
- if (await this.checkChildSharePermissions(user, shareId, childId)) {
- return this.deleteShare(user, childId, true)
- }
+ await this.checkChildSharePermissions(user, shareId, childId)
+ return this.deleteShare(user, childId, true)
}
- async createChildShare(user: UserModel, createOrUpdateShareDto: CreateOrUpdateShareDto): Promise<ShareProps> {
+ async createChildShare(user: UserModel, createOrUpdateShareDto: ValidatedCreateOrUpdateShareDto): Promise<ShareProps> {
// check parent share
- const pSharePermissions = await this.sharesQueries.permissions(user.id, createOrUpdateShareDto.parent.alias, +user.isAdmin)
+ const pSharePermissions = await this.sharesQueries.permissions(user.id, createOrUpdateShareDto.parent!.alias, +user.isAdmin)
if (!pSharePermissions) {
this.logger.warn({
tag: this.createChildShare.name,
- msg: `parent share does not exist or not authorized : ${createOrUpdateShareDto.parent.alias}`
+ msg: `parent share does not exist or not authorized : ${createOrUpdateShareDto.parent!.alias}`
})
throw new HttpException('Parent share not found', HttpStatus.NOT_FOUND)
}
@@ -335,14 +343,14 @@ export class SharesManager {
throw new HttpException('You are not allowed to do this action', HttpStatus.FORBIDDEN)
}
if (!pSharePermissions.enabled) {
- this.logger.warn({ tag: this.createChildShare.name, msg: `parent share is disabled : ${createOrUpdateShareDto.parent.alias}` })
+ this.logger.warn({ tag: this.createChildShare.name, msg: `parent share is disabled : ${createOrUpdateShareDto.parent!.alias}` })
throw new HttpException('Parent share is disabled', HttpStatus.FORBIDDEN)
}
let pShare: Partial<SpaceEnv>
let filePath: string
- if (pSharePermissions.root.externalPath) {
- const highestParentId = await this.sharesQueries.findHighestParentShare(pSharePermissions.id)
+ if (pSharePermissions.root!.externalPath) {
+ const highestParentId = await this.sharesQueries.findHighestParentShare(pSharePermissions.id!)
if (!highestParentId) {
this.logger.warn({
tag: this.createChildShare.name,
@@ -351,21 +359,21 @@ export class SharesManager {
throw new HttpException('Parent share not found', HttpStatus.NOT_FOUND)
}
pShare = await this.sharesQueries.shareEnv(highestParentId)
- filePath = path.join(pSharePermissions.root?.file?.path || '', createOrUpdateShareDto.file.path)
+ filePath = path.join(pSharePermissions.root?.file?.path || '', createOrUpdateShareDto.file!.path)
} else {
- pShare = await this.sharesQueries.shareEnv(pSharePermissions.id)
- filePath = createOrUpdateShareDto.file.path
+ pShare = await this.sharesQueries.shareEnv(pSharePermissions.id!)
+ filePath = createOrUpdateShareDto.file!.path
}
// create a fake space env -> share env
- const pShareEnv: Partial<ShareEnv> = new SpaceEnv(pShare, null, false)
+ const pShareEnv = new SpaceEnv(pShare, null, false) as SpaceEnv & ShareEnv
try {
pShareEnv.setPaths(user, null, filePath.split('/'))
} catch (e) {
if (e instanceof FileError) {
throw new HttpException(e.message, e.httpCode)
}
- throw new HttpException(e.message, HttpStatus.BAD_REQUEST)
+ throw new HttpException(toErrorMessage(e), HttpStatus.BAD_REQUEST)
}
// check file
if (!(await isPathExists(pShareEnv.realPath))) {
@@ -380,16 +388,16 @@ export class SharesManager {
// special case, the parent share is directly linked to the space root file
const isLinkedToShareSpaceRoot =
pShareEnv.fileId === null &&
- Number(createOrUpdateShareDto.file.id) === Number(pSharePermissions.root?.id) &&
- createOrUpdateShareDto.file.path === '.'
+ Number(createOrUpdateShareDto.file!.id) === Number(pSharePermissions.root?.id) &&
+ createOrUpdateShareDto.file!.path === '.'
// special case, the parent share is directly linked to the share with an external path
const isLinkedToShareExternalPath =
- createOrUpdateShareDto.file.id < 0 && !!pShareEnv.root.externalPath && createOrUpdateShareDto.file.path === '.'
- let fileId: number = null
+ createOrUpdateShareDto.file!.id < 0 && !!pShareEnv.root!.externalPath && createOrUpdateShareDto.file!.path === '.'
+ let fileId: number | null = null
if (!isLinkedToShareSpaceRoot && !isLinkedToShareExternalPath) {
// fileId is mandatory for a file in a child share
const fileProps: FileProps = { ...(await getProps(pShareEnv.realPath, pShareEnv.dbFile.path)), id: undefined }
- fileId = await this.spacesQueries.getOrCreateSpaceFile(createOrUpdateShareDto.file.id, fileProps, pShareEnv.dbFile, {
+ fileId = await this.spacesQueries.getOrCreateSpaceFile(createOrUpdateShareDto.file!.id, fileProps, pShareEnv.dbFile, {
rejectIdMismatch: true
})
}
@@ -403,8 +411,8 @@ export class SharesManager {
parentId: pSharePermissions.id,
fileId: fileId,
description: createOrUpdateShareDto.description,
- externalPath: pShareEnv.root.externalPath,
- enabled: createOrUpdateShareDto.enabled,
+ externalPath: pShareEnv.root!.externalPath,
+ enabled: createOrUpdateShareDto.enabled ?? undefined,
disabledAt: createOrUpdateShareDto.enabled ? null : new Date(),
type: createOrUpdateShareDto.type || SHARE_TYPE.COMMON
}
@@ -412,15 +420,15 @@ export class SharesManager {
share.id = await this.sharesQueries.createShare(share)
// intersect parent share permissions for members
for (const m of createOrUpdateShareDto.members) {
- m.permissions = intersectPermissions(pSharePermissions.permissions, m.permissions)
+ m.permissions = intersectPermissions(pSharePermissions.permissions!, m.permissions ?? '')
}
// intersect parent share permissions for links
for (const l of createOrUpdateShareDto.links) {
- l.permissions = intersectPermissions(pSharePermissions.permissions, l.permissions)
+ l.permissions = intersectPermissions(pSharePermissions.permissions!, l.permissions ?? '')
}
// check & update members
- await this.createOrUpdateLinksAsMembers(user, share, LINK_TYPE.SHARE, createOrUpdateShareDto.links)
- await this.updateMembers(user, share, [], createOrUpdateShareDto.members)
+ await this.createOrUpdateLinksAsMembers(user, share as ShareIdentity, LINK_TYPE.SHARE, createOrUpdateShareDto.links)
+ await this.updateMembers(user, share as ShareIdentity, [], createOrUpdateShareDto.members)
return this.getShareWithMembers(user, share.id)
}
@@ -442,13 +450,7 @@ export class SharesManager {
const [rmOwners, upOwners] = await this.diffSharesPermissions(currentMembers, toRemove, toUpdate, spaceManagerIds)
if (!rmOwners.length && !upOwners.length) return
- const owners: Record<
- number,
- {
- type: ACTION.UPDATE | ACTION.DELETE
- rmPermissions?: SPACE_OPERATION[]
- }
- > = {
+ const owners: Record<number, { type: ACTION.UPDATE; rmPermissions: SPACE_OPERATION[] } | { type: ACTION.DELETE }> = {
...Object.fromEntries(rmOwners.map((uId: number) => [uId, { type: ACTION.DELETE }])),
...Object.fromEntries(
upOwners.reduce(
@@ -476,22 +478,22 @@ export class SharesManager {
spaceId,
Object.keys(owners).map((id: string) => parseInt(id))
)) {
- if (share.ownerId in owners) {
- const action = owners[share.ownerId]
+ if ((share.ownerId as number) in owners) {
+ const action = owners[share.ownerId as number]
if (action.type === ACTION.UPDATE) {
this.removeChildSharesPermissions(
share.id,
[
{
- ids: [share.ownerId],
+ ids: [share.ownerId as number],
rmPermissions: action.rmPermissions
}
],
false
- ).catch((e: Error) => this.logger.error({ tag: this.updateSharesFromSpace.name, msg: `${e}` }))
+ ).catch((e: Error) => this.logger.error({ tag: this.updateSharesFromSpace.name, msg: toErrorMessage(e) }))
} else {
- this.removeShareFromOwners(share.id, [share.ownerId], false).catch((e: Error) =>
- this.logger.error({ tag: this.updateSharesFromSpace.name, msg: `${e}` })
+ this.removeShareFromOwners(share.id, [share.ownerId as number], false).catch((e: Error) =>
+ this.logger.error({ tag: this.updateSharesFromSpace.name, msg: toErrorMessage(e) })
)
}
this.logger.log({
@@ -525,14 +527,14 @@ export class SharesManager {
}
],
false
- ).catch((e: Error) => this.logger.error({ tag: this.updateSharesFromSpaceRoots.name, msg: `${e}` }))
+ ).catch((e: Error) => this.logger.error({ tag: this.updateSharesFromSpaceRoots.name, msg: toErrorMessage(e) }))
}
}
for (const rootId of toRemove) {
for (const share of await this.sharesQueries.selectShares({ spaceId: spaceId, spaceRootId: rootId, parentId: null })) {
// use await ! avoid database lock ! next action is to delete the root space which is cascaded with share.spaceRootId
- await this.removeShareFromOwners(share.id, [share.ownerId], false)
+ await this.removeShareFromOwners(share.id, [share.ownerId as number], false)
}
}
}
@@ -540,7 +542,7 @@ export class SharesManager {
async removeSharesFromSpace(spaceId: number): Promise<void> {
for (const share of await this.sharesQueries.selectShares({ spaceId: spaceId, parentId: null })) {
// use await ! avoid database lock ! next action is to delete the space which is cascaded with share.spaceId
- await this.removeShareFromOwners(share.id, [share.ownerId], false)
+ await this.removeShareFromOwners(share.id, [share.ownerId as number], false)
}
}
@@ -557,7 +559,7 @@ export class SharesManager {
}
async getShareLink(user: UserModel, shareId: number, asAdmin: boolean = false): Promise<ShareLink> {
- const shareLink: ShareLink = await this.sharesQueries.listShareLinks(user, shareId, asAdmin)
+ const shareLink = await this.sharesQueries.listShareLinks(user, shareId, asAdmin)
if (!shareLink) {
throw new HttpException('Unauthorized', HttpStatus.FORBIDDEN)
}
@@ -583,29 +585,29 @@ export class SharesManager {
return linkGuest
}
- async createOrUpdateLinksAsMembers(
+ async createOrUpdateLinksAsMembers<T extends SpaceMemberDto | ShareMemberDto>(
user: UserModel,
- spaceOrShare: Partial<SpaceProps> | Partial<ShareProps>,
+ spaceOrShare: Pick<SpaceProps | ShareProps, 'id' | 'name'>,
type: LINK_TYPE,
- links: SpaceMemberDto[] | ShareMemberDto[]
- ): Promise<SpaceMemberDto[] | ShareMemberDto[]> {
+ links: T[]
+ ): Promise<T[]> {
/* only used during the share creation from the share manager */
- const linkMembers: SpaceMemberDto[] | ShareMemberDto[] = []
+ const linkMembers: T[] = []
for (const link of links) {
if (link.id < 0) {
// new link (permissions are needed to create guest link)
- await this.createLinkFromSpaceOrShare(user, link.linkSettings.uuid, spaceOrShare.id, type, {
- ...link.linkSettings,
+ await this.createLinkFromSpaceOrShare(user, link.linkSettings!.uuid!, spaceOrShare.id, type, {
+ ...link.linkSettings!,
permissions: link.permissions
})
// notify the guest link (if email is specified)
this.notifyGuestLink(user, link, spaceOrShare.name, type === LINK_TYPE.SHARE ? ACTION.ADD : ACTION.UPDATE).catch((e: Error) =>
- this.logger.error({ tag: this.createOrUpdateLinksAsMembers.name, msg: `${e}` })
+ this.logger.error({ tag: this.createOrUpdateLinksAsMembers.name, msg: toErrorMessage(e) })
)
} else {
if (link.linkSettings) {
// modified link
- await this.updateLinkFromSpaceOrShare(user, link.linkId, spaceOrShare.id, type, link.linkSettings)
+ await this.updateLinkFromSpaceOrShare(user, link.linkId!, spaceOrShare.id, type, link.linkSettings)
}
// unmodified link
linkMembers.push(link)
@@ -614,6 +616,22 @@ export class SharesManager {
return linkMembers
}
+ async updateLinkFromSpaceOrShare(
+ user: UserModel,
+ linkId: number,
+ spaceOrShareId: number,
+ type: LINK_TYPE,
+ createOrUpdateLinkDto: CreateOrUpdateLinkDto,
+ fromAPI: true
+ ): Promise<LinkGuest>
+ async updateLinkFromSpaceOrShare(
+ user: UserModel,
+ linkId: number,
+ spaceOrShareId: number,
+ type: LINK_TYPE,
+ createOrUpdateLinkDto: CreateOrUpdateLinkDto,
+ fromAPI?: false
+ ): Promise<null | undefined>
async updateLinkFromSpaceOrShare(
user: UserModel,
linkId: number,
@@ -621,7 +639,7 @@ export class SharesManager {
type: LINK_TYPE,
createOrUpdateLinkDto: CreateOrUpdateLinkDto,
fromAPI: boolean = false
- ): Promise<LinkGuest> {
+ ): Promise<LinkGuest | null | undefined> {
const link: LinkGuest = await this.getLinkFromSpaceOrShare(user, linkId, spaceOrShareId, type)
if (!link) {
this.logger.error({
@@ -649,12 +667,13 @@ export class SharesManager {
Partial<Pick<Share, 'alias' | 'name' | 'description'>>,
Partial<Pick<ShareMembers, 'permissions'>>
] = [{}, {}, {}, {}]
+ const currentLink: Partial<CreateOrUpdateLinkDto> = link
for (const [k, v] of Object.entries(createOrUpdateLinkDto) as Entries<CreateOrUpdateLinkDto>) {
- if (fieldsWhiteList.indexOf(k) > -1 && link[k] !== v) {
+ if (fieldsWhiteList.indexOf(k) > -1 && currentLink[k] !== v) {
switch (k) {
case 'password':
if (v) {
- updateUser.password = await hashPassword(v)
+ updateUser.password = await hashPassword(v as string)
}
break
case 'permissions':
@@ -662,35 +681,35 @@ export class SharesManager {
// permissions are only present if the share type is link
// intersect permissions to ensure that the user does not attempt to exceed his rights
const shareLink: ShareLink = await this.getShareLink(user, spaceOrShareId)
- updateMember.permissions = intersectPermissions(shareLink.file.permissions, v)
+ updateMember.permissions = intersectPermissions(shareLink.file.permissions!, v as string)
this.sharesQueries
.clearCachePermissions(shareLink.alias, [link.userId])
- .catch((e: Error) => this.logger.error({ tag: this.updateLinkFromSpaceOrShare.name, msg: `${e}` }))
+ .catch((e: Error) => this.logger.error({ tag: this.updateLinkFromSpaceOrShare.name, msg: toErrorMessage(e) }))
}
break
case 'language':
- updateUser.language = v
+ updateUser.language = v as User['language']
break
case 'isActive':
- updateUser.isActive = v
+ updateUser.isActive = v as boolean
if (v) {
updateUser.passwordAttempts = 0
}
break
case 'shareName':
- updateShare.name = v
- updateShare.alias = await this.uniqueShareAlias(v, spaceOrShareId)
+ updateShare.name = v as string
+ updateShare.alias = await this.uniqueShareAlias(v as string, spaceOrShareId)
break
case 'shareDescription':
- updateShare.description = v
+ updateShare.description = v as string | null
break
case 'expiresAt':
- if (JSON.stringify(link[k]) !== JSON.stringify(v)) {
- updateLink[k] = v
+ if (JSON.stringify(currentLink[k]) !== JSON.stringify(v)) {
+ Reflect.set(updateLink, k, v)
}
break
default:
- updateLink[k] = v
+ Reflect.set(updateLink, k, v)
}
}
}
@@ -713,7 +732,7 @@ export class SharesManager {
})}`
})
} catch (e) {
- this.logger.error({ tag: this.updateLinkFromSpaceOrShare.name, msg: `${e}` })
+ this.logger.error({ tag: this.updateLinkFromSpaceOrShare.name, msg: toErrorMessage(e) })
throw new HttpException('Unable to update link', HttpStatus.INTERNAL_SERVER_ERROR)
}
if (fromAPI) {
@@ -727,8 +746,8 @@ export class SharesManager {
async createGuestLink(
permission: GUEST_PERMISSION.SPACES | GUEST_PERMISSION.SHARES,
- password?: string,
- language?: string,
+ password?: string | null,
+ language?: string | null,
isActive: boolean = true
): Promise<Partial<User>> {
const random = generateShortUUID(64)
@@ -742,12 +761,12 @@ export class SharesManager {
password: await hashPassword(password || generateShortUUID(24)),
role: USER_ROLE.LINK,
isActive: isActive
- } satisfies CreateUserDto
+ }
try {
- ;(guestLink as Partial<User>).id = await this.usersQueries.createUserOrGuest(guestLink, USER_ROLE.LINK)
+ ;(guestLink as Partial<User>).id = await this.usersQueries.createUserOrGuest(guestLink as CreateUserDto, USER_ROLE.LINK)
return guestLink
} catch (e) {
- this.logger.error({ tag: this.createGuestLink.name, msg: `unable to create guest link : ${e}` })
+ this.logger.error({ tag: this.createGuestLink.name, msg: `unable to create guest link : ${toErrorMessage(e)}` })
throw new HttpException('Unable to create guest link', HttpStatus.INTERNAL_SERVER_ERROR)
}
}
@@ -774,13 +793,13 @@ export class SharesManager {
}
}
- private async updateMembers(user: UserModel, share: Partial<Share>, oldMembers: ShareMemberDto[], currentMembers: ShareMemberDto[]) {
+ private async updateMembers(user: UserModel, share: ShareIdentity, oldMembers: ShareProps['members'], currentMembers: ShareMemberDto[]) {
if (oldMembers.length === 0 && currentMembers.length === 0) {
return
}
+ const normalizedOldMembers: ShareMemberDto[] = shareMemberSchema.array().parse(oldMembers)
// diff
- const [add, update, remove]: [ShareMemberDto[], Record<string | 'object', { old: any; new: any } | ShareMemberDto>[], ShareMemberDto[]] =
- diffCollection(oldMembers, currentMembers, ['permissions'], ['id', 'type'])
+ const [add, update, remove] = diffCollection(normalizedOldMembers, currentMembers, ['permissions'], ['id', 'type'])
// check members whitelists
let toAdd: ShareMemberDto[] = []
@@ -807,7 +826,9 @@ export class SharesManager {
// filter links
const toRemove = remove.filter((m) => !m.linkId)
// do remove links
- this.deleteLinkMembers(remove.filter((m) => !!m.linkId)).catch((e: Error) => this.logger.error({ tag: this.updateMembers.name, msg: `${e}` }))
+ this.deleteLinkMembers(remove.filter((m) => !!m.linkId)).catch((e: Error) =>
+ this.logger.error({ tag: this.updateMembers.name, msg: toErrorMessage(e) })
+ )
// do update members
const status: Record<
Exclude<ACTION, ACTION.DELETE_PERMANENTLY>,
@@ -832,12 +853,12 @@ export class SharesManager {
)
} else if (action === ACTION.UPDATE) {
// stores permissions updates and members who might own child shares created from the current share
- for (const m of update as { object: ShareMemberDto; permissions: { old: string; new: string } }[]) {
+ for (const m of update) {
if (
((m.object.type === MEMBER_TYPE.USER || m.object.type === MEMBER_TYPE.GUEST) && members.userIds.indexOf(m.object.id) > -1) ||
((m.object.type === MEMBER_TYPE.GROUP || m.object.type === MEMBER_TYPE.PGROUP) && members.groupIds.indexOf(m.object.id) > -1)
) {
- const diffPermissions = differencePermissions(m.permissions.old, m.permissions.new) as SPACE_OPERATION[]
+ const diffPermissions = differencePermissions(m.permissions!.old!, m.permissions!.new!) as SPACE_OPERATION[]
if (diffPermissions.length) {
upMembersChildShares.push({ object: m.object, rmPermissions: diffPermissions })
}
@@ -846,13 +867,15 @@ export class SharesManager {
}
// clear cache &|| notify
- this.onShareActionForMembers(share, action, members, user).catch((e: Error) => this.logger.error({ tag: this.updateMembers.name, msg: `${e}` }))
+ this.onShareActionForMembers(share, action, members, user).catch((e: Error) =>
+ this.logger.error({ tag: this.updateMembers.name, msg: toErrorMessage(e) })
+ )
}
// do updates
// remove or update potential child shares
this.updateMembersChildSharesPermissions(share.id, currentMembers, rmMembersChildShares, upMembersChildShares).catch((e: Error) =>
- this.logger.error({ tag: this.updateMembers.name, msg: `${e}` })
+ this.logger.error({ tag: this.updateMembers.name, msg: toErrorMessage(e) })
)
}
@@ -892,7 +915,7 @@ export class SharesManager {
(m) =>
(m.type === MEMBER_TYPE.GROUP || m.type === MEMBER_TYPE.PGROUP) &&
memberGroupIds.indexOf(m.id) > -1 &&
- havePermission(m.permissions, SPACE_OPERATION.SHARE_OUTSIDE)
+ havePermission(m.permissions ?? '', SPACE_OPERATION.SHARE_OUTSIDE)
)
if (groupSharePermission) {
this.logger.debug({
@@ -919,7 +942,7 @@ export class SharesManager {
const groupPermissions = currentMembers
.filter((m) => (m.type === MEMBER_TYPE.GROUP || m.type === MEMBER_TYPE.PGROUP) && memberGroupIds.indexOf(m.id) > -1)
.reduce((perms: string[], m: ShareMemberDto) => {
- for (const p of m.permissions.split(SPACE_PERMS_SEP).filter((p: string) => p !== '' && perms.indexOf(p) === -1)) {
+ for (const p of (m.permissions ?? '').split(SPACE_PERMS_SEP).filter((p: string) => p !== '' && perms.indexOf(p) === -1)) {
perms.push(p)
}
return perms
@@ -975,7 +998,7 @@ export class SharesManager {
((m.type === MEMBER_TYPE.USER || m.type === MEMBER_TYPE.GUEST) && m.id === uId)
)
.reduce((perms: string[], m: ShareMemberDto) => {
- for (const p of m.permissions.split(SPACE_PERMS_SEP).filter((p: string) => p !== '' && perms.indexOf(p) === -1)) {
+ for (const p of (m.permissions ?? '').split(SPACE_PERMS_SEP).filter((p: string) => p !== '' && perms.indexOf(p) === -1)) {
perms.push(p)
}
return perms
@@ -1011,7 +1034,12 @@ export class SharesManager {
for (const share of await this.sharesQueries.selectShares(where)) {
try {
// store current child shares members before delete parent share
- const members: ShareChildMember[] = await this.sharesQueries.membersFromChildSharesPermissions(share.id, [share.ownerId], null, false)
+ const members: ShareChildMember[] = await this.sharesQueries.membersFromChildSharesPermissions(
+ share.id,
+ [share.ownerId as number],
+ undefined,
+ false
+ )
await this.sharesQueries.deleteShare(share.id)
this.logger.log({
tag: this.removeShareFromOwners.name,
@@ -1020,14 +1048,14 @@ export class SharesManager {
// clear cache and notify users
if (share.ownerId && (!fromUserId || fromUserId !== share.ownerId)) {
this.clearCachePermissionsAndOrNotify(share, ACTION.DELETE_PERMANENTLY, [share.ownerId]).catch((e: Error) =>
- this.logger.error({ tag: this.removeShareFromOwners.name, msg: `${e}` })
+ this.logger.error({ tag: this.removeShareFromOwners.name, msg: toErrorMessage(e) })
)
}
members.forEach((m) => this.clearCachePermissionsAndOrNotify({ alias: m.shareAlias, name: m.shareName }, ACTION.DELETE, [m.userId]))
} catch (e) {
this.logger.error({
tag: this.removeShareFromOwners.name,
- msg: `share *${share.alias}* (${share.id}) from owner (${share.ownerId}) was not removed : ${e}`
+ msg: `share *${share.alias}* (${share.id}) from owner (${share.ownerId}) was not removed : ${toErrorMessage(e)}`
})
}
}
@@ -1061,7 +1089,7 @@ export class SharesManager {
},
ACTION.UPDATE,
[m.userId]
- ).catch((e: Error) => this.logger.error({ tag: this.removeChildSharesPermissions.name, msg: `${e}` }))
+ ).catch((e: Error) => this.logger.error({ tag: this.removeChildSharesPermissions.name, msg: toErrorMessage(e) }))
this.logger.log({
tag: this.removeChildSharesPermissions.name,
msg: `user (${m.id}) permissions ${JSON.stringify(userPerm.rmPermissions)} on share : ${m.shareAlias} (${m.shareId}) was removed`
@@ -1069,15 +1097,15 @@ export class SharesManager {
} catch (e) {
this.logger.error({
tag: this.removeChildSharesPermissions.name,
- msg: `user (${m.id}) permissions on share *${m.shareAlias}* (${m.shareId}) was not removed : ${e}`
+ msg: `user (${m.id}) permissions on share *${m.shareAlias}* (${m.shareId}) was not removed : ${toErrorMessage(e)}`
})
}
}
}
}
- private async checkChildSharePermissions(user: UserModel, shareId: number, childId: number): Promise<boolean> {
- const isOwnerForChildShare: number = await this.sharesQueries.childExistsForShareOwner(user.id, shareId, childId, user.isAdmin)
+ private async checkChildSharePermissions(user: UserModel, shareId: number, childId: number): Promise<void> {
+ const isOwnerForChildShare = await this.sharesQueries.childExistsForShareOwner(user.id, shareId, childId, user.isAdmin)
if (isOwnerForChildShare !== childId) {
this.logger.warn({
tag: this.checkChildSharePermissions.name,
@@ -1085,10 +1113,9 @@ export class SharesManager {
})
throw new HttpException('Unauthorized', HttpStatus.FORBIDDEN)
}
- return true
}
- private async onShareActionForMembers(share: Partial<Share>, action: ACTION, members: { groupIds: number[]; userIds: number[] }, user?: UserModel) {
+ private async onShareActionForMembers(share: ShareIdentity, action: ACTION, members: { groupIds: number[]; userIds: number[] }, user?: UserModel) {
this.clearCachePermissionsAndOrNotify(
share,
action,
@@ -1096,7 +1123,7 @@ export class SharesManager {
(uid) => uid !== user?.id
),
user
- ).catch((e: Error) => this.logger.error({ tag: this.onShareActionForMembers.name, msg: `${e}` }))
+ ).catch((e: Error) => this.logger.error({ tag: this.onShareActionForMembers.name, msg: toErrorMessage(e) }))
}
private async createLinkFromSpaceOrShare(
@@ -1112,7 +1139,7 @@ export class SharesManager {
throw new HttpException('UUID was not reserved', HttpStatus.BAD_REQUEST)
}
const permission = type === LINK_TYPE.SPACE ? GUEST_PERMISSION.SPACES : GUEST_PERMISSION.SHARES
- const guestLink: Partial<User> = await this.createGuestLink(
+ const guestLink = await this.createGuestLink(
permission,
createOrUpdateLinkDto.password,
createOrUpdateLinkDto.language,
@@ -1121,22 +1148,22 @@ export class SharesManager {
this.logger.debug({ tag: this.createLinkFromSpaceOrShare.name, msg: `guest link (${guestLink.id}) created` })
let linkId: number
try {
- linkId = await this.linksQueries.createLinkToSpaceOrShare(guestLink.id, spaceOrShareId, type, {
+ linkId = await this.linksQueries.createLinkToSpaceOrShare(guestLink.id!, spaceOrShareId, type, {
...createOrUpdateLinkDto,
uuid: uuid,
- userId: guestLink.id
+ userId: guestLink.id!
})
this.logger.debug({
tag: this.createLinkFromSpaceOrShare.name,
msg: `link (${linkId}) for guest link (${guestLink.id}) created : ${JSON.stringify(createOrUpdateLinkDto)}`
})
} catch (e) {
- this.logger.error({ tag: this.createLinkFromSpaceOrShare.name, msg: `unable to create link with uuid (${uuid}) : ${e}` })
+ this.logger.error({ tag: this.createLinkFromSpaceOrShare.name, msg: `unable to create link with uuid (${uuid}) : ${toErrorMessage(e)}` })
throw new HttpException('Unable to update link', HttpStatus.INTERNAL_SERVER_ERROR)
}
}
- private async deleteGuestLinks(guestLinks: Partial<{ id: number; linkId: number }>[]) {
+ private async deleteGuestLinks(guestLinks: { id: number; linkId?: number | null }[]) {
let deletionError: unknown
for (const guestLink of guestLinks) {
try {
@@ -1146,7 +1173,10 @@ export class SharesManager {
this.logger.log({ tag: this.deleteGuestLinks.name, msg: `guest (${guestLink.id}) (link: ${guestLink.linkId}) was removed` })
} catch (e) {
deletionError ??= e
- this.logger.error({ tag: this.deleteGuestLinks.name, msg: `guest (${guestLink.id}) (link: ${guestLink.linkId}) was not removed : ${e}` })
+ this.logger.error({
+ tag: this.deleteGuestLinks.name,
+ msg: `guest (${guestLink.id}) (link: ${guestLink.linkId}) was not removed : ${toErrorMessage(e)}`
+ })
}
}
if (deletionError) throw deletionError
@@ -1154,7 +1184,7 @@ export class SharesManager {
/* MANAGE CACHE PERMISSIONS AND NOTIFY */
- private async clearCachePermissionsAndOrNotify(share: Partial<Share>, action: ACTION, memberIds: number[], user?: UserModel): Promise<void> {
+ private async clearCachePermissionsAndOrNotify(share: ShareDescriptor, action: ACTION, memberIds: number[], user?: UserModel): Promise<void> {
if (!memberIds?.length) {
return
}
@@ -1166,13 +1196,21 @@ export class SharesManager {
// clear permissions for share members
this.sharesQueries
.clearCachePermissions(share.alias, memberIds)
- .catch((e: Error) => this.logger.error({ tag: this.clearCachePermissionsAndOrNotify.name, msg: `${e}` }))
+ .catch((e: Error) => this.logger.error({ tag: this.clearCachePermissionsAndOrNotify.name, msg: toErrorMessage(e) }))
}
if (action !== ACTION.UPDATE) {
// notify the members who have joined or left the share
+ const event = user
+ ? action === ACTION.ADD || action === ACTION.DELETE
+ ? NOTIFICATION_APP_EVENT.SHARES[action]
+ : undefined
+ : NOTIFICATION_APP_EVENT.SHARES_WITHOUT_OWNER[action]
+ if (!event) {
+ return
+ }
const notification: NotificationContent = {
app: NOTIFICATION_APP.SHARES,
- event: user ? NOTIFICATION_APP_EVENT.SHARES[action] : NOTIFICATION_APP_EVENT.SHARES_WITHOUT_OWNER[action],
+ event,
element: share.name,
url: SPACE_REPOSITORY.SHARES
}
@@ -1181,12 +1219,17 @@ export class SharesManager {
author: user,
action: action
})
- .catch((e: Error) => this.logger.error({ tag: this.clearCachePermissionsAndOrNotify.name, msg: `${e}` }))
+ .catch((e: Error) => this.logger.error({ tag: this.clearCachePermissionsAndOrNotify.name, msg: toErrorMessage(e) }))
}
}
- private async notifyGuestLink(user: UserModel, link: SpaceMemberDto | ShareMemberDto, spaceOrShareName: string, action: ACTION) {
- if (!link.linkSettings.email) {
+ private async notifyGuestLink(
+ user: UserModel,
+ link: SpaceMemberDto | ShareMemberDto,
+ spaceOrShareName: string,
+ action: ACTION.ADD | ACTION.UPDATE
+ ) {
+ if (!link.linkSettings!.email) {
return
}
this.notificationsManager
@@ -1194,8 +1237,8 @@ export class SharesManager {
[
{
id: -1,
- email: link.linkSettings.email,
- language: link.linkSettings.language,
+ email: link.linkSettings!.email,
+ language: link.linkSettings!.language as string,
notification: USER_NOTIFICATION.APPLICATION_EMAIL
} satisfies UserMailNotification
],
@@ -1207,11 +1250,11 @@ export class SharesManager {
} satisfies NotificationContent,
{
author: user,
- linkUUID: link.linkSettings.uuid,
- linkPassword: link.linkSettings.password,
+ linkUUID: link.linkSettings!.uuid as string,
+ linkPassword: link.linkSettings!.password as string,
action: action
} satisfies NotificationOptions
)
- .catch((e: Error) => this.logger.error({ tag: this.notifyGuestLink.name, msg: `${e}` }))
+ .catch((e: Error) => this.logger.error({ tag: this.notifyGuestLink.name, msg: toErrorMessage(e) }))
}
}
diff --git a/backend/src/applications/shares/services/shares-queries.service.spec.ts b/backend/src/applications/shares/services/shares-queries.service.spec.ts
index d612200f..b6cb8a34 100644
--- a/backend/src/applications/shares/services/shares-queries.service.spec.ts
+++ b/backend/src/applications/shares/services/shares-queries.service.spec.ts
@@ -43,8 +43,8 @@ describe(SharesQueries.name, () => {
const result = await service.permissions(7, 'grandchild')
expect(findHighestParentShare).not.toHaveBeenCalled()
- expect(result.root.externalParentShareId).toBe(10)
- expect(result.permissions).toBe('d:r')
+ expect(result!.root!.externalParentShareId).toBe(10)
+ expect(result!.permissions).toBe('d:r')
})
it('returns no permissions when the query rejects an unresolved external hierarchy', async () => {
diff --git a/backend/src/applications/shares/services/shares-queries.service.ts b/backend/src/applications/shares/services/shares-queries.service.ts
index 8f3838c3..78aac1d1 100644
--- a/backend/src/applications/shares/services/shares-queries.service.ts
+++ b/backend/src/applications/shares/services/shares-queries.service.ts
@@ -1,9 +1,10 @@
+import { toErrorMessage } from '../../../common/errors.js'
import { Inject, Injectable, Logger } from '@nestjs/common'
-import { and, count, eq, inArray, isNotNull, isNull, ne, or, SelectedFields, SQL, sql } from 'drizzle-orm'
-import { alias, MySqlSelectDynamic, union } from 'drizzle-orm/mysql-core'
+import { and, count, eq, inArray, isNotNull, isNull, ne, or, SQL, sql } from 'drizzle-orm'
+import { alias, MySqlSelectDynamic, type SelectedFields, union } from 'drizzle-orm/mysql-core'
import { MySql2PreparedQuery, MySqlQueryResult } from 'drizzle-orm/mysql2'
import { ACTION } from '../../../common/constants.js'
-import { uniquePermissions } from '../../../common/functions.js'
+import { type ConvertedDiffUpdate, uniquePermissions } from '../../../common/functions.js'
import { createSlug, popFromObject } from '../../../common/shared.js'
import { CacheDecorator } from '../../../infrastructure/cache/cache.decorator.js'
import { Cache } from '../../../infrastructure/cache/cache.service.js'
@@ -48,6 +49,7 @@ import type { ShareProps } from '../interfaces/share-props.interface.js'
import { ShareChild } from '../models/share-child.model.js'
import type { ShareMembers } from '../schemas/share-members.interface.js'
import type { Share } from '../schemas/share.interface.js'
+import type { ShareOwnerIdentity, ShareSelection } from '../interfaces/share-identity.interface.js'
import { sharesMembers } from '../schemas/shares-members.schema.js'
import { shares } from '../schemas/shares.schema.js'
import { externalShareScopeSQL } from '../utils/external-share-scope.sql.js'
@@ -55,12 +57,12 @@ import { externalShareScopeSQL } from '../utils/external-share-scope.sql.js'
@Injectable()
export class SharesQueries {
private readonly logger = new Logger(SharesQueries.name)
- private sharesListQuery: MySql2PreparedQuery<any> = null
- private shareIdentitiesQuery: MySql2PreparedQuery<any> = null
- private shareLinksListQuery: MySql2PreparedQuery<any> = null
- private shareWithMembersQuery: MySql2PreparedQuery<any> = null
- private sharePermissionsQuery: MySql2PreparedQuery<any> = null
- private shareRootFilesQuery: MySql2PreparedQuery<any> = null
+ private sharesListQuery: MySql2PreparedQuery<any> | null = null
+ private shareIdentitiesQuery: MySql2PreparedQuery<any> | null = null
+ private shareLinksListQuery: MySql2PreparedQuery<any> | null = null
+ private shareWithMembersQuery: MySql2PreparedQuery<any> | null = null
+ private sharePermissionsQuery: MySql2PreparedQuery<any> | null = null
+ private shareRootFilesQuery: MySql2PreparedQuery<any> | null = null
constructor(
@Inject(DB_TOKEN_PROVIDER) private readonly db: DBSchema,
@@ -71,11 +73,11 @@ export class SharesQueries {
return createUniqueAlias(createSlug(name, true), (alias: string) => this.shareExistsForAlias(alias, excludedShareId))
}
- shareExistsForOwner(userId: number, shareId: number): any | undefined {
+ shareExistsForOwner(userId: number, shareId: number) {
return this.db.query.shares.findFirst({ columns: { id: true }, where: and(eq(shares.id, shareId), eq(shares.ownerId, userId)) })
}
- async childExistsForShareOwner(userId: number, shareId: number, childId: number, isAdmin: boolean = false): Promise<number> {
+ async childExistsForShareOwner(userId: number, shareId: number, childId: number, isAdmin: boolean = false): Promise<number | null> {
const childShare: any = alias(shares, 'childShare')
const withChildren: any = sql`
WITH RECURSIVE child (id, parentId) AS
@@ -98,7 +100,7 @@ export class SharesQueries {
return r.length ? r[0].id : null
}
- async findHighestParentShare(childShareId: number): Promise<number> {
+ async findHighestParentShare(childShareId: number): Promise<number | null> {
const parentShare: any = alias(shares, 'parentShare')
const withParents: any = sql`
WITH RECURSIVE parent (id, parentId) AS
@@ -120,7 +122,7 @@ export class SharesQueries {
return r.length ? r[0].id : null
}
- selectShares(props: Partial<Record<keyof Share, any>>): Promise<Partial<Share>[]> {
+ selectShares(props: Partial<Record<keyof Share, any>>): Promise<ShareSelection[]> {
const where: SQL[] = convertToWhere(shares, props)
return this.db
.select({ id: shares.id, ownerId: shares.ownerId, alias: shares.alias, name: shares.name })
@@ -128,7 +130,7 @@ export class SharesQueries {
.where(and(...where))
}
- selectParentSharesFromSpaceId(spaceId: number, ownerIds?: number[]): Promise<Partial<Share>[]> {
+ selectParentSharesFromSpaceId(spaceId: number, ownerIds?: number[]): Promise<ShareOwnerIdentity[]> {
const where: SQL[] = [eq(shares.spaceId, spaceId), isNull(shares.spaceRootId), isNull(shares.parentId)]
if (ownerIds && ownerIds.length) {
where.push(inArray(shares.ownerId, ownerIds))
@@ -139,7 +141,7 @@ export class SharesQueries {
.where(and(...where))
}
- sharesQuotaExternalPaths(shareId?: number): Promise<Partial<Share>[]> {
+ sharesQuotaExternalPaths(shareId?: number): Promise<(Pick<Share, 'id' | 'alias' | 'storageUsage' | 'storageQuota'> & { externalPath: string })[]> {
return this.db
.select({
id: shares.id,
@@ -149,16 +151,18 @@ export class SharesQueries {
externalPath: shares.externalPath
})
.from(shares)
- .where(and(isNotNull(shares.externalPath), ...[...(shareId ? [eq(shares.id, shareId)] : [])]))
+ .where(and(isNotNull(shares.externalPath), shareId ? eq(shares.id, shareId) : undefined)) as Promise<
+ (Pick<Share, 'id' | 'alias' | 'storageUsage' | 'storageQuota'> & { externalPath: string })[]
+ >
}
- async listShareLinks(user: UserModel, shareId: number, asAdmin?: boolean): Promise<ShareLink>
+ async listShareLinks(user: UserModel, shareId: number, asAdmin?: boolean): Promise<ShareLink | null>
async listShareLinks(user: UserModel, shareId?: number, asAdmin?: boolean): Promise<ShareLink[]>
- async listShareLinks(user: UserModel, shareId?: number, asAdmin: boolean = false): Promise<ShareLink[] | ShareLink> {
+ async listShareLinks(user: UserModel, shareId?: number, asAdmin: boolean = false): Promise<ShareLink[] | ShareLink | null> {
if (!this.shareLinksListQuery) {
const [selectFile, shareRootFile, parentShare, parentShareFile, childShareFromRoot, shareMembers] = this.shareFileSelect()
const linkGuest: any = alias(users, 'linkGuest')
- const select: ShareLink | SelectedFields<any, any> = {
+ const select = {
id: shares.id,
ownerId: shares.ownerId,
alias: shares.alias,
@@ -190,7 +194,7 @@ export class SharesQueries {
currentIp: linkGuest.currentIp,
lastIp: linkGuest.lastIp
}
- }
+ } satisfies Record<keyof ShareLink, any>
this.shareLinksListQuery = this.shareFileJoin(select, shareRootFile, parentShare, parentShareFile, childShareFromRoot, shareMembers)
.innerJoin(links, eq(links.id, shareMembers.linkId))
.innerJoin(linkGuest, eq(linkGuest.id, links.userId))
@@ -207,7 +211,7 @@ export class SharesQueries {
)
.prepare()
}
- const shareLinks: ShareLink[] = await this.shareLinksListQuery.execute({
+ const shareLinks: ShareLink[] = await this.shareLinksListQuery!.execute({
userId: user.id,
shareId: shareId || 0,
isAdmin: +user.isAdmin,
@@ -219,16 +223,16 @@ export class SharesQueries {
return shareLinks
}
- async getShareWithMembers(user: UserModel, shareId: number, asAdmin = false): Promise<ShareProps> {
+ async getShareWithMembers(user: UserModel, shareId: number, asAdmin = false): Promise<ShareProps | null> {
// asAdmin : true if the user is the owner of the parent share or if the share is requested from the administration
if (!this.shareWithMembersQuery) {
const [selectFile, shareRootFile, parentShare, parentShareFile, childShareFromRoot, shareMembers] = this.shareFileSelect()
const linkUsers: any = alias(users, 'linkUsers')
- const select: ShareProps | SelectedFields<any, any> = {
+ const select = {
id: shares.id,
ownerId: shares.ownerId,
- name: shares.name,
alias: shares.alias,
+ name: shares.name,
externalPath: sql`IF (${shares.externalPath} IS NOT NULL AND ${shares.ownerId} IS NOT NULL, '.', ${shares.externalPath})`,
enabled: shares.enabled,
description: shares.description,
@@ -272,7 +276,7 @@ export class SharesQueries {
permissions: shareMembers.permissions,
createdAt: dateTimeUTC(shareMembers.createdAt)
})
- }
+ } satisfies SelectedFields
this.shareWithMembersQuery = this.shareFileJoin(select, shareRootFile, parentShare, parentShareFile, childShareFromRoot, shareMembers)
.leftJoin(users, and(isNull(shareMembers.linkId), eq(users.id, shareMembers.userId)))
.leftJoin(groups, eq(groups.id, shareMembers.groupId))
@@ -292,7 +296,7 @@ export class SharesQueries {
.limit(1)
.prepare()
}
- const [share] = await this.shareWithMembersQuery.execute({ userId: user.id, shareId, isAdmin: +user.isAdmin, asAdmin: +asAdmin })
+ const [share] = await this.shareWithMembersQuery!.execute({ userId: user.id, shareId, isAdmin: +user.isAdmin, asAdmin: +asAdmin })
if (!share) return null
// merge members
share.members = [...popFromObject('users', share), ...popFromObject('links', share), ...popFromObject('groups', share)]
@@ -309,7 +313,7 @@ export class SharesQueries {
this.logger.verbose({ tag: this.updateShare.name, msg: `share (${id}) was updated : ${JSON.stringify(set)}` })
return true
} catch (e) {
- this.logger.error({ tag: this.updateShare.name, msg: `share (${id}) was not updated : ${JSON.stringify(set)} : ${e}` })
+ this.logger.error({ tag: this.updateShare.name, msg: `share (${id}) was not updated : ${JSON.stringify(set)} : ${toErrorMessage(e)}` })
return false
}
}
@@ -332,7 +336,10 @@ export class SharesQueries {
this.logger.debug({ tag: this.updateMember.name, msg: `${JSON.stringify(filters)} was updated : ${JSON.stringify(set)}` })
return true
} catch (e) {
- this.logger.error({ tag: this.updateMember.name, msg: `${JSON.stringify(filters)} was not updated : ${JSON.stringify(set)} : ${e}` })
+ this.logger.error({
+ tag: this.updateMember.name,
+ msg: `${JSON.stringify(filters)} was not updated : ${JSON.stringify(set)} : ${toErrorMessage(e)}`
+ })
return false
}
}
@@ -340,7 +347,7 @@ export class SharesQueries {
async updateMembers(
shareId: number,
add: ShareMemberDto[],
- update: Record<string | 'object', Partial<ShareMembers> | ShareMemberDto>[],
+ update: ConvertedDiffUpdate<ShareMemberDto, 'permissions'>[],
remove: ShareMemberDto[]
): Promise<Record<Exclude<ACTION, ACTION.DELETE_PERMANENTLY>, { userIds: number[]; groupIds: number[] }>> {
// store status
@@ -363,7 +370,10 @@ export class SharesQueries {
status[ACTION.ADD][`${m.type === MEMBER_TYPE.USER || m.type === MEMBER_TYPE.GUEST ? 'userIds' : 'groupIds'}`].push(m.id)
this.logger.debug({ tag: this.updateMembers.name, msg: `${m.type} (${m.id}) added to the share (${shareId})` })
} catch (e) {
- this.logger.error({ tag: this.updateMembers.name, msg: `${m.type} (${m.id}) was not added to the share (${shareId}) -> : ${e}` })
+ this.logger.error({
+ tag: this.updateMembers.name,
+ msg: `${m.type} (${m.id}) was not added to the share (${shareId}) -> : ${toErrorMessage(e)}`
+ })
}
}
// update
@@ -388,7 +398,7 @@ export class SharesQueries {
} catch (e) {
this.logger.error({
tag: this.updateMembers.name,
- msg: `${m.type} (${m.id}) was not updated on share (${shareId}) : ${JSON.stringify(props)} : ${e}`
+ msg: `${m.type} (${m.id}) was not updated on share (${shareId}) : ${JSON.stringify(props)} : ${toErrorMessage(e)}`
})
}
}
@@ -409,7 +419,10 @@ export class SharesQueries {
status[ACTION.DELETE][`${m.type === MEMBER_TYPE.USER || m.type === MEMBER_TYPE.GUEST ? 'userIds' : 'groupIds'}`].push(m.id)
this.logger.debug({ tag: this.updateMembers.name, msg: `${m.type} (${m.id}) removed from share (${shareId})` })
} catch (e) {
- this.logger.error({ tag: this.updateMembers.name, msg: `${m.type} (${m.id}) was not removed from share (${shareId}) : ${e}` })
+ this.logger.error({
+ tag: this.updateMembers.name,
+ msg: `${m.type} (${m.id}) was not removed from share (${shareId}) : ${toErrorMessage(e)}`
+ })
}
}
return status
@@ -417,7 +430,7 @@ export class SharesQueries {
async shareEnv(shareId: number): Promise<Partial<ShareEnv>> {
const shareSpaceRoot: any = alias(spacesRoots, 'shareSpaceRoot')
- const select: ShareEnv | SelectedFields<any, any> = {
+ const select: any = {
id: shares.id,
alias: shares.alias,
enabled: shares.enabled,
@@ -440,7 +453,7 @@ export class SharesQueries {
},
externalPath: shares.externalPath
}
- }
+ } satisfies { [K in keyof ShareEnv]: any }
const [shareEnv] = await this.db
.select(select)
.from(shares)
@@ -486,7 +499,7 @@ export class SharesQueries {
async listShares(user: UserModel): Promise<ShareFile[]> {
if (!this.sharesListQuery) {
const [selectFile, shareRootFile, parentShare, parentShareFile, childShareFromRoot, shareMembers] = this.shareFileSelect()
- const select: ShareFile | SelectedFields<any, any> = {
+ const select = {
id: shares.id,
name: shares.name,
alias: shares.alias,
@@ -509,7 +522,7 @@ export class SharesQueries {
groups: count(shareMembers.groupId),
links: count(shareMembers.linkId)
}
- }
+ } satisfies Record<keyof Omit<ShareFile, 'syncs'>, any>
this.sharesListQuery = this.shareFileJoin(select, shareRootFile, parentShare, parentShareFile, childShareFromRoot, shareMembers)
.where(
and(
@@ -520,7 +533,7 @@ export class SharesQueries {
.groupBy(shares.id)
.prepare()
}
- const r: ShareFile[] = await this.sharesListQuery.execute({ userId: user.id, shareType: SHARE_TYPE.COMMON, isAdmin: +user.isAdmin })
+ const r: ShareFile[] = await this.sharesListQuery!.execute({ userId: user.id, shareType: SHARE_TYPE.COMMON, isAdmin: +user.isAdmin })
await this.setShareCounts(r)
return r
}
@@ -649,7 +662,7 @@ export class SharesQueries {
const shareSpaceRoot: any = alias(spacesRoots, 'shareSpaceRoot')
const originOwner: any = alias(users, 'originOwner')
const childShare: any = alias(shares, 'childShare')
- const selectUnion: FileProps | SelectedFields<any, any> = {
+ const selectUnion = {
id: files.id,
path: sql`IF (${files.id} IS NOT NULL, ${filePathSQL(files)}, '')`.as('path'),
isDir: files.isDir,
@@ -683,8 +696,8 @@ export class SharesQueries {
syncPathId: sql`${syncPaths.id}`.as('syncPathId'),
syncPathClientId: sql`${syncClients.id}`.as('syncPathClientId'),
syncPathClientName: sql`JSON_VALUE(${syncClients.info}, '$.node')`.as('syncPathClientName')
- }
- const filters: SQL[] = [or(isNull(shares.ownerId), ne(shares.ownerId, sql.placeholder('userId')))]
+ } satisfies SelectedFields
+ const filters: SQL[] = [or(isNull(shares.ownerId), ne(shares.ownerId, sql.placeholder('userId')))!]
const externalShareFilters = [...filters, isNotNull(shares.externalPath)]
const externalShareTargets = union(
this.fromUserQuery({ id: shares.id, parentId: shares.parentId, externalPath: shares.externalPath }, externalShareFilters),
@@ -747,7 +760,7 @@ export class SharesQueries {
.leftJoin(originOwner, and(isNull(shares.externalPath), eq(originOwner.id, files.ownerId)))
}
const unionAlias = union(fromUser, fromGroups, fromAdminShares).as('union_alias')
- const select: FileProps | SelectedFields<any, any> = {
+ const select: any = {
id: unionAlias.id,
path: unionAlias.path,
isDir: unionAlias.isDir,
@@ -793,7 +806,7 @@ export class SharesQueries {
})}, '[]')`.mapWith(dbParseJson),
hasComments: sql<boolean>`IF (${sql.placeholder('withDetails')}, ${fileHasCommentsSubquerySQL(unionAlias.id)}, 0)`.mapWith(Boolean),
isFavorite: isNotNull(filesFavorites.fileId).mapWith(Boolean)
- }
+ } satisfies Partial<Record<keyof FileProps, any>>
this.shareRootFilesQuery = this.db
.select(select)
.from(unionAlias)
@@ -821,13 +834,13 @@ export class SharesQueries {
withSyncs: +(details?.syncs ?? false)
})
for (const f of fps) {
- f.root.permissions = uniquePermissions(f.root.permissions)
+ f.root!.permissions = uniquePermissions(f.root!.permissions!)
}
return fps
}
@CacheDecorator()
- async permissions(userId: number, shareAlias: string, isAdmin: number = 0): Promise<Partial<SpaceEnv>> {
+ async permissions(userId: number, shareAlias: string, isAdmin: number = 0): Promise<Partial<SpaceEnv> | undefined> {
if (!this.sharePermissionsQuery) {
const shareSpaceRoot: any = alias(spacesRoots, 'shareSpaceRoot')
// Make every file operation through a nested external share address the
@@ -844,7 +857,7 @@ export class SharesQueries {
.from(shares)
.where(eq(shares.alias, sql.placeholder('shareAlias')))
const externalRootScope = externalShareScopeSQL(targetShare, 'permissionExternalScope', { mapExternalRootToSelf: false })
- const selectUnion: SpaceEnv | SelectedFields<any, any> = {
+ const selectUnion = {
id: shares.id,
alias: shares.alias,
name: shares.name,
@@ -861,7 +874,7 @@ export class SharesQueries {
rootSpaceRootId: sql`IF (${spacesRoots.id} IS NULL, ${shareSpaceRoot.id}, ${spacesRoots.id})`.as('rootSpaceRootId'),
rootSpaceRootExternalPath: sql`IF (${spacesRoots.externalPath} IS NULL,
${shareSpaceRoot.externalPath}, ${spacesRoots.externalPath})`.as('rootSpaceRootExternalPath')
- }
+ } satisfies SelectedFields
const filters: SQL[] = [eq(shares.alias, sql.placeholder('shareAlias'))]
const fromUser = this.fromUserQuery(selectUnion, filters).$dynamic()
const fromGroups = this.fromGroupsQuery(selectUnion, filters).$dynamic()
@@ -890,7 +903,7 @@ export class SharesQueries {
.leftJoin(users, eq(users.id, files.ownerId))
}
const unionAlias = union(fromUser, fromGroups, fromAdminShares).as('union_alias')
- const select: SpaceEnv | SelectedFields<any, any> = {
+ const select: any = {
id: unionAlias.id,
alias: unionAlias.alias,
name: unionAlias.name,
@@ -908,7 +921,7 @@ export class SharesQueries {
externalPath: unionAlias.rootExternalPath,
externalParentShareId: externalRootScope.storageShareId
}
- }
+ } satisfies Partial<Record<keyof SpaceEnv, any>>
this.sharePermissionsQuery = this.db
.select(select)
.from(unionAlias)
@@ -921,7 +934,7 @@ export class SharesQueries {
// `isAdmin` is used in `fromAdminSharesQuery` function
const [r]: Partial<SpaceEnv>[] = await this.sharePermissionsQuery.execute({ userId, shareAlias, isAdmin })
if (r) {
- r.permissions = uniquePermissions(r.permissions)
+ r.permissions = uniquePermissions(r.permissions!)
}
return r
}
@@ -953,7 +966,7 @@ export class SharesQueries {
const keys = await this.cache.keys(pattern)
if (keys.length) {
this.logger.verbose({ tag: this.clearCacheIdentities.name, msg: `${JSON.stringify(keys)}` })
- this.cache.mdel(keys).catch((e: Error) => this.logger.error({ tag: this.clearCacheIdentities.name, msg: `${e}` }))
+ this.cache.mdel(keys).catch((e: Error) => this.logger.error({ tag: this.clearCacheIdentities.name, msg: toErrorMessage(e) }))
}
}
}
@@ -966,19 +979,19 @@ export class SharesQueries {
const keys = await this.cache.keys(pattern)
if (keys.length) {
this.logger.verbose({ tag: this.clearCachePermissions.name, msg: `${JSON.stringify(keys)}` })
- this.cache.mdel(keys).catch((e: Error) => this.logger.error({ tag: this.clearCachePermissions.name, msg: `${e}` }))
+ this.cache.mdel(keys).catch((e: Error) => this.logger.error({ tag: this.clearCachePermissions.name, msg: toErrorMessage(e) }))
}
}
}
- private shareExistsForAlias(alias: string, excludedShareId?: number): any | undefined {
+ private shareExistsForAlias(alias: string, excludedShareId?: number) {
return this.db.query.shares.findFirst({
columns: { id: true },
where: excludedShareId === undefined ? eq(shares.alias, alias) : and(eq(shares.alias, alias), ne(shares.id, excludedShareId))
})
}
- private fromUserQuery(select: SelectedFields<any, any>, filters: SQL[] = []) {
+ private fromUserQuery(select: Record<string, any>, filters: SQL[] = []) {
const where: SQL[] = [eq(sharesMembers.userId, sql.placeholder('userId')), ...filters]
return this.db
.select(select)
@@ -987,7 +1000,7 @@ export class SharesQueries {
.where(and(...where))
}
- private fromGroupsQuery(select: SelectedFields<any, any>, filters: SQL[] = []) {
+ private fromGroupsQuery(select: Record<string, any>, filters: SQL[] = []) {
const where: SQL[] = [eq(sharesMembers.groupId, usersGroups.groupId), ...filters]
return this.db
.select(select)
@@ -997,7 +1010,7 @@ export class SharesQueries {
.where(and(...where))
}
- private fromAdminSharesQuery(select: SelectedFields<any, any>, filters: SQL[] = []) {
+ private fromAdminSharesQuery(select: Record<string, any>, filters: SQL[] = []) {
const where: SQL[] = [eq(sql.placeholder('isAdmin'), sql`1`), isNull(shares.ownerId), ...filters]
return this.db
.select(select)
@@ -1011,7 +1024,7 @@ export class SharesQueries {
const parentShareFile: any = alias(files, 'parentShareFile')
const childShareFromRoot: any = alias(spacesRoots, 'childShareFromRoot')
const shareMembers: any = alias(sharesMembers, 'shareMembers')
- const selectFile: FileSpace | SelectedFields<any, any> = {
+ const selectFile = {
id: sql`IF (${shares.fileId} IS NULL AND ${shareRootFile.id} IS NOT NULL,
${shareRootFile.id}, ${files.id})`.as('fileId'),
ownerId: sql`IF (${shares.spaceId} IS NOT NULL,
@@ -1040,7 +1053,7 @@ export class SharesQueries {
name: sql`IF (${shares.parentId} IS NULL, ${spacesRoots.name}, NULL)`
}
}
- }
+ } satisfies Record<keyof Omit<FileSpace, 'permissions'>, any>
return [selectFile, shareRootFile, parentShare, parentShareFile, childShareFromRoot, shareMembers]
}
diff --git a/backend/src/applications/shares/shares.controller.ts b/backend/src/applications/shares/shares.controller.ts
index a84630c7..78735f00 100644
--- a/backend/src/applications/shares/shares.controller.ts
+++ b/backend/src/applications/shares/shares.controller.ts
@@ -1,6 +1,7 @@
-import { Body, Controller, Delete, Get, Param, ParseIntPipe, Post, Put, UseGuards } from '@nestjs/common'
+import { Body, Controller, Delete, Get, Param, Post, Put, UseGuards } from '@nestjs/common'
+import { integerFromStringSchema } from '../../configuration/config.schema.js'
import { LINK_TYPE } from '../links/constants/links.js'
-import { CreateOrUpdateLinkDto } from '../links/dto/create-or-update-link.dto.js'
+import { type CreateOrUpdateLinkDto, createOrUpdateLinkSchema } from '../links/dto/create-or-update-link.dto.js'
import { LinkGuest } from '../links/interfaces/link-guest.interface.js'
import { USER_PERMISSION, USER_ROLE } from '../users/constants/user.js'
import { UserHavePermission } from '../users/decorators/permissions.decorator.js'
@@ -10,12 +11,13 @@ import { UserPermissionsGuard } from '../users/guards/permissions.guard.js'
import { UserRolesGuard } from '../users/guards/roles.guard.js'
import { UserModel } from '../users/models/user.model.js'
import { SHARES_ROUTE } from './constants/routes.js'
-import { CreateOrUpdateShareDto } from './dto/create-or-update-share.dto.js'
+import { createOrUpdateShareSchema, type ValidatedCreateOrUpdateShareDto } from './dto/create-or-update-share.dto.js'
import type { ShareFile } from './interfaces/share-file.interface.js'
import { ShareLink } from './interfaces/share-link.interface.js'
import type { ShareProps } from './interfaces/share-props.interface.js'
import { ShareChild } from './models/share-child.model.js'
import { SharesManager } from './services/shares-manager.service.js'
+import { linkTypeParameterSchema } from './shares.schema.js'
@Controller(SHARES_ROUTE.BASE)
@UserHaveRole(USER_ROLE.USER)
@@ -32,12 +34,15 @@ export class SharesController {
}
@Get(':id')
- getShareWithMembers(@GetUser() user: UserModel, @Param('id', ParseIntPipe) shareId: number): Promise<ShareProps> {
+ getShareWithMembers(@GetUser() user: UserModel, @Param('id', { schema: integerFromStringSchema }) shareId: number): Promise<ShareProps> {
return this.sharesManager.getShareWithMembers(user, shareId)
}
@Post()
- createShare(@GetUser() user: UserModel, @Body() createOrUpdateShareDto: CreateOrUpdateShareDto): Promise<ShareProps> {
+ createShare(
+ @GetUser() user: UserModel,
+ @Body({ schema: createOrUpdateShareSchema }) createOrUpdateShareDto: ValidatedCreateOrUpdateShareDto
+ ): Promise<ShareProps> {
if (createOrUpdateShareDto.parent?.alias) {
return this.sharesManager.createChildShare(user, createOrUpdateShareDto)
}
@@ -47,29 +52,29 @@ export class SharesController {
@Put(':id')
updateShare(
@GetUser() user: UserModel,
- @Param('id', ParseIntPipe) shareId: number,
- @Body() createOrUpdateShareDto: CreateOrUpdateShareDto
+ @Param('id', { schema: integerFromStringSchema }) shareId: number,
+ @Body({ schema: createOrUpdateShareSchema }) createOrUpdateShareDto: ValidatedCreateOrUpdateShareDto
): Promise<ShareProps> {
return this.sharesManager.updateShare(user, shareId, createOrUpdateShareDto)
}
@Delete(':id')
- deleteShare(@GetUser() user: UserModel, @Param('id', ParseIntPipe) shareId: number): Promise<void> {
+ deleteShare(@GetUser() user: UserModel, @Param('id', { schema: integerFromStringSchema }) shareId: number): Promise<void> {
return this.sharesManager.deleteShare(user, shareId)
}
/* MANAGE CHILD SHARES */
@Get(`:id/${SHARES_ROUTE.CHILDREN}`)
- listChildShares(@GetUser() user: UserModel, @Param('id', ParseIntPipe) shareId: number): Promise<ShareChild[]> {
+ listChildShares(@GetUser() user: UserModel, @Param('id', { schema: integerFromStringSchema }) shareId: number): Promise<ShareChild[]> {
return this.sharesManager.listChildShares(user, shareId)
}
@Get(`:id/${SHARES_ROUTE.CHILDREN}/:cid`)
getShareChild(
@GetUser() user: UserModel,
- @Param('id', ParseIntPipe) shareId: number,
- @Param('cid', ParseIntPipe) childId: number
+ @Param('id', { schema: integerFromStringSchema }) shareId: number,
+ @Param('cid', { schema: integerFromStringSchema }) childId: number
): Promise<ShareProps> {
return this.sharesManager.getChildShare(user, shareId, childId)
}
@@ -77,9 +82,9 @@ export class SharesController {
@Put(`:id/${SHARES_ROUTE.CHILDREN}/:cid`)
updateShareChild(
@GetUser() user: UserModel,
- @Param('id', ParseIntPipe) shareId: number,
- @Param('cid', ParseIntPipe) childId: number,
- @Body() createOrUpdateShareDto: CreateOrUpdateShareDto
+ @Param('id', { schema: integerFromStringSchema }) shareId: number,
+ @Param('cid', { schema: integerFromStringSchema }) childId: number,
+ @Body({ schema: createOrUpdateShareSchema }) createOrUpdateShareDto: ValidatedCreateOrUpdateShareDto
): Promise<ShareProps> {
return this.sharesManager.updateChildShare(user, shareId, childId, createOrUpdateShareDto)
}
@@ -87,8 +92,8 @@ export class SharesController {
@Delete(`:id/${SHARES_ROUTE.CHILDREN}/:cid`)
deleteShareChild(
@GetUser() user: UserModel,
- @Param('id', ParseIntPipe) shareId: number,
- @Param('cid', ParseIntPipe) childId: number
+ @Param('id', { schema: integerFromStringSchema }) shareId: number,
+ @Param('cid', { schema: integerFromStringSchema }) childId: number
): Promise<void> {
return this.sharesManager.deleteChildShare(user, shareId, childId)
}
@@ -107,15 +112,15 @@ export class SharesController {
}
@Get(`${SHARES_ROUTE.LINKS}/:id`)
- getShareLink(@GetUser() user: UserModel, @Param('id', ParseIntPipe) shareId: number): Promise<ShareLink> {
+ getShareLink(@GetUser() user: UserModel, @Param('id', { schema: integerFromStringSchema }) shareId: number): Promise<ShareLink> {
return this.sharesManager.getShareLink(user, shareId)
}
@Get(`${SHARES_ROUTE.LINKS}/:id/${SHARES_ROUTE.CHILDREN}/:cid`)
getChildShareLink(
@GetUser() user: UserModel,
- @Param('id', ParseIntPipe) shareId: number,
- @Param('cid', ParseIntPipe) childId: number
+ @Param('id', { schema: integerFromStringSchema }) shareId: number,
+ @Param('cid', { schema: integerFromStringSchema }) childId: number
): Promise<ShareLink> {
return this.sharesManager.getChildShare(user, shareId, childId, true)
}
@@ -123,9 +128,9 @@ export class SharesController {
@Get(`${SHARES_ROUTE.LINKS}/:id/:type(space|share)/:typeId`)
getLinkFromSpaceOrShare(
@GetUser() user: UserModel,
- @Param('id', ParseIntPipe) linkId: number,
- @Param('type') type: LINK_TYPE,
- @Param('typeId', ParseIntPipe) typeId: number
+ @Param('id', { schema: integerFromStringSchema }) linkId: number,
+ @Param('type', { schema: linkTypeParameterSchema }) type: LINK_TYPE,
+ @Param('typeId', { schema: integerFromStringSchema }) typeId: number
): Promise<LinkGuest> {
return this.sharesManager.getLinkFromSpaceOrShare(user, linkId, typeId, type)
}
@@ -133,10 +138,10 @@ export class SharesController {
@Put(`${SHARES_ROUTE.LINKS}/:id/:type(space|share)/:typeId`)
updateLinkFromSpaceOrShare(
@GetUser() user: UserModel,
- @Param('id', ParseIntPipe) linkId: number,
- @Param('type') type: LINK_TYPE,
- @Param('typeId', ParseIntPipe) typeId: number,
- @Body() createOrUpdateLinkDto: CreateOrUpdateLinkDto
+ @Param('id', { schema: integerFromStringSchema }) linkId: number,
+ @Param('type', { schema: linkTypeParameterSchema }) type: LINK_TYPE,
+ @Param('typeId', { schema: integerFromStringSchema }) typeId: number,
+ @Body({ schema: createOrUpdateLinkSchema }) createOrUpdateLinkDto: CreateOrUpdateLinkDto
): Promise<LinkGuest> {
return this.sharesManager.updateLinkFromSpaceOrShare(user, linkId, typeId, type, createOrUpdateLinkDto, true)
}
diff --git a/backend/src/applications/shares/shares.e2e-spec.ts b/backend/src/applications/shares/shares.e2e-spec.ts
index b73e9737..34bbf1e5 100644
--- a/backend/src/applications/shares/shares.e2e-spec.ts
+++ b/backend/src/applications/shares/shares.e2e-spec.ts
@@ -24,14 +24,14 @@ describe('Shares (e2e)', () => {
let module: TestingModule
let db: DBSchema
let sharesQueries: SharesQueries
- let actorId: number | undefined
- let childActorId: number | undefined
- let ownerId: number | undefined
- let externalRootId: number | undefined
- let childId: number | undefined
- let grandchildId: number | undefined
- let internalRootId: number | undefined
- let externalFileId: number | undefined
+ let actorId: number
+ let childActorId: number
+ let ownerId: number
+ let externalRootId: number
+ let childId: number
+ let grandchildId: number
+ let internalRootId: number
+ let externalFileId: number
const suffix = randomUUID().replaceAll('-', '').slice(0, 12)
const aliases = {
@@ -168,13 +168,13 @@ describe('Shares (e2e)', () => {
permissions: 'm',
root: { externalPath, externalParentShareId: externalRootId }
})
- expect(grandchild.root.externalParentShareId).not.toBe(childId)
+ expect(grandchild!.root!.externalParentShareId).not.toBe(childId)
})
it('uses the same external root scope without replacing each listed share permissions', async () => {
const roots = await sharesQueries.shareRootFiles({ id: actorId, isAdmin: false } as UserModel, null)
- const child = roots.find((root) => root.root.alias === aliases.child)
- const grandchild = roots.find((root) => root.root.alias === aliases.grandchild)
+ const child = roots.find((root) => root.root!.alias === aliases.child)
+ const grandchild = roots.find((root) => root.root!.alias === aliases.grandchild)
expect(child).toMatchObject({ origin: { shareExternalId: externalRootId }, root: { permissions: 'd:m' } })
expect(grandchild).toMatchObject({ origin: { shareExternalId: externalRootId }, root: { permissions: 'm' } })
@@ -208,6 +208,6 @@ describe('Shares (e2e)', () => {
await expect(sharesQueries.permissions(actorId, aliases.malformedChild)).resolves.toBeUndefined()
const roots = await sharesQueries.shareRootFiles({ id: actorId, isAdmin: false } as UserModel, null)
- expect(roots.some((root) => root.root.alias === aliases.malformedChild)).toBe(false)
+ expect(roots.some((root) => root.root!.alias === aliases.malformedChild)).toBe(false)
})
})
diff --git a/backend/src/applications/shares/shares.schema.ts b/backend/src/applications/shares/shares.schema.ts
new file mode 100644
index 00000000..414bd900
--- /dev/null
+++ b/backend/src/applications/shares/shares.schema.ts
@@ -0,0 +1,4 @@
+import { z } from 'zod'
+import { LINK_TYPE } from '../links/constants/links.js'
+
+export const linkTypeParameterSchema = z.enum(LINK_TYPE)
diff --git a/backend/src/applications/spaces/constants/spaces.ts b/backend/src/applications/spaces/constants/spaces.ts
index d6bfa165..308e2f38 100644
--- a/backend/src/applications/spaces/constants/spaces.ts
+++ b/backend/src/applications/spaces/constants/spaces.ts
@@ -32,7 +32,7 @@ export enum SPACE_ROLE {
export const SPACE_ALL_OPERATIONS: string = Object.values(SPACE_OPERATION).sort().join(SPACE_PERMS_SEP)
-export const SPACE_HTTP_PERMISSION: Record<string, SPACE_OPERATION> = {
+export const SPACE_HTTP_PERMISSION: Record<string, SPACE_OPERATION | null> = {
GET: null,
POST: SPACE_OPERATION.ADD,
PUT: SPACE_OPERATION.ADD,
diff --git a/backend/src/applications/spaces/dto/create-or-update-space.dto.spec.ts b/backend/src/applications/spaces/dto/create-or-update-space.dto.spec.ts
new file mode 100644
index 00000000..984a8cb0
--- /dev/null
+++ b/backend/src/applications/spaces/dto/create-or-update-space.dto.spec.ts
@@ -0,0 +1,57 @@
+import { MEMBER_TYPE } from '../../users/constants/member.js'
+import { createOrUpdateSpaceSchema } from './create-or-update-space.dto.js'
+
+describe('createOrUpdateSpaceSchema', () => {
+ const manager = { id: 1, type: MEMBER_TYPE.USER }
+ const largeInteger = 2 ** 53
+
+ it.each([
+ { name: 'space', managers: [manager] },
+ { name: 'space', managers: [manager], members: null, links: null }
+ ])('normalizes missing or null member collections', (input) => {
+ expect(createOrUpdateSpaceSchema.parse(input)).toEqual(expect.objectContaining({ members: [], links: [], storageQuota: null }))
+ })
+
+ it('normalizes a null alias to an empty string', () => {
+ expect(createOrUpdateSpaceSchema.parse({ name: 'space', alias: null, managers: [manager] }).alias).toBe('')
+ })
+
+ it('accepts large space, member and link ids and storage quotas', () => {
+ const member = { id: largeInteger, type: MEMBER_TYPE.USER, linkId: largeInteger }
+ const result = createOrUpdateSpaceSchema.parse({
+ id: largeInteger,
+ name: 'space',
+ storageQuota: largeInteger,
+ managers: [member],
+ members: [member],
+ links: [member]
+ })
+
+ expect(result).toMatchObject({
+ id: largeInteger,
+ storageQuota: largeInteger,
+ managers: [member],
+ members: [member],
+ links: [member]
+ })
+ })
+
+ it.each(['id', 'storageQuota'])('still rejects a fractional %s', (field) => {
+ expect(createOrUpdateSpaceSchema.safeParse({ name: 'space', managers: [manager], [field]: 1.5 }).success).toBe(false)
+ })
+
+ it.each(['id', 'linkId'])('still rejects a fractional member %s', (field) => {
+ expect(createOrUpdateSpaceSchema.safeParse({ name: 'space', managers: [manager], members: [{ ...manager, [field]: 1.5 }] }).success).toBe(false)
+ })
+
+ it('preserves null ids, storage quotas and member link ids', () => {
+ const result = createOrUpdateSpaceSchema.parse({
+ name: 'space',
+ id: null,
+ storageQuota: null,
+ managers: [{ ...manager, linkId: null }]
+ })
+
+ expect(result).toMatchObject({ id: null, storageQuota: null, managers: [{ linkId: null }] })
+ })
+})
diff --git a/backend/src/applications/spaces/dto/create-or-update-space.dto.ts b/backend/src/applications/spaces/dto/create-or-update-space.dto.ts
index 610de2f5..55e83c37 100644
--- a/backend/src/applications/spaces/dto/create-or-update-space.dto.ts
+++ b/backend/src/applications/spaces/dto/create-or-update-space.dto.ts
@@ -1,112 +1,65 @@
-import { Transform, Type } from 'class-transformer'
-import { ArrayMinSize, IsArray, IsBoolean, IsInt, IsNotEmpty, IsOptional, IsString, ValidateNested } from 'class-validator'
+import { z } from 'zod'
+import { integerNumberSchema } from '../../../configuration/config.schema.js'
import { sanitizeName } from '../../files/utils/files.js'
-import { CreateOrUpdateLinkDto } from '../../links/dto/create-or-update-link.dto.js'
+import { createOrUpdateLinkSchema } from '../../links/dto/create-or-update-link.dto.js'
import { MEMBER_TYPE, MEMBER_TYPE_REVERSE } from '../../users/constants/member.js'
+import type { Member } from '../../users/interfaces/member.interface.js'
import { SPACE_ROLE } from '../constants/spaces.js'
-import { SpaceRootDto } from './space-roots.dto.js'
-
-export class SpaceMemberDto {
- @IsNotEmpty()
- @IsInt()
- id: number
-
- @IsNotEmpty()
- @IsString()
- @Transform(({ value }) => MEMBER_TYPE_REVERSE[value])
- type: MEMBER_TYPE
-
- @IsNotEmpty()
- @IsInt()
- spaceRole?: SPACE_ROLE = SPACE_ROLE.IS_MEMBER
-
- @IsOptional()
- @IsString()
- permissions?: string = ''
-
- @IsOptional()
- @IsInt()
- linkId?: number
-
- @IsOptional()
- @ValidateNested()
- @Type(() => CreateOrUpdateLinkDto)
- linkSettings?: CreateOrUpdateLinkDto = null
-}
-
-export class CreateOrUpdateSpaceDto {
- @IsOptional()
- @IsInt()
- id?: number
-
- @IsNotEmpty()
- @IsString()
- @Transform(({ value }) => (value ? sanitizeName(value.trim()) : ''))
- name: string
-
- @IsOptional()
- @IsString()
- @Transform(({ value }) => (value ? sanitizeName(value.trim()) : ''))
- alias?: string
-
- @IsOptional()
- @IsString()
- description?: string
-
- @IsOptional()
- @IsBoolean()
- enabled?: boolean
-
- @IsOptional()
- @IsInt()
- storageQuota?: number = null
-
- @IsOptional()
- @IsBoolean()
- storageIndexing?: boolean
-
- @IsOptional()
- @IsArray()
- @ValidateNested({ each: true })
- @Type(() => SpaceRootDto)
- roots?: SpaceRootDto[]
-
- @IsArray()
- @ArrayMinSize(1)
- @Transform(({ value }) =>
- value.map((m: SpaceMemberDto) => {
- m.spaceRole = SPACE_ROLE.IS_MANAGER
- return m
- })
+import { spaceRootSchema } from './space-roots.dto.js'
+
+const memberTypeSchema = z.enum(MEMBER_TYPE).overwrite((value) => MEMBER_TYPE_REVERSE[value])
+
+export const spaceMemberSchema = z.object({
+ id: integerNumberSchema,
+ type: memberTypeSchema,
+ spaceRole: z
+ .number()
+ .int()
+ .transform((value) => value as SPACE_ROLE)
+ .default(SPACE_ROLE.IS_MEMBER),
+ permissions: z.string().nullish().default(''),
+ linkId: integerNumberSchema.nullish(),
+ linkSettings: createOrUpdateLinkSchema.nullish().default(null)
+})
+
+export type SpaceMemberDto = z.infer<typeof spaceMemberSchema>
+
+export type SpaceMemberInputDto = Pick<Member, 'id' | 'type' | 'spaceRole' | 'permissions' | 'linkId' | 'linkSettings'>
+
+const sanitizedSpaceNameSchema = z.string().trim().overwrite(sanitizeName)
+const nullableSanitizedSpaceNameSchema = sanitizedSpaceNameSchema.nullable().transform((value) => value ?? '')
+
+const membersWithRoleSchema = (spaceRole: SPACE_ROLE, minimum = 0) =>
+ z.preprocess(
+ (members) =>
+ members == null ? [] : Array.isArray(members) ? members.map((member) => ({ ...(member as Record<string, unknown>), spaceRole })) : members,
+ z.array(spaceMemberSchema).min(minimum)
)
- @ValidateNested({ each: true })
- @Type(() => SpaceMemberDto)
- // contains managers (users)
- managers: SpaceMemberDto[]
- @IsOptional()
- @IsArray()
- @Transform(({ value }) =>
- value.map((m: SpaceMemberDto) => {
- m.spaceRole = SPACE_ROLE.IS_MEMBER
- return m
- })
- )
- @ValidateNested({ each: true })
- @Type(() => SpaceMemberDto)
+export const createOrUpdateSpaceSchema = z.object({
+ id: integerNumberSchema.nullish(),
+ name: sanitizedSpaceNameSchema.min(1),
+ alias: nullableSanitizedSpaceNameSchema.optional(),
+ description: z.string().nullish(),
+ enabled: z.boolean().nullish(),
+ storageQuota: integerNumberSchema.nullish().default(null),
+ storageIndexing: z.boolean().nullish(),
+ roots: z.array(spaceRootSchema).nullish(),
+ // contains managers (users)
+ managers: membersWithRoleSchema(SPACE_ROLE.IS_MANAGER, 1),
// contains members (users, guests, groups, personal groups)
- members?: SpaceMemberDto[]
-
- @IsOptional()
- @IsArray()
- @Transform(({ value }) =>
- value.map((m: SpaceMemberDto) => {
- m.spaceRole = SPACE_ROLE.IS_MEMBER
- return m
- })
- )
- @ValidateNested({ each: true })
- @Type(() => SpaceMemberDto)
+ members: membersWithRoleSchema(SPACE_ROLE.IS_MEMBER),
// contains links
- links?: SpaceMemberDto[]
+ links: membersWithRoleSchema(SPACE_ROLE.IS_MEMBER)
+})
+
+type CreateOrUpdateSpaceSchemaOutput = z.output<typeof createOrUpdateSpaceSchema>
+
+export type CreateOrUpdateSpaceDto = Omit<z.input<typeof createOrUpdateSpaceSchema>, 'alias' | 'managers' | 'members' | 'links'> & {
+ alias?: string
+ managers: SpaceMemberInputDto[]
+ members?: SpaceMemberInputDto[] | null
+ links?: SpaceMemberInputDto[] | null
}
+
+export type ValidatedCreateOrUpdateSpaceDto = CreateOrUpdateSpaceSchemaOutput & Required<Pick<CreateOrUpdateSpaceSchemaOutput, 'managers'>>
diff --git a/backend/src/applications/spaces/dto/delete-space.dto.ts b/backend/src/applications/spaces/dto/delete-space.dto.ts
index 4c7d8114..74077cf0 100644
--- a/backend/src/applications/spaces/dto/delete-space.dto.ts
+++ b/backend/src/applications/spaces/dto/delete-space.dto.ts
@@ -1,7 +1,7 @@
-import { IsBoolean, IsOptional } from 'class-validator'
+import { z } from 'zod'
-export class DeleteSpaceDto {
- @IsOptional()
- @IsBoolean()
- deleteNow: boolean
-}
+export const deleteSpaceSchema = z.object({
+ deleteNow: z.boolean().nullish()
+})
+
+export type DeleteSpaceDto = z.infer<typeof deleteSpaceSchema>
diff --git a/backend/src/applications/spaces/dto/search-space.dto.ts b/backend/src/applications/spaces/dto/search-space.dto.ts
index 96634f79..d6a5636e 100644
--- a/backend/src/applications/spaces/dto/search-space.dto.ts
+++ b/backend/src/applications/spaces/dto/search-space.dto.ts
@@ -1,16 +1,10 @@
-import { Transform } from 'class-transformer'
-import { IsBoolean, IsInt, IsOptional, IsString } from 'class-validator'
+import { z } from 'zod'
-export class SearchSpaceDto {
- @IsString()
- @Transform(({ value }) => value.trim().toLowerCase())
- search: string
+export const searchSpaceSchema = z.object({
+ search: z.string().trim().toLowerCase(),
+ limit: z.number().int().nullish().default(6),
+ shareInsidePermission: z.boolean().nullish()
+})
- @IsOptional()
- @IsInt()
- limit?: number = 6
-
- @IsOptional()
- @IsBoolean()
- shareInsidePermission?: boolean
-}
+export type SearchSpaceDto = z.input<typeof searchSpaceSchema>
+export type ValidatedSearchSpaceDto = z.output<typeof searchSpaceSchema>
diff --git a/backend/src/applications/spaces/dto/space-roots.dto.spec.ts b/backend/src/applications/spaces/dto/space-roots.dto.spec.ts
new file mode 100644
index 00000000..d614973f
--- /dev/null
+++ b/backend/src/applications/spaces/dto/space-roots.dto.spec.ts
@@ -0,0 +1,58 @@
+import { spaceRootFileSchema, spaceRootSchema } from './space-roots.dto.js'
+
+describe('spaceRootSchema', () => {
+ const largeInteger = 2 ** 53
+ const root = { id: 0, alias: 'docs', name: 'Docs', permissions: '' }
+
+ it.each(['../../foo/bar', 'files/personal/../../../foo/bar'])('normalizes the path %s with the zero file marker', (path) => {
+ expect(spaceRootFileSchema.parse({ id: 0, path })).toEqual({ id: 0, path: 'foo/bar' })
+ })
+
+ it.each([0, -largeInteger, largeInteger])('accepts the integer file id %s without a safe-integer limit', (id) => {
+ expect(spaceRootFileSchema.parse({ id, path: 'folder' })).toEqual({ id, path: 'folder' })
+ })
+
+ it('accepts a large negative inode as both the new root id and file reference', () => {
+ const input = {
+ ...root,
+ id: -largeInteger,
+ file: { id: -largeInteger, path: 'files/personal/folder//file.txt' }
+ }
+
+ expect(spaceRootSchema.parse(input)).toMatchObject({
+ id: -largeInteger,
+ file: { id: -largeInteger, path: 'folder/file.txt' }
+ })
+ })
+
+ it('accepts large persisted root, owner and file ids', () => {
+ const input = { ...root, id: largeInteger, owner: { id: largeInteger, login: 'owner' }, file: { id: largeInteger, path: 'folder' } }
+
+ expect(spaceRootSchema.parse(input)).toEqual(input)
+ })
+
+ it.each([1.5, -1.5, Infinity, -Infinity])('rejects an invalid file reference %s when file validation applies', (id) => {
+ const result = spaceRootSchema.safeParse({ ...root, file: { id, path: 'folder' } })
+
+ expect(result.success).toBe(false)
+ if (!result.success) {
+ expect(result.error.issues).toEqual(expect.arrayContaining([expect.objectContaining({ path: ['file', 'id'] })]))
+ }
+ })
+
+ it('still rejects a fractional root id', () => {
+ expect(spaceRootSchema.safeParse({ ...root, id: 1.5 }).success).toBe(false)
+ })
+
+ it('still rejects a fractional owner id', () => {
+ expect(spaceRootSchema.safeParse({ ...root, owner: { id: 1.5, login: 'owner' } }).success).toBe(false)
+ })
+
+ it.each([undefined, null, { id: null, path: null }, { id: 0, path: null }])('preserves conditional validation for hidden files', (file) => {
+ expect(spaceRootSchema.safeParse({ ...root, owner: null, file }).success).toBe(true)
+ })
+
+ it('preserves skipped file validation for external roots', () => {
+ expect(spaceRootSchema.safeParse({ ...root, externalPath: '/external', file: { id: largeInteger, path: null } }).success).toBe(true)
+ })
+})
diff --git a/backend/src/applications/spaces/dto/space-roots.dto.ts b/backend/src/applications/spaces/dto/space-roots.dto.ts
index 7a262280..63b83f6c 100644
--- a/backend/src/applications/spaces/dto/space-roots.dto.ts
+++ b/backend/src/applications/spaces/dto/space-roots.dto.ts
@@ -1,71 +1,93 @@
-import { Transform, Type } from 'class-transformer'
-import { IsDefined, IsInt, IsNotEmpty, IsNotEmptyObject, IsObject, IsOptional, IsString, ValidateIf, ValidateNested } from 'class-validator'
+import { z } from 'zod'
+import { integerNumberSchema } from '../../../configuration/config.schema.js'
import { sanitizeName, sanitizePath } from '../../files/utils/files.js'
import { SPACE_ALIAS, SPACE_REPOSITORY } from '../constants/spaces.js'
import type { SpaceRootProps } from '../models/space-root-props.model.js'
-class SpaceRootOwnerDto {
- @IsNotEmpty()
- @IsInt()
- id: number
+const spaceRootOwnerSchema = z.object({
+ id: integerNumberSchema,
+ login: z.string().min(1)
+})
- @IsNotEmpty()
- @IsString()
- login: string
-}
+type SpaceRootOwnerDto = z.infer<typeof spaceRootOwnerSchema>
-export class SpaceRootFileDto {
- @IsNotEmpty()
- @IsInt()
- id: number
+const conditionalSpaceRootOwnerSchema = z
+ .unknown()
+ .transform((owner, ctx): SpaceRootOwnerDto | null | undefined => {
+ if (owner == null || !(owner as SpaceRootOwnerDto)?.id) return owner as SpaceRootOwnerDto | null | undefined
+ const result = spaceRootOwnerSchema.safeParse(owner)
+ if (!result.success) {
+ for (const issue of result.error.issues) {
+ ctx.addIssue({ code: 'custom', input: owner, message: issue.message, path: issue.path })
+ }
+ return z.NEVER
+ }
+ return result.data
+ })
+ .optional()
- @IsNotEmpty()
- @IsString()
- @Transform(({ value }) => (value ? sanitizePath(value).replace(`${SPACE_REPOSITORY.FILES}/${SPACE_ALIAS.PERSONAL}/`, '') : ''))
- path: string
-}
+export const spaceRootFileSchema = z.object({
+ id: integerNumberSchema,
+ path: z
+ .string()
+ .overwrite((value) => sanitizePath(value).replace(`${SPACE_REPOSITORY.FILES}/${SPACE_ALIAS.PERSONAL}/`, ''))
+ .min(1)
+})
-export class SpaceRootDto implements SpaceRootProps {
- @IsNotEmpty()
- @IsInt()
- id: number
+// Conditional validation receives the path already normalized by transformSpaceRootFile.
+const normalizedSpaceRootFileSchema = spaceRootFileSchema.extend({ path: z.string().min(1) })
- @IsNotEmpty()
- @IsString()
- @Transform(({ value }) => (value ? sanitizeName(value.trim()) : ''))
- alias: string
+export type SpaceRootFileDto = z.infer<typeof spaceRootFileSchema>
- @IsNotEmpty()
- @IsString()
- @Transform(({ value }) => (value ? sanitizeName(value.trim()) : ''))
- name: string
+const sanitizedRootNameSchema = z.string().trim().overwrite(sanitizeName).min(1)
- @IsDefined()
- @IsString()
- permissions: string
+const transformSpaceRootFile = (value: unknown): unknown => {
+ if (value === null || typeof value !== 'object' || Array.isArray(value)) return value
+ const file = { ...value } as Record<string, unknown>
+ if ('path' in file) {
+ file.path =
+ typeof file.path === 'string' && file.path
+ ? sanitizePath(file.path).replace(`${SPACE_REPOSITORY.FILES}/${SPACE_ALIAS.PERSONAL}/`, '')
+ : file.path
+ ? file.path
+ : ''
+ }
+ return file
+}
- @IsOptional()
- @IsString()
- externalPath?: string
+const spaceRootBaseSchema = z.object({
+ id: integerNumberSchema,
+ alias: sanitizedRootNameSchema,
+ name: sanitizedRootNameSchema,
+ permissions: z.string(),
+ externalPath: z.string().nullish(),
+ owner: conditionalSpaceRootOwnerSchema,
+ // We intentionally defer validation: the legacy ValidateIf only validated a file
+ // when it was internal and its id was visible to the current user.
+ file: z.unknown().transform(transformSpaceRootFile).optional()
+})
- @IsOptional()
- @ValidateIf((_, owner) => !!owner?.id)
- @IsObject()
- @ValidateNested()
- @Type(() => SpaceRootOwnerDto)
- owner?: SpaceRootOwnerDto
+export const spaceRootSchema = spaceRootBaseSchema.transform((root, ctx): SpaceRootProps => {
+ const file = root.file as SpaceRootFileDto | null | undefined
+ if (!root.externalPath && file?.id) {
+ const result = normalizedSpaceRootFileSchema.safeParse(file)
+ if (!result.success) {
+ for (const issue of result.error.issues) {
+ ctx.addIssue({ code: 'custom', input: file, message: issue.message, path: ['file', ...issue.path] })
+ }
+ return z.NEVER
+ }
+ return { ...root, file: result.data } as SpaceRootProps
+ }
+ return root as SpaceRootProps
+})
- @ValidateIf((_, file) => !_.externalPath && file?.id)
- // we hide file.id & file.path if not owned by the current user
- @IsNotEmptyObject()
- @IsObject()
- @ValidateNested()
- @Type(() => SpaceRootFileDto)
- file: SpaceRootFileDto
-}
+export type SpaceRootDto = z.infer<typeof spaceRootSchema>
-export class CheckRootExternalPathDto {
- @IsNotEmpty()
- @IsString()
- path: string
-}
+export const spaceRootsSchema = z.array(spaceRootSchema)
+
+export const checkRootExternalPathSchema = z.object({
+ path: z.string().min(1)
+})
+
+export type CheckRootExternalPathDto = z.infer<typeof checkRootExternalPathSchema>
diff --git a/backend/src/applications/spaces/guards/space.guard.ts b/backend/src/applications/spaces/guards/space.guard.ts
index 4a914d90..60f03cc8 100644
--- a/backend/src/applications/spaces/guards/space.guard.ts
+++ b/backend/src/applications/spaces/guards/space.guard.ts
@@ -1,5 +1,6 @@
import { CanActivate, ExecutionContext, HttpException, HttpStatus, Injectable, Logger } from '@nestjs/common'
import { Reflector } from '@nestjs/core'
+import { toErrorMessage } from '../../../common/errors.js'
import { HTTP_METHOD } from '../../applications.constants.js'
import { FILE_ERROR } from '../../files/constants/errors.js'
import { COLLABORA_CONTEXT } from '../../files/editors/collabora-online/collabora-online.constants.js'
@@ -29,7 +30,7 @@ export class SpaceGuard implements CanActivate {
) {}
static async checkPermissions(req: FastifySpaceRequest, logger: Logger, overrideSpacePermission?: SPACE_OPERATION) {
- let permission: SPACE_OPERATION
+ let permission: SPACE_OPERATION | null
if (req.method === HTTP_METHOD.PUT && (await isPathExists(req.space.realPath)) && !(await isPathIsDir(req.space.realPath))) {
// PUT method may either create a new resource or replace an existing one.
// Therefore, we must check whether the target resource already exists to apply the appropriate permission rules.
@@ -42,7 +43,7 @@ export class SpaceGuard implements CanActivate {
logger.warn(`is not allowed to ${req.method} on this space path : *${req.space.alias}* (${req.space.id}) : ${req.space.url}`)
throw new HttpException('You are not allowed to do this action', HttpStatus.FORBIDDEN)
}
- if ([SPACE_OPERATION.ADD, SPACE_OPERATION.MODIFY].indexOf(permission) > -1) {
+ if ([SPACE_OPERATION.ADD, SPACE_OPERATION.MODIFY].indexOf(permission as SPACE_OPERATION) > -1) {
if (req.space.inTrashRepository) {
throw new HttpException('The trash is read-only', HttpStatus.FORBIDDEN)
}
@@ -65,11 +66,11 @@ export class SpaceGuard implements CanActivate {
const urlSegments = this.urlSegmentsFromContext(req, webDAVContext, syncContext, collaboraOnlineContext)
this.checkAccessToSpace(req, urlSegments)
- let space: SpaceEnv
+ let space: SpaceEnv | null
try {
space = await this.spacesManager.spaceEnv(req.user, urlSegments)
} catch (e) {
- this.logger.warn({ tag: this.canActivate.name, msg: `${e}` })
+ this.logger.warn({ tag: this.canActivate.name, msg: toErrorMessage(e) })
throw new HttpException('Space path is not valid', HttpStatus.BAD_REQUEST)
}
if (!space) {
@@ -100,8 +101,8 @@ export class SpaceGuard implements CanActivate {
}
return PATH_TO_SPACE_SEGMENTS(req.params['*'])
} catch (e) {
- this.logger.warn({ tag: this.canActivate.name, msg: `${e}` })
- throw new HttpException(e.message, HttpStatus.NOT_FOUND)
+ this.logger.warn({ tag: this.canActivate.name, msg: toErrorMessage(e) })
+ throw new HttpException(toErrorMessage(e), HttpStatus.NOT_FOUND)
}
}
diff --git a/backend/src/applications/spaces/interfaces/space-diff.interface.ts b/backend/src/applications/spaces/interfaces/space-diff.interface.ts
index 71cb945a..b32253ac 100644
--- a/backend/src/applications/spaces/interfaces/space-diff.interface.ts
+++ b/backend/src/applications/spaces/interfaces/space-diff.interface.ts
@@ -1,4 +1,16 @@
-import { SyncDiffDto } from '../../sync/dtos/sync-operations.dto.js'
+import type { ConvertedDiffUpdate } from '../../../common/functions.js'
+import type { SyncDiffDto } from '../../sync/dtos/sync-operations.dto.js'
+import type { SPACE_OPERATION } from '../constants/spaces.js'
+import type { SpaceMemberDto } from '../dto/create-or-update-space.dto.js'
+import type { SpaceMembers } from '../schemas/space-members.interface.js'
+import type { SpaceRoot } from '../schemas/space-root.interface.js'
+
+export type SpaceMemberUpdate = ConvertedDiffUpdate<SpaceMemberDto, 'permissions' | 'spaceRole'> & Partial<Pick<SpaceMembers, 'role'>>
+
+export interface SpaceRootPermissionUpdate {
+ id: SpaceRoot['id']
+ rmPermissions: SPACE_OPERATION[]
+}
export interface ParseDiffContext {
regexBasePath: RegExp
diff --git a/backend/src/applications/spaces/interfaces/space-identity.interface.ts b/backend/src/applications/spaces/interfaces/space-identity.interface.ts
new file mode 100644
index 00000000..61e7520e
--- /dev/null
+++ b/backend/src/applications/spaces/interfaces/space-identity.interface.ts
@@ -0,0 +1,3 @@
+import type { SpaceProps } from '../models/space-props.model.js'
+
+export type SpaceIdentity = Pick<SpaceProps, 'id' | 'alias' | 'name'> & Partial<Omit<SpaceProps, 'id' | 'alias' | 'name'>>
diff --git a/backend/src/applications/spaces/interfaces/space-request.interface.ts b/backend/src/applications/spaces/interfaces/space-request.interface.ts
index 841064b0..5f367859 100644
--- a/backend/src/applications/spaces/interfaces/space-request.interface.ts
+++ b/backend/src/applications/spaces/interfaces/space-request.interface.ts
@@ -2,5 +2,6 @@ import { FastifyAuthenticatedRequest } from '../../../authentication/interfaces/
import { SpaceEnv } from '../models/space-env.model.js'
export interface FastifySpaceRequest extends FastifyAuthenticatedRequest {
+ params: { '*': string } & Record<string, string | undefined>
space: SpaceEnv
}
diff --git a/backend/src/applications/spaces/models/space-env.model.ts b/backend/src/applications/spaces/models/space-env.model.ts
index 7e7f5e48..75704616 100644
--- a/backend/src/applications/spaces/models/space-env.model.ts
+++ b/backend/src/applications/spaces/models/space-env.model.ts
@@ -4,20 +4,20 @@ import { FileTaskProps } from '../../files/models/file-task.js'
import { FILE_OPERATION } from '../../files/constants/operations.js'
import { UserModel } from '../../users/models/user.model.js'
import { SPACE_ALIAS, SPACE_ALL_OPERATIONS, SPACE_OPERATION, SPACE_PERMS_SEP, SPACE_REPOSITORY, SPACE_ROLE } from '../constants/spaces.js'
-import { Space } from '../schemas/space.interface.js'
+import type { Space } from '../schemas/space.interface.js'
import { dbFileFromSpace, realPathFromSpace } from '../utils/paths.js'
import { getEnvPermissions, removePermissions } from '../utils/permissions.js'
export class SpaceEnv implements Pick<Space, 'id' | 'alias' | 'name' | 'enabled'> {
/* the space environment determines the context of access, permissions and the targeted resource */
- id: number
- alias: string
- name: string
+ id!: number
+ alias!: string
+ name!: string
enabled: boolean = true
// space or share permissions
- permissions: string
- role: SPACE_ROLE
- repository: SPACE_REPOSITORY
+ permissions!: string
+ role!: SPACE_ROLE
+ repository!: SPACE_REPOSITORY
// in share case the root is the file of the share
root?: {
// if the id equal to 0, the root is located inside the space (not in the user files)
@@ -42,16 +42,16 @@ export class SpaceEnv implements Pick<Space, 'id' | 'alias' | 'name' | 'enabled'
root?: { id: number; externalPath: string }
}
}
- paths?: string[]
+ paths!: string[]
// computed properties
- url: string
- relativeUrl: string
- realPath: string
- realBasePath: string
- dbFile: FileDBProps
+ url!: string
+ relativeUrl!: string
+ realPath!: string
+ realBasePath!: string
+ dbFile!: FileDBProps
// merged permissions from space and root
- envPermissions: string
+ envPermissions!: string
// states
inFilesRepository = false
inTrashRepository = false
@@ -59,22 +59,29 @@ export class SpaceEnv implements Pick<Space, 'id' | 'alias' | 'name' | 'enabled'
inPersonalSpace = false
inSharesList = false
// quota
- storageUsage: number
- storageQuota: number
+ storageUsage!: number
+ storageQuota!: number | null
quotaIsExceeded = false
// event
task?: { id: string; type: FILE_OPERATION; cacheKey: string; props: FileTaskProps }
- constructor(props: Partial<SpaceEnv>, rootAlias = '', mustHaveRoot = true) {
+ constructor(props: Partial<SpaceEnv>, rootAlias: string | null = '', mustHaveRoot = true) {
Object.assign(this, props)
if (mustHaveRoot && (this.root?.id === null || this.root?.id === undefined)) {
/* The root is a resource located inside the space but not anchored, this is why we set the id to 0 and the permissions are inherited */
- this.root = { id: 0, alias: rootAlias, name: rootAlias, permissions: this.permissions }
+ this.root = { id: 0, alias: rootAlias as string, name: rootAlias as string, permissions: this.permissions }
}
this.quotaIsExceeded = this.storageQuota !== null && this.storageUsage >= this.storageQuota
}
- setup(user: UserModel, repository: SPACE_REPOSITORY, rootAlias: string, paths: string[], urlSegments: string[], skipEndpointProtection = false) {
+ setup(
+ user: UserModel,
+ repository: SPACE_REPOSITORY,
+ rootAlias: string | null,
+ paths: string[],
+ urlSegments: string[],
+ skipEndpointProtection = false
+ ) {
// Ordering is important here
this.setRepository(repository)
this.setPaths(user, rootAlias, paths)
@@ -113,7 +120,7 @@ export class SpaceEnv implements Pick<Space, 'id' | 'alias' | 'name' | 'enabled'
}
}
- setPaths(user: UserModel, rootAlias: string, paths: string[]) {
+ setPaths(user: UserModel, rootAlias: string | null, paths: string[]) {
this.paths = this.inSharesRepository && rootAlias ? [rootAlias, ...paths] : paths
if (!this.inSharesList) {
// realPathFromSpace may throw a FileError exception
diff --git a/backend/src/applications/spaces/models/space-props.model.ts b/backend/src/applications/spaces/models/space-props.model.ts
index 674f01a6..4d280fc7 100644
--- a/backend/src/applications/spaces/models/space-props.model.ts
+++ b/backend/src/applications/spaces/models/space-props.model.ts
@@ -2,28 +2,28 @@ import { uniquePermissions } from '../../../common/functions.js'
import { MEMBER_TYPE } from '../../users/constants/member.js'
import { Member } from '../../users/interfaces/member.interface.js'
import { SPACE_ALL_OPERATIONS, SPACE_ROLE } from '../constants/spaces.js'
-import { Space } from '../schemas/space.interface.js'
-import { SpaceRootProps } from './space-root-props.model.js'
+import type { Space } from '../schemas/space.interface.js'
+import type { SpaceRootProps } from './space-root-props.model.js'
export class SpaceProps implements Space {
- id: number
- alias: string
- name: string
- enabled: boolean
- description: string
- storageQuota: number
- storageUsage: number
- storageIndexing: boolean
- modifiedAt: Date
- disabledAt: Date
- createdAt: Date
+ id!: Space['id']
+ alias!: Space['alias']
+ name!: Space['name']
+ enabled!: Space['enabled']
+ description!: Space['description']
+ storageQuota!: Space['storageQuota']
+ storageUsage!: Space['storageUsage']
+ storageIndexing!: Space['storageIndexing']
+ modifiedAt!: Space['modifiedAt']
+ disabledAt!: Space['disabledAt']
+ createdAt!: Space['createdAt']
// Extra properties
members: Member[] = []
- roots?: SpaceRootProps[] = []
- permissions: string
+ roots: SpaceRootProps[] = []
+ permissions!: string
role?: number
- counts?: { users: number; groups: number; links: number; roots: number; shares: number }
+ counts?: { users: number; groups: number; links: number; roots?: number; shares: number }
constructor(props: Partial<SpaceProps>, userId?: number) {
if (props?.role === SPACE_ROLE.IS_MANAGER) {
@@ -54,7 +54,7 @@ export class SpaceProps implements Space {
}
for (const r of this.roots) {
if (r.owner?.id === userId) {
- this.counts.roots++
+ this.counts.roots = (this.counts.roots ?? 0) + 1
}
}
}
diff --git a/backend/src/applications/spaces/models/space-root-props.model.ts b/backend/src/applications/spaces/models/space-root-props.model.ts
index 2acbe7c9..1002642d 100644
--- a/backend/src/applications/spaces/models/space-root-props.model.ts
+++ b/backend/src/applications/spaces/models/space-root-props.model.ts
@@ -1,14 +1,13 @@
import type { FileProps } from '../../files/interfaces/file-props.interface.js'
import type { Owner } from '../../users/interfaces/owner.interface.js'
-import type { SpaceRoot } from '../schemas/space-root.interface.js'
-export class SpaceRootProps implements Partial<SpaceRoot> {
+export interface SpaceRootProps {
id: number
alias: string
name: string
permissions: string
createdAt?: Date
- externalPath?: string
+ externalPath?: string | null
owner?: Owner | any
file: FileProps | any
}
diff --git a/backend/src/applications/spaces/models/space.model.ts b/backend/src/applications/spaces/models/space.model.ts
index b2f23994..a2252e1b 100644
--- a/backend/src/applications/spaces/models/space.model.ts
+++ b/backend/src/applications/spaces/models/space.model.ts
@@ -4,21 +4,21 @@ import { configuration } from '../../../configuration/config.environment.js'
import { TEMPORARY_PATH } from '../../files/constants/files.js'
import { isPathInside } from '../../files/utils/files.js'
import { SPACE_REPOSITORY } from '../constants/spaces.js'
-import { SpaceRoot } from '../schemas/space-root.interface.js'
-import { Space } from '../schemas/space.interface.js'
+import type { SpaceRoot } from '../schemas/space-root.interface.js'
+import type { Space } from '../schemas/space.interface.js'
export class SpaceModel implements Space {
- id: number
- alias: string
- enabled: boolean
- name: string
- description: string
- storageQuota: number
- storageUsage: number
- storageIndexing: boolean
- modifiedAt: Date
- disabledAt: Date
- createdAt: Date
+ id!: number
+ alias!: string
+ enabled!: boolean
+ name!: string
+ description!: string
+ storageQuota!: number
+ storageUsage!: number
+ storageIndexing!: boolean
+ modifiedAt!: Date
+ disabledAt!: Date
+ createdAt!: Date
// outside db schema
root: SpaceRoot[] = []
diff --git a/backend/src/applications/spaces/schemas/space-members.interface.ts b/backend/src/applications/spaces/schemas/space-members.interface.ts
index 1a29f575..69bf969e 100644
--- a/backend/src/applications/spaces/schemas/space-members.interface.ts
+++ b/backend/src/applications/spaces/schemas/space-members.interface.ts
@@ -1,15 +1,3 @@
import type { spacesMembers } from './spaces-members.schema.js'
-type SpaceMembersSchema = typeof spacesMembers.$inferSelect
-
-export class SpaceMembers implements SpaceMembersSchema {
- id: number
- role: number
- spaceId: number
- userId: number
- groupId: number
- linkId: number
- permissions: string
- createdAt: Date
- modifiedAt: Date
-}
+export type SpaceMembers = typeof spacesMembers.$inferSelect
diff --git a/backend/src/applications/spaces/schemas/space-root.interface.ts b/backend/src/applications/spaces/schemas/space-root.interface.ts
index 3705cd36..42fb45c4 100644
--- a/backend/src/applications/spaces/schemas/space-root.interface.ts
+++ b/backend/src/applications/spaces/schemas/space-root.interface.ts
@@ -2,7 +2,7 @@ import type { spacesRoots } from './spaces-roots.schema.js'
type SpaceRootSchema = typeof spacesRoots.$inferSelect
-export class SpaceRoot implements SpaceRootSchema {
+export interface SpaceRoot extends SpaceRootSchema {
id: number
alias: string
name: string
diff --git a/backend/src/applications/spaces/schemas/space.interface.ts b/backend/src/applications/spaces/schemas/space.interface.ts
index 9c5d72c1..1416defc 100644
--- a/backend/src/applications/spaces/schemas/space.interface.ts
+++ b/backend/src/applications/spaces/schemas/space.interface.ts
@@ -1,17 +1,3 @@
import type { spaces } from './spaces.schema.js'
-type SpaceSchema = typeof spaces.$inferSelect
-
-export class Space implements SpaceSchema {
- id: number
- alias: string
- name: string
- enabled: boolean
- description: string
- storageUsage: number
- storageQuota: number
- storageIndexing: boolean
- createdAt: Date
- modifiedAt: Date
- disabledAt: Date
-}
+export type Space = typeof spaces.$inferSelect
diff --git a/backend/src/applications/spaces/services/spaces-browser.service.ts b/backend/src/applications/spaces/services/spaces-browser.service.ts
index b77b04e1..838d0ed4 100644
--- a/backend/src/applications/spaces/services/spaces-browser.service.ts
+++ b/backend/src/applications/spaces/services/spaces-browser.service.ts
@@ -1,6 +1,7 @@
-import { HttpException, Injectable, Logger } from '@nestjs/common'
+import { HttpException, HttpStatus, Injectable, Logger } from '@nestjs/common'
import fs from 'node:fs/promises'
import path from 'node:path'
+import { toErrorMessage } from '../../../common/errors.js'
import { configuration } from '../../../configuration/config.environment.js'
import { FileDBProps } from '../../files/interfaces/file-db-props.interface.js'
import { FileLock } from '../../files/interfaces/file-lock.interface.js'
@@ -8,6 +9,7 @@ import { FileProps } from '../../files/interfaces/file-props.interface.js'
import { FilesLockManager } from '../../files/services/files-lock-manager.service.js'
import { FilesQueries } from '../../files/services/files-queries.service.js'
import { FilesRecents } from '../../files/services/files-recents.service.js'
+import { FileError } from '../../files/models/file-error.js'
import { dirName, fileName, getProps, isInternalTemporaryEntry } from '../../files/utils/files.js'
import { SharesQueries } from '../../shares/services/shares-queries.service.js'
import { UserModel } from '../../users/models/user.model.js'
@@ -62,12 +64,14 @@ export class SpacesBrowser {
await this.enrichWithLocks(space, spaceFiles.files)
}
// update recents files
- this.filesRecents.updateRecents(user, space, spaceFiles.files).catch((e: Error) => this.logger.error({ tag: this.browse.name, msg: `${e}` }))
+ this.filesRecents
+ .updateRecents(user, space, spaceFiles.files)
+ .catch((e: Error) => this.logger.error({ tag: this.browse.name, msg: toErrorMessage(e) }))
return spaceFiles
}
private async parseRootFiles(user: UserModel, space: SpaceEnv, details: SpaceBrowseDetails): Promise<FileProps[]> {
- if (space.inFilesRepository && space.id && !space.root.alias) {
+ if (space.inFilesRepository && space.id && !space.root!.alias) {
// list roots in the space
return Promise.all((await this.spacesQueries.spaceRootFiles(user.id, space.id, details)).map((f) => this.updateRootFile(f, details)))
} else if (space.inSharesList) {
@@ -88,8 +92,9 @@ export class SpacesBrowser {
try {
await IsRealPathIsDirAndExists(space.realPath)
} catch (e) {
- this.logger.warn({ tag: this.parseFS.name, msg: `${space.realPath} : ${e.message}` })
- throw new HttpException(e.message, e.httpCode)
+ const message = toErrorMessage(e)
+ this.logger.warn({ tag: this.parseFS.name, msg: `${space.realPath} : ${message}` })
+ throw new HttpException(message, e instanceof FileError ? e.httpCode : HttpStatus.INTERNAL_SERVER_ERROR)
}
for await (const f of this.parsePath(space)) {
fsFiles.push(f)
@@ -118,19 +123,23 @@ export class SpacesBrowser {
try {
yield await getProps(realPath, filePath, isDir)
} catch (e) {
- this.logger.warn({ tag: this.parsePath.name, msg: `unable get stats from ${realPath} : ${e}` })
+ this.logger.warn({ tag: this.parsePath.name, msg: `unable get stats from ${realPath} : ${toErrorMessage(e)}` })
}
}
} catch (e) {
- this.logger.error({ tag: this.parsePath.name, msg: `unable to parse ${space.realPath} : ${e}` })
+ this.logger.error({ tag: this.parsePath.name, msg: `unable to parse ${space.realPath} : ${toErrorMessage(e)}` })
}
}
private async updateRootFile(f: FileProps, details: SpaceBrowseDetails): Promise<FileProps> {
- const realPath = realPathFromRootFile(f)
const originalPath = f.path
- f.path = f.root.name
try {
+ const realPath = realPathFromRootFile(f)
+ const root = f.root
+ if (!realPath || !root?.name) {
+ throw new Error('Root file path not found')
+ }
+ f.path = root.name
const fileProps: FileProps = await getProps(realPath, f.path)
if (details) {
fileProps.shares = f.shares
@@ -142,7 +151,7 @@ export class SpacesBrowser {
if (details?.syncs) {
fileProps.syncs = f.syncs
}
- if (details && (f.origin || f.root?.owner)) {
+ if (details && (f.origin || root.owner)) {
// `f.origin` is used for shares
// `f.root.owner` is used for anchored files in spaces
// all other files are handled in the `enrichWithLocks` function
@@ -151,9 +160,9 @@ export class SpacesBrowser {
? { spaceId: f.origin.spaceId, ...(f.origin.spaceExternalRootId ? { spaceExternalRootId: f.origin.spaceExternalRootId } : {}) }
: f.origin?.shareExternalId
? { shareExternalId: f.origin.shareExternalId }
- : { ownerId: f.origin?.ownerId ?? f.root.owner.id }),
+ : { ownerId: f.origin?.ownerId ?? root.owner.id }),
path: originalPath,
- inTrash: f.inTrash
+ inTrash: f.inTrash ?? false
}
const locks = await this.filesLockManager.getLocksByPath(dbFile)
if (locks.length > 0) {
@@ -161,27 +170,27 @@ export class SpacesBrowser {
}
}
// `owner.id` is only used for lock details
- delete f.root.owner?.id
+ delete root.owner.id
// check `f.id`; it can be null for external roots
if (f.id) {
// todo: check if a db file referenced under external roots have an id and correctly parsed here
this.filesQueries
.compareAndUpdateFileProps(f, fileProps)
- .catch((e: Error) => this.logger.error({ tag: this.updateRootFile.name, msg: `${e}` }))
+ .catch((e: Error) => this.logger.error({ tag: this.updateRootFile.name, msg: toErrorMessage(e) }))
fileProps.id = f.id
}
fileProps.root = {
- id: f.root.id,
- alias: f.root.alias,
- description: f.root.description,
- enabled: typeof f.root.enabled === 'undefined' ? true : f.root.enabled,
- permissions: f.root.permissions,
- owner: f.root.owner
+ id: root.id,
+ alias: root.alias,
+ description: root.description,
+ enabled: root.enabled ?? true,
+ permissions: root.permissions,
+ owner: root.owner
}
return fileProps
} catch (e) {
- this.logger.error({ tag: this.updateRootFile.name, msg: `${JSON.stringify(f)} - ${e}` })
- return { ...f, name: fileName(f.path), path: dirName(f.path), ...{ root: { ...f.root, enabled: false } } }
+ this.logger.error({ tag: this.updateRootFile.name, msg: `${JSON.stringify(f)} - ${toErrorMessage(e)}` })
+ return { ...f, name: fileName(f.path), path: dirName(f.path), root: { ...f.root, enabled: false } } as FileProps
}
}
@@ -205,7 +214,7 @@ export class SpacesBrowser {
}
this.filesQueries
.compareAndUpdateFileProps(dbFile, fsFile)
- .catch((e: Error) => this.logger.error({ tag: this.updateDBFiles.name, msg: `${e}` }))
+ .catch((e: Error) => this.logger.error({ tag: this.updateDBFiles.name, msg: toErrorMessage(e) }))
} else {
this.logger.warn({ tag: this.updateDBFiles.name, msg: `missing ${dbFile.path}/${dbFile.name} (${dbFile.id}) from fs, delete it from db` })
if (details) {
@@ -226,7 +235,7 @@ export class SpacesBrowser {
}
}
}
- this.deleteDBFile(user, space, dbFile).catch((e: Error) => this.logger.error({ tag: this.updateDBFiles.name, msg: `${e}` }))
+ this.deleteDBFile(user, space, dbFile).catch((e: Error) => this.logger.error({ tag: this.updateDBFiles.name, msg: toErrorMessage(e) }))
}
}
}
@@ -234,8 +243,8 @@ export class SpacesBrowser {
private async deleteDBFile(user: UserModel, space: SpaceEnv, dbFile: FileProps) {
const spaceEnv = await this.spacesManager.spaceEnv(user, path.join(space.url, dbFile.name).split('/'))
this.filesQueries
- .deleteFiles(spaceEnv.dbFile, dbFile.isDir, true)
- .catch((e: Error) => this.logger.error({ tag: this.deleteDBFile.name, msg: `${e}` }))
+ .deleteFiles(spaceEnv!.dbFile, dbFile.isDir, true)
+ .catch((e: Error) => this.logger.error({ tag: this.deleteDBFile.name, msg: toErrorMessage(e) }))
}
private async mergeSpaceRootFiles(space: SpaceEnv, rootFiles: FileProps[], fsFiles: FileProps[], spaceFiles: SpaceFiles) {
@@ -247,38 +256,38 @@ export class SpacesBrowser {
spaceFiles.hasRoots = true
for (const f of rootFiles) {
// check root alias (must be unique in the space)
- const newAlias: string = await this.spacesManager.uniqueRootAlias(
+ const newAlias = await this.spacesManager.uniqueRootAlias(
space.id,
- f.root.alias,
+ f.root!.alias,
fsFiles.map((f) => f.name),
true,
- f.root.id
+ f.root!.id
)
if (newAlias) {
- this.logger.log({ tag: this.mergeSpaceRootFiles.name, msg: `update space root alias (${f.root.id}) : ${f.root.alias} -> ${newAlias}` })
+ this.logger.log({ tag: this.mergeSpaceRootFiles.name, msg: `update space root alias (${f.root!.id}) : ${f.root!.alias} -> ${newAlias}` })
// update in db
this.spacesQueries
- .updateRoot({ alias: newAlias }, { id: f.root.id })
- .catch((e: Error) => this.logger.error({ tag: this.mergeSpaceRootFiles.name, msg: `${e}` }))
+ .updateRoot({ alias: newAlias }, { id: f.root!.id })
+ .catch((e: Error) => this.logger.error({ tag: this.mergeSpaceRootFiles.name, msg: toErrorMessage(e) }))
// cleanup cache
this.spacesQueries
- .clearCachePermissions(space.alias, [f.root.alias, newAlias])
- .catch((e: Error) => this.logger.error({ tag: this.mergeSpaceRootFiles.name, msg: `${e}` }))
+ .clearCachePermissions(space.alias, [f.root!.alias, newAlias])
+ .catch((e: Error) => this.logger.error({ tag: this.mergeSpaceRootFiles.name, msg: toErrorMessage(e) }))
// assign
- f.root.alias = newAlias
+ f.root!.alias = newAlias
}
// check root name (must be unique in the space)
// f.name is equal to root name
- const newName: string = this.spacesManager.uniqueRootName(
+ const newName = this.spacesManager.uniqueRootName(
f.name,
fsFiles.map((f) => f.name)
)
if (newName) {
- this.logger.log({ tag: this.mergeSpaceRootFiles.name, msg: `update space root name (${f.root.id}) : ${f.name} -> ${newName}` })
+ this.logger.log({ tag: this.mergeSpaceRootFiles.name, msg: `update space root name (${f.root!.id}) : ${f.name} -> ${newName}` })
// update in db
this.spacesQueries
- .updateRoot({ name: newName }, { id: f.root.id })
- .catch((e: Error) => this.logger.error({ tag: this.mergeSpaceRootFiles.name, msg: `${e}` }))
+ .updateRoot({ name: newName }, { id: f.root!.id })
+ .catch((e: Error) => this.logger.error({ tag: this.mergeSpaceRootFiles.name, msg: toErrorMessage(e) }))
// assign
f.name = newName
}
diff --git a/backend/src/applications/spaces/services/spaces-manager.service.spec.ts b/backend/src/applications/spaces/services/spaces-manager.service.spec.ts
index 51f1f07b..dc2304aa 100644
--- a/backend/src/applications/spaces/services/spaces-manager.service.spec.ts
+++ b/backend/src/applications/spaces/services/spaces-manager.service.spec.ts
@@ -3,7 +3,6 @@ import { Test, TestingModule } from '@nestjs/testing'
import fs from 'node:fs/promises'
import os from 'node:os'
import path from 'node:path'
-import { transformAndValidate } from '../../../common/functions.js'
import { configuration } from '../../../configuration/config.environment.js'
import { Cache } from '../../../infrastructure/cache/cache.service.js'
import { DB_TOKEN_PROVIDER } from '../../../infrastructure/database/constants.js'
@@ -20,8 +19,8 @@ import { UserModel } from '../../users/models/user.model.js'
import { UsersQueries } from '../../users/services/users-queries.service.js'
import { generateUserTest } from '../../users/utils/test.js'
import { SPACE_ALIAS, SPACE_ALL_OPERATIONS, SPACE_OPERATION, SPACE_PERMS_SEP, SPACE_REPOSITORY } from '../constants/spaces.js'
-import { CreateOrUpdateSpaceDto, SpaceMemberDto } from '../dto/create-or-update-space.dto.js'
-import { SpaceRootFileDto } from '../dto/space-roots.dto.js'
+import { createOrUpdateSpaceSchema, spaceMemberSchema } from '../dto/create-or-update-space.dto.js'
+import { spaceRootFileSchema } from '../dto/space-roots.dto.js'
import { SpaceEnv } from '../models/space-env.model.js'
import { SpaceModel } from '../models/space.model.js'
import { IsRealPathIsDirAndExists } from '../utils/paths.js'
@@ -82,32 +81,32 @@ describe(SpacesManager.name, () => {
})
it('should prevent path traversal', () => {
- const createOrUpdateSpaceDto = transformAndValidate(CreateOrUpdateSpaceDto, {
+ const createOrUpdateSpaceDto = createOrUpdateSpaceSchema.parse({
name: '../../../foo/..bar',
alias: '../../bar.',
- managers: [transformAndValidate(SpaceMemberDto, { id: 0, type: MEMBER_TYPE.USER })]
- } satisfies CreateOrUpdateSpaceDto)
+ managers: [spaceMemberSchema.parse({ id: 0, type: MEMBER_TYPE.USER })]
+ })
expect(createOrUpdateSpaceDto.name).toEqual('foobar')
expect(createOrUpdateSpaceDto.alias).toEqual('bar')
- const spaceRootFileDto = transformAndValidate(SpaceRootFileDto, { id: 0, path: '../../foo/bar' } satisfies SpaceRootFileDto)
+ const spaceRootFileDto = spaceRootFileSchema.parse({ id: 0, path: '../../foo/bar' })
expect(spaceRootFileDto.path).toEqual('foo/bar')
- const spaceRootFileDto2 = transformAndValidate(SpaceRootFileDto, {
+ const spaceRootFileDto2 = spaceRootFileSchema.parse({
id: 0,
path: `${SPACE_REPOSITORY.FILES}/${SPACE_ALIAS.PERSONAL}/../../../foo/bar`
- } satisfies SpaceRootFileDto)
+ })
expect(spaceRootFileDto2.path).toEqual('foo/bar')
})
it('should validate the permissions on personal & shares space', async () => {
- const personalSpace = await spacesManager.spaceEnv(userTest, ['files', SPACE_ALIAS.PERSONAL])
+ const personalSpace = (await spacesManager.spaceEnv(userTest, ['files', SPACE_ALIAS.PERSONAL]))!
expect(personalSpace.envPermissions).toBe(
Object.values(SPACE_OPERATION)
.filter((p) => p !== SPACE_OPERATION.DELETE)
.join(SPACE_PERMS_SEP)
)
- const personalTrash = await spacesManager.spaceEnv(userTest, ['trash', SPACE_ALIAS.PERSONAL])
+ const personalTrash = (await spacesManager.spaceEnv(userTest, ['trash', SPACE_ALIAS.PERSONAL]))!
expect(personalTrash.envPermissions).toBe(SPACE_ALL_OPERATIONS)
- const sharesSpace = await spacesManager.spaceEnv(userTest, ['shares'])
+ const sharesSpace = (await spacesManager.spaceEnv(userTest, ['shares']))!
expect(sharesSpace.envPermissions).toBe('')
})
@@ -129,7 +128,7 @@ describe(SpacesManager.name, () => {
it("should validate (or not) the user's personal space (files & trash repositories)", async () => {
for (const repository of [SPACE_REPOSITORY.FILES, SPACE_REPOSITORY.TRASH]) {
- const spaceEnv = await spacesManager.spaceEnv(userTest, [repository, SPACE_ALIAS.PERSONAL, 'foo', 'bar'])
+ const spaceEnv = (await spacesManager.spaceEnv(userTest, [repository, SPACE_ALIAS.PERSONAL, 'foo', 'bar']))!
expect(spaceEnv.envPermissions).toBe(SPACE_ALL_OPERATIONS)
await expect(IsRealPathIsDirAndExists(spaceEnv.realPath)).rejects.toThrow()
const repoPath = UserModel.getRepositoryPath(userTest.login, spaceEnv.inTrashRepository)
@@ -155,12 +154,12 @@ describe(SpacesManager.name, () => {
}
spacesQueries.permissions = vi.fn().mockReturnValue(permissions)
for (const repository of [SPACE_REPOSITORY.FILES, SPACE_REPOSITORY.TRASH]) {
- const spaceEnv = await spacesManager.spaceEnv(userTest, [repository, spaceAlias, 'foo', 'bar'])
+ const spaceEnv = (await spacesManager.spaceEnv(userTest, [repository, spaceAlias, 'foo', 'bar']))!
await expect(IsRealPathIsDirAndExists(spaceEnv.realPath)).rejects.toThrow()
const repoPath = SpaceModel.getRepositoryPath(spaceAlias, spaceEnv.inTrashRepository)
- await fs.mkdir(path.join(repoPath, spaceEnv.root.alias, ...spaceEnv.paths), { recursive: true })
+ await fs.mkdir(path.join(repoPath, spaceEnv.root!.alias, ...spaceEnv.paths), { recursive: true })
await expect(IsRealPathIsDirAndExists(spaceEnv.realPath)).resolves.toBeUndefined()
- await removeFiles(path.join(repoPath, spaceEnv.root.alias, ...spaceEnv.paths))
+ await removeFiles(path.join(repoPath, spaceEnv.root!.alias, ...spaceEnv.paths))
}
})
@@ -173,7 +172,7 @@ describe(SpacesManager.name, () => {
root: { id: 1, alias: 'foo', name: 'foo', externalPath: tmpDir, permissions: SPACE_ALL_OPERATIONS }
}
spacesQueries.permissions = vi.fn().mockReturnValueOnce(permissions)
- const spaceEnv = await spacesManager.spaceEnv(userTest, [SPACE_REPOSITORY.FILES, spaceAlias, 'foo', 'bar'])
+ const spaceEnv = (await spacesManager.spaceEnv(userTest, [SPACE_REPOSITORY.FILES, spaceAlias, 'foo', 'bar']))!
const rootPath = path.join(tmpDir, ...spaceEnv.paths)
await fs.mkdir(rootPath, { recursive: true })
await expect(IsRealPathIsDirAndExists(spaceEnv.realPath)).resolves.toBeUndefined()
@@ -197,12 +196,12 @@ describe(SpacesManager.name, () => {
}
}
spacesQueries.permissions = vi.fn().mockReturnValueOnce(permissions)
- const spaceEnv = await spacesManager.spaceEnv(userTest, [SPACE_REPOSITORY.FILES, spaceAlias, 'document', 'bar'])
+ const spaceEnv = (await spacesManager.spaceEnv(userTest, [SPACE_REPOSITORY.FILES, spaceAlias, 'document', 'bar']))!
await fs.mkdir(path.join(UserModel.getFilesPath(userTest.login), 'foo', 'bar'), { recursive: true })
await expect(IsRealPathIsDirAndExists(spaceEnv.realPath)).resolves.toBeUndefined()
await removeFiles(path.join(UserModel.getFilesPath(userTest.login), 'foo', 'bar'))
await expect(IsRealPathIsDirAndExists(spaceEnv.realPath)).rejects.toThrow()
- delete spaceEnv.root.file.path
+ delete (spaceEnv.root!.file as { path?: string }).path
try {
await IsRealPathIsDirAndExists(spaceEnv.realPath)
} catch (e) {
diff --git a/backend/src/applications/spaces/services/spaces-manager.service.ts b/backend/src/applications/spaces/services/spaces-manager.service.ts
index 625f52a9..b331cae0 100644
--- a/backend/src/applications/spaces/services/spaces-manager.service.ts
+++ b/backend/src/applications/spaces/services/spaces-manager.service.ts
@@ -3,6 +3,7 @@ import { eq, isNotNull } from 'drizzle-orm'
import fs from 'node:fs/promises'
import path from 'node:path'
import { ACTION } from '../../../common/constants.js'
+import { toErrorMessage } from '../../../common/errors.js'
import { convertDiffUpdate, diffCollection, differencePermissions } from '../../../common/functions.js'
import type { Entries } from '../../../common/interfaces.js'
import { createSlug, InvalidSlugError, regExpNumberSuffix } from '../../../common/shared.js'
@@ -14,7 +15,7 @@ import { LINK_TYPE } from '../../links/constants/links.js'
import { NOTIFICATION_APP, NOTIFICATION_APP_EVENT } from '../../notifications/constants/notifications.js'
import { NotificationContent } from '../../notifications/interfaces/notification-properties.interface.js'
import { NotificationsManager } from '../../notifications/services/notifications-manager.service.js'
-import { CreateOrUpdateShareDto } from '../../shares/dto/create-or-update-share.dto.js'
+import type { ValidatedCreateOrUpdateShareDto } from '../../shares/dto/create-or-update-share.dto.js'
import type { ShareLink } from '../../shares/interfaces/share-link.interface.js'
import type { ShareProps } from '../../shares/interfaces/share-props.interface.js'
import type { ShareChild } from '../../shares/models/share-child.model.js'
@@ -34,15 +35,16 @@ import {
SPACE_ROLE,
SPACE_SHARES
} from '../constants/spaces.js'
-import { CreateOrUpdateSpaceDto, SpaceMemberDto } from '../dto/create-or-update-space.dto.js'
-import { DeleteSpaceDto } from '../dto/delete-space.dto.js'
-import { SearchSpaceDto } from '../dto/search-space.dto.js'
+import { type SpaceMemberDto, spaceMemberSchema, type ValidatedCreateOrUpdateSpaceDto } from '../dto/create-or-update-space.dto.js'
+import type { DeleteSpaceDto } from '../dto/delete-space.dto.js'
+import type { ValidatedSearchSpaceDto } from '../dto/search-space.dto.js'
+import type { SpaceRootPermissionUpdate } from '../interfaces/space-diff.interface.js'
+import type { SpaceIdentity } from '../interfaces/space-identity.interface.js'
import { SpaceTrash } from '../interfaces/space-trash.interface.js'
import { SpaceEnv } from '../models/space-env.model.js'
import { SpaceProps } from '../models/space-props.model.js'
import type { SpaceRootProps } from '../models/space-root-props.model.js'
import { SpaceModel } from '../models/space.model.js'
-import type { SpaceRoot } from '../schemas/space-root.interface.js'
import type { Space } from '../schemas/space.interface.js'
import { spaces } from '../schemas/spaces.schema.js'
import { createUniqueAlias } from '../utils/alias.js'
@@ -64,7 +66,7 @@ export class SpacesManager {
private readonly notificationsManager: NotificationsManager
) {}
- listSpaces(userId: number): Promise<Partial<SpaceProps>[]> {
+ listSpaces(userId: number): Promise<SpaceProps[]> {
return this.spacesQueries.spaces(userId)
}
@@ -92,9 +94,10 @@ export class SpacesManager {
return null
}
- async spaceEnv(user: UserModel, urlSegments: string[], skipEndpointProtection = false): Promise<SpaceEnv> {
+ async spaceEnv(user: UserModel, urlSegments: string[], skipEndpointProtection = false): Promise<SpaceEnv | null> {
/* SpaceEnv builder */
- let [repository, spaceAlias, rootAlias, ...paths] = urlSegments
+ const [repository, spaceAlias, initialRootAlias, ...paths] = urlSegments
+ let rootAlias: string | null = initialRootAlias ?? null
if (
!repository ||
@@ -104,7 +107,7 @@ export class SpacesManager {
throw new Error(`Space path is not valid : ${urlSegments}`)
}
- let space: SpaceEnv
+ let space: SpaceEnv | undefined
if (spaceAlias === SPACE_ALIAS.PERSONAL) {
/* Personal Space (static) */
if (rootAlias) {
@@ -116,7 +119,7 @@ export class SpacesManager {
} else if (repository === SPACE_REPOSITORY.SHARES) {
if (spaceAlias) {
/* Share */
- const spacePermissions: Partial<SpaceEnv> = await this.sharesManager.permissions(user, spaceAlias)
+ const spacePermissions = await this.sharesManager.permissions(user, spaceAlias)
if (spacePermissions) {
space = new SpaceEnv(spacePermissions, null, false)
}
@@ -131,7 +134,7 @@ export class SpacesManager {
paths.unshift(rootAlias)
rootAlias = null
}
- const spacePermissions: Partial<SpaceEnv> = await this.spacesQueries.permissions(user.id, spaceAlias, rootAlias)
+ const spacePermissions = await this.spacesQueries.permissions(user.id, spaceAlias, rootAlias)
if (spacePermissions) {
space = new SpaceEnv(spacePermissions, rootAlias || '')
}
@@ -142,13 +145,14 @@ export class SpacesManager {
await this.filesQuotaManager.setQuotaExceeded(user, space)
return space
} catch (e) {
- this.logger.warn({ tag: this.spaceEnv.name, msg: `*${space.alias}* : ${e}` })
- throw new HttpException(e.message, e instanceof FileError ? e.httpCode : HttpStatus.BAD_REQUEST)
+ this.logger.warn({ tag: this.spaceEnv.name, msg: `*${space.alias}* : ${toErrorMessage(e)}` })
+ throw new HttpException(toErrorMessage(e), e instanceof FileError ? e.httpCode : HttpStatus.BAD_REQUEST)
}
}
- async searchSpaces(userId: number, searchSpaceDto: SearchSpaceDto): Promise<SpaceProps[]> {
+ async searchSpaces(userId: number, searchSpaceDto: ValidatedSearchSpaceDto): Promise<SpaceProps[]> {
const sps: SpaceProps[] = []
+ const limit = searchSpaceDto.limit ?? 6
for (const s of await this.spacesQueries.spaces(userId, true)) {
if (searchSpaceDto.shareInsidePermission && !haveSpacePermission(s, SPACE_OPERATION.SHARE_INSIDE)) {
continue
@@ -156,7 +160,7 @@ export class SpacesManager {
if (!searchSpaceDto.search || `${s.name} ${s.alias} ${s.description || ''}`.toLowerCase().indexOf(searchSpaceDto.search) > -1) {
sps.push(s)
}
- if (sps.length >= searchSpaceDto.limit) {
+ if (sps.length >= limit) {
break
}
}
@@ -184,7 +188,15 @@ export class SpacesManager {
ctime: 0,
enabled: true
}
- const spaces = (await this.listSpaces(user.id)) as SpaceTrash[]
+ const spaces: SpaceTrash[] = (await this.listSpaces(user.id)).map(({ id, name, alias, enabled }) => ({
+ id,
+ name,
+ alias,
+ enabled,
+ nb: 0,
+ mtime: 0,
+ ctime: 0
+ }))
if (user.havePermission(USER_PERMISSION.PERSONAL_SPACE)) spaces.push(personalTrash)
for (const space of spaces) {
const rPath = space.alias === SPACE_ALIAS.PERSONAL ? user.trashPath : SpaceModel.getTrashPath(space.alias)
@@ -206,7 +218,7 @@ export class SpacesManager {
trashes.push(space)
}
} catch (e) {
- this.logger.error({ tag: this.listTrashes.name, msg: `${e}` })
+ this.logger.error({ tag: this.listTrashes.name, msg: toErrorMessage(e) })
}
}
return trashes
@@ -223,7 +235,7 @@ export class SpacesManager {
return space
}
- async createSpace(user: UserModel, createOrUpdateSpaceDto: CreateOrUpdateSpaceDto): Promise<SpaceProps> {
+ async createSpace(user: UserModel, createOrUpdateSpaceDto: ValidatedCreateOrUpdateSpaceDto): Promise<SpaceProps> {
/* only users with admin space role can create a space */
await this.validateManagers(createOrUpdateSpaceDto.managers)
// create space
@@ -231,43 +243,47 @@ export class SpacesManager {
name: createOrUpdateSpaceDto.name,
alias: await this.uniqueSpaceAlias(createOrUpdateSpaceDto.name, true),
description: createOrUpdateSpaceDto.description,
- enabled: createOrUpdateSpaceDto.enabled,
+ enabled: createOrUpdateSpaceDto.enabled ?? undefined,
storageQuota: createOrUpdateSpaceDto.storageQuota,
- storageIndexing: createOrUpdateSpaceDto.storageIndexing,
+ storageIndexing: createOrUpdateSpaceDto.storageIndexing ?? undefined,
disabledAt: createOrUpdateSpaceDto.enabled ? null : new Date()
})
try {
space.id = await this.spacesQueries.createSpace(space)
} catch (e) {
- this.logger.error({ tag: this.createSpace.name, msg: `unable to create space *${space.alias}* : ${e}` })
- throw new HttpException('Unable to create space', e)
+ this.logger.error({ tag: this.createSpace.name, msg: `unable to create space *${space.alias}* : ${toErrorMessage(e)}` })
+ throw new HttpException('Unable to create space', HttpStatus.INTERNAL_SERVER_ERROR)
}
// create space paths
await SpaceModel.makePaths(space.alias)
// add roots
- await this.updateRoots(user, space, space.roots, createOrUpdateSpaceDto.roots, [], [])
+ await this.updateRoots(user, space, space.roots, createOrUpdateSpaceDto.roots as SpaceRootProps[], [], [])
// add members
await this.updateMembers(user, space, createOrUpdateSpaceDto.members.concat(createOrUpdateSpaceDto.managers))
// create links after members, user must be a space manager to create links
await this.sharesManager.createOrUpdateLinksAsMembers(user, space, LINK_TYPE.SPACE, createOrUpdateSpaceDto.links)
- return this.spacesQueries.getSpaceAsAdminOrManager(user, space.id)
+ const createdSpace = await this.spacesQueries.getSpaceAsAdminOrManager(user, space.id)
+ if (!createdSpace) {
+ throw new HttpException('Unable to retrieve the created space', HttpStatus.INTERNAL_SERVER_ERROR)
+ }
+ return createdSpace
}
- async updateSpace(user: UserModel, spaceId: number, createOrUpdateSpaceDto: CreateOrUpdateSpaceDto): Promise<SpaceProps> {
+ async updateSpace(user: UserModel, spaceId: number, createOrUpdateSpaceDto: ValidatedCreateOrUpdateSpaceDto): Promise<SpaceProps | null> {
/* only managers of the space can update it */
const space: SpaceProps = await this.userCanAccessSpace(user, spaceId, true)
await this.validateManagers(createOrUpdateSpaceDto.managers)
// check and update space info
let mustInvalidateCache = false
- let renamedSpaceAlias: string
+ let renamedSpaceAlias: string | undefined
const spaceDiffProps: Partial<SpaceProps> = { modifiedAt: new Date() }
- const props: (keyof CreateOrUpdateSpaceDto)[] = ['name', 'description', 'enabled', 'storageQuota', 'storageIndexing']
+ const props = ['name', 'description', 'enabled', 'storageQuota', 'storageIndexing'] as const
for (const prop of props) {
if (createOrUpdateSpaceDto[prop] !== space[prop]) {
- spaceDiffProps[prop] = createOrUpdateSpaceDto[prop]
+ ;(spaceDiffProps as Record<string, unknown>)[prop] = createOrUpdateSpaceDto[prop]
if (prop === 'name') {
renamedSpaceAlias = space.alias
- spaceDiffProps.alias = await this.uniqueSpaceAlias(spaceDiffProps.name, true, space.id)
+ spaceDiffProps.alias = await this.uniqueSpaceAlias(spaceDiffProps.name!, true, space.id)
if (space.alias !== spaceDiffProps.alias) {
// must move the space to match the new alias
const spaceLocationWasRenamed: boolean = await this.renameSpaceLocation(space.alias, spaceDiffProps.alias)
@@ -291,7 +307,7 @@ export class SpacesManager {
}
// update quota in cache
if ('storageQuota' in spaceDiffProps) {
- void this.filesQuotaManager.updateStorageQuota(spaceId, FILE_REPOSITORY.SPACE, spaceDiffProps.storageQuota)
+ void this.filesQuotaManager.updateStorageQuota(spaceId, FILE_REPOSITORY.SPACE, spaceDiffProps.storageQuota as number | null)
}
// checks & updates members
const linkMembers: SpaceMemberDto[] = await this.sharesManager.createOrUpdateLinksAsMembers(
@@ -300,19 +316,19 @@ export class SpacesManager {
LINK_TYPE.SPACE,
createOrUpdateSpaceDto.links
)
- const rootOwnerIds: number[] = await this.updateMembers(user, space, [
+ const rootOwnerIds: number[] = (await this.updateMembers(user, space, [
...createOrUpdateSpaceDto.members,
...createOrUpdateSpaceDto.managers,
...linkMembers
- ])
+ ]))!
if (rootOwnerIds.length) {
// removes the roots of removed members or those no longer having the `share inside` permission
- createOrUpdateSpaceDto.roots = createOrUpdateSpaceDto.roots.filter((r) => rootOwnerIds.indexOf(r.owner.id) === -1)
+ createOrUpdateSpaceDto.roots = createOrUpdateSpaceDto.roots!.filter((r) => rootOwnerIds.indexOf(r.owner.id) === -1)
}
// checks & updates roots
const aliases: string[] = space.roots.map((r) => r.alias)
const names: string[] = [...(await dirListFileNames(SpaceModel.getFilesPath(space.alias))), ...space.roots.map((r) => r.name)]
- await this.updateRoots(user, space, space.roots, createOrUpdateSpaceDto.roots, aliases, names)
+ await this.updateRoots(user, space, space.roots, createOrUpdateSpaceDto.roots as SpaceRootProps[], aliases, names)
if (mustInvalidateCache) {
void this.spacesQueries.clearCachePermissions(space.alias, undefined, [user.id])
}
@@ -336,7 +352,10 @@ export class SpacesManager {
await this.deleteOrDisableSpace(space, deleteNow)
this.logger.log({ tag: this.deleteSpace.name, msg: `*${space.alias}* (${space.id}) was ${deleteNow ? 'deleted' : 'disabled'}` })
} catch (e) {
- this.logger.error({ tag: this.deleteSpace.name, msg: `*${space.alias}* (${space.id}) was not ${deleteNow ? 'deleted' : 'disabled'} : ${e}` })
+ this.logger.error({
+ tag: this.deleteSpace.name,
+ msg: `*${space.alias}* (${space.id}) was not ${deleteNow ? 'deleted' : 'disabled'} : ${toErrorMessage(e)}`
+ })
throw new HttpException('Unable to delete space', HttpStatus.INTERNAL_SERVER_ERROR)
}
}
@@ -347,7 +366,7 @@ export class SpacesManager {
}
async updateUserRoots(user: UserModel, spaceId: number, userRoots: SpaceRootProps[], addOnly: boolean = false): Promise<SpaceRootProps[]> {
- const space: Partial<SpaceProps> = await this.userCanAccessSpace(user, spaceId)
+ const space = await this.userCanAccessSpace(user, spaceId)
if (space.role !== SPACE_ROLE.IS_MANAGER && !haveSpacePermission(space, SPACE_OPERATION.SHARE_INSIDE)) {
this.logger.warn({ tag: this.updateUserRoots.name, msg: `is not allowed to share inside on this space : *${space.alias}* (${space.id})` })
throw new HttpException('You are not allowed to do this action', HttpStatus.FORBIDDEN)
@@ -369,9 +388,9 @@ export class SpacesManager {
[],
[]
)
- Object.entries(status).forEach(([action, roots]: [ACTION, SpaceRootProps[]]) =>
+ ;(Object.entries(status) as [Exclude<ACTION, ACTION.DELETE_PERMANENTLY>, SpaceRootProps[]][]).forEach(([action, roots]) =>
this.clearCachePermissionsAndOrNotify(space, action, user, null, roots).catch((e: Error) =>
- this.logger.error({ tag: this.updateUserRoots.name, msg: `${e}` })
+ this.logger.error({ tag: this.updateUserRoots.name, msg: toErrorMessage(e) })
)
)
return this.getUserRoots(user, spaceId)
@@ -382,7 +401,13 @@ export class SpacesManager {
}
}
- async uniqueRootAlias(spaceId: number, alias: string, aliasesAndNames: string[], replaceCount = false, excludedRootId?: number): Promise<string> {
+ async uniqueRootAlias(
+ spaceId: number,
+ alias: string,
+ aliasesAndNames: string[],
+ replaceCount = false,
+ excludedRootId?: number
+ ): Promise<string | null> {
/* for some webdav clients the root alias is displayed instead of the file name.
* This is why a root alias must be unique for files too */
const aliasExists = (candidate: string): boolean => {
@@ -408,57 +433,60 @@ export class SpacesManager {
/* Removes spaces that have been disabled for more than 30 days */
const props: (keyof Space)[] = ['id', 'name', 'alias', 'disabledAt']
for (const space of await this.spacesQueries.selectSpaces(props, [eq(spaces.enabled, false), isNotNull(spaces.disabledAt)])) {
- const disabled = new Date(space.disabledAt)
+ const disabled = new Date(space.disabledAt!)
disabled.setDate(disabled.getDate() + SPACE_MAX_DISABLED_DAYS)
if (new Date() > disabled) {
try {
- await this.sharesManager.deleteAllLinkMembers(space.id, LINK_TYPE.SPACE)
- await this.deleteOrDisableSpace(space, true)
+ await this.sharesManager.deleteAllLinkMembers(space.id!, LINK_TYPE.SPACE)
+ await this.deleteOrDisableSpace(space as SpaceIdentity, true)
this.logger.log({ tag: this.deleteExpiredSpaces.name, msg: `space *${space.alias}* (${space.id}) was deleted` })
} catch (e) {
- this.logger.error({ tag: this.deleteExpiredSpaces.name, msg: `space *${space.alias}* (${space.id}) was not deleted : ${e}` })
+ this.logger.error({
+ tag: this.deleteExpiredSpaces.name,
+ msg: `space *${space.alias}* (${space.id}) was not deleted : ${toErrorMessage(e)}`
+ })
}
}
}
}
async listSpaceShares(user: UserModel, spaceId: number): Promise<ShareChild[]> {
- if (await this.userIsAdminOrSpaceManager(user, spaceId)) {
- return this.sharesManager.listSpaceShares(spaceId)
- }
+ await this.userIsAdminOrSpaceManager(user, spaceId)
+ return this.sharesManager.listSpaceShares(spaceId)
}
async getSpaceShare(user: UserModel, spaceId: number, shareId: number): Promise<ShareProps> {
- if (await this.userIsAdminOrSpaceManager(user, spaceId, shareId)) {
- return this.sharesManager.getShareWithMembers(user, shareId, true)
- }
+ await this.userIsAdminOrSpaceManager(user, spaceId, shareId)
+ return this.sharesManager.getShareWithMembers(user, shareId, true)
}
- async updateSpaceShare(user: UserModel, spaceId: number, shareId: number, createOrUpdateShareDto: CreateOrUpdateShareDto): Promise<ShareProps> {
- if (await this.userIsAdminOrSpaceManager(user, spaceId, shareId)) {
- return this.sharesManager.updateShare(user, shareId, createOrUpdateShareDto, true)
- }
+ async updateSpaceShare(
+ user: UserModel,
+ spaceId: number,
+ shareId: number,
+ createOrUpdateShareDto: ValidatedCreateOrUpdateShareDto
+ ): Promise<ShareProps> {
+ await this.userIsAdminOrSpaceManager(user, spaceId, shareId)
+ return this.sharesManager.updateShare(user, shareId, createOrUpdateShareDto, true)
}
async deleteSpaceShare(user: UserModel, spaceId: number, shareId: number): Promise<void> {
- if (await this.userIsAdminOrSpaceManager(user, spaceId, shareId)) {
- return this.sharesManager.deleteShare(user, shareId, true)
- }
+ await this.userIsAdminOrSpaceManager(user, spaceId, shareId)
+ return this.sharesManager.deleteShare(user, shareId, true)
}
async getSpaceShareLink(user: UserModel, spaceId: number, shareId: number): Promise<ShareLink> {
- if (await this.userIsAdminOrSpaceManager(user, spaceId, shareId)) {
- return this.sharesManager.getShareLink(user, shareId, true)
- }
+ await this.userIsAdminOrSpaceManager(user, spaceId, shareId)
+ return this.sharesManager.getShareLink(user, shareId, true)
}
- private async updateMembers(user: UserModel, space: SpaceProps, currentMembers: SpaceMemberDto[]): Promise<number[]> {
+ private async updateMembers(user: UserModel, space: SpaceProps, currentMembers: SpaceMemberDto[]): Promise<number[] | undefined> {
if (space.members.length === 0 && currentMembers.length === 0) {
return
}
+ const previousMembers: SpaceMemberDto[] = spaceMemberSchema.array().parse(space.members)
// diff
- const [add, update, remove]: [SpaceMemberDto[], Record<string | 'object', { old: any; new: any } | SpaceMemberDto>[], SpaceMemberDto[]] =
- diffCollection(space.members, currentMembers, ['permissions', 'spaceRole'], ['id', 'type'])
+ const [add, update, remove] = diffCollection(previousMembers, currentMembers, ['permissions', 'spaceRole'], ['id', 'type'])
// check members whitelists
let toAdd: SpaceMemberDto[] = []
@@ -487,7 +515,7 @@ export class SpacesManager {
// do remove links
this.sharesManager
.deleteLinkMembers(remove.filter((m) => !!m.linkId))
- .catch((e: Error) => this.logger.error({ tag: this.updateMembers.name, msg: `${e}` }))
+ .catch((e: Error) => this.logger.error({ tag: this.updateMembers.name, msg: toErrorMessage(e) }))
// do update members
const status: Record<
Exclude<ACTION, ACTION.DELETE_PERMANENTLY>,
@@ -523,11 +551,7 @@ export class SpacesManager {
} else if (action === ACTION.UPDATE) {
// stores permissions updates and members who might own shares created from the current space
// ignore space managers (they have all permissions)
- for (const m of update as {
- object: SpaceMemberDto
- permissions?: { old: string; new: string }
- spaceRole?: { old: number; new: number }
- }[]) {
+ for (const m of update) {
if (
((m.object.type === MEMBER_TYPE.USER || m.object.type === MEMBER_TYPE.GUEST) &&
m.object.spaceRole !== SPACE_ROLE.IS_MANAGER &&
@@ -535,11 +559,11 @@ export class SpacesManager {
((m.object.type === MEMBER_TYPE.GROUP || m.object.type === MEMBER_TYPE.PGROUP) && members.groupIds.indexOf(m.object.id) > -1)
) {
// special case, the manager was moved to members without permissions change
- if (!m.permissions && m.spaceRole.new === SPACE_ROLE.IS_MEMBER) {
- m.permissions = { old: SPACE_ALL_OPERATIONS, new: m.object.permissions }
+ if (!m.permissions && m.spaceRole!.new === SPACE_ROLE.IS_MEMBER) {
+ m.permissions = { old: SPACE_ALL_OPERATIONS, new: m.object.permissions ?? '' }
}
// `share inside` permission is only used for spaces
- const diffPermissions = differencePermissions(m.permissions.old, m.permissions.new).filter((p) => p !== SPACE_OPERATION.SHARE_INSIDE)
+ const diffPermissions = differencePermissions(m.permissions!.old!, m.permissions!.new!).filter((p) => p !== SPACE_OPERATION.SHARE_INSIDE)
if (diffPermissions.length) {
upShareOwners.push({ object: m.object, rmPermissions: diffPermissions as SPACE_OPERATION[] })
}
@@ -547,13 +571,15 @@ export class SpacesManager {
}
}
// clear cache &|| notify
- this.onSpaceActionForMembers(space, action, members, user).catch((e: Error) => this.logger.error({ tag: this.updateMembers.name, msg: `${e}` }))
+ this.onSpaceActionForMembers(space, action, members, user).catch((e: Error) =>
+ this.logger.error({ tag: this.updateMembers.name, msg: toErrorMessage(e) })
+ )
}
// do updates
// remove or update potential shares
this.sharesManager
.updateSharesFromSpace(space.id, currentMembers, rmShareOwners, upShareOwners)
- .catch((e: Error) => this.logger.error({ tag: this.updateMembers.name, msg: `${e}` }))
+ .catch((e: Error) => this.logger.error({ tag: this.updateMembers.name, msg: toErrorMessage(e) }))
// return potential root owner ids
return rmRootOwners
}
@@ -570,33 +596,21 @@ export class SpacesManager {
private async updateRoots(
user: UserModel,
- space: Partial<SpaceProps>,
+ space: SpaceIdentity,
curRoots: SpaceRootProps[],
newRoots: SpaceRootProps[],
aliases: string[],
names: string[]
) {
// diff
- const [add, toUpdate, toRemove]: [
- SpaceRootProps[],
- Record<
- string | 'object',
- | {
- old: any
- new: any
- }
- | SpaceRootProps
- | any
- >[],
- SpaceRootProps[]
- ] = diffCollection(curRoots, newRoots, ['name', 'alias', 'permissions'])
+ const [add, toUpdate, toRemove] = diffCollection(curRoots, newRoots, ['name', 'alias', 'permissions'])
// update
for (const props of toUpdate) {
- const root = props.object as SpaceRootProps
- if ('alias' in props) {
+ const root = props.object
+ if (props.alias) {
const aliasesAndNames = aliases.concat(names)
- const currentName = 'name' in props ? props.name.old : root.name
+ const currentName = props.name ? props.name.old : root.name
for (const currentValue of [props.alias.old, currentName]) {
const currentValueIndex = aliasesAndNames.findIndex((aliasOrName: string) => aliasOrName.toLowerCase() === currentValue.toLowerCase())
if (currentValueIndex > -1) {
@@ -607,7 +621,7 @@ export class SpacesManager {
// remove from space cache permissions
this.spacesQueries
.clearCachePermissions(space.alias, [props.alias.old, props.alias.new])
- .catch((e: Error) => this.logger.error({ tag: this.updateRoots.name, msg: `${e}` }))
+ .catch((e: Error) => this.logger.error({ tag: this.updateRoots.name, msg: toErrorMessage(e) }))
// update aliases list for next roots
const currentAliasIndex = aliases.indexOf(props.alias.old)
if (currentAliasIndex > -1) {
@@ -616,7 +630,7 @@ export class SpacesManager {
aliases.push(props.alias.new)
}
}
- if ('name' in props) {
+ if (props.name) {
props.name.new = this.uniqueRootName(props.name.new, names) || props.name.new
// update names list for next roots
const currentNameIndex = names.lastIndexOf(props.name.old)
@@ -634,24 +648,16 @@ export class SpacesManager {
// remove a root implies that all shares with a reference to root.id will be deleted in cascade
// however, it is "cleaner" to warn users about the deletion of these shares and to clear the permission caches before the cascade deletion
// it must be assumed that the deletion and modifications of space roots will be successful
- const [rmRoots, rmRootPermissions]: [
- SpaceRoot['id'][],
- {
- id: SpaceRoot['id']
- rmPermissions: SPACE_OPERATION[]
- }[]
- ] = [
- toRemove.map((r) => r.id),
- (toUpdate as any).reduce((acc: typeof rmRootPermissions, r: any): typeof rmRootPermissions => {
- if (r.permissions !== undefined) {
- const diffPermissions = differencePermissions(r.permissions.old, r.permissions.new) as SPACE_OPERATION[]
- if (diffPermissions.length) {
- acc.push({ id: r.object.id, rmPermissions: diffPermissions })
- }
+ const rmRoots = toRemove.map((r) => r.id)
+ const rmRootPermissions = toUpdate.reduce<SpaceRootPermissionUpdate[]>((acc, r) => {
+ if (r.permissions !== undefined) {
+ const diffPermissions = differencePermissions(r.permissions.old, r.permissions.new) as SPACE_OPERATION[]
+ if (diffPermissions.length) {
+ acc.push({ id: r.object.id, rmPermissions: diffPermissions })
}
- return acc
- }, [])
- ]
+ }
+ return acc
+ }, [])
// do share updates
await this.sharesManager.updateSharesFromSpaceRoots(space.id, rmRoots, rmRootPermissions)
@@ -663,16 +669,16 @@ export class SpacesManager {
convertDiffUpdate(toUpdate),
toRemove
)
- Object.entries(status).forEach(([action, roots]: [ACTION, SpaceRootProps[]]) =>
+ ;(Object.entries(status) as [Exclude<ACTION, ACTION.DELETE_PERMANENTLY>, SpaceRootProps[]][]).forEach(([action, roots]) =>
this.clearCachePermissionsAndOrNotify(space, action, user, null, roots).catch((e: Error) =>
- this.logger.error({ tag: this.updateRoots.name, msg: `${e}` })
+ this.logger.error({ tag: this.updateRoots.name, msg: toErrorMessage(e) })
)
)
}
private async validateNewRoots(
user: UserModel,
- space: Partial<SpaceProps>,
+ space: SpaceIdentity,
curRoots: SpaceRootProps[],
newRoots: SpaceRootProps[],
aliases: string[],
@@ -693,9 +699,10 @@ export class SpacesManager {
continue
}
// check if a parent exists for an externalPath or if the file (or parent) is already anchored
- let rExists: SpaceRootProps
+ let rExists: SpaceRootProps | undefined
if (r.externalPath) {
- rExists = curRoots.find((cr) => cr.externalPath && r.externalPath.startsWith(cr.externalPath))
+ const externalPath = r.externalPath
+ rExists = curRoots.find((cr) => cr.externalPath && externalPath.startsWith(cr.externalPath))
} else {
rExists = curRoots.find(
(cr) => cr.file?.id === r.file.id || (cr.owner?.id === r.owner.id && cr.file?.path && r.file.path.startsWith(cr.file.path))
@@ -725,12 +732,12 @@ export class SpacesManager {
return toAdd
}
- private async deleteOrDisableSpace(space: Partial<SpaceProps>, deleteNow: boolean = false) {
+ private async deleteOrDisableSpace(space: SpaceIdentity, deleteNow: boolean = false) {
if (deleteNow) {
// clear cache &|| notify
const memberIds: { groupIds: number[]; userIds: number[] } = await this.spacesQueries.getSpaceMemberIds(space.id)
this.onSpaceActionForMembers(space, ACTION.DELETE_PERMANENTLY, memberIds).catch((e: Error) =>
- this.logger.error({ tag: this.deleteOrDisableSpace.name, msg: `${e}` })
+ this.logger.error({ tag: this.deleteOrDisableSpace.name, msg: toErrorMessage(e) })
)
// remove all shares related to the space
await this.sharesManager.removeSharesFromSpace(space.id)
@@ -739,7 +746,7 @@ export class SpacesManager {
if (deleteNow) {
this.spacesQueries.cache
.del(genQuotaCacheKey(space.id, FILE_REPOSITORY.SPACE))
- .catch((e: Error) => this.logger.error({ tag: this.deleteOrDisableSpace.name, msg: `${e}` }))
+ .catch((e: Error) => this.logger.error({ tag: this.deleteOrDisableSpace.name, msg: toErrorMessage(e) }))
await this.deleteSpaceLocation(space.alias)
}
}
@@ -770,7 +777,7 @@ export class SpacesManager {
await moveFiles(newSpaceLocation, currentSpaceLocation, true)
this.logger.error({
tag: this.renameSpaceLocation.name,
- msg: `unable to rename space location from *${currentSpaceLocation}* to *${newSpaceLocation}* : ${e}`
+ msg: `unable to rename space location from *${currentSpaceLocation}* to *${newSpaceLocation}* : ${toErrorMessage(e)}`
})
return false
}
@@ -799,11 +806,11 @@ export class SpacesManager {
}
private async userCanAccessSpace(user: UserModel, spaceId: number, asManager: true): Promise<SpaceProps>
- private async userCanAccessSpace(user: UserModel, spaceId: number, asManager?: false): Promise<Partial<SpaceProps>>
- private async userCanAccessSpace(user: UserModel, spaceId: number, asManager: boolean = false): Promise<Partial<SpaceProps>> {
+ private async userCanAccessSpace(user: UserModel, spaceId: number, asManager?: false): Promise<SpaceIdentity>
+ private async userCanAccessSpace(user: UserModel, spaceId: number, asManager: boolean = false): Promise<SpaceIdentity> {
if (asManager) {
// Get all space details if user is a manager
- const space: SpaceProps = await this.spacesQueries.getSpaceAsAdminOrManager(user, spaceId)
+ const space = await this.spacesQueries.getSpaceAsAdminOrManager(user, spaceId)
if (!space) {
this.logger.warn({ tag: this.userCanAccessSpace.name, msg: `space (${spaceId}) not found or not authorized for user (${user.id})` })
throw new HttpException('Unauthorized', HttpStatus.FORBIDDEN)
@@ -819,16 +826,15 @@ export class SpacesManager {
}
}
- private async userIsAdminOrSpaceManager(user: UserModel, spaceId: number, shareId?: number): Promise<boolean> {
- if (await this.spacesQueries.userIsAdminOrSpaceManager(user, spaceId, shareId)) {
- return true
+ private async userIsAdminOrSpaceManager(user: UserModel, spaceId: number, shareId?: number): Promise<void> {
+ if (!(await this.spacesQueries.userIsAdminOrSpaceManager(user, spaceId, shareId))) {
+ this.logger.warn({ tag: this.userIsAdminOrSpaceManager.name, msg: `space (${spaceId}) not found or not authorized for user (${user.id})` })
+ throw new HttpException('Unauthorized', HttpStatus.FORBIDDEN)
}
- this.logger.warn({ tag: this.userIsAdminOrSpaceManager.name, msg: `space (${spaceId}) not found or not authorized for user (${user.id})` })
- throw new HttpException('Unauthorized', HttpStatus.FORBIDDEN)
}
private async onSpaceActionForMembers(
- space: Partial<SpaceProps>,
+ space: SpaceIdentity,
action: ACTION,
members: {
groupIds: number[]
@@ -841,14 +847,14 @@ export class SpacesManager {
action,
user,
Array.from(new Set([...(await this.usersQueries.allUserIdsFromGroupsAndSubGroups(members.groupIds)), ...members.userIds]))
- ).catch((e: Error) => this.logger.error({ tag: this.onSpaceActionForMembers.name, msg: `${e}` }))
+ ).catch((e: Error) => this.logger.error({ tag: this.onSpaceActionForMembers.name, msg: toErrorMessage(e) }))
}
private async clearCachePermissionsAndOrNotify(
- space: Partial<SpaceProps>,
+ space: SpaceIdentity,
action: ACTION,
user?: UserModel,
- memberIds?: number[],
+ memberIds?: number[] | null,
roots?: SpaceRootProps[]
): Promise<void> {
if (memberIds?.length) {
@@ -857,7 +863,7 @@ export class SpacesManager {
this.logger.verbose({ tag: this.clearCachePermissionsAndOrNotify.name, msg: `space:${space.alias} ${action}` })
this.spacesQueries
.clearCachePermissions(space.alias)
- .catch((e: Error) => this.logger.error({ tag: this.clearCachePermissionsAndOrNotify.name, msg: `${e}` }))
+ .catch((e: Error) => this.logger.error({ tag: this.clearCachePermissionsAndOrNotify.name, msg: toErrorMessage(e) }))
} else {
// update space members cache
this.logger.verbose({
@@ -866,7 +872,7 @@ export class SpacesManager {
})
this.spacesQueries
.clearCachePermissions(space.alias, undefined, memberIds)
- .catch((e: Error) => this.logger.error({ tag: this.clearCachePermissionsAndOrNotify.name, msg: `${e}` }))
+ .catch((e: Error) => this.logger.error({ tag: this.clearCachePermissionsAndOrNotify.name, msg: toErrorMessage(e) }))
}
// notify
const notificationMemberIds = memberIds.filter((uid) => uid !== user?.id)
@@ -882,7 +888,7 @@ export class SpacesManager {
.create(notificationMemberIds, notification, {
action: action
})
- .catch((e: Error) => this.logger.error({ tag: this.clearCachePermissionsAndOrNotify.name, msg: `${e}` }))
+ .catch((e: Error) => this.logger.error({ tag: this.clearCachePermissionsAndOrNotify.name, msg: toErrorMessage(e) }))
}
} else if (roots?.length) {
// clear permissions for space roots
@@ -894,10 +900,13 @@ export class SpacesManager {
if (action !== ACTION.ADD) {
this.spacesQueries
.clearCachePermissions(space.alias, rootAliases)
- .catch((e: Error) => this.logger.error({ tag: this.clearCachePermissionsAndOrNotify.name, msg: `${e}` }))
+ .catch((e: Error) => this.logger.error({ tag: this.clearCachePermissionsAndOrNotify.name, msg: toErrorMessage(e) }))
}
// notify
if (action !== ACTION.UPDATE) {
+ if (action !== ACTION.ADD && action !== ACTION.DELETE) {
+ return
+ }
// notify the space members that a new root was anchored / unanchored
const spaceMembers = await this.spacesQueries.getSpaceMemberIds(space.id)
const spaceUserIds = Array.from(
@@ -915,10 +924,10 @@ export class SpacesManager {
}
this.notificationsManager
.create(spaceUserIds, notification, {
- author: user,
+ author: user!,
action: action
})
- .catch((e: Error) => this.logger.error({ tag: this.clearCachePermissionsAndOrNotify.name, msg: `${e}` }))
+ .catch((e: Error) => this.logger.error({ tag: this.clearCachePermissionsAndOrNotify.name, msg: toErrorMessage(e) }))
}
}
}
diff --git a/backend/src/applications/spaces/services/spaces-queries.service.ts b/backend/src/applications/spaces/services/spaces-queries.service.ts
index 8f0e6235..19fa70da 100644
--- a/backend/src/applications/spaces/services/spaces-queries.service.ts
+++ b/backend/src/applications/spaces/services/spaces-queries.service.ts
@@ -1,8 +1,10 @@
+import { toErrorMessage } from '../../../common/errors.js'
import { Inject, Injectable, Logger } from '@nestjs/common'
-import { and, countDistinct, eq, isNotNull, isNull, max, ne, or, SelectedFields, SQL, sql } from 'drizzle-orm'
-import { alias, union } from 'drizzle-orm/mysql-core'
+import { and, countDistinct, eq, isNotNull, isNull, max, ne, or, SQL, sql } from 'drizzle-orm'
+import { alias, type SelectedFields, union } from 'drizzle-orm/mysql-core'
import { MySql2PreparedQuery, MySqlQueryResult } from 'drizzle-orm/mysql2'
import { ACTION } from '../../../common/constants.js'
+import type { ConvertedDiffUpdate } from '../../../common/functions.js'
import { popFromObject } from '../../../common/shared.js'
import { CacheDecorator } from '../../../infrastructure/cache/cache.decorator.js'
import { Cache } from '../../../infrastructure/cache/cache.service.js'
@@ -21,7 +23,7 @@ import { fileHasCommentsSubquerySQL } from '../../comments/schemas/comments.sche
import { FileDBProps } from '../../files/interfaces/file-db-props.interface.js'
import { FileProps } from '../../files/interfaces/file-props.interface.js'
import { filesFavorites } from '../../files/schemas/files-favorites.schema.js'
-import { File } from '../../files/schemas/file.interface.js'
+import type { File } from '../../files/schemas/file.interface.js'
import { filePathSQL, files } from '../../files/schemas/files.schema.js'
import { FilesQueries } from '../../files/services/files-queries.service.js'
import { links } from '../../links/schemas/links.schema.js'
@@ -37,14 +39,15 @@ import { groups } from '../../users/schemas/groups.schema.js'
import { usersGroups } from '../../users/schemas/users-groups.schema.js'
import { userFullNameSQL, users } from '../../users/schemas/users.schema.js'
import { SPACE_ROLE } from '../constants/spaces.js'
-import { SpaceMemberDto } from '../dto/create-or-update-space.dto.js'
+import type { SpaceMemberDto } from '../dto/create-or-update-space.dto.js'
+import type { SpaceMemberUpdate } from '../interfaces/space-diff.interface.js'
import type { GetOrCreateSpaceFileOptions, SpaceBrowseDetails } from '../interfaces/space-files.interface.js'
import { SpaceEnv } from '../models/space-env.model.js'
import { SpaceProps } from '../models/space-props.model.js'
-import { SpaceRootProps } from '../models/space-root-props.model.js'
-import { SpaceMembers } from '../schemas/space-members.interface.js'
-import { SpaceRoot } from '../schemas/space-root.interface.js'
-import { Space } from '../schemas/space.interface.js'
+import type { SpaceRootProps } from '../models/space-root-props.model.js'
+import type { SpaceMembers } from '../schemas/space-members.interface.js'
+import type { SpaceRoot } from '../schemas/space-root.interface.js'
+import type { Space } from '../schemas/space.interface.js'
import { spacesMembers } from '../schemas/spaces-members.schema.js'
import { spacesRoots } from '../schemas/spaces-roots.schema.js'
import { spaceGroupConcatPermissions, spaces } from '../schemas/spaces.schema.js'
@@ -52,15 +55,15 @@ import { spaceGroupConcatPermissions, spaces } from '../schemas/spaces.schema.js
@Injectable()
export class SpacesQueries {
private readonly logger = new Logger(SpacesQueries.name)
- private spacePermissionsQuery: MySql2PreparedQuery<any> = null
- private spaceAndRootPermissionsQuery: MySql2PreparedQuery<any> = null
- private spacesWithDetailsQuery: MySql2PreparedQuery<any> = null
- private spacesQuery: MySql2PreparedQuery<any> = null
- private spaceIdentitiesQuery: MySql2PreparedQuery<any> = null
- private spaceQuery: MySql2PreparedQuery<any> = null
- private spacesWithPermissionsQuery: MySql2PreparedQuery<any> = null
- private spaceFromIdWithPermissionsQuery: MySql2PreparedQuery<any> = null
- private spaceRootFilesQuery: MySql2PreparedQuery<any> = null
+ private spacePermissionsQuery: MySql2PreparedQuery<any> | null = null
+ private spaceAndRootPermissionsQuery: MySql2PreparedQuery<any> | null = null
+ private spacesWithDetailsQuery: MySql2PreparedQuery<any> | null = null
+ private spacesQuery: MySql2PreparedQuery<any> | null = null
+ private spaceIdentitiesQuery: MySql2PreparedQuery<any> | null = null
+ private spaceQuery: MySql2PreparedQuery<any> | null = null
+ private spacesWithPermissionsQuery: MySql2PreparedQuery<any> | null = null
+ private spaceFromIdWithPermissionsQuery: MySql2PreparedQuery<any> | null = null
+ private spaceRootFilesQuery: MySql2PreparedQuery<any> | null = null
constructor(
@Inject(DB_TOKEN_PROVIDER) private readonly db: DBSchema,
@@ -68,14 +71,14 @@ export class SpacesQueries {
private readonly filesQueries: FilesQueries
) {}
- spaceExistsForAlias(alias: string, excludedSpaceId?: number): any | undefined {
+ spaceExistsForAlias(alias: string, excludedSpaceId?: number) {
return this.db.query.spaces.findFirst({
columns: { id: true },
where: excludedSpaceId === undefined ? eq(spaces.alias, alias) : and(eq(spaces.alias, alias), ne(spaces.id, excludedSpaceId))
})
}
- spaceRootExistsForAlias(spaceId: number, rootAlias: string, excludedRootId?: number): any | undefined {
+ spaceRootExistsForAlias(spaceId: number, rootAlias: string, excludedRootId?: number) {
return this.db.query.spacesRoots.findFirst({
columns: { id: true },
where:
@@ -85,15 +88,15 @@ export class SpacesQueries {
})
}
- selectSpaces(fields: Partial<keyof Space>[] = ['id', 'alias', 'name'], where: SQL[]): Promise<Partial<Space>[]> {
- const select: Record<keyof Space, any> = convertToSelect(spaces, fields)
+ selectSpaces<K extends keyof Space>(fields: readonly K[], where: SQL[]): Promise<Pick<Space, K>[]> {
+ const select = convertToSelect(spaces, fields)
return this.db
.select(select)
.from(spaces)
- .where(and(...where))
+ .where(and(...where)) as Promise<Pick<Space, K>[]>
}
- spacesQuotaPaths(spaceId?: number): Promise<(Partial<Space> & { externalPaths: string[] })[]> {
+ spacesQuotaPaths(spaceId?: number): Promise<(Pick<Space, 'id' | 'alias' | 'storageUsage' | 'storageQuota'> & { externalPaths: string[] })[]> {
return this.db
.select({
id: spaces.id,
@@ -104,7 +107,7 @@ export class SpacesQueries {
})
.from(spaces)
.leftJoin(spacesRoots, and(eq(spacesRoots.spaceId, spaces.id), isNotNull(spacesRoots.externalPath)))
- .where(and(...[...(spaceId ? [eq(spaces.id, spaceId)] : [])]))
+ .where(spaceId ? eq(spaces.id, spaceId) : undefined)
.groupBy(spaces.id)
}
@@ -126,7 +129,7 @@ export class SpacesQueries {
return !!r
}
- async getSpaceAsAdminOrManager(user: UserModel, spaceId: number): Promise<SpaceProps> {
+ async getSpaceAsAdminOrManager(user: UserModel, spaceId: number): Promise<SpaceProps | null> {
/* User must be an admin or the manager of the space */
if (!this.spaceQuery) {
const otherMembers: any = alias(spacesMembers, 'otherMembers')
@@ -187,7 +190,7 @@ export class SpacesQueries {
permissions: otherMembers.permissions,
createdAt: dateTimeUTC(otherMembers.createdAt)
})
- } satisfies SpaceProps | SelectedFields<any, any>)
+ } satisfies SelectedFields)
.from(spaces)
.leftJoin(
spacesMembers,
@@ -243,14 +246,14 @@ export class SpacesQueries {
this.logger.verbose({ tag: this.updateSpace.name, msg: `space (${id}) was updated : ${JSON.stringify(set)}` })
return true
} catch (e) {
- this.logger.error({ tag: this.updateSpace.name, msg: `space (${id}) was not updated : ${JSON.stringify(set)} : ${e}` })
+ this.logger.error({ tag: this.updateSpace.name, msg: `space (${id}) was not updated : ${JSON.stringify(set)} : ${toErrorMessage(e)}` })
return false
}
}
async spaceRootFiles(userId: number, spaceId: number, details: SpaceBrowseDetails): Promise<FileProps[]> {
if (!this.spaceRootFilesQuery) {
- const select: FileProps | SelectedFields<any, any> = {
+ const select: any = {
id: files.id,
path: filePathSQL(files),
isDir: files.isDir,
@@ -280,7 +283,7 @@ export class SpacesQueries {
})}, '[]')`.mapWith(dbParseJson),
hasComments: sql<boolean>`IF (${sql.placeholder('withDetails')}, ${fileHasCommentsSubquerySQL(files.id)}, 0)`.mapWith(Boolean),
isFavorite: isNotNull(filesFavorites.fileId).mapWith(Boolean)
- }
+ } satisfies Partial<Record<keyof FileProps, any>>
this.spaceRootFilesQuery = this.db
.select(select)
.from(spacesRoots)
@@ -349,7 +352,7 @@ export class SpacesQueries {
}
async getSpaceMemberIds(spaceId: number): Promise<{ groupIds: number[]; userIds: number[] }> {
- const members = { userIds: [], groupIds: [] }
+ const members: { userIds: number[]; groupIds: number[] } = { userIds: [], groupIds: [] }
for (const m of await this.db
.select({
userId: spacesMembers.userId,
@@ -360,7 +363,7 @@ export class SpacesQueries {
if (m.userId) {
members.userIds.push(m.userId)
} else {
- members.groupIds.push(m.groupId)
+ members.groupIds.push(m.groupId as number)
}
}
return members
@@ -369,7 +372,7 @@ export class SpacesQueries {
async updateMembers(
spaceId: number,
add: SpaceMemberDto[],
- update: Record<string | 'object', Partial<SpaceMembers> | SpaceMemberDto>[],
+ update: SpaceMemberUpdate[],
remove: SpaceMemberDto[]
): Promise<Record<Exclude<ACTION, ACTION.DELETE_PERMANENTLY>, { userIds: number[]; groupIds: number[] }>> {
// store status
@@ -393,7 +396,10 @@ export class SpacesQueries {
status[ACTION.ADD][`${m.type === MEMBER_TYPE.USER || m.type === MEMBER_TYPE.GUEST ? 'userIds' : 'groupIds'}`].push(m.id)
this.logger.debug({ tag: this.updateMembers.name, msg: `${m.type} (${m.id}) added to the space (${spaceId})` })
} catch (e) {
- this.logger.error({ tag: this.updateMembers.name, msg: `${m.type} (${m.id}) was not added to the space ${spaceId} -> : ${e}` })
+ this.logger.error({
+ tag: this.updateMembers.name,
+ msg: `${m.type} (${m.id}) was not added to the space ${spaceId} -> : ${toErrorMessage(e)}`
+ })
}
}
// update
@@ -422,7 +428,7 @@ export class SpacesQueries {
} catch (e) {
this.logger.error({
tag: this.updateMembers.name,
- msg: `${m.type} (${m.id}) was not updated on space (${spaceId}) : ${JSON.stringify(props)} : ${e}`
+ msg: `${m.type} (${m.id}) was not updated on space (${spaceId}) : ${JSON.stringify(props)} : ${toErrorMessage(e)}`
})
}
}
@@ -443,7 +449,10 @@ export class SpacesQueries {
status[ACTION.DELETE][`${m.type === MEMBER_TYPE.USER || m.type === MEMBER_TYPE.GUEST ? 'userIds' : 'groupIds'}`].push(m.id)
this.logger.debug({ tag: this.updateMembers.name, msg: `${m.type} (${m.id}) removed from space (${spaceId})` })
} catch (e) {
- this.logger.error({ tag: this.updateMembers.name, msg: `${m.type} (${m.id}) was not removed from space (${spaceId}) : ${e}` })
+ this.logger.error({
+ tag: this.updateMembers.name,
+ msg: `${m.type} (${m.id}) was not removed from space (${spaceId}) : ${toErrorMessage(e)}`
+ })
}
}
return status
@@ -453,7 +462,7 @@ export class SpacesQueries {
userId: number,
spaceId: number,
add: SpaceRootProps[],
- update: Record<string | 'object', Partial<SpaceRootProps> | SpaceRootProps>[],
+ update: ConvertedDiffUpdate<SpaceRootProps, 'name' | 'alias' | 'permissions'>[],
remove: SpaceRootProps[]
): Promise<Record<Exclude<ACTION, ACTION.DELETE_PERMANENTLY>, SpaceRootProps[]>> {
// store status
@@ -496,7 +505,7 @@ export class SpacesQueries {
@CacheDecorator()
async spaces(userId: number, withPermissions = false, fromId?: number): Promise<SpaceProps[]> {
- let pQuery: MySql2PreparedQuery<any>
+ let pQuery: MySql2PreparedQuery<any> | null
if (fromId) {
pQuery = this.spaceFromIdWithPermissionsQuery
} else if (withPermissions) {
@@ -505,7 +514,7 @@ export class SpacesQueries {
pQuery = this.spacesQuery
}
if (!pQuery) {
- const selectUnion: SpaceProps | SelectedFields<any, any> = {
+ const selectUnion = {
id: spaces.id,
alias: spaces.alias,
name: spaces.name,
@@ -514,9 +523,9 @@ export class SpacesQueries {
createdAt: spaces.createdAt,
modifiedAt: spaces.modifiedAt,
...(withPermissions && { permissions: spacesMembers.permissions, role: spacesMembers.role })
- }
+ } satisfies Partial<Record<keyof SpaceProps, any>>
const unionAlias = this.fromUserAndGroups(selectUnion)
- const select: SpaceProps | SelectedFields<any, any> = {
+ const select = {
id: unionAlias.id,
alias: unionAlias.alias,
name: unionAlias.name,
@@ -528,7 +537,7 @@ export class SpacesQueries {
permissions: spaceGroupConcatPermissions(unionAlias.permissions),
role: max(unionAlias.role)
})
- }
+ } satisfies Partial<Record<keyof SpaceProps, any>>
if (fromId) {
pQuery = this.db
.select(select)
@@ -553,7 +562,7 @@ export class SpacesQueries {
async spacesWithDetails(userId: number): Promise<SpaceProps[]> {
if (!this.spacesWithDetailsQuery) {
- const selectUnion: SpaceProps | SelectedFields<any, any> = {
+ const selectUnion = {
id: spaces.id,
alias: spaces.alias,
name: spaces.name,
@@ -564,10 +573,10 @@ export class SpacesQueries {
createdAt: spaces.createdAt,
modifiedAt: spaces.modifiedAt,
disabledAt: spaces.disabledAt
- }
+ } satisfies Partial<Record<keyof SpaceProps, any>>
const unionAlias = this.fromUserAndGroups(selectUnion)
const managers: any = alias(users, 'managers')
- const select: SpaceProps | SelectedFields<any, any> = {
+ const select = {
id: unionAlias.id,
alias: unionAlias.alias,
name: unionAlias.name,
@@ -587,35 +596,33 @@ export class SpacesQueries {
spaceRole: spacesMembers.role,
permissions: sql<string>`''`,
createdAt: dateTimeUTC(spacesMembers.createdAt)
- } satisfies Record<keyof Pick<Member, 'id' | 'name' | 'login' | 'description' | 'type' | 'permissions' | 'spaceRole' | 'createdAt'>, any>),
+ } satisfies { [K in keyof Member]: any }),
counts: {
- users: sql`COUNT(DISTINCT(CASE WHEN ${spacesMembers.userId} IS NOT NULL AND ${spacesMembers.linkId} IS NULL THEN ${spacesMembers.userId} END))`,
+ users: sql<number>`COUNT(DISTINCT(CASE WHEN ${spacesMembers.userId} IS NOT NULL AND ${spacesMembers.linkId} IS NULL THEN ${spacesMembers.userId} END))`,
groups: countDistinct(spacesMembers.groupId),
- links: sql`COUNT(DISTINCT(CASE WHEN ${spacesMembers.linkId} IS NOT NULL THEN ${spacesMembers.linkId} END))`,
+ links: sql<number>`COUNT(DISTINCT(CASE WHEN ${spacesMembers.linkId} IS NOT NULL THEN ${spacesMembers.linkId} END))`,
roots: countDistinct(files.id),
- shares: sql`COUNT(DISTINCT(CASE WHEN ${shares.id} IS NOT NULL THEN ${shares.id} END))`
+ shares: sql<number>`COUNT(DISTINCT(CASE WHEN ${shares.id} IS NOT NULL THEN ${shares.id} END))`
}
- }
+ } satisfies Partial<Record<keyof SpaceProps, any>>
this.spacesWithDetailsQuery = this.db
.select(select)
.from(unionAlias)
.leftJoin(spacesMembers, eq(spacesMembers.spaceId, unionAlias.id))
- .leftJoin(users, eq(users.id, spacesMembers.userId))
- .leftJoin(groups, eq(groups.id, spacesMembers.groupId))
.leftJoin(managers, and(eq(spacesMembers.userId, managers.id), eq(spacesMembers.role, SPACE_ROLE.IS_MANAGER)))
.leftJoin(spacesRoots, eq(spacesRoots.spaceId, unionAlias.id))
.leftJoin(files, and(eq(files.id, spacesRoots.fileId), eq(files.ownerId, sql.placeholder('userId'))))
- .leftJoin(shares, and(eq(unionAlias.role, 1), eq(shares.spaceId, unionAlias.id), isNotNull(shares.spaceId)))
+ .leftJoin(shares, and(eq(unionAlias.role, SPACE_ROLE.IS_MANAGER), eq(shares.spaceId, unionAlias.id)))
.groupBy(unionAlias.id)
.prepare()
}
const r: MySqlQueryResult = await this.spacesWithDetailsQuery.execute({ userId })
- return r.length ? r.map((s: Partial<SpaceProps>) => new SpaceProps(s)) : []
+ return r.map((s: Partial<SpaceProps>) => new SpaceProps(s))
}
async spacesAsAdmin(): Promise<SpaceProps[]> {
const managers: any = alias(users, 'managers')
- const select: SpaceProps | SelectedFields<any, any> = {
+ const select = {
id: spaces.id,
alias: spaces.alias,
name: spaces.name,
@@ -635,33 +642,27 @@ export class SpacesQueries {
spaceRole: spacesMembers.role,
permissions: sql<string>`''`,
createdAt: dateTimeUTC(spacesMembers.createdAt)
- } satisfies Record<keyof Pick<Member, 'id' | 'name' | 'login' | 'description' | 'type' | 'permissions' | 'spaceRole' | 'createdAt'>, any>),
+ } satisfies { [K in keyof Member]: any }),
counts: {
- users: sql`COUNT(DISTINCT(CASE WHEN ${spacesMembers.userId} IS NOT NULL AND ${spacesMembers.linkId} IS NULL THEN ${spacesMembers.userId} END))`,
+ users: sql<number>`COUNT(DISTINCT(CASE WHEN ${spacesMembers.userId} IS NOT NULL AND ${spacesMembers.linkId} IS NULL THEN ${spacesMembers.userId} END))`,
groups: countDistinct(spacesMembers.groupId),
- links: sql`COUNT(DISTINCT(CASE WHEN ${spacesMembers.linkId} IS NOT NULL THEN ${spacesMembers.linkId} END))`,
- shares: sql`COUNT(DISTINCT(CASE WHEN ${shares.id} IS NOT NULL THEN ${shares.id} END))`
+ links: sql<number>`COUNT(DISTINCT(CASE WHEN ${spacesMembers.linkId} IS NOT NULL THEN ${spacesMembers.linkId} END))`,
+ shares: sql<number>`COUNT(DISTINCT(CASE WHEN ${shares.id} IS NOT NULL THEN ${shares.id} END))`
}
- }
+ } satisfies Partial<Record<keyof SpaceProps, any>>
const r = await this.db
.select(select)
.from(spaces)
.leftJoin(spacesMembers, eq(spacesMembers.spaceId, spaces.id))
- .leftJoin(users, eq(users.id, spacesMembers.userId))
- .leftJoin(groups, eq(groups.id, spacesMembers.groupId))
.leftJoin(managers, and(eq(spacesMembers.userId, managers.id), eq(spacesMembers.role, SPACE_ROLE.IS_MANAGER)))
- .leftJoin(spacesRoots, eq(spacesRoots.spaceId, spaces.id))
- .leftJoin(shares, and(eq(shares.spaceId, spaces.id), isNotNull(shares.spaceId)))
+ .leftJoin(shares, eq(shares.spaceId, spaces.id))
.groupBy(spaces.id)
- return r.length ? r.map((s: Partial<SpaceProps>) => new SpaceProps(s)) : []
+ return r.map((s) => new SpaceProps(s as Partial<SpaceProps>))
}
@CacheDecorator()
- async permissions(userId: number, spaceAlias: string, rootAlias: string): Promise<Partial<SpaceEnv>> {
- if (rootAlias) {
- return await this.spaceAndRootPermissions(userId, spaceAlias, rootAlias)
- }
- return await this.spacePermissions(userId, spaceAlias)
+ permissions(userId: number, spaceAlias: string, rootAlias: string | null): Promise<Partial<SpaceEnv> | null> {
+ return rootAlias ? this.spaceAndRootPermissions(userId, spaceAlias, rootAlias) : this.spacePermissions(userId, spaceAlias)
}
async addRoot(userId: number, spaceId: number, root: SpaceRootProps): Promise<boolean> {
@@ -676,7 +677,10 @@ export class SpacesQueries {
this.logger.debug({ tag: this.addRoot.name, msg: `*${root.alias}* (${root.id}) added` })
return true
} catch (e) {
- this.logger.error({ tag: this.addRoot.name, msg: `*${root.alias}* (${root.id}) was not added : ${JSON.stringify(root)} : ${e}` })
+ this.logger.error({
+ tag: this.addRoot.name,
+ msg: `*${root.alias}* (${root.id}) was not added : ${JSON.stringify(root)} : ${toErrorMessage(e)}`
+ })
return false
}
}
@@ -695,12 +699,15 @@ export class SpacesQueries {
this.logger.debug({ tag: this.updateRoot.name, msg: `${JSON.stringify(filters)} was updated : ${JSON.stringify(set)}` })
return true
} catch (e) {
- this.logger.error({ tag: this.updateRoot.name, msg: `${JSON.stringify(filters)} was not updated : ${JSON.stringify(set)} : ${e}` })
+ this.logger.error({
+ tag: this.updateRoot.name,
+ msg: `${JSON.stringify(filters)} was not updated : ${JSON.stringify(set)} : ${toErrorMessage(e)}`
+ })
return false
}
}
- getUserFile(userId: number, fileId: number): Promise<Pick<File, 'id' | 'path'>> {
+ getUserFile(userId: number, fileId: number): Promise<Pick<File, 'id' | 'path'> | null> {
return this.filesQueries.getUserFile(userId, fileId)
}
@@ -724,8 +731,8 @@ export class SpacesQueries {
// clear cache on accessible space identities
patterns.push(this.cache.genSlugKey(this.constructor.name, this.spaceIdentities.name, uid))
// clear cache on spaces list
- patterns.push(this.cache.genSlugKey(...[this.constructor.name, this.spaces.name, uid]))
- patterns.push(this.cache.genSlugKey(...[this.constructor.name, this.spaces.name, uid, '*']))
+ patterns.push(this.cache.genSlugKey(this.constructor.name, this.spaces.name, uid))
+ patterns.push(this.cache.genSlugKey(this.constructor.name, this.spaces.name, uid, '*'))
// clear cache on spaces and roots
patterns.push(this.cache.genSlugKey(...basePattern), this.cache.genSlugKey(...basePattern, '*'))
}
@@ -733,7 +740,7 @@ export class SpacesQueries {
const keys = await this.cache.keys(p)
if (keys.length) {
this.logger.verbose({ tag: this.clearCachePermissions.name, msg: `${JSON.stringify(keys)}` })
- this.cache.mdel(keys).catch((e: Error) => this.logger.error({ tag: this.clearCachePermissions.name, msg: `${e}` }))
+ this.cache.mdel(keys).catch((e: Error) => this.logger.error({ tag: this.clearCachePermissions.name, msg: toErrorMessage(e) }))
}
}
}
@@ -745,31 +752,31 @@ export class SpacesQueries {
this.logger.debug({ tag: this.removeRoot.name, msg: `root (${id}) removed` })
return true
} catch (e) {
- this.logger.error({ tag: this.removeRoot.name, msg: `root (${id}) was not deleted : ${e}` })
+ this.logger.error({ tag: this.removeRoot.name, msg: `root (${id}) was not deleted : ${toErrorMessage(e)}` })
return false
}
}
- private async spacePermissions(userId: number, spaceAlias: string): Promise<Partial<SpaceEnv>> {
+ private async spacePermissions(userId: number, spaceAlias: string): Promise<Partial<SpaceEnv> | null> {
if (!this.spacePermissionsQuery) {
- const selectUnion: SpaceEnv | SelectedFields<any, any> = {
+ const selectUnion = {
id: spaces.id,
alias: spaces.alias,
name: spaces.name,
enabled: spaces.enabled,
permissions: spacesMembers.permissions,
role: spacesMembers.role
- }
+ } satisfies Partial<Record<keyof SpaceEnv, any>>
const filters: SQL[] = [eq(spaces.alias, sql.placeholder('spaceAlias'))]
const unionAlias = this.fromUserAndGroups(selectUnion, filters)
- const select: SpaceEnv | SelectedFields<any, any> = {
+ const select = {
id: unionAlias.id,
alias: unionAlias.alias,
name: unionAlias.name,
enabled: unionAlias.enabled,
permissions: spaceGroupConcatPermissions(unionAlias.permissions),
role: max(unionAlias.role)
- }
+ } satisfies Partial<Record<keyof SpaceEnv, any>>
this.spacePermissionsQuery = this.db.select(select).from(unionAlias).groupBy(unionAlias.id).limit(1).prepare()
}
// `userId` is used in `fromUserAndGroups` function
@@ -777,9 +784,9 @@ export class SpacesQueries {
return r.length ? r.at(0) : null
}
- private async spaceAndRootPermissions(userId: number, spaceAlias: string, rootAlias: string): Promise<Partial<SpaceEnv>> {
+ private async spaceAndRootPermissions(userId: number, spaceAlias: string, rootAlias: string): Promise<Partial<SpaceEnv> | null> {
if (!this.spaceAndRootPermissionsQuery) {
- const selectUnion: SpaceEnv | SelectedFields<any, any> = {
+ const selectUnion = {
id: spaces.id,
alias: spaces.alias,
name: spaces.name,
@@ -796,7 +803,7 @@ export class SpacesQueries {
rootFilePath: filePathSQL(files).as('rootFilePath'),
rootFileInTrash: files.inTrash,
rootExternalPath: spacesRoots.externalPath
- }
+ } satisfies SelectedFields
const filters: SQL[] = [eq(spaces.alias, sql.placeholder('spaceAlias'))]
const fromUser = this.fromUserQuery(selectUnion, filters).$dynamic()
const fromGroups = this.fromGroupsQuery(selectUnion, filters).$dynamic()
@@ -806,7 +813,7 @@ export class SpacesQueries {
.leftJoin(users, eq(users.id, files.ownerId))
}
const unionAlias = union(fromUser, fromGroups).as('union_alias')
- const select: SpaceEnv | SelectedFields<any, any> = {
+ const select: any = {
id: unionAlias.id,
alias: unionAlias.alias,
name: unionAlias.name,
@@ -822,7 +829,7 @@ export class SpacesQueries {
file: { id: unionAlias.rootFileId, path: unionAlias.rootFilePath, inTrash: unionAlias.rootFileInTrash },
externalPath: unionAlias.rootExternalPath
}
- }
+ } satisfies Partial<Record<keyof SpaceEnv, any>>
this.spaceAndRootPermissionsQuery = this.db.select(select).from(unionAlias).groupBy(unionAlias.id).limit(1).prepare()
}
// `userId` is used in `fromUserQuery` and `fromGroupsQuery` function
@@ -830,11 +837,11 @@ export class SpacesQueries {
return r.length ? r.at(0) : null
}
- private fromUserAndGroups(select: SelectedFields<any, any>, filters: SQL[] = []) {
+ private fromUserAndGroups(select: Record<string, any>, filters: SQL[] = []) {
return union(this.fromUserQuery(select, filters), this.fromGroupsQuery(select, filters)).as('union_alias')
}
- private fromUserQuery(select: SelectedFields<any, any>, filters: SQL[] = []) {
+ private fromUserQuery(select: Record<string, any>, filters: SQL[] = []) {
const where = [eq(spacesMembers.userId, sql.placeholder('userId')), ...filters]
return this.db
.select(select)
@@ -843,7 +850,7 @@ export class SpacesQueries {
.where(and(...where))
}
- private fromGroupsQuery(select: SelectedFields<any, any>, filters: SQL[] = []) {
+ private fromGroupsQuery(select: Record<string, any>, filters: SQL[] = []) {
const where = [eq(spacesMembers.groupId, usersGroups.groupId), ...filters]
return this.db
.select(select)
diff --git a/backend/src/applications/spaces/services/spaces-scheduler.service.ts b/backend/src/applications/spaces/services/spaces-scheduler.service.ts
index 3a238007..259d9cd7 100644
--- a/backend/src/applications/spaces/services/spaces-scheduler.service.ts
+++ b/backend/src/applications/spaces/services/spaces-scheduler.service.ts
@@ -1,3 +1,4 @@
+import { toErrorMessage } from '../../../common/errors.js'
import { Injectable, Logger } from '@nestjs/common'
import { Cron, CronExpression } from '@nestjs/schedule'
import { SpacesManager } from './spaces-manager.service.js'
@@ -15,7 +16,7 @@ export class SpacesScheduler {
try {
await this.spacesManager.deleteExpiredSpaces()
} catch (e) {
- this.logger.error({ tag: this.deleteExpiredSpaces.name, msg: `${e}` })
+ this.logger.error({ tag: this.deleteExpiredSpaces.name, msg: toErrorMessage(e) })
}
this.logger.log({ tag: this.deleteExpiredSpaces.name, msg: `DONE` })
}
diff --git a/backend/src/applications/spaces/spaces.controller.ts b/backend/src/applications/spaces/spaces.controller.ts
index 2142371b..cccb33b2 100644
--- a/backend/src/applications/spaces/spaces.controller.ts
+++ b/backend/src/applications/spaces/spaces.controller.ts
@@ -1,28 +1,13 @@
-import {
- Body,
- Controller,
- DefaultValuePipe,
- Delete,
- Get,
- HttpException,
- HttpStatus,
- Param,
- ParseArrayPipe,
- ParseBoolPipe,
- ParseIntPipe,
- Post,
- Put,
- Query,
- Search,
- UseGuards
-} from '@nestjs/common'
+import { Body, Controller, Delete, Get, HttpException, HttpStatus, Param, Post, Put, Query, Search, UseGuards } from '@nestjs/common'
+import { toErrorMessage } from '../../common/errors.js'
+import { integerFromStringSchema } from '../../configuration/config.schema.js'
import { FileTree } from '../files/interfaces/file-tree.interface.js'
import { FileError } from '../files/models/file-error.js'
import { checkExternalPath } from '../files/utils/files.js'
import { convertToFilesTree, convertToSpacesTree } from '../files/utils/files-tree.js'
-import { CreateOrUpdateShareDto } from '../shares/dto/create-or-update-share.dto.js'
+import { createOrUpdateShareSchema, type ValidatedCreateOrUpdateShareDto } from '../shares/dto/create-or-update-share.dto.js'
import { ShareLink } from '../shares/interfaces/share-link.interface.js'
-import { ShareProps } from '../shares/interfaces/share-props.interface.js'
+import type { ShareProps } from '../shares/interfaces/share-props.interface.js'
import { ShareChild } from '../shares/models/share-child.model.js'
import { USER_PERMISSION, USER_ROLE } from '../users/constants/user.js'
import { UserHavePermission } from '../users/decorators/permissions.decorator.js'
@@ -33,10 +18,10 @@ import { UserRolesGuard } from '../users/guards/roles.guard.js'
import { UserModel } from '../users/models/user.model.js'
import { SPACES_BASE_ROUTE, SPACES_ROUTE } from './constants/routes.js'
import { GetSpace } from './decorators/space.decorator.js'
-import { CreateOrUpdateSpaceDto } from './dto/create-or-update-space.dto.js'
-import { DeleteSpaceDto } from './dto/delete-space.dto.js'
-import { SearchSpaceDto } from './dto/search-space.dto.js'
-import { CheckRootExternalPathDto, SpaceRootDto } from './dto/space-roots.dto.js'
+import { createOrUpdateSpaceSchema, type ValidatedCreateOrUpdateSpaceDto } from './dto/create-or-update-space.dto.js'
+import type { DeleteSpaceDto } from './dto/delete-space.dto.js'
+import { searchSpaceSchema, type ValidatedSearchSpaceDto } from './dto/search-space.dto.js'
+import { type CheckRootExternalPathDto, checkRootExternalPathSchema, type SpaceRootDto, spaceRootsSchema } from './dto/space-roots.dto.js'
import { SpaceGuard } from './guards/space.guard.js'
import { SpaceFiles } from './interfaces/space-files.interface.js'
import { SpaceTrash } from './interfaces/space-trash.interface.js'
@@ -44,6 +29,7 @@ import { SpaceEnv } from './models/space-env.model.js'
import { SpaceProps } from './models/space-props.model.js'
import { SpacesBrowser } from './services/spaces-browser.service.js'
import { SpacesManager } from './services/spaces-manager.service.js'
+import { optionalDeleteSpaceBodySchema, showFilesQuerySchema } from './spaces.schema.js'
@Controller(SPACES_ROUTE.BASE)
@UserHaveRole(USER_ROLE.USER)
@@ -77,7 +63,7 @@ export class SpacesController {
async treeFiles(
@GetUser() user: UserModel,
@GetSpace() space: SpaceEnv,
- @Query('showFiles', new DefaultValuePipe(false), ParseBoolPipe) showFiles?: boolean
+ @Query('showFiles', { schema: showFilesQuerySchema }) showFiles = false
): Promise<FileTree[]> {
const spaceFiles = await this.spacesBrowser.browse(user, space)
return convertToFilesTree(space, spaceFiles.files, !showFiles)
@@ -104,18 +90,21 @@ export class SpacesController {
/* MANAGE SPACES */
@Search()
- searchSpaces(@GetUser() user: UserModel, @Body() searchSpaceDto: SearchSpaceDto): Promise<SpaceProps[]> {
+ searchSpaces(@GetUser() user: UserModel, @Body({ schema: searchSpaceSchema }) searchSpaceDto: ValidatedSearchSpaceDto): Promise<SpaceProps[]> {
return this.spacesManager.searchSpaces(user.id, searchSpaceDto)
}
@Get(':id')
- getSpace(@GetUser() user: UserModel, @Param('id', ParseIntPipe) spaceId: number): Promise<SpaceProps> {
+ getSpace(@GetUser() user: UserModel, @Param('id', { schema: integerFromStringSchema }) spaceId: number): Promise<SpaceProps> {
return this.spacesManager.getSpace(user, spaceId)
}
@Post()
@UserHavePermission(USER_PERMISSION.SPACES_ADMIN)
- createSpace(@GetUser() user: UserModel, @Body() createOrUpdateSpaceDto: CreateOrUpdateSpaceDto): Promise<SpaceProps> {
+ createSpace(
+ @GetUser() user: UserModel,
+ @Body({ schema: createOrUpdateSpaceSchema }) createOrUpdateSpaceDto: ValidatedCreateOrUpdateSpaceDto
+ ): Promise<SpaceProps> {
return this.spacesManager.createSpace(user, createOrUpdateSpaceDto)
}
@@ -123,30 +112,34 @@ export class SpacesController {
// can be used by space managers
updateSpace(
@GetUser() user: UserModel,
- @Param('id', ParseIntPipe) spaceId: number,
- @Body() createOrUpdateSpaceDto: CreateOrUpdateSpaceDto
- ): Promise<SpaceProps> {
+ @Param('id', { schema: integerFromStringSchema }) spaceId: number,
+ @Body({ schema: createOrUpdateSpaceSchema }) createOrUpdateSpaceDto: ValidatedCreateOrUpdateSpaceDto
+ ): Promise<SpaceProps | null> {
return this.spacesManager.updateSpace(user, spaceId, createOrUpdateSpaceDto)
}
@Delete(':id')
// can be used by space managers
- deleteSpace(@GetUser() user: UserModel, @Param('id', ParseIntPipe) spaceId: number, @Body() deleteSpaceDto?: DeleteSpaceDto) {
+ deleteSpace(
+ @GetUser() user: UserModel,
+ @Param('id', { schema: integerFromStringSchema }) spaceId: number,
+ @Body({ schema: optionalDeleteSpaceBodySchema }) deleteSpaceDto?: DeleteSpaceDto
+ ) {
return this.spacesManager.deleteSpace(user, spaceId, deleteSpaceDto)
}
/* MANAGE SPACE ROOTS */
@Get(`:id/${SPACES_ROUTE.ROOTS}`)
- getUserRoots(@GetUser() user: UserModel, @Param('id', ParseIntPipe) spaceId: number): Promise<SpaceRootDto[]> {
+ getUserRoots(@GetUser() user: UserModel, @Param('id', { schema: integerFromStringSchema }) spaceId: number): Promise<SpaceRootDto[]> {
return this.spacesManager.getUserRoots(user, spaceId)
}
@Post(`:id/${SPACES_ROUTE.ROOTS}`)
createUserRoots(
@GetUser() user: UserModel,
- @Param('id', ParseIntPipe) spaceId: number,
- @Body(new ParseArrayPipe({ items: SpaceRootDto, whitelist: true })) roots: SpaceRootDto[]
+ @Param('id', { schema: integerFromStringSchema }) spaceId: number,
+ @Body({ schema: spaceRootsSchema }) roots: SpaceRootDto[]
): Promise<SpaceRootDto[]> {
return this.spacesManager.updateUserRoots(user, spaceId, roots, true)
}
@@ -154,8 +147,8 @@ export class SpacesController {
@Put(`:id/${SPACES_ROUTE.ROOTS}`)
updateUserRoots(
@GetUser() user: UserModel,
- @Param('id', ParseIntPipe) spaceId: number,
- @Body(new ParseArrayPipe({ items: SpaceRootDto, whitelist: true })) roots: SpaceRootDto[]
+ @Param('id', { schema: integerFromStringSchema }) spaceId: number,
+ @Body({ schema: spaceRootsSchema }) roots: SpaceRootDto[]
): Promise<SpaceRootDto[]> {
return this.spacesManager.updateUserRoots(user, spaceId, roots)
}
@@ -164,31 +157,27 @@ export class SpacesController {
@Post(SPACES_ROUTE.ROOT_CHECK)
@UserHavePermission(USER_PERMISSION.SPACES_ADMIN)
@UserHaveRole(USER_ROLE.ADMINISTRATOR)
- async checkRootExternalPath(@Body() checkRootExternalPathDto: CheckRootExternalPathDto) {
+ async checkRootExternalPath(@Body({ schema: checkRootExternalPathSchema }) checkRootExternalPathDto: CheckRootExternalPathDto) {
/* reserved to admins */
try {
await checkExternalPath(checkRootExternalPathDto.path)
- } catch (e: any) {
- if (e instanceof FileError) {
- throw new HttpException(e.message, e.httpCode)
- } else {
- throw new HttpException(e.message, HttpStatus.INTERNAL_SERVER_ERROR)
- }
+ } catch (e) {
+ throw new HttpException(toErrorMessage(e), e instanceof FileError ? e.httpCode : HttpStatus.INTERNAL_SERVER_ERROR)
}
}
/* MANAGE SPACE SHARES */
@Get(`:id/${SPACES_ROUTE.SHARES}`)
- listSpaceShares(@GetUser() user: UserModel, @Param('id', ParseIntPipe) spaceId: number): Promise<ShareChild[]> {
+ listSpaceShares(@GetUser() user: UserModel, @Param('id', { schema: integerFromStringSchema }) spaceId: number): Promise<ShareChild[]> {
return this.spacesManager.listSpaceShares(user, spaceId)
}
@Get(`:id/${SPACES_ROUTE.SHARES}/:sid`)
getSpaceShare(
@GetUser() user: UserModel,
- @Param('id', ParseIntPipe) spaceId: number,
- @Param('sid', ParseIntPipe) shareId: number
+ @Param('id', { schema: integerFromStringSchema }) spaceId: number,
+ @Param('sid', { schema: integerFromStringSchema }) shareId: number
): Promise<ShareProps> {
return this.spacesManager.getSpaceShare(user, spaceId, shareId)
}
@@ -196,9 +185,9 @@ export class SpacesController {
@Put(`:id/${SPACES_ROUTE.SHARES}/:sid`)
updateSpaceShare(
@GetUser() user: UserModel,
- @Param('id', ParseIntPipe) spaceId: number,
- @Param('sid', ParseIntPipe) shareId: number,
- @Body() createOrUpdateShareDto: CreateOrUpdateShareDto
+ @Param('id', { schema: integerFromStringSchema }) spaceId: number,
+ @Param('sid', { schema: integerFromStringSchema }) shareId: number,
+ @Body({ schema: createOrUpdateShareSchema }) createOrUpdateShareDto: ValidatedCreateOrUpdateShareDto
): Promise<ShareProps> {
return this.spacesManager.updateSpaceShare(user, spaceId, shareId, createOrUpdateShareDto)
}
@@ -206,8 +195,8 @@ export class SpacesController {
@Delete(`:id/${SPACES_ROUTE.SHARES}/:sid`)
deleteSpaceShare(
@GetUser() user: UserModel,
- @Param('id', ParseIntPipe) spaceId: number,
- @Param('sid', ParseIntPipe) shareId: number
+ @Param('id', { schema: integerFromStringSchema }) spaceId: number,
+ @Param('sid', { schema: integerFromStringSchema }) shareId: number
): Promise<void> {
return this.spacesManager.deleteSpaceShare(user, spaceId, shareId)
}
@@ -215,8 +204,8 @@ export class SpacesController {
@Get(`:id/${SPACES_ROUTE.LINKS}/:sid`)
getSpaceShareLink(
@GetUser() user: UserModel,
- @Param('id', ParseIntPipe) spaceId: number,
- @Param('sid', ParseIntPipe) shareId: number
+ @Param('id', { schema: integerFromStringSchema }) spaceId: number,
+ @Param('sid', { schema: integerFromStringSchema }) shareId: number
): Promise<ShareLink> {
return this.spacesManager.getSpaceShareLink(user, spaceId, shareId)
}
diff --git a/backend/src/applications/spaces/spaces.schema.ts b/backend/src/applications/spaces/spaces.schema.ts
new file mode 100644
index 00000000..2f0e0f46
--- /dev/null
+++ b/backend/src/applications/spaces/spaces.schema.ts
@@ -0,0 +1,5 @@
+import { booleanFromStringSchema } from '../../configuration/config.schema.js'
+import { deleteSpaceSchema } from './dto/delete-space.dto.js'
+
+export const showFilesQuerySchema = booleanFromStringSchema.optional()
+export const optionalDeleteSpaceBodySchema = deleteSpaceSchema.optional()
diff --git a/backend/src/applications/spaces/utils/paths.ts b/backend/src/applications/spaces/utils/paths.ts
index 18fe8952..2c594df2 100644
--- a/backend/src/applications/spaces/utils/paths.ts
+++ b/backend/src/applications/spaces/utils/paths.ts
@@ -1,6 +1,7 @@
import { HttpStatus } from '@nestjs/common'
import fs from 'fs/promises'
import path from 'node:path'
+import { toErrorMessage } from '../../../common/errors.js'
import { FileDBProps } from '../../files/interfaces/file-db-props.interface.js'
import { FileProps } from '../../files/interfaces/file-props.interface.js'
import { FileError } from '../../files/models/file-error.js'
@@ -22,10 +23,10 @@ export async function IsRealPathIsDirAndExists(rPath: string) {
if (e instanceof FileError) {
throw new FileError(e.httpCode, e.message)
}
- if (e.code === 'ENOENT') {
+ if ((e as NodeJS.ErrnoException).code === 'ENOENT') {
throw new FileError(HttpStatus.NOT_FOUND, 'Location not found')
}
- throw new FileError(HttpStatus.BAD_REQUEST, e.message)
+ throw new FileError(HttpStatus.BAD_REQUEST, toErrorMessage(e))
}
}
@@ -47,11 +48,11 @@ export function realPathFromSpace(user: UserModel, space: SpaceEnv, withBasePath
} else {
fPath = space.paths
}
- } else if (space.root.file?.path && space.root.owner?.login) {
+ } else if (space.root?.file?.path && space.root.owner?.login) {
// space root linked to a file in a personal space
bPath = path.join(UserModel.getRepositoryPath(space.root.owner.login, space.root.file.inTrash), space.root.file.path)
fPath = space.paths
- } else if (space.root.file?.space?.id) {
+ } else if (space.root?.file?.space?.id) {
// share case
if (space.root.file.root?.id) {
// share linked to a file in a root space with an external path or directly to the root space
@@ -61,7 +62,7 @@ export function realPathFromSpace(user: UserModel, space: SpaceEnv, withBasePath
bPath = path.join(SpaceModel.getRepositoryPath(space.root.file.space.alias, space.root.file.inTrash), space.root.file.path || '')
}
fPath = space.paths
- } else if (space.alias) {
+ } else if (space.alias && space.root) {
// space files (no root)
bPath = SpaceModel.getRepositoryPath(space.alias, space.inTrashRepository)
fPath = [space.root.alias, ...space.paths]
@@ -174,15 +175,18 @@ export function temporaryRootFromSpace(user: UserModel, space: SpaceEnv): string
throw new FileError(HttpStatus.NOT_FOUND, 'Space root not found')
}
-export function realPathFromRootFile(f: FileProps): string {
+export function realPathFromRootFile(f: FileProps): string | undefined {
// get realpath
+ const root = f.root
+ if (!root) return undefined
+
if (f.origin) {
// share case (the order of the tests is important)
if (f.origin.ownerLogin) {
return path.join(UserModel.getRepositoryPath(f.origin.ownerLogin, f.inTrash), f.path)
- } else if (f.root.externalPath) {
+ } else if (root.externalPath) {
// in case of share child from a share with external path, child share should have an external path and a fileId (file path)
- return path.join(f.root.externalPath, f.path || '')
+ return path.join(root.externalPath, f.path || '')
} else if (f.origin.spaceRootExternalPath) {
return path.join(f.origin.spaceRootExternalPath, f.path)
} else if (f.origin.spaceAlias) {
@@ -190,17 +194,17 @@ export function realPathFromRootFile(f: FileProps): string {
}
} else {
// space case
- if (f.root.owner.login) {
- return path.join(UserModel.getRepositoryPath(f.root.owner.login, f.inTrash), f.path)
- } else if (f.root.externalPath) {
- return f.root.externalPath
+ if (root.owner.login) {
+ return path.join(UserModel.getRepositoryPath(root.owner.login, f.inTrash), f.path)
+ } else if (root.externalPath) {
+ return root.externalPath
}
}
return undefined
}
export function dbFileFromSpace(userId: number, space: SpaceEnv): FileDBProps {
- const dbFile: FileDBProps = {} as any
+ const dbFile: FileDBProps = {} as FileDBProps
dbFile.inTrash = space.repository === SPACE_REPOSITORY.TRASH
if (space.inPersonalSpace) {
// personal user space (ignore root alias)
@@ -214,7 +218,7 @@ export function dbFileFromSpace(userId: number, space: SpaceEnv): FileDBProps {
if (space.inSharesRepository) {
// in this case space.id is the share.id
// if the `externalParentShareId` property is defined, the external child share must use its highest parent share id
- dbFile.shareExternalId = space.root?.externalParentShareId ? space.root.externalParentShareId : space.id
+ dbFile.shareExternalId = space.root.externalParentShareId ? space.root.externalParentShareId : space.id
} else {
dbFile.shareExternalId = null
}
@@ -224,12 +228,12 @@ export function dbFileFromSpace(userId: number, space: SpaceEnv): FileDBProps {
} else {
dbFile.path = path.join(...space.paths)
}
- } else if (space.root.file?.path && space.root.owner?.login) {
+ } else if (space.root?.file?.path && space.root.owner?.login) {
// space root linked to a file in a personal space
dbFile.ownerId = space.root.owner.id
dbFile.inTrash = space.root.file.inTrash
dbFile.path = path.join(space.root.file.path, ...space.paths)
- } else if (space.root.file?.space?.id) {
+ } else if (space.root?.file?.space?.id) {
// share linked to a file in a space file or an external space root
dbFile.spaceId = space.root.file.space.id
dbFile.spaceExternalRootId = space.root.file.root?.id || null
@@ -238,7 +242,7 @@ export function dbFileFromSpace(userId: number, space: SpaceEnv): FileDBProps {
dbFile.inTrash = space.root.file.inTrash
}
dbFile.path = path.join(space.root.file.path || '', ...space.paths)
- } else if (space.id) {
+ } else if (space.id && space.root) {
// space files (no root)
dbFile.spaceId = space.id
dbFile.spaceExternalRootId = null
diff --git a/backend/src/applications/spaces/utils/permissions.ts b/backend/src/applications/spaces/utils/permissions.ts
index 656340af..0fc57001 100644
--- a/backend/src/applications/spaces/utils/permissions.ts
+++ b/backend/src/applications/spaces/utils/permissions.ts
@@ -10,7 +10,7 @@ export function havePermission(currentPermissions: string, mustHavePermission: S
return currentPermissions.indexOf(mustHavePermission) > -1
}
-export function haveSpaceEnvPermissions(space: SpaceEnv, permission: SPACE_OPERATION): boolean {
+export function haveSpaceEnvPermissions(space: SpaceEnv, permission: SPACE_OPERATION | null): boolean {
if (permission) {
return havePermission(space.envPermissions, permission)
}
@@ -18,10 +18,10 @@ export function haveSpaceEnvPermissions(space: SpaceEnv, permission: SPACE_OPERA
}
export function haveSpacePermission(space: Partial<SpaceProps>, permission: SPACE_OPERATION): boolean {
- return havePermission(space.permissions, permission)
+ return havePermission(space.permissions!, permission)
}
-export function getEnvPermissions(space: SpaceEnv, root: Partial<SpaceRoot>): string {
+export function getEnvPermissions(space: SpaceEnv, root?: Partial<SpaceRoot>): string {
/* In a root space, we have to intersect the space & the root permissions */
if (root?.id && typeof root?.permissions === 'string') {
return intersectPermissions(space.permissions, root.permissions)
@@ -33,7 +33,7 @@ export function getEnvPermissions(space: SpaceEnv, root: Partial<SpaceRoot>): st
export function removePermissions(permissions: string, rmPermissions: SPACE_OPERATION[]): string {
return permissions
.split(SPACE_PERMS_SEP)
- .filter((p: SPACE_OPERATION) => rmPermissions.indexOf(p) === -1)
+ .filter((p) => rmPermissions.indexOf(p as SPACE_OPERATION) === -1)
.sort()
.join(SPACE_PERMS_SEP)
}
diff --git a/backend/src/applications/sync/dtos/sync-client-auth.dto.ts b/backend/src/applications/sync/dtos/sync-client-auth.dto.ts
index 7883278c..b3d1ec3e 100644
--- a/backend/src/applications/sync/dtos/sync-client-auth.dto.ts
+++ b/backend/src/applications/sync/dtos/sync-client-auth.dto.ts
@@ -1,26 +1,11 @@
-import { Type } from 'class-transformer'
-import { IsBoolean, IsDefined, IsNotEmpty, IsNotEmptyObject, IsObject, IsOptional, IsString, IsUUID, ValidateNested } from 'class-validator'
-import { SyncClientInfoDto } from './sync-client-info.dto.js'
+import { z } from 'zod'
+import { syncClientInfoSchema } from './sync-client-info.dto.js'
-export class SyncClientAuthDto {
- @IsNotEmpty()
- @IsString()
- @IsUUID()
- clientId: string
+export const syncClientAuthSchema = z.object({
+ clientId: z.uuid(),
+ token: z.uuid(),
+ info: syncClientInfoSchema,
+ tokenHasExpired: z.boolean().nullish()
+})
- @IsNotEmpty()
- @IsString()
- @IsUUID()
- token: string
-
- @IsDefined()
- @IsObject()
- @IsNotEmptyObject()
- @ValidateNested()
- @Type(() => SyncClientInfoDto)
- info: SyncClientInfoDto
-
- @IsOptional()
- @IsBoolean()
- tokenHasExpired?: boolean
-}
+export type SyncClientAuthDto = z.infer<typeof syncClientAuthSchema>
diff --git a/backend/src/applications/sync/dtos/sync-client-info.dto.ts b/backend/src/applications/sync/dtos/sync-client-info.dto.ts
index 612368ab..a5354019 100644
--- a/backend/src/applications/sync/dtos/sync-client-info.dto.ts
+++ b/backend/src/applications/sync/dtos/sync-client-info.dto.ts
@@ -1,23 +1,11 @@
-import { IsEnum, IsString } from 'class-validator'
+import { z } from 'zod'
import { SYNC_CLIENT_TYPE } from '../constants/sync.js'
-import { SyncClientInfo } from '../interfaces/sync-client.interface.js'
-export class SyncClientInfoDto implements SyncClientInfo {
- @IsString()
- node: string
-
- @IsString()
- os: string
-
- @IsString()
- osRelease: string
-
- @IsString()
- user: string
-
- @IsEnum(SYNC_CLIENT_TYPE)
- type: SYNC_CLIENT_TYPE
-
- @IsString()
- version: string
-}
+export const syncClientInfoSchema = z.object({
+ node: z.string(),
+ os: z.string(),
+ osRelease: z.string(),
+ user: z.string(),
+ type: z.enum(SYNC_CLIENT_TYPE),
+ version: z.string()
+})
diff --git a/backend/src/applications/sync/dtos/sync-client-registration.dto.ts b/backend/src/applications/sync/dtos/sync-client-registration.dto.ts
index a182cb4a..f5192fc0 100644
--- a/backend/src/applications/sync/dtos/sync-client-registration.dto.ts
+++ b/backend/src/applications/sync/dtos/sync-client-registration.dto.ts
@@ -1,43 +1,19 @@
-import { Type } from 'class-transformer'
-import { IsDefined, IsNotEmpty, IsNotEmptyObject, IsObject, IsOptional, IsString, IsUUID, ValidateNested } from 'class-validator'
-import { SyncClientInfoDto } from './sync-client-info.dto.js'
+import { z } from 'zod'
+import { syncClientInfoSchema } from './sync-client-info.dto.js'
-export class SyncClientRegistrationDto {
- @IsNotEmpty()
- @IsString()
- login: string
+export const syncClientRegistrationSchema = z.object({
+ login: z.string().min(1),
+ password: z.string().min(1),
+ code: z.string().nullish(),
+ clientId: z.uuid(),
+ info: syncClientInfoSchema
+})
- @IsNotEmpty()
- @IsString()
- password: string
+export type SyncClientRegistrationDto = z.infer<typeof syncClientRegistrationSchema>
- @IsOptional()
- @IsString()
- code?: string
+export const syncClientAuthRegistrationSchema = z.object({
+ clientId: z.uuid().nullish(),
+ info: syncClientInfoSchema
+})
- @IsNotEmpty()
- @IsString()
- @IsUUID()
- clientId: string
-
- @IsDefined()
- @IsObject()
- @IsNotEmptyObject()
- @ValidateNested()
- @Type(() => SyncClientInfoDto)
- info: SyncClientInfoDto
-}
-
-export class SyncClientAuthRegistrationDto {
- @IsOptional()
- @IsString()
- @IsUUID()
- clientId?: string
-
- @IsDefined()
- @IsObject()
- @IsNotEmptyObject()
- @ValidateNested()
- @Type(() => SyncClientInfoDto)
- info: SyncClientInfoDto
-}
+export type SyncClientAuthRegistrationDto = z.infer<typeof syncClientAuthRegistrationSchema>
diff --git a/backend/src/applications/sync/dtos/sync-operations.dto.ts b/backend/src/applications/sync/dtos/sync-operations.dto.ts
index aaf288e3..b3cb642a 100644
--- a/backend/src/applications/sync/dtos/sync-operations.dto.ts
+++ b/backend/src/applications/sync/dtos/sync-operations.dto.ts
@@ -1,52 +1,40 @@
-import { Transform } from 'class-transformer'
-import { IsBoolean, IsDefined, IsInt, IsNotEmpty, IsObject, IsOptional, IsString } from 'class-validator'
-import { MakeFileDto } from '../../files/dto/file-operations.dto.js'
-import { SyncFileStats } from '../interfaces/sync-diff.interface.js'
+import { z } from 'zod'
+import { makeFileSchema } from '../../files/dto/file-operations.dto.js'
+import type { SyncFileStats } from '../interfaces/sync-diff.interface.js'
import { transformPathFilters } from '../utils/functions.js'
import { NormalizedMap } from '../utils/normalizedMap.js'
-export class SyncDiffDto {
- @IsDefined()
- @IsBoolean()
- secureDiff: boolean
-
- @IsDefined()
- @IsBoolean()
- firstSync: boolean
-
- @IsDefined()
- @IsString({ each: true })
- @Transform(({ value }) => new Set(value))
- defaultFilters: Set<string>
-
- @IsOptional()
- @Transform(({ value }) => transformPathFilters(value))
- pathFilters?: RegExp = null
-
- @IsOptional()
- @IsObject()
- @Transform(({ value }): NormalizedMap<string, SyncFileStats> => new NormalizedMap(Object.entries(value)))
- snapshot?: Map<string, SyncFileStats>
-}
-
-export class SyncPropsDto {
- @IsDefined()
- @IsInt()
- mtime: number
-}
-
-export class SyncMakeDto extends MakeFileDto {
- @IsDefined()
- @IsInt()
- mtime: number
-}
-
-export class SyncCopyMoveDto {
- @IsString()
- @IsNotEmpty()
- destination: string
-
- @IsOptional()
- @IsInt()
- mtime?: number
-}
+export const syncDiffSchema = z.object({
+ secureDiff: z.boolean(),
+ firstSync: z.boolean(),
+ defaultFilters: z.array(z.string()).transform((value) => new Set(value)),
+ pathFilters: z
+ .unknown()
+ .optional()
+ .transform((value) => transformPathFilters(value)),
+ snapshot: z
+ .record(z.string(), z.unknown())
+ .transform((value) => new NormalizedMap<string, SyncFileStats>(Object.entries(value) as [string, SyncFileStats][]))
+ .optional()
+})
+
+export type SyncDiffDto = z.infer<typeof syncDiffSchema>
+
+export const syncPropsSchema = z.object({
+ mtime: z.number().int()
+})
+
+export type SyncPropsDto = z.infer<typeof syncPropsSchema>
+
+export const syncMakeSchema = makeFileSchema.extend({
+ mtime: z.number().int()
+})
+
+export type SyncMakeDto = z.infer<typeof syncMakeSchema>
+
+export const syncCopyMoveSchema = z.object({
+ destination: z.string().min(1),
+ mtime: z.number().int().nullish()
+})
+
+export type SyncCopyMoveDto = z.infer<typeof syncCopyMoveSchema>
diff --git a/backend/src/applications/sync/dtos/sync-path.dto.ts b/backend/src/applications/sync/dtos/sync-path.dto.ts
index 39a7b85f..ade2d6ec 100644
--- a/backend/src/applications/sync/dtos/sync-path.dto.ts
+++ b/backend/src/applications/sync/dtos/sync-path.dto.ts
@@ -1,5 +1,5 @@
-import { Transform, Type } from 'class-transformer'
-import { ArrayMaxSize, IsArray, IsBoolean, IsEnum, IsInt, IsNotEmpty, IsOptional, IsString, MaxLength, ValidateNested } from 'class-validator'
+import { z } from 'zod'
+import { integerNumberSchema } from '../../../configuration/config.schema.js'
import {
SYNC_MAX_PATH_FILTER_LENGTH,
SYNC_MAX_PATH_FILTERS,
@@ -8,82 +8,48 @@ import {
SYNC_PATH_MODE,
SYNC_PATH_SCHEDULER_UNIT
} from '../constants/sync.js'
-import { SyncPathSettings } from '../interfaces/sync-path.interface.js'
-class SyncPathSchedulerDto {
- @IsInt()
- value: number
-
- @IsEnum(SYNC_PATH_SCHEDULER_UNIT)
- unit: SYNC_PATH_SCHEDULER_UNIT
-}
-
-export class SyncPathDto implements SyncPathSettings {
- @IsOptional()
- @IsInt()
- id?: number
-
- @IsNotEmpty()
- @IsString()
- name: string
-
- @IsNotEmpty()
- @IsString()
- localPath: string
-
- @IsNotEmpty()
- @IsString()
- remotePath: string
-
- @IsOptional()
- @IsString()
- permissions: string
-
- @Transform(({ value }) => (typeof value === 'string' ? value.toLowerCase() : value))
- @IsEnum(SYNC_PATH_MODE)
- mode: SYNC_PATH_MODE
-
- @IsOptional()
- @IsBoolean()
- ignoreDelete: boolean
-
- @Transform(({ value }) => (typeof value === 'string' ? value.toLowerCase() : value))
- @IsEnum(SYNC_PATH_DIFF_MODE)
- diffMode: SYNC_PATH_DIFF_MODE
-
- @Transform(({ value }) => (typeof value === 'string' ? value.toLowerCase() : value))
- @IsEnum(SYNC_PATH_CONFLICT_MODE)
- conflictMode: SYNC_PATH_CONFLICT_MODE
-
- @Transform(({ value }) => (Array.isArray(value) ? value.map((filter) => (typeof filter === 'string' ? filter.trim() : filter)) : value))
- @IsArray()
- @ArrayMaxSize(SYNC_MAX_PATH_FILTERS)
- @IsString({ each: true })
- @MaxLength(SYNC_MAX_PATH_FILTER_LENGTH, { each: true })
- filters: string[]
-
- @Transform(({ value }) => (value ? value : { value: 0, unit: SYNC_PATH_SCHEDULER_UNIT.DISABLED }))
- @ValidateNested()
- @Type(() => SyncPathSchedulerDto)
- scheduler: SyncPathSchedulerDto
-
- @IsInt()
- timestamp: number
-
- @IsBoolean()
- enabled: boolean
-
- @IsOptional()
- lastSync: Date
-}
-
-export class SyncPathUpdateDto extends SyncPathDto {
- @IsOptional()
- declare localPath: string
-
- @IsOptional()
- declare remotePath: string
-
- @IsOptional()
- declare timestamp: number
-}
+const syncPathSchedulerSchema = z.object({
+ value: z.number().int(),
+ unit: z.enum(SYNC_PATH_SCHEDULER_UNIT)
+})
+
+const syncPathLastSyncSchema = z.union([z.string(), z.number(), z.date()])
+
+const lowerCaseEnum = <T extends Record<string, string>>(values: T) => z.string().toLowerCase().pipe(z.enum(values))
+
+export const syncPathSchema = z.object({
+ id: integerNumberSchema.nullish(),
+ name: z.string().min(1),
+ localPath: z.string().min(1),
+ remotePath: z.string().min(1),
+ permissions: z.string().nullish(),
+ mode: lowerCaseEnum(SYNC_PATH_MODE),
+ ignoreDelete: z.boolean().nullish(),
+ diffMode: lowerCaseEnum(SYNC_PATH_DIFF_MODE),
+ conflictMode: lowerCaseEnum(SYNC_PATH_CONFLICT_MODE),
+ filters: z.array(z.string().trim().max(SYNC_MAX_PATH_FILTER_LENGTH)).max(SYNC_MAX_PATH_FILTERS),
+ scheduler: z.preprocess((value) => value || { value: 0, unit: SYNC_PATH_SCHEDULER_UNIT.DISABLED }, syncPathSchedulerSchema),
+ timestamp: z.number().int(),
+ enabled: z.boolean(),
+ lastSync: syncPathLastSyncSchema.nullish()
+})
+
+type SyncPathSchemaOutput = z.infer<typeof syncPathSchema>
+type SyncPathRequiredKey = 'mode' | 'diffMode' | 'conflictMode' | 'scheduler'
+
+// With strictNullChecks disabled, Zod pipeline metadata makes these output keys
+// optional. Restore only the fields backed by pipe or preprocess.
+export type SyncPathDto = SyncPathSchemaOutput & Required<Pick<SyncPathSchemaOutput, SyncPathRequiredKey>>
+
+export const syncPathUpdateSchema = syncPathSchema.extend({
+ localPath: syncPathSchema.shape.localPath.nullish(),
+ remotePath: syncPathSchema.shape.remotePath.nullish(),
+ timestamp: syncPathSchema.shape.timestamp.nullish()
+})
+
+type SyncPathUpdateSchemaOutput = z.infer<typeof syncPathUpdateSchema>
+
+export type SyncPathUpdateDto = SyncPathUpdateSchemaOutput & Required<Pick<SyncPathUpdateSchemaOutput, SyncPathRequiredKey>>
+
+export const syncPathsSchema = z.array(syncPathSchema)
diff --git a/backend/src/applications/sync/dtos/sync-upload.dto.spec.ts b/backend/src/applications/sync/dtos/sync-upload.dto.spec.ts
new file mode 100644
index 00000000..8949b705
--- /dev/null
+++ b/backend/src/applications/sync/dtos/sync-upload.dto.spec.ts
@@ -0,0 +1,31 @@
+import { syncUploadSchema } from './sync-upload.dto.js'
+
+describe('syncUploadSchema', () => {
+ it('parses integer query parameters', () => {
+ expect(syncUploadSchema.parse({ mtime: '1700000000', size: '42' })).toEqual({ mtime: 1700000000, size: 42 })
+ })
+
+ it.each(['', ' ', '1.5', '1e3', '0x10'])('rejects an ambiguous integer query parameter: %j', (value) => {
+ expect(syncUploadSchema.safeParse({ mtime: value, size: '42' }).success).toBe(false)
+ })
+
+ it('rejects a negative upload size', () => {
+ expect(syncUploadSchema.safeParse({ mtime: '1700000000', size: '-1' }).success).toBe(false)
+ })
+
+ it('accepts query parameters at the safe integer boundary', () => {
+ const boundary = String(Number.MAX_SAFE_INTEGER)
+ expect(syncUploadSchema.parse({ mtime: boundary, size: boundary })).toEqual({
+ mtime: Number.MAX_SAFE_INTEGER,
+ size: Number.MAX_SAFE_INTEGER
+ })
+ })
+
+ it.each(['9007199254740992', '-9007199254740992'])('rejects an unsafe upload timestamp: %s', (mtime) => {
+ expect(syncUploadSchema.safeParse({ mtime, size: '42' }).success).toBe(false)
+ })
+
+ it('rejects an unsafe upload size', () => {
+ expect(syncUploadSchema.safeParse({ mtime: '1700000000', size: '9007199254740992' }).success).toBe(false)
+ })
+})
diff --git a/backend/src/applications/sync/dtos/sync-upload.dto.ts b/backend/src/applications/sync/dtos/sync-upload.dto.ts
index 9bdc2ce7..fcebde7c 100644
--- a/backend/src/applications/sync/dtos/sync-upload.dto.ts
+++ b/backend/src/applications/sync/dtos/sync-upload.dto.ts
@@ -1,22 +1,10 @@
-import { Transform } from 'class-transformer'
-import { IsDefined, IsInt, IsNotEmpty, IsOptional, IsString, Min } from 'class-validator'
+import { z } from 'zod'
+import { safeIntegerFromStringSchema } from '../../../configuration/config.schema.js'
-export class SyncUploadDto {
- @IsOptional()
- @IsNotEmpty()
- @IsString()
- checksum?: string
+export const syncUploadSchema = z.object({
+ checksum: z.string().min(1).nullish(),
+ mtime: safeIntegerFromStringSchema,
+ size: safeIntegerFromStringSchema.pipe(z.number().min(0))
+})
- @IsDefined()
- @IsNotEmpty()
- @Transform(({ value }) => parseInt(value))
- @IsInt()
- mtime: number
-
- @IsDefined()
- @IsNotEmpty()
- @Transform(({ value }) => parseInt(value))
- @IsInt()
- @Min(0)
- size: number
-}
+export type SyncUploadDto = z.infer<typeof syncUploadSchema>
diff --git a/backend/src/applications/sync/interceptors/sync-diff-gzip-body.interceptor.spec.ts b/backend/src/applications/sync/interceptors/sync-diff-gzip-body.interceptor.spec.ts
index 5e0fa440..cb4dad40 100644
--- a/backend/src/applications/sync/interceptors/sync-diff-gzip-body.interceptor.spec.ts
+++ b/backend/src/applications/sync/interceptors/sync-diff-gzip-body.interceptor.spec.ts
@@ -144,7 +144,7 @@ describe('SyncDiffGzipBodyInterceptor', () => {
it('should throw Payload Too Large when decompressed gzip body exceeds the limit', async () => {
vi.spyOn(zlib, 'gunzip').mockImplementationOnce(((_body, _options, callback) => {
- callback(new Error('maxOutputLength exceeded'), null)
+ callback(new Error('maxOutputLength exceeded'), null as never)
}) as typeof zlib.gunzip)
const req: any = {
headers: { 'content-encoding': 'gzip' },
diff --git a/backend/src/applications/sync/interceptors/sync-diff-gzip-body.interceptor.ts b/backend/src/applications/sync/interceptors/sync-diff-gzip-body.interceptor.ts
index a34767c5..4733a475 100644
--- a/backend/src/applications/sync/interceptors/sync-diff-gzip-body.interceptor.ts
+++ b/backend/src/applications/sync/interceptors/sync-diff-gzip-body.interceptor.ts
@@ -3,6 +3,7 @@ import { FastifyRequest } from 'fastify'
import { IncomingMessage } from 'node:http'
import zlib from 'node:zlib'
import { Observable } from 'rxjs'
+import { toErrorMessage } from '../../../common/errors.js'
export const MAX_COMPRESSED_SYNC_DIFF_BODY_SIZE = 25 * 1024 * 1024
export const MAX_DECOMPRESSED_SYNC_DIFF_BODY_SIZE = 50 * 1024 * 1024
@@ -14,7 +15,7 @@ export class SyncDiffGzipBodyInterceptor implements NestInterceptor {
if (req.headers['content-encoding'] === 'gzip') {
const body: Buffer<ArrayBufferLike> = await this.readBody(req.raw)
await new Promise<void>((resolve, reject) => {
- zlib.gunzip(body, { maxOutputLength: MAX_DECOMPRESSED_SYNC_DIFF_BODY_SIZE }, (err: Error, decoded: Buffer<ArrayBufferLike>) => {
+ zlib.gunzip(body, { maxOutputLength: MAX_DECOMPRESSED_SYNC_DIFF_BODY_SIZE }, (err: Error | null, decoded: Buffer<ArrayBufferLike>) => {
if (err) {
return reject(new HttpException('Invalid gzip body', this.gzipErrorStatus(err)))
}
@@ -22,7 +23,7 @@ export class SyncDiffGzipBodyInterceptor implements NestInterceptor {
req.body = JSON.parse(decoded.toString())
resolve()
} catch (e) {
- reject(new HttpException(`Invalid JSON : ${e}`, HttpStatus.BAD_REQUEST))
+ reject(new HttpException(`Invalid JSON : ${toErrorMessage(e)}`, HttpStatus.BAD_REQUEST))
}
})
})
diff --git a/backend/src/applications/sync/interfaces/sync-client-paths.interface.ts b/backend/src/applications/sync/interfaces/sync-client-paths.interface.ts
index 1fc04d62..af7f28ef 100644
--- a/backend/src/applications/sync/interfaces/sync-client-paths.interface.ts
+++ b/backend/src/applications/sync/interfaces/sync-client-paths.interface.ts
@@ -1,5 +1,5 @@
-import { SyncClient } from '../schemas/sync-client.interface.js'
-import { SyncPath } from '../schemas/sync-path.interface.js'
+import type { SyncClient } from '../schemas/sync-client.interface.js'
+import type { SyncPath } from '../schemas/sync-path.interface.js'
import { SyncClientInfo } from './sync-client.interface.js'
export interface SyncClientPaths extends Partial<SyncClient> {
@@ -7,10 +7,10 @@ export interface SyncClientPaths extends Partial<SyncClient> {
tokenExpiration: number
info: SyncClientInfo
enabled: boolean
- currentIp: string
- lastIp: string
- currentAccess: Date
- lastAccess: Date
+ currentIp: string | null
+ lastIp: string | null
+ currentAccess: Date | null
+ lastAccess: Date | null
createdAt: Date
// extra property
diff --git a/backend/src/applications/sync/interfaces/sync-path.interface.ts b/backend/src/applications/sync/interfaces/sync-path.interface.ts
index 41a21dfe..0558df8c 100644
--- a/backend/src/applications/sync/interfaces/sync-path.interface.ts
+++ b/backend/src/applications/sync/interfaces/sync-path.interface.ts
@@ -1,4 +1,5 @@
import type { SYNC_PATH_CONFLICT_MODE, SYNC_PATH_DIFF_MODE, SYNC_PATH_MODE } from '../constants/sync.js'
+import type { SyncPathDto } from '../dtos/sync-path.dto.js'
import type { SyncPath } from '../schemas/sync-path.interface.js'
export type SyncDBProps = Partial<Pick<SyncPath, 'ownerId' | 'spaceId' | 'spaceRootId' | 'shareId' | 'fileId'>>
@@ -8,16 +9,16 @@ export interface SyncPathSettings {
name: string
localPath: string
remotePath: string
- permissions: string
+ permissions?: string | null
mode: SYNC_PATH_MODE
- ignoreDelete: boolean
+ ignoreDelete?: boolean | null
enabled: boolean
diffMode: SYNC_PATH_DIFF_MODE
conflictMode: SYNC_PATH_CONFLICT_MODE
filters: string[]
scheduler: { value: number; unit: string }
timestamp: number
- lastSync: Date
+ lastSync?: string | number | Date | null
}
export interface SyncPathFromClient extends SyncPathSettings {
@@ -26,3 +27,11 @@ export interface SyncPathFromClient extends SyncPathSettings {
mainError: string
lastErrors: string[]
}
+
+export type ExistingSyncPathDto = SyncPathDto & { id: number }
+
+export interface SyncPathsDiff {
+ add: SyncPathSettings[]
+ update: ({ id: number } & Partial<Omit<SyncPathSettings, 'id'>>)[]
+ delete: number[]
+}
diff --git a/backend/src/applications/sync/schemas/sync-client.interface.ts b/backend/src/applications/sync/schemas/sync-client.interface.ts
index 22fd84dc..2b3408f8 100644
--- a/backend/src/applications/sync/schemas/sync-client.interface.ts
+++ b/backend/src/applications/sync/schemas/sync-client.interface.ts
@@ -1,18 +1,3 @@
-import { SyncClientInfo } from '../interfaces/sync-client.interface.js'
import type { syncClients } from './sync-clients.schema.js'
-type SyncClientSchema = typeof syncClients.$inferSelect
-
-export class SyncClient implements SyncClientSchema {
- id: string
- ownerId: number
- token: string
- tokenExpiration: number
- info: SyncClientInfo
- enabled: boolean
- currentIp: string
- lastIp: string
- currentAccess: Date
- lastAccess: Date
- createdAt: Date
-}
+export type SyncClient = typeof syncClients.$inferSelect
diff --git a/backend/src/applications/sync/schemas/sync-path.interface.ts b/backend/src/applications/sync/schemas/sync-path.interface.ts
index 9896112d..8f6cf651 100644
--- a/backend/src/applications/sync/schemas/sync-path.interface.ts
+++ b/backend/src/applications/sync/schemas/sync-path.interface.ts
@@ -1,16 +1,3 @@
-import type { SyncPathSettings } from '../interfaces/sync-path.interface.js'
-import { syncPaths } from './sync-paths.schema.js'
+import type { syncPaths } from './sync-paths.schema.js'
-type SyncPathSchema = typeof syncPaths.$inferSelect
-
-export class SyncPath implements SyncPathSchema {
- id: number
- clientId: string
- ownerId: number
- spaceId: number
- spaceRootId: number
- shareId: number
- fileId: number
- settings: SyncPathSettings
- createdAt: Date
-}
+export type SyncPath = typeof syncPaths.$inferSelect
diff --git a/backend/src/applications/sync/services/sync-clients-manager.service.ts b/backend/src/applications/sync/services/sync-clients-manager.service.ts
index 3aa72759..06fb391f 100644
--- a/backend/src/applications/sync/services/sync-clients-manager.service.ts
+++ b/backend/src/applications/sync/services/sync-clients-manager.service.ts
@@ -1,3 +1,4 @@
+import { toErrorMessage } from '../../../common/errors.js'
import { HttpService } from '@nestjs/axios'
import { HttpException, HttpStatus, Injectable, Logger } from '@nestjs/common'
import { AxiosResponse } from 'axios'
@@ -24,12 +25,12 @@ import { CLIENT_AUTH_TYPE, CLIENT_TOKEN_EXPIRATION_TIME, CLIENT_TOKEN_EXPIRED_ER
import { APP_STORE_DIRNAME, APP_STORE_MANIFEST_FILE, APP_STORE_REPOSITORY } from '../constants/store.js'
import { SYNC_CLIENT_TYPE } from '../constants/sync.js'
import type { SyncClientAuthDto } from '../dtos/sync-client-auth.dto.js'
-import { SyncClientAuthRegistrationDto, SyncClientRegistrationDto } from '../dtos/sync-client-registration.dto.js'
+import type { SyncClientAuthRegistrationDto, SyncClientRegistrationDto } from '../dtos/sync-client-registration.dto.js'
import { AppStoreManifest } from '../interfaces/store-manifest.interface.js'
import { SyncClientAuthCookie, SyncClientAuthRegistration, SyncClientAuthToken } from '../interfaces/sync-client-auth.interface.js'
import { SyncClientPaths } from '../interfaces/sync-client-paths.interface.js'
import { SyncClientInfo } from '../interfaces/sync-client.interface.js'
-import { SyncClient } from '../schemas/sync-client.interface.js'
+import type { SyncClient } from '../schemas/sync-client.interface.js'
import { SyncQueries } from './sync-queries.service.js'
@Injectable()
@@ -46,7 +47,7 @@ export class SyncClientsManager {
) {}
async register(clientRegistrationDto: SyncClientRegistrationDto, ip: string): Promise<SyncClientAuthRegistration> {
- const user: UserModel = await this.authProvider.validateUser(clientRegistrationDto.login, clientRegistrationDto.password, ip, AUTH_SCOPE.CLIENT)
+ const user = await this.authProvider.validateUser(clientRegistrationDto.login, clientRegistrationDto.password, ip, AUTH_SCOPE.CLIENT)
if (!user) {
this.logger.warn({ tag: this.register.name, msg: `auth failed for user *${clientRegistrationDto.login}*` })
throw new HttpException('Wrong login or password', HttpStatus.UNAUTHORIZED)
@@ -64,10 +65,10 @@ export class SyncClientsManager {
this.logger.warn({ tag: this.register.name, msg: `missing two-fa code for user *${user.login}* (${user.id})` })
throw new HttpException('Missing TWO-FA code', HttpStatus.UNAUTHORIZED)
}
- const authCode = this.authProvider2FA.validateTwoFactorCode(clientRegistrationDto.code, user.secrets.twoFaSecret)
+ const authCode = this.authProvider2FA.validateTwoFactorCode(clientRegistrationDto.code, user.secrets!.twoFaSecret!)
if (!authCode.success) {
this.logger.warn({ tag: this.register.name, msg: `two-fa code for *${user.login}* (${user.id}) - ${authCode.message}` })
- const authRCode = await this.authProvider2FA.validateRecoveryCode(user.id, clientRegistrationDto.code, user.secrets.recoveryCodes)
+ const authRCode = await this.authProvider2FA.validateRecoveryCode(user.id, clientRegistrationDto.code, user.secrets!.recoveryCodes!)
if (!authRCode.success) {
this.logger.warn({ tag: this.register.name, msg: `two-fa recovery code for *${user.login}* (${user.id}) - ${authRCode.message}` })
await this.usersManager.updateAccesses(user, ip, false)
@@ -88,9 +89,9 @@ export class SyncClientsManager {
async unregister(user: UserModel): Promise<void> {
try {
- await this.syncQueries.deleteClient(user.id, user.clientId)
+ await this.syncQueries.deleteClient(user.id, user.clientId!)
} catch (e) {
- this.logger.error({ tag: this.unregister.name, msg: `${e}` })
+ this.logger.error({ tag: this.unregister.name, msg: toErrorMessage(e) })
throw new HttpException('Error during the removing of client registration', HttpStatus.INTERNAL_SERVER_ERROR)
}
}
@@ -101,7 +102,7 @@ export class SyncClientsManager {
ip: string,
res: FastifyReply
): Promise<SyncClientAuthToken | SyncClientAuthCookie> {
- const client = await this.syncQueries.getClient(syncClientAuthDto.clientId, null, syncClientAuthDto.token)
+ const client = await this.syncQueries.getClient(syncClientAuthDto.clientId, undefined, syncClientAuthDto.token)
if (!client) {
throw new HttpException('Client is unknown', HttpStatus.FORBIDDEN)
}
@@ -111,8 +112,10 @@ export class SyncClientsManager {
if (currentTimeStamp() >= client.tokenExpiration) {
throw new HttpException(CLIENT_TOKEN_EXPIRED_ERROR, HttpStatus.FORBIDDEN)
}
- this.syncQueries.updateClientInfo(client, client.info, ip).catch((e: Error) => this.logger.error({ tag: this.authenticate.name, msg: `${e}` }))
- const user: UserModel = await this.usersManager.fromUserId(client.ownerId)
+ this.syncQueries
+ .updateClientInfo(client, client.info, ip)
+ .catch((e: Error) => this.logger.error({ tag: this.authenticate.name, msg: toErrorMessage(e) }))
+ const user = await this.usersManager.fromUserId(client.ownerId)
if (!user) {
throw new HttpException('User does not exist', HttpStatus.FORBIDDEN)
}
@@ -126,8 +129,8 @@ export class SyncClientsManager {
// set clientId
user.clientId = client.id
// update accesses
- this.usersManager.updateAccesses(user, ip, true).catch((e: Error) => this.logger.error({ tag: this.authenticate.name, msg: `${e}` }))
- let r: SyncClientAuthToken | SyncClientAuthCookie
+ this.usersManager.updateAccesses(user, ip, true).catch((e: Error) => this.logger.error({ tag: this.authenticate.name, msg: toErrorMessage(e) }))
+ let r!: SyncClientAuthToken | SyncClientAuthCookie
if (authType === CLIENT_AUTH_TYPE.COOKIE) {
// used by the desktop app to perform the login setup using cookies
r = await this.authManager.setCookies(user, res)
@@ -157,7 +160,7 @@ export class SyncClientsManager {
} catch (e) {
this.logger.error({
tag: this.renewTokenAndExpiration.name,
- msg: `unable to renew token for user *${owner.login}* and client *${client.id}* : ${e}`
+ msg: `unable to renew token for user *${owner.login}* and client *${client.id}* : ${toErrorMessage(e)}`
})
throw new HttpException('Unable to update client token', HttpStatus.BAD_REQUEST)
}
@@ -168,14 +171,14 @@ export class SyncClientsManager {
try {
await this.syncQueries.deleteClient(user.id, clientId)
} catch (e) {
- this.logger.error({ tag: this.deleteClient.name, msg: `${e}` })
+ this.logger.error({ tag: this.deleteClient.name, msg: toErrorMessage(e) })
throw new HttpException('Unable to delete client', HttpStatus.INTERNAL_SERVER_ERROR)
}
}
@CacheDecorator(3600)
- async checkAppStore(): Promise<AppStoreManifest> {
- let manifest: AppStoreManifest = null
+ async checkAppStore(): Promise<AppStoreManifest | null> {
+ let manifest: AppStoreManifest | null = null
if (configuration.applications.appStore.repository === APP_STORE_REPOSITORY.PUBLIC) {
const url = `${RELEASES_URL}/${APP_STORE_MANIFEST_FILE}`
try {
@@ -183,10 +186,10 @@ export class SyncClientsManager {
method: HTTP_METHOD.GET,
url: url
})
- manifest = res.data
+ manifest = res.data as AppStoreManifest
manifest.repository = APP_STORE_REPOSITORY.PUBLIC
} catch (e) {
- this.logger.warn({ tag: this.checkAppStore.name, msg: `unable to retrieve ${url} : ${e}` })
+ this.logger.warn({ tag: this.checkAppStore.name, msg: `unable to retrieve ${url} : ${toErrorMessage(e)}` })
}
} else {
const latestFile = path.join(STATIC_PATH, APP_STORE_DIRNAME, APP_STORE_MANIFEST_FILE)
@@ -194,7 +197,7 @@ export class SyncClientsManager {
this.logger.warn({ tag: this.checkAppStore.name, msg: `${latestFile} does not exist` })
} else {
try {
- manifest = JSON.parse(await fs.readFile(latestFile, 'utf8'))
+ manifest = JSON.parse(await fs.readFile(latestFile, 'utf8')) as AppStoreManifest
manifest.repository = APP_STORE_REPOSITORY.LOCAL
// rewrite urls to local repository
for (const [os, packages] of Object.entries(manifest.platform)) {
@@ -207,7 +210,7 @@ export class SyncClientsManager {
}
}
} catch (e) {
- this.logger.error({ tag: this.checkAppStore.name, msg: `${latestFile} : ${e}` })
+ this.logger.error({ tag: this.checkAppStore.name, msg: `${latestFile} : ${toErrorMessage(e)}` })
}
}
}
@@ -220,7 +223,7 @@ export class SyncClientsManager {
this.logger.log({ tag: this.getOrCreateClient.name, msg: `client *${clientInfo.type}* was registered for user *${user.login}* (${user.id})` })
return { clientId: clientId, clientToken: token } satisfies SyncClientAuthRegistration
} catch (e) {
- this.logger.error({ tag: this.getOrCreateClient.name, msg: `${e}` })
+ this.logger.error({ tag: this.getOrCreateClient.name, msg: toErrorMessage(e) })
throw new HttpException('Error during the client registration', HttpStatus.INTERNAL_SERVER_ERROR)
}
}
diff --git a/backend/src/applications/sync/services/sync-manager.service.spec.ts b/backend/src/applications/sync/services/sync-manager.service.spec.ts
index 9d30a320..ba8cd770 100644
--- a/backend/src/applications/sync/services/sync-manager.service.spec.ts
+++ b/backend/src/applications/sync/services/sync-manager.service.spec.ts
@@ -24,16 +24,20 @@ vi.mock('fs/promises', () => ({
}))
// Mock helper functions used in service
-vi.mock('../../files/utils/files.js', () => ({
- __esModule: true,
- checksumFile: vi.fn(),
- isInternalTemporaryEntry: vi.fn((name: string) => name === '.sync-in-tmp' || name.startsWith('.sync-in.')),
- isPathExists: vi.fn(),
- isPathIsDir: vi.fn(),
- removeFiles: vi.fn(),
- touchFile: vi.fn(),
- sanitizePath: vi.fn((p: string) => p)
-}))
+vi.mock('../../files/utils/files.js', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('../../files/utils/files.js')>()
+ return {
+ ...actual,
+ __esModule: true,
+ checksumFile: vi.fn(),
+ isInternalTemporaryEntry: vi.fn((name: string) => name === '.sync-in-tmp' || name.startsWith('.sync-in.')),
+ isPathExists: vi.fn(),
+ isPathIsDir: vi.fn(),
+ removeFiles: vi.fn(),
+ touchFile: vi.fn(),
+ sanitizePath: vi.fn((p: string) => p)
+ }
+})
// Mock regExpPathPattern to a simple, predictable behavior
vi.mock('../../../common/functions.js', () => ({
@@ -141,7 +145,7 @@ describe(SyncManager.name, () => {
})
it.each([
- ['LockConflict maps to 423', new LockConflict(null, 'locked'), HttpStatus.LOCKED],
+ ['LockConflict maps to 423', new LockConflict(null as never, 'locked'), HttpStatus.LOCKED],
['FileError maps to its http code', new FileError(HttpStatus.BAD_REQUEST, 'bad'), HttpStatus.BAD_REQUEST],
['generic Error maps to 500', new Error('oops'), HttpStatus.INTERNAL_SERVER_ERROR]
])('should map errors (%s)', async (_title, thrown, expectedStatus) => {
@@ -247,7 +251,7 @@ describe(SyncManager.name, () => {
it('should map errors via handleError', async () => {
const req = makeReq()
- filesManager.delete.mockRejectedValue(new LockConflict(null, 'locked'))
+ filesManager.delete.mockRejectedValue(new LockConflict(null as never, 'locked'))
await expect(service.delete(req as any)).rejects.toMatchObject({ status: HttpStatus.LOCKED })
})
@@ -296,7 +300,7 @@ describe(SyncManager.name, () => {
it('should map errors via handleError', async () => {
const req = makeReq()
- filesManager.mkDir.mockRejectedValue(new LockConflict(null, 'locked'))
+ filesManager.mkDir.mockRejectedValue(new LockConflict(null as never, 'locked'))
await expect(service.make(req as any, { type: 'directory', mtime: 0 } as any)).rejects.toMatchObject({ status: HttpStatus.LOCKED })
})
@@ -354,7 +358,7 @@ describe(SyncManager.name, () => {
const req = makeReq()
const dstSpace = { realPath: '/dst/err-move', url: '/space/dst/err-move' }
spacesManager.spaceEnv.mockResolvedValue(dstSpace)
- filesManager.copyMove.mockRejectedValue(new LockConflict(null, 'locked'))
+ filesManager.copyMove.mockRejectedValue(new LockConflict(null as never, 'locked'))
const spy = vi.spyOn(service as any, 'handleError')
diff --git a/backend/src/applications/sync/services/sync-manager.service.ts b/backend/src/applications/sync/services/sync-manager.service.ts
index 7a5ccda3..6067cbc0 100644
--- a/backend/src/applications/sync/services/sync-manager.service.ts
+++ b/backend/src/applications/sync/services/sync-manager.service.ts
@@ -3,10 +3,12 @@ import { FastifyReply } from 'fastify'
import fs from 'fs/promises'
import { Dirent, Stats } from 'node:fs'
import path from 'node:path'
+import { toErrorMessage } from '../../../common/errors.js'
import { regExpPathPattern } from '../../../common/functions.js'
import { FILE_ERROR } from '../../files/constants/errors.js'
import { FILE_OPERATION } from '../../files/constants/operations.js'
import { FileError } from '../../files/models/file-error.js'
+import type { SaveStreamTmpFileValidationContext } from '../../files/interfaces/save-stream.interface.js'
import { LockConflict } from '../../files/models/file-lock-error.js'
import { FilesManager } from '../../files/services/files-manager.service.js'
import { checksumFile, isInternalTemporaryEntry, isPathExists, isPathIsDir, touchFile } from '../../files/utils/files.js'
@@ -17,10 +19,9 @@ import { SpaceEnv } from '../../spaces/models/space-env.model.js'
import { SpacesManager } from '../../spaces/services/spaces-manager.service.js'
import { UserModel } from '../../users/models/user.model.js'
import { F_SPECIAL_STAT, F_STAT, SYNC_CHECKSUM_ALG, SYNC_DIFF_DONE } from '../constants/sync.js'
-import { SyncCopyMoveDto, SyncDiffDto, SyncMakeDto, SyncPropsDto } from '../dtos/sync-operations.dto.js'
-import { SyncUploadDto } from '../dtos/sync-upload.dto.js'
+import type { SyncCopyMoveDto, SyncDiffDto, SyncMakeDto, SyncPropsDto } from '../dtos/sync-operations.dto.js'
+import type { SyncUploadDto } from '../dtos/sync-upload.dto.js'
import { SyncFileSpecialStats, SyncFileStats } from '../interfaces/sync-diff.interface.js'
-import { SyncPathSettings } from '../interfaces/sync-path.interface.js'
import { getSyncTmpFilePath } from '../utils/functions.js'
import { SYNC_PATH_TO_SPACE_SEGMENTS } from '../utils/routes.js'
import { SyncQueries } from './sync-queries.service.js'
@@ -52,7 +53,7 @@ export class SyncManager {
tmpPath: tmpPath,
expectedUploadSize: syncUploadDto.size,
...(syncUploadDto.checksum && { checksumAlg: SYNC_CHECKSUM_ALG }),
- validateTmpFile: async ({ tmpPath, checksum }) => {
+ validateTmpFile: async ({ tmpPath, checksum }: SaveStreamTmpFileValidationContext) => {
const tmpStats = await fs.stat(tmpPath)
if (tmpStats.size !== syncUploadDto.size) {
throw new FileError(HttpStatus.BAD_REQUEST, `sizes are not identical : ${tmpStats.size} != ${syncUploadDto.size}`)
@@ -105,7 +106,10 @@ export class SyncManager {
async copyMove(req: FastifySpaceRequest, syncCopyMoveDto: SyncCopyMoveDto, isMove: true): Promise<void>
async copyMove(req: FastifySpaceRequest, syncCopyMoveDto: SyncCopyMoveDto, isMove: false): Promise<{ ino: number; mtime: number }>
async copyMove(req: FastifySpaceRequest, syncCopyMoveDto: SyncCopyMoveDto, isMove: boolean): Promise<void | { ino: number; mtime: number }> {
- const dstSpace: SpaceEnv = await this.spacesManager.spaceEnv(req.user, SYNC_PATH_TO_SPACE_SEGMENTS(syncCopyMoveDto.destination))
+ const dstSpace = await this.spacesManager.spaceEnv(req.user, SYNC_PATH_TO_SPACE_SEGMENTS(syncCopyMoveDto.destination))
+ if (!dstSpace) {
+ throw new HttpException('Destination space not found', HttpStatus.NOT_FOUND)
+ }
try {
await this.filesManager.copyMove(req.user, req.space, dstSpace, isMove, true, true)
if (!isMove) {
@@ -126,15 +130,15 @@ export class SyncManager {
if (!user.clientId) {
throw new HttpException('Client id is missing', HttpStatus.BAD_REQUEST)
}
- const syncPathSettings: SyncPathSettings = await this.syncQueries.getPathSettings(user.clientId, pathId)
+ const syncPathSettings = await this.syncQueries.getPathSettings(user.clientId, pathId)
if (!syncPathSettings) {
throw new HttpException('Path not found', HttpStatus.NOT_FOUND)
}
- let space: SpaceEnv
+ let space: SpaceEnv | null
try {
space = await this.spacesManager.spaceEnv(user, SYNC_PATH_TO_SPACE_SEGMENTS(syncPathSettings.remotePath))
} catch (e) {
- throw new HttpException(e.message, HttpStatus.BAD_REQUEST)
+ throw new HttpException(toErrorMessage(e), HttpStatus.BAD_REQUEST)
}
if (!space) {
throw new HttpException('Space not found', HttpStatus.NOT_FOUND)
@@ -159,8 +163,9 @@ export class SyncManager {
}
res.raw.write(SYNC_DIFF_DONE)
} catch (e) {
- this.logger.error({ tag: this.diff.name, msg: `${e.message}` })
- res.raw.write(`${e.message}\n`)
+ const errorMessage = toErrorMessage(e)
+ this.logger.error({ tag: this.diff.name, msg: errorMessage })
+ res.raw.write(`${errorMessage}\n`)
res.status(HttpStatus.INTERNAL_SERVER_ERROR)
}
res.raw.end()
@@ -187,25 +192,25 @@ export class SyncManager {
continue
}
if (entry.isDirectory()) {
- const dirStats: Record<string, SyncFileStats | SyncFileSpecialStats> = await this.analyzeFile(entry, ctx)
+ const dirStats = await this.analyzeFile(entry, ctx)
if (dirStats !== null) {
yield dirStats
}
yield* this.parseFiles(realPath, ctx)
} else {
- const fileStats: Record<string, SyncFileStats | SyncFileSpecialStats> = await this.analyzeFile(entry, ctx)
+ const fileStats = await this.analyzeFile(entry, ctx)
if (fileStats !== null) {
yield fileStats
}
}
}
} catch (e) {
- this.logger.error({ tag: this.parseFiles.name, msg: `unable to parse directory : ${dir} : ${e}` })
+ this.logger.error({ tag: this.parseFiles.name, msg: `unable to parse directory : ${dir} : ${toErrorMessage(e)}` })
throw new Error('Unable to parse path')
}
}
- private async analyzeFile(entry: Dirent, ctx: ParseDiffContext): Promise<Record<string, SyncFileStats | SyncFileSpecialStats>> {
+ private async analyzeFile(entry: Dirent, ctx: ParseDiffContext): Promise<Record<string, SyncFileStats | SyncFileSpecialStats> | null> {
if (ctx.syncDiff.defaultFilters.has(entry.name)) {
return null
}
@@ -217,8 +222,8 @@ export class SyncManager {
try {
stats = await fs.stat(realPath)
} catch (e) {
- this.logger.warn({ tag: this.analyzeFile.name, msg: `unable to get file stats : ${realPath} : ${e}` })
- return { [filePath]: [F_SPECIAL_STAT.ERROR, e.toString()] }
+ this.logger.warn({ tag: this.analyzeFile.name, msg: `unable to get file stats : ${realPath} : ${toErrorMessage(e)}` })
+ return { [filePath]: [F_SPECIAL_STAT.ERROR, toErrorMessage(e)] }
}
if (ctx.syncDiff.pathFilters && ctx.syncDiff.pathFilters.test(filePath)) {
@@ -237,16 +242,16 @@ export class SyncManager {
try {
await this.checkSumFile(ctx, filePath, realPath, fileStats)
} catch (e) {
- this.logger.error({ tag: this.analyzeFile.name, msg: `file error : ${realPath} - ${e}` })
- return { [filePath]: [F_SPECIAL_STAT.ERROR, e.toString()] }
+ this.logger.error({ tag: this.analyzeFile.name, msg: `file error : ${realPath} - ${toErrorMessage(e)}` })
+ return { [filePath]: [F_SPECIAL_STAT.ERROR, toErrorMessage(e)] }
}
}
return { [filePath]: fileStats }
}
private async checkSumFile(ctx: ParseDiffContext, filePath: string, realPath: string, fileStats: SyncFileStats): Promise<void> {
- if (!ctx.syncDiff.firstSync && ctx.syncDiff.snapshot.has(filePath)) {
- const snapFileStats: SyncFileStats = ctx.syncDiff.snapshot.get(filePath)
+ if (!ctx.syncDiff.firstSync && ctx.syncDiff.snapshot!.has(filePath)) {
+ const snapFileStats = ctx.syncDiff.snapshot!.get(filePath)!
if (
snapFileStats[F_STAT.CHECKSUM] &&
snapFileStats[F_STAT.MTIME] == fileStats[F_STAT.MTIME] &&
@@ -260,10 +265,13 @@ export class SyncManager {
fileStats[F_STAT.CHECKSUM] = await checksumFile(realPath, SYNC_CHECKSUM_ALG)
}
- private handleError(space: SpaceEnv, action: string, e: any, dstSpace?: SpaceEnv) {
- this.logger.error({ tag: this.handleError.name, msg: `unable to ${action} ${space.url}${dstSpace?.url ? ` -> ${dstSpace.url}` : ''} : ${e}` })
+ private handleError(space: SpaceEnv, action: string, e: unknown, dstSpace?: SpaceEnv): never {
+ this.logger.error({
+ tag: this.handleError.name,
+ msg: `unable to ${action} ${space.url}${dstSpace?.url ? ` -> ${dstSpace.url}` : ''} : ${toErrorMessage(e)}`
+ })
// Remove the last part to avoid exposing the path
- const errorMsg = e.message.split(',')[0]
+ const errorMsg = toErrorMessage(e).split(',')[0]
if (e instanceof LockConflict) {
throw new HttpException('The file is locked', HttpStatus.LOCKED)
} else if (e instanceof FileError) {
diff --git a/backend/src/applications/sync/services/sync-paths-manager.service.spec.ts b/backend/src/applications/sync/services/sync-paths-manager.service.spec.ts
index 15d5d488..a8acffb3 100644
--- a/backend/src/applications/sync/services/sync-paths-manager.service.spec.ts
+++ b/backend/src/applications/sync/services/sync-paths-manager.service.spec.ts
@@ -488,7 +488,7 @@ describe(SyncPathsManager.name, () => {
await flush()
expect(loggerSpy).toHaveBeenCalled()
- expect(loggerSpy.mock.calls.some(([payload]: { tag: string }[]) => payload?.tag === 'updatePaths')).toBe(true)
+ expect(loggerSpy.mock.calls.some(([payload]) => (payload as { tag?: string })?.tag === 'updatePaths')).toBe(true)
})
it('should catch notify failure at updatePaths level when building notification fails', async () => {
@@ -496,7 +496,6 @@ describe(SyncPathsManager.name, () => {
// No server paths: will mark client path as deleted and call notify
syncQueries.getPaths.mockResolvedValue([])
const loggerSpy = vi.spyOn((service as any).logger, 'error').mockImplementation(() => undefined)
- // BAD first segment to make notify fail while building URL (before notificationsManager.create)
const client = [{ id: 1, remotePath: 'BAD/a/b', timestamp: 1, lastSync: 1, permissions: 'p' } as any]
const res = await service.updatePaths(userWith('c1') as any, client)
@@ -504,8 +503,7 @@ describe(SyncPathsManager.name, () => {
expect(res.delete).toEqual([1])
expect(loggerSpy).toHaveBeenCalled()
- expect(loggerSpy.mock.calls.some(([payload]: { tag: string }[]) => payload?.tag === 'updatePaths')).toBe(true)
- // create not called because we failed before reaching it
+ expect(loggerSpy.mock.calls.some(([payload]) => (payload as { tag?: string })?.tag === 'updatePaths')).toBe(true)
expect(notificationsManager.create).not.toHaveBeenCalled()
})
@@ -523,7 +521,7 @@ describe(SyncPathsManager.name, () => {
expect(res.delete).toEqual([2])
expect(loggerSpy).toHaveBeenCalled()
// error comes from notify() catch
- expect(loggerSpy.mock.calls.some(([payload]: { tag: string }[]) => payload?.tag === 'notify')).toBe(true)
+ expect(loggerSpy.mock.calls.some(([payload]) => (payload as { tag?: string })?.tag === 'notify')).toBe(true)
})
})
diff --git a/backend/src/applications/sync/services/sync-paths-manager.service.ts b/backend/src/applications/sync/services/sync-paths-manager.service.ts
index f565ed46..6fe36048 100644
--- a/backend/src/applications/sync/services/sync-paths-manager.service.ts
+++ b/backend/src/applications/sync/services/sync-paths-manager.service.ts
@@ -1,5 +1,6 @@
import { HttpException, HttpStatus, Injectable, Logger } from '@nestjs/common'
import { ACTION } from '../../../common/constants.js'
+import { toErrorMessage } from '../../../common/errors.js'
import { currentTimeStamp } from '../../../common/shared.js'
import { FILE_ERROR } from '../../files/constants/errors.js'
import type { FileProps } from '../../files/interfaces/file-props.interface.js'
@@ -14,9 +15,8 @@ import { SpacesManager } from '../../spaces/services/spaces-manager.service.js'
import { getEnvPermissions } from '../../spaces/utils/permissions.js'
import { UserModel } from '../../users/models/user.model.js'
import { SYNC_PATH_REPOSITORY } from '../constants/sync.js'
-import { SyncPathDto, SyncPathUpdateDto } from '../dtos/sync-path.dto.js'
-import { SyncDBProps, SyncPathSettings } from '../interfaces/sync-path.interface.js'
-import { SyncClient } from '../schemas/sync-client.interface.js'
+import type { SyncPathDto, SyncPathUpdateDto } from '../dtos/sync-path.dto.js'
+import { ExistingSyncPathDto, SyncDBProps, SyncPathsDiff, SyncPathSettings } from '../interfaces/sync-path.interface.js'
import { SYNC_PATH_TO_SPACE_SEGMENTS } from '../utils/routes.js'
import { SyncQueries } from './sync-queries.service.js'
@@ -40,7 +40,7 @@ export class SyncPathsManager {
}
// Check DB path
- const syncDBProps: SyncDBProps = await this.getDBProps(req.space)
+ const syncDBProps: SyncDBProps = (await this.getDBProps(req.space))!
if (!(await isPathExists(req.space.realPath))) {
throw new HttpException(`Remote path not found : ${syncPathDto.remotePath}`, HttpStatus.NOT_FOUND)
@@ -48,7 +48,7 @@ export class SyncPathsManager {
if (!(await isPathIsDir(req.space.realPath))) {
throw new HttpException('Remote path must be a directory', HttpStatus.BAD_REQUEST)
}
- const client: SyncClient = await this.syncQueries.getClient(req.user.clientId, req.user.id)
+ const client = await this.syncQueries.getClient(req.user.clientId, req.user.id)
if (!client) {
throw new HttpException('Client not found', HttpStatus.NOT_FOUND)
}
@@ -59,7 +59,8 @@ export class SyncPathsManager {
syncPathDto.permissions = getEnvPermissions(req.space, req.space.root)
// Backward compatibility: clients predating this setting omit it.
syncPathDto.ignoreDelete = syncPathDto.ignoreDelete === true
- const pathId = await this.syncQueries.createPath(client.id, syncDBProps, syncPathDto)
+ const syncPathSettings = { ...syncPathDto, id: syncPathDto.id ?? undefined } satisfies SyncPathSettings
+ const pathId = await this.syncQueries.createPath(client.id, syncDBProps, syncPathSettings)
return { id: pathId, permissions: syncPathDto.permissions }
}
@@ -74,7 +75,7 @@ export class SyncPathsManager {
try {
await this.syncQueries.deletePath(clientId, pathId)
} catch (e) {
- this.logger.error({ tag: this.deletePath.name, msg: `${e}` })
+ this.logger.error({ tag: this.deletePath.name, msg: toErrorMessage(e) })
throw new HttpException('Unable to remove path', HttpStatus.BAD_REQUEST)
}
}
@@ -83,7 +84,7 @@ export class SyncPathsManager {
if (!(await this.syncQueries.clientExistsForOwner(user.id, clientId))) {
throw new HttpException('You are not allowed to do this action', HttpStatus.FORBIDDEN)
}
- const syncPathSettings: SyncPathSettings = await this.syncQueries.getPathSettings(clientId, pathId)
+ const syncPathSettings = await this.syncQueries.getPathSettings(clientId, pathId)
if (!syncPathSettings) {
throw new HttpException('Sync path not found', HttpStatus.NOT_FOUND)
}
@@ -100,7 +101,7 @@ export class SyncPathsManager {
try {
await this.syncQueries.updatePathSettings(clientId, pathId, syncPathSettings)
} catch (e) {
- this.logger.error({ tag: this.updatePath.name, msg: `${e}` })
+ this.logger.error({ tag: this.updatePath.name, msg: toErrorMessage(e) })
throw new HttpException('Unable to update path', HttpStatus.INTERNAL_SERVER_ERROR)
} finally {
// clear cache
@@ -109,14 +110,7 @@ export class SyncPathsManager {
return syncPathSettings
}
- async updatePaths(
- user: UserModel,
- syncPathsDto: SyncPathDto[]
- ): Promise<{
- add: SyncPathSettings[]
- update: Partial<Record<keyof SyncPathSettings, any>>[]
- delete: number[]
- }> {
+ async updatePaths(user: UserModel, syncPathsDto: ExistingSyncPathDto[]): Promise<SyncPathsDiff> {
/* Update the client or server paths */
if (!user.clientId) {
throw new HttpException('Client id is missing', HttpStatus.BAD_REQUEST)
@@ -125,9 +119,15 @@ export class SyncPathsManager {
throw new HttpException('You are not allowed to do this action', HttpStatus.FORBIDDEN)
}
const clientPathIds: number[] = syncPathsDto.map((p) => p.id)
- const serverPathIds: number[] = []
+ const clientPathsById = new Map<number, ExistingSyncPathDto>()
+ for (const clientPath of syncPathsDto) {
+ if (!clientPathsById.has(clientPath.id)) {
+ clientPathsById.set(clientPath.id, clientPath)
+ }
+ }
+ const serverPathIds = new Set<number>()
- const clientDiff: { add: SyncPathSettings[]; update: Partial<Record<keyof SyncPathSettings, any>>[]; delete: number[] } = {
+ const clientDiff: SyncPathsDiff = {
add: [],
update: [],
delete: []
@@ -138,25 +138,25 @@ export class SyncPathsManager {
// unable to determine path, will be stored as deleted
continue
}
- let space: SpaceEnv
+ let space: SpaceEnv | null
try {
space = await this.spacesManager.spaceEnv(user, SYNC_PATH_TO_SPACE_SEGMENTS(serverPath.remotePath), true)
} catch (e) {
- throw new HttpException(e.message, HttpStatus.BAD_REQUEST)
+ throw new HttpException(toErrorMessage(e), HttpStatus.BAD_REQUEST)
}
if (!space) {
// removed or inaccessible space, the path will be stored as deleted
continue
}
- serverPathIds.push(serverPath.id)
- if (clientPathIds.indexOf(serverPath.id) === -1) {
+ serverPathIds.add(serverPath.id)
+ const clientPath = clientPathsById.get(serverPath.id)
+ if (!clientPath) {
// path exists on server but not on client, add it to client
clientDiff.add.push({ ...serverPath.settings, id: serverPath.id, remotePath: serverPath.remotePath, permissions: space.envPermissions })
continue
}
// path exists on both server and client side
- const clientPath: SyncPathDto = syncPathsDto.find((p) => p.id === serverPath.id)
// remotePath and permissions settings are only managed by server
const updateClientInfo: { remotePath?: string; permissions?: string } = {
...(serverPath.remotePath !== clientPath.remotePath && { remotePath: serverPath.remotePath }),
@@ -177,13 +177,13 @@ export class SyncPathsManager {
...updateClientInfo
}
} else if (serverNewer) {
- clientDiff.update.push({ id: clientPath.id, ...serverPath.settings, ...updateClientInfo })
+ clientDiff.update.push({ ...serverPath.settings, ...updateClientInfo, id: clientPath.id })
}
if (clientNewer || hasUpdates || serverPath.settings.lastSync !== clientPath.lastSync) {
this.syncQueries
.updatePathSettings(user.clientId, clientPath.id, { ...updatedSettings, lastSync: clientPath.lastSync })
- .catch((e: Error) => this.logger.error({ tag: this.updatePaths.name, msg: `${e}` }))
+ .catch((e: Error) => this.logger.error({ tag: this.updatePaths.name, msg: toErrorMessage(e) }))
}
if (!clientNewer && hasUpdates) {
@@ -191,17 +191,21 @@ export class SyncPathsManager {
}
}
// path does not exist on server side
- clientDiff.delete = clientPathIds.filter((cid) => serverPathIds.indexOf(cid) === -1)
+ clientDiff.delete = clientPathIds.filter((cid) => !serverPathIds.has(cid))
for (const cPathId of clientDiff.delete) {
- const cPath: SyncPathDto = syncPathsDto.find((p) => p.id === cPathId)
- this.notify(user.id, ACTION.DELETE, cPath.remotePath).catch((e: Error) => this.logger.error({ tag: this.updatePaths.name, msg: `${e}` }))
+ const cPath = clientPathsById.get(cPathId)!
+ this.notify(user.id, ACTION.DELETE, cPath.remotePath).catch((e: Error) =>
+ this.logger.error({ tag: this.updatePaths.name, msg: toErrorMessage(e) })
+ )
}
// clear cache
- clientDiff.update.forEach((path) => this.syncQueries.clearCachePathSettings(user.clientId, path.id))
+ for (const path of clientDiff.update) {
+ this.syncQueries.clearCachePathSettings(user.clientId, path.id)
+ }
return clientDiff
}
- private async getDBProps(space: SpaceEnv): Promise<SyncDBProps> {
+ private async getDBProps(space: SpaceEnv): Promise<SyncDBProps | undefined> {
if (space.inSharesList) {
throw new HttpException('Syncing all shares is not supported. Please select a subdirectory', HttpStatus.BAD_REQUEST)
} else if (space.inPersonalSpace) {
@@ -231,20 +235,22 @@ export class SyncPathsManager {
private async getOrCreateFileId(space: SpaceEnv): Promise<number> {
const fileProps: FileProps = await getProps(space.realPath, space.dbFile.path)
- return this.filesQueries.getOrCreateSpaceFile(fileProps.id, { ...fileProps, id: undefined }, space.dbFile)
+ return this.filesQueries.getOrCreateSpaceFile(fileProps.id!, { ...fileProps, id: undefined }, space.dbFile)
}
- private async notify(userId: number, action: ACTION, remotePath: string) {
+ private async notify(userId: number, action: ACTION.DELETE, remotePath: string) {
const notification: NotificationContent = {
app: NOTIFICATION_APP.SYNC,
event: NOTIFICATION_APP_EVENT.SYNC[action],
element: remotePath,
- url: [...SYNC_PATH_REPOSITORY[remotePath.split('/').at(0)], ...remotePath.split('/').slice(1, -1)].join('/')
+ url: [...SYNC_PATH_REPOSITORY[remotePath.split('/').at(0) as keyof typeof SYNC_PATH_REPOSITORY], ...remotePath.split('/').slice(1, -1)].join(
+ '/'
+ )
}
this.notificationsManager
.create([userId], notification, {
action: action
})
- .catch((e: Error) => this.logger.error({ tag: this.notify.name, msg: `${e}` }))
+ .catch((e: Error) => this.logger.error({ tag: this.notify.name, msg: toErrorMessage(e) }))
}
}
diff --git a/backend/src/applications/sync/services/sync-queries.service.ts b/backend/src/applications/sync/services/sync-queries.service.ts
index d054b66a..2f0d4bce 100644
--- a/backend/src/applications/sync/services/sync-queries.service.ts
+++ b/backend/src/applications/sync/services/sync-queries.service.ts
@@ -19,9 +19,9 @@ import { SYNC_REPOSITORY } from '../constants/sync.js'
import { SyncClientPaths } from '../interfaces/sync-client-paths.interface.js'
import { SyncClientInfo } from '../interfaces/sync-client.interface.js'
import { SyncDBProps, SyncPathSettings } from '../interfaces/sync-path.interface.js'
-import { SyncClient } from '../schemas/sync-client.interface.js'
+import type { SyncClient } from '../schemas/sync-client.interface.js'
import { syncClients } from '../schemas/sync-clients.schema.js'
-import { SyncPath } from '../schemas/sync-path.interface.js'
+import type { SyncPath } from '../schemas/sync-path.interface.js'
import { syncPaths } from '../schemas/sync-paths.schema.js'
@Injectable()
@@ -79,7 +79,7 @@ export class SyncQueries {
}
}
- async getClient(clientId: string, ownerId?: number, token?: string): Promise<SyncClient> {
+ async getClient(clientId: string, ownerId?: number, token?: string): Promise<SyncClient | undefined> {
const where: SQL[] = [
eq(syncClients.id, clientId),
...(ownerId ? [eq(syncClients.ownerId, ownerId)] : []),
@@ -210,7 +210,7 @@ export class SyncQueries {
}
@CacheDecorator(900)
- async getPathSettings(clientId: string, pathId: number): Promise<SyncPathSettings> {
+ async getPathSettings(clientId: string, pathId: number): Promise<SyncPathSettings | null> {
const [path] = await this.db
.select({
settings: syncPaths.settings
diff --git a/backend/src/applications/sync/sync.config.ts b/backend/src/applications/sync/sync.config.ts
index d44fce51..9f973832 100644
--- a/backend/src/applications/sync/sync.config.ts
+++ b/backend/src/applications/sync/sync.config.ts
@@ -1,7 +1,4 @@
-import { IsEnum } from 'class-validator'
+import { z } from 'zod'
import { APP_STORE_REPOSITORY } from './constants/store.js'
-export class AppStoreConfig {
- @IsEnum(APP_STORE_REPOSITORY)
- repository: APP_STORE_REPOSITORY = APP_STORE_REPOSITORY.PUBLIC
-}
+export const AppStoreConfigSchema = z.looseObject({ repository: z.enum(APP_STORE_REPOSITORY).default(APP_STORE_REPOSITORY.PUBLIC) })
diff --git a/backend/src/applications/sync/sync.controller.ts b/backend/src/applications/sync/sync.controller.ts
index 76ceb3e0..a75c3b74 100644
--- a/backend/src/applications/sync/sync.controller.ts
+++ b/backend/src/applications/sync/sync.controller.ts
@@ -9,8 +9,6 @@ import {
HttpStatus,
Move,
Param,
- ParseArrayPipe,
- ParseIntPipe,
Post,
Proppatch,
Put,
@@ -25,6 +23,7 @@ import { type FastifyReply, type FastifyRequest } from 'fastify'
import { AuthTokenSkip } from '../../authentication/decorators/auth-token-skip.decorator.js'
import { AuthRateLimitGuard } from '../../authentication/guards/auth-rate-limit.guard.js'
import { type FastifyAuthenticatedRequest } from '../../authentication/interfaces/auth-request.interface.js'
+import { integerFromStringSchema } from '../../configuration/config.schema.js'
import { SkipSpacePermissionsCheck } from '../spaces/decorators/space-skip-permissions.decorator.js'
import { type FastifySpaceRequest } from '../spaces/interfaces/space-request.interface.js'
import { USER_PERMISSION } from '../users/constants/user.js'
@@ -36,19 +35,34 @@ import { CLIENT_AUTH_TYPE } from './constants/auth.js'
import { SYNC_ROUTE } from './constants/routes.js'
import { CHECK_SERVER_RESP, SYNC_IN_SERVER_AGENT } from './constants/sync.js'
import { SyncEnvironment } from './decorators/sync-environment.decorator.js'
-import { SyncClientAuthDto } from './dtos/sync-client-auth.dto.js'
-import { SyncClientAuthRegistrationDto, SyncClientRegistrationDto } from './dtos/sync-client-registration.dto.js'
-import { SyncCopyMoveDto, SyncDiffDto, SyncMakeDto, SyncPropsDto } from './dtos/sync-operations.dto.js'
-import { SyncPathDto, SyncPathUpdateDto } from './dtos/sync-path.dto.js'
-import { SyncUploadDto } from './dtos/sync-upload.dto.js'
+import { type SyncClientAuthDto, syncClientAuthSchema } from './dtos/sync-client-auth.dto.js'
+import {
+ type SyncClientAuthRegistrationDto,
+ syncClientAuthRegistrationSchema,
+ type SyncClientRegistrationDto,
+ syncClientRegistrationSchema
+} from './dtos/sync-client-registration.dto.js'
+import {
+ type SyncCopyMoveDto,
+ syncCopyMoveSchema,
+ type SyncDiffDto,
+ syncDiffSchema,
+ type SyncMakeDto,
+ syncMakeSchema,
+ type SyncPropsDto,
+ syncPropsSchema
+} from './dtos/sync-operations.dto.js'
+import { type SyncPathDto, syncPathSchema, syncPathsSchema, type SyncPathUpdateDto, syncPathUpdateSchema } from './dtos/sync-path.dto.js'
+import { type SyncUploadDto, syncUploadSchema } from './dtos/sync-upload.dto.js'
import { SyncDiffGzipBodyInterceptor } from './interceptors/sync-diff-gzip-body.interceptor.js'
import { AppStoreManifest } from './interfaces/store-manifest.interface.js'
import { SyncClientAuthCookie, SyncClientAuthRegistration, SyncClientAuthToken } from './interfaces/sync-client-auth.interface.js'
import { SyncClientPaths } from './interfaces/sync-client-paths.interface.js'
-import { SyncPathSettings } from './interfaces/sync-path.interface.js'
+import { ExistingSyncPathDto, SyncPathsDiff, SyncPathSettings } from './interfaces/sync-path.interface.js'
import { SyncClientsManager } from './services/sync-clients-manager.service.js'
import { SyncManager } from './services/sync-manager.service.js'
import { SyncPathsManager } from './services/sync-paths-manager.service.js'
+import { clientAuthTypeParameterSchema, clientIdParameterSchema } from './sync.schema.js'
@Controller(SYNC_ROUTE.BASE)
export class SyncController {
@@ -63,7 +77,7 @@ export class SyncController {
@Get(SYNC_ROUTE.HANDSHAKE)
@AuthTokenSkip()
handshake(@Req() req: FastifyRequest) {
- if ('user-agent' in req.headers && req.headers['user-agent'].startsWith(SYNC_IN_SERVER_AGENT)) {
+ if ('user-agent' in req.headers && (req.headers['user-agent'] as string).startsWith(SYNC_IN_SERVER_AGENT)) {
return CHECK_SERVER_RESP
}
throw new HttpException('Server not found', HttpStatus.NOT_FOUND)
@@ -73,7 +87,10 @@ export class SyncController {
@Header('Cache-Control', 'no-store')
@AuthTokenSkip()
@UseGuards(AuthRateLimitGuard)
- register(@Body() syncClientRegistrationDto: SyncClientRegistrationDto, @Req() req: FastifyRequest): Promise<SyncClientAuthRegistration> {
+ register(
+ @Body({ schema: syncClientRegistrationSchema }) syncClientRegistrationDto: SyncClientRegistrationDto,
+ @Req() req: FastifyRequest
+ ): Promise<SyncClientAuthRegistration> {
return this.syncClientsManager.register(syncClientRegistrationDto, req.ip)
}
@@ -82,7 +99,7 @@ export class SyncController {
@UserHavePermission(USER_PERMISSION.DESKTOP_APP)
@UseGuards(UserPermissionsGuard)
registerWithAuth(
- @Body() clientAuthenticatedRegistrationDto: SyncClientAuthRegistrationDto,
+ @Body({ schema: syncClientAuthRegistrationSchema }) clientAuthenticatedRegistrationDto: SyncClientAuthRegistrationDto,
@Req() req: FastifyAuthenticatedRequest
): Promise<SyncClientAuthRegistration> {
return this.syncClientsManager.registerWithAuth(clientAuthenticatedRegistrationDto, req)
@@ -97,7 +114,7 @@ export class SyncController {
@Get(SYNC_ROUTE.APP_STORE)
@AuthTokenSkip()
- checkAppStore(): Promise<AppStoreManifest> {
+ checkAppStore(): Promise<AppStoreManifest | null> {
// This route must be public to allow clients to receive updates
return this.syncClientsManager.checkAppStore()
}
@@ -107,8 +124,8 @@ export class SyncController {
@AuthTokenSkip()
@UseGuards(AuthRateLimitGuard)
authenticate(
- @Param('type') type: CLIENT_AUTH_TYPE,
- @Body() clientAuthDto: SyncClientAuthDto,
+ @Param('type', { schema: clientAuthTypeParameterSchema }) type: CLIENT_AUTH_TYPE,
+ @Body({ schema: syncClientAuthSchema }) clientAuthDto: SyncClientAuthDto,
@Req() req: FastifyRequest,
@Res({ passthrough: true }) res: FastifyReply
): Promise<SyncClientAuthCookie | SyncClientAuthToken> {
@@ -125,7 +142,7 @@ export class SyncController {
@Delete(`${SYNC_ROUTE.CLIENTS}/:id`)
@UserHavePermission(USER_PERMISSION.DESKTOP_APP)
@UseGuards(UserPermissionsGuard)
- deleteClient(@GetUser() user: UserModel, @Param('id') clientId: string): Promise<void> {
+ deleteClient(@GetUser() user: UserModel, @Param('id', { schema: clientIdParameterSchema }) clientId: string): Promise<void> {
return this.syncClientsManager.deleteClient(user, clientId)
}
@@ -134,7 +151,11 @@ export class SyncController {
@Delete(`${SYNC_ROUTE.CLIENTS}/:id/${SYNC_ROUTE.PATHS}/:pathId`)
@UserHavePermission(USER_PERMISSION.DESKTOP_APP_SYNC)
@UseGuards(UserPermissionsGuard)
- deleteClientPath(@GetUser() user: UserModel, @Param('id') clientId: string, @Param('pathId', ParseIntPipe) pathId: number): Promise<void> {
+ deleteClientPath(
+ @GetUser() user: UserModel,
+ @Param('id', { schema: clientIdParameterSchema }) clientId: string,
+ @Param('pathId', { schema: integerFromStringSchema }) pathId: number
+ ): Promise<void> {
return this.syncPathsManager.deletePath(user, pathId, clientId)
}
@@ -143,9 +164,9 @@ export class SyncController {
@UseGuards(UserPermissionsGuard)
updatePath(
@GetUser() user: UserModel,
- @Param('id') clientId: string,
- @Param('pathId', ParseIntPipe) pathId: number,
- @Body() syncPathUpdateDto: SyncPathUpdateDto
+ @Param('id', { schema: clientIdParameterSchema }) clientId: string,
+ @Param('pathId', { schema: integerFromStringSchema }) pathId: number,
+ @Body({ schema: syncPathUpdateSchema }) syncPathUpdateDto: SyncPathUpdateDto
): Promise<SyncPathSettings> {
return this.syncPathsManager.updatePath(user, clientId, pathId, syncPathUpdateDto)
}
@@ -155,7 +176,7 @@ export class SyncController {
@SyncEnvironment()
createPath(
@Req() req: FastifySpaceRequest,
- @Body() syncPathDto: SyncPathDto
+ @Body({ schema: syncPathSchema }) syncPathDto: SyncPathDto
): Promise<{
id: number
permissions: string
@@ -166,21 +187,14 @@ export class SyncController {
@Delete(`${SYNC_ROUTE.PATHS}/:id`)
@UserHavePermission(USER_PERMISSION.DESKTOP_APP_SYNC)
@UseGuards(UserPermissionsGuard)
- deletePath(@GetUser() user: UserModel, @Param('id', ParseIntPipe) pathId: number): Promise<void> {
+ deletePath(@GetUser() user: UserModel, @Param('id', { schema: integerFromStringSchema }) pathId: number): Promise<void> {
return this.syncPathsManager.deletePath(user, pathId)
}
@Put(SYNC_ROUTE.PATHS)
@UserHavePermission(USER_PERMISSION.DESKTOP_APP_SYNC)
@UseGuards(UserPermissionsGuard)
- updatePaths(
- @GetUser() user: UserModel,
- @Body(new ParseArrayPipe({ items: SyncPathDto, whitelist: true })) syncPathsDto: SyncPathDto[]
- ): Promise<{
- add: SyncPathSettings[]
- update: Partial<Record<keyof SyncPathSettings, any>>[]
- delete: number[]
- }> {
+ updatePaths(@GetUser() user: UserModel, @Body({ schema: syncPathsSchema }) syncPathsDto: ExistingSyncPathDto[]): Promise<SyncPathsDiff> {
return this.syncPathsManager.updatePaths(user, syncPathsDto)
}
@@ -192,8 +206,8 @@ export class SyncController {
@UseInterceptors(SyncDiffGzipBodyInterceptor)
diff(
@GetUser() user: UserModel,
- @Param('id', ParseIntPipe) pathId: number,
- @Body() syncDiffDto: SyncDiffDto,
+ @Param('id', { schema: integerFromStringSchema }) pathId: number,
+ @Body({ schema: syncDiffSchema }) syncDiffDto: SyncDiffDto,
@Res({ passthrough: true }) res: FastifyReply
): Promise<void> {
return this.syncManager.diff(user, pathId, syncDiffDto, res)
@@ -207,37 +221,40 @@ export class SyncController {
@Post(`${SYNC_ROUTE.OPERATION}/*`)
@SyncEnvironment()
- uploadCreate(@Req() req: FastifySpaceRequest, @Query() syncUploadDto: SyncUploadDto): Promise<{ ino: number }> {
+ uploadCreate(@Req() req: FastifySpaceRequest, @Query({ schema: syncUploadSchema }) syncUploadDto: SyncUploadDto): Promise<{ ino: number }> {
return this.syncManager.upload(req, syncUploadDto)
}
@Put(`${SYNC_ROUTE.OPERATION}/*`)
@SyncEnvironment()
- uploadOverwrite(@Req() req: FastifySpaceRequest, @Query() syncUploadDto: SyncUploadDto): Promise<{ ino: number }> {
+ uploadOverwrite(@Req() req: FastifySpaceRequest, @Query({ schema: syncUploadSchema }) syncUploadDto: SyncUploadDto): Promise<{ ino: number }> {
return this.syncManager.upload(req, syncUploadDto)
}
@Post(`${SYNC_ROUTE.OPERATION}/${SYNC_ROUTE.MAKE}/*`)
@SyncEnvironment()
- make(@Req() req: FastifySpaceRequest, @Body() syncMakeDto: SyncMakeDto): Promise<{ ino: number }> {
+ make(@Req() req: FastifySpaceRequest, @Body({ schema: syncMakeSchema }) syncMakeDto: SyncMakeDto): Promise<{ ino: number }> {
return this.syncManager.make(req, syncMakeDto)
}
@Proppatch(`${SYNC_ROUTE.OPERATION}/*`)
@SyncEnvironment()
- props(@Req() req: FastifySpaceRequest, @Body() syncPropsDto: SyncPropsDto): Promise<void> {
+ props(@Req() req: FastifySpaceRequest, @Body({ schema: syncPropsSchema }) syncPropsDto: SyncPropsDto): Promise<void> {
return this.syncManager.props(req, syncPropsDto)
}
@Move(`${SYNC_ROUTE.OPERATION}/*`)
@SyncEnvironment()
- move(@Req() req: FastifySpaceRequest, @Body() syncCopyMoveDto: SyncCopyMoveDto): Promise<void> {
+ move(@Req() req: FastifySpaceRequest, @Body({ schema: syncCopyMoveSchema }) syncCopyMoveDto: SyncCopyMoveDto): Promise<void> {
return this.syncManager.copyMove(req, syncCopyMoveDto, true)
}
@Copy(`${SYNC_ROUTE.OPERATION}/*`)
@SyncEnvironment()
- copy(@Req() req: FastifySpaceRequest, @Body() syncCopyMoveDto: SyncCopyMoveDto): Promise<{ ino: number; mtime: number }> {
+ copy(
+ @Req() req: FastifySpaceRequest,
+ @Body({ schema: syncCopyMoveSchema }) syncCopyMoveDto: SyncCopyMoveDto
+ ): Promise<{ ino: number; mtime: number }> {
return this.syncManager.copyMove(req, syncCopyMoveDto, false)
}
diff --git a/backend/src/applications/sync/sync.schema.ts b/backend/src/applications/sync/sync.schema.ts
new file mode 100644
index 00000000..b3e727d1
--- /dev/null
+++ b/backend/src/applications/sync/sync.schema.ts
@@ -0,0 +1,5 @@
+import { z } from 'zod'
+import { CLIENT_AUTH_TYPE } from './constants/auth.js'
+
+export const clientAuthTypeParameterSchema = z.enum(CLIENT_AUTH_TYPE)
+export const clientIdParameterSchema = z.string()
diff --git a/backend/src/applications/sync/utils/routes.ts b/backend/src/applications/sync/utils/routes.ts
index 744c434d..8c84a72d 100644
--- a/backend/src/applications/sync/utils/routes.ts
+++ b/backend/src/applications/sync/utils/routes.ts
@@ -4,9 +4,9 @@ import { SYNC_PATH_REPOSITORY } from '../constants/sync.js'
export function SYNC_PATH_TO_SPACE_SEGMENTS(path: string): string[] {
const urlSegments = PATH_TO_SPACE_SEGMENTS(path)
const repository = urlSegments.shift()
- if (!(repository in SYNC_PATH_REPOSITORY)) {
+ if (!((repository as string) in SYNC_PATH_REPOSITORY)) {
throw new Error(`Repository not found : ${repository}`)
}
- urlSegments.unshift(...SYNC_PATH_REPOSITORY[repository])
+ urlSegments.unshift(...SYNC_PATH_REPOSITORY[repository as keyof typeof SYNC_PATH_REPOSITORY])
return urlSegments
}
diff --git a/backend/src/applications/users/admin-users.controller.ts b/backend/src/applications/users/admin-users.controller.ts
index 479c3091..74d69ba1 100644
--- a/backend/src/applications/users/admin-users.controller.ts
+++ b/backend/src/applications/users/admin-users.controller.ts
@@ -1,19 +1,27 @@
-import { Body, Controller, Delete, Get, Param, ParseIntPipe, Patch, Post, Put, Res, Search, UseGuards } from '@nestjs/common'
+import { Body, Controller, Delete, Get, Param, Patch, Post, Put, Res, Search, UseGuards } from '@nestjs/common'
import { type FastifyReply } from 'fastify'
import { LoginResponseDto } from '../../authentication/dto/login-response.dto.js'
import {
AuthTwoFaVerificationGuard,
AuthTwoFaVerificationWithoutPasswordGuard
} from '../../authentication/providers/two-fa/guards/auth-two-fa-verification.guard.js'
+import { integerFromStringSchema } from '../../configuration/config.schema.js'
import { GROUP_TYPE } from './constants/group.js'
import { ADMIN_USERS_ROUTE } from './constants/routes.js'
import { USER_ROLE } from './constants/user.js'
import { UserHaveRole } from './decorators/roles.decorator.js'
import { GetUser } from './decorators/user.decorator.js'
-import { CreateOrUpdateGroupDto } from './dto/create-or-update-group.dto.js'
-import { CreateUserDto, UpdateUserDto, UpdateUserFromGroupDto } from './dto/create-or-update-user.dto.js'
-import { DeleteUserDto } from './dto/delete-user.dto.js'
-import { SearchMembersDto } from './dto/search-members.dto.js'
+import { type CreateOrUpdateGroupDto, createOrUpdateGroupSchema, userIdsSchema } from './dto/create-or-update-group.dto.js'
+import {
+ type CreateUserDto,
+ createUserSchema,
+ type UpdateUserDto,
+ type UpdateUserFromGroupDto,
+ updateUserFromGroupSchema,
+ updateUserSchema
+} from './dto/create-or-update-user.dto.js'
+import { type DeleteUserDto, deleteUserSchema } from './dto/delete-user.dto.js'
+import { searchMembersSchema, type ValidatedSearchMembersDto } from './dto/search-members.dto.js'
import { UserRolesGuard } from './guards/roles.guard.js'
import { AdminGroup } from './interfaces/admin-group.interface.js'
import { AdminUser } from './interfaces/admin-user.interface.js'
@@ -22,6 +30,7 @@ import { GuestUser } from './interfaces/guest-user.interface.js'
import { Member } from './interfaces/member.interface.js'
import { UserModel } from './models/user.model.js'
import { AdminUsersManager } from './services/admin-users-manager.service.js'
+import { optionalGroupNameParameterSchema } from './users.schema.js'
@Controller(ADMIN_USERS_ROUTE.BASE)
@UserHaveRole(USER_ROLE.ADMINISTRATOR)
@@ -35,110 +44,124 @@ export class AdminUsersController {
}
@Get(`${ADMIN_USERS_ROUTE.USERS}/:id`)
- getUser(@Param('id', ParseIntPipe) userId: number): Promise<AdminUser> {
+ getUser(@Param('id', { schema: integerFromStringSchema }) userId: number): Promise<AdminUser> {
return this.adminUsersManager.getUser(userId)
}
@Post(ADMIN_USERS_ROUTE.USERS)
@UseGuards(AuthTwoFaVerificationWithoutPasswordGuard)
- createUser(@Body() createUserDto: CreateUserDto): Promise<AdminUser> {
- return this.adminUsersManager.createUserOrGuest(
- createUserDto,
- typeof createUserDto?.role !== 'undefined' ? createUserDto.role : USER_ROLE.USER,
- true
- )
+ createUser(@Body({ schema: createUserSchema }) createUserDto: CreateUserDto): Promise<AdminUser> {
+ return this.adminUsersManager.createUserOrGuest(createUserDto, createUserDto.role ?? USER_ROLE.USER, true)
}
@Put(`${ADMIN_USERS_ROUTE.USERS}/:id`)
@UseGuards(AuthTwoFaVerificationWithoutPasswordGuard)
- updateUser(@Param('id', ParseIntPipe) userId: number, @Body() updateUserDto: UpdateUserDto): Promise<AdminUser> {
+ updateUser(
+ @Param('id', { schema: integerFromStringSchema }) userId: number,
+ @Body({ schema: updateUserSchema }) updateUserDto: UpdateUserDto
+ ): Promise<AdminUser> {
return this.adminUsersManager.updateUserOrGuest(userId, updateUserDto)
}
@Delete(`${ADMIN_USERS_ROUTE.USERS}/:id`)
@UseGuards(AuthTwoFaVerificationGuard)
- deleteUser(@Param('id', ParseIntPipe) userId: number, @Body() deleteUserDto: DeleteUserDto): Promise<void> {
+ deleteUser(
+ @Param('id', { schema: integerFromStringSchema }) userId: number,
+ @Body({ schema: deleteUserSchema }) deleteUserDto: DeleteUserDto
+ ): Promise<void> {
return this.adminUsersManager.deleteUserFromAdmin(userId, deleteUserDto)
}
@Get(`${ADMIN_USERS_ROUTE.GUESTS}/${ADMIN_USERS_ROUTE.LIST}`)
- listGuests(): Promise<AdminUser[]> {
+ listGuests(): Promise<GuestUser[]> {
return this.adminUsersManager.listGuests()
}
@Get(`${ADMIN_USERS_ROUTE.GUESTS}/:id`)
- getGuest(@Param('id', ParseIntPipe) guestId: number): Promise<AdminUser> {
+ getGuest(@Param('id', { schema: integerFromStringSchema }) guestId: number): Promise<GuestUser> {
return this.adminUsersManager.getGuest(guestId)
}
@Post(ADMIN_USERS_ROUTE.GUESTS)
@UseGuards(AuthTwoFaVerificationWithoutPasswordGuard)
- createGuest(@GetUser() user: UserModel, @Body() createGuestDto: CreateUserDto): Promise<GuestUser> {
+ createGuest(@GetUser() user: UserModel, @Body({ schema: createUserSchema }) createGuestDto: CreateUserDto): Promise<GuestUser> {
return this.adminUsersManager.createGuest(user, createGuestDto)
}
@Put(`${ADMIN_USERS_ROUTE.GUESTS}/:id`)
@UseGuards(AuthTwoFaVerificationWithoutPasswordGuard)
- updateGuest(@Param('id', ParseIntPipe) guestId: number, @Body() updateGuestDto: UpdateUserDto): Promise<GuestUser> {
+ updateGuest(
+ @Param('id', { schema: integerFromStringSchema }) guestId: number,
+ @Body({ schema: updateUserSchema }) updateGuestDto: UpdateUserDto
+ ): Promise<GuestUser> {
return this.adminUsersManager.updateGuest(guestId, updateGuestDto)
}
@Delete(`${ADMIN_USERS_ROUTE.GUESTS}/:id`)
@UseGuards(AuthTwoFaVerificationGuard)
- deleteGuest(@Param('id', ParseIntPipe) guestId: number): Promise<void> {
+ deleteGuest(@Param('id', { schema: integerFromStringSchema }) guestId: number): Promise<void> {
return this.adminUsersManager.deleteGuestFromAdmin(guestId)
}
@Search(ADMIN_USERS_ROUTE.MEMBERS)
- searchMembers(@Body() searchMembersDto: SearchMembersDto): Promise<Member[]> {
+ searchMembers(@Body({ schema: searchMembersSchema }) searchMembersDto: ValidatedSearchMembersDto): Promise<Member[]> {
return this.adminUsersManager.searchMembers(searchMembersDto)
}
@Get(`${ADMIN_USERS_ROUTE.GROUPS}/${ADMIN_USERS_ROUTE.BROWSE}/:name?`)
- browseGroups(@Param('name') name?: string): Promise<GroupBrowse> {
+ browseGroups(@Param('name', { schema: optionalGroupNameParameterSchema }) name?: string): Promise<GroupBrowse> {
return this.adminUsersManager.browseGroups(name)
}
@Get(`${ADMIN_USERS_ROUTE.PGROUPS}/${ADMIN_USERS_ROUTE.BROWSE}/:name?`)
- browsePersonalGroups(@Param('name') name?: string): Promise<GroupBrowse> {
+ browsePersonalGroups(@Param('name', { schema: optionalGroupNameParameterSchema }) name?: string): Promise<GroupBrowse> {
return this.adminUsersManager.browseGroups(name, GROUP_TYPE.PERSONAL)
}
@Get(`${ADMIN_USERS_ROUTE.GROUPS}/:id`)
- getGroup(@Param('id', ParseIntPipe) groupId: number): Promise<AdminGroup> {
+ getGroup(@Param('id', { schema: integerFromStringSchema }) groupId: number): Promise<AdminGroup> {
return this.adminUsersManager.getGroup(groupId)
}
@Post(`${ADMIN_USERS_ROUTE.GROUPS}`)
- createGroup(@Body() createGroupDto: CreateOrUpdateGroupDto): Promise<AdminGroup> {
+ createGroup(@Body({ schema: createOrUpdateGroupSchema }) createGroupDto: CreateOrUpdateGroupDto): Promise<AdminGroup> {
return this.adminUsersManager.createGroup(createGroupDto)
}
@Put(`${ADMIN_USERS_ROUTE.GROUPS}/:id`)
- updateGroup(@Param('id', ParseIntPipe) groupId: number, @Body() updateGroupDto: CreateOrUpdateGroupDto): Promise<AdminGroup> {
+ updateGroup(
+ @Param('id', { schema: integerFromStringSchema }) groupId: number,
+ @Body({ schema: createOrUpdateGroupSchema }) updateGroupDto: CreateOrUpdateGroupDto
+ ): Promise<AdminGroup> {
return this.adminUsersManager.updateGroup(groupId, updateGroupDto)
}
@Delete(`${ADMIN_USERS_ROUTE.GROUPS}/:id`)
- deleteGroup(@Param('id', ParseIntPipe) groupId: number): Promise<void> {
+ deleteGroup(@Param('id', { schema: integerFromStringSchema }) groupId: number): Promise<void> {
return this.adminUsersManager.deleteGroup(groupId)
}
@Patch(`${ADMIN_USERS_ROUTE.GROUPS}/:groupId/${ADMIN_USERS_ROUTE.USERS}`)
- addUsersToGroup(@Param('groupId', ParseIntPipe) groupId: number, @Body() userIds: number[]): Promise<void> {
+ addUsersToGroup(
+ @Param('groupId', { schema: integerFromStringSchema }) groupId: number,
+ @Body({ schema: userIdsSchema }) userIds: number[]
+ ): Promise<void> {
return this.adminUsersManager.addUsersToGroup(groupId, userIds)
}
@Delete(`${ADMIN_USERS_ROUTE.GROUPS}/:groupId/${ADMIN_USERS_ROUTE.USERS}/:userId`)
- removeUserFromGroup(@Param('groupId', ParseIntPipe) groupId: number, @Param('userId', ParseIntPipe) userId: number): Promise<void> {
+ removeUserFromGroup(
+ @Param('groupId', { schema: integerFromStringSchema }) groupId: number,
+ @Param('userId', { schema: integerFromStringSchema }) userId: number
+ ): Promise<void> {
return this.adminUsersManager.removeUserFromGroup(groupId, userId)
}
@Patch(`${ADMIN_USERS_ROUTE.GROUPS}/:groupId/${ADMIN_USERS_ROUTE.USERS}/:userId`)
updateUserFromGroup(
- @Param('groupId', ParseIntPipe) groupId: number,
- @Param('userId', ParseIntPipe) userId: number,
- @Body() updateUserFromGroupDto: UpdateUserFromGroupDto
+ @Param('groupId', { schema: integerFromStringSchema }) groupId: number,
+ @Param('userId', { schema: integerFromStringSchema }) userId: number,
+ @Body({ schema: updateUserFromGroupSchema }) updateUserFromGroupDto: UpdateUserFromGroupDto
): Promise<void> {
return this.adminUsersManager.updateUserFromGroup(groupId, userId, updateUserFromGroupDto)
}
@@ -147,7 +170,7 @@ export class AdminUsersController {
@UseGuards(AuthTwoFaVerificationGuard)
impersonateUser(
@GetUser() admin: UserModel,
- @Param('id', ParseIntPipe) userId: number,
+ @Param('id', { schema: integerFromStringSchema }) userId: number,
@Res({ passthrough: true }) res: FastifyReply
): Promise<LoginResponseDto> {
return this.adminUsersManager.impersonateUser(admin, userId, res)
diff --git a/backend/src/applications/users/constants/member.ts b/backend/src/applications/users/constants/member.ts
index f5651a30..82a297c2 100644
--- a/backend/src/applications/users/constants/member.ts
+++ b/backend/src/applications/users/constants/member.ts
@@ -7,9 +7,9 @@ export enum MEMBER_TYPE {
}
export const MEMBER_TYPE_REVERSE = {
- user: 'user',
- guest: 'guest',
- link: 'user',
- group: 'group',
- ['personal group']: 'personal group'
+ [MEMBER_TYPE.USER]: MEMBER_TYPE.USER,
+ [MEMBER_TYPE.GUEST]: MEMBER_TYPE.GUEST,
+ [MEMBER_TYPE.LINK]: MEMBER_TYPE.USER,
+ [MEMBER_TYPE.GROUP]: MEMBER_TYPE.GROUP,
+ [MEMBER_TYPE.PGROUP]: MEMBER_TYPE.PGROUP
}
diff --git a/backend/src/applications/users/dto/create-or-update-group.dto.ts b/backend/src/applications/users/dto/create-or-update-group.dto.ts
index f1b59035..9b9af9fe 100644
--- a/backend/src/applications/users/dto/create-or-update-group.dto.ts
+++ b/backend/src/applications/users/dto/create-or-update-group.dto.ts
@@ -1,30 +1,23 @@
-import { Transform } from 'class-transformer'
-import { IsEnum, IsInt, IsOptional, IsString, MinLength } from 'class-validator'
+import { z } from 'zod'
+import { integerNumberSchema } from '../../../configuration/config.schema.js'
import { sanitizeName } from '../../files/utils/files.js'
import { GROUP_VISIBILITY } from '../constants/group.js'
-export class UserCreateOrUpdateGroupDto {
- @IsOptional()
- @IsString()
- @Transform(({ value }) => (value ? sanitizeName(value.trim()) : ''))
- @MinLength(1)
- name?: string
+const optionalGroupNameSchema = z.string().trim().overwrite(sanitizeName).min(1).optional()
- @IsOptional()
- @IsString()
- description?: string
-}
+export const userCreateOrUpdateGroupSchema = z.object({
+ name: optionalGroupNameSchema,
+ description: z.string().nullish()
+})
-export class CreateOrUpdateGroupDto extends UserCreateOrUpdateGroupDto {
- @IsOptional()
- @IsEnum(GROUP_VISIBILITY)
- visibility?: GROUP_VISIBILITY
+export type UserCreateOrUpdateGroupDto = z.infer<typeof userCreateOrUpdateGroupSchema>
- @IsOptional()
- @IsString()
- permissions?: string
+export const createOrUpdateGroupSchema = userCreateOrUpdateGroupSchema.extend({
+ visibility: z.enum(GROUP_VISIBILITY).nullish(),
+ permissions: z.string().nullish(),
+ parentId: integerNumberSchema.nullish()
+})
- @IsOptional()
- @IsInt()
- parentId?: number
-}
+export type CreateOrUpdateGroupDto = z.infer<typeof createOrUpdateGroupSchema>
+
+export const userIdsSchema = z.array(integerNumberSchema)
diff --git a/backend/src/applications/users/dto/create-or-update-user.dto.spec.ts b/backend/src/applications/users/dto/create-or-update-user.dto.spec.ts
new file mode 100644
index 00000000..f8381720
--- /dev/null
+++ b/backend/src/applications/users/dto/create-or-update-user.dto.spec.ts
@@ -0,0 +1,59 @@
+import { createUserSchema, updateUserSchema } from './create-or-update-user.dto.js'
+
+describe('user schemas', () => {
+ it('normalizes null profile names to empty strings', () => {
+ const user = createUserSchema.parse({
+ login: 'user',
+ email: '[email protected]',
+ password: 'password',
+ firstName: null,
+ lastName: null
+ })
+
+ expect(user).toEqual(expect.objectContaining({ firstName: '', lastName: '' }))
+ expect(updateUserSchema.parse({ firstName: null, lastName: null })).toEqual({ firstName: '', lastName: '' })
+ })
+
+ it('keeps omitted profile names undefined', () => {
+ expect(updateUserSchema.parse({})).toEqual({})
+ })
+
+ it('accepts an omitted active state but rejects null', () => {
+ const input = {
+ login: 'user',
+ email: '[email protected]',
+ password: 'password',
+ firstName: 'User'
+ }
+
+ expect(createUserSchema.parse(input).isActive).toBeUndefined()
+ expect(createUserSchema.safeParse({ ...input, isActive: null }).success).toBe(false)
+ expect(updateUserSchema.safeParse({ isActive: null }).success).toBe(false)
+ })
+
+ it('accepts large integer quotas and member ids without changing their values', () => {
+ const largeInteger = 2 ** 53
+ const properties = { storageQuota: largeInteger, groups: [largeInteger], managers: [largeInteger] }
+ const user = createUserSchema.parse({
+ login: 'user',
+ email: '[email protected]',
+ password: 'password',
+ firstName: 'User',
+ ...properties
+ })
+
+ expect(user).toEqual(expect.objectContaining(properties))
+ expect(updateUserSchema.parse(properties)).toEqual(properties)
+ })
+
+ it.each([{ storageQuota: 1.5 }, { groups: [1.5] }, { managers: [1.5] }])('rejects fractional quotas and member ids: %j', (properties) => {
+ expect(updateUserSchema.safeParse(properties).success).toBe(false)
+ })
+
+ it('preserves null and omitted quotas and member lists', () => {
+ const properties = { storageQuota: null, groups: null, managers: null }
+
+ expect(updateUserSchema.parse(properties)).toEqual(properties)
+ expect(updateUserSchema.parse({})).toEqual({})
+ })
+})
diff --git a/backend/src/applications/users/dto/create-or-update-user.dto.ts b/backend/src/applications/users/dto/create-or-update-user.dto.ts
index a4f25264..1bc2ec69 100644
--- a/backend/src/applications/users/dto/create-or-update-user.dto.ts
+++ b/backend/src/applications/users/dto/create-or-update-user.dto.ts
@@ -1,109 +1,54 @@
-import { Transform } from 'class-transformer'
-import { IsArray, IsBoolean, IsEmail, IsEnum, IsInt, IsNotEmpty, IsOptional, IsString, Max, MaxLength, Min, MinLength } from 'class-validator'
+import { z } from 'zod'
+import { integerNumberSchema } from '../../../configuration/config.schema.js'
import { USER_GROUP_ROLE, USER_NOTIFICATION, USER_PASSWORD_MIN_LENGTH, USER_ROLE } from '../constants/user.js'
-import { IsUserLogin } from './user-login.dto.decorator.js'
-
-export class OptionalUserDto {
- @IsOptional()
- @IsString()
- @Transform(({ value }) => (value ? value.trim() : ''))
- @MaxLength(255)
- lastName?: string
-
- @IsOptional()
- @IsEnum(USER_ROLE)
- role?: USER_ROLE
-
- @IsOptional()
- @IsBoolean()
- isActive?: boolean
-
- @IsOptional()
- @IsString()
- language?: string
-
- @IsOptional()
- @IsEnum(USER_NOTIFICATION)
- notification?: USER_NOTIFICATION
-
- @IsOptional()
- @IsString()
- permissions?: string
-
- @IsOptional()
- @IsInt()
- storageQuota?: number
-
+import { userLoginSchema } from './user-login.schema.js'
+
+const trimmedStringSchema = z.string().trim()
+
+const loginSchema = trimmedStringSchema.pipe(userLoginSchema.min(2).max(255))
+const emailSchema = trimmedStringSchema.pipe(z.email({ pattern: z.regexes.html5Email }).min(2).max(254))
+const profileNameSchema = trimmedStringSchema
+ .max(255)
+ .nullable()
+ .transform((value) => value ?? '')
+
+export const optionalUserSchema = z.object({
+ lastName: profileNameSchema.optional(),
+ role: z.enum(USER_ROLE).nullish(),
+ isActive: z.boolean().optional(),
+ language: z.string().nullish(),
+ notification: z.enum(USER_NOTIFICATION).nullish(),
+ permissions: z.string().nullish(),
+ storageQuota: integerNumberSchema.nullish(),
// for users and guests
- @IsOptional()
- @IsArray()
- @IsInt({ each: true })
- groups?: number[]
-
+ groups: z.array(integerNumberSchema).nullish(),
// for guests
- @IsOptional()
- @IsArray()
- @IsInt({ each: true })
- managers?: number[]
-}
-
-export class CreateUserDto extends OptionalUserDto {
- @IsNotEmpty()
- @Transform(({ value }) => (value ? value.trim() : ''))
- @MinLength(2)
- @MaxLength(255)
- @IsUserLogin()
- login: string
-
- @IsNotEmpty()
- @Transform(({ value }) => (value ? value.trim() : ''))
- @IsEmail()
- @MinLength(2)
- @MaxLength(255)
- email: string
+ managers: z.array(integerNumberSchema).nullish()
+})
- @IsString()
- @MinLength(USER_PASSWORD_MIN_LENGTH)
- @MaxLength(255)
- password: string
+export const createUserSchema = optionalUserSchema.extend({
+ login: loginSchema,
+ email: emailSchema,
+ password: z.string().min(USER_PASSWORD_MIN_LENGTH).max(255),
+ firstName: profileNameSchema
+})
- @IsString()
- @MaxLength(255)
- @Transform(({ value }) => (value ? value.trim() : ''))
- firstName: string
-}
+type CreateUserSchemaOutput = z.output<typeof createUserSchema>
+type CreateUserRequiredKey = 'login' | 'email' | 'firstName'
-export class UpdateUserDto extends OptionalUserDto {
- @IsOptional()
- @Transform(({ value }) => (value ? value.trim() : ''))
- @MinLength(2)
- @MaxLength(255)
- @IsUserLogin()
- login?: string
+export type CreateUserDto = CreateUserSchemaOutput & Required<Pick<CreateUserSchemaOutput, CreateUserRequiredKey>>
- @IsOptional()
- @Transform(({ value }) => (value ? value.trim() : ''))
- @IsEmail()
- @MinLength(2)
- @MaxLength(255)
- email?: string
+export const updateUserSchema = optionalUserSchema.extend({
+ login: loginSchema.optional(),
+ email: emailSchema.optional(),
+ password: z.string().min(USER_PASSWORD_MIN_LENGTH).max(255).nullish(),
+ firstName: profileNameSchema.optional()
+})
- @IsOptional()
- @IsString()
- @MinLength(USER_PASSWORD_MIN_LENGTH)
- @MaxLength(255)
- password?: string
+export type UpdateUserDto = z.infer<typeof updateUserSchema>
- @IsOptional()
- @IsString()
- @Transform(({ value }) => (value ? value.trim() : ''))
- @MaxLength(255)
- firstName?: string
-}
+export const updateUserFromGroupSchema = z.object({
+ role: z.enum(USER_GROUP_ROLE)
+})
-export class UpdateUserFromGroupDto {
- @IsInt()
- @Min(USER_GROUP_ROLE.MEMBER)
- @Max(USER_GROUP_ROLE.MANAGER)
- role: USER_GROUP_ROLE
-}
+export type UpdateUserFromGroupDto = z.infer<typeof updateUserFromGroupSchema>
diff --git a/backend/src/applications/users/dto/delete-user.dto.ts b/backend/src/applications/users/dto/delete-user.dto.ts
index a14408f1..9fa31452 100644
--- a/backend/src/applications/users/dto/delete-user.dto.ts
+++ b/backend/src/applications/users/dto/delete-user.dto.ts
@@ -1,6 +1,7 @@
-import { IsBoolean } from 'class-validator'
+import { z } from 'zod'
-export class DeleteUserDto {
- @IsBoolean()
- deleteSpace: boolean
-}
+export const deleteUserSchema = z.object({
+ deleteSpace: z.boolean()
+})
+
+export type DeleteUserDto = z.infer<typeof deleteUserSchema>
diff --git a/backend/src/applications/users/dto/search-members.dto.spec.ts b/backend/src/applications/users/dto/search-members.dto.spec.ts
new file mode 100644
index 00000000..9e8ff2a2
--- /dev/null
+++ b/backend/src/applications/users/dto/search-members.dto.spec.ts
@@ -0,0 +1,7 @@
+import { searchMembersSchema } from './search-members.dto.js'
+
+describe('searchMembersSchema', () => {
+ it('normalizes a null search to an empty string', () => {
+ expect(searchMembersSchema.parse({ search: null })).toEqual(expect.objectContaining({ search: '' }))
+ })
+})
diff --git a/backend/src/applications/users/dto/search-members.dto.ts b/backend/src/applications/users/dto/search-members.dto.ts
index 1de8e07f..22f1c679 100644
--- a/backend/src/applications/users/dto/search-members.dto.ts
+++ b/backend/src/applications/users/dto/search-members.dto.ts
@@ -1,44 +1,26 @@
-import { Transform } from 'class-transformer'
-import { IsBoolean, IsInt, IsOptional, IsString } from 'class-validator'
-
-export class SearchMembersDto {
- @IsString()
- @Transform(({ value }) => (value ? value.trim().toLowerCase() : ''))
- search: string
-
- @IsOptional()
- @IsInt({ each: true })
- ignoreUserIds?: number[]
-
- @IsOptional()
- @IsInt({ each: true })
- ignoreGroupIds?: number[]
-
- @IsOptional()
- @IsBoolean()
- onlyUsers?: boolean = false
-
- @IsOptional()
- @IsBoolean()
- onlyGroups?: boolean = false
-
- @IsOptional()
- @IsBoolean()
- excludePersonalGroups?: boolean = false
-
- @IsOptional()
- @IsBoolean()
- onlyPersonalGroups?: boolean = false
-
- @IsOptional()
- @IsBoolean()
- isGroupManager?: boolean = false
-
- @IsOptional()
- @IsInt()
- usersRole?: number
-
- @IsOptional()
- @IsBoolean()
- withPermissions?: boolean = false
-}
+import { z } from 'zod'
+import { integerNumberSchema } from '../../../configuration/config.schema.js'
+
+export const searchMembersSchema = z.object({
+ search: z
+ .string()
+ .trim()
+ .toLowerCase()
+ .nullable()
+ .transform((value) => value ?? ''),
+ ignoreUserIds: z.array(integerNumberSchema).nullish(),
+ ignoreGroupIds: z.array(integerNumberSchema).nullish(),
+ onlyUsers: z.boolean().nullish().default(false),
+ onlyGroups: z.boolean().nullish().default(false),
+ excludePersonalGroups: z.boolean().nullish().default(false),
+ onlyPersonalGroups: z.boolean().nullish().default(false),
+ isGroupManager: z.boolean().nullish().default(false),
+ usersRole: z.number().int().nullish(),
+ withPermissions: z.boolean().nullish().default(false)
+})
+
+type SearchMembersSchemaInput = z.input<typeof searchMembersSchema>
+type SearchMembersSchemaOutput = z.output<typeof searchMembersSchema>
+
+export type SearchMembersDto = Omit<SearchMembersSchemaInput, 'search'> & { search: string }
+export type ValidatedSearchMembersDto = SearchMembersSchemaOutput & Required<Pick<SearchMembersSchemaOutput, 'search'>>
diff --git a/backend/src/applications/users/dto/user-login.dto.decorator.ts b/backend/src/applications/users/dto/user-login.dto.decorator.ts
deleted file mode 100644
index c024db5a..00000000
--- a/backend/src/applications/users/dto/user-login.dto.decorator.ts
+++ /dev/null
@@ -1,21 +0,0 @@
-import { registerDecorator, ValidationArguments, ValidationOptions } from 'class-validator'
-import { isValidUserLogin } from '../utils/login.js'
-
-export function IsUserLogin(validationOptions?: ValidationOptions) {
- return function (object: object, propertyName: string) {
- registerDecorator({
- name: 'IsUserLogin',
- target: object.constructor,
- propertyName,
- options: validationOptions,
- validator: {
- validate(value: unknown) {
- return isValidUserLogin(value)
- },
- defaultMessage(args: ValidationArguments) {
- return `${args.property} must be a valid user login`
- }
- }
- })
- }
-}
diff --git a/backend/src/applications/users/dto/user-login.schema.ts b/backend/src/applications/users/dto/user-login.schema.ts
new file mode 100644
index 00000000..6257339b
--- /dev/null
+++ b/backend/src/applications/users/dto/user-login.schema.ts
@@ -0,0 +1,4 @@
+import { z } from 'zod'
+import { isValidUserLogin } from '../utils/login.js'
+
+export const userLoginSchema = z.string().refine(isValidUserLogin, { message: 'must be a valid user login' })
diff --git a/backend/src/applications/users/dto/user-properties.dto.ts b/backend/src/applications/users/dto/user-properties.dto.ts
index b16b7201..527f0905 100644
--- a/backend/src/applications/users/dto/user-properties.dto.ts
+++ b/backend/src/applications/users/dto/user-properties.dto.ts
@@ -1,81 +1,58 @@
-import { Transform } from 'class-transformer'
-import { IsBoolean, IsDate, IsDefined, IsEnum, IsIn, IsInt, IsNotEmpty, IsOptional, IsString, MinLength, ValidateIf } from 'class-validator'
+import { z } from 'zod'
import { AUTH_SCOPE } from '../../../authentication/constants/scope.js'
import { currentDate } from '../../../common/shared.js'
import { COLLABORA_EDITOR } from '../../files/editors/collabora-online/collabora-online.constants.js'
import { EURO_OFFICE_EDITOR, ONLY_OFFICE_EDITOR } from '../../files/editors/only-office/only-office.constants.js'
import { USER_PASSWORD_MIN_LENGTH } from '../constants/user.js'
import { USER_SIDEBAR_QUICK_ACCESS_POSITION, USER_SIDEBAR_QUICK_ACCESS_VISIBILITY, USER_THEME } from '../constants/user-preferences.js'
-import type { UserPreferences } from '../interfaces/user-preferences.interface.js'
-export class UserLanguageDto {
- @ValidateIf((_, language) => language === null || typeof language === 'string')
- language: string | null
-}
+export const userLanguageSchema = z.object({
+ language: z.string().nullable()
+})
-export class UserNotificationDto {
- @IsNotEmpty()
- @IsInt()
- notification: number
-}
+export type UserLanguageDto = z.infer<typeof userLanguageSchema>
-export class UserStorageIndexingDto {
- @IsDefined()
- @IsBoolean()
- storageIndexing: boolean
-}
+export const userNotificationSchema = z.object({
+ notification: z.number().int()
+})
-export class UserPreferencesDto implements Partial<UserPreferences> {
- @ValidateIf((_, value) => value !== undefined)
- @IsEnum(USER_THEME)
- theme?: UserPreferences['theme']
+export type UserNotificationDto = z.infer<typeof userNotificationSchema>
- @ValidateIf((_, value) => value !== undefined)
- @IsIn([COLLABORA_EDITOR, ONLY_OFFICE_EDITOR, EURO_OFFICE_EDITOR, null])
- editor?: UserPreferences['editor']
+export const userStorageIndexingSchema = z.object({
+ storageIndexing: z.boolean()
+})
- @ValidateIf((_, value) => value !== undefined)
- @IsBoolean()
- useSystemNotifications?: UserPreferences['useSystemNotifications']
+export type UserStorageIndexingDto = z.infer<typeof userStorageIndexingSchema>
- @ValidateIf((_, value) => value !== undefined)
- @IsEnum(USER_SIDEBAR_QUICK_ACCESS_VISIBILITY)
- sidebarQuickAccessVisibility?: UserPreferences['sidebarQuickAccessVisibility']
+export const userPreferencesSchema = z.object({
+ theme: z.enum(USER_THEME).optional(),
+ editor: z.enum([COLLABORA_EDITOR, ONLY_OFFICE_EDITOR, EURO_OFFICE_EDITOR]).nullish(),
+ useSystemNotifications: z.boolean().optional(),
+ sidebarQuickAccessVisibility: z.enum(USER_SIDEBAR_QUICK_ACCESS_VISIBILITY).optional(),
+ sidebarQuickAccessPosition: z.enum(USER_SIDEBAR_QUICK_ACCESS_POSITION).optional()
+})
- @ValidateIf((_, value) => value !== undefined)
- @IsEnum(USER_SIDEBAR_QUICK_ACCESS_POSITION)
- sidebarQuickAccessPosition?: UserPreferences['sidebarQuickAccessPosition']
-}
+export type UserPreferencesDto = z.infer<typeof userPreferencesSchema>
-export class UserUpdatePasswordDto {
- @IsNotEmpty()
- @IsString()
- oldPassword: string
+export const userUpdatePasswordSchema = z.object({
+ oldPassword: z.string().min(1),
+ newPassword: z.string().min(USER_PASSWORD_MIN_LENGTH)
+})
- @IsNotEmpty()
- @IsString()
- @MinLength(USER_PASSWORD_MIN_LENGTH)
- newPassword: string
-}
+export type UserUpdatePasswordDto = z.infer<typeof userUpdatePasswordSchema>
-export class UserPasswordDto {
- @IsNotEmpty()
- @IsString()
- @MinLength(USER_PASSWORD_MIN_LENGTH)
- password: string
-}
+export const userPasswordSchema = z.object({
+ password: z.string().min(USER_PASSWORD_MIN_LENGTH)
+})
-export class UserAppPasswordDto {
- @IsNotEmpty()
- @IsString()
- name: string
+export type UserPasswordDto = z.infer<typeof userPasswordSchema>
- @Transform(({ value }) => value.toLowerCase())
- @IsEnum(AUTH_SCOPE)
- app: AUTH_SCOPE
+export const userAppPasswordSchema = z.object({
+ name: z.string().min(1),
+ app: z.string().toLowerCase().pipe(z.enum(AUTH_SCOPE)),
+ expiration: z
+ .preprocess((value) => (typeof value === 'string' ? (value ? currentDate(value) : null) : value ? value : null), z.date().nullable())
+ .optional()
+})
- @IsOptional()
- @Transform(({ value }) => (value ? currentDate(value) : null))
- @IsDate()
- expiration?: Date
-}
+export type UserAppPasswordDto = z.infer<typeof userAppPasswordSchema>
diff --git a/backend/src/applications/users/guards/roles.guard.spec.ts b/backend/src/applications/users/guards/roles.guard.spec.ts
index 3b050c04..b52731e4 100644
--- a/backend/src/applications/users/guards/roles.guard.spec.ts
+++ b/backend/src/applications/users/guards/roles.guard.spec.ts
@@ -57,7 +57,7 @@ describe(UserRolesGuard.name, () => {
})
it('should not pass with an undefined user role', async () => {
- userTest.role = undefined
+ ;(userTest as any).role = undefined
context = createMock<ExecutionContext>()
UserHaveRole(USER_ROLE.USER)(context.getHandler())
context.switchToHttp().getRequest.mockReturnValue({
diff --git a/backend/src/applications/users/interfaces/admin-group.interface.ts b/backend/src/applications/users/interfaces/admin-group.interface.ts
index d567ac3a..e5afd8f7 100644
--- a/backend/src/applications/users/interfaces/admin-group.interface.ts
+++ b/backend/src/applications/users/interfaces/admin-group.interface.ts
@@ -5,10 +5,10 @@ export interface AdminGroup extends Omit<Group, 'parentId' | 'type'> {
id: number
name: string
type: GROUP_TYPE
- description: string
+ description: string | null
permissions: string
visibility: GROUP_VISIBILITY
createdAt: Date
- modifiedAt: Date
- parent: Pick<Group, 'id' | 'name'> & { description?: Group['description'] }
+ modifiedAt: Date | null
+ parent: (Pick<Group, 'id' | 'name'> & { description?: Group['description'] }) | null
}
diff --git a/backend/src/applications/users/interfaces/admin-user.interface.ts b/backend/src/applications/users/interfaces/admin-user.interface.ts
index 1d50d60b..ea63d682 100644
--- a/backend/src/applications/users/interfaces/admin-user.interface.ts
+++ b/backend/src/applications/users/interfaces/admin-user.interface.ts
@@ -1,4 +1,5 @@
import type { User } from '../schemas/user.interface.js'
import type { Member } from './member.interface.js'
-export type AdminUser = Partial<User> & { fullName: string; groups?: Member[]; twoFaEnabled?: boolean }
+export type AdminUser = Partial<User> &
+ Required<Pick<User, 'id' | 'login' | 'email' | 'role'>> & { fullName: string; groups?: Member[]; twoFaEnabled?: boolean }
diff --git a/backend/src/applications/users/interfaces/group-browse.interface.ts b/backend/src/applications/users/interfaces/group-browse.interface.ts
index 65b607d6..9bd8d3fa 100644
--- a/backend/src/applications/users/interfaces/group-browse.interface.ts
+++ b/backend/src/applications/users/interfaces/group-browse.interface.ts
@@ -3,6 +3,6 @@ import { USER_GROUP_ROLE } from '../constants/user.js'
import type { Member } from './member.interface.js'
export interface GroupBrowse {
- parentGroup: { id: number; name: string; type: GROUP_TYPE; role?: USER_GROUP_ROLE }
+ parentGroup?: { id: number; name: string; type: GROUP_TYPE; role?: USER_GROUP_ROLE }
members: Member[]
}
diff --git a/backend/src/applications/users/interfaces/guest-user.interface.ts b/backend/src/applications/users/interfaces/guest-user.interface.ts
index 80b8a03f..44d1b3a1 100644
--- a/backend/src/applications/users/interfaces/guest-user.interface.ts
+++ b/backend/src/applications/users/interfaces/guest-user.interface.ts
@@ -2,6 +2,10 @@ import type { User } from '../schemas/user.interface.js'
import type { Member } from './member.interface.js'
export type GuestUser = Partial<User> & {
+ id: number
+ login: string
+ email: string
+ role: number
fullName: string
managers?: Member[]
groups?: Member[]
diff --git a/backend/src/applications/users/interfaces/member.interface.ts b/backend/src/applications/users/interfaces/member.interface.ts
index 53bfa70a..5ef26e06 100644
--- a/backend/src/applications/users/interfaces/member.interface.ts
+++ b/backend/src/applications/users/interfaces/member.interface.ts
@@ -6,14 +6,14 @@ import type { USER_GROUP_ROLE } from '../constants/user.js'
export interface Member {
id: number
name: string // user full name or group name
- description: string // user email or group description
+ description: string | null // user email or group description
type: MEMBER_TYPE
- login?: string // only for user
- linkId?: number // only for link
- linkSettings?: CreateOrUpdateLinkDto // only for link
- permissions?: string
- createdAt?: Date
- modifiedAt?: Date
+ login?: string | null // only for user
+ linkId?: number | null // only for link
+ linkSettings?: CreateOrUpdateLinkDto | null // only for link
+ permissions?: string | null
+ createdAt?: Date | null
+ modifiedAt?: Date | null
spaceRole?: SPACE_ROLE // only for user
groupRole?: USER_GROUP_ROLE // only for groups
counts?: { users?: number; groups?: number } // only for admin group members
diff --git a/backend/src/applications/users/interfaces/user-secrets.interface.ts b/backend/src/applications/users/interfaces/user-secrets.interface.ts
index 337bcfd8..8fe185cb 100644
--- a/backend/src/applications/users/interfaces/user-secrets.interface.ts
+++ b/backend/src/applications/users/interfaces/user-secrets.interface.ts
@@ -5,11 +5,11 @@ export interface UserAppPassword {
name: string
app: AUTH_SCOPE
password: string
- expiration: Date
- currentIp: string
- lastIp: string
- currentAccess: Date
- lastAccess: Date
+ expiration: Date | string | null
+ currentIp: string | null
+ lastIp: string | null
+ currentAccess: Date | string | null
+ lastAccess: Date | string | null
createdAt: Date
}
diff --git a/backend/src/applications/users/interfaces/websocket.interface.ts b/backend/src/applications/users/interfaces/websocket.interface.ts
index 57d523c2..67a4e412 100644
--- a/backend/src/applications/users/interfaces/websocket.interface.ts
+++ b/backend/src/applications/users/interfaces/websocket.interface.ts
@@ -1,4 +1,5 @@
-import type { USER_ONLINE_STATUS } from '../constants/user.js'
+import { z } from 'zod'
+import { USER_ONLINE_STATUS } from '../constants/user.js'
export interface UserOnline {
id: number
@@ -13,7 +14,9 @@ export interface EventUpdateOnlineStatus {
status: USER_ONLINE_STATUS
}
-export interface EventChangeOnlineStatus {
- status: USER_ONLINE_STATUS
- store: boolean
-}
+export const eventChangeOnlineStatusSchema = z.object({
+ status: z.enum(USER_ONLINE_STATUS),
+ store: z.boolean()
+})
+
+export type EventChangeOnlineStatus = z.infer<typeof eventChangeOnlineStatusSchema>
diff --git a/backend/src/applications/users/models/user.model.spec.ts b/backend/src/applications/users/models/user.model.spec.ts
new file mode 100644
index 00000000..b510db19
--- /dev/null
+++ b/backend/src/applications/users/models/user.model.spec.ts
@@ -0,0 +1,50 @@
+import { USER_ROLE } from '../constants/user.js'
+import { UserModel } from './user.model.js'
+
+describe(UserModel.name, () => {
+ it('serializes only public user properties', () => {
+ const user = new UserModel(
+ {
+ id: 1,
+ login: 'alice',
+ role: USER_ROLE.USER,
+ password: 'password-hash',
+ externalId: 'external-subject',
+ secrets: { twoFaSecret: 'totp-secret', appPasswords: [{ name: 'desktop', password: 'app-password' }] }
+ } as any,
+ false
+ )
+ user.exp = 123456
+
+ const serialized = JSON.parse(JSON.stringify(user))
+
+ expect(serialized).not.toHaveProperty('password')
+ expect(serialized).not.toHaveProperty('secrets')
+ expect(serialized).not.toHaveProperty('externalId')
+ expect(serialized).not.toHaveProperty('exp')
+ expect(serialized).toEqual(expect.objectContaining({ id: 1, login: 'alice', twoFaEnabled: true, appPasswords: 1 }))
+ })
+
+ it('drops private properties when restoring a cached user', () => {
+ const user = UserModel.fromSerialized({
+ id: 1,
+ login: 'alice',
+ role: USER_ROLE.USER,
+ applications: [],
+ twoFaEnabled: false,
+ password: 'password-hash',
+ secrets: { twoFaSecret: 'totp-secret' },
+ externalId: 'external-subject',
+ exp: 123456
+ })
+
+ expect(user).not.toHaveProperty('password')
+ expect(user.secrets).toEqual({ twoFaSecret: false })
+ expect(user.externalId).toBeUndefined()
+ expect(user.exp).toBeUndefined()
+ const serialized = JSON.parse(JSON.stringify(user))
+ expect(serialized).not.toHaveProperty('secrets')
+ expect(serialized).not.toHaveProperty('externalId')
+ expect(serialized).not.toHaveProperty('exp')
+ })
+})
diff --git a/backend/src/applications/users/models/user.model.ts b/backend/src/applications/users/models/user.model.ts
index 3194ea66..64239958 100644
--- a/backend/src/applications/users/models/user.model.ts
+++ b/backend/src/applications/users/models/user.model.ts
@@ -1,6 +1,6 @@
-import { Exclude, Expose } from 'class-transformer'
import fs from 'node:fs/promises'
import path from 'node:path'
+import { z } from 'zod'
import type { AUTH_SESSION } from '../../../authentication/providers/auth-providers.constants.js'
import { popFromObject } from '../../../common/shared.js'
import { configuration } from '../../../configuration/config.environment.js'
@@ -14,51 +14,105 @@ import type { User } from '../schemas/user.interface.js'
import { isSafePathSegment, validateUserId } from '../utils/login.js'
import { normalizeUserPreferences } from '../utils/user.js'
-export class UserModel implements User {
- id: number
- login: string
- email: string
- firstName: string
- lastName: string
- role: number
- language: string
- isActive: boolean
- preferences: UserPreferences
- notification: number
- onlineStatus: number
- permissions: string
- storageUsage: number
- storageQuota: number
- storageIndexing: boolean
- passwordAttempts: number
- currentIp: string
- lastIp: string
- currentAccess: Date
- lastAccess: Date
- createdAt: Date
- // exclusions
- @Exclude()
- externalId: string | null
- @Exclude()
- password: string
- @Exclude()
- secrets: UserSecrets
- @Exclude()
- // only used on backend
+// Explicit public representation of a user. Sensitive and backend-only fields
+// such as password, secrets, externalId, impersonatedFromId and exp are
+// intentionally absent and are therefore stripped by Zod.
+const serializedUserSchema = z
+ .object({
+ id: z.number(),
+ login: z.string(),
+ email: z.string().nullable(),
+ firstName: z.string().nullable(),
+ lastName: z.string().nullable(),
+ role: z.number(),
+ language: z.string().nullable(),
+ isActive: z.boolean(),
+ preferences: z.unknown(),
+ notification: z.number(),
+ onlineStatus: z.number(),
+ permissions: z.string(),
+ storageUsage: z.number().nullable(),
+ storageQuota: z.number().nullable(),
+ storageIndexing: z.boolean(),
+ passwordAttempts: z.number(),
+ currentIp: z.string().nullable(),
+ lastIp: z.string().nullable(),
+ currentAccess: z.union([z.date(), z.string()]).nullable(),
+ lastAccess: z.union([z.date(), z.string()]).nullable(),
+ createdAt: z.union([z.date(), z.string()]),
+ impersonatedClientId: z.string(),
+ clientId: z.string(),
+ fullName: z.string(),
+ impersonated: z.boolean(),
+ authSession: z.unknown(),
+ avatarBase64: z.string()
+ })
+ .partial()
+ .extend({
+ applications: z.array(z.string()),
+ // Computed getters are not enumerable class properties, so they must be
+ // explicitly included in the serialized representation.
+ isAdmin: z.boolean(),
+ isUser: z.boolean(),
+ isGuest: z.boolean(),
+ isLink: z.boolean(),
+ quotaIsExceeded: z.boolean(),
+ twoFaEnabled: z.boolean(),
+ appPasswords: z.number()
+ })
+
+// Derived getters are recomputed when the cached data creates a new UserModel.
+// twoFaEnabled is retained because it is needed to restore the corresponding
+// public authentication state without caching the underlying secret.
+const cachedUserSchema = serializedUserSchema.omit({
+ isAdmin: true,
+ isUser: true,
+ isGuest: true,
+ isLink: true,
+ quotaIsExceeded: true,
+ appPasswords: true
+})
+
+export class UserModel implements Omit<User, 'password' | 'permissions'> {
+ id!: number
+ login!: string
+ email!: string
+ firstName!: string | null
+ lastName!: string | null
+ role!: number
+ language!: string | null
+ isActive!: boolean
+ preferences!: UserPreferences
+ notification!: number
+ onlineStatus!: number
+ permissions?: string
+ storageUsage!: number | null
+ storageQuota!: number | null
+ storageIndexing!: boolean
+ passwordAttempts!: number
+ currentIp!: string | null
+ lastIp!: string | null
+ currentAccess!: Date | null
+ lastAccess!: Date | null
+ createdAt!: Date
+ // Sensitive/internal values intentionally excluded from serializedUserSchema.
+ externalId!: string | null
+ password?: string
+ secrets!: UserSecrets | null
+ // Backend-only impersonation source; never exposed in the public representation.
impersonatedFromId?: number
impersonatedClientId?: string
// used for desktop|cmd app
clientId?: string
-
// outside db schema
- fullName: string
+ fullName!: string
impersonated?: boolean
authSession?: AUTH_SESSION
avatarBase64?: string
// permissions as a list
applications: string[] = []
- @Exclude({ toPlainOnly: true })
- exp?: number // refresh token expiration needed to refresh
+ // Token-only refresh expiration; never exposed in the public representation.
+ exp?: number
constructor(props: Partial<User> & { exp?: number; twoFaEnabled?: boolean }, removePassword = true) {
// User model can be instantiated with data from the database or from a token payload
@@ -75,61 +129,59 @@ export class UserModel implements User {
this.setProfile()
}
- private _homePath: string
+ static fromSerialized(value: unknown): UserModel {
+ return new UserModel(cachedUserSchema.parse(value) as ConstructorParameters<typeof UserModel>[0])
+ }
+
+ #homePath!: string
get homePath(): string {
- return (this._homePath ||= this.isLink ? UserModel.getLinkHomePath(this.id) : UserModel.getHomePath(this.login))
+ return (this.#homePath ||= this.isLink ? UserModel.getLinkHomePath(this.id) : UserModel.getHomePath(this.login))
}
- private _filesPath: string
+ #filesPath!: string
get filesPath(): string {
- return (this._filesPath ||= path.join(this.homePath, SPACE_REPOSITORY.FILES))
+ return (this.#filesPath ||= path.join(this.homePath, SPACE_REPOSITORY.FILES))
}
- private _trashPath: string
+ #trashPath!: string
get trashPath(): string {
- return (this._trashPath ||= path.join(this.homePath, SPACE_REPOSITORY.TRASH))
+ return (this.#trashPath ||= path.join(this.homePath, SPACE_REPOSITORY.TRASH))
}
- private _tmpPath: string
+ #tmpPath!: string
get tmpPath(): string {
- return (this._tmpPath ||= path.join(this.homePath, USER_TMP_DIRECTORY))
+ return (this.#tmpPath ||= path.join(this.homePath, USER_TMP_DIRECTORY))
}
- @Expose()
+ // Public computed values explicitly included in serializedUserSchema.
get isAdmin(): boolean {
return this.role === USER_ROLE.ADMINISTRATOR
}
- @Expose()
get isUser(): boolean {
return this.role === USER_ROLE.USER || this.role === USER_ROLE.ADMINISTRATOR
}
- @Expose()
get isGuest(): boolean {
return this.role === USER_ROLE.GUEST
}
- @Expose()
get isLink(): boolean {
return this.role === USER_ROLE.LINK
}
- @Expose()
get quotaIsExceeded(): boolean {
- return this.storageQuota !== null && this.storageUsage >= this.storageQuota
+ return this.storageQuota !== null && this.storageUsage! >= this.storageQuota
}
- @Expose()
get twoFaEnabled(): boolean {
return !!this.secrets?.twoFaSecret
}
- @Expose()
get appPasswords(): number {
return this.secrets?.appPasswords?.length || 0
}
@@ -181,6 +233,22 @@ export class UserModel implements User {
return `*User <${this.login}> (${this.id})*`
}
+ serialize() {
+ return serializedUserSchema.parse(this)
+ }
+
+ // noinspection JSUnusedGlobalSymbols
+ toJSON() {
+ /*
+ * This hook is called implicitly by JSON.stringify(), including when Fastify
+ * serializes an HTTP response containing a UserModel instance. It delegates to
+ * the Zod-backed serializer to expose computed public properties while omitting
+ * sensitive and backend-only properties. Use serialize() directly when an
+ * explicit plain-object representation is needed.
+ */
+ return this.serialize()
+ }
+
removePassword() {
delete this.password
}
@@ -230,9 +298,9 @@ export class UserModel implements User {
return this.role <= role
}
- private initSecrets(props: Partial<UserModel>) {
- // Remove the `twoFaEnabled` property to avoid conflicts with the current getter when using `plainToClass` with `class-validator`
- // The `props` variable may be empty when the class is instantiated using `plainToClass`
+ private initSecrets(props: Partial<User> & { exp?: number; twoFaEnabled?: boolean }) {
+ // Remove the serialized `twoFaEnabled` property before assigning values to the model,
+ // because the public value is exposed through a getter.
if (props && 'twoFaEnabled' in props) {
// Only used when the User model is instantiated from a token payload
// Set a `twoFaSecret` property (boolean) on the `secrets` property so that the `twoFaEnabled` getter returns `true`
diff --git a/backend/src/applications/users/schemas/group.interface.ts b/backend/src/applications/users/schemas/group.interface.ts
index 7463840c..51fee8f3 100644
--- a/backend/src/applications/users/schemas/group.interface.ts
+++ b/backend/src/applications/users/schemas/group.interface.ts
@@ -1,15 +1,3 @@
import type { groups } from './groups.schema.js'
-type GroupSchema = typeof groups.$inferSelect
-
-export class Group implements GroupSchema {
- id: number
- name: string
- description: string
- type: number
- visibility: number
- parentId: number
- permissions: string
- createdAt: Date
- modifiedAt: Date
-}
+export type Group = typeof groups.$inferSelect
diff --git a/backend/src/applications/users/schemas/user-group.interface.ts b/backend/src/applications/users/schemas/user-group.interface.ts
index a33a90a8..927767d2 100644
--- a/backend/src/applications/users/schemas/user-group.interface.ts
+++ b/backend/src/applications/users/schemas/user-group.interface.ts
@@ -1,10 +1,3 @@
import type { usersGroups } from './users-groups.schema.js'
-type UserGroupSchema = typeof usersGroups.$inferSelect
-
-export class UserGroup implements UserGroupSchema {
- userId: number
- groupId: number
- role: number
- createdAt: Date
-}
+export type UserGroup = typeof usersGroups.$inferSelect
diff --git a/backend/src/applications/users/schemas/user.interface.ts b/backend/src/applications/users/schemas/user.interface.ts
index 4ef4429e..49869164 100644
--- a/backend/src/applications/users/schemas/user.interface.ts
+++ b/backend/src/applications/users/schemas/user.interface.ts
@@ -1,32 +1,3 @@
-import type { UserPreferences } from '../interfaces/user-preferences.interface.js'
-import type { UserSecrets } from '../interfaces/user-secrets.interface.js'
import type { users } from './users.schema.js'
-type UserSchema = typeof users.$inferSelect
-
-export class User implements UserSchema {
- id: number
- email: string
- login: string
- externalId: string | null
- firstName: string
- lastName: string
- password: string
- role: number
- isActive: boolean
- secrets: UserSecrets
- preferences: UserPreferences
- language: string
- permissions: string
- storageUsage: number
- storageQuota: number
- storageIndexing: boolean
- notification: number
- onlineStatus: number
- passwordAttempts: number
- currentIp: string
- lastIp: string
- currentAccess: Date
- lastAccess: Date
- createdAt: Date
-}
+export type User = typeof users.$inferSelect
diff --git a/backend/src/applications/users/services/admin-users-manager.service.spec.ts b/backend/src/applications/users/services/admin-users-manager.service.spec.ts
index 6fddd044..b07744bf 100644
--- a/backend/src/applications/users/services/admin-users-manager.service.spec.ts
+++ b/backend/src/applications/users/services/admin-users-manager.service.spec.ts
@@ -5,7 +5,7 @@ import { GROUP_TYPE } from '../constants/group.js'
import { USER_GROUP_ROLE, USER_ROLE } from '../constants/user.js'
import type { CreateOrUpdateGroupDto } from '../dto/create-or-update-group.dto.js'
import type { CreateUserDto, UpdateUserDto, UpdateUserFromGroupDto } from '../dto/create-or-update-user.dto.js'
-import type { SearchMembersDto } from '../dto/search-members.dto.js'
+import { searchMembersSchema, type ValidatedSearchMembersDto } from '../dto/search-members.dto.js'
import { UserModel } from '../models/user.model.js'
import { AdminUsersManager } from './admin-users-manager.service.js'
import { AdminUsersQueries } from './admin-users-queries.service.js'
@@ -14,12 +14,16 @@ import { Mock } from 'vitest'
import * as _fs from '../../files/utils/files.js'
// mock file utils used by the service (delete/rename user space)
-vi.mock('../../files/utils/files.js', () => ({
- isPathInside: vi.fn(() => true),
- isPathExists: vi.fn(),
- moveFiles: vi.fn(),
- removeFiles: vi.fn()
-}))
+vi.mock('../../files/utils/files.js', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('../../files/utils/files.js')>()
+ return {
+ ...actual,
+ isPathInside: vi.fn(() => true),
+ isPathExists: vi.fn(),
+ moveFiles: vi.fn(),
+ removeFiles: vi.fn()
+ }
+})
// mock hash/anonymize utilities (preserve other module exports)
vi.mock('../../../common/functions.js', async (importOriginal) => {
@@ -431,14 +435,14 @@ describe(AdminUsersManager.name, () => {
expect(root.parentGroup).toBeUndefined()
expect(root.members).toEqual([{ id: 3 }])
- adminQueriesMock.groupFromName.mockResolvedValueOnce(null)
+ adminQueriesMock.groupFromName.mockResolvedValueOnce(undefined)
await expectHttp(service.browseGroups('unknown'))
})
it('getGroup OK / NOT_FOUND', async () => {
adminQueriesMock.groupFromId.mockResolvedValueOnce({ id: 9 })
expect(await service.getGroup(9)).toEqual({ id: 9 })
- adminQueriesMock.groupFromId.mockResolvedValueOnce(null)
+ adminQueriesMock.groupFromId.mockResolvedValueOnce(undefined)
await expectHttp(service.getGroup(999))
})
@@ -490,7 +494,7 @@ describe(AdminUsersManager.name, () => {
})
it('addUsersToGroup: NOT_FOUND + error', async () => {
- adminQueriesMock.groupFromId.mockResolvedValueOnce(null)
+ adminQueriesMock.groupFromId.mockResolvedValueOnce(undefined)
await expectHttp(service.addUsersToGroup(1, [2, 3]))
adminQueriesMock.groupFromId.mockResolvedValueOnce({ id: 1, type: GROUP_TYPE.USER })
@@ -509,7 +513,7 @@ describe(AdminUsersManager.name, () => {
describe('searchMembers', () => {
it('forwards to usersQueries.searchUsersOrGroups', async () => {
- const dto = { search: 'jo' } as SearchMembersDto
+ const dto = searchMembersSchema.parse({ search: 'jo' }) as ValidatedSearchMembersDto
adminQueriesMock.usersQueries.searchUsersOrGroups.mockResolvedValueOnce([{ id: 1 }])
expect(await service.searchMembers(dto)).toEqual([{ id: 1 }])
expect(adminQueriesMock.usersQueries.searchUsersOrGroups).toHaveBeenCalledWith(dto)
@@ -554,7 +558,7 @@ describe(AdminUsersManager.name, () => {
const guests = [{ id: 2 }]
adminQueriesMock.usersQueries.listGuests.mockResolvedValueOnce(guests as any)
expect(await service.listGuests()).toEqual(guests)
- expect(adminQueriesMock.usersQueries.listGuests).toHaveBeenCalledWith(null, null, true)
+ expect(adminQueriesMock.usersQueries.listGuests).toHaveBeenCalledWith(null, null as never, true)
})
})
diff --git a/backend/src/applications/users/services/admin-users-manager.service.ts b/backend/src/applications/users/services/admin-users-manager.service.ts
index 26a65df6..0cd3e6a4 100644
--- a/backend/src/applications/users/services/admin-users-manager.service.ts
+++ b/backend/src/applications/users/services/admin-users-manager.service.ts
@@ -2,21 +2,21 @@ import { HttpException, HttpStatus, Injectable, Logger } from '@nestjs/common'
import { FastifyReply } from 'fastify'
import { AuthManager } from '../../../authentication/auth.service.js'
import { LoginResponseDto } from '../../../authentication/dto/login-response.dto.js'
+import { toErrorMessage } from '../../../common/errors.js'
import { anonymizePassword, hashPassword } from '../../../common/functions.js'
import { isPathExists, moveFiles, removeFiles } from '../../files/utils/files.js'
import { GROUP_TYPE } from '../constants/group.js'
-import { USER_ROLE } from '../constants/user.js'
+import { USER_NOTIFICATION, USER_ROLE } from '../constants/user.js'
import type { CreateOrUpdateGroupDto } from '../dto/create-or-update-group.dto.js'
import type { CreateUserDto, UpdateUserDto, UpdateUserFromGroupDto } from '../dto/create-or-update-user.dto.js'
import type { DeleteUserDto } from '../dto/delete-user.dto.js'
-import type { SearchMembersDto } from '../dto/search-members.dto.js'
+import type { ValidatedSearchMembersDto } from '../dto/search-members.dto.js'
import type { AdminGroup } from '../interfaces/admin-group.interface.js'
import type { AdminUser } from '../interfaces/admin-user.interface.js'
import type { GroupBrowse } from '../interfaces/group-browse.interface.js'
import type { GuestUser } from '../interfaces/guest-user.interface.js'
import type { Member } from '../interfaces/member.interface.js'
import { UserModel } from '../models/user.model.js'
-import type { Group } from '../schemas/group.interface.js'
import type { User } from '../schemas/user.interface.js'
import { isValidUserLogin } from '../utils/login.js'
import { AdminUsersQueries } from './admin-users-queries.service.js'
@@ -38,13 +38,13 @@ export class AdminUsersManager {
}
async getUser(userId: number): Promise<AdminUser> {
- const user: AdminUser = await this.adminQueries.listUsers(userId)
+ const user = await this.adminQueries.listUsers(userId)
this.checkUser(user, true)
return user
}
async getGuest(guestId: number): Promise<GuestUser> {
- const user: GuestUser = await this.adminQueries.usersQueries.listGuests(guestId, 0, true)
+ const user = await this.adminQueries.usersQueries.listGuests(guestId, 0, true)
this.checkUser(user, true)
return user
}
@@ -62,7 +62,15 @@ export class AdminUsersManager {
try {
createUserDto.password = await hashPassword(createUserDto.password)
const userId: number = await this.adminQueries.usersQueries.createUserOrGuest(createUserDto, userRole)
- const user = new UserModel({ ...createUserDto, id: userId, role: userRole })
+ const { groups: _groups, managers: _managers, ...userProperties } = createUserDto
+ const user = new UserModel({
+ ...userProperties,
+ id: userId,
+ role: userRole,
+ isActive: userProperties.isActive ?? true,
+ notification: userProperties.notification ?? USER_NOTIFICATION.APPLICATION_EMAIL,
+ permissions: userProperties.permissions ?? ''
+ })
this.logger.log({
tag: this.createUserOrGuest.name,
msg: `${USER_ROLE[userRole]} (${userId}) was created : ${JSON.stringify(anonymizePassword(createUserDto))}`
@@ -75,7 +83,7 @@ export class AdminUsersManager {
return asAdmin ? this.getGuest(user.id) : user
}
} catch (e) {
- this.logger.error({ tag: this.createUserOrGuest.name, msg: `unable to create user *${createUserDto.login}* : ${e}` })
+ this.logger.error({ tag: this.createUserOrGuest.name, msg: `unable to create user *${createUserDto.login}* : ${toErrorMessage(e)}` })
throw new HttpException('Unable to create user', HttpStatus.INTERNAL_SERVER_ERROR)
}
}
@@ -92,57 +100,57 @@ export class AdminUsersManager {
const updateUserGroups: { add: number[]; delete: number[] } = { add: [], delete: [] }
const updateGuestManagers: { add: number[]; delete: number[] } = { add: [], delete: [] }
- for (const [k, v] of Object.entries(updateUserDto)) {
- switch (k as keyof UpdateUserDto) {
+ for (const [k, v] of Object.entries(updateUserDto) as { [K in keyof UpdateUserDto]-?: [K, UpdateUserDto[K]] }[keyof UpdateUserDto][]) {
+ switch (k) {
case 'login':
if (user.login === v) {
break
}
- this.validateUserLogin(v)
- if (await this.adminQueries.usersQueries.checkUserExists(v)) {
+ this.validateUserLogin(v as string)
+ if (await this.adminQueries.usersQueries.checkUserExists(v as string)) {
throw new HttpException('Login already used', HttpStatus.FORBIDDEN)
}
if (userRole === USER_ROLE.USER || userRole === USER_ROLE.GUEST) {
- if (!(await this.renameUserSpace(user.login, v))) {
+ if (!(await this.renameUserSpace(user.login, v as string))) {
throw new HttpException('Unable to rename user space', HttpStatus.INTERNAL_SERVER_ERROR)
}
}
- updateUser.login = v
+ updateUser.login = v as string
break
case 'email':
if (user.email === v) {
break
}
- if (await this.adminQueries.usersQueries.checkUserExists(null, v)) {
+ if (await this.adminQueries.usersQueries.checkUserExists(null, v as string)) {
throw new HttpException('Email already used', HttpStatus.FORBIDDEN)
}
- updateUser.email = v
+ updateUser.email = v as string
break
case 'isActive':
- updateUser.isActive = v
+ updateUser.isActive = v as boolean
if (v) {
updateUser.passwordAttempts = 0
}
break
case 'password':
- updateUser.password = await hashPassword(updateUserDto.password)
+ updateUser.password = await hashPassword(updateUserDto.password!)
break
case 'groups': {
// allowed for users and guests
const currentGroups: number[] = user.groups?.length ? user.groups.map((g) => g.id) : []
- updateUserGroups.add = v.filter((id: number) => currentGroups.indexOf(id) === -1)
- updateUserGroups.delete = currentGroups.filter((id: number) => v.indexOf(id) === -1)
+ updateUserGroups.add = (v as number[]).filter((id: number) => currentGroups.indexOf(id) === -1)
+ updateUserGroups.delete = currentGroups.filter((id: number) => (v as number[]).indexOf(id) === -1)
break
}
case 'managers':
if (userRole === USER_ROLE.GUEST) {
const currentManagers: number[] = user.managers?.length ? user.managers.map((m) => m.id) : []
- updateGuestManagers.add = v.filter((id: number) => currentManagers.indexOf(id) === -1)
- updateGuestManagers.delete = currentManagers.filter((id: number) => v.indexOf(id) === -1)
+ updateGuestManagers.add = (v as number[]).filter((id: number) => currentManagers.indexOf(id) === -1)
+ updateGuestManagers.delete = currentManagers.filter((id: number) => (v as number[]).indexOf(id) === -1)
}
break
default:
- updateUser[k] = v
+ Object.assign(updateUser, { [k]: v })
}
}
@@ -155,7 +163,7 @@ export class AdminUsersManager {
}
// update quota in cache
if ('storageQuota' in updateUser) {
- void this.filesQuotaManager.updateStorageQuota(user.id, FILE_REPOSITORY.USER, updateUser.storageQuota)
+ void this.filesQuotaManager.updateStorageQuota(user.id, FILE_REPOSITORY.USER, updateUser.storageQuota as number | null)
}
}
@@ -191,7 +199,7 @@ export class AdminUsersManager {
await this.deleteUserSpace(userLogin)
}
} catch (e) {
- this.logger.error({ tag: this.deleteUserOrGuest.name, msg: `unable to delete *${userLogin}* (${userId}) : ${e}` })
+ this.logger.error({ tag: this.deleteUserOrGuest.name, msg: `unable to delete *${userLogin}* (${userId}) : ${toErrorMessage(e)}` })
throw new HttpException('Unable to delete user', HttpStatus.INTERNAL_SERVER_ERROR)
}
}
@@ -212,11 +220,12 @@ export class AdminUsersManager {
await this.deleteUserOrGuest(guestToDelete.id, guestToDelete.login, { deleteSpace: true })
}
- listGuests(): Promise<AdminUser[]> {
+ listGuests(): Promise<GuestUser[]> {
return this.adminQueries.usersQueries.listGuests(null, null, true)
}
createGuest(user: UserModel, createGuestDto: CreateUserDto): Promise<GuestUser> {
+ createGuestDto.managers ??= []
if (!createGuestDto.managers.length) {
createGuestDto.managers.push(user.id)
}
@@ -235,7 +244,7 @@ export class AdminUsersManager {
async browseGroups(name?: string, type: GROUP_TYPE = GROUP_TYPE.USER): Promise<GroupBrowse> {
if (name) {
- const group: Pick<Group, 'id' | 'name' | 'type'> = await this.adminQueries.groupFromName(name)
+ const group = await this.adminQueries.groupFromName(name)
if (!group) {
throw new HttpException('Group not found', HttpStatus.NOT_FOUND)
}
@@ -261,9 +270,9 @@ export class AdminUsersManager {
try {
const groupId: number = await this.adminQueries.createGroup(createGroupDto)
this.logger.log({ tag: this.createGroup.name, msg: `group (${groupId}) was created : ${JSON.stringify(createGroupDto)}` })
- return this.adminQueries.groupFromId(groupId)
+ return this.getGroup(groupId)
} catch (e) {
- this.logger.error({ tag: this.createGroup.name, msg: `group was not created : ${JSON.stringify(createGroupDto)} : ${e}` })
+ this.logger.error({ tag: this.createGroup.name, msg: `group was not created : ${JSON.stringify(createGroupDto)} : ${toErrorMessage(e)}` })
throw new HttpException('Unable to create group', HttpStatus.INTERNAL_SERVER_ERROR)
}
}
@@ -284,7 +293,7 @@ export class AdminUsersManager {
if (updateGroupDto.visibility !== undefined) {
void this.adminQueries.usersQueries.clearWhiteListCaches('*')
}
- return this.adminQueries.groupFromId(groupId)
+ return this.getGroup(groupId)
}
async deleteGroup(groupId: number): Promise<void> {
@@ -301,14 +310,14 @@ export class AdminUsersManager {
}
async addUsersToGroup(groupId: number, userIds: number[]): Promise<void> {
- const group: AdminGroup = await this.adminQueries.groupFromId(groupId)
+ const group = await this.adminQueries.groupFromId(groupId)
if (!group) {
throw new HttpException('Group not found', HttpStatus.NOT_FOUND)
}
try {
await this.adminQueries.addUsersToGroup(groupId, userIds, group.type === GROUP_TYPE.USER ? USER_ROLE.USER : undefined)
} catch (e) {
- throw new HttpException(e.message, HttpStatus.BAD_REQUEST)
+ throw new HttpException(toErrorMessage(e), HttpStatus.BAD_REQUEST)
}
}
@@ -316,7 +325,7 @@ export class AdminUsersManager {
try {
await this.adminQueries.updateUserFromGroup(groupId, userId, updateUserFromGroupDto.role)
} catch (e) {
- throw new HttpException(e.message, HttpStatus.BAD_REQUEST)
+ throw new HttpException(toErrorMessage(e), HttpStatus.BAD_REQUEST)
}
}
@@ -324,11 +333,11 @@ export class AdminUsersManager {
try {
await this.adminQueries.removeUserFromGroup(groupId, userId)
} catch (e) {
- throw new HttpException(e.message, HttpStatus.BAD_REQUEST)
+ throw new HttpException(toErrorMessage(e), HttpStatus.BAD_REQUEST)
}
}
- searchMembers(searchMembersDto: SearchMembersDto): Promise<Member[]> {
+ searchMembers(searchMembersDto: ValidatedSearchMembersDto): Promise<Member[]> {
return this.adminQueries.usersQueries.searchUsersOrGroups(searchMembersDto)
}
@@ -364,14 +373,14 @@ export class AdminUsersManager {
this.logger.warn({ tag: this.deleteUserSpace.name, msg: `user space *${userLogin}* does not exist : ${userSpace}` })
}
} catch (e) {
- this.logger.warn({ tag: this.deleteUserSpace.name, msg: `user space *${userLogin}* (${userSpace}) was not deleted : ${e}` })
+ this.logger.warn({ tag: this.deleteUserSpace.name, msg: `user space *${userLogin}* (${userSpace}) was not deleted : ${toErrorMessage(e)}` })
throw new HttpException('Unable to delete user space', HttpStatus.INTERNAL_SERVER_ERROR)
}
}
- checkUser(user: User | AdminUser | GuestUser, checkOnly: true): void
- checkUser(user: User | AdminUser | GuestUser, checkOnly?: false): UserModel
- checkUser(user: User | AdminUser | GuestUser, checkOnly = false): UserModel | void {
+ checkUser(user: User | AdminUser | GuestUser | null | undefined, checkOnly: true): asserts user is User | AdminUser | GuestUser
+ checkUser(user: User | AdminUser | GuestUser | null | undefined, checkOnly?: false): UserModel
+ checkUser(user: User | AdminUser | GuestUser | null | undefined, checkOnly = false): UserModel | void {
if (!user) {
throw new HttpException('User not found', HttpStatus.NOT_FOUND)
}
@@ -397,7 +406,10 @@ export class AdminUsersManager {
} catch (e) {
// try to restore
await moveFiles(newUserSpace, currentUserSpace, true)
- this.logger.error({ tag: this.renameUserSpace.name, msg: `unable to rename user space from *${currentUserSpace}* to *${newUserSpace}* : ${e}` })
+ this.logger.error({
+ tag: this.renameUserSpace.name,
+ msg: `unable to rename user space from *${currentUserSpace}* to *${newUserSpace}* : ${toErrorMessage(e)}`
+ })
return false
}
}
diff --git a/backend/src/applications/users/services/admin-users-queries.service.ts b/backend/src/applications/users/services/admin-users-queries.service.ts
index aeb2dd7b..45ab018b 100644
--- a/backend/src/applications/users/services/admin-users-queries.service.ts
+++ b/backend/src/applications/users/services/admin-users-queries.service.ts
@@ -1,5 +1,6 @@
+import { toErrorMessage } from '../../../common/errors.js'
import { Inject, Injectable, Logger } from '@nestjs/common'
-import { and, count, countDistinct, eq, inArray, isNotNull, isNull, lte, SelectedFields, SQL, sql } from 'drizzle-orm'
+import { and, count, countDistinct, eq, inArray, isNotNull, isNull, lte, SQL, sql } from 'drizzle-orm'
import { alias, union } from 'drizzle-orm/mysql-core'
import { DB_TOKEN_PROVIDER } from '../../../infrastructure/database/constants.js'
import { type DBSchema } from '../../../infrastructure/database/interfaces/database.interface.js'
@@ -8,13 +9,13 @@ import { UserMailNotification } from '../../notifications/interfaces/user-mail-n
import { GROUP_TYPE } from '../constants/group.js'
import { MEMBER_TYPE } from '../constants/member.js'
import { USER_GROUP_ROLE, USER_ROLE, USER_SECRET } from '../constants/user.js'
-import { CreateOrUpdateGroupDto } from '../dto/create-or-update-group.dto.js'
+import type { CreateOrUpdateGroupDto } from '../dto/create-or-update-group.dto.js'
import type { AdminGroup } from '../interfaces/admin-group.interface.js'
import type { AdminUser } from '../interfaces/admin-user.interface.js'
import { Member } from '../interfaces/member.interface.js'
import type { Group } from '../schemas/group.interface.js'
import { groups } from '../schemas/groups.schema.js'
-import { UserGroup } from '../schemas/user-group.interface.js'
+import type { UserGroup } from '../schemas/user-group.interface.js'
import { usersGroups } from '../schemas/users-groups.schema.js'
import { usersGuests } from '../schemas/users-guests.schema.js'
import { userFullNameSQL, users } from '../schemas/users.schema.js'
@@ -30,8 +31,8 @@ export class AdminUsersQueries {
) {}
async listUsers(): Promise<AdminUser[]>
- async listUsers(userId: number): Promise<AdminUser>
- async listUsers(userId?: number): Promise<AdminUser | AdminUser[]> {
+ async listUsers(userId: number): Promise<AdminUser | null>
+ async listUsers(userId?: number): Promise<AdminUser | AdminUser[] | null> {
const where: SQL[] = [lte(users.role, USER_ROLE.USER), ...(userId ? [eq(users.id, userId)] : [])]
const q = this.db
.select({
@@ -54,7 +55,7 @@ export class AdminUsersQueries {
type: sql`${MEMBER_TYPE.GROUP}`,
permissions: groups.permissions,
createdAt: dateTimeUTC(usersGroups.createdAt)
- } satisfies Record<keyof Pick<Member, 'id' | 'name' | 'description' | 'type' | 'permissions' | 'createdAt'>, any>)
+ } satisfies { [K in keyof Member]: any })
}),
language: users.language,
passwordAttempts: users.passwordAttempts,
@@ -65,7 +66,7 @@ export class AdminUsersQueries {
currentAccess: users.currentAccess,
lastAccess: users.lastAccess,
createdAt: users.createdAt
- } satisfies AdminUser | SelectedFields<any, any>)
+ } satisfies { [K in keyof AdminUser]: any })
.from(users)
if (userId) {
q.leftJoin(usersGroups, eq(usersGroups.userId, users.id))
@@ -87,7 +88,7 @@ export class AdminUsersQueries {
.where(eq(users.role, USER_ROLE.ADMINISTRATOR))
}
- async groupFromId(groupId: number): Promise<AdminGroup> {
+ async groupFromId(groupId: number): Promise<AdminGroup | undefined> {
const groupParent = alias(groups, 'groupParent')
const [group] = await this.db
.select({
@@ -100,7 +101,7 @@ export class AdminUsersQueries {
createdAt: groups.createdAt,
modifiedAt: groups.modifiedAt,
parent: { id: groupParent.id, name: groupParent.name }
- } satisfies AdminGroup | SelectedFields<any, any>)
+ } satisfies Record<keyof AdminGroup, any>)
.from(groups)
.leftJoin(groupParent, eq(groupParent.id, groups.parentId))
.where(eq(groups.id, groupId))
@@ -112,13 +113,13 @@ export class AdminUsersQueries {
return dbCheckAffectedRows(await this.db.delete(users).where(and(eq(users.id, userId), eq(users.login, userLogin))), 1, false)
}
- async groupFromName(groupName: string): Promise<Pick<Group, 'id' | 'name' | 'type'>> {
+ async groupFromName(groupName: string): Promise<Pick<Group, 'id' | 'name' | 'type'> | undefined> {
const [group] = await this.db
.select({
id: groups.id,
name: groups.name,
type: groups.type
- } satisfies Pick<Group, 'id' | 'name' | 'type'> | SelectedFields<any, any>)
+ } satisfies Partial<Record<keyof Group, any>>)
.from(groups)
.where(eq(groups.name, groupName))
.limit(1)
@@ -136,7 +137,7 @@ export class AdminUsersQueries {
modifiedAt: groups.modifiedAt,
type: sql<MEMBER_TYPE>`IF(${groups.type} = ${GROUP_TYPE.USER}, ${MEMBER_TYPE.GROUP}, ${MEMBER_TYPE.PGROUP})`,
counts: { users: count(usersGroups.userId), groups: countDistinct(childGroups.id) }
- } satisfies Member | SelectedFields<any, any>)
+ } satisfies { [K in keyof Member]: any })
.from(groups)
.leftJoin(usersGroups, eq(usersGroups.groupId, groups.id))
.leftJoin(childGroups, eq(childGroups.parentId, groups.id))
@@ -159,14 +160,14 @@ export class AdminUsersQueries {
type: sql<MEMBER_TYPE>`${MEMBER_TYPE.USER}`,
groupRole: sql<USER_GROUP_ROLE>`${usersGroups.role}`.mapWith(Number),
counts: { users: sql<number>`0`, groups: sql<number>`0` }
- } satisfies Member | SelectedFields<any, any>)
+ } satisfies { [K in keyof Member]: any })
.from(groups)
.innerJoin(usersGroups, eq(usersGroups.groupId, groups.id))
.leftJoin(users, eq(users.id, usersGroups.userId))
.where(and(eq(groups.id, groupId), eq(groups.type, type), isNotNull(users.id)))
.groupBy(users.id)
if (type === GROUP_TYPE.PERSONAL) {
- return userMembers
+ return userMembers as Promise<Member[]>
}
const groupMembers: any = this.db
.select({
@@ -179,7 +180,7 @@ export class AdminUsersQueries {
type: sql<MEMBER_TYPE>`${MEMBER_TYPE.GROUP}`,
groupRole: sql<USER_GROUP_ROLE>`null`,
counts: { users: count(usersGroups.userId), groups: count(subChildGroups.id) }
- } satisfies Member | SelectedFields<any, any>)
+ } satisfies { [K in keyof Member]: any })
.from(groups)
.innerJoin(childGroups, eq(childGroups.parentId, groups.id))
.leftJoin(usersGroups, eq(usersGroups.groupId, childGroups.id))
@@ -187,7 +188,7 @@ export class AdminUsersQueries {
.leftJoin(subChildGroups, eq(subChildGroups.parentId, childGroups.id))
.where(and(eq(groups.id, groupId), eq(groups.type, type), isNotNull(childGroups.id)))
.groupBy(childGroups.id)
- return union(userMembers, groupMembers)
+ return union(userMembers, groupMembers) as Promise<Member[]>
}
async updateUserGroups(userId: number, groups: { add: number[]; delete: number[] }): Promise<void> {
@@ -206,7 +207,10 @@ export class AdminUsersQueries {
void this.usersQueries.clearWhiteListCaches([userId])
await this.usersQueries.clearWebDAVAuthCache(userId)
} catch (e) {
- this.logger.error({ tag: this.updateUserGroups.name, msg: `user (${userId}) groups ${JSON.stringify(groups.add)} was not added: ${e}` })
+ this.logger.error({
+ tag: this.updateUserGroups.name,
+ msg: `user (${userId}) groups ${JSON.stringify(groups.add)} was not added: ${toErrorMessage(e)}`
+ })
throw new Error('User groups was not added')
}
}
@@ -220,7 +224,10 @@ export class AdminUsersQueries {
void this.usersQueries.clearWhiteListCaches([userId])
await this.usersQueries.clearWebDAVAuthCache(userId)
} catch (e) {
- this.logger.error({ tag: this.updateUserGroups.name, msg: `user (${userId}) groups ${JSON.stringify(groups.delete)} was not deleted: ${e}` })
+ this.logger.error({
+ tag: this.updateUserGroups.name,
+ msg: `user (${userId}) groups ${JSON.stringify(groups.delete)} was not deleted: ${toErrorMessage(e)}`
+ })
throw new Error('User groups was not deleted')
}
}
@@ -236,7 +243,7 @@ export class AdminUsersQueries {
this.logger.log({ tag: this.updateGroup.name, msg: `group (${groupId}) was updated : ${JSON.stringify(set)}` })
return true
} catch (e) {
- this.logger.error({ tag: this.updateGroup.name, msg: `group (${groupId}) was not updated : ${JSON.stringify(set)} : ${e}` })
+ this.logger.error({ tag: this.updateGroup.name, msg: `group (${groupId}) was not updated : ${JSON.stringify(set)} : ${toErrorMessage(e)}` })
return false
}
}
@@ -277,7 +284,7 @@ export class AdminUsersQueries {
void this.usersQueries.clearWhiteListCaches(userIds)
await this.usersQueries.clearWebDAVAuthCache(userIds)
} catch (e) {
- this.logger.error({ tag: this.addUsersToGroup.name, msg: `unable to add users (${userIds}) to group (${groupId}) : ${e}` })
+ this.logger.error({ tag: this.addUsersToGroup.name, msg: `unable to add users (${userIds}) to group (${groupId}) : ${toErrorMessage(e)}` })
throw new Error('Unable to add users to group')
}
}
@@ -296,7 +303,7 @@ export class AdminUsersQueries {
} catch (e) {
this.logger.error({
tag: this.updateUserFromGroup.name,
- msg: `user (${userId}) was not updated on group (${groupId}) as ${USER_GROUP_ROLE[role]} : ${e}`
+ msg: `user (${userId}) was not updated on group (${groupId}) as ${USER_GROUP_ROLE[role]} : ${toErrorMessage(e)}`
})
throw new Error('Unable to update user from group')
}
@@ -315,7 +322,7 @@ export class AdminUsersQueries {
void this.usersQueries.clearWhiteListCaches([userId])
await this.usersQueries.clearWebDAVAuthCache(userId)
} catch (e) {
- this.logger.error({ tag: this.removeUserFromGroup.name, msg: `user (${userId}) or group (${groupId}) does not exist : ${e}` })
+ this.logger.error({ tag: this.removeUserFromGroup.name, msg: `user (${userId}) or group (${groupId}) does not exist : ${toErrorMessage(e)}` })
throw new Error('Unable to remove user from group')
}
}
@@ -336,7 +343,7 @@ export class AdminUsersQueries {
} catch (e) {
this.logger.error({
tag: this.updateGuestManagers.name,
- msg: `guest (${guestId}) managers ${JSON.stringify(managers.add)} was not added: ${e}`
+ msg: `guest (${guestId}) managers ${JSON.stringify(managers.add)} was not added: ${toErrorMessage(e)}`
})
throw new Error('Guest managers was not added')
}
@@ -351,7 +358,7 @@ export class AdminUsersQueries {
} catch (e) {
this.logger.error({
tag: this.updateGuestManagers.name,
- msg: `guest (${guestId}) managers ${JSON.stringify(managers.delete)} was not deleted: ${e}`
+ msg: `guest (${guestId}) managers ${JSON.stringify(managers.delete)} was not deleted: ${toErrorMessage(e)}`
})
throw new Error('Guest managers was not deleted')
}
diff --git a/backend/src/applications/users/services/users-manager.service.spec.ts b/backend/src/applications/users/services/users-manager.service.spec.ts
index a3d6dad7..6f7bcbec 100755
--- a/backend/src/applications/users/services/users-manager.service.spec.ts
+++ b/backend/src/applications/users/services/users-manager.service.spec.ts
@@ -28,8 +28,8 @@ import {
USER_PERMISSION,
USER_ROLE
} from '../constants/user.js'
-import { CreateUserDto } from '../dto/create-or-update-user.dto.js'
-import { DeleteUserDto } from '../dto/delete-user.dto.js'
+import type { CreateUserDto } from '../dto/create-or-update-user.dto.js'
+import type { DeleteUserDto } from '../dto/delete-user.dto.js'
import { UserSecrets } from '../interfaces/user-secrets.interface.js'
import { UserModel } from '../models/user.model.js'
import { generateUserTest } from '../utils/test.js'
@@ -168,11 +168,11 @@ describe(UsersManager.name, () => {
expect(u1.password).toBeUndefined()
const u2 = await usersManager.findUser(userTest.login, false)
expect(u2).toBeInstanceOf(UserModel)
- expect(u2.password).toBeDefined()
- const externalLookupSpy = vi.spyOn(usersQueriesService, 'fromExternalIdOrEmail').mockResolvedValue(userTest)
+ expect(u2!.password).toBeDefined()
+ const externalLookupSpy = vi.spyOn(usersQueriesService, 'fromExternalIdOrEmail').mockResolvedValue(userTest as any)
const externalUser = await usersManager.findUserByExternalIdOrEmail('subject-1', userTest.email, false)
expect(externalUser).toBeInstanceOf(UserModel)
- expect(externalUser.password).toBeDefined()
+ expect(externalUser!.password).toBeDefined()
expect(externalLookupSpy).toHaveBeenCalledWith('subject-1', userTest.email)
const me1: any = await usersManager.me(userTest)
expect(me1.user.password).toBeUndefined()
@@ -214,11 +214,11 @@ describe(UsersManager.name, () => {
const resolved = await usersManager.fromAuthToken(authUser)
- expect(resolved.role).toBe(USER_ROLE.USER)
- expect(resolved.applications).toEqual([USER_PERMISSION.SPACES])
- expect(resolved.clientId).toBe('client-id')
- expect(resolved.authSession).toBe(AUTH_SESSION.OIDC)
- expect(resolved.exp).toBe(1234)
+ expect(resolved!.role).toBe(USER_ROLE.USER)
+ expect(resolved!.applications).toEqual([USER_PERMISSION.SPACES])
+ expect(resolved!.clientId).toBe('client-id')
+ expect(resolved!.authSession).toBe(AUTH_SESSION.OIDC)
+ expect(resolved!.exp).toBe(1234)
usersQueriesService.from = vi.fn().mockResolvedValue({ ...currentUser, isActive: false })
await expect(usersManager.fromAuthToken(authUser)).resolves.toBeNull()
@@ -237,8 +237,8 @@ describe(UsersManager.name, () => {
const resolved = await usersManager.fromAuthToken(authUser)
- expect(resolved.impersonatedFromId).toBe(admin.id)
- expect(resolved.impersonatedClientId).toBe('admin-client')
+ expect(resolved!.impersonatedFromId).toBe(admin.id)
+ expect(resolved!.impersonatedClientId).toBe('admin-client')
const formerAdmin = { ...generateUserTest(), id: 1, role: USER_ROLE.USER }
usersQueriesService.from = vi.fn().mockImplementation(async (id: number) => (id === authUser.id ? currentUser : formerAdmin))
@@ -264,7 +264,7 @@ describe(UsersManager.name, () => {
usersQueriesService.checkUserExists = vi.fn().mockReturnValue(undefined)
usersQueriesService.createUserOrGuest = vi.fn().mockReturnValue(888)
usersQueriesService.clearWhiteListCaches = vi.fn()
- const created = await adminUsersManager.createUserOrGuest(userTest satisfies CreateUserDto, USER_ROLE.USER)
+ const created = await adminUsersManager.createUserOrGuest(userTest as CreateUserDto, USER_ROLE.USER)
expect(created).toBeInstanceOf(UserModel)
expect(await isPathExists(created.filesPath)).toBe(true)
@@ -273,12 +273,12 @@ describe(UsersManager.name, () => {
.mockReturnValueOnce({ login: userTest.login, email: '' })
.mockReturnValueOnce({ login: '', email: userTest.email })
.mockReturnValueOnce(undefined)
- await expect(adminUsersManager.createUserOrGuest(userTest satisfies CreateUserDto, USER_ROLE.USER)).rejects.toThrow()
- await expect(adminUsersManager.createUserOrGuest(userTest satisfies CreateUserDto, USER_ROLE.USER)).rejects.toThrow()
+ await expect(adminUsersManager.createUserOrGuest(userTest as CreateUserDto, USER_ROLE.USER)).rejects.toThrow()
+ await expect(adminUsersManager.createUserOrGuest(userTest as CreateUserDto, USER_ROLE.USER)).rejects.toThrow()
usersQueriesService.createUserOrGuest = vi.fn().mockImplementation(() => {
throw new Error('testing')
})
- await expect(adminUsersManager.createUserOrGuest(userTest satisfies CreateUserDto, USER_ROLE.USER)).rejects.toThrow()
+ await expect(adminUsersManager.createUserOrGuest(userTest as CreateUserDto, USER_ROLE.USER)).rejects.toThrow()
adminUsersQueries.deleteUser = vi.fn().mockReturnValue(true)
await expect(adminUsersManager.deleteUserOrGuest(userTest.id, userTest.login, deleteUserDto)).resolves.not.toThrow()
@@ -320,7 +320,7 @@ describe(UsersManager.name, () => {
const out = await usersManager.logUser(uBad, 'bad', '1.1.1.1')
expect(out).toBeNull()
await flush()
- expect(errSpy.mock.calls.some(([payload]: { msg: string }[]) => payload?.msg?.includes('reject-auth'))).toBe(true)
+ expect(errSpy.mock.calls.some(([payload]) => (payload as { msg?: string } | undefined)?.msg?.includes('reject-auth'))).toBe(true)
expect(updateAccessesSpy).toHaveBeenCalledWith(uBad, '1.1.1.1', false)
vi.mocked(comparePassword).mockResolvedValue(true)
const uGood = new UserModel({ ...generateUserTest(), isActive: true, passwordAttempts: 0 }, false)
@@ -567,7 +567,7 @@ describe(UsersManager.name, () => {
await expect(usersManager.validateAppPassword(localUser, 'pwd', '192.0.2.10', AUTH_SCOPE.WEBDAV)).resolves.toBe(true)
expect(getCurrentSecrets().twoFaSecret).toBe('two-fa')
- expect(getCurrentSecrets().appPasswords[0]).toEqual(
+ expect(getCurrentSecrets().appPasswords![0]).toEqual(
expect.objectContaining({
name: matchedPassword.name,
lastAccess: matchedPassword.currentAccess,
@@ -1091,7 +1091,7 @@ describe(UsersManager.name, () => {
usersQueriesService.listGuests = vi.fn().mockResolvedValue([{ id: 1 }])
await expect(usersManager.listGuests(userTest)).resolves.toEqual([{ id: 1 }])
- const checkSpy = vi.spyOn(adminUsersManager, 'checkUser').mockImplementation(() => undefined)
+ const checkSpy = vi.spyOn(adminUsersManager, 'checkUser').mockImplementation(() => undefined as never)
usersQueriesService.listGuests = vi.fn().mockResolvedValue({ id: 9 })
await expect(usersManager.getGuest(userTest, 9)).resolves.toEqual({ id: 9 })
expect(checkSpy).toHaveBeenCalled()
@@ -1101,14 +1101,14 @@ describe(UsersManager.name, () => {
usersQueriesService.usersWhitelist = vi.fn().mockResolvedValue([userTest.id, 100])
const createSpy = vi.spyOn(adminUsersManager, 'createUserOrGuest').mockResolvedValue({ id: 55 } as any)
- const dto1: CreateUserDto = { ...userTest, managers: [100], password: 'x' }
+ const dto1 = { ...userTest, managers: [100], password: 'x' } as CreateUserDto
const r = await usersManager.createGuest(userTest, dto1)
expect(createSpy).toHaveBeenCalled()
expect(r).toEqual({ id: 55 })
const args1 = vi.mocked(createSpy).mock.calls[0][0]
expect(args1.managers).toEqual(expect.arrayContaining([userTest.id]))
vi.mocked(createSpy).mockClear()
- const dto2: CreateUserDto = { ...userTest, managers: [userTest.id, 100], password: 'y' }
+ const dto2 = { ...userTest, managers: [userTest.id, 100], password: 'y' } as CreateUserDto
await usersManager.createGuest(userTest, dto2)
const args2 = vi.mocked(createSpy).mock.calls[0][0]
expect((args2.managers as number[]).filter((m: number) => m === userTest.id)).toHaveLength(1)
@@ -1120,7 +1120,7 @@ describe(UsersManager.name, () => {
usersQueriesService.groupsWhitelist = vi.fn().mockResolvedValue([10])
const createSpy = vi.spyOn(adminUsersManager, 'createUserOrGuest').mockResolvedValue({ id: 55 } as any)
- const dto: CreateUserDto = { ...userTest, managers: [100], groups: [10, 11], password: 'x' }
+ const dto = { ...userTest, managers: [100], groups: [10, 11], password: 'x' } as CreateUserDto
await expect(usersManager.createGuest(userTest, dto)).resolves.toEqual({ id: 55 })
expect(usersQueriesService.groupsWhitelist).toHaveBeenCalledWith(userTest.id, GROUP_TYPE.PERSONAL, USER_GROUP_ROLE.MANAGER)
const args = vi.mocked(createSpy).mock.calls[0][0]
@@ -1134,7 +1134,7 @@ describe(UsersManager.name, () => {
usersQueriesService.groupsWhitelist = vi.fn().mockResolvedValue([10, 11])
const createSpy = vi.spyOn(adminUsersManager, 'createUserOrGuest').mockResolvedValue({ id: 55 } as any)
- const dto: CreateUserDto = { ...userTest, managers: [100], groups: [10, 11], password: 'x' }
+ const dto = { ...userTest, managers: [100], groups: [10, 11], password: 'x' } as CreateUserDto
await expect(usersManager.createGuest(userTest, dto)).resolves.toEqual({ id: 55 })
expect(usersQueriesService.groupsWhitelist).toHaveBeenCalledWith(userTest.id, GROUP_TYPE.PERSONAL, USER_GROUP_ROLE.MANAGER)
const args = vi.mocked(createSpy).mock.calls[0][0]
diff --git a/backend/src/applications/users/services/users-manager.service.ts b/backend/src/applications/users/services/users-manager.service.ts
index 506b51ec..8157bbcb 100755
--- a/backend/src/applications/users/services/users-manager.service.ts
+++ b/backend/src/applications/users/services/users-manager.service.ts
@@ -1,4 +1,3 @@
-import { MultipartFile } from '@fastify/multipart'
import { HttpException, HttpStatus, Injectable, Logger } from '@nestjs/common'
import bcrypt from 'bcryptjs'
import { WriteStream } from 'fs'
@@ -9,9 +8,10 @@ import { AUTH_SCOPE } from '../../../authentication/constants/scope.js'
import { LoginResponseDto } from '../../../authentication/dto/login-response.dto.js'
import { AuthPasswordWorkLimitException } from '../../../authentication/errors/auth-password-work-limit.exception.js'
import { FastifyAuthenticatedRequest } from '../../../authentication/interfaces/auth-request.interface.js'
-import { JwtIdentityPayload } from '../../../authentication/interfaces/jwt-payload.interface.js'
+import type { JwtIdentityPayload } from '../../../authentication/interfaces/jwt-payload.interface.js'
import { AUTH_SESSION } from '../../../authentication/providers/auth-providers.constants.js'
import { consumePasswordWorkRateLimit } from '../../../authentication/utils/auth-rate-limit.js'
+import { toErrorMessage } from '../../../common/errors.js'
import { comparePassword, hashPassword } from '../../../common/functions.js'
import { convertTempImageToPng, generateAvatar, imgMimeTypePrefix, pngMimeType, svgMimeType } from '../../../common/image.js'
import { createLightSlug, genPassword } from '../../../common/shared.js'
@@ -32,7 +32,7 @@ import {
} from '../constants/user.js'
import type { UserCreateOrUpdateGroupDto } from '../dto/create-or-update-group.dto.js'
import type { CreateUserDto, UpdateUserDto, UpdateUserFromGroupDto } from '../dto/create-or-update-user.dto.js'
-import type { SearchMembersDto } from '../dto/search-members.dto.js'
+import type { ValidatedSearchMembersDto } from '../dto/search-members.dto.js'
import type {
UserAppPasswordDto,
UserLanguageDto,
@@ -49,9 +49,6 @@ import type { UserPreferences } from '../interfaces/user-preferences.interface.j
import type { UserAppPassword, UserSecrets } from '../interfaces/user-secrets.interface.js'
import type { UserOnline } from '../interfaces/websocket.interface.js'
import { UserModel } from '../models/user.model.js'
-import type { Group } from '../schemas/group.interface.js'
-import type { UserGroup } from '../schemas/user-group.interface.js'
-import type { User } from '../schemas/user.interface.js'
import { saveAvatarMetadata, USER_AVATAR_FILE_NAME, USER_AVATAR_MAX_UPLOAD_SIZE, USER_DEFAULT_AVATAR_FILE_PATH } from '../utils/avatar.js'
import { AdminUsersManager } from './admin-users-manager.service.js'
import { UsersQueries } from './users-queries.service.js'
@@ -67,8 +64,8 @@ export class UsersManager {
private readonly cache: Cache
) {}
- async fromUserId(id: number): Promise<UserModel> {
- const user: User = await this.usersQueries.from(id)
+ async fromUserId(id: number): Promise<UserModel | null> {
+ const user = await this.usersQueries.from(id)
return user ? new UserModel(user, true) : null
}
@@ -91,17 +88,17 @@ export class UsersManager {
return user
}
- async findUser(loginOrEmail: string, removePassword: false): Promise<UserModel>
- async findUser(loginOrEmail: string, removePassword?: true): Promise<Omit<UserModel, 'password'>>
- async findUser(loginOrEmail: string, removePassword: boolean = true): Promise<Omit<UserModel, 'password'>> {
- const user: User = await this.usersQueries.from(null, loginOrEmail)
+ async findUser(loginOrEmail: string, removePassword: false): Promise<UserModel | null>
+ async findUser(loginOrEmail: string, removePassword?: true): Promise<Omit<UserModel, 'password'> | null>
+ async findUser(loginOrEmail: string, removePassword: boolean = true): Promise<Omit<UserModel, 'password'> | null> {
+ const user = await this.usersQueries.from(null, loginOrEmail)
return user ? new UserModel(user, removePassword) : null
}
- async findUserByExternalIdOrEmail(externalId: string, email: string, removePassword: false): Promise<UserModel>
- async findUserByExternalIdOrEmail(externalId: string, email: string, removePassword?: true): Promise<Omit<UserModel, 'password'>>
- async findUserByExternalIdOrEmail(externalId: string, email: string, removePassword: boolean = true): Promise<Omit<UserModel, 'password'>> {
- const user: User = await this.usersQueries.fromExternalIdOrEmail(externalId, email)
+ async findUserByExternalIdOrEmail(externalId: string, email: string, removePassword: false): Promise<UserModel | null>
+ async findUserByExternalIdOrEmail(externalId: string, email: string, removePassword?: true): Promise<Omit<UserModel, 'password'> | null>
+ async findUserByExternalIdOrEmail(externalId: string, email: string, removePassword: boolean = true): Promise<Omit<UserModel, 'password'> | null> {
+ const user = await this.usersQueries.fromExternalIdOrEmail(externalId, email)
return user ? new UserModel(user, removePassword) : null
}
@@ -112,7 +109,7 @@ export class UsersManager {
scope?: AUTH_SCOPE,
canAuthenticate?: (user: UserModel) => boolean
): Promise<UserModel | null> {
- const user: UserModel = await this.findUser(loginOrEmail, false)
+ const user = await this.findUser(loginOrEmail, false)
return this.validateLocalPasswordForUser(user, loginOrEmail, password, ip, scope, canAuthenticate)
}
@@ -145,10 +142,10 @@ export class UsersManager {
}
return null
}
- return this.logUser(user, password, ip, scope)
+ return this.logUser(user, password, ip as string | null, scope)
}
- async logUser(user: UserModel, password: string, ip: string, scope?: AUTH_SCOPE): Promise<UserModel | null> {
+ async logUser(user: UserModel, password: string, ip: string | null, scope?: AUTH_SCOPE): Promise<UserModel | null> {
let accessDenied: HttpException | null = null
try {
await this.validateUserAccess(user)
@@ -169,7 +166,7 @@ export class UsersManager {
if (!authSuccess && scope) {
authSuccess = await this.validateAppPassword(user, password, ip, scope)
}
- this.updateAccesses(user, ip, authSuccess).catch((e: Error) => this.logger.error({ tag: this.logUser.name, msg: `${e}` }))
+ this.updateAccesses(user, ip, authSuccess).catch((e: Error) => this.logger.error({ tag: this.logUser.name, msg: toErrorMessage(e) }))
if (authSuccess) {
await user.makePaths()
return user
@@ -261,7 +258,7 @@ export class UsersManager {
try {
return await this.usersQueries.updateUserPreferences(user.id, patch)
} catch (e) {
- this.logger.error({ tag: this.updatePreferences.name, msg: `Unable to update preferences for user (${user.id}) : ${e}` })
+ this.logger.error({ tag: this.updatePreferences.name, msg: `Unable to update preferences for user (${user.id}) : ${toErrorMessage(e)}` })
throw new HttpException('Unable to update preferences', HttpStatus.INTERNAL_SERVER_ERROR)
}
}
@@ -273,19 +270,19 @@ export class UsersManager {
}
async updateAvatar(req: FastifyAuthenticatedRequest) {
- const part: MultipartFile = await req.file({ limits: { fileSize: USER_AVATAR_MAX_UPLOAD_SIZE } })
- if (!part.mimetype.startsWith(imgMimeTypePrefix)) {
+ const part = await req.file({ limits: { fileSize: USER_AVATAR_MAX_UPLOAD_SIZE } })
+ if (!part!.mimetype.startsWith(imgMimeTypePrefix)) {
throw new HttpException('Unsupported file type', HttpStatus.BAD_REQUEST)
}
const tmpPath = temporaryFilePath(req.user.tmpPath, USER_AVATAR_FILE_NAME, 'avatar')
try {
- await pipeline(part.file, createWriteStream(tmpPath))
+ await pipeline(part!.file, createWriteStream(tmpPath))
} catch (e) {
void removeFiles(tmpPath)
- this.logger.error({ tag: this.updateAvatar.name, msg: `${e}` })
+ this.logger.error({ tag: this.updateAvatar.name, msg: toErrorMessage(e) })
throw new HttpException('Unable to upload avatar', HttpStatus.INTERNAL_SERVER_ERROR)
}
- if (part.file.truncated) {
+ if (part!.file.truncated) {
void removeFiles(tmpPath)
this.logger.warn({ tag: this.updateAvatar.name, msg: `image is too large` })
throw new HttpException('Image is too large', HttpStatus.PAYLOAD_TOO_LARGE)
@@ -296,7 +293,7 @@ export class UsersManager {
void saveAvatarMetadata(req.user.login, 'user')
} catch (e) {
void removeFiles(tmpPath)
- this.logger.error({ tag: this.updateAvatar.name, msg: `${e}` })
+ this.logger.error({ tag: this.updateAvatar.name, msg: toErrorMessage(e) })
throw new HttpException('Unable to convert or create avatar', HttpStatus.BAD_REQUEST)
}
}
@@ -311,7 +308,7 @@ export class UsersManager {
await this.usersQueries.clearWebDAVAuthCache(userId)
}
} catch (e) {
- this.logger.error({ tag: this.updateSecrets.name, msg: `Unable to update secrets for user (${userId}) : ${e}` })
+ this.logger.error({ tag: this.updateSecrets.name, msg: `Unable to update secrets for user (${userId}) : ${toErrorMessage(e)}` })
throw new HttpException('Unable to update secrets', HttpStatus.INTERNAL_SERVER_ERROR)
}
}
@@ -331,7 +328,7 @@ export class UsersManager {
})
}
- async updateAccesses(user: UserModel, ip: string, success: boolean, isAuthTwoFa = false) {
+ async updateAccesses(user: UserModel, ip: string | null, success: boolean, isAuthTwoFa = false) {
const preservePasswordAttempts = success && !isAuthTwoFa && configuration.auth.mfa.totp.enabled && user.twoFaEnabled
const result = await this.usersQueries.updateAccesses(user.id, ip, preservePasswordAttempts ? 'preserve' : success ? 'reset' : 'increment')
if (!result.success) {
@@ -342,9 +339,9 @@ export class UsersManager {
}
}
- async getAvatar(userLogin: string, generate: true, generateIsNotExists?: boolean): Promise<undefined>
+ async getAvatar(userLogin: string, generate: true, generateIsNotExists?: boolean): Promise<void>
async getAvatar(userLogin: string, generate?: false, generateIsNotExists?: boolean): Promise<[path: string, mime: string]>
- async getAvatar(userLogin: string, generate: boolean = false, generateIsNotExists?: boolean): Promise<[path: string, mime: string]> {
+ async getAvatar(userLogin: string, generate: boolean = false, generateIsNotExists?: boolean): Promise<[path: string, mime: string] | void> {
const avatarPath = path.join(UserModel.getHomePath(userLogin), USER_AVATAR_FILE_NAME)
const avatarExists = await isPathExists(avatarPath)
if (!avatarExists && generateIsNotExists) {
@@ -356,7 +353,7 @@ export class UsersManager {
if (!(await isPathExists(UserModel.getHomePath(userLogin)))) {
throw new HttpException(`Home path for user *${userLogin}* does not exist`, HttpStatus.FORBIDDEN)
}
- const user: Partial<UserModel> = await this.findUser(userLogin)
+ const user = await this.findUser(userLogin)
if (!user) {
throw new HttpException(`avatar not found`, HttpStatus.NOT_FOUND)
}
@@ -366,7 +363,7 @@ export class UsersManager {
await pipeline(avatarStream, avatarFile)
void saveAvatarMetadata(user.login, 'local')
} catch (e) {
- this.logger.error({ tag: this.getAvatar.name, msg: `${e}` })
+ this.logger.error({ tag: this.getAvatar.name, msg: toErrorMessage(e) })
throw new HttpException('Unable to create avatar', HttpStatus.INTERNAL_SERVER_ERROR)
}
if (generateIsNotExists) {
@@ -391,7 +388,7 @@ export class UsersManager {
const appPassword: UserAppPassword = {
name: slugName,
app: userAppPasswordDto.app,
- expiration: userAppPasswordDto.expiration,
+ expiration: userAppPasswordDto.expiration as Date | null,
password: await hashPassword(clearPassword),
createdAt: new Date(),
currentIp: null,
@@ -412,7 +409,7 @@ export class UsersManager {
})
} catch (e) {
if (e instanceof HttpException) throw e
- this.logger.error({ tag: this.generateAppPassword.name, msg: `Unable to update app passwords for user (${user.id}) : ${e}` })
+ this.logger.error({ tag: this.generateAppPassword.name, msg: `Unable to update app passwords for user (${user.id}) : ${toErrorMessage(e)}` })
throw new HttpException('Unable to update app passwords', HttpStatus.INTERNAL_SERVER_ERROR)
}
// return clear password only once
@@ -432,7 +429,7 @@ export class UsersManager {
}
})
} catch (e) {
- this.logger.error({ tag: this.deleteAppPassword.name, msg: `Unable to delete app password for user (${user.id}) : ${e}` })
+ this.logger.error({ tag: this.deleteAppPassword.name, msg: `Unable to delete app password for user (${user.id}) : ${toErrorMessage(e)}` })
throw new HttpException('Unable to delete app password', HttpStatus.INTERNAL_SERVER_ERROR)
}
if (!appPassword) {
@@ -444,7 +441,7 @@ export class UsersManager {
}
}
- async validateAppPassword(user: UserModel, password: string, ip: string, scope: AUTH_SCOPE): Promise<boolean> {
+ async validateAppPassword(user: UserModel, password: string, ip: string | null, scope: AUTH_SCOPE): Promise<boolean> {
if (!scope) return false
if (!user.haveRole(USER_ROLE.USER)) {
// Keep scoped auth timing close even when app passwords cannot apply to this role.
@@ -461,7 +458,7 @@ export class UsersManager {
for (const p of secrets.appPasswords) {
if (p.app !== scope) continue
const expMs = p.expiration ? new Date(p.expiration) : null
- if (p.expiration && new Date() > expMs) continue // expired
+ if (expMs && new Date() > expMs) continue // expired
hasComparedAppPassword = true
if (await comparePassword(password, p.password)) {
// Keep bcrypt outside the transaction, then recheck that the matched credential still exists under the row lock.
@@ -498,7 +495,9 @@ export class UsersManager {
}
setOnlineStatus(user: JwtIdentityPayload, onlineStatus: USER_ONLINE_STATUS) {
- this.usersQueries.setOnlineStatus(user.id, onlineStatus).catch((e: Error) => this.logger.error({ tag: this.setOnlineStatus.name, msg: `${e}` }))
+ this.usersQueries
+ .setOnlineStatus(user.id, onlineStatus)
+ .catch((e: Error) => this.logger.error({ tag: this.setOnlineStatus.name, msg: toErrorMessage(e) }))
}
getOnlineUsers(userIds: number[]): Promise<UserOnline[]> {
@@ -509,9 +508,9 @@ export class UsersManager {
return this.usersQueries.usersWhitelist(userId)
}
- async browseGroups(user: UserModel, name: string): Promise<GroupBrowse> {
+ async browseGroups(user: UserModel, name?: string): Promise<GroupBrowse> {
if (name) {
- const group: Pick<Group, 'id' | 'name' | 'type'> & { role: UserGroup['role'] } = await this.usersQueries.groupFromName(user.id, name)
+ const group = await this.usersQueries.groupFromName(user.id, name)
if (!group) {
throw new HttpException('Group not found', HttpStatus.NOT_FOUND)
}
@@ -547,7 +546,10 @@ export class UsersManager {
void this.usersQueries.clearWhiteListCaches([user.id])
return this.getGroup(user, groupId, false)
} catch (e) {
- this.logger.error({ tag: this.createPersonalGroup.name, msg: `group was not created : ${JSON.stringify(userCreateOrUpdateGroupDto)} : ${e}` })
+ this.logger.error({
+ tag: this.createPersonalGroup.name,
+ msg: `group was not created : ${JSON.stringify(userCreateOrUpdateGroupDto)} : ${toErrorMessage(e)}`
+ })
throw new HttpException('Unable to create group', HttpStatus.INTERNAL_SERVER_ERROR)
}
}
@@ -566,7 +568,7 @@ export class UsersManager {
try {
await this.usersQueries.updateGroup(groupId, userCreateOrUpdateGroupDto)
} catch (e) {
- throw new HttpException(e.message, HttpStatus.INTERNAL_SERVER_ERROR)
+ throw new HttpException(toErrorMessage(e), HttpStatus.INTERNAL_SERVER_ERROR)
}
return this.getGroup(user, groupId, false, user.isAdmin)
}
@@ -627,7 +629,7 @@ export class UsersManager {
}
async leavePersonalGroup(user: UserModel, groupId: number): Promise<void> {
- const currentGroup: GroupWithMembers = await this.usersQueries.getGroupWithMembers(user.id, groupId, true)
+ const currentGroup = await this.usersQueries.getGroupWithMembers(user.id, groupId, true)
if (!currentGroup || currentGroup.type === MEMBER_TYPE.GROUP) {
throw new HttpException('You are not allowed to do this action', HttpStatus.FORBIDDEN)
}
@@ -644,8 +646,8 @@ export class UsersManager {
await this.usersQueries.updateGroupMembers(groupId, { remove: [user.id] })
this.logger.log({ tag: this.leavePersonalGroup.name, msg: `user (${user.id}) has left group (${groupId})` })
} catch (e) {
- this.logger.error({ tag: this.leavePersonalGroup.name, msg: `user (${user.id}) has not left group (${groupId}) : ${e}` })
- throw new HttpException(e.message, HttpStatus.INTERNAL_SERVER_ERROR)
+ this.logger.error({ tag: this.leavePersonalGroup.name, msg: `user (${user.id}) has not left group (${groupId}) : ${toErrorMessage(e)}` })
+ throw new HttpException(toErrorMessage(e), HttpStatus.INTERNAL_SERVER_ERROR)
}
}
@@ -666,7 +668,7 @@ export class UsersManager {
}
async getGuest(user: UserModel, guestId: number): Promise<GuestUser> {
- const guest: GuestUser = await this.usersQueries.listGuests(guestId, user.id)
+ const guest = await this.usersQueries.listGuests(guestId, user.id)
this.adminUsersManager.checkUser(guest, true)
return guest
}
@@ -674,8 +676,8 @@ export class UsersManager {
async createGuest(user: UserModel, createGuestDto: CreateUserDto): Promise<GuestUser> {
// only allow managers visible to the current user
const userWhiteList = await this.usersQueries.usersWhitelist(user.id, USER_ROLE.USER)
- createGuestDto.managers = createGuestDto.managers.filter((id) => userWhiteList.indexOf(id) > -1)
- if (createGuestDto.managers.indexOf(user.id) === -1) {
+ createGuestDto.managers = (createGuestDto.managers ?? []).filter((id) => userWhiteList.includes(id))
+ if (!createGuestDto.managers.includes(user.id)) {
// force user as manager during creation
createGuestDto.managers.push(user.id)
}
@@ -683,7 +685,7 @@ export class UsersManager {
// only allow personal groups where the current user is a manager
const groupWhiteList = await this.usersQueries.groupsWhitelist(user.id, GROUP_TYPE.PERSONAL, USER_GROUP_ROLE.MANAGER)
const nbGroups = createGuestDto.groups.length
- createGuestDto.groups = createGuestDto.groups.filter((id) => groupWhiteList.indexOf(id) > -1)
+ createGuestDto.groups = createGuestDto.groups.filter((id) => groupWhiteList.includes(id))
if (nbGroups !== createGuestDto.groups.length) {
this.logger.warn({ tag: this.createGuest.name, msg: 'Some groups were not allowed' })
}
@@ -691,7 +693,7 @@ export class UsersManager {
return this.adminUsersManager.createUserOrGuest(createGuestDto, USER_ROLE.GUEST, true)
}
- async updateGuest(user: UserModel, guestId: number, updateGuestDto: UpdateUserDto): Promise<GuestUser> {
+ async updateGuest(user: UserModel, guestId: number, updateGuestDto: UpdateUserDto): Promise<GuestUser | null> {
if (!Object.keys(updateGuestDto).length) {
throw new HttpException('No changes to update', HttpStatus.BAD_REQUEST)
}
@@ -716,7 +718,7 @@ export class UsersManager {
}
}
const guest = await this.adminUsersManager.updateUserOrGuest(guestId, updateGuestDto, USER_ROLE.GUEST)
- return guest.managers.find((m) => m.id === user.id) ? guest : null
+ return guest.managers!.find((m) => m.id === user.id) ? guest : null
}
async deleteGuest(user: UserModel, guestId: number): Promise<void> {
@@ -728,19 +730,19 @@ export class UsersManager {
return this.adminUsersManager.deleteUserOrGuest(guest.id, guest.login, { deleteSpace: true })
}
- searchMembers(user: UserModel, searchMembersDto: SearchMembersDto): Promise<Member[]> {
+ searchMembers(user: UserModel, searchMembersDto: ValidatedSearchMembersDto): Promise<Member[]> {
return this.usersQueries.searchUsersOrGroups(searchMembersDto, user.id)
}
- private notifyTemporaryAccountLock(user: UserModel, ip: string): void {
+ private notifyTemporaryAccountLock(user: UserModel, ip: string | null): void {
const notification = {
app: NOTIFICATION_APP.AUTH_LOCKED,
event: NOTIFICATION_APP_EVENT.AUTH_LOCKED,
element: '',
- url: ip
+ url: ip as string
} satisfies NotificationContent
this.notificationsManager
.sendEmailNotification([user], notification)
- .catch((e: Error) => this.logger.error({ tag: this.notifyTemporaryAccountLock.name, msg: `${e}` }))
+ .catch((e: Error) => this.logger.error({ tag: this.notifyTemporaryAccountLock.name, msg: toErrorMessage(e) }))
}
}
diff --git a/backend/src/applications/users/services/users-queries.service.spec.ts b/backend/src/applications/users/services/users-queries.service.spec.ts
index 1900b0d1..b193bccd 100644
--- a/backend/src/applications/users/services/users-queries.service.spec.ts
+++ b/backend/src/applications/users/services/users-queries.service.spec.ts
@@ -1,8 +1,13 @@
+import { Logger } from '@nestjs/common'
import { CACHE_AUTH_WEBDAV_PREFIX } from '../../../authentication/constants/cache.js'
import type { Cache } from '../../../infrastructure/cache/cache.service.js'
import type { DBSchema } from '../../../infrastructure/database/interfaces/database.interface.js'
import { UsersQueries } from './users-queries.service.js'
+beforeAll(() => {
+ Logger.overrideLogger(['fatal'])
+})
+
describe(`${UsersQueries.name}.from`, () => {
it('trims the identifier before searching by login or email', async () => {
const execute = vi.fn().mockResolvedValue([])
diff --git a/backend/src/applications/users/services/users-queries.service.ts b/backend/src/applications/users/services/users-queries.service.ts
index 86fecbbe..449c1d7b 100644
--- a/backend/src/applications/users/services/users-queries.service.ts
+++ b/backend/src/applications/users/services/users-queries.service.ts
@@ -1,5 +1,6 @@
+import { toErrorMessage } from '../../../common/errors.js'
import { Inject, Injectable, Logger } from '@nestjs/common'
-import { and, countDistinct, desc, eq, gte, inArray, isNotNull, isNull, like, lte, ne, notInArray, or, SelectedFields, SQL, sql } from 'drizzle-orm'
+import { and, countDistinct, desc, eq, gte, inArray, isNotNull, isNull, like, lte, ne, notInArray, or, SQL, sql } from 'drizzle-orm'
import { alias } from 'drizzle-orm/mysql-core'
import { MySql2PreparedQuery, MySqlQueryResult } from 'drizzle-orm/mysql2'
import { CACHE_AUTH_WEBDAV_PREFIX } from '../../../authentication/constants/cache.js'
@@ -20,9 +21,9 @@ import {
import { GROUP_TYPE, GROUP_VISIBILITY } from '../constants/group.js'
import { MEMBER_TYPE } from '../constants/member.js'
import { USER_GROUP_ROLE, USER_MAX_PASSWORD_ATTEMPTS, USER_ONLINE_STATUS, USER_PERMS_SEP, USER_ROLE } from '../constants/user.js'
-import { UserCreateOrUpdateGroupDto } from '../dto/create-or-update-group.dto.js'
-import { CreateUserDto } from '../dto/create-or-update-user.dto.js'
-import { SearchMembersDto } from '../dto/search-members.dto.js'
+import type { UserCreateOrUpdateGroupDto } from '../dto/create-or-update-group.dto.js'
+import type { CreateUserDto } from '../dto/create-or-update-user.dto.js'
+import type { ValidatedSearchMembersDto } from '../dto/search-members.dto.js'
import { GroupMember, GroupWithMembers } from '../interfaces/group-member.js'
import { GuestUser } from '../interfaces/guest-user.interface.js'
import { Member } from '../interfaces/member.interface.js'
@@ -31,10 +32,10 @@ import type { UserPreferences } from '../interfaces/user-preferences.interface.j
import { UserSecrets } from '../interfaces/user-secrets.interface.js'
import { UserOnline } from '../interfaces/websocket.interface.js'
import { UserModel } from '../models/user.model.js'
-import { Group } from '../schemas/group.interface.js'
+import type { Group } from '../schemas/group.interface.js'
import { groups } from '../schemas/groups.schema.js'
-import { UserGroup } from '../schemas/user-group.interface.js'
-import { User } from '../schemas/user.interface.js'
+import type { UserGroup } from '../schemas/user-group.interface.js'
+import type { User } from '../schemas/user.interface.js'
import { usersGroups } from '../schemas/users-groups.schema.js'
import { usersGuests } from '../schemas/users-guests.schema.js'
import { userFullNameSQL, users } from '../schemas/users.schema.js'
@@ -43,16 +44,16 @@ import { normalizeUserPreferences } from '../utils/user.js'
@Injectable()
export class UsersQueries {
private readonly logger = new Logger(UsersQueries.name)
- private fromExternalIdOrEmailPermissionsQuery: MySql2PreparedQuery<any> = null
- private fromLoginOrEmailPermissionsQuery: MySql2PreparedQuery<any> = null
- private fromIdPermissionsQuery: MySql2PreparedQuery<any> = null
+ private fromExternalIdOrEmailPermissionsQuery: MySql2PreparedQuery<any> | null = null
+ private fromLoginOrEmailPermissionsQuery: MySql2PreparedQuery<any> | null = null
+ private fromIdPermissionsQuery: MySql2PreparedQuery<any> | null = null
constructor(
@Inject(DB_TOKEN_PROVIDER) private readonly db: DBSchema,
private readonly cache: Cache
) {}
- checkUserExists(login?: string, email?: string): Promise<{ login?: string; email?: string }> {
+ checkUserExists(login?: string | null, email?: string | null): Promise<{ login?: string; email?: string } | undefined> {
if (!login && !email) {
throw new Error('login or email must be specified')
}
@@ -85,7 +86,7 @@ export class UsersQueries {
email: users.email,
fullName: userFullNameSQL(users),
onlineStatus: users.onlineStatus
- } satisfies UserOnline | SelectedFields<any, any>)
+ } satisfies Record<keyof UserOnline, any>)
.from(users)
.where(inArray(users.id, userIds))
}
@@ -96,13 +97,13 @@ export class UsersQueries {
}
async compareUserPassword(userId: number, password: string): Promise<boolean> {
- const [hash] = (await this.selectUsers(['password'], [eq(users.id, userId)])) as { password: string }[]
+ const [hash] = await this.selectUsers(['password'], [eq(users.id, userId)])
return comparePassword(password, hash?.password)
}
- async from(userId?: number, loginOrEmail?: string): Promise<User> {
+ async from(userId?: number | null, loginOrEmail?: string): Promise<User | null> {
// retrieve user with application permissions
- let pQuery: MySql2PreparedQuery<any> = userId ? this.fromIdPermissionsQuery : this.fromLoginOrEmailPermissionsQuery
+ let pQuery = userId ? this.fromIdPermissionsQuery : this.fromLoginOrEmailPermissionsQuery
if (!pQuery) {
const where = userId
? eq(users.id, sql.placeholder('userId'))
@@ -136,7 +137,7 @@ export class UsersQueries {
return user
}
- async fromExternalIdOrEmail(externalId: string, email: string): Promise<User> {
+ async fromExternalIdOrEmail(externalId: string, email: string): Promise<User | null> {
if (!this.fromExternalIdOrEmailPermissionsQuery) {
const externalIdPlaceholder = sql.placeholder('externalId')
const emailPlaceholder = sql.placeholder('email')
@@ -162,19 +163,14 @@ export class UsersQueries {
}
async getUserSecrets(userId: number): Promise<UserSecrets> {
- const [r]: { secrets: UserSecrets }[] = await this.db.select({ secrets: users.secrets }).from(users).where(eq(users.id, userId)).limit(1)
- return r.secrets || {}
+ const [r] = await this.db.select({ secrets: users.secrets }).from(users).where(eq(users.id, userId)).limit(1)
+ return r!.secrets || {}
}
async mutateUserSecrets<T>(userId: number, mutate: (secrets: UserSecrets) => { result: T; secrets?: UserSecrets }): Promise<T> {
// Every secrets writer must use the latest document while holding the same row lock.
return this.db.transaction(async (tx) => {
- const [user]: { secrets: UserSecrets }[] = await tx
- .select({ secrets: users.secrets })
- .from(users)
- .where(eq(users.id, userId))
- .limit(1)
- .for('update')
+ const [user] = await tx.select({ secrets: users.secrets }).from(users).where(eq(users.id, userId)).limit(1).for('update')
if (!user) {
throw new Error(`User (${userId}) not found`)
}
@@ -208,12 +204,12 @@ export class UsersQueries {
})
}
- selectUsers(fields: Partial<keyof User>[] = ['id', 'login', 'email'], where: SQL[]): Promise<Partial<User>[]> {
- const select: Record<keyof User, any> = convertToSelect(users, fields)
+ selectUsers<K extends keyof User>(fields: readonly K[], where: SQL[]): Promise<Pick<User, K>[]> {
+ const select = convertToSelect(users, fields)
return this.db
.select(select)
.from(users)
- .where(and(...where))
+ .where(and(...where)) as Promise<Pick<User, K>[]>
}
async usersHaveRole(userIds: number[], role: USER_ROLE): Promise<boolean> {
@@ -226,10 +222,10 @@ export class UsersQueries {
return matchingUsers.length === uniqueUserIds.length
}
- async selectUserProperties(userId: number, fields: Partial<keyof User>[]): Promise<Partial<User>> {
- const select: Record<keyof User, any> = convertToSelect(users, fields)
- const [r]: Record<string, any>[] = await this.db.select(select).from(users).where(eq(users.id, userId)).limit(1)
- return r
+ async selectUserProperties<K extends keyof User>(userId: number, fields: readonly K[]): Promise<Pick<User, K> | undefined> {
+ const select = convertToSelect(users, fields)
+ const [user] = (await this.db.select(select).from(users).where(eq(users.id, userId)).limit(1)) as Pick<User, K>[]
+ return user
}
async createUserOrGuest(createUserDto: CreateUserDto, userRole: USER_ROLE): Promise<User['id']> {
@@ -260,7 +256,7 @@ export class UsersQueries {
} catch (e) {
this.logger.error({
tag: this.updateUserOrGuest.name,
- msg: `user (${userId}) was not updated : ${JSON.stringify(anonymizePassword(set))} : ${e}`
+ msg: `user (${userId}) was not updated : ${JSON.stringify(anonymizePassword(set))} : ${toErrorMessage(e)}`
})
return false
}
@@ -301,12 +297,12 @@ export class UsersQueries {
}
return isBound
} catch (e) {
- this.logger.error({ tag: this.bindExternalId.name, msg: `external identity was not bound to user (${userId}) : ${e}` })
+ this.logger.error({ tag: this.bindExternalId.name, msg: `external identity was not bound to user (${userId}) : ${toErrorMessage(e)}` })
return false
}
}
- async updateAccesses(userId: number, ip: string, attemptsAction: 'preserve' | 'reset' | 'increment'): Promise<UserAccessUpdateResult> {
+ async updateAccesses(userId: number, ip: string | null, attemptsAction: 'preserve' | 'reset' | 'increment'): Promise<UserAccessUpdateResult> {
const passwordAttemptsUpdate =
attemptsAction === 'reset'
? sql`, ${sql.identifier(users.passwordAttempts.name)} = ${sql.param(0, users.passwordAttempts)}`
@@ -351,7 +347,7 @@ export class UsersQueries {
this.logger.verbose({ tag: this.updateAccesses.name, msg: `accesses for user (${userId}) were updated` })
return { success: true, temporaryLockStarted }
} catch (e) {
- this.logger.error({ tag: this.updateAccesses.name, msg: `accesses for user (${userId}) were not updated : ${e}` })
+ this.logger.error({ tag: this.updateAccesses.name, msg: `accesses for user (${userId}) were not updated : ${toErrorMessage(e)}` })
return { success: false, temporaryLockStarted: false }
}
}
@@ -376,7 +372,10 @@ export class UsersQueries {
this.logger.verbose({ tag: this.resetExpiredPasswordAttempts.name, msg: `expired password lock for user (${userId}) was released` })
return true
} catch (e) {
- this.logger.error({ tag: this.resetExpiredPasswordAttempts.name, msg: `expired password lock for user (${userId}) was not released : ${e}` })
+ this.logger.error({
+ tag: this.resetExpiredPasswordAttempts.name,
+ msg: `expired password lock for user (${userId}) was not released : ${toErrorMessage(e)}`
+ })
return false
}
}
@@ -385,7 +384,7 @@ export class UsersQueries {
dbCheckAffectedRows(await this.db.delete(users).where(and(eq(users.id, userId), eq(users.role, USER_ROLE.LINK))), 1)
}
- async searchUsersOrGroups(searchMembersDto: SearchMembersDto, userId?: number): Promise<Member[]> {
+ async searchUsersOrGroups(searchMembersDto: ValidatedSearchMembersDto, userId?: number): Promise<Member[]> {
// `userId` is required for user routes to avoid searching across all users and groups
const limit = searchMembersDto.onlyUsers || searchMembersDto.onlyGroups ? 6 : 3
const members: Member[] = []
@@ -415,14 +414,14 @@ export class UsersQueries {
return members
}
- async groupFromName(userId: number, name: string): Promise<Pick<Group, 'id' | 'name' | 'type'> & { role: UserGroup['role'] }> {
+ async groupFromName(userId: number, name: string): Promise<(Pick<Group, 'id' | 'name' | 'type'> & { role: UserGroup['role'] }) | undefined> {
const [group] = await this.db
.select({
id: groups.id,
name: groups.name,
type: groups.type,
role: usersGroups.role
- } satisfies (Pick<Group, 'id' | 'name' | 'type'> & { role: UserGroup['role'] }) | SelectedFields<any, any>)
+ } satisfies Partial<Record<keyof Group, any>> & { role: any })
.from(usersGroups)
.innerJoin(groups, eq(groups.id, usersGroups.groupId))
.where(and(eq(usersGroups.userId, userId), eq(groups.name, name)))
@@ -442,14 +441,14 @@ export class UsersQueries {
type: sql<MEMBER_TYPE>`IF(${groups.type} = ${GROUP_TYPE.USER}, ${MEMBER_TYPE.GROUP}, ${MEMBER_TYPE.PGROUP})`,
groupRole: sql<USER_GROUP_ROLE>`${usersGroups.role}`,
counts: { users: countDistinct(members.userId) }
- } satisfies Member | SelectedFields<any, any>)
+ } satisfies { [K in keyof Member]: any })
.from(usersGroups)
.innerJoin(groups, and(eq(groups.id, usersGroups.groupId), eq(usersGroups.userId, userId)))
.leftJoin(members, eq(members.groupId, groups.id))
.groupBy(groups.id)
}
- async browseGroupMembers(groupId: number): Promise<Member[]> {
+ browseGroupMembers(groupId: number): Promise<Member[]> {
return this.db
.select({
id: users.id,
@@ -459,11 +458,11 @@ export class UsersQueries {
createdAt: usersGroups.createdAt,
type: sql<MEMBER_TYPE>`IF(${users.role} = ${USER_ROLE.GUEST}, ${MEMBER_TYPE.GUEST}, ${MEMBER_TYPE.USER})`,
groupRole: sql<USER_GROUP_ROLE>`${usersGroups.role}`
- } satisfies Member | SelectedFields<any, any>)
+ } satisfies { [K in keyof Member]: any })
.from(groups)
.innerJoin(usersGroups, and(eq(usersGroups.groupId, groups.id), eq(usersGroups.groupId, groupId)))
.leftJoin(users, eq(users.id, usersGroups.userId))
- .groupBy(users.id)
+ .groupBy(users.id) as Promise<Member[]>
}
async canDeletePersonalGroup(userId: number, groupId: number): Promise<boolean> {
@@ -483,7 +482,7 @@ export class UsersQueries {
return !!group?.id
}
- async getGroup(userId: number, groupId: number, asAdmin = false): Promise<GroupMember> {
+ async getGroup(userId: number, groupId: number, asAdmin = false): Promise<GroupMember | undefined> {
const [group] = await this.db
.select({
id: groups.id,
@@ -505,7 +504,7 @@ export class UsersQueries {
return group
}
- async getGroupWithMembers(userId: number, groupId: number, asAdmin = false): Promise<GroupWithMembers> {
+ async getGroupWithMembers(userId: number, groupId: number, asAdmin = false): Promise<GroupWithMembers | undefined> {
const usersGroupsAlias: any = alias(usersGroups, 'usersFromGroups')
const [group] = await this.db
.select({
@@ -523,8 +522,8 @@ export class UsersQueries {
type: sql<MEMBER_TYPE>`IF(${users.role} = ${USER_ROLE.GUEST}, ${MEMBER_TYPE.GUEST}, ${MEMBER_TYPE.USER})`,
groupRole: usersGroupsAlias.role,
createdAt: dateTimeUTC(usersGroupsAlias.createdAt)
- } satisfies Record<keyof Pick<Member, 'id' | 'name' | 'login' | 'description' | 'type' | 'groupRole' | 'createdAt'>, any>)
- } satisfies GroupWithMembers | SelectedFields<any, any>)
+ } satisfies { [K in keyof Member]: any })
+ } satisfies { [K in keyof GroupWithMembers]: any })
.from(usersGroups)
.innerJoin(groups, eq(groups.id, usersGroups.groupId))
.leftJoin(usersGroupsAlias, and(eq(usersGroupsAlias.groupId, groups.id)))
@@ -569,7 +568,7 @@ export class UsersQueries {
await this.db.update(groups).set(set).where(eq(groups.id, groupId))
this.logger.log({ tag: this.updateGroup.name, msg: `group (${groupId}) was updated : ${JSON.stringify(set)}` })
} catch (e) {
- this.logger.error({ tag: this.updateGroup.name, msg: `group (${groupId}) was not updated : ${JSON.stringify(set)} : ${e}` })
+ this.logger.error({ tag: this.updateGroup.name, msg: `group (${groupId}) was not updated : ${JSON.stringify(set)} : ${toErrorMessage(e)}` })
throw new Error('Group was not updated')
}
}
@@ -594,7 +593,7 @@ export class UsersQueries {
} catch (e) {
this.logger.error({
tag: this.updateGroupMembers.name,
- msg: `users ${JSON.stringify(members.add.map((m) => m.id))} was not added to group (${groupId}) : ${e}`
+ msg: `users ${JSON.stringify(members.add.map((m) => m.id))} was not added to group (${groupId}) : ${toErrorMessage(e)}`
})
throw new Error('Group members was not added')
}
@@ -611,17 +610,17 @@ export class UsersQueries {
} catch (e) {
this.logger.error({
tag: this.updateGroupMembers.name,
- msg: `users ${JSON.stringify(members.remove)} was not removed from group (${groupId}) : ${e}`
+ msg: `users ${JSON.stringify(members.remove)} was not removed from group (${groupId}) : ${toErrorMessage(e)}`
})
throw new Error('Group members was not removed')
}
}
}
- async listGuests(guestId: null, managerId?: number, asAdmin?: boolean): Promise<GuestUser[]>
- async listGuests(guestId: number, managerId?: number, asAdmin?: boolean): Promise<GuestUser>
- async listGuests(guestId: number | null, managerId?: number, asAdmin = false): Promise<GuestUser | GuestUser[]> {
- const where: SQL[] = [...(guestId ? [eq(usersGuests.guestId, guestId)] : []), ...(asAdmin ? [] : [eq(usersGuests.userId, managerId)])]
+ async listGuests(guestId: null, managerId?: number | null, asAdmin?: boolean): Promise<GuestUser[]>
+ async listGuests(guestId: number, managerId?: number | null, asAdmin?: boolean): Promise<GuestUser | undefined>
+ async listGuests(guestId: number | null, managerId?: number | null, asAdmin = false): Promise<GuestUser | GuestUser[] | undefined> {
+ const where: SQL[] = [...(guestId ? [eq(usersGuests.guestId, guestId)] : []), ...(asAdmin ? [] : [eq(usersGuests.userId, managerId as number)])]
const managersGuestAlias: any = alias(usersGuests, 'managersGuestAlias')
const managersAlias: any = alias(users, 'managersAlias')
const q = this.db
@@ -649,7 +648,7 @@ export class UsersQueries {
type: sql`${MEMBER_TYPE.USER}`,
description: managersAlias.email,
createdAt: dateTimeUTC(managersGuestAlias.createdAt)
- } satisfies Record<keyof Pick<Member, 'id' | 'name' | 'login' | 'description' | 'type' | 'createdAt'>, any>),
+ } satisfies { [K in keyof Member]: any }),
...(guestId && {
groups: concatDistinctObjectsInArray(groups.id, {
id: groups.id,
@@ -658,9 +657,9 @@ export class UsersQueries {
type: sql`${MEMBER_TYPE.PGROUP}`,
permissions: groups.permissions,
createdAt: dateTimeUTC(usersGroups.createdAt)
- } satisfies Record<keyof Pick<Member, 'id' | 'name' | 'description' | 'type' | 'permissions' | 'createdAt'>, any>)
+ } satisfies { [K in keyof Member]: any })
})
- } satisfies GuestUser | SelectedFields<any, any>)
+ } satisfies { [K in keyof GuestUser]: any })
.from(usersGuests)
q.innerJoin(users, and(eq(users.id, usersGuests.guestId), eq(users.role, USER_ROLE.GUEST)))
q.leftJoin(managersGuestAlias, eq(managersGuestAlias.guestId, users.id))
@@ -671,9 +670,10 @@ export class UsersQueries {
}
q.where(and(...where))
q.groupBy(users.id)
- q.limit(guestId ? 1 : undefined)
+ if (guestId) q.limit(1)
const guests = await q
- return guestId ? guests[0] : guests
+ if (!guestId) return guests as GuestUser[]
+ return guests[0]
}
async isGuestManager(managerId: number, guestId: number): Promise<{ id: number; login: string } | undefined> {
@@ -703,7 +703,7 @@ export class UsersQueries {
return []
}
const showUngroupedUsers = +configuration.applications.users.showUngroupedUsers
- const userIds: any = sql`
+ const userIds = sql`
WITH visible_groups AS (
SELECT ${groups.id} AS id
FROM ${groups}
@@ -777,8 +777,8 @@ export class UsersQueries {
OR ${usersGuests.guestId} = ${userId}
) AS usersUnion
`
- const [r] = await this.db.execute(userIds)
- return dbParseJson(r[0].ids) || []
+ const [r] = (await this.db.execute(userIds)) as unknown as [{ ids: unknown }[], unknown]
+ return dbParseJson(r[0]!.ids) || []
}
@CacheDecorator(1800)
@@ -808,8 +808,8 @@ export class UsersQueries {
or(eq(groups.visibility, GROUP_VISIBILITY.VISIBLE), and(eq(groups.visibility, GROUP_VISIBILITY.PRIVATE), isNotNull(usersGroups.userId)))
)
)
- const [r] = await this.db.execute(q)
- return dbParseJson(r[0].ids) || []
+ const [r] = (await this.db.execute(q)) as unknown as [{ ids: unknown }[], unknown]
+ return dbParseJson(r[0]!.ids) || []
}
async clearWhiteListCaches(userIds: number[] | '*'): Promise<void> {
@@ -834,7 +834,7 @@ export class UsersQueries {
this.logger.verbose({ tag: this.clearWhiteListCaches.name, msg: JSON.stringify(keysToDelete) })
await this.cache.mdel(keysToDelete)
} catch (e) {
- this.logger.error({ tag: this.clearWhiteListCaches.name, msg: `${e}` })
+ this.logger.error({ tag: this.clearWhiteListCaches.name, msg: toErrorMessage(e) })
}
}
@@ -856,7 +856,7 @@ export class UsersQueries {
await this.cache.mdel(keysToDelete)
}
} catch (e) {
- this.logger.error({ tag: this.clearWebDAVAuthCache.name, msg: `${e}` })
+ this.logger.error({ tag: this.clearWebDAVAuthCache.name, msg: toErrorMessage(e) })
}
}
@@ -878,7 +878,7 @@ export class UsersQueries {
INNER JOIN ${usersGroups} ON child.id = ${usersGroups.groupId}
`
const [r]: { userId: number }[][] = (await this.db.execute(withChildren)) as MySqlQueryResult
- return r.length ? r.map((r) => r.userId) : []
+ return r.map(({ userId }) => userId)
}
private async isGuestLink(userId: number): Promise<boolean> {
@@ -887,17 +887,17 @@ export class UsersQueries {
}
private async searchGroups(
- searchMembersDto: SearchMembersDto,
+ searchMembersDto: ValidatedSearchMembersDto,
userId?: number,
limit = 3
): Promise<Pick<Group, 'id' | 'name' | 'description' | 'type' | 'permissions'>[]> {
/* Search for groups */
- const where: SQL[] = [or(like(groups.name, `%${searchMembersDto.search}%`), like(groups.description, `%${searchMembersDto.search}%`))]
+ const where: SQL[] = [or(like(groups.name, `%${searchMembersDto.search}%`), like(groups.description, `%${searchMembersDto.search}%`))!]
if (userId) {
const userRole = searchMembersDto.isGroupManager ? USER_GROUP_ROLE.MANAGER : undefined
let idsWhitelist: number[] = await this.groupsWhitelist(userId, undefined, userRole)
if (searchMembersDto.ignoreGroupIds?.length) {
- idsWhitelist = idsWhitelist.filter((id) => searchMembersDto.ignoreGroupIds.indexOf(id) === -1)
+ idsWhitelist = idsWhitelist.filter((id) => searchMembersDto.ignoreGroupIds!.indexOf(id) === -1)
}
where.unshift(inArray(groups.id, idsWhitelist))
} else if (searchMembersDto.ignoreGroupIds?.length) {
@@ -918,19 +918,19 @@ export class UsersQueries {
}
private async searchUsers(
- searchMembersDto: SearchMembersDto,
+ searchMembersDto: ValidatedSearchMembersDto,
userId?: number,
limit = 3
): Promise<Pick<UserModel, 'id' | 'login' | 'email' | 'fullName' | 'role' | 'permissions'>[]> {
/* Search for users */
const where: SQL[] = [
ne(users.role, USER_ROLE.LINK),
- or(like(sql`CONCAT_WS('-', ${users.login}, ${users.email}, ${users.firstName}, ${users.lastName})`, `%${searchMembersDto.search}%`))
+ or(like(sql`CONCAT_WS('-', ${users.login}, ${users.email}, ${users.firstName}, ${users.lastName})`, `%${searchMembersDto.search}%`))!
]
if (userId) {
let idsWhitelist: number[] = await this.usersWhitelist(userId)
if (searchMembersDto.ignoreUserIds?.length) {
- idsWhitelist = idsWhitelist.filter((id) => searchMembersDto.ignoreUserIds.indexOf(id) === -1)
+ idsWhitelist = idsWhitelist.filter((id) => searchMembersDto.ignoreUserIds!.indexOf(id) === -1)
}
where.unshift(inArray(users.id, idsWhitelist))
} else {
@@ -941,9 +941,9 @@ export class UsersQueries {
if (typeof searchMembersDto.usersRole !== 'undefined') {
if (searchMembersDto.usersRole === USER_ROLE.USER) {
// allow admin users
- where.unshift(lte(users.role, searchMembersDto.usersRole))
+ where.unshift(lte(users.role, searchMembersDto.usersRole as USER_ROLE))
} else {
- where.unshift(eq(users.role, searchMembersDto.usersRole))
+ where.unshift(eq(users.role, searchMembersDto.usersRole as USER_ROLE))
}
}
return this.db
diff --git a/backend/src/applications/users/users.config.ts b/backend/src/applications/users/users.config.ts
index a48ca1df..3e25d046 100644
--- a/backend/src/applications/users/users.config.ts
+++ b/backend/src/applications/users/users.config.ts
@@ -1,6 +1,3 @@
-import { IsBoolean } from 'class-validator'
+import { z } from 'zod'
-export class UsersConfig {
- @IsBoolean()
- showUngroupedUsers = true
-}
+export const UsersConfigSchema = z.looseObject({ showUngroupedUsers: z.boolean().default(true) })
diff --git a/backend/src/applications/users/users.controller.ts b/backend/src/applications/users/users.controller.ts
index 6b81761c..2e7b984e 100755
--- a/backend/src/applications/users/users.controller.ts
+++ b/backend/src/applications/users/users.controller.ts
@@ -1,4 +1,4 @@
-import { Body, Controller, Delete, Get, Header, Param, ParseIntPipe, Patch, Post, Put, Req, Search, StreamableFile, UseGuards } from '@nestjs/common'
+import { Body, Controller, Delete, Get, Header, Param, Patch, Post, Put, Req, Search, StreamableFile, UseGuards } from '@nestjs/common'
import { createReadStream } from 'fs'
import { LoginResponseDto } from '../../authentication/dto/login-response.dto.js'
import { type FastifyAuthenticatedRequest } from '../../authentication/interfaces/auth-request.interface.js'
@@ -6,22 +6,36 @@ import {
AuthTwoFaVerificationOrPasswordGuard,
AuthTwoFaVerificationWithoutPasswordGuard
} from '../../authentication/providers/two-fa/guards/auth-two-fa-verification.guard.js'
+import { integerFromStringSchema } from '../../configuration/config.schema.js'
import { makeContentDispositionAttachment } from '../files/utils/send-file.js'
import { USERS_ROUTE } from './constants/routes.js'
import { USER_PERMISSION, USER_ROLE } from './constants/user.js'
import { UserHavePermission } from './decorators/permissions.decorator.js'
import { UserHaveRole } from './decorators/roles.decorator.js'
import { GetUser } from './decorators/user.decorator.js'
-import { UserCreateOrUpdateGroupDto } from './dto/create-or-update-group.dto.js'
-import { CreateUserDto, UpdateUserDto, UpdateUserFromGroupDto } from './dto/create-or-update-user.dto.js'
-import { SearchMembersDto } from './dto/search-members.dto.js'
+import { type UserCreateOrUpdateGroupDto, userCreateOrUpdateGroupSchema, userIdsSchema } from './dto/create-or-update-group.dto.js'
import {
- UserAppPasswordDto,
- UserLanguageDto,
- UserNotificationDto,
- UserPreferencesDto,
- UserStorageIndexingDto,
- UserUpdatePasswordDto
+ type CreateUserDto,
+ createUserSchema,
+ type UpdateUserDto,
+ type UpdateUserFromGroupDto,
+ updateUserFromGroupSchema,
+ updateUserSchema
+} from './dto/create-or-update-user.dto.js'
+import { searchMembersSchema, type ValidatedSearchMembersDto } from './dto/search-members.dto.js'
+import {
+ type UserAppPasswordDto,
+ userAppPasswordSchema,
+ type UserLanguageDto,
+ userLanguageSchema,
+ type UserNotificationDto,
+ userNotificationSchema,
+ type UserPreferencesDto,
+ userPreferencesSchema,
+ type UserStorageIndexingDto,
+ userStorageIndexingSchema,
+ type UserUpdatePasswordDto,
+ userUpdatePasswordSchema
} from './dto/user-properties.dto.js'
import { UserPermissionsGuard } from './guards/permissions.guard.js'
import { UserRolesGuard } from './guards/roles.guard.js'
@@ -33,6 +47,7 @@ import type { UserPreferences } from './interfaces/user-preferences.interface.js
import { UserAppPassword } from './interfaces/user-secrets.interface.js'
import { UserModel } from './models/user.model.js'
import { UsersManager } from './services/users-manager.service.js'
+import { appPasswordNameParameterSchema, avatarLoginParameterSchema, optionalGroupNameParameterSchema } from './users.schema.js'
import { USER_AVATAR_FILE_NAME } from './utils/avatar.js'
@Controller(USERS_ROUTE.BASE)
@@ -56,51 +71,54 @@ export class UsersController {
@Post(`${USERS_ROUTE.ME}/${USERS_ROUTE.APP_PASSWORDS}`)
@UserHaveRole(USER_ROLE.USER)
@UseGuards(AuthTwoFaVerificationOrPasswordGuard)
- generateAppPassword(@GetUser() user: UserModel, @Body() userAppPasswordDto: UserAppPasswordDto): Promise<UserAppPassword> {
+ generateAppPassword(
+ @GetUser() user: UserModel,
+ @Body({ schema: userAppPasswordSchema }) userAppPasswordDto: UserAppPasswordDto
+ ): Promise<UserAppPassword> {
return this.usersManager.generateAppPassword(user, userAppPasswordDto)
}
@Delete(`${USERS_ROUTE.ME}/${USERS_ROUTE.APP_PASSWORDS}/:name`)
@UserHaveRole(USER_ROLE.USER)
@UseGuards(AuthTwoFaVerificationOrPasswordGuard)
- deleteAppPassword(@GetUser() user: UserModel, @Param('name') name: string): Promise<void> {
+ deleteAppPassword(@GetUser() user: UserModel, @Param('name', { schema: appPasswordNameParameterSchema }) name: string): Promise<void> {
return this.usersManager.deleteAppPassword(user, name)
}
@Put(`${USERS_ROUTE.ME}/${USERS_ROUTE.LANGUAGE}`)
@UserHaveRole(USER_ROLE.GUEST)
- updateLanguage(@GetUser() user: UserModel, @Body() userLanguageDto: UserLanguageDto) {
+ updateLanguage(@GetUser() user: UserModel, @Body({ schema: userLanguageSchema }) userLanguageDto: UserLanguageDto) {
return this.usersManager.updateLanguage(user, userLanguageDto)
}
@Put(`${USERS_ROUTE.ME}/${USERS_ROUTE.PASSWORD}`)
@UseGuards(AuthTwoFaVerificationWithoutPasswordGuard)
- updatePassword(@GetUser() user: UserModel, @Body() userPasswordDto: UserUpdatePasswordDto) {
+ updatePassword(@GetUser() user: UserModel, @Body({ schema: userUpdatePasswordSchema }) userPasswordDto: UserUpdatePasswordDto) {
return this.usersManager.updatePassword(user, userPasswordDto)
}
@Put(`${USERS_ROUTE.ME}/${USERS_ROUTE.NOTIFICATION}`)
@UserHaveRole(USER_ROLE.GUEST)
- updateNotification(@GetUser() user: UserModel, @Body() userNotificationDto: UserNotificationDto) {
+ updateNotification(@GetUser() user: UserModel, @Body({ schema: userNotificationSchema }) userNotificationDto: UserNotificationDto) {
return this.usersManager.updateNotification(user, userNotificationDto)
}
@Patch(`${USERS_ROUTE.ME}/${USERS_ROUTE.PREFERENCES}`)
@UserHaveRole(USER_ROLE.GUEST)
- updatePreferences(@GetUser() user: UserModel, @Body() dto: UserPreferencesDto): Promise<UserPreferences> {
+ updatePreferences(@GetUser() user: UserModel, @Body({ schema: userPreferencesSchema }) dto: UserPreferencesDto): Promise<UserPreferences> {
return this.usersManager.updatePreferences(user, dto)
}
@Put(`${USERS_ROUTE.ME}/${USERS_ROUTE.STORAGE_INDEXING}`)
@UserHaveRole(USER_ROLE.USER)
- updateStorageIndexing(@GetUser() user: UserModel, @Body() userStorageIndexingDto: UserStorageIndexingDto) {
+ updateStorageIndexing(@GetUser() user: UserModel, @Body({ schema: userStorageIndexingSchema }) userStorageIndexingDto: UserStorageIndexingDto) {
return this.usersManager.updateStorageIndexing(user, userStorageIndexingDto)
}
@Get(`${USERS_ROUTE.AVATAR}/:login`)
@UserHaveRole(USER_ROLE.LINK)
@Header('cache-control', 'public,max-age=86400')
- async avatar(@GetUser() user: UserModel, @Param('login') login: 'me' | string): Promise<StreamableFile> {
+ async avatar(@GetUser() user: UserModel, @Param('login', { schema: avatarLoginParameterSchema }) login: 'me' | string): Promise<StreamableFile> {
const isMe: boolean = login === 'me'
const [path, mime] = await this.usersManager.getAvatar(isMe ? user.login : login, false, isMe && user.role <= USER_ROLE.USER)
return new StreamableFile(createReadStream(path), { type: mime, disposition: makeContentDispositionAttachment(USER_AVATAR_FILE_NAME) })
@@ -117,51 +135,58 @@ export class UsersController {
}
@Search()
- searchMembers(@GetUser() user: UserModel, @Body() searchMembersDto: SearchMembersDto): Promise<Member[]> {
+ searchMembers(@GetUser() user: UserModel, @Body({ schema: searchMembersSchema }) searchMembersDto: ValidatedSearchMembersDto): Promise<Member[]> {
return this.usersManager.searchMembers(user, searchMembersDto)
}
@Get(`${USERS_ROUTE.ME}/${USERS_ROUTE.GROUPS}/${USERS_ROUTE.BROWSE}/:name?`)
- browseGroups(@GetUser() user: UserModel, @Param('name') name?: string): Promise<GroupBrowse> {
+ browseGroups(@GetUser() user: UserModel, @Param('name', { schema: optionalGroupNameParameterSchema }) name?: string): Promise<GroupBrowse> {
return this.usersManager.browseGroups(user, name)
}
@Post(`${USERS_ROUTE.ME}/${USERS_ROUTE.GROUPS}`)
@UserHavePermission(USER_PERMISSION.PERSONAL_GROUPS_ADMIN)
@UseGuards(UserPermissionsGuard)
- createPersonalGroup(@GetUser() user: UserModel, @Body() userCreateOrUpdateGroupDto: UserCreateOrUpdateGroupDto): Promise<GroupMember> {
+ createPersonalGroup(
+ @GetUser() user: UserModel,
+ @Body({ schema: userCreateOrUpdateGroupSchema }) userCreateOrUpdateGroupDto: UserCreateOrUpdateGroupDto
+ ): Promise<GroupMember> {
return this.usersManager.createPersonalGroup(user, userCreateOrUpdateGroupDto)
}
@Put(`${USERS_ROUTE.ME}/${USERS_ROUTE.GROUPS}/:id`)
updatePersonalGroup(
@GetUser() user: UserModel,
- @Param('id', ParseIntPipe) groupId: number,
- @Body() userCreateOrUpdateGroupDto: UserCreateOrUpdateGroupDto
+ @Param('id', { schema: integerFromStringSchema }) groupId: number,
+ @Body({ schema: userCreateOrUpdateGroupSchema }) userCreateOrUpdateGroupDto: UserCreateOrUpdateGroupDto
): Promise<GroupMember> {
return this.usersManager.updatePersonalGroup(user, groupId, userCreateOrUpdateGroupDto)
}
@Delete(`${USERS_ROUTE.ME}/${USERS_ROUTE.GROUPS}/:id`)
- deletePersonalGroup(@GetUser() user: UserModel, @Param('id', ParseIntPipe) groupId: number): Promise<void> {
+ deletePersonalGroup(@GetUser() user: UserModel, @Param('id', { schema: integerFromStringSchema }) groupId: number): Promise<void> {
return this.usersManager.deletePersonalGroup(user, groupId)
}
@Delete(`${USERS_ROUTE.ME}/${USERS_ROUTE.GROUPS}/${USERS_ROUTE.GROUPS_LEAVE}/:id`)
- leavePersonalGroup(@GetUser() user: UserModel, @Param('id', ParseIntPipe) groupId: number): Promise<void> {
+ leavePersonalGroup(@GetUser() user: UserModel, @Param('id', { schema: integerFromStringSchema }) groupId: number): Promise<void> {
return this.usersManager.leavePersonalGroup(user, groupId)
}
@Patch(`${USERS_ROUTE.ME}/${USERS_ROUTE.GROUPS}/:groupId/${USERS_ROUTE.USERS}`)
- addUsersToGroup(@GetUser() user: UserModel, @Param('groupId', ParseIntPipe) groupId: number, @Body() userIds: number[]): Promise<void> {
+ addUsersToGroup(
+ @GetUser() user: UserModel,
+ @Param('groupId', { schema: integerFromStringSchema }) groupId: number,
+ @Body({ schema: userIdsSchema }) userIds: number[]
+ ): Promise<void> {
return this.usersManager.addUsersToGroup(user, groupId, userIds)
}
@Delete(`${USERS_ROUTE.ME}/${USERS_ROUTE.GROUPS}/:groupId/${USERS_ROUTE.USERS}/:userId`)
removeUserFromGroup(
@GetUser() user: UserModel,
- @Param('groupId', ParseIntPipe) groupId: number,
- @Param('userId', ParseIntPipe) userId: number
+ @Param('groupId', { schema: integerFromStringSchema }) groupId: number,
+ @Param('userId', { schema: integerFromStringSchema }) userId: number
): Promise<void> {
return this.usersManager.removeUserFromGroup(user, groupId, userId)
}
@@ -169,9 +194,9 @@ export class UsersController {
@Patch(`${USERS_ROUTE.ME}/${USERS_ROUTE.GROUPS}/:groupId/${USERS_ROUTE.USERS}/:userId`)
updateUserFromPersonalGroup(
@GetUser() user: UserModel,
- @Param('groupId', ParseIntPipe) groupId: number,
- @Param('userId', ParseIntPipe) userId: number,
- @Body() updateUserFromGroupDto: UpdateUserFromGroupDto
+ @Param('groupId', { schema: integerFromStringSchema }) groupId: number,
+ @Param('userId', { schema: integerFromStringSchema }) userId: number,
+ @Body({ schema: updateUserFromGroupSchema }) updateUserFromGroupDto: UpdateUserFromGroupDto
): Promise<void> {
return this.usersManager.updateUserFromPersonalGroup(user, groupId, userId, updateUserFromGroupDto)
}
@@ -182,24 +207,28 @@ export class UsersController {
}
@Get(`${USERS_ROUTE.ME}/${USERS_ROUTE.GUESTS}/:id`)
- getGuest(@GetUser() user: UserModel, @Param('id', ParseIntPipe) guestId: number): Promise<GuestUser> {
+ getGuest(@GetUser() user: UserModel, @Param('id', { schema: integerFromStringSchema }) guestId: number): Promise<GuestUser> {
return this.usersManager.getGuest(user, guestId)
}
@Post(`${USERS_ROUTE.ME}/${USERS_ROUTE.GUESTS}`)
@UserHavePermission(USER_PERMISSION.GUESTS_ADMIN)
@UseGuards(UserPermissionsGuard)
- createGuest(@GetUser() user: UserModel, @Body() createGuestDto: CreateUserDto): Promise<GuestUser> {
+ createGuest(@GetUser() user: UserModel, @Body({ schema: createUserSchema }) createGuestDto: CreateUserDto): Promise<GuestUser> {
return this.usersManager.createGuest(user, createGuestDto)
}
@Put(`${USERS_ROUTE.ME}/${USERS_ROUTE.GUESTS}/:id`)
- updateGuest(@GetUser() user: UserModel, @Param('id', ParseIntPipe) guestId: number, @Body() updateGuestDto: UpdateUserDto): Promise<GuestUser> {
+ updateGuest(
+ @GetUser() user: UserModel,
+ @Param('id', { schema: integerFromStringSchema }) guestId: number,
+ @Body({ schema: updateUserSchema }) updateGuestDto: UpdateUserDto
+ ): Promise<GuestUser | null> {
return this.usersManager.updateGuest(user, guestId, updateGuestDto)
}
@Delete(`${USERS_ROUTE.ME}/${USERS_ROUTE.GUESTS}/:id`)
- deleteGuest(@GetUser() user: UserModel, @Param('id', ParseIntPipe) guestId: number): Promise<void> {
+ deleteGuest(@GetUser() user: UserModel, @Param('id', { schema: integerFromStringSchema }) guestId: number): Promise<void> {
return this.usersManager.deleteGuest(user, guestId)
}
}
diff --git a/backend/src/applications/users/users.e2e-spec.ts b/backend/src/applications/users/users.e2e-spec.ts
index 923abe32..024e8ed2 100644
--- a/backend/src/applications/users/users.e2e-spec.ts
+++ b/backend/src/applications/users/users.e2e-spec.ts
@@ -1,11 +1,12 @@
import { NestFastifyApplication } from '@nestjs/platform-fastify'
import { appBootstrap } from '../../app.bootstrap.js'
import { AuthManager } from '../../authentication/auth.service.js'
-import { TokenResponseDto } from '../../authentication/dto/token-response.dto.js'
+import type { TokenResponseDto } from '../../authentication/dto/token-response.dto.js'
import { dbCheckConnection } from '../../infrastructure/database/utils.js'
import { API_USERS_AVATAR, API_USERS_ME } from './constants/routes.js'
import { USER_ROLE } from './constants/user.js'
-import { DeleteUserDto } from './dto/delete-user.dto.js'
+import type { CreateUserDto } from './dto/create-or-update-user.dto.js'
+import type { DeleteUserDto } from './dto/delete-user.dto.js'
import { UserModel } from './models/user.model.js'
import { AdminUsersManager } from './services/admin-users-manager.service.js'
import { UsersQueries } from './services/users-queries.service.js'
@@ -59,7 +60,7 @@ describe('Users (e2e)', () => {
})
it(`GET ${API_USERS_ME} => 200`, async () => {
- userTest = await adminUsersManager.createUserOrGuest(userTest, USER_ROLE.USER)
+ userTest = await adminUsersManager.createUserOrGuest(userTest as CreateUserDto, USER_ROLE.USER)
expect(userTest.id).toBeDefined()
tokens = await authManager.getTokens(userTest)
const res = await app.inject({
@@ -75,26 +76,26 @@ describe('Users (e2e)', () => {
it('should bind and resolve external identities in the database', async () => {
const externalId = 'SUBJECT-1'
- legacyUserTest = await adminUsersManager.createUserOrGuest(legacyUserTest, USER_ROLE.USER)
+ legacyUserTest = await adminUsersManager.createUserOrGuest(legacyUserTest as CreateUserDto, USER_ROLE.USER)
expect(await usersQueries.bindExternalId(userTest.id, externalId)).toBe(true)
- expect((await usersQueries.from(userTest.id)).externalId).toBe(externalId)
+ expect((await usersQueries.from(userTest.id))!.externalId).toBe(externalId)
expect(await usersQueries.bindExternalId(userTest.id, externalId)).toBe(true)
expect(await usersQueries.bindExternalId(userTest.id, 'subject-1')).toBe(false)
expect(await usersQueries.bindExternalId(0, externalId)).toBe(false)
const emailFallback = await usersQueries.fromExternalIdOrEmail('unknown-subject', legacyUserTest.email)
- expect(emailFallback.id).toBe(legacyUserTest.id)
+ expect(emailFallback!.id).toBe(legacyUserTest.id)
const externalIdPriority = await usersQueries.fromExternalIdOrEmail(externalId, legacyUserTest.email)
- expect(externalIdPriority.id).toBe(userTest.id)
+ expect(externalIdPriority!.id).toBe(userTest.id)
const concurrentExternalIds = ['CONCURRENT-SUBJECT-1', 'CONCURRENT-SUBJECT-2']
const concurrentBindings = await Promise.all(
concurrentExternalIds.map((concurrentExternalId) => usersQueries.bindExternalId(legacyUserTest.id, concurrentExternalId))
)
expect(concurrentBindings.filter(Boolean)).toHaveLength(1)
- expect(concurrentExternalIds).toContain((await usersQueries.from(legacyUserTest.id)).externalId)
+ expect(concurrentExternalIds).toContain((await usersQueries.from(legacyUserTest.id))!.externalId)
})
it(`GET ${API_USERS_AVATAR} => 200`, async () => {
diff --git a/backend/src/applications/users/users.gateway.ts b/backend/src/applications/users/users.gateway.ts
index 2c3cf7db..072602ea 100644
--- a/backend/src/applications/users/users.gateway.ts
+++ b/backend/src/applications/users/users.gateway.ts
@@ -1,3 +1,4 @@
+import { toErrorMessage } from '../../common/errors.js'
import { BeforeApplicationShutdown, Logger } from '@nestjs/common'
import {
MessageBody,
@@ -9,19 +10,24 @@ import {
WebSocketServer
} from '@nestjs/websockets'
import { Server } from 'socket.io'
-import { JwtIdentityPayload } from '../../authentication/interfaces/jwt-payload.interface.js'
+import type { JwtIdentityPayload } from '../../authentication/interfaces/jwt-payload.interface.js'
import { sleep } from '../../common/functions.js'
import { GetWsUser } from '../../infrastructure/websocket/decorators/web-socket-user.decorator.js'
import { AuthenticatedSocketIO } from '../../infrastructure/websocket/interfaces/auth-socket-io.interface.js'
import { getClientAddress } from '../../infrastructure/websocket/utils.js'
import { USER_ONLINE_STATUS } from './constants/user.js'
import { USER_ROOM_PREFIX, USERS_WS } from './constants/websocket.js'
-import { type EventChangeOnlineStatus, EventUpdateOnlineStatus, UserOnline } from './interfaces/websocket.interface.js'
+import {
+ type EventChangeOnlineStatus,
+ eventChangeOnlineStatusSchema,
+ type EventUpdateOnlineStatus,
+ type UserOnline
+} from './interfaces/websocket.interface.js'
import { UsersManager } from './services/users-manager.service.js'
@WebSocketGateway()
export class WebSocketUsers implements BeforeApplicationShutdown, OnGatewayInit, OnGatewayConnection, OnGatewayDisconnect {
- @WebSocketServer() server: Server
+ @WebSocketServer() server!: Server
private readonly internalEventOnlineUsers = 'listOnlineUsers'
private readonly logger = new Logger(WebSocketUsers.name)
private initialized = false
@@ -44,9 +50,9 @@ export class WebSocketUsers implements BeforeApplicationShutdown, OnGatewayInit,
if (this.shuttingDown) return
socket.join(`${USER_ROOM_PREFIX}${socket.user.id}`)
this.sendOnlineUser(socket.user, parseInt((socket.handshake.query.onlineStatus as string) || '0')).catch((e: Error) =>
- this.logger.error({ tag: this.handleConnection.name, msg: `${e}` })
+ this.logger.error({ tag: this.handleConnection.name, msg: toErrorMessage(e) })
)
- this.sendAllOnlineUsers(socket.user.id).catch((e: Error) => this.logger.error({ tag: this.handleConnection.name, msg: `${e}` }))
+ this.sendAllOnlineUsers(socket.user.id).catch((e: Error) => this.logger.error({ tag: this.handleConnection.name, msg: toErrorMessage(e) }))
this.logger.log({
tag: this.handleConnection.name,
msg: `Connected: *${socket.user.login}* (${socket.user.id}) [${socket.id}] ${getClientAddress(socket)} ${socket.handshake.headers['user-agent']}`
@@ -56,7 +62,7 @@ export class WebSocketUsers implements BeforeApplicationShutdown, OnGatewayInit,
async handleDisconnect(socket: AuthenticatedSocketIO): Promise<void> {
if (this.shuttingDown) return
socket.leave(`${USER_ROOM_PREFIX}${socket.user.id}`)
- this.sendOfflineUser(socket.user.id).catch((e: Error) => this.logger.error({ tag: this.handleDisconnect.name, msg: `${e}` }))
+ this.sendOfflineUser(socket.user.id).catch((e: Error) => this.logger.error({ tag: this.handleDisconnect.name, msg: toErrorMessage(e) }))
this.logger.log({
tag: this.handleDisconnect.name,
msg: `Disconnected: *${socket.user.login}* (${socket.user.id}) [${socket.id}] ${getClientAddress(socket)} ${socket.handshake.headers['user-agent']}`
@@ -64,12 +70,12 @@ export class WebSocketUsers implements BeforeApplicationShutdown, OnGatewayInit,
}
@SubscribeMessage(USERS_WS.EVENTS.ONLINE_STATUS)
- setOnlineStatus(@GetWsUser() user: JwtIdentityPayload, @MessageBody() body: EventChangeOnlineStatus) {
+ setOnlineStatus(@GetWsUser() user: JwtIdentityPayload, @MessageBody({ schema: eventChangeOnlineStatusSchema }) body: EventChangeOnlineStatus) {
if (body.store) {
// store in db
this.usersManager.setOnlineStatus(user, body.status)
}
- this.sendOnlineStatus(user.id, body.status).catch((e: Error) => this.logger.error({ tag: this.setOnlineStatus.name, msg: `${e}` }))
+ this.sendOnlineStatus(user.id, body.status).catch((e: Error) => this.logger.error({ tag: this.setOnlineStatus.name, msg: toErrorMessage(e) }))
}
private sendMessageToUsers(userIds: number[], eventName: string, body: any) {
@@ -106,7 +112,7 @@ export class WebSocketUsers implements BeforeApplicationShutdown, OnGatewayInit,
// check if user room is empty before send event
if ((await this.getOnlineUserIds()).indexOf(userId) === -1) {
this.sendOnlineStatus(userId, USER_ONLINE_STATUS.OFFLINE).catch((e: Error) =>
- this.logger.error({ tag: this.sendOfflineUser.name, msg: `${e}` })
+ this.logger.error({ tag: this.sendOfflineUser.name, msg: toErrorMessage(e) })
)
}
}
@@ -156,6 +162,6 @@ export class WebSocketUsers implements BeforeApplicationShutdown, OnGatewayInit,
}
private filterUserRooms(rooms: Iterable<string>): number[] {
- return [...rooms].filter((r) => r.startsWith(USER_ROOM_PREFIX)).map((ur) => parseInt(ur.split(USER_ROOM_PREFIX).pop()))
+ return [...rooms].filter((r) => r.startsWith(USER_ROOM_PREFIX)).map((ur) => parseInt(ur.split(USER_ROOM_PREFIX).pop()!))
}
}
diff --git a/backend/src/applications/users/users.schema.ts b/backend/src/applications/users/users.schema.ts
new file mode 100644
index 00000000..a71716b7
--- /dev/null
+++ b/backend/src/applications/users/users.schema.ts
@@ -0,0 +1,5 @@
+import { z } from 'zod'
+
+export const appPasswordNameParameterSchema = z.string()
+export const avatarLoginParameterSchema = z.string()
+export const optionalGroupNameParameterSchema = z.string().optional()
diff --git a/backend/src/applications/webdav/constants/routes.ts b/backend/src/applications/webdav/constants/routes.ts
index 60e74fef..42b97751 100644
--- a/backend/src/applications/webdav/constants/routes.ts
+++ b/backend/src/applications/webdav/constants/routes.ts
@@ -12,7 +12,7 @@ export const WEBDAV_NS = {
TRASH: SPACE_ALIAS.TRASH
} as const
-export const WEBDAV_SPACES: Record<(typeof WEBDAV_NS)[keyof typeof WEBDAV_NS], { route: string; spaceRepository: string[] }> = {
+export const WEBDAV_SPACES: Record<(typeof WEBDAV_NS)[keyof typeof WEBDAV_NS], { route: string; spaceRepository: string[] | null }> = {
[WEBDAV_NS.SERVER]: { route: '/', spaceRepository: null },
[WEBDAV_NS.WEBDAV]: { route: `/${WEBDAV_BASE_PATH}`, spaceRepository: null },
[WEBDAV_NS.PERSONAL]: { route: `/${WEBDAV_BASE_PATH}/${WEBDAV_NS.PERSONAL}`, spaceRepository: [SPACE_REPOSITORY.FILES, SPACE_ALIAS.PERSONAL] },
diff --git a/backend/src/applications/webdav/constants/webdav.ts b/backend/src/applications/webdav/constants/webdav.ts
index 942ddc3d..8f23eaae 100644
--- a/backend/src/applications/webdav/constants/webdav.ts
+++ b/backend/src/applications/webdav/constants/webdav.ts
@@ -65,7 +65,7 @@ export enum DEPTH {
MEMBERS = '1'
}
-export type LOCK_DEPTH = Omit<DEPTH, DEPTH.MEMBERS>
+export type LOCK_DEPTH = DEPTH.INFINITY | DEPTH.RESOURCE
export enum PROPSTAT {
ALLPROP = 'allprop',
diff --git a/backend/src/applications/webdav/decorators/if-header.decorator.ts b/backend/src/applications/webdav/decorators/if-header.decorator.ts
index f76a01ec..67753b3a 100644
--- a/backend/src/applications/webdav/decorators/if-header.decorator.ts
+++ b/backend/src/applications/webdav/decorators/if-header.decorator.ts
@@ -2,12 +2,12 @@ import { FastifyReply } from 'fastify'
import { FastifyDAVRequest } from '../interfaces/webdav.interface.js'
export function IfHeaderDecorator() {
- return (_target: any, _key?: string | symbol, descriptor?: TypedPropertyDescriptor<any>) => {
- const originalMethod = descriptor.value
- descriptor.value = async function (...args: any[]) {
- const req: FastifyDAVRequest = args[0]
- const res: FastifyReply = args[1]
- if (!(await this.evaluateIfHeaders(req, res))) {
+ return (_target: object, _key: string | symbol, descriptor: PropertyDescriptor): void => {
+ const originalMethod = descriptor.value as (...args: unknown[]) => unknown
+ descriptor.value = async function (this: unknown, ...args: unknown[]) {
+ const req = args[0] as FastifyDAVRequest
+ const res = args[1] as FastifyReply
+ if (!(await (this as { evaluateIfHeaders(req: FastifyDAVRequest, res: FastifyReply): Promise<boolean> }).evaluateIfHeaders(req, res))) {
// if there is an error the response is generated inside the `evaluateIfHeaders` function
return
}
diff --git a/backend/src/applications/webdav/guards/webdav-protocol.guard.spec.ts b/backend/src/applications/webdav/guards/webdav-protocol.guard.spec.ts
index 7df4f9ec..9826a74b 100644
--- a/backend/src/applications/webdav/guards/webdav-protocol.guard.spec.ts
+++ b/backend/src/applications/webdav/guards/webdav-protocol.guard.spec.ts
@@ -60,7 +60,7 @@ describe(WebDAVProtocolGuard.name, () => {
const expectIfHeadersParsed = (req: FastifyDAVRequest) => {
expect(Array.isArray(req.dav.ifHeaders)).toBe(true)
- expect(req.dav.ifHeaders.length).toBeGreaterThan(0)
+ expect(req.dav.ifHeaders!.length).toBeGreaterThan(0)
}
beforeEach(async () => {
@@ -236,9 +236,9 @@ describe(WebDAVProtocolGuard.name, () => {
const res = makeRes()
const ctx = makeCtx(req, res)
await expect(guard.canActivate(ctx)).resolves.toBe(true)
- expect(req.dav.lock.timeout).toBe(CACHE_LOCK_DEFAULT_TTL)
- expect(req.dav.lock.lockscope).toBe(LOCK_SCOPE.EXCLUSIVE)
- expect(req.dav.lock.owner).toContain('Custom Owner')
+ expect(req.dav.lock!.timeout).toBe(CACHE_LOCK_DEFAULT_TTL)
+ expect(req.dav.lock!.lockscope).toBe(LOCK_SCOPE.EXCLUSIVE)
+ expect(req.dav.lock!.owner).toContain('Custom Owner')
expect(req.dav.depth).toBe(DEPTH.RESOURCE)
})
@@ -250,9 +250,9 @@ describe(WebDAVProtocolGuard.name, () => {
const res = makeRes()
const ctx = makeCtx(req, res)
await expect(guard.canActivate(ctx)).resolves.toBe(true)
- expect(req.dav.lock.timeout).toBe(10)
- expect(req.dav.lock.lockscope).toBe(LOCK_SCOPE.SHARED)
- expect(req.dav.lock.owner).toMatch(/^me/)
+ expect(req.dav.lock!.timeout).toBe(10)
+ expect(req.dav.lock!.lockscope).toBe(LOCK_SCOPE.SHARED)
+ expect(req.dav.lock!.owner).toMatch(/^me/)
expect(req.dav.depth).toBe(DEPTH.INFINITY)
})
@@ -265,7 +265,7 @@ describe(WebDAVProtocolGuard.name, () => {
const res = makeRes()
const ctx = makeCtx(req, res)
await expect(guard.canActivate(ctx)).resolves.toBe(true)
- expect(req.dav.lock.timeout).toBe(CACHE_LOCK_DEFAULT_TTL)
+ expect(req.dav.lock!.timeout).toBe(CACHE_LOCK_DEFAULT_TTL)
})
it('invalid timeout -> NaN (no fallback), depth=infinity', async () => {
@@ -276,7 +276,7 @@ describe(WebDAVProtocolGuard.name, () => {
const res = makeRes()
const ctx = makeCtx(req, res)
await expect(guard.canActivate(ctx)).resolves.toBe(true)
- expect(Number.isNaN(req.dav.lock.timeout)).toBe(true)
+ expect(Number.isNaN(req.dav.lock!.timeout)).toBe(true)
expect(req.dav.depth).toBe(DEPTH.INFINITY)
})
@@ -312,7 +312,7 @@ describe(WebDAVProtocolGuard.name, () => {
try {
await expect(guard.canActivate(ctx)).resolves.toBe(true)
- expect(req.dav.lock.timeout).toBe(CACHE_LOCK_DEFAULT_TTL)
+ expect(req.dav.lock!.timeout).toBe(CACHE_LOCK_DEFAULT_TTL)
expect(req.dav.ifHeaders).toBeUndefined()
} finally {
spyIf.mockRestore()
@@ -403,7 +403,7 @@ describe(WebDAVProtocolGuard.name, () => {
const ctx = makeCtx(req, res)
await expect(guard.canActivate(ctx)).resolves.toBe(true)
expect(req.dav.lock).toBeDefined()
- expect(req.dav.lock.timeout).toBeUndefined()
+ expect(req.dav.lock!.timeout).toBeUndefined()
})
})
@@ -422,7 +422,7 @@ describe(WebDAVProtocolGuard.name, () => {
const res = makeRes()
const ctx = makeCtx(req, res)
await expect(guard.canActivate(ctx)).resolves.toBe(true)
- expect(req.dav.lock.token).toBe('abc')
+ expect(req.dav.lock!.token).toBe('abc')
expectIfHeadersParsed(req)
})
})
diff --git a/backend/src/applications/webdav/guards/webdav-protocol.guard.ts b/backend/src/applications/webdav/guards/webdav-protocol.guard.ts
index 65930765..e7543ef9 100644
--- a/backend/src/applications/webdav/guards/webdav-protocol.guard.ts
+++ b/backend/src/applications/webdav/guards/webdav-protocol.guard.ts
@@ -1,6 +1,6 @@
import { CanActivate, ExecutionContext, HttpException, HttpStatus, Injectable, Logger } from '@nestjs/common'
-import { ValidationError } from 'fast-xml-parser'
import { FastifyReply } from 'fastify'
+import { toErrorMessage } from '../../../common/errors.js'
import { urlToPath } from '../../../common/functions.js'
import { decodeUrl } from '../../../common/shared.js'
import { HTTP_METHOD } from '../../applications.constants.js'
@@ -17,7 +17,7 @@ import {
REGEX_BASE_PATH
} from '../constants/webdav.js'
import { IfHeader } from '../interfaces/if-header.interface.js'
-import { FastifyDAVRequest, WebDAVContext } from '../interfaces/webdav.interface.js'
+import { FastifyDAVPendingRequest, FastifyDAVRequest } from '../interfaces/webdav.interface.js'
import { parseIfHeader } from '../utils/if-header.js'
import { PROPFIND_ALL_PROP } from '../utils/webdav.js'
import { xmlIsValid, xmlParse } from '../utils/xml.js'
@@ -35,7 +35,7 @@ export class WebDAVProtocolGuard implements CanActivate {
case HTTP_METHOD.OPTIONS:
// hook to stop propagation and return headers on all webdav routes
res.headers(OPTIONS_HEADERS)
- throw new HttpException(null, HttpStatus.OK)
+ throw new HttpException('', HttpStatus.OK)
case HTTP_METHOD.PROPFIND:
return this.propfindMethod(req)
case HTTP_METHOD.LOCK:
@@ -59,27 +59,35 @@ export class WebDAVProtocolGuard implements CanActivate {
}
}
- private checkUserPermission(req: FastifyDAVRequest) {
+ private checkUserPermission(req: FastifyDAVPendingRequest) {
if (req.method !== HTTP_METHOD.OPTIONS && !req.user.havePermission(USER_PERMISSION.WEBDAV)) {
this.logger.warn({ tag: this.checkUserPermission.name, msg: `does not have permission : ${USER_PERMISSION.WEBDAV}` })
throw new HttpException('Missing permission', HttpStatus.FORBIDDEN)
}
}
- private setDAVContext(req: FastifyDAVRequest) {
+ private setDAVContext(req: FastifyDAVPendingRequest): void {
req.dav = {
url: decodeUrl(req.originalUrl),
depth: DEPTH.RESOURCE
- } as WebDAVContext
+ }
}
private parseBody(req: FastifyDAVRequest) {
let body = null
- let valid: true | ValidationError
+ let valid: true | { err: { code?: string; msg: string; line: number; col: number } }
try {
valid = xmlIsValid(req.body.toString())
} catch (e) {
- valid = { err: { code: e.code, msg: `Invalid body content: ${e.message}`, line: 0, col: 0 } }
+ const code = e !== null && typeof e === 'object' && 'code' in e && typeof e.code === 'string' ? e.code : undefined
+ valid = {
+ err: {
+ code,
+ msg: `Invalid body content: ${toErrorMessage(e)}`,
+ line: 0,
+ col: 0
+ }
+ }
}
if (valid === true) {
body = xmlParse(req.body)
@@ -103,7 +111,7 @@ export class WebDAVProtocolGuard implements CanActivate {
}
private propfindMethod(req: FastifyDAVRequest) {
- req.dav.depth = (req.headers[HEADER.DEPTH] as string | undefined)?.toLowerCase()
+ req.dav.depth = (req.headers[HEADER.DEPTH] as string | undefined)?.toLowerCase() as DEPTH
if (!req.dav.depth || (req.dav.depth !== DEPTH.MEMBERS && req.dav.depth !== DEPTH.RESOURCE)) {
if (!req.dav.depth) {
this.logger.warn({ tag: this.propfindMethod.name, msg: 'Missing propfind depth, default value 1 was set' })
@@ -137,7 +145,7 @@ export class WebDAVProtocolGuard implements CanActivate {
}
private proppatchMethod(req: FastifyDAVRequest) {
- req.dav.depth = ((req.headers[HEADER.DEPTH] as any) || DEPTH.RESOURCE).toLowerCase()
+ req.dav.depth = ((req.headers[HEADER.DEPTH] as any) || DEPTH.RESOURCE).toLowerCase() as DEPTH
this.parseBody(req)
if (!req.dav.body || Object.keys(req.dav.body).indexOf(PROPPATCH_PROP_UPDATE) === -1) {
this.logger.debug({ tag: this.proppatchMethod.name, msg: `'${PROPPATCH_PROP_UPDATE}' is missing : ${JSON.stringify(req.dav.body)}` })
@@ -160,7 +168,7 @@ export class WebDAVProtocolGuard implements CanActivate {
const seconds = parseInt(timeoutSplit[timeoutSplit.length - 1], 10)
req.dav.lock.timeout = seconds > CACHE_LOCK_DEFAULT_TTL ? CACHE_LOCK_DEFAULT_TTL : seconds
} catch (e) {
- this.logger.warn({ tag: this.lockMethod.name, msg: `unable to set timeout, use the default value : ${e}` })
+ this.logger.warn({ tag: this.lockMethod.name, msg: `unable to set timeout, use the default value : ${toErrorMessage(e)}` })
req.dav.lock.timeout = CACHE_LOCK_DEFAULT_TTL
}
}
@@ -174,7 +182,10 @@ export class WebDAVProtocolGuard implements CanActivate {
try {
req.dav.lock.lockscope = Object.keys(req.dav.body.lockinfo.lockscope)[0] as LOCK_SCOPE
} catch (e) {
- this.logger.warn({ tag: this.lockMethod.name, msg: `invalid or undefined lockscope : ${JSON.stringify(req.dav.body.lockinfo)} : ${e}` })
+ this.logger.warn({
+ tag: this.lockMethod.name,
+ msg: `invalid or undefined lockscope : ${JSON.stringify(req.dav.body.lockinfo)} : ${toErrorMessage(e)}`
+ })
throw new HttpException('Invalid or undefined lockscope', HttpStatus.BAD_REQUEST)
}
if (Object.values(LOCK_SCOPE).indexOf(req.dav.lock.lockscope) === -1) {
@@ -235,7 +246,7 @@ export class WebDAVProtocolGuard implements CanActivate {
this.logger.warn({ tag: this.copyMoveMethod.name, msg: `The destination does not match the webdav base path : ${destination}` })
throw new HttpException('The destination does not match', HttpStatus.BAD_REQUEST)
}
- req.dav.depth = ((req.headers[HEADER.DEPTH] as any) || DEPTH.INFINITY).toLowerCase()
+ req.dav.depth = ((req.headers[HEADER.DEPTH] as any) || DEPTH.INFINITY).toLowerCase() as DEPTH
req.dav.copyMove = {
overwrite: ((req.headers[HEADER.OVERWRITE] as any) || 't').toLowerCase() === 't',
destination: destination,
diff --git a/backend/src/applications/webdav/interfaces/webdav.interface.ts b/backend/src/applications/webdav/interfaces/webdav.interface.ts
index adfcf6ac..32b4b6cc 100644
--- a/backend/src/applications/webdav/interfaces/webdav.interface.ts
+++ b/backend/src/applications/webdav/interfaces/webdav.interface.ts
@@ -7,15 +7,23 @@ export interface WebDAVContext {
url: string
body?: any // xml content
ifHeaders?: IfHeader[]
- depth?: DEPTH | string
+ depth: DEPTH | null
propfindMode?: PROPSTAT
- lock?: { timeout?: number; lockscope?: LOCK_SCOPE; owner?: any; token?: string }
- proppatch?: { props: Record<string, string>; errors: any[] }
+ lock?: { timeout?: number; lockscope?: LOCK_SCOPE; owner?: string; token?: string }
+ proppatch?: { props: Record<string, string | null>; errors: any[] }
copyMove?: { overwrite: boolean; destination: string; isMove: boolean }
}
-export interface FastifyDAVRequest extends FastifyAuthenticatedRequest {
+export interface FastifyDAVPendingRequest extends FastifyAuthenticatedRequest {
body: any
dav?: WebDAVContext
space?: SpaceEnv
}
+
+export interface FastifyDAVRequest extends FastifyDAVPendingRequest {
+ dav: WebDAVContext
+}
+
+export interface FastifyDAVSpaceRequest extends FastifyDAVRequest {
+ space: SpaceEnv
+}
diff --git a/backend/src/applications/webdav/models/webdav-file.model.ts b/backend/src/applications/webdav/models/webdav-file.model.ts
index 96abf11d..65b5c6c2 100644
--- a/backend/src/applications/webdav/models/webdav-file.model.ts
+++ b/backend/src/applications/webdav/models/webdav-file.model.ts
@@ -6,20 +6,20 @@ import { FileProps } from '../../files/interfaces/file-props.interface.js'
import { genEtag } from '../../files/utils/files.js'
import { PROPFIND_COLLECTION, SUPPORTED_LOCKS } from '../utils/webdav.js'
-export class WebDAVFile implements Omit<FileProps, 'path'> {
- id: number
- name: string
- isDir: boolean
- size: number
- ctime: number
- mtime: number
- mime: string
+export class WebDAVFile implements Omit<FileProps, 'path' | 'mime'> {
+ id!: number
+ name!: string
+ isDir!: boolean
+ size!: number
+ ctime!: number
+ mtime!: number
+ mime?: string
// extra props
- alias: string
+ alias!: string
href: string
- constructor(props: Omit<FileProps, 'path'> & { alias?: string }, currentUrl: string, isCurrent = false) {
+ constructor(props: Omit<FileProps, 'path' | 'mime'> & { alias?: string; mime?: string }, currentUrl: string, isCurrent = false) {
Object.assign(this, props)
if (props?.root?.alias) {
this.alias = props.root.alias
diff --git a/backend/src/applications/webdav/services/webdav-methods.service.spec.ts b/backend/src/applications/webdav/services/webdav-methods.service.spec.ts
index 7a7cee5b..c93ee170 100644
--- a/backend/src/applications/webdav/services/webdav-methods.service.spec.ts
+++ b/backend/src/applications/webdav/services/webdav-methods.service.spec.ts
@@ -17,15 +17,19 @@ import { WebDAVSpaces } from './webdav-spaces.service.js'
import { Mocked } from 'vitest'
// Mock external dependencies
-vi.mock('../../files/utils/files.js', () => ({
- isPathExists: vi.fn().mockReturnValue(false),
- isPathIsDir: vi.fn(),
- fileName: vi.fn().mockReturnValue('fileName'),
- dirName: vi.fn(),
- genEtag: vi.fn().mockReturnValue('W/"etag-123"'),
- removeFiles: vi.fn(() => Promise.resolve()),
- temporaryFilePath: vi.fn().mockReturnValue('/space/tmp/users/1/~tmp-upload-id-file.txt')
-}))
+vi.mock('../../files/utils/files.js', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('../../files/utils/files.js')>()
+ return {
+ ...actual,
+ isPathExists: vi.fn().mockReturnValue(false),
+ isPathIsDir: vi.fn(),
+ fileName: vi.fn().mockReturnValue('fileName'),
+ dirName: vi.fn(),
+ genEtag: vi.fn().mockReturnValue('W/"etag-123"'),
+ removeFiles: vi.fn(() => Promise.resolve()),
+ temporaryFilePath: vi.fn().mockReturnValue('/space/tmp/users/1/~tmp-upload-id-file.txt')
+ }
+})
vi.mock('../../spaces/utils/permissions.js', () => ({
haveSpaceEnvPermissions: vi.fn()
@@ -279,10 +283,10 @@ describe('WebDAVMethods', () => {
owner: { fullName: 'LockOwner', email: '[email protected]' },
dbFilePath: _dbFile?.path,
options: {
- lockRoot: options.lockRoot,
- lockToken: options.lockToken,
- lockScope: options.lockScope,
- lockInfo: options.lockInfo
+ lockRoot: options!.lockRoot,
+ lockToken: options!.lockToken,
+ lockScope: options!.lockScope,
+ lockInfo: options!.lockInfo
}
} as Partial<FileLock>
] as any
@@ -343,10 +347,10 @@ describe('WebDAVMethods', () => {
owner: { fullName: 'LockOwner', email: '[email protected]' },
dbFilePath: _dbFile?.path,
options: {
- lockRoot: options.lockRoot,
- lockToken: options.lockToken,
- lockScope: options.lockScope,
- lockInfo: options.lockInfo
+ lockRoot: options!.lockRoot,
+ lockToken: options!.lockToken,
+ lockScope: options!.lockScope,
+ lockInfo: options!.lockInfo
}
}
] as any
@@ -1504,7 +1508,7 @@ describe('WebDAVMethods', () => {
// Expected to throw
}
- expect(logSpy.mock.calls.some(([payload]: { msg: string }[]) => payload?.msg?.includes(' -> /webdav/test/dest.txt'))).toBe(true)
+ expect(logSpy.mock.calls.some(([payload]) => (payload as { msg?: string })?.msg?.includes(' -> /webdav/test/dest.txt'))).toBe(true)
})
})
})
@@ -2094,8 +2098,8 @@ describe('WebDAVMethods', () => {
// Expected to throw
}
- expect(logSpy.mock.calls.some(([payload]: { msg: string }[]) => payload?.msg?.includes('PUT'))).toBe(true)
- expect(logSpy.mock.calls.some(([payload]: { msg: string }[]) => payload?.msg?.includes('/webdav/test.txt'))).toBe(true)
+ expect(logSpy.mock.calls.some(([payload]) => (payload as { msg?: string })?.msg?.includes('PUT'))).toBe(true)
+ expect(logSpy.mock.calls.some(([payload]) => (payload as { msg?: string })?.msg?.includes('/webdav/test.txt'))).toBe(true)
})
it('should include destination URL in log when provided', () => {
@@ -2110,7 +2114,7 @@ describe('WebDAVMethods', () => {
// Expected to throw
}
- expect(logSpy.mock.calls.some(([payload]: { msg: string }[]) => payload?.msg?.includes(' -> /webdav/destination.txt'))).toBe(true)
+ expect(logSpy.mock.calls.some(([payload]) => (payload as { msg?: string })?.msg?.includes(' -> /webdav/destination.txt'))).toBe(true)
})
})
})
diff --git a/backend/src/applications/webdav/services/webdav-methods.service.ts b/backend/src/applications/webdav/services/webdav-methods.service.ts
index c4685a0f..3346f88b 100644
--- a/backend/src/applications/webdav/services/webdav-methods.service.ts
+++ b/backend/src/applications/webdav/services/webdav-methods.service.ts
@@ -1,5 +1,6 @@
import { HttpException, HttpStatus, Injectable, Logger, StreamableFile } from '@nestjs/common'
import { type FastifyReply } from 'fastify'
+import { toErrorMessage } from '../../../common/errors.js'
import { currentTimeStamp, encodeUrl } from '../../../common/shared.js'
import { HTTP_METHOD, HTTP_VERSION } from '../../applications.constants.js'
import { FileLock, FileLockOptions } from '../../files/interfaces/file-lock.interface.js'
@@ -13,6 +14,7 @@ import { SPACE_OPERATION, SPACE_REPOSITORY } from '../../spaces/constants/spaces
import { SpaceEnv } from '../../spaces/models/space-env.model.js'
import { dbFileFromSpace, temporaryRootFromSpace } from '../../spaces/utils/paths.js'
import { haveSpaceEnvPermissions } from '../../spaces/utils/permissions.js'
+import type { LOCK_DEPTH } from '../constants/webdav.js'
import {
DEPTH,
HEADER,
@@ -30,7 +32,7 @@ import {
XML_CONTENT_TYPE
} from '../constants/webdav.js'
import { IfHeaderDecorator } from '../decorators/if-header.decorator.js'
-import { type FastifyDAVRequest } from '../interfaces/webdav.interface.js'
+import { type FastifyDAVRequest, type FastifyDAVSpaceRequest } from '../interfaces/webdav.interface.js'
import { extractAllTokens, extractOneToken } from '../utils/if-header.js'
import { DAV_ERROR_RES, LOCK_DISCOVERY, LOCK_PROP, MULTI_STATUS, PROP, PROP_STAT } from '../utils/webdav.js'
import { xmlBuild } from '../utils/xml.js'
@@ -46,7 +48,7 @@ export class WebDAVMethods {
private readonly filesLockManager: FilesLockManager
) {}
- async headOrGet(req: FastifyDAVRequest, res: FastifyReply, repository: string): Promise<StreamableFile> {
+ async headOrGet(req: FastifyDAVSpaceRequest, res: FastifyReply, repository: string): Promise<StreamableFile> {
if (repository === SPACE_REPOSITORY.FILES && !req.space.inSharesList) {
if ((await isPathExists(req.space.realPath)) && (await isPathIsDir(req.space.realPath))) {
// Directory case
@@ -70,7 +72,7 @@ export class WebDAVMethods {
}
@IfHeaderDecorator()
- async lock(req: FastifyDAVRequest, res: FastifyReply) {
+ async lock(req: FastifyDAVSpaceRequest, res: FastifyReply) {
const isLockRefresh = !req.dav.body
const rExists = await isPathExists(req.space.realPath)
@@ -98,7 +100,7 @@ export class WebDAVMethods {
const lockOptions: FileLockOptions = {
lockRoot: req.dav.url,
lockToken: this.filesLockManager.genDAVToken(),
- lockScope: req.dav.lock.lockscope,
+ lockScope: req.dav.lock!.lockscope!,
lockInfo: req.dav.lock?.owner
}
@@ -106,9 +108,9 @@ export class WebDAVMethods {
req.user,
req.space.dbFile,
WEBDAV_APP_LOCK,
- req.dav.depth,
+ req.dav.depth as LOCK_DEPTH,
lockOptions,
- req.dav.lock.timeout
+ req.dav.lock!.timeout
)
if (ok) {
// Locking unmapped URLs: must create an empty resource (that is not a collection)
@@ -123,23 +125,20 @@ export class WebDAVMethods {
.status(rExists ? HttpStatus.OK : HttpStatus.CREATED)
.send(xmlBuild(lockProp))
}
- if (fileLock) {
- const lockProp = LOCK_PROP([fileLock])
- return res.type(XML_CONTENT_TYPE).status(HttpStatus.LOCKED).send(xmlBuild(lockProp))
- }
- return DAV_ERROR_RES(HttpStatus.LOCKED, PRECONDITION.LOCK_CONFLICT, res, fileLock.options?.lockRoot || fileLock.dbFilePath)
+ const lockProp = LOCK_PROP([fileLock])
+ return res.type(XML_CONTENT_TYPE).status(HttpStatus.LOCKED).send(xmlBuild(lockProp))
}
@IfHeaderDecorator()
- async unlock(req: FastifyDAVRequest, res: FastifyReply) {
+ async unlock(req: FastifyDAVSpaceRequest, res: FastifyReply) {
if (!(await isPathExists(req.space.realPath))) {
this.logger.warn({ tag: this.unlock.name, msg: `Unable to unlock: ${req.dav.url} - resource does not exist` })
return res.status(HttpStatus.NOT_FOUND).send(req.dav.url)
}
- const lock = await this.filesLockManager.isLockedWithToken(req.dav.lock.token, req.space.dbFile.path)
+ const lock = await this.filesLockManager.isLockedWithToken(req.dav.lock!.token!, req.space.dbFile.path)
if (!lock) {
- this.logger.warn({ tag: this.unlock.name, msg: `Lock token does not exist or not match URL : ${req.dav.lock.token}` })
+ this.logger.warn({ tag: this.unlock.name, msg: `Lock token does not exist or not match URL : ${req.dav.lock!.token}` })
return DAV_ERROR_RES(HttpStatus.CONFLICT, PRECONDITION.LOCK_TOKEN_MISMATCH, res)
}
if (req.user.id !== lock.owner.id) {
@@ -152,9 +151,9 @@ export class WebDAVMethods {
@IfHeaderDecorator()
async propfind(req: FastifyDAVRequest, res: FastifyReply, repository: string): Promise<string> {
- const isFileSystemResource = repository === SPACE_REPOSITORY.FILES && !req.space.inSharesList
+ const isFileSystemResource = repository === SPACE_REPOSITORY.FILES && !req.space!.inSharesList
if (isFileSystemResource) {
- if (!(await isPathExists(req.space.realPath))) {
+ if (!(await isPathExists(req.space!.realPath))) {
return res.status(HttpStatus.NOT_FOUND).send(req.dav.url)
}
}
@@ -174,10 +173,10 @@ export class WebDAVMethods {
if (req.dav.propfindMode !== PROPSTAT.PROPNAME && isFileSystemResource) {
if (req.dav.depth === DEPTH.RESOURCE) {
// match depth '0'
- locks = await this.filesLockManager.browseLocks(req.space.dbFile)
+ locks = await this.filesLockManager.browseLocks(req.space!.dbFile)
} else {
// match depth '1' or 'infinity'
- locks = await this.filesLockManager.browseParentChildLocks(req.space.dbFile)
+ locks = await this.filesLockManager.browseParentChildLocks(req.space!.dbFile)
}
}
@@ -190,13 +189,13 @@ export class WebDAVMethods {
for (const p of requestedProps) {
let fP: any
if (p === LOCK_DISCOVERY_PROP) {
- let lockDiscovery: any[] = null
+ let lockDiscovery: any[] | null = null
if (isFileSystemResource) {
if (f.name in locks) {
lockDiscovery = LOCK_DISCOVERY([locks[f.name]])
} else {
// The lock name may correspond to the original file at the space root.
- const fName = fileName(req.space.dbFile.path)
+ const fName = fileName(req.space!.dbFile.path)
if (fName in locks) {
lockDiscovery = LOCK_DISCOVERY([locks[fName]])
}
@@ -204,7 +203,7 @@ export class WebDAVMethods {
}
fP = lockDiscovery
} else {
- fP = f[p]
+ fP = f[p as keyof typeof f]
}
if (fP !== undefined) prop[`${NS_PREFIX}:${p}`] = fP
}
@@ -216,7 +215,7 @@ export class WebDAVMethods {
}
@IfHeaderDecorator()
- async put(req: FastifyDAVRequest, res: FastifyReply): Promise<FastifyReply> {
+ async put(req: FastifyDAVSpaceRequest, res: FastifyReply): Promise<FastifyReply> {
const isRangeUpload = req.headers['content-range'] !== undefined
let tmpPath: string | undefined
let rExists: boolean
@@ -253,7 +252,7 @@ export class WebDAVMethods {
}
@IfHeaderDecorator()
- async delete(req: FastifyDAVRequest, res: FastifyReply) {
+ async delete(req: FastifyDAVSpaceRequest, res: FastifyReply) {
try {
await this.filesManager.delete(req.user, req.space, { lockTokens: extractAllTokens(req.dav.ifHeaders) })
} catch (e) {
@@ -263,7 +262,7 @@ export class WebDAVMethods {
}
@IfHeaderDecorator()
- async proppatch(req: FastifyDAVRequest, res: FastifyReply) {
+ async proppatch(req: FastifyDAVSpaceRequest, res: FastifyReply) {
/* only support 'time modifications' */
if (!(await isPathExists(req.space.realPath))) {
return res.status(HttpStatus.NOT_FOUND).send(req.dav.url)
@@ -271,7 +270,7 @@ export class WebDAVMethods {
// check locks
try {
- await this.filesLockManager.checkConflicts(req.space.dbFile, req.dav.depth, {
+ await this.filesLockManager.checkConflicts(req.space.dbFile, req.dav.depth as LOCK_DEPTH, {
userId: req.user.id,
lockTokens: extractAllTokens(req.dav.ifHeaders)
})
@@ -307,7 +306,7 @@ export class WebDAVMethods {
}
for (const prop of req.dav.body[PROPPATCH_PROP_UPDATE][action][PROPSTAT.PROP] as Record<string, string>[]) {
- for (let [name, value] of Object.entries(prop)) {
+ for (let [name, value] of Object.entries(prop) as [string, string | null][]) {
if (action === PROPPATCH_METHOD.REMOVE) {
value = null
this.logger.debug({ tag: this.proppatch.name, msg: `Proppatch remove method not handled : ${name} -> ${value}` })
@@ -343,9 +342,9 @@ export class WebDAVMethods {
for (const [name, value] of Object.entries(req.dav.proppatch.props)) {
if (PROPPATCH_MODIFIED_PROPS.indexOf(name) > -1) {
try {
- await this.filesManager.touch(req.user, req.space, currentTimeStamp(new Date(value)), false)
+ await this.filesManager.touch(req.user, req.space, currentTimeStamp(new Date(value as string)), false)
} catch (e) {
- this.logger.error({ tag: this.proppatch.name, msg: `unable to modify mtime on ${req.dav.url} : ${e}` })
+ this.logger.error({ tag: this.proppatch.name, msg: `unable to modify mtime on ${req.dav.url} : ${toErrorMessage(e)}` })
states[name] = false
atLeastOneError = true
}
@@ -369,9 +368,12 @@ export class WebDAVMethods {
}
@IfHeaderDecorator()
- async mkcol(req: FastifyDAVRequest, res: FastifyReply) {
+ async mkcol(req: FastifyDAVSpaceRequest, res: FastifyReply) {
try {
- await this.filesManager.mkDir(req.user, req.space, false, { depth: req.dav.depth, lockTokens: extractAllTokens(req.dav.ifHeaders) })
+ await this.filesManager.mkDir(req.user, req.space, false, {
+ depth: req.dav.depth as LOCK_DEPTH,
+ lockTokens: extractAllTokens(req.dav.ifHeaders)
+ })
} catch (e) {
return this.handleError(req, res, e)
}
@@ -379,26 +381,26 @@ export class WebDAVMethods {
}
@IfHeaderDecorator()
- async copyMove(req: FastifyDAVRequest, res: FastifyReply) {
- const dstSpace: SpaceEnv = await this.webDAVHandler.spaceEnv(req.user, req.dav.copyMove.destination)
+ async copyMove(req: FastifyDAVSpaceRequest, res: FastifyReply) {
+ const dstSpace = await this.webDAVHandler.spaceEnv(req.user, req.dav.copyMove!.destination)
if (!dstSpace) {
- this.logger.warn({ tag: this.copyMove.name, msg: `Space not found for destination : ${req.dav.copyMove.destination}` })
- return res.status(HttpStatus.NOT_FOUND).send(req.dav.copyMove.destination)
+ this.logger.warn({ tag: this.copyMove.name, msg: `Space not found for destination : ${req.dav.copyMove!.destination}` })
+ return res.status(HttpStatus.NOT_FOUND).send(req.dav.copyMove!.destination)
}
const dstExisted = await isPathExists(dstSpace.realPath)
// We must evaluate the if-headers on the destination
const fakeDstReq = {
- dav: { ...req.dav, url: req.dav.copyMove.destination },
+ dav: { ...req.dav, url: req.dav.copyMove!.destination },
user: req.user,
space: dstSpace
- } as FastifyDAVRequest
+ } as FastifyDAVSpaceRequest
if (!(await this.evaluateIfHeaders(fakeDstReq, res))) {
// if there is an error, the response is generated inside the `evaluateIfHeaders` function
return
}
try {
- await this.filesManager.copyMove(req.user, req.space, dstSpace, req.dav.copyMove.isMove, req.dav.copyMove.overwrite, false, {
- depth: req.dav.depth,
+ await this.filesManager.copyMove(req.user, req.space, dstSpace, req.dav.copyMove!.isMove, req.dav.copyMove!.overwrite, false, {
+ depth: req.dav.depth as LOCK_DEPTH,
lockTokens: extractAllTokens(req.dav.ifHeaders)
})
} catch (e) {
@@ -407,13 +409,13 @@ export class WebDAVMethods {
return res.status(dstExisted ? HttpStatus.NO_CONTENT : HttpStatus.CREATED).send()
}
- protected async evaluateIfHeaders(req: FastifyDAVRequest, res: FastifyReply): Promise<boolean> {
+ protected async evaluateIfHeaders(req: FastifyDAVSpaceRequest, res: FastifyReply): Promise<boolean> {
if (!req.dav.ifHeaders) return true
const errors: string[] = []
- let lastPath = null
- let lastSpaceEnv: SpaceEnv
- let lastRPath = undefined
- let lastEtag = undefined // for now, we only generate one etag type (weak)
+ let lastPath: string | null = null
+ let lastSpaceEnv: SpaceEnv | null | undefined
+ let lastRPath: string | null | undefined = undefined
+ let lastEtag: string | null | undefined = undefined // for now, we only generate one etag type (weak)
let atLeastOneOk = false
for (const condition of req.dav.ifHeaders) {
@@ -441,14 +443,14 @@ export class WebDAVMethods {
continue
}
} catch (e) {
- errors.push(`have lock condition mismatch : ${e.message}`)
+ errors.push(`have lock condition mismatch : ${toErrorMessage(e)}`)
continue
}
}
if (condition.token) {
const token = await this.filesLockManager.getLockByToken(condition.token.value)
- const match = token && lastPath.startsWith(token.options?.lockRoot)
+ const match = token && lastPath!.startsWith(token.options?.lockRoot as string)
if (condition.token.mustMatch !== match) {
if (!token) {
errors.push(`lock token not found`)
@@ -484,7 +486,7 @@ export class WebDAVMethods {
return atLeastOneOk
}
- private async lockRefresh(req: FastifyDAVRequest, res: FastifyReply, dbFilePath: string) {
+ private async lockRefresh(req: FastifyDAVSpaceRequest, res: FastifyReply, dbFilePath: string) {
if (req.dav?.ifHeaders?.length !== 1) {
this.logger.warn({ tag: this.lockRefresh.name, msg: 'Expected a lock token (only one lock may be refreshed at a time)' })
return res.status(HttpStatus.BAD_REQUEST).send('Expected a lock token (only one lock may be refreshed at a time)')
@@ -494,7 +496,7 @@ export class WebDAVMethods {
try {
token = extractOneToken(req.dav.ifHeaders)
} catch (e) {
- this.logger.warn({ tag: this.lockRefresh.name, msg: `unable to extract token : ${JSON.stringify(req.dav.ifHeaders)} (${e})` })
+ this.logger.warn({ tag: this.lockRefresh.name, msg: `unable to extract token : ${JSON.stringify(req.dav.ifHeaders)} (${toErrorMessage(e)})` })
return res.status(HttpStatus.BAD_REQUEST).send('Unable to extract token')
}
@@ -508,15 +510,16 @@ export class WebDAVMethods {
return res.status(HttpStatus.FORBIDDEN).send('Lock token does not match owner')
}
- await this.filesLockManager.refreshLockTimeout(lock, req.dav.lock.timeout)
+ await this.filesLockManager.refreshLockTimeout(lock, req.dav.lock!.timeout!)
const lockProp = LOCK_PROP([lock])
return res.type(XML_CONTENT_TYPE).status(HttpStatus.OK).send(xmlBuild(lockProp))
}
- private handleError(req: FastifyDAVRequest, res: FastifyReply, e: any, toUrl?: string) {
- this.logger.error({ tag: this.handleError.name, msg: `Unable to ${req.method} ${req.dav.url}${toUrl ? ` -> ${toUrl}` : ''} : ${e.message}` })
+ private handleError(req: FastifyDAVRequest, res: FastifyReply, e: unknown, toUrl?: string) {
+ const errorMessage = toErrorMessage(e)
+ this.logger.error({ tag: this.handleError.name, msg: `Unable to ${req.method} ${req.dav.url}${toUrl ? ` -> ${toUrl}` : ''} : ${errorMessage}` })
// Remove the last part to avoid exposing the path
- const errorMsg = e.message.split(',')[0]
+ const errorMsg = errorMessage.split(',')[0]
if (e instanceof LockConflict) {
return DAV_ERROR_RES(HttpStatus.LOCKED, PRECONDITION.LOCK_CONFLICT, res, e.lock.options?.lockRoot || e.lock.dbFilePath)
} else if (e instanceof FileError) {
diff --git a/backend/src/applications/webdav/services/webdav-spaces.service.spec.ts b/backend/src/applications/webdav/services/webdav-spaces.service.spec.ts
index 0691b2a4..c2b0698e 100644
--- a/backend/src/applications/webdav/services/webdav-spaces.service.spec.ts
+++ b/backend/src/applications/webdav/services/webdav-spaces.service.spec.ts
@@ -12,11 +12,15 @@ import { WebDAVSpaces } from './webdav-spaces.service.js'
import { Mocked } from 'vitest'
// mocks for file utils and permissions
-vi.mock('../../files/utils/files.js', () => ({
- getProps: vi.fn(),
- isPathExists: vi.fn(),
- isPathIsDir: vi.fn()
-}))
+vi.mock('../../files/utils/files.js', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('../../files/utils/files.js')>()
+ return {
+ ...actual,
+ getProps: vi.fn(),
+ isPathExists: vi.fn(),
+ isPathIsDir: vi.fn()
+ }
+})
vi.mock('../../spaces/utils/permissions.js', () => ({
canAccessToSpaceUrl: vi.fn()
}))
@@ -131,7 +135,7 @@ describe(WebDAVSpaces.name, () => {
vi.mocked(spacesManager.listSpaces).mockResolvedValue([
{ id: 10, name: 'Team A', alias: 'team-a', createdAt: now.toISOString(), modifiedAt: now.toISOString() },
{ id: 11, name: 'Team B', alias: 'team-b', createdAt: now.toISOString(), modifiedAt: now.toISOString() }
- ])
+ ] as never)
const req = { user, dav: { url: '/webdav/spaces', depth: DEPTH.MEMBERS } } as unknown as FastifyDAVRequest
const items = await collectGenerator(service.propfind(req, WEBDAV_NS.SPACES as any))
@@ -151,7 +155,7 @@ describe(WebDAVSpaces.name, () => {
vi.mocked(spacesManager.listTrashes).mockResolvedValue([
{ id: 1, alias: 'personal', nb: 2, mtime: 3, ctime: 4, name: 'Personal files' },
{ id: 2, alias: 'team-a', nb: 5, mtime: 6, ctime: 7, name: 'Team A' }
- ])
+ ] as never)
const req = { user, dav: { url: '/webdav/trash', depth: DEPTH.MEMBERS } } as unknown as FastifyDAVRequest
const items = await collectGenerator(service.propfind(req, WEBDAV_NS.TRASH as any))
expect(items.map((i: any) => i.name)).toEqual([WEBDAV_NS.TRASH, 'personal (2)', 'team-a (5)'])
@@ -169,7 +173,7 @@ describe(WebDAVSpaces.name, () => {
it('yields shares root and children when inSharesList=true and depth=1', async () => {
vi.mocked(spacesBrowser.browse).mockResolvedValue({
files: [{ id: 1, name: 'doc.txt', isDir: false, size: 12, ctime: 1, mtime: 2, mime: 'text/plain' }]
- })
+ } as never)
const req = {
user,
@@ -206,11 +210,11 @@ describe(WebDAVSpaces.name, () => {
ctime: Date.now(),
mtime: Date.now(),
mime: undefined
- })
+ } as never)
vi.mocked(isPathIsDir).mockResolvedValue(true)
vi.mocked(spacesBrowser.browse).mockResolvedValue({
files: [{ id: 2, name: 'child.txt', isDir: false, size: 1, ctime: 1, mtime: 2, mime: 'text/plain' }]
- })
+ } as never)
const req = {
user,
@@ -232,10 +236,9 @@ describe(WebDAVSpaces.name, () => {
ctime: Date.now(),
mtime: Date.now(),
mime: 'text/plain'
- })
+ } as never)
vi.mocked(isPathIsDir).mockResolvedValue(false)
- vi.mocked(spacesBrowser.browse).mockResolvedValue({ files: [] })
-
+ vi.mocked(spacesBrowser.browse).mockResolvedValue({ files: [] } as never)
const req = {
user,
dav: { url: '/webdav/files/personal/current', depth: DEPTH.MEMBERS },
@@ -253,7 +256,7 @@ describe(WebDAVSpaces.name, () => {
const req = { user, dav: { url: '/webdav/unknown', depth: DEPTH.RESOURCE } } as unknown as FastifyDAVRequest
try {
service.propfind(req, 'unknown' as any)
- fail('Expected HttpException to be thrown')
+ throw new Error('Expected HttpException to be thrown')
} catch (err) {
expect(err).toBeInstanceOf(HttpException)
expect((err as HttpException).getStatus()).toBe(HttpStatus.NOT_FOUND)
diff --git a/backend/src/applications/webdav/services/webdav-spaces.service.ts b/backend/src/applications/webdav/services/webdav-spaces.service.ts
index f90f5820..0d9ca888 100644
--- a/backend/src/applications/webdav/services/webdav-spaces.service.ts
+++ b/backend/src/applications/webdav/services/webdav-spaces.service.ts
@@ -1,3 +1,4 @@
+import { toErrorMessage } from '../../../common/errors.js'
import { HttpException, HttpStatus, Injectable, Logger } from '@nestjs/common'
import { getProps, isPathExists, isPathIsDir } from '../../files/utils/files.js'
import { SPACE_REPOSITORY } from '../../spaces/constants/spaces.js'
@@ -15,22 +16,21 @@ import { WEBDAV_PATH_TO_SPACE_SEGMENTS } from '../utils/routes.js'
@Injectable()
export class WebDAVSpaces {
private readonly logger = new Logger(WebDAVSpaces.name)
- private readonly roots: Record<string, WebDAVFile> = {}
+ private readonly roots = {} as Record<keyof typeof WEBDAV_SPACES, WebDAVFile>
constructor(
private readonly spacesManager: SpacesManager,
private readonly spacesBrowser: SpacesBrowser
) {
for (const [name, info] of Object.entries(WEBDAV_SPACES)) {
- this.roots[name] = new WebDAVFile(
+ this.roots[name as keyof typeof WEBDAV_SPACES] = new WebDAVFile(
{
id: 0,
name: name,
isDir: true,
size: 0,
ctime: new Date().getTime(),
- mtime: new Date().getTime(),
- mime: undefined
+ mtime: new Date().getTime()
},
info.route,
true
@@ -38,14 +38,14 @@ export class WebDAVSpaces {
}
}
- async spaceEnv(user: UserModel, path: string) {
+ async spaceEnv(user: UserModel, path: string): Promise<SpaceEnv | null> {
try {
- const space: SpaceEnv = await this.spacesManager.spaceEnv(user, WEBDAV_PATH_TO_SPACE_SEGMENTS(path))
+ const space = await this.spacesManager.spaceEnv(user, WEBDAV_PATH_TO_SPACE_SEGMENTS(path))
if (space) {
return space
}
} catch (e) {
- this.logger.warn({ tag: this.spaceEnv.name, msg: `${e}` })
+ this.logger.warn({ tag: this.spaceEnv.name, msg: toErrorMessage(e) })
return null
}
@@ -56,7 +56,7 @@ export class WebDAVSpaces {
propfind(req: FastifyDAVRequest, space: string): AsyncGenerator<WebDAVFile> {
switch (space) {
case SPACE_REPOSITORY.FILES:
- return this.listFiles(req, req.space)
+ return this.listFiles(req, req.space!)
case WEBDAV_NS.SERVER:
return this.listServer(req)
case WEBDAV_NS.WEBDAV:
@@ -86,7 +86,7 @@ export class WebDAVSpaces {
for (const root of Object.values(this.roots)) {
if ([WEBDAV_NS.SERVER as string, WEBDAV_NS.WEBDAV as string].indexOf(root.name) === -1) {
// filter repositories based on user applications
- if (!canAccessToSpaceUrl(req.user, WEBDAV_SPACES[root.name].spaceRepository)) {
+ if (!canAccessToSpaceUrl(req.user, WEBDAV_SPACES[root.name as keyof typeof WEBDAV_SPACES].spaceRepository!)) {
continue
}
yield root
@@ -107,9 +107,8 @@ export class WebDAVSpaces {
alias: s.alias,
isDir: true,
size: 0,
- mime: undefined,
- ctime: new Date(s.createdAt).getTime(),
- mtime: new Date(s.modifiedAt).getTime()
+ ctime: new Date(s.createdAt!).getTime(),
+ mtime: new Date(s.modifiedAt!).getTime()
},
req.dav.url
)
@@ -129,7 +128,6 @@ export class WebDAVSpaces {
name: `${f.alias} (${f.nb})`,
isDir: true,
size: 0,
- mime: undefined,
mtime: f.mtime,
ctime: f.ctime
},
@@ -140,7 +138,7 @@ export class WebDAVSpaces {
}
private async *listFiles(req: FastifyDAVRequest, space: SpaceEnv): AsyncGenerator<WebDAVFile> {
- let isDir: boolean
+ let isDir!: boolean
if (space.inSharesList) {
// The shares are defined like a files (direct link)
diff --git a/backend/src/applications/webdav/utils/if-header.ts b/backend/src/applications/webdav/utils/if-header.ts
index 0f2b1889..89864679 100644
--- a/backend/src/applications/webdav/utils/if-header.ts
+++ b/backend/src/applications/webdav/utils/if-header.ts
@@ -9,7 +9,7 @@ import { IfHeader } from '../interfaces/if-header.interface.js'
const ifHeaderRegExp = /(?:<([^>]+)>)?\s*\(([^)]+)\)/g
const ifHeaderInternalRegExp = /((not)|\[([^\]]+)\]|<(DAV:no-lock)>|<([^>]+)>|([^\s]+))/gi
-function parseIfHeaderInternal(path: string, group: string) {
+function parseIfHeaderInternal(path: string | undefined, group: string) {
let match = ifHeaderInternalRegExp.exec(group)
let mustMatch = true
@@ -42,22 +42,22 @@ function parseIfHeaderInternal(path: string, group: string) {
export function parseIfHeader(ifHeader: string): IfHeader[] {
const orArray: IfHeader[] = []
let match = ifHeaderRegExp.exec(ifHeader)
- let path = undefined
+ let path: string | undefined = undefined
while (match) {
if (match[1]) {
path = urlToPath(match[1])
}
- orArray.push(parseIfHeaderInternal(path, match[2]))
+ orArray.push(parseIfHeaderInternal(path, match[2]!))
match = ifHeaderRegExp.exec(ifHeader)
}
return orArray
}
-export function extractOneToken(ifHeaders: IfHeader[]): string {
- return ifHeaders[0].token.value
+export function extractOneToken(ifHeaders?: IfHeader[]): string {
+ return ifHeaders![0].token!.value
}
-export function extractAllTokens(ifHeaders: IfHeader[]): string[] {
- return ifHeaders ? ifHeaders.map((i: IfHeader) => i.token?.value).filter(Boolean) : []
+export function extractAllTokens(ifHeaders?: IfHeader[]): string[] {
+ return (ifHeaders ? ifHeaders.map((i: IfHeader) => i.token?.value).filter(Boolean) : []) as string[]
}
diff --git a/backend/src/applications/webdav/utils/routes.ts b/backend/src/applications/webdav/utils/routes.ts
index 9cac4efa..083c51df 100644
--- a/backend/src/applications/webdav/utils/routes.ts
+++ b/backend/src/applications/webdav/utils/routes.ts
@@ -7,9 +7,9 @@ export function WEBDAV_PATH_TO_SPACE_SEGMENTS(path: string): string[] {
urlSegments.shift()
}
const repository = urlSegments.shift()
- if (!(repository in WEBDAV_SPACES)) {
+ if (!((repository as string) in WEBDAV_SPACES)) {
throw new Error(`Repository not found : ${repository}`)
}
- urlSegments.unshift(...WEBDAV_SPACES[repository].spaceRepository)
+ urlSegments.unshift(...WEBDAV_SPACES[repository as keyof typeof WEBDAV_SPACES].spaceRepository!)
return urlSegments
}
diff --git a/backend/src/applications/webdav/utils/webdav.ts b/backend/src/applications/webdav/utils/webdav.ts
index 996e3d00..37dff8a3 100644
--- a/backend/src/applications/webdav/utils/webdav.ts
+++ b/backend/src/applications/webdav/utils/webdav.ts
@@ -90,6 +90,6 @@ export function DAV_ERROR_RES(code: number, error: string, res: FastifyReply, hr
}
function formatLockOwner(lock: FileLock) {
- const lockInfo = `${lock.options.lockInfo ? `${lock.options.lockInfo}` : ''}${lock.app ? ` ${lock.app}` : ''}`
+ const lockInfo = `${lock.options!.lockInfo ? `${lock.options!.lockInfo}` : ''}${lock.app ? ` ${lock.app}` : ''}`
return `${lock.owner.fullName} (${lock.owner.email})${lockInfo ? ` - ${lockInfo}` : ''}`
}
diff --git a/backend/src/applications/webdav/webdav.controller.ts b/backend/src/applications/webdav/webdav.controller.ts
index 5c2ff60d..530dc777 100644
--- a/backend/src/applications/webdav/webdav.controller.ts
+++ b/backend/src/applications/webdav/webdav.controller.ts
@@ -5,8 +5,9 @@ import { SPACE_REPOSITORY } from '../spaces/constants/spaces.js'
import { SpaceGuard } from '../spaces/guards/space.guard.js'
import { WEBDAV_BASE_PATH, WEBDAV_NS } from './constants/routes.js'
import { WebDAVEnvironment } from './decorators/webdav-context.decorator.js'
-import { type FastifyDAVRequest } from './interfaces/webdav.interface.js'
+import { type FastifyDAVRequest, type FastifyDAVSpaceRequest } from './interfaces/webdav.interface.js'
import { WebDAVMethods } from './services/webdav-methods.service.js'
+import { repositoryParameterSchema } from './webdav.schema.js'
@Controller()
@WebDAVEnvironment()
@@ -45,14 +46,14 @@ export class WebDAVController {
async repositoriesPropfind(
@Req() req: FastifyDAVRequest,
@Res({ passthrough: true }) res: FastifyReply,
- @Param('repository') repository: string
+ @Param('repository', { schema: repositoryParameterSchema }) repository: string
): Promise<string> {
return this.webdavMethods.propfind(req, res, repository)
}
@All(`${WEBDAV_BASE_PATH}/*`)
@UseGuards(SpaceGuard)
- async files(@Req() req: FastifyDAVRequest, @Res({ passthrough: true }) res: FastifyReply): Promise<string | StreamableFile> {
+ async files(@Req() req: FastifyDAVSpaceRequest, @Res({ passthrough: true }) res: FastifyReply): Promise<string | StreamableFile | void> {
// OPTIONS method is handled in the `WebDAVProtocolGuard`
switch (req.method) {
case HTTP_METHOD.PROPFIND:
diff --git a/backend/src/applications/webdav/webdav.schema.ts b/backend/src/applications/webdav/webdav.schema.ts
new file mode 100644
index 00000000..1ddb1d51
--- /dev/null
+++ b/backend/src/applications/webdav/webdav.schema.ts
@@ -0,0 +1,4 @@
+import { z } from 'zod'
+import { WEBDAV_NS } from './constants/routes.js'
+
+export const repositoryParameterSchema = z.enum([WEBDAV_NS.SPACES, WEBDAV_NS.TRASH])
diff --git a/backend/src/authentication/auth.config.ts b/backend/src/authentication/auth.config.ts
index c6d43514..b8d368e9 100644
--- a/backend/src/authentication/auth.config.ts
+++ b/backend/src/authentication/auth.config.ts
@@ -1,119 +1,80 @@
-import { Exclude, Type } from 'class-transformer'
-import { IsDefined, IsEnum, IsIn, IsNotEmpty, IsNotEmptyObject, IsObject, IsOptional, IsString, ValidateIf, ValidateNested } from 'class-validator'
+import { z } from 'zod'
+import { nonEmptyStringSchema } from '../configuration/config.schema.js'
import { ACCESS_KEY, CSRF_KEY, REFRESH_KEY, WS_KEY } from './constants/auth.js'
import { AUTH_PROVIDER } from './providers/auth-providers.constants.js'
-import { AuthProviderLDAPConfig } from './providers/ldap/auth-ldap.config.js'
-import { AuthProviderOIDCConfig } from './providers/oidc/auth-oidc.config.js'
-import { AuthMFAConfig } from './providers/two-fa/auth-two-fa.config.js'
-
-export class AuthTokenAccessConfig {
- @Exclude({ toClassOnly: true })
- // force default name
- name = ACCESS_KEY
-
- @IsString()
- @IsNotEmpty()
- secret: string
-
- @IsString()
- @IsNotEmpty()
- expiration = '15m'
+import { type AuthProviderLDAPConfig, AuthProviderLDAPConfigSchema, hydrateAuthProviderLDAPConfig } from './providers/ldap/auth-ldap.config.js'
+import { type AuthProviderOIDCConfig, AuthProviderOIDCConfigSchema, hydrateAuthProviderOIDCConfig } from './providers/oidc/auth-oidc.config.js'
+import { AuthMFAConfigSchema } from './providers/two-fa/auth-two-fa.config.js'
+
+export type AuthTokenAccessConfig = z.output<typeof AuthTokenAccessConfigSchema>
+export type AuthTokenRefreshConfig = z.output<typeof AuthTokenRefreshConfigSchema>
+export type AuthConfig = z.output<typeof AuthConfigSchema>
+
+// Token and cookie names are fixed application identifiers.
+// Missing or custom configuration values are replaced with the expected server-controlled name.
+function createTokenConfigSchema(name: string, expiration: string) {
+ return z.looseObject({
+ name: z.literal(name).catch(name),
+ secret: nonEmptyStringSchema,
+ expiration: nonEmptyStringSchema.default(expiration)
+ })
}
-export class AuthTokenRefreshConfig {
- @Exclude({ toClassOnly: true })
- // force default name
- name = REFRESH_KEY
-
- @IsString()
- @IsNotEmpty()
- secret: string
-
- @IsString()
- @IsNotEmpty()
- expiration = '4h'
+export const AuthTokenAccessConfigSchema = createTokenConfigSchema(ACCESS_KEY, '15m')
+export const AuthTokenRefreshConfigSchema = createTokenConfigSchema(REFRESH_KEY, '4h')
+export const AuthTokenCsrfConfigSchema = createTokenConfigSchema(CSRF_KEY, '4h')
+export const AuthTokenWSConfigSchema = createTokenConfigSchema(WS_KEY, '4h')
+
+export const AuthTokenConfigSchema = z.looseObject({
+ access: AuthTokenAccessConfigSchema,
+ refresh: AuthTokenRefreshConfigSchema,
+ csrf: AuthTokenCsrfConfigSchema,
+ ws: AuthTokenWSConfigSchema,
+ // Derived by the loader; retain the former unchecked contract for these keys.
+ access_2fa: z
+ .custom<AuthTokenAccessConfig>()
+ .optional()
+ .transform((value) => value as AuthTokenAccessConfig),
+ csrf_2fa: z
+ .custom<AuthTokenAccessConfig>()
+ .optional()
+ .transform((value) => value as AuthTokenAccessConfig)
+})
+
+// Inactive providers keep their defaults without validating user-supplied values.
+const inactiveLDAPConfigSchema = z
+ .custom<AuthProviderLDAPConfig>()
+ .optional()
+ .transform((value) => hydrateAuthProviderLDAPConfig(value) as AuthProviderLDAPConfig)
+const inactiveOIDCConfigSchema = z
+ .custom<AuthProviderOIDCConfig>()
+ .optional()
+ .transform((value) => hydrateAuthProviderOIDCConfig(value) as AuthProviderOIDCConfig)
+
+const authConfigShape = {
+ encryptionKey: z.string().nullish(),
+ mfa: AuthMFAConfigSchema.prefault({}),
+ cookieSameSite: z.enum(['lax', 'strict']).default('strict'),
+ token: AuthTokenConfigSchema
}
-export class AuthTokenCsrfConfig extends AuthTokenRefreshConfig {
- @IsString()
- @IsNotEmpty()
- override name: string = CSRF_KEY
-}
-
-export class AuthTokenWSConfig extends AuthTokenRefreshConfig {
- @IsString()
- @IsNotEmpty()
- override name: string = WS_KEY
-}
-
-export class AuthTokenConfig {
- @IsDefined()
- @IsNotEmptyObject()
- @IsObject()
- @ValidateNested()
- @Type(() => AuthTokenAccessConfig)
- access: AuthTokenAccessConfig
-
- @IsDefined()
- @IsNotEmptyObject()
- @IsObject()
- @ValidateNested()
- @Type(() => AuthTokenRefreshConfig)
- refresh: AuthTokenRefreshConfig
-
- @IsDefined()
- @IsNotEmptyObject()
- @IsObject()
- @ValidateNested()
- @Type(() => AuthTokenCsrfConfig)
- csrf: AuthTokenCsrfConfig
-
- @IsDefined()
- @IsNotEmptyObject()
- @IsObject()
- @ValidateNested()
- @Type(() => AuthTokenWSConfig)
- ws: AuthTokenWSConfig
-}
-
-export class AuthConfig {
- @IsString()
- @IsEnum(AUTH_PROVIDER)
- provider: AUTH_PROVIDER = AUTH_PROVIDER.MYSQL
-
- @IsOptional()
- @IsString()
- encryptionKey: string
-
- @IsDefined()
- @IsNotEmptyObject()
- @IsObject()
- @ValidateNested()
- @Type(() => AuthMFAConfig)
- mfa: AuthMFAConfig = new AuthMFAConfig()
-
- @IsString()
- @IsIn(['lax', 'strict'])
- cookieSameSite: 'lax' | 'strict' = 'strict'
-
- @IsDefined()
- @IsNotEmptyObject()
- @IsObject()
- @ValidateNested()
- @Type(() => AuthTokenConfig)
- token: AuthTokenConfig
-
- @ValidateIf((o: AuthConfig) => o.provider === AUTH_PROVIDER.LDAP)
- @IsDefined()
- @IsObject()
- @ValidateNested()
- @Type(() => AuthProviderLDAPConfig)
- ldap: AuthProviderLDAPConfig
-
- @ValidateIf((o: AuthConfig) => o.provider === AUTH_PROVIDER.OIDC)
- @IsDefined()
- @IsObject()
- @ValidateNested()
- @Type(() => AuthProviderOIDCConfig)
- oidc: AuthProviderOIDCConfig
-}
+export const AuthConfigSchema = z.discriminatedUnion('provider', [
+ z.looseObject({
+ ...authConfigShape,
+ provider: z.literal(AUTH_PROVIDER.MYSQL).default(AUTH_PROVIDER.MYSQL),
+ ldap: inactiveLDAPConfigSchema,
+ oidc: inactiveOIDCConfigSchema
+ }),
+ z.looseObject({
+ ...authConfigShape,
+ provider: z.literal(AUTH_PROVIDER.LDAP),
+ ldap: AuthProviderLDAPConfigSchema,
+ oidc: inactiveOIDCConfigSchema
+ }),
+ z.looseObject({
+ ...authConfigShape,
+ provider: z.literal(AUTH_PROVIDER.OIDC),
+ ldap: inactiveLDAPConfigSchema,
+ oidc: AuthProviderOIDCConfigSchema
+ })
+])
diff --git a/backend/src/authentication/auth.controller.spec.ts b/backend/src/authentication/auth.controller.spec.ts
index 3f794b48..a40cef6a 100755
--- a/backend/src/authentication/auth.controller.spec.ts
+++ b/backend/src/authentication/auth.controller.spec.ts
@@ -1,5 +1,5 @@
import fastifyCookie, { sign } from '@fastify/cookie'
-import { ExecutionContext, UnauthorizedException, ValidationPipe } from '@nestjs/common'
+import { ExecutionContext, StandardSchemaValidationPipe, UnauthorizedException } from '@nestjs/common'
import { APP_GUARD, Reflector } from '@nestjs/core'
import { JwtService } from '@nestjs/jwt'
import { PassportModule } from '@nestjs/passport'
@@ -26,13 +26,13 @@ import { AUTH_TOKEN_SKIP } from './decorators/auth-token-skip.decorator.js'
import { LoginResponseDto, LoginVerify2FaDto } from './dto/login-response.dto.js'
import { AuthLocalGuard } from './guards/auth-local.guard.js'
import { AuthRateLimitGuard } from './guards/auth-rate-limit.guard.js'
-import { JwtPayload } from './interfaces/jwt-payload.interface.js'
+import type { JwtPayload } from './interfaces/jwt-payload.interface.js'
import { TOKEN_TYPE } from './interfaces/token.interface.js'
import { AuthProvider2FA } from './providers/two-fa/auth-provider-two-fa.service.js'
import { AuthTokenTwoFaGuard } from './providers/two-fa/guards/auth-token-two-fa.guard.js'
import { AuthTokenTwoFaStrategy } from './providers/two-fa/guards/auth-token-two-fa.strategy.js'
import { AuthTwoFaVerificationGuard } from './providers/two-fa/guards/auth-two-fa-verification.guard.js'
-import { TwoFaVerifyDto, TwoFaVerifyWithPasswordDto } from './providers/two-fa/auth-two-fa.dtos.js'
+import type { TwoFaVerifyDto, TwoFaVerifyWithPasswordDto } from './providers/two-fa/auth-two-fa.dtos.js'
describe(AuthController.name, () => {
let module: TestingModule
@@ -124,7 +124,7 @@ describe(AuthController.name, () => {
const res: any = { clearCookie: vi.fn() }
await expect(authController.logout(res)).resolves.not.toThrow()
expect(res.clearCookie).toHaveBeenCalledTimes(Object.keys(TOKEN_PATHS).length)
- for (const [type, path] of Object.entries(TOKEN_PATHS)) {
+ for (const [type, path] of Object.entries(TOKEN_PATHS) as [keyof typeof TOKEN_PATHS, string][]) {
expect(res.clearCookie).toHaveBeenCalledWith(authConfig.token[type].name, { path })
}
})
@@ -325,7 +325,7 @@ describe(`${AuthController.name} HTTP`, () => {
userTest = new UserModel({ ...generateUserTest(), id: 888 }, false)
app = module.createNestApplication<NestFastifyApplication>(new FastifyAdapter())
await app.register(fastifyCookie, { secret: authConfig.token.csrf.secret })
- app.useGlobalPipes(new ValidationPipe({ transform: true, whitelist: true }))
+ app.useGlobalPipes(new StandardSchemaValidationPipe())
await app.init()
await app.getHttpAdapter().getInstance().ready()
})
@@ -390,7 +390,7 @@ describe(`${AuthController.name} HTTP`, () => {
[TOKEN_TYPE.REFRESH]: expect.any(String)
})
)
- expect(validateTwoFactorCodeSpy).toHaveBeenCalledWith('123456', twoFaUser.secrets.twoFaSecret)
+ expect(validateTwoFactorCodeSpy).toHaveBeenCalledWith('123456', twoFaUser.secrets!.twoFaSecret)
expect(getTokensSpy).toHaveBeenCalledWith(userTest)
})
@@ -526,7 +526,7 @@ describe(`${AuthController.name} HTTP`, () => {
expect(response.json()).toEqual(result)
expect(loadUserSpy).toHaveBeenCalledWith(administrator.id, expect.any(String))
expect(verifyUserPasswordSpy).toHaveBeenCalledWith(administrator, 'password', expect.any(String))
- expect(validateTwoFactorCodeSpy).toHaveBeenCalledWith('123456', administrator.secrets.twoFaSecret)
+ expect(validateTwoFactorCodeSpy).toHaveBeenCalledWith('123456', administrator.secrets!.twoFaSecret)
expect(adminResetUserTwoFaSpy).toHaveBeenCalledWith(42)
})
diff --git a/backend/src/authentication/auth.controller.ts b/backend/src/authentication/auth.controller.ts
index bba6acd2..16929a7a 100755
--- a/backend/src/authentication/auth.controller.ts
+++ b/backend/src/authentication/auth.controller.ts
@@ -1,17 +1,18 @@
-import { Body, Controller, Get, Header, Param, ParseIntPipe, Post, Req, Res, UseGuards } from '@nestjs/common'
+import { Body, Controller, Get, Header, Param, Post, Req, Res, UseGuards } from '@nestjs/common'
import { type FastifyReply } from 'fastify'
import { USER_ROLE } from '../applications/users/constants/user.js'
import { UserHaveRole } from '../applications/users/decorators/roles.decorator.js'
import { GetUser } from '../applications/users/decorators/user.decorator.js'
import { UserRolesGuard } from '../applications/users/guards/roles.guard.js'
import { UserModel } from '../applications/users/models/user.model.js'
+import { integerFromStringSchema } from '../configuration/config.schema.js'
import { AvailabilitySkip } from '../infrastructure/availability/availability.decorator.js'
import { AuthManager } from './auth.service.js'
import { ACCESS_KEY, TOKEN_PATHS } from './constants/auth.js'
import { AUTH_ROUTE } from './constants/routes.js'
import { AuthTokenSkip } from './decorators/auth-token-skip.decorator.js'
import { LoginResponseDto, LoginVerify2FaDto } from './dto/login-response.dto.js'
-import { TokenResponseDto } from './dto/token-response.dto.js'
+import type { TokenResponseDto } from './dto/token-response.dto.js'
import { AuthLocalGuard } from './guards/auth-local.guard.js'
import { AuthRateLimitGuard } from './guards/auth-rate-limit.guard.js'
import { AuthTokenRefreshGuard } from './guards/auth-token-refresh.guard.js'
@@ -21,7 +22,13 @@ import type { AuthOIDCSettings } from './providers/oidc/auth-oidc.interfaces.js'
import { AuthProvider2FA } from './providers/two-fa/auth-provider-two-fa.service.js'
import { AuthTokenTwoFaGuard } from './providers/two-fa/guards/auth-token-two-fa.guard.js'
import { AuthTwoFaVerificationGuard, AuthTwoFaVerificationWithoutPasswordGuard } from './providers/two-fa/guards/auth-two-fa-verification.guard.js'
-import { TwoFaResponseDto, TwoFaVerifyDto, TwoFaVerifyWithPasswordDto } from './providers/two-fa/auth-two-fa.dtos.js'
+import {
+ type TwoFaResponseDto,
+ type TwoFaVerifyDto,
+ twoFaVerifySchema,
+ type TwoFaVerifyWithPasswordDto,
+ twoFaVerifyWithPasswordSchema
+} from './providers/two-fa/auth-two-fa.dtos.js'
import { TwoFaSetup, TwoFaVerifyResult } from './providers/two-fa/auth-two-fa.interfaces.js'
@Controller(AUTH_ROUTE.BASE)
@@ -88,14 +95,20 @@ export class AuthController {
@Header('Cache-Control', 'no-store')
@UseGuards(AuthRateLimitGuard, UserRolesGuard)
@UserHaveRole(USER_ROLE.USER)
- twoFaEnable(@Body() body: TwoFaVerifyWithPasswordDto, @Req() req: FastifyAuthenticatedRequest): Promise<TwoFaVerifyResult> {
+ twoFaEnable(
+ @Body({ schema: twoFaVerifyWithPasswordSchema }) body: TwoFaVerifyWithPasswordDto,
+ @Req() req: FastifyAuthenticatedRequest
+ ): Promise<TwoFaVerifyResult> {
return this.authProvider2FA.enableTwoFactor(body, req)
}
@Post(`${AUTH_ROUTE.TWO_FA_BASE}/${AUTH_ROUTE.TWO_FA_DISABLE}`)
@UseGuards(AuthRateLimitGuard, UserRolesGuard)
@UserHaveRole(USER_ROLE.USER)
- twoFaDisable(@Body() body: TwoFaVerifyWithPasswordDto, @Req() req: FastifyAuthenticatedRequest): Promise<TwoFaVerifyResult> {
+ twoFaDisable(
+ @Body({ schema: twoFaVerifyWithPasswordSchema }) body: TwoFaVerifyWithPasswordDto,
+ @Req() req: FastifyAuthenticatedRequest
+ ): Promise<TwoFaVerifyResult> {
return this.authProvider2FA.disableTwoFactor(body, req)
}
@@ -104,7 +117,7 @@ export class AuthController {
@UseGuards(AuthRateLimitGuard, AuthTokenTwoFaGuard, UserRolesGuard)
@UserHaveRole(USER_ROLE.USER)
async twoFaLogin(
- @Body() body: TwoFaVerifyDto,
+ @Body({ schema: twoFaVerifySchema }) body: TwoFaVerifyDto,
@Req() req: FastifyAuthenticatedRequest,
@Res({ passthrough: true }) res: FastifyReply
): Promise<TwoFaResponseDto | TwoFaVerifyResult> {
@@ -121,7 +134,7 @@ export class AuthController {
@Post(`${AUTH_ROUTE.TWO_FA_BASE}/${AUTH_ROUTE.TWO_FA_ADMIN_RESET_USER}/:id`)
@UseGuards(AuthRateLimitGuard, UserRolesGuard, AuthTwoFaVerificationGuard)
@UserHaveRole(USER_ROLE.ADMINISTRATOR)
- twoFaReset(@Param('id', ParseIntPipe) userId: number): Promise<TwoFaVerifyResult> {
+ twoFaReset(@Param('id', { schema: integerFromStringSchema }) userId: number): Promise<TwoFaVerifyResult> {
return this.authProvider2FA.adminResetUserTwoFa(userId)
}
}
diff --git a/backend/src/authentication/auth.e2e-spec.ts b/backend/src/authentication/auth.e2e-spec.ts
index ec11405f..8d328b30 100644
--- a/backend/src/authentication/auth.e2e-spec.ts
+++ b/backend/src/authentication/auth.e2e-spec.ts
@@ -1,17 +1,17 @@
import { JwtService } from '@nestjs/jwt'
import { NestFastifyApplication } from '@nestjs/platform-fastify'
-import { Type } from 'class-transformer'
-import { IsInt, ValidateNested } from 'class-validator'
+import { z } from 'zod'
import { appBootstrap } from '../app.bootstrap.js'
import { USER_PERMISSION, USER_ROLE } from '../applications/users/constants/user.js'
-import { DeleteUserDto } from '../applications/users/dto/delete-user.dto.js'
+import type { CreateUserDto } from '../applications/users/dto/create-or-update-user.dto.js'
+import type { DeleteUserDto } from '../applications/users/dto/delete-user.dto.js'
import { UserModel } from '../applications/users/models/user.model.js'
import { AdminUsersManager } from '../applications/users/services/admin-users-manager.service.js'
import { UsersManager } from '../applications/users/services/users-manager.service.js'
import { UsersQueries } from '../applications/users/services/users-queries.service.js'
import { generateUserTest } from '../applications/users/utils/test.js'
import { XML_CONTENT_TYPE } from '../applications/webdav/constants/webdav.js'
-import { convertHumanTimeToSeconds, transformAndValidate } from '../common/functions.js'
+import { convertHumanTimeToSeconds } from '../common/functions.js'
import { currentTimeStamp, decodeUrl } from '../common/shared.js'
import { configuration } from '../configuration/config.environment.js'
import { Cache } from '../infrastructure/cache/cache.service.js'
@@ -20,33 +20,22 @@ import { AuthConfig } from './auth.config.js'
import { CSRF_ERROR, TOKEN_PATHS, TOKEN_TYPES } from './constants/auth.js'
import { API_AUTH_LOGIN, API_AUTH_LOGOUT, API_AUTH_REFRESH, API_AUTH_TOKEN, API_AUTH_TOKEN_REFRESH } from './constants/routes.js'
import { AUTH_SCOPE } from './constants/scope.js'
-import { TokenResponseDto } from './dto/token-response.dto.js'
-import { JwtPayload } from './interfaces/jwt-payload.interface.js'
+import { tokenResponseSchema } from './dto/token-response.dto.js'
+import type { JwtPayload } from './interfaces/jwt-payload.interface.js'
import { TOKEN_TYPE } from './interfaces/token.interface.js'
import { genWebDAVAuthCacheKey } from './utils/auth-cache.js'
-class BrowserRefreshUserResponseDto {
- @IsInt()
- id: number
-}
-
-class BrowserRefreshTokenResponseDto {
- @IsInt()
- access_expiration: number
-
- @IsInt()
- refresh_expiration: number
-}
-
-class BrowserRefreshResponseDto {
- @ValidateNested()
- @Type(() => BrowserRefreshUserResponseDto)
- user: BrowserRefreshUserResponseDto
+const browserRefreshResponseSchema = z.object({
+ user: z.object({
+ id: z.number().int()
+ }),
+ token: z.object({
+ access_expiration: z.number().int(),
+ refresh_expiration: z.number().int()
+ })
+})
- @ValidateNested()
- @Type(() => BrowserRefreshTokenResponseDto)
- token: BrowserRefreshTokenResponseDto
-}
+type CookieTokenType = keyof typeof TOKEN_PATHS
describe('Auth (e2e)', () => {
let app: NestFastifyApplication
@@ -108,7 +97,8 @@ describe('Auth (e2e)', () => {
})
it(`POST ${API_AUTH_LOGIN} => 201`, async () => {
- const userId = (await adminUsersManager.createUserOrGuest({ ...userTest, permissions: USER_PERMISSION.WEBDAV }, USER_ROLE.USER)).id
+ const userId = (await adminUsersManager.createUserOrGuest({ ...userTest, permissions: USER_PERMISSION.WEBDAV } as CreateUserDto, USER_ROLE.USER))
+ .id
expect(userId).toBeDefined()
userTest.id = userId
const res = await app.inject({
@@ -120,7 +110,7 @@ describe('Auth (e2e)', () => {
expect(res.statusCode).toEqual(201)
expect(Object.keys(res.json())).toEqual(expect.arrayContaining(['user', 'token']))
expect(res.headers['set-cookie']).toHaveLength(4)
- const cookies: { type: TOKEN_TYPE; content: string[] }[] = getCookies(res.headers['set-cookie'] as string[])
+ const cookies: { type: CookieTokenType; content: string[] }[] = getCookies(res.headers['set-cookie'] as string[])
/* Access cookie
[
'sync-in-access=value,
@@ -219,7 +209,7 @@ describe('Auth (e2e)', () => {
const res = await app.inject({
method: 'POST',
url: API_AUTH_LOGOUT,
- body: null
+ body: null as never
})
expect(res.statusCode).toEqual(201)
expect(res.headers['set-cookie']).toHaveLength(5)
@@ -287,11 +277,11 @@ describe('Auth (e2e)', () => {
cookies: { [authConfig.token.refresh.name]: refreshToken }
})
expect(res.statusCode).toEqual(201)
- const content = transformAndValidate(BrowserRefreshResponseDto, res.json())
+ const content = browserRefreshResponseSchema.parse(res.json())
expect(content.user.id).toBe(userTest.id)
const expectedAccessExpiration = currentTimeStamp() + convertHumanTimeToSeconds(authConfig.token.access.expiration)
expect(content.token.access_expiration).toBeCloseTo(expectedAccessExpiration, -1)
- const cookies: { type: TOKEN_TYPE; content: string[] }[] = getCookies(res.headers['set-cookie'] as string[])
+ const cookies: { type: CookieTokenType; content: string[] }[] = getCookies(res.headers['set-cookie'] as string[])
cookiesChecks(cookies)
})
@@ -334,7 +324,7 @@ describe('Auth (e2e)', () => {
})
expect(res.statusCode).toEqual(201)
const content = res.json()
- expect(() => transformAndValidate(TokenResponseDto, content)).not.toThrow()
+ expect(() => tokenResponseSchema.parse(content)).not.toThrow()
for (const type of TOKEN_TYPES.filter((p) => p === TOKEN_TYPE.ACCESS || p === TOKEN_TYPE.REFRESH)) {
expect(content[type]).toBeDefined()
expect(content[`${type}_expiration`]).toBeCloseTo(currentTimeStamp() + convertHumanTimeToSeconds(authConfig.token[type].expiration), -1)
@@ -357,7 +347,7 @@ describe('Auth (e2e)', () => {
headers: { authorization: `Bearer ${refreshToken}` }
})
expect(res.statusCode).toEqual(201)
- expect(() => transformAndValidate(TokenResponseDto, res.json())).not.toThrow()
+ expect(() => tokenResponseSchema.parse(res.json())).not.toThrow()
})
it('should invalidate cached WebDAV app-password authentication after revocation', async () => {
@@ -389,9 +379,9 @@ describe('Auth (e2e)', () => {
const appPassword = await usersManager.generateAppPassword(userTest, { name: passwordName, app: AUTH_SCOPE.WEBDAV })
const cacheKey = webDAVAuthCacheKey(appPassword.password)
const getUserSecrets = usersQueries.getUserSecrets.bind(usersQueries)
- let secretsRead: () => void
+ let secretsRead!: () => void
const secretsWereRead = new Promise<void>((resolve) => (secretsRead = resolve))
- let resumeValidation: () => void
+ let resumeValidation!: () => void
const revocationCompleted = new Promise<void>((resolve) => (resumeValidation = resolve))
// Keep the stale read suspended until revocation commits, then let validation enter its bcrypt comparison.
const getUserSecretsSpy = vi.spyOn(usersQueries, 'getUserSecrets').mockImplementationOnce(async (userId) => {
@@ -417,8 +407,8 @@ describe('Auth (e2e)', () => {
}
})
- function getCookies(setCookie: string[]): { type: TOKEN_TYPE; content: string[] }[] {
- const cookies: { type: TOKEN_TYPE; content: string[] }[] = []
+ function getCookies(setCookie: string[]): { type: CookieTokenType; content: string[] }[] {
+ const cookies: { type: CookieTokenType; content: string[] }[] = []
for (const c of setCookie) {
const cookieName = c.split('=')[0]
const cookieValues = c.split('; ')
@@ -440,7 +430,7 @@ describe('Auth (e2e)', () => {
return cookies
}
- function cookiesChecks(cookies: { type: TOKEN_TYPE; content: string[] }[], clear = false) {
+ function cookiesChecks(cookies: { type: CookieTokenType; content: string[] }[], clear = false) {
for (const cookie of cookies) {
expect(cookie.content[0].split('=')[0]).toBe(authConfig.token[cookie.type].name)
expect(cookie.content[2].split('=')[1]).toBe(TOKEN_PATHS[cookie.type])
diff --git a/backend/src/authentication/auth.service.ts b/backend/src/authentication/auth.service.ts
index 1315c1b7..08523b58 100755
--- a/backend/src/authentication/auth.service.ts
+++ b/backend/src/authentication/auth.service.ts
@@ -11,8 +11,8 @@ import { configuration, serverConfig } from '../configuration/config.environment
import { CSRF_ERROR, CSRF_KEY, TOKEN_2FA_TYPES, TOKEN_PATHS, TOKEN_TYPES } from './constants/auth.js'
import { API_OIDC_LOGIN } from './constants/routes.js'
import { LoginResponseDto, LoginVerify2FaDto } from './dto/login-response.dto.js'
-import { TokenResponseDto } from './dto/token-response.dto.js'
-import { JwtIdentity2FaPayload, JwtIdentityPayload, JwtPayload } from './interfaces/jwt-payload.interface.js'
+import type { TokenResponseDto } from './dto/token-response.dto.js'
+import type { JwtIdentity2FaPayload, JwtIdentityPayload, JwtPayload } from './interfaces/jwt-payload.interface.js'
import { TOKEN_TYPE } from './interfaces/token.interface.js'
import { AUTH_PROVIDER, AUTH_SESSION } from './providers/auth-providers.constants.js'
import type { AuthOIDCSettings } from './providers/oidc/auth-oidc.interfaces.js'
@@ -25,12 +25,12 @@ export class AuthManager {
async getTokens(user: UserModel, refresh = false): Promise<TokenResponseDto> {
const currentTime = currentTimeStamp()
- if (refresh && user.exp < currentTime) {
+ if (refresh && user.exp! < currentTime) {
this.logger.error({ tag: this.getTokens.name, msg: `token refresh has incorrect expiration : *${user.login}*` })
throw new HttpException('Token has expired', HttpStatus.FORBIDDEN)
}
const accessExpiration = convertHumanTimeToSeconds(configuration.auth.token.access.expiration)
- const refreshExpiration = refresh ? user.exp - currentTime : convertHumanTimeToSeconds(configuration.auth.token.refresh.expiration)
+ const refreshExpiration = refresh ? user.exp! - currentTime : convertHumanTimeToSeconds(configuration.auth.token.refresh.expiration)
return {
[TOKEN_TYPE.ACCESS]: await this.jwtSign(user, TOKEN_TYPE.ACCESS, accessExpiration),
[TOKEN_TYPE.REFRESH]: await this.jwtSign(user, TOKEN_TYPE.REFRESH, refreshExpiration),
@@ -53,14 +53,14 @@ export class AuthManager {
const response = verify2Fa ? new LoginVerify2FaDto(serverConfig) : new LoginResponseDto(user, serverConfig)
const currentTime = currentTimeStamp()
const csrfToken: string = crypto.randomUUID()
- const tokenTypes: TOKEN_TYPE[] = verify2Fa ? TOKEN_2FA_TYPES : TOKEN_TYPES
+ const tokenTypes = verify2Fa ? TOKEN_2FA_TYPES : TOKEN_TYPES
for (const type of tokenTypes) {
const isCSRFToken = type === TOKEN_TYPE.CSRF || type === TOKEN_TYPE.CSRF_2FA
const tokenExpiration = convertHumanTimeToSeconds(configuration.auth.token[type].expiration)
let cookieValue: string
if (isCSRFToken) {
cookieValue = csrfToken
- } else if (verify2Fa) {
+ } else if (type === TOKEN_TYPE.ACCESS_2FA) {
cookieValue = await this.jwtSign2Fa(user, type, tokenExpiration, csrfToken)
} else {
cookieValue = await this.jwtSign(user, type, tokenExpiration, csrfToken)
@@ -109,7 +109,7 @@ export class AuthManager {
}
async clearCookies(res: FastifyReply) {
- for (const [type, path] of Object.entries(TOKEN_PATHS)) {
+ for (const [type, path] of Object.entries(TOKEN_PATHS) as [keyof typeof TOKEN_PATHS, string][]) {
res.clearCookie(configuration.auth.token[type].name, { path: path })
}
}
@@ -148,12 +148,17 @@ export class AuthManager {
}
return {
loginUrl: API_OIDC_LOGIN,
- autoRedirect: configuration.auth.oidc.options.autoRedirect,
+ autoRedirect: configuration.auth.oidc.options.autoRedirect ?? false,
buttonText: configuration.auth.oidc.options.buttonText
}
}
- private jwtSign(user: UserModel, type: TOKEN_TYPE, expiration: number, csrfToken?: string): Promise<string> {
+ private jwtSign(
+ user: UserModel,
+ type: TOKEN_TYPE.ACCESS | TOKEN_TYPE.REFRESH | TOKEN_TYPE.WS,
+ expiration: number,
+ csrfToken?: string
+ ): Promise<string> {
return this.jwt.signAsync(
{
tokenType: type,
@@ -180,7 +185,7 @@ export class AuthManager {
)
}
- private jwtSign2Fa(user: UserModel, type: TOKEN_TYPE, expiration: number, csrfToken: string): Promise<string> {
+ private jwtSign2Fa(user: UserModel, type: TOKEN_TYPE.ACCESS_2FA, expiration: number, csrfToken: string): Promise<string> {
// Restrict the temporary token to the minimum required information
return this.jwt.signAsync(
{
diff --git a/backend/src/authentication/constants/auth.ts b/backend/src/authentication/constants/auth.ts
index 16e65439..737f2616 100644
--- a/backend/src/authentication/constants/auth.ts
+++ b/backend/src/authentication/constants/auth.ts
@@ -37,8 +37,8 @@ export const TOKEN_PATHS = {
[TOKEN_TYPE.CSRF_2FA]: '/'
} as const
-export const TOKEN_TYPES: TOKEN_TYPE[] = [TOKEN_TYPE.REFRESH, TOKEN_TYPE.ACCESS, TOKEN_TYPE.WS, TOKEN_TYPE.CSRF] as const
-export const TOKEN_2FA_TYPES: TOKEN_TYPE[] = [TOKEN_TYPE.ACCESS_2FA, TOKEN_TYPE.CSRF_2FA] as const
+export const TOKEN_TYPES = [TOKEN_TYPE.REFRESH, TOKEN_TYPE.ACCESS, TOKEN_TYPE.WS, TOKEN_TYPE.CSRF] as const
+export const TOKEN_2FA_TYPES = [TOKEN_TYPE.ACCESS_2FA, TOKEN_TYPE.CSRF_2FA] as const
export const CSRF_ERROR = {
MISSING_JWT: 'Missing CSRF in JWT',
diff --git a/backend/src/authentication/dto/login-response.dto.ts b/backend/src/authentication/dto/login-response.dto.ts
index d4621991..3e9e1e88 100644
--- a/backend/src/authentication/dto/login-response.dto.ts
+++ b/backend/src/authentication/dto/login-response.dto.ts
@@ -1,26 +1,24 @@
import { UserModel } from '../../applications/users/models/user.model.js'
import { ServerConfig } from '../../configuration/config.interfaces.js'
-import { TokenResponseDto } from './token-response.dto.js'
+import type { TokenExpirationResponseDto } from './token-response.dto.js'
export class LoginResponseDto {
server: ServerConfig
user: UserModel
- token: TokenResponseDto
+ token: TokenExpirationResponseDto = {}
constructor(user: UserModel, serverConfig: ServerConfig) {
this.server = serverConfig
this.user = user
- this.token = new TokenResponseDto()
}
}
export class LoginVerify2FaDto {
server: ServerConfig
user: { twoFaEnabled: boolean } = { twoFaEnabled: true }
- token: TokenResponseDto
+ token: TokenExpirationResponseDto = {}
constructor(serverConfig: ServerConfig) {
this.server = serverConfig
- this.token = new TokenResponseDto()
}
}
diff --git a/backend/src/authentication/dto/token-response.dto.ts b/backend/src/authentication/dto/token-response.dto.ts
index 4160b3a1..2fa0dd1a 100644
--- a/backend/src/authentication/dto/token-response.dto.ts
+++ b/backend/src/authentication/dto/token-response.dto.ts
@@ -1,19 +1,21 @@
-import { IsInt, IsOptional, IsString } from 'class-validator'
+import { z } from 'zod'
-export class TokenResponseDto {
- @IsString()
- access: string
+export const tokenResponseSchema = z.object({
+ access: z.string(),
+ refresh: z.string(),
+ access_expiration: z.number().int(),
+ refresh_expiration: z.number().int(),
+ access_2fa_expiration: z.number().int().nullish()
+})
- @IsString()
- refresh: string
+export type TokenResponseDto = z.infer<typeof tokenResponseSchema>
- @IsInt()
- access_expiration: number
+export const tokenExpirationResponseSchema = tokenResponseSchema
+ .pick({
+ access_expiration: true,
+ refresh_expiration: true,
+ access_2fa_expiration: true
+ })
+ .partial()
- @IsInt()
- refresh_expiration: number
-
- @IsOptional()
- @IsInt()
- access_2fa_expiration?: number
-}
+export type TokenExpirationResponseDto = z.infer<typeof tokenExpirationResponseSchema>
diff --git a/backend/src/authentication/guards/auth-anonymous.strategy.ts b/backend/src/authentication/guards/auth-anonymous.strategy.ts
index 25ca9ce2..029a5b82 100644
--- a/backend/src/authentication/guards/auth-anonymous.strategy.ts
+++ b/backend/src/authentication/guards/auth-anonymous.strategy.ts
@@ -4,7 +4,7 @@ import { Strategy } from 'passport-strategy'
@Injectable()
export class AuthAnonymousStrategy extends PassportStrategy(Strategy, 'anonymous') {
- validate: undefined
+ declare validate: (...args: unknown[]) => unknown
constructor() {
super()
diff --git a/backend/src/authentication/guards/auth-basic.strategy.ts b/backend/src/authentication/guards/auth-basic.strategy.ts
index e1a76778..cfc4c4bc 100644
--- a/backend/src/authentication/guards/auth-basic.strategy.ts
+++ b/backend/src/authentication/guards/auth-basic.strategy.ts
@@ -1,7 +1,7 @@
+import { toErrorMessage } from '../../common/errors.js'
import { Injectable } from '@nestjs/common'
import { AbstractStrategy, PassportStrategy } from '@nestjs/passport'
import { ThrottlerException } from '@nestjs/throttler'
-import { instanceToPlain, plainToInstance } from 'class-transformer'
import { FastifyRequest } from 'fastify'
import { PinoLogger } from 'nestjs-pino'
import { UserModel } from '../../applications/users/models/user.model.js'
@@ -36,8 +36,7 @@ export class AuthBasicStrategy extends PassportStrategy(HttpBasicStrategy, 'basi
const userFromCache: null | undefined | Partial<UserModel> = await this.cache.get(basicAuthCacheKey)
if (userFromCache) {
// Only successful credentials are usable from cache; ignore any stale negative entry.
- // Warning: plainToInstance do not use constructor to instantiate the class
- return plainToInstance(UserModel, userFromCache)
+ return UserModel.fromSerialized(userFromCache)
}
// Every WebDAV request is authenticated: only rate limit credentials that still require an actual provider lookup.
@@ -47,7 +46,7 @@ export class AuthBasicStrategy extends PassportStrategy(HttpBasicStrategy, 'basi
throw new ThrottlerException(AUTH_RATE_LIMIT_ERROR_MESSAGE)
}
- let userFromDB: UserModel
+ let userFromDB: UserModel | null
try {
userFromDB = await this.authProvider.validateUser(loginOrEmail, password, req.ip, AUTH_SCOPE.WEBDAV)
} catch (e) {
@@ -59,10 +58,10 @@ export class AuthBasicStrategy extends PassportStrategy(HttpBasicStrategy, 'basi
if (userFromDB === null) return null
userFromDB.removePassword()
- const userToCache: Record<string, any> = instanceToPlain(userFromDB, { excludePrefixes: ['_'] })
+ const userToCache: Record<string, any> = userFromDB.serialize()
this.cache
.set(basicAuthCacheKey, userToCache, AuthBasicStrategy.cacheAuthWebDAVTTL)
- .catch((e: Error) => this.logger.error({ tag: this.validate.name, msg: `${e}` }))
+ .catch((e: Error) => this.logger.error({ tag: this.validate.name, msg: toErrorMessage(e) }))
return userFromDB
}
}
diff --git a/backend/src/authentication/guards/auth-local.strategy.ts b/backend/src/authentication/guards/auth-local.strategy.ts
index 11173920..66399747 100755
--- a/backend/src/authentication/guards/auth-local.strategy.ts
+++ b/backend/src/authentication/guards/auth-local.strategy.ts
@@ -18,7 +18,7 @@ export class AuthLocalStrategy extends PassportStrategy(Strategy, 'local') imple
async validate(req: FastifyRequest, loginOrEmail: string, password: string): Promise<UserModel> {
loginOrEmail = loginOrEmail.trim()
this.logger.assign({ user: loginOrEmail })
- const user: UserModel = await this.authProvider.validateUser(loginOrEmail, password, req.ip)
+ const user = await this.authProvider.validateUser(loginOrEmail, password, req.ip)
if (user) {
user.removePassword()
return user
diff --git a/backend/src/authentication/guards/auth-token-access.guard.spec.ts b/backend/src/authentication/guards/auth-token-access.guard.spec.ts
index ba8fb6fa..966596f2 100644
--- a/backend/src/authentication/guards/auth-token-access.guard.spec.ts
+++ b/backend/src/authentication/guards/auth-token-access.guard.spec.ts
@@ -15,7 +15,7 @@ import { AuthManager } from '../auth.service.js'
import { CSRF_ERROR } from '../constants/auth.js'
import { AuthTokenOptional } from '../decorators/auth-token-optional.decorator.js'
import { AUTH_TOKEN_SKIP, AuthTokenSkip } from '../decorators/auth-token-skip.decorator.js'
-import { JwtIdentityPayload, JwtPayload } from '../interfaces/jwt-payload.interface.js'
+import type { JwtIdentityPayload, JwtPayload } from '../interfaces/jwt-payload.interface.js'
import { TOKEN_TYPE } from '../interfaces/token.interface.js'
import { AuthAnonymousGuard } from './auth-anonymous.guard.js'
import { AuthAnonymousStrategy } from './auth-anonymous.strategy.js'
diff --git a/backend/src/authentication/guards/auth-token-access.strategy.ts b/backend/src/authentication/guards/auth-token-access.strategy.ts
index 07272262..5367d5b2 100755
--- a/backend/src/authentication/guards/auth-token-access.strategy.ts
+++ b/backend/src/authentication/guards/auth-token-access.strategy.ts
@@ -6,7 +6,7 @@ import { ExtractJwt, Strategy } from 'passport-jwt'
import { UserModel } from '../../applications/users/models/user.model.js'
import { configuration } from '../../configuration/config.environment.js'
import { AuthManager } from '../auth.service.js'
-import { JwtPayload } from '../interfaces/jwt-payload.interface.js'
+import type { JwtPayload } from '../interfaces/jwt-payload.interface.js'
import { TOKEN_TYPE } from '../interfaces/token.interface.js'
@Injectable()
@@ -37,7 +37,7 @@ export class AuthTokenAccessStrategy extends PassportStrategy(Strategy, 'tokenAc
static extractJWTFromCookie(req: FastifyRequest): string | null {
if (typeof req.cookies === 'object' && req.cookies[AuthTokenAccessStrategy.accessCookieName] !== undefined) {
- return req.cookies[AuthTokenAccessStrategy.accessCookieName]
+ return req.cookies[AuthTokenAccessStrategy.accessCookieName] as string
}
return null
}
diff --git a/backend/src/authentication/guards/auth-token-refresh.guard.spec.ts b/backend/src/authentication/guards/auth-token-refresh.guard.spec.ts
index 054af65a..8b26cc32 100644
--- a/backend/src/authentication/guards/auth-token-refresh.guard.spec.ts
+++ b/backend/src/authentication/guards/auth-token-refresh.guard.spec.ts
@@ -12,7 +12,7 @@ import { configuration } from '../../configuration/config.environment.js'
import { AuthConfig } from '../auth.config.js'
import { AuthManager } from '../auth.service.js'
import { CSRF_ERROR } from '../constants/auth.js'
-import { JwtPayload } from '../interfaces/jwt-payload.interface.js'
+import type { JwtPayload } from '../interfaces/jwt-payload.interface.js'
import { TOKEN_TYPE } from '../interfaces/token.interface.js'
import { AuthTokenRefreshGuard } from './auth-token-refresh.guard.js'
import { AuthTokenRefreshStrategy } from './auth-token-refresh.strategy.js'
diff --git a/backend/src/authentication/guards/auth-token-refresh.strategy.ts b/backend/src/authentication/guards/auth-token-refresh.strategy.ts
index be0e1930..07b72bfa 100755
--- a/backend/src/authentication/guards/auth-token-refresh.strategy.ts
+++ b/backend/src/authentication/guards/auth-token-refresh.strategy.ts
@@ -7,7 +7,7 @@ import { UserModel } from '../../applications/users/models/user.model.js'
import { UsersManager } from '../../applications/users/services/users-manager.service.js'
import { configuration } from '../../configuration/config.environment.js'
import { AuthManager } from '../auth.service.js'
-import { JwtPayload } from '../interfaces/jwt-payload.interface.js'
+import type { JwtPayload } from '../interfaces/jwt-payload.interface.js'
import { TOKEN_TYPE } from '../interfaces/token.interface.js'
@Injectable()
@@ -43,7 +43,7 @@ export class AuthTokenRefreshStrategy extends PassportStrategy(Strategy, 'tokenR
private static extractJWTFromCookie(req: FastifyRequest): string | null {
if (typeof req.cookies === 'object' && req.cookies[AuthTokenRefreshStrategy.refreshCookieName] !== undefined) {
- return req.cookies[AuthTokenRefreshStrategy.refreshCookieName]
+ return req.cookies[AuthTokenRefreshStrategy.refreshCookieName] as string
}
return null
}
diff --git a/backend/src/authentication/interfaces/jwt-payload.interface.ts b/backend/src/authentication/interfaces/jwt-payload.interface.ts
index d1aea054..81ec1492 100644
--- a/backend/src/authentication/interfaces/jwt-payload.interface.ts
+++ b/backend/src/authentication/interfaces/jwt-payload.interface.ts
@@ -1,12 +1,12 @@
import type { AUTH_SESSION } from '../providers/auth-providers.constants.js'
import { TOKEN_TYPE } from './token.interface.js'
-export class JwtIdentityPayload {
+export interface JwtIdentityPayload {
id: number
login: string
email: string
fullName: string
- language: string
+ language: string | null
role: number
applications: string[]
impersonatedFromId?: number
@@ -16,10 +16,10 @@ export class JwtIdentityPayload {
twoFaEnabled?: boolean
}
-export class JwtIdentity2FaPayload {
+export interface JwtIdentity2FaPayload {
id: number
login: string
- language: string
+ language: string | null
role: number
twoFaEnabled: true
}
diff --git a/backend/src/authentication/providers/auth-providers.models.ts b/backend/src/authentication/providers/auth-providers.models.ts
index 82a9ef7f..35e1451d 100644
--- a/backend/src/authentication/providers/auth-providers.models.ts
+++ b/backend/src/authentication/providers/auth-providers.models.ts
@@ -2,5 +2,5 @@ import type { UserModel } from '../../applications/users/models/user.model.js'
import type { AUTH_SCOPE } from '../constants/scope.js'
export abstract class AuthProvider {
- abstract validateUser(loginOrEmail: string, password: string, ip?: string, scope?: AUTH_SCOPE): Promise<UserModel>
+ abstract validateUser(loginOrEmail: string, password: string, ip?: string, scope?: AUTH_SCOPE): Promise<UserModel | null>
}
diff --git a/backend/src/authentication/providers/ldap/auth-ldap.config.ts b/backend/src/authentication/providers/ldap/auth-ldap.config.ts
index a9abf2cf..e12d19ec 100644
--- a/backend/src/authentication/providers/ldap/auth-ldap.config.ts
+++ b/backend/src/authentication/providers/ldap/auth-ldap.config.ts
@@ -1,103 +1,79 @@
-import { Transform, Type } from 'class-transformer'
-import {
- ArrayNotEmpty,
- IsArray,
- IsBoolean,
- IsDefined,
- IsEnum,
- IsNotEmpty,
- IsNotEmptyObject,
- IsObject,
- IsOptional,
- IsString,
- ValidateNested
-} from 'class-validator'
+import { z } from 'zod'
import { USER_PERMISSION } from '../../../applications/users/constants/user.js'
+import { hydrateConfigDefaults, nonEmptyStringSchema } from '../../../configuration/config.schema.js'
import { LDAP_COMMON_ATTR, LDAP_LOGIN_ATTR } from './auth-ldap.constants.js'
import { DEFAULT_STORAGE_QUOTA_FIELD } from '../auth-providers.constants.js'
-export class AuthProviderLDAPAttributesConfig {
- @IsOptional()
- @Transform(({ value }) => value || LDAP_LOGIN_ATTR.UID)
- @IsEnum(LDAP_LOGIN_ATTR)
- login: LDAP_LOGIN_ATTR = LDAP_LOGIN_ATTR.UID
-
- @IsOptional()
- @IsString()
- @Transform(({ value }) => value || LDAP_COMMON_ATTR.MAIL)
- email: string = LDAP_COMMON_ATTR.MAIL
-
- @IsOptional()
- @IsString()
- @Transform(({ value }) => value || DEFAULT_STORAGE_QUOTA_FIELD)
- storageQuota: string = DEFAULT_STORAGE_QUOTA_FIELD
+type AuthProviderLDAPAttributesConfig = z.output<typeof AuthProviderLDAPAttributesConfigSchema>
+type AuthProviderLDAPOptionsConfig = z.output<typeof AuthProviderLDAPOptionsConfigSchema>
+export type AuthProviderLDAPConfig = z.output<typeof AuthProviderLDAPConfigSchema>
+
+export function hydrateAuthProviderLDAPConfig(value: unknown): AuthProviderLDAPConfig | unknown {
+ if (value === null || typeof value !== 'object' || Array.isArray(value)) {
+ return value
+ }
+
+ const input = value as Record<string, unknown>
+ return {
+ ...input,
+ ...(Array.isArray(input.servers) ? { servers: input.servers.filter(Boolean) } : {}),
+ attributes: hydrateLDAPAttributes(input.attributes),
+ options: hydrateLDAPOptions(input.options)
+ }
}
-export class AuthProviderLDAPOptionsConfig {
- @IsOptional()
- @IsString()
- adminGroup?: string
-
- @IsOptional()
- @IsBoolean()
- autoCreateUser? = true
-
- @IsOptional()
- @IsArray()
- @IsEnum(USER_PERMISSION, { each: true })
- autoCreatePermissions?: USER_PERMISSION[] = []
-
- @IsOptional()
- @IsBoolean()
- enablePasswordAuthFallback? = false
+const defaultWhenFalsy =
+ <T>(defaultValue: T) =>
+ (value: unknown): unknown =>
+ value || defaultValue
+
+export const AuthProviderLDAPAttributesConfigSchema = z.looseObject({
+ login: z.preprocess(defaultWhenFalsy(LDAP_LOGIN_ATTR.UID), z.enum(LDAP_LOGIN_ATTR)).default(LDAP_LOGIN_ATTR.UID),
+ email: z.preprocess(defaultWhenFalsy(LDAP_COMMON_ATTR.MAIL), z.string()).default(LDAP_COMMON_ATTR.MAIL),
+ storageQuota: z.preprocess(defaultWhenFalsy(DEFAULT_STORAGE_QUOTA_FIELD), z.string()).default(DEFAULT_STORAGE_QUOTA_FIELD)
+})
+
+export const AuthProviderLDAPOptionsConfigSchema = z.looseObject({
+ adminGroup: z.string().nullish(),
+ autoCreateUser: z.boolean().nullish().default(true),
+ autoCreatePermissions: z
+ .array(z.enum(USER_PERMISSION))
+ .nullish()
+ .default(() => []),
+ enablePasswordAuthFallback: z.boolean().nullish().default(false)
+})
+
+export const AuthProviderLDAPConfigSchema = z.looseObject({
+ servers: z.preprocess((value) => (Array.isArray(value) ? value.filter(Boolean) : value), z.array(z.string()).min(1)),
+ tlsOptions: z.record(z.string(), z.unknown()).nullish(),
+ baseDN: nonEmptyStringSchema,
+ filter: z.string().nullish(),
+ attributes: AuthProviderLDAPAttributesConfigSchema.prefault({}),
+ upnSuffix: z.string().nullish(),
+ netbiosName: z.string().nullish(),
+ serviceBindDN: z.string().nullish(),
+ serviceBindPassword: z.string().nullish(),
+ options: AuthProviderLDAPOptionsConfigSchema.prefault({})
+})
+
+function hydrateLDAPAttributes(value: unknown): AuthProviderLDAPAttributesConfig | unknown {
+ if (value === undefined) {
+ return AuthProviderLDAPAttributesConfigSchema.parse({})
+ }
+ if (value === null || typeof value !== 'object' || Array.isArray(value)) {
+ return value
+ }
+
+ const attributes = hydrateConfigDefaults(AuthProviderLDAPAttributesConfigSchema.parse({}), value) as AuthProviderLDAPAttributesConfig
+ attributes.login ||= LDAP_LOGIN_ATTR.UID
+ attributes.email ||= LDAP_COMMON_ATTR.MAIL
+ attributes.storageQuota ||= DEFAULT_STORAGE_QUOTA_FIELD
+ return attributes
}
-export class AuthProviderLDAPConfig {
- @Transform(({ value }) => (Array.isArray(value) ? value.filter((v: string) => Boolean(v)) : value))
- @ArrayNotEmpty()
- @IsArray()
- @IsString({ each: true })
- servers: string[]
-
- @IsOptional()
- @IsObject()
- tlsOptions?: Record<string, any> & { ca: string | string[] | Buffer }
-
- @IsString()
- @IsNotEmpty()
- baseDN: string
-
- @IsOptional()
- @IsString()
- filter?: string
-
- @IsDefined()
- @IsNotEmptyObject()
- @IsObject()
- @ValidateNested()
- @Type(() => AuthProviderLDAPAttributesConfig)
- attributes: AuthProviderLDAPAttributesConfig = new AuthProviderLDAPAttributesConfig()
-
- @IsOptional()
- @IsString()
- upnSuffix?: string
-
- @IsOptional()
- @IsString()
- netbiosName?: string
-
- @IsOptional()
- @IsString()
- serviceBindDN?: string
-
- @IsOptional()
- @IsString()
- serviceBindPassword?: string
-
- @IsDefined()
- @IsNotEmptyObject()
- @IsObject()
- @ValidateNested()
- @Type(() => AuthProviderLDAPOptionsConfig)
- options: AuthProviderLDAPOptionsConfig = new AuthProviderLDAPOptionsConfig()
+function hydrateLDAPOptions(value: unknown): AuthProviderLDAPOptionsConfig | unknown {
+ if (value === undefined) {
+ return AuthProviderLDAPOptionsConfigSchema.parse({})
+ }
+ return hydrateConfigDefaults(AuthProviderLDAPOptionsConfigSchema.parse({}), value)
}
diff --git a/backend/src/authentication/providers/ldap/auth-provider-ldap.service.ts b/backend/src/authentication/providers/ldap/auth-provider-ldap.service.ts
index ec2715c0..5f2e9ac7 100644
--- a/backend/src/authentication/providers/ldap/auth-provider-ldap.service.ts
+++ b/backend/src/authentication/providers/ldap/auth-provider-ldap.service.ts
@@ -20,6 +20,7 @@ import type { CreateUserDto, UpdateUserDto } from '../../../applications/users/d
import { UserModel } from '../../../applications/users/models/user.model.js'
import { AdminUsersManager } from '../../../applications/users/services/admin-users-manager.service.js'
import { UsersManager } from '../../../applications/users/services/users-manager.service.js'
+import { toErrorMessage } from '../../../common/errors.js'
import { comparePassword, splitFullName } from '../../../common/functions.js'
import { configuration } from '../../../configuration/config.environment.js'
import type { AUTH_SCOPE } from '../../constants/scope.js'
@@ -45,7 +46,7 @@ export class AuthProviderLDAP implements AuthProvider {
private readonly adminUsersManager: AdminUsersManager
) {}
- async validateUser(loginOrEmail: string, password: string, ip?: string, scope?: AUTH_SCOPE): Promise<UserModel> {
+ async validateUser(loginOrEmail: string, password: string, ip?: string, scope?: AUTH_SCOPE): Promise<UserModel | null> {
if (password.length === 0) {
return null
}
@@ -53,18 +54,18 @@ export class AuthProviderLDAP implements AuthProvider {
// Authenticate user via LDAP and sync local user state.
// Find user from his login or email
const localLogin = this.dbLogin(loginOrEmail)
- let user: UserModel = await this.usersManager.findUser(localLogin, false)
+ let user = await this.usersManager.findUser(localLogin, false)
if (user && (user.isGuest || scope)) {
// Allow local password authentication for guest users and application scopes (app passwords)
return this.usersManager.validateLocalPasswordForUser(user, localLogin, password, ip, scope)
}
- let ldapErrorMessage: string
+ let ldapErrorMessage: string | undefined
let entry: false | LdapUserEntry = false
try {
// If a user was found, use the stored login. This allows logging in with an email.
entry = await this.checkAuth(user?.login || loginOrEmail, password)
} catch (e) {
- ldapErrorMessage = e.message
+ ldapErrorMessage = toErrorMessage(e)
}
// LDAP auth failed or exception raised
@@ -74,7 +75,7 @@ export class AuthProviderLDAP implements AuthProvider {
// - admin users (break-glass access)
// - regular users when password authentication fallback is enabled
const canUseLocalFallback = (candidate: UserModel): boolean =>
- candidate.isAdmin || (Boolean(ldapErrorMessage) && this.ldapConfig.options.enablePasswordAuthFallback)
+ Boolean(candidate.isAdmin || (Boolean(ldapErrorMessage) && this.ldapConfig.options.enablePasswordAuthFallback))
// Always pass through the local validator so missing or rejected fallback users take the dummy bcrypt path.
const localUser = await this.usersManager.validateLocalPasswordForUser(user, localLogin, password, ip, undefined, canUseLocalFallback)
if (user && canUseLocalFallback(user)) {
@@ -111,7 +112,9 @@ export class AuthProviderLDAP implements AuthProvider {
const identity = this.createIdentity(entry, password)
user = await this.updateOrCreateUser(identity, user)
- this.usersManager.updateAccesses(user, ip, true).catch((e: Error) => this.logger.error({ tag: this.validateUser.name, msg: `${e}` }))
+ this.usersManager
+ .updateAccesses(user, ip as string | null, true)
+ .catch((e: Error) => this.logger.error({ tag: this.validateUser.name, msg: toErrorMessage(e) }))
return user
}
@@ -130,8 +133,8 @@ export class AuthProviderLDAP implements AuthProvider {
let attemptedBindDN = bindUserDN
try {
if (this.hasServiceBind) {
- attemptedBindDN = this.ldapConfig.serviceBindDN
- await client.bind(this.ldapConfig.serviceBindDN, this.ldapConfig.serviceBindPassword)
+ attemptedBindDN = this.ldapConfig.serviceBindDN!
+ await client.bind(this.ldapConfig.serviceBindDN!, this.ldapConfig.serviceBindPassword!)
const result = await this.findUserEntry(ldapLogin, client)
if (!result) {
return false
@@ -158,7 +161,7 @@ export class AuthProviderLDAP implements AuthProvider {
}
}
if (error) {
- this.logger.error({ tag: this.checkAuth.name, msg: `${error}` })
+ this.logger.error({ tag: this.checkAuth.name, msg: toErrorMessage(error) })
if (CONNECT_ERROR_CODE.has(error.code)) {
throw new Error('Authentication service error')
}
@@ -184,7 +187,7 @@ export class AuthProviderLDAP implements AuthProvider {
}
}
- private async readTlsCa(ca: LdapCa): Promise<LdapCa> {
+ private async readTlsCa(ca: unknown): Promise<LdapCa> {
if (Buffer.isBuffer(ca)) {
return ca
}
@@ -203,7 +206,7 @@ export class AuthProviderLDAP implements AuthProvider {
try {
return await readFile(ca, 'utf8')
} catch (e) {
- this.logger.error({ tag: this.readTlsCa.name, msg: `unable to read ca path: ${e}` })
+ this.logger.error({ tag: this.readTlsCa.name, msg: `unable to read ca path: ${toErrorMessage(e)}` })
return ca
}
}
@@ -226,7 +229,7 @@ export class AuthProviderLDAP implements AuthProvider {
this.logger.warn({
tag: this.checkAccessByDN.name,
- msg: `exact LDAP entry read unavailable for bind DN, using verified subtree fallback : ${bindUserDN} : ${e}`
+ msg: `exact LDAP entry read unavailable for bind DN, using verified subtree fallback : ${bindUserDN} : ${toErrorMessage(e)}`
})
const candidate = await this.findDirectBindFallbackCandidate(ldapLogin, client)
if (!candidate) {
@@ -251,7 +254,7 @@ export class AuthProviderLDAP implements AuthProvider {
}
private async findUserEntryByDN(bindUserDN: string, client: Client): Promise<{ entry: LdapUserEntry; userDn?: string } | false> {
- const searchFilter = this.buildBaseUserFilter(this.ldapConfig.filter)
+ const searchFilter = this.buildBaseUserFilter(this.ldapConfig.filter ?? undefined)
try {
const { searchEntries } = await client.search(bindUserDN, {
scope: LDAP_SEARCH_ATTR.BASE,
@@ -269,13 +272,13 @@ export class AuthProviderLDAP implements AuthProvider {
return await this.buildUserEntryResult(searchEntries[0], client, bindUserDN)
} catch (e) {
this.logger.debug({ tag: this.findUserEntryByDN.name, msg: `search filter : ${searchFilter}` })
- this.logger.error({ tag: this.findUserEntryByDN.name, msg: `${bindUserDN} : ${e}` })
+ this.logger.error({ tag: this.findUserEntryByDN.name, msg: `${bindUserDN} : ${toErrorMessage(e)}` })
throw e
}
}
private async findDirectBindFallbackCandidate(ldapLogin: string, client: Client): Promise<LdapUserCandidate | false> {
- const searchFilter = this.buildConfiguredLoginFilter(ldapLogin, this.ldapConfig.filter)
+ const searchFilter = this.buildConfiguredLoginFilter(ldapLogin, this.ldapConfig.filter ?? undefined)
try {
const { searchEntries } = await client.search(this.ldapConfig.baseDN, {
scope: LDAP_SEARCH_ATTR.SUB,
@@ -302,13 +305,13 @@ export class AuthProviderLDAP implements AuthProvider {
return { rawEntry, userDn }
} catch (e) {
this.logger.debug({ tag: this.findDirectBindFallbackCandidate.name, msg: `search filter : ${searchFilter}` })
- this.logger.error({ tag: this.findDirectBindFallbackCandidate.name, msg: `${ldapLogin} : ${e}` })
+ this.logger.error({ tag: this.findDirectBindFallbackCandidate.name, msg: `${ldapLogin} : ${toErrorMessage(e)}` })
throw e
}
}
private async findUserEntry(login: string, client: Client, bindUserDN?: string): Promise<{ entry: LdapUserEntry; userDn?: string } | false> {
- const searchFilter = this.buildUserFilter(login, this.ldapConfig.filter)
+ const searchFilter = this.buildUserFilter(login, this.ldapConfig.filter ?? undefined)
try {
const { searchEntries } = await client.search(this.ldapConfig.baseDN, {
scope: LDAP_SEARCH_ATTR.SUB,
@@ -330,7 +333,7 @@ export class AuthProviderLDAP implements AuthProvider {
return await this.buildUserEntryResult(searchEntries[0], client, bindUserDN)
} catch (e) {
this.logger.debug({ tag: this.findUserEntry.name, msg: `search filter : ${searchFilter}` })
- this.logger.error({ tag: this.findUserEntry.name, msg: `${login} : ${e}` })
+ this.logger.error({ tag: this.findUserEntry.name, msg: `${login} : ${toErrorMessage(e)}` })
return false
}
}
@@ -341,7 +344,7 @@ export class AuthProviderLDAP implements AuthProvider {
if (this.ldapConfig.options.adminGroup && !this.hasAdminGroup(entry, this.ldapConfig.options.adminGroup)) {
if (userDn && (await this.isMemberOfGroupOfNames(this.ldapConfig.options.adminGroup, userDn, client))) {
- const existing = Array.isArray(entry[LDAP_COMMON_ATTR.MEMBER_OF]) ? entry[LDAP_COMMON_ATTR.MEMBER_OF] : []
+ const existing = Array.isArray(entry[LDAP_COMMON_ATTR.MEMBER_OF]) ? (entry[LDAP_COMMON_ATTR.MEMBER_OF] as string[]) : []
entry[LDAP_COMMON_ATTR.MEMBER_OF] = [...new Set([...existing, this.ldapConfig.options.adminGroup])]
}
}
@@ -349,12 +352,12 @@ export class AuthProviderLDAP implements AuthProvider {
return { entry, userDn }
}
- private async updateOrCreateUser(identity: CreateUserDto, user: UserModel): Promise<UserModel> {
+ private async updateOrCreateUser(identity: CreateUserDto, user: UserModel | null): Promise<UserModel> {
// Create or update the local user record from LDAP identity.
if (user === null) {
// Create
- identity.permissions = this.ldapConfig.options.autoCreatePermissions.join(',')
- const createdUser = await this.adminUsersManager.createUserOrGuest(identity, identity.role)
+ identity.permissions = this.ldapConfig.options.autoCreatePermissions!.join(',')
+ const createdUser = await this.adminUsersManager.createUserOrGuest(identity, identity.role!)
const freshUser = await this.usersManager.fromUserId(createdUser.id)
if (!freshUser) {
this.logger.error({ tag: this.updateOrCreateUser.name, msg: `user was not found : ${createdUser.login} (${createdUser.id})` })
@@ -372,16 +375,16 @@ export class AuthProviderLDAP implements AuthProvider {
const identityHasChanged: UpdateUserDto = Object.fromEntries(
(
await Promise.all(
- Object.keys(identity).map(async (key: string) => {
+ (Object.keys(identity) as (keyof CreateUserDto)[]).map(async (key) => {
if (key === 'password') {
- const isSame = await comparePassword(identity[key], user.password)
+ const isSame = await comparePassword(identity[key]!, user.password)
return isSame ? null : [key, identity[key]]
}
- return identity[key] !== user[key] ? [key, identity[key]] : null
+ return identity[key] !== user[key as keyof UserModel] ? [key, identity[key]] : null
})
)
- ).filter(Boolean)
- )
+ ).filter(Boolean) as Iterable<readonly [PropertyKey, any]>
+ ) as UpdateUserDto
if (Object.keys(identityHasChanged).length > 0) {
try {
@@ -407,7 +410,7 @@ export class AuthProviderLDAP implements AuthProvider {
user.setFullName(true)
}
} catch (e) {
- this.logger.warn({ tag: this.updateOrCreateUser.name, msg: `unable to update user *${user.login}* : ${e}` })
+ this.logger.warn({ tag: this.updateOrCreateUser.name, msg: `unable to update user *${user.login}* : ${toErrorMessage(e)}` })
}
}
return user
@@ -433,7 +436,7 @@ export class AuthProviderLDAP implements AuthProvider {
}
if (Array.isArray(entry[attr])) {
// Keep only the first value for all other attributes (e.g., email)
- entry[attr] = entry[attr].length > 0 ? entry[attr][0] : null
+ entry[attr] = entry[attr].length > 0 ? entry[attr][0] : (null as any)
}
}
return entry as LdapUserEntry
@@ -477,7 +480,7 @@ export class AuthProviderLDAP implements AuthProvider {
private dbLogin(login: string): string {
// Normalize domain-qualified logins to the user part.
if (login.includes('\\')) {
- return login.split('\\').slice(-1)[0]
+ return login.split('\\').slice(-1)[0]!
}
return login
}
@@ -550,7 +553,7 @@ export class AuthProviderLDAP implements AuthProvider {
private hasAdminGroup(entry: LdapUserEntry, adminGroup: string): boolean {
// Check for the admin group in the normalized `memberOf` list.
- return Array.isArray(entry[LDAP_COMMON_ATTR.MEMBER_OF]) && entry[LDAP_COMMON_ATTR.MEMBER_OF].includes(adminGroup)
+ return Array.isArray(entry[LDAP_COMMON_ATTR.MEMBER_OF]) && (entry[LDAP_COMMON_ATTR.MEMBER_OF] as string[]).includes(adminGroup)
}
private async isMemberOfGroupOfNames(adminGroup: string, userDn: string, client: Client): Promise<boolean> {
@@ -578,7 +581,7 @@ export class AuthProviderLDAP implements AuthProvider {
// Any matching entry implies membership.
return searchEntries.length > 0
} catch (e) {
- this.logger.warn({ tag: this.isMemberOfGroupOfNames.name, msg: `${e}` })
+ this.logger.warn({ tag: this.isMemberOfGroupOfNames.name, msg: toErrorMessage(e) })
return false
}
}
@@ -601,11 +604,11 @@ export class AuthProviderLDAP implements AuthProvider {
// Prefer the most specific LDAP error when multiple errors are returned.
if (error?.errors?.length) {
for (const err of error.errors) {
- this.logger.warn({ tag: this.handleBindError.name, msg: `${attemptedBindDN} : ${err}` })
+ this.logger.warn({ tag: this.handleBindError.name, msg: `${attemptedBindDN} : ${toErrorMessage(err)}` })
}
return error.errors[error.errors.length - 1]
}
- this.logger.warn({ tag: this.handleBindError.name, msg: `${attemptedBindDN} : ${error}` })
+ this.logger.warn({ tag: this.handleBindError.name, msg: `${attemptedBindDN} : ${toErrorMessage(error)}` })
return error
}
}
diff --git a/backend/src/authentication/providers/mysql/auth-provider-mysql.service.spec.ts b/backend/src/authentication/providers/mysql/auth-provider-mysql.service.spec.ts
index f77c9bb7..110d786f 100644
--- a/backend/src/authentication/providers/mysql/auth-provider-mysql.service.spec.ts
+++ b/backend/src/authentication/providers/mysql/auth-provider-mysql.service.spec.ts
@@ -52,8 +52,8 @@ describe(AuthProviderMySQL.name, () => {
it('should validate the user', async () => {
userTest.makePaths = vi.fn()
- usersManager.findUser = vi.fn().mockReturnValue({ ...userTest, password: await hashPassword(userTest.password) })
- expect(await authProviderMySQL.validateUser(userTest.login, userTest.password)).toBeDefined()
+ usersManager.findUser = vi.fn().mockReturnValue({ ...userTest, password: await hashPassword(userTest.password!) })
+ expect(await authProviderMySQL.validateUser(userTest.login, userTest.password!)).toBeDefined()
expect(userTest.makePaths).toHaveBeenCalled()
})
@@ -68,9 +68,9 @@ describe(AuthProviderMySQL.name, () => {
cause: { code: Array.from(CONNECT_ERROR_CODE)[0] }
})
)
- expect(await authProviderMySQL.validateUser(userTest.login, userTest.password)).toBeNull()
- expect(await authProviderMySQL.validateUser(userTest.login, userTest.password)).toBeNull()
- await expect(authProviderMySQL.validateUser(userTest.login, userTest.password)).rejects.toThrow(/db error/i)
- await expect(authProviderMySQL.validateUser(userTest.login, userTest.password)).rejects.toThrow(/authentication service/i)
+ expect(await authProviderMySQL.validateUser(userTest.login, userTest.password!)).toBeNull()
+ expect(await authProviderMySQL.validateUser(userTest.login, userTest.password!)).toBeNull()
+ await expect(authProviderMySQL.validateUser(userTest.login, userTest.password!)).rejects.toThrow(/db error/i)
+ await expect(authProviderMySQL.validateUser(userTest.login, userTest.password!)).rejects.toThrow(/authentication service/i)
})
})
diff --git a/backend/src/authentication/providers/mysql/auth-provider-mysql.service.ts b/backend/src/authentication/providers/mysql/auth-provider-mysql.service.ts
index 00751c81..d377268f 100644
--- a/backend/src/authentication/providers/mysql/auth-provider-mysql.service.ts
+++ b/backend/src/authentication/providers/mysql/auth-provider-mysql.service.ts
@@ -2,6 +2,7 @@ import { HttpException, HttpStatus, Injectable, Logger } from '@nestjs/common'
import { CONNECT_ERROR_CODE } from '../../../app.constants.js'
import { UserModel } from '../../../applications/users/models/user.model.js'
import { UsersManager } from '../../../applications/users/services/users-manager.service.js'
+import { toErrorMessage } from '../../../common/errors.js'
import { AUTH_SCOPE } from '../../constants/scope.js'
import { AuthProvider } from '../auth-providers.models.js'
@@ -11,16 +12,20 @@ export class AuthProviderMySQL implements AuthProvider {
constructor(private readonly usersManager: UsersManager) {}
- async validateUser(loginOrEmail: string, password: string, ip?: string, scope?: AUTH_SCOPE): Promise<UserModel> {
+ async validateUser(loginOrEmail: string, password: string, ip?: string, scope?: AUTH_SCOPE): Promise<UserModel | null> {
try {
return await this.usersManager.validateLocalPasswordByLogin(loginOrEmail, password, ip, scope)
} catch (e) {
if (e instanceof HttpException) {
throw e
}
- this.logger.error({ tag: this.validateUser.name, msg: `${e}` })
+ this.logger.error({ tag: this.validateUser.name, msg: toErrorMessage(e) })
+ const causeCode =
+ e instanceof Error && e.cause !== null && typeof e.cause === 'object' && 'code' in e.cause && typeof e.cause.code === 'string'
+ ? e.cause.code
+ : undefined
throw new HttpException(
- CONNECT_ERROR_CODE.has(e.cause?.code) ? 'Authentication service error' : e.cause?.code || e.message,
+ causeCode && CONNECT_ERROR_CODE.has(causeCode) ? 'Authentication service error' : causeCode || toErrorMessage(e),
HttpStatus.INTERNAL_SERVER_ERROR
)
}
diff --git a/backend/src/authentication/providers/oidc/auth-oidc.config.ts b/backend/src/authentication/providers/oidc/auth-oidc.config.ts
index 3f8d0571..dde73f7b 100644
--- a/backend/src/authentication/providers/oidc/auth-oidc.config.ts
+++ b/backend/src/authentication/providers/oidc/auth-oidc.config.ts
@@ -1,123 +1,93 @@
-import { Transform, Type } from 'class-transformer'
-import {
- IsArray,
- IsBoolean,
- IsDefined,
- IsEnum,
- IsNotEmpty,
- IsNotEmptyObject,
- IsObject,
- IsOptional,
- IsString,
- Matches,
- ValidateNested
-} from 'class-validator'
+import { z } from 'zod'
import { USER_PERMISSION } from '../../../applications/users/constants/user.js'
+import { hydrateConfigDefaults, nonEmptyStringSchema } from '../../../configuration/config.schema.js'
import { OAuthTokenEndpoint } from './auth-oidc.constants.js'
import { DEFAULT_STORAGE_QUOTA_FIELD } from '../auth-providers.constants.js'
-export class AuthProviderOIDCSecurityConfig {
- @IsString()
- @Matches(/\bopenid\b/, { message: 'OIDC scope must include "openid"' })
- scope = 'openid email profile'
-
- @IsOptional()
- @IsBoolean()
- supportPKCE? = true
-
- @IsOptional()
- @IsBoolean()
- allowInsecureRequests? = false
-
- @Transform(({ value }) => value || OAuthTokenEndpoint.ClientSecretBasic)
- @IsEnum(OAuthTokenEndpoint)
- tokenEndpointAuthMethod: OAuthTokenEndpoint = OAuthTokenEndpoint.ClientSecretBasic
-
- @IsString()
- @IsNotEmpty()
- tokenSigningAlg = 'RS256'
-
- @IsOptional()
- @IsString()
- userInfoSigningAlg? = undefined
-
- @IsOptional()
- @IsBoolean()
- skipSubjectCheck? = false
-
- @IsOptional()
- @IsBoolean()
- requireVerifiedEmail? = true
-
- @IsOptional()
- @IsBoolean()
- allowPrivateIpAvatarDownload? = false
+type AuthProviderOIDCSecurityConfig = z.output<typeof AuthProviderOIDCSecurityConfigSchema>
+type AuthProviderOIDCOptionsConfig = z.output<typeof AuthProviderOIDCOptionsConfigSchema>
+export type AuthProviderOIDCConfig = z.output<typeof AuthProviderOIDCConfigSchema>
+
+export function hydrateAuthProviderOIDCConfig(value: unknown): AuthProviderOIDCConfig | unknown {
+ if (value === null || typeof value !== 'object' || Array.isArray(value)) {
+ return value
+ }
+
+ const input = value as Record<string, unknown>
+ return {
+ ...input,
+ options: hydrateOIDCOptions(input.options),
+ security: hydrateOIDCSecurity(input.security)
+ }
}
-export class AuthProviderOIDCOptionsConfig {
- @IsOptional()
- @IsBoolean()
- autoCreateUser? = true
-
- @IsOptional()
- @IsArray()
- @IsEnum(USER_PERMISSION, { each: true })
- autoCreatePermissions?: USER_PERMISSION[] = []
-
- @IsOptional()
- @IsBoolean()
- autoRedirect? = false
-
- @IsOptional()
- @IsBoolean()
- enablePasswordAuth? = false
-
- @IsOptional()
- @IsBoolean()
- autoSyncAvatar? = false
-
- @IsOptional()
- @IsString()
- adminRoleOrGroup?: string
-
- @IsOptional()
- @IsString()
- @Transform(({ value }) => value || DEFAULT_STORAGE_QUOTA_FIELD)
- storageQuotaClaim?: string = DEFAULT_STORAGE_QUOTA_FIELD
-
- @IsString()
- @IsNotEmpty()
- buttonText: string = 'Continue with OpenID Connect'
+const defaultWhenFalsy =
+ <T>(defaultValue: T) =>
+ (value: unknown): unknown =>
+ value || defaultValue
+
+export const AuthProviderOIDCSecurityConfigSchema = z.looseObject({
+ scope: z
+ .string()
+ .regex(/\bopenid\b/, 'OIDC scope must include "openid"')
+ .default('openid email profile'),
+ supportPKCE: z.boolean().nullish().default(true),
+ allowInsecureRequests: z.boolean().nullish().default(false),
+ tokenEndpointAuthMethod: z
+ .preprocess(defaultWhenFalsy(OAuthTokenEndpoint.ClientSecretBasic), z.enum(OAuthTokenEndpoint))
+ .default(OAuthTokenEndpoint.ClientSecretBasic),
+ tokenSigningAlg: nonEmptyStringSchema.default('RS256'),
+ userInfoSigningAlg: z.string().nullish(),
+ skipSubjectCheck: z.boolean().nullish().default(false),
+ requireVerifiedEmail: z.boolean().nullish().default(true),
+ allowPrivateIpAvatarDownload: z.boolean().nullish().default(false)
+})
+
+export const AuthProviderOIDCOptionsConfigSchema = z.looseObject({
+ autoCreateUser: z.boolean().nullish().default(true),
+ autoCreatePermissions: z
+ .array(z.enum(USER_PERMISSION))
+ .nullish()
+ .default(() => []),
+ autoRedirect: z.boolean().nullish().default(false),
+ enablePasswordAuth: z.boolean().nullish().default(false),
+ autoSyncAvatar: z.boolean().nullish().default(false),
+ adminRoleOrGroup: z.string().nullish(),
+ storageQuotaClaim: z.preprocess(defaultWhenFalsy(DEFAULT_STORAGE_QUOTA_FIELD), z.string()).default(DEFAULT_STORAGE_QUOTA_FIELD),
+ buttonText: nonEmptyStringSchema.default('Continue with OpenID Connect')
+})
+
+export const AuthProviderOIDCConfigSchema = z.looseObject({
+ issuerUrl: nonEmptyStringSchema,
+ clientId: nonEmptyStringSchema,
+ clientSecret: nonEmptyStringSchema,
+ redirectUri: nonEmptyStringSchema,
+ options: AuthProviderOIDCOptionsConfigSchema.prefault({}),
+ security: AuthProviderOIDCSecurityConfigSchema.prefault({})
+})
+
+function hydrateOIDCOptions(value: unknown): AuthProviderOIDCOptionsConfig | unknown {
+ if (value === undefined) {
+ return AuthProviderOIDCOptionsConfigSchema.parse({})
+ }
+ if (value === null || typeof value !== 'object' || Array.isArray(value)) {
+ return value
+ }
+
+ const options = hydrateConfigDefaults(AuthProviderOIDCOptionsConfigSchema.parse({}), value) as AuthProviderOIDCOptionsConfig
+ options.storageQuotaClaim ||= DEFAULT_STORAGE_QUOTA_FIELD
+ return options
}
-export class AuthProviderOIDCConfig {
- @IsString()
- @IsNotEmpty()
- issuerUrl: string
-
- @IsString()
- @IsNotEmpty()
- clientId: string
-
- @IsString()
- @IsNotEmpty()
- clientSecret: string
-
- @IsString()
- @IsNotEmpty()
- redirectUri: string
-
- @IsDefined()
- @IsNotEmptyObject()
- @IsObject()
- @ValidateNested()
- @Type(() => AuthProviderOIDCOptionsConfig)
- options: AuthProviderOIDCOptionsConfig = new AuthProviderOIDCOptionsConfig()
-
- @IsDefined()
- @IsNotEmptyObject()
- @IsObject()
- @ValidateNested()
- @Type(() => AuthProviderOIDCSecurityConfig)
- security: AuthProviderOIDCSecurityConfig = new AuthProviderOIDCSecurityConfig()
+function hydrateOIDCSecurity(value: unknown): AuthProviderOIDCSecurityConfig | unknown {
+ if (value === undefined) {
+ return AuthProviderOIDCSecurityConfigSchema.parse({})
+ }
+ if (value === null || typeof value !== 'object' || Array.isArray(value)) {
+ return value
+ }
+
+ const security = hydrateConfigDefaults(AuthProviderOIDCSecurityConfigSchema.parse({}), value) as AuthProviderOIDCSecurityConfig
+ security.tokenEndpointAuthMethod ||= OAuthTokenEndpoint.ClientSecretBasic
+ return security
}
diff --git a/backend/src/authentication/providers/oidc/auth-oidc.controller.ts b/backend/src/authentication/providers/oidc/auth-oidc.controller.ts
index d109ae51..29411c7b 100644
--- a/backend/src/authentication/providers/oidc/auth-oidc.controller.ts
+++ b/backend/src/authentication/providers/oidc/auth-oidc.controller.ts
@@ -7,6 +7,7 @@ import { AuthTokenSkip } from '../../decorators/auth-token-skip.decorator.js'
import type { LoginResponseDto } from '../../dto/login-response.dto.js'
import { AUTH_SESSION } from '../auth-providers.constants.js'
import { OAuthDesktopPortParam } from './auth-oidc-desktop.constants.js'
+import { oauthDesktopPortSchema, oidcCallbackQuerySchema } from './auth-oidc.schema.js'
import { AuthProviderOIDC } from './auth-provider-oidc.service.js'
@Controller(AUTH_ROUTE.BASE)
@@ -18,7 +19,10 @@ export class AuthOIDCController {
@Get(AUTH_ROUTE.OIDC_LOGIN)
@AuthTokenSkip()
- async oidcLogin(@Query(OAuthDesktopPortParam) desktopPort: number, @Res() res: FastifyReply): Promise<void> {
+ async oidcLogin(
+ @Query(OAuthDesktopPortParam, { schema: oauthDesktopPortSchema }) desktopPort: number | undefined,
+ @Res() res: FastifyReply
+ ): Promise<void> {
const url = await this.authProviderOIDC.getAuthorizationUrl(res, desktopPort)
// Redirect to OIDC provider
return res.redirect(url, HttpStatus.FOUND)
@@ -26,9 +30,13 @@ export class AuthOIDCController {
@Get(AUTH_ROUTE.OIDC_CALLBACK)
@AuthTokenSkip()
- async oidcCallback(@Query() query: Record<string, string>, @Req() req: FastifyRequest, @Res() res: FastifyReply): Promise<void> {
+ async oidcCallback(
+ @Query({ schema: oidcCallbackQuerySchema }) query: Record<string, string>,
+ @Req() req: FastifyRequest,
+ @Res() res: FastifyReply
+ ): Promise<void> {
const user: UserModel = await this.authProviderOIDC.handleCallback(req, res, query)
const r: LoginResponseDto = await this.authManager.setCookies(user, res, false, AUTH_SESSION.OIDC)
- return res.redirect(this.authProviderOIDC.getRedirectCallbackUrl(r.token.access_expiration, r.token.refresh_expiration), HttpStatus.FOUND)
+ return res.redirect(this.authProviderOIDC.getRedirectCallbackUrl(r.token.access_expiration!, r.token.refresh_expiration!), HttpStatus.FOUND)
}
}
diff --git a/backend/src/authentication/providers/oidc/auth-oidc.schema.ts b/backend/src/authentication/providers/oidc/auth-oidc.schema.ts
new file mode 100644
index 00000000..be1a36f1
--- /dev/null
+++ b/backend/src/authentication/providers/oidc/auth-oidc.schema.ts
@@ -0,0 +1,5 @@
+import { z } from 'zod'
+import { safeIntegerFromStringSchema } from '../../../configuration/config.schema.js'
+
+export const oauthDesktopPortSchema = safeIntegerFromStringSchema.optional()
+export const oidcCallbackQuerySchema = z.record(z.string(), z.string())
diff --git a/backend/src/authentication/providers/oidc/auth-provider-oidc.service.spec.ts b/backend/src/authentication/providers/oidc/auth-provider-oidc.service.spec.ts
index 385b06b5..2dfdefc6 100644
--- a/backend/src/authentication/providers/oidc/auth-provider-oidc.service.spec.ts
+++ b/backend/src/authentication/providers/oidc/auth-provider-oidc.service.spec.ts
@@ -22,6 +22,7 @@ import { DownloadFile } from '../../../applications/files/utils/download-file.js
import * as imageUtils from '../../../common/image.js'
import { AUTH_SCOPE } from '../../constants/scope.js'
import { DEFAULT_STORAGE_QUOTA_FIELD } from '../auth-providers.constants.js'
+import { OAuthDesktopCallBackURI, OAuthDesktopLoopbackPorts } from './auth-oidc-desktop.constants.js'
import { OAuthCookie } from './auth-oidc.constants.js'
import { AuthProviderOIDC } from './auth-provider-oidc.service.js'
import { Mock } from 'vitest'
@@ -167,6 +168,22 @@ describe(AuthProviderOIDC.name, () => {
;(service as any).oidcConfig.options.autoSyncAvatar = false
})
+ describe('getRedirectURI', () => {
+ it('uses the configured web callback when the desktop port is absent', () => {
+ expect(service.getRedirectURI()).toBe('https://api.example.test/auth/oidc/callback')
+ })
+
+ it('accepts only an allowlisted desktop port', () => {
+ const desktopPort = OAuthDesktopLoopbackPorts.values().next().value as number
+
+ expect(service.getRedirectURI(desktopPort)).toBe(`http://127.0.0.1:${desktopPort}${OAuthDesktopCallBackURI}`)
+ expect(() => service.getRedirectURI(0)).toThrow('Invalid desktop_port')
+ expect(() => service.getRedirectURI('0')).toThrow('Invalid desktop_port')
+ expect(() => service.getRedirectURI('')).toThrow('Invalid desktop_port')
+ expect(() => service.getRedirectURI(65535)).toThrow('Invalid desktop_port')
+ })
+ })
+
it('returns null when user is not found', async () => {
usersManager.validateLocalPasswordByLogin.mockResolvedValue(null)
diff --git a/backend/src/authentication/providers/oidc/auth-provider-oidc.service.ts b/backend/src/authentication/providers/oidc/auth-provider-oidc.service.ts
index de6ff46d..54fa2e0c 100644
--- a/backend/src/authentication/providers/oidc/auth-provider-oidc.service.ts
+++ b/backend/src/authentication/providers/oidc/auth-provider-oidc.service.ts
@@ -13,7 +13,6 @@ import {
Configuration,
discovery,
fetchUserInfo,
- IDToken,
None,
randomNonce,
randomPKCECodeVerifier,
@@ -32,7 +31,8 @@ import {
USER_AVATAR_FILE_NAME,
USER_AVATAR_MAX_UPLOAD_SIZE
} from '../../../applications/users/utils/avatar.js'
-import { generateShortUUID, splitFullName, transformAndValidate } from '../../../common/functions.js'
+import { toErrorMessage } from '../../../common/errors.js'
+import { generateShortUUID, splitFullName } from '../../../common/functions.js'
import { configuration } from '../../../configuration/config.environment.js'
import { AUTH_ROUTE } from '../../constants/routes.js'
import type { AUTH_SCOPE } from '../../constants/scope.js'
@@ -44,7 +44,7 @@ import { OAuthDesktopCallBackURI, OAuthDesktopLoopbackPorts, OAuthDesktopPortPar
import type { AuthProviderOIDCConfig } from './auth-oidc.config.js'
import { OAuthCookie, OAuthCookieSettings, OAuthTokenEndpoint, OIDC_LOGIN_HASH_LENGTH, OIDC_LOGIN_MAX_LENGTH } from './auth-oidc.constants.js'
import { HttpService } from '@nestjs/axios'
-import { DownloadFileDto } from '../../../applications/files/dto/file-operations.dto.js'
+import { type DownloadFileDto, downloadFileSchema } from '../../../applications/files/dto/file-operations.dto.js'
import { DownloadFile } from '../../../applications/files/utils/download-file.js'
import { convertTempImageToPng, imgMimeTypePrefix } from '../../../common/image.js'
import { fileSize, temporaryFilePath } from '../../../applications/files/utils/files.js'
@@ -53,8 +53,8 @@ import { fileSize, temporaryFilePath } from '../../../applications/files/utils/f
export class AuthProviderOIDC implements AuthProvider {
private readonly logger = new Logger(AuthProviderOIDC.name)
private readonly oidcConfig: AuthProviderOIDCConfig = configuration.auth.oidc
- private frontendBaseUrl: string
- private config: Configuration = null
+ private frontendBaseUrl!: string
+ private config: Configuration | null = null
constructor(
private readonly http: HttpService,
@@ -62,14 +62,14 @@ export class AuthProviderOIDC implements AuthProvider {
private readonly adminUsersManager: AdminUsersManager
) {}
- async validateUser(login: string, password: string, ip?: string, scope?: AUTH_SCOPE): Promise<UserModel> {
+ async validateUser(login: string, password: string, ip?: string, scope?: AUTH_SCOPE): Promise<UserModel | null> {
// Non-OIDC fallback: allow local password authentication only for:
// - guest users
// - administrators (break-glass access)
// - scoped application access (app passwords)
// - regular users when password authentication is enabled
const canUseLocalPassword = (user: UserModel): boolean =>
- user.isGuest || user.isAdmin || Boolean(scope) || this.oidcConfig.options.enablePasswordAuth
+ Boolean(user.isGuest || user.isAdmin || Boolean(scope) || this.oidcConfig.options.enablePasswordAuth)
return this.usersManager.validateLocalPasswordByLogin(login, password, ip, scope, canUseLocalPassword)
}
@@ -117,7 +117,7 @@ export class AuthProviderOIDC implements AuthProvider {
res.setCookie(OAuthCookie.State, state, OAuthCookieSettings)
res.setCookie(OAuthCookie.Nonce, nonce, OAuthCookieSettings)
if (isPKCEEnabled) {
- res.setCookie(OAuthCookie.CodeVerifier, codeVerifier, OAuthCookieSettings)
+ res.setCookie(OAuthCookie.CodeVerifier, codeVerifier!, OAuthCookieSettings)
}
return authUrl.toString()
}
@@ -159,7 +159,7 @@ export class AuthProviderOIDC implements AuthProvider {
})
// Get validated ID token claims
- const claims: IDToken = tokens.claims()
+ const claims = tokens.claims()
if (!claims) {
throw new HttpException('No ID token claims found', HttpStatus.BAD_REQUEST)
}
@@ -181,7 +181,7 @@ export class AuthProviderOIDC implements AuthProvider {
} catch (error: AuthorizationResponseError | HttpException | any) {
if (error instanceof AuthorizationResponseError) {
this.logger.error({ tag: this.handleCallback.name, msg: `OIDC callback error: ${error.code} - ${error.error_description}` })
- throw new HttpException(error.error_description, HttpStatus.BAD_REQUEST)
+ throw new HttpException(error.error_description as string, HttpStatus.BAD_REQUEST)
} else {
const errorMessage = await this.getOIDCErrorMessage(error)
this.logger.error({ tag: this.handleCallback.name, msg: `OIDC callback error: ${errorMessage}` })
@@ -214,14 +214,14 @@ export class AuthProviderOIDC implements AuthProvider {
return url.toString()
}
- getRedirectURI(desktopPort?: number | string): string {
+ getRedirectURI(desktopPort?: number | string | null): string {
// web / default callback
- if (!desktopPort) return this.oidcConfig.redirectUri
+ if (desktopPort === undefined || desktopPort === null) return this.oidcConfig.redirectUri
// desktop app callback
if (typeof desktopPort === 'string') {
desktopPort = Number(desktopPort)
}
- if (!Number.isInteger(desktopPort) || !OAuthDesktopLoopbackPorts.has(desktopPort)) {
+ if (!Number.isInteger(desktopPort) || !OAuthDesktopLoopbackPorts.has(desktopPort as number)) {
throw new HttpException('Invalid desktop_port', HttpStatus.BAD_REQUEST)
}
// The redirect url must be known from provider
@@ -238,7 +238,7 @@ export class AuthProviderOIDC implements AuthProvider {
client_secret: this.oidcConfig.clientSecret,
response_types: ['code'],
id_token_signed_response_alg: this.oidcConfig.security.tokenSigningAlg,
- userinfo_signed_response_alg: this.oidcConfig.security.userInfoSigningAlg
+ userinfo_signed_response_alg: this.oidcConfig.security.userInfoSigningAlg ?? undefined
},
this.getTokenAuthMethod(this.oidcConfig.security.tokenEndpointAuthMethod, this.oidcConfig.clientSecret),
{
@@ -277,17 +277,17 @@ export class AuthProviderOIDC implements AuthProvider {
}
}
- private async getOIDCErrorMessage(error: any): Promise<string> {
- const cause = error?.cause
+ private async getOIDCErrorMessage(error: unknown): Promise<string> {
+ const cause = error !== null && typeof error === 'object' && 'cause' in error ? error.cause : undefined
if (cause instanceof Response) {
try {
return await cause.clone().text()
} catch {
- return `${cause}`
+ return toErrorMessage(cause)
}
}
- return `${cause || error}`
+ return toErrorMessage(cause ?? error)
}
private getTokenAuthMethod(tokenEndpointAuthMethod: OAuthTokenEndpoint, clientSecret?: string) {
@@ -319,7 +319,7 @@ export class AuthProviderOIDC implements AuthProvider {
const { login, email } = this.extractLoginAndEmail(userInfo)
// Resolve an already linked external identity first, then fall back to email for existing OIDC users.
- let user: UserModel = await this.usersManager.findUserByExternalIdOrEmail(externalId, email, false)
+ let user = await this.usersManager.findUserByExternalIdOrEmail(externalId, email, false)
if (user?.externalId && user.externalId !== externalId) {
this.logger.warn({ tag: this.processUserInfo.name, msg: `OIDC email is already linked to another external identity` })
@@ -357,7 +357,9 @@ export class AuthProviderOIDC implements AuthProvider {
await this.updatePictureUrl(user, userInfo)
}
// Update user access log
- this.usersManager.updateAccesses(user, ip, true).catch((e: Error) => this.logger.error({ tag: this.processUserInfo.name, msg: `${e}` }))
+ this.usersManager
+ .updateAccesses(user, ip as string | null, true)
+ .catch((e: Error) => this.logger.error({ tag: this.processUserInfo.name, msg: toErrorMessage(e) }))
return user
}
@@ -397,7 +399,7 @@ export class AuthProviderOIDC implements AuthProvider {
firstName,
lastName
}
- applyStorageQuotaToIdentity(identity, userInfo as Record<string, unknown>, this.oidcConfig.options.storageQuotaClaim)
+ applyStorageQuotaToIdentity(identity, userInfo as Record<string, unknown>, this.oidcConfig.options.storageQuotaClaim!)
return identity
}
@@ -412,11 +414,11 @@ export class AuthProviderOIDC implements AuthProvider {
// Check if user information has changed. The local login is initialized once and remains stable.
const identityHasChanged: UpdateUserDto = Object.fromEntries(
- Object.keys(identity)
+ (Object.keys(identity) as (keyof typeof identity)[])
.filter((key) => key !== 'password' && key !== 'login')
- .map((key: string) => (identity[key] !== user[key] ? [key, identity[key]] : null))
- .filter(Boolean)
- )
+ .map((key) => (identity[key] !== user[key as keyof UserModel] ? [key, identity[key]] : null))
+ .filter(Boolean) as Iterable<readonly [PropertyKey, any]>
+ ) as UpdateUserDto
if (Object.keys(identityHasChanged).length > 0) {
try {
@@ -438,7 +440,7 @@ export class AuthProviderOIDC implements AuthProvider {
user.setFullName(true)
}
} catch (e) {
- this.logger.warn({ tag: this.updateOrCreateUser.name, msg: `unable to update user *${user.login}* : ${e}` })
+ this.logger.warn({ tag: this.updateOrCreateUser.name, msg: `unable to update user *${user.login}* : ${toErrorMessage(e)}` })
}
}
@@ -458,9 +460,9 @@ export class AuthProviderOIDC implements AuthProvider {
login,
externalId,
password: generateShortUUID(24),
- permissions: this.oidcConfig.options.autoCreatePermissions.join(',')
+ permissions: this.oidcConfig.options.autoCreatePermissions!.join(',')
} as CreateUserDto & { externalId: string }
- const createdUser = await this.adminUsersManager.createUserOrGuest(userWithPassword, identity.role)
+ const createdUser = await this.adminUsersManager.createUserOrGuest(userWithPassword, identity.role!)
const freshUser = await this.usersManager.fromUserId(createdUser.id)
if (!freshUser) {
this.logger.error({ tag: this.createUser.name, msg: `user was not found : ${createdUser.login} (${createdUser.id})` })
@@ -480,9 +482,9 @@ export class AuthProviderOIDC implements AuthProvider {
// validate URL
let downloadDto: DownloadFileDto
try {
- downloadDto = transformAndValidate(DownloadFileDto, { url: pictureUrl })
+ downloadDto = downloadFileSchema.parse({ url: pictureUrl })
} catch (e) {
- this.logger.warn({ tag: this.updatePictureUrl.name, msg: `unable to validate picture URL *${pictureUrl}* : ${e}` })
+ this.logger.warn({ tag: this.updatePictureUrl.name, msg: `unable to validate picture URL *${pictureUrl}* : ${toErrorMessage(e)}` })
return
}
@@ -490,7 +492,7 @@ export class AuthProviderOIDC implements AuthProvider {
let pictureContentLength: number | undefined
let pictureLastModified: string | undefined
const downloader = new DownloadFile(this.http)
- const allowPrivateIP = this.oidcConfig.security.allowPrivateIpAvatarDownload
+ const allowPrivateIP = this.oidcConfig.security.allowPrivateIpAvatarDownload ?? undefined
const userAvatarTmpPath = temporaryFilePath(user.tmpPath, USER_AVATAR_FILE_NAME, 'avatar')
try {
// retrieve headers
@@ -520,14 +522,14 @@ export class AuthProviderOIDC implements AuthProvider {
return
}
} catch (e) {
- this.logger.warn({ tag: this.updatePictureUrl.name, msg: `checks failed: ${e}` })
+ this.logger.warn({ tag: this.updatePictureUrl.name, msg: `checks failed: ${toErrorMessage(e)}` })
}
// download avatar
try {
await downloader.download(downloadDto, userAvatarTmpPath, { allowPrivateIP, maxSize: USER_AVATAR_MAX_UPLOAD_SIZE })
} catch (e) {
- this.logger.warn({ tag: this.updatePictureUrl.name, msg: `download failed: ${e}` })
+ this.logger.warn({ tag: this.updatePictureUrl.name, msg: `download failed: ${toErrorMessage(e)}` })
return
}
@@ -546,7 +548,7 @@ export class AuthProviderOIDC implements AuthProvider {
const avatarMetadataSize = pictureContentLength !== undefined && pictureContentLength > 0 ? pictureContentLength : avatarSize
void saveAvatarMetadata(user.login, pictureUrl, avatarMetadataSize, pictureLastModified)
} catch (e) {
- this.logger.warn({ tag: this.updatePictureUrl.name, msg: `convert failed: ${e}` })
+ this.logger.warn({ tag: this.updatePictureUrl.name, msg: `convert failed: ${toErrorMessage(e)}` })
} finally {
fs.unlink(userAvatarTmpPath).catch(() => undefined)
}
diff --git a/backend/src/authentication/providers/two-fa/auth-provider-two-fa.service.spec.ts b/backend/src/authentication/providers/two-fa/auth-provider-two-fa.service.spec.ts
index 8c880bb8..94aa10c8 100644
--- a/backend/src/authentication/providers/two-fa/auth-provider-two-fa.service.spec.ts
+++ b/backend/src/authentication/providers/two-fa/auth-provider-two-fa.service.spec.ts
@@ -8,7 +8,7 @@ import { Cache } from '../../../infrastructure/cache/cache.service.js'
import { FastifyAuthenticatedRequest } from '../../interfaces/auth-request.interface.js'
import { decryptSecret, encryptSecret } from '../../utils/crypt-secret.js'
import { AuthProvider2FA } from './auth-provider-two-fa.service.js'
-import { TwoFaVerifyDto, TwoFaVerifyWithPasswordDto } from './auth-two-fa.dtos.js'
+import type { TwoFaVerifyDto, TwoFaVerifyWithPasswordDto } from './auth-two-fa.dtos.js'
import { Mocked } from 'vitest'
vi.mock('../../utils/crypt-secret.js')
@@ -263,7 +263,7 @@ describe(AuthProvider2FA.name, () => {
it('should fail when recovery codes are empty', async () => {
const recoveryDto: TwoFaVerifyDto = { code: 'code-1', isRecoveryCode: true }
const userWithoutCodes = { ...mockUser, secrets: { ...mockUser.secrets, recoveryCodes: [] } }
- usersManager.fromUserId.mockResolvedValue(userWithoutCodes as UserModel)
+ usersManager.fromUserId.mockResolvedValue(userWithoutCodes as unknown as UserModel)
const result = await service.verify(recoveryDto, mockRequest as FastifyAuthenticatedRequest)
diff --git a/backend/src/authentication/providers/two-fa/auth-provider-two-fa.service.ts b/backend/src/authentication/providers/two-fa/auth-provider-two-fa.service.ts
index a3c4288a..9e5abcdc 100644
--- a/backend/src/authentication/providers/two-fa/auth-provider-two-fa.service.ts
+++ b/backend/src/authentication/providers/two-fa/auth-provider-two-fa.service.ts
@@ -6,6 +6,7 @@ import { NotificationsManager } from '../../../applications/notifications/servic
import { UserModel } from '../../../applications/users/models/user.model.js'
import { UsersManager } from '../../../applications/users/services/users-manager.service.js'
import { ACTION } from '../../../common/constants.js'
+import { toErrorMessage } from '../../../common/errors.js'
import { generateShortUUID } from '../../../common/functions.js'
import { qrcodeToDataURL } from '../../../common/qrcode.js'
import { configuration } from '../../../configuration/config.environment.js'
@@ -13,7 +14,7 @@ import { Cache } from '../../../infrastructure/cache/cache.service.js'
import { TWO_FA_CODE_LENGTH } from '../../constants/auth.js'
import { FastifyAuthenticatedRequest } from '../../interfaces/auth-request.interface.js'
import { decryptSecret, encryptSecret } from '../../utils/crypt-secret.js'
-import { TwoFaVerifyDto, TwoFaVerifyWithPasswordDto } from './auth-two-fa.dtos.js'
+import type { TwoFaVerifyDto, TwoFaVerifyWithPasswordDto } from './auth-two-fa.dtos.js'
import { TwoFaEnableResult, TwoFaSetup, TwoFaVerifyResult } from './auth-two-fa.interfaces.js'
@Injectable()
@@ -99,14 +100,14 @@ export class AuthProvider2FA {
auth.success = true
} catch (e) {
auth.success = false
- auth.message = e.message
- this.logger.error({ tag: this.adminResetUserTwoFa.name, msg: `${e}` })
+ auth.message = toErrorMessage(e)
+ this.logger.error({ tag: this.adminResetUserTwoFa.name, msg: toErrorMessage(e) })
}
return auth
}
async loadUser(userId: number, ip: string) {
- const user: UserModel = await this.usersManager.fromUserId(userId)
+ const user = await this.usersManager.fromUserId(userId)
if (!user) {
this.logger.warn({ tag: this.loadUser.name, msg: `User ${userId} (${ip}) not found` })
throw new HttpException(`User not found`, HttpStatus.NOT_FOUND)
@@ -125,13 +126,13 @@ export class AuthProvider2FA {
}
private async validateVerificationCode(verifyDto: TwoFaVerifyDto, user: UserModel, secret?: string): Promise<TwoFaVerifyResult> {
- secret = secret || user.secrets.twoFaSecret
+ secret = secret || user.secrets!.twoFaSecret
return verifyDto.isRecoveryCode
- ? await this.validateRecoveryCode(user.id, verifyDto.code, user.secrets.recoveryCodes)
+ ? await this.validateRecoveryCode(user.id, verifyDto.code, user.secrets!.recoveryCodes)
: this.validateTwoFactorCode(verifyDto.code, secret)
}
- validateTwoFactorCode(code: string, encryptedSecret: string): TwoFaVerifyResult {
+ validateTwoFactorCode(code: string, encryptedSecret?: string): TwoFaVerifyResult {
const auth: TwoFaVerifyResult = { success: false, message: '' }
if (!encryptedSecret) {
auth.message = 'Incorrect code or password'
@@ -141,20 +142,20 @@ export class AuthProvider2FA {
auth.success = Totp.validate({ passcode: code, secret: this.decryptSecret(encryptedSecret), drift: 1 })
if (!auth.success) auth.message = 'Incorrect code or password'
} catch (e) {
- this.logger.error({ tag: this.validateTwoFactorCode.name, msg: `${e}` })
- auth.message = e.message
+ this.logger.error({ tag: this.validateTwoFactorCode.name, msg: toErrorMessage(e) })
+ auth.message = toErrorMessage(e)
}
return auth
}
- async validateRecoveryCode(userId: number, code: string, encryptedCodes: string[]): Promise<TwoFaVerifyResult> {
+ async validateRecoveryCode(userId: number, code: string, encryptedCodes?: string[]): Promise<TwoFaVerifyResult> {
const auth: TwoFaVerifyResult = { success: false, message: '' }
if (!encryptedCodes || encryptedCodes.length === 0) {
auth.message = 'Invalid code'
return auth
}
try {
- let matchedEncryptedCode: string
+ let matchedEncryptedCode: string | undefined
for (const encCode of encryptedCodes) {
const decryptedCode = this.decryptSecret(encCode)
if (code === decryptedCode) {
@@ -169,8 +170,8 @@ export class AuthProvider2FA {
auth.message = 'Invalid code'
}
} catch (e) {
- this.logger.error({ tag: this.validateRecoveryCode.name, msg: `${e}` })
- auth.message = e.message || 'Invalid code'
+ this.logger.error({ tag: this.validateRecoveryCode.name, msg: toErrorMessage(e) })
+ auth.message = toErrorMessage(e, 'Invalid code')
}
return auth
}
@@ -205,15 +206,15 @@ export class AuthProvider2FA {
return Array.from({ length: count }, () => generateShortUUID())
}
- private sendEmailNotification(req: FastifyAuthenticatedRequest, action: ACTION) {
+ private sendEmailNotification(req: FastifyAuthenticatedRequest, action: ACTION.ADD | ACTION.DELETE) {
const notification: NotificationContent = {
app: NOTIFICATION_APP.AUTH_2FA,
event: NOTIFICATION_APP_EVENT.AUTH_2FA[action],
- element: req.headers['user-agent'],
+ element: req.headers['user-agent'] as string,
url: req.ip
}
this.notificationsManager
.sendEmailNotification([req.user], notification)
- .catch((e: Error) => this.logger.error({ tag: this.sendEmailNotification.name, msg: `${e}` }))
+ .catch((e: Error) => this.logger.error({ tag: this.sendEmailNotification.name, msg: toErrorMessage(e) }))
}
}
diff --git a/backend/src/authentication/providers/two-fa/auth-two-fa.config.ts b/backend/src/authentication/providers/two-fa/auth-two-fa.config.ts
index ef45b199..0743a7d9 100644
--- a/backend/src/authentication/providers/two-fa/auth-two-fa.config.ts
+++ b/backend/src/authentication/providers/two-fa/auth-two-fa.config.ts
@@ -1,20 +1,9 @@
-import { Type } from 'class-transformer'
-import { IsBoolean, IsDefined, IsNotEmptyObject, IsObject, IsString, ValidateNested } from 'class-validator'
+import { z } from 'zod'
import { SERVER_NAME } from '../../../common/shared.js'
-export class AuthMFATotpConfig {
- @IsBoolean()
- enabled = true
+export const AuthMFATotpConfigSchema = z.looseObject({
+ enabled: z.boolean().default(true),
+ issuer: z.string().default(SERVER_NAME)
+})
- @IsString()
- issuer = SERVER_NAME
-}
-
-export class AuthMFAConfig {
- @IsDefined()
- @IsNotEmptyObject()
- @IsObject()
- @ValidateNested()
- @Type(() => AuthMFATotpConfig)
- totp: AuthMFATotpConfig = new AuthMFATotpConfig()
-}
+export const AuthMFAConfigSchema = z.looseObject({ totp: AuthMFATotpConfigSchema.prefault({}) })
diff --git a/backend/src/authentication/providers/two-fa/auth-two-fa.dtos.ts b/backend/src/authentication/providers/two-fa/auth-two-fa.dtos.ts
index a1a4b011..6b290351 100644
--- a/backend/src/authentication/providers/two-fa/auth-two-fa.dtos.ts
+++ b/backend/src/authentication/providers/two-fa/auth-two-fa.dtos.ts
@@ -1,23 +1,20 @@
-import { IsBoolean, IsNotEmpty, IsOptional, IsString } from 'class-validator'
-import { LoginResponseDto } from '../../dto/login-response.dto.js'
+import { z } from 'zod'
+import type { LoginResponseDto } from '../../dto/login-response.dto.js'
-export class TwoFaResponseDto extends LoginResponseDto {
+export type TwoFaResponseDto = LoginResponseDto & {
success: boolean
message: string
}
-export class TwoFaVerifyDto {
- @IsString()
- @IsNotEmpty()
- code!: string
+export const twoFaVerifySchema = z.object({
+ code: z.string().min(1),
+ isRecoveryCode: z.boolean().nullish()
+})
- @IsOptional()
- @IsBoolean()
- isRecoveryCode?: boolean
-}
+export type TwoFaVerifyDto = z.infer<typeof twoFaVerifySchema>
-export class TwoFaVerifyWithPasswordDto extends TwoFaVerifyDto {
- @IsString()
- @IsNotEmpty()
- password!: string
-}
+export const twoFaVerifyWithPasswordSchema = twoFaVerifySchema.extend({
+ password: z.string().min(1)
+})
+
+export type TwoFaVerifyWithPasswordDto = z.infer<typeof twoFaVerifyWithPasswordSchema>
diff --git a/backend/src/authentication/providers/two-fa/guards/auth-token-two-fa.guard.spec.ts b/backend/src/authentication/providers/two-fa/guards/auth-token-two-fa.guard.spec.ts
index fbb4cfbd..6473445b 100644
--- a/backend/src/authentication/providers/two-fa/guards/auth-token-two-fa.guard.spec.ts
+++ b/backend/src/authentication/providers/two-fa/guards/auth-token-two-fa.guard.spec.ts
@@ -10,7 +10,7 @@ import { configuration } from '../../../../configuration/config.environment.js'
import { AuthConfig } from '../../../auth.config.js'
import { AuthManager } from '../../../auth.service.js'
import { CSRF_ERROR } from '../../../constants/auth.js'
-import { JwtPayload } from '../../../interfaces/jwt-payload.interface.js'
+import type { JwtPayload } from '../../../interfaces/jwt-payload.interface.js'
import { TOKEN_TYPE } from '../../../interfaces/token.interface.js'
import { AuthTokenTwoFaGuard } from './auth-token-two-fa.guard.js'
import { AuthTokenTwoFaStrategy } from './auth-token-two-fa.strategy.js'
diff --git a/backend/src/authentication/providers/two-fa/guards/auth-token-two-fa.strategy.ts b/backend/src/authentication/providers/two-fa/guards/auth-token-two-fa.strategy.ts
index 974e15ad..91e3c101 100644
--- a/backend/src/authentication/providers/two-fa/guards/auth-token-two-fa.strategy.ts
+++ b/backend/src/authentication/providers/two-fa/guards/auth-token-two-fa.strategy.ts
@@ -6,7 +6,7 @@ import { ExtractJwt, Strategy } from 'passport-jwt'
import { UserModel } from '../../../../applications/users/models/user.model.js'
import { configuration } from '../../../../configuration/config.environment.js'
import { AuthManager } from '../../../auth.service.js'
-import { JwtPayload } from '../../../interfaces/jwt-payload.interface.js'
+import type { JwtPayload } from '../../../interfaces/jwt-payload.interface.js'
import { TOKEN_TYPE } from '../../../interfaces/token.interface.js'
@Injectable()
@@ -37,7 +37,7 @@ export class AuthTokenTwoFaStrategy extends PassportStrategy(Strategy, 'tokenTwo
private static extractJWTFromCookie(req: FastifyRequest): string | null {
if (typeof req.cookies === 'object' && req.cookies[AuthTokenTwoFaStrategy.accessCookieName] !== undefined) {
- return req.cookies[AuthTokenTwoFaStrategy.accessCookieName]
+ return req.cookies[AuthTokenTwoFaStrategy.accessCookieName] as string
}
return null
}
diff --git a/backend/src/common/decorators.ts b/backend/src/common/decorators.ts
deleted file mode 100644
index 235fa7bc..00000000
--- a/backend/src/common/decorators.ts
+++ /dev/null
@@ -1,20 +0,0 @@
-import { registerDecorator, ValidationArguments, ValidationOptions } from 'class-validator'
-
-export function RejectIfMatch(regex: RegExp, validationOptions?: ValidationOptions) {
- return function (object: any, propertyName: string) {
- registerDecorator({
- name: 'RejectIfMatch',
- target: object.constructor,
- propertyName: propertyName,
- options: validationOptions,
- validator: {
- validate(value: any, _args: ValidationArguments) {
- return typeof value === 'string' && !regex.test(value)
- },
- defaultMessage(args: ValidationArguments) {
- return `${args.property} ne doit pas correspondre à ${regex}`
- }
- }
- })
- }
-}
diff --git a/backend/src/common/errors.spec.ts b/backend/src/common/errors.spec.ts
new file mode 100644
index 00000000..fe2894cd
--- /dev/null
+++ b/backend/src/common/errors.spec.ts
@@ -0,0 +1,29 @@
+import { toErrorMessage } from './errors.js'
+
+describe(toErrorMessage.name, () => {
+ it.each([
+ [new Error('failure'), 'failure'],
+ [{ message: 'failure' }, 'failure'],
+ ['failure', 'failure'],
+ [42, '42']
+ ])('should extract a message from %p', (error, expectedMessage) => {
+ expect(toErrorMessage(error)).toBe(expectedMessage)
+ })
+
+ it.each([null, undefined, '', new Error(''), { message: '' }])('should use the fallback for %p', (error) => {
+ expect(toErrorMessage(error, 'fallback')).toBe('fallback')
+ })
+
+ it('should use the fallback when the value cannot be inspected or stringified', () => {
+ const error = new Proxy(
+ {},
+ {
+ has: () => {
+ throw new Error('inspection failure')
+ }
+ }
+ )
+
+ expect(toErrorMessage(error, 'fallback')).toBe('fallback')
+ })
+})
diff --git a/backend/src/common/errors.ts b/backend/src/common/errors.ts
new file mode 100644
index 00000000..3ae90a59
--- /dev/null
+++ b/backend/src/common/errors.ts
@@ -0,0 +1,17 @@
+export function toErrorMessage(error: unknown, fallback = 'Unknown error'): string {
+ try {
+ if (error instanceof Error) {
+ return error.message || fallback
+ }
+
+ if (error !== null && typeof error === 'object' && 'message' in error && typeof error.message === 'string') {
+ return error.message || fallback
+ }
+
+ if (error === null || error === undefined) return fallback
+
+ return String(error) || fallback
+ } catch {
+ return fallback
+ }
+}
diff --git a/backend/src/common/functions.ts b/backend/src/common/functions.ts
index 3125e238..21454cbd 100755
--- a/backend/src/common/functions.ts
+++ b/backend/src/common/functions.ts
@@ -1,9 +1,5 @@
import { parse as parseMs } from '@lukeed/ms'
import bcrypt from 'bcryptjs'
-import type { ClassTransformOptions } from 'class-transformer'
-import { plainToInstance } from 'class-transformer'
-import type { ValidationError, ValidatorOptions } from 'class-validator'
-import { validateSync } from 'class-validator'
import crypto from 'node:crypto'
import { setTimeout } from 'node:timers/promises'
import { SPACE_PERMS_SEP } from '../applications/spaces/constants/spaces.js'
@@ -26,11 +22,11 @@ export function regExpPathPattern(path: string): RegExp {
}
export function convertHumanTimeToSeconds(value: string): number {
- return parseMs(value) / 1000
+ return parseMs(value)! / 1000
}
export function convertHumanTimeToMs(value: string): number {
- return parseMs(value)
+ return parseMs(value)!
}
export function formatDateISOString(date: Date): string {
@@ -83,39 +79,6 @@ export function splitFullName(fullName?: string): { firstName: string; lastName:
return { firstName, lastName }
}
-function formatValidationErrors(errors: ValidationError[], parentPath = ''): string[] {
- const messages: string[] = []
- for (const error of errors) {
- const propertyPath = [parentPath, error.property].filter(Boolean).join('.')
- if (error.constraints) {
- const constraints = Object.values(error.constraints).join(', ')
- messages.push(propertyPath ? `${propertyPath}: ${constraints}` : constraints)
- }
- if (error.children && error.children.length > 0) {
- messages.push(...formatValidationErrors(error.children, propertyPath))
- }
- }
- return messages
-}
-
-export function transformAndValidate<T extends object>(
- schema: new () => T,
- object: any,
- transformOptions: ClassTransformOptions = {},
- validatorOptions: ValidatorOptions = {},
- context?: string
-): T {
- // warning: plainToInstance do not use constructor to instantiate class
- const instance: T = plainToInstance(schema, object, transformOptions)
- const errors: ValidationError[] = validateSync(instance, validatorOptions)
- if (errors.length > 0) {
- const messages = formatValidationErrors(errors)
- const details = messages.length > 0 ? messages : [errors.toString()]
- throw new Error(context ? `${context}:\n- ${details.join('\n- ')}` : details.join('; '))
- }
- return instance
-}
-
export function uniquePermissions(permissions: string, permissionsSeparator: string = SPACE_PERMS_SEP) {
/*
Returns unique permissions : 'c:r:w:c:r' -> 'c:r:w'
@@ -147,7 +110,7 @@ export function sortObjByName(a: { name: string }, b: { name: string }, asc = fa
}
}
-function diffProperties(a: any, b: any, props: string[]): boolean {
+function diffProperties<T>(a: T, b: T, props: Extract<keyof T, string>[]): boolean {
for (const p of props) {
if (a[p] !== b[p]) {
return false
@@ -156,25 +119,32 @@ function diffProperties(a: any, b: any, props: string[]): boolean {
return true
}
-export function diffCollection<T>(
+export type DiffChanges<T, K extends keyof T> = {
+ [P in K]?: { old: T[P]; new: T[P] }
+}
+
+export type DiffUpdate<T, K extends keyof T> = DiffChanges<T, K> & { object: T }
+
+export type ConvertedDiffUpdate<T, K extends keyof T> = Partial<Pick<T, K>> & { object: T }
+
+export function diffCollection<T, K extends Exclude<Extract<keyof T, string>, 'object'>>(
curCollection: T[],
newCollection: T[],
- updateProps: string[],
- compareProps: string[] = ['id']
-): [T[], Record<string | 'object', { old: any; new: any } | T>[], T[]] {
+ updateProps: K[],
+ compareProps: Extract<keyof T, string>[] = ['id' as Extract<keyof T, string>]
+): [T[], DiffUpdate<T, K>[], T[]] {
const toAdd: T[] = []
- const toUpdate: Record<string | 'object', { old: any; new: any } | T>[] = []
+ const toUpdate: DiffUpdate<T, K>[] = []
const toRemove: T[] = curCollection.filter((c: T) => !newCollection.find((n: T) => diffProperties(c, n, compareProps)))
for (const n of newCollection) {
const o = curCollection.find((c: T) => diffProperties(c, n, compareProps))
if (o) {
- const diff: Record<string | 'object', { old: any; new: any } | T> = {}
- for (const p of updateProps.filter((p: string) => n[p] !== o[p])) {
+ const diff: DiffChanges<T, K> = {}
+ for (const p of updateProps.filter((p) => n[p] !== o[p])) {
diff[p] = { old: o[p], new: n[p] }
}
if (Object.keys(diff).length) {
- diff['object'] = n
- toUpdate.push(diff)
+ toUpdate.push(Object.assign(diff, { object: n }))
}
} else {
toAdd.push(n)
@@ -183,7 +153,12 @@ export function diffCollection<T>(
return [toAdd, toUpdate, toRemove]
}
-export function convertDiffUpdate(update: Record<string | 'object', { old: any; new: any } | any>[]): Record<string | 'object', any>[] {
+export function convertDiffUpdate<T, K extends keyof T>(update: DiffUpdate<T, K>[]): ConvertedDiffUpdate<T, K>[] {
// only keep the new values
- return update.map((o) => Object.fromEntries(Object.entries(o).map(([p, v]) => [p, p === 'object' ? v : v.new])))
+ return update.map(
+ (o) =>
+ Object.fromEntries(
+ Object.entries(o).map(([p, v]) => [p, p === 'object' ? v : (v as unknown as DiffChanges<T, K>[K])!.new])
+ ) as ConvertedDiffUpdate<T, K>
+ )
}
diff --git a/backend/src/common/image.ts b/backend/src/common/image.ts
index 6bf2b858..8637337b 100644
--- a/backend/src/common/image.ts
+++ b/backend/src/common/image.ts
@@ -36,7 +36,7 @@ export async function generateThumbnail(filePath: string, size: number, sourceMi
throw maxFileSizeExceededError()
}
const normalizedFilePath = filePath.toLowerCase()
- const inputFormat = sharpInputFormats.find(({ input }) => input.fileSuffix?.some((suffix) => normalizedFilePath.endsWith(suffix)))
+ const inputFormat = sharpInputFormats.find(({ input }) => input.fileSuffix?.some((suffix: string) => normalizedFilePath.endsWith(suffix)))
if (!inputFormat) {
return {
mimeType: sourceMimeType.replace('image-', imgMimeTypePrefix),
diff --git a/backend/src/common/interfaces.ts b/backend/src/common/interfaces.ts
index 411291a2..2b3f14fd 100644
--- a/backend/src/common/interfaces.ts
+++ b/backend/src/common/interfaces.ts
@@ -1,6 +1,6 @@
-export type Entries<T> = { [K in keyof T]: [K, T[K]] }[keyof T][]
+export type Entries<T> = { [K in keyof T]-?: [K, T[K]] }[keyof T][]
export interface StorageQuota {
storageUsage: number
- storageQuota: number
+ storageQuota: number | null
}
diff --git a/backend/src/common/shared.ts b/backend/src/common/shared.ts
index 5d5cb381..df54b396 100644
--- a/backend/src/common/shared.ts
+++ b/backend/src/common/shared.ts
@@ -30,7 +30,7 @@ export function isValidFileName(fileName: string) {
}
}
-export function currentTimeStamp(date?: Date, ms = false): number {
+export function currentTimeStamp(date?: Date | null, ms = false): number {
return Math.floor((date ? date : new Date()).getTime() / (ms ? 1 : 1000))
}
diff --git a/backend/src/configuration/config.environment.ts b/backend/src/configuration/config.environment.ts
index ec7ff90b..6f63fc3b 100755
--- a/backend/src/configuration/config.environment.ts
+++ b/backend/src/configuration/config.environment.ts
@@ -1,14 +1,14 @@
import { join } from 'node:path'
import { getDocumentTypes } from '../applications/files/constants/samples.js'
-import { FilesContentIndexingConfig } from '../applications/files/files.config.js'
-import { AuthTokenAccessConfig, AuthTokenRefreshConfig } from '../authentication/auth.config.js'
+import { FilesContentIndexingConfigSchema } from '../applications/files/files.config.js'
+import type { AuthTokenAccessConfig, AuthTokenRefreshConfig } from '../authentication/auth.config.js'
import { ACCESS_KEY, CSRF_KEY, TWO_FA_VERIFY_EXPIRATION, WS_KEY } from '../authentication/constants/auth.js'
import { TOKEN_TYPE } from '../authentication/interfaces/token.interface.js'
-import { transformAndValidate } from '../common/functions.js'
import { ServerConfig } from './config.interfaces.js'
import { ENVIRONMENT_PREFIX } from './config.constants.js'
import { configLoader } from './config.loader.js'
-import { GlobalConfig } from './config.validation.js'
+import { isConfigRecord } from './config.schema.js'
+import { type GlobalConfig, GlobalConfigSchema } from './config.validation.js'
export const configuration: GlobalConfig = loadConfiguration()
export const serverConfig: ServerConfig = {
@@ -58,13 +58,15 @@ export function loadConfiguration(): GlobalConfig {
deprecatedFilesEditorsConfig(config)
deprecatedFilesContentIndexingConfig(config)
- return transformAndValidate(
- GlobalConfig,
- config,
- { exposeDefaultValues: true },
- { skipMissingProperties: false },
- 'Invalid configuration in environment.yaml'
- )
+ const result = GlobalConfigSchema.safeParse(config)
+ if (!result.success) {
+ const details = result.error.issues.map((issue) => {
+ const path = issue.path.map(String).join('.')
+ return path ? `${path}: ${issue.message}` : issue.message
+ })
+ throw new Error(`Invalid configuration in environment.yaml:\n- ${details.join('\n- ')}`)
+ }
+ return result.data
}
function deprecatedFilesEditorsEnvConfig(): void {
@@ -105,21 +107,23 @@ function deprecatedServerTrustProxyConfig(config: GlobalConfig): void {
}
function deprecatedFilesEditorsConfig(config: GlobalConfig): void {
- const files = config.applications.files as unknown as Record<string, any>
+ const files: unknown = config.applications.files
+ if (!isConfigRecord(files)) return
const legacyEditors = ['onlyoffice', 'collabora'].filter((editor) => Object.prototype.hasOwnProperty.call(files, editor))
if (legacyEditors.length === 0) {
return
}
- files.editors ??= {}
+ const configuredEditors = files['editors']
+ const editors = isConfigRecord(configuredEditors) ? configuredEditors : {}
+ files['editors'] = editors
for (const editor of legacyEditors) {
const legacyConfig = files[editor]
- const currentConfig = files.editors[editor]
- files.editors[editor] =
- legacyConfig && currentConfig && typeof legacyConfig === 'object' && typeof currentConfig === 'object'
- ? { ...legacyConfig, ...currentConfig }
- : (currentConfig ?? legacyConfig)
+ const currentConfig = editors[editor]
+ const editorConfig =
+ isConfigRecord(legacyConfig) && isConfigRecord(currentConfig) ? { ...legacyConfig, ...currentConfig } : (currentConfig ?? legacyConfig)
+ editors[editor] = editorConfig
delete files[editor]
}
@@ -135,8 +139,7 @@ function deprecatedFilesContentIndexingConfig(config: GlobalConfig): void {
return
}
- const filesContentIndexingConfig = new FilesContentIndexingConfig()
- filesContentIndexingConfig.enabled = config.applications.files.contentIndexing
+ const filesContentIndexingConfig = FilesContentIndexingConfigSchema.parse({ enabled: config.applications.files.contentIndexing })
config.applications.files.contentIndexing = filesContentIndexingConfig
console.warn(
'[DEPRECATED][CONFIGURATION] applications.files.contentIndexing is deprecated and will be removed in a future version. ' +
diff --git a/backend/src/configuration/config.loader.ts b/backend/src/configuration/config.loader.ts
index a56bc438..32d2035b 100644
--- a/backend/src/configuration/config.loader.ts
+++ b/backend/src/configuration/config.loader.ts
@@ -1,3 +1,4 @@
+import { toErrorMessage } from '../common/errors.js'
import deepmerge from 'deepmerge'
import * as yaml from 'js-yaml'
import fs from 'node:fs'
@@ -142,7 +143,7 @@ function getEnvOverrides(config: Record<string, any>): Record<string, any> {
try {
setObjectPropertyFromString(result, path, fs.readFileSync(rawValue, 'utf-8').trim())
} catch (e) {
- console.error(`Unable to store secret from file ${rawValue} : ${e}`)
+ console.error(`Unable to store secret from file ${rawValue} : ${toErrorMessage(e)}`)
}
} else {
setObjectPropertyFromString(result, path, parseEnvValue(rawValue))
diff --git a/backend/src/configuration/config.logger.ts b/backend/src/configuration/config.logger.ts
index 33880e0f..7ad829e9 100644
--- a/backend/src/configuration/config.logger.ts
+++ b/backend/src/configuration/config.logger.ts
@@ -128,6 +128,6 @@ export const configLogger = (loggerConfig: LoggerConfig) => {
return undefined
}
},
- transport: loggerConfig.jsonOutput ? null : createPrettyTransport(loggerConfig)
+ ...(loggerConfig.jsonOutput ? {} : { transport: createPrettyTransport(loggerConfig) })
} satisfies Options<FastifyLoggerRequest>
}
diff --git a/backend/src/configuration/config.schema.spec.ts b/backend/src/configuration/config.schema.spec.ts
new file mode 100644
index 00000000..c8cce279
--- /dev/null
+++ b/backend/src/configuration/config.schema.spec.ts
@@ -0,0 +1,104 @@
+import { HttpException, StandardSchemaValidationPipe } from '@nestjs/common'
+import { z } from 'zod'
+import {
+ httpUrlSchema,
+ integerFromStringSchema,
+ integerNumberSchema,
+ optionalHttpBaseUrlSchema,
+ positiveIntegerFromStringSchema,
+ safeIntegerFromStringSchema
+} from './config.schema.js'
+
+describe('configuration schemas', () => {
+ describe('integer schemas', () => {
+ it.each([2 ** 53, -(2 ** 54)])('preserves the large integer %s as a number', (value) => {
+ expect(integerNumberSchema.parse(value)).toBe(value)
+ expect(integerFromStringSchema.parse(String(value))).toBe(value)
+ })
+
+ it.each([1.5, NaN, Infinity, -Infinity])('rejects a non-integer or non-finite number: %s', (value) => {
+ expect(integerNumberSchema.safeParse(value).success).toBe(false)
+ })
+
+ it.each(['42.0', '1e3', '0x10', '+42', ' 42 ', '42abc', ''])('keeps strict decimal parsing for %s', (value) => {
+ expect(integerFromStringSchema.safeParse(value).success).toBe(false)
+ })
+
+ it('retains the safe integer limit for bounded query parameters', () => {
+ expect(safeIntegerFromStringSchema.parse(String(Number.MAX_SAFE_INTEGER))).toBe(Number.MAX_SAFE_INTEGER)
+ expect(safeIntegerFromStringSchema.safeParse(String(2 ** 53)).success).toBe(false)
+ expect(positiveIntegerFromStringSchema.safeParse(String(2 ** 53)).success).toBe(false)
+ expect(positiveIntegerFromStringSchema.safeParse('0').success).toBe(false)
+ expect(positiveIntegerFromStringSchema.parse('42')).toBe(42)
+ })
+ })
+
+ describe('httpUrlSchema', () => {
+ it.each(['https://files.example.test/archive.zip', 'http://203.0.113.1/archive.zip', 'http://[2001:db8::1]/archive.zip'])(
+ 'accepts an HTTP(S) URL with a public domain or an IP address: %s',
+ (url) => {
+ expect(httpUrlSchema.parse(url)).toBe(url)
+ }
+ )
+
+ it.each([
+ 'not-a-url',
+ 'https://internal',
+ 'https://-example.test',
+ 'https://example-.test',
+ 'https://example..test',
+ 'https://.example.test',
+ 'https:///example.test',
+ 'https://example.test:0'
+ ])('rejects a URL outside the former IsUrl contract without throwing: %s', (url) => {
+ expect(httpUrlSchema.safeParse(url).success).toBe(false)
+ })
+ })
+
+ describe('optionalHttpBaseUrlSchema', () => {
+ it('trims the URL without changing its trailing slash', () => {
+ expect(optionalHttpBaseUrlSchema.parse(' https://editor.example.test/subpath/ ')).toBe('https://editor.example.test/subpath/')
+ expect(optionalHttpBaseUrlSchema.parse('http://onlyoffice:80/')).toBe('http://onlyoffice:80/')
+ expect(optionalHttpBaseUrlSchema.parse('http://[2001:db8::1]:8080/')).toBe('http://[2001:db8::1]:8080/')
+ })
+
+ it('normalizes an empty value to null', () => {
+ expect(optionalHttpBaseUrlSchema.parse(' ')).toBeNull()
+ expect(optionalHttpBaseUrlSchema.parse(null)).toBeNull()
+ })
+
+ it.each([
+ 'ftp://editor.example.test',
+ 'https://user:[email protected]',
+ 'https://editor.example.test/path?token=secret',
+ 'https://editor.example.test/path#fragment',
+ 'https://[email protected]',
+ 'https://@editor.example.test',
+ 'https://editor_server.example.test',
+ 'https://-editor.example.test',
+ 'https://editor-.example.test',
+ 'https://editor..example.test',
+ 'https://.editor.example.test',
+ 'https://editor.example.test./',
+ 'https:///editor.example.test',
+ 'https://editor.example.test:0',
+ 'not-a-url'
+ ])('rejects a non-base HTTP URL: %s', (url) => {
+ expect(optionalHttpBaseUrlSchema.safeParse(url).success).toBe(false)
+ })
+ })
+
+ it('keeps StandardSchema validation errors in the array format handled by the frontend', async () => {
+ const pipe = new StandardSchemaValidationPipe()
+
+ try {
+ await pipe.transform({ externalServer: 'not-a-url' }, { type: 'body', schema: z.object({ externalServer: optionalHttpBaseUrlSchema }) })
+ expect.unreachable('validation should fail')
+ } catch (error) {
+ const response = (error as HttpException).getResponse() as { error: string; message: string[]; statusCode: number }
+ expect(response.statusCode).toBe(400)
+ expect(response.error).toBe('Bad Request')
+ expect(response.message).toEqual([expect.stringContaining('externalServer:')])
+ }
+ })
+})
diff --git a/backend/src/configuration/config.schema.ts b/backend/src/configuration/config.schema.ts
new file mode 100644
index 00000000..6176ea04
--- /dev/null
+++ b/backend/src/configuration/config.schema.ts
@@ -0,0 +1,74 @@
+import { isIP } from 'node:net'
+import { z } from 'zod'
+
+const MAX_URL_LENGTH = 2084
+const HTTP_AUTHORITY_REGEX = /^https?:\/\/([^/?#]*)/i
+export const nonEmptyStringSchema = z.string().min(1)
+const httpUrlCandidateSchema = z.url({ protocol: z.regexes.httpProtocol }).max(MAX_URL_LENGTH)
+
+// z.httpUrl validates domains and TLDs but excludes IP hosts accepted by the former IsUrl contract.
+const httpIpUrlSchema = httpUrlCandidateSchema.refine((value) => {
+ const url = URL.parse(value)
+ return url !== null && isIP(urlHostname(url)) !== 0
+}, 'URL hostname must be a valid IP address')
+
+export const httpUrlSchema = z.union([z.httpUrl().max(MAX_URL_LENGTH), httpIpUrlSchema]).check(httpUrlCheck())
+
+export const httpBaseUrlSchema = httpUrlCandidateSchema.check(httpUrlCheck(true))
+
+export const optionalHttpBaseUrlSchema = z.preprocess(
+ (value) => (typeof value === 'string' ? value.trim() || null : value),
+ httpBaseUrlSchema.nullish()
+)
+
+// Preserve the former IsInt contract for number-based SQL IDs and storage limits.
+// Zod's .int() additionally restricts numbers to the safe integer range.
+export const integerNumberSchema = z.number().refine(Number.isInteger, { message: 'Expected an integer' })
+
+export const integerFromStringSchema = z
+ .string()
+ .regex(/^-?\d+$/)
+ .transform((value) => Number(value))
+ .pipe(integerNumberSchema)
+
+export const safeIntegerFromStringSchema = integerFromStringSchema.pipe(z.number().int())
+
+export const positiveIntegerFromStringSchema = safeIntegerFromStringSchema.pipe(z.number().positive())
+
+export const booleanFromStringSchema = z.stringbool({ truthy: ['true'], falsy: ['false'], case: 'sensitive' })
+
+function urlHostname(url: URL): string {
+ const { hostname } = url
+ return hostname.startsWith('[') && hostname.endsWith(']') ? hostname.slice(1, -1) : hostname
+}
+
+function httpUrlCheck(isBaseUrl = false) {
+ return z.superRefine<string>((value, ctx) => {
+ const url = URL.parse(value)
+ if (url === null || (url.protocol !== 'http:' && url.protocol !== 'https:')) return
+
+ const authority = HTTP_AUTHORITY_REGEX.exec(value)?.[1]
+ const addIssue = (message: string) => ctx.addIssue({ code: 'custom', input: value, message })
+
+ if (!authority) addIssue('URL must contain an explicit HTTP(S) authority')
+ if (url.port === '0') addIssue('URL port must be between 1 and 65535')
+ if (!isBaseUrl) return
+
+ const hostname = urlHostname(url)
+ if (isIP(hostname) === 0 && (!z.regexes.hostname.test(hostname) || hostname.endsWith('.'))) {
+ addIssue('URL hostname must be a valid IP address or hostname')
+ }
+ if (authority?.includes('@') || value.includes('?') || value.includes('#')) {
+ addIssue('URL must not contain authentication, query parameters, or a fragment')
+ }
+ })
+}
+
+export function isConfigRecord(value: unknown): value is Record<string, unknown> {
+ return value !== null && typeof value === 'object' && !Array.isArray(value)
+}
+
+export function hydrateConfigDefaults<T extends object>(defaults: T, value: unknown): T | unknown {
+ // Inactive sections keep their unvalidated values, including explicit undefined overrides.
+ return isConfigRecord(value) ? Object.assign(defaults, value) : value
+}
diff --git a/backend/src/configuration/config.validation.spec.ts b/backend/src/configuration/config.validation.spec.ts
new file mode 100644
index 00000000..8e600376
--- /dev/null
+++ b/backend/src/configuration/config.validation.spec.ts
@@ -0,0 +1,286 @@
+import { SAMPLE_DOCUMENT_GROUPS } from '../applications/files/constants/samples.js'
+import { FilesContentIndexingConfigSchema } from '../applications/files/files.config.js'
+import { OnlyOfficeConfigSchema } from '../applications/files/editors/only-office/only-office.config.js'
+import { APP_STORE_REPOSITORY } from '../applications/sync/constants/store.js'
+import { AuthConfigSchema, AuthTokenConfigSchema } from '../authentication/auth.config.js'
+import { ACCESS_KEY, CSRF_KEY, REFRESH_KEY, WS_KEY } from '../authentication/constants/auth.js'
+import { AUTH_PROVIDER, DEFAULT_STORAGE_QUOTA_FIELD } from '../authentication/providers/auth-providers.constants.js'
+import { AuthProviderLDAPConfigSchema } from '../authentication/providers/ldap/auth-ldap.config.js'
+import { LDAP_COMMON_ATTR, LDAP_LOGIN_ATTR } from '../authentication/providers/ldap/auth-ldap.constants.js'
+import { AuthProviderOIDCConfigSchema } from '../authentication/providers/oidc/auth-oidc.config.js'
+import { OAuthTokenEndpoint } from '../authentication/providers/oidc/auth-oidc.constants.js'
+import { SERVER_NAME } from '../common/shared.js'
+import { CacheConfigSchema } from '../infrastructure/cache/cache.config.js'
+import { DB_CHARSET } from '../infrastructure/database/constants.js'
+import { MailerConfigSchema } from '../infrastructure/mailer/mailer.config.js'
+import { WebSocketConfigSchema } from '../infrastructure/websocket/web-socket.config.js'
+import { DEFAULT_LOG_FILE_PATH } from './config.constants.js'
+import { GlobalConfigSchema, LoggerConfigSchema } from './config.validation.js'
+
+const filePaths = { dataPath: '/data', usersPath: '/data/users', spacesPath: '/data/spaces', linksPath: '/data/links' }
+const ldapRequired = { servers: ['ldap://directory.example.test'], baseDN: 'dc=example,dc=test' }
+const oidcRequired = { issuerUrl: 'https://identity.example.test', clientId: 'client', clientSecret: 'secret', redirectUri: '/callback' }
+
+function tokenConfiguration() {
+ return {
+ access: { secret: 'access-secret' },
+ refresh: { secret: 'refresh-secret' },
+ csrf: { secret: 'refresh-secret' },
+ ws: { secret: 'refresh-secret' }
+ }
+}
+
+function minimalConfiguration() {
+ return {
+ mysql: { url: 'mysql://localhost/sync-in' },
+ auth: { provider: AUTH_PROVIDER.MYSQL, token: tokenConfiguration() },
+ applications: { files: { ...filePaths } }
+ }
+}
+
+function parseAuth(overrides: Record<string, unknown> = {}) {
+ return AuthConfigSchema.parse({ ...minimalConfiguration().auth, ...overrides })
+}
+
+describe('configuration contracts', () => {
+ it('fills every nested default in a minimal configuration', () => {
+ const config = GlobalConfigSchema.parse(minimalConfiguration())
+
+ expect(config).toMatchObject({
+ server: { host: '0.0.0.0', port: 8080, workers: 1, trustProxy: true, restartOnFailure: true },
+ logger: { level: 'info', stdout: true, colorize: true, filePath: DEFAULT_LOG_FILE_PATH, jsonOutput: false },
+ mysql: { url: `mysql://localhost/sync-in?charset=${DB_CHARSET}`, logQueries: false },
+ cache: { adapter: 'mysql', ttl: 60, redis: 'redis://127.0.0.1:6379' },
+ websocket: { adapter: 'cluster', redis: 'redis://127.0.0.1:6379' },
+ auth: {
+ provider: AUTH_PROVIDER.MYSQL,
+ cookieSameSite: 'strict',
+ mfa: { totp: { enabled: true, issuer: SERVER_NAME } },
+ token: {
+ access: { name: ACCESS_KEY, expiration: '15m' },
+ refresh: { name: REFRESH_KEY, expiration: '4h' },
+ csrf: { name: CSRF_KEY, expiration: '4h' },
+ ws: { name: WS_KEY, expiration: '4h' }
+ }
+ },
+ applications: {
+ users: { showUngroupedUsers: true },
+ appStore: { repository: APP_STORE_REPOSITORY.PUBLIC },
+ files: {
+ ...filePaths,
+ maxUploadSize: 5368709120,
+ contentIndexing: { enabled: true, ocr: { enabled: true, languages: ['eng'], offline: false } },
+ trashRetention: { users: false, spaces: false },
+ showHiddenFiles: false,
+ sampleDocuments: [...SAMPLE_DOCUMENT_GROUPS],
+ editors: {
+ onlyoffice: { enabled: false, externalServer: null, verifySSL: false },
+ eurooffice: { enabled: false, externalServer: null, verifySSL: false },
+ collabora: { enabled: false, externalServer: null },
+ drawio: { enabled: false, externalServer: null }
+ }
+ }
+ }
+ })
+ expect(config.server.publicUrl).toBeUndefined()
+ expect(config.auth.ldap).toBeUndefined()
+ expect(config.auth.oidc).toBeUndefined()
+ expect(config.mail).toBeUndefined()
+ })
+
+ it('creates independent nested objects and arrays for each configuration', () => {
+ const first = GlobalConfigSchema.parse(minimalConfiguration())
+ const second = GlobalConfigSchema.parse(minimalConfiguration())
+ first.applications.files.sampleDocuments.pop()
+ first.applications.files.editors.onlyoffice.verifySSL = true
+ first.auth.mfa.totp.enabled = false
+
+ expect(second.applications.files.sampleDocuments).toEqual([...SAMPLE_DOCUMENT_GROUPS])
+ expect(second.applications.files.editors.onlyoffice.verifySSL).toBe(false)
+ expect(second.auth.mfa.totp.enabled).toBe(true)
+ expect(first.applications.files.contentIndexing.ocr).not.toBe(second.applications.files.contentIndexing.ocr)
+
+ const firstLDAP = AuthProviderLDAPConfigSchema.parse(ldapRequired)
+ const secondLDAP = AuthProviderLDAPConfigSchema.parse(ldapRequired)
+ const firstOIDC = AuthProviderOIDCConfigSchema.parse(oidcRequired)
+ const secondOIDC = AuthProviderOIDCConfigSchema.parse(oidcRequired)
+ expect(firstLDAP.attributes).not.toBe(secondLDAP.attributes)
+ expect(firstLDAP.options.autoCreatePermissions).not.toBe(secondLDAP.options.autoCreatePermissions)
+ expect(firstOIDC.security).not.toBe(secondOIDC.security)
+ expect(firstOIDC.options.autoCreatePermissions).not.toBe(secondOIDC.options.autoCreatePermissions)
+ })
+
+ it('hydrates inactive LDAP objects without validating their fields', () => {
+ const ldap = parseAuth({
+ ldap: {
+ servers: ['', false, 'ldap://directory.example.test', 42],
+ attributes: { login: '', email: null, storageQuota: false, customAttribute: 'preserved' },
+ options: { autoCreateUser: 'invalid', enablePasswordAuthFallback: undefined }
+ }
+ }).ldap
+
+ expect(ldap).toMatchObject({
+ servers: ['ldap://directory.example.test', 42],
+ attributes: {
+ login: LDAP_LOGIN_ATTR.UID,
+ email: LDAP_COMMON_ATTR.MAIL,
+ storageQuota: DEFAULT_STORAGE_QUOTA_FIELD,
+ customAttribute: 'preserved'
+ },
+ options: { autoCreateUser: 'invalid', autoCreatePermissions: [] }
+ })
+ expect(ldap.options.enablePasswordAuthFallback).toBeUndefined()
+ })
+
+ it('hydrates inactive OIDC objects while preserving invalid and explicitly undefined values', () => {
+ const oidc = parseAuth({
+ oidc: {
+ options: { autoCreateUser: undefined, autoRedirect: 'invalid', storageQuotaClaim: '' },
+ security: { scope: 'invalid', supportPKCE: undefined, tokenEndpointAuthMethod: null }
+ }
+ }).oidc
+
+ expect(oidc).toMatchObject({
+ options: { autoRedirect: 'invalid', autoCreatePermissions: [], storageQuotaClaim: DEFAULT_STORAGE_QUOTA_FIELD },
+ security: { scope: 'invalid', tokenEndpointAuthMethod: OAuthTokenEndpoint.ClientSecretBasic, tokenSigningAlg: 'RS256' }
+ })
+ expect(oidc.options.autoCreateUser).toBeUndefined()
+ expect(oidc.security.supportPKCE).toBeUndefined()
+ })
+
+ it('fills omitted nested defaults of inactive LDAP and OIDC objects', () => {
+ const auth = parseAuth({ ldap: {}, oidc: {} })
+
+ expect(auth.ldap).toMatchObject({
+ attributes: { login: LDAP_LOGIN_ATTR.UID, email: LDAP_COMMON_ATTR.MAIL, storageQuota: DEFAULT_STORAGE_QUOTA_FIELD },
+ options: { autoCreateUser: true, autoCreatePermissions: [], enablePasswordAuthFallback: false }
+ })
+ expect(auth.oidc).toMatchObject({
+ options: {
+ autoCreateUser: true,
+ autoCreatePermissions: [],
+ autoRedirect: false,
+ enablePasswordAuth: false,
+ autoSyncAvatar: false,
+ storageQuotaClaim: DEFAULT_STORAGE_QUOTA_FIELD,
+ buttonText: 'Continue with OpenID Connect'
+ },
+ security: {
+ scope: 'openid email profile',
+ supportPKCE: true,
+ allowInsecureRequests: false,
+ tokenEndpointAuthMethod: OAuthTokenEndpoint.ClientSecretBasic,
+ tokenSigningAlg: 'RS256',
+ skipSubjectCheck: false,
+ requireVerifiedEmail: true,
+ allowPrivateIpAvatarDownload: false
+ }
+ })
+ })
+
+ it.each([null, undefined, false, 42, 'inactive', []].map((value) => [value]))('preserves non-object inactive providers: %s', (value) => {
+ const auth = parseAuth({ ldap: value, oidc: value })
+ expect(auth.ldap).toEqual(value)
+ expect(auth.oidc).toEqual(value)
+ })
+
+ it.each([null, false, 42, 'inactive', []].map((value) => [value]))('preserves non-object inactive provider subsections: %s', (value) => {
+ const auth = parseAuth({ ldap: { attributes: value, options: value }, oidc: { options: value, security: value } })
+ expect(auth.ldap.attributes).toEqual(value)
+ expect(auth.ldap.options).toEqual(value)
+ expect(auth.oidc.options).toEqual(value)
+ expect(auth.oidc.security).toEqual(value)
+ })
+
+ it.each([
+ [AUTH_PROVIDER.LDAP, { ldap: { ...ldapRequired, options: { autoCreateUser: 'invalid' } } }],
+ [AUTH_PROVIDER.LDAP, { ldap: { ...ldapRequired, servers: ['ldap://directory.example.test', 42] } }],
+ [AUTH_PROVIDER.OIDC, { oidc: { ...oidcRequired, options: { autoRedirect: 'invalid' } } }],
+ [AUTH_PROVIDER.OIDC, { oidc: { ...oidcRequired, security: { scope: 'invalid' } } }]
+ ])('validates the active %s provider', (provider, overrides) => {
+ expect(AuthConfigSchema.safeParse({ ...minimalConfiguration().auth, provider, ...overrides }).success).toBe(false)
+ })
+
+ it('hydrates OCR permissively when content indexing is disabled', () => {
+ expect(FilesContentIndexingConfigSchema.parse({ enabled: false, ocr: { languages: 42, offline: undefined } }).ocr).toMatchObject({
+ enabled: true,
+ languages: 42
+ })
+ expect(FilesContentIndexingConfigSchema.parse({ enabled: false, ocr: { offline: undefined } }).ocr).toMatchObject({ offline: undefined })
+ expect(FilesContentIndexingConfigSchema.parse({ enabled: false }).ocr).toMatchObject({ enabled: true, languages: ['eng'], offline: false })
+ expect(FilesContentIndexingConfigSchema.safeParse({ enabled: true, ocr: { languages: 42 } }).success).toBe(false)
+ })
+
+ it.each([null, false, 42, 'inactive', []].map((value) => [value]))('preserves non-object OCR when content indexing is disabled: %s', (ocr) => {
+ expect(FilesContentIndexingConfigSchema.parse({ enabled: false, ocr }).ocr).toEqual(ocr)
+ })
+
+ it('keeps inactive cache, websocket, OCR and editor fields permissive', () => {
+ expect(CacheConfigSchema.parse({ adapter: 'mysql', redis: null }).redis).toBeNull()
+ expect(WebSocketConfigSchema.parse({ adapter: 'cluster', redis: 42 }).redis).toBe(42)
+ expect(FilesContentIndexingConfigSchema.parse({ enabled: true, ocr: { enabled: false, languages: 42 } }).ocr).toMatchObject({ languages: 42 })
+ expect(OnlyOfficeConfigSchema.parse({ enabled: false, secret: 42 }).secret).toBe(42)
+ expect(CacheConfigSchema.safeParse({ adapter: 'redis', redis: null }).success).toBe(false)
+ expect(WebSocketConfigSchema.safeParse({ adapter: 'redis', redis: 42 }).success).toBe(false)
+ expect(OnlyOfficeConfigSchema.safeParse({ enabled: true, secret: 42 }).success).toBe(false)
+ expect(OnlyOfficeConfigSchema.safeParse({ enabled: false, externalServer: 'invalid' }).success).toBe(false)
+ })
+
+ it('preserves explicit nullish settings instead of replacing them with defaults', () => {
+ expect(LoggerConfigSchema.parse({ jsonOutput: null }).jsonOutput).toBeNull()
+ expect(parseAuth({ encryptionKey: null }).encryptionKey).toBeNull()
+ expect(AuthProviderLDAPConfigSchema.parse({ ...ldapRequired, tlsOptions: null, options: { autoCreateUser: null } })).toMatchObject({
+ tlsOptions: null,
+ options: { autoCreateUser: null }
+ })
+ expect(
+ AuthProviderOIDCConfigSchema.parse({ ...oidcRequired, options: { autoCreatePermissions: null }, security: { supportPKCE: null } })
+ ).toMatchObject({
+ options: { autoCreatePermissions: null },
+ security: { supportPKCE: null }
+ })
+ expect(MailerConfigSchema.parse({ host: 'smtp.example.test', secure: null, auth: null, sender: null, logger: null })).toMatchObject({
+ port: 25,
+ secure: null,
+ ignoreTLS: false,
+ rejectUnauthorized: true,
+ auth: null,
+ sender: null,
+ logger: null
+ })
+ })
+
+ it('preserves unknown properties at every validated nesting level', () => {
+ const input = minimalConfiguration()
+ const config = GlobalConfigSchema.parse({
+ ...input,
+ customRoot: 'root',
+ server: { customServer: 'server' },
+ auth: { ...input.auth, customAuth: 'auth', token: { ...input.auth.token, access: { secret: 'access-secret', customToken: 'token' } } },
+ applications: { files: { ...filePaths, contentIndexing: { customIndexing: 'indexing', ocr: { customOCR: 'ocr' } } } }
+ })
+ expect(config).toMatchObject({
+ customRoot: 'root',
+ server: { customServer: 'server' },
+ auth: { customAuth: 'auth', token: { access: { customToken: 'token' } } },
+ applications: { files: { contentIndexing: { customIndexing: 'indexing', ocr: { customOCR: 'ocr' } } } }
+ })
+ })
+
+ it.each([undefined, null, 'custom-token', 42])('enforces server-controlled token names for %s', (name) => {
+ const tokens = Object.fromEntries(Object.entries(tokenConfiguration()).map(([key, value]) => [key, { ...value, name }]))
+ expect(AuthTokenConfigSchema.parse(tokens)).toMatchObject({
+ access: { name: ACCESS_KEY },
+ refresh: { name: REFRESH_KEY },
+ csrf: { name: CSRF_KEY },
+ ws: { name: WS_KEY }
+ })
+ })
+
+ it.each([undefined, null, false, 42, 'derived-token', { custom: true }])('preserves unchecked derived tokens: %s', (value) => {
+ const tokens = AuthTokenConfigSchema.parse({ ...tokenConfiguration(), access_2fa: value, csrf_2fa: value })
+
+ expect(tokens.access_2fa).toBe(value)
+ expect(tokens.csrf_2fa).toBe(value)
+ })
+})
diff --git a/backend/src/configuration/config.validation.ts b/backend/src/configuration/config.validation.ts
index 1ad1879b..fcec2d8e 100644
--- a/backend/src/configuration/config.validation.ts
+++ b/backend/src/configuration/config.validation.ts
@@ -1,138 +1,47 @@
-import { Transform, Type } from 'class-transformer'
-import {
- IsBoolean,
- IsDefined,
- IsInt,
- IsIP,
- IsNotEmpty,
- IsNotEmptyObject,
- IsObject,
- IsOptional,
- IsString,
- IsUrl,
- Max,
- Min,
- ValidateNested
-} from 'class-validator'
import { cpus } from 'node:os'
-import type { Level } from 'pino'
-import { ApplicationsConfig } from '../applications/applications.config.js'
-import { AuthConfig } from '../authentication/auth.config.js'
-import { CacheConfig } from '../infrastructure/cache/cache.config.js'
-import { MySQLConfig } from '../infrastructure/database/database.config.js'
-import { MailerConfig } from '../infrastructure/mailer/mailer.config.js'
-import { WebSocketConfig } from '../infrastructure/websocket/web-socket.config.js'
+import { z } from 'zod'
+import { ApplicationsConfigSchema } from '../applications/applications.config.js'
+import { AuthConfigSchema } from '../authentication/auth.config.js'
+import { CacheConfigSchema } from '../infrastructure/cache/cache.config.js'
+import { MySQLConfigSchema } from '../infrastructure/database/database.config.js'
+import { MailerConfigSchema } from '../infrastructure/mailer/mailer.config.js'
+import { WebSocketConfigSchema } from '../infrastructure/websocket/web-socket.config.js'
import { DEFAULT_LOG_FILE_PATH } from './config.constants.js'
-
-export class ServerConfig {
- @IsIP()
- host: string = '0.0.0.0'
-
- @IsInt()
- @Min(1024)
- @Max(65535)
- port: number = 8080
-
- @Transform(({ value }) => (typeof value === 'string' ? value.trim().replace(/\/+$/, '') || undefined : value))
- @IsOptional()
- @IsUrl({
- protocols: ['http', 'https'],
- require_protocol: true,
- require_tld: false,
- disallow_auth: true,
- allow_query_components: false,
- allow_fragments: false
- })
- publicUrl?: string
-
- @Transform(({ value }) => (value === 0 || value === 'auto' ? cpus().length : Math.max(Number(value), 1)))
- @IsInt()
- @Min(1)
- workers: number = 1
-
- // Temporary compatibility for deprecated numeric hop counts.
- @Transform(({ value }) => (typeof value === 'number' ? value >= 1 : value))
- @IsOptional()
- trustProxy: boolean | string = true
-
- @IsBoolean()
- restartOnFailure: boolean = true
-}
-
-export class LoggerConfig {
- @IsString()
- @IsNotEmpty()
- level: Level = 'info'
-
- @IsBoolean()
- stdout: boolean = true
-
- @IsBoolean()
- colorize: boolean = true
-
- @IsOptional()
- @IsString()
- @Transform(({ value }) => value || DEFAULT_LOG_FILE_PATH)
- filePath: string = DEFAULT_LOG_FILE_PATH
-
- @IsOptional()
- @IsBoolean()
- jsonOutput: boolean = false
-}
-
-export class GlobalConfig {
- @IsDefined()
- @IsObject()
- @IsNotEmptyObject()
- @ValidateNested()
- @Type(() => ServerConfig)
- server: ServerConfig = new ServerConfig()
-
- @IsDefined()
- @IsObject()
- @IsNotEmptyObject()
- @ValidateNested()
- @Type(() => LoggerConfig)
- logger: LoggerConfig = new LoggerConfig()
-
- @IsDefined()
- @IsObject()
- @IsNotEmptyObject()
- @ValidateNested()
- @Type(() => MySQLConfig)
- mysql: MySQLConfig
-
- @IsDefined()
- @IsObject()
- @IsNotEmptyObject()
- @ValidateNested()
- @Type(() => CacheConfig)
- cache: CacheConfig = new CacheConfig()
-
- @IsOptional()
- @IsObject()
- @IsNotEmptyObject()
- @ValidateNested()
- @Type(() => WebSocketConfig)
- websocket: WebSocketConfig = new WebSocketConfig()
-
- @IsDefined()
- @IsObject()
- @IsNotEmptyObject()
- @ValidateNested()
- @Type(() => AuthConfig)
- auth: AuthConfig
-
- @IsOptional()
- @IsObject()
- @ValidateNested()
- @Type(() => MailerConfig)
- mail?: MailerConfig
-
- @IsDefined()
- @IsObject()
- @IsNotEmptyObject()
- @ValidateNested()
- @Type(() => ApplicationsConfig)
- applications: ApplicationsConfig
-}
+import { httpBaseUrlSchema, nonEmptyStringSchema } from './config.schema.js'
+
+export type LoggerConfig = z.output<typeof LoggerConfigSchema>
+export type GlobalConfig = z.output<typeof GlobalConfigSchema>
+
+export const ServerConfigSchema = z.looseObject({
+ host: z.union([z.ipv4(), z.ipv6()]).default('0.0.0.0'),
+ port: z.number().int().min(1024).max(65535).default(8080),
+ publicUrl: z.preprocess(
+ (value) => (typeof value === 'string' ? value.trim().replace(/\/+$/, '') || undefined : value),
+ httpBaseUrlSchema.nullish()
+ ),
+ workers: z
+ .preprocess((value) => (value === 0 || value === 'auto' ? cpus().length : Math.max(Number(value), 1)), z.number().int().min(1))
+ .default(1),
+ // Preserve permissive proxy settings and deprecated numeric hop counts.
+ trustProxy: z.preprocess((value) => (typeof value === 'number' ? value >= 1 : value), z.custom<boolean | string>()).default(true),
+ restartOnFailure: z.boolean().default(true)
+})
+
+export const LoggerConfigSchema = z.looseObject({
+ level: nonEmptyStringSchema.default('info'),
+ stdout: z.boolean().default(true),
+ colorize: z.boolean().default(true),
+ filePath: z.preprocess((value) => value || DEFAULT_LOG_FILE_PATH, z.string()).default(DEFAULT_LOG_FILE_PATH),
+ jsonOutput: z.boolean().nullish().default(false)
+})
+
+export const GlobalConfigSchema = z.looseObject({
+ server: ServerConfigSchema.prefault({}),
+ logger: LoggerConfigSchema.prefault({}),
+ mysql: MySQLConfigSchema,
+ cache: CacheConfigSchema.prefault({}),
+ websocket: WebSocketConfigSchema.prefault({}),
+ auth: AuthConfigSchema,
+ mail: MailerConfigSchema.nullish(),
+ applications: ApplicationsConfigSchema
+})
diff --git a/backend/src/infrastructure/availability/availability.service.ts b/backend/src/infrastructure/availability/availability.service.ts
index e53dc2d6..f9e16ce0 100644
--- a/backend/src/infrastructure/availability/availability.service.ts
+++ b/backend/src/infrastructure/availability/availability.service.ts
@@ -1,3 +1,4 @@
+import { toErrorMessage } from '../../common/errors.js'
import { Injectable, Logger } from '@nestjs/common'
import type { AvailabilityDependency, AvailabilityListener } from './availability.interfaces.js'
@@ -41,7 +42,7 @@ export class Availability {
try {
listener(dependency, isAvailable)
} catch (e) {
- this.logger.error({ tag: this.notifyListeners.name, msg: `${e}` })
+ this.logger.error({ tag: this.notifyListeners.name, msg: toErrorMessage(e) })
}
}
}
diff --git a/backend/src/infrastructure/availability/scripts/check-health.ts b/backend/src/infrastructure/availability/scripts/check-health.ts
index eef638a5..b8a9f708 100644
--- a/backend/src/infrastructure/availability/scripts/check-health.ts
+++ b/backend/src/infrastructure/availability/scripts/check-health.ts
@@ -1,3 +1,5 @@
+import { toErrorMessage } from '../../../common/errors.js'
+
async function checkHealth(): Promise<void> {
const url = process.env.SYNC_IN_HEALTHCHECK_URL
@@ -13,7 +15,6 @@ async function checkHealth(): Promise<void> {
}
checkHealth().catch((error: unknown) => {
- const message = error instanceof Error ? error.message : String(error)
- console.error(`Health check failed: ${message}`)
+ console.error(`Health check failed: ${toErrorMessage(error)}`)
process.exitCode = 1
})
diff --git a/backend/src/infrastructure/cache/adapters/mysql-cache.adapter.ts b/backend/src/infrastructure/cache/adapters/mysql-cache.adapter.ts
index 23bbde49..75c94607 100644
--- a/backend/src/infrastructure/cache/adapters/mysql-cache.adapter.ts
+++ b/backend/src/infrastructure/cache/adapters/mysql-cache.adapter.ts
@@ -1,5 +1,6 @@
import { Inject, Injectable, Logger } from '@nestjs/common'
import { and, between, eq, exists, inArray, notBetween, SQL, sql } from 'drizzle-orm'
+import { toErrorMessage } from '../../../common/errors.js'
import { createCacheKeySlug, currentTimeStamp } from '../../../common/shared.js'
import { configuration } from '../../../configuration/config.environment.js'
import { INFRASTRUCTURE_DEPENDENCY } from '../../availability/availability.constants.js'
@@ -9,10 +10,16 @@ import { type DBSchema } from '../../database/interfaces/database.interface.js'
import { dbCheckAffectedRows, dbParseJson } from '../../database/utils.js'
import { SchedulerManager } from '../../scheduler/scheduler-manager.service.js'
import type { CacheRateLimitResult, CacheRateLimitState } from '../interfaces/cache-rate-limit.interface.js'
-import { MysqlCache } from '../schemas/mysql-cache.interface.js'
+import type { MysqlCache } from '../schemas/mysql-cache.interface.js'
import { cache } from '../schemas/mysql-cache.schema.js'
import { Cache } from '../cache.service.js'
+function getErrorSource(error: unknown): string | undefined {
+ if (error === null || typeof error !== 'object') return undefined
+ if ('sql' in error && typeof error.sql === 'string') return error.sql
+ return 'code' in error && typeof error.code === 'string' ? error.code : undefined
+}
+
@Injectable()
export class MysqlCacheAdapter implements Cache {
/* Useful SQL commands to stats the scheduler
@@ -122,7 +129,7 @@ export class MysqlCacheAdapter implements Cache {
})
return result.affectedRows === 1 && Number(result.insertId) === 0 ? initialValue : Number(result.insertId)
} catch (e) {
- this.logger.error({ tag: this.increment.name, msg: `${e}` })
+ this.logger.error({ tag: this.increment.name, msg: toErrorMessage(e) })
throw e
}
}
@@ -186,7 +193,7 @@ export class MysqlCacheAdapter implements Cache {
})
return true
} catch (e) {
- this.logger.error({ tag: this.set.name, msg: `${e}` })
+ this.logger.error({ tag: this.set.name, msg: toErrorMessage(e) })
return false
}
}
@@ -209,7 +216,7 @@ export class MysqlCacheAdapter implements Cache {
private readonly whereExpired: () => SQL = () => between(cache.expiration, 0, currentTimeStamp())
- private getTTL(ttl: number): number {
+ private getTTL(ttl?: number): number {
/* ttl (seconds):
- 0 : infinite expiration
- undefined : default ttl
@@ -243,9 +250,9 @@ export class MysqlCacheAdapter implements Cache {
}
this.logger.log(`Using MySQL scheduler`)
} catch (e) {
- const errorSource = e?.sql || e?.code
+ const errorSource = getErrorSource(e)
this.logger.error(
- `MariaDB event scheduler configuration failed${errorSource ? ` on '${errorSource}'` : ''}: ${e.message || e}. ` +
+ `MariaDB event scheduler configuration failed${errorSource ? ` on '${errorSource}'` : ''}: ${toErrorMessage(e)}. ` +
`Enable the scheduler with "SET GLOBAL event_scheduler = ON" as a MariaDB user with SUPER`
)
this.useInternalScheduler()
@@ -264,7 +271,7 @@ export class MysqlCacheAdapter implements Cache {
try {
await this.db.delete(cache).where(this.whereExpired())
} catch (e) {
- this.logger.error({ tag: this.clearExpiredKeys.name, msg: `${e?.code || e}` })
+ this.logger.error({ tag: this.clearExpiredKeys.name, msg: getErrorSource(e) ?? toErrorMessage(e) })
}
}
}
diff --git a/backend/src/infrastructure/cache/adapters/redis-cache.adapter.ts b/backend/src/infrastructure/cache/adapters/redis-cache.adapter.ts
index 94846692..7fde0d2f 100644
--- a/backend/src/infrastructure/cache/adapters/redis-cache.adapter.ts
+++ b/backend/src/infrastructure/cache/adapters/redis-cache.adapter.ts
@@ -1,5 +1,6 @@
import { Injectable, Logger } from '@nestjs/common'
import type { RedisClientOptions, RedisClientType } from 'redis'
+import { toErrorMessage } from '../../../common/errors.js'
import { createCacheKeySlug } from '../../../common/shared.js'
import { configuration } from '../../../configuration/config.environment.js'
import { INFRASTRUCTURE_CONNECTION_RETRY_DELAY, INFRASTRUCTURE_DEPENDENCY } from '../../availability/availability.constants.js'
@@ -13,7 +14,7 @@ export class RedisCacheAdapter implements Cache {
defaultTTL: number = configuration.cache.ttl
infiniteExpiration = -1
private readonly logger = new Logger(Cache.name.toUpperCase())
- private client: RedisClientType
+ private client!: RedisClientType
private readonly redactedRedisUrl = redactRedisUrl(configuration.cache.redis)
constructor(private readonly availability: Availability) {
@@ -28,7 +29,7 @@ export class RedisCacheAdapter implements Cache {
} satisfies RedisClientOptions)
this.client.on('error', (e: Error) => {
this.availability.setAvailable(INFRASTRUCTURE_DEPENDENCY.CACHE, this.client.isReady)
- this.logger.error(e.message || e)
+ this.logger.error(toErrorMessage(e))
})
this.client.on('reconnecting', () => this.availability.setAvailable(INFRASTRUCTURE_DEPENDENCY.CACHE, false))
this.client.on('ready', () => {
@@ -147,7 +148,7 @@ export class RedisCacheAdapter implements Cache {
try {
return (await this.client.set(key, this.serialize(data), options)) === 'OK'
} catch (e) {
- this.logger.error({ tag: this.set.name, msg: `${e}` })
+ this.logger.error({ tag: this.set.name, msg: toErrorMessage(e) })
return false
}
}
@@ -179,7 +180,7 @@ export class RedisCacheAdapter implements Cache {
return INFRASTRUCTURE_CONNECTION_RETRY_DELAY
}
- private getTTL(ttl: number): number {
+ private getTTL(ttl?: number): number {
/* ttl (seconds):
- 0: infinite expiration
- undefined: default ttl
diff --git a/backend/src/infrastructure/cache/cache.config.ts b/backend/src/infrastructure/cache/cache.config.ts
index f6c45653..db0774b3 100644
--- a/backend/src/infrastructure/cache/cache.config.ts
+++ b/backend/src/infrastructure/cache/cache.config.ts
@@ -1,17 +1,16 @@
-import { IsIn, IsInt, IsNotEmpty, IsString, Min, ValidateIf } from 'class-validator'
+import { z } from 'zod'
+import { nonEmptyStringSchema } from '../../configuration/config.schema.js'
-export class CacheConfig {
- @IsString()
- @IsNotEmpty()
- @IsIn(['redis', 'mysql'])
- adapter: 'redis' | 'mysql' = 'mysql'
-
- @IsInt()
- @Min(1)
- ttl: number = 60 // seconds
-
- @ValidateIf((o: CacheConfig) => o.adapter === 'redis')
- @IsString()
- @IsNotEmpty()
- redis: string = 'redis://127.0.0.1:6379'
-}
+export const CacheConfigSchema = z.discriminatedUnion('adapter', [
+ z.looseObject({
+ adapter: z.literal('mysql').default('mysql'),
+ ttl: z.number().int().min(1).default(60),
+ // Preserve the public type without validating an inactive Redis configuration.
+ redis: z.custom<string>().default('redis://127.0.0.1:6379')
+ }),
+ z.looseObject({
+ adapter: z.literal('redis'),
+ ttl: z.number().int().min(1).default(60),
+ redis: nonEmptyStringSchema.default('redis://127.0.0.1:6379')
+ })
+])
diff --git a/backend/src/infrastructure/cache/cache.decorator.spec.ts b/backend/src/infrastructure/cache/cache.decorator.spec.ts
index 62cd30b7..e0099ac4 100644
--- a/backend/src/infrastructure/cache/cache.decorator.spec.ts
+++ b/backend/src/infrastructure/cache/cache.decorator.spec.ts
@@ -76,7 +76,7 @@ describe(CacheDecorator.name, () => {
await expect(service.compute(4, 5)).resolves.toBe(9)
- expect(loggerError).toHaveBeenCalledWith({ tag: 'compute', msg: `${cacheError}` })
+ expect(loggerError).toHaveBeenCalledWith({ tag: 'compute', msg: 'cache read failed' })
expect(service.original).toHaveBeenCalledOnce()
expect(service.original).toHaveBeenCalledWith(4, 5)
expect(cache.set).toHaveBeenCalledWith('cache-key', 9, 60)
@@ -106,7 +106,7 @@ describe(CacheDecorator.name, () => {
expect(service.original).toHaveBeenCalledOnce()
await vi.waitFor(() => {
- expect(loggerError).toHaveBeenCalledWith({ tag: 'compute', msg: `${cacheError}` })
+ expect(loggerError).toHaveBeenCalledWith({ tag: 'compute', msg: 'cache write failed' })
})
})
@@ -132,7 +132,7 @@ describe(CacheDecorator.name, () => {
await expect(service.compute(8)).resolves.toBe(10)
await vi.waitFor(() => {
- expect(loggerError).toHaveBeenCalledWith({ tag: 'compute', msg: `${refreshError}` })
+ expect(loggerError).toHaveBeenCalledWith({ tag: 'compute', msg: 'refresh failed' })
})
expect(cache.set).not.toHaveBeenCalled()
})
diff --git a/backend/src/infrastructure/cache/cache.decorator.ts b/backend/src/infrastructure/cache/cache.decorator.ts
index 552a6c54..f0ac767e 100644
--- a/backend/src/infrastructure/cache/cache.decorator.ts
+++ b/backend/src/infrastructure/cache/cache.decorator.ts
@@ -1,3 +1,4 @@
+import { toErrorMessage } from '../../common/errors.js'
import { Inject, Logger } from '@nestjs/common'
import { Cache } from './cache.service.js'
@@ -6,11 +7,11 @@ export function CacheDecorator(TTL = 120, updateCache: boolean = false) {
const injector = Inject(Cache)
const logger = new Logger(CacheDecorator.name)
- return (target: any, _key?: string | symbol, descriptor?: TypedPropertyDescriptor<any>) => {
+ return (target: object, _key: string | symbol, descriptor: PropertyDescriptor): void => {
injector(target, 'cache')
- const originalMethod = descriptor.value
+ const originalMethod = descriptor.value as (...args: unknown[]) => Promise<unknown>
- const memoize = async function (...args: any[]): Promise<any> {
+ const memoize = async function (this: { cache: Cache; constructor: { name: string } }, ...args: unknown[]): Promise<unknown> {
let cacheKey: string | undefined
try {
cacheKey = this.cache.genSlugKey(this.constructor.name, originalMethod.name, ...args)
@@ -19,19 +20,19 @@ export function CacheDecorator(TTL = 120, updateCache: boolean = false) {
if (updateCache) {
originalMethod
.apply(this, args)
- .then((r: any) => {
- this.cache.set(cacheKey, r, TTL).catch((e: Error) => logger.error({ tag: memoize.name, msg: `${e}` }))
+ .then((r: unknown) => {
+ this.cache.set(cacheKey!, r, TTL).catch((e: Error) => logger.error({ tag: memoize.name, msg: toErrorMessage(e) }))
})
- .catch((e: Error) => logger.error({ tag: memoize.name, msg: `${e}` }))
+ .catch((e: Error) => logger.error({ tag: memoize.name, msg: toErrorMessage(e) }))
}
return cacheResult
}
} catch (e) {
- logger.error({ tag: memoize.name, msg: `${e}` })
+ logger.error({ tag: memoize.name, msg: toErrorMessage(e) })
}
- const r: any = await originalMethod.apply(this, args)
+ const r = await originalMethod.apply(this, args)
if (cacheKey !== undefined) {
- this.cache.set(cacheKey, r, TTL).catch((e: Error) => logger.error({ tag: memoize.name, msg: `${e}` }))
+ this.cache.set(cacheKey, r, TTL).catch((e: Error) => logger.error({ tag: memoize.name, msg: toErrorMessage(e) }))
}
return r
}
diff --git a/backend/src/infrastructure/cache/schemas/mysql-cache.interface.ts b/backend/src/infrastructure/cache/schemas/mysql-cache.interface.ts
index c9fc9dd2..7fdfbd18 100644
--- a/backend/src/infrastructure/cache/schemas/mysql-cache.interface.ts
+++ b/backend/src/infrastructure/cache/schemas/mysql-cache.interface.ts
@@ -1,9 +1,3 @@
-import { cache } from './mysql-cache.schema.js'
+import type { cache } from './mysql-cache.schema.js'
-type MysqlCacheSchema = typeof cache.$inferSelect
-
-export class MysqlCache implements MysqlCacheSchema {
- key: string
- value: any
- expiration: number
-}
+export type MysqlCache = typeof cache.$inferSelect
diff --git a/backend/src/infrastructure/database/database.config.ts b/backend/src/infrastructure/database/database.config.ts
index a4e43486..6afb28d7 100644
--- a/backend/src/infrastructure/database/database.config.ts
+++ b/backend/src/infrastructure/database/database.config.ts
@@ -1,13 +1,8 @@
-import { Transform } from 'class-transformer'
-import { IsBoolean, IsNotEmpty, IsString } from 'class-validator'
+import { z } from 'zod'
+import { nonEmptyStringSchema } from '../../configuration/config.schema.js'
import { DB_CHARSET } from './constants.js'
-export class MySQLConfig {
- @IsString()
- @IsNotEmpty()
- @Transform(({ value }) => (value.endsWith(`?charset=${DB_CHARSET}`) ? value : `${value}?charset=${DB_CHARSET}`))
- url: string
-
- @IsBoolean()
- logQueries: boolean = false
-}
+export const MySQLConfigSchema = z.looseObject({
+ url: nonEmptyStringSchema.overwrite((value) => (value.endsWith(`?charset=${DB_CHARSET}`) ? value : `${value}?charset=${DB_CHARSET}`)),
+ logQueries: z.boolean().default(false)
+})
diff --git a/backend/src/infrastructure/database/database.module.ts b/backend/src/infrastructure/database/database.module.ts
index 6145c182..260ff540 100644
--- a/backend/src/infrastructure/database/database.module.ts
+++ b/backend/src/infrastructure/database/database.module.ts
@@ -113,7 +113,7 @@ export class DatabaseModule implements OnModuleInit, BeforeApplicationShutdown {
await setTimeout(INFRASTRUCTURE_CONNECTION_RETRY_DELAY, undefined, { signal: this.shutdownController.signal })
return true
} catch (error) {
- if ((error as Error).name === 'AbortError') return false
+ if (error instanceof Error && error.name === 'AbortError') return false
throw error
}
}
diff --git a/backend/src/infrastructure/database/scripts/check-db.ts b/backend/src/infrastructure/database/scripts/check-db.ts
index 0d1b8cf6..befe5531 100644
--- a/backend/src/infrastructure/database/scripts/check-db.ts
+++ b/backend/src/infrastructure/database/scripts/check-db.ts
@@ -1,4 +1,5 @@
import { sql } from 'drizzle-orm'
+import { toErrorMessage } from '../../../common/errors.js'
import { DatabaseConfigurationError, getDB } from './db.js'
async function checkConnection() {
@@ -13,8 +14,7 @@ async function checkConnection() {
}
checkConnection().catch((error: unknown) => {
- const message = error instanceof Error ? error.message : String(error)
const isConfigurationError = error instanceof DatabaseConfigurationError
- console.error(`${isConfigurationError ? 'Database configuration error' : 'Database check failed'}: ${message}`)
+ console.error(`${isConfigurationError ? 'Database configuration error' : 'Database check failed'}: ${toErrorMessage(error)}`)
process.exitCode = isConfigurationError ? 2 : 1
})
diff --git a/backend/src/infrastructure/database/scripts/create-user.ts b/backend/src/infrastructure/database/scripts/create-user.ts
index e1e1eb74..b6cb2c77 100644
--- a/backend/src/infrastructure/database/scripts/create-user.ts
+++ b/backend/src/infrastructure/database/scripts/create-user.ts
@@ -1,6 +1,6 @@
import { count, eq, or } from 'drizzle-orm'
import { USER_PERMISSION, USER_ROLE } from '../../../applications/users/constants/user.js'
-import { User } from '../../../applications/users/schemas/user.interface.js'
+import type { User } from '../../../applications/users/schemas/user.interface.js'
import { users } from '../../../applications/users/schemas/users.schema.js'
import { hashPassword } from '../../../common/functions.js'
import { capitalizeString, stripMatchingQuotes } from '../../../common/shared.js'
@@ -14,7 +14,7 @@ interface InitUser extends Partial<User> {
lastName: string
role: USER_ROLE
permissions?: string
- storageQuota?: number
+ storageQuota?: number | null
}
async function createUserInDatabase(user: InitUser) {
diff --git a/backend/src/infrastructure/database/scripts/seed/usersgroups.ts b/backend/src/infrastructure/database/scripts/seed/usersgroups.ts
index c23f96ce..a47cb7e9 100644
--- a/backend/src/infrastructure/database/scripts/seed/usersgroups.ts
+++ b/backend/src/infrastructure/database/scripts/seed/usersgroups.ts
@@ -1,9 +1,9 @@
import { faker } from '@faker-js/faker'
import type { ResultSetHeader } from 'mysql2/promise'
import { USER_PERMISSION, USER_ROLE } from '../../../../applications/users/constants/user.js'
-import { Group } from '../../../../applications/users/schemas/group.interface.js'
+import type { Group } from '../../../../applications/users/schemas/group.interface.js'
import { groups } from '../../../../applications/users/schemas/groups.schema.js'
-import { User } from '../../../../applications/users/schemas/user.interface.js'
+import type { User } from '../../../../applications/users/schemas/user.interface.js'
import { usersGroups } from '../../../../applications/users/schemas/users-groups.schema.js'
import { users } from '../../../../applications/users/schemas/users.schema.js'
import { hashPassword } from '../../../../common/functions.js'
diff --git a/backend/src/infrastructure/database/utils.ts b/backend/src/infrastructure/database/utils.ts
index 3f7856a1..e0d71c7e 100644
--- a/backend/src/infrastructure/database/utils.ts
+++ b/backend/src/infrastructure/database/utils.ts
@@ -1,6 +1,6 @@
import { NestFastifyApplication } from '@nestjs/platform-fastify'
import { TestingModule } from '@nestjs/testing'
-import { Column, eq, inArray, isNull, SQL, sql } from 'drizzle-orm'
+import { Column, eq, inArray, isNull, SQL, sql, SQLWrapper } from 'drizzle-orm'
import { MySqlDatabase, MySqlTableWithColumns } from 'drizzle-orm/mysql-core'
import { MySqlQueryResult } from 'drizzle-orm/mysql2'
import { DB_TOKEN_PROVIDER } from './constants.js'
@@ -8,7 +8,7 @@ import * as schema from './schema.js'
async function dbGetConnection(app: NestFastifyApplication | TestingModule, mode: 'pool' | 'client' = 'pool') {
const db: MySqlDatabase<any, any> = await app.resolve(DB_TOKEN_PROVIDER)
- let connection: any = db['session'].client
+ let connection: any = (db as any)['session'].client
if (mode === 'pool') {
connection = connection.pool
}
@@ -44,8 +44,8 @@ export function dbGetInsertedId(queryResult: MySqlQueryResult): number {
return insertedId
}
-export function convertToSelect<T>(table: T, fields: Partial<keyof T>[]) {
- const select = {} as Record<keyof T, any>
+export function convertToSelect<T, K extends keyof T>(table: T, fields: readonly K[]): Pick<T, K> {
+ const select = {} as Pick<T, K>
for (const f of fields) {
select[f] = table[f]
}
@@ -54,10 +54,10 @@ export function convertToSelect<T>(table: T, fields: Partial<keyof T>[]) {
export function convertToWhere<T>(table: T, filters: Partial<Record<keyof T, any>>): SQL[] {
// only handles AND operator
- return Object.entries(filters).map(([k, v]) => {
- if (v === null) return isNull(table[k])
- if (Array.isArray(v)) return inArray(table[k], v)
- return eq(table[k], v)
+ return (Object.entries(filters) as [keyof T, unknown][]).map(([k, v]) => {
+ if (v === null) return isNull((table as any)[k])
+ if (Array.isArray(v)) return inArray((table as any)[k], v)
+ return eq((table as any)[k], v)
})
}
@@ -67,16 +67,16 @@ export function dbParseJson(value: unknown): any {
return typeof value === 'string' ? JSON.parse(value) : value
}
-export function concatDistinctObjectsInArray(mustBeNotNull: Column, object: Record<string, Column | object>): SQL<any> {
+export function concatDistinctObjectsInArray(mustBeNotNull: SQLWrapper, object: Record<string, SQLWrapper | Record<string, SQLWrapper>>): SQL<any> {
/* Concat json objects in array (only one nesting level is supported) */
const expr: SQL<any> = sql`IFNULL(CONCAT('[', GROUP_CONCAT(DISTINCT IF(${mustBeNotNull} IS NULL, NULL, JSON_OBJECT(`
const keys = Object.keys(object)
keys.forEach((k, index) => {
- if (object[k].constructor.name === 'Object') {
+ if ((object[k] as SQLWrapper).constructor.name === 'Object') {
expr.append(sql`${k},JSON_OBJECT(`)
- const subKeys = Object.keys(object[k])
+ const subKeys = Object.keys(object[k] as Record<string, SQLWrapper>)
subKeys.forEach((subK, subIndex) => {
- expr.append(sql`${subK},${sql`${object[k][subK]}`}${subIndex === subKeys.length - 1 ? sql`)` : sql`,`}`)
+ expr.append(sql`${subK},${sql`${(object[k] as Record<string, SQLWrapper>)[subK]}`}${subIndex === subKeys.length - 1 ? sql`)` : sql`,`}`)
})
} else {
expr.append(sql`${k},${sql`${object[k]}`}`)
diff --git a/backend/src/infrastructure/mailer/mailer.config.ts b/backend/src/infrastructure/mailer/mailer.config.ts
index d7d7402c..14ddf1d1 100644
--- a/backend/src/infrastructure/mailer/mailer.config.ts
+++ b/backend/src/infrastructure/mailer/mailer.config.ts
@@ -1,49 +1,20 @@
-import { Type } from 'class-transformer'
-import { IsBoolean, IsInt, IsNotEmpty, IsObject, IsOptional, IsString, Max, Min, ValidateNested } from 'class-validator'
-
-export class AuthMailConfig {
- @IsString()
- @IsNotEmpty()
- user: string
-
- @IsString()
- @IsNotEmpty()
- pass: string
-}
-
-export class MailerConfig {
- @IsString()
- @IsNotEmpty()
- host: string
-
- @IsInt()
- @Min(0)
- @Max(65535)
- port: number = 25
-
- @IsOptional()
- @IsBoolean()
- secure?: boolean = false
-
- @IsOptional()
- @IsBoolean()
- ignoreTLS?: boolean = false
-
- @IsOptional()
- @IsBoolean()
- rejectUnauthorized?: boolean = true
-
- @IsOptional()
- @IsObject()
- @ValidateNested()
- @Type(() => AuthMailConfig)
- auth?: AuthMailConfig
-
- @IsOptional()
- @IsString()
- sender?: string = 'Sync-in<[email protected]>'
-
- @IsOptional()
- @IsBoolean()
- logger?: boolean = false
-}
+import { z } from 'zod'
+import { nonEmptyStringSchema } from '../../configuration/config.schema.js'
+
+export type MailerConfig = z.output<typeof MailerConfigSchema>
+
+export const AuthMailConfigSchema = z.looseObject({
+ user: nonEmptyStringSchema,
+ pass: nonEmptyStringSchema
+})
+
+export const MailerConfigSchema = z.looseObject({
+ host: nonEmptyStringSchema,
+ port: z.number().int().min(0).max(65535).default(25),
+ secure: z.boolean().nullish().default(false),
+ ignoreTLS: z.boolean().nullish().default(false),
+ rejectUnauthorized: z.boolean().nullish().default(true),
+ auth: AuthMailConfigSchema.nullish(),
+ sender: z.string().nullish().default('Sync-in<[email protected]>'),
+ logger: z.boolean().nullish().default(false)
+})
diff --git a/backend/src/infrastructure/mailer/mailer.service.spec.ts b/backend/src/infrastructure/mailer/mailer.service.spec.ts
index d321affc..479d6a8f 100644
--- a/backend/src/infrastructure/mailer/mailer.service.spec.ts
+++ b/backend/src/infrastructure/mailer/mailer.service.spec.ts
@@ -77,9 +77,9 @@ describe(Mailer.name, () => {
it('should initialize secure transport with no secure port', async () => {
await initModule({ ...mailerConfig, secure: true })
- expect(mailer['configuration'].secure).toBe(false)
+ expect(mailer['configuration']!.secure).toBe(false)
await initModule({ ...mailerConfig, port: 25, secure: true, logger: true })
- expect(mailer['configuration'].secure).toBe(false)
+ expect(mailer['configuration']!.secure).toBe(false)
const loggerWarnSpy = vi.spyOn(logger, 'warn')
expect(loggerWarnSpy).toHaveBeenCalledWith(expect.stringMatching(/has been disabled/i))
loggerWarnSpy.mockClear()
@@ -114,6 +114,15 @@ describe(Mailer.name, () => {
)
})
+ it('should preserve explicit null settings passed to nodemailer', async () => {
+ await initModule({ ...mailerConfig, auth: null, secure: null, ignoreTLS: null, rejectUnauthorized: null, sender: null })
+
+ expect(nodemailer.createTransport).toHaveBeenLastCalledWith(
+ expect.objectContaining({ auth: null, secure: null, ignoreTLS: null, tls: { rejectUnauthorized: null } }),
+ { from: null }
+ )
+ })
+
it.each([
{ loggerLevel: 'info', smtpDebug: false },
{ loggerLevel: 'debug', smtpDebug: true },
diff --git a/backend/src/infrastructure/mailer/mailer.service.ts b/backend/src/infrastructure/mailer/mailer.service.ts
index e50d155b..bf0dd6ef 100644
--- a/backend/src/infrastructure/mailer/mailer.service.ts
+++ b/backend/src/infrastructure/mailer/mailer.service.ts
@@ -1,15 +1,16 @@
+import { toErrorMessage } from '../../common/errors.js'
import { Injectable, type OnModuleInit } from '@nestjs/common'
import { PinoLogger } from 'nestjs-pino'
import type { SendMailOptions, SMTPTransportOptions, Transporter } from 'nodemailer'
import { configuration } from '../../configuration/config.environment.js'
import type { MailProps } from './interfaces/mail.interface.js'
-import { MailerConfig } from './mailer.config.js'
+import type { MailerConfig } from './mailer.config.js'
@Injectable()
export class Mailer implements OnModuleInit {
public available: boolean = false
- private transporter: Transporter
- private readonly configuration: MailerConfig
+ private transporter!: Transporter
+ private readonly configuration: MailerConfig | null | undefined
constructor(private readonly logger: PinoLogger) {
this.logger.setContext(Mailer.name.toUpperCase())
@@ -26,6 +27,7 @@ export class Mailer implements OnModuleInit {
this.configuration.secure = false
}
const smtpLoggerEnabled = this.configuration.logger === true
+ // Keep legacy null values at the Nodemailer boundary; its types omit them.
this.transporter = nodemailer.createTransport(
{
host: this.configuration.host,
@@ -36,8 +38,8 @@ export class Mailer implements OnModuleInit {
tls: { rejectUnauthorized: this.configuration.rejectUnauthorized },
debug: smtpLoggerEnabled && this.logger.logger.isLevelEnabled('debug'),
logger: smtpLoggerEnabled ? (this.logger as SMTPTransportOptions['logger']) : false
- } satisfies SMTPTransportOptions,
- { from: this.configuration.sender } satisfies SendMailOptions
+ } as SMTPTransportOptions,
+ { from: this.configuration.sender } as SendMailOptions
)
await this.verify()
}
@@ -53,7 +55,7 @@ export class Mailer implements OnModuleInit {
await this.transporter.sendMail(m)
this.logger.info(`Mail sent to '${m.to}' with subject '${m.subject}'`)
} catch (e) {
- this.logger.error(`Mail was not sent to '${m.to}' with subject '${m.subject}' : ${e}`)
+ this.logger.error(`Mail was not sent to '${m.to}' with subject '${m.subject}' : ${toErrorMessage(e)}`)
}
})
)
@@ -62,11 +64,11 @@ export class Mailer implements OnModuleInit {
private async verify(): Promise<void> {
try {
await this.transporter.verify()
- this.logger.info(`Using Mail Server at ${this.configuration.host}:${this.configuration.port} (secure: ${this.configuration.secure})`)
+ this.logger.info(`Using Mail Server at ${this.configuration!.host}:${this.configuration!.port} (secure: ${this.configuration!.secure})`)
this.available = true
} catch (e) {
this.logger.error(
- `Unable to use Mail Server at ${this.configuration.host}:${this.configuration.port} (secure: ${this.configuration.secure}) : ${e}`
+ `Unable to use Mail Server at ${this.configuration!.host}:${this.configuration!.port} (secure: ${this.configuration!.secure}) : ${toErrorMessage(e)}`
)
this.available = false
}
diff --git a/backend/src/infrastructure/utils.ts b/backend/src/infrastructure/utils.ts
index cafb1c17..6ecce0b7 100644
--- a/backend/src/infrastructure/utils.ts
+++ b/backend/src/infrastructure/utils.ts
@@ -1,3 +1,4 @@
+import { toErrorMessage } from '../common/errors.js'
import { RETRYABLE_CONNECTION_ERROR_CODES } from './constants.js'
export function redactRedisUrl(url: string): string {
@@ -24,6 +25,6 @@ function connectionErrors(error: unknown): unknown[] {
function isRetryableError(error: unknown): boolean {
const code = (error as { code?: string })?.code
- const message = error instanceof Error ? error.message : String(error)
+ const message = toErrorMessage(error)
return (!!code && RETRYABLE_CONNECTION_ERROR_CODES.has(code)) || message.includes('Socket closed unexpectedly')
}
diff --git a/backend/src/infrastructure/websocket/adapters/cluster.adapter.spec.ts b/backend/src/infrastructure/websocket/adapters/cluster.adapter.spec.ts
index 6ec30a6c..f4726354 100644
--- a/backend/src/infrastructure/websocket/adapters/cluster.adapter.spec.ts
+++ b/backend/src/infrastructure/websocket/adapters/cluster.adapter.spec.ts
@@ -7,7 +7,7 @@ describe(ClusterAdapter.name, () => {
it('should allow NestJS to close the Socket.IO server', async () => {
const close = vi.fn((callback: () => void) => callback())
const server = { adapter: vi.fn(), close }
- vi.spyOn(IoAdapter.prototype, 'createIOServer').mockReturnValue(server)
+ vi.spyOn(IoAdapter.prototype, 'createIOServer').mockReturnValue(server as any)
const clusterAdapter = new ClusterAdapter()
const ioServer = clusterAdapter.createIOServer(0)
diff --git a/backend/src/infrastructure/websocket/adapters/redis.adapter.ts b/backend/src/infrastructure/websocket/adapters/redis.adapter.ts
index 36c27b6b..e2784f74 100644
--- a/backend/src/infrastructure/websocket/adapters/redis.adapter.ts
+++ b/backend/src/infrastructure/websocket/adapters/redis.adapter.ts
@@ -4,6 +4,7 @@ import { IoAdapter } from '@nestjs/platform-socket.io'
import type { createAdapter as createRedisAdapter } from '@socket.io/redis-adapter'
import type { RedisClientType } from 'redis'
import type { ServerOptions } from 'socket.io'
+import { toErrorMessage } from '../../../common/errors.js'
import { INFRASTRUCTURE_CONNECTION_RETRY_DELAY, INFRASTRUCTURE_DEPENDENCY } from '../../availability/availability.constants.js'
import { Availability } from '../../availability/availability.service.js'
import { connectionErrorMessage, isRetryableConnectionError, redactRedisUrl } from '../../utils.js'
@@ -12,7 +13,7 @@ import type { WebSocketConfig } from '../web-socket.config.js'
export class RedisAdapter extends IoAdapter {
protected override readonly logger = new Logger('WebSocketAdapter')
private readonly availability: Availability
- private adapterConstructor: ReturnType<typeof createRedisAdapter>
+ private adapterConstructor!: ReturnType<typeof createRedisAdapter>
private pubClient?: RedisClientType
private subClient?: RedisClientType
@@ -66,7 +67,7 @@ export class RedisAdapter extends IoAdapter {
private registerClientEvents(client: RedisClientType, name: 'PubClient' | 'SubClient', redactedRedisUrl: string): void {
client.on('error', (error: Error) => {
this.updateAvailability()
- this.logger.error(`${name}: ${error.message || error}`)
+ this.logger.error(`${name}: ${toErrorMessage(error)}`)
})
client.on('reconnecting', () => this.updateAvailability())
client.on('ready', () => {
diff --git a/backend/src/infrastructure/websocket/adapters/web-socket.adapter.spec.ts b/backend/src/infrastructure/websocket/adapters/web-socket.adapter.spec.ts
index a850337e..b8421133 100644
--- a/backend/src/infrastructure/websocket/adapters/web-socket.adapter.spec.ts
+++ b/backend/src/infrastructure/websocket/adapters/web-socket.adapter.spec.ts
@@ -1,5 +1,6 @@
import 'reflect-metadata'
import { Socket } from 'socket.io'
+import type { Mock } from 'vitest'
import { UserModel } from '../../../applications/users/models/user.model.js'
import { TOKEN_TYPE } from '../../../authentication/interfaces/token.interface.js'
import { configuration } from '../../../configuration/config.environment.js'
@@ -13,7 +14,7 @@ describe(WebSocketAdapter.name, () => {
let jwtService: { verify: ReturnType<typeof vi.fn> }
let usersManager: { fromAuthToken: ReturnType<typeof vi.fn> }
let socket: Socket
- let next: ReturnType<typeof vi.fn>
+ let next: Mock<(err?: Error) => void>
beforeEach(() => {
jwtService = {
@@ -49,7 +50,7 @@ describe(WebSocketAdapter.name, () => {
},
id: 'socket-id'
} as unknown as Socket
- next = vi.fn()
+ next = vi.fn<(err?: Error) => void>()
})
it('should authenticate a socket with a WebSocket token', async () => {
@@ -58,7 +59,7 @@ describe(WebSocketAdapter.name, () => {
identity
})
- await Reflect.apply(Reflect.get(adapter, 'authenticateSocket'), adapter, [socket, next])
+ await adapter['authenticateSocket'](socket, next)
expect(fastify.parseCookie).toHaveBeenCalledWith(`${configuration.auth.token.ws.name}=${token}`)
expect(jwtService.verify).toHaveBeenCalledWith(token, {
@@ -75,7 +76,7 @@ describe(WebSocketAdapter.name, () => {
identity
})
- await Reflect.apply(Reflect.get(adapter, 'authenticateSocket'), adapter, [socket, next])
+ await adapter['authenticateSocket'](socket, next)
expect(socket).not.toHaveProperty('user')
expect(next).toHaveBeenCalledOnce()
@@ -91,7 +92,7 @@ describe(WebSocketAdapter.name, () => {
})
usersManager.fromAuthToken.mockResolvedValue(null)
- await Reflect.apply(Reflect.get(adapter, 'authenticateSocket'), adapter, [socket, next])
+ await adapter['authenticateSocket'](socket, next)
expect(socket).not.toHaveProperty('user')
expect(next.mock.calls[0][0]).toMatchObject({
diff --git a/backend/src/infrastructure/websocket/adapters/web-socket.adapter.ts b/backend/src/infrastructure/websocket/adapters/web-socket.adapter.ts
index 9b843a75..209d83bd 100644
--- a/backend/src/infrastructure/websocket/adapters/web-socket.adapter.ts
+++ b/backend/src/infrastructure/websocket/adapters/web-socket.adapter.ts
@@ -11,6 +11,7 @@ import { UserModel } from '../../../applications/users/models/user.model.js'
import { UsersManager } from '../../../applications/users/services/users-manager.service.js'
import { type JwtPayload } from '../../../authentication/interfaces/jwt-payload.interface.js'
import { TOKEN_TYPE } from '../../../authentication/interfaces/token.interface.js'
+import { toErrorMessage } from '../../../common/errors.js'
import { configuration } from '../../../configuration/config.environment.js'
import { getClientAddress } from '../utils.js'
import { ClusterAdapter } from './cluster.adapter.js'
@@ -18,7 +19,7 @@ import { RedisAdapter } from './redis.adapter.js'
@Injectable()
export class WebSocketAdapter extends IoAdapter {
- private adapter: RedisAdapter | ClusterAdapter
+ private adapter?: RedisAdapter | ClusterAdapter
private readonly app: NestFastifyApplication
private readonly fastify: FastifyInstance
protected override readonly logger: Logger = new Logger(WebSocketAdapter.name)
@@ -38,10 +39,10 @@ export class WebSocketAdapter extends IoAdapter {
}
createIOServer(port: number, options?: ServerOptions) {
- const server = this.adapter.createIOServer(port, {
+ const server = this.adapter!.createIOServer(port, {
...options,
transports: ['websocket']
- } satisfies ServerOptions)
+ } as ServerOptions)
// Authentication
server.use(this.authenticateSocket.bind(this))
server.on('new_namespace', (namespace: Namespace) => {
@@ -65,7 +66,7 @@ export class WebSocketAdapter extends IoAdapter {
await redisIoAdapter.connect(configuration.websocket.redis)
return redisIoAdapter
} catch (e) {
- this.logger.error(e.message)
+ this.logger.error(toErrorMessage(e))
throw e
}
} else {
@@ -90,7 +91,7 @@ export class WebSocketAdapter extends IoAdapter {
try {
payload = this.jwtService.verify<JwtPayload>(token, { secret: configuration.auth.token.ws.secret })
} catch (e) {
- this.onAuthError(e.message, socket, next)
+ this.onAuthError(toErrorMessage(e), socket, next)
return
}
if (!payload) {
@@ -101,11 +102,11 @@ export class WebSocketAdapter extends IoAdapter {
this.onAuthError('Invalid token type', socket, next)
return
}
- let user: UserModel
+ let user: UserModel | null
try {
user = await this.usersManager.fromAuthToken(new UserModel(payload.identity))
} catch (e) {
- this.onAuthError(e.message, socket, next)
+ this.onAuthError(toErrorMessage(e), socket, next)
return
}
if (!user) {
@@ -117,7 +118,9 @@ export class WebSocketAdapter extends IoAdapter {
}
private onAuthError(error: string, socket: Socket, next: (err?: Error) => void) {
- this.logger.warn(`${error} - ${getClientAddress(socket)} ${socket.id} ${socket.handshake.url} ${socket.handshake.headers['user-agent']}`)
+ this.logger.warn(
+ `${toErrorMessage(error)} - ${getClientAddress(socket)} ${socket.id} ${socket.handshake.url} ${socket.handshake.headers['user-agent']}`
+ )
next(new WsException('Unauthorized'))
}
}
diff --git a/backend/src/infrastructure/websocket/interfaces/auth-socket-io.interface.ts b/backend/src/infrastructure/websocket/interfaces/auth-socket-io.interface.ts
index 5780fd94..db93cf2f 100644
--- a/backend/src/infrastructure/websocket/interfaces/auth-socket-io.interface.ts
+++ b/backend/src/infrastructure/websocket/interfaces/auth-socket-io.interface.ts
@@ -1,4 +1,4 @@
import { Socket } from 'socket.io'
-import { JwtIdentityPayload } from '../../../authentication/interfaces/jwt-payload.interface.js'
+import type { JwtIdentityPayload } from '../../../authentication/interfaces/jwt-payload.interface.js'
export type AuthenticatedSocketIO = Socket & { user: JwtIdentityPayload }
diff --git a/backend/src/infrastructure/websocket/web-socket.config.ts b/backend/src/infrastructure/websocket/web-socket.config.ts
index 252b6c18..a69f6aa7 100644
--- a/backend/src/infrastructure/websocket/web-socket.config.ts
+++ b/backend/src/infrastructure/websocket/web-socket.config.ts
@@ -1,14 +1,16 @@
-import { IsIn, IsNotEmpty, IsString, ValidateIf } from 'class-validator'
+import { z } from 'zod'
+import { nonEmptyStringSchema } from '../../configuration/config.schema.js'
-export class WebSocketConfig {
- @IsString()
- @IsNotEmpty()
- @IsIn(['redis', 'cluster'])
- adapter: 'redis' | 'cluster' = 'cluster'
+export type WebSocketConfig = z.output<typeof WebSocketConfigSchema>
- @ValidateIf((o: WebSocketConfig) => o.adapter === 'redis')
- @IsString()
- @IsNotEmpty()
- // requires optional dependency: @socket.io/redis-adapter
- redis: string = 'redis://127.0.0.1:6379'
-}
+export const WebSocketConfigSchema = z.discriminatedUnion('adapter', [
+ z.looseObject({
+ adapter: z.literal('cluster').default('cluster'),
+ // Preserve the public type without validating an inactive Redis configuration.
+ redis: z.custom<string>().default('redis://127.0.0.1:6379')
+ }),
+ z.looseObject({
+ adapter: z.literal('redis'),
+ redis: nonEmptyStringSchema.default('redis://127.0.0.1:6379')
+ })
+])
diff --git a/backend/src/main.ts b/backend/src/main.ts
index 1e36e27d..c765ece1 100755
--- a/backend/src/main.ts
+++ b/backend/src/main.ts
@@ -1,10 +1,12 @@
#!/usr/bin/env node
+import { toErrorMessage } from './common/errors.js'
import { NestFastifyApplication } from '@nestjs/platform-fastify'
import { Logger } from 'nestjs-pino'
import { setTimeout } from 'node:timers/promises'
import { appBootstrap } from './app.bootstrap.js'
import { AppService } from './app.service.js'
import { configuration } from './configuration/config.environment.js'
+import { connectionErrorMessage } from './infrastructure/utils.js'
async function bootstrap(): Promise<void> {
let logger: Logger | undefined
@@ -23,15 +25,15 @@ async function bootstrap(): Promise<void> {
address = url.toString()
}
if (error) {
- logger.error(`Server listening error at ${address} : ${error}`, 'HTTP')
+ logger!.error(`Server listening error at ${address} : ${toErrorMessage(error)}`, 'HTTP')
process.exit(1)
} else {
- logger.log(`Server listening at ${address}`, 'HTTP')
+ logger!.log(`Server listening at ${address}`, 'HTTP')
}
}
)
} catch (e) {
- const failureMessage = `Bootstrap failed: ${e?.errors || e}`
+ const failureMessage = `Bootstrap failed: ${connectionErrorMessage(e)}`
const nextActionMessage = `${configuration.server.restartOnFailure ? 'Retrying' : 'Exiting'} ...`
if (logger) {
logger.error(failureMessage, 'BOOTSTRAP')
diff --git a/backend/tsconfig.json b/backend/tsconfig.json
index fca2e080..6a407e0c 100755
--- a/backend/tsconfig.json
+++ b/backend/tsconfig.json
@@ -3,7 +3,7 @@
"module": "nodenext",
"moduleResolution": "nodenext",
"resolvePackageJsonExports": true,
- "strict": false,
+ "strict": true,
"declaration": true,
"removeComments": true,
"emitDecoratorMetadata": true,
@@ -15,8 +15,6 @@
"incremental": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
- "noImplicitAny": false,
- "strictBindCallApply": false,
"noFallthroughCasesInSwitch": false,
"resolveJsonModule": true,
"types": [
diff --git a/package-lock.json b/package-lock.json
index 796ecf56..1dcf3f5b 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -64,8 +64,6 @@
"@socket.io/redis-adapter": "^8.3.0",
"@zip.js/zip.js": "^2.8.26",
"bcryptjs": "^3.0.3",
- "class-transformer": "^0.5.1",
- "class-validator": "^0.15.1",
"deepmerge": "^4.3.1",
"drizzle-kit": "^0.31.10",
"drizzle-orm": "^0.45.2",
@@ -98,7 +96,8 @@
"tesseract.js": "^7.0.0",
"text-to-svg": "^3.1.5",
"time2fa": "^1.4.2",
- "unpdf": "^1.8.1"
+ "unpdf": "^1.8.1",
+ "zod": "^4.6.5"
},
"devDependencies": {
"@eslint/js": "^9.18.0",
@@ -1506,6 +1505,16 @@
"node": "^20.19.0 || ^22.12.0 || >=23"
}
},
+ "node_modules/@angular/cli/node_modules/zod": {
+ "version": "4.3.6",
+ "resolved": "https://registry.npmjs.org/zod/-/zod-4.3.6.tgz",
+ "integrity": "sha512-rftlrkhHZOcjDwkGlnUtZZkvaPHCsDATp4pGpuOOMDaTdDDXF91wuVDJoWoPsKX/3YPQ5fHuF3STjcYyKr+Qhg==",
+ "dev": true,
+ "license": "MIT",
+ "funding": {
+ "url": "https://github.com/sponsors/colinhacks"
+ }
+ },
"node_modules/@angular/common": {
"version": "21.2.25",
"resolved": "https://registry.npmjs.org/@angular/common/-/common-21.2.25.tgz",
@@ -10064,12 +10073,6 @@
"@types/opentype.js": "*"
}
},
- "node_modules/@types/validator": {
- "version": "13.15.10",
- "resolved": "https://registry.npmjs.org/@types/validator/-/validator-13.15.10.tgz",
- "integrity": "sha512-T8L6i7wCuyoK8A/ZeLYt1+q0ty3Zb9+qbSSvrIVitzT3YjZqkTZ40IbRsPanlB4h1QB3JVL1SYCdR6ngtFYcuA==",
- "license": "MIT"
- },
"node_modules/@types/ws": {
"version": "8.18.2",
"resolved": "https://registry.npmjs.org/@types/ws/-/ws-8.18.2.tgz",
@@ -11922,23 +11925,6 @@
"node": ">=6.0"
}
},
- "node_modules/class-transformer": {
- "version": "0.5.1",
- "resolved": "https://registry.npmjs.org/class-transformer/-/class-transformer-0.5.1.tgz",
- "integrity": "sha512-SQa1Ws6hUbfC98vKGxZH3KFY0Y1lm5Zm0SY8XX9zbK7FJCyVEac3ATW0RIpwzW+oOfmHE5PMPufDG9hCfoEOMw==",
- "license": "MIT"
- },
- "node_modules/class-validator": {
- "version": "0.15.1",
- "resolved": "https://registry.npmjs.org/class-validator/-/class-validator-0.15.1.tgz",
- "integrity": "sha512-LqoS80HBBSCVhz/3KloUly0ovokxpdOLR++Al3J3+dHXWt9sTKlKd4eYtoxhxyUjoe5+UcIM+5k9MIxyBWnRTw==",
- "license": "MIT",
- "dependencies": {
- "@types/validator": "^13.15.3",
- "libphonenumber-js": "^1.11.1",
- "validator": "^13.15.22"
- }
- },
"node_modules/cli-cursor": {
"version": "5.0.0",
"resolved": "https://registry.npmjs.org/cli-cursor/-/cli-cursor-5.0.0.tgz",
@@ -16082,12 +16068,6 @@
"node": ">= 0.8.0"
}
},
- "node_modules/libphonenumber-js": {
- "version": "1.13.15",
- "resolved": "https://registry.npmjs.org/libphonenumber-js/-/libphonenumber-js-1.13.15.tgz",
- "integrity": "sha512-AHdhEQeDFEJ4GKDAQ9AwxChy+v2kUILUB3TGQRpkXMkWePjXTU/WQEzWVQoIx/Gz8fE73Wr5SEuZCy2vk8jrMQ==",
- "license": "MIT"
- },
"node_modules/light-my-request": {
"version": "6.6.0",
"resolved": "https://registry.npmjs.org/light-my-request/-/light-my-request-6.6.0.tgz",
@@ -21064,15 +21044,6 @@
"node": "^20.17.0 || >=22.9.0"
}
},
- "node_modules/validator": {
- "version": "13.15.35",
- "resolved": "https://registry.npmjs.org/validator/-/validator-13.15.35.tgz",
- "integrity": "sha512-TQ5pAGhd5whStmqWvYF4OjQROlmv9SMFVt37qoCBdqRffuuklWYQlCNnEs2ZaIBD1kZRNnikiZOS1eqgkar0iw==",
- "license": "MIT",
- "engines": {
- "node": ">= 0.10"
- }
- },
"node_modules/vary": {
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz",
@@ -21692,10 +21663,9 @@
}
},
"node_modules/zod": {
- "version": "4.3.6",
- "resolved": "https://registry.npmjs.org/zod/-/zod-4.3.6.tgz",
- "integrity": "sha512-rftlrkhHZOcjDwkGlnUtZZkvaPHCsDATp4pGpuOOMDaTdDDXF91wuVDJoWoPsKX/3YPQ5fHuF3STjcYyKr+Qhg==",
- "dev": true,
+ "version": "4.6.5",
+ "resolved": "https://registry.npmjs.org/zod/-/zod-4.6.5.tgz",
+ "integrity": "sha512-v5l/aFXZQeai4awLbOpSoHecE9UiMrnfx75tEXLjNonXVARxQ5mOeipTjROUchszUNCqnE+hqAMujRsRHsut2Q==",
"license": "MIT",
"funding": {
"url": "https://github.com/sponsors/colinhacks"