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(auth): add cache-backed rate limiting (#272)
Johan Legrand829df9e04453
diff --git a/backend/package.json b/backend/package.jsonindex fcc76560..6dc3f914 100755--- a/backend/package.json+++ b/backend/package.json@@ -50,6 +50,7 @@"@nestjs/platform-fastify": "^11.1.24","@nestjs/platform-socket.io": "^11.1.24","@nestjs/schedule": "^6.1.3",+ "@nestjs/throttler": "^6.5.0","@nestjs/websockets": "^11.1.24","@socket.io/cluster-adapter": "^0.3.0","@socket.io/redis-adapter": "^8.3.0",diff --git a/backend/src/applications/links/constants/links.ts b/backend/src/applications/links/constants/links.tsindex 2a797114..2a5e1114 100644--- a/backend/src/applications/links/constants/links.ts+++ b/backend/src/applications/links/constants/links.ts@@ -10,3 +10,9 @@ export enum LINK_TYPE {SPACE = 'space',SHARE = 'share'}++export const LINK_DOWNLOAD_RATE_LIMIT_OPTIONS = {+ limit: 30,+ ttl: 60_000,+ blockDuration: 60_000+} as constdiff --git a/backend/src/applications/links/links.controller.spec.ts b/backend/src/applications/links/links.controller.spec.tsindex 68054074..adb9693e 100644--- a/backend/src/applications/links/links.controller.spec.ts+++ b/backend/src/applications/links/links.controller.spec.ts@@ -1,5 +1,6 @@import { StreamableFile } from '@nestjs/common'import { Test, TestingModule } from '@nestjs/testing'+import { AuthRateLimitGuard } from '../../authentication/guards/auth-rate-limit.guard'import { LinksController } from './links.controller'import { LinksManager } from './services/links-manager.service'import { Mock } from 'vitest'@@ -19,10 +20,12 @@ describe(LinksController.name, () => {linkAuthentication: vi.fn()}- const module: TestingModule = await Test.createTestingModule({+ const testingModuleBuilder = Test.createTestingModule({controllers: [LinksController],providers: [{ provide: LinksManager, useValue: linksManager }]- }).compile()+ })+ testingModuleBuilder.overrideGuard(AuthRateLimitGuard).useValue({ canActivate: () => true })+ const module: TestingModule = await testingModuleBuilder.compile()controller = module.get<LinksController>(LinksController)})diff --git a/backend/src/applications/links/links.controller.ts b/backend/src/applications/links/links.controller.tsindex 06ed9d1f..0f26527b 100644--- a/backend/src/applications/links/links.controller.ts+++ b/backend/src/applications/links/links.controller.ts@@ -1,10 +1,13 @@-import { Body, Controller, Get, Param, Post, Req, Res, StreamableFile } from '@nestjs/common'+import { Body, Controller, Get, Param, Post, Req, Res, StreamableFile, UseGuards } from '@nestjs/common'+import { Throttle } from '@nestjs/throttler'import { FastifyReply, FastifyRequest } from 'fastify'import { AuthTokenOptional } from '../../authentication/decorators/auth-token-optional.decorator'import { LoginResponseDto } from '../../authentication/dto/login-response.dto'+import { AuthRateLimitGuard } from '../../authentication/guards/auth-rate-limit.guard'import { GetUser } from '../users/decorators/user.decorator'import { UserPasswordDto } from '../users/dto/user-properties.dto'import { UserModel } from '../users/models/user.model'+import { LINK_DOWNLOAD_RATE_LIMIT_OPTIONS } from './constants/links'import { PUBLIC_LINKS_ROUTE } from './constants/routes'import { SpaceLink } from './interfaces/link-space.interface'import { LinksManager } from './services/links-manager.service'@@ -15,6 +18,7 @@ export class LinksController {constructor(private readonly linksManager: LinksManager) {}@Get(`${PUBLIC_LINKS_ROUTE.VALIDATION}/:uuid`)+ @UseGuards(AuthRateLimitGuard)linkValidation(@GetUser() user: UserModel,@Param('uuid') uuid: string@@ -27,6 +31,7 @@ export class LinksController {}@Get(`${PUBLIC_LINKS_ROUTE.ACCESS}/:uuid`)+ @UseGuards(AuthRateLimitGuard)linkAccess(@GetUser() user: UserModel,@Param('uuid') uuid: string,@@ -37,6 +42,8 @@ export class LinksController {}@Get(`${PUBLIC_LINKS_ROUTE.DOWNLOAD}/:uuid`)+ @Throttle({ default: LINK_DOWNLOAD_RATE_LIMIT_OPTIONS })+ @UseGuards(AuthRateLimitGuard)linkDownload(@GetUser() user: UserModel,@Param('uuid') uuid: string,@@ -47,6 +54,7 @@ export class LinksController {}@Post(`${PUBLIC_LINKS_ROUTE.AUTH}/:uuid`)+ @UseGuards(AuthRateLimitGuard)linkAuthentication(@GetUser() user: UserModel,@Param('uuid') uuid: string,diff --git a/backend/src/applications/sync/sync.controller.spec.ts b/backend/src/applications/sync/sync.controller.spec.tsindex 5237d7db..a881d4b8 100644--- a/backend/src/applications/sync/sync.controller.spec.ts+++ b/backend/src/applications/sync/sync.controller.spec.ts@@ -1,4 +1,5 @@import { Test, TestingModule } from '@nestjs/testing'+import { AuthRateLimitGuard } from '../../authentication/guards/auth-rate-limit.guard'import { ContextManager } from '../../infrastructure/context/services/context-manager.service'import { SpacesManager } from '../spaces/services/spaces-manager.service'import { SyncClientsManager } from './services/sync-clients-manager.service'@@ -10,7 +11,7 @@ describe(SyncController.name, () => {let controller: SyncControllerbeforeAll(async () => {- const module: TestingModule = await Test.createTestingModule({+ const testingModuleBuilder = Test.createTestingModule({controllers: [SyncController],providers: [{ provide: ContextManager, useValue: {} },@@ -19,7 +20,9 @@ describe(SyncController.name, () => {{ provide: SyncClientsManager, useValue: {} },{ provide: SyncPathsManager, useValue: {} }]- }).compile()+ })+ testingModuleBuilder.overrideGuard(AuthRateLimitGuard).useValue({ canActivate: () => true })+ const module: TestingModule = await testingModuleBuilder.compile()controller = module.get<SyncController>(SyncController)})diff --git a/backend/src/applications/sync/sync.controller.ts b/backend/src/applications/sync/sync.controller.tsindex 31d41b1b..7116631c 100644--- a/backend/src/applications/sync/sync.controller.ts+++ b/backend/src/applications/sync/sync.controller.ts@@ -22,6 +22,7 @@ import {} from '@nestjs/common'import { FastifyReply, FastifyRequest } from 'fastify'import { AuthTokenSkip } from '../../authentication/decorators/auth-token-skip.decorator'+import { AuthRateLimitGuard } from '../../authentication/guards/auth-rate-limit.guard'import { FastifyAuthenticatedRequest } from '../../authentication/interfaces/auth-request.interface'import { ContextInterceptor } from '../../infrastructure/context/interceptors/context.interceptor'import { SkipSpacePermissionsCheck } from '../spaces/decorators/space-skip-permissions.decorator'@@ -70,6 +71,7 @@ export class SyncController {@Post(SYNC_ROUTE.REGISTER)@AuthTokenSkip()+ @UseGuards(AuthRateLimitGuard)register(@Body() syncClientRegistrationDto: SyncClientRegistrationDto, @Req() req: FastifyRequest): Promise<SyncClientAuthRegistration> {return this.syncClientsManager.register(syncClientRegistrationDto, req.ip)}@@ -100,6 +102,7 @@ export class SyncController {@Post(`${SYNC_ROUTE.AUTH}/:type`)@AuthTokenSkip()+ @UseGuards(AuthRateLimitGuard)authenticate(@Param('type') type: CLIENT_AUTH_TYPE,@Body() clientAuthDto: SyncClientAuthDto,diff --git a/backend/src/authentication/adapters/auth-rate-limit-storage.adapter.ts b/backend/src/authentication/adapters/auth-rate-limit-storage.adapter.tsnew file mode 100644index 00000000..fee0ce04--- /dev/null+++ b/backend/src/authentication/adapters/auth-rate-limit-storage.adapter.ts@@ -0,0 +1,13 @@+import { ThrottlerStorage } from '@nestjs/throttler'+import { Cache } from '../../infrastructure/cache/cache.service'+import type { CacheRateLimitResult } from '../../infrastructure/cache/interfaces/cache-rate-limit.interface'+import { CACHE_AUTH_RATE_LIMIT_PREFIX } from '../constants/cache'++export class AuthRateLimitStorage implements ThrottlerStorage {+ constructor(private readonly cache: Cache) {}++ increment(key: string, ttl: number, limit: number, blockDuration: number): Promise<CacheRateLimitResult> {+ // Nest already includes the route, throttler name and client tracker in its hashed key.+ return this.cache.consumeRateLimit(`${CACHE_AUTH_RATE_LIMIT_PREFIX}-${key}`, ttl, limit, blockDuration)+ }+}diff --git a/backend/src/authentication/auth.controller.spec.ts b/backend/src/authentication/auth.controller.spec.tsindex c2bc3215..cb2c098e 100755--- a/backend/src/authentication/auth.controller.spec.ts+++ b/backend/src/authentication/auth.controller.spec.ts@@ -26,6 +26,7 @@ import { API_AUTH_SETTINGS, API_AUTH_TOKEN, API_TWO_FA_ADMIN_RESET_USER, API_TWOimport { AUTH_TOKEN_SKIP } from './decorators/auth-token-skip.decorator'import { LoginResponseDto, LoginVerify2FaDto } from './dto/login-response.dto'import { AuthLocalGuard } from './guards/auth-local.guard'+import { AuthRateLimitGuard } from './guards/auth-rate-limit.guard'import { JwtPayload } from './interfaces/jwt-payload.interface'import { TOKEN_TYPE } from './interfaces/token.interface'import { AuthProvider2FA } from './providers/two-fa/auth-provider-two-fa.service'@@ -43,7 +44,7 @@ describe(AuthController.name, () => {let userTest: UserModelbeforeAll(async () => {- module = await Test.createTestingModule({+ const testingModuleBuilder = Test.createTestingModule({imports: [await ConfigModule.forRoot({ load: [exportConfiguration], isGlobal: true }), PassportModule],controllers: [AuthController],providers: [@@ -57,7 +58,9 @@ describe(AuthController.name, () => {{ provide: UsersManager, useValue: { updateAccesses: vi.fn().mockResolvedValue(undefined) } },{ provide: NotificationsManager, useValue: {} }]- }).compile()+ })+ testingModuleBuilder.overrideGuard(AuthRateLimitGuard).useValue({ canActivate: () => true })+ module = await testingModuleBuilder.compile()module.useLogger(['fatal'])authConfig = module.get<ConfigService>(ConfigService).get<AuthConfig>('auth')@@ -314,6 +317,7 @@ describe(`${AuthController.name} HTTP`, () => {return true}})+ testingModuleBuilder.overrideGuard(AuthRateLimitGuard).useValue({ canActivate: () => true })const module: TestingModule = await testingModuleBuilder.compile()module.useLogger(['fatal'])diff --git a/backend/src/authentication/auth.controller.ts b/backend/src/authentication/auth.controller.tsindex efd0e59c..393d6575 100755--- a/backend/src/authentication/auth.controller.ts+++ b/backend/src/authentication/auth.controller.ts@@ -12,6 +12,7 @@ import { AuthTokenSkip } from './decorators/auth-token-skip.decorator'import { LoginResponseDto, LoginVerify2FaDto } from './dto/login-response.dto'import { TokenResponseDto } from './dto/token-response.dto'import { AuthLocalGuard } from './guards/auth-local.guard'+import { AuthRateLimitGuard } from './guards/auth-rate-limit.guard'import { AuthTokenRefreshGuard } from './guards/auth-token-refresh.guard'import { FastifyAuthenticatedRequest } from './interfaces/auth-request.interface'import { TOKEN_TYPE } from './interfaces/token.interface'@@ -31,7 +32,7 @@ export class AuthController {@Post(AUTH_ROUTE.LOGIN)@AuthTokenSkip()- @UseGuards(AuthLocalGuard)+ @UseGuards(AuthRateLimitGuard, AuthLocalGuard)login(@GetUser() user: UserModel, @Res({ passthrough: true }) res: FastifyReply): Promise<LoginResponseDto | LoginVerify2FaDto> {return this.authManager.setCookies(user, res, true)}@@ -51,7 +52,7 @@ export class AuthController {@Post(AUTH_ROUTE.TOKEN)@AuthTokenSkip()- @UseGuards(AuthLocalGuard, AuthTwoFaVerificationWithoutPasswordGuard)+ @UseGuards(AuthRateLimitGuard, AuthLocalGuard, AuthTwoFaVerificationWithoutPasswordGuard)token(@GetUser() user: UserModel): Promise<TokenResponseDto> {return this.authManager.getTokens(user)}@@ -80,14 +81,14 @@ export class AuthController {}@Post(`${AUTH_ROUTE.TWO_FA_BASE}/${AUTH_ROUTE.TWO_FA_ENABLE}`)- @UseGuards(UserRolesGuard)+ @UseGuards(AuthRateLimitGuard, UserRolesGuard)@UserHaveRole(USER_ROLE.USER)twoFaEnable(@Body() body: TwoFaVerifyWithPasswordDto, @Req() req: FastifyAuthenticatedRequest): Promise<TwoFaVerifyResult> {return this.authProvider2FA.enableTwoFactor(body, req)}@Post(`${AUTH_ROUTE.TWO_FA_BASE}/${AUTH_ROUTE.TWO_FA_DISABLE}`)- @UseGuards(UserRolesGuard)+ @UseGuards(AuthRateLimitGuard, UserRolesGuard)@UserHaveRole(USER_ROLE.USER)twoFaDisable(@Body() body: TwoFaVerifyWithPasswordDto, @Req() req: FastifyAuthenticatedRequest): Promise<TwoFaVerifyResult> {return this.authProvider2FA.disableTwoFactor(body, req)@@ -95,7 +96,7 @@ export class AuthController {@Post(`${AUTH_ROUTE.TWO_FA_BASE}/${AUTH_ROUTE.TWO_FA_LOGIN_VERIFY}`)@AuthTokenSkip()- @UseGuards(AuthTokenTwoFaGuard, UserRolesGuard)+ @UseGuards(AuthRateLimitGuard, AuthTokenTwoFaGuard, UserRolesGuard)@UserHaveRole(USER_ROLE.USER)async twoFaLogin(@Body() body: TwoFaVerifyDto,@@ -113,7 +114,7 @@ export class AuthController {}@Post(`${AUTH_ROUTE.TWO_FA_BASE}/${AUTH_ROUTE.TWO_FA_ADMIN_RESET_USER}/:id`)- @UseGuards(UserRolesGuard, AuthTwoFaVerificationGuard)+ @UseGuards(AuthRateLimitGuard, UserRolesGuard, AuthTwoFaVerificationGuard)@UserHaveRole(USER_ROLE.ADMINISTRATOR)twoFaReset(@Param('id', ParseIntPipe) userId: number): Promise<TwoFaVerifyResult> {return this.authProvider2FA.adminResetUserTwoFa(userId)diff --git a/backend/src/authentication/auth.module.ts b/backend/src/authentication/auth.module.tsindex 26c90789..7d95fe6d 100755--- a/backend/src/authentication/auth.module.ts+++ b/backend/src/authentication/auth.module.ts@@ -2,16 +2,22 @@ import { Global, Module } from '@nestjs/common'import { APP_GUARD } from '@nestjs/core'import { JwtModule } from '@nestjs/jwt'import { PassportModule } from '@nestjs/passport'+import { ThrottlerModule } from '@nestjs/throttler'import { UsersModule } from '../applications/users/users.module'import { configuration } from '../configuration/config.environment'+import { CacheModule } from '../infrastructure/cache/cache.module'+import { Cache } from '../infrastructure/cache/cache.service'+import { AuthRateLimitStorage } from './adapters/auth-rate-limit-storage.adapter'import { AuthController } from './auth.controller'import { AuthManager } from './auth.service'+import { AUTH_RATE_LIMIT_OPTIONS } from './constants/auth'import { AuthAnonymousGuard } from './guards/auth-anonymous.guard'import { AuthAnonymousStrategy } from './guards/auth-anonymous.strategy'import { AuthBasicGuard } from './guards/auth-basic.guard'import { AuthBasicStrategy } from './guards/auth-basic.strategy'import { AuthLocalGuard } from './guards/auth-local.guard'import { AuthLocalStrategy } from './guards/auth-local.strategy'+import { AuthRateLimitGuard } from './guards/auth-rate-limit.guard'import { AuthTokenAccessGuard } from './guards/auth-token-access.guard'import { AuthTokenAccessStrategy } from './guards/auth-token-access.strategy'import { AuthTokenRefreshGuard } from './guards/auth-token-refresh.guard'@@ -28,6 +34,14 @@ import { AuthTokenTwoFaStrategy } from './providers/two-fa/guards/auth-token-two@Module({imports: [JwtModule.register({ global: true }),+ ThrottlerModule.forRootAsync({+ imports: [CacheModule],+ inject: [Cache],+ useFactory: (cache: Cache) => ({+ throttlers: [AUTH_RATE_LIMIT_OPTIONS],+ storage: new AuthRateLimitStorage(cache)+ })+ }),UsersModule,PassportModule,...(configuration.auth.provider === AUTH_PROVIDER.OIDC ? [AuthProviderOIDCModule] : [])@@ -38,6 +52,7 @@ import { AuthTokenTwoFaStrategy } from './providers/two-fa/guards/auth-token-twoprovide: APP_GUARD,useClass: AuthTokenAccessGuard},+ AuthRateLimitGuard,AuthTokenRefreshGuard,AuthTokenTwoFaGuard,AuthLocalGuard,@@ -53,6 +68,6 @@ import { AuthTokenTwoFaStrategy } from './providers/two-fa/guards/auth-token-twoAuthProvider2FA,selectAuthProvider(configuration.auth.provider)],- exports: [AuthManager, AuthProvider, AuthProvider2FA]+ exports: [AuthManager, AuthProvider, AuthProvider2FA, AuthRateLimitGuard]})export class AuthModule {}diff --git a/backend/src/authentication/constants/auth.ts b/backend/src/authentication/constants/auth.tsindex 8df68348..9cfc9807 100644--- a/backend/src/authentication/constants/auth.ts+++ b/backend/src/authentication/constants/auth.ts@@ -11,6 +11,18 @@ export const TWO_FA_VERIFY_EXPIRATION = '5m'export const TWO_FA_HEADER_CODE = 'sync-in-two-fa-code'export const TWO_FA_HEADER_PASSWORD = 'sync-in-two-fa-password'+export const AUTH_RATE_LIMIT_OPTIONS = {+ limit: 6,+ ttl: 60_000,+ blockDuration: 60_000+} as const+export const AUTH_WEBDAV_RATE_LIMIT_OPTIONS = {+ limit: 60,+ ttl: 60_000,+ blockDuration: 60_000+} as const+export const AUTH_RATE_LIMIT_ERROR_MESSAGE = 'Too many requests. Please try again later.'+export const TOKEN_PATHS = {[TOKEN_TYPE.ACCESS]: '/',[TOKEN_TYPE.REFRESH]: API_AUTH_REFRESH,diff --git a/backend/src/authentication/constants/cache.ts b/backend/src/authentication/constants/cache.tsindex 4586b6fc..56f86a76 100644--- a/backend/src/authentication/constants/cache.ts+++ b/backend/src/authentication/constants/cache.ts@@ -1,3 +1,4 @@// cache key = `auth-webdav-${sha256(login + password)}` => UserModel | nullexport const CACHE_AUTH_WEBDAV_PREFIX = 'auth-webdav' as constexport const CACHE_AUTH_WEBDAV_TTL = 900 as const+export const CACHE_AUTH_RATE_LIMIT_PREFIX = 'auth-rate-limit' as constdiff --git a/backend/src/authentication/guards/auth-basic.guard.spec.ts b/backend/src/authentication/guards/auth-basic.guard.spec.tsindex 1f0a95ef..0e6da24a 100644--- a/backend/src/authentication/guards/auth-basic.guard.spec.ts+++ b/backend/src/authentication/guards/auth-basic.guard.spec.ts@@ -1,11 +1,13 @@import { createMock, DeepMocked } from '@golevelup/ts-vitest'import { ExecutionContext } from '@nestjs/common'import { Test, TestingModule } from '@nestjs/testing'+import type { FastifyRequest } from 'fastify'import { PinoLogger } from 'nestjs-pino'import { UserModel } from '../../applications/users/models/user.model'import { generateUserTest } from '../../applications/users/utils/test'import { WEBDAV_BASE_PATH } from '../../applications/webdav/constants/routes'import { Cache } from '../../infrastructure/cache/cache.service'+import { AUTH_RATE_LIMIT_ERROR_MESSAGE } from '../constants/auth'import { AuthProvider } from '../providers/auth-providers.models'import { AuthBasicGuard } from './auth-basic.guard'import { AuthBasicStrategy } from './auth-basic.strategy'@@ -18,6 +20,7 @@ describe(AuthBasicGuard.name, () => {let userTest: UserModellet encodedAuth: stringlet context: DeepMocked<ExecutionContext>+ const requestIp = '127.0.0.1'beforeAll(async () => {const module: TestingModule = await Test.createTestingModule({@@ -42,6 +45,7 @@ describe(AuthBasicGuard.name, () => {useValue: {get: (_key: string) => undefined,set: async (_key: string, _value: string, _ttl: number) => undefined,+ consumeRateLimit: vi.fn().mockResolvedValue({ totalHits: 1, timeToExpire: 60, isBlocked: false, timeToBlockExpire: 0 }),genSlugKey: () => 'test'}}@@ -70,6 +74,7 @@ describe(AuthBasicGuard.name, () => {it('should validate the user authentication', async () => {authProvider.validateUser = vi.fn().mockReturnValueOnce(userTest)context.switchToHttp().getRequest.mockReturnValue({+ ip: requestIp,raw: { user: '' },headers: { authorization: `Basic ${encodedAuth}` }})@@ -88,6 +93,7 @@ describe(AuthBasicGuard.name, () => {return userWithColonPassword})context.switchToHttp().getRequest.mockReturnValue({+ ip: requestIp,raw: { user: '' },headers: { authorization: `Basic ${encodedAuthWithColon}` }})@@ -107,22 +113,32 @@ describe(AuthBasicGuard.name, () => {expect(authProvider.validateUser).not.toHaveBeenCalled()})- it('should validate the user authentication with cache', async () => {+ it('should validate cached credentials without consuming the rate limit', async () => {cache.get = vi.fn().mockReturnValueOnce(userTest)+ const rateLimitSpy = vi.mocked(cache.consumeRateLimit).mockClear()+ authProvider.validateUser = vi.fn()context.switchToHttp().getRequest.mockReturnValue({+ ip: requestIp,raw: { user: '' },headers: { authorization: `Basic ${encodedAuth}` }})expect(await authBasicGuard.canActivate(context)).toBe(true)+ expect(rateLimitSpy).not.toHaveBeenCalled()+ expect(authProvider.validateUser).not.toHaveBeenCalled()})- it('should not validate the user authentication when cache returns null (explicitly unauthorized)', async () => {+ it('should reject cached invalid credentials without consuming the rate limit', async () => {cache.get = vi.fn().mockReturnValueOnce(null)+ const rateLimitSpy = vi.mocked(cache.consumeRateLimit).mockClear()+ authProvider.validateUser = vi.fn()context.switchToHttp().getRequest.mockReturnValue({+ ip: requestIp,raw: { user: '' },headers: { authorization: `Basic ${encodedAuth}` }})await expect(authBasicGuard.canActivate(context)).rejects.toThrow()+ expect(rateLimitSpy).not.toHaveBeenCalled()+ expect(authProvider.validateUser).not.toHaveBeenCalled()})it('should not validate the user authentication when cache returns undefined and database return null', async () => {@@ -130,6 +146,7 @@ describe(AuthBasicGuard.name, () => {authProvider.validateUser = vi.fn().mockReturnValueOnce(null)vi.spyOn(cache, 'set').mockRejectedValueOnce(new Error('cache failed'))context.switchToHttp().getRequest.mockReturnValue({+ ip: requestIp,raw: { user: '' },headers: { authorization: `Basic ${encodedAuth}` }})@@ -143,6 +160,7 @@ describe(AuthBasicGuard.name, () => {it('should not validate the user authentication', async () => {context.switchToHttp().getRequest.mockReturnValue({+ ip: requestIp,raw: { user: '' },headers: { authorization: `Basic ${encodedAuth}` }})@@ -181,4 +199,15 @@ describe(AuthBasicGuard.name, () => {})await expect(authBasicGuard.canActivate(context)).rejects.toThrow()})++ it('should rate limit unknown credentials before calling the authentication provider', async () => {+ cache.get = vi.fn().mockResolvedValueOnce(undefined)+ cache.consumeRateLimit = vi.fn().mockResolvedValueOnce({ totalHits: 61, timeToExpire: 60, isBlocked: true, timeToBlockExpire: 60 })+ authProvider.validateUser = vi.fn()++ await expect(authBasicStrategy.validate({ ip: requestIp } as FastifyRequest, userTest.login, 'unknown-password')).rejects.toThrow(+ AUTH_RATE_LIMIT_ERROR_MESSAGE+ )+ expect(authProvider.validateUser).not.toHaveBeenCalled()+ })})diff --git a/backend/src/authentication/guards/auth-basic.strategy.ts b/backend/src/authentication/guards/auth-basic.strategy.tsindex 910443e0..5a23344d 100644--- a/backend/src/authentication/guards/auth-basic.strategy.ts+++ b/backend/src/authentication/guards/auth-basic.strategy.ts@@ -1,5 +1,6 @@import { Injectable } from '@nestjs/common'import { AbstractStrategy, PassportStrategy } from '@nestjs/passport'+import { ThrottlerException } from '@nestjs/throttler'import { instanceToPlain, plainToInstance } from 'class-transformer'import { FastifyRequest } from 'fastify'import { PinoLogger } from 'nestjs-pino'@@ -7,7 +8,8 @@ import { genHash } from '../../applications/files/utils/files'import { UserModel } from '../../applications/users/models/user.model'import { SERVER_NAME } from '../../common/shared'import { Cache } from '../../infrastructure/cache/cache.service'-import { CACHE_AUTH_WEBDAV_PREFIX, CACHE_AUTH_WEBDAV_TTL } from '../constants/cache'+import { AUTH_RATE_LIMIT_ERROR_MESSAGE, AUTH_WEBDAV_RATE_LIMIT_OPTIONS } from '../constants/auth'+import { CACHE_AUTH_RATE_LIMIT_PREFIX, CACHE_AUTH_WEBDAV_PREFIX, CACHE_AUTH_WEBDAV_TTL } from '../constants/cache'import { AUTH_SCOPE } from '../constants/scope'import { AuthProvider } from '../providers/auth-providers.models'import { HttpBasicStrategy } from './implementations/http-basic.strategy'@@ -28,7 +30,7 @@ export class AuthBasicStrategy extends PassportStrategy(HttpBasicStrategy, 'basiconst basicAuthCacheKey = `${CACHE_AUTH_WEBDAV_PREFIX}-${genHash(`${loginOrEmail}\u0000${password}`, 'sha256')}`const userFromCache: null | undefined | Partial<UserModel> = await this.cache.get(basicAuthCacheKey)if (userFromCache === null) {- // not authorized+ // These credentials were already rejected, so avoid another provider lookup.return null}if (userFromCache !== undefined) {@@ -36,6 +38,20 @@ export class AuthBasicStrategy extends PassportStrategy(HttpBasicStrategy, 'basi// warning: plainToInstance do not use constructor to instantiate the classreturn plainToInstance(UserModel, userFromCache)}++ // Every WebDAV request is authenticated: only rate limit credentials that still require an actual provider lookup.+ // Track by IP across all logins to also prevent password-spraying attempts.+ const rateLimitTracker = genHash(req.ip, 'sha256')+ const rateLimit = await this.cache.consumeRateLimit(+ `${CACHE_AUTH_RATE_LIMIT_PREFIX}-webdav-${rateLimitTracker}`,+ AUTH_WEBDAV_RATE_LIMIT_OPTIONS.ttl,+ AUTH_WEBDAV_RATE_LIMIT_OPTIONS.limit,+ AUTH_WEBDAV_RATE_LIMIT_OPTIONS.blockDuration+ )+ if (rateLimit.isBlocked) {+ throw new ThrottlerException(AUTH_RATE_LIMIT_ERROR_MESSAGE)+ }+const userFromDB: UserModel = await this.authProvider.validateUser(loginOrEmail, password, req.ip, AUTH_SCOPE.WEBDAV)if (userFromDB !== null) {userFromDB.removePassword()diff --git a/backend/src/authentication/guards/auth-rate-limit.guard.spec.ts b/backend/src/authentication/guards/auth-rate-limit.guard.spec.tsnew file mode 100644index 00000000..d8799546--- /dev/null+++ b/backend/src/authentication/guards/auth-rate-limit.guard.spec.ts@@ -0,0 +1,46 @@+import { Controller, Get, UseGuards } from '@nestjs/common'+import { FastifyAdapter, NestFastifyApplication } from '@nestjs/platform-fastify'+import { Test, TestingModule } from '@nestjs/testing'+import { ThrottlerModule } from '@nestjs/throttler'+import { AUTH_RATE_LIMIT_ERROR_MESSAGE, AUTH_RATE_LIMIT_OPTIONS } from '../constants/auth'+import { AuthRateLimitGuard } from './auth-rate-limit.guard'++@Controller('rate-limit-test')+class RateLimitTestController {+ @Get()+ @UseGuards(AuthRateLimitGuard)+ handle(): boolean {+ return true+ }+}++describe(AuthRateLimitGuard.name, () => {+ let app: NestFastifyApplication++ beforeAll(async () => {+ const module: TestingModule = await Test.createTestingModule({+ imports: [ThrottlerModule.forRoot([AUTH_RATE_LIMIT_OPTIONS])],+ controllers: [RateLimitTestController],+ providers: [AuthRateLimitGuard]+ }).compile()++ app = module.createNestApplication<NestFastifyApplication>(new FastifyAdapter())+ await app.init()+ await app.getHttpAdapter().getInstance().ready()+ })++ afterAll(async () => app.close())++ it('should block requests over the limit and expose the retry delay', async () => {+ for (let request = 0; request < AUTH_RATE_LIMIT_OPTIONS.limit; request++) {+ const response = await app.inject({ method: 'GET', url: '/rate-limit-test' })+ expect(response.statusCode).toBe(200)+ }++ const response = await app.inject({ method: 'GET', url: '/rate-limit-test' })++ expect(response.statusCode).toBe(429)+ expect(response.headers['retry-after']).toBe(String(AUTH_RATE_LIMIT_OPTIONS.blockDuration / 1000))+ expect(response.json().message).toBe(AUTH_RATE_LIMIT_ERROR_MESSAGE)+ })+})diff --git a/backend/src/authentication/guards/auth-rate-limit.guard.ts b/backend/src/authentication/guards/auth-rate-limit.guard.tsnew file mode 100644index 00000000..8aaec596--- /dev/null+++ b/backend/src/authentication/guards/auth-rate-limit.guard.ts@@ -0,0 +1,8 @@+import { Injectable } from '@nestjs/common'+import { ThrottlerGuard } from '@nestjs/throttler'+import { AUTH_RATE_LIMIT_ERROR_MESSAGE } from '../constants/auth'++@Injectable()+export class AuthRateLimitGuard extends ThrottlerGuard {+ protected override errorMessage = AUTH_RATE_LIMIT_ERROR_MESSAGE+}diff --git a/backend/src/infrastructure/cache/adapters/mysql-cache.adapter.ts b/backend/src/infrastructure/cache/adapters/mysql-cache.adapter.tsindex 85ef0877..fda760ba 100644--- a/backend/src/infrastructure/cache/adapters/mysql-cache.adapter.ts+++ b/backend/src/infrastructure/cache/adapters/mysql-cache.adapter.ts@@ -7,8 +7,9 @@ import { createCacheKeySlug, currentTimeStamp } from '../../../common/shared'import { configuration } from '../../../configuration/config.environment'import { DB_TOKEN_PROVIDER } from '../../database/constants'import { DBSchema } from '../../database/interfaces/database.interface'-import { dbCheckAffectedRows } from '../../database/utils'+import { dbCheckAffectedRows, dbParseJson } from '../../database/utils'import { SCHEDULER_ENV, SCHEDULER_STATE } from '../../scheduler/scheduler.constants'+import type { CacheRateLimitResult, CacheRateLimitState } from '../interfaces/cache-rate-limit.interface'import { MysqlCache } from '../schemas/mysql-cache.interface'import { cache } from '../schemas/mysql-cache.schema'import { Cache } from '../cache.service'@@ -125,6 +126,50 @@ export class MysqlCacheAdapter implements Cache {}}+ async consumeRateLimit(key: string, ttl: number, limit: number, blockDuration: number): Promise<CacheRateLimitResult> {+ return this.db.transaction(async (tx) => {+ // The no-op upsert creates or locks the row, serializing concurrent workers from the first request.+ await tx+ .insert(cache)+ .values({ key, value: null, expiration: this.infiniteExpiration } satisfies MysqlCache)+ .onDuplicateKeyUpdate({ set: { key: sql`${cache.key}` } })++ const [entry] = await tx+ .select({ value: cache.value, now: sql<number>`UNIX_TIMESTAMP(CURRENT_TIMESTAMP(3)) * 1000`.mapWith(Number) })+ .from(cache)+ .where(eq(cache.key, key))+ .limit(1)+ .for('update')+ const now = entry.now+ const state: CacheRateLimitState = dbParseJson(entry.value) ?? { hits: [], blockExpiresAt: 0 }++ // A completed block starts a fresh window, as in the in-memory throttler storage.+ if (state.blockExpiresAt > 0 && state.blockExpiresAt <= now) {+ state.hits = []+ state.blockExpiresAt = 0+ }+ state.hits = state.hits.filter((expiresAt) => expiresAt > now)+ // Requests received during a block do not extend it.+ if (state.blockExpiresAt === 0) {+ state.hits.push(now + ttl)+ if (state.hits.length > limit) {+ state.blockExpiresAt = now + blockDuration+ }+ }++ // The cache table stores its physical expiration in seconds; throttler durations use milliseconds.+ const expiration = Math.ceil(Math.max(state.blockExpiresAt, ...state.hits) / 1000)+ await tx.update(cache).set({ value: state, expiration }).where(eq(cache.key, key))++ return {+ totalHits: state.hits.length,+ timeToExpire: Math.max(0, Math.ceil(((state.hits[0] ?? now) - now) / 1000)),+ isBlocked: state.blockExpiresAt > now,+ timeToBlockExpire: Math.max(0, Math.ceil((state.blockExpiresAt - now) / 1000))+ }+ })+ }+async set(key: string, data: unknown, ttl?: number): Promise<boolean> {data = this.serialize(data)const exp = this.getTTL(ttl)diff --git a/backend/src/infrastructure/cache/adapters/redis-cache.adapter.ts b/backend/src/infrastructure/cache/adapters/redis-cache.adapter.tsindex 3c4cf1ec..cb9a172d 100644--- a/backend/src/infrastructure/cache/adapters/redis-cache.adapter.ts+++ b/backend/src/infrastructure/cache/adapters/redis-cache.adapter.ts@@ -5,6 +5,7 @@ import { createCacheKeySlug } from '../../../common/shared'import { configuration } from '../../../configuration/config.environment'import { redactRedisUrl } from '../../utils'import { Cache } from '../cache.service'+import type { CacheRateLimitResult } from '../interfaces/cache-rate-limit.interface'@Injectable()export class RedisCacheAdapter implements Cache {@@ -84,6 +85,51 @@ export class RedisCacheAdapter implements Cache {return Number(value)}+ async consumeRateLimit(key: string, ttl: number, limit: number, blockDuration: number): Promise<CacheRateLimitResult> {+ // Keep the complete state transition atomic and use Redis time across workers.+ const result = (await this.client.eval(+ `local time = redis.call('TIME')+ local now = tonumber(time[1]) * 1000 + math.floor(tonumber(time[2]) / 1000)+ local ttl = tonumber(ARGV[1])+ local limit = tonumber(ARGV[2])+ local blockDuration = tonumber(ARGV[3])+ local value = redis.call('GET', KEYS[1])+ local state = value and cjson.decode(value) or { hits = {}, blockExpiresAt = 0 }++ -- A completed block starts a fresh window.+ if state.blockExpiresAt > 0 and state.blockExpiresAt <= now then+ state.hits = {}+ state.blockExpiresAt = 0+ end+ -- Keep only the hits that remain in the sliding window.+ local hits = {}+ for _, expiresAt in ipairs(state.hits) do+ if expiresAt > now then+ table.insert(hits, expiresAt)+ end+ end+ state.hits = hits+ -- Requests received during a block do not extend it.+ if state.blockExpiresAt == 0 then+ table.insert(hits, now + ttl)+ if #hits > limit then+ state.blockExpiresAt = now + blockDuration+ end+ end++ local expiration = state.blockExpiresAt+ for _, expiresAt in ipairs(hits) do+ expiration = math.max(expiration, expiresAt)+ end+ redis.call('SET', KEYS[1], cjson.encode(state), 'PXAT', expiration)+ return { #hits, math.max(0, math.ceil(((hits[1] or now) - now) / 1000)), state.blockExpiresAt > now and 1 or 0,+ math.max(0, math.ceil((state.blockExpiresAt - now) / 1000)) }`,+ { keys: [key], arguments: [String(ttl), String(limit), String(blockDuration)] }+ )) as number[]++ return { totalHits: result[0], timeToExpire: result[1], isBlocked: result[2] === 1, timeToBlockExpire: result[3] }+ }+async set(key: string, data: unknown, ttl?: number): Promise<boolean> {const exp = this.getTTL(ttl)return (await this.client.set(key, this.serialize(data), { expiration: { type: 'EX', value: exp === -1 ? undefined : exp } })) === 'OK'diff --git a/backend/src/infrastructure/cache/cache.e2e-spec.ts b/backend/src/infrastructure/cache/cache.e2e-spec.tsindex 726e1b02..e6d0024a 100644--- a/backend/src/infrastructure/cache/cache.e2e-spec.ts+++ b/backend/src/infrastructure/cache/cache.e2e-spec.ts@@ -83,4 +83,20 @@ describe(Cache.name, () => {it('should create a slug key from parameters', () => {expect(cache.genSlugKey('foo', 'BAR', 12341)).toBe('foo-bar-12341')})++ it('should consume, block and reset a rate limit', async () => {+ const key = 'rate-limit-test'+ await cache.del(key)++ expect(await cache.consumeRateLimit(key, 5_000, 2, 1_000)).toMatchObject({ totalHits: 1, isBlocked: false })+ expect(await cache.consumeRateLimit(key, 5_000, 2, 1_000)).toMatchObject({ totalHits: 2, isBlocked: false })+ expect(await cache.consumeRateLimit(key, 5_000, 2, 1_000)).toMatchObject({ totalHits: 3, isBlocked: true })++ // Blocked requests neither add hits nor extend the block duration.+ expect(await cache.consumeRateLimit(key, 5_000, 2, 1_000)).toMatchObject({ totalHits: 3, isBlocked: true })+ await setTimeout(1_100)+ expect(await cache.consumeRateLimit(key, 5_000, 2, 1_000)).toMatchObject({ totalHits: 1, isBlocked: false })++ await cache.del(key)+ })})diff --git a/backend/src/infrastructure/cache/cache.service.ts b/backend/src/infrastructure/cache/cache.service.tsindex fe2668c1..3c1175f7 100644--- a/backend/src/infrastructure/cache/cache.service.ts+++ b/backend/src/infrastructure/cache/cache.service.ts@@ -1,4 +1,5 @@import { OnModuleDestroy, OnModuleInit } from '@nestjs/common'+import type { CacheRateLimitResult } from './interfaces/cache-rate-limit.interface'export abstract class Cache implements OnModuleInit, OnModuleDestroy {abstract defaultTTL: number@@ -21,6 +22,9 @@ export abstract class Cache implements OnModuleInit, OnModuleDestroy {abstract increment(key: string, amount?: number, ttl?: number, minimum?: number): Promise<number>+ // Atomically consumes a request; ttl and blockDuration are in milliseconds.+ abstract consumeRateLimit(key: string, ttl: number, limit: number, blockDuration: number): Promise<CacheRateLimitResult>+/* ttl (seconds):- 0: infinite expiration- undefined: default ttldiff --git a/backend/src/infrastructure/cache/interfaces/cache-rate-limit.interface.ts b/backend/src/infrastructure/cache/interfaces/cache-rate-limit.interface.tsnew file mode 100644index 00000000..82bd22f6--- /dev/null+++ b/backend/src/infrastructure/cache/interfaces/cache-rate-limit.interface.ts@@ -0,0 +1,13 @@+export interface CacheRateLimitState {+ // Absolute expiration timestamps in milliseconds, including one per request.+ hits: number[]+ blockExpiresAt: number+}++export interface CacheRateLimitResult {+ totalHits: number+ // Remaining durations in seconds.+ timeToExpire: number+ isBlocked: boolean+ timeToBlockExpire: number+}diff --git a/frontend/src/app/applications/admin/components/admin-users.component.html b/frontend/src/app/applications/admin/components/admin-users.component.htmlindex 7f1656be..2fa42986 100644--- a/frontend/src/app/applications/admin/components/admin-users.component.html+++ b/frontend/src/app/applications/admin/components/admin-users.component.html@@ -137,7 +137,7 @@@case ('isActive') {<span class="{{u.isActive ? 'text-success' : 'text-danger'}}" l10nTranslate>@if (!u.isActive && u.passwordAttempts) {- too many login attempts+ Too many login attempts} @else {{{ u.userIsActiveText }}}diff --git a/frontend/src/app/applications/links/components/public/public-link-auth.component.html b/frontend/src/app/applications/links/components/public/public-link-auth.component.htmlindex 61d8ed37..642f8088 100644--- a/frontend/src/app/applications/links/components/public/public-link-auth.component.html+++ b/frontend/src/app/applications/links/components/public/public-link-auth.component.html@@ -11,13 +11,14 @@<div class="input-group input-group-lg" style="max-width: 220px"><input [(ngModel)]="password"(keyup.enter)="validPassword()"- [class.is-invalid]="password?.length < passwordMinLength"+ [class.is-invalid]="retryAfter === 0 && password?.length < passwordMinLength"+ [disabled]="submitted || retryAfter > 0"autocomplete="off"class="form-control"[placeholder]="'Password' | translate:locale.language"type="password"required>- <button [disabled]="password?.length < passwordMinLength"+ <button [disabled]="password?.length < passwordMinLength || submitted || retryAfter > 0"(click)="validPassword()"class="btn btn-custom"type="button">@@ -27,8 +28,15 @@</div><div class="link-text"><span class="hr"></span>- <div>- <span class="info" l10nTranslate>This access is protected by a password</span>+ <div aria-live="polite">+ @if (retryAfter > 0) {+ <span class="info d-block text-danger">{{ 'Too many login attempts' | translate:locale.language }}</span>+ <span class="d-block mt-1 fw-normal opacity-75">+ {{ 'auth_retry_after' | translate:locale.language:{ delay: retryDelayLabel() } }}+ </span>+ } @else {+ <span class="info" l10nTranslate>This access is protected by a password</span>+ }</div></div></div>diff --git a/frontend/src/app/applications/links/components/public/public-link-auth.component.ts b/frontend/src/app/applications/links/components/public/public-link-auth.component.tsindex 3c44da13..4e718a69 100644--- a/frontend/src/app/applications/links/components/public/public-link-auth.component.ts+++ b/frontend/src/app/applications/links/components/public/public-link-auth.component.ts@@ -1,9 +1,11 @@-import { Component, inject } from '@angular/core'+import { Component, inject, OnDestroy } from '@angular/core'import { FormsModule } from '@angular/forms'import { ActivatedRoute, Params, RouterLink } from '@angular/router'import { LucideDynamicIcon, LucideKeyRound, LucideLogIn } from '@lucide/angular'import { USER_PASSWORD_MIN_LENGTH } from '@sync-in-server/backend/src/applications/users/constants/user'import { L10N_LOCALE, L10nLocale, L10nTranslateDirective, L10nTranslatePipe } from 'angular-l10n'+import { finalize } from 'rxjs/operators'+import { getAuthRetryAfter } from '../../../../auth/auth.utils'import { linkProtected } from '../../../files/files.constants'import { LinksService } from '../../services/links.service'@@ -12,23 +14,62 @@ import { LinksService } from '../../services/links.service'imports: [RouterLink, FormsModule, LucideDynamicIcon, L10nTranslatePipe, L10nTranslateDirective],templateUrl: 'public-link-auth.component.html'})-export class PublicLinkAuthComponent {+export class PublicLinkAuthComponent implements OnDestroy {protected readonly locale = inject<L10nLocale>(L10N_LOCALE)protected readonly linkProtected = linkProtectedprotected readonly icons = { LucideKeyRound, LucideLogIn }protected readonly passwordMinLength = USER_PASSWORD_MIN_LENGTHprotected password = ''+ protected retryAfter = 0+ protected submitted = falseprivate readonly activatedRoute = inject(ActivatedRoute)private readonly linksService = inject(LinksService)+ private retryTimer: ReturnType<typeof setInterval> | null = nullprivate uuid: stringconstructor() {this.activatedRoute.params.subscribe((p: Params) => (this.uuid = p.uuid))}+ ngOnDestroy() {+ this.clearRetryCountdown()+ }+validPassword() {- if (this.password && this.password.length >= this.passwordMinLength) {- this.linksService.linkAuthentication(this.uuid, this.password).subscribe(() => (this.password = ''))+ if (!this.password || this.password.length < this.passwordMinLength || this.submitted || this.retryAfter > 0) return++ this.submitted = true+ this.linksService+ .linkAuthentication(this.uuid, this.password)+ .pipe(finalize(() => (this.submitted = false)))+ .subscribe({+ next: () => (this.password = ''),+ error: (e) => {+ this.password = ''+ const retryAfter = getAuthRetryAfter(e)+ if (retryAfter) this.startRetryCountdown(retryAfter)+ }+ })+ }++ protected retryDelayLabel(): string {+ return new Intl.RelativeTimeFormat(this.locale.language, { numeric: 'always' }).format(this.retryAfter, 'second')+ }++ private startRetryCountdown(delay: number) {+ this.clearRetryCountdown()+ const retryAt = Date.now() + delay * 1000+ const updateRetryAfter = () => {+ this.retryAfter = Math.max(0, Math.ceil((retryAt - Date.now()) / 1000))+ if (this.retryAfter === 0) this.clearRetryCountdown()}+ updateRetryAfter()+ if (this.retryAfter > 0) this.retryTimer = setInterval(updateRetryAfter, 1000)+ }++ private clearRetryCountdown() {+ if (this.retryTimer !== null) clearInterval(this.retryTimer)+ this.retryTimer = null+ this.retryAfter = 0}}diff --git a/frontend/src/app/applications/links/links.constants.ts b/frontend/src/app/applications/links/links.constants.tsindex a8b4fb82..7bc03f0b 100644--- a/frontend/src/app/applications/links/links.constants.ts+++ b/frontend/src/app/applications/links/links.constants.ts@@ -1,14 +1,17 @@import { LINK_ERROR } from '@sync-in-server/backend/src/applications/links/constants/links'+import { AUTH_RATE_LIMIT_ERROR_MESSAGE } from '@sync-in-server/backend/src/authentication/constants/auth'export const LINKS_PATH = {LINKS: 'links',LINK: 'link',- AUTH: 'auth'+ AUTH: 'auth',+ RATE_LIMIT: 'rate-limit'}export const LINK_ERROR_TRANSLATION = {[LINK_ERROR.NOT_FOUND]: 'The link was not found',[LINK_ERROR.DISABLED]: 'The link is disabled',[LINK_ERROR.EXPIRED]: 'The link is expired',- [LINK_ERROR.EXCEEDED]: 'The maximum number of access allowed to the link is exceeded'+ [LINK_ERROR.EXCEEDED]: 'The maximum number of access allowed to the link is exceeded',+ [LINKS_PATH.RATE_LIMIT]: AUTH_RATE_LIMIT_ERROR_MESSAGE}diff --git a/frontend/src/app/applications/links/services/links.service.ts b/frontend/src/app/applications/links/services/links.service.tsindex 0a325259..b1302834 100644--- a/frontend/src/app/applications/links/services/links.service.ts+++ b/frontend/src/app/applications/links/services/links.service.ts@@ -23,7 +23,7 @@ import type { UserPasswordDto } from '@sync-in-server/backend/src/applications/uimport type { LoginResponseDto } from '@sync-in-server/backend/src/authentication/dto/login-response.dto'import { BsModalRef } from 'ngx-bootstrap/modal'import { ClipboardService } from 'ngx-clipboard'-import { catchError, map, Observable, of } from 'rxjs'+import { catchError, EMPTY, map, Observable, of, throwError } from 'rxjs'import { take } from 'rxjs/operators'import { AuthService } from '../../../auth/auth.service'import { downloadWithAnchor } from '../../../common/utils/functions'@@ -82,7 +82,11 @@ export class LinksService {}return false}),- catchError((): Observable<false> => {+ catchError((e: HttpErrorResponse): Observable<false> => {+ if (e.status === 429) {+ this.navigateToPublicLinkError(uuid, LINKS_PATH.RATE_LIMIT)+ return of(false)+ }this.authService.logout()return of(false)})@@ -90,26 +94,38 @@ export class LinksService {}linkAccessOrView(uuid: string, link: SpaceLink, fileToView?: FileModel) {- this.http.get<LoginResponseDto>(`${API_PUBLIC_LINK_ACCESS}/${uuid}`).subscribe((r) => {- if (!r.token) {- // Already authenticated- this.authService.initUser(r)- } else {- // First authentication with token- this.authService.initUserFromResponse(r)- }- if (fileToView) {- this.filesService.openViewerDialog(fileToView, [], link.share.permissions).catch(console.error)- } else if (link.space) {- this.router.navigate([SPACES_PATH.SPACES_FILES, link.space.alias]).catch(console.error)- } else {- if (link.share.isDir) {- this.router.navigate([SPACES_PATH.SPACES_SHARES, link.share.alias]).catch(console.error)+ this.http+ .get<LoginResponseDto>(`${API_PUBLIC_LINK_ACCESS}/${uuid}`)+ .pipe(+ catchError((e: HttpErrorResponse) => {+ if (e.status === 429) {+ this.navigateToPublicLinkError(uuid, LINKS_PATH.RATE_LIMIT)+ } else {+ console.error(e)+ }+ return EMPTY+ })+ )+ .subscribe((r) => {+ if (!r.token) {+ // Already authenticated+ this.authService.initUser(r)} else {- this.router.navigate([SPACES_PATH.SPACES_SHARES], { queryParams: { select: link.share.alias } }).catch(console.error)+ // First authentication with token+ this.authService.initUserFromResponse(r)}- }- })+ if (fileToView) {+ this.filesService.openViewerDialog(fileToView, [], link.share.permissions).catch(console.error)+ } else if (link.space) {+ this.router.navigate([SPACES_PATH.SPACES_FILES, link.space.alias]).catch(console.error)+ } else {+ if (link.share.isDir) {+ this.router.navigate([SPACES_PATH.SPACES_SHARES, link.share.alias]).catch(console.error)+ } else {+ this.router.navigate([SPACES_PATH.SPACES_SHARES], { queryParams: { select: link.share.alias } }).catch(console.error)+ }+ }+ })}linkDownload(uuid: string) {@@ -123,7 +139,8 @@ export class LinksService {this.router.navigate([`${LINKS_PATH.LINK}/${uuid}`]).catch(console.error)return true}),- catchError((e) => {+ catchError((e: HttpErrorResponse) => {+ if (e.status === 429) return throwError(() => e)if (e.error.message === LINK_ERROR.UNAUTHORIZED) {this.layout.sendNotification('error', 'Link', 'Bad password')} else {@@ -222,4 +239,8 @@ export class LinksService {private genLink(link: string): string {return `${document.location.origin}/#/${LINKS_PATH.LINK}/${link}`}++ private navigateToPublicLinkError(uuid: string, error: string) {+ this.router.navigate([`${LINKS_PATH.LINK}/${uuid}/${error}`]).catch(console.error)+ }}diff --git a/frontend/src/app/applications/users/components/user-guests.component.html b/frontend/src/app/applications/users/components/user-guests.component.htmlindex 3945f19d..74054d91 100644--- a/frontend/src/app/applications/users/components/user-guests.component.html+++ b/frontend/src/app/applications/users/components/user-guests.component.html@@ -90,7 +90,7 @@@case ('isActive') {<span class="{{u.isActive ? 'text-success' : 'text-danger'}}" l10nTranslate>@if (!u.isActive && u.passwordAttempts) {- too many login attempts+ Too many login attempts} @else {{{ u.userIsActiveText }}}diff --git a/frontend/src/app/auth/auth.component.html b/frontend/src/app/auth/auth.component.htmlindex c884364c..11a157a8 100644--- a/frontend/src/app/auth/auth.component.html+++ b/frontend/src/app/auth/auth.component.html@@ -6,7 +6,16 @@</div><div class="body">@if (twoFaVerify) {- <p class="mb-3 {{hasError ? 'text-danger' : 'text-white-50'}}" l10nTranslate>{{ hasError || 'Two-Factor Authentication' }}</p>+ <p class="mb-3 {{hasError ? 'text-danger' : 'text-white-50'}}" aria-live="polite">+ @if (retryAfter > 0) {+ <span class="d-block">{{ hasError | translate:locale.language }}</span>+ <span class="d-block mt-1 text-white-50">+ {{ 'auth_retry_after' | translate:locale.language:{ delay: retryDelayLabel() } }}+ </span>+ } @else {+ <span l10nTranslate>{{ hasError || 'Two-Factor Authentication' }}</span>+ }+ </p><form (ngSubmit)="onSubmit2Fa()" [formGroup]="twoFaForm"><div class="input-group input-group-lg mt-2 mb-4">@if (isRecoveryCode) {@@ -43,7 +52,7 @@<div class="auth-actions d-flex flex-column flex-sm-row gap-2 mt-4"><button type="button" (click)="onCancel2Fa()" class="btn btn-secondary auth-action-btn" l10nTranslate>Cancel</button><button type="submit"- [disabled]="isRecoveryCode ? twoFaForm.controls.recoveryCode.invalid : twoFaForm.controls.totpCode.invalid || submitted"+ [disabled]="(isRecoveryCode ? twoFaForm.controls.recoveryCode.invalid : twoFaForm.controls.totpCode.invalid) || submitted || retryAfter > 0"class="btn btn-primary auth-action-btn" l10nTranslate>Confirm</button>@@ -51,7 +60,16 @@</form>} @else {<form (ngSubmit)="onSubmit()" [formGroup]="loginForm">- <p class="mb-3 {{hasError ? 'text-danger' : 'text-white-50'}}" l10nTranslate>{{ hasError || 'Sign-in to your account' }}</p>+ <p class="mb-3 {{hasError ? 'text-danger' : 'text-white-50'}}" aria-live="polite">+ @if (retryAfter > 0) {+ <span class="d-block">{{ hasError | translate:locale.language }}</span>+ <span class="d-block mt-1 text-white-50">+ {{ 'auth_retry_after' | translate:locale.language:{ delay: retryDelayLabel() } }}+ </span>+ } @else {+ <span l10nTranslate>{{ hasError || 'Sign-in to your account' }}</span>+ }+ </p><div class="input-group input-group-lg my-2"><span class="input-group-text"><svg [lucideIcon]="icons.LucideUserRound"></svg>@@ -65,7 +83,7 @@<input class="form-control form-control-lg" formControlName="password" [placeholder]="'Password' | translate:locale.language" type="password" /></div><div class="d-flex">- <button type="submit" [disabled]="loginForm.invalid || submitted" class="btn btn-lg btn-primary w-100" l10nTranslate>Sign in</button>+ <button type="submit" [disabled]="loginForm.invalid || submitted || retryAfter > 0" class="btn btn-lg btn-primary w-100" l10nTranslate>Sign in</button></div></form>@if (oidcSettings) {diff --git a/frontend/src/app/auth/auth.component.ts b/frontend/src/app/auth/auth.component.tsindex e919752c..d7af8426 100644--- a/frontend/src/app/auth/auth.component.ts+++ b/frontend/src/app/auth/auth.component.ts@@ -1,4 +1,4 @@-import { Component, inject } from '@angular/core'+import { Component, inject, OnDestroy } from '@angular/core'import { FormGroup, ReactiveFormsModule, UntypedFormBuilder, Validators } from '@angular/forms'import { ActivatedRoute, Router } from '@angular/router'import { LucideDynamicIcon, LucideKeyRound, LucideLock, LucideQrCode, LucideUserRound } from '@lucide/angular'@@ -14,17 +14,19 @@ import { APP_PATH } from '../app.constants'import { AutofocusDirective } from '../common/directives/auto-focus.directive'import type { AuthResult } from './auth.interface'import { AuthService } from './auth.service'+import { getAuthRetryAfter } from './auth.utils'@Component({selector: 'app-auth',templateUrl: 'auth.component.html',imports: [AutofocusDirective, ReactiveFormsModule, LucideDynamicIcon, L10nTranslateDirective, L10nTranslatePipe]})-export class AuthComponent {+export class AuthComponent implements OnDestroy {protected readonly locale = inject<L10nLocale>(L10N_LOCALE)protected readonly icons = { LucideLock, LucideUserRound, LucideKeyRound, LucideQrCode }protected twoFaCodelength = TWO_FA_CODE_LENGTHprotected hasError: any = null+ protected retryAfter = 0protected submitted = falseprotected twoFaVerify = falseprivate route = inject(ActivatedRoute)@@ -32,6 +34,7 @@ export class AuthComponent {private readonly router = inject(Router)private readonly auth = inject(AuthService)private readonly fb = inject(UntypedFormBuilder)+ private retryTimer: ReturnType<typeof setInterval> | null = nullprotected loginForm: FormGroup = this.fb.group({username: this.fb.control('', [Validators.required]),password: this.fb.control('', [Validators.required])@@ -51,30 +54,46 @@ export class AuthComponent {}}+ ngOnDestroy() {+ this.clearRetryCountdown()+ }+onSubmit() {+ if (this.retryAfter > 0) returnthis.submitted = truethis.auth.login(this.loginForm.value.username, this.loginForm.value.password).pipe(finalize(() => setTimeout(() => (this.submitted = false), 1500))).subscribe({next: (res: AuthResult) => this.isLogged(res),- error: (e) => this.isLogged({ success: false, message: e.error ? e.error.message : e })+ error: (e) => this.isLogged({ success: false, message: e.error ? e.error.message : e, retryAfter: getAuthRetryAfter(e) })})}async onSubmit2Fa() {+ if (this.retryAfter > 0) returnthis.submitted = trueconst code = this.isRecoveryCode ? this.twoFaForm.value.recoveryCode : this.twoFaForm.value.totpCodeif (this.auth.electron.enabled) {this.auth.electron.register(this.loginForm.value.username, this.loginForm.value.password, code).subscribe({next: (res: AuthResult) => this.is2FaVerified(res as TwoFaResponseDto),- error: (e) => this.is2FaVerified({ success: false, message: e.error ? e.error.message : e } as TwoFaResponseDto)+ error: (e) =>+ this.is2FaVerified({+ success: false,+ message: e.error ? e.error.message : e,+ retryAfter: getAuthRetryAfter(e)+ } as TwoFaResponseDto & AuthResult)})} else {this.auth.loginWith2Fa({ code: code, isRecoveryCode: this.isRecoveryCode } satisfies TwoFaVerifyDto).subscribe({next: (res: TwoFaResponseDto) => this.is2FaVerified(res),- error: (e) => this.is2FaVerified({ success: false, message: e.error ? e.error.message : e } as TwoFaResponseDto)+ error: (e) =>+ this.is2FaVerified({+ success: false,+ message: e.error ? e.error.message : e,+ retryAfter: getAuthRetryAfter(e)+ } as TwoFaResponseDto & AuthResult)})}}@@ -85,6 +104,7 @@ export class AuthComponent {this.twoFaVerify = falsethis.submitted = falsethis.hasError = null+ this.clearRetryCountdown()}async loginWithOIDC() {@@ -125,15 +145,20 @@ export class AuthComponent {}}- private is2FaVerified(res: TwoFaResponseDto) {+ protected retryDelayLabel(): string {+ return new Intl.RelativeTimeFormat(this.locale.language, { numeric: 'always' }).format(this.retryAfter, 'second')+ }++ private is2FaVerified(res: TwoFaResponseDto & Partial<AuthResult>) {if (res.success) {+ this.clearRetryCountdown()if (!this.auth.electron.enabled) {// Web: in this case, the user and tokens are providedthis.auth.initUserFromResponse(res)}this.isLogged({ success: true, message: res.message })} else {- this.hasError = res.message || 'Unable to verify code'+ this.setAuthError(res.message || 'Unable to verify code', res.retryAfter)this.submitted = false}this.twoFaForm.patchValue({ totpCode: '', recoveryCode: '' })@@ -141,6 +166,7 @@ export class AuthComponent {private isLogged(res: AuthResult) {if (res.success) {+ this.clearRetryCountdown()this.hasError = nullif (res.twoFaEnabled) {this.twoFaVerify = true@@ -157,9 +183,32 @@ export class AuthComponent {this.router.navigate([APP_PATH.HOME]).then(() => this.loginForm.reset())}} else {- this.hasError = res.message || 'Server connection error'+ this.setAuthError(res.message || 'Server connection error', res.retryAfter)this.submitted = false}this.loginForm.patchValue({ password: '' })}++ private setAuthError(message: any, retryAfter?: number) {+ this.clearRetryCountdown()+ this.hasError = retryAfter ? 'Too many login attempts' : message+ if (!retryAfter) return++ const retryAt = Date.now() + retryAfter * 1000+ const updateRetryAfter = () => {+ this.retryAfter = Math.max(0, Math.ceil((retryAt - Date.now()) / 1000))+ if (this.retryAfter === 0) {+ this.clearRetryCountdown()+ this.hasError = null+ }+ }+ updateRetryAfter()+ if (this.retryAfter > 0) this.retryTimer = setInterval(updateRetryAfter, 1000)+ }++ private clearRetryCountdown() {+ if (this.retryTimer !== null) clearInterval(this.retryTimer)+ this.retryTimer = null+ this.retryAfter = 0+ }}diff --git a/frontend/src/app/auth/auth.interface.ts b/frontend/src/app/auth/auth.interface.tsindex 20b8818a..c851e5d8 100644--- a/frontend/src/app/auth/auth.interface.ts+++ b/frontend/src/app/auth/auth.interface.ts@@ -2,6 +2,7 @@ export interface AuthResult {success: booleanmessage: anytwoFaEnabled?: boolean+ retryAfter?: number}export interface AuthOIDCQueryParams {diff --git a/frontend/src/app/auth/auth.service.ts b/frontend/src/app/auth/auth.service.tsindex 5483a273..2972f4a1 100644--- a/frontend/src/app/auth/auth.service.ts+++ b/frontend/src/app/auth/auth.service.ts@@ -33,6 +33,7 @@ import { LayoutService } from '../layout/layout.service'import { StoreService } from '../store/store.service'import { AUTH_PATHS } from './auth.constants'import type { AuthOIDCQueryParams, AuthResult } from './auth.interface'+import { AUTH_RATE_LIMIT_ERROR_MESSAGE, getAuthRetryAfter, isDesktopRateLimitError } from './auth.utils'@Injectable({providedIn: 'root'@@ -88,9 +89,14 @@ export class AuthService {this.initUserFromResponse(r)return of<AuthResult>({ success: true, message: null })}),- catchError((e) => {+ catchError((e: HttpErrorResponse) => {console.error(e)- return of<AuthResult>({ success: false, message: e?.error?.message ?? e?.message })+ const retryAfter = getAuthRetryAfter(e)+ return of<AuthResult>({+ success: false,+ message: e?.error?.message ?? e?.message,+ retryAfter+ })}))}@@ -275,6 +281,7 @@ export class AuthService {)}console.error(`${this.authOIDCDesktopClient.name} - ${message}`)+ this.notifyDesktopRateLimit(e)this.logout(true)return of(false)})@@ -347,6 +354,7 @@ export class AuthService {private handleDesktopAuthError(e: unknown): Observable<boolean> {const message = this.desktopAuthErrorMessage(e)console.debug(`${this.authDesktopClient.name} - ${message}`)+ this.notifyDesktopRateLimit(e)if (message === CLIENT_TOKEN_EXPIRED_ERROR) {this.electron.send(EVENT.SERVER.AUTHENTICATION_TOKEN_EXPIRED)} else if (message !== CLIENT_MISSING_ERROR) {@@ -357,6 +365,8 @@ export class AuthService {}private desktopAuthErrorMessage(e: unknown): string {+ if (isDesktopRateLimitError(e)) return AUTH_RATE_LIMIT_ERROR_MESSAGE+const rawMessage = (e as HttpErrorResponse)?.error?.message ?? (e as Error)?.message ?? econst message = Array.isArray(rawMessage) ? rawMessage.join(', ') : String(rawMessage)if (message.includes(CLIENT_TOKEN_EXPIRED_ERROR)) {@@ -368,6 +378,12 @@ export class AuthService {return message}+ private notifyDesktopRateLimit(e: unknown) {+ if (isDesktopRateLimitError(e)) {+ this.layout.sendNotification('error', 'Authentication', AUTH_RATE_LIMIT_ERROR_MESSAGE)+ }+ }+private refreshTokenHasExpired(): boolean {return this.refreshExpiration === 0 || currentTimeStamp() >= this.refreshExpiration}diff --git a/frontend/src/app/auth/auth.utils.ts b/frontend/src/app/auth/auth.utils.tsnew file mode 100644index 00000000..1ca2f0c4--- /dev/null+++ b/frontend/src/app/auth/auth.utils.ts@@ -0,0 +1,16 @@+import { HttpErrorResponse } from '@angular/common/http'+import { AUTH_RATE_LIMIT_ERROR_MESSAGE, AUTH_RATE_LIMIT_OPTIONS } from '@sync-in-server/backend/src/authentication/constants/auth'++export { AUTH_RATE_LIMIT_ERROR_MESSAGE }++export function getAuthRetryAfter(error: unknown): number | undefined {+ if (!(error instanceof HttpErrorResponse) || error.status !== 429) return undefined++ const retryAfter = Number.parseInt(error.headers.get('Retry-After') ?? '', 10)+ return retryAfter > 0 ? retryAfter : Math.ceil(AUTH_RATE_LIMIT_OPTIONS.blockDuration / 1000)+}++export function isDesktopRateLimitError(error: unknown): boolean {+ const message = error instanceof Error ? error.message : String(error)+ return message.includes(AUTH_RATE_LIMIT_ERROR_MESSAGE)+}diff --git a/frontend/src/i18n/de.json b/frontend/src/i18n/de.jsonindex 6b8e6fff..b1da18e1 100644--- a/frontend/src/i18n/de.json+++ b/frontend/src/i18n/de.json@@ -177,7 +177,9 @@"Password has been updated": "Passwort wurde aktualisiert","Unable to update password": "Passwort kann nicht aktualisiert werden","Bad password": "Falsches Passwort",- "too many login attempts": "zu viele Anmeldeversuche",+ "Too many login attempts": "Zu viele Anmeldeversuche",+ "auth_retry_after": "Erneut versuchen {{ delay }}",+ "Too many requests. Please try again later.": "Zu viele Anfragen. Bitte versuchen Sie es später erneut.","Language": "Sprache","Language updated": "Sprache aktualisiert","Unable to update language": "Sprache kann nicht aktualisiert werden",diff --git a/frontend/src/i18n/en.json b/frontend/src/i18n/en.jsonindex afa66d17..1c4225de 100644--- a/frontend/src/i18n/en.json+++ b/frontend/src/i18n/en.json@@ -11,6 +11,9 @@"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 ?",diff --git a/frontend/src/i18n/es.json b/frontend/src/i18n/es.jsonindex 07cbb776..d9b7390a 100644--- a/frontend/src/i18n/es.json+++ b/frontend/src/i18n/es.json@@ -177,7 +177,9 @@"Password has been updated": "La contraseña ha sido actualizada","Unable to update password": "No se puede actualizar la contraseña","Bad password": "Contraseña incorrecta",- "too many login attempts": "demasiados intentos de inicio de sesión",+ "Too many login attempts": "Demasiados intentos de inicio de sesión",+ "auth_retry_after": "Vuelve a intentarlo {{ delay }}",+ "Too many requests. Please try again later.": "Demasiadas solicitudes. Inténtalo de nuevo más tarde.","Language": "Idioma","Language updated": "Idioma actualizado","Unable to update language": "No se puede actualizar el idioma",diff --git a/frontend/src/i18n/fr.json b/frontend/src/i18n/fr.jsonindex 85843ed6..7cc2253e 100644--- a/frontend/src/i18n/fr.json+++ b/frontend/src/i18n/fr.json@@ -177,7 +177,9 @@"Password has been updated": "Mot de passe mis à jour","Unable to update password": "Impossible de mettre à jour le mot de passe","Bad password": "Mauvais mot de passe",- "too many login attempts": "trop de tentatives de connexion",+ "Too many login attempts": "Trop de tentatives de connexion",+ "auth_retry_after": "Nouvelle tentative {{ delay }}",+ "Too many requests. Please try again later.": "Trop de requêtes. Veuillez réessayer plus tard.","Language": "Langue","Language updated": "Langue mise à jour","Unable to update language": "Impossible de mettre à jour la langue",diff --git a/frontend/src/i18n/hi.json b/frontend/src/i18n/hi.jsonindex 4e240941..693b9330 100644--- a/frontend/src/i18n/hi.json+++ b/frontend/src/i18n/hi.json@@ -177,7 +177,9 @@"Password has been updated": "पासवर्ड अपडेट किया गया","Unable to update password": "पासवर्ड अपडेट नहीं किया जा सका","Bad password": "गलत पासवर्ड",- "too many login attempts": "बहुत अधिक लॉगिन प्रयास",+ "Too many login attempts": "बहुत अधिक लॉगिन प्रयास",+ "auth_retry_after": "{{ delay }} पुनः प्रयास करें",+ "Too many requests. Please try again later.": "बहुत अधिक अनुरोध। कृपया बाद में पुनः प्रयास करें।","Language": "भाषा","Language updated": "भाषा अपडेट की गई","Unable to update language": "भाषा अपडेट नहीं की जा सकी",diff --git a/frontend/src/i18n/it.json b/frontend/src/i18n/it.jsonindex b6b42c81..c6e05f22 100644--- a/frontend/src/i18n/it.json+++ b/frontend/src/i18n/it.json@@ -177,7 +177,9 @@"Password has been updated": "La password è stata aggiornata","Unable to update password": "Impossibile aggiornare la password","Bad password": "Password errata",- "too many login attempts": "troppi tentativi di accesso",+ "Too many login attempts": "Troppi tentativi di accesso",+ "auth_retry_after": "Riprova {{ delay }}",+ "Too many requests. Please try again later.": "Troppe richieste. Riprova più tardi.","Language": "Lingua","Language updated": "Lingua aggiornata","Unable to update language": "Impossibile aggiornare la lingua",diff --git a/frontend/src/i18n/ja.json b/frontend/src/i18n/ja.jsonindex 0ae6e1a9..c0b2be88 100644--- a/frontend/src/i18n/ja.json+++ b/frontend/src/i18n/ja.json@@ -177,7 +177,9 @@"Password has been updated": "パスワードを更新しました","Unable to update password": "パスワードを更新できません","Bad password": "不正なパスワード",- "too many login attempts": "ログイン試行が多すぎます",+ "Too many login attempts": "ログイン試行が多すぎます",+ "auth_retry_after": "{{ delay }}にもう一度お試しください",+ "Too many requests. Please try again later.": "リクエストが多すぎます。後でもう一度お試しください。","Language": "言語","Language updated": "言語を更新しました","Unable to update language": "言語を更新できません",diff --git a/frontend/src/i18n/ko.json b/frontend/src/i18n/ko.jsonindex e9988c40..6a1a28d6 100644--- a/frontend/src/i18n/ko.json+++ b/frontend/src/i18n/ko.json@@ -177,7 +177,9 @@"Password has been updated": "비밀번호가 업데이트되었습니다","Unable to update password": "비밀번호를 업데이트할 수 없습니다","Bad password": "잘못된 비밀번호",- "too many login attempts": "로그인 시도가 너무 많습니다",+ "Too many login attempts": "로그인 시도가 너무 많습니다",+ "auth_retry_after": "{{ delay }} 다시 시도하세요",+ "Too many requests. Please try again later.": "요청이 너무 많습니다. 나중에 다시 시도하세요.","Language": "언어","Language updated": "언어가 업데이트되었습니다","Unable to update language": "언어를 업데이트할 수 없습니다",diff --git a/frontend/src/i18n/nl.json b/frontend/src/i18n/nl.jsonindex b12b2985..6fe2e160 100644--- a/frontend/src/i18n/nl.json+++ b/frontend/src/i18n/nl.json@@ -177,7 +177,9 @@"Password has been updated": "Wachtwoord is bijgewerkt","Unable to update password": "Wachtwoord kan niet worden bijgewerkt","Bad password": "Slecht wachtwoord",- "too many login attempts": "te veel inlogpogingen",+ "Too many login attempts": "Te veel inlogpogingen",+ "auth_retry_after": "Probeer het opnieuw {{ delay }}",+ "Too many requests. Please try again later.": "Te veel verzoeken. Probeer het later opnieuw.","Language": "Taal","Language updated": "Taal bijgewerkt","Unable to update language": "Kan taal niet bijwerken",diff --git a/frontend/src/i18n/pl.json b/frontend/src/i18n/pl.jsonindex 2f50d779..56ec23c0 100644--- a/frontend/src/i18n/pl.json+++ b/frontend/src/i18n/pl.json@@ -177,7 +177,9 @@"Password has been updated": "Hasło zostało zaktualizowane","Unable to update password": "Nie można zaktualizować hasła","Bad password": "Nieprawidłowe hasło",- "too many login attempts": "zbyt wiele prób logowania",+ "Too many login attempts": "Zbyt wiele prób logowania",+ "auth_retry_after": "Spróbuj ponownie {{ delay }}",+ "Too many requests. Please try again later.": "Zbyt wiele żądań. Spróbuj ponownie później.","Language": "Język","Language updated": "Zaktualizowano język","Unable to update language": "Nie można zaktualizować języka",diff --git a/frontend/src/i18n/pt-BR.json b/frontend/src/i18n/pt-BR.jsonindex c8f7d4df..07e10757 100644--- a/frontend/src/i18n/pt-BR.json+++ b/frontend/src/i18n/pt-BR.json@@ -177,7 +177,9 @@"Password has been updated": "A senha foi atualizada","Unable to update password": "Não foi possível atualizar a senha","Bad password": "Senha incorreta",- "too many login attempts": "muitas tentativas de login",+ "Too many login attempts": "Muitas tentativas de login",+ "auth_retry_after": "Tente novamente {{ delay }}",+ "Too many requests. Please try again later.": "Muitas solicitações. Tente novamente mais tarde.","Language": "Idioma","Language updated": "Idioma atualizado","Unable to update language": "Não foi possível atualizar o idioma",diff --git a/frontend/src/i18n/pt.json b/frontend/src/i18n/pt.jsonindex 38b7d82a..ee15ab2c 100644--- a/frontend/src/i18n/pt.json+++ b/frontend/src/i18n/pt.json@@ -177,7 +177,9 @@"Password has been updated": "A senha foi atualizada","Unable to update password": "Não é possível atualizar a senha","Bad password": "Senha incorreta",- "too many login attempts": "muitas tentativas de login",+ "Too many login attempts": "Muitas tentativas de login",+ "auth_retry_after": "Tente novamente {{ delay }}",+ "Too many requests. Please try again later.": "Demasiados pedidos. Tente novamente mais tarde.","Language": "Idioma","Language updated": "Idioma atualizado","Unable to update language": "Não é possível atualizar o idioma",diff --git a/frontend/src/i18n/ru.json b/frontend/src/i18n/ru.jsonindex 14b577d1..e5746603 100644--- a/frontend/src/i18n/ru.json+++ b/frontend/src/i18n/ru.json@@ -177,7 +177,9 @@"Password has been updated": "Пароль обновлён","Unable to update password": "Не удалось обновить пароль","Bad password": "Неверный пароль",- "too many login attempts": "слишком много попыток входа",+ "Too many login attempts": "Слишком много попыток входа",+ "auth_retry_after": "Повторите попытку {{ delay }}",+ "Too many requests. Please try again later.": "Слишком много запросов. Повторите попытку позже.","Language": "Язык","Language updated": "Язык обновлён","Unable to update language": "Не удалось обновить язык",diff --git a/frontend/src/i18n/tr.json b/frontend/src/i18n/tr.jsonindex e8074b1a..33254a80 100644--- a/frontend/src/i18n/tr.json+++ b/frontend/src/i18n/tr.json@@ -177,7 +177,9 @@"Password has been updated": "Parola güncellendi","Unable to update password": "Parola güncellenemedi","Bad password": "Hatalı parola",- "too many login attempts": "çok fazla giriş denemesi",+ "Too many login attempts": "Çok fazla giriş denemesi",+ "auth_retry_after": "{{ delay }} tekrar deneyin",+ "Too many requests. Please try again later.": "Çok fazla istek. Lütfen daha sonra tekrar deneyin.","Language": "Dil","Language updated": "Dil güncellendi","Unable to update language": "Dil güncellenemedi",diff --git a/frontend/src/i18n/zh.json b/frontend/src/i18n/zh.jsonindex 2d55197c..447197c7 100644--- a/frontend/src/i18n/zh.json+++ b/frontend/src/i18n/zh.json@@ -177,7 +177,9 @@"Password has been updated": "密码已更新","Unable to update password": "无法更新密码","Bad password": "密码错误",- "too many login attempts": "登录尝试次数过多",+ "Too many login attempts": "登录尝试次数过多",+ "auth_retry_after": "{{ delay }}重试",+ "Too many requests. Please try again later.": "请求过多,请稍后重试。","Language": "语言","Language updated": "语言已更新","Unable to update language": "无法更新语言",diff --git a/package-lock.json b/package-lock.jsonindex a1b52b57..c72c5898 100644--- a/package-lock.json+++ b/package-lock.json@@ -59,6 +59,7 @@"@nestjs/platform-fastify": "^11.1.24","@nestjs/platform-socket.io": "^11.1.24","@nestjs/schedule": "^6.1.3",+ "@nestjs/throttler": "^6.5.0","@nestjs/websockets": "^11.1.24","@socket.io/cluster-adapter": "^0.3.0","@socket.io/redis-adapter": "^8.3.0",@@ -6665,6 +6666,17 @@}}},+ "node_modules/@nestjs/throttler": {+ "version": "6.5.0",+ "resolved": "https://registry.npmjs.org/@nestjs/throttler/-/throttler-6.5.0.tgz",+ "integrity": "sha512-9j0ZRfH0QE1qyrj9JjIRDz5gQLPqq9yVC2nHsrosDVAfI5HHw08/aUAWx9DZLSdQf4HDkmhTTEGLrRFHENvchQ==",+ "license": "MIT",+ "peerDependencies": {+ "@nestjs/common": "^7.0.0 || ^8.0.0 || ^9.0.0 || ^10.0.0 || ^11.0.0",+ "@nestjs/core": "^7.0.0 || ^8.0.0 || ^9.0.0 || ^10.0.0 || ^11.0.0",+ "reflect-metadata": "^0.1.13 || ^0.2.0"+ }+ },"node_modules/@nestjs/websockets": {"version": "11.2.3","resolved": "https://registry.npmjs.org/@nestjs/websockets/-/websockets-11.2.3.tgz",