Page Menu
Home
Phorge
Search
Configure Global Search
Log In
Files
F33317518
D11761.1768832719.diff
No One
Temporary
Actions
View File
Edit File
Delete File
View Transforms
Subscribe
Flag For Later
Award Token
Size
15 KB
Referenced Files
None
Subscribers
None
D11761.1768832719.diff
View Options
diff --git a/lib/keyserver-conn/keyserver-auth.js b/lib/keyserver-conn/keyserver-auth.js
new file mode 100644
--- /dev/null
+++ b/lib/keyserver-conn/keyserver-auth.js
@@ -0,0 +1,174 @@
+// @flow
+
+import invariant from 'invariant';
+import * as React from 'react';
+
+import { extractKeyserverIDFromID } from './keyserver-call-utils.js';
+import {
+ CANCELLED_ERROR,
+ type CallKeyserverEndpoint,
+} from './keyserver-conn-types.js';
+import {
+ keyserverAuthActionTypes,
+ keyserverAuthRawAction,
+} from '../actions/user-actions.js';
+import { filterThreadIDsInFilterList } from '../reducers/calendar-filters-reducer.js';
+import {
+ cookieSelector,
+ deviceTokenSelector,
+} from '../selectors/keyserver-selectors.js';
+import { IdentityClientContext } from '../shared/identity-client-context.js';
+import type { AuthActionSource } from '../types/account-types.js';
+import { authoritativeKeyserverID } from '../utils/authoritative-keyserver.js';
+import { getConfig } from '../utils/config.js';
+import { useDispatchActionPromise } from '../utils/redux-promise-utils.js';
+import { useSelector } from '../utils/redux-utils.js';
+import sleep from '../utils/sleep.js';
+
+const AUTH_RETRY_DELAY_MS = 60000;
+
+type KeyserverAuthInputs = {
+ +authActionSource: AuthActionSource,
+ +setInProgress: boolean => mixed,
+ +hasBeenCancelled: () => boolean,
+ +doNotRegister: boolean,
+};
+
+type RawKeyserverAuthFunc =
+ KeyserverAuthInputs => CallKeyserverEndpoint => Promise<void>;
+
+function useRawKeyserverAuth(keyserverID: string): RawKeyserverAuthFunc {
+ const navInfo = useSelector(state => state.navInfo);
+ const calendarFilters = useSelector(state => state.calendarFilters);
+ const calendarQuery = React.useMemo(() => {
+ const filters = filterThreadIDsInFilterList(
+ calendarFilters,
+ (threadID: string) => extractKeyserverIDFromID(threadID) === keyserverID,
+ );
+ return {
+ startDate: navInfo.startDate,
+ endDate: navInfo.endDate,
+ filters,
+ };
+ }, [calendarFilters, keyserverID, navInfo.endDate, navInfo.startDate]);
+
+ const cookie = useSelector(cookieSelector(keyserverID));
+
+ const keyserverDeviceToken = useSelector(deviceTokenSelector(keyserverID));
+ // We have an assumption that we should be always connected to the
+ // authoritative keyserver. It is possible that a token which it has is
+ // correct, so we can try to use it. In worst case it is invalid and our
+ // push-handler will try to fix it.
+ const authoritativeKeyserverDeviceToken = useSelector(
+ deviceTokenSelector(authoritativeKeyserverID()),
+ );
+ const deviceToken = keyserverDeviceToken ?? authoritativeKeyserverDeviceToken;
+
+ const dispatchActionPromise = useDispatchActionPromise();
+
+ const identityContext = React.useContext(IdentityClientContext);
+ invariant(identityContext, 'Identity context should be set');
+ const { identityClient, getAuthMetadata } = identityContext;
+
+ const { olmAPI } = getConfig();
+
+ const currentUserInfo = useSelector(state => state.currentUserInfo);
+
+ return React.useCallback(
+ (inputs: KeyserverAuthInputs) =>
+ async (innerCallKeyserverEndpoint: CallKeyserverEndpoint) => {
+ const {
+ authActionSource,
+ setInProgress,
+ hasBeenCancelled,
+ doNotRegister,
+ } = inputs;
+ try {
+ const [keyserverKeys] = await Promise.all([
+ identityClient.getKeyserverKeys(keyserverID),
+ olmAPI.initializeCryptoAccount(),
+ ]);
+
+ if (hasBeenCancelled()) {
+ throw new Error(CANCELLED_ERROR);
+ }
+
+ const [notifsSession, contentSession, { userID, deviceID }] =
+ await Promise.all([
+ olmAPI.notificationsSessionCreator(
+ cookie,
+ keyserverKeys.identityKeysBlob.notificationIdentityPublicKeys,
+ keyserverKeys.notifInitializationInfo,
+ keyserverID,
+ ),
+ olmAPI.contentOutboundSessionCreator(
+ keyserverKeys.identityKeysBlob.primaryIdentityPublicKeys,
+ keyserverKeys.contentInitializationInfo,
+ ),
+ getAuthMetadata(),
+ ]);
+
+ invariant(userID, 'userID should be set');
+ invariant(deviceID, 'deviceID should be set');
+
+ const deviceTokenUpdateInput = deviceToken
+ ? { [keyserverID]: { deviceToken } }
+ : {};
+
+ if (hasBeenCancelled()) {
+ throw new Error(CANCELLED_ERROR);
+ }
+
+ const authPromise = keyserverAuthRawAction(
+ innerCallKeyserverEndpoint,
+ )({
+ userID,
+ deviceID,
+ doNotRegister,
+ calendarQuery,
+ deviceTokenUpdateInput,
+ authActionSource,
+ keyserverData: {
+ [keyserverID]: {
+ initialContentEncryptedMessage:
+ contentSession.encryptedData.message,
+ initialNotificationsEncryptedMessage: notifsSession,
+ },
+ },
+ preRequestUserInfo: currentUserInfo,
+ });
+
+ await dispatchActionPromise(keyserverAuthActionTypes, authPromise);
+ } catch (e) {
+ if (hasBeenCancelled()) {
+ return;
+ }
+ console.log(
+ `Error while authenticating to keyserver with id ${keyserverID}`,
+ e,
+ );
+ throw e;
+ } finally {
+ if (!hasBeenCancelled()) {
+ void (async () => {
+ await sleep(AUTH_RETRY_DELAY_MS);
+ setInProgress(false);
+ })();
+ }
+ }
+ },
+ [
+ calendarQuery,
+ cookie,
+ deviceToken,
+ dispatchActionPromise,
+ getAuthMetadata,
+ identityClient,
+ keyserverID,
+ olmAPI,
+ currentUserInfo,
+ ],
+ );
+}
+
+export { useRawKeyserverAuth };
diff --git a/lib/keyserver-conn/keyserver-connection-handler.js b/lib/keyserver-conn/keyserver-connection-handler.js
--- a/lib/keyserver-conn/keyserver-connection-handler.js
+++ b/lib/keyserver-conn/keyserver-connection-handler.js
@@ -1,36 +1,23 @@
// @flow
-import invariant from 'invariant';
import * as React from 'react';
import { useCallKeyserverEndpointContext } from './call-keyserver-endpoint-provider.react.js';
import type { CallSingleKeyserverEndpoint } from './call-single-keyserver-endpoint.js';
-import { extractKeyserverIDFromID } from './keyserver-call-utils.js';
-import {
- CANCELLED_ERROR,
- type CallKeyserverEndpoint,
-} from './keyserver-conn-types.js';
+import { useRawKeyserverAuth } from './keyserver-auth.js';
+import type { CallKeyserverEndpoint } from './keyserver-conn-types.js';
import { useKeyserverRecoveryLogIn } from './recovery-utils.js';
-import {
- keyserverAuthActionTypes,
- logOutActionTypes,
- keyserverAuthRawAction,
- useLogOut,
-} from '../actions/user-actions.js';
-import { filterThreadIDsInFilterList } from '../reducers/calendar-filters-reducer.js';
+import { logOutActionTypes, useLogOut } from '../actions/user-actions.js';
import {
connectionSelector,
cookieSelector,
- deviceTokenSelector,
} from '../selectors/keyserver-selectors.js';
import { isLoggedInToKeyserver } from '../selectors/user-selectors.js';
import { useInitialNotificationsEncryptedMessage } from '../shared/crypto-utils.js';
-import { IdentityClientContext } from '../shared/identity-client-context.js';
import type { BaseSocketProps } from '../socket/socket.react.js';
import {
logInActionSources,
type RecoveryFromReduxActionSource,
- type AuthActionSource,
} from '../types/account-types.js';
import { authoritativeKeyserverID } from '../utils/authoritative-keyserver.js';
import { getConfig } from '../utils/config.js';
@@ -41,15 +28,12 @@
usingCommServicesAccessToken,
relyingOnAuthoritativeKeyserver,
} from '../utils/services-utils.js';
-import sleep from '../utils/sleep.js';
type Props = {
...BaseSocketProps,
+socketComponent: React.ComponentType<BaseSocketProps>,
};
-const AUTH_RETRY_DELAY_MS = 60000;
-
function KeyserverConnectionHandler(props: Props) {
const { socketComponent: Socket, ...socketProps } = props;
const { keyserverID } = props;
@@ -86,30 +70,6 @@
const dataLoaded = useSelector(state => state.dataLoaded);
- const keyserverDeviceToken = useSelector(deviceTokenSelector(keyserverID));
- // We have an assumption that we should be always connected to Ashoat's
- // keyserver. It is possible that a token which it has is correct, so we can
- // try to use it. In worst case it is invalid and our push-handler will try
- // to fix it.
- const ashoatKeyserverDeviceToken = useSelector(
- deviceTokenSelector(authoritativeKeyserverID()),
- );
- const deviceToken = keyserverDeviceToken ?? ashoatKeyserverDeviceToken;
-
- const navInfo = useSelector(state => state.navInfo);
- const calendarFilters = useSelector(state => state.calendarFilters);
- const calendarQuery = React.useMemo(() => {
- const filters = filterThreadIDsInFilterList(
- calendarFilters,
- (threadID: string) => extractKeyserverIDFromID(threadID) === keyserverID,
- );
- return {
- startDate: navInfo.startDate,
- endDate: navInfo.endDate,
- filters,
- };
- }, [calendarFilters, keyserverID, navInfo.endDate, navInfo.startDate]);
-
React.useEffect(() => {
if (
hasConnectionIssue &&
@@ -120,105 +80,7 @@
}
}, [callLogOut, hasConnectionIssue, dispatchActionPromise, keyserverID]);
- const identityContext = React.useContext(IdentityClientContext);
- invariant(identityContext, 'Identity context should be set');
- const { identityClient, getAuthMetadata } = identityContext;
-
- const currentUserInfo = useSelector(state => state.currentUserInfo);
- const innerPerformAuth = React.useCallback(
- (
- authActionSource: AuthActionSource,
- setInProgress: boolean => mixed,
- hasBeenCancelled: () => boolean,
- doNotRegister: boolean,
- ) =>
- async (innerCallKeyserverEndpoint: CallKeyserverEndpoint) => {
- try {
- const [keyserverKeys] = await Promise.all([
- identityClient.getKeyserverKeys(keyserverID),
- olmAPI.initializeCryptoAccount(),
- ]);
-
- if (hasBeenCancelled()) {
- throw new Error(CANCELLED_ERROR);
- }
-
- const [notifsSession, contentSession, { userID, deviceID }] =
- await Promise.all([
- olmAPI.notificationsSessionCreator(
- cookie,
- keyserverKeys.identityKeysBlob.notificationIdentityPublicKeys,
- keyserverKeys.notifInitializationInfo,
- keyserverID,
- ),
- olmAPI.contentOutboundSessionCreator(
- keyserverKeys.identityKeysBlob.primaryIdentityPublicKeys,
- keyserverKeys.contentInitializationInfo,
- ),
- getAuthMetadata(),
- ]);
-
- invariant(userID, 'userID should be set');
- invariant(deviceID, 'deviceID should be set');
-
- const deviceTokenUpdateInput = deviceToken
- ? { [keyserverID]: { deviceToken } }
- : {};
-
- if (hasBeenCancelled()) {
- throw new Error(CANCELLED_ERROR);
- }
-
- const authPromise = keyserverAuthRawAction(
- innerCallKeyserverEndpoint,
- )({
- userID,
- deviceID,
- doNotRegister,
- calendarQuery,
- deviceTokenUpdateInput,
- authActionSource,
- keyserverData: {
- [keyserverID]: {
- initialContentEncryptedMessage:
- contentSession.encryptedData.message,
- initialNotificationsEncryptedMessage: notifsSession,
- },
- },
- preRequestUserInfo: currentUserInfo,
- });
-
- await dispatchActionPromise(keyserverAuthActionTypes, authPromise);
- } catch (e) {
- if (hasBeenCancelled()) {
- return;
- }
- console.log(
- `Error while authenticating to keyserver with id ${keyserverID}`,
- e,
- );
- throw e;
- } finally {
- if (!hasBeenCancelled()) {
- void (async () => {
- await sleep(AUTH_RETRY_DELAY_MS);
- setInProgress(false);
- })();
- }
- }
- },
- [
- calendarQuery,
- cookie,
- deviceToken,
- dispatchActionPromise,
- getAuthMetadata,
- identityClient,
- keyserverID,
- olmAPI,
- currentUserInfo,
- ],
- );
+ const rawKeyserverAuth = useRawKeyserverAuth(keyserverID);
const [authInProgress, setAuthInProgress] = React.useState(false);
const { callKeyserverEndpoint } = useCallKeyserverEndpointContext();
@@ -234,14 +96,14 @@
const promise = (async () => {
try {
- await innerPerformAuth(
- process.env.BROWSER
+ await rawKeyserverAuth({
+ authActionSource: process.env.BROWSER
? logInActionSources.keyserverAuthFromWeb
: logInActionSources.keyserverAuthFromNative,
- setAuthInProgress,
+ setInProgress: setAuthInProgress,
hasBeenCancelled,
- false,
- )(callKeyserverEndpoint);
+ doNotRegister: false,
+ })(callKeyserverEndpoint);
} catch (e) {
if (
!dataLoaded &&
@@ -255,7 +117,7 @@
return [promise, cancel];
}, [
- innerPerformAuth,
+ rawKeyserverAuth,
callKeyserverEndpoint,
dataLoaded,
keyserverID,
@@ -288,12 +150,12 @@
) => {
if (usingCommServicesAccessToken) {
try {
- await innerPerformAuth(
- recoveryActionSource,
+ await rawKeyserverAuth({
+ authActionSource: recoveryActionSource,
setInProgress,
hasBeenCancelled,
- true,
- )(innerCallKeyserverEndpoint);
+ doNotRegister: true,
+ })(innerCallKeyserverEndpoint);
} catch (e) {
console.log(
`Tried to recover session with keyserver ${keyserverID} but got ` +
@@ -317,7 +179,7 @@
);
},
[
- innerPerformAuth,
+ rawKeyserverAuth,
resolveKeyserverSessionInvalidationUsingNativeCredentials,
dispatchActionPromise,
keyserverID,
@@ -364,13 +226,13 @@
const prevPerformAuth = React.useRef(performAuth);
const hasAccessToken = useSelector(state => !!state.commServicesAccessToken);
+ const hasCurrentUserInfo = useSelector(
+ state => !!state.currentUserInfo && !state.currentUserInfo.anonymous,
+ );
const isUserLoggedInToKeyserver = useSelector(
isLoggedInToKeyserver(keyserverID),
);
- const canInitiateRecovery =
- !!currentUserInfo &&
- !currentUserInfo.anonymous &&
- isUserLoggedInToKeyserver;
+ const canInitiateRecovery = hasCurrentUserInfo && isUserLoggedInToKeyserver;
const cancelPendingRecovery = React.useRef<?() => void>(null);
const prevPerformRecovery = React.useRef(performRecovery);
File Metadata
Details
Attached
Mime Type
text/plain
Expires
Mon, Jan 19, 2:25 PM (16 h, 48 m)
Storage Engine
blob
Storage Format
Raw Data
Storage Handle
5956845
Default Alt Text
D11761.1768832719.diff (15 KB)
Attached To
Mode
D11761: [lib] Extract useRawKeyserverAuth
Attached
Detach File
Event Timeline
Log In to Comment