Repository navigation
regression: 2fa inline errors for API calls #40678
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Closed
Closed
Changes from 6 commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
af70d19
fix: Password sent unencrypted
gabriellsh a25a2ea
wip refactor
gabriellsh 7290717
Undo
gabriellsh ed0593e
fix ts
gabriellsh 18d1694
remove logs
gabriellsh 068699b
Fix issues with modal not closing sometimes
gabriellsh 786e3c8
Improve cleanup
gabriellsh f0ef21f
Add tests
gabriellsh 6be1d19
Update packages/api-client/src/errors.ts
gabriellsh File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,161 @@ | ||
| import type { TwoFactorMethod } from '@rocket.chat/api-client'; | ||
| import { isTotpInvalidError, isTotpRequiredError, hasRequiredTwoFactorMethod, isTotpMaxAttemptsError } from '@rocket.chat/api-client'; | ||
| import { SHA256 } from '@rocket.chat/sha256'; | ||
| import { imperativeModal } from '@rocket.chat/ui-client'; | ||
| import { lazy } from 'react'; | ||
|
|
||
| import { getUser } from '../user'; | ||
|
|
||
| const TwoFactorModal = lazy(() => import('../../components/TwoFactorModal')); | ||
|
|
||
| type RejectChallenge = (error: unknown) => void; | ||
| type OnConfirm = (twoFactorCode: string) => Promise<void>; | ||
| type OnClose = () => void; | ||
| type UnresolvedChallenge = { | ||
| onConfirm: OnConfirm; | ||
| rejectChallenge: RejectChallenge; | ||
| onClose: OnClose; | ||
| }; | ||
|
|
||
| // This is a "store" for callbacks that need to be accessed outside of the challenge2fa function's scope | ||
| // e.g. We cannot update modal props, so callbacks that can change are stored here, and then wrapped in another function | ||
| // that will call whatever is present here. | ||
| let unresolvedChallenge: undefined | UnresolvedChallenge = undefined; | ||
|
|
||
| const saveChallenge = (challenge: UnresolvedChallenge) => { | ||
| unresolvedChallenge = challenge; | ||
| }; | ||
|
|
||
| const endChallenge = (rejectError?: unknown) => { | ||
| if (rejectError) { | ||
| unresolvedChallenge?.rejectChallenge(rejectError); | ||
| } | ||
| unresolvedChallenge = undefined; | ||
| imperativeModal.close(); | ||
| }; | ||
|
|
||
| const wrapWithEndChallenge = (cb: () => void) => () => { | ||
| endChallenge(); | ||
| cb(); | ||
| }; | ||
|
|
||
| // Helper to extract the resolvers from a promise without TS complaining the functions might not exist | ||
| const makeResolvablePromise = <T>() => { | ||
| let resolve: undefined | ((value: T) => void) = undefined; | ||
| let reject: undefined | ((error: unknown) => void) = undefined; | ||
| const promise = new Promise<T>((_resolve, _reject) => { | ||
| resolve = _resolve; | ||
| reject = _reject; | ||
| }); | ||
|
|
||
| if (!resolve || !reject) { | ||
| throw new Error('Failed to create resolvable promise'); | ||
| } | ||
|
|
||
| return [promise, resolve as (value: T | PromiseLike<T>) => void, reject as (error: unknown) => void] as const; | ||
| }; | ||
|
|
||
| const getProps = ( | ||
| method: 'totp' | 'email' | 'password', | ||
| emailOrUsername?: { username: string } | { email: string } | { id: string } | string, | ||
| ) => { | ||
| switch (method) { | ||
| case 'totp': | ||
| return { method }; | ||
| case 'email': | ||
| return { | ||
| method, | ||
| emailOrUsername: typeof emailOrUsername === 'string' ? emailOrUsername : getUser()?.username, | ||
| }; | ||
| case 'password': | ||
| return { method }; | ||
| } | ||
| }; | ||
|
|
||
| function assertModalProps(props: { | ||
| method: TwoFactorMethod; | ||
| emailOrUsername?: string; | ||
| }): asserts props is { method: 'totp' } | { method: 'password' } | { method: 'email'; emailOrUsername: string } { | ||
| if (props.method === 'email' && typeof props.emailOrUsername !== 'string') { | ||
| throw new Error('Invalid Two Factor method'); | ||
| } | ||
| } | ||
|
|
||
| type Request2faPromptOptions = { | ||
| error: unknown; | ||
| emailOrUsername?: string; | ||
| }; | ||
|
|
||
| export const challenge2fa = ({ error, emailOrUsername }: Request2faPromptOptions): [Promise<string>, () => void] | undefined => { | ||
| if (isTotpMaxAttemptsError(error)) { | ||
| Promise.all([import('../../../app/utils/lib/i18n'), import('../toast')]).then(([{ t }, { dispatchToastMessage }]) => { | ||
| dispatchToastMessage({ | ||
| type: 'error', | ||
| message: t('totp-max-attempts'), | ||
| }); | ||
| }); | ||
|
|
||
| if (unresolvedChallenge) { | ||
| endChallenge(error); | ||
| } | ||
|
|
||
| throw error; | ||
| } | ||
| if ((!isTotpRequiredError(error) && !isTotpInvalidError(error)) || !hasRequiredTwoFactorMethod(error)) { | ||
| if (unresolvedChallenge) { | ||
| endChallenge(error); | ||
| } | ||
|
|
||
| throw error; | ||
| } | ||
|
|
||
| const twoFactorMethod = 'details' in error ? error.details.method : 'password'; | ||
|
|
||
| // `code` promise is resolved with the actual code | ||
| const [code, resolveCode, rejectCode] = makeResolvablePromise<string>(); | ||
| // `challengePromise` is resolved async when the user completes the challenge | ||
| // or rejected with the new error in case this is a retry | ||
| const [challengePromise, resolveChallenge, rejectChallengePromise] = makeResolvablePromise<void>(); | ||
|
|
||
| const onConfirm = async (twoFactorCode: string): Promise<void> => { | ||
| const actualCode = twoFactorMethod === 'password' ? SHA256(twoFactorCode) : twoFactorCode; | ||
| resolveCode(actualCode); | ||
| await challengePromise; | ||
| endChallenge(); | ||
| }; | ||
|
|
||
| const onClose = () => { | ||
| endChallenge(); | ||
| rejectCode(new Error('Two-factor_authentication_cancelled')); | ||
| }; | ||
|
|
||
| const rejectChallenge = (error: unknown) => { | ||
| rejectChallengePromise(error); | ||
| }; | ||
|
|
||
| if (unresolvedChallenge) { | ||
| // This is a retry, the modal will catch this error in order to show inline information | ||
| unresolvedChallenge.rejectChallenge(error); | ||
| saveChallenge({ onConfirm, rejectChallenge, onClose }); | ||
| return [code, wrapWithEndChallenge(resolveChallenge)]; | ||
| } | ||
|
|
||
| saveChallenge({ onConfirm, rejectChallenge, onClose }); | ||
|
|
||
| const method = error.details.method ? error.details.method : 'password'; | ||
|
|
||
| const props = getProps(method, emailOrUsername || error.details.emailOrUsername || getUser()?.username); | ||
|
|
||
| assertModalProps(props); | ||
|
|
||
| imperativeModal.open({ | ||
| component: TwoFactorModal, | ||
| props: { | ||
| ...props, | ||
| onConfirm: (code) => unresolvedChallenge?.onConfirm(code), | ||
| onClose: () => unresolvedChallenge?.onClose(), | ||
| }, | ||
| }); | ||
|
|
||
| return [code, wrapWithEndChallenge(resolveChallenge)]; | ||
| }; | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change | ||||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
|
|
@@ -11,9 +11,9 @@ import { stringify } from 'query-string'; | |||||||||||||||||
|
|
||||||||||||||||||
| import type { Credentials } from './Credentials'; | ||||||||||||||||||
| import type { Middleware, RestClientInterface } from './RestClientInterface'; | ||||||||||||||||||
| import { hasRequiredTwoFactorMethod, isTotpInvalidError, isTotpRequiredError } from './errors'; | ||||||||||||||||||
|
|
||||||||||||||||||
| export type { RestClientInterface, Credentials }; | ||||||||||||||||||
| export * from './errors'; | ||||||||||||||||||
|
|
||||||||||||||||||
| const pipe = | ||||||||||||||||||
| <T extends (...args: any[]) => any>(fn: T) => | ||||||||||||||||||
|
|
@@ -51,11 +51,7 @@ const checkIfIsFormData = (data: any = {}): boolean => { | |||||||||||||||||
| }; | ||||||||||||||||||
|
|
||||||||||||||||||
| export class RestClient implements RestClientInterface { | ||||||||||||||||||
| private twoFactorHandler?: (args: { | ||||||||||||||||||
| method: 'totp' | 'email' | 'password'; | ||||||||||||||||||
| emailOrUsername?: string; | ||||||||||||||||||
| invalidAttempt?: boolean; | ||||||||||||||||||
| }) => Promise<string>; | ||||||||||||||||||
| private challenge2fa?: (args: { error: unknown }) => [code: Promise<string>, resolveChallenge: () => void] | undefined; | ||||||||||||||||||
|
|
||||||||||||||||||
| private readonly baseUrl: string; | ||||||||||||||||||
|
|
||||||||||||||||||
|
|
@@ -223,28 +219,35 @@ export class RestClient implements RestClientInterface { | |||||||||||||||||
|
|
||||||||||||||||||
| const error = await clone.json(); | ||||||||||||||||||
|
|
||||||||||||||||||
| if ((isTotpRequiredError(error) || isTotpInvalidError(error)) && hasRequiredTwoFactorMethod(error) && this.twoFactorHandler) { | ||||||||||||||||||
| const method2fa = 'details' in error ? error.details.method : 'password'; | ||||||||||||||||||
|
|
||||||||||||||||||
| const code = await this.twoFactorHandler({ | ||||||||||||||||||
| method: method2fa, | ||||||||||||||||||
| emailOrUsername: error.details.emailOrUsername, | ||||||||||||||||||
| invalidAttempt: isTotpInvalidError(error), | ||||||||||||||||||
| }); | ||||||||||||||||||
|
|
||||||||||||||||||
| return this.send(endpoint, method, { | ||||||||||||||||||
| ...options, | ||||||||||||||||||
| headers: { | ||||||||||||||||||
| ...this.getCredentialsAsHeaders(), | ||||||||||||||||||
| ...this.headers, | ||||||||||||||||||
| ...headers, | ||||||||||||||||||
| 'x-2fa-code': code, | ||||||||||||||||||
| 'x-2fa-method': method2fa, | ||||||||||||||||||
| }, | ||||||||||||||||||
| }); | ||||||||||||||||||
| const method2fa = 'details' in error ? error.details.method : 'password'; | ||||||||||||||||||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. P1: Guard Prompt for AI agents
Suggested change
|
||||||||||||||||||
|
|
||||||||||||||||||
| if (!this.challenge2fa) { | ||||||||||||||||||
| return Promise.reject(error); | ||||||||||||||||||
| } | ||||||||||||||||||
|
|
||||||||||||||||||
| return Promise.reject(response); | ||||||||||||||||||
| const challengeResult = this.challenge2fa({ error }); | ||||||||||||||||||
|
|
||||||||||||||||||
| if (!challengeResult) { | ||||||||||||||||||
| return Promise.reject(error); | ||||||||||||||||||
| } | ||||||||||||||||||
|
|
||||||||||||||||||
| const [code, resolveChallenge] = challengeResult; | ||||||||||||||||||
|
|
||||||||||||||||||
| const resolvedCode = await code; | ||||||||||||||||||
|
|
||||||||||||||||||
| return this.send(endpoint, method, { | ||||||||||||||||||
| ...options, | ||||||||||||||||||
| headers: { | ||||||||||||||||||
| ...this.getCredentialsAsHeaders(), | ||||||||||||||||||
| ...this.headers, | ||||||||||||||||||
| ...headers, | ||||||||||||||||||
| 'x-2fa-code': resolvedCode, | ||||||||||||||||||
| 'x-2fa-method': method2fa, | ||||||||||||||||||
| }, | ||||||||||||||||||
| }).then((response) => { | ||||||||||||||||||
| resolveChallenge(); | ||||||||||||||||||
| return response; | ||||||||||||||||||
| }); | ||||||||||||||||||
| }); | ||||||||||||||||||
| } | ||||||||||||||||||
|
|
||||||||||||||||||
|
|
@@ -297,9 +300,7 @@ export class RestClient implements RestClientInterface { | |||||||||||||||||
| } as RestClientInterface['send']; | ||||||||||||||||||
| } | ||||||||||||||||||
|
|
||||||||||||||||||
| handleTwoFactorChallenge( | ||||||||||||||||||
| cb: (args: { method: 'totp' | 'email' | 'password'; emailOrUsername?: string; invalidAttempt?: boolean }) => Promise<string>, | ||||||||||||||||||
| ): void { | ||||||||||||||||||
| this.twoFactorHandler = cb; | ||||||||||||||||||
| handleTwoFactorChallenge(challenge2fa: (args: { error: unknown }) => [Promise<string>, () => void] | undefined): void { | ||||||||||||||||||
| this.challenge2fa = challenge2fa; | ||||||||||||||||||
| } | ||||||||||||||||||
| } | ||||||||||||||||||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.