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): app passwords
johaven91eda5cbc396
diff --git a/backend/src/applications/users/constants/routes.ts b/backend/src/applications/users/constants/routes.tsindex ebbfe33c..841048e5 100644--- a/backend/src/applications/users/constants/routes.ts+++ b/backend/src/applications/users/constants/routes.ts@@ -11,6 +11,7 @@ export const USERS_ROUTE = {ME: 'me',LANGUAGE: 'language',PASSWORD: 'password',+ APP_PASSWORDS: 'app_passwords',NOTIFICATION: 'notification',AVATAR: 'avatar',GROUPS: 'groups',@@ -23,6 +24,7 @@ export const USERS_ROUTE = {export const API_USERS_ME = `${USERS_ROUTE.BASE}/${USERS_ROUTE.ME}`export const API_USERS_MY_LANGUAGE = `${API_USERS_ME}/${USERS_ROUTE.LANGUAGE}`export const API_USERS_MY_PASSWORD = `${API_USERS_ME}/${USERS_ROUTE.PASSWORD}`+export const API_USERS_MY_APP_PASSWORDS = `${API_USERS_ME}/${USERS_ROUTE.APP_PASSWORDS}`export const API_USERS_MY_NOTIFICATION = `${API_USERS_ME}/${USERS_ROUTE.NOTIFICATION}`export const API_USERS_MY_AVATAR = `${API_USERS_ME}/${USERS_ROUTE.AVATAR}`export const API_USERS_MY_GROUPS = `${API_USERS_ME}/${USERS_ROUTE.GROUPS}`diff --git a/backend/src/applications/users/constants/user.ts b/backend/src/applications/users/constants/user.tsindex fbd8d1b0..4d105f53 100644--- a/backend/src/applications/users/constants/user.ts+++ b/backend/src/applications/users/constants/user.ts@@ -68,5 +68,5 @@ export const USER_NOTIFICATION_TEXT = {export const USER_SECRET = {TWO_FA_SECRET: 'twoFaSecret',RECOVERY_CODES: 'recoveryCodes',- WEBDAV_PASSWORD: 'webdavPassword'+ APP_PASSWORDS: 'appPasswords'} as constdiff --git a/backend/src/applications/users/dto/user-properties.dto.ts b/backend/src/applications/users/dto/user-properties.dto.tsindex 34ad45f3..205dc985 100644--- a/backend/src/applications/users/dto/user-properties.dto.ts+++ b/backend/src/applications/users/dto/user-properties.dto.ts@@ -4,7 +4,10 @@* See the LICENSE file for licensing details*/-import { IsInt, IsNotEmpty, IsString, MinLength, ValidateIf } from 'class-validator'+import { Transform } from 'class-transformer'+import { IsDate, IsEnum, IsInt, IsNotEmpty, IsOptional, IsString, MinLength, ValidateIf } from 'class-validator'+import { AUTH_SCOPE } from '../../../authentication/constants/scope'+import { currentDate } from '../../../common/shared'import { USER_PASSWORD_MIN_LENGTH } from '../constants/user'export class UserLanguageDto {@@ -35,3 +38,18 @@ export class UserPasswordDto {@MinLength(USER_PASSWORD_MIN_LENGTH)password: string}++export class UserAppPasswordDto {+ @IsNotEmpty()+ @IsString()+ name: string++ @Transform(({ value }) => value.toLowerCase())+ @IsEnum(AUTH_SCOPE)+ app: AUTH_SCOPE++ @IsOptional()+ @Transform(({ value }) => (value ? currentDate(value) : null))+ @IsDate()+ expiration?: Date+}diff --git a/backend/src/applications/users/interfaces/user-secrets.interface.ts b/backend/src/applications/users/interfaces/user-secrets.interface.tsindex 9e5242bf..f947c57b 100644--- a/backend/src/applications/users/interfaces/user-secrets.interface.ts+++ b/backend/src/applications/users/interfaces/user-secrets.interface.ts@@ -4,10 +4,23 @@* See the LICENSE file for licensing details*/+import { AUTH_SCOPE } from '../../../authentication/constants/scope'import { USER_SECRET } from '../constants/user'+export interface UserAppPassword {+ name: string+ app: AUTH_SCOPE+ password: string+ expiration: Date+ currentIp: string+ lastIp: string+ currentAccess: Date+ lastAccess: Date+ createdAt: Date+}+export interface UserSecrets {[USER_SECRET.TWO_FA_SECRET]?: string[USER_SECRET.RECOVERY_CODES]?: string[]- [USER_SECRET.WEBDAV_PASSWORD]?: string+ [USER_SECRET.APP_PASSWORDS]?: UserAppPassword[]}diff --git a/backend/src/applications/users/models/user.model.ts b/backend/src/applications/users/models/user.model.tsindex 22312b6a..a62011a3 100644--- a/backend/src/applications/users/models/user.model.ts+++ b/backend/src/applications/users/models/user.model.ts@@ -133,6 +133,11 @@ export class UserModel implements User {return !!this.secrets?.twoFaSecret}+ @Expose()+ get appPasswords(): number {+ return this.secrets?.appPasswords?.length || 0+ }+static getHomePath(userLogin: string, isGuest = false, isLink = false): string {if (isGuest || isLink) {return path.join(configuration.applications.files.tmpPath, isGuest ? 'guests' : 'links', userLogin)diff --git a/backend/src/applications/users/services/users-manager.service.ts b/backend/src/applications/users/services/users-manager.service.tsindex 159b251d..56cdaf5a 100755--- a/backend/src/applications/users/services/users-manager.service.ts+++ b/backend/src/applications/users/services/users-manager.service.ts@@ -12,27 +12,29 @@ import { WriteStream } from 'fs'import { createWriteStream } from 'node:fs'import path from 'node:path'import { pipeline } from 'node:stream/promises'+import { AUTH_SCOPE } from '../../../authentication/constants/scope'import { LoginResponseDto } from '../../../authentication/dto/login-response.dto'import { FastifyAuthenticatedRequest } from '../../../authentication/interfaces/auth-request.interface'import { JwtIdentityPayload } from '../../../authentication/interfaces/jwt-payload.interface'import { ACTION } from '../../../common/constants'-import { comparePassword } from '../../../common/functions'+import { comparePassword, hashPassword } from '../../../common/functions'import { generateAvatar, pngMimeType, svgMimeType } from '../../../common/image'+import { createLightSlug, genPassword } from '../../../common/shared'import { configuration, serverConfig } from '../../../configuration/config.environment'import { isPathExists, moveFiles } from '../../files/utils/files'import { NOTIFICATION_APP, NOTIFICATION_APP_EVENT } from '../../notifications/constants/notifications'import { NotificationsManager } from '../../notifications/services/notifications-manager.service'import { MEMBER_TYPE } from '../constants/member'import { USER_GROUP_ROLE, USER_MAX_PASSWORD_ATTEMPTS, USER_ONLINE_STATUS, USER_ROLE } from '../constants/user'-import { UserCreateOrUpdateGroupDto } from '../dto/create-or-update-group.dto'-import { CreateUserDto, UpdateUserDto, UpdateUserFromGroupDto } from '../dto/create-or-update-user.dto'-import { SearchMembersDto } from '../dto/search-members.dto'-import type { UserLanguageDto, UserNotificationDto, UserUpdatePasswordDto } from '../dto/user-properties.dto'+import type { UserCreateOrUpdateGroupDto } from '../dto/create-or-update-group.dto'+import type { CreateUserDto, UpdateUserDto, UpdateUserFromGroupDto } from '../dto/create-or-update-user.dto'+import type { SearchMembersDto } from '../dto/search-members.dto'+import type { UserAppPasswordDto, UserLanguageDto, UserNotificationDto, UserUpdatePasswordDto } from '../dto/user-properties.dto'import type { GroupBrowse } from '../interfaces/group-browse.interface'import type { GroupMember, GroupWithMembers } from '../interfaces/group-member'import type { GuestUser } from '../interfaces/guest-user.interface'import type { Member } from '../interfaces/member.interface'-import type { UserSecrets } from '../interfaces/user-secrets.interface'+import type { UserAppPassword, UserSecrets } from '../interfaces/user-secrets.interface'import type { UserOnline } from '../interfaces/websocket.interface'import { UserModel } from '../models/user.model'import type { Group } from '../schemas/group.interface'@@ -64,9 +66,12 @@ export class UsersManager {return user ? new UserModel(user, removePassword) : null}- async logUser(user: UserModel, password: string, ip: string): Promise<UserModel> {+ async logUser(user: UserModel, password: string, ip: string, scope?: AUTH_SCOPE): Promise<UserModel> {this.validateUserAccess(user, ip)- const authSuccess: boolean = await comparePassword(password, user.password)+ let authSuccess: boolean = await comparePassword(password, user.password)+ if (!authSuccess && scope) {+ authSuccess = await this.validateAppPassword(user, password, ip, scope)+ }this.updateAccesses(user, ip, authSuccess).catch((e: Error) => this.logger.error(`${this.logUser.name} - ${e}`))if (authSuccess) {await user.makePaths()@@ -212,6 +217,76 @@ export class UsersManager {}}+ async listAppPasswords(user: UserModel): Promise<Omit<UserAppPassword, 'password'>[]> {+ const secrets = (await this.usersQueries.selectUserProperties(user.id, ['secrets'])).secrets as UserSecrets+ if (Array.isArray(secrets.appPasswords)) {+ // remove passwords from response+ return secrets.appPasswords.map(({ password, ...rest }: UserAppPassword) => rest)+ }+ return []+ }++ async generateAppPassword(user: UserModel, userAppPasswordDto: UserAppPasswordDto): Promise<UserAppPassword> {+ const secrets = (await this.usersQueries.selectUserProperties(user.id, ['secrets'])).secrets as UserSecrets+ const slugName = createLightSlug(userAppPasswordDto.name)+ if (Array.isArray(secrets.appPasswords) && secrets.appPasswords.find((p: UserAppPassword) => p.name === slugName)) {+ throw new HttpException('Name already used', HttpStatus.BAD_REQUEST)+ }+ secrets.appPasswords = Array.isArray(secrets.appPasswords) ? secrets.appPasswords : []+ const clearPassword = genPassword(24)+ const appPassword: UserAppPassword = {+ name: createLightSlug(userAppPasswordDto.name),+ app: userAppPasswordDto.app,+ expiration: userAppPasswordDto.expiration,+ password: await hashPassword(clearPassword),+ createdAt: new Date(),+ currentIp: null,+ currentAccess: null,+ lastIp: null,+ lastAccess: null+ }+ secrets.appPasswords.unshift(appPassword)+ if (!(await this.usersQueries.updateUserOrGuest(user.id, { secrets: secrets }))) {+ throw new HttpException('Unable to update app passwords', HttpStatus.INTERNAL_SERVER_ERROR)+ }+ // return clear password only once+ return { ...appPassword, password: clearPassword }+ }++ async deleteAppPassword(user: UserModel, passwordName: string): Promise<void> {+ const secrets = (await this.usersQueries.selectUserProperties(user.id, ['secrets'])).secrets as UserSecrets+ if (!Array.isArray(secrets.appPasswords) || !secrets.appPasswords.find((p: UserAppPassword) => p.name === passwordName)) {+ throw new HttpException('App password not found', HttpStatus.NOT_FOUND)+ }+ secrets.appPasswords = secrets.appPasswords.filter((p: UserAppPassword) => p.name !== passwordName)+ if (!(await this.usersQueries.updateUserOrGuest(user.id, { secrets: secrets }))) {+ throw new HttpException('Unable to delete app password', HttpStatus.INTERNAL_SERVER_ERROR)+ }+ }++ async validateAppPassword(user: UserModel, password: string, ip: string, scope: AUTH_SCOPE): Promise<boolean> {+ if (!scope || !user.haveRole(USER_ROLE.USER)) return false+ const secrets = (await this.usersQueries.selectUserProperties(user.id, ['secrets'])).secrets as UserSecrets+ if (!Array.isArray(secrets.appPasswords)) return false+ for (const p of secrets.appPasswords) {+ if (p.app !== scope) continue+ const expMs = p.expiration ? new Date(p.expiration) : null+ if (p.expiration && new Date() > expMs) continue // expired+ if (await comparePassword(password, p.password)) {+ p.lastAccess = p.currentAccess+ p.currentAccess = new Date()+ p.lastIp = p.currentIp+ p.currentIp = ip+ // update accesses+ this.usersQueries+ .updateUserOrGuest(user.id, { secrets: secrets })+ .catch((e: Error) => this.logger.error(`${this.validateAppPassword.name} - ${e}`))+ return true+ }+ }+ return false+ }+setOnlineStatus(user: JwtIdentityPayload, onlineStatus: USER_ONLINE_STATUS) {this.usersQueries.setOnlineStatus(user.id, onlineStatus).catch((e: Error) => this.logger.error(`${this.setOnlineStatus.name} - ${e}`))}diff --git a/backend/src/applications/users/users.controller.ts b/backend/src/applications/users/users.controller.tsindex 4bd13975..d4019c9b 100755--- a/backend/src/applications/users/users.controller.ts+++ b/backend/src/applications/users/users.controller.ts@@ -17,13 +17,14 @@ import { GetUser } from './decorators/user.decorator'import { UserCreateOrUpdateGroupDto } from './dto/create-or-update-group.dto'import { CreateUserDto, UpdateUserDto, UpdateUserFromGroupDto } from './dto/create-or-update-user.dto'import { SearchMembersDto } from './dto/search-members.dto'-import { UserLanguageDto, UserNotificationDto, UserUpdatePasswordDto } from './dto/user-properties.dto'+import { UserAppPasswordDto, UserLanguageDto, UserNotificationDto, UserUpdatePasswordDto } from './dto/user-properties.dto'import { UserPermissionsGuard } from './guards/permissions.guard'import { UserRolesGuard } from './guards/roles.guard'import { GroupBrowse } from './interfaces/group-browse.interface'import { GroupMember } from './interfaces/group-member'import { GuestUser } from './interfaces/guest-user.interface'import { Member } from './interfaces/member.interface'+import { UserAppPassword } from './interfaces/user-secrets.interface'import { UserModel } from './models/user.model'import { UsersManager } from './services/users-manager.service'@@ -39,6 +40,24 @@ export class UsersController {return this.usersManager.me(user)}+ @Get(`${USERS_ROUTE.ME}/${USERS_ROUTE.APP_PASSWORDS}`)+ @UserHaveRole(USER_ROLE.USER)+ listAppPasswords(@GetUser() user: UserModel): Promise<Omit<UserAppPassword, 'password'>[]> {+ return this.usersManager.listAppPasswords(user)+ }++ @Post(`${USERS_ROUTE.ME}/${USERS_ROUTE.APP_PASSWORDS}`)+ @UserHaveRole(USER_ROLE.USER)+ generateAppPassword(@GetUser() user: UserModel, @Body() userAppPasswordDto: UserAppPasswordDto): Promise<UserAppPassword> {+ return this.usersManager.generateAppPassword(user, userAppPasswordDto)+ }++ @Delete(`${USERS_ROUTE.ME}/${USERS_ROUTE.APP_PASSWORDS}/:name`)+ @UserHaveRole(USER_ROLE.USER)+ deleteAppPassword(@GetUser() user: UserModel, @Param('name') name: string): Promise<void> {+ return this.usersManager.deleteAppPassword(user, name)+ }+@Put(`${USERS_ROUTE.ME}/${USERS_ROUTE.LANGUAGE}`)@UserHaveRole(USER_ROLE.GUEST)updateLanguage(@GetUser() user: UserModel, @Body() userLanguageDto: UserLanguageDto) {diff --git a/backend/src/authentication/constants/auth.ts b/backend/src/authentication/constants/auth.tsindex a3d3f189..7a7f3306 100644--- a/backend/src/authentication/constants/auth.ts+++ b/backend/src/authentication/constants/auth.ts@@ -14,7 +14,6 @@ export const WS_KEY = 'sync-in-ws'export const TWO_FA_CODE_LENGTH = 6export const TWO_FA_VERIFY_EXPIRATION = '5m'-export const TWO_FA_HEADER = 'sync-in-two-fa-code'export const TOKEN_PATHS = {diff --git a/backend/src/authentication/constants/scope.ts b/backend/src/authentication/constants/scope.tsnew file mode 100644index 00000000..c9817ad3--- /dev/null+++ b/backend/src/authentication/constants/scope.ts@@ -0,0 +1,9 @@+/*+ * Copyright (C) 2012-2025 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 enum AUTH_SCOPE {+ WEBDAV = 'webdav'+}diff --git a/backend/src/authentication/guards/auth-basic.strategy.ts b/backend/src/authentication/guards/auth-basic.strategy.tsindex 47a373c0..bfba94ba 100644--- a/backend/src/authentication/guards/auth-basic.strategy.ts+++ b/backend/src/authentication/guards/auth-basic.strategy.ts@@ -13,11 +13,13 @@ import { BasicStrategy } from 'passport-http'import { SERVER_NAME } from '../../app.constants'import { UserModel } from '../../applications/users/models/user.model'import { Cache } from '../../infrastructure/cache/services/cache.service'+import { AUTH_SCOPE } from '../constants/scope'import { AuthMethod } from '../models/auth-method'@Injectable()export class AuthBasicStrategy extends PassportStrategy(BasicStrategy, 'basic') implements AbstractStrategy {- static readonly CACHE_TTL = 900+ private readonly CACHE_TTL = 900+ private readonly CACHE_KEY_PREFIX = 'auth-webdav'constructor(private readonly authMethod: AuthMethod,@@ -29,7 +31,7 @@ export class AuthBasicStrategy extends PassportStrategy(BasicStrategy, 'basic')async validate(req: FastifyRequest, loginOrEmail: string, password: string): Promise<Omit<UserModel, 'password'> | null> {this.logger.assign({ user: loginOrEmail })- const authBasicUser = `auth-webdav-${req.headers['authorization'].split(' ').at(-1).toLowerCase()}`+ const authBasicUser = `${this.CACHE_KEY_PREFIX}-${req.headers['authorization'].split(' ').at(-1).toLowerCase()}`const userFromCache: any = await this.cache.get(authBasicUser)if (userFromCache === null) {// not authorized@@ -40,12 +42,12 @@ export class AuthBasicStrategy extends PassportStrategy(BasicStrategy, 'basic')// warning: plainToInstance do not use constructor to instantiate classreturn plainToInstance(UserModel, userFromCache)}- const userFromDB: UserModel = await this.authMethod.validateUser(loginOrEmail, password, req.ip)+ const userFromDB: UserModel = await this.authMethod.validateUser(loginOrEmail, password, req.ip, AUTH_SCOPE.WEBDAV)if (userFromDB !== null) {userFromDB.removePassword()}const userToCache: Record<string, any> | null = userFromDB ? instanceToPlain(userFromDB, { excludePrefixes: ['_'] }) : null- this.cache.set(authBasicUser, userToCache, AuthBasicStrategy.CACHE_TTL).catch((e: Error) => this.logger.error(`${this.validate.name} - ${e}`))+ this.cache.set(authBasicUser, userToCache, this.CACHE_TTL).catch((e: Error) => this.logger.error(`${this.validate.name} - ${e}`))return userFromDB}}diff --git a/backend/src/authentication/models/auth-method.ts b/backend/src/authentication/models/auth-method.tsindex bddcc237..1b6aed9f 100644--- a/backend/src/authentication/models/auth-method.ts+++ b/backend/src/authentication/models/auth-method.ts@@ -4,8 +4,9 @@* See the LICENSE file for licensing details*/-import { UserModel } from '../../applications/users/models/user.model'+import type { UserModel } from '../../applications/users/models/user.model'+import type { AUTH_SCOPE } from '../constants/scope'export abstract class AuthMethod {- abstract validateUser(loginOrEmail: string, password: string, ip?: string): Promise<UserModel>+ abstract validateUser(loginOrEmail: string, password: string, ip?: string, scope?: AUTH_SCOPE): Promise<UserModel>}diff --git a/backend/src/authentication/services/auth-methods/auth-method-database.service.ts b/backend/src/authentication/services/auth-methods/auth-method-database.service.tsindex 990ab874..37c4104b 100644--- a/backend/src/authentication/services/auth-methods/auth-method-database.service.ts+++ b/backend/src/authentication/services/auth-methods/auth-method-database.service.ts@@ -8,6 +8,7 @@ import { HttpException, HttpStatus, Injectable, Logger } from '@nestjs/common'import { CONNECT_ERROR_CODE } from '../../../app.constants'import { UserModel } from '../../../applications/users/models/user.model'import { UsersManager } from '../../../applications/users/services/users-manager.service'+import { AUTH_SCOPE } from '../../constants/scope'import { AuthMethod } from '../../models/auth-method'@Injectable()@@ -16,7 +17,7 @@ export class AuthMethodDatabase implements AuthMethod {constructor(private readonly usersManager: UsersManager) {}- async validateUser(loginOrEmail: string, password: string, ip?: string): Promise<UserModel> {+ async validateUser(loginOrEmail: string, password: string, ip?: string, scope?: AUTH_SCOPE): Promise<UserModel> {let user: UserModeltry {user = await this.usersManager.findUser(loginOrEmail, false)@@ -28,6 +29,6 @@ export class AuthMethodDatabase implements AuthMethod {this.logger.warn(`${this.validateUser.name} - login or email not found for *${loginOrEmail}*`)return null}- return await this.usersManager.logUser(user, password, ip)+ return await this.usersManager.logUser(user, password, ip, scope)}}diff --git a/backend/src/authentication/services/auth-methods/auth-method-ldap.service.ts b/backend/src/authentication/services/auth-methods/auth-method-ldap.service.tsindex a6fa5b43..135ac16f 100644--- a/backend/src/authentication/services/auth-methods/auth-method-ldap.service.ts+++ b/backend/src/authentication/services/auth-methods/auth-method-ldap.service.ts@@ -8,12 +8,13 @@ import { HttpException, HttpStatus, Injectable, Logger } from '@nestjs/common'import { Client, ClientOptions, Entry, InvalidCredentialsError } from 'ldapts'import { CONNECT_ERROR_CODE } from '../../../app.constants'import { USER_ROLE } from '../../../applications/users/constants/user'-import { CreateUserDto, UpdateUserDto } from '../../../applications/users/dto/create-or-update-user.dto'+import type { CreateUserDto, UpdateUserDto } from '../../../applications/users/dto/create-or-update-user.dto'import { UserModel } from '../../../applications/users/models/user.model'import { AdminUsersManager } from '../../../applications/users/services/admin-users-manager.service'import { UsersManager } from '../../../applications/users/services/users-manager.service'import { comparePassword, splitFullName } from '../../../common/functions'import { configuration } from '../../../configuration/config.environment'+import type { AUTH_SCOPE } from '../../constants/scope'import { AuthMethod } from '../../models/auth-method'type LdapUserEntry = Entry & { uid: string; mail: string; cn: string }@@ -29,8 +30,8 @@ export class AuthMethodLdapService implements AuthMethod {private readonly adminUsersManager: AdminUsersManager) {}- async validateUser(loginOrEmail: string, password: string, ip?: string): Promise<UserModel> {- let user = await this.usersManager.findUser(loginOrEmail, false)+ async validateUser(loginOrEmail: string, password: string, ip?: string, scope?: AUTH_SCOPE): Promise<UserModel> {+ let user: UserModel = await this.usersManager.findUser(loginOrEmail, false)if (user) {if (user.isGuest) {// allow guests to be authenticated from db and check if the current user is defined as active@@ -43,8 +44,18 @@ export class AuthMethodLdapService implements AuthMethod {}const entry: false | LdapUserEntry = await this.checkAuth(loginOrEmail, password)if (entry === false) {+ // LDAP auth failedif (user) {- this.usersManager.updateAccesses(user, ip, false).catch((e: Error) => this.logger.error(`${this.validateUser.name} : ${e}`))+ let authSuccess = false+ if (scope) {+ // try user app password+ authSuccess = await this.usersManager.validateAppPassword(user, password, ip, scope)+ }+ this.usersManager.updateAccesses(user, ip, authSuccess).catch((e: Error) => this.logger.error(`${this.validateUser.name} : ${e}`))+ if (authSuccess) {+ // logged with app password+ return user+ }}return null} else if (!entry.mail || !entry.uid) {diff --git a/backend/src/common/shared.ts b/backend/src/common/shared.tsindex 003fbb57..ec2da21f 100644--- a/backend/src/common/shared.ts+++ b/backend/src/common/shared.ts@@ -36,6 +36,24 @@ export function createSlug(input: string, replaceCount = false): string {return r}+export function createLightSlug(input: string) {+ return input+ .toLowerCase()+ .trim()+ .normalize('NFD')+ .replace(/[\u0300-\u036f]/g, '')+}++export function genPassword(length = 12) {+ const chars = '0123456789abcdefghijklmnopqrstuvwxyz!@#$%^&*()ABCDEFGHIJKLMNOPQRSTUVWXYZ'+ let password = ''+ for (let i = 0; i <= length; i++) {+ const randomNumber = Math.floor(Math.random() * chars.length)+ password += chars.substring(randomNumber, randomNumber + 1)+ }+ return password+}+export function popFromObject(key: string, object: any): any {const item = object[key]delete object[key]diff --git a/frontend/src/app/applications/links/components/dialogs/link-dialog.component.html b/frontend/src/app/applications/links/components/dialogs/link-dialog.component.htmlindex 084d6d84..05b71494 100644--- a/frontend/src/app/applications/links/components/dialogs/link-dialog.component.html+++ b/frontend/src/app/applications/links/components/dialogs/link-dialog.component.html@@ -158,14 +158,14 @@<div class="d-flex align-items-center justify-content-between"><label for="expiration" l10nTranslate>Expiration</label><input+ bsDatepickerid="expiration"formControlName="expiresAt"placement="left"type="text"class="form-control form-control-sm ms-auto w-50"[class.text-danger]="linkIsExpired"- [placeholder]="'Unlimited' | translate:locale.language"- bsDatepicker+ [placeholder]="'Never expires' | translate:locale.language"[bsConfig]="{dateInputFormat: 'YYYY-MM-DD',containerClass: 'theme-dark-blue',diff --git a/frontend/src/app/applications/users/components/dialogs/user-auth-manage-app-passwords-dialog.component.html b/frontend/src/app/applications/users/components/dialogs/user-auth-manage-app-passwords-dialog.component.htmlnew file mode 100644index 00000000..0d94e0d8--- /dev/null+++ b/frontend/src/app/applications/users/components/dialogs/user-auth-manage-app-passwords-dialog.component.html@@ -0,0 +1,162 @@+<!--+ ~ Copyright (C) 2012-2025 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+ -->++<div class="modal-header align-items-center">+ <h4 class="modal-title">+ <fa-icon [icon]="icons.faKey" class="me-2"></fa-icon>+ <span l10nTranslate>Manage app passwords</span>+ </h4>+ <button (click)="onClose()" aria-label="Close" class="btn-close btn-close-white ms-auto" type="button"></button>+</div>+<div class="modal-body">+ @if (allowGeneration && !generatedPassword) {+ <div class="d-flex flex-fill flex-column">+ <div class="fw-500 mb-3" l10nTranslate>Generate a new app password</div>+ <div class="d-flex flex-column align-items-start">+ <form [formGroup]="appPasswordForm" (ngSubmit)="genAppPassword()" class="w-100">+ <div class="input-group input-group-sm flex-nowrap">+ <input appAutofocus+ name="name"+ formControlName="name"+ type="text"+ class="flex-grow-1 form-control form-control-sm pe-0"+ [class.is-invalid]="appPasswordForm.controls.name.invalid"+ [placeholder]="'Password name' | translate: locale.language" required>+ <div class="input-group-text" l10nTranslate>Application</div>+ <select class="form-select form-select-sm" formControlName="app" style="max-width: 150px">+ @for (s of availableApps; track $index) {+ <option [value]="s" l10nTranslate>{{ s }}</option>+ }+ </select>+ <input+ bsDatepicker+ id="expiration"+ formControlName="expiration"+ placement="bottom"+ type="text"+ class="form-control form-control-sm"+ style="max-width: 120px;"+ [placeholder]="'Never expires' | translate:locale.language"+ [bsConfig]="{+ dateInputFormat: 'YYYY-MM-DD',+ containerClass: 'theme-dark-blue',+ returnFocusToInput: true,+ minDate: minDate,+ showWeekNumbers: false }">+ <button+ [disabled]="appPasswordForm.invalid || submitted"+ class="btn btn-xs btn-primary"+ type="submit"+ l10nTranslate>+ Generate+ </button>+ </div>+ </form>+ </div>+ </div>+ @if (!this.generatedPassword) {+ @if (hasError) {+ <div class="alert alert-danger text-center my-3" l10nTranslate>+ {{ hasError }}+ </div>+ } @else {+ <div class="alert alert-secondary text-center my-3" l10nTranslate>+ This password will only be shown once after it is generated+ </div>+ }+ @if (appPasswords.length) {+ <hr class="mb-1 mt-4">+ }+ }+ }+ @if (generatedPassword) {+ <div class="d-flex flex-column alert alert-success text-center my-3">+ <div class="d-flex">+ <strong l10nTranslate>Password name</strong>: {{ generatedPassword.name }}+ </div>+ <div class="d-flex">+ <strong l10nTranslate>Application</strong>: {{ generatedPassword.app | translate: locale.language }}+ </div>+ @if (generatedPassword.expiration) {+ <div class="d-flex">+ <strong l10nTranslate>Expiration</strong>: {{ generatedPassword.expiration }}+ </div>+ }+ <div class="d-flex">+ <strong l10nTranslate>Generated password</strong>: + <span class="font-monospace link-body-emphasis" (click)="clipBoardPassword()" role="button">+ <fa-icon [icon]="icons.faCopy"></fa-icon>+ <span>{{ generatedPassword.password }}</span>+ </span>+ </div>+ </div>+ @if (appPasswords.length) {+ <hr class="mb-1 mt-4">+ }+ }+ @if (appPasswords.length) {+ <table class="table table-striped table-hover align-middle text-center">+ <thead>+ <tr>+ <th scope="col" l10nTranslate>Name</th>+ <th scope="col" l10nTranslate>Application</th>+ <th scope="col" l10nTranslate>Access</th>+ <th scope="col" l10nTranslate>IP</th>+ <th scope="col" l10nTranslate>Expiration</th>+ <th scope="col" l10nTranslate>Created</th>+ <th scope="col" l10nTranslate>Action</th>+ </tr>+ </thead>+ <tbody class="table-group-divider">+ @for (p of appPasswords; track p.name) {+ <tr>+ <td>{{ p.name }}</td>+ <td>{{ p.app | translate: locale.language }}</td>+ <td class="fs-xxxs">+ <div class="d-flex flex-column align-items-center justify-content-center">+ <div>{{ p.currentAccess ? (p.currentAccess | amDateFormat) : '-' }}</div>+ @if (p.lastAccess) {+ <div>{{ p.lastAccess | amDateFormat }}</div>+ }+ </div>+ </td>+ <td class="fs-xxxs">+ <div class="d-flex flex-column align-items-center justify-content-center">+ <div>{{ p.currentIp || '-' }}</div>+ @if (p.lastIp) {+ <div>{{ p.lastIp }}</div>+ }+ </div>+ </td>+ <td class="fs-xxxs">{{ p.expiration ? (p.expiration | amDateFormat:'L') : ('never' | translate: locale.language) }}</td>+ <td class="fs-xxxs">{{ p.createdAt | amDateFormat }}</td>+ <td>+ <button class="btn btn-sm btn-outline-danger" (click)="deleteAppPassword(p.name)">Delete</button>+ </td>+ </tr>+ }+ </tbody>+ </table>+ }+</div>+<div class="modal-footer">+ <button [ngModel]="allowGeneration"+ (ngModelChange)="onAllowGenerationChange()"+ class="btn btn-sm btn-outline-success me-auto"+ role="button"+ type="button"+ btnCheckbox+ l10nTranslate>+ <fa-icon [icon]="icons.faPlus"></fa-icon>+ <fa-icon [icon]="icons.faKey"></fa-icon>+ Password+ </button>+ <button (click)="onClose()" class="btn btn-sm btn-secondary" data-dismiss="modal" type="button" l10nTranslate>Close</button>+</div>++++diff --git a/frontend/src/app/applications/users/components/dialogs/user-auth-manage-app-passwords-dialog.component.ts b/frontend/src/app/applications/users/components/dialogs/user-auth-manage-app-passwords-dialog.component.tsnew file mode 100644index 00000000..5814ba1b--- /dev/null+++ b/frontend/src/app/applications/users/components/dialogs/user-auth-manage-app-passwords-dialog.component.ts@@ -0,0 +1,123 @@+/*+ * Copyright (C) 2012-2025 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 { HttpErrorResponse } from '@angular/common/http'+import { Component, EventEmitter, inject, Input, OnInit, Output } from '@angular/core'+import { FormGroup, FormsModule, ReactiveFormsModule, UntypedFormBuilder, Validators } from '@angular/forms'+import { FaIconComponent } from '@fortawesome/angular-fontawesome'+import { faCopy, faKey, faPlus } from '@fortawesome/free-solid-svg-icons'+import { UserAppPassword } from '@sync-in-server/backend/src/applications/users/interfaces/user-secrets.interface'++import { AUTH_SCOPE } from '@sync-in-server/backend/src/authentication/constants/scope'+import { createLightSlug, currentDate } from '@sync-in-server/backend/src/common/shared'+import { L10N_LOCALE, L10nLocale, L10nTranslateDirective, L10nTranslatePipe } from 'angular-l10n'+import { ButtonCheckboxDirective } from 'ngx-bootstrap/buttons'+import { BsDatepickerDirective, BsDatepickerInputDirective } from 'ngx-bootstrap/datepicker'+import { ClipboardService } from 'ngx-clipboard'+import { filter } from 'rxjs/operators'+import { AutofocusDirective } from '../../../../common/directives/auto-focus.directive'+import { TimeDateFormatPipe } from '../../../../common/pipes/time-date-format.pipe'+import { LayoutService } from '../../../../layout/layout.service'+import { UserService } from '../../user.service'++@Component({+ selector: 'app-user-auth-manage-app-passwords',+ imports: [+ FaIconComponent,+ L10nTranslateDirective,+ TimeDateFormatPipe,+ FormsModule,+ AutofocusDirective,+ L10nTranslatePipe,+ BsDatepickerDirective,+ BsDatepickerInputDirective,+ ReactiveFormsModule,+ ButtonCheckboxDirective+ ],+ templateUrl: './user-auth-manage-app-passwords-dialog.component.html'+})+export class UserAuthManageAppPasswordsDialogComponent implements OnInit {+ @Input({ required: true }) appPasswords: Omit<UserAppPassword, 'password'>[] = []+ @Output() nbAppPasswords = new EventEmitter<number>()+ protected locale = inject<L10nLocale>(L10N_LOCALE)+ protected availableApps: AUTH_SCOPE[] = Object.values(AUTH_SCOPE)+ protected allowGeneration = false+ protected generatedPassword: UserAppPassword+ protected readonly minDate: Date = currentDate()+ protected hasError: string+ protected submitted = false+ protected readonly icons = { faKey, faCopy, faPlus }+ private readonly fb = inject(UntypedFormBuilder)+ protected appPasswordForm: FormGroup = this.fb.group({+ name: this.fb.control('', [Validators.required]),+ app: this.fb.control(AUTH_SCOPE.WEBDAV, [Validators.required]),+ expiration: this.fb.control(null)+ })+ private readonly layout = inject(LayoutService)+ private readonly userService = inject(UserService)+ private readonly clipBoardService = inject(ClipboardService)++ constructor() {+ // set picker expiration to current date + 1 day+ this.minDate.setDate(this.minDate.getDate() + 1)+ this.appPasswordForm.controls.name.valueChanges.pipe(filter(Boolean)).subscribe((value: string) => {+ this.hasError = undefined+ this.appPasswordForm.controls.name.setValue(createLightSlug(value), { emitEvent: false })+ })+ }++ ngOnInit() {+ if (this.appPasswords.length === 0) {+ this.allowGeneration = true+ }+ }++ onClose() {+ this.layout.closeDialog()+ }++ deleteAppPassword(passwordName: string) {+ this.userService.deleteAppPassword(passwordName).subscribe({+ next: () => {+ this.appPasswords = this.appPasswords.filter((pwd) => pwd.name !== passwordName)+ this.nbAppPasswords.emit(this.appPasswords.length)+ },+ error: (e: HttpErrorResponse) => this.layout.sendNotification('error', 'Application Passwords', 'Unable to revoke', e)+ })+ }++ genAppPassword() {+ for (const appPwd of this.appPasswords) {+ if (appPwd.name === this.appPasswordForm.value.name) {+ this.hasError = 'This name is already used'+ return+ }+ }+ this.userService.generateAppPassword(this.appPasswordForm.value).subscribe({+ next: (appPassword: UserAppPassword) => {+ this.appPasswordForm.patchValue({ name: '', expiration: null })+ this.appPasswords.unshift(appPassword)+ this.generatedPassword = appPassword+ this.nbAppPasswords.emit(this.appPasswords.length)+ },+ error: (e: HttpErrorResponse) => this.layout.sendNotification('error', 'Application Passwords', 'Unable to generate', e)+ })+ }++ clipBoardPassword() {+ this.clipBoardService.copyFromContent(this.generatedPassword.password)+ this.layout.sendNotification('info', 'Generated password', 'Copied')+ }++ onAllowGenerationChange() {+ if (this.generatedPassword) {+ this.generatedPassword = null+ this.allowGeneration = true+ } else {+ this.allowGeneration = !this.allowGeneration+ }+ }+}diff --git a/frontend/src/app/applications/users/components/user-account.component.html b/frontend/src/app/applications/users/components/user-account.component.htmlindex 3a26c0c3..0ff47c33 100755--- a/frontend/src/app/applications/users/components/user-account.component.html+++ b/frontend/src/app/applications/users/components/user-account.component.html@@ -153,29 +153,30 @@<span class="col-3 align-self-start text-nowrap" l10nTranslate>Security</span><div class="col-auto"><div class="fw-500 mb-2" l10nTranslate>Two-Factor Authentication</div>+ <button (click)="enable2Fa()"+ [disabled]="!store.server().twoFaEnabled"+ class="btn btn-xs btn-primary"+ type="button" l10nTranslate>+ {{user.twoFaEnabled ? 'Reset' : 'Enable'}}+ </button>@if (user.twoFaEnabled) {- <button (click)="enable2Fa()"+ <button (click)="disable2Fa()"[disabled]="!store.server().twoFaEnabled"- class="btn btn-xs btn-warning me-2"+ class="btn btn-xs btn-danger ms-2"type="button" l10nTranslate>- Reset+ Disable</button>- <button (click)="disable2Fa()"- [disabled]="!store.server().twoFaEnabled"- class="btn btn-xs btn-danger"- type="button" l10nTranslate>- Disable- </button>- } @else {- <div class="mb-1">- <button (click)="enable2Fa()"- [disabled]="!store.server().twoFaEnabled"- class="btn btn-xs btn-primary me-1"- type="button" l10nTranslate>- Enable- </button>- </div>}+ <div class="fw-500 mt-3 mb-2" l10nTranslate>Application Passwords</div>+ <button (click)="manageAppPasswords()"+ class="btn btn-xs btn-primary me-1"+ type="button" l10nTranslate>+ @if (user.appPasswords > 0) {+ <span l10nTranslate>Manage</span> <span>({{user.appPasswords}})</span>+ } @else {+ <span l10nTranslate>Generate</span>+ }+ </button></div></div>}diff --git a/frontend/src/app/applications/users/components/user-account.component.ts b/frontend/src/app/applications/users/components/user-account.component.tsindex a6daa6ed..42351236 100644--- a/frontend/src/app/applications/users/components/user-account.component.ts+++ b/frontend/src/app/applications/users/components/user-account.component.ts@@ -14,6 +14,7 @@ import {USER_ONLINE_STATUS_LIST,USER_PASSWORD_MIN_LENGTH} from '@sync-in-server/backend/src/applications/users/constants/user'+import { UserAppPassword } from '@sync-in-server/backend/src/applications/users/interfaces/user-secrets.interface'import { WEBDAV_BASE_PATH } from '@sync-in-server/backend/src/applications/webdav/constants/routes'import { TwoFaSetup } from '@sync-in-server/backend/src/authentication/interfaces/two-fa-setup.interface'import { L10N_LOCALE, L10nLocale, L10nTranslateDirective, L10nTranslatePipe } from 'angular-l10n'@@ -35,6 +36,7 @@ import { UserType } from '../interfaces/user.interface'import { USER_ICON, USER_LANGUAGE_AUTO, USER_PATH, USER_TITLE } from '../user.constants'import { UserService } from '../user.service'import { UserAuth2faEnableDialogComponent } from './dialogs/user-auth-2fa-enable-dialog.component'+import { UserAuthManageAppPasswordsDialogComponent } from './dialogs/user-auth-manage-app-passwords-dialog.component'@Component({selector: 'app-user-account',@@ -156,7 +158,7 @@ export class UserAccountComponent implements OnDestroy {this.user.notification = statusthis.layout.sendNotification('info', 'Configuration', 'Notification preference updated')},- error: () => this.layout.sendNotification('error', 'Configuration', 'Unable to update notification preference')+ error: (e: HttpErrorResponse) => this.layout.sendNotification('error', 'Configuration', 'Unable to update notification preference', e)})}@@ -205,6 +207,22 @@ export class UserAccountComponent implements OnDestroy {})}+ async manageAppPasswords() {+ this.userService.listAppPasswords().subscribe({+ next: (appPasswords: Omit<UserAppPassword, 'password'>[]) => {+ const modalRef: BsModalRef<UserAuthManageAppPasswordsDialogComponent> = this.layout.openDialog(+ UserAuthManageAppPasswordsDialogComponent,+ 'md',+ { initialState: { appPasswords: appPasswords } as UserAuthManageAppPasswordsDialogComponent }+ )+ modalRef.content.nbAppPasswords.subscribe((nb: number) => {+ this.store.user.next({ ...this.store.user.getValue(), appPasswords: nb })+ })+ },+ error: (e: HttpErrorResponse) => this.layout.sendNotification('error', 'Configuration', 'Unable to get app passwords', e)+ })+ }+private updateLanguage(language: string) {this.user.language = languagethis.layout.setLanguage(language)diff --git a/frontend/src/app/applications/users/user.service.ts b/frontend/src/app/applications/users/user.service.tsindex 6ea76c2e..542db434 100644--- a/frontend/src/app/applications/users/user.service.ts+++ b/frontend/src/app/applications/users/user.service.ts@@ -11,6 +11,7 @@ import { SPACE_OPERATION } from '@sync-in-server/backend/src/applications/spacesimport { SYNC_ROUTE } from '@sync-in-server/backend/src/applications/sync/constants/routes'import { AppStoreManifest } from '@sync-in-server/backend/src/applications/sync/interfaces/store-manifest.interface'import {+ API_USERS_MY_APP_PASSWORDS,API_USERS_MY_AVATAR,API_USERS_MY_GROUPS,API_USERS_MY_GROUPS_BROWSE,@@ -31,6 +32,7 @@ import type {} from '@sync-in-server/backend/src/applications/users/dto/create-or-update-user.dto'import type { SearchMembersDto } from '@sync-in-server/backend/src/applications/users/dto/search-members.dto'import type {+ UserAppPasswordDto,UserLanguageDto,UserNotificationDto,UserPasswordDto,@@ -40,6 +42,7 @@ import type { GroupBrowse } from '@sync-in-server/backend/src/applications/usersimport type { GroupMember } from '@sync-in-server/backend/src/applications/users/interfaces/group-member'import type { GuestUser } from '@sync-in-server/backend/src/applications/users/interfaces/guest-user.interface'import type { Member } from '@sync-in-server/backend/src/applications/users/interfaces/member.interface'+import type { UserAppPassword } from '@sync-in-server/backend/src/applications/users/interfaces/user-secrets.interface'import type {EventChangeOnlineStatus,EventUpdateOnlineStatus,@@ -285,6 +288,18 @@ export class UserService {})}+ listAppPasswords(): Observable<Omit<UserAppPassword, 'password'>[]> {+ return this.http.get<Omit<UserAppPassword, 'password'>[]>(API_USERS_MY_APP_PASSWORDS)+ }++ generateAppPassword(userAppPasswordDto: UserAppPasswordDto): Observable<UserAppPassword> {+ return this.http.post<UserAppPassword>(API_USERS_MY_APP_PASSWORDS, userAppPasswordDto)+ }++ deleteAppPassword(name: string): Observable<void> {+ return this.http.delete<void>(`${API_USERS_MY_APP_PASSWORDS}/${name}`)+ }+init2Fa(): Observable<TwoFaSetup> {return this.http.get<TwoFaSetup>(API_TWO_FA_ENABLE)}diff --git a/frontend/src/app/common/components/input-password.component.ts b/frontend/src/app/common/components/input-password.component.tsindex 1f0ce71a..a099d91e 100644--- a/frontend/src/app/common/components/input-password.component.ts+++ b/frontend/src/app/common/components/input-password.component.ts@@ -9,8 +9,9 @@ import { FormsModule, ReactiveFormsModule } from '@angular/forms'import { FaIconComponent } from '@fortawesome/angular-fontawesome'import { faDice, faEye, faEyeSlash } from '@fortawesome/free-solid-svg-icons'import { USER_PASSWORD_MIN_LENGTH } from '@sync-in-server/backend/src/applications/users/constants/user'+import { genPassword } from '@sync-in-server/backend/src/common/shared'import { L10N_LOCALE, L10nLocale, L10nTranslateDirective, L10nTranslatePipe } from 'angular-l10n'-import { genPassword, togglePasswordType } from '../utils/functions'+import { togglePasswordType } from '../utils/functions'@Component({selector: 'app-input-password',diff --git a/frontend/src/app/common/utils/functions.ts b/frontend/src/app/common/utils/functions.tsindex 9abad733..0e731ff4 100644--- a/frontend/src/app/common/utils/functions.ts+++ b/frontend/src/app/common/utils/functions.ts@@ -58,16 +58,6 @@ export function genRandomUUID(): string {return Math.random().toString(36).substring(7)}-export function genPassword(length = 12) {- const chars = '0123456789abcdefghijklmnopqrstuvwxyz!@#$%^&*()ABCDEFGHIJKLMNOPQRSTUVWXYZ'- let password = ''- for (let i = 0; i <= length; i++) {- const randomNumber = Math.floor(Math.random() * chars.length)- password += chars.substring(randomNumber, randomNumber + 1)- }- return password-}-export function convertTextToBytes(bytes: number, unit: string, precision = 0): number {const exponent = units.indexOf(unit.toUpperCase())return parseInt((bytes * Math.pow(1024, Math.floor(exponent))).toFixed(precision), 10)diff --git a/frontend/src/i18n/fr.json b/frontend/src/i18n/fr.jsonindex 1c6ec18f..9d00a9fd 100644--- a/frontend/src/i18n/fr.json+++ b/frontend/src/i18n/fr.json@@ -212,6 +212,7 @@"Update share": "Modifier le partage","Delete share": "Supprimer le partage","Child shares": "Partages enfants",+ "webdav": "WebDAV","Share is disabled": "Le partage est désactivé","Space": "Espace","Spaces": "Espaces",@@ -334,6 +335,7 @@"The client will no longer have permission to access your account and will no longer be able to synchronize.": "Le client n'aura plus l'autorisation d'accéder à votre compte et ne pourra plus synchroniser.","The access expires": "L'accès expire","The access has expired": "L'accès a expiré",+ "Never expires": "N’expire jamais","synchronization": "synchronisation","Synchronization": "Synchronisation","Synchronizations": "Synchronisations",@@ -681,6 +683,13 @@"Secret copied": "Secret copié","Recovery codes copied": "Codes de récupération copiés","Invalid code": "Code invalide",+ "Application Passwords": "Mots de passe d'application",+ "Generate a new app password": "Générer un nouveau mot de passe d’application",+ "Generated password": "Mot de passe généré",+ "This password will only be shown once after it is generated": "Ce mot de passe ne sera affiché qu’une seule fois après sa génération",+ "Password name": "Nom du mot de passe",+ "Manage": "Gérer",+ "Manage app passwords": "Gérer les mots de passe d’application","Two-Factor Authentication": "Authentification à deux facteurs","Two-Factor Authentication is enabled": "L’authentification à deux facteurs est activée","Two-Factor Authentication is disabled": "L’authentification à deux facteurs est désactivée",