Sync-in · Sovereign platform for file storage, sharing, synchronization, and collaboration.
TypeScript cloud-alternativecollaborationcollaborative-editingdropboxfile-serverfile-sharingfile-storagefile-syncfull-text-searchhomelabnextcloudon-premiseopen-sourceprivacy-firstprivate-cloudrealtimesecureself-hostedstorage-serverwebdav
fix(backend:auth): make password-attempt locks temporary
johaven413dd45157d1
diff --git a/backend/src/applications/links/services/links-manager.service.spec.ts b/backend/src/applications/links/services/links-manager.service.spec.tsindex 5e495e47..8b51d051 100644--- a/backend/src/applications/links/services/links-manager.service.spec.ts+++ b/backend/src/applications/links/services/links-manager.service.spec.ts@@ -1,4 +1,5 @@import { HttpService } from '@nestjs/axios'+import { HttpException, HttpStatus } from '@nestjs/common'import { ConfigService } from '@nestjs/config'import { JwtService } from '@nestjs/jwt'import { Test, TestingModule } from '@nestjs/testing'@@ -54,6 +55,7 @@ describe(LinksManager.name, () => {} as anyusersManagerMock = {+ validatePasswordAttempts: vi.fn(),compareUserPassword: vi.fn(),updateAccesses: vi.fn()} as any@@ -311,6 +313,7 @@ describe(LinksManager.name, () => {const result = await service.linkAuthentication(identity, link.uuid, { password: 'secret' } as any, req, res)expect(result).toBe(loginDto)+ expect(usersManagerMock.validatePasswordAttempts).toHaveBeenCalledWith(expect.objectContaining({ id: link.user.id }))expect(usersManagerMock.compareUserPassword).toHaveBeenCalledWith(link.user.id, 'secret')expect(usersManagerMock.updateAccesses).toHaveBeenCalledWith(expect.anything(), req.ip, true)expect(authManagerMock.setCookies).toHaveBeenCalled()@@ -327,6 +330,16 @@ describe(LinksManager.name, () => {await expect(service.linkAuthentication(identity, link.uuid, { password: 'bad' } as any, req, res)).rejects.toMatchObject({ status: 403 })})+ it('rejects a temporarily locked link before comparing its password', async () => {+ const link = { ...baseLink, requireAuth: true }+ linksQueriesMock.linkFromUUID.mockResolvedValueOnce(link)+ usersManagerMock.validatePasswordAttempts.mockRejectedValueOnce(new HttpException('Account locked', HttpStatus.FORBIDDEN))++ await expect(service.linkAuthentication(identity, link.uuid, { password: 'secret' } as any, req, res)).rejects.toMatchObject({ status: 403 })+ expect(usersManagerMock.compareUserPassword).not.toHaveBeenCalled()+ expect(usersManagerMock.updateAccesses).not.toHaveBeenCalled()+ })+it('throws BAD_REQUEST when link is invalid (e.g., expired)', async () => {const expired = { ...baseLink, expiresAt: new Date(Date.now() - 60_000) }linksQueriesMock.linkFromUUID.mockResolvedValueOnce(expired)diff --git a/backend/src/applications/links/services/links-manager.service.ts b/backend/src/applications/links/services/links-manager.service.tsindex 12f677b9..867e6072 100644--- a/backend/src/applications/links/services/links-manager.service.ts+++ b/backend/src/applications/links/services/links-manager.service.ts@@ -105,8 +105,9 @@ export class LinksManager {this.logger.warn({ tag: this.linkAuthentication.name, msg: `*${link.user.login}* (${link.user.id}) : ${check}` })throw new HttpException(check as string, HttpStatus.BAD_REQUEST)}- const authSuccess: boolean = await this.usersManager.compareUserPassword(link.user.id, linkPasswordDto.password)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}` }))diff --git a/backend/src/applications/notifications/constants/notifications.ts b/backend/src/applications/notifications/constants/notifications.tsindex bb1eb39d..cb91fbbd 100644--- a/backend/src/applications/notifications/constants/notifications.ts+++ b/backend/src/applications/notifications/constants/notifications.ts@@ -44,9 +44,7 @@ export const NOTIFICATION_APP_EVENT = {[ACTION.ADD]: 'Two-factor authentication (2FA) on your account has been enabled',[ACTION.DELETE]: 'Two-factor authentication (2FA) on your account has been disabled'},- AUTH_LOCKED: {- [ACTION.DELETE]: 'Your account has been locked after several unsuccessful authentication attempts'- },+ AUTH_LOCKED: 'Your account is temporarily locked for 15 minutes due to too many failed sign-in attempts',UNLOCK_REQUEST: 'sends you a request to unlock the file',UPDATE_AVAILABLE: 'A new update is available'}diff --git a/backend/src/applications/notifications/i18n/de.ts b/backend/src/applications/notifications/i18n/de.tsindex d75be0ef..6160f81a 100644--- a/backend/src/applications/notifications/i18n/de.ts+++ b/backend/src/applications/notifications/i18n/de.ts@@ -33,10 +33,10 @@ export const de = {'Sie erhalten diese Benachrichtigung, weil Sie eine Sperre auf dieser Datei haben.','sends you a request to unlock the file': 'sendet Ihnen eine Anfrage zum Entsperren der Datei','Security notification': 'Sicherheitsbenachrichtigung',- 'Your account has been locked after several unsuccessful authentication attempts':- 'Ihr Konto wurde nach mehreren fehlgeschlagenen Anmeldeversuchen gesperrt',- 'This security notification concerns your Sync-in account. Please contact an administrator to perform the analysis and unlock your account.':- 'Diese Sicherheitsbenachrichtigung betrifft Ihr Sync-in-Konto. Bitte wenden Sie sich an einen Administrator, damit er die Analyse durchführt und Ihr Konto entsperrt.',+ 'Your account is temporarily locked for 15 minutes due to too many failed sign-in attempts':+ 'Ihr Konto ist aufgrund zu vieler fehlgeschlagener Anmeldeversuche vorübergehend für 15 Minuten gesperrt',+ 'You can try signing in again after 15 minutes. If you did not make these attempts, please contact your administrator.':+ 'Sie können sich nach 15 Minuten erneut anmelden. Wenn diese Versuche nicht von Ihnen stammen, wenden Sie sich bitte an Ihren Administrator.','Two-factor authentication (2FA) on your account has been disabled': 'Die Zwei-Faktor-Authentifizierung (2FA) für Ihr Konto wurde deaktiviert','Two-factor authentication (2FA) on your account has been enabled': 'Die Zwei-Faktor-Authentifizierung (2FA) für Ihr Konto wurde aktiviert','You received this notification because the security of your Sync-in account has changed. If you think this was a mistake, please review your security settings or contact your administrator.':diff --git a/backend/src/applications/notifications/i18n/es.ts b/backend/src/applications/notifications/i18n/es.tsindex 33ea5315..18f91c40 100644--- a/backend/src/applications/notifications/i18n/es.ts+++ b/backend/src/applications/notifications/i18n/es.ts@@ -32,10 +32,10 @@ export const es = {'You receive this notification because you have a lock on this file.': 'Recibe esta notificación porque tiene un bloqueo en este archivo.','sends you a request to unlock the file': 'le envía una solicitud para desbloquear el archivo','Security notification': 'Notificación de seguridad',- 'Your account has been locked after several unsuccessful authentication attempts':- 'Su cuenta ha sido bloqueada tras varios intentos de autenticación fallidos',- 'This security notification concerns your Sync-in account. Please contact an administrator to perform the analysis and unlock your account.':- 'Esta notificación de seguridad concierne a su cuenta de Sync-in. Póngase en contacto con un administrador para realizar el análisis y desbloquear su cuenta.',+ 'Your account is temporarily locked for 15 minutes due to too many failed sign-in attempts':+ 'Su cuenta está bloqueada temporalmente durante 15 minutos debido a demasiados intentos de inicio de sesión fallidos',+ 'You can try signing in again after 15 minutes. If you did not make these attempts, please contact your administrator.':+ 'Puede intentar iniciar sesión de nuevo después de 15 minutos. Si no ha realizado estos intentos, póngase en contacto con su administrador.','Two-factor authentication (2FA) on your account has been disabled': 'La autenticación de dos factores (2FA) de su cuenta ha sido desactivada','Two-factor authentication (2FA) on your account has been enabled': 'La autenticación de dos factores (2FA) de su cuenta ha sido activada','You received this notification because the security of your Sync-in account has changed. If you think this was a mistake, please review your security settings or contact your administrator.':diff --git a/backend/src/applications/notifications/i18n/fr.ts b/backend/src/applications/notifications/i18n/fr.tsindex 2e17e384..12c089e2 100644--- a/backend/src/applications/notifications/i18n/fr.ts+++ b/backend/src/applications/notifications/i18n/fr.ts@@ -31,9 +31,10 @@ export const fr = {'You receive this notification because you have a lock on this file.': 'Vous recevez cette notification car vous avez un verrou sur ce fichier.','sends you a request to unlock the file': 'vous envoie une demande de déverrouillage du fichier','Security notification': 'Notification de sécurité',- 'Your account has been locked after several unsuccessful authentication attempts':- 'Votre compte a été verrouillé après plusieurs tentatives d’authentification infructueuses',- 'This security notification concerns your Sync-in account. Please contact an administrator to perform the analysis and unlock your account.': `Cette notification de sécurité concerne votre compte Sync-in. Merci de contacter un administrateur afin qu’il procède à l’analyse et au déverrouillage de votre compte.`,+ 'Your account is temporarily locked for 15 minutes due to too many failed sign-in attempts':+ 'Votre compte est temporairement verrouillé pendant 15 minutes en raison d’un trop grand nombre de tentatives de connexion infructueuses',+ 'You can try signing in again after 15 minutes. If you did not make these attempts, please contact your administrator.':+ 'Vous pourrez réessayer de vous connecter après 15 minutes. Si vous n’êtes pas à l’origine de ces tentatives, contactez votre administrateur.','Two-factor authentication (2FA) on your account has been disabled': `L’authentification à deux facteurs (2FA) sur votre compte a été désactivée`,'Two-factor authentication (2FA) on your account has been enabled': `L’authentification à deux facteurs (2FA) sur votre compte a été activée`,'You received this notification because the security of your Sync-in account has changed. If you think this was a mistake, please review your security settings or contact your administrator.': `Vous recevez cette notification car la sécurité de votre compte Sync-in a été modifiée. Si vous pensez qu’il s’agit d’une erreur, vérifiez vos paramètres de sécurité ou contactez votre administrateur.`,diff --git a/backend/src/applications/notifications/i18n/hi.ts b/backend/src/applications/notifications/i18n/hi.tsindex 9162538d..f8e92e4f 100644--- a/backend/src/applications/notifications/i18n/hi.ts+++ b/backend/src/applications/notifications/i18n/hi.ts@@ -32,10 +32,10 @@ export const hi = {'You receive this notification because you have a lock on this file.': 'यह सूचना आपको इसलिए प्राप्त हुई है क्योंकि इस फ़ाइल पर आपका लॉक है।','sends you a request to unlock the file': 'आपको फ़ाइल अनलॉक करने का अनुरोध भेजता है','Security notification': 'सुरक्षा सूचना',- 'Your account has been locked after several unsuccessful authentication attempts':- 'कई असफल प्रमाणीकरण प्रयासों के बाद आपका खाता लॉक कर दिया गया है',- 'This security notification concerns your Sync-in account. Please contact an administrator to perform the analysis and unlock your account.':- 'यह सुरक्षा सूचना आपके Sync-in खाते से संबंधित है। कृपया विश्लेषण करने और अपना खाता अनलॉक करने के लिए किसी प्रशासक से संपर्क करें।',+ 'Your account is temporarily locked for 15 minutes due to too many failed sign-in attempts':+ 'बहुत अधिक असफल साइन-इन प्रयासों के कारण आपका खाता 15 मिनट के लिए अस्थायी रूप से लॉक है',+ 'You can try signing in again after 15 minutes. If you did not make these attempts, please contact your administrator.':+ 'आप 15 मिनट बाद फिर से साइन इन करने का प्रयास कर सकते हैं। यदि ये प्रयास आपने नहीं किए थे, तो कृपया अपने प्रशासक से संपर्क करें।','Two-factor authentication (2FA) on your account has been disabled': 'आपके खाते पर दो‑कारक प्रमाणीकरण (2FA) अक्षम कर दिया गया है','Two-factor authentication (2FA) on your account has been enabled': 'आपके खाते पर दो‑कारक प्रमाणीकरण (2FA) सक्षम कर दिया गया है','You received this notification because the security of your Sync-in account has changed. If you think this was a mistake, please review your security settings or contact your administrator.':diff --git a/backend/src/applications/notifications/i18n/it.ts b/backend/src/applications/notifications/i18n/it.tsindex 740eb587..e7c6adf5 100644--- a/backend/src/applications/notifications/i18n/it.ts+++ b/backend/src/applications/notifications/i18n/it.ts@@ -32,9 +32,10 @@ export const it = {'You receive this notification because you have a lock on this file.': 'Ricevi questa notifica perché hai un blocco su questo file.','sends you a request to unlock the file': 'ti invia una richiesta per sbloccare il file','Security notification': 'Notifica di sicurezza',- 'Your account has been locked after several unsuccessful authentication attempts':- 'Il tuo account è stato bloccato dopo diversi tentativi di autenticazione non riusciti',- 'This security notification concerns your Sync-in account. Please contact an administrator to perform the analysis and unlock your account.': `Questa notifica di sicurezza riguarda il tuo account Sync-in. Contatta un amministratore per effettuare l'analisi e sbloccare il tuo account.`,+ 'Your account is temporarily locked for 15 minutes due to too many failed sign-in attempts':+ 'Il tuo account è temporaneamente bloccato per 15 minuti a causa di troppi tentativi di accesso non riusciti',+ 'You can try signing in again after 15 minutes. If you did not make these attempts, please contact your administrator.':+ 'Puoi provare ad accedere di nuovo dopo 15 minuti. Se non hai effettuato tu questi tentativi, contatta il tuo amministratore.','Two-factor authentication (2FA) on your account has been disabled': `L'autenticazione a due fattori (2FA) sul tuo account è stata disabilitata`,'Two-factor authentication (2FA) on your account has been enabled': `L'autenticazione a due fattori (2FA) sul tuo account è stata abilitata`,'You received this notification because the security of your Sync-in account has changed. If you think this was a mistake, please review your security settings or contact your administrator.':diff --git a/backend/src/applications/notifications/i18n/ja.ts b/backend/src/applications/notifications/i18n/ja.tsindex 32f8a636..8486a5d5 100644--- a/backend/src/applications/notifications/i18n/ja.ts+++ b/backend/src/applications/notifications/i18n/ja.ts@@ -32,9 +32,10 @@ export const ja = {'You receive this notification because you have a lock on this file.': 'このファイルにロックが設定されているため、この通知を受け取っています。','sends you a request to unlock the file': 'あなたにファイルのロック解除をリクエストしました','Security notification': 'セキュリティ通知',- 'Your account has been locked after several unsuccessful authentication attempts': '複数回の認証失敗により、あなたのアカウントはロックされました',- 'This security notification concerns your Sync-in account. Please contact an administrator to perform the analysis and unlock your account.':- 'このセキュリティ通知はあなたの Sync-in アカウントに関するものです。分析とアカウントのロック解除のため、管理者に連絡してください。',+ 'Your account is temporarily locked for 15 minutes due to too many failed sign-in attempts':+ 'サインインの失敗回数が多すぎるため、アカウントは15分間一時的にロックされています',+ 'You can try signing in again after 15 minutes. If you did not make these attempts, please contact your administrator.':+ '15分後に再度サインインできます。これらの試行に心当たりがない場合は、管理者に連絡してください。','Two-factor authentication (2FA) on your account has been disabled': 'あなたのアカウントの二要素認証(2FA)が無効化されました','Two-factor authentication (2FA) on your account has been enabled': 'あなたのアカウントの二要素認証(2FA)が有効化されました','You received this notification because the security of your Sync-in account has changed. If you think this was a mistake, please review your security settings or contact your administrator.':diff --git a/backend/src/applications/notifications/i18n/ko.ts b/backend/src/applications/notifications/i18n/ko.tsindex b45a23b2..c9971d0c 100644--- a/backend/src/applications/notifications/i18n/ko.ts+++ b/backend/src/applications/notifications/i18n/ko.ts@@ -32,9 +32,10 @@ export const ko = {'You receive this notification because you have a lock on this file.': '이 파일에 잠금이 설정되어 있어 이 알림을 받았습니다.','sends you a request to unlock the file': '파일 잠금 해제 요청을 보냈습니다','Security notification': '보안 알림',- 'Your account has been locked after several unsuccessful authentication attempts': '여러 번 인증에 실패하여 계정이 잠겼습니다',- 'This security notification concerns your Sync-in account. Please contact an administrator to perform the analysis and unlock your account.':- '이 보안 알림은 귀하의 Sync-in 계정과 관련된 것입니다. 분석 및 계정 잠금 해제를 위해 관리자에게 문의해 주세요.',+ 'Your account is temporarily locked for 15 minutes due to too many failed sign-in attempts':+ '로그인 실패 횟수가 너무 많아 계정이 15분 동안 일시적으로 잠겼습니다',+ 'You can try signing in again after 15 minutes. If you did not make these attempts, please contact your administrator.':+ '15분 후에 다시 로그인할 수 있습니다. 본인이 시도한 것이 아니라면 관리자에게 문의하세요.','Two-factor authentication (2FA) on your account has been disabled': '계정의 이중 인증(2FA)이 비활성화되었습니다','Two-factor authentication (2FA) on your account has been enabled': '계정의 이중 인증(2FA)이 활성화되었습니다','You received this notification because the security of your Sync-in account has changed. If you think this was a mistake, please review your security settings or contact your administrator.':diff --git a/backend/src/applications/notifications/i18n/nl.ts b/backend/src/applications/notifications/i18n/nl.tsindex c79ed483..b1ed5623 100644--- a/backend/src/applications/notifications/i18n/nl.ts+++ b/backend/src/applications/notifications/i18n/nl.ts@@ -32,10 +32,10 @@ export const nl = {'You receive this notification because you have a lock on this file.': 'U ontvangt deze melding omdat u dit bestand hebt vergrendeld.','sends you a request to unlock the file': 'stuurt u een verzoek om het bestand te ontgrendelen','Security notification': 'Beveiligingsmelding',- 'Your account has been locked after several unsuccessful authentication attempts':- 'Uw account is vergrendeld na meerdere mislukte pogingen tot authenticatie',- 'This security notification concerns your Sync-in account. Please contact an administrator to perform the analysis and unlock your account.':- 'Deze beveiligingsmelding betreft uw Sync-in-account. Neem contact op met een beheerder om dit te laten onderzoeken en uw account te ontgrendelen.',+ 'Your account is temporarily locked for 15 minutes due to too many failed sign-in attempts':+ 'Uw account is vanwege te veel mislukte aanmeldpogingen tijdelijk 15 minuten geblokkeerd',+ 'You can try signing in again after 15 minutes. If you did not make these attempts, please contact your administrator.':+ 'U kunt na 15 minuten opnieuw proberen in te loggen. Als u deze pogingen niet hebt gedaan, neem dan contact op met uw beheerder.','Two-factor authentication (2FA) on your account has been disabled': 'Twee-factor-authenticatie (2FA) op uw account is uitgeschakeld','Two-factor authentication (2FA) on your account has been enabled': 'Twee-factor-authenticatie (2FA) op uw account is ingeschakeld','You received this notification because the security of your Sync-in account has changed. If you think this was a mistake, please review your security settings or contact your administrator.':diff --git a/backend/src/applications/notifications/i18n/pl.ts b/backend/src/applications/notifications/i18n/pl.tsindex 125f482c..799e4ea0 100644--- a/backend/src/applications/notifications/i18n/pl.ts+++ b/backend/src/applications/notifications/i18n/pl.ts@@ -32,10 +32,10 @@ export const pl = {'You receive this notification because you have a lock on this file.': 'Otrzymujesz to powiadomienie, ponieważ masz blokadę na tym pliku.','sends you a request to unlock the file': 'wysyła ci prośbę o odblokowanie pliku','Security notification': 'Powiadomienie bezpieczeństwa',- 'Your account has been locked after several unsuccessful authentication attempts':- 'Twoje konto zostało zablokowane po kilku nieudanych próbach uwierzytelnienia',- 'This security notification concerns your Sync-in account. Please contact an administrator to perform the analysis and unlock your account.':- 'To powiadomienie bezpieczeństwa dotyczy twojego konta Sync-in. Skontaktuj się z administratorem, aby przeprowadzić analizę i odblokować konto.',+ 'Your account is temporarily locked for 15 minutes due to too many failed sign-in attempts':+ 'Twoje konto jest tymczasowo zablokowane na 15 minut z powodu zbyt wielu nieudanych prób logowania',+ 'You can try signing in again after 15 minutes. If you did not make these attempts, please contact your administrator.':+ 'Możesz spróbować zalogować się ponownie po 15 minutach. Jeśli te próby nie zostały wykonane przez ciebie, skontaktuj się z administratorem.','Two-factor authentication (2FA) on your account has been disabled': 'Uwierzytelnianie dwuskładnikowe (2FA) na twoim koncie zostało wyłączone','Two-factor authentication (2FA) on your account has been enabled': 'Uwierzytelnianie dwuskładnikowe (2FA) na twoim koncie zostało włączone','You received this notification because the security of your Sync-in account has changed. If you think this was a mistake, please review your security settings or contact your administrator.':diff --git a/backend/src/applications/notifications/i18n/pt.ts b/backend/src/applications/notifications/i18n/pt.tsindex 8e51f73a..b0792d20 100644--- a/backend/src/applications/notifications/i18n/pt.ts+++ b/backend/src/applications/notifications/i18n/pt.ts@@ -32,10 +32,10 @@ export const pt = {'You receive this notification because you have a lock on this file.': 'Recebe esta notificação porque tem um bloqueio neste ficheiro.','sends you a request to unlock the file': 'envia-lhe um pedido para desbloquear o ficheiro','Security notification': 'Notificação de segurança',- 'Your account has been locked after several unsuccessful authentication attempts':- 'A sua conta foi bloqueada após várias tentativas de autenticação sem sucesso',- 'This security notification concerns your Sync-in account. Please contact an administrator to perform the analysis and unlock your account.':- 'Esta notificação de segurança diz respeito à sua conta Sync-in. Contacte um administrador para proceder à análise e desbloquear a sua conta.',+ 'Your account is temporarily locked for 15 minutes due to too many failed sign-in attempts':+ 'A sua conta está temporariamente bloqueada durante 15 minutos devido a demasiadas tentativas de início de sessão sem sucesso',+ 'You can try signing in again after 15 minutes. If you did not make these attempts, please contact your administrator.':+ 'Pode tentar iniciar sessão novamente após 15 minutos. Se não efetuou estas tentativas, contacte o seu administrador.','Two-factor authentication (2FA) on your account has been disabled': 'A autenticação de dois fatores (2FA) na sua conta foi desativada','Two-factor authentication (2FA) on your account has been enabled': 'A autenticação de dois fatores (2FA) na sua conta foi ativada','You received this notification because the security of your Sync-in account has changed. If you think this was a mistake, please review your security settings or contact your administrator.':diff --git a/backend/src/applications/notifications/i18n/pt_br.ts b/backend/src/applications/notifications/i18n/pt_br.tsindex 6f3b66fd..5de4a224 100644--- a/backend/src/applications/notifications/i18n/pt_br.ts+++ b/backend/src/applications/notifications/i18n/pt_br.ts@@ -32,10 +32,10 @@ export const pt_BR = {'You receive this notification because you have a lock on this file.': 'Você recebe esta notificação porque você tem um bloqueio neste arquivo.','sends you a request to unlock the file': 'lhe envia uma solicitação para desbloquear o arquivo','Security notification': 'Notificação de segurança',- 'Your account has been locked after several unsuccessful authentication attempts':- 'Sua conta foi bloqueada após várias tentativas de autenticação sem sucesso',- 'This security notification concerns your Sync-in account. Please contact an administrator to perform the analysis and unlock your account.':- 'Esta notificação de segurança diz respeito à sua conta Sync-in. Entre em contato com um administrador para realizar a análise e desbloquear sua conta.',+ 'Your account is temporarily locked for 15 minutes due to too many failed sign-in attempts':+ 'Sua conta está temporariamente bloqueada por 15 minutos devido a muitas tentativas de login malsucedidas',+ 'You can try signing in again after 15 minutes. If you did not make these attempts, please contact your administrator.':+ 'Você pode tentar entrar novamente após 15 minutos. Se não realizou essas tentativas, entre em contato com o administrador.','Two-factor authentication (2FA) on your account has been disabled': 'A autenticação de dois fatores (2FA) na sua conta foi desativada','Two-factor authentication (2FA) on your account has been enabled': 'A autenticação de dois fatores (2FA) na sua conta foi ativada','You received this notification because the security of your Sync-in account has changed. If you think this was a mistake, please review your security settings or contact your administrator.':diff --git a/backend/src/applications/notifications/i18n/ru.ts b/backend/src/applications/notifications/i18n/ru.tsindex 2eaf6bd5..1ce0443a 100644--- a/backend/src/applications/notifications/i18n/ru.ts+++ b/backend/src/applications/notifications/i18n/ru.ts@@ -33,10 +33,10 @@ export const ru = {'Вы получили это уведомление, потому что у вас есть блокировка на этом файле.','sends you a request to unlock the file': 'отправляет вам запрос на разблокировку файла','Security notification': 'Уведомление безопасности',- 'Your account has been locked after several unsuccessful authentication attempts':- 'Ваш аккаунт был заблокирован после нескольких неудачных попыток входа',- 'This security notification concerns your Sync-in account. Please contact an administrator to perform the analysis and unlock your account.':- 'Это уведомление касается вашего аккаунта в Sync-in. Пожалуйста, обратитесь к администратору для анализа и разблокировки аккаунта.',+ 'Your account is temporarily locked for 15 minutes due to too many failed sign-in attempts':+ 'Ваша учетная запись временно заблокирована на 15 минут из-за слишком большого количества неудачных попыток входа',+ 'You can try signing in again after 15 minutes. If you did not make these attempts, please contact your administrator.':+ 'Вы можете повторить попытку входа через 15 минут. Если эти попытки совершали не вы, обратитесь к администратору.','Two-factor authentication (2FA) on your account has been disabled': 'Двухфакторная аутентификация (2FA) для вашего аккаунта была отключена','Two-factor authentication (2FA) on your account has been enabled': 'Двухфакторная аутентификация (2FA) для вашего аккаунта была включена','You received this notification because the security of your Sync-in account has changed. If you think this was a mistake, please review your security settings or contact your administrator.':diff --git a/backend/src/applications/notifications/i18n/tr.ts b/backend/src/applications/notifications/i18n/tr.tsindex 97a36209..66224185 100644--- a/backend/src/applications/notifications/i18n/tr.ts+++ b/backend/src/applications/notifications/i18n/tr.ts@@ -32,10 +32,10 @@ export const tr = {'You receive this notification because you have a lock on this file.': 'Bu dosya üzerinde bir kilidiniz olduğu için bu bildirimi alıyorsunuz.','sends you a request to unlock the file': 'size dosyanın kilidini açma talebi gönderiyor','Security notification': 'Güvenlik bildirimi',- 'Your account has been locked after several unsuccessful authentication attempts':- 'Birkaç başarısız kimlik doğrulama girişiminden sonra hesabınız kilitlendi',- 'This security notification concerns your Sync-in account. Please contact an administrator to perform the analysis and unlock your account.':- 'Bu güvenlik bildirimi, Sync-in hesabınızla ilgilidir. Analiz yapılması ve hesabınızın kilidinin açılması için lütfen bir yöneticiyle iletişime geçin.',+ 'Your account is temporarily locked for 15 minutes due to too many failed sign-in attempts':+ 'Çok fazla başarısız oturum açma denemesi nedeniyle hesabınız geçici olarak 15 dakika kilitlendi',+ 'You can try signing in again after 15 minutes. If you did not make these attempts, please contact your administrator.':+ '15 dakika sonra tekrar oturum açmayı deneyebilirsiniz. Bu denemeleri siz yapmadıysanız yöneticinizle iletişime geçin.','Two-factor authentication (2FA) on your account has been disabled': 'Hesabınızda iki faktörlü kimlik doğrulama (2FA) devre dışı bırakıldı','Two-factor authentication (2FA) on your account has been enabled': 'Hesabınızda iki faktörlü kimlik doğrulama (2FA) etkinleştirildi','You received this notification because the security of your Sync-in account has changed. If you think this was a mistake, please review your security settings or contact your administrator.':diff --git a/backend/src/applications/notifications/i18n/zh.ts b/backend/src/applications/notifications/i18n/zh.tsindex 15cc8594..c29f7577 100644--- a/backend/src/applications/notifications/i18n/zh.ts+++ b/backend/src/applications/notifications/i18n/zh.ts@@ -31,9 +31,9 @@ export const zh = {'You receive this notification because you have a lock on this file.': '您收到此通知是因为您对该文件设置了锁。','sends you a request to unlock the file': '向您发送了解锁该文件的请求','Security notification': '安全通知',- 'Your account has been locked after several unsuccessful authentication attempts': '在多次身份验证失败后,您的账户已被锁定',- 'This security notification concerns your Sync-in account. Please contact an administrator to perform the analysis and unlock your account.':- '此安全通知与您的 Sync-in 账户相关。请联系管理员进行分析并解锁您的账户。',+ 'Your account is temporarily locked for 15 minutes due to too many failed sign-in attempts': '您的账户因登录失败次数过多而被暂时锁定 15 分钟',+ 'You can try signing in again after 15 minutes. If you did not make these attempts, please contact your administrator.':+ '您可以在 15 分钟后再次尝试登录。如果这些尝试并非由您发起,请联系您的管理员。','Two-factor authentication (2FA) on your account has been disabled': '您账户的双重身份验证 (2FA) 已被禁用','Two-factor authentication (2FA) on your account has been enabled': '您账户的双重身份验证 (2FA) 已被启用','You received this notification because the security of your Sync-in account has changed. If you think this was a mistake, please review your security settings or contact your administrator.':diff --git a/backend/src/applications/notifications/mails/models.ts b/backend/src/applications/notifications/mails/models.tsindex 328530a9..6bb14743 100644--- a/backend/src/applications/notifications/mails/models.ts+++ b/backend/src/applications/notifications/mails/models.ts@@ -191,8 +191,7 @@ export function auth2FaMail(language: i18nLocale, notification: NotificationContexport function authLockedMail(language: i18nLocale, notification: NotificationContent): [string, string] {const tr = translateObject(language, {title: 'Security notification',- footer:- 'This security notification concerns your Sync-in account. Please contact an administrator to perform the analysis and unlock your account.',+ footer: 'You can try signing in again after 15 minutes. If you did not make these attempts, please contact your administrator.',event: notification.event,addressIp: 'Address IP'})diff --git a/backend/src/applications/users/constants/user.ts b/backend/src/applications/users/constants/user.tsindex 448bdf58..181b66e6 100644--- a/backend/src/applications/users/constants/user.ts+++ b/backend/src/applications/users/constants/user.ts@@ -1,5 +1,6 @@export const USER_PASSWORD_MIN_LENGTH = 8export const USER_MAX_PASSWORD_ATTEMPTS = 10+export const USER_PASSWORD_ATTEMPTS_LOCK_DURATION_MS = 15 * 60_000export const USER_LOGIN_VALIDATION = /^(?! )(?!.* $)[a-zA-Z0-9@\-._ ]{2,255}$/export const USER_TMP_DIRECTORY = 'tmp'diff --git a/backend/src/applications/users/interfaces/user-access-update-result.interface.ts b/backend/src/applications/users/interfaces/user-access-update-result.interface.tsnew file mode 100644index 00000000..8499e086--- /dev/null+++ b/backend/src/applications/users/interfaces/user-access-update-result.interface.ts@@ -0,0 +1,4 @@+export interface UserAccessUpdateResult {+ success: boolean+ temporaryLockStarted: boolean+}diff --git a/backend/src/applications/users/services/users-manager.service.spec.ts b/backend/src/applications/users/services/users-manager.service.spec.tsindex 0d737997..fea3e43f 100755--- a/backend/src/applications/users/services/users-manager.service.spec.ts+++ b/backend/src/applications/users/services/users-manager.service.spec.ts@@ -1,7 +1,7 @@import { HttpStatus } from '@nestjs/common'import { Test, TestingModule } from '@nestjs/testing'import bcrypt from 'bcryptjs'-import { SQL } from 'drizzle-orm'+import { MySqlDialect } from 'drizzle-orm/mysql-core'import fs from 'node:fs/promises'import os from 'node:os'import path from 'node:path'@@ -20,7 +20,7 @@ import { fileName, isPathExists } from '../../files/utils/files'import { NotificationsManager } from '../../notifications/services/notifications-manager.service'import { GROUP_TYPE } from '../constants/group'import { MEMBER_TYPE } from '../constants/member'-import { USER_GROUP_ROLE, USER_MAX_PASSWORD_ATTEMPTS, USER_PERMISSION, USER_ROLE } from '../constants/user'+import { USER_GROUP_ROLE, USER_MAX_PASSWORD_ATTEMPTS, USER_PASSWORD_ATTEMPTS_LOCK_DURATION_MS, USER_PERMISSION, USER_ROLE } from '../constants/user'import { CreateUserDto } from '../dto/create-or-update-user.dto'import { DeleteUserDto } from '../dto/delete-user.dto'import { UserSecrets } from '../interfaces/user-secrets.interface'@@ -93,10 +93,6 @@ describe(UsersManager.name, () => {return () => currentSecrets}- const notificationsManager = {- sendEmailNotification: vi.fn().mockResolvedValue(undefined)- }-beforeAll(async () => {testDataPath = await fs.mkdtemp(path.join(os.tmpdir(), 'sync-in-users-manager-spec-'))configuration.applications.files.dataPath = testDataPath@@ -114,8 +110,8 @@ describe(UsersManager.name, () => {provide: FilesQuotaManager,useValue: { updateStorageQuota: () => vi.fn() }},- { provide: NotificationsManager, useValue: notificationsManager },{ provide: AuthManager, useValue: {} },+ { provide: NotificationsManager, useValue: { sendEmailNotification: vi.fn().mockResolvedValue(undefined) } },{ provide: DB_TOKEN_PROVIDER, useValue: {} },{ provide: Cache, useValue: {} }]@@ -188,7 +184,8 @@ describe(UsersManager.name, () => {...generateUserTest(),id: 42,role: USER_ROLE.USER,- permissions: USER_PERMISSION.SPACES+ permissions: USER_PERMISSION.SPACES,+ passwordAttempts: USER_MAX_PASSWORD_ATTEMPTS}usersQueriesService.from = vi.fn().mockResolvedValue(currentUser)@@ -212,7 +209,7 @@ describe(UsersManager.name, () => {impersonatedClientId: 'admin-client'} as any)const currentUser = { ...generateUserTest(), id: 42 }- const admin = { ...generateUserTest(), id: 1, role: USER_ROLE.ADMINISTRATOR }+ const admin = { ...generateUserTest(), id: 1, role: USER_ROLE.ADMINISTRATOR, passwordAttempts: USER_MAX_PASSWORD_ATTEMPTS }usersQueriesService.from = vi.fn().mockImplementation(async (id: number) => (id === authUser.id ? currentUser : admin))const resolved = await usersManager.fromAuthToken(authUser)@@ -277,30 +274,68 @@ describe(UsersManager.name, () => {const uLocked = new UserModel({ ...generateUserTest(), isActive: false, passwordAttempts: 5 }, false)const errSpy = vi.spyOn((usersManager as any)['logger'], 'error').mockImplementation(() => undefined as any)- const updSpy1 = vi.spyOn(usersManager, 'updateAccesses').mockRejectedValue(new Error('reject-locked'))+ const updateAccessesSpy = vi.spyOn(usersManager, 'updateAccesses').mockResolvedValue(undefined)await expect(usersManager.logUser(uLocked, 'pwd', 'ip')).rejects.toThrow('Account locked')- await flush()- expect(errSpy.mock.calls.some(([payload]: { msg: string }[]) => payload?.msg?.includes('reject-locked'))).toBe(true)- expect(updSpy1).toHaveBeenCalledWith(uLocked, 'ip', false)+ expect(updateAccessesSpy).not.toHaveBeenCalled()vi.mocked(comparePassword).mockResolvedValue(false)const uBad = new UserModel({ ...generateUserTest(), isActive: true, passwordAttempts: 0 }, false)- const errSpy2 = vi.spyOn((usersManager as any)['logger'], 'error').mockImplementation(() => undefined as any)- const updSpy2 = vi.spyOn(usersManager, 'updateAccesses').mockRejectedValue(new Error('reject-auth'))+ updateAccessesSpy.mockRejectedValueOnce(new Error('reject-auth'))const out = await usersManager.logUser(uBad, 'bad', '1.1.1.1')expect(out).toBeNull()await flush()- expect(errSpy2.mock.calls.some(([payload]: { msg: string }[]) => payload?.msg?.includes('reject-auth'))).toBe(true)- expect(updSpy2).toHaveBeenCalledWith(uBad, '1.1.1.1', false)+ expect(errSpy.mock.calls.some(([payload]: { msg: string }[]) => payload?.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)- const updSpy3 = vi.spyOn(usersManager, 'updateAccesses').mockResolvedValue(undefined)+ updateAccessesSpy.mockResolvedValue(undefined)const pathsSpy = vi.spyOn(uGood, 'makePaths').mockResolvedValue(undefined)const out2 = await usersManager.logUser(uGood, 'good', '8.8.8.8')expect(out2).toBe(uGood)- expect(updSpy3).toHaveBeenCalledWith(uGood, '8.8.8.8', true)+ expect(updateAccessesSpy).toHaveBeenCalledWith(uGood, '8.8.8.8', true)expect(pathsSpy).toHaveBeenCalled()})+ it('should release an expired password lock without extending an active lock', async () => {+ const now = new Date('2026-09-08T12:00:00.000Z').getTime()+ vi.spyOn(Date, 'now').mockReturnValue(now)+ vi.mocked(comparePassword).mockClear()+ vi.mocked(comparePassword).mockResolvedValue(true)+ const resetSpy = vi.spyOn(usersQueriesService, 'resetExpiredPasswordAttempts').mockResolvedValue(true)+ const updateAccessesSpy = vi.spyOn(usersManager, 'updateAccesses').mockResolvedValue(undefined)++ const activeLockDate = new Date(now - USER_PASSWORD_ATTEMPTS_LOCK_DURATION_MS + 1)+ const temporarilyLockedUser = new UserModel(+ { ...generateUserTest(), isActive: true, passwordAttempts: USER_MAX_PASSWORD_ATTEMPTS, currentAccess: activeLockDate },+ false+ )+ await expect(usersManager.logUser(temporarilyLockedUser, 'password', '127.0.0.1')).rejects.toThrow('Account locked')+ expect(temporarilyLockedUser.currentAccess).toEqual(activeLockDate)+ expect(resetSpy).not.toHaveBeenCalled()+ expect(updateAccessesSpy).not.toHaveBeenCalled()+ expect(comparePassword).not.toHaveBeenCalled()++ const expiredLockDate = new Date(now - USER_PASSWORD_ATTEMPTS_LOCK_DURATION_MS)+ const expiredLockUser = new UserModel(+ { ...generateUserTest(), isActive: true, passwordAttempts: USER_MAX_PASSWORD_ATTEMPTS, currentAccess: expiredLockDate },+ false+ )+ vi.spyOn(expiredLockUser, 'makePaths').mockResolvedValue(undefined)++ await expect(usersManager.logUser(expiredLockUser, 'password', '127.0.0.1')).resolves.toBe(expiredLockUser)+ expect(resetSpy).toHaveBeenCalledWith(expiredLockUser.id, expiredLockDate)+ expect(expiredLockUser.passwordAttempts).toBe(0)+ expect(updateAccessesSpy).toHaveBeenCalledWith(expiredLockUser, '127.0.0.1', true)++ vi.mocked(comparePassword).mockClear()+ resetSpy.mockResolvedValueOnce(false)+ const concurrentlyUpdatedUser = new UserModel(+ { ...generateUserTest(), isActive: true, passwordAttempts: USER_MAX_PASSWORD_ATTEMPTS, currentAccess: expiredLockDate },+ false+ )+ await expect(usersManager.logUser(concurrentlyUpdatedUser, 'password', '127.0.0.1')).rejects.toThrow('Account locked')+ expect(comparePassword).not.toHaveBeenCalled()+ })+it('local password validation burns time when user is missing or rejected by policy', async () => {vi.mocked(comparePassword).mockResolvedValue(false)usersQueriesService.from = vi.fn().mockResolvedValue(null)@@ -554,7 +589,7 @@ describe(UsersManager.name, () => {await expect(usersManager.updateNotification(userTest, { notification: 2 })).resolves.toBeUndefined()const u1 = new UserModel({ ...generateUserTest(), isActive: true, passwordAttempts: 3 } as any, false)- usersQueriesService.updateAccesses = vi.fn().mockResolvedValue(true)+ usersQueriesService.updateAccesses = vi.fn().mockResolvedValue({ success: true, temporaryLockStarted: false })await expect(usersManager.updateAccesses(u1, '5.6.7.8', true)).resolves.toBeUndefined()expect(usersQueriesService.updateAccesses).toHaveBeenCalledWith(u1.id, '5.6.7.8', 'reset')@@ -566,7 +601,7 @@ describe(UsersManager.name, () => {} as any,false)- usersQueriesService.updateAccesses = vi.fn().mockResolvedValue(true)+ usersQueriesService.updateAccesses = vi.fn().mockResolvedValue({ success: true, temporaryLockStarted: false })await expect(usersManager.updateAccesses(u2, 'new.ip', false)).resolves.toBeUndefined()expect(usersQueriesService.updateAccesses).toHaveBeenCalledWith(u2.id, 'new.ip', 'increment')@@ -576,30 +611,78 @@ describe(UsersManager.name, () => {await expect(usersManager.updateAccesses(u3, 'new.ip', false)).resolves.toBeUndefined()expect(usersQueriesService.updateAccesses).toHaveBeenCalledWith(u3.id, 'new.ip', 'increment')- usersQueriesService.updateAccesses = vi.fn().mockResolvedValue(false)+ usersQueriesService.updateAccesses = vi.fn().mockResolvedValue({ success: false, temporaryLockStarted: false })await expect(usersManager.updateAccesses(u1, 'new.ip', false)).rejects.toThrow('Unable to update user accesses')})- it('should update password attempts atomically', async () => {+ it('should update access history and password attempts atomically', async () => {+ const execute = vi.fn().mockResolvedValue([{ affectedRows: 1 }])+ const lock = vi+ .fn()+ .mockResolvedValueOnce([{ passwordAttempts: USER_MAX_PASSWORD_ATTEMPTS - 1 }])+ .mockResolvedValueOnce([{ passwordAttempts: USER_MAX_PASSWORD_ATTEMPTS }])+ const selectLimit = vi.fn().mockReturnValue({ for: lock })+ const selectWhere = vi.fn().mockReturnValue({ limit: selectLimit })+ const from = vi.fn().mockReturnValue({ where: selectWhere })+ const select = vi.fn().mockReturnValue({ from })const where = vi.fn().mockResolvedValue([{ affectedRows: 1 }])const set = vi.fn().mockReturnValue({ where })const update = vi.fn().mockReturnValue({ set })- const usersQueries = new UsersQueries({ update } as any, {} as Cache)-- await expect(usersQueries.updateAccesses(userTest.id, '127.0.0.1', 'increment')).resolves.toBe(true)- const increment = set.mock.calls[0][0]- expect(increment.isActive).toBeInstanceOf(SQL)- expect(increment.passwordAttempts).toBeInstanceOf(SQL)-- await expect(usersQueries.updateAccesses(userTest.id, '127.0.0.1', 'reset')).resolves.toBe(true)- const reset = set.mock.calls[1][0]- expect(reset.passwordAttempts).toBe(0)- expect(reset.isActive).toBeUndefined()-- await expect(usersQueries.updateAccesses(userTest.id, '127.0.0.1', 'preserve')).resolves.toBe(true)- const preserve = set.mock.calls[2][0]- expect(preserve.passwordAttempts).toBeUndefined()- expect(preserve.isActive).toBeUndefined()+ const transaction = vi.fn().mockImplementation(async (callback) => callback({ select, execute }))+ const usersQueries = new UsersQueries({ execute, update, transaction } as any, {} as Cache)+ const dialect = new MySqlDialect()++ await expect(usersQueries.updateAccesses(userTest.id, '127.0.0.1', 'increment')).resolves.toEqual({+ success: true,+ temporaryLockStarted: true+ })+ expect(lock).toHaveBeenCalledWith('update')+ const increment = dialect.sqlToQuery(execute.mock.calls[0][0])+ const incrementSql = increment.sql.replace(/\s+/g, ' ')+ const lastAccessAssignment = incrementSql.indexOf('`lastAccess` = `users`.`currentAccess`')+ const currentAccessAssignment = incrementSql.indexOf('`currentAccess` = ?')+ const lastIpAssignment = incrementSql.indexOf('`lastIp` = `users`.`currentIp`')+ const currentIpAssignment = incrementSql.indexOf('`currentIp` = ?')+ expect(lastAccessAssignment).toBeGreaterThanOrEqual(0)+ expect(currentAccessAssignment).toBeGreaterThanOrEqual(0)+ expect(lastAccessAssignment).toBeLessThan(currentAccessAssignment)+ expect(lastIpAssignment).toBeGreaterThanOrEqual(0)+ expect(currentIpAssignment).toBeGreaterThanOrEqual(0)+ expect(lastIpAssignment).toBeLessThan(currentIpAssignment)+ expect(incrementSql).toContain('`passwordAttempts` = LEAST(`users`.`passwordAttempts` + 1, ?)')++ await expect(usersQueries.updateAccesses(userTest.id, '127.0.0.1', 'reset')).resolves.toEqual({+ success: true,+ temporaryLockStarted: false+ })+ const reset = dialect.sqlToQuery(execute.mock.calls[1][0])+ expect(reset.sql).toContain('`passwordAttempts` = ?')+ expect(reset.params).toContain(0)++ await expect(usersQueries.updateAccesses(userTest.id, '127.0.0.1', 'preserve')).resolves.toEqual({+ success: true,+ temporaryLockStarted: false+ })+ const preserve = dialect.sqlToQuery(execute.mock.calls[2][0])+ expect(preserve.sql).not.toContain('`passwordAttempts` =')+ expect(increment.sql).not.toContain('`isActive` =')+ expect(reset.sql).not.toContain('`isActive` =')+ expect(preserve.sql).not.toContain('`isActive` =')++ await expect(usersQueries.updateAccesses(userTest.id, '127.0.0.1', 'increment')).resolves.toEqual({+ success: true,+ temporaryLockStarted: false+ })+ expect(execute).toHaveBeenCalledTimes(3)++ const expiredBefore = new Date('2026-09-08T12:00:00.000Z')+ await expect(usersQueries.resetExpiredPasswordAttempts(userTest.id, expiredBefore)).resolves.toBe(true)+ const expiredReset = set.mock.calls[0][0]+ expect(expiredReset.passwordAttempts).toBe(0)+ expect(expiredReset.currentAccess).toBeUndefined()++ where.mockResolvedValueOnce([{ affectedRows: 0 }])+ await expect(usersQueries.resetExpiredPasswordAttempts(userTest.id, expiredBefore)).resolves.toBe(false)})it('should lock the user row while mutating secrets', async () => {diff --git a/backend/src/applications/users/services/users-manager.service.ts b/backend/src/applications/users/services/users-manager.service.tsindex 3b6a2860..ec1aa85b 100755--- a/backend/src/applications/users/services/users-manager.service.ts+++ b/backend/src/applications/users/services/users-manager.service.ts@@ -11,7 +11,6 @@ import { LoginResponseDto } from '../../../authentication/dto/login-response.dtoimport { FastifyAuthenticatedRequest } from '../../../authentication/interfaces/auth-request.interface'import { JwtIdentityPayload } from '../../../authentication/interfaces/jwt-payload.interface'import { AUTH_SESSION } from '../../../authentication/providers/auth-providers.constants'-import { ACTION } from '../../../common/constants'import { comparePassword, hashPassword } from '../../../common/functions'import { convertTempImageToPng, generateAvatar, imgMimeTypePrefix, pngMimeType, svgMimeType } from '../../../common/image'import { createLightSlug, genPassword } from '../../../common/shared'@@ -19,10 +18,17 @@ import { configuration, serverConfig } from '../../../configuration/config.envirimport { Cache } from '../../../infrastructure/cache/cache.service'import { isPathExists, removeFiles, sanitizeName, temporaryFilePath } from '../../files/utils/files'import { NOTIFICATION_APP, NOTIFICATION_APP_EVENT } from '../../notifications/constants/notifications'+import type { NotificationContent } from '../../notifications/interfaces/notification-properties.interface'import { NotificationsManager } from '../../notifications/services/notifications-manager.service'import { GROUP_TYPE } from '../constants/group'import { MEMBER_TYPE } from '../constants/member'-import { USER_GROUP_ROLE, USER_MAX_PASSWORD_ATTEMPTS, USER_ONLINE_STATUS, USER_ROLE } from '../constants/user'+import {+ USER_GROUP_ROLE,+ USER_MAX_PASSWORD_ATTEMPTS,+ USER_ONLINE_STATUS,+ USER_PASSWORD_ATTEMPTS_LOCK_DURATION_MS,+ USER_ROLE+} from '../constants/user'import type { UserCreateOrUpdateGroupDto } from '../dto/create-or-update-group.dto'import type { CreateUserDto, UpdateUserDto, UpdateUserFromGroupDto } from '../dto/create-or-update-user.dto'import type { SearchMembersDto } from '../dto/search-members.dto'@@ -65,12 +71,12 @@ export class UsersManager {async fromAuthToken(authUser: UserModel): Promise<UserModel | null> {const user = await this.fromUserId(authUser.id)- if (!user?.isActive || user.passwordAttempts >= USER_MAX_PASSWORD_ATTEMPTS) {+ if (!user?.isActive) {return null}if (authUser.impersonatedFromId) {const impersonatingUser = await this.fromUserId(authUser.impersonatedFromId)- if (!impersonatingUser?.isActive || !impersonatingUser.isAdmin || impersonatingUser.passwordAttempts >= USER_MAX_PASSWORD_ATTEMPTS) {+ if (!impersonatingUser?.isActive || !impersonatingUser.isAdmin) {return null}user.impersonatedFromId = authUser.impersonatedFromId@@ -136,7 +142,7 @@ export class UsersManager {}async logUser(user: UserModel, password: string, ip: string, scope?: AUTH_SCOPE): Promise<UserModel | null> {- this.validateUserAccess(user, ip)+ await this.validateUserAccess(user)const webDAVRequiresAppPassword = scope === AUTH_SCOPE.WEBDAV && configuration.auth.mfa.totp.enabled && user.twoFaEnabled// Keep the primary-password bcrypt path for scoped auth timing, but never accept it for 2FA WebDAV.const primaryPasswordMatches: boolean = await comparePassword(password, user.password)@@ -153,19 +159,33 @@ export class UsersManager {return null}- validateUserAccess(user: UserModel, ip: string) {+ async validateUserAccess(user: UserModel): Promise<void> {if (user.role === USER_ROLE.LINK) {this.logger.error({ tag: this.validateUserAccess.name, msg: `guest link account ${user} is not authorized to login` })throw new HttpException('Account is not allowed', HttpStatus.FORBIDDEN)}- if (!user.isActive || user.passwordAttempts >= USER_MAX_PASSWORD_ATTEMPTS) {- this.updateAccesses(user, ip, false).catch((e: Error) => this.logger.error({ tag: this.validateUserAccess.name, msg: `${e}` }))+ if (!user.isActive) {this.logger.error({ tag: this.validateUserAccess.name, msg: `user account *${user.login}* is locked` })- if (user.isActive) {- this.notifyAccountLocked(user, ip)- }throw new HttpException('Account locked', HttpStatus.FORBIDDEN)}+ await this.validatePasswordAttempts(user)+ }++ async validatePasswordAttempts(user: UserModel): Promise<void> {+ if ((user.passwordAttempts ?? 0) < USER_MAX_PASSWORD_ATTEMPTS) return++ const now = Date.now()+ const lastAttemptAt = user.currentAccess?.getTime() ?? Number.NaN+ if (Number.isFinite(lastAttemptAt) && lastAttemptAt + USER_PASSWORD_ATTEMPTS_LOCK_DURATION_MS > now) {+ this.logger.error({ tag: this.validatePasswordAttempts.name, msg: `user account *${user.login}* is temporarily locked` })+ throw new HttpException('Account locked', HttpStatus.FORBIDDEN)+ }++ const expiredBefore = new Date(now - USER_PASSWORD_ATTEMPTS_LOCK_DURATION_MS)+ if (!(await this.usersQueries.resetExpiredPasswordAttempts(user.id, expiredBefore))) {+ throw new HttpException('Account locked', HttpStatus.FORBIDDEN)+ }+ user.passwordAttempts = 0}async me(authUser: UserModel): Promise<Omit<LoginResponseDto, 'token'>> {@@ -276,9 +296,13 @@ export class UsersManager {async updateAccesses(user: UserModel, ip: string, success: boolean, isAuthTwoFa = false) {const preservePasswordAttempts = success && !isAuthTwoFa && configuration.auth.mfa.totp.enabled && user.twoFaEnabled- if (!(await this.usersQueries.updateAccesses(user.id, ip, preservePasswordAttempts ? 'preserve' : success ? 'reset' : 'increment'))) {+ const result = await this.usersQueries.updateAccesses(user.id, ip, preservePasswordAttempts ? 'preserve' : success ? 'reset' : 'increment')+ if (!result.success) {throw new Error('Unable to update user accesses')}+ if (result.temporaryLockStarted) {+ this.notifyTemporaryAccountLock(user, ip)+ }}async getAvatar(userLogin: string, generate: true, generateIsNotExists?: boolean): Promise<undefined>@@ -687,14 +711,15 @@ export class UsersManager {}}- private notifyAccountLocked(user: UserModel, ip: string) {+ private notifyTemporaryAccountLock(user: UserModel, ip: string): void {+ const notification = {+ app: NOTIFICATION_APP.AUTH_LOCKED,+ event: NOTIFICATION_APP_EVENT.AUTH_LOCKED,+ element: '',+ url: ip+ } satisfies NotificationContentthis.notificationsManager- .sendEmailNotification([user], {- app: NOTIFICATION_APP.AUTH_LOCKED,- event: NOTIFICATION_APP_EVENT.AUTH_LOCKED[ACTION.DELETE],- element: null,- url: ip- })- .catch((e: Error) => this.logger.error({ tag: this.notifyAccountLocked.name, msg: `${e}` }))+ .sendEmailNotification([user], notification)+ .catch((e: Error) => this.logger.error({ tag: this.notifyTemporaryAccountLock.name, msg: `${e}` }))}}diff --git a/backend/src/applications/users/services/users-queries.service.ts b/backend/src/applications/users/services/users-queries.service.tsindex 72db605c..656347d8 100644--- a/backend/src/applications/users/services/users-queries.service.ts+++ b/backend/src/applications/users/services/users-queries.service.ts@@ -1,5 +1,5 @@import { Inject, Injectable, Logger } from '@nestjs/common'-import { and, countDistinct, desc, eq, 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, SelectedFields, SQL, sql } from 'drizzle-orm'import { alias } from 'drizzle-orm/mysql-core'import { MySql2PreparedQuery, MySqlQueryResult } from 'drizzle-orm/mysql2'import { anonymizePassword, comparePassword, uniquePermissions } from '../../../common/functions'@@ -25,6 +25,7 @@ import { SearchMembersDto } from '../dto/search-members.dto'import { GroupMember, GroupWithMembers } from '../interfaces/group-member'import { GuestUser } from '../interfaces/guest-user.interface'import { Member } from '../interfaces/member.interface'+import type { UserAccessUpdateResult } from '../interfaces/user-access-update-result.interface'import { UserSecrets } from '../interfaces/user-secrets.interface'import { UserOnline } from '../interfaces/websocket.interface'import { UserModel } from '../models/user.model'@@ -267,26 +268,77 @@ export class UsersQueries {}}- async updateAccesses(userId: number, ip: string, passwordAttempts: 'preserve' | 'reset' | 'increment'): Promise<boolean> {- const set: Partial<Record<keyof User, any>> = {- lastAccess: users.currentAccess,- currentAccess: new Date(),- lastIp: users.currentIp,- currentIp: ip- }- if (passwordAttempts === 'reset') {- set.passwordAttempts = 0- } else if (passwordAttempts === 'increment') {- // Keep the increment and account lock in one UPDATE to avoid lost updates under concurrent authentication failures.- set.isActive = sql`IF(${users.passwordAttempts} >= ${USER_MAX_PASSWORD_ATTEMPTS - 1}, FALSE, ${users.isActive})`- set.passwordAttempts = sql`LEAST(${users.passwordAttempts} + 1, ${USER_MAX_PASSWORD_ATTEMPTS})`- }+ async updateAccesses(userId: number, ip: string, attemptsAction: 'preserve' | 'reset' | 'increment'): Promise<UserAccessUpdateResult> {+ const passwordAttemptsUpdate =+ attemptsAction === 'reset'+ ? sql`, ${sql.identifier(users.passwordAttempts.name)} = ${sql.param(0, users.passwordAttempts)}`+ : attemptsAction === 'increment'+ ? sql`, ${sql.identifier(users.passwordAttempts.name)} = LEAST(${users.passwordAttempts} + 1, ${USER_MAX_PASSWORD_ATTEMPTS})`+ : sql``+ const updateAccessesQuery = () => sql`+ UPDATE ${users}+ SET ${sql.identifier(users.lastAccess.name)} = ${users.currentAccess},+ ${sql.identifier(users.currentAccess.name)} = ${sql.param(new Date(), users.currentAccess)},+ ${sql.identifier(users.lastIp.name)} = ${users.currentIp},+ ${sql.identifier(users.currentIp.name)} = ${sql.param(ip, users.currentIp)} ${passwordAttemptsUpdate}+ WHERE ${users.id} = ${userId}+ `try {- dbCheckAffectedRows(await this.db.update(users).set(set).where(eq(users.id, userId)), 1)+ // Drizzle orders UPDATE assignments by schema order.+ // Keep each previous value assignment first because MariaDB evaluates them left-to-right.+ let temporaryLockStarted = false+ if (attemptsAction === 'increment') {+ // Serialize failures so only one request can report the transition to a temporary lock.+ temporaryLockStarted = await this.db.transaction(async (tx) => {+ const [user]: Pick<User, 'passwordAttempts'>[] = await tx+ .select({ passwordAttempts: users.passwordAttempts })+ .from(users)+ .where(eq(users.id, userId))+ .limit(1)+ .for('update')+ if (!user) {+ throw new Error(`User (${userId}) not found`)+ }+ const currentPasswordAttempts = user.passwordAttempts ?? 0+ if (currentPasswordAttempts >= USER_MAX_PASSWORD_ATTEMPTS) {+ // Do not move currentAccess: it is also the start of the temporary lock period.+ return false+ }+ dbCheckAffectedRows(await tx.execute(updateAccessesQuery()), 1)+ return currentPasswordAttempts + 1 >= USER_MAX_PASSWORD_ATTEMPTS+ })+ } else {+ dbCheckAffectedRows(await this.db.execute(updateAccessesQuery()), 1)+ }this.logger.verbose({ tag: this.updateAccesses.name, msg: `accesses for user (${userId}) were updated` })- return true+ return { success: true, temporaryLockStarted }} catch (e) {this.logger.error({ tag: this.updateAccesses.name, msg: `accesses for user (${userId}) were not updated : ${e}` })+ return { success: false, temporaryLockStarted: false }+ }+ }++ async resetExpiredPasswordAttempts(userId: number, expiredBefore: Date): Promise<boolean> {+ try {+ // The conditional update lets concurrent requests release an expired lock without resetting newer failures.+ const result = await this.db+ .update(users)+ .set({ passwordAttempts: 0 })+ .where(+ and(+ eq(users.id, userId),+ gte(users.passwordAttempts, USER_MAX_PASSWORD_ATTEMPTS),+ or(isNull(users.currentAccess), lte(users.currentAccess, expiredBefore))+ )+ )+ if (!dbCheckAffectedRows(result, 1, false)) {+ this.logger.warn({ tag: this.resetExpiredPasswordAttempts.name, msg: `expired password lock for user (${userId}) was not released` })+ return false+ }+ 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}` })return false}}diff --git a/backend/src/applications/users/users.md b/backend/src/applications/users/users.mdindex 363f6f70..6b0d8e1c 100644--- a/backend/src/applications/users/users.md+++ b/backend/src/applications/users/users.md@@ -25,6 +25,44 @@ every authenticated user type. The numeric order is therefore security-sensitive`isLink` match only their exact roles. `USER_GROUP_ROLE` values (`MEMBER` and`MANAGER`) describe membership inside a group and are independent of these user types.+## Account state and password attempts++The persistent account state and the temporary authentication lock are independent controls. Password failures never change `isActive`, and reaching+the password-attempt limit does not suspend the account.++### Persistent account state (`isActive`)++`isActive` is the durable administrative switch for a local user record:++- `isActive: false` is rejected by local password and app-password paths as well as by the LDAP and OIDC provider flows;+- authenticated requests and token refreshes reload the local user record, so disabling the account also invalidates existing sessions;+- the account remains disabled until an administrator reactivates it; there is no automatic expiration;+- reactivating the account resets `passwordAttempts` to zero.++Public-link pseudo-users also use `isActive` as their persistent enabled or disabled state. A disabled pseudo-user cannot authenticate or access its+link.++### Temporary authentication lock++The temporary lock limits repeated checks against an active account without changing `isActive`:++- failed password, app-password, TOTP, or recovery-code checks recorded by the shared access-update path increment `passwordAttempts` up to a maximum+ of 10;+- a successful authentication resets the counter; for a TOTP-enabled login, a successful password step preserves it until the TOTP or recovery-code+ step succeeds;+- the transition from 9 to 10 attempts starts a 15-minute lock. The timestamp written to `currentAccess` by that failed attempt is the lock-period+ anchor;+- while the lock is active, password, app-password, and verification-code checks are rejected before their cryptographic comparison. These rejected+ requests do not update the access history, increment the counter, extend the lock, or send another lock notification;+- expiration is checked lazily on the next authentication attempt. A conditional database update resets the expired counter without clearing newer+ failures from a concurrent request. Only the request that successfully resets the counter continues; a concurrent request based on stale lock data+ fails closed. A new failure after reset counts as the first attempt of a new period;+- the temporary lock does not invalidate access, refresh, or websocket tokens that were issued before the lock.++The counter transition is serialized in the database so concurrent failures cannot lose increments or produce several 9-to-10 transitions. When+email delivery is available, only the request that reaches 10 attempts schedules the temporary-lock security notification. Route-level request+throttling is documented in [`auth.md`](../../authentication/auth.md#authentication-rate-limiting).+## Application permissionsApplication permissions control access to features and protected operations. They are independent from the role hierarchy and from the permissionsdiff --git a/backend/src/applications/users/users.module.ts b/backend/src/applications/users/users.module.tsindex 1a0b678f..74079ed3 100755--- a/backend/src/applications/users/users.module.ts+++ b/backend/src/applications/users/users.module.ts@@ -1,4 +1,5 @@import { Global, Module } from '@nestjs/common'+import { NotificationsModule } from '../notifications/notifications.module'import { AdminUsersController } from './admin-users.controller'import { UserPermissionsGuard } from './guards/permissions.guard'import { UserRolesGuard } from './guards/roles.guard'@@ -11,6 +12,7 @@ import { WebSocketUsers } from './users.gateway'@Global()@Module({+ imports: [NotificationsModule],controllers: [UsersController, AdminUsersController],providers: [WebSocketUsers, UserRolesGuard, UserPermissionsGuard, UsersManager, UsersQueries, AdminUsersManager, AdminUsersQueries],exports: [UsersManager, UsersQueries, AdminUsersManager, AdminUsersQueries]diff --git a/backend/src/authentication/auth.md b/backend/src/authentication/auth.mdindex 333be2da..87e31baa 100644--- a/backend/src/authentication/auth.md+++ b/backend/src/authentication/auth.md@@ -163,10 +163,22 @@ local password access or password-fallback step-up. Users authenticated throughreset, and disable flows still verify the local Sync-in password. Administrator accounts should have a local Sync-in password configured and keptavailable for break-glass recovery. See `providers/oidc/oidc.md`.-## Access updates and password attempts+## Authentication rate limiting-Authentication success and failure update the user's access metadata asynchronously. Failed password or code checks increment password attempts. A-successful password step for a TOTP-enabled user preserves password attempts until the TOTP verification step succeeds; the final 2FA success resets-the attempt counter.+Sensitive authentication and verification routes explicitly use `AuthRateLimitGuard`. The guard is selective rather than global: an unguarded route+does not inherit this policy merely because it belongs to the authentication module.-Accounts that are inactive or have reached the maximum password attempts are rejected before password or app-password validation.+The default policy allows six requests for the same route and client IP in a rolling 60-second window. Every request that reaches the guard counts,+regardless of its authentication outcome. The next request starts a 60-second block and returns HTTP `429` with+`Too many requests. Please try again later.` Requests received during that block do not extend it. Rate-limit response headers expose the configured+limit, remaining requests, reset delay, and block retry delay. Individual routes can override the default policy when their traffic profile requires+another limit.++Nest builds each limiter key from the controller handler, throttler name, and `req.ip`, which keeps counters separate between routes and clients. The+client address therefore follows Fastify's `server.trustProxy` configuration. Limiter state is updated atomically in the configured shared cache,+whether the cache adapter is MySQL or Redis, so concurrent server workers observe the same counter and block period.++Rate limiting and the temporary account lock cover different levels. The route limiter bounds requests from one IP before expensive authentication+work, while the account lock stops further cryptographic checks for one account after repeated failures. A distributed source can use several IPs,+so an edge or reverse-proxy limit remains a complementary deployment control. WebDAV HTTP Basic authentication uses its own rate-limit policy rather+than the default route guard described here.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.tsindex fcc8d24d..b6af273d 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@@ -334,7 +334,7 @@ describe(AuthProvider2FA.name, () => {const result = await service.loadUser(1, '127.0.0.1')expect(result).toBe(mockUser)- expect(usersManager.validateUserAccess).toHaveBeenCalledWith(mockUser, '127.0.0.1')+ expect(usersManager.validateUserAccess).toHaveBeenCalledWith(mockUser)})it('should throw error if user not found', async () => {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.tsindex dadcfb7a..0e21a629 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@@ -111,7 +111,7 @@ export class AuthProvider2FA {this.logger.warn({ tag: this.loadUser.name, msg: `User ${userId} (${ip}) not found` })throw new HttpException(`User not found`, HttpStatus.NOT_FOUND)}- this.usersManager.validateUserAccess(user, ip)+ await this.usersManager.validateUserAccess(user)return user}diff --git a/backend/src/authentication/providers/two-fa/two-fa.md b/backend/src/authentication/providers/two-fa/two-fa.mdindex a5630257..cf4f823f 100644--- a/backend/src/authentication/providers/two-fa/two-fa.md+++ b/backend/src/authentication/providers/two-fa/two-fa.md@@ -153,8 +153,8 @@ WebDAV-scoped app password, not the primary account password.## Password attempts and account access-TOTP verification always reloads the user and applies the normal account-access checks. A missing user, inactive account, or account over the-password-attempt limit is rejected before code validation.+TOTP verification always reloads the user and applies the normal account-access checks. A missing user, inactive account, or account within the+15-minute password-attempt lock period is rejected before code validation. The lock expires automatically and blocked requests do not extend it.After a successful password step for a TOTP-enabled login, password attempts are preserved until the TOTP step succeeds. A successful TOTP step resetsattempts; a failed password or failed code increments attempts through the shared access tracking path.diff --git a/frontend/src/app/applications/admin/components/admin-users.component.html b/frontend/src/app/applications/admin/components/admin-users.component.htmlindex 2fa42986..f6b259b3 100644--- a/frontend/src/app/applications/admin/components/admin-users.component.html+++ b/frontend/src/app/applications/admin/components/admin-users.component.html@@ -135,13 +135,9 @@</div>}@case ('isActive') {- <span class="{{u.isActive ? 'text-success' : 'text-danger'}}" l10nTranslate>- @if (!u.isActive && u.passwordAttempts) {- Too many login attempts- } @else {- {{ u.userIsActiveText }}- }- </span>+ <span class="{{u.isActive && !u.isTemporarilyLocked ? 'text-success' : 'text-danger'}}" l10nTranslate>+ {{ u.userIsActiveText }}+ </span>}@case ('currentAccess') {@if (u.currentAccess) {diff --git a/frontend/src/app/applications/admin/components/dialogs/admin-user-dialog.component.html b/frontend/src/app/applications/admin/components/dialogs/admin-user-dialog.component.htmlindex ed6a4d5a..8d44b767 100644--- a/frontend/src/app/applications/admin/components/dialogs/admin-user-dialog.component.html+++ b/frontend/src/app/applications/admin/components/dialogs/admin-user-dialog.component.html@@ -219,6 +219,9 @@</div></div></div>+ @if (user?.isTemporarilyLocked) {+ <small class="text-danger" l10nTranslate>Temporarily locked</small>+ }<div class="card dialog-check-card dialog-check-card--interactive"[class.dialog-check-card--active]="userForm.value.isAdmin"diff --git a/frontend/src/app/applications/admin/models/admin-user.model.ts b/frontend/src/app/applications/admin/models/admin-user.model.tsindex ab5a68bc..52c432f0 100644--- a/frontend/src/app/applications/admin/models/admin-user.model.ts+++ b/frontend/src/app/applications/admin/models/admin-user.model.ts@@ -4,7 +4,7 @@ import type { GuestUser } from '@sync-in-server/backend/src/applications/users/iimport { getNewly, titleCase } from '../../../common/utils/functions'import { dJs } from '../../../common/utils/time'import { MemberModel } from '../../users/models/member.model'-import { userAvatarUrl } from '../../users/user.functions'+import { isUserTemporarilyLocked, userAvatarUrl } from '../../users/user.functions'export class AdminUserModel implements AdminUser {id: number@@ -31,6 +31,7 @@ export class AdminUserModel implements AdminUser {// extra propertiesisAdmin = false+ isTemporarilyLocked = falsetwoFaEnabled?: booleanuserRoleText: stringuserIsActiveText: string@@ -47,9 +48,10 @@ export class AdminUserModel implements AdminUser {this.setManagers(user)Object.assign(this, user)this.isAdmin = user.role === USER_ROLE.ADMINISTRATOR+ this.isTemporarilyLocked = isUserTemporarilyLocked(this.isActive, this.passwordAttempts, this.currentAccess)this.userRoleText = titleCase(USER_ROLE[user.role])this.avatarUrl = userAvatarUrl(user.login)- this.userIsActiveText = this.isActive ? 'active' : 'suspended'+ this.userIsActiveText = this.isTemporarilyLocked ? 'locked' : this.isActive ? 'active' : 'suspended'this.hTimeAgo = dJs(this.currentAccess).fromNow(true)this.newly = getNewly(this.currentAccess)if (this.permissions) {diff --git a/frontend/src/app/applications/users/components/dialogs/user-guest-dialog.component.html b/frontend/src/app/applications/users/components/dialogs/user-guest-dialog.component.htmlindex f365dca8..590348db 100644--- a/frontend/src/app/applications/users/components/dialogs/user-guest-dialog.component.html+++ b/frontend/src/app/applications/users/components/dialogs/user-guest-dialog.component.html@@ -140,6 +140,9 @@</div></div></div>+ @if (guest?.isTemporarilyLocked) {+ <small class="text-danger" l10nTranslate>Temporarily locked</small>+ }</div></div>@@ -147,14 +150,14 @@<div class="card dialog-tab-card w-100"><div class="card-body"><div class="row g-3">- <div class="col-12">+ <div class="col-12 col-md-5"><div class="d-flex flex-column"><label class="form-label" for="created" l10nTranslate>Creation date</label><div class="fs-sm" id="created">{{ guest.createdAt | amDateFormat }}</div></div></div>- <div class="col-12">- <div class="d-flex flex-column">+ <div class="col-12 col-md-7">+ <div class="d-flex flex-column text-md-end"><label class="form-label" for="access" l10nTranslate>Last accesses</label><div class="fs-sm" id="access">@if (guest.lastAccess) {@@ -167,7 +170,7 @@<span>{{ guest.lastIp }}</span></div>} @else {- <span class="badge bg-danger" l10nTranslate>never</span>+ <span class="text-danger" l10nTranslate>never</span>}</div></div>diff --git a/frontend/src/app/applications/users/components/user-guests.component.html b/frontend/src/app/applications/users/components/user-guests.component.htmlindex 74054d91..a5893c93 100644--- a/frontend/src/app/applications/users/components/user-guests.component.html+++ b/frontend/src/app/applications/users/components/user-guests.component.html@@ -88,13 +88,9 @@<app-user-avatar-stack [users]="u.managers" [isMember]="true" [container]="'body'"></app-user-avatar-stack>}@case ('isActive') {- <span class="{{u.isActive ? 'text-success' : 'text-danger'}}" l10nTranslate>- @if (!u.isActive && u.passwordAttempts) {- Too many login attempts- } @else {- {{ u.userIsActiveText }}- }- </span>+ <span class="{{u.isActive && !u.isTemporarilyLocked ? 'text-success' : 'text-danger'}}" l10nTranslate>+ {{ u.userIsActiveText }}+ </span>}@case ('createdAt') {{{ u.createdAt | amTimeAgo:true }}diff --git a/frontend/src/app/applications/users/models/guest.model.ts b/frontend/src/app/applications/users/models/guest.model.tsindex 5d76e79e..a2fd048e 100644--- a/frontend/src/app/applications/users/models/guest.model.ts+++ b/frontend/src/app/applications/users/models/guest.model.ts@@ -1,7 +1,7 @@import type { GuestUser } from '@sync-in-server/backend/src/applications/users/interfaces/guest-user.interface'import { getNewly } from '../../../common/utils/functions'import { dJs } from '../../../common/utils/time'-import { userAvatarUrl } from '../user.functions'+import { isUserTemporarilyLocked, userAvatarUrl } from '../user.functions'import { MemberModel } from './member.model'export class GuestUserModel implements GuestUser {@@ -25,6 +25,7 @@ export class GuestUserModel implements GuestUser {groups: MemberModel[]// extra properties+ isTemporarilyLocked = falseuserIsActiveText: stringavatarUrl?: stringnewly = 0@@ -37,8 +38,9 @@ export class GuestUserModel implements GuestUser {this.setManagers(guest)this.setGroups(guest)Object.assign(this, guest)+ this.isTemporarilyLocked = isUserTemporarilyLocked(this.isActive, this.passwordAttempts, this.currentAccess)this.avatarUrl = userAvatarUrl(guest.login)- this.userIsActiveText = this.isActive ? 'active' : 'suspended'+ this.userIsActiveText = this.isTemporarilyLocked ? 'locked' : this.isActive ? 'active' : 'suspended'this.hTimeAgo = dJs(this.currentAccess).fromNow(true)this.newly = getNewly(this.currentAccess)}diff --git a/frontend/src/app/applications/users/user.functions.ts b/frontend/src/app/applications/users/user.functions.tsindex 387e4ce3..1eb35bf5 100644--- a/frontend/src/app/applications/users/user.functions.ts+++ b/frontend/src/app/applications/users/user.functions.ts@@ -1,5 +1,16 @@+import { USER_MAX_PASSWORD_ATTEMPTS, USER_PASSWORD_ATTEMPTS_LOCK_DURATION_MS } from '@sync-in-server/backend/src/applications/users/constants/user'import { API_USERS_AVATAR } from '@sync-in-server/backend/src/applications/users/constants/routes'+export function isUserTemporarilyLocked(isActive: boolean, passwordAttempts: number, currentAccess: Date | string): boolean {+ const currentAccessTimestamp = currentAccess ? (currentAccess instanceof Date ? currentAccess.getTime() : Date.parse(currentAccess)) : Number.NaN+ return (+ isActive &&+ (passwordAttempts ?? 0) >= USER_MAX_PASSWORD_ATTEMPTS &&+ Number.isFinite(currentAccessTimestamp) &&+ currentAccessTimestamp + USER_PASSWORD_ATTEMPTS_LOCK_DURATION_MS > Date.now()+ )+}+export function userAvatarUrl(login: string) {return `${API_USERS_AVATAR}/${login}`}diff --git a/frontend/src/i18n/de.json b/frontend/src/i18n/de.jsonindex b1da18e1..62ff11b2 100644--- a/frontend/src/i18n/de.json+++ b/frontend/src/i18n/de.json@@ -463,6 +463,8 @@"active": "aktiv","Active": "Aktiv","suspended": "ausgesetzt",+ "locked": "gesperrt",+ "Temporarily locked": "Vorübergehend gesperrt","Unable to rename user space": "Benutzerbereich kann nicht umbenannt werden","Unable to delete user space": "Benutzerbereich kann nicht gelöscht werden","Unable to update user": "Benutzer kann nicht aktualisiert werden",diff --git a/frontend/src/i18n/en.json b/frontend/src/i18n/en.jsonindex 1c4225de..b41e4ce6 100644--- a/frontend/src/i18n/en.json+++ b/frontend/src/i18n/en.json@@ -11,9 +11,7 @@"one_notification": "{{ nb }} unread notification","nb_notifications": "{{ nb }} unread notifications","available_space_is_low": "Available space is low ( {{ nb }}% )",- "Too many login attempts": "Too many login attempts","auth_retry_after": "Try again {{ delay }}",- "Too many requests. Please try again later.": "Too many requests. Please try again later.","trash_one_file": "Would you like to move <b>{{arg}}</b> to trash ?","delete_one_file": "Do you want to permanently delete <b>{{arg}}</b> ?","trash_multiple_files": "Would you like to move <b>{{arg}} files</b> to trash ?",@@ -25,9 +23,6 @@"office_editor_init_error": "{{ editor }} editor failed to initialize","office_editor_unknown_error": "Unknown {{ editor }} error","edit_in_office_editor": "Edit in {{ editor }}",- "Personal space": "Personal space",- "Collaborative": "Collaborative",- "Collaborative spaces": "Collaborative spaces","personal_space": "Personal space access","spaces_access": "Spaces access","spaces_admin": "Spaces administration",diff --git a/frontend/src/i18n/es.json b/frontend/src/i18n/es.jsonindex d9b7390a..99ad77f3 100644--- a/frontend/src/i18n/es.json+++ b/frontend/src/i18n/es.json@@ -463,6 +463,8 @@"active": "activo","Active": "Activo","suspended": "suspendido",+ "locked": "bloqueado",+ "Temporarily locked": "Bloqueado temporalmente","Unable to rename user space": "No se puede renombrar el espacio del usuario","Unable to delete user space": "No se puede eliminar el espacio del usuario","Unable to update user": "No se puede actualizar el usuario",diff --git a/frontend/src/i18n/fr.json b/frontend/src/i18n/fr.jsonindex 7cc2253e..e8cc1d3c 100644--- a/frontend/src/i18n/fr.json+++ b/frontend/src/i18n/fr.json@@ -463,6 +463,8 @@"active": "actif","Active": "Actif","suspended": "suspendu",+ "locked": "verrouillé",+ "Temporarily locked": "Verrouillé temporairement","Unable to rename user space": "Impossible de renommer l'espace utilisateur","Unable to delete user space": "Impossible de supprimer l'espace utilisateur","Unable to update user": "Impossible de mettre à jour l'utilisateur",diff --git a/frontend/src/i18n/hi.json b/frontend/src/i18n/hi.jsonindex 693b9330..9d8bc982 100644--- a/frontend/src/i18n/hi.json+++ b/frontend/src/i18n/hi.json@@ -463,6 +463,8 @@"active": "सक्रिय","Active": "सक्रिय","suspended": "निलंबित",+ "locked": "लॉक किया गया",+ "Temporarily locked": "अस्थायी रूप से लॉक किया गया","Unable to rename user space": "उपयोगकर्ता स्पेस का नाम नहीं बदला जा सका","Unable to delete user space": "उपयोगकर्ता स्पेस हटाया नहीं जा सका","Unable to update user": "उपयोगकर्ता अपडेट नहीं किया जा सका",diff --git a/frontend/src/i18n/it.json b/frontend/src/i18n/it.jsonindex c6e05f22..889fb926 100644--- a/frontend/src/i18n/it.json+++ b/frontend/src/i18n/it.json@@ -463,6 +463,8 @@"active": "attivo","Active": "Attivo","suspended": "sospeso",+ "locked": "bloccato",+ "Temporarily locked": "Bloccato temporaneamente","Unable to rename user space": "Impossibile rinominare lo spazio utente","Unable to delete user space": "Impossibile eliminare lo spazio utente","Unable to update user": "Impossibile aggiornare l’utente",diff --git a/frontend/src/i18n/ja.json b/frontend/src/i18n/ja.jsonindex c0b2be88..ec83c1b3 100644--- a/frontend/src/i18n/ja.json+++ b/frontend/src/i18n/ja.json@@ -463,6 +463,8 @@"active": "有効","Active": "有効","suspended": "一時停止",+ "locked": "ロック中",+ "Temporarily locked": "一時的にロック","Unable to rename user space": "ユーザースペースの名前を変更できません","Unable to delete user space": "ユーザースペースを削除できません","Unable to update user": "ユーザーを更新できません",diff --git a/frontend/src/i18n/ko.json b/frontend/src/i18n/ko.jsonindex 6a1a28d6..c40c64ed 100644--- a/frontend/src/i18n/ko.json+++ b/frontend/src/i18n/ko.json@@ -463,6 +463,8 @@"active": "활성","Active": "활성","suspended": "일시 중지됨",+ "locked": "잠김",+ "Temporarily locked": "일시적으로 잠김","Unable to rename user space": "사용자 스페이스의 이름을 변경할 수 없습니다","Unable to delete user space": "사용자 스페이스를 삭제할 수 없습니다","Unable to update user": "사용자를 업데이트할 수 없습니다",diff --git a/frontend/src/i18n/nl.json b/frontend/src/i18n/nl.jsonindex 6fe2e160..5612ce42 100644--- a/frontend/src/i18n/nl.json+++ b/frontend/src/i18n/nl.json@@ -463,6 +463,8 @@"active": "actief","Active": "Actief","suspended": "geschorst",+ "locked": "geblokkeerd",+ "Temporarily locked": "Tijdelijk geblokkeerd","Unable to rename user space": "Kan gebruikersruimte niet hernoemen","Unable to delete user space": "Kan gebruikersruimte niet verwijderen","Unable to update user": "Kan gebruiker niet bijwerken",diff --git a/frontend/src/i18n/pl.json b/frontend/src/i18n/pl.jsonindex 56ec23c0..0c3fbbd9 100644--- a/frontend/src/i18n/pl.json+++ b/frontend/src/i18n/pl.json@@ -463,6 +463,8 @@"active": "aktywne","Active": "Aktywne","suspended": "zawieszone",+ "locked": "zablokowane",+ "Temporarily locked": "Tymczasowo zablokowane","Unable to rename user space": "Nie można zmienić nazwy przestrzeni użytkownika","Unable to delete user space": "Nie można usunąć przestrzeni użytkownika","Unable to update user": "Nie można zaktualizować użytkownika",diff --git a/frontend/src/i18n/pt-BR.json b/frontend/src/i18n/pt-BR.jsonindex 07e10757..c0442041 100644--- a/frontend/src/i18n/pt-BR.json+++ b/frontend/src/i18n/pt-BR.json@@ -463,6 +463,8 @@"active": "ativo","Active": "Ativo","suspended": "suspenso",+ "locked": "bloqueado",+ "Temporarily locked": "Bloqueado temporariamente","Unable to rename user space": "Não foi possível renomear o espaço do usuário","Unable to delete user space": "Não foi possível excluir o espaço do usuário","Unable to update user": "Não foi possível atualizar o usuário",diff --git a/frontend/src/i18n/pt.json b/frontend/src/i18n/pt.jsonindex ee15ab2c..d7d135f9 100644--- a/frontend/src/i18n/pt.json+++ b/frontend/src/i18n/pt.json@@ -463,6 +463,8 @@"active": "ativo","Active": "Ativo","suspended": "suspenso",+ "locked": "bloqueado",+ "Temporarily locked": "Bloqueado temporariamente","Unable to rename user space": "Não é possível renomear o espaço do usuário","Unable to delete user space": "Não é possível excluir o espaço do usuário","Unable to update user": "Não é possível atualizar o usuário",diff --git a/frontend/src/i18n/ru.json b/frontend/src/i18n/ru.jsonindex e5746603..902c4a5b 100644--- a/frontend/src/i18n/ru.json+++ b/frontend/src/i18n/ru.json@@ -463,6 +463,8 @@"active": "активен","Active": "Активен","suspended": "приостановлен",+ "locked": "заблокирован",+ "Temporarily locked": "Временно заблокирован","Unable to rename user space": "Не удалось переименовать пользовательское пространство","Unable to delete user space": "Не удалось удалить пользовательское пространство","Unable to update user": "Не удалось обновить пользователя",diff --git a/frontend/src/i18n/tr.json b/frontend/src/i18n/tr.jsonindex 33254a80..005344cd 100644--- a/frontend/src/i18n/tr.json+++ b/frontend/src/i18n/tr.json@@ -463,6 +463,8 @@"active": "aktif","Active": "Aktif","suspended": "askıda",+ "locked": "kilitli",+ "Temporarily locked": "Geçici olarak kilitlendi","Unable to rename user space": "Kullanıcı alanı yeniden adlandırılamıyor","Unable to delete user space": "Kullanıcı alanı silinemiyor","Unable to update user": "Kullanıcı güncellenemiyor",diff --git a/frontend/src/i18n/zh.json b/frontend/src/i18n/zh.jsonindex 447197c7..e810deb5 100644--- a/frontend/src/i18n/zh.json+++ b/frontend/src/i18n/zh.json@@ -463,6 +463,8 @@"active": "活跃","Active": "活跃","suspended": "已暂停",+ "locked": "已锁定",+ "Temporarily locked": "暂时锁定","Unable to rename user space": "无法重命名用户空间","Unable to delete user space": "无法删除用户空间","Unable to update user": "无法更新用户",