Sync-in · Sovereign platform for file storage, sharing, synchronization, and collaboration.
TypeScript cloud-alternativecollaborationcollaborative-editingdropboxfile-serverfile-sharingfile-storagefile-syncfull-text-searchhomelabnextcloudon-premiseopen-sourceprivacy-firstprivate-cloudrealtimesecureself-hostedstorage-serverwebdav
feat(backend:sync): handle 2FA during client registration
johavenb0aadde6323f
diff --git a/backend/src/applications/sync/dtos/sync-client-registration.dto.ts b/backend/src/applications/sync/dtos/sync-client-registration.dto.tsindex f7874f1b..7acfad96 100644--- a/backend/src/applications/sync/dtos/sync-client-registration.dto.ts+++ b/backend/src/applications/sync/dtos/sync-client-registration.dto.ts@@ -4,7 +4,7 @@* See the LICENSE file for licensing details*/-import { IsDefined, IsNotEmpty, IsNotEmptyObject, IsObject, IsString, IsUUID } from 'class-validator'+import { IsDefined, IsNotEmpty, IsNotEmptyObject, IsObject, IsOptional, IsString, IsUUID } from 'class-validator'import { SyncClientInfo } from '../interfaces/sync-client.interface'export class SyncClientRegistrationDto {@@ -16,6 +16,10 @@ export class SyncClientRegistrationDto {@IsString()password: string+ @IsOptional()+ @IsString()+ code?: string+@IsNotEmpty()@IsString()@IsUUID()diff --git a/backend/src/applications/sync/services/sync-clients-manager.service.spec.ts b/backend/src/applications/sync/services/sync-clients-manager.service.spec.tsindex ced1f9dc..e9f3dd10 100644--- a/backend/src/applications/sync/services/sync-clients-manager.service.spec.ts+++ b/backend/src/applications/sync/services/sync-clients-manager.service.spec.ts@@ -12,12 +12,14 @@ import crypto from 'node:crypto'import fs from 'node:fs/promises'import { AuthMethod } from '../../../authentication/models/auth-method'import { AuthManager } from '../../../authentication/services/auth-manager.service'+import { AuthMethod2FA } from '../../../authentication/services/auth-methods/auth-method-two-fa.service'import * as commonFunctions from '../../../common/functions'import * as commonShared from '../../../common/shared'import { configuration } from '../../../configuration/config.environment'import { Cache } from '../../../infrastructure/cache/services/cache.service'import { isPathExists } from '../../files/utils/files'-import { UsersQueries } from '../../users/services/users-queries.service'+import { UserModel } from '../../users/models/user.model'+import { UsersManager } from '../../users/services/users-manager.service'import { CLIENT_AUTH_TYPE, CLIENT_TOKEN_EXPIRED_ERROR } from '../constants/auth'import { APP_STORE_DIRNAME, APP_STORE_REPOSITORY } from '../constants/store'import { SYNC_CLIENT_TYPE } from '../constants/sync'@@ -53,7 +55,7 @@ describe(SyncClientsManager.name, () => {let http: { axiosRef: jest.Mock }let authManager: { setCookies: jest.Mock; getTokens: jest.Mock }let authMethod: { validateUser: jest.Mock }- let usersQueries: { from: jest.Mock; updateUserOrGuest: jest.Mock }+ let usersManager: { fromUserId: jest.Mock; updateAccesses: jest.Mock }let syncQueries: {getOrCreateClient: jest.MockdeleteClient: jest.Mock@@ -76,23 +78,24 @@ describe(SyncClientsManager.name, () => {info: { type: 'desktop' },...overrides})- const makeUser = (overrides: any = {}) => ({- id: 1,- isActive: true,- login: 'u',- email: 'u@x',- firstName: 'U',- lastName: 'X',- role: 1,- permissions: 'desktop',- ...overrides- })+ const makeUser = (overrides: any = {}) =>+ new UserModel({+ id: 1,+ isActive: true,+ login: 'u',+ email: 'u@x',+ firstName: 'U',+ lastName: 'X',+ role: 1,+ permissions: 'desktop',+ ...overrides+ })beforeAll(async () => {http = { axiosRef: jest.fn() }authManager = { setCookies: jest.fn(), getTokens: jest.fn() }authMethod = { validateUser: jest.fn() }- usersQueries = { from: jest.fn(), updateUserOrGuest: jest.fn() }+ usersManager = { fromUserId: jest.fn(), updateAccesses: jest.fn() }syncQueries = {getOrCreateClient: jest.fn(),deleteClient: jest.fn(),@@ -114,9 +117,10 @@ describe(SyncClientsManager.name, () => {{ provide: Cache, useValue: cacheMock },{ provide: HttpService, useValue: http },{ provide: SyncQueries, useValue: syncQueries },- { provide: UsersQueries, useValue: usersQueries },+ { provide: UsersManager, useValue: usersManager },{ provide: AuthManager, useValue: authManager },- { provide: AuthMethod, useValue: authMethod }+ { provide: AuthMethod, useValue: authMethod },+ { provide: AuthMethod2FA, useValue: {} }]}).compile()@@ -139,7 +143,7 @@ describe(SyncClientsManager.name, () => {;(isPathExists as jest.Mock).mockReset();(fs.readFile as jest.Mock).mockReset();(syncQueries.updateClientInfo as jest.Mock).mockResolvedValue(undefined)- ;(usersQueries.updateUserOrGuest as jest.Mock).mockResolvedValue(undefined)+ ;(usersManager.updateAccesses as jest.Mock).mockResolvedValue(undefined);(service as any).cache = cacheMockcacheMock.get.mockResolvedValue(undefined)cacheMock.get.mockClear()@@ -222,7 +226,7 @@ describe(SyncClientsManager.name, () => {it('should forbid when owner user does not exist', async () => {syncQueries.getClient.mockResolvedValue(makeClient())syncQueries.updateClientInfo.mockRejectedValueOnce(new Error('update-fails')) // silence expected- usersQueries.from.mockResolvedValue(null)+ usersManager.fromUserId.mockResolvedValue(null)await expect(service.authenticate(CLIENT_AUTH_TYPE.TOKEN, dto as any, ip, {} as FastifyReply)).rejects.toMatchObject({status: HttpStatus.FORBIDDEN,response: 'User does not exist'@@ -231,7 +235,7 @@ describe(SyncClientsManager.name, () => {it('should forbid when owner account is inactive', async () => {syncQueries.getClient.mockResolvedValue(makeClient())- usersQueries.from.mockResolvedValue(makeUser({ isActive: false }))+ usersManager.fromUserId.mockResolvedValue(makeUser({ isActive: false }))await expect(service.authenticate(CLIENT_AUTH_TYPE.TOKEN, dto as any, ip, {} as FastifyReply)).rejects.toMatchObject({status: HttpStatus.FORBIDDEN,response: 'Account suspended or not authorized'@@ -241,7 +245,7 @@ describe(SyncClientsManager.name, () => {it('should forbid when owner lacks DESKTOP_APP permission', async () => {mockHavePermission = falsesyncQueries.getClient.mockResolvedValue(makeClient())- usersQueries.from.mockResolvedValue(makeUser({ permissions: '', role: 999 }))+ usersManager.fromUserId.mockResolvedValue(makeUser({ permissions: '', role: 999 }))await expect(service.authenticate(CLIENT_AUTH_TYPE.TOKEN, dto as any, ip, {} as FastifyReply)).rejects.toMatchObject({status: HttpStatus.FORBIDDEN,response: 'Missing permission'@@ -250,8 +254,8 @@ describe(SyncClientsManager.name, () => {it('should perform COOKIE authentication and renew client token when needed', async () => {syncQueries.getClient.mockResolvedValue(makeClient({ ownerId: 7 }))- usersQueries.from.mockResolvedValue(makeUser({ id: 7, login: 'john', email: 'john@doe', firstName: 'John', lastName: 'Doe' }))- usersQueries.updateUserOrGuest.mockRejectedValueOnce(new Error('update-access-fail')) // silence expected+ usersManager.fromUserId.mockResolvedValue(makeUser({ id: 7, login: 'john', email: 'john@doe', firstName: 'John', lastName: 'Doe' }))+ usersManager.updateAccesses.mockRejectedValueOnce(new Error('update-access-fail')) // silence expectedauthManager.setCookies.mockResolvedValue({ access_token: 'a', refresh_token: 'b' })jest.spyOn(service, 'renewTokenAndExpiration').mockResolvedValue('new-client-token')@@ -265,7 +269,7 @@ describe(SyncClientsManager.name, () => {it('should perform TOKEN authentication and not renew when not needed', async () => {syncQueries.getClient.mockResolvedValue(makeClient({ ownerId: 8 }))- usersQueries.from.mockResolvedValue(makeUser({ id: 8, login: 'alice', email: 'alice@doe', firstName: 'Alice' }))+ usersManager.fromUserId.mockResolvedValue(makeUser({ id: 8, login: 'alice', email: 'alice@doe', firstName: 'Alice' }))authManager.getTokens.mockResolvedValue({ access_token: 'x', refresh_token: 'y' })jest.spyOn(service, 'renewTokenAndExpiration').mockResolvedValue(undefined)@@ -276,7 +280,7 @@ describe(SyncClientsManager.name, () => {it('should throw when auth type is unknown (else branch)', async () => {syncQueries.getClient.mockResolvedValue(makeClient({ ownerId: 9 }))- usersQueries.from.mockResolvedValue(makeUser({ id: 9, login: 'bob', email: 'bob@doe', firstName: 'Bob' }))+ usersManager.fromUserId.mockResolvedValue(makeUser({ id: 9, login: 'bob', email: 'bob@doe', firstName: 'Bob' }))jest.spyOn(service, 'renewTokenAndExpiration').mockResolvedValue(undefined)await expect(service.authenticate('unknown' as any, { clientId: 'cid', token: 'ctok' } as any, ip, {} as FastifyReply)).rejects.toBeInstanceOf(TypeError@@ -307,9 +311,9 @@ describe(SyncClientsManager.name, () => {it('should renew token and return new value when close to expiration', async () => {;(commonShared.currentTimeStamp as jest.Mock).mockReturnValue(1_000);(commonFunctions.convertHumanTimeToSeconds as jest.Mock).mockImplementation((v: string) =>- v === '90d' ? 90 * 24 * 3600 : v === '180d' ? 180 * 24 * 3600 : 0+ v === '60d' ? 60 * 24 * 3600 : v === '120d' ? 120 * 24 * 3600 : 0)- const client = { id: 'cid', tokenExpiration: 1_000 + 90 * 24 * 3600 - 1 } as any+ const client = { id: 'cid', tokenExpiration: 1_000 + 60 * 24 * 3600 - 1 } as anysyncQueries.renewClientTokenAndExpiration.mockResolvedValue(undefined)const r = await service.renewTokenAndExpiration(client, owner)diff --git a/backend/src/applications/sync/services/sync-clients-manager.service.ts b/backend/src/applications/sync/services/sync-clients-manager.service.tsindex b4d1eb7b..6281a53c 100644--- a/backend/src/applications/sync/services/sync-clients-manager.service.ts+++ b/backend/src/applications/sync/services/sync-clients-manager.service.ts@@ -13,6 +13,7 @@ import fs from 'node:fs/promises'import path from 'node:path'import { AuthMethod } from '../../../authentication/models/auth-method'import { AuthManager } from '../../../authentication/services/auth-manager.service'+import { AuthMethod2FA } from '../../../authentication/services/auth-methods/auth-method-two-fa.service'import { convertHumanTimeToSeconds } from '../../../common/functions'import { currentTimeStamp } from '../../../common/shared'import { STATIC_PATH } from '../../../configuration/config.constants'@@ -22,8 +23,7 @@ import { HTTP_METHOD } from '../../applications.constants'import { isPathExists } from '../../files/utils/files'import { USER_PERMISSION } from '../../users/constants/user'import { UserModel } from '../../users/models/user.model'-import type { User } from '../../users/schemas/user.interface'-import { UsersQueries } from '../../users/services/users-queries.service'+import { UsersManager } from '../../users/services/users-manager.service'import { CLIENT_AUTH_TYPE, CLIENT_TOKEN_EXPIRATION_TIME, CLIENT_TOKEN_EXPIRED_ERROR, CLIENT_TOKEN_RENEW_TIME } from '../constants/auth'import { APP_STORE_DIRNAME, APP_STORE_MANIFEST_FILE, APP_STORE_REPOSITORY, APP_STORE_URL } from '../constants/store'import { SYNC_CLIENT_TYPE } from '../constants/sync'@@ -43,7 +43,8 @@ export class SyncClientsManager {private readonly http: HttpService,private readonly authManager: AuthManager,private readonly authMethod: AuthMethod,- private readonly usersQueries: UsersQueries,+ private readonly authMethod2Fa: AuthMethod2FA,+ private readonly usersManager: UsersManager,private readonly syncQueries: SyncQueries) {}@@ -51,12 +52,24 @@ export class SyncClientsManager {const user: UserModel = await this.authMethod.validateUser(clientRegistrationDto.login, clientRegistrationDto.password)if (!user) {this.logger.warn(`${this.register.name} - auth failed for user *${clientRegistrationDto.login}*`)- throw new HttpException('Not authorized', HttpStatus.UNAUTHORIZED)+ throw new HttpException('Wrong login or password', HttpStatus.UNAUTHORIZED)}if (!user.havePermission(USER_PERMISSION.DESKTOP_APP)) {- this.logger.warn(`${this.register.name} - does not have permission : ${USER_PERMISSION.DESKTOP_APP}`)+ this.logger.warn(`${this.register.name} - user *${user.login}* (${user.id}) does not have permission : ${USER_PERMISSION.DESKTOP_APP}`)throw new HttpException('Missing permission', HttpStatus.FORBIDDEN)}+ if (configuration.auth.mfa.totp.enabled && user.twoFaEnabled) {+ if (!clientRegistrationDto.code) {+ this.logger.warn(`${this.register.name} - missing two-fa code for user *${user.login}* (${user.id})`)+ throw new HttpException('Missing TWO-FA code', HttpStatus.UNAUTHORIZED)+ }+ const auth = this.authMethod2Fa.validateTwoFactorCode(clientRegistrationDto.code, user.secrets.twoFaSecret)+ if (!auth.success) {+ this.logger.warn(`${this.register.name} - wrong two-fa code for user *${user.login}* (${user.id})`)+ this.usersManager.updateAccesses(user, ip, false).catch((e: Error) => this.logger.error(`${this.register.name} - ${e}`))+ throw new HttpException(auth.message, HttpStatus.UNAUTHORIZED)+ }+ }try {const token = await this.syncQueries.getOrCreateClient(user.id, clientRegistrationDto.clientId, clientRegistrationDto.info, ip)this.logger.log(`${this.register.name} - client *${clientRegistrationDto.info.type}* was registered for user *${user.login}* (${user.id})`)@@ -93,39 +106,31 @@ export class SyncClientsManager {throw new HttpException(CLIENT_TOKEN_EXPIRED_ERROR, HttpStatus.FORBIDDEN)}this.syncQueries.updateClientInfo(client, client.info, ip).catch((e: Error) => this.logger.error(`${this.authenticate.name} - ${e}`))- const user: User = await this.usersQueries.from(client.ownerId)+ const user: UserModel = await this.usersManager.fromUserId(client.ownerId)if (!user) {throw new HttpException('User does not exist', HttpStatus.FORBIDDEN)}if (!user.isActive) {throw new HttpException('Account suspended or not authorized', HttpStatus.FORBIDDEN)}- const owner = new UserModel(user)- if (!owner.havePermission(USER_PERMISSION.DESKTOP_APP)) {+ if (!user.havePermission(USER_PERMISSION.DESKTOP_APP)) {this.logger.warn(`${this.register.name} - does not have permission : ${USER_PERMISSION.DESKTOP_APP}`)throw new HttpException('Missing permission', HttpStatus.FORBIDDEN)}// set clientId- owner.clientId = client.id+ user.clientId = client.id// update accesses- this.usersQueries- .updateUserOrGuest(owner.id, {- lastAccess: owner.currentAccess,- currentAccess: new Date(),- lastIp: owner.currentIp,- currentIp: ip- })- .catch((e: Error) => this.logger.error(`${this.authenticate.name} - ${e}`))+ this.usersManager.updateAccesses(user, ip, true).catch((e: Error) => this.logger.error(`${this.authenticate.name} - ${e}`))let r: ClientAuthTokenDto | ClientAuthCookieDtoif (authType === CLIENT_AUTH_TYPE.COOKIE) {// used by the desktop app to perform the login setup using cookies- r = await this.authManager.setCookies(owner, res)+ r = await this.authManager.setCookies(user, res)} else if (authType === CLIENT_AUTH_TYPE.TOKEN) {// used by the cli app and the sync core- r = await this.authManager.getTokens(owner)+ r = await this.authManager.getTokens(user)}// check if the client token must be updated- r.client_token_update = await this.renewTokenAndExpiration(client, owner)+ r.client_token_update = await this.renewTokenAndExpiration(client, user)return r}