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): refresh browser user state with token renewal
johavencad5f12fe0a5
diff --git a/backend/src/app.e2e-spec.ts b/backend/src/app.e2e-spec.tsindex eaa979bf..e9f46687 100644--- a/backend/src/app.e2e-spec.ts+++ b/backend/src/app.e2e-spec.ts@@ -1,6 +1,5 @@import { NestFastifyApplication } from '@nestjs/platform-fastify'import { appBootstrap } from './app.bootstrap'-import { dbCloseConnection } from './infrastructure/database/utils'describe('AppStaticFiles (e2e)', () => {let app: NestFastifyApplication@@ -12,7 +11,6 @@ describe('AppStaticFiles (e2e)', () => {})afterAll(async () => {- await dbCloseConnection(app)await app.close()})diff --git a/backend/src/authentication/auth.controller.spec.ts b/backend/src/authentication/auth.controller.spec.tsindex 3169621f..c2bc3215 100755--- a/backend/src/authentication/auth.controller.spec.ts+++ b/backend/src/authentication/auth.controller.spec.ts@@ -129,13 +129,16 @@ describe(AuthController.name, () => {})it('should refresh JWT in cookies', async () => {- userTest.exp = currentTimeStamp() + convertHumanTimeToSeconds('30s')+ const currentTime = currentTimeStamp()+ userTest.exp = currentTime + convertHumanTimeToSeconds('30s')const res: any = { setCookie: vi.fn() }const result = await authController.refreshCookies(userTest, res)expect(result).toBeDefined()+ expect(result).toBeInstanceOf(LoginResponseDto)+ expect(result.user).toBe(userTest)expect(res.setCookie).toHaveBeenCalledTimes(4)- expect(result.access_expiration).toBeCloseTo(convertHumanTimeToSeconds(authConfig.token.access.expiration) + currentTimeStamp(), -1)- expect(result.refresh_expiration).toBe(userTest.exp)+ expect(result.token.access_expiration).toBeCloseTo(convertHumanTimeToSeconds(authConfig.token.access.expiration) + currentTime, -1)+ expect(result.token.refresh_expiration).toBe(userTest.exp)})it('should not refresh JWT in cookies', async () => {diff --git a/backend/src/authentication/auth.controller.ts b/backend/src/authentication/auth.controller.tsindex 7fb43a33..56216443 100755--- a/backend/src/authentication/auth.controller.ts+++ b/backend/src/authentication/auth.controller.ts@@ -45,7 +45,7 @@ export class AuthController {@Post(AUTH_ROUTE.REFRESH)@AuthTokenSkip()@UseGuards(AuthTokenRefreshGuard)- refreshCookies(@GetUser() user: UserModel, @Res({ passthrough: true }) res: FastifyReply): Promise<TokenResponseDto> {+ refreshCookies(@GetUser() user: UserModel, @Res({ passthrough: true }) res: FastifyReply): Promise<LoginResponseDto> {return this.authManager.refreshCookies(user, res)}diff --git a/backend/src/authentication/auth.e2e-spec.ts b/backend/src/authentication/auth.e2e-spec.tsindex 74b45abb..5b9b1ae3 100644--- a/backend/src/authentication/auth.e2e-spec.ts+++ b/backend/src/authentication/auth.e2e-spec.ts@@ -1,6 +1,8 @@import { ConfigService } from '@nestjs/config'import { JwtService } from '@nestjs/jwt'import { NestFastifyApplication } from '@nestjs/platform-fastify'+import { Type } from 'class-transformer'+import { IsInt, ValidateNested } from 'class-validator'import { appBootstrap } from '../app.bootstrap'import { USER_ROLE } from '../applications/users/constants/user'import { DeleteUserDto } from '../applications/users/dto/delete-user.dto'@@ -17,6 +19,29 @@ import { TokenResponseDto } from './dto/token-response.dto'import { JwtPayload } from './interfaces/jwt-payload.interface'import { TOKEN_TYPE } from './interfaces/token.interface'+class BrowserRefreshUserResponseDto {+ @IsInt()+ id: number+}++class BrowserRefreshTokenResponseDto {+ @IsInt()+ access_expiration: number++ @IsInt()+ refresh_expiration: number+}++class BrowserRefreshResponseDto {+ @ValidateNested()+ @Type(() => BrowserRefreshUserResponseDto)+ user: BrowserRefreshUserResponseDto++ @ValidateNested()+ @Type(() => BrowserRefreshTokenResponseDto)+ token: BrowserRefreshTokenResponseDto+}+describe('Auth (e2e)', () => {let app: NestFastifyApplicationlet authConfig: AuthConfig@@ -210,6 +235,10 @@ describe('Auth (e2e)', () => {cookies: { [authConfig.token.refresh.name]: refreshToken }})expect(res.statusCode).toEqual(201)+ const content = transformAndValidate(BrowserRefreshResponseDto, res.json())+ expect(content.user.id).toBe(userTest.id)+ const expectedAccessExpiration = currentTimeStamp() + convertHumanTimeToSeconds(authConfig.token.access.expiration)+ expect(content.token.access_expiration).toBeCloseTo(expectedAccessExpiration, -1)const cookies: { type: TOKEN_TYPE; content: string[] }[] = getCookies(res.headers['set-cookie'] as string[])cookiesChecks(cookies)})diff --git a/backend/src/authentication/auth.service.ts b/backend/src/authentication/auth.service.tsindex b1a7a857..0b9f1fdb 100755--- a/backend/src/authentication/auth.service.ts+++ b/backend/src/authentication/auth.service.ts@@ -72,18 +72,16 @@ export class AuthManager {return response}- async refreshCookies(user: UserModel, res: FastifyReply): Promise<TokenResponseDto> {- const response = {} as TokenResponseDto+ async refreshCookies(user: UserModel, res: FastifyReply): Promise<LoginResponseDto> {+ const response = new LoginResponseDto(user, serverConfig)const currentTime = currentTimeStamp()- let refreshTokenExpiration: number// refresh cookie must have the `exp` attribute// reuse token expiration to make it final- if (user.exp && user.exp > currentTime) {- refreshTokenExpiration = user.exp - currentTime- } else {+ if (!user.exp || user.exp <= currentTime) {this.logger.error({ tag: this.refreshCookies.name, msg: `token ${TOKEN_TYPE.REFRESH} has incorrect expiration : *${user.login}*` })throw new HttpException('Token has expired', HttpStatus.FORBIDDEN)}+ const refreshTokenExpiration = user.exp - currentTimeconst csrfToken: string = crypto.randomUUID()for (const type of TOKEN_TYPES) {const tokenExpiration =@@ -96,7 +94,7 @@ export class AuthManager {httpOnly: type !== TOKEN_TYPE.CSRF})if (type === TOKEN_TYPE.ACCESS || type === TOKEN_TYPE.REFRESH) {- response[`${type}_expiration`] = tokenExpiration + currentTime+ response.token[`${type}_expiration`] = tokenExpiration + currentTime}}return responsediff --git a/backend/vitest-e2e.config.mts b/backend/vitest-e2e.config.mtsindex c200d1d2..9d214bfc 100644--- a/backend/vitest-e2e.config.mts+++ b/backend/vitest-e2e.config.mts@@ -7,12 +7,13 @@ export default defineConfig({globals: true,root: './',testTimeout: 30000,+ typecheck: {+ enabled: true+ },coverage: {provider: 'v8',reportsDirectory: '../coverage/e2e',- include: [- 'src/**/*.controller.{ts,js}'- ]+ include: ['src/**/*.controller.{ts,js}']}},plugins: [diff --git a/frontend/src/app/auth/auth.service.ts b/frontend/src/app/auth/auth.service.tsindex c93eb8b5..34b831e9 100644--- a/frontend/src/app/auth/auth.service.ts+++ b/frontend/src/app/auth/auth.service.ts@@ -15,7 +15,6 @@ import {API_TWO_FA_LOGIN_VERIFY} from '@sync-in-server/backend/src/authentication/constants/routes'import type { LoginResponseDto } from '@sync-in-server/backend/src/authentication/dto/login-response.dto'-import type { TokenResponseDto } from '@sync-in-server/backend/src/authentication/dto/token-response.dto'import type { AuthOIDCSettings } from '@sync-in-server/backend/src/authentication/providers/oidc/auth-oidc.interfaces'import type { TwoFaResponseDto, TwoFaVerifyDto } from '@sync-in-server/backend/src/authentication/providers/two-fa/auth-two-fa.dtos'import { currentTimeStamp } from '@sync-in-server/backend/src/common/shared'@@ -129,10 +128,9 @@ export class AuthService {}refreshToken(): Observable<boolean> {- return this.http.post<TokenResponseDto>(API_AUTH_REFRESH, null).pipe(+ return this.http.post<LoginResponseDto>(API_AUTH_REFRESH, null).pipe(map((r) => {- this.accessExpiration = r.access_expiration- this.refreshExpiration = r.refresh_expiration+ this.initUserFromResponse(r)return true}),catchError((e: HttpErrorResponse) => {