diff --git a/web/account/account-hooks.js b/web/account/account-hooks.js new file mode 100644 index 000000000..b794a1381 --- /dev/null +++ b/web/account/account-hooks.js @@ -0,0 +1,35 @@ +// @flow + +import * as React from 'react'; + +import type { SignedIdentityKeysBlob } from 'lib/types/crypto-types.js'; + +import { useSelector } from '../redux/redux-utils.js'; +import { getSignedIdentityKeysBlobSelector } from '../selectors/socket-selectors.js'; + +function useSignedIdentityKeysBlob(): ?SignedIdentityKeysBlob { + const getSignedIdentityKeysBlob: ?() => Promise = + useSelector(getSignedIdentityKeysBlobSelector); + + const [signedIdentityKeysBlob, setSignedIdentityKeysBlob] = + React.useState(null); + + React.useEffect(() => { + (async () => { + if ( + getSignedIdentityKeysBlob === null || + getSignedIdentityKeysBlob === undefined + ) { + setSignedIdentityKeysBlob(null); + return; + } + const resolvedSignedIdentityKeysBlob: SignedIdentityKeysBlob = + await getSignedIdentityKeysBlob(); + setSignedIdentityKeysBlob(resolvedSignedIdentityKeysBlob); + })(); + }, [getSignedIdentityKeysBlob]); + + return signedIdentityKeysBlob; +} + +export { useSignedIdentityKeysBlob }; diff --git a/web/account/siwe-login-form.react.js b/web/account/siwe-login-form.react.js index 0b5ada9bd..fdd68e63a 100644 --- a/web/account/siwe-login-form.react.js +++ b/web/account/siwe-login-form.react.js @@ -1,187 +1,186 @@ // @flow import '@rainbow-me/rainbowkit/styles.css'; import invariant from 'invariant'; import * as React from 'react'; import { useAccount, useSigner } from 'wagmi'; import { getSIWENonce, getSIWENonceActionTypes, siweAuth, siweAuthActionTypes, } from 'lib/actions/siwe-actions.js'; import ConnectedWalletInfo from 'lib/components/connected-wallet-info.react.js'; import SWMansionIcon from 'lib/components/SWMansionIcon.react.js'; import { createLoadingStatusSelector } from 'lib/selectors/loading-selectors.js'; import type { LogInStartingPayload } from 'lib/types/account-types.js'; import type { OLMIdentityKeys, SignedIdentityKeysBlob, } from 'lib/types/crypto-types.js'; import { useDispatchActionPromise, useServerCall, } from 'lib/utils/action-utils.js'; import { createSIWEMessage, getSIWEStatementForPublicKey, siweMessageSigningExplanationStatements, } from 'lib/utils/siwe-utils.js'; +import { useSignedIdentityKeysBlob } from './account-hooks.js'; import HeaderSeparator from './header-separator.react.js'; import css from './siwe.css'; import Button from '../components/button.react.js'; import OrBreak from '../components/or-break.react.js'; import LoadingIndicator from '../loading-indicator.react.js'; import { useSelector } from '../redux/redux-utils.js'; import { webLogInExtraInfoSelector } from '../selectors/account-selectors.js'; -import { signedIdentityKeysBlobSelector } from '../selectors/socket-selectors.js'; type SIWELoginFormProps = { +cancelSIWEAuthFlow: () => void, }; const getSIWENonceLoadingStatusSelector = createLoadingStatusSelector( getSIWENonceActionTypes, ); function SIWELoginForm(props: SIWELoginFormProps): React.Node { const { address } = useAccount(); const { data: signer } = useSigner(); const dispatchActionPromise = useDispatchActionPromise(); const getSIWENonceCall = useServerCall(getSIWENonce); const getSIWENonceCallLoadingStatus = useSelector( getSIWENonceLoadingStatusSelector, ); const siweAuthCall = useServerCall(siweAuth); const logInExtraInfo = useSelector(webLogInExtraInfoSelector); const [siweNonce, setSIWENonce] = React.useState(null); const siweNonceShouldBeFetched = !siweNonce && getSIWENonceCallLoadingStatus !== 'loading'; React.useEffect(() => { if (!siweNonceShouldBeFetched) { return; } dispatchActionPromise( getSIWENonceActionTypes, (async () => { const response = await getSIWENonceCall(); setSIWENonce(response); })(), ); }, [dispatchActionPromise, getSIWENonceCall, siweNonceShouldBeFetched]); const primaryIdentityPublicKeys: ?OLMIdentityKeys = useSelector( state => state.cryptoStore.primaryIdentityKeys, ); - const signedIdentityKeysBlob: ?SignedIdentityKeysBlob = useSelector( - signedIdentityKeysBlobSelector, - ); + const signedIdentityKeysBlob: ?SignedIdentityKeysBlob = + useSignedIdentityKeysBlob(); const callSIWEAuthEndpoint = React.useCallback( (message: string, signature: string, extraInfo) => { invariant( signedIdentityKeysBlob, 'signedIdentityKeysBlob must be set in attemptSIWEAuth', ); return siweAuthCall({ message, signature, signedIdentityKeysBlob, ...extraInfo, }); }, [signedIdentityKeysBlob, siweAuthCall], ); const attemptSIWEAuth = React.useCallback( (message: string, signature: string) => { const extraInfo = logInExtraInfo(); dispatchActionPromise( siweAuthActionTypes, callSIWEAuthEndpoint(message, signature, extraInfo), undefined, ({ calendarQuery: extraInfo.calendarQuery }: LogInStartingPayload), ); }, [callSIWEAuthEndpoint, dispatchActionPromise, logInExtraInfo], ); const onSignInButtonClick = React.useCallback(async () => { invariant(signer, 'signer must be present during SIWE attempt'); invariant(siweNonce, 'nonce must be present during SIWE attempt'); invariant( primaryIdentityPublicKeys, 'primaryIdentityPublicKeys must be present during SIWE attempt', ); const statement = getSIWEStatementForPublicKey( primaryIdentityPublicKeys.ed25519, ); const message = createSIWEMessage(address, statement, siweNonce); const signature = await signer.signMessage(message); attemptSIWEAuth(message, signature); }, [address, attemptSIWEAuth, primaryIdentityPublicKeys, signer, siweNonce]); const { cancelSIWEAuthFlow } = props; const backButtonColor = React.useMemo( () => ({ backgroundColor: '#211E2D' }), [], ); const signInButtonColor = React.useMemo( () => ({ backgroundColor: '#6A20E3' }), [], ); if (!siweNonce || !primaryIdentityPublicKeys || !signedIdentityKeysBlob) { return (
); } return (

Sign in with Ethereum

Wallet Connected

{siweMessageSigningExplanationStatements}

By signing up, you agree to our{' '} Terms of Use &{' '} Privacy Policy.

); } export default SIWELoginForm; diff --git a/web/account/traditional-login-form.react.js b/web/account/traditional-login-form.react.js index 9bd4cb340..fb0596167 100644 --- a/web/account/traditional-login-form.react.js +++ b/web/account/traditional-login-form.react.js @@ -1,194 +1,193 @@ // @flow import invariant from 'invariant'; import * as React from 'react'; import { logIn, logInActionTypes } from 'lib/actions/user-actions.js'; import { useModalContext } from 'lib/components/modal-provider.react.js'; import { createLoadingStatusSelector } from 'lib/selectors/loading-selectors.js'; import { oldValidUsernameRegex, validEmailRegex, } from 'lib/shared/account-utils.js'; import type { LogInExtraInfo, LogInStartingPayload, } from 'lib/types/account-types.js'; import { logInActionSources } from 'lib/types/account-types.js'; import type { SignedIdentityKeysBlob } from 'lib/types/crypto-types.js'; import { useDispatchActionPromise, useServerCall, } from 'lib/utils/action-utils.js'; +import { useSignedIdentityKeysBlob } from './account-hooks.js'; import HeaderSeparator from './header-separator.react.js'; import css from './log-in-form.css'; import PasswordInput from './password-input.react.js'; import Button from '../components/button.react.js'; import LoadingIndicator from '../loading-indicator.react.js'; import Input from '../modals/input.react.js'; import { useSelector } from '../redux/redux-utils.js'; import { webLogInExtraInfoSelector } from '../selectors/account-selectors.js'; -import { signedIdentityKeysBlobSelector } from '../selectors/socket-selectors.js'; const loadingStatusSelector = createLoadingStatusSelector(logInActionTypes); function TraditionalLoginForm(): React.Node { const inputDisabled = useSelector(loadingStatusSelector) === 'loading'; const loginExtraInfo = useSelector(webLogInExtraInfoSelector); const callLogIn = useServerCall(logIn); const dispatchActionPromise = useDispatchActionPromise(); const modalContext = useModalContext(); - const signedIdentityKeysBlob: ?SignedIdentityKeysBlob = useSelector( - signedIdentityKeysBlobSelector, - ); + const signedIdentityKeysBlob: ?SignedIdentityKeysBlob = + useSignedIdentityKeysBlob(); const usernameInputRef = React.useRef(); React.useEffect(() => { usernameInputRef.current?.focus(); }, []); const [username, setUsername] = React.useState(''); const onUsernameChange = React.useCallback(e => { invariant(e.target instanceof HTMLInputElement, 'target not input'); setUsername(e.target.value); }, []); const onUsernameBlur = React.useCallback(() => { setUsername(untrimmedUsername => untrimmedUsername.trim()); }, []); const [password, setPassword] = React.useState(''); const onPasswordChange = React.useCallback(e => { invariant(e.target instanceof HTMLInputElement, 'target not input'); setPassword(e.target.value); }, []); const [errorMessage, setErrorMessage] = React.useState(''); const logInAction = React.useCallback( async (extraInfo: LogInExtraInfo) => { try { invariant( signedIdentityKeysBlob, 'signedIdentityKeysBlob must be set in logInAction', ); const result = await callLogIn({ ...extraInfo, username, password, logInActionSource: logInActionSources.logInFromWebForm, signedIdentityKeysBlob, }); modalContext.popModal(); return result; } catch (e) { setUsername(''); setPassword(''); if (e.message === 'invalid_credentials') { setErrorMessage('incorrect username or password'); } else { setErrorMessage('unknown error'); } usernameInputRef.current?.focus(); throw e; } }, [callLogIn, modalContext, password, signedIdentityKeysBlob, username], ); const onSubmit = React.useCallback( (event: SyntheticEvent) => { event.preventDefault(); if (username.search(validEmailRegex) > -1) { setUsername(''); setErrorMessage('usernames only, not emails'); usernameInputRef.current?.focus(); return; } else if (username.search(oldValidUsernameRegex) === -1) { setUsername(''); setErrorMessage('alphanumeric usernames only'); usernameInputRef.current?.focus(); return; } else if (password === '') { setErrorMessage('password is empty'); usernameInputRef.current?.focus(); return; } const extraInfo = loginExtraInfo(); dispatchActionPromise( logInActionTypes, logInAction(extraInfo), undefined, ({ calendarQuery: extraInfo.calendarQuery }: LogInStartingPayload), ); }, [dispatchActionPromise, logInAction, loginExtraInfo, username, password], ); const loginButtonContent = React.useMemo(() => { if (inputDisabled) { return ; } return 'Sign in'; }, [inputDisabled]); const signInButtonColor = React.useMemo( () => ({ backgroundColor: '#6A20E3' }), [], ); return (

Sign in to Comm

Username
Password
{errorMessage}
); } export default TraditionalLoginForm; diff --git a/web/selectors/socket-selectors.js b/web/selectors/socket-selectors.js index 566da2579..87921a6be 100644 --- a/web/selectors/socket-selectors.js +++ b/web/selectors/socket-selectors.js @@ -1,134 +1,126 @@ // @flow import olm from '@matrix-org/olm'; import { createSelector } from 'reselect'; import { getClientResponsesSelector, sessionStateFuncSelector, } from 'lib/selectors/socket-selectors.js'; import { createOpenSocketFunction } from 'lib/shared/socket-utils.js'; import type { OLMIdentityKeys, PickledOLMAccount, SignedIdentityKeysBlob, IdentityKeysBlob, } from 'lib/types/crypto-types.js'; import type { ClientServerRequest, ClientClientResponse, } from 'lib/types/request-types.js'; import type { SessionIdentification, SessionState, } from 'lib/types/session-types.js'; import type { OneTimeKeyGenerator } from 'lib/types/socket-types.js'; +import { initOlm } from '../olm/olm-utils.js'; import type { AppState } from '../redux/redux-setup.js'; const openSocketSelector: (state: AppState) => () => WebSocket = createSelector( (state: AppState) => state.baseHref, createOpenSocketFunction, ); const sessionIdentificationSelector: ( state: AppState, ) => SessionIdentification = createSelector( (state: AppState) => state.sessionID, (sessionID: ?string): SessionIdentification => ({ sessionID }), ); -const signedIdentityKeysBlobSelector: ( +const getSignedIdentityKeysBlobSelector: ( state: AppState, -) => ?SignedIdentityKeysBlob = createSelector( +) => ?() => Promise = createSelector( (state: AppState) => state.cryptoStore.primaryAccount, (state: AppState) => state.cryptoStore.primaryIdentityKeys, (state: AppState) => state.cryptoStore.notificationIdentityKeys, ( primaryAccount: ?PickledOLMAccount, primaryIdentityKeys: ?OLMIdentityKeys, notificationIdentityKeys: ?OLMIdentityKeys, ) => { if (!primaryAccount || !primaryIdentityKeys || !notificationIdentityKeys) { return null; } - const primaryOLMAccount = new olm.Account(); - primaryOLMAccount.unpickle( - primaryAccount.picklingKey, - primaryAccount.pickledAccount, - ); + return async () => { + await initOlm(); + const primaryOLMAccount = new olm.Account(); + primaryOLMAccount.unpickle( + primaryAccount.picklingKey, + primaryAccount.pickledAccount, + ); - const identityKeysBlob: IdentityKeysBlob = { - primaryIdentityPublicKeys: primaryIdentityKeys, - notificationIdentityPublicKeys: notificationIdentityKeys, - }; + const identityKeysBlob: IdentityKeysBlob = { + primaryIdentityPublicKeys: primaryIdentityKeys, + notificationIdentityPublicKeys: notificationIdentityKeys, + }; - const payloadToBeSigned: string = JSON.stringify(identityKeysBlob); - const signedIdentityKeysBlob: SignedIdentityKeysBlob = { - payload: payloadToBeSigned, - signature: primaryOLMAccount.sign(payloadToBeSigned), - }; - - return signedIdentityKeysBlob; - }, -); + const payloadToBeSigned: string = JSON.stringify(identityKeysBlob); + const signedIdentityKeysBlob: SignedIdentityKeysBlob = { + payload: payloadToBeSigned, + signature: primaryOLMAccount.sign(payloadToBeSigned), + }; -const getSignedIdentityKeysBlobSelector: ( - state: AppState, -) => ?() => Promise = createSelector( - signedIdentityKeysBlobSelector, - (signedIdentityKeysBlob: ?SignedIdentityKeysBlob) => { - if (!signedIdentityKeysBlob) { - return null; - } - return async () => signedIdentityKeysBlob; + return signedIdentityKeysBlob; + }; }, ); const webGetClientResponsesSelector: ( state: AppState, ) => ( serverRequests: $ReadOnlyArray, ) => Promise<$ReadOnlyArray> = createSelector( getClientResponsesSelector, getSignedIdentityKeysBlobSelector, (state: AppState) => state.navInfo.tab === 'calendar', ( getClientResponsesFunc: ( calendarActive: boolean, oneTimeKeyGenerator: ?OneTimeKeyGenerator, getSignedIdentityKeysBlob: ?() => Promise, serverRequests: $ReadOnlyArray, ) => Promise<$ReadOnlyArray>, getSignedIdentityKeysBlob: ?() => Promise, calendarActive: boolean, ) => (serverRequests: $ReadOnlyArray) => getClientResponsesFunc( calendarActive, null, getSignedIdentityKeysBlob, serverRequests, ), ); const webSessionStateFuncSelector: (state: AppState) => () => SessionState = createSelector( sessionStateFuncSelector, (state: AppState) => state.navInfo.tab === 'calendar', ( sessionStateFunc: (calendarActive: boolean) => SessionState, calendarActive: boolean, ) => () => sessionStateFunc(calendarActive), ); export { openSocketSelector, sessionIdentificationSelector, - signedIdentityKeysBlobSelector, + getSignedIdentityKeysBlobSelector, webGetClientResponsesSelector, webSessionStateFuncSelector, };