Skip to content

armgit / ente

Public Imported from GitHub
0

πŸ’š End-to-end encrypted cloud for everything.

credential page complete

Abhinave463baac2bfb
diff --git a/apps/photos/src/pages/credentials/index.tsx b/apps/photos/src/pages/credentials/index.tsx
index 66e72dc2b4..2155c5cc12 100644
--- a/apps/photos/src/pages/credentials/index.tsx
+++ b/apps/photos/src/pages/credentials/index.tsx
@@ -1,264 +1,17 @@
-import React, { useContext, useEffect, useState } from 'react';
-
-import { t } from 'i18next';
-
-import {
- clearData,
- getData,
- LS_KEYS,
- setData,
-} from 'utils/storage/localStorage';
+import CredentialPage from '@ente/accounts/pages/credentials';
import { useRouter } from 'next/router';
-import { PAGES } from 'constants/pages';
-import {
- SESSION_KEYS,
- getKey,
- removeKey,
- setKey,
-} from 'utils/storage/sessionStorage';
-import {
- decryptAndStoreToken,
- generateAndSaveIntermediateKeyAttributes,
- generateLoginSubKey,
- generateSRPSetupAttributes,
- saveKeyInSessionStore,
-} from 'utils/crypto';
-import {
- logoutUser,
- configureSRP,
- loginViaSRP,
- getSRPAttributes,
-} from 'services/userService';
-import { isFirstLogin, setIsFirstLogin } from 'utils/storage';
import { AppContext } from 'pages/_app';
-import { logError } from 'utils/sentry';
-import { KeyAttributes, SRPAttributes, User } from 'types/user';
-import FormPaper from 'components/Form/FormPaper';
-import FormPaperTitle from 'components/Form/FormPaper/Title';
-import FormPaperFooter from 'components/Form/FormPaper/Footer';
-import LinkButton from 'components/pages/gallery/LinkButton';
-import isElectron from 'is-electron';
-import safeStorageService from 'services/electron/safeStorage';
-import { VerticallyCentered } from 'components/Container';
-import EnteSpinner from 'components/EnteSpinner';
-import VerifyMasterPasswordForm, {
- VerifyMasterPasswordFormProps,
-} from 'components/VerifyMasterPasswordForm';
-import { APPS, getAppName } from 'constants/apps';
-import { addLocalLog } from 'utils/logging';
-import ComlinkCryptoWorker from 'utils/comlink/ComlinkCryptoWorker';
-import { B64EncryptionResult } from 'types/crypto';
-import { CustomError } from 'utils/error';
-import InMemoryStore, { MS_KEYS } from 'services/InMemoryStore';
+import { useContext } from 'react';
+import { APPS } from '@ente/shared/apps/constants';
-export default function Credentials() {
- const router = useRouter();
- const [srpAttributes, setSrpAttributes] = useState<SRPAttributes>();
- const [keyAttributes, setKeyAttributes] = useState<KeyAttributes>();
+export default function Credential() {
const appContext = useContext(AppContext);
- const [user, setUser] = useState<User>();
-
- useEffect(() => {
- router.prefetch(PAGES.GALLERY);
- const main = async () => {
- const user: User = getData(LS_KEYS.USER);
- if (!user?.email) {
- router.push(PAGES.ROOT);
- return;
- }
- setUser(user);
- let key = getKey(SESSION_KEYS.ENCRYPTION_KEY);
- if (!key && isElectron()) {
- key = await safeStorageService.getEncryptionKey();
- if (key) {
- await saveKeyInSessionStore(
- SESSION_KEYS.ENCRYPTION_KEY,
- key,
- true
- );
- }
- }
- if (key) {
- router.push(PAGES.GALLERY);
- return;
- }
- const kekEncryptedAttributes: B64EncryptionResult = getKey(
- SESSION_KEYS.KEY_ENCRYPTION_KEY
- );
- const keyAttributes: KeyAttributes = getData(
- LS_KEYS.KEY_ATTRIBUTES
- );
- if (kekEncryptedAttributes && keyAttributes) {
- removeKey(SESSION_KEYS.KEY_ENCRYPTION_KEY);
- const cryptoWorker = await ComlinkCryptoWorker.getInstance();
- const kek = await cryptoWorker.decryptB64(
- kekEncryptedAttributes.encryptedData,
- kekEncryptedAttributes.nonce,
- kekEncryptedAttributes.key
- );
- const key = await cryptoWorker.decryptB64(
- keyAttributes.encryptedKey,
- keyAttributes.keyDecryptionNonce,
- kek
- );
- useMasterPassword(key, kek, keyAttributes);
- return;
- }
- if (keyAttributes) {
- if (
- (!user?.token && !user?.encryptedToken) ||
- (keyAttributes && !keyAttributes.memLimit)
- ) {
- clearData();
- router.push(PAGES.ROOT);
- return;
- }
- setKeyAttributes(keyAttributes);
- return;
- }
-
- const srpAttributes: SRPAttributes = getData(
- LS_KEYS.SRP_ATTRIBUTES
- );
- if (srpAttributes) {
- setSrpAttributes(srpAttributes);
- } else {
- router.push(PAGES.ROOT);
- }
- };
- main();
- appContext.showNavBar(true);
- }, []);
-
- const getKeyAttributes: VerifyMasterPasswordFormProps['getKeyAttributes'] =
- async (kek: string) => {
- try {
- const cryptoWorker = await ComlinkCryptoWorker.getInstance();
- const {
- keyAttributes,
- encryptedToken,
- token,
- id,
- twoFactorSessionID,
- } = await loginViaSRP(srpAttributes, kek);
- if (twoFactorSessionID) {
- const sessionKeyAttributes =
- await cryptoWorker.generateKeyAndEncryptToB64(kek);
- setKey(
- SESSION_KEYS.KEY_ENCRYPTION_KEY,
- sessionKeyAttributes
- );
- const user = getData(LS_KEYS.USER);
- setData(LS_KEYS.USER, {
- ...user,
- twoFactorSessionID,
- isTwoFactorEnabled: true,
- });
- setIsFirstLogin(true);
- router.push(PAGES.TWO_FACTOR_VERIFY);
- throw Error(CustomError.TWO_FACTOR_ENABLED);
- } else {
- const user = getData(LS_KEYS.USER);
- setData(LS_KEYS.USER, {
- ...user,
- token,
- encryptedToken,
- id,
- isTwoFactorEnabled: false,
- });
- setData(LS_KEYS.KEY_ATTRIBUTES, keyAttributes);
- return keyAttributes;
- }
- } catch (e) {
- if (e.message !== CustomError.TWO_FACTOR_ENABLED) {
- logError(e, 'getKeyAttributes failed');
- }
- throw e;
- }
- };
-
- const useMasterPassword: VerifyMasterPasswordFormProps['callback'] = async (
- key,
- kek,
- keyAttributes,
- passphrase
- ) => {
- try {
- if (isFirstLogin() && passphrase) {
- await generateAndSaveIntermediateKeyAttributes(
- passphrase,
- keyAttributes,
- key
- );
- }
- await saveKeyInSessionStore(SESSION_KEYS.ENCRYPTION_KEY, key);
- await decryptAndStoreToken(keyAttributes, key);
- try {
- let srpAttributes: SRPAttributes = getData(
- LS_KEYS.SRP_ATTRIBUTES
- );
- if (!srpAttributes) {
- srpAttributes = await getSRPAttributes(user.email);
- if (srpAttributes) {
- setData(LS_KEYS.SRP_ATTRIBUTES, srpAttributes);
- }
- }
- addLocalLog(() => `userSRPSetupPending ${!srpAttributes}`);
- if (!srpAttributes) {
- const loginSubKey = await generateLoginSubKey(kek);
- const srpSetupAttributes = await generateSRPSetupAttributes(
- loginSubKey
- );
- await configureSRP(srpSetupAttributes);
- }
- } catch (e) {
- logError(e, 'migrate to srp failed');
- }
- const redirectURL = InMemoryStore.get(MS_KEYS.REDIRECT_URL);
- InMemoryStore.delete(MS_KEYS.REDIRECT_URL);
- const appName = getAppName();
- if (appName === APPS.AUTH) {
- router.push(PAGES.AUTH);
- } else {
- router.push(redirectURL ?? PAGES.GALLERY);
- }
- } catch (e) {
- logError(e, 'useMasterPassword failed');
- }
- };
-
- const redirectToRecoverPage = () => router.push(PAGES.RECOVER);
-
- if (!keyAttributes && !srpAttributes) {
- return (
- <VerticallyCentered>
- <EnteSpinner />
- </VerticallyCentered>
- );
- }
-
+ const router = useRouter();
return (
- <VerticallyCentered>
- <FormPaper style={{ minWidth: '320px' }}>
- <FormPaperTitle>{t('PASSWORD')}</FormPaperTitle>
-
- <VerifyMasterPasswordForm
- buttonText={t('VERIFY_PASSPHRASE')}
- callback={useMasterPassword}
- user={user}
- keyAttributes={keyAttributes}
- getKeyAttributes={getKeyAttributes}
- srpAttributes={srpAttributes}
- />
- <FormPaperFooter style={{ justifyContent: 'space-between' }}>
- <LinkButton onClick={redirectToRecoverPage}>
- {t('FORGOT_PASSWORD')}
- </LinkButton>
- <LinkButton onClick={logoutUser}>
- {t('CHANGE_EMAIL')}
- </LinkButton>
- </FormPaperFooter>
- </FormPaper>
- </VerticallyCentered>
+ <CredentialPage
+ appContext={appContext}
+ router={router}
+ appName={APPS.PHOTOS}
+ />
);
}
diff --git a/packages/accounts/api/srp.ts b/packages/accounts/api/srp.ts
index c9c2f2c0d1..77f7ea57eb 100644
--- a/packages/accounts/api/srp.ts
+++ b/packages/accounts/api/srp.ts
@@ -4,12 +4,16 @@ import { getEndpoint } from '@ente/shared/network/api';
import {
CompleteSRPSetupRequest,
CompleteSRPSetupResponse,
+ CreateSRPSessionResponse,
GetSRPAttributesResponse,
SRPAttributes,
+ SRPVerificationResponse,
SetupSRPRequest,
SetupSRPResponse,
} from '../types/srp';
import { getToken } from '@ente/shared/storage/localStorage/helpers';
+import { ApiError, CustomError } from '@ente/shared/error';
+import { HttpStatusCode } from 'axios';
const ENDPOINT = getEndpoint();
@@ -67,3 +71,48 @@ export const completeSRPSetup = async (
// throw e;
// }
};
+
+export const createSRPSession = async (srpUserID: string, srpA: string) => {
+ // try {
+ const resp = await HTTPService.post(
+ `${ENDPOINT}/users/srp/create-session`,
+ {
+ srpUserID,
+ srpA,
+ }
+ );
+ return resp.data as CreateSRPSessionResponse;
+ // } catch (e) {
+ // logError(e, 'createSRPSession failed');
+ // throw e;
+ // }
+};
+
+export const verifySRPSession = async (
+ sessionID: string,
+ srpUserID: string,
+ srpM1: string
+) => {
+ try {
+ const resp = await HTTPService.post(
+ `${ENDPOINT}/users/srp/verify-session`,
+ {
+ sessionID,
+ srpUserID,
+ srpM1,
+ },
+ undefined
+ );
+ return resp.data as SRPVerificationResponse;
+ } catch (e) {
+ // logError(e, 'verifySRPSession failed');
+ if (
+ e instanceof ApiError &&
+ e.httpStatusCode === HttpStatusCode.Forbidden
+ ) {
+ throw Error(CustomError.INCORRECT_PASSWORD);
+ } else {
+ throw e;
+ }
+ }
+};
diff --git a/packages/accounts/constants/pages.ts b/packages/accounts/constants/pages.ts
index f4bc3614c9..0853a915b7 100644
--- a/packages/accounts/constants/pages.ts
+++ b/packages/accounts/constants/pages.ts
@@ -11,4 +11,7 @@ export enum PAGES {
TWO_FACTOR_VERIFY = '/two-factor/verify',
TWO_FACTOR_RECOVER = '/two-factor/recover',
VERIFY = '/verify',
+ GALLERY = '/gallery',
+ AUTH = '/auth',
+ SHARED_ALBUMS = '/shared-albums',
}
diff --git a/packages/accounts/pages/credentials.tsx b/packages/accounts/pages/credentials.tsx
new file mode 100644
index 0000000000..22c646cad5
--- /dev/null
+++ b/packages/accounts/pages/credentials.tsx
@@ -0,0 +1,282 @@
+import { useEffect, useState } from 'react';
+
+import { t } from 'i18next';
+
+import {
+ clearData,
+ getData,
+ LS_KEYS,
+ setData,
+} from '@ente/shared/storage/localStorage';
+import { PAGES } from '../constants/pages';
+import {
+ SESSION_KEYS,
+ getKey,
+ removeKey,
+ setKey,
+} from '@ente/shared/storage/sessionStorage';
+import {
+ decryptAndStoreToken,
+ generateAndSaveIntermediateKeyAttributes,
+ generateLoginSubKey,
+ saveKeyInSessionStore,
+} from '@ente/shared/crypto/helpers';
+import { generateSRPSetupAttributes } from '../services/srp';
+import { logoutUser } from '../services/user';
+
+import { configureSRP, loginViaSRP } from '../services/srp';
+import { getSRPAttributes } from '../api/srp';
+import { SRPAttributes } from '../types/srp';
+
+import {
+ isFirstLogin,
+ setIsFirstLogin,
+} from '@ente/shared/storage/localStorage/helpers';
+import { KeyAttributes, User } from '@ente/shared/user/types';
+import FormPaper from '@ente/shared/components/Form/FormPaper';
+import FormPaperTitle from '@ente/shared/components/Form/FormPaper/Title';
+import FormPaperFooter from '@ente/shared/components/Form/FormPaper/Footer';
+import LinkButton from '@ente/shared/components/LinkButton';
+// import isElectron from 'is-electron';
+// import safeStorageService from 'services/electron/safeStorage';
+import { VerticallyCentered } from '@ente/shared/components/Container';
+import EnteSpinner from '@ente/shared/components/EnteSpinner';
+import VerifyMasterPasswordForm, {
+ VerifyMasterPasswordFormProps,
+} from '@ente/shared/components/VerifyMasterPasswordForm';
+// import { APPS, getAppName } from '@ente/shared/apps';
+// import { addLocalLog } from 'utils/logging';
+import ComlinkCryptoWorker from '@ente/shared/crypto';
+import { B64EncryptionResult } from '@ente/shared/crypto/types';
+import { CustomError } from '@ente/shared/error';
+import InMemoryStore, { MS_KEYS } from '@ente/shared/storage/InMemoryStore';
+import { PageProps } from '@ente/shared/apps/types';
+import { APPS } from '@ente/shared/apps/constants';
+
+export default function Credentials({
+ appContext,
+ router,
+ appName,
+}: PageProps) {
+ const [srpAttributes, setSrpAttributes] = useState<SRPAttributes>();
+ const [keyAttributes, setKeyAttributes] = useState<KeyAttributes>();
+ const [user, setUser] = useState<User>();
+
+ useEffect(() => {
+ if (appName === APPS.AUTH) {
+ router.prefetch(PAGES.AUTH);
+ } else if (appName === APPS.PHOTOS) {
+ router.prefetch(PAGES.GALLERY);
+ } else {
+ router.prefetch(PAGES.SHARED_ALBUMS);
+ }
+ const main = async () => {
+ const user: User = getData(LS_KEYS.USER);
+ if (!user?.email) {
+ router.push(PAGES.ROOT);
+ return;
+ }
+ setUser(user);
+ const key = getKey(SESSION_KEYS.ENCRYPTION_KEY);
+ // if (!key && isElectron()) {
+ // key = await safeStorageService.getEncryptionKey();
+ // if (key) {
+ // await saveKeyInSessionStore(
+ // SESSION_KEYS.ENCRYPTION_KEY,
+ // key,
+ // true
+ // );
+ // }
+ // }
+ if (key) {
+ router.push(PAGES.GALLERY);
+ return;
+ }
+ const kekEncryptedAttributes: B64EncryptionResult = getKey(
+ SESSION_KEYS.KEY_ENCRYPTION_KEY
+ );
+ const keyAttributes: KeyAttributes = getData(
+ LS_KEYS.KEY_ATTRIBUTES
+ );
+ if (kekEncryptedAttributes && keyAttributes) {
+ removeKey(SESSION_KEYS.KEY_ENCRYPTION_KEY);
+ const cryptoWorker = await ComlinkCryptoWorker.getInstance();
+ const kek = await cryptoWorker.decryptB64(
+ kekEncryptedAttributes.encryptedData,
+ kekEncryptedAttributes.nonce,
+ kekEncryptedAttributes.key
+ );
+ const key = await cryptoWorker.decryptB64(
+ keyAttributes.encryptedKey,
+ keyAttributes.keyDecryptionNonce,
+ kek
+ );
+ useMasterPassword(key, kek, keyAttributes);
+ return;
+ }
+ if (keyAttributes) {
+ if (
+ (!user?.token && !user?.encryptedToken) ||
+ (keyAttributes && !keyAttributes.memLimit)
+ ) {
+ clearData();
+ router.push(PAGES.ROOT);
+ return;
+ }
+ setKeyAttributes(keyAttributes);
+ return;
+ }
+
+ const srpAttributes: SRPAttributes = getData(
+ LS_KEYS.SRP_ATTRIBUTES
+ );
+ if (srpAttributes) {
+ setSrpAttributes(srpAttributes);
+ } else {
+ router.push(PAGES.ROOT);
+ }
+ };
+ main();
+ appContext.showNavBar(true);
+ }, []);
+
+ const getKeyAttributes: VerifyMasterPasswordFormProps['getKeyAttributes'] =
+ async (kek: string) => {
+ try {
+ if (!srpAttributes) {
+ throw Error('SRP attributes are missing');
+ }
+ const cryptoWorker = await ComlinkCryptoWorker.getInstance();
+ const response = await loginViaSRP(srpAttributes, kek);
+ if (response.twoFactorSessionID) {
+ const { twoFactorSessionID } = response;
+ const sessionKeyAttributes =
+ await cryptoWorker.generateKeyAndEncryptToB64(kek);
+ setKey(
+ SESSION_KEYS.KEY_ENCRYPTION_KEY,
+ sessionKeyAttributes
+ );
+ const user = getData(LS_KEYS.USER);
+ setData(LS_KEYS.USER, {
+ ...user,
+ twoFactorSessionID,
+ isTwoFactorEnabled: true,
+ });
+ setIsFirstLogin(true);
+ router.push(PAGES.TWO_FACTOR_VERIFY);
+ throw Error(CustomError.TWO_FACTOR_ENABLED);
+ } else {
+ const { token, encryptedToken, id, keyAttributes } =
+ response;
+ const user = getData(LS_KEYS.USER);
+ setData(LS_KEYS.USER, {
+ ...user,
+ token,
+ encryptedToken,
+ id,
+ isTwoFactorEnabled: false,
+ });
+ if (keyAttributes) {
+ setData(LS_KEYS.KEY_ATTRIBUTES, keyAttributes);
+ }
+ return keyAttributes;
+ }
+ } catch (e) {
+ if (
+ e instanceof Error &&
+ e.message !== CustomError.TWO_FACTOR_ENABLED
+ ) {
+ // logError(e, 'getKeyAttributes failed');
+ }
+ throw e;
+ }
+ };
+
+ const useMasterPassword: VerifyMasterPasswordFormProps['callback'] = async (
+ key,
+ kek,
+ keyAttributes,
+ passphrase
+ ) => {
+ try {
+ if (isFirstLogin() && passphrase) {
+ await generateAndSaveIntermediateKeyAttributes(
+ passphrase,
+ keyAttributes,
+ key
+ );
+ }
+ await saveKeyInSessionStore(SESSION_KEYS.ENCRYPTION_KEY, key);
+ await decryptAndStoreToken(keyAttributes, key);
+ try {
+ let srpAttributes: SRPAttributes = getData(
+ LS_KEYS.SRP_ATTRIBUTES
+ );
+ if (!srpAttributes) {
+ srpAttributes = await getSRPAttributes(user.email);
+ if (srpAttributes) {
+ setData(LS_KEYS.SRP_ATTRIBUTES, srpAttributes);
+ }
+ }
+ // addLocalLog(() => `userSRPSetupPending ${!srpAttributes}`);
+ if (!srpAttributes) {
+ const loginSubKey = await generateLoginSubKey(kek);
+ const srpSetupAttributes = await generateSRPSetupAttributes(
+ loginSubKey
+ );
+ await configureSRP(srpSetupAttributes);
+ }
+ } catch (e) {
+ // logError(e, 'migrate to srp failed');
+ }
+ const redirectURL = InMemoryStore.get(MS_KEYS.REDIRECT_URL);
+ InMemoryStore.delete(MS_KEYS.REDIRECT_URL);
+ if (appName === APPS.AUTH) {
+ router.push(PAGES.AUTH);
+ } else {
+ router.push(redirectURL ?? PAGES.GALLERY);
+ }
+ } catch (e) {
+ // logError(e, 'useMasterPassword failed');
+ }
+ };
+
+ const redirectToRecoverPage = () => router.push(PAGES.RECOVER);
+
+ if (!keyAttributes && !srpAttributes) {
+ return (
+ <VerticallyCentered>
+ <EnteSpinner />
+ </VerticallyCentered>
+ );
+ }
+
+ const logoutHandler = () => {
+ logoutUser(router);
+ };
+
+ return (
+ <VerticallyCentered>
+ <FormPaper style={{ minWidth: '320px' }}>
+ <FormPaperTitle>{t('PASSWORD')}</FormPaperTitle>
+
+ <VerifyMasterPasswordForm
+ buttonText={t('VERIFY_PASSPHRASE')}
+ callback={useMasterPassword}
+ user={user}
+ keyAttributes={keyAttributes}
+ getKeyAttributes={getKeyAttributes}
+ srpAttributes={srpAttributes}
+ />
+ <FormPaperFooter style={{ justifyContent: 'space-between' }}>
+ <LinkButton onClick={redirectToRecoverPage}>
+ {t('FORGOT_PASSWORD')}
+ </LinkButton>
+ <LinkButton onClick={logoutHandler}>
+ {t('CHANGE_EMAIL')}
+ </LinkButton>
+ </FormPaperFooter>
+ </FormPaper>
+ </VerticallyCentered>
+ );
+}
diff --git a/packages/accounts/services/srp.ts b/packages/accounts/services/srp.ts
index 7d81209277..9478ac638e 100644
--- a/packages/accounts/services/srp.ts
+++ b/packages/accounts/services/srp.ts
@@ -1,10 +1,19 @@
import { SRP, SrpClient } from 'fast-srp-hap';
-import { SRPSetupAttributes } from '../types/srp';
+import { SRPAttributes, SRPSetupAttributes } from '../types/srp';
import InMemoryStore, { MS_KEYS } from '@ente/shared/storage/InMemoryStore';
import { convertBase64ToBuffer, convertBufferToBase64 } from '../utils';
-import { completeSRPSetup, startSRPSetup } from '../api/srp';
+import {
+ completeSRPSetup,
+ createSRPSession,
+ startSRPSetup,
+ verifySRPSession,
+} from '../api/srp';
+import { v4 as uuidv4 } from 'uuid';
+import ComlinkCryptoWorker from '@ente/shared/crypto';
+import { generateLoginSubKey } from '@ente/shared/crypto/helpers';
+import { UserVerificationResponse } from '@ente/shared/user/types';
const SRP_PARAMS = SRP.params['4096'];
@@ -57,6 +66,83 @@ export const configureSRP = async ({
}
};
+export const generateSRPSetupAttributes = async (
+ loginSubKey: string
+): Promise<SRPSetupAttributes> => {
+ const cryptoWorker = await ComlinkCryptoWorker.getInstance();
+
+ const srpSalt = await cryptoWorker.generateSaltToDeriveKey();
+
+ const srpUserID = uuidv4();
+
+ const srpVerifierBuffer = SRP.computeVerifier(
+ SRP_PARAMS,
+ convertBase64ToBuffer(srpSalt),
+ Buffer.from(srpUserID),
+ convertBase64ToBuffer(loginSubKey)
+ );
+
+ const srpVerifier = convertBufferToBase64(srpVerifierBuffer);
+
+ // addLocalLog(
+ // () => `SRP setup attributes generated',
+ // ${JSON.stringify({
+ // srpSalt,
+ // srpUserID,
+ // srpVerifier,
+ // loginSubKey,
+ // })}`
+ // );
+
+ return {
+ srpUserID,
+ srpSalt,
+ srpVerifier,
+ loginSubKey,
+ };
+};
+
+export const loginViaSRP = async (
+ srpAttributes: SRPAttributes,
+ kek: string
+): Promise<UserVerificationResponse> => {
+ // try {
+ const loginSubKey = await generateLoginSubKey(kek);
+ const srpClient = await generateSRPClient(
+ srpAttributes.srpSalt,
+ srpAttributes.srpUserID,
+ loginSubKey
+ );
+ const srpA = srpClient.computeA();
+ const { srpB, sessionID } = await createSRPSession(
+ srpAttributes.srpUserID,
+ convertBufferToBase64(srpA)
+ );
+ srpClient.setB(convertBase64ToBuffer(srpB));
+
+ const m1 = srpClient.computeM1();
+ // addLocalLog(() => `srp m1: ${convertBufferToBase64(m1)}`);
+ const { srpM2, ...rest } = await verifySRPSession(
+ sessionID,
+ srpAttributes.srpUserID,
+ convertBufferToBase64(m1)
+ );
+ // addLocalLog(() => `srp verify session successful,srpM2: ${srpM2}`);
+
+ srpClient.checkM2(convertBase64ToBuffer(srpM2));
+
+ // addLocalLog(() => `srp server verify successful`);
+ return rest;
+ // } catch (e) {
+ // logError(e, 'srp verify failed');
+ // throw e;
+ // }
+};
+
+// ====================
+// HELPERS
+// ====================
+
const generateSRPClient = async (
srpSalt: string,
srpUserID: string,
diff --git a/packages/accounts/tsconfig.json b/packages/accounts/tsconfig.json
index 44e758e2b2..0d15c40108 100644
--- a/packages/accounts/tsconfig.json
+++ b/packages/accounts/tsconfig.json
@@ -1,5 +1,17 @@
{
"extends": "../../tsconfig.base.json",
+ "compilerOptions": {
+ "downlevelIteration": true,
+ "jsx": "preserve",
+ "jsxImportSource": "@emotion/react",
+ "lib": ["dom", "dom.iterable", "esnext", "webworker"],
+ "noImplicitAny": false,
+ "noUnusedLocals": false,
+ "noUnusedParameters": false,
+ "strictNullChecks": false,
+ "target": "es5",
+ "useUnknownInCatchVariables": false
+ },
"include": [
"**/*.ts",
"**/*.tsx",
diff --git a/packages/accounts/types/srp.ts b/packages/accounts/types/srp.ts
index b30d61e50a..f913c54f1a 100644
--- a/packages/accounts/types/srp.ts
+++ b/packages/accounts/types/srp.ts
@@ -1,3 +1,5 @@
+import { UserVerificationResponse } from '@ente/shared/user/types';
+
export interface SRPAttributes {
srpUserID: string;
srpSalt: string;
@@ -39,3 +41,12 @@ export interface CompleteSRPSetupResponse {
setupID: string;
srpM2: string;
}
+
+export interface CreateSRPSessionResponse {
+ sessionID: string;
+ srpB: string;
+}
+
+export interface SRPVerificationResponse extends UserVerificationResponse {
+ srpM2: string;
+}
diff --git a/packages/shared/apps/types.ts b/packages/shared/apps/types.ts
index 18854d0119..87ac58fac8 100644
--- a/packages/shared/apps/types.ts
+++ b/packages/shared/apps/types.ts
@@ -1,9 +1,10 @@
import { NextRouter } from 'next/router';
+import { APPS } from './constants';
export interface PageProps {
appContext: {
showNavBar: (show: boolean) => void;
};
router: NextRouter;
- appName: string;
+ appName: APPS;
}
diff --git a/packages/shared/components/VerifyMasterPasswordForm.tsx b/packages/shared/components/VerifyMasterPasswordForm.tsx
new file mode 100644
index 0000000000..6d00158ef2
--- /dev/null
+++ b/packages/shared/components/VerifyMasterPasswordForm.tsx
@@ -0,0 +1,122 @@
+import SingleInputForm, {
+ SingleInputFormProps,
+} from '../components/SingleInputForm';
+// import { logError } from 'utils/sentry';
+import { CustomError } from '../error';
+
+import { ButtonProps, Input } from '@mui/material';
+import { KeyAttributes, User } from '../user/types';
+import { SRPAttributes } from '@ente/accounts/types/srp';
+import ComlinkCryptoWorker from '../crypto';
+import { t } from 'i18next';
+
+export interface VerifyMasterPasswordFormProps {
+ user: User;
+ keyAttributes: KeyAttributes;
+ callback: (
+ key: string,
+ kek: string,
+ keyAttributes: KeyAttributes,
+ passphrase?: string
+ ) => void;
+ buttonText: string;
+ submitButtonProps?: ButtonProps;
+ getKeyAttributes?: (kek: string) => Promise<KeyAttributes>;
+ srpAttributes?: SRPAttributes;
+}
+
+export default function VerifyMasterPasswordForm({
+ user,
+ keyAttributes,
+ srpAttributes,
+ callback,
+ buttonText,
+ submitButtonProps,
+ getKeyAttributes,
+}: VerifyMasterPasswordFormProps) {
+ const verifyPassphrase: SingleInputFormProps['callback'] = async (
+ passphrase,
+ setFieldError
+ ) => {
+ try {
+ const cryptoWorker = await ComlinkCryptoWorker.getInstance();
+ let kek: string;
+ try {
+ if (srpAttributes) {
+ kek = await cryptoWorker.deriveKey(
+ passphrase,
+ srpAttributes.kekSalt,
+ srpAttributes.opsLimit,
+ srpAttributes.memLimit
+ );
+ } else {
+ kek = await cryptoWorker.deriveKey(
+ passphrase,
+ keyAttributes.kekSalt,
+ keyAttributes.opsLimit,
+ keyAttributes.memLimit
+ );
+ }
+ } catch (e) {
+ // logError(e, 'failed to derive key');
+ throw Error(CustomError.WEAK_DEVICE);
+ }
+ if (!keyAttributes && typeof getKeyAttributes === 'function') {
+ keyAttributes = await getKeyAttributes(kek);
+ }
+ if (!keyAttributes) {
+ throw Error("couldn't get key attributes");
+ }
+ try {
+ const key = await cryptoWorker.decryptB64(
+ keyAttributes.encryptedKey,
+ keyAttributes.keyDecryptionNonce,
+ kek
+ );
+ callback(key, kek, keyAttributes, passphrase);
+ } catch (e) {
+ // logError(e, 'user entered a wrong password');
+ throw Error(CustomError.INCORRECT_PASSWORD);
+ }
+ } catch (e) {
+ if (e instanceof Error) {
+ if (e.message === CustomError.TWO_FACTOR_ENABLED) {
+ // two factor enabled, user has been redirected to two factor page
+ return;
+ }
+ // logError(e, 'failed to verify passphrase');
+ switch (e.message) {
+ case CustomError.WEAK_DEVICE:
+ setFieldError(t('WEAK_DEVICE'));
+ break;
+ case CustomError.INCORRECT_PASSWORD:
+ setFieldError(t('INCORRECT_PASSPHRASE'));
+ break;
+ default:
+ setFieldError(`${t('UNKNOWN_ERROR')} ${e.message}`);
+ }
+ }
+ }
+ };
+
+ return (
+ <SingleInputForm
+ callback={verifyPassphrase}
+ placeholder={t('RETURN_PASSPHRASE_HINT')}
+ buttonText={buttonText}
+ submitButtonProps={submitButtonProps}
+ hiddenPreInput={
+ <Input
+ id="email"
+ name="email"
+ autoComplete="username"
+ type="email"
+ hidden
+ value={user?.email}
+ />
+ }
+ autoComplete={'current-password'}
+ fieldType="password"
+ />
+ );
+}
diff --git a/packages/shared/crypto/constants.ts b/packages/shared/crypto/constants.ts
new file mode 100644
index 0000000000..e39e675030
--- /dev/null
+++ b/packages/shared/crypto/constants.ts
@@ -0,0 +1,7 @@
+export const ENCRYPTION_CHUNK_SIZE = 4 * 1024 * 1024;
+
+export enum PasswordStrength {
+ WEAK = 'WEAK',
+ MODERATE = 'MODERATE',
+ STRONG = 'STRONG',
+}
diff --git a/packages/shared/crypto/helpers.ts b/packages/shared/crypto/helpers.ts
new file mode 100644
index 0000000000..3a1d17f7b9
--- /dev/null
+++ b/packages/shared/crypto/helpers.ts
@@ -0,0 +1,109 @@
+import ComlinkCryptoWorker from '.';
+import { LS_KEYS, getData, setData } from '../storage/localStorage';
+import { SESSION_KEYS, setKey } from '../storage/sessionStorage';
+import { KeyAttributes } from '../user/types';
+
+const LOGIN_SUB_KEY_LENGTH = 32;
+const LOGIN_SUB_KEY_ID = 1;
+const LOGIN_SUB_KEY_CONTEXT = 'loginctx';
+const LOGIN_SUB_KEY_BYTE_LENGTH = 16;
+
+export async function decryptAndStoreToken(
+ keyAttributes: KeyAttributes,
+ masterKey: string
+) {
+ const cryptoWorker = await ComlinkCryptoWorker.getInstance();
+ const user = getData(LS_KEYS.USER);
+ let decryptedToken = null;
+ const { encryptedToken } = user;
+ if (encryptedToken && encryptedToken.length > 0) {
+ const secretKey = await cryptoWorker.decryptB64(
+ keyAttributes.encryptedSecretKey,
+ keyAttributes.secretKeyDecryptionNonce,
+ masterKey
+ );
+ const urlUnsafeB64DecryptedToken = await cryptoWorker.boxSealOpen(
+ encryptedToken,
+ keyAttributes.publicKey,
+ secretKey
+ );
+ const decryptedTokenBytes = await cryptoWorker.fromB64(
+ urlUnsafeB64DecryptedToken
+ );
+ decryptedToken = await cryptoWorker.toURLSafeB64(decryptedTokenBytes);
+ setData(LS_KEYS.USER, {
+ ...user,
+ token: decryptedToken,
+ encryptedToken: null,
+ });
+ }
+}
+
+// We encrypt the masterKey, with an intermediate key derived from the
+// passphrase (with Interactive mem and ops limits) to avoid saving it to local
+// storage in plain text. This means that on the web user will always have to
+// enter their passphrase to access their masterKey.
+export async function generateAndSaveIntermediateKeyAttributes(
+ passphrase: string,
+ existingKeyAttributes: KeyAttributes,
+ key: string
+): Promise<KeyAttributes> {
+ const cryptoWorker = await ComlinkCryptoWorker.getInstance();
+ const intermediateKekSalt = await cryptoWorker.generateSaltToDeriveKey();
+ const intermediateKek = await cryptoWorker.deriveInteractiveKey(
+ passphrase,
+ intermediateKekSalt
+ );
+ const encryptedKeyAttributes = await cryptoWorker.encryptToB64(
+ key,
+ intermediateKek.key
+ );
+
+ const intermediateKeyAttributes = Object.assign(existingKeyAttributes, {
+ kekSalt: intermediateKekSalt,
+ encryptedKey: encryptedKeyAttributes.encryptedData,
+ keyDecryptionNonce: encryptedKeyAttributes.nonce,
+ opsLimit: intermediateKek.opsLimit,
+ memLimit: intermediateKek.memLimit,
+ });
+ setData(LS_KEYS.KEY_ATTRIBUTES, intermediateKeyAttributes);
+ return intermediateKeyAttributes;
+}
+
+export const generateLoginSubKey = async (kek: string) => {
+ const cryptoWorker = await ComlinkCryptoWorker.getInstance();
+ const kekSubKeyString = await cryptoWorker.generateSubKey(
+ kek,
+ LOGIN_SUB_KEY_LENGTH,
+ LOGIN_SUB_KEY_ID,
+ LOGIN_SUB_KEY_CONTEXT
+ );
+ const kekSubKey = await cryptoWorker.fromB64(kekSubKeyString);
+
+ // use first 16 bytes of generated kekSubKey as loginSubKey
+ const loginSubKey = await cryptoWorker.toB64(
+ kekSubKey.slice(0, LOGIN_SUB_KEY_BYTE_LENGTH)
+ );
+
+ return loginSubKey;
+};
+
+export const saveKeyInSessionStore = async (
+ keyType: SESSION_KEYS,
+ key: string,
+ fromDesktop?: boolean
+) => {
+ const cryptoWorker = await ComlinkCryptoWorker.getInstance();
+ const sessionKeyAttributes = await cryptoWorker.generateKeyAndEncryptToB64(
+ key
+ );
+ setKey(keyType, sessionKeyAttributes);
+ console.log('fromDesktop', fromDesktop);
+ // if (
+ // isElectron() &&
+ // !fromDesktop &&
+ // keyType === SESSION_KEYS.ENCRYPTION_KEY
+ // ) {
+ // safeStorageService.setEncryptionKey(key);
+ // }
+};
diff --git a/packages/shared/crypto/index.ts b/packages/shared/crypto/index.ts
new file mode 100644
index 0000000000..8f3b4db3ae
--- /dev/null
+++ b/packages/shared/crypto/index.ts
@@ -0,0 +1,27 @@
+import { Remote } from 'comlink';
+import { DedicatedCryptoWorker } from './internal/crypto.worker';
+import { ComlinkWorker } from '../worker/comlinkWorker';
+
+class ComlinkCryptoWorker {
+ private comlinkWorkerInstance:
+ | Promise<Remote<DedicatedCryptoWorker>>
+ | undefined;
+
+ async getInstance() {
+ if (!this.comlinkWorkerInstance) {
+ const comlinkWorker = getDedicatedCryptoWorker();
+ this.comlinkWorkerInstance = comlinkWorker.remote;
+ }
+ return this.comlinkWorkerInstance;
+ }
+}
+
+export const getDedicatedCryptoWorker = () => {
+ const cryptoComlinkWorker = new ComlinkWorker<typeof DedicatedCryptoWorker>(
+ 'ente-crypto-worker',
+ new Worker(new URL('worker/crypto.worker.ts', import.meta.url))
+ );
+ return cryptoComlinkWorker;
+};
+
+export default new ComlinkCryptoWorker();
diff --git a/packages/shared/crypto/internal/crypto.worker.ts b/packages/shared/crypto/internal/crypto.worker.ts
new file mode 100644
index 0000000000..3dbacbd0a4
--- /dev/null
+++ b/packages/shared/crypto/internal/crypto.worker.ts
@@ -0,0 +1,182 @@
+import * as Comlink from 'comlink';
+import { StateAddress } from 'libsodium-wrappers';
+import * as libsodium from './libsodium';
+
+export class DedicatedCryptoWorker {
+ async decryptMetadata(
+ encryptedMetadata: string,
+ header: string,
+ key: string
+ ) {
+ const encodedMetadata = await libsodium.decryptChaChaOneShot(
+ await libsodium.fromB64(encryptedMetadata),
+ await libsodium.fromB64(header),
+ key
+ );
+ return JSON.parse(new TextDecoder().decode(encodedMetadata));
+ }
+
+ async decryptThumbnail(
+ fileData: Uint8Array,
+ header: Uint8Array,
+ key: string
+ ) {
+ return libsodium.decryptChaChaOneShot(fileData, header, key);
+ }
+
+ async decryptFile(fileData: Uint8Array, header: Uint8Array, key: string) {
+ return libsodium.decryptChaCha(fileData, header, key);
+ }
+
+ async encryptMetadata(metadata: Object, key: string) {
+ const encodedMetadata = new TextEncoder().encode(
+ JSON.stringify(metadata)
+ );
+
+ const { file: encryptedMetadata } =
+ await libsodium.encryptChaChaOneShot(encodedMetadata, key);
+ const { encryptedData, ...other } = encryptedMetadata;
+ return {
+ file: {
+ encryptedData: await libsodium.toB64(encryptedData),
+ ...other,
+ },
+ key,
+ };
+ }
+
+ async encryptThumbnail(fileData: Uint8Array, key: string) {
+ return libsodium.encryptChaChaOneShot(fileData, key);
+ }
+
+ async encryptFile(fileData: Uint8Array) {
+ return libsodium.encryptChaCha(fileData);
+ }
+
+ async encryptFileChunk(
+ data: Uint8Array,
+ pushState: StateAddress,
+ isFinalChunk: boolean
+ ) {
+ return libsodium.encryptFileChunk(data, pushState, isFinalChunk);
+ }
+
+ async initChunkEncryption() {
+ return libsodium.initChunkEncryption();
+ }
+
+ async initChunkDecryption(header: Uint8Array, key: Uint8Array) {
+ return libsodium.initChunkDecryption(header, key);
+ }
+
+ async decryptFileChunk(fileData: Uint8Array, pullState: StateAddress) {
+ return libsodium.decryptFileChunk(fileData, pullState);
+ }
+
+ async initChunkHashing() {
+ return libsodium.initChunkHashing();
+ }
+
+ async hashFileChunk(hashState: StateAddress, chunk: Uint8Array) {
+ return libsodium.hashFileChunk(hashState, chunk);
+ }
+
+ async completeChunkHashing(hashState: StateAddress) {
+ return libsodium.completeChunkHashing(hashState);
+ }
+
+ async deriveKey(
+ passphrase: string,
+ salt: string,
+ opsLimit: number,
+ memLimit: number
+ ) {
+ return libsodium.deriveKey(passphrase, salt, opsLimit, memLimit);
+ }
+
+ async deriveSensitiveKey(passphrase: string, salt: string) {
+ return libsodium.deriveSensitiveKey(passphrase, salt);
+ }
+
+ async deriveInteractiveKey(passphrase: string, salt: string) {
+ return libsodium.deriveInteractiveKey(passphrase, salt);
+ }
+
+ async decryptB64(data: string, nonce: string, key: string) {
+ return libsodium.decryptB64(data, nonce, key);
+ }
+
+ async decryptToUTF8(data: string, nonce: string, key: string) {
+ return libsodium.decryptToUTF8(data, nonce, key);
+ }
+
+ async encryptToB64(data: string, key: string) {
+ return libsodium.encryptToB64(data, key);
+ }
+
+ async generateKeyAndEncryptToB64(data: string) {
+ return libsodium.generateKeyAndEncryptToB64(data);
+ }
+
+ async encryptUTF8(data: string, key: string) {
+ return libsodium.encryptUTF8(data, key);
+ }
+
+ async generateEncryptionKey() {
+ return libsodium.generateEncryptionKey();
+ }
+
+ async generateSaltToDeriveKey() {
+ return libsodium.generateSaltToDeriveKey();
+ }
+
+ async generateKeyPair() {
+ return libsodium.generateKeyPair();
+ }
+
+ async boxSealOpen(input: string, publicKey: string, secretKey: string) {
+ return libsodium.boxSealOpen(input, publicKey, secretKey);
+ }
+
+ async boxSeal(input: string, publicKey: string) {
+ return libsodium.boxSeal(input, publicKey);
+ }
+
+ async generateSubKey(
+ key: string,
+ subKeyLength: number,
+ subKeyID: number,
+ context: string
+ ) {
+ return libsodium.generateSubKey(key, subKeyLength, subKeyID, context);
+ }
+
+ async fromUTF8(string: string) {
+ return libsodium.fromUTF8(string);
+ }
+ async toUTF8(data: string) {
+ return libsodium.toUTF8(data);
+ }
+
+ async toB64(data: Uint8Array) {
+ return libsodium.toB64(data);
+ }
+
+ async toURLSafeB64(data: Uint8Array) {
+ return libsodium.toURLSafeB64(data);
+ }
+
+ async fromB64(string: string) {
+ return libsodium.fromB64(string);
+ }
+
+ async toHex(string: string) {
+ return libsodium.toHex(string);
+ }
+
+ async fromHex(string: string) {
+ return libsodium.fromHex(string);
+ }
+}
+
+Comlink.expose(DedicatedCryptoWorker);
diff --git a/packages/shared/crypto/internal/libsodium.ts b/packages/shared/crypto/internal/libsodium.ts
new file mode 100644
index 0000000000..de7e2f9c7e
--- /dev/null
+++ b/packages/shared/crypto/internal/libsodium.ts
@@ -0,0 +1,422 @@
+import sodium, { StateAddress } from 'libsodium-wrappers';
+import { ENCRYPTION_CHUNK_SIZE } from '../constants';
+import { B64EncryptionResult } from '../types';
+import { CustomError } from '@ente/shared/error';
+
+export async function decryptChaChaOneShot(
+ data: Uint8Array,
+ header: Uint8Array,
+ key: string
+) {
+ await sodium.ready;
+ const pullState = sodium.crypto_secretstream_xchacha20poly1305_init_pull(
+ header,
+ await fromB64(key)
+ );
+ const pullResult = sodium.crypto_secretstream_xchacha20poly1305_pull(
+ pullState,
+ data,
+ null
+ );
+ return pullResult.message;
+}
+
+export async function decryptChaCha(
+ data: Uint8Array,
+ header: Uint8Array,
+ key: string
+) {
+ await sodium.ready;
+ const pullState = sodium.crypto_secretstream_xchacha20poly1305_init_pull(
+ header,
+ await fromB64(key)
+ );
+ const decryptionChunkSize =
+ ENCRYPTION_CHUNK_SIZE +
+ sodium.crypto_secretstream_xchacha20poly1305_ABYTES;
+ let bytesRead = 0;
+ const decryptedData = [];
+ let tag = sodium.crypto_secretstream_xchacha20poly1305_TAG_MESSAGE;
+ while (tag !== sodium.crypto_secretstream_xchacha20poly1305_TAG_FINAL) {
+ let chunkSize = decryptionChunkSize;
+ if (bytesRead + chunkSize > data.length) {
+ chunkSize = data.length - bytesRead;
+ }
+ const buffer = data.slice(bytesRead, bytesRead + chunkSize);
+ const pullResult = sodium.crypto_secretstream_xchacha20poly1305_pull(
+ pullState,
+ buffer
+ );
+ if (!pullResult.message) {
+ throw new Error(CustomError.PROCESSING_FAILED);
+ }
+ for (let index = 0; index < pullResult.message.length; index++) {
+ decryptedData.push(pullResult.message[index]);
+ }
+ tag = pullResult.tag;
+ bytesRead += chunkSize;
+ }
+ return Uint8Array.from(decryptedData);
+}
+
+export async function initChunkDecryption(header: Uint8Array, key: Uint8Array) {
+ await sodium.ready;
+ const pullState = sodium.crypto_secretstream_xchacha20poly1305_init_pull(
+ header,
+ key
+ );
+ const decryptionChunkSize =
+ ENCRYPTION_CHUNK_SIZE +
+ sodium.crypto_secretstream_xchacha20poly1305_ABYTES;
+ const tag = sodium.crypto_secretstream_xchacha20poly1305_TAG_MESSAGE;
+ return { pullState, decryptionChunkSize, tag };
+}
+
+export async function decryptFileChunk(
+ data: Uint8Array,
+ pullState: StateAddress
+) {
+ await sodium.ready;
+ const pullResult = sodium.crypto_secretstream_xchacha20poly1305_pull(
+ pullState,
+ data
+ );
+ if (!pullResult.message) {
+ throw new Error(CustomError.PROCESSING_FAILED);
+ }
+ const newTag = pullResult.tag;
+ return { decryptedData: pullResult.message, newTag };
+}
+
+export async function encryptChaChaOneShot(data: Uint8Array, key: string) {
+ await sodium.ready;
+
+ const uintkey: Uint8Array = await fromB64(key);
+ const initPushResult =
+ sodium.crypto_secretstream_xchacha20poly1305_init_push(uintkey);
+ const [pushState, header] = [initPushResult.state, initPushResult.header];
+
+ const pushResult = sodium.crypto_secretstream_xchacha20poly1305_push(
+ pushState,
+ data,
+ null,
+ sodium.crypto_secretstream_xchacha20poly1305_TAG_FINAL
+ );
+ return {
+ key: await toB64(uintkey),
+ file: {
+ encryptedData: pushResult,
+ decryptionHeader: await toB64(header),
+ },
+ };
+}
+
+export async function encryptChaCha(data: Uint8Array) {
+ await sodium.ready;
+
+ const uintkey: Uint8Array =
+ sodium.crypto_secretstream_xchacha20poly1305_keygen();
+
+ const initPushResult =
+ sodium.crypto_secretstream_xchacha20poly1305_init_push(uintkey);
+ const [pushState, header] = [initPushResult.state, initPushResult.header];
+ let bytesRead = 0;
+ let tag = sodium.crypto_secretstream_xchacha20poly1305_TAG_MESSAGE;
+
+ const encryptedData = [];
+
+ while (tag !== sodium.crypto_secretstream_xchacha20poly1305_TAG_FINAL) {
+ let chunkSize = ENCRYPTION_CHUNK_SIZE;
+ if (bytesRead + chunkSize >= data.length) {
+ chunkSize = data.length - bytesRead;
+ tag = sodium.crypto_secretstream_xchacha20poly1305_TAG_FINAL;
+ }
+
+ const buffer = data.slice(bytesRead, bytesRead + chunkSize);
+ bytesRead += chunkSize;
+ const pushResult = sodium.crypto_secretstream_xchacha20poly1305_push(
+ pushState,
+ buffer,
+ null,
+ tag
+ );
+ for (let index = 0; index < pushResult.length; index++) {
+ encryptedData.push(pushResult[index]);
+ }
+ }
+ return {
+ key: await toB64(uintkey),
+ file: {
+ encryptedData: new Uint8Array(encryptedData),
+ decryptionHeader: await toB64(header),
+ },
+ };
+}
+
+export async function initChunkEncryption() {
+ await sodium.ready;
+ const key = sodium.crypto_secretstream_xchacha20poly1305_keygen();
+ const initPushResult =
+ sodium.crypto_secretstream_xchacha20poly1305_init_push(key);
+ const [pushState, header] = [initPushResult.state, initPushResult.header];
+ return {
+ key: await toB64(key),
+ decryptionHeader: await toB64(header),
+ pushState,
+ };
+}
+
+export async function encryptFileChunk(
+ data: Uint8Array,
+ pushState: sodium.StateAddress,
+ isFinalChunk: boolean
+) {
+ await sodium.ready;
+ const tag = isFinalChunk
+ ? sodium.crypto_secretstream_xchacha20poly1305_TAG_FINAL
+ : sodium.crypto_secretstream_xchacha20poly1305_TAG_MESSAGE;
+ const pushResult = sodium.crypto_secretstream_xchacha20poly1305_push(
+ pushState,
+ data,
+ null,
+ tag
+ );
+
+ return pushResult;
+}
+export async function encryptToB64(data: string, key: string) {
+ await sodium.ready;
+ const encrypted = await encrypt(await fromB64(data), await fromB64(key));
+
+ return {
+ encryptedData: await toB64(encrypted.encryptedData),
+ key: await toB64(encrypted.key),
+ nonce: await toB64(encrypted.nonce),
+ } as B64EncryptionResult;
+}
+
+export async function generateKeyAndEncryptToB64(data: string) {
+ await sodium.ready;
+ const key = sodium.crypto_secretbox_keygen();
+ return await encryptToB64(data, await toB64(key));
+}
+
+export async function encryptUTF8(data: string, key: string) {
+ const b64Data = await toB64(await fromUTF8(data));
+ return await encryptToB64(b64Data, key);
+}
+
+export async function decryptB64(data: string, nonce: string, key: string) {
+ await sodium.ready;
+ const decrypted = await decrypt(
+ await fromB64(data),
+ await fromB64(nonce),
+ await fromB64(key)
+ );
+
+ return await toB64(decrypted);
+}
+
+export async function decryptToUTF8(data: string, nonce: string, key: string) {
+ await sodium.ready;
+ const decrypted = await decrypt(
+ await fromB64(data),
+ await fromB64(nonce),
+ await fromB64(key)
+ );
+
+ return sodium.to_string(decrypted);
+}
+
+async function encrypt(data: Uint8Array, key: Uint8Array) {
+ await sodium.ready;
+ const nonce = sodium.randombytes_buf(sodium.crypto_secretbox_NONCEBYTES);
+ const encryptedData = sodium.crypto_secretbox_easy(data, nonce, key);
+ return {
+ encryptedData,
+ key,
+ nonce,
+ };
+}
+
+async function decrypt(data: Uint8Array, nonce: Uint8Array, key: Uint8Array) {
+ await sodium.ready;
+ return sodium.crypto_secretbox_open_easy(data, nonce, key);
+}
+
+export async function initChunkHashing() {
+ await sodium.ready;
+ const hashState = sodium.crypto_generichash_init(
+ null,
+ sodium.crypto_generichash_BYTES_MAX
+ );
+ return hashState;
+}
+
+export async function hashFileChunk(
+ hashState: sodium.StateAddress,
+ chunk: Uint8Array
+) {
+ await sodium.ready;
+ sodium.crypto_generichash_update(hashState, chunk);
+}
+
+export async function completeChunkHashing(hashState: sodium.StateAddress) {
+ await sodium.ready;
+ const hash = sodium.crypto_generichash_final(
+ hashState,
+ sodium.crypto_generichash_BYTES_MAX
+ );
+ const hashString = toB64(hash);
+ return hashString;
+}
+
+export async function deriveKey(
+ passphrase: string,
+ salt: string,
+ opsLimit: number,
+ memLimit: number
+) {
+ await sodium.ready;
+ return await toB64(
+ sodium.crypto_pwhash(
+ sodium.crypto_secretbox_KEYBYTES,
+ await fromUTF8(passphrase),
+ await fromB64(salt),
+ opsLimit,
+ memLimit,
+ sodium.crypto_pwhash_ALG_ARGON2ID13
+ )
+ );
+}
+
+export async function deriveSensitiveKey(passphrase: string, salt: string) {
+ await sodium.ready;
+ const minMemLimit = sodium.crypto_pwhash_MEMLIMIT_MIN;
+ let opsLimit = sodium.crypto_pwhash_OPSLIMIT_SENSITIVE;
+ let memLimit = sodium.crypto_pwhash_MEMLIMIT_SENSITIVE;
+ while (memLimit > minMemLimit) {
+ try {
+ const key = await deriveKey(passphrase, salt, opsLimit, memLimit);
+ return {
+ key,
+ opsLimit,
+ memLimit,
+ };
+ } catch (e) {
+ opsLimit *= 2;
+ memLimit /= 2;
+ }
+ }
+}
+
+export async function deriveInteractiveKey(passphrase: string, salt: string) {
+ await sodium.ready;
+ const key = await toB64(
+ sodium.crypto_pwhash(
+ sodium.crypto_secretbox_KEYBYTES,
+ await fromUTF8(passphrase),
+ await fromB64(salt),
+ sodium.crypto_pwhash_OPSLIMIT_INTERACTIVE,
+ sodium.crypto_pwhash_MEMLIMIT_INTERACTIVE,
+ sodium.crypto_pwhash_ALG_ARGON2ID13
+ )
+ );
+ return {
+ key,
+ opsLimit: sodium.crypto_pwhash_OPSLIMIT_INTERACTIVE,
+ memLimit: sodium.crypto_pwhash_MEMLIMIT_INTERACTIVE,
+ };
+}
+
+export async function generateEncryptionKey() {
+ await sodium.ready;
+ return await toB64(sodium.crypto_kdf_keygen());
+}
+
+export async function generateSaltToDeriveKey() {
+ await sodium.ready;
+ return await toB64(sodium.randombytes_buf(sodium.crypto_pwhash_SALTBYTES));
+}
+
+export async function generateKeyPair() {
+ await sodium.ready;
+ const keyPair: sodium.KeyPair = sodium.crypto_box_keypair();
+ return {
+ privateKey: await toB64(keyPair.privateKey),
+ publicKey: await toB64(keyPair.publicKey),
+ };
+}
+
+export async function boxSealOpen(
+ input: string,
+ publicKey: string,
+ secretKey: string
+) {
+ await sodium.ready;
+ return await toB64(
+ sodium.crypto_box_seal_open(
+ await fromB64(input),
+ await fromB64(publicKey),
+ await fromB64(secretKey)
+ )
+ );
+}
+
+export async function boxSeal(input: string, publicKey: string) {
+ await sodium.ready;
+ return await toB64(
+ sodium.crypto_box_seal(await fromB64(input), await fromB64(publicKey))
+ );
+}
+
+export async function generateSubKey(
+ key: string,
+ subKeyLength: number,
+ subKeyID: number,
+ context: string
+) {
+ await sodium.ready;
+ return await toB64(
+ sodium.crypto_kdf_derive_from_key(
+ subKeyLength,
+ subKeyID,
+ context,
+ await fromB64(key)
+ )
+ );
+}
+
+export async function fromB64(input: string) {
+ await sodium.ready;
+ return sodium.from_base64(input, sodium.base64_variants.ORIGINAL);
+}
+
+export async function toB64(input: Uint8Array) {
+ await sodium.ready;
+ return sodium.to_base64(input, sodium.base64_variants.ORIGINAL);
+}
+
+export async function toURLSafeB64(input: Uint8Array) {
+ await sodium.ready;
+ return sodium.to_base64(input, sodium.base64_variants.URLSAFE);
+}
+
+export async function fromUTF8(input: string) {
+ await sodium.ready;
+ return sodium.from_string(input);
+}
+
+export async function toUTF8(input: string) {
+ await sodium.ready;
+ return sodium.to_string(await fromB64(input));
+}
+export async function toHex(input: string) {
+ await sodium.ready;
+ return sodium.to_hex(await fromB64(input));
+}
+
+export async function fromHex(input: string) {
+ await sodium.ready;
+ return await toB64(sodium.from_hex(input));
+}
diff --git a/packages/shared/crypto/types.ts b/packages/shared/crypto/types.ts
new file mode 100644
index 0000000000..e591820f08
--- /dev/null
+++ b/packages/shared/crypto/types.ts
@@ -0,0 +1,5 @@
+export interface B64EncryptionResult {
+ encryptedData: string;
+ key: string;
+ nonce: string;
+}
diff --git a/packages/shared/worker/comlinkWorker.ts b/packages/shared/worker/comlinkWorker.ts
new file mode 100644
index 0000000000..3e3e8e3b99
--- /dev/null
+++ b/packages/shared/worker/comlinkWorker.ts
@@ -0,0 +1,31 @@
+import { Remote, wrap } from 'comlink';
+// import { WorkerElectronCacheStorageClient } from 'services/workerElectronCache/client';
+// import { addLocalLog } from 'utils/logging';
+
+export class ComlinkWorker<T extends new () => InstanceType<T>> {
+ public remote: Promise<Remote<InstanceType<T>>>;
+ private worker: Worker;
+ private name: string;
+
+ constructor(name: string, worker: Worker) {
+ this.name = name;
+ this.worker = worker;
+
+ this.worker.onerror = (errorEvent) => {
+ console.error('Got error event from worker', errorEvent);
+ };
+ // addLocalLog(() => `Initiated ${this.name}`);
+ const comlink = wrap<T>(this.worker);
+ this.remote = new comlink() as Promise<Remote<InstanceType<T>>>;
+ // expose(WorkerElectronCacheStorageClient, this.worker);
+ }
+
+ public getName() {
+ return this.name;
+ }
+
+ public terminate() {
+ this.worker.terminate();
+ // addLocalLog(() => `Terminated ${this.name}`);
+ }
+}