ActivityPub-federated video streaming platform using P2P directly in your web browser
Better too long password error UX
Chocobozzzdb5d1358e399
diff --git a/client/src/app/+login/login.component.html b/client/src/app/+login/login.component.htmlindex 9ab1926519..47bc00fe52 100644--- a/client/src/app/+login/login.component.html+++ b/client/src/app/+login/login.component.html@@ -34,9 +34,17 @@<my-alert type="danger">{{ error }}- @if (error === 'User email is not verified.') {+ @if (emailNotVerifiedError) {<a class="ms-1 link-primary" i18n routerLink="/verify-account/ask-send-email">Request new verification email</a>}++ @if (passwordTooLongError) {+ <div>+ <button type="button" i18n class="button-unstyle link-primary" (click)="openForgotPasswordModal()">+ Reset your password+ </button>+ </div>+ }</my-alert>}diff --git a/client/src/app/+login/login.component.ts b/client/src/app/+login/login.component.tsindex 18117927e3..fce88fae8a 100644--- a/client/src/app/+login/login.component.ts+++ b/client/src/app/+login/login.component.ts@@ -59,7 +59,11 @@ export class LoginComponent extends FormReactive implements OnInit, AfterViewInireadonly instanceAboutAccordion = viewChild<InstanceAboutAccordionComponent>('instanceAboutAccordion')accordion: NgbAccordionDirective+error: string = null+ emailNotVerifiedError = false+ passwordTooLongError = false+forgotPasswordEmail = ''isAuthenticatedWithExternalAuth = false@@ -156,6 +160,8 @@ export class LoginComponent extends FormReactive implements OnInit, AfterViewInilogin () {this.error = null+ this.emailNotVerifiedError = false+ this.passwordTooLongError = falseconst options = {username: this.form.value['username'],@@ -242,12 +248,12 @@ The link will expire within 1 hour.`return}- if (err.message.includes('credentials are invalid')) {+ if (err.body?.code === ServerErrorCode.INVALID_GRANT) {this.error = $localize`Incorrect username or password.`return}- if (err.message.includes('blocked')) {+ if (err.body?.code === ServerErrorCode.ACCOUNT_BLOCKED) {this.error = $localize`Your account is blocked.`return}@@ -262,6 +268,16 @@ The link will expire within 1 hour.`return}+ if (err.body?.code === ServerErrorCode.TOO_LONG_PASSWORD) {+ this.error = $localize`Your current password is too long. Please reset it.`+ this.passwordTooLongError = true+ return+ }++ if (err.body?.code === ServerErrorCode.EMAIL_NOT_VERIFIED) {+ this.emailNotVerifiedError = true+ }+this.error = err.message}diff --git a/packages/models/src/server/server-error-code.enum.ts b/packages/models/src/server/server-error-code.enum.tsindex 2b863731d8..53c54e2369 100644--- a/packages/models/src/server/server-error-code.enum.ts+++ b/packages/models/src/server/server-error-code.enum.ts@@ -41,8 +41,12 @@ export const ServerErrorCode = {COMMENT_NOT_ASSOCIATED_TO_VIDEO: 'comment_not_associated_to_video',+ INVALID_GRANT: 'invalid_grant',MISSING_TWO_FACTOR: 'missing_two_factor',+ TOO_LONG_PASSWORD: 'too_long_password',INVALID_TWO_FACTOR: 'invalid_two_factor',+ ACCOUNT_BLOCKED: 'account_blocked',+ EMAIL_NOT_VERIFIED: 'email_not_verified',ACCOUNT_WAITING_FOR_APPROVAL: 'account_waiting_for_approval',ACCOUNT_APPROVAL_REJECTED: 'account_approval_rejected',diff --git a/packages/tests/src/api/check-params/user-me.ts b/packages/tests/src/api/check-params/user-me.tsindex 70c5024d3a..762560f72f 100644--- a/packages/tests/src/api/check-params/user-me.ts+++ b/packages/tests/src/api/check-params/user-me.ts@@ -113,12 +113,23 @@ describe('Test my user API validators', function () {})it('Should fail with a too long password', async function () {- const fields = {- currentPassword: 'password',- password: 'super'.repeat(61)+ {+ const fields = {+ currentPassword: 'password',+ password: 'super'.repeat(61)+ }++ await makePutBodyRequest({ url: server.url, path: path + 'me', token: userToken, fields })}- await makePutBodyRequest({ url: server.url, path: path + 'me', token: userToken, fields })+ {+ const fields = {+ currentPassword: 'password',+ password: '😁'.repeat(20)+ }++ await makePutBodyRequest({ url: server.url, path: path + 'me', token: userToken, fields })+ }})it('Should fail without the current password', async function () {diff --git a/packages/tests/src/api/users/users-email-verification.ts b/packages/tests/src/api/users/users-email-verification.tsindex 9f3863db2f..f4f956e001 100644--- a/packages/tests/src/api/users/users-email-verification.ts+++ b/packages/tests/src/api/users/users-email-verification.ts@@ -75,8 +75,8 @@ describe('Test users email verification', function () {})it('Should not allow login for user with unverified email', async function () {- const { detail } = await server.login.login({ user: user1, expectedStatus: HttpStatusCode.BAD_REQUEST_400 })- expect(detail).to.contain('User email is not verified.')+ const { code } = await server.login.login({ user: user1, expectedStatus: HttpStatusCode.BAD_REQUEST_400 })+ expect(code).to.equal('email_not_verified')})it('Should verify the user via email and allow login', async function () {diff --git a/server/core/helpers/custom-validators/users.ts b/server/core/helpers/custom-validators/users.tsindex 1cc69fc98c..9d6f40cbbc 100644--- a/server/core/helpers/custom-validators/users.ts+++ b/server/core/helpers/custom-validators/users.ts@@ -8,7 +8,13 @@ import { exists, isArray, isBooleanValid } from './misc.js'const USERS_CONSTRAINTS_FIELDS = CONSTRAINTS_FIELDS.USERSexport function isUserPasswordValid (value: string) {- return validator.default.isLength(value, USERS_CONSTRAINTS_FIELDS.PASSWORD)+ return validator.default.isLength(value, { min: USERS_CONSTRAINTS_FIELDS.PASSWORD.min }) &&+ isUserPasswordTooLong(value) !== true+}++export function isUserPasswordTooLong (value: string) {+ return !validator.default.isLength(value, { max: USERS_CONSTRAINTS_FIELDS.PASSWORD.max }) ||+ Buffer.byteLength(value, 'utf8') > USERS_CONSTRAINTS_FIELDS.PASSWORD.maxBytes}export function isUserPasswordValidOrEmpty (value: string) {diff --git a/server/core/initializers/constants.ts b/server/core/initializers/constants.tsindex f5744dc55b..cf064d4f62 100644--- a/server/core/initializers/constants.ts+++ b/server/core/initializers/constants.ts@@ -378,7 +378,7 @@ export const CONSTRAINTS_FIELDS = {NAME: { min: 1, max: 120 }, // LengthDESCRIPTION: { min: 3, max: 1000 }, // LengthUSERNAME: { min: 1, max: 50 }, // Length- PASSWORD: { min: CONFIG.USER.PASSWORD_CONSTRAINTS.MIN_LENGTH, max: 50 }, // Length+ PASSWORD: { min: CONFIG.USER.PASSWORD_CONSTRAINTS.MIN_LENGTH, max: 50, maxBytes: 72 }, // Limited by bcrypt algorithmVIDEO_QUOTA: { min: -1 },VIDEO_QUOTA_DAILY: { min: -1 },VIDEO_LANGUAGES: { max: 500 }, // Array lengthdiff --git a/server/core/lib/auth/oauth-model.ts b/server/core/lib/auth/oauth-model.tsindex 31e7a0c021..1202d31616 100644--- a/server/core/lib/auth/oauth-model.ts+++ b/server/core/lib/auth/oauth-model.ts@@ -1,13 +1,14 @@-import express from 'express'import { AccessDeniedError } from '@node-oauth/oauth2-server'+import { pick } from '@peertube/peertube-core-utils'+import { AttributesOnly } from '@peertube/peertube-typescript-utils'+import { isUserPasswordTooLong } from '@server/helpers/custom-validators/users.js'import { PluginManager } from '@server/lib/plugins/plugin-manager.js'import { AccountModel } from '@server/models/account/account.js'import { AuthenticatedResultUpdaterFieldName, RegisterServerAuthenticatedResult } from '@server/types/index.js'import { MOAuthClient } from '@server/types/models/index.js'import { MOAuthTokenUser } from '@server/types/models/oauth/oauth-token.js'import { MUser, MUserDefault } from '@server/types/models/user/user.js'-import { pick } from '@peertube/peertube-core-utils'-import { AttributesOnly } from '@peertube/peertube-typescript-utils'+import express from 'express'import { logger } from '../../helpers/logger.js'import { CONFIG } from '../../initializers/config.js'import { OAuthClientModel } from '../../models/oauth/oauth-client.js'@@ -16,6 +17,7 @@ import { UserModel } from '../../models/user/user.js'import { findAvailableLocalActorName } from '../local-actor.js'import { buildUser, createUserAccountAndChannelAndPlaylist, getByEmailPermissive } from '../user.js'import { ExternalUser } from './external-auth.js'+import { AccountBlockedError, EmailNotVerifiedError, TooLongPasswordError } from './oauth.js'import { TokensCache } from './tokens-cache.js'type TokenInfo = {@@ -88,7 +90,13 @@ async function getRefreshToken (refreshToken: string) {return tokenInfo}-async function getUser (usernameOrEmail?: string, password?: string, bypassLogin?: BypassLogin) {+// Keep this function signature, required by oauth2-server+async function getUser (usernameOrEmail?: string, password?: string, options?: {+ bypassLogin?: BypassLogin+ req: express.Request+}) {+ const { bypassLogin, req } = options+// Special treatment coming from a pluginif (bypassLogin?.bypass === true) {logger.info('Bypassing oauth login by plugin %s.', bypassLogin.pluginName)@@ -102,7 +110,7 @@ async function getUser (usernameOrEmail?: string, password?: string, bypassLogin}// Cannot create a user- if (!user) throw new AccessDeniedError('Cannot create such user: an actor with that name already exists.')+ if (!user) throw new AccessDeniedError(req.t('Cannot create such user: an actor with that name already exists.'))// If the user does not belongs to a plugin, it was created before its installation// Then we just go through a regular login process@@ -119,7 +127,7 @@ async function getUser (usernameOrEmail?: string, password?: string, bypassLoginreturn null}- checkUserValidityOrThrow(user)+ checkUserValidityOrThrow(user, req)return user}@@ -142,12 +150,16 @@ async function getUser (usernameOrEmail?: string, password?: string, bypassLoginconst passwordMatch = await user.isPasswordMatch(password)if (passwordMatch !== true) return null- checkUserValidityOrThrow(user)+ if (isUserPasswordTooLong(password)) {+ throw new TooLongPasswordError(req.t('Password is too long. Please reset it using the password reset procedure.'))+ }++ checkUserValidityOrThrow(user, req)if (CONFIG.SIGNUP.REQUIRES_EMAIL_VERIFICATION && user.emailVerified === false) {// Keep this message sync with the client// TODO: use custom server code- throw new AccessDeniedError('User email is not verified.')+ throw new EmailNotVerifiedError(req.t('User email is not verified.'))}return user@@ -313,8 +325,8 @@ async function updateUserFromExternal (return user.save()}-function checkUserValidityOrThrow (user: MUser) {- if (user.blocked) throw new AccessDeniedError('User is blocked.')+function checkUserValidityOrThrow (user: MUser, req: express.Request) {+ if (user.blocked) throw new AccountBlockedError(req.t('User is blocked.'))}function buildExpiresIn (expiresAt: Date) {diff --git a/server/core/lib/auth/oauth.ts b/server/core/lib/auth/oauth.tsindex 172e91c7af..701660ff1b 100644--- a/server/core/lib/auth/oauth.ts+++ b/server/core/lib/auth/oauth.ts@@ -25,6 +25,21 @@ class MissingTwoFactorError extends Error {name = ServerErrorCode.MISSING_TWO_FACTOR}+class TooLongPasswordError extends Error {+ code = HttpStatusCode.BAD_REQUEST_400+ name = ServerErrorCode.TOO_LONG_PASSWORD+}++class AccountBlockedError extends Error {+ code = HttpStatusCode.BAD_REQUEST_400+ name = ServerErrorCode.ACCOUNT_BLOCKED+}++class EmailNotVerifiedError extends Error {+ code = HttpStatusCode.BAD_REQUEST_400+ name = ServerErrorCode.EMAIL_NOT_VERIFIED+}+class InvalidTwoFactorError extends Error {code = HttpStatusCode.BAD_REQUEST_400name = ServerErrorCode.INVALID_TWO_FACTOR@@ -62,19 +77,19 @@ const oAuthServer = new OAuth2Server({// ---------------------------------------------------------------------------async function handleOAuthToken (req: express.Request, options: { refreshTokenAuthName?: string, bypassLogin?: BypassLogin }) {- const request = new Request(req)+ const oauthRequest = new Request(req)const { refreshTokenAuthName, bypassLogin } = options- if (request.method !== 'POST') {+ if (oauthRequest.method !== 'POST') {throw new InvalidRequestError('Invalid request: method must be POST')}- if (!request.is([ 'application/x-www-form-urlencoded' ])) {+ if (!oauthRequest.is([ 'application/x-www-form-urlencoded' ])) {throw new InvalidRequestError('Invalid request: content must be application/x-www-form-urlencoded')}- const clientId = request.body.client_id- const clientSecret = request.body.client_secret+ const clientId = oauthRequest.body.client_id+ const clientSecret = oauthRequest.body.client_secretif (!clientId || !clientSecret) {throw new InvalidClientError('Invalid client: cannot retrieve client credentials')@@ -85,7 +100,7 @@ async function handleOAuthToken (req: express.Request, options: { refreshTokenAuthrow new InvalidClientError('Invalid client: client is invalid')}- const grantType = request.body.grant_type+ const grantType = oauthRequest.body.grant_typeif (!grantType) {throw new InvalidRequestError('Missing parameter: `grant_type`')}@@ -103,7 +118,8 @@ async function handleOAuthToken (req: express.Request, options: { refreshTokenAuif (grantType === 'password') {return handlePasswordGrant({- request,+ req,+ oauthRequest,client,bypassLogin,ip,@@ -112,7 +128,8 @@ async function handleOAuthToken (req: express.Request, options: { refreshTokenAu}return handleRefreshGrant({- request,+ req,+ oauthRequest,client,refreshTokenAuthName,ip,@@ -131,56 +148,60 @@ export {handleOAuthAuthenticate,handleOAuthToken,InvalidTwoFactorError,- MissingTwoFactorError+ MissingTwoFactorError,+ TooLongPasswordError,+ AccountBlockedError,+ EmailNotVerifiedError}// ---------------------------------------------------------------------------async function handlePasswordGrant (options: {- request: Request+ req: express.Request+ oauthRequest: Requestclient: MOAuthClientbypassLogin?: BypassLoginip: stringuserAgent: string}) {- const { client } = options+ const { req, oauthRequest, client } = optionsconst { bypassLogin, usernameOrEmail, password } = await Hooks.wrapObject({bypassLogin: options.bypassLogin,- usernameOrEmail: options.request.body.username,- password: options.request.body.password+ usernameOrEmail: oauthRequest.body.username,+ password: oauthRequest.body.password}, 'filter:oauth.password-grant.get-user.params')- if (!options.request.body.username) {- throw new InvalidRequestError('Missing parameter: `username`')+ if (!options.oauthRequest.body.username) {+ throw new InvalidRequestError(req.t('Missing parameter: `username`'))}- if (!bypassLogin && !options.request.body.password) {- throw new InvalidRequestError('Missing parameter: `password`')+ if (!bypassLogin && !options.oauthRequest.body.password) {+ throw new InvalidRequestError(req.t('Missing parameter: `password`'))}- const user = await getUser(usernameOrEmail, password, bypassLogin)+ const user = await getUser(usernameOrEmail, password, { bypassLogin, req })if (!user) {const registrations = await UserRegistrationModel.listByEmailCaseInsensitiveOrUsername(usernameOrEmail)if (registrations.length === 1) {if (registrations[0].state === UserRegistrationState.REJECTED) {- throw new RegistrationApprovalRejected('Registration approval for this account has been rejected')+ throw new RegistrationApprovalRejected(req.t('Registration approval for this account has been rejected'))} else if (registrations[0].state === UserRegistrationState.PENDING) {- throw new RegistrationWaitingForApproval('Registration for this account is awaiting approval')+ throw new RegistrationWaitingForApproval(req.t('Registration for this account is awaiting approval'))}}- throw new InvalidGrantError('Invalid grant: user credentials are invalid')+ throw new InvalidGrantError(req.t('Invalid grant: user credentials are invalid'))}if (user.otpSecret) {- if (!options.request.headers[OTP.HEADER_NAME]) {- throw new MissingTwoFactorError('Missing two factor header')+ if (!options.oauthRequest.headers[OTP.HEADER_NAME]) {+ throw new MissingTwoFactorError(req.t('Missing two factor header'))}- if (await isOTPValid({ encryptedSecret: user.otpSecret, token: options.request.headers[OTP.HEADER_NAME] }) !== true) {- throw new InvalidTwoFactorError('Invalid two factor header')+ if (await isOTPValid({ encryptedSecret: user.otpSecret, token: options.oauthRequest.headers[OTP.HEADER_NAME] }) !== true) {+ throw new InvalidTwoFactorError(req.t('Invalid two factor header'))}}@@ -199,30 +220,31 @@ async function handlePasswordGrant (options: {}async function handleRefreshGrant (options: {- request: Request+ req: express.Request+ oauthRequest: Requestclient: MOAuthClientrefreshTokenAuthName: stringip: stringuserAgent: string}) {- const { request, client, refreshTokenAuthName } = options+ const { req, oauthRequest, client, refreshTokenAuthName } = options- if (!request.body.refresh_token) {- throw new InvalidRequestError('Missing parameter: `refresh_token`')+ if (!oauthRequest.body.refresh_token) {+ throw new InvalidRequestError(req.t('Missing parameter: `refresh_token`'))}- const refreshToken = await getRefreshToken(request.body.refresh_token)+ const refreshToken = await getRefreshToken(oauthRequest.body.refresh_token)if (!refreshToken) {- throw new InvalidGrantError('Invalid grant: refresh token is invalid')+ throw new InvalidGrantError(req.t('Invalid grant: refresh token is invalid'))}if (refreshToken.client.id !== client.id) {- throw new InvalidGrantError('Invalid grant: refresh token is invalid')+ throw new InvalidGrantError(req.t('Invalid grant: refresh token is invalid'))}if (refreshToken.refreshTokenExpiresAt && refreshToken.refreshTokenExpiresAt < new Date()) {- throw new InvalidGrantError('Invalid grant: refresh token has expired')+ throw new InvalidGrantError(req.t('Invalid grant: refresh token has expired'))}await revokeToken({ refreshToken: refreshToken.refreshToken })diff --git a/server/core/middlewares/validators/users/users.ts b/server/core/middlewares/validators/users/users.tsindex 7a5181e9f3..46470117b5 100644--- a/server/core/middlewares/validators/users/users.ts+++ b/server/core/middlewares/validators/users/users.ts@@ -304,23 +304,25 @@ export const usersUpdateMeValidator = [) {return res.fail({status: HttpStatusCode.BAD_REQUEST_400,- message: 'Cannot use same flags in nsfwFlagsDisplayed, nsfwFlagsHidden, nsfwFlagsBlurred and nsfwFlagsWarned at the same time'+ message: req.t(+ 'Cannot use same flags in nsfwFlagsDisplayed, nsfwFlagsHidden, nsfwFlagsBlurred and nsfwFlagsWarned at the same time'+ )})}if (body.password || body.email) {if (user.pluginAuth !== null) {- return res.fail({ message: 'You cannot update your email or password that is associated with an external auth system.' })+ return res.fail({ message: req.t('You cannot update your email or password that is associated with an external auth system.') })}if (!body.currentPassword) {- return res.fail({ message: 'currentPassword parameter is missing' })+ return res.fail({ message: req.t('currentPassword parameter is missing') })}if (await user.isPasswordMatch(body.currentPassword) !== true) {return res.fail({status: HttpStatusCode.UNAUTHORIZED_401,- message: 'currentPassword is invalid.',+ message: req.t('currentPassword is invalid.'),type: ServerErrorCode.CURRENT_PASSWORD_IS_INVALID})}diff --git a/support/doc/api/openapi.yaml b/support/doc/api/openapi.yamlindex 622ec10fd7..868b5d6898 100644--- a/support/doc/api/openapi.yaml+++ b/support/doc/api/openapi.yaml@@ -8522,7 +8522,7 @@ components:type: stringformat: passwordminLength: 6- maxLength: 255+ maxLength: 50VideoCategorySet:type: integer