π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
Remove vendored accounts code from albums app
Anand Baburajan9cbaef342620
diff --git a/web/apps/albums/package.json b/web/apps/albums/package.jsonindex 78204c6ce0..6d51284f8f 100644--- a/web/apps/albums/package.json+++ b/web/apps/albums/package.json@@ -13,14 +13,12 @@"@mui/material": "^7.3.4","@mui/system": "^7.3.3","@mui/x-date-pickers": "^8.14.0",- "bip39": "^3.1.0","bs58": "^6.0.0","chrono-node": "^2.9.0","comlink": "^4.4.2","dayjs": "^1.11.18","debounce": "^2.2.0","exifreader": "^4.32.0",- "fast-srp-hap": "^2.0.4","file-type": "21.3.1","formik": "^2.4.6","get-user-locale": "^3.0.0",@@ -53,7 +51,6 @@"sanitize-filename": "^1.6.3","similarity-transformation": "^0.0.1","supercluster": "^8.0.1",- "uuid": "^13.0.0","zod": "^4.1.12"},"devDependencies": {diff --git a/web/apps/albums/vendor/ente-accounts/components/layouts/centered-paper.tsx b/web/apps/albums/src/components/AccountsPage.tsxsimilarity index 65%rename from web/apps/albums/vendor/ente-accounts/components/layouts/centered-paper.tsxrename to web/apps/albums/src/components/AccountsPage.tsxindex 521707f864..078da3ec53 100644--- a/web/apps/albums/vendor/ente-accounts/components/layouts/centered-paper.tsx+++ b/web/apps/albums/src/components/AccountsPage.tsx@@ -3,19 +3,6 @@ import { CenteredFill } from "ente-base/components/containers";import { EnteLogo } from "ente-base/components/EnteLogo";import { NavbarBase } from "ente-base/components/Navbar";-/**- * An ad-hoc component that abstracts the layout common to many of the pages- * exported by the the accounts package.- *- * The layout is roughly:- * - Set height to 100vh- * - An app bar at the top- * - Center a {@link Paper} in the rest of the space.- * - The children passed to this component go within this {@link Paper}.- *- * {@link AccountsPageTitle} and {@link AccountsPageFooter} are meant to be used- * in tandem with, as children of, {@link AccountsPageContents}.- */export const AccountsPageContents: React.FC<React.PropsWithChildren> = ({children,}) => (@@ -69,20 +56,3 @@ export const AccountsPageTitle: React.FC<React.PropsWithChildren> = ({{children}</Typography>);--export const AccountsPageFooter: React.FC<React.PropsWithChildren> = ({- children,-}) => (- <Stack- direction="row"- sx={{- mx: "4px",- // Put the items to the side,- justifyContent: "space-between",- // Unless there is just one, in which case center it.- "& :only-child": { marginInline: "auto" },- }}- >- {children}- </Stack>-);diff --git a/web/apps/albums/src/pages/index.tsx b/web/apps/albums/src/pages/index.tsxindex 280692c051..9c2d42019d 100644--- a/web/apps/albums/src/pages/index.tsx+++ b/web/apps/albums/src/pages/index.tsx@@ -25,10 +25,6 @@ import { FileListWithViewer } from "components/FileListWithViewer";import { PublicAlbumSingleFileViewer } from "components/PublicAlbumSingleFileViewer";import { TripLayout } from "components/TripLayout";import { Upload } from "components/Upload";-import {- AccountsPageContents,- AccountsPageTitle,-} from "ente-accounts/components/layouts/centered-paper";import { SpacedRow, Stack100vhCenter } from "ente-base/components/containers";import { EnteLogo } from "ente-base/components/EnteLogo";import {@@ -105,6 +101,10 @@ import { t } from "i18next";import { useRouter } from "next/router";import { useCallback, useEffect, useMemo, useRef, useState } from "react";import { type FileWithPath } from "react-dropzone";+import {+ AccountsPageContents,+ AccountsPageTitle,+} from "../components/AccountsPage";import { uploadManager } from "services/upload-manager";import { getSelectedFiles, type SelectedState } from "utils/file";import { getEnteURL } from "utils/public-album";diff --git a/web/apps/albums/tsconfig.json b/web/apps/albums/tsconfig.jsonindex 95895cf067..d3f5405c2e 100644--- a/web/apps/albums/tsconfig.json+++ b/web/apps/albums/tsconfig.json@@ -27,7 +27,6 @@"services/*": ["vendor/photos/services/*"],"utils/*": ["vendor/photos/utils/*"],"styles/*": ["vendor/photos/styles/*"],- "ente-accounts/*": ["vendor/ente-accounts/*"],"ente-base/*": ["vendor/ente-base/*"],"ente-gallery/*": ["vendor/ente-gallery/*"],"ente-media/*": ["vendor/ente-media/*"],diff --git a/web/apps/albums/vendor/ente-accounts/services/accounts-db.ts b/web/apps/albums/vendor/ente-accounts/services/accounts-db.tsdeleted file mode 100644index a1b6214674..0000000000--- a/web/apps/albums/vendor/ente-accounts/services/accounts-db.ts+++ /dev/null@@ -1,460 +0,0 @@-/**- * @file [Note: Accounts DB]- *- * The accounts package stores various state both during the login / signup- * flow, and post login to identify the logged in user.- *- * This state is stored in local storage.- *- * Most of this state is meant to be transitory - various bits and bobs that we- * accumulate and want to persist as the user goes through the login or signup- * flow. One the user is successfully logged in and the first pull has- * completed, then only a few of these are expected to remain:- *- * - "user"- * - "keyAttributes"- * - "originalKeyAttributes"- * - "srpAttributes"- */--import { savedAuthToken } from "ente-base/token";-import { nullToUndefined } from "ente-utils/transform";-import { z } from "zod";-import {- RemoteSRPAttributes,- SRPSetupAttributes,- type SRPAttributes,-} from "./srp";-import {- RemoteKeyAttributes,- type KeyAttributes,- type LocalUser,-} from "./user";--/**- * The local storage data about the user before login or signup is complete.- *- * [Note: Partial local user]- *- * During login or signup, the user object exists in various partial states in- * local storage.- *- * - Initially, there is no user object in local storage.- *- * - When the user enters their email, the email property of the stored object- * is set, but nothing else.- *- * - After they verify their password, we have two cases: if second factor- * verification is not set, and when it is set.- *- * - If second factor verification is not set, then after verifying their- * password their {@link id} and {@link encryptedToken} will get filled in,- * and {@link isTwoFactorEnabled} will be set to false.- *- * - If they have second factor verification set, then after verifying their- * password {@link isTwoFactorEnabled} and {@link twoFactorSessionID} will- * also get filled in. Once they verify their TOTP based second factor, their- * {@link id} and {@link encryptedToken} will also get filled in.- *- * - If they have a passkey set as a second factor set, then after verifying- * their password the {@link passkeySessionID} will be set.- *- * - As the login or signup sequence completes, a {@link token} obtained from- * the {@link encryptedToken} will be written out, and the- * {@link encryptedToken} cleared since it is not needed anymore.- *- * So while the underlying storage is the same, we offer two APIs for code to- * obtain the user:- *- * - Before login is complete, or when it is unknown if login is complete or- * not, then {@link savedPartialLocalUser} can be used to obtain a- * {@link PartialLocalUser} with all of its properties set to be optional (and- * some additional properties not available in the regular user object).- *- * - When we know that the login has completed, we can use either- * {@link savedLocalUser} (which returns `undefined` if our assumption is- * false) or {@link ensureSavedLocalUser} (which throws if our assumption is- * false) to obtain an object with all the properties expected to be present- * for a locally persisted user set to be required.- */-export interface PartialLocalUser {- id?: number;- email?: string;- token?: string;- encryptedToken?: string;- isTwoFactorEnabled?: boolean;- twoFactorSessionID?: string;- passkeySessionID?: string;-}--const PartialLocalUser = z.object({- id: z.number().nullish().transform(nullToUndefined),- email: z.string().nullish().transform(nullToUndefined),- token: z.string().nullish().transform(nullToUndefined),- encryptedToken: z.string().nullish().transform(nullToUndefined),- isTwoFactorEnabled: z.boolean().nullish().transform(nullToUndefined),- twoFactorSessionID: z.string().nullish().transform(nullToUndefined),- passkeySessionID: z.string().nullish().transform(nullToUndefined),-});--/**- * Zod schema for the {@link LocalUser} TypeScript type.- *- * The type itself is in `user.ts`.- */-const LocalUser = z.object({- id: z.number(),- email: z.string(),- token: z.string(),- isTwoFactorEnabled: z.boolean().nullish().transform(nullToUndefined),-});--/**- * Return the local storage value of the user's data.- *- * This function is meant to be called during the login or signup sequence.- * After the user is logged in, use {@link savedLocalUser} or- * {@link ensureLocalUser} instead.- *- * Use {@link replaceSavedLocalUser} to updated the saved value.- */-export const savedPartialLocalUser = (): PartialLocalUser | undefined => {- const jsonString = localStorage.getItem("user");- if (!jsonString) return undefined;- const result = PartialLocalUser.parse(JSON.parse(jsonString));- void ensureTokensMatch(result);- return result;-};--/**- * Save the users data as we accrue it during the signup or login flow.- *- * See: [Note: Partial local user].- *- * This method replaces the existing data. Use {@link updateSavedLocalUser} to- * update selected fields while keeping the other fields as it is.- */-export const replaceSavedLocalUser = (partialLocalUser: PartialLocalUser) =>- localStorage.setItem("user", JSON.stringify(partialLocalUser));--/**- * Partially update the saved user data.- *- * This is a delta variant of {@link replaceSavedLocalUser}, which replaces the- * entire saved object, while this function spreads the provided {@link updates}- * onto the currently saved value.- *- * @param updates A subset of {@link PartialLocalUser} fields that we'd like to- * update. The other fields, if present in local storage, remain unchanged.- */-export const updateSavedLocalUser = (updates: Partial<PartialLocalUser>) =>- replaceSavedLocalUser({ ...savedPartialLocalUser(), ...updates });--/**- * Return data about the logged-in user, if someone is indeed logged in.- * Otherwise return `undefined`.- *- * The user's data is stored in the browser's localStorage. Thus, this function- * only works from the main thread, not from web workers since local storage is- * not accessible to web workers.- *- * There is no setter corresponding to this function since this is only a view- * on data saved using {@link replaceSavedLocalUser} or- * {@link updateSavedLocalUser}.- *- * See: [Note: Partial local user] for more about the whole shebang.- */-export const savedLocalUser = (): LocalUser | undefined => {- const jsonString = localStorage.getItem("user");- if (!jsonString) return undefined;- // We might have some data, but not all of it. So do a non-throwing parse.- const { success, data } = LocalUser.safeParse(JSON.parse(jsonString));- if (success) void ensureTokensMatch(data);- return success ? data : undefined;-};--/**- * Sanity check to ensure that KV token and local storage token are the same.- *- * TODO: Added July 2025, can just be removed soon, there is already a sanity- * check `isLocalStorageAndIndexedDBMismatch` on app start (tag: Migration).- */-export const ensureTokensMatch = async (user: PartialLocalUser | undefined) => {- if (user?.token !== (await savedAuthToken())) {- throw new Error("Token mismatch");- }-};--/**- * Return true if the user's data is in local storage but not in IndexedDB.- *- * This acts a sanity check on IndexedDB by ensuring that if the user has a- * token in local storage, then it should also be present in IndexedDB.- */-export const isLocalStorageAndIndexedDBMismatch = async () =>- savedPartialLocalUser()?.token && !(await savedAuthToken());--/**- * Return the user's {@link KeyAttributes} if they are present in local storage.- *- * The key attributes are stored in the browser's localStorage. Thus, this- * function only works from the main thread, not from web workers (local storage- * is not accessible to web workers).- *- * See also: [Note: Original vs interactive key attributes]- */-export const savedKeyAttributes = (): KeyAttributes | undefined => {- const jsonString = localStorage.getItem("keyAttributes");- if (!jsonString) return undefined;- return RemoteKeyAttributes.parse(JSON.parse(jsonString));-};--/**- * Save the user's {@link KeyAttributes} in local storage.- *- * Use {@link savedKeyAttributes} to retrieve them.- */-export const saveKeyAttributes = (keyAttributes: KeyAttributes) =>- localStorage.setItem("keyAttributes", JSON.stringify(keyAttributes));--/**- * Return the user's original {@link KeyAttributes} if they are present in local- * storage.- *- * [Note: Original vs interactive key attributes]- *- * This function is similar to {@link savedKeyAttributes} except it returns the- * user's "original" key attributes. These are the key attributes that were- * either freshly generated (if the user signed up on this client) or were- * fetched from remote (otherwise).- *- * > NOTE: Currently the code does not guarantee that savedOriginalKeyAttributes- * > will always be set when savedKeyAttributes is set.- *- * In contrast, the regular key attributes get overwritten by the local only- * interactive key attributes for the user's convenience. See the documentation- * of {@link generateAndSaveInteractiveKeyAttributes} for more details.- */-export const savedOriginalKeyAttributes = (): KeyAttributes | undefined => {- const jsonString = localStorage.getItem("originalKeyAttributes");- if (!jsonString) return undefined;- return RemoteKeyAttributes.parse(JSON.parse(jsonString));-};--/**- * Save the user's {@link KeyAttributes} in local storage.- *- * Once saved, these values are not replaced (in contrast with the regular key- * attributes which can get overwritten with interactive ones).- *- * Use {@link savedOriginalKeyAttributes} to retrieve them.- */-export const saveOriginalKeyAttributes = (keyAttributes: KeyAttributes) =>- localStorage.setItem(- "originalKeyAttributes",- JSON.stringify(keyAttributes),- );--/**- * Return the user's {@link SRPAttributes} if they are present in local storage.- *- * Like key attributes, SRP attributes are also stored in the browser's local- * storage so will not be accessible to web workers.- */-export const savedSRPAttributes = (): SRPAttributes | undefined => {- const jsonString = localStorage.getItem("srpAttributes");- if (!jsonString) return undefined;- return RemoteSRPAttributes.parse(JSON.parse(jsonString));-};--/**- * Save the user's {@link SRPAttributes} in local storage.- *- * Use {@link savedSRPAttributes} to retrieve them.- */-export const saveSRPAttributes = (srpAttributes: SRPAttributes) =>- localStorage.setItem("srpAttributes", JSON.stringify(srpAttributes));--/**- * Save {@link SRPSetupAttributes} in local storage for later use via- * {@link unstashAfterUseSRPSetupAttributes}.- *- * See: [Note: SRP setup attributes]- */-export const stashSRPSetupAttributes = (- srpSetupAttributes: SRPSetupAttributes,-) =>- localStorage.setItem(- "srpSetupAttributes",- JSON.stringify(srpSetupAttributes),- );--/**- * Retrieve the {@link SRPSetupAttributes}, if any, that were stashed by a- * previous call to {@link stashSRPSetupAttributes}.- *- * - If they are found, then invoke the provided callback ({@link cb}) with the- * value. If the promise returned by the callback fulfills, then remove the- * stashed value from local storage.- *- * - If they are not found, then the callback is not invoked.- */-export const unstashAfterUseSRPSetupAttributes = async (- cb: (srpSetupAttributes: SRPSetupAttributes) => Promise<void>,-) => {- const jsonString = localStorage.getItem("srpSetupAttributes");- if (!jsonString) return;- const srpSetupAttributes = SRPSetupAttributes.parse(JSON.parse(jsonString));- await cb(srpSetupAttributes);- localStorage.removeItem("srpSetupAttributes");-};--/**- * Zod schema for the legacy format in which the {@link savedIsFirstLogin} and- * {@link savedJustSignedUp} flags were saved in local storage.- *- * Starting 1.7.15-beta (July 2025), we started saving the booleans directly,- * but when reading we fallback to the old format if needed. This fallback can- * be removed, and soonish, since these are transient flags that are saved- * during the login / signup sequence and wouldn't be expected to remain in the- * user's local storage for long anyway. (tag: Migration).- */-const LocalLegacyBooleanFlag = z.object({- status: z.boolean().nullish().transform(nullToUndefined),-});--/**- * Return `true` if it is the user's first login on this client.- *- * The {@link savedIsFirstLogin} flag is saved in local storage (using- * {@link saveIsFirstLogin}) if we determine during the login flow that it a- * fresh login on this client. If so, we- *- * - Generate interactive key attributes for them, and- *- * - Display them a special indicator post login to notify them that the first- * load might take extra time. At this point, we also clear the flag (the read- * and clear is done by the same {@link getAndClearIsFirstLogin} function).- */-export const savedIsFirstLogin = () => {- const jsonString = localStorage.getItem("isFirstLogin");- if (!jsonString) return false;- try {- return z.boolean().parse(JSON.parse(jsonString));- } catch {- return (- LocalLegacyBooleanFlag.parse(JSON.parse(jsonString)).status ?? false- );- }-};--/**- * Save a flag in local storage to indicate that this is the user's first login- * on this client.- *- * This is the setter corresponding to {@link savedIsFirstLogin}.- */-export const saveIsFirstLogin = () => {- localStorage.setItem("isFirstLogin", JSON.stringify({ status: true }));-};--/**- * Get the saved value of the local storage flag that indicates that this is the- * user' first login on this client. Also remove the flag after reading.- *- * The flag can be set by using {@link saveIsFirstLogin}, and can be read- * without clearing it by using {@link savedIsFirstLogin}.- */-export const getAndClearIsFirstLogin = () => {- // Completely unrelated, but since this code runs on each /gallery load, use- // this as a chance to remove the unused "showBackButton" property saved in- // local storage. This code was added 1.7.15-beta (July 2025) and can be- // removed after a while, soonish (tag: Migration).- localStorage.removeItem("showBackButton");-- const result = savedIsFirstLogin();- localStorage.removeItem("isFirstLogin");- return result;-};--/**- * Return `true` if the user created a new account on this client during the- * current (in-progress) or just completed login / signup sequence.- */-export const savedJustSignedUp = () => {- const jsonString = localStorage.getItem("justSignedUp");- if (!jsonString) return false;- try {- return z.boolean().parse(JSON.parse(jsonString));- } catch {- return (- LocalLegacyBooleanFlag.parse(JSON.parse(jsonString)).status ?? false- );- }-};--/**- * Save a flag in local storage to indicate that the user signed up for a- * new Ente account during the current login / signup sequence.- *- * This is the setter corresponding to {@link savedJustSignedUp}.- */-export const saveJustSignedUp = () => {- localStorage.setItem("justSignedUp", JSON.stringify({ status: true }));-};--/**- * Get the saved value of the local storage flag that indicates that the user just- * signed up. Also remove the flag from local storage after reading.- *- * The flag can be set by using {@link saveJustSignedUp}, and can be read- * without clearing it by using {@link savedJustSignedUp}.- */-export const getAndClearJustSignedUp = () => {- const result = savedJustSignedUp();- localStorage.removeItem("justSignedUp");- return result;-};--/**- * Zod schema for the format in which the {@link stashReferralSource} used to- * saved the referral source in local storage.- *- * Starting 1.7.15-beta (July 2025), we started saving the string directly, but- * when reading we fallback to the old format if needed. This fallback can be- * removed, and soonish, since these is a transient value that isn't expected to- * remain in the user's local storage for long anyway. (tag: Migration).- */-const LocalLegacyReferralSource = z.object({ source: z.string() });--/**- * Save the referral source entered by the user on the signup screen in local- * storage.- *- * The saved value can be retrieved post email verification using- * {@link unstashReferralSource}.- */-export const stashReferralSource = (referralSource: string) => {- localStorage.setItem("referralSource", referralSource);-};--/**- * Retrieve the previously saved referral source (using- * {@link stashReferralSource}), returning the saved value and also clearing it- * from local storage.- */-export const unstashReferralSource = () => {- const jsonString = localStorage.getItem("referralSource");- if (!jsonString) return undefined;- localStorage.removeItem("referralSource");- try {- // Try the old format first. The trim is also a legacy expectation and- // can be removed when we remove this fallfront.- return LocalLegacyReferralSource.parse(- JSON.parse(jsonString),- ).source.trim();- } catch {- // Otherwise try the new format.- return jsonString;- }-};diff --git a/web/apps/albums/vendor/ente-accounts/services/passkey.ts b/web/apps/albums/vendor/ente-accounts/services/passkey.tsdeleted file mode 100644index c2803d4d70..0000000000--- a/web/apps/albums/vendor/ente-accounts/services/passkey.ts+++ /dev/null@@ -1,280 +0,0 @@-import {- saveKeyAttributes,- updateSavedLocalUser,-} from "ente-accounts/services/accounts-db";-import {- resetSavedLocalUserTokens,- TwoFactorAuthorizationResponse,-} from "ente-accounts/services/user";-import { clientPackageName, isDesktop } from "ente-base/app";-import { encryptBox, generateKey } from "ente-base/crypto";-import {- authenticatedRequestHeaders,- ensureOk,- HTTPError,- publicRequestHeaders,-} from "ente-base/http";-import { apiURL } from "ente-base/origins";-import { z } from "zod";-import { getUserRecoveryKey } from "./recovery-key";-import { unstashRedirect } from "./redirect";--/**- * Construct a redirect URL to take the user to Ente accounts app to- * authenticate using their second factor, a passkey they've configured.- *- * On successful verification, the accounts app will redirect back to our- * `/passkeys/finish` page.- *- * @param accountsURL The URL for the accounts app (provided to us by remote in- * the email or SRP verification response).- *- * @param passkeySessionID An identifier provided by museum for this passkey- * verification session.- */-export const passkeyVerificationRedirectURL = (- accountsURL: string,- passkeySessionID: string,-) => {- const clientPackage = clientPackageName;- // Using `window.location.origin` will work both when we're running in a web- // browser, and in our desktop app. See: [Note: Using deeplinks to navigate- // in desktop app]- const redirect = `${window.location.origin}/passkeys/finish`;- // See: [Note: Conditional passkey recover option on accounts]- const recoverOption: Record<string, string> = isDesktop- ? {}- : { recover: `${window.location.origin}/passkeys/recover` };- const params = new URLSearchParams({- clientPackage,- passkeySessionID,- redirect,- ...recoverOption,- });- return `${accountsURL}/passkeys/verify?${params.toString()}`;-};--interface OpenPasskeyVerificationURLOptions {- /**- * The passkeySessionID for which we are redirecting.- *- * This is compared to the saved session id in the browser's session storage- * to allow us to ignore redirects to the passkey flow finish page except- * the ones for this specific session we're awaiting.- */- passkeySessionID: string;- /** The URL to redirect to or open in the system browser. */- url: string;-}--/**- * Open or redirect to a passkey verification URL previously constructed using- * {@link passkeyVerificationRedirectURL}.- *- * [Note: Passkey verification in the desktop app]- *- * Our desktop app bundles the web app and serves it over a custom protocol.- * Passkeys are tied to origins, and will not work with this custom protocol- * even if we move the passkey creation and authentication inline to within the- * Photos web app.- *- * Thus, passkey creation and authentication in the desktop app works the same- * way it works in the mobile app - the system browser is invoked to open- * accounts.ente.io.- *- * - For passkey creation, this is a one-way open. Passkeys get created at- * accounts.ente.io, and that's it.- *- * - For passkey verification, the flow is two-way. We register a custom- * protocol and provide that as a return path redirect. Passkey authentication- * happens at accounts.ente.io, and on success there is redirected back to the- * desktop app.- */-export const openPasskeyVerificationURL = ({- passkeySessionID,- url,-}: OpenPasskeyVerificationURLOptions) => {- sessionStorage.setItem("inflightPasskeySessionID", passkeySessionID);-- if (globalThis.electron) window.open(url);- else window.location.href = url;-};--/**- * Open a new window showing a page on the Ente accounts app where the user can- * see and their manage their passkeys.- */-export const openAccountsManagePasskeysPage = async () => {- // Check if the user has passkey recovery enabled.- const { isPasskeyRecoveryEnabled } = await getTwoFactorRecoveryStatus();- if (!isPasskeyRecoveryEnabled) {- // If not, enable it for them by creating the necessary recovery- // information to prevent them from getting locked out.- const resetSecret = await generateKey();- const { encryptedData, nonce } = await encryptBox(- resetSecret,- await getUserRecoveryKey(),- );- await configurePasskeyRecovery(resetSecret, encryptedData, nonce);- }-- // Redirect to the Ente Accounts app where they can view and add and manage- // their passkeys.- const { accountsToken: token, accountsUrl: accountsURL } =- await getAccountsTokenAndURL();- const params = new URLSearchParams({ token });-- window.open(`${accountsURL}/passkeys?${params.toString()}`);-};--const TwoFactorRecoveryStatus = z.object({- /**- * `true` if the passkey recovery setup has been completed.- */- isPasskeyRecoveryEnabled: z.boolean(),-});--/**- * Obtain the second factor recovery status from remote.- */-export const getTwoFactorRecoveryStatus = async () => {- const res = await fetch(await apiURL("/users/two-factor/recovery-status"), {- headers: await authenticatedRequestHeaders(),- });- ensureOk(res);- return TwoFactorRecoveryStatus.parse(await res.json());-};--/**- * Allow the user to bypass their passkeys by saving the provided recovery- * credentials on remote.- */-const configurePasskeyRecovery = async (- secret: string,- userSecretCipher: string,- userSecretNonce: string,-) =>- ensureOk(- await fetch(- await apiURL("/users/two-factor/passkeys/configure-recovery"),- {- method: "POST",- headers: await authenticatedRequestHeaders(),- body: JSON.stringify({- secret,- userSecretCipher,- userSecretNonce,- }),- },- ),- );--/**- * Fetch an Ente Accounts specific JWT token.- *- * This token can be used to authenticate with the Ente accounts app running at- * accountsURL (the result contains both pieces of information).- */-const getAccountsTokenAndURL = async () => {- const res = await fetch(await apiURL("/users/accounts-token"), {- headers: await authenticatedRequestHeaders(),- });- ensureOk(res);- return z- .object({- // The origin that serves the accounts app.- accountsUrl: z.string(),- // A token that can be used to authenticate with the accounts app.- accountsToken: z.string(),- })- .parse(await res.json());-};--/**- * The passkey session whose status we are trying to check has already expired.- * The user should attempt to login again.- */-export const passkeySessionExpiredErrorMessage = "Passkey session has expired";--/**- * Check if the user has already authenticated using their passkey for the given- * session.- *- * This is useful in case the automatic redirect back from accounts.ente.io to- * the desktop app does not work for some reason. In such cases, the user can- * press the "Check status" button: we'll make an API call to see if the- * authentication has already completed, and if so, get the same "response"- * object we'd have gotten as a query parameter in a redirect in- * {@link saveCredentialsAndNavigateTo} on the "/passkeys/finish" page.- *- * @param sessionID The passkey session whose session we wish to check the- * status of.- *- * @returns A {@link TwoFactorAuthorizationResponse} if the passkey- * authentication has completed, and `undefined` otherwise.- *- * @throws In addition to arbitrary errors, it throws errors with the message- * {@link passkeySessionExpiredErrorMessage}.- */-export const checkPasskeyVerificationStatus = async (- sessionID: string,-): Promise<TwoFactorAuthorizationResponse | undefined> => {- const res = await fetch(- await apiURL("/users/two-factor/passkeys/get-token", { sessionID }),- { headers: publicRequestHeaders() },- );- if (!res.ok) {- if (res.status == 404 || res.status == 410)- throw new Error(passkeySessionExpiredErrorMessage);- if (res.status == 400) return undefined; /* verification pending */- throw new HTTPError(res);- }- return TwoFactorAuthorizationResponse.parse(await res.json());-};--/**- * Extract credentials from a successful passkey verification response and save- * them to local storage for use by subsequent steps (or normal functioning) of- * the app.- *- * @param response The result of a successful- * {@link checkPasskeyVerificationStatus}.- *- * @returns the slug that we should navigate to now.- */-export const saveCredentialsAndNavigateTo = async (- response: TwoFactorAuthorizationResponse,-) => {- // [Note: Ending the passkey flow]- //- // The implementation of this function is similar to that of the- // `saveQueryCredentialsAndNavigateTo` on the "/passkeys/finish" page.- //- // This one, `saveCredentialsAndNavigateTo`, is used when the user presses- // the check verification status button on the page that triggered the- // passkey flow (when they're using the desktop app).- //- // The other one, `saveQueryCredentialsAndNavigateTo`, is used when the user- // goes through the passkey flow in the browser itself (when they are using- // the web app).-- clearInflightPasskeySessionID();-- const { id, encryptedToken, keyAttributes } = response;-- await resetSavedLocalUserTokens(id, encryptedToken);- updateSavedLocalUser({ passkeySessionID: undefined });- saveKeyAttributes(keyAttributes);-- return unstashRedirect() ?? "/credentials";-};--/**- * Remove the inflight passkey session ID, if any, present in session storage.- *- * This should be called whenever we get back control from the passkey app to- * clean up after ourselves.- */-export const clearInflightPasskeySessionID = () => {- sessionStorage.removeItem("inflightPasskeySessionID");-};diff --git a/web/apps/albums/vendor/ente-accounts/services/recovery-key.ts b/web/apps/albums/vendor/ente-accounts/services/recovery-key.tsdeleted file mode 100644index 3f2648ee6a..0000000000--- a/web/apps/albums/vendor/ente-accounts/services/recovery-key.ts+++ /dev/null@@ -1,116 +0,0 @@-import * as bip39 from "bip39";-import { savedKeyAttributes } from "ente-accounts/services/accounts-db";-import {- decryptBox,- encryptBox,- fromHex,- generateKey,- toHex,-} from "ente-base/crypto";-import { ensureMasterKeyFromSession } from "ente-base/session";-import { saveKeyAttributes } from "./accounts-db";-import { putUserRecoveryKeyAttributes, type KeyAttributes } from "./user";--// Mobile client library only supports English.-bip39.setDefaultWordlist("english");--/**- * Convert the provided BIP-39 mnemonic string into its base64 representation.- *- * @param recoveryKeyMnemonicOrHex The BIP-39 mnemonic (24 word) string- * representing the recovery key. For legacy compatibility, the function also- * works if provided the hex representation of the recovery key.- *- * @returns A base64 string representing the underlying bytes of the recovery key.- */-export const recoveryKeyFromMnemonic = (recoveryKeyMnemonicOrHex: string) => {- const trimmedInput = recoveryKeyMnemonicOrHex- .trim()- .split(" ")- .map((part) => part.trim())- .filter((part) => !!part)- .join(" ");-- let recoveryKeyHex: string;- // Check if user is entering mnemonic recovery key.- if (trimmedInput.indexOf(" ") > 0) {- if (trimmedInput.split(" ").length != 24) {- throw new Error("recovery code should have 24 words");- }- recoveryKeyHex = bip39.mnemonicToEntropy(trimmedInput);- } else {- recoveryKeyHex = trimmedInput;- }-- return fromHex(recoveryKeyHex);-};--/**- * Convert the provided base64 encoded recovery key into its BIP-39 mnemonic.- *- * @param recoveryKey The base64 encoded recovery key to mnemonize.- *- * @returns A 24-word mnemonic that serves as the user visible recovery key.- */-export const recoveryKeyToMnemonic = async (recoveryKey: string) =>- bip39.entropyToMnemonic(await toHex(recoveryKey));--/**- * Return the (decrypted) recovery key of the logged in user, reading it from- * local storage.- *- * As a fallback for old accounts that generated recovery keys on first view,- * this function will also generate a new recovery key if needed.- *- * @returns The user's base64 encoded recovery key.- */-export const getUserRecoveryKey = async () => {- const masterKey = await ensureMasterKeyFromSession();-- const keyAttributes = savedKeyAttributes()!;- const { recoveryKeyEncryptedWithMasterKey, recoveryKeyDecryptionNonce } =- keyAttributes;-- if (recoveryKeyEncryptedWithMasterKey && recoveryKeyDecryptionNonce) {- return decryptBox(- {- encryptedData: recoveryKeyEncryptedWithMasterKey,- nonce: recoveryKeyDecryptionNonce,- },- masterKey,- );- } else {- return createNewRecoveryKey(masterKey, keyAttributes);- }-};--/**- * Generate a new recovery key, tell remote about it, update our local state,- * and then return it.- *- * This function is meant only for (very!) old accounts for whom the app did not- * generate recovery keys on sign up but instead generated them on first view.- *- * @returns a new base64 encoded recovery key.- */-const createNewRecoveryKey = async (- masterKey: string,- existingKeyAttributes: KeyAttributes,-) => {- const recoveryKey = await generateKey();- const encryptedMasterKey = await encryptBox(masterKey, recoveryKey);- const encryptedRecoveryKey = await encryptBox(recoveryKey, masterKey);-- const recoveryKeyAttributes = {- masterKeyEncryptedWithRecoveryKey: encryptedMasterKey.encryptedData,- masterKeyDecryptionNonce: encryptedMasterKey.nonce,- recoveryKeyEncryptedWithMasterKey: encryptedRecoveryKey.encryptedData,- recoveryKeyDecryptionNonce: encryptedRecoveryKey.nonce,- };-- await putUserRecoveryKeyAttributes(recoveryKeyAttributes);-- saveKeyAttributes({ ...existingKeyAttributes, ...recoveryKeyAttributes });-- return recoveryKey;-};diff --git a/web/apps/albums/vendor/ente-accounts/services/redirect.ts b/web/apps/albums/vendor/ente-accounts/services/redirect.tsdeleted file mode 100644index 5b601c08a5..0000000000--- a/web/apps/albums/vendor/ente-accounts/services/redirect.ts+++ /dev/null@@ -1,35 +0,0 @@-import { appName } from "ente-base/app";--/**- * The default page ("home route") for each of our apps.- *- * This is where we redirect to after successful authentication.- */-export const appHomeRoute: string = {- accounts: "/passkeys",- albums: "/",- auth: "/auth",- cast: "/" /* The cast app doesn't use this, this is an arbitrary value. */,- embed: "/" /* The embed app doesn't use this either. */,- share: "/" /* The locker public app also doesn't use this. */,- photos: "/gallery",- ensu: "/",- locker: "/locker",-}[appName];--let _stashedRedirect: string | undefined;--/**- * An in-memory redirect saved during the login flow (mostly).- */-export const stashedRedirect = () => _stashedRedirect;--export const stashRedirect = (r: string) => (_stashedRedirect = r);--export const unstashRedirect = () => {- const r = _stashedRedirect;- _stashedRedirect = undefined;- return r;-};--export const clearStashedRedirect = () => (_stashedRedirect = undefined);diff --git a/web/apps/albums/vendor/ente-accounts/services/srp.ts b/web/apps/albums/vendor/ente-accounts/services/srp.tsdeleted file mode 100644index 20f58f5b83..0000000000--- a/web/apps/albums/vendor/ente-accounts/services/srp.ts+++ /dev/null@@ -1,624 +0,0 @@-import {- deriveSubKeyBytes,- generateDeriveKeySalt,- toB64,-} from "ente-base/crypto";-import {- authenticatedRequestHeaders,- ensureOk,- publicRequestHeaders,-} from "ente-base/http";-import { apiURL } from "ente-base/origins";-import { ensure } from "ente-utils/ensure";-import { SRP, SrpClient } from "fast-srp-hap";-import { v4 as uuidv4 } from "uuid";-import { z } from "zod";-import { saveSRPAttributes } from "./accounts-db";-import {- RemoteSRPVerificationResponse,- type EmailOrSRPVerificationResponse,-} from "./user";--/**- * The SRP attributes for a user.- *- * These are created by a client on signup, saved to remote. During logins, they- * are fetched from remote. In both cases they are also persisted in local- * storage (both network ops and local storage use the same schema).- *- * [Note: SRP]- *- * The SRP (Secure Remote Password) protocol is a modified Diffie-Hellman key- * exchange that allows the remote to verify the user's possession of a- * password, and the user to ensure that remote is not being impersonated,- * without the password ever leaving the device.- *- * It is used as an (user selectable) alternative to email verification.- *- * For more about the what and why, see the announcement blog post- * https://ente.io/blog/ente-adopts-secure-remote-passwords/- *- * Here we do not focus on the math (the above blog post links to reference- * material, and there is also an RFC), but instead of the various bits of- * information that get exchanged.- *- * Broadly, there are two scenarios: SRP setup, and SRP verification.- *- * [Note: SRP setup] -------------------- *- * During SRP setup, client generates- *- * 01. A SRP user ID (a new UUID-v4)- * 02. A SRP password (deterministically derived from their regular KEK)- * 03. A SRP salt (randomly generated)- *- * These 3 things are enough to create a SRP verifier and client. The SRP client- * can just be thought of an ephemeral stateful mechanism to avoid passing all- * the state accrued so far to each operation. Each time when creating a SRP- * client, the app generates a new random secret and uses it during init.- *- * 04. Compute verifier = computeSRPVerifier({ userID, password, salt })- * 05. Generates a new (ephemeral and random) clientSecret- * 06. Create client = new SRPClient({ userID, password, salt, clientSecret })- *- * The client (app) then starts the setup ceremony with remote:- *- * 07. Use SRP client to conjure secret `a` and use that to compute a public A- * 08. Send { userID, salt, verifier, A } to remote ("/users/srp/setup")- *- * Remote then:- *- * 09. Generates a new (ephemeral and random) serverSecret- * 10. Saves { userID, serverSecret, A } into SRP sessions table- * 11. Creates server = new SRPServer({ verifier, serverSecret })- * 12. Uses SRP server to conjure secret `b` and use that to compute a public B- * 13. Stashes { sessionID, userID, salt, verifier } into SRP setups table- * 14. Returns { setupID, B } to client- *- * Client then- *- * 15. Tells its SRP client about B- * 16. Computes SRP M1 (evidence message) using the SRP client- * 17. Sends { setupID, M1 } to remote ("/users/srp/complete")- *- * Remote then- *- * 18. Uses setupID to read the stashed { sessionID, verifier }- * 19. Uses sessionID to read { serverSecret, A }- * 20. Recreates server = new SRPServer({ verifier, serverSecret })- * 21. Sets server.A- * 22. Verifies M1 using the SRP server, obtaining a SRP M2 (evidence message)- * 23. Returns M2- *- * Client then- *- * 24. Verifies M2- *- * SRP setup is now complete.- *- * A similar flow is used when the user changes their password. On password- * change, a new KEK is generated, thus the SRP password also changes, and so a- * subset of the steps above are done to update both client and remote.- *- * [Note: SRP verification] ------------------------ *- * When the user is signing on a new device, the client- *- * 01. Fetches SRP attributes for a user to get { (SRP) userID, (SRP) salt }- * 02. Rederives SRP password from their KEK- * 03. Generates a new (ephemeral and random) clientSecret- * 04. Creates client = new SRPClient({ userID, password, salt, clientSecret })- * 05. Uses SRP client to conjure secret `a` and use that to compute a public A- * 06. Sends { userID, A } to remote ("/users/srp/create-session")- *- * Remote- *- * 07. Retrieves { verifier } corresponding to the userID- * 08. Generates a new (ephemeral and random) serverSecret- * 09. Saves { userID, serverSecret, A } into SRP sessions table- * 10. Creates server = new SRPServer({ verifier, serverSecret })- * 11. Sets server.A- * 12. Uses SRP server to conjure secret `b` and use that to compute a public B- * 13. Returns { sessionID, B } to client- *- * Client then- *- * 14. Sets client.B- * 15. Computes M1 (evidence message)- * 16. Sends { userID, sessionID, M1 } to remote ("/users/srp/verify-session")- *- * Remote- *- * 17. Retrieves { verifier } corresponding to the userID- * 17. Retrieves { serverSecret, A } using sessionID- * 18. Recreates server = new SRPServer({ verifier, serverSecret })- * 19. Sets server.A- * 20. Verifies M1 using the SRP server, obtaining a SRP M2 (evidence message)- * 21. Returns M2- *- * Client then- *- * 22. Verifies M2- *- * SRP verification is now complete.- */-export interface SRPAttributes {- /**- * The SRP user ID for the (Ente) user.- *- * Each Ente user gets a new randomly generated UUID v4 assigned as their- * SRP user ID during SRP setup.- */- srpUserID: string;- /**- * The SRP salt.- *- * This is a randomly generated salt created for each SRP user during SRP- * setup. It is not meant to be secret.- */- srpSalt: string;- /**- * The mem limit used during the KEK derivation from the password.- *- * See also the discussion in {@link kekSalt}.- */- memLimit: number;- /**- * The ops limit used during the KEK derivation from the password.- *- * See also the discussion in {@link kekSalt}.- */- opsLimit: number;- /**- * The salt used during the KEK derivation from the password.- *- * Base64 encoded.- *- * This is the same value as the {@link kekSalt} in {@link KeyAttributes},- * made available by remote also as part of SRP attributes for convenience.- * See: [Note: KEK three tuple] for more details.- */- kekSalt: string;- /**- * If true, then the client should use email verification instead of SRP.- */- isEmailMFAEnabled: boolean;-}--/**- * Zod schema for the {@link SRPAttributes} TypeScript type.- *- * We retain the SRP attributes response we get from remote verbatim when saving- * it to local storage, so the same schema describes both the remote type and- * the local storage type.- */-export const RemoteSRPAttributes = z.object({- srpUserID: z.string(),- srpSalt: z.string(),- memLimit: z.number(),- opsLimit: z.number(),- kekSalt: z.string(),- isEmailMFAEnabled: z.boolean(),-});--/**- * Fetch the {@link SRPAttributes} from remote for the Ente user with the- * provided email.- *- * Returns `undefined` if either there is no Ente user with the given- * {@link email}, or if there is a a user but they've not yet completed the SRP- * setup ceremony.- *- * @param email The email of the user whose SRP attributes we're fetching.- */-export const getSRPAttributes = async (- email: string,-): Promise<SRPAttributes | undefined> => {- const res = await fetch(await apiURL("/users/srp/attributes", { email }), {- headers: publicRequestHeaders(),- });- if (res.status == 404) return undefined;- ensureOk(res);- return z.object({ attributes: RemoteSRPAttributes }).parse(await res.json())- .attributes;-};--/**- * A local-only structure holding information required for SRP setup.- *- * [Note: SRP setup attributes]- *- * In some cases, there might be a step between the client having access to the- * KEK (which we need for generating the SRP attributes, in particular the SRP- * password) and the time where the client can proceed with the SRP setup (which- * can only happen once we have an auth token).- *- * For example, when the user is signing up for a new account, the client has- * the KEK on the signup screen since the user just set their password, but then- * has to redirect to the screen for email verification, and it is only after- * email verification that the client obtains an auth token and the SRP setup- * can proceed (at which point it doesn't have access to the password and so- * cannot derive the KEK).- *- * This gap is not just about different screens, but since there is an email- * verification step involved, it might take time enough for the browser tab to- * get closed and reopened. So instead of keeping the attributes we need to- * continue with the SRP setup after email verification in memory, we- * temporarily stash them in local storage using an object that conforms to the- * following {@link SRPSetupAttributes} schema.- */-export const SRPSetupAttributes = z.object({- srpUserID: z.string(),- srpSalt: z.string(),- srpVerifier: z.string(),- loginSubKey: z.string(),-});--export type SRPSetupAttributes = z.infer<typeof SRPSetupAttributes>;--/**- * Generate {@link SRPSetupAttributes} from the provided {@link kek}.- *- * @param kek The designated key encryption key (base64 encoded) for the user.- * This will be used to (deterministically) derive a SRP password.- */-export const generateSRPSetupAttributes = async (- kek: string,-): Promise<SRPSetupAttributes> => {- const loginSubKey = await deriveSRPLoginSubKey(kek);-- // Museum schema requires this to be a UUID.- const srpUserID = uuidv4();- const srpSalt = await generateDeriveKeySalt();-- const srpVerifier = bufferToB64(- SRP.computeVerifier(- SRP.params["4096"],- b64ToBuffer(srpSalt),- Buffer.from(srpUserID),- b64ToBuffer(loginSubKey),- ),- );-- return { srpUserID, srpSalt, srpVerifier, loginSubKey };-};--/**- * Derive a "login sub-key" (which is really an arbitrary binary value, not- * human generated) for use as the SRP user password by applying a deterministic- * KDF (Key Derivation Function) to the provided {@link kek}.- *- * @param kek The user's KEK (key encryption key) as a base64 string.- *- * @returns A base64 encoded key that can be used as the SRP user password.- */-const deriveSRPLoginSubKey = async (kek: string) => {- const kekSubKeyBytes = await deriveSubKeyBytes(kek, 32, 1, "loginctx");- // Use the first 16 bytes (128 bits) of the KEK's KDF subkey as the SRP- // password (instead of entire 32 bytes).- return toB64(kekSubKeyBytes.slice(0, 16));-};--const b64ToBuffer = (base64: string) => Buffer.from(base64, "base64");--const bufferToB64 = (buffer: Buffer) => buffer.toString("base64");--/**- * Use the provided {@link SRPSetupAttributes} to, well, setup SRP.- *- * See: [Note: SRP setup]- *- * @param srpSetupAttributes SRP setup attributes.- */-export const setupSRP = async (srpSetupAttributes: SRPSetupAttributes) =>- srpSetupOrReconfigure(srpSetupAttributes, completeSRPSetup);--/**- * A function that is called by {@link srpSetupOrReconfigure} to exchange the- * evidence message M1 for the evidence message M2 from remote.- *- * It is passed M1, and is expected to fulfill with M2.- */-type SRPSetupOrReconfigureExchangeCallback = ({- setupID,- srpM1,-}: {- setupID: string;- srpM1: string;-}) => Promise<{ srpM2: string }>;--/**- * Use the provided {@link SRPSetupAttributes} to either setup (afresh) or- * reconfigure SRP (when the user changes their password).- *- * The flow (described in [Note: SRP setup]) is mostly the same except the tail- * end of the process where we exchange the evidence message M1 for the evidence- * message M2 from remote. To handle this variance, we provide a callback- * {@link exchangeCB}) that is invoked at this point in the sequence.- *- * @param srpSetupAttributes SRP setup attributes.- */-const srpSetupOrReconfigure = async (- { srpSalt, srpUserID, srpVerifier, loginSubKey }: SRPSetupAttributes,- exchangeCB: SRPSetupOrReconfigureExchangeCallback,-) => {- const srpClient = await generateSRPClient(srpSalt, srpUserID, loginSubKey);-- const srpA = bufferToB64(srpClient.computeA());-- const { setupID, srpB } = await startSRPSetup({- srpUserID,- srpSalt,- srpVerifier,- srpA,- });-- srpClient.setB(b64ToBuffer(srpB));-- const srpM1 = bufferToB64(srpClient.computeM1());-- const { srpM2 } = await exchangeCB({ srpM1, setupID });-- srpClient.checkM2(b64ToBuffer(srpM2));-};--const generateSRPClient = async (- srpSalt: string,- srpUserID: string,- loginSubKey: string,-) =>- new Promise<SrpClient>((resolve, reject) => {- SRP.genKey((err, clientKey) => {- if (err) reject(err);- resolve(- new SrpClient(- SRP.params["4096"],- b64ToBuffer(srpSalt),- Buffer.from(srpUserID),- b64ToBuffer(loginSubKey),- // The random `clientKey` parameterizes the current instance- // of the SRP client.- clientKey!,- false,- ),- );- });- });--interface SetupSRPRequest {- srpUserID: string;- srpSalt: string;- srpVerifier: string;- srpA: string;-}--const SetupSRPResponse = z.object({ setupID: z.string(), srpB: z.string() });--type SetupSRPResponse = z.infer<typeof SetupSRPResponse>;--/**- * Initiate SRP setup on remote.- *- * Part of the [Note: SRP setup] sequence.- */-const startSRPSetup = async (- setupSRPRequest: SetupSRPRequest,-): Promise<SetupSRPResponse> => {- const res = await fetch(await apiURL("/users/srp/setup"), {- method: "POST",- headers: await authenticatedRequestHeaders(),- body: JSON.stringify(setupSRPRequest),- });- ensureOk(res);- return SetupSRPResponse.parse(await res.json());-};--interface CompleteSRPSetupRequest {- setupID: string;- srpM1: string;-}--const CompleteSRPSetupResponse = z.object({- setupID: z.string(),- srpM2: z.string(),-});--type CompleteSRPSetupResponse = z.infer<typeof CompleteSRPSetupResponse>;--/**- * Complete a previously initiated SRP setup on remote.- *- * Part of the [Note: SRP setup] sequence.- */-const completeSRPSetup = async (- completeSRPSetupRequest: CompleteSRPSetupRequest,-) => {- const res = await fetch(await apiURL("/users/srp/complete"), {- method: "POST",- headers: await authenticatedRequestHeaders(),- body: JSON.stringify(completeSRPSetupRequest),- });- ensureOk(res);- return CompleteSRPSetupResponse.parse(await res.json());-};--/**- * Fetch the SRP attributes from remote and use them to update the SRP- * attributes we have saved locally.- *- * This function is intended to be called after {@link srpSetupOrReconfigure} to- * also update our local state to match remote.- *- * @param userEmail The email of the user whose SRP attributes we want to fetch.- * This should be the email address of the logged in user, or the user who is- * going through the login / signup sequence currently.- */-export const getAndSaveSRPAttributes = async (userEmail: string) =>- saveSRPAttributes(ensure(await getSRPAttributes(userEmail)));--/**- * The subset of {@link KeyAttributes} that get updated when the user changes- * their password.- */-export interface UpdatedKeyAttr {- kekSalt: string;- encryptedKey: string;- keyDecryptionNonce: string;- opsLimit: number;- memLimit: number;-}--/**- * Update the user's affected key and SRP attributes when they change their- * password.- *- * The flow on changing password is similar to the flow on initial SRP setup,- * with some differences at the tail end of the flow. See: [Note: SRP setup].- *- * @param srpSetupAttributes Attributes for the user's updated SRP setup.- *- * @param updatedKeyAttr The subset of the user's key attributes which need to- * be updated to reflect their changed password.- */-export const updateSRPAndKeyAttributes = (- srpSetupAttributes: SRPSetupAttributes,- updatedKeyAttr: UpdatedKeyAttr,-) =>- srpSetupOrReconfigure(srpSetupAttributes, ({ setupID, srpM1 }) =>- updateSRPAndKeys({ setupID, srpM1, updatedKeyAttr }),- );--export interface UpdateSRPAndKeysRequest {- setupID: string;- srpM1: string;- updatedKeyAttr: UpdatedKeyAttr;- /**- * If true (default), then all existing sessions for the user will be- * invalidated.- */- logOutOtherDevices?: boolean;-}--const UpdateSRPAndKeysResponse = z.object({- srpM2: z.string(),- setupID: z.string(),-});--type UpdateSRPAndKeysResponse = z.infer<typeof UpdateSRPAndKeysResponse>;--/**- * Update the SRP attributes and a subset of the key attributes on remote.- *- * This is invoked during the flow when the user changes their password, and SRP- * needs to be reconfigured. See: [Note: SRP setup].- */-const updateSRPAndKeys = async (- updateSRPAndKeysRequest: UpdateSRPAndKeysRequest,-): Promise<UpdateSRPAndKeysResponse> => {- const res = await fetch(await apiURL("/users/srp/update"), {- method: "POST",- headers: await authenticatedRequestHeaders(),- body: JSON.stringify(updateSRPAndKeysRequest),- });- ensureOk(res);- return UpdateSRPAndKeysResponse.parse(await res.json());-};--/**- * The message of the {@link Error} that is thrown by {@link verifySRP} if- * remote fails SRP verification with a HTTP 401.- *- * The API contract allows for a SRP verification 401 both because of incorrect- * credentials or a non existent account.- */-export const srpVerificationUnauthorizedErrorMessage =- "SRP verification failed (HTTP 401 Unauthorized)";--/**- * Log the user in to a new device by performing SRP verification.- *- * This function implements the flow described in [Note: SRP verification].- *- * @param srpAttributes The user's SRP attributes.- *- * @param kek The user's key encryption key as a base64 string.- *- * @returns If SRP verification is successful, it returns a- * {@link EmailOrSRPVerificationResponse}.- *- * @throws An Error with {@link srpVerificationUnauthorizedErrorMessage} in case- * there is no such account, or if the credentials (kek) are incorrect.- */-export const verifySRP = async (- { srpUserID, srpSalt }: SRPAttributes,- kek: string,-): Promise<EmailOrSRPVerificationResponse> => {- const loginSubKey = await deriveSRPLoginSubKey(kek);- const srpClient = await generateSRPClient(srpSalt, srpUserID, loginSubKey);-- // Send A, obtain B.- const { srpB, sessionID } = await createSRPSession({- srpUserID,- srpA: bufferToB64(srpClient.computeA()),- });-- srpClient.setB(b64ToBuffer(srpB));-- // Send M1, obtain M2.- const { srpM2, ...rest } = await verifySRPSession({- sessionID,- srpUserID,- srpM1: bufferToB64(srpClient.computeM1()),- });-- srpClient.checkM2(b64ToBuffer(srpM2));-- return rest;-};--interface CreateSRPSessionRequest {- srpUserID: string;- srpA: string;-}--const CreateSRPSessionResponse = z.object({- sessionID: z.string(),- srpB: z.string(),-});--type CreateSRPSessionResponse = z.infer<typeof CreateSRPSessionResponse>;--const createSRPSession = async (- createSRPSessionRequest: CreateSRPSessionRequest,-): Promise<CreateSRPSessionResponse> => {- const res = await fetch(await apiURL("/users/srp/create-session"), {- method: "POST",- headers: publicRequestHeaders(),- body: JSON.stringify(createSRPSessionRequest),- });- ensureOk(res);- return CreateSRPSessionResponse.parse(await res.json());-};--interface VerifySRPSessionRequest {- sessionID: string;- srpUserID: string;- srpM1: string;-}--type SRPVerificationResponse = z.infer<typeof RemoteSRPVerificationResponse>;--const verifySRPSession = async (- verifySRPSessionRequest: VerifySRPSessionRequest,-): Promise<SRPVerificationResponse> => {- const res = await fetch(await apiURL("/users/srp/verify-session"), {- method: "POST",- headers: publicRequestHeaders(),- body: JSON.stringify(verifySRPSessionRequest),- });- if (res.status == 401) {- throw new Error(srpVerificationUnauthorizedErrorMessage);- }- ensureOk(res);- return RemoteSRPVerificationResponse.parse(await res.json());-};diff --git a/web/apps/albums/vendor/ente-accounts/services/user.ts b/web/apps/albums/vendor/ente-accounts/services/user.tsdeleted file mode 100644index e9e4661bef..0000000000--- a/web/apps/albums/vendor/ente-accounts/services/user.ts+++ /dev/null@@ -1,1046 +0,0 @@-import {- replaceSavedLocalUser,- savedKeyAttributes,- savedLocalUser,- savedPartialLocalUser,- saveKeyAttributes,- saveSRPAttributes,- updateSavedLocalUser,-} from "ente-accounts/services/accounts-db";-import {- generateSRPSetupAttributes,- getAndSaveSRPAttributes,- getSRPAttributes,- updateSRPAndKeyAttributes,- type UpdatedKeyAttr,-} from "ente-accounts/services/srp";-import {- boxSealOpenBytes,- decryptBox,- deriveInteractiveKey,- deriveSensitiveKey,- encryptBox,- generateKey,- generateKeyPair,- toB64URLSafe,-} from "ente-base/crypto";-import {- authenticatedRequestHeaders,- ensureOk,- publicRequestHeaders,-} from "ente-base/http";-import { apiURL } from "ente-base/origins";-import { ensureMasterKeyFromSession } from "ente-base/session";-import {- removeAuthToken,- saveAuthToken,- savedAuthToken,-} from "ente-base/token";-import { ensure } from "ente-utils/ensure";-import { nullToUndefined } from "ente-utils/transform";-import { z } from "zod";-import { clearInflightPasskeySessionID } from "./passkey";-import { getUserRecoveryKey, recoveryKeyFromMnemonic } from "./recovery-key";--/**- * The locally persisted data we have about the user after they've logged in.- *- * This type arguably belongs to accounts-db (since that's what persists it and- * its shadow alias, {@link PartialLocalUser}), but since most code that will- * need this will need this after login has completed, and will be using the- * {@link ensureLocalUser} method below, we keep this in the same file to reduce- * the need to import the type from a separate file.- */-export interface LocalUser {- /**- * The user's ID.- */- id: number;- /**- * The email associated with the user's Ente account.- */- email: string;- /**- * The user's (plaintext) auth token.- *- * It is used for making API calls on their behalf, by passing this token as- * the value of the X-Auth-Token header in the HTTP request.- *- * Usually you shouldn't be needing to access this property; instead use- * {@link savedAuthToken()} which is kept in sync with this value, and lives- * in IndexedDB and thus can also be used in web workers.- */- token: string;- /**- * `true` if the TOTP based second factor is enabled for the user.- */- isTwoFactorEnabled?: boolean;-}--/**- * Return the currently logged in {@link LocalUser}, throwing it the user is not- * logged in.- *- * This is a wrapper over the {@link savedLocalUser} function that throws if no- * one is logged in. A more appropriate name for this function, keeping in line- * with the conventions the other methods follow, would've been- * {@link ensureSavedLocalUser}. The shorter name is for readability.- */-export const ensureLocalUser = (): LocalUser =>- ensureExpectedLoggedInValue(savedLocalUser());--/**- * A function throws an error if a value that is expected to be truthy when the- * user is logged in is instead falsey.- *- * This is meant as a convenience wrapper to assert that a value we expect when- * the user is logged in is indeed there.- */-export const ensureExpectedLoggedInValue = <T>(t: T | undefined): T => {- if (!t) throw new Error("Not logged in");- return t;-};--/**- * The user's various encrypted keys and their related attributes.- *- * - Attributes to derive the KEK, the (master) key encryption key.- * - Encrypted master key (with KEK)- * - Encrypted master key (with recovery key)- * - Encrypted recovery key (with master key).- * - Public key and encrypted private key (with master key).- *- * The various "key" attributes are base64 encoded representations of the- * underlying binary data.- *- * [Note: Key attribute mutability]- *- * The key attributes contain two subsets:- *- * - Attributes that changes when the user changes their password. These are the- * {@link UpdatedKeyAttr}.- *- * - All other attributes never change after initial setup.- */-export interface KeyAttributes {- /**- * The user's master key encrypted with the key encryption key.- *- * Base64 encoded.- *- * [Note: Key encryption key]- *- * The user's master key is encrypted with a "key encryption key" (lovingly- * called a "KEK" sometimes).- *- * The KEK itself is derived from the user's password.- *- * 1. User enters password on new device.- *- * 2. Client derives KEK from this password (using the {@link kekSalt},- * {@link opsLimit} and {@link memLimit} as parameters for the- * derivation).- *- * 3. Client use KEK to decrypt the master key from {@link encryptedKey} and- * {@link keyDecryptionNonce}.- */- encryptedKey: string;- /**- * The nonce used during the encryption of the master key.- *- * Base64 encoded.- *- * @see {@link encryptedKey}.- */- keyDecryptionNonce: string;- /**- * The salt used during the derivation of the KEK.- *- * Base64 encoded.- *- * [Note: KEK three tuple]- *- * The three tuple (kekSalt, opsLimit, memLimit) is needed (along with the- * user's password) to rederive the KEK when the user logs in on a new- * client (See: [Note: Key encryption key]).- *- * The client can obtain these three by fetching their key attributes from- * remote, however unless {@link isEmailMFAEnabled} is enabled (which is not- * by default), then the user's credentials are verified using SRP instead- * of email verification. So as a convenience for this (majority) flow,- * remote also provides this exact same three tuple as part of the- * {@link SRPAttributes} fetched from remote.- *- * So on remote the KEK three tuple is the same whether it be part of key- * attributes or SRP attributes. When the user changes their password, both- * of them also get updated simulataneously (they use the same storage).- *- * However, on the client side these two sets of three tuples might diverge- * because of the client generating interactive key attributes. When that- * happens, the locally saved key attributes will be overwritten by the KEK- * three tuple for the new generated interactive KEK parameters, while the- * SRP attributes will continue to reflect the "original" KEK three tuple we- * got from remote.- */- kekSalt: string;- /**- * The operation limit used during the derivation of the KEK.- *- * The {@link opsLimit} and {@link memLimit} are complementary parameters- * that define the amount of work done by the key derivation function. See- * the {@link deriveKey}, {@link deriveSensitiveKey} and- * {@link deriveInteractiveKey} functions for more detail about them.- *- * See: [Note: Key encryption key].- */- opsLimit: number;- /**- * The memory limit used during the derivation of the KEK.- *- * See {@link opsLimit} for more details.- */- memLimit: number;- /**- * The user's public key (part of their public-key keypair, the other half- * being the {@link encryptedSecretKey}).- *- * Base64 encoded.- */- publicKey: string;- /**- * The user's private key (part of their public-key keypair, the other half- * being the {@link publicKey}) encrypted with their master key.- *- * Base64 encoded.- *- * [Note: privateKey and secretKey]- *- * The nomenclature for the key pair follows libsodium's conventions- * (https://doc.libsodium.org/public-key_cryptography/authenticated_encryption#key-pair-generation),- * who possibly chose public + secret instead of public + private to avoid- * confusion with shorthand notation (pk).- *- * However, the library author later changed their mind on this, so while- * libsodium itself (the C library) and the documentation uses "secretKey",- * the JavaScript implementation (libsodium.js) uses "privateKey".- *- * This structure uses the term "secretKey" since that is what the remote- * protocol already was based on. Within the web app codebase, we use- * "privateKey" since that is what the underlying libsodium.js uses.- */- encryptedSecretKey: string;- /**- * The nonce used during the encryption of {@link encryptedSecretKey}.- */- secretKeyDecryptionNonce: string;- /**- * The user's master key after being encrypted with their recovery key.- *- * Base64 encoded.- *- * This allows the user to recover their master key if they forget their- * password but still have their recovery key.- *- * Note: This value doesn't change after being initially created.- */- masterKeyEncryptedWithRecoveryKey?: string;- /**- * The nonce used during the encryption of- * {@link masterKeyEncryptedWithRecoveryKey}.- *- * Base64 encoded.- */- masterKeyDecryptionNonce?: string;- /**- * The user's recovery key after being encrypted with their master key.- *- * Base64 encoded.- *- * Note: This value doesn't change after being initially created.- */- recoveryKeyEncryptedWithMasterKey?: string;- /**- * The nonce used during the encryption of- * {@link recoveryKeyEncryptedWithMasterKey}.- *- * Base64 encoded.- */- recoveryKeyDecryptionNonce?: string;-}--/**- * Zod schema for {@link KeyAttributes}.- */-export const RemoteKeyAttributes = z.object({- kekSalt: z.string(),- encryptedKey: z.string(),- keyDecryptionNonce: z.string(),- publicKey: z.string(),- encryptedSecretKey: z.string(),- secretKeyDecryptionNonce: z.string(),- memLimit: z.number(),- opsLimit: z.number(),- masterKeyEncryptedWithRecoveryKey: z- .string()- .nullish()- .transform(nullToUndefined),- masterKeyDecryptionNonce: z.string().nullish().transform(nullToUndefined),- recoveryKeyEncryptedWithMasterKey: z- .string()- .nullish()- .transform(nullToUndefined),- recoveryKeyDecryptionNonce: z.string().nullish().transform(nullToUndefined),-});--/**- * A variant of {@link savedKeyAttributes} that throws if keyAttributes are not- * present in local storage.- */-export const ensureSavedKeyAttributes = (): KeyAttributes =>- ensureExpectedLoggedInValue(savedKeyAttributes());--export interface GenerateKeysAndAttributesResult {- masterKey: string;- kek: string;- keyAttributes: KeyAttributes;-}--/**- * Generate a new set of key attributes.- *- * @param password The password to use for deriving the key encryption key.- *- * @returns a newly generated master key (base64 string), kek (base64 string)- * and the key attributes associated with the combination.- */-export async function generateKeysAndAttributes(- password: string,-): Promise<GenerateKeysAndAttributesResult> {- const masterKey = await generateKey();- const recoveryKey = await generateKey();- const {- key: kek,- salt: kekSalt,- opsLimit,- memLimit,- } = await deriveSensitiveKey(password);-- const { encryptedData: encryptedKey, nonce: keyDecryptionNonce } =- await encryptBox(masterKey, kek);- const {- encryptedData: masterKeyEncryptedWithRecoveryKey,- nonce: masterKeyDecryptionNonce,- } = await encryptBox(masterKey, recoveryKey);- const {- encryptedData: recoveryKeyEncryptedWithMasterKey,- nonce: recoveryKeyDecryptionNonce,- } = await encryptBox(recoveryKey, masterKey);-- const keyPair = await generateKeyPair();- const {- encryptedData: encryptedSecretKey,- nonce: secretKeyDecryptionNonce,- } = await encryptBox(keyPair.privateKey, masterKey);-- const keyAttributes: KeyAttributes = {- encryptedKey,- keyDecryptionNonce,- kekSalt,- opsLimit,- memLimit,- publicKey: keyPair.publicKey,- encryptedSecretKey,- secretKeyDecryptionNonce,- masterKeyEncryptedWithRecoveryKey,- masterKeyDecryptionNonce,- recoveryKeyEncryptedWithMasterKey,- recoveryKeyDecryptionNonce,- };-- return { masterKey, kek, keyAttributes };-}--/**- * Update or set the user's {@link KeyAttributes} on remote.- */-export const putUserKeyAttributes = async (keyAttributes: KeyAttributes) =>- ensureOk(- await fetch(await apiURL("/users/attributes"), {- method: "PUT",- headers: await authenticatedRequestHeaders(),- body: JSON.stringify({ keyAttributes }),- }),- );--export interface RecoveryKeyAttributes {- masterKeyEncryptedWithRecoveryKey: string;- masterKeyDecryptionNonce: string;- recoveryKeyEncryptedWithMasterKey: string;- recoveryKeyDecryptionNonce: string;-}--/**- * Update the encrypted recovery key attributes for the logged in user.- *- * In practice, this is not expected to be called and is meant as a rare- * fallback for very old accounts created prior to recovery key related- * attributes being assigned on account setup. Even for these, it'll be called- * only once.- */-export const putUserRecoveryKeyAttributes = async (- recoveryKeyAttributes: RecoveryKeyAttributes,-) =>- ensureOk(- await fetch(await apiURL("/users/recovery-key"), {- method: "PUT",- headers: await authenticatedRequestHeaders(),- body: JSON.stringify(recoveryKeyAttributes),- }),- );--/**- * Ask remote to send a OTP / OTT to the given email to verify that the user has- * access to it. Subsequent the app will pass this OTT back via the- * {@link verifyOTT} method.- *- * @param email The email to verify.- *- * @param purpose In which context is the email being verified. Remote applies- * additional business rules depending on this. For example, passing the purpose- * "login" ensures that the OTT is only sent to an already registered email.- *- * In cases where the purpose is ambiguous (e.g. we're not sure if it is an- * existing login or a new signup), the purpose can be set to `undefined`.- */-export const sendOTT = async (- email: string,- purpose: "change" | "signup" | "login" | undefined,-) =>- ensureOk(- await fetch(await apiURL("/users/ott"), {- method: "POST",- headers: publicRequestHeaders(),- body: JSON.stringify({ email, purpose }),- }),- );--/**- * The response from remote on a successful user verification, either via- * {@link verifyEmail} or {@link verifySRP}.- *- * The {@link id} is always present. The rest of the values are are optional- * since only a subset of them will be returned depending on the case:- *- * 1. If the user has both passkeys and TOTP based second factor enabled, then- * the following will be set:- * - {@link passkeySessionID}, {@link accountsUrl}- * - {@link twoFactorSessionIDV2}- *- * 2. If the user has only passkeys enabled, then the following will be set:- * - {@link passkeySessionID}, {@link accountsUrl}- *- * 3. If the user has only TOTP based second factor enabled, then the following- * will be set:- * - {@link twoFactorSessionID}- *- * 4. If the user doesn't have any second factor, but has already setup their- * key attributes, then the following will be set:- * - {@link keyAttributes}- * - {@link encryptedToken}- *- * 5. Finally, in the rare case that the user has not yet setup their key- * attributes, then the following will be set:- * - {@link token}- */-export interface EmailOrSRPVerificationResponse {- /**- * The user's ID.- */- id: number;- /**- * The user's key attributes.- *- * These will be set (along with the {@link encryptedToken}) if the user- * does not have a second factor.- */- keyAttributes?: KeyAttributes;- /**- * The base64 representation of an encrypted auth token, encrypted using the- * user's public key.- *- * These will be set (along with the {@link keyAttributes}) if the user- * does not have a second factor.- */- encryptedToken?: string;- /**- * The base64 representation of an auth token.- *- * This will be set in the rare edge case for when the user has not yet- * setup their key attributes.- */- token?: string;- /**- * A session ID that can be used to complete the TOTP based second factor.- *- * This will be set if the user has enabled a TOTP based second factor but- * has not enabled passkeys.- */- twoFactorSessionID?: string;- /**- * A session ID that can be used to complete passkey verification.- *- * This will be set if the user has added a passkey to their account.- */- passkeySessionID?: string;- /**- * Base URL for the accounts app where we should redirect to for passkey- * verification.- *- * This will only be set if the user has setup a passkey (i.e., whenever- * {@link passkeySessionID} is defined).- */- accountsUrl?: string;- /**- * A session ID that can be used to complete the TOTP based second fator.- *- * This will be set in lieu of {@link twoFactorSessionID} if the user has- * setup both passkeys and TOTP based two factors are enabled for their- * account.- *- * ---- *- * Historical context: {@link twoFactorSessionIDV2} is only set if user has- * both passkey and two factor enabled. This is to ensure older clients keep- * using passkey flow when both are set. It is intended to be removed once- * all clients starts surfacing both options for performing 2FA.- *- * See also {@link useSecondFactorChoiceIfNeeded}.- */- twoFactorSessionIDV2?: string;-}--/**- * Zod schema for the {@link EmailOrSRPVerificationResponse} type.- *- * See: [Note: Duplicated Zod schema and TypeScript type]- */-const RemoteEmailOrSRPVerificationResponse = z.object({- id: z.number(),- keyAttributes: RemoteKeyAttributes.nullish().transform(nullToUndefined),- encryptedToken: z.string().nullish().transform(nullToUndefined),- token: z.string().nullish().transform(nullToUndefined),- twoFactorSessionID: z.string().nullish().transform(nullToUndefined),- passkeySessionID: z.string().nullish().transform(nullToUndefined),- accountsUrl: z.string().nullish().transform(nullToUndefined),- twoFactorSessionIDV2: z.string().nullish().transform(nullToUndefined),-});--/**- * A specialization of {@link RemoteEmailOrSRPVerificationResponse} for SRP- * verification, which results in the {@link srpM2} field in addition to the- * other ones.- *- * The declaration conceptually belongs to `srp.ts`, but is here to avoid cyclic- * dependencies.- */-export const RemoteSRPVerificationResponse = z.object({- ...RemoteEmailOrSRPVerificationResponse.shape,- /**- * The SRP M2 (evidence message), the proof that the server has the- * verifier.- */- srpM2: z.string(),-});--/**- * Verify user's access to the given {@link email} by comparing the OTT that- * remote previously sent to that email.- *- * @param email The email to verify.- *- * @param ott The OTT that the user entered.- *- * @param source During signup, we ask the user the referral "source" through- * which they heard about Ente. When present (i.e. during signup, and if the- * user indeed provided it), that source should be passed as this parameter.- */-export const verifyEmail = async (- email: string,- ott: string,- source: string | undefined,-): Promise<EmailOrSRPVerificationResponse> => {- const res = await fetch(await apiURL("/users/verify-email"), {- method: "POST",- headers: publicRequestHeaders(),- body: JSON.stringify({ email, ott, ...(source && { source }) }),- });- ensureOk(res);- return RemoteEmailOrSRPVerificationResponse.parse(await res.json());-};--/**- * Log the user out on remote, if possible and needed.- */-export const remoteLogoutIfNeeded = async () => {- if (!(await savedAuthToken())) {- // If the logout is attempted during the login / signup flow itself,- // then we won't have an auth token. Handle that gracefully.- return;- }-- const res = await fetch(await apiURL("/users/logout"), {- method: "POST",- headers: await authenticatedRequestHeaders(),- });- if (res.status == 401) {- // Ignore if we get a 401 Unauthorized, this is expected to happen on- // token expiry.- return;- }-- ensureOk(res);-};--/**- * Generate a new local-only KEK (key encryption key) suitable for interactive- * use and update the locally saved key attributes to reflect it.- *- * See {@link deriveInteractiveKey} for more details.- *- * In brief, after the initial password verification, we create a new- * inetractive KEK derived from the same password as the original KEK, but with- * so called interactive mem and ops limits which result in a noticeably faster- * key derivation.- *- * We then overwrite the encrypted master key, encryption nonce and the KEK- * derivation parameters (see: [Note: KEK three tuple]) in the locally persisted- * {@link KeyAttributes} so that these interactive parameters get used- * subsequent reauthentication.- *- * These are more ergonomic for the user especially in the web app where they- * need to enter their password to access their masterKey when repopening the- * app in a new tab (on desktop we can avoid this by using OS storage, see- * [Note: Safe storage and interactive KEK attributes]).- *- * @param password The user's password.- *- * @param keyAttributes The existing "original" key attributes, which we- * might've generated locally (new signup) or fetched from remote (existing- * login).- *- * @param masterKey The user's master key (base64 encoded).- *- * @returns the update key attributes.- */-export const generateAndSaveInteractiveKeyAttributes = async (- password: string,- 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,- };- saveKeyAttributes(interactiveKeyAttributes);- return interactiveKeyAttributes;-};--/**- * Change the email associated with the user's account (both locally and on- * remote)- *- * @param email The new email.- *- * @param ott The verification code that was sent to the new email.- */-export const changeEmail = async (email: string, ott: string) => {- await postChangeEmail(email, ott);- updateSavedLocalUser({ email });-};--/**- * Change the email associated with the user's account on remote.- */-const postChangeEmail = async (email: string, ott: string) =>- ensureOk(- await fetch(await apiURL("/users/change-email"), {- method: "POST",- headers: await authenticatedRequestHeaders(),- body: JSON.stringify({ email, ott }),- }),- );--/**- * Change the user's password on both remote and locally.- *- * @param password The new password.- */-export const changePassword = async (password: string) => {- const user = ensureLocalUser();- const masterKey = await ensureMasterKeyFromSession();- const keyAttributes = ensureSavedKeyAttributes();-- // Generate new KEK.- const {- key: kek,- salt: kekSalt,- opsLimit,- memLimit,- } = await deriveSensitiveKey(password);-- // Generate new key attributes.- const { encryptedData: encryptedKey, nonce: keyDecryptionNonce } =- await encryptBox(masterKey, kek);- const updatedKeyAttr: UpdatedKeyAttr = {- encryptedKey,- keyDecryptionNonce,- kekSalt,- opsLimit,- memLimit,- };-- // Update SRP and key attributes on remote.- await updateSRPAndKeyAttributes(- await generateSRPSetupAttributes(kek),- updatedKeyAttr,- );-- // Update SRP attributes locally.- await getAndSaveSRPAttributes(user.email);-- const srpAttributes = await getSRPAttributes(user.email);- saveSRPAttributes(ensure(srpAttributes));-- // Update key attributes locally, generating a new interactive kek while- // we're at it.- await generateAndSaveInteractiveKeyAttributes(- password,- { ...keyAttributes, ...updatedKeyAttr },- masterKey,- );-};--/**- * Update the {@link id} and {@link encryptedToken} present in the saved partial- * local user.- *- * This function removes the {@link token}, if any, present in the saved partial- * local user and sets the provided {@link encryptedToken}.- *- * It is expected that the code will subsequently redirect to "/credentials",- * which should call {@link decryptAndStoreTokenIfNeeded} which will decrypt the- * newly set {@link encryptedToken} and write out the decrypted value as the- * {@link token} in the saved local user.- *- * @param userID The ID of the user whose token this is. This is also saved to- * the partial local user (after doing a sanity check that we're not replacing- * partial data with a different userID).- *- * @param encryptedToken The newly obtained base64 encoded encrypted token from- * remote (e.g. as a result of the user verifying their email).- */-export const resetSavedLocalUserTokens = async (- userID: number,- encryptedToken: string,-) => {- const user = savedPartialLocalUser();- if (user?.id && user.id != userID) {- throw new Error(`User ID mismatch (${user.id}, ${userID})`);- }- replaceSavedLocalUser({- ...user,- id: userID,- token: undefined,- encryptedToken,- });- return removeAuthToken();-};--/**- * Decrypt the user's {@link encryptedToken}, if present, and use it to update- * both the locally saved user and the KV DB.- *- * @param keyAttributes The user's key attributes.- *- * @param masterKey The user's master key (base64 encoded).- */-export const decryptAndStoreTokenIfNeeded = async (- keyAttributes: KeyAttributes,- masterKey: string,-) => {- const { encryptedToken } = savedPartialLocalUser() ?? {};- if (!encryptedToken) return;-- const { encryptedSecretKey, secretKeyDecryptionNonce, publicKey } =- keyAttributes;- const privateKey = await decryptBox(- { encryptedData: encryptedSecretKey, nonce: secretKeyDecryptionNonce },- masterKey,- );-- const token = await toB64URLSafe(- await boxSealOpenBytes(encryptedToken, { publicKey, privateKey }),- );-- updateSavedLocalUser({ token, encryptedToken: undefined });- return saveAuthToken(token);-};--const TwoFactorSecret = z.object({- /**- * The 2FA secret code.- */- secretCode: z.string(),- /**- * A base64 encoded "image/png".- */- qrCode: z.string(),-});--export type TwoFactorSecret = z.infer<typeof TwoFactorSecret>;--/**- * Start a TOTP based two factor setup process by fetching a secret code (and- * the corresponding QR code) from remote.- *- * Once the user provides us with a TOTP generated using the provided secret, we- * can finish the setup with {@link setupTwoFactorFinish}.- */-export const setupTwoFactor = async (): Promise<TwoFactorSecret> => {- const res = await fetch(await apiURL("/users/two-factor/setup"), {- method: "POST",- headers: await authenticatedRequestHeaders(),- });- ensureOk(res);- return TwoFactorSecret.parse(await res.json());-};--/**- * Finish the TOTP based two factor setup by provided a previously obtained- * secret (using {@link setupTwoFactor}) and the current TOTP generated using- * that secret.- *- * This updates both the state both locally and on remote.- *- * @param secretCode The value of {@link secretCode} from the- * {@link TwoFactorSecret} obtained by {@link setupTwoFactor}.- *- * @param totp The current TOTP corresponding to {@link secretCode}.- */-export const setupTwoFactorFinish = async (- secretCode: string,- totp: string,-) => {- const box = await encryptBox(secretCode, await getUserRecoveryKey());- await enableTwoFactor({- code: totp,- encryptedTwoFactorSecret: box.encryptedData,- twoFactorSecretDecryptionNonce: box.nonce,- });- updateSavedLocalUser({ isTwoFactorEnabled: true });-};--interface EnableTwoFactorRequest {- /**- * The current value of the TOTP corresponding to the two factor {@link- * secretCode} obtained from a previous call to {@link setupTwoFactor}.- */- code: string;- /**- * The {@link secretCode} encrypted with the user's recovery key.- *- * This is used in the case of second factor recovery.- */- encryptedTwoFactorSecret: string;- /**- * The nonce that was used when encrypting {@link encryptedTwoFactorSecret}.- */- twoFactorSecretDecryptionNonce: string;-}--/**- * Enable the TOTP based two factor for the user by providing the current 2FA- * code corresponding the two factor secret, and encrypted secrets for future- * recovery (if needed).- */-const enableTwoFactor = async (req: EnableTwoFactorRequest) =>- ensureOk(- await fetch(await apiURL("/users/two-factor/enable"), {- method: "POST",- headers: await authenticatedRequestHeaders(),- body: JSON.stringify(req),- }),- );--/**- * The result of a successful two factor verification (TOTP or passkey),- * recovery removal (TOTP) or recovery bypass (passkey).- */-export const TwoFactorAuthorizationResponse = z.object({- /**- * The user's ID.- */- id: z.number(),- /**- * The user's key attributes.- */- keyAttributes: RemoteKeyAttributes,- /**- * A encrypted auth token.- */- encryptedToken: z.string(),-});--export type TwoFactorAuthorizationResponse = z.infer<- typeof TwoFactorAuthorizationResponse->;--export const verifyTwoFactor = async (- code: string,- sessionID: string,-): Promise<TwoFactorAuthorizationResponse> => {- const res = await fetch(await apiURL("/users/two-factor/verify"), {- method: "POST",- headers: publicRequestHeaders(),- body: JSON.stringify({ code, sessionID }),- });- ensureOk(res);- return TwoFactorAuthorizationResponse.parse(await res.json());-};--/** The type of the second factor we're trying to act on */-export type TwoFactorType = "totp" | "passkey";--const TwoFactorRecoveryResponse = z.object({- /**- * The recovery secret, encrypted using the user's recovery key.- */- encryptedSecret: z.string(),- /**- * The nonce used during encryption of {@link encryptedSecret}.- */- secretDecryptionNonce: z.string(),-});--export type TwoFactorRecoveryResponse = z.infer<- typeof TwoFactorRecoveryResponse->;--/**- * Initiate second factor reset or bypass by requesting the encrypted second- * factor recovery secret (and nonce) from remote. The user can then decrypt- * these using their recovery key to reset or bypass their second factor.- *- * @param twoFactorType The type of second factor to reset or bypass.- *- * @param sessionID A two factor session ID ({@link twoFactorSessionID} or- * {@link passkeySessionID}) for the user.- *- * [Note: Second factor recovery]- *- * 1. When setting up a TOTP based second factor, client sends a (encrypted 2fa- * recovery secret, nonce) pair to remote. This is a randomly generated- * secret (and nonce) encrypted using the user's recovery key.- *- * 2. Similarly, when setting up a passkey as the second factor, the client- * sends a encrypted recovery secret (see {@link configurePasskeyRecovery}).- *- * 3. When the user wishes to reset or bypass their second factor, the client- * asks remote for these encrypted secrets (using {@link getRecoverTwoFactor}).- *- * 4. User then enters their recovery key, which the client uses to decrypt the- * recovery secret and provide it back to remote for verification (using- * {@link removeTwoFactor}).- *- * 5. If the recovery secret matches, then remote resets (TOTP based) or bypass- * (passkey based) the user's second factor.- */-export const getRecoverTwoFactor = async (- twoFactorType: TwoFactorType,- sessionID: string,-): Promise<TwoFactorRecoveryResponse> => {- const res = await fetch(- await apiURL("/users/two-factor/recover", { twoFactorType, sessionID }),- { headers: publicRequestHeaders() },- );- ensureOk(res);- return TwoFactorRecoveryResponse.parse(await res.json());-};--/**- * Finish the second factor recovery / bypass initiated by- * {@link getRecoverTwoFactor} using the provided recovery key mnemonic entered- * by the user.- *- * See: [Note: Second factor recovery].- *- * This completes the recovery process both locally, and on remote.- *- * @param twoFactorType The second factor type (same value as what would've been- * passed to {@link getRecoverTwoFactor} for obtaining- * {@link recoveryResponse}).- *- * @param sessionID The second factor session ID (same value as what would've- * been passed to {@link getRecoverTwoFactor} for obtaining- * {@link recoveryResponse}).- *- * @param recoveryResponse The response to a previous call to- * {@link getRecoverTwoFactor}.- *- * @param recoveryKeyMnemonic The 24-word BIP-39 recovery key mnemonic provided- * by the user to complete recovery.- */-export const recoverTwoFactorFinish = async (- twoFactorType: TwoFactorType,- sessionID: string,- recoveryResponse: TwoFactorRecoveryResponse,- recoveryKeyMnemonic: string,-) => {- const { encryptedSecret: encryptedData, secretDecryptionNonce: nonce } =- recoveryResponse;- const twoFactorSecret = await decryptBox(- { encryptedData, nonce },- await recoveryKeyFromMnemonic(recoveryKeyMnemonic),- );- const { id, keyAttributes, encryptedToken } = await removeTwoFactor(- twoFactorType,- sessionID,- twoFactorSecret,- );- await resetSavedLocalUserTokens(id, encryptedToken);- updateSavedLocalUser({- isTwoFactorEnabled: undefined,- twoFactorSessionID: undefined,- passkeySessionID: undefined,- });- if (twoFactorType == "passkey") clearInflightPasskeySessionID();- saveKeyAttributes(keyAttributes);-};--const removeTwoFactor = async (- twoFactorType: TwoFactorType,- sessionID: string,- secret: string,-): Promise<TwoFactorAuthorizationResponse> => {- const res = await fetch(await apiURL("/users/two-factor/remove"), {- method: "POST",- headers: publicRequestHeaders(),- body: JSON.stringify({ twoFactorType, sessionID, secret }),- });- ensureOk(res);- return TwoFactorAuthorizationResponse.parse(await res.json());-};diff --git a/web/apps/albums/vendor/ente-new/photos/services/auth-state.ts b/web/apps/albums/vendor/ente-new/photos/services/auth-state.tsnew file mode 100644index 0000000000..3347aa78aa--- /dev/null+++ b/web/apps/albums/vendor/ente-new/photos/services/auth-state.ts@@ -0,0 +1,85 @@+import { savedAuthToken } from "ente-base/token";+import { nullToUndefined } from "ente-utils/transform";+import { z } from "zod";++export interface LocalUser {+ id: number;+ email: string;+ token: string;+ isTwoFactorEnabled?: boolean;+}++const LocalUser = z.object({+ id: z.number(),+ email: z.string(),+ token: z.string(),+ isTwoFactorEnabled: z.boolean().nullish().transform(nullToUndefined),+});++export interface KeyAttributes {+ encryptedKey: string;+ keyDecryptionNonce: string;+ kekSalt: string;+ opsLimit: number;+ memLimit: number;+ publicKey: string;+ encryptedSecretKey: string;+ secretKeyDecryptionNonce: string;+ masterKeyEncryptedWithRecoveryKey?: string;+ masterKeyDecryptionNonce?: string;+ recoveryKeyEncryptedWithMasterKey?: string;+ recoveryKeyDecryptionNonce?: string;+}++const KeyAttributes = z.object({+ kekSalt: z.string(),+ encryptedKey: z.string(),+ keyDecryptionNonce: z.string(),+ publicKey: z.string(),+ encryptedSecretKey: z.string(),+ secretKeyDecryptionNonce: z.string(),+ memLimit: z.number(),+ opsLimit: z.number(),+ masterKeyEncryptedWithRecoveryKey: z+ .string()+ .nullish()+ .transform(nullToUndefined),+ masterKeyDecryptionNonce: z.string().nullish().transform(nullToUndefined),+ recoveryKeyEncryptedWithMasterKey: z+ .string()+ .nullish()+ .transform(nullToUndefined),+ recoveryKeyDecryptionNonce: z.string().nullish().transform(nullToUndefined),+});++const ensureTokensMatch = async (user: LocalUser | undefined) => {+ if (user?.token !== (await savedAuthToken())) {+ throw new Error("Token mismatch");+ }+};++const savedLocalUser = (): LocalUser | undefined => {+ const jsonString = localStorage.getItem("user");+ if (!jsonString) return undefined;++ const { success, data } = LocalUser.safeParse(JSON.parse(jsonString));+ if (success) void ensureTokensMatch(data);+ return success ? data : undefined;+};++const savedKeyAttributes = (): KeyAttributes | undefined => {+ const jsonString = localStorage.getItem("keyAttributes");+ if (!jsonString) return undefined;+ return KeyAttributes.parse(JSON.parse(jsonString));+};++const ensureExpectedLoggedInValue = <T>(value: T | undefined): T => {+ if (!value) throw new Error("Not logged in");+ return value;+};++export const ensureLocalUser = (): LocalUser =>+ ensureExpectedLoggedInValue(savedLocalUser());++export const ensureSavedKeyAttributes = (): KeyAttributes =>+ ensureExpectedLoggedInValue(savedKeyAttributes());diff --git a/web/apps/albums/vendor/ente-new/photos/services/collection.ts b/web/apps/albums/vendor/ente-new/photos/services/collection.tsindex 19cf930c01..0eaa6c26a8 100644--- a/web/apps/albums/vendor/ente-new/photos/services/collection.ts+++ b/web/apps/albums/vendor/ente-new/photos/services/collection.ts@@ -1,7 +1,4 @@-import {- ensureLocalUser,- ensureSavedKeyAttributes,-} from "ente-accounts/services/user";+import { ensureLocalUser, ensureSavedKeyAttributes } from "./auth-state";import { boxSealOpen, decryptBox, encryptBox } from "ente-base/crypto";import { authenticatedRequestHeaders, ensureOk } from "ente-base/http";import { apiURL } from "ente-base/origins";