π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
Keep authenticated account crypto in app WASM
Manav Rathi10046f5398b6
diff --git a/rust/bindings/wasm/space/Cargo.toml b/rust/bindings/wasm/space/Cargo.tomlindex 86f8f8f951..af9161c97a 100644--- a/rust/bindings/wasm/space/Cargo.toml+++ b/rust/bindings/wasm/space/Cargo.toml@@ -8,7 +8,7 @@ crate-type = ["cdylib"][dependencies]ente-core.workspace = trueente-space.workspace = true-ente-wasm-lib.workspace = true+ente-wasm-lib = { workspace = true, features = ["crypto"] }js-sys.workspace = truelog.workspace = trueserde.workspace = truediff --git a/rust/bindings/wasm/space/src/space.rs b/rust/bindings/wasm/space/src/space.rsindex 92c531c10b..ac2283a38f 100644--- a/rust/bindings/wasm/space/src/space.rs+++ b/rust/bindings/wasm/space/src/space.rs@@ -444,23 +444,6 @@ fn decode_b64_field(value: &str) -> Result<Vec<u8>, Error> {.map_err(Into::into)}-#[wasm_bindgen(js_name = encryptSpaceRootEntityKey)]-pub fn encrypt_space_root_entity_key(- space_root_key_b64: &str,- master_key_b64: &str,-) -> Result<String, Error> {- ente_space::encrypt_space_root_entity_key(space_root_key_b64, master_key_b64)- .map_err(Into::into)-}--#[wasm_bindgen(js_name = decryptSpaceRootEntityKey)]-pub fn decrypt_space_root_entity_key(- encrypted_key_b64: &str,- master_key_b64: &str,-) -> Result<String, Error> {- ente_space::decrypt_space_root_entity_key(encrypted_key_b64, master_key_b64).map_err(Into::into)-}-fn utf8_field(bytes: Vec<u8>, field: &str) -> Result<String, Error> {String::from_utf8(bytes).map_err(|err| {ente_space::Error::InvalidInput(format!("invalid {field} utf8: {err}")).into()diff --git a/rust/crates/space/src/crypto.rs b/rust/crates/space/src/crypto.rsindex 3b07117e11..47c4480456 100644--- a/rust/crates/space/src/crypto.rs+++ b/rust/crates/space/src/crypto.rs@@ -7,30 +7,6 @@ use crate::error::Result;pub(crate) const SECRETBOX_PAYLOAD_OVERHEAD_BYTES: usize = Nonce::BYTES + secretbox::MAC_BYTES;pub(crate) const ASSET_PAYLOAD_OVERHEAD_BYTES: usize = Header::BYTES + blob::ABYTES;-pub fn encrypt_space_root_entity_key(- space_root_key_b64: &str,- master_key_b64: &str,-) -> Result<String> {- let space_root_key = b64::decode(space_root_key_b64)?;- let master_key = b64::decode(master_key_b64)?;- Ok(b64::encode(&encrypt_secretbox_payload(- &master_key,- &space_root_key,- )?))-}--pub fn decrypt_space_root_entity_key(- encrypted_key_b64: &str,- master_key_b64: &str,-) -> Result<String> {- let encrypted_key = b64::decode(encrypted_key_b64)?;- let master_key = b64::decode(master_key_b64)?;- Ok(b64::encode(&decrypt_secretbox_payload(- &master_key,- &encrypted_key,- )?))-}-pub(crate) fn generate_key() -> Vec<u8> {Key::generate().as_bytes().to_vec()}@@ -88,15 +64,6 @@ pub(crate) fn decrypt_asset_payload(key: &[u8], payload: &[u8]) -> Result<Vec<u8mod tests {use super::*;- #[test]- fn secretbox_payload_round_trip() {- let key = b64::encode(&generate_key());- let plaintext = b64::encode(b"hello space");- let payload = encrypt_space_root_entity_key(&plaintext, &key).unwrap();- let decrypted = decrypt_space_root_entity_key(&payload, &key).unwrap();- assert_eq!(decrypted, plaintext);- }-#[test]fn asset_round_trip() {let key = generate_key();diff --git a/rust/crates/space/src/lib.rs b/rust/crates/space/src/lib.rsindex 5d03eecebd..c6b5c61693 100644--- a/rust/crates/space/src/lib.rs+++ b/rust/crates/space/src/lib.rs@@ -11,7 +11,6 @@ pub use client::{MAX_SPACE_MESSAGE_TEXT_BYTES, MAX_SPACE_MESSAGE_TEXT_CHARS, MAX_SPACE_POST_PLAINTEXT_BYTES,MAX_SPACE_POST_UPLOAD_BYTES, PostPhotoAssetOptions, SpaceLinkCtx,};-pub use crypto::{decrypt_space_root_entity_key, encrypt_space_root_entity_key};pub use error::{Error, Result};pub use models::{CreatedSpace, CreatedSpaceLink, DecryptedFriendShare, DecryptedMessage, DecryptedPost,diff --git a/web/apps/auth/src/auth-page-config.ts b/web/apps/auth/src/auth-page-config.tsindex 38aa9eba64..c6baacfc2b 100644--- a/web/apps/auth/src/auth-page-config.ts+++ b/web/apps/auth/src/auth-page-config.ts@@ -1,8 +1,10 @@import { AuthShell } from "@/components/AuthShell";import type { AuthPageConfig } from "ente-accounts/components/auth/AuthPageProvider";+import { decryptBox } from "ente-auth-wasm";import { LoginFrame } from "./components/auth/LoginFrame";export const authPageConfig: AuthPageConfig = {+ decryptBox,encryptWithRecoveryKey: async (data) => {const { encryptWithRecoveryKey } =await import("./services/recovery-key");diff --git a/web/apps/locker/src/auth-page-config.ts b/web/apps/locker/src/auth-page-config.tsindex 22ddac82d2..fe1f3019da 100644--- a/web/apps/locker/src/auth-page-config.ts+++ b/web/apps/locker/src/auth-page-config.ts@@ -1,7 +1,9 @@import { LockerAuthShell } from "@/components/auth/LockerAuthShell";import type { AuthPageConfig } from "ente-accounts/components/auth/AuthPageProvider";+import { decryptBox } from "ente-locker-wasm";export const authPageConfig: AuthPageConfig = {+ decryptBox,encryptWithRecoveryKey: async (data) => {const { encryptWithRecoveryKey } =await import("./services/recovery-key");diff --git a/web/apps/locker/src/components/auth/LockerAuthenticateUser.tsx b/web/apps/locker/src/components/auth/LockerAuthenticateUser.tsxindex c643b4cebd..d231e49e68 100644--- a/web/apps/locker/src/components/auth/LockerAuthenticateUser.tsx+++ b/web/apps/locker/src/components/auth/LockerAuthenticateUser.tsx@@ -9,6 +9,7 @@ import {InputAdornment,Stack,} from "@mui/material";+import { useAuthPageConfig } from "ente-accounts/components/auth/AuthPageProvider";import {VerifyMasterPasswordForm,type VerifyMasterPasswordPresentationProps,@@ -102,6 +103,7 @@ export const LockerAuthenticateUser: React.FC<LockerAuthenticateUserProps> = ({const LockerAuthenticateUserDialogContents: React.FC<LockerAuthenticateUserProps> = ({ open, onClose, onAuthenticate }) => {+ const { decryptBox } = useAuthPageConfig();const { logout, showMiniDialog } = useBaseContext();const [user, setUser] = useState<LocalUser | undefined>();@@ -139,6 +141,7 @@ const LockerAuthenticateUserDialogContents: React.FC<return (<VerifyMasterPasswordForm+ decryptBox={decryptBox}presentation={LockerPasswordForm}userEmail={user.email}keyAttributes={keyAttributes}diff --git a/web/apps/photos/src/auth-page-config.ts b/web/apps/photos/src/auth-page-config.tsindex bc04d25e78..3f88a9b34d 100644--- a/web/apps/photos/src/auth-page-config.ts+++ b/web/apps/photos/src/auth-page-config.ts@@ -1,8 +1,10 @@import { PasskeyVerificationPresentation } from "@/components/auth/PasskeyVerificationForm";import { PhotosAuthShell } from "@/components/PhotosAuthShell";import type { AuthPageConfig } from "ente-accounts/components/auth/AuthPageProvider";+import { decryptBox } from "ente-photos-wasm";export const authPageConfig: AuthPageConfig = {+ decryptBox,encryptWithRecoveryKey: async (data) => {const { encryptWithRecoveryKey } =await import("./services/recovery-key");diff --git a/web/apps/photos/src/components/AuthenticateUser.tsx b/web/apps/photos/src/components/AuthenticateUser.tsxindex eef702dc11..90d98e27d8 100644--- a/web/apps/photos/src/components/AuthenticateUser.tsx+++ b/web/apps/photos/src/components/AuthenticateUser.tsx@@ -1,3 +1,4 @@+import { useAuthPageConfig } from "ente-accounts/components/auth/AuthPageProvider";import { VerifyMasterPasswordForm } from "ente-accounts/components/VerifyMasterPasswordForm";import { checkSessionValidity } from "ente-accounts/services/session";import {@@ -40,6 +41,7 @@ const AuthenticateUserDialogContents: React.FC<AuthenticateUserProps> = ({onClose,onAuthenticate,}) => {+ const { decryptBox } = useAuthPageConfig();const { logout, showMiniDialog } = useBaseContext();const [user, setUser] = useState<LocalUser | undefined>();@@ -76,6 +78,7 @@ const AuthenticateUserDialogContents: React.FC<AuthenticateUserProps> = ({return (<VerifyMasterPasswordForm+ decryptBox={decryptBox}userEmail={user.email}keyAttributes={keyAttributes}submitButtonTitle={t("authenticate")}diff --git a/web/apps/space/src/services/persistent-session.ts b/web/apps/space/src/services/persistent-session.tsindex 297d1b3db0..0512af7019 100644--- a/web/apps/space/src/services/persistent-session.ts+++ b/web/apps/space/src/services/persistent-session.ts@@ -2,21 +2,15 @@ import {replaceSavedLocalUser,savedPartialLocalUser,} from "ente-accounts/services/accounts-db";-import {- decryptBox,- encryptBox,- fromB64,- generateKey,- toB64,-} from "ente-accounts/services/crypto";import { accountLogout } from "ente-accounts/services/logout";import { ensureOk, publicRequestHeaders } from "ente-base/http";import log from "ente-base/log";import { apiURL } from "ente-base/origins";import { removeAuthToken } from "ente-base/token";import {- decryptSpaceRootEntityKey,- encryptSpaceRootEntityKey,+ decryptBox,+ encryptBox,+ generateKey,type SpaceKeyResponse,} from "ente-space-wasm";import { spaceBootstrapAuthHeaders } from "services/bootstrap-auth";@@ -68,34 +62,6 @@ const SpaceEntityKeyResponse = z.object({encryptedKey: z.string(),header: z.string(),});-type SpaceEntityKeyResponse = z.infer<typeof SpaceEntityKeyResponse>;--const spaceEntityKeyHeaderBytes = 24;--const splitSpaceEntityKey = async (encryptedKey: string) => {- const combined = await fromB64(encryptedKey);- if (combined.length <= spaceEntityKeyHeaderBytes) {- throw new Error("Space entity key is missing header.");- }- return {- encryptedKey: await toB64(combined.slice(spaceEntityKeyHeaderBytes)),- header: await toB64(combined.slice(0, spaceEntityKeyHeaderBytes)),- };-};--const combineSpaceEntityKey = async ({- encryptedKey,- header,-}: SpaceEntityKeyResponse) => {- const headerBytes = await fromB64(header);- const encryptedKeyBytes = await fromB64(encryptedKey);- const combined = new Uint8Array(- headerBytes.length + encryptedKeyBytes.length,- );- combined.set(headerBytes);- combined.set(encryptedKeyBytes, headerBytes.length);- return toB64(combined);-};const savedPersistedSession = () => {const value = localStorage.getItem(spaceBrowserSessionStorageKey);@@ -264,20 +230,22 @@ export const getOrCreateSpaceRootKey = async (authToken: string,) => {const candidate = await generateKey();- const encryptedKey = await encryptSpaceRootEntityKey(candidate, masterKey);- const splitKey = await splitSpaceEntityKey(encryptedKey);+ const { encryptedData: encryptedKey, nonce: header } = await encryptBox(+ candidate,+ masterKey,+ );const res = await fetch(await apiURL("/user-entity/key/ensure"), {method: "POST",headers: {...spaceBootstrapAuthHeaders(authToken),"Content-Type": "application/json",},- body: JSON.stringify({ type: "space", ...splitKey }),+ body: JSON.stringify({ type: "space", encryptedKey, header }),});ensureOk(res);const ensured = SpaceEntityKeyResponse.parse(await res.json());- return await decryptSpaceRootEntityKey(- await combineSpaceEntityKey(ensured),+ return decryptBox(+ { encryptedData: ensured.encryptedKey, nonce: ensured.header },masterKey,);};diff --git a/web/apps/space/tests/friend-errors.test.ts b/web/apps/space/tests/friend-errors.test.tsindex a958e36dbe..903009ec1c 100644--- a/web/apps/space/tests/friend-errors.test.ts+++ b/web/apps/space/tests/friend-errors.test.ts@@ -1,5 +1,5 @@import {- encryptSpaceRootEntityKey,+ encryptBox,openSpaceAccountContext,type SpaceAccountCtxHandle,} from "ente-space-wasm";@@ -16,6 +16,7 @@ const publicKey = Buffer.from([9, ...new Array<number>(31).fill(0)]).toString(beforeEach(async () => {const key = Buffer.alloc(32, 1).toString("base64");+ const { encryptedData, nonce } = await encryptBox(key, key);ctx = await openSpaceAccountContext({baseUrl: "http://localhost",clientPackage: "io.ente.space.web",@@ -26,7 +27,10 @@ beforeEach(async () => {spaceId: "self",spaceSlug: "self",keyVersion: 1,- rootWrappedSpaceKey: await encryptSpaceRootEntityKey(key, key),+ rootWrappedSpaceKey: Buffer.concat([+ Buffer.from(nonce, "base64"),+ Buffer.from(encryptedData, "base64"),+ ]).toString("base64"),},],});diff --git a/web/apps/space/tests/post-upload.test.ts b/web/apps/space/tests/post-upload.test.tsindex 6bdff67aeb..75101939c2 100644--- a/web/apps/space/tests/post-upload.test.ts+++ b/web/apps/space/tests/post-upload.test.ts@@ -1,7 +1,4 @@-import {- encryptSpaceRootEntityKey,- openSpaceAccountContext,-} from "ente-space-wasm";+import { encryptBox, openSpaceAccountContext } from "ente-space-wasm";import { afterEach, expect, test, vi } from "vitest";afterEach(() => vi.unstubAllGlobals());@@ -26,6 +23,7 @@ interface UploadedPost {const uploadFixture = async (failSecondUpload = false) => {const rootKey = btoa("r".repeat(32));const spaceKey = btoa("s".repeat(32));+ const { encryptedData, nonce } = await encryptBox(spaceKey, rootKey);const ctx = await openSpaceAccountContext({baseUrl: "http://localhost",spaceSessionToken: "test-session",@@ -35,10 +33,10 @@ const uploadFixture = async (failSecondUpload = false) => {{spaceId: "test-space",spaceSlug: "test",- rootWrappedSpaceKey: await encryptSpaceRootEntityKey(- spaceKey,- rootKey,- ),+ rootWrappedSpaceKey: Buffer.concat([+ Buffer.from(nonce, "base64"),+ Buffer.from(encryptedData, "base64"),+ ]).toString("base64"),publicKey: "",encryptedSecretKey: "",encryptedProfile: "",diff --git a/web/packages/accounts/components/VerifyMasterPasswordForm.tsx b/web/packages/accounts/components/VerifyMasterPasswordForm.tsxindex 76ab63b5ed..74e0b0b7f4 100644--- a/web/packages/accounts/components/VerifyMasterPasswordForm.tsx+++ b/web/packages/accounts/components/VerifyMasterPasswordForm.tsx@@ -1,11 +1,12 @@import { Input, TextField } from "@mui/material";-import { decryptBox, deriveKey } from "ente-accounts/services/crypto";+import { deriveKey } from "ente-accounts/services/crypto";import type { SRPAttributes } from "ente-accounts/services/srp";import type { KeyAttributes } from "ente-accounts/services/user";import { LoadingButton } from "ente-base/components/mui/LoadingButton";import { ShowHidePasswordInputAdornment } from "ente-base/components/mui/PasswordInputAdornment";import { isNamedError } from "ente-base/error";import log from "ente-base/log";+import type { SessionStorageCrypto } from "ente-base/session-storage";import { useFormik } from "formik";import { t } from "i18next";import { useCallback, useState, type ComponentType } from "react";@@ -23,6 +24,7 @@ export interface VerifyMasterPasswordPresentationProps {}export interface VerifyMasterPasswordFormProps {+ decryptBox: SessionStorageCrypto["decryptBox"];userEmail: string;srpAttributes?: SRPAttributes;keyAttributes: KeyAttributes | undefined;@@ -43,6 +45,7 @@ export interface VerifyMasterPasswordFormProps {export const VerifyMasterPasswordForm: React.FC<VerifyMasterPasswordFormProps> = ({+ decryptBox,userEmail,keyAttributes,srpAttributes,@@ -82,34 +85,23 @@ export const VerifyMasterPasswordForm: React.FC<password: string,setFieldError: (message: string) => void,) => {+ const kdfAttributes = srpAttributes ?? keyAttributes;+ if (!kdfAttributes)+ throw new Error("Both SRP and key attributes are missing");+let kek: string;- if (srpAttributes) {- try {- kek = await deriveKey(- password,- srpAttributes.kekSalt,- srpAttributes.opsLimit,- srpAttributes.memLimit,- );- } catch (e) {- log.error("Failed to derive kek", e);- setFieldError(t("weak_device_hint"));- return;- }- } else if (keyAttributes) {- try {- kek = await deriveKey(- password,- keyAttributes.kekSalt,- keyAttributes.opsLimit,- keyAttributes.memLimit,- );- } catch (e) {- log.error("Failed to derive kek", e);- setFieldError(t("weak_device_hint"));- return;- }- } else throw new Error("Both SRP and key attributes are missing");+ try {+ kek = await deriveKey(+ password,+ kdfAttributes.kekSalt,+ kdfAttributes.opsLimit,+ kdfAttributes.memLimit,+ );+ } catch (e) {+ log.error("Failed to derive kek", e);+ setFieldError(t("weak_device_hint"));+ return;+ }if (!keyAttributes && getKeyAttributes && srpAttributes) {try {diff --git a/web/packages/accounts/components/auth/AuthPageProvider.ts b/web/packages/accounts/components/auth/AuthPageProvider.tsindex 001ccc9db6..35f4638dda 100644--- a/web/packages/accounts/components/auth/AuthPageProvider.ts+++ b/web/packages/accounts/components/auth/AuthPageProvider.ts@@ -1,3 +1,4 @@+import type { SessionStorageCrypto } from "ente-base/session-storage";import {createContext,useContext,@@ -12,6 +13,7 @@ export interface AuthLoginFrameProps extends PropsWithChildren {}export interface AuthPageConfig {+ decryptBox: SessionStorageCrypto["decryptBox"];LoginFrame?: ComponentType<AuthLoginFrameProps>;keepLoginLoadingOnRedirect?: boolean;recoveryKeyCloseDestination?: string;diff --git a/web/packages/accounts/pages/change-password.tsx b/web/packages/accounts/pages/change-password.tsxindex a20e52afd2..b9bd851816 100644--- a/web/packages/accounts/pages/change-password.tsx+++ b/web/packages/accounts/pages/change-password.tsx@@ -6,12 +6,14 @@ import {AccountsPageFooter,AccountsPageTitle,} from "ente-accounts/components/layouts/centered-paper";+import { changePassword } from "ente-accounts/services/password";import { appHomeRoute, stashRedirect } from "ente-accounts/services/redirect";-import { changePassword, type LocalUser } from "ente-accounts/services/user";+import type { LocalUser } from "ente-accounts/services/user";import { LinkButton } from "ente-base/components/LinkButton";import { LoadingIndicator } from "ente-base/components/loaders";import { isNamedError } from "ente-base/error";import log from "ente-base/log";+import { decryptBox as preloginDecryptBox } from "ente-prelogin-wasm";import { t } from "i18next";import { useRouter } from "next/router";import React, { useCallback, useEffect, useState } from "react";@@ -53,12 +55,13 @@ interface PageContentsProps {}const PageContents: React.FC<PageContentsProps> = ({ user, isReset }) => {- const { Shell } = useAuthPageConfig();+ const { Shell, decryptBox: appDecryptBox } = useAuthPageConfig();+ const decryptBox = isReset ? preloginDecryptBox : appDecryptBox;const router = useRouter();const handleSubmit: NewPasswordFormProps["onSubmit"] = useCallback(async (password, setPasswordsFieldError) =>- changePassword(password)+ changePassword(password, decryptBox).then(() => void router.push(appHomeRoute)).catch((e: unknown) => {log.error("Could not change password", e);@@ -68,7 +71,7 @@ const PageContents: React.FC<PageContentsProps> = ({ user, isReset }) => {: t("generic_error"),);}),- [router],+ [router, decryptBox],);if (isReset) {diff --git a/web/packages/accounts/pages/credentials.tsx b/web/packages/accounts/pages/credentials.tsxindex 1f1581cd50..b2273b5fea 100644--- a/web/packages/accounts/pages/credentials.tsx+++ b/web/packages/accounts/pages/credentials.tsx@@ -354,6 +354,7 @@ const Page: React.FC = () => {host={host}passwordForm={<VerifyMasterPasswordForm+ decryptBox={decryptBox}{...{userEmail,keyAttributes,diff --git a/web/packages/accounts/services/key-attributes.ts b/web/packages/accounts/services/key-attributes.tsnew file mode 100644index 0000000000..38ae633f6f--- /dev/null+++ b/web/packages/accounts/services/key-attributes.ts@@ -0,0 +1,25 @@+import { deriveInteractiveKey, encryptBox } from "./crypto";+import type { KeyAttributes } from "./user";++export const generateInteractiveKeyAttributes = async (+ password: string,+ keyAttributes: KeyAttributes,+ masterKey: string,+): Promise<KeyAttributes> => {+ const {+ key: kek,+ salt: kekSalt,+ opsLimit,+ memLimit,+ } = await deriveInteractiveKey(password);+ const { encryptedData: encryptedKey, nonce: keyDecryptionNonce } =+ await encryptBox(masterKey, kek);+ return {+ ...keyAttributes,+ encryptedKey,+ keyDecryptionNonce,+ kekSalt,+ opsLimit,+ memLimit,+ };+};diff --git a/web/packages/accounts/services/password.ts b/web/packages/accounts/services/password.tsnew file mode 100644index 0000000000..56eaa6680f--- /dev/null+++ b/web/packages/accounts/services/password.ts@@ -0,0 +1,32 @@+import {+ readMasterKeyFromSession,+ type SessionStorageCrypto,+} from "ente-base/session-storage";+import { ComlinkWorker } from "ente-base/worker/comlink-worker";+import { saveKeyAttributes, saveSRPAttributes } from "./accounts-db";+import type { PasswordWorker } from "./password.worker";+import { ensureLocalUser, ensureSavedKeyAttributes } from "./user";++export const changePassword = async (+ password: string,+ decryptBox: SessionStorageCrypto["decryptBox"],+) => {+ const { email } = ensureLocalUser();+ const keyAttributes = ensureSavedKeyAttributes();+ const masterKey = await readMasterKeyFromSession(decryptBox);+ if (!masterKey) throw new Error("Master key not found in session");++ const worker = new ComlinkWorker<typeof PasswordWorker>(+ "password",+ new Worker(new URL("password.worker.ts", import.meta.url)),+ );+ try {+ const updated = await (+ await worker.remote+ ).changePassword(password, masterKey, keyAttributes, email);+ saveSRPAttributes(updated.srpAttributes);+ saveKeyAttributes(updated.keyAttributes);+ } finally {+ worker.terminate();+ }+};diff --git a/web/packages/accounts/services/password.worker.ts b/web/packages/accounts/services/password.worker.tsnew file mode 100644index 0000000000..aaaef37224--- /dev/null+++ b/web/packages/accounts/services/password.worker.ts@@ -0,0 +1,53 @@+import { expose } from "comlink";+import { logUnhandledErrorsAndRejectionsInWorker } from "ente-base/log-web";+import { deriveSensitiveKey, encryptBox } from "ente-prelogin-wasm";+import { ensure } from "ente-utils/ensure";+import { generateInteractiveKeyAttributes } from "./key-attributes";+import {+ generateSRPSetupAttributes,+ getSRPAttributes,+ updateSRPAndKeyAttributes,+} from "./srp";+import type { KeyAttributes } from "./user";++export class PasswordWorker {+ async changePassword(+ password: string,+ masterKey: string,+ keyAttributes: KeyAttributes,+ email: string,+ ) {+ const {+ key: kek,+ salt: kekSalt,+ opsLimit,+ memLimit,+ } = await deriveSensitiveKey(password);+ const { encryptedData: encryptedKey, nonce: keyDecryptionNonce } =+ await encryptBox(masterKey, kek);+ const updatedKeyAttr = {+ encryptedKey,+ keyDecryptionNonce,+ kekSalt,+ opsLimit,+ memLimit,+ };++ await updateSRPAndKeyAttributes(+ await generateSRPSetupAttributes(kek),+ updatedKeyAttr,+ );++ const srpAttributes = ensure(await getSRPAttributes(email));+ const interactiveKeyAttributes = await generateInteractiveKeyAttributes(+ password,+ { ...keyAttributes, ...updatedKeyAttr },+ masterKey,+ );+ return { srpAttributes, keyAttributes: interactiveKeyAttributes };+ }+}++expose(PasswordWorker);++logUnhandledErrorsAndRejectionsInWorker();diff --git a/web/packages/accounts/services/srp.ts b/web/packages/accounts/services/srp.tsindex 6a718e75a5..c32498c948 100644--- a/web/packages/accounts/services/srp.ts+++ b/web/packages/accounts/services/srp.ts@@ -142,7 +142,7 @@ const completeSRPSetup = async ({export const getAndSaveSRPAttributes = async (userEmail: string) =>saveSRPAttributes(ensure(await getSRPAttributes(userEmail)));-export interface UpdatedKeyAttr {+interface UpdatedKeyAttr {kekSalt: string;encryptedKey: string;keyDecryptionNonce: string;diff --git a/web/packages/accounts/services/user.ts b/web/packages/accounts/services/user.tsindex c0f5c6e8bb..ae96d0f81e 100644--- a/web/packages/accounts/services/user.ts+++ b/web/packages/accounts/services/user.ts@@ -9,20 +9,13 @@ import {import {boxSealOpenBytes,decryptBox,- deriveInteractiveKey,deriveSensitiveKey,encryptBox,generateKey,generateKeyPair,toB64URLSafe,} from "ente-accounts/services/crypto";-import { ensureMasterKeyFromSession } from "ente-accounts/services/prelogin-session";-import {- generateSRPSetupAttributes,- getAndSaveSRPAttributes,- updateSRPAndKeyAttributes,- type UpdatedKeyAttr,-} from "ente-accounts/services/srp";+import { generateInteractiveKeyAttributes } from "ente-accounts/services/key-attributes";import {authenticatedRequestHeaders,ensureOk,@@ -276,24 +269,11 @@ export const generateAndSaveInteractiveKeyAttributes = async (keyAttributes: KeyAttributes,key: string,): Promise<KeyAttributes> => {- const {- key: interactiveKEK,- salt: kekSalt,- opsLimit,- memLimit,- } = await deriveInteractiveKey(password);-- const { encryptedData: encryptedKey, nonce: keyDecryptionNonce } =- await encryptBox(key, interactiveKEK);-- const interactiveKeyAttributes = {- ...keyAttributes,- encryptedKey,- keyDecryptionNonce,- kekSalt,- opsLimit,- memLimit,- };+ const interactiveKeyAttributes = await generateInteractiveKeyAttributes(+ password,+ keyAttributes,+ key,+ );saveKeyAttributes(interactiveKeyAttributes);return interactiveKeyAttributes;};@@ -312,42 +292,6 @@ const postChangeEmail = async (email: string, ott: string) =>}),);-export const changePassword = async (password: string) => {- const user = ensureLocalUser();- const masterKey = await ensureMasterKeyFromSession();- const keyAttributes = ensureSavedKeyAttributes();-- const {- key: kek,- salt: kekSalt,- opsLimit,- memLimit,- } = await deriveSensitiveKey(password);-- const { encryptedData: encryptedKey, nonce: keyDecryptionNonce } =- await encryptBox(masterKey, kek);- const updatedKeyAttr: UpdatedKeyAttr = {- encryptedKey,- keyDecryptionNonce,- kekSalt,- opsLimit,- memLimit,- };-- await updateSRPAndKeyAttributes(- await generateSRPSetupAttributes(kek),- updatedKeyAttr,- );-- await getAndSaveSRPAttributes(user.email);-- await generateAndSaveInteractiveKeyAttributes(- password,- { ...keyAttributes, ...updatedKeyAttr },- masterKey,- );-};-export const resetSavedLocalUserTokens = async (userID: number,encryptedToken: string,diff --git a/web/packages/base/session-storage.ts b/web/packages/base/session-storage.tsindex c288873572..2bb2116b3c 100644--- a/web/packages/base/session-storage.ts+++ b/web/packages/base/session-storage.ts@@ -17,7 +17,7 @@ const SessionKeyData = z.object({type SessionKeyData = z.infer<typeof SessionKeyData>;-interface SessionStorageCrypto {+export interface SessionStorageCrypto {decryptBox: (box: { encryptedData: string; nonce: string },key: string,diff --git a/web/packages/wasm/space/index.ts b/web/packages/wasm/space/index.tsindex 3f638e1581..d184731a08 100644--- a/web/packages/wasm/space/index.ts+++ b/web/packages/wasm/space/index.ts@@ -1,4 +1,5 @@import type {+ EncryptedBox,OpenAccountSpaceCtxInput,OpenSpaceLinkCtxInput,SpaceAccountCtxHandle,@@ -22,15 +23,13 @@ export type {const wasm = () => import("./pkg/ente_space_wasm");-export const encryptSpaceRootEntityKey = async (- spaceRootKeyB64: string,- masterKeyB64: string,-) => (await wasm()).encryptSpaceRootEntityKey(spaceRootKeyB64, masterKeyB64);+export const generateKey = async () => (await wasm()).cryptoGenerateKey();-export const decryptSpaceRootEntityKey = async (- encryptedKeyB64: string,- masterKeyB64: string,-) => (await wasm()).decryptSpaceRootEntityKey(encryptedKeyB64, masterKeyB64);+export const encryptBox = async (dataB64: string, keyB64: string) =>+ (await wasm()).cryptoEncryptBox(dataB64, keyB64);++export const decryptBox = async (box: EncryptedBox, keyB64: string) =>+ (await wasm()).cryptoDecryptBox(box.encryptedData, box.nonce, keyB64);export const openSpaceAccountContext = async (input: OpenAccountSpaceCtxInput,