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): support desktop app OIDC authentication flow
johaven0d6963f95a86
diff --git a/backend/src/applications/sync/dtos/sync-client-auth.dto.ts b/backend/src/applications/sync/dtos/sync-client-auth.dto.tsindex 174763be..0086b94b 100644--- a/backend/src/applications/sync/dtos/sync-client-auth.dto.ts+++ b/backend/src/applications/sync/dtos/sync-client-auth.dto.ts@@ -4,8 +4,9 @@* See the LICENSE file for licensing details*/-import { IsBoolean, IsDefined, IsNotEmpty, IsNotEmptyObject, IsObject, IsOptional, IsString, IsUUID } from 'class-validator'-import type { SyncClientInfo } from '../interfaces/sync-client.interface'+import { Type } from 'class-transformer'+import { IsBoolean, IsDefined, IsNotEmpty, IsNotEmptyObject, IsObject, IsOptional, IsString, IsUUID, ValidateNested } from 'class-validator'+import { SyncClientInfoDto } from './sync-client-info.dto'export class SyncClientAuthDto {@IsNotEmpty()@@ -19,9 +20,11 @@ export class SyncClientAuthDto {token: string@IsDefined()- @IsNotEmptyObject()@IsObject()- info: SyncClientInfo+ @IsNotEmptyObject()+ @ValidateNested()+ @Type(() => SyncClientInfoDto)+ info: SyncClientInfoDto@IsOptional()@IsBoolean()diff --git a/backend/src/applications/sync/dtos/sync-client-info.dto.ts b/backend/src/applications/sync/dtos/sync-client-info.dto.tsnew file mode 100644index 00000000..32c4a410--- /dev/null+++ b/backend/src/applications/sync/dtos/sync-client-info.dto.ts@@ -0,0 +1,29 @@+/*+ * Copyright (C) 2012-2026 Johan Legrand <[email protected]>+ * This file is part of Sync-in | The open source file sync and share solution+ * See the LICENSE file for licensing details+ */++import { IsEnum, IsString } from 'class-validator'+import { SYNC_CLIENT_TYPE } from '../constants/sync'+import { SyncClientInfo } from '../interfaces/sync-client.interface'++export class SyncClientInfoDto implements SyncClientInfo {+ @IsString()+ node: string++ @IsString()+ os: string++ @IsString()+ osRelease: string++ @IsString()+ user: string++ @IsEnum(SYNC_CLIENT_TYPE)+ type: SYNC_CLIENT_TYPE++ @IsString()+ version: string+}diff --git a/backend/src/applications/sync/dtos/sync-client-registration.dto.ts b/backend/src/applications/sync/dtos/sync-client-registration.dto.tsindex 8598e738..0d8e17fb 100644--- a/backend/src/applications/sync/dtos/sync-client-registration.dto.ts+++ b/backend/src/applications/sync/dtos/sync-client-registration.dto.ts@@ -4,8 +4,9 @@* See the LICENSE file for licensing details*/-import { IsDefined, IsNotEmpty, IsNotEmptyObject, IsObject, IsOptional, IsString, IsUUID } from 'class-validator'-import { SyncClientInfo } from '../interfaces/sync-client.interface'+import { Type } from 'class-transformer'+import { IsDefined, IsNotEmpty, IsNotEmptyObject, IsObject, IsOptional, IsString, IsUUID, ValidateNested } from 'class-validator'+import { SyncClientInfoDto } from './sync-client-info.dto'export class SyncClientRegistrationDto {@IsNotEmpty()@@ -26,9 +27,11 @@ export class SyncClientRegistrationDto {clientId: string@IsDefined()- @IsNotEmptyObject()@IsObject()- info: SyncClientInfo // TODO: create a DTO for validation+ @IsNotEmptyObject()+ @ValidateNested()+ @Type(() => SyncClientInfoDto)+ info: SyncClientInfoDto}export class SyncClientAuthRegistrationDto {@@ -38,7 +41,9 @@ export class SyncClientAuthRegistrationDto {clientId?: string@IsDefined()- @IsNotEmptyObject()@IsObject()- info: SyncClientInfo // TODO: create a DTO for validation+ @IsNotEmptyObject()+ @ValidateNested()+ @Type(() => SyncClientInfoDto)+ info: SyncClientInfoDto}diff --git a/backend/src/authentication/constants/routes.ts b/backend/src/authentication/constants/routes.tsindex d4e4adcf..a6617ccf 100644--- a/backend/src/authentication/constants/routes.ts+++ b/backend/src/authentication/constants/routes.ts@@ -35,3 +35,4 @@ export const API_TWO_FA_DISABLE = `${AUTH_ROUTE.BASE}/${AUTH_ROUTE.TWO_FA_BASE}/export const API_TWO_FA_LOGIN_VERIFY = `${AUTH_ROUTE.BASE}/${AUTH_ROUTE.TWO_FA_BASE}/${AUTH_ROUTE.TWO_FA_LOGIN_VERIFY}`export const API_TWO_FA_ADMIN_RESET_USER = `${AUTH_ROUTE.BASE}/${AUTH_ROUTE.TWO_FA_BASE}/${AUTH_ROUTE.TWO_FA_ADMIN_RESET_USER}`export const API_OIDC_LOGIN = `${AUTH_ROUTE.BASE}/${AUTH_ROUTE.OIDC_LOGIN}`+export const API_OIDC_CALLBACK = `${AUTH_ROUTE.BASE}/${AUTH_ROUTE.OIDC_CALLBACK}`diff --git a/backend/src/authentication/providers/oidc/auth-oidc-desktop.constants.ts b/backend/src/authentication/providers/oidc/auth-oidc-desktop.constants.tsnew file mode 100644index 00000000..fec106a7--- /dev/null+++ b/backend/src/authentication/providers/oidc/auth-oidc-desktop.constants.ts@@ -0,0 +1,9 @@+/*+ * Copyright (C) 2012-2026 Johan Legrand <[email protected]>+ * This file is part of Sync-in | The open source file sync and share solution+ * See the LICENSE file for licensing details+ */++export const OAuthDesktopPortParam = 'desktop_port' as const+export const OAuthDesktopCallBackURI = '/oidc/callback' as const+export const OAuthDesktopLoopbackPorts = new Set<number>([49152, 49153, 49154])diff --git a/backend/src/authentication/providers/oidc/auth-oidc.controller.ts b/backend/src/authentication/providers/oidc/auth-oidc.controller.tsindex 3b775628..35f2b5ab 100644--- a/backend/src/authentication/providers/oidc/auth-oidc.controller.ts+++ b/backend/src/authentication/providers/oidc/auth-oidc.controller.ts@@ -11,6 +11,7 @@ import { AuthManager } from '../../auth.service'import { AUTH_ROUTE } from '../../constants/routes'import { AuthTokenSkip } from '../../decorators/auth-token-skip.decorator'import type { LoginResponseDto } from '../../dto/login-response.dto'+import { OAuthDesktopPortParam } from './auth-oidc-desktop.constants'import { AuthProviderOIDC } from './auth-provider-oidc.service'@Controller(AUTH_ROUTE.BASE)@@ -22,8 +23,8 @@ export class AuthOIDCController {@Get(AUTH_ROUTE.OIDC_LOGIN)@AuthTokenSkip()- async oidcLogin(@Res() res: FastifyReply): Promise<void> {- const url = await this.authProviderOIDC.getAuthorizationUrl(res)+ async oidcLogin(@Query(OAuthDesktopPortParam) desktopPort: number, @Res() res: FastifyReply): Promise<void> {+ const url = await this.authProviderOIDC.getAuthorizationUrl(res, desktopPort)// Redirect to OIDC providerreturn res.redirect(url, HttpStatus.FOUND)}diff --git a/backend/src/authentication/providers/oidc/auth-provider-oidc.service.ts b/backend/src/authentication/providers/oidc/auth-provider-oidc.service.tsindex 07359af8..b8f100bd 100644--- a/backend/src/authentication/providers/oidc/auth-provider-oidc.service.ts+++ b/backend/src/authentication/providers/oidc/auth-provider-oidc.service.ts@@ -36,6 +36,7 @@ import type { AUTH_SCOPE } from '../../constants/scope'import { TOKEN_TYPE } from '../../interfaces/token.interface'import { AUTH_PROVIDER } from '../auth-providers.constants'import { AuthProvider } from '../auth-providers.models'+import { OAuthDesktopCallBackURI, OAuthDesktopLoopbackPorts, OAuthDesktopPortParam } from './auth-oidc-desktop.constants'import type { AuthMethodOIDCConfig } from './auth-oidc.config'import { OAuthCookie, OAuthCookieSettings, OAuthTokenEndpoint } from './auth-oidc.constants'@@ -78,7 +79,8 @@ export class AuthProviderOIDC implements AuthProvider {return this.config}- async getAuthorizationUrl(res: FastifyReply): Promise<string> {+ async getAuthorizationUrl(res: FastifyReply, desktopPort?: number): Promise<string> {+ const redirectURI = this.getRedirectURI(desktopPort)const config = await this.getConfig()// state: CSRF protection, nonce: binds the ID Token to this auth request (replay protection)@@ -90,7 +92,7 @@ export class AuthProviderOIDC implements AuthProvider {const authUrl = new URL(config.serverMetadata().authorization_endpoint!)authUrl.searchParams.set('client_id', this.oidcConfig.clientId!)- authUrl.searchParams.set('redirect_uri', this.oidcConfig.redirectUri)+ authUrl.searchParams.set('redirect_uri', redirectURI)authUrl.searchParams.set('response_type', 'code')authUrl.searchParams.set('scope', this.oidcConfig.security.scope)authUrl.searchParams.set('state', state)@@ -139,8 +141,14 @@ export class AuthProviderOIDC implements AuthProvider {const pkceCodeVerifier = supportsPKCE ? codeVerifier : undefinedconst callbackParams = new URLSearchParams(query)+ // Get Desktop Port if defined+ const desktopPort: string | null = callbackParams.get(OAuthDesktopPortParam)+ if (desktopPort) {+ callbackParams.delete(OAuthDesktopPortParam)+ }+// Exchange authorization code for tokens- const callbackUrl = new URL(this.oidcConfig.redirectUri)+ const callbackUrl = new URL(this.getRedirectURI(desktopPort))callbackUrl.search = callbackParams.toString()const tokens = await authorizationCodeGrant(config, callbackUrl, {expectedState,@@ -174,7 +182,10 @@ export class AuthProviderOIDC implements AuthProvider {throw new HttpException(error.error_description, HttpStatus.BAD_REQUEST)} else {this.logger.error(`${this.handleCallback.name} - OIDC callback error: ${error}`)- throw new HttpException('OIDC authentication failed', error instanceof HttpException ? error.getStatus() : HttpStatus.INTERNAL_SERVER_ERROR)+ throw new HttpException(+ error.error_description ?? 'OIDC authentication failed',+ error instanceof HttpException ? error.getStatus() : (error.status ?? HttpStatus.INTERNAL_SERVER_ERROR)+ )}} finally {// Always clear temporary OIDC cookies (success or failure)@@ -200,6 +211,20 @@ export class AuthProviderOIDC implements AuthProvider {return url.toString()}+ getRedirectURI(desktopPort?: number | string): string {+ // web / default callback+ if (!desktopPort) return this.oidcConfig.redirectUri+ // desktop app callback+ if (typeof desktopPort === 'string') {+ desktopPort = Number(desktopPort)+ }+ if (!Number.isInteger(desktopPort) || !OAuthDesktopLoopbackPorts.has(desktopPort)) {+ throw new HttpException('Invalid desktop_port', HttpStatus.BAD_REQUEST)+ }+ // The redirect url must be known from provider+ return `http://127.0.0.1:${desktopPort}${OAuthDesktopCallBackURI}`+ }+private async initializeOIDCClient(): Promise<Configuration> {try {const issuerUrl = new URL(this.oidcConfig.issuerUrl)diff --git a/environment/environment.dist.yaml b/environment/environment.dist.yamlindex bb2d7f66..c6021e1c 100755--- a/environment/environment.dist.yaml+++ b/environment/environment.dist.yaml@@ -184,6 +184,15 @@ auth:# redirectUri: The callback URL where users are redirected after authentication# This URL must be registered in your OIDC provider's allowed redirect URIs# Example (API callback): https://sync-in.domain.com/api/auth/oidc/callback+ #+ # To allow authentication from the desktop application, the following redirect URLs must also be registered in your OIDC provider:+ # - http://127.0.0.1:49152/oidc/callback+ # - http://127.0.0.1:49153/oidc/callback+ # - http://127.0.0.1:49154/oidc/callback+ #+ # If your OIDC provider supports wildcards or regular expressions, you may instead register a single entry such as:+ # - http://127.0.0.1/*+ ## requiredredirectUri: https://sync-in.domain.com/api/auth/oidc/callbackoptions:diff --git a/frontend/src/app/auth/auth.component.html b/frontend/src/app/auth/auth.component.htmlindex 93963a57..994edbae 100644--- a/frontend/src/app/auth/auth.component.html+++ b/frontend/src/app/auth/auth.component.html@@ -80,6 +80,7 @@<buttontype="button"class="btn btn-primary px-4 w-100"+ [disabled]="OIDCSubmitted"(click)="loginWithOIDC()"><span l10nTranslate>{{ oidcSettings.buttonText }}</span></button>diff --git a/frontend/src/app/auth/auth.component.ts b/frontend/src/app/auth/auth.component.tsindex 3ff2f64e..07c0d28c 100644--- a/frontend/src/app/auth/auth.component.ts+++ b/frontend/src/app/auth/auth.component.ts@@ -11,6 +11,8 @@ import { FaIconComponent } from '@fortawesome/angular-fontawesome'import { faKey, faLock, faQrcode, faUserAlt } from '@fortawesome/free-solid-svg-icons'import { USER_PASSWORD_MIN_LENGTH } from '@sync-in-server/backend/src/applications/users/constants/user'import { TWO_FA_CODE_LENGTH } from '@sync-in-server/backend/src/authentication/constants/auth'+import { API_OIDC_CALLBACK } from '@sync-in-server/backend/src/authentication/constants/routes'+import { OAuthDesktopPortParam } from '@sync-in-server/backend/src/authentication/providers/oidc/auth-oidc-desktop.constants'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 { L10N_LOCALE, L10nLocale, L10nTranslateDirective, L10nTranslatePipe } from 'angular-l10n'@@ -33,6 +35,7 @@ export class AuthComponent {protected logoUrl = logoDarkUrlprotected hasError: any = nullprotected submitted = false+ protected OIDCSubmitted = falseprotected twoFaVerify = falseprivate route = inject(ActivatedRoute)protected oidcSettings: AuthOIDCSettings | false = this.route.snapshot.data.authSettings@@ -51,7 +54,7 @@ export class AuthComponent {constructor() {if (this.oidcSettings && this.oidcSettings.autoRedirect) {- this.loginWithOIDC()+ void this.loginWithOIDC()}}@@ -91,9 +94,45 @@ export class AuthComponent {this.hasError = null}- loginWithOIDC() {- if (this.oidcSettings) {- window.location.href = this.oidcSettings.loginUrl+ async loginWithOIDC() {+ if (!this.oidcSettings) return+ if (!this.auth.electron.enabled) {+ window.location.assign(this.oidcSettings.loginUrl)+ return+ }+ this.OIDCSubmitted = true+ try {+ const desktopPort = await this.auth.electron.startOIDCDesktopAuth()++ if (!desktopPort) {+ this.OIDCSubmitted = false+ console.error('OIDC desktop auth failed')+ return+ }++ // Called when the OIDC provider redirects to desktop app+ this.auth.electron+ .waitOIDCDesktopCallbackParams()+ .then((callbackParams: Record<string, string>) => {+ // Receive callback params from desktop app and send it to backend to be authenticated.+ const params = new URLSearchParams(callbackParams)+ // Indicates the desktop app port used to reconstruct the redirect URI expected by the backend+ params.set(OAuthDesktopPortParam, String(desktopPort))+ window.location.assign(`${API_OIDC_CALLBACK}?${params.toString()}`)+ // Show desktop app window+ this.auth.electron.setActiveAndShow()+ })+ .catch((e: Error) => {+ this.OIDCSubmitted = false+ console.error('Unavailable OIDC desktop callback params:', e)+ })++ // With the desktop app, navigation to the OIDC provider is intercepted and opened in the user's browser.+ // The backend sends the oidc cookies to desktop app before the redirection.+ window.location.assign(`${this.oidcSettings.loginUrl}?${this.auth.electron.genParamOIDCDesktopPort(desktopPort)}`)+ } catch (e) {+ this.OIDCSubmitted = false+ console.error(e)}}diff --git a/frontend/src/app/auth/auth.service.ts b/frontend/src/app/auth/auth.service.tsindex 30bb3a61..f340e97c 100644--- a/frontend/src/app/auth/auth.service.ts+++ b/frontend/src/app/auth/auth.service.ts@@ -153,8 +153,7 @@ export class AuthService {checkUserAuthAndLoad(returnUrl: string, authFromOIDC?: AuthOIDCQueryParams): Observable<boolean> {if (authFromOIDC) {- // At this point, the cookies are stored in the session.- console.debug(`${this.checkUserAuthAndLoad.name} - auth from OIDC`)+ // At this point, the auth cookies are already stored in the session.this.accessExpiration = parseInt(authFromOIDC.access_expiration)this.refreshExpiration = parseInt(authFromOIDC.refresh_expiration)if (this.electron.enabled) {@@ -276,16 +275,19 @@ export class AuthService {}private authOIDCDesktopClient(): Observable<boolean> {+ // Retrieve authentication info from the desktop appreturn this.electron.authenticate().pipe(switchMap((auth: SyncClientAuthDto) => {if (!auth.clientId || auth.tokenHasExpired) {// The client must be registered, or the token must be renewedreturn this.http.post<SyncClientAuthRegistration>(API_SYNC_REGISTER_AUTH, auth).pipe(switchMap((externalAuth: SyncClientAuthRegistration) => {+ // Store the clientId and the clientToken on the desktop appreturn this.electron.externalRegister(externalAuth).pipe(switchMap((success: boolean) => {if (success) {console.debug(`${this.authOIDCDesktopClient.name} - ${auth.clientId ? 'client was registered' : 'client token renewed'}`)+ // Starts authenticationreturn this.authDesktopClient()} else {this.logout(true, true)@@ -301,7 +303,7 @@ export class AuthService {}))} else {- // The client must be authenticated+ // The client must be (re)authenticatedreturn this.authDesktopClient()}})diff --git a/frontend/src/app/electron/constants/events.ts b/frontend/src/app/electron/constants/events.tsindex 5c0e3218..2503d81e 100644--- a/frontend/src/app/electron/constants/events.ts+++ b/frontend/src/app/electron/constants/events.ts@@ -11,7 +11,13 @@ export const EVENT = {AUTHENTICATION: 'server-authentication',AUTHENTICATION_FAILED: 'server-authentication-failed',AUTHENTICATION_TOKEN_UPDATE: 'server-authentication-token-update',- AUTHENTICATION_TOKEN_EXPIRED: 'server-authentication-token-expired'+ AUTHENTICATION_TOKEN_EXPIRED: 'server-authentication-token-expired',+ SET_ACTIVE_AND_SHOW: 'server-set-active-and-show'+ },+ // oidc authentication+ OIDC: {+ START_LOOPBACK: 'oidc-start-loopback',+ WAIT_CALLBACK: 'oidc-wait-callback'},// syncSYNC: {diff --git a/frontend/src/app/electron/electron.service.ts b/frontend/src/app/electron/electron.service.tsindex dc9a5ede..e41705c9 100644--- a/frontend/src/app/electron/electron.service.ts+++ b/frontend/src/app/electron/electron.service.ts@@ -9,6 +9,7 @@ import { toObservable } from '@angular/core/rxjs-interop'import { FileTask } from '@sync-in-server/backend/src/applications/files/models/file-task'import type { SyncClientAuthDto } from '@sync-in-server/backend/src/applications/sync/dtos/sync-client-auth.dto'import type { SyncClientAuthRegistration } from '@sync-in-server/backend/src/applications/sync/interfaces/sync-client-auth.interface'+import { OAuthDesktopPortParam } from '@sync-in-server/backend/src/authentication/providers/oidc/auth-oidc-desktop.constants'import { combineLatest, from, map, Observable } from 'rxjs'import { NotificationModel } from '../applications/notifications/models/notification.model'import { CLIENT_APP_COUNTER, CLIENT_SCHEDULER_STATE } from '../applications/sync/constants/client'@@ -93,6 +94,21 @@ export class Electron {)}+ async startOIDCDesktopAuth(): Promise<number> {+ const desktop: { redirectPort: number } = await this.invoke(EVENT.OIDC.START_LOOPBACK)+ console.debug(`Starting OIDC desktop auth with port ${desktop.redirectPort}`)+ return desktop.redirectPort+ }++ async waitOIDCDesktopCallbackParams(): Promise<Record<string, string>> {+ console.debug('Waiting for OIDC desktop callback parameters')+ return await this.invoke(EVENT.OIDC.WAIT_CALLBACK)+ }++ genParamOIDCDesktopPort(desktopPort: number): string {+ return `${OAuthDesktopPortParam}=${desktopPort}`+ }+openPath(path: string) {this.send(EVENT.MISC.FILE_OPEN, path)}@@ -101,6 +117,10 @@ export class Electron {this.send(EVENT.MISC.URL_OPEN, url)}+ setActiveAndShow() {+ this.send(EVENT.SERVER.SET_ACTIVE_AND_SHOW)+ }+private setSync(sync: SyncStatus) {if (sync.reportOnly) {this.store.clientSyncIsReporting.next(sync.state)