Skip to content

armgit / ente

Public Imported from GitHub
0

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

Prune comments in the small apps and packages

Manav Rathif451dd417c77
diff --git a/web/apps/accounts/src/pages/_app.tsx b/web/apps/accounts/src/pages/_app.tsx
index 37ae448e14..c99bb6dd35 100644
--- a/web/apps/accounts/src/pages/_app.tsx
+++ b/web/apps/accounts/src/pages/_app.tsx
@@ -23,10 +23,8 @@ const App: React.FC<AppProps> = ({ Component, pageProps }) => {
const isI18nReady = useSetupI18n();
const { showMiniDialog, miniDialogProps } = useAttributedMiniDialog();
- // No code in the accounts app is currently expected to reach a code path
- // where they would need to "logout". Also, the accounts app doesn't store
- // any user specific persistent state that'd need to be cleared, so there
- // really isn't anything to do here even if we needed to.
+ // No code in the accounts app is expected to reach a logout code path,
+ // and there is no user specific persistent state to clear anyway.
const logout = assertionFailed;
const baseContext = useMemo(
diff --git a/web/apps/accounts/src/pages/index.tsx b/web/apps/accounts/src/pages/index.tsx
index 2ca9d20bda..293dc07c9f 100644
--- a/web/apps/accounts/src/pages/index.tsx
+++ b/web/apps/accounts/src/pages/index.tsx
@@ -2,7 +2,6 @@ import React, { useEffect } from "react";
const Page: React.FC = () => {
useEffect(() => {
- // There are no user navigable pages on the accounts app.
window.location.href = "https://ente.com";
}, []);
diff --git a/web/apps/accounts/src/pages/passkeys/index.tsx b/web/apps/accounts/src/pages/passkeys/index.tsx
index 85ae11b57d..89210b0cf4 100644
--- a/web/apps/accounts/src/pages/passkeys/index.tsx
+++ b/web/apps/accounts/src/pages/passkeys/index.tsx
@@ -86,8 +86,6 @@ const Page: React.FC = () => {
const accountsURL = accountsUrl ? new URL(accountsUrl) : undefined;
if (accountsURL && accountsURL.origin !== window.location.origin) {
- // The accounts URL might change if this was the last passkey
- // on the legacy RPID.
const redirectURL = new URL(accountsURL.href);
if (!redirectURL.pathname.endsWith("/")) {
redirectURL.pathname += "/";
@@ -120,11 +118,8 @@ const Page: React.FC = () => {
const handleDrawerClose = () => {
setShowPasskeyDrawer(false);
- // Don't clear the selected passkey, let the stale value be so that the
- // drawer closing animation is nicer.
- //
- // The value will get overwritten the next time we open the drawer for a
- // different passkey, so this will not have a functional impact.
+ // The selected passkey is deliberately not cleared here so that the
+ // drawer close animation looks right. The next open overwrites it.
};
const handleUpdateOrDeletePasskey = () => {
@@ -209,13 +204,7 @@ const Page: React.FC = () => {
export default Page;
interface AddPasskeyFormProps {
- /**
- * The token to use for the API request for adding the passkey.
- */
token: string;
- /**
- * Called to refresh the list of passkeys shown on the page after the passkey was successfully added.
- */
onRefreshPasskeys: () => Promise<void>;
}
@@ -239,12 +228,9 @@ export const AddPasskeyForm: React.FC<AddPasskeyFormProps> = ({
await registerPasskey(token, value);
} catch (e) {
log.error("Failed to register a new passkey", e);
- // If the user cancels the operation, then an error with name
- // "NotAllowedError" is thrown.
- //
- // Ignore these, but in other cases add an error indicator to the
- // add passkey text field. The browser is expected to already have
- // shown an error dialog to the user.
+ // The browser throws an error named "NotAllowedError" when the
+ // user cancels the operation, and shows its own error dialog
+ // for other failures, so "NotAllowedError" is ignored here.
if (!(e instanceof Error && e.name == "NotAllowedError")) {
setValueFieldError(t("passkey_add_failed"));
}
@@ -266,7 +252,6 @@ export const AddPasskeyForm: React.FC<AddPasskeyFormProps> = ({
margin="normal"
disabled={formik.isSubmitting}
error={!!formik.errors.value}
- // See: [Note: Use space as default TextField helperText]
helperText={formik.errors.value ?? " "}
label={t("enter_passkey_name")}
/>
@@ -283,13 +268,7 @@ export const AddPasskeyForm: React.FC<AddPasskeyFormProps> = ({
};
interface PasskeysListProps {
- /** The list of {@link Passkey}s to show. */
passkeys: Passkey[];
- /**
- * Callback to invoke when an passkey in the list is clicked.
- *
- * It is passed the corresponding {@link Passkey}.
- */
onSelectPasskey: (passkey: Passkey) => void;
}
@@ -313,13 +292,7 @@ const PasskeysList: React.FC<PasskeysListProps> = ({
};
interface PasskeyListItemProps {
- /** The passkey to show in the item. */
passkey: Passkey;
- /**
- * Callback to invoke when the item is clicked.
- *
- * It is passed the item's {@link passkey}.
- */
onClick: (passkey: Passkey) => void;
}
@@ -342,35 +315,15 @@ const PasskeyListItem: React.FC<PasskeyListItemProps> = ({
);
const PasskeyLabel = styled("div")`
- /* If the name of the passkey does not fit in one line, break the text into
- multiple lines as necessary */
white-space: normal;
`;
interface ManagePasskeyDrawerProps {
- /** If `true`, then the drawer is shown. */
open: boolean;
- /** Callback to invoke when the drawer wants to be closed. */
onClose: () => void;
- /**
- * The token to use for authenticating with the backend when making requests
- * for editing or deleting passkeys.
- *
- * It is guaranteed that this will be defined when `open` is true.
- */
+ // Both token and passkey are guaranteed to be defined when open is true.
token: string | undefined;
- /**
- * The {@link Passkey} whose details should be shown in the drawer.
- *
- * It is guaranteed that this will be defined when `open` is true.
- */
passkey: Passkey | undefined;
- /**
- * Callback to invoke when the passkey in the modified or deleted.
- *
- * The passkey that the drawer is showing will be out of date at this point,
- * so the list of passkeys should be refreshed and the drawer closed.
- */
onUpdateOrDeletePasskey: () => void;
}
diff --git a/web/apps/accounts/src/pages/passkeys/verify.tsx b/web/apps/accounts/src/pages/passkeys/verify.tsx
index f8a1e03858..6f7fd4d246 100644
--- a/web/apps/accounts/src/pages/passkeys/verify.tsx
+++ b/web/apps/accounts/src/pages/passkeys/verify.tsx
@@ -25,36 +25,28 @@ import { t } from "i18next";
import React, { useCallback, useEffect, useState } from "react";
const Page = () => {
- /**
- * The state of our component as we go through the passkey authentication
- * flow.
- *
- * To avoid confusion with useState, we call it status instead. */
type Status =
- | "loading" /* Can happen multiple times in the flow */
- | "webAuthnNotSupported" /* Unrecoverable error */
- | "unknownRedirect" /* Unrecoverable error */
- | "sessionAlreadyClaimed" /* Unrecoverable error */
- | "unrecoverableFailure" /* Unrecoverable error - generic */
- | "failedDuringSignChallenge" /* Recoverable error in signChallenge */
- | "failed" /* Recoverable error otherwise */
- | "lockerRegistrationDisabled" /* Locker only for Photos paid users */
- | "lockerRolloutLimitReached" /* Locker beta seats exhausted */
- | "needUserFocus" /* See docs for `Continuation` */
- | "waitingForUser" /* ...to authenticate with their passkey */
- | "redirectingWeb" /* Redirect back to the requesting app (HTTP) */
- | "redirectingApp"; /* Other redirects (mobile / desktop redirect) */
+ | "loading"
+ | "webAuthnNotSupported"
+ | "unknownRedirect"
+ | "sessionAlreadyClaimed"
+ | "unrecoverableFailure"
+ | "failedDuringSignChallenge"
+ | "failed"
+ | "lockerRegistrationDisabled"
+ | "lockerRolloutLimitReached"
+ | "needUserFocus"
+ | "waitingForUser"
+ | "redirectingWeb"
+ | "redirectingApp";
const [status, setStatus] = useState<Status>("loading");
- /**
- * Safari keeps on saying "NotAllowedError: The document is not focused"
- * even though it just opened the page and brought it to the front.
- *
- * Because of their incompetence, we need to break our entire flow into two
- * parts, and stash away a lot of state when we're in the "needUserFocus"
- * state.
- */
+ // Safari can reject the WebAuthn call with "NotAllowedError: The document
+ // is not focused" even when it has just opened the page and brought it to
+ // the front. So the flow is split into two phases: the state phase 2 needs
+ // is stashed in this continuation, and phase 2 runs again after an
+ // explicit user click (the "needUserFocus" status).
interface Continuation {
redirectURL: URL;
clientPackage: string;
@@ -65,18 +57,10 @@ const Page = () => {
Continuation | undefined
>();
- // Safari throws sometimes
- // (no reason, just to show their incompetence). The retry doesn't seem to
- // help mostly, but cargo cult anyway.
-
- // The URL we're redirecting to on success.
- //
- // This will only be set when status is "redirecting*".
const [successRedirectURL, setSuccessRedirectURL] = useState<
URL | undefined
>();
- /** Phase 1 of {@link authenticate}. */
const authenticateBegin = useCallback(async () => {
if (!isWebAuthnSupported()) {
setStatus("webAuthnNotSupported");
@@ -85,20 +69,14 @@ const Page = () => {
const searchParams = new URLSearchParams(window.location.search);
- // Extract redirect from the query params.
const redirect = nullToUndefined(searchParams.get("redirect"));
const redirectURL = parseRedirectURLParam(redirect);
-
- // Ensure that redirectURL is valid/whitelisted, otherwise show an
- // invalid "login" URL error to the user.
if (!redirectURL) {
log.error(`Redirect '${redirect}' is not whitelisted`);
setStatus("unknownRedirect");
return;
}
- // The server needs to know the app on whose behalf we're trying to
- // authenticate.
const clientPackage = nullToUndefined(
searchParams.get("clientPackage"),
);
@@ -109,7 +87,6 @@ const Page = () => {
setStatus("loading");
- // Extract passkeySessionID from the query params.
const passkeySessionID = nullToUndefined(
searchParams.get("passkeySessionID"),
);
@@ -135,10 +112,6 @@ const Page = () => {
return { redirectURL, passkeySessionID, clientPackage, beginResponse };
}, []);
- /**
- * Phase 2 of {@link authenticate}, separated by a potential user
- * interaction.
- */
const authenticateContinue = useCallback(async (cont: Continuation) => {
const { redirectURL, passkeySessionID, clientPackage, beginResponse } =
cont;
@@ -201,7 +174,6 @@ const Page = () => {
);
}, []);
- /** (re)start the authentication flow */
const authenticate = useCallback(async () => {
const cont = await authenticateBegin();
if (cont) {
@@ -225,15 +197,7 @@ const Page = () => {
const handleRecover = (() => {
const searchParams = new URLSearchParams(window.location.search);
const recover = nullToUndefined(searchParams.get("recover"));
- if (!recover) {
- // [Note: Conditional passkey recover option on accounts]
- //
- // Only show the recover option if the calling app provided us with
- // the "recover" query parameter. For example, the mobile app does
- // not pass it since it already shows a recovery option within the
- // waiting screen that it shows.
- return undefined;
- }
+ if (!recover) return undefined;
const recoverURL = parseRedirectURLParam(recover);
if (!recoverURL) return undefined;
@@ -313,7 +277,6 @@ const Page = () => {
export default Page;
-// Not 100% accurate, but good enough for our purposes.
const isHTTP = (url: URL) => url.protocol.startsWith("http");
const redirectToURL = (url: URL) => {
@@ -392,14 +355,9 @@ const ContentPaper = styled(Paper)(({ theme }) => ({
}));
interface VerifyProps {
- /** Called when the user presses the "Verify" button. */
onVerify: () => void;
}
-/**
- * Gain focus for the current page by requesting the user to explicitly click a
- * button. For more details, see the documentation for `Continuation`.
- */
const Verify: React.FC<VerifyProps> = ({ onVerify }) => (
<ContentPaper>
<KeyIcon color="secondary" fontSize="large" />
@@ -416,23 +374,8 @@ const Verify: React.FC<VerifyProps> = ({ onVerify }) => (
);
interface RetriableFailedProps {
- /**
- * Set this attribute to indicate that this failure occurred during the
- * actual passkey verification (`navigator.credentials.get`).
- *
- * We customize the error message for such cases to give a hint to the user
- * that they can try on their other devices too.
- */
duringSignChallenge?: boolean;
- /** Callback invoked when the user presses the try again button. */
onRetry: () => void;
- /**
- * Callback invoked when the user presses the button to recover their second
- * factor, e.g. if they cannot login using it.
- *
- * This is optional. See [Note: Conditional passkey recover option on
- * accounts].
- */
onRecover: (() => void) | undefined;
}
@@ -509,7 +452,6 @@ const RedirectingWeb: React.FC = () => (
);
interface RedirectingAppProps {
- /** Called when the user presses the button to redirect again */
onRetry: () => void;
}
diff --git a/web/apps/accounts/src/services/passkey.ts b/web/apps/accounts/src/services/passkey.ts
index 242821e32a..877f1ce0fa 100644
--- a/web/apps/accounts/src/services/passkey.ts
+++ b/web/apps/accounts/src/services/passkey.ts
@@ -10,15 +10,8 @@ import { apiURL } from "ente-base/origins";
import { nullToUndefined } from "ente-utils/transform";
import { z } from "zod";
-/** Return true if the user's browser supports WebAuthn (Passkeys). */
export const isWebAuthnSupported = () => !!navigator.credentials;
-/**
- * Variant of {@link authenticatedRequestHeaders} but for authenticated requests
- * made by the accounts app.
- *
- * @param token The accounts specific auth token to use for making API requests.
- */
const accountsAuthenticatedRequestHeaders = (
token: string,
): Record<string, string> => ({
@@ -27,16 +20,8 @@ const accountsAuthenticatedRequestHeaders = (
});
const Passkey = z.object({
- /** A unique ID for the passkey */
id: z.string(),
- /**
- * An arbitrary name associated by the user with the passkey (a.k.a
- * its "friendly name").
- */
friendlyName: z.string(),
- /**
- * Epoch microseconds when this passkey was created.
- */
createdAt: z.number(),
});
@@ -47,14 +32,6 @@ const GetPasskeysResponse = z.object({
passkeys: z.array(Passkey).nullish().transform(nullToUndefined),
});
-/**
- * Fetch the existing passkeys for the user.
- *
- * @param token The accounts specific auth token to use for making API requests.
- *
- * @returns An array of {@link Passkey}s. The array will be empty if the user
- * has no passkeys.
- */
export const getPasskeys = async (token: string) => {
const res = await fetch(await apiURL("/passkeys"), {
headers: accountsAuthenticatedRequestHeaders(token),
@@ -66,15 +43,6 @@ export const getPasskeys = async (token: string) => {
return { accountsUrl, passkeys: passkeys ?? [] };
};
-/**
- * Rename one of the user's existing passkey with the given {@link id}.
- *
- * @param token The accounts specific auth token to use for making API requests.
- *
- * @param id The `id` of the existing passkey to rename.
- *
- * @param name The new name (a.k.a. "friendly name").
- */
export const renamePasskey = async (
token: string,
id: string,
@@ -88,13 +56,6 @@ export const renamePasskey = async (
ensureOk(res);
};
-/**
- * Delete one of the user's existing passkeys.
- *
- * @param token The accounts specific auth token to use for making API requests.
- *
- * @param id The `id` of the existing passkey to delete.
- */
export const deletePasskey = async (token: string, id: string) => {
const res = await fetch(await apiURL(`/passkeys/${id}`), {
method: "DELETE",
@@ -103,23 +64,11 @@ export const deletePasskey = async (token: string, id: string) => {
ensureOk(res);
};
-/**
- * Add a new passkey as the second factor to the user's account.
- *
- * @param token The accounts specific auth token to use for making API requests.
- *
- * @param name An arbitrary name that the user wishes to label this passkey with
- * (a.k.a. "friendly name").
- */
export const registerPasskey = async (token: string, name: string) => {
- // Get options (and sessionID) from the backend.
const { sessionID, options } = await beginPasskeyRegistration(token);
- // Ask the browser to new (public key) credentials using these options.
const credential = (await navigator.credentials.create(options))!;
- // Finish by letting the backend know about these credentials so that it can
- // save the public key for future authentication.
await finishPasskeyRegistration({
token,
friendlyName: name,
@@ -129,17 +78,7 @@ export const registerPasskey = async (token: string, name: string) => {
};
interface BeginPasskeyRegistrationResponse {
- /**
- * An identifier for this registration ceremony / session.
- *
- * This sessionID is subsequently passed to the API when finish credential
- * creation to tie things together.
- */
sessionID: string;
- /**
- * Options that should be passed to `navigator.credential.create` when
- * creating the new {@link Credential}.
- */
options: { publicKey: PublicKeyCredentialCreationOptions };
}
@@ -150,75 +89,6 @@ const beginPasskeyRegistration = async (token: string) => {
});
ensureOk(res);
- // [Note: Converting binary data in WebAuthn API payloads]
- //
- // The server returns a JSON containing a "sessionID" (to tie together the
- // beginning and the end of the registration), and "options" that we should
- // pass on to the browser when asking it to create credentials.
- //
- // However, some massaging needs to be done first. On the backend, we use
- // the [go-webauthn](https://github.com/go-webauthn/webauthn) library to
- // begin the registration ceremony, and we verbatim credential creation
- // options that the library returns to us. These are meant to plug directly
- // into `CredentialCreationOptions` that `navigator.credential.create`
- // expects. Specifically, since we're creating a public key credential, the
- // `publicKey` attribute of the returned options will be in the shape of the
- // `PublicKeyCredentialCreationOptions` expected by the browser). Except,
- // binary data.
- //
- // Binary data in the returned `PublicKeyCredentialCreationOptions` are
- // serialized as a "URLEncodedBase64", which is a URL-encoded base64 string
- // without any padding. The library is following the WebAuthn recommendation
- // when it does this:
- //
- // > The term "Base64url Encoding refers" to the base64 encoding using the
- // > URL- and filename-safe character set defined in Section 5 of RFC4648,
- // > which all trailing '=' characters omitted (as permitted by Section 3.2)
- // >
- // > https://www.w3.org/TR/webauthn-3/#base64url-encoding
- //
- // However, the browser expects binary data as an "ArrayBuffer, TypedArray
- // or DataView".
- // https://developer.mozilla.org/en-US/docs/Web/API/PublicKeyCredentialCreationOptions
- //
- // So we do the conversion here.
- //
- // 1. To avoid inventing an intermediary type and the boilerplate that'd
- // come with it, we do a force typecast the options in the response to
- // one that has `PublicKeyCredentialCreationOptions`.
- //
- // 2. Convert the two binary data fields that are expected to be in the
- // response from URLEncodedBase64 strings to Uint8Arrays. There is a
- // third possibility, excludedCredentials[].id, but that we don't
- // currently use.
- //
- // The web.dev guide calls this out too:
- //
- // > ArrayBuffer values transferred from the server such as `challenge`,
- // > `user.id` and credential `id` for `excludeCredentials` need to be
- // > encoded on transmission. Don't forget to decode them on the frontend
- // > before passing to the WebAuthn API call. We recommend using Base64URL
- // > encode.
- // >
- // > https://web.dev/articles/passkey-registration
- //
- // So that's that. But to further complicate things, the libdom.ts typings
- // included with the current TypeScript version (5.4) indicate these binary
- // types as a:
- //
- // type BufferSource = ArrayBufferView | ArrayBuffer
- //
- // However MDN documentation states that they can be TypedArrays (e.g.
- // Uint8Arrays), and using Uint8Arrays works in practice too. So another
- // force cast is needed.
- //
- // ----
- //
- // Finally, the same process needs to happen, in reverse, when we're sending
- // the browser's response to credential creation to our backend for storing
- // that credential (for future authentication). Binary fields need to be
- // converted to URL-safe B64 before transmission.
-
const { sessionID, options } =
(await res.json()) as BeginPasskeyRegistrationResponse;
@@ -233,33 +103,22 @@ const beginPasskeyRegistration = async (token: string) => {
return { sessionID, options };
};
-/**
- * This is the function that does the dirty work for the binary conversion,
- * including the unfortunate typecasts.
- *
- * See: [Note: Converting binary data in WebAuthn API payloads]
- */
+// WebAuthn binary fields (challenges, user ids, credential ids and responses)
+// travel over the wire as unpadded URL-safe base64 strings, the encoding the
+// WebAuthn spec recommends, while the browser APIs produce and expect
+// BufferSource. These two helpers convert in each direction; the force casts
+// are needed because the DOM types say BufferSource where the wire actually
+// carries strings.
+
const serverB64ToBinary = async (b: BufferSource) => {
- // This is actually a URL-safe B64 string without trailing padding.
const b64String = b as unknown as string;
- // Convert it to a Uint8Array by doing the appropriate B64 decoding.
const bytes = await fromB64URLSafeNoPadding(b64String);
- // Cast again to satisfy the incomplete BufferSource type.
return bytes as unknown as BufferSource;
};
-/**
- * This is the sibling of {@link serverB64ToBinary} that does the conversions in
- * the other direction.
- *
- * See: [Note: Converting binary data in WebAuthn API payloads]
- */
const binaryToServerB64 = async (b: ArrayBuffer) => {
- // Convert it to a Uint8Array
const bytes = new Uint8Array(b);
- // Convert to a URL-safe B64 string without any trailing padding.
const b64String = await toB64URLSafeNoPadding(bytes);
- // Lie about the types to make the compiler happy.
return b64String as unknown as BufferSource;
};
@@ -295,9 +154,9 @@ const finishPasskeyRegistration = async ({
headers: accountsAuthenticatedRequestHeaders(token),
body: JSON.stringify({
id: credential.id,
- // This is meant to be the ArrayBuffer version of the (base64
- // encoded) `id`, but since we then would need to base64 encode it
- // anyways for transmission, we can just reuse the same string.
+ // rawId is nominally the binary form of id, but id is already its
+ // base64url encoding, which is what the wire wants, so the same
+ // string can be reused.
rawId: credential.id,
type: credential.type,
response: { attestationObject, clientDataJSON, transports },
@@ -306,41 +165,13 @@ const finishPasskeyRegistration = async ({
ensureOk(res);
};
-/**
- * A function to hide the type casts necessary to extract an
- * {@link AuthenticatorAttestationResponse} from the {@link Credential} we
- * obtain during a new passkey registration.
- */
const authenticatorAttestationResponse = (credential: Credential) => {
- // We passed `options: { publicKey }` to `navigator.credentials.create`, and
- // so we will get back an `PublicKeyCredential`:
- // https://developer.mozilla.org/en-US/docs/Web/API/PublicKeyCredentialCreationOptions#creating_a_public_key_credential
- //
- // However, the return type of `create` is the base `Credential`, so we need
- // to cast.
const pkCredential = credential as PublicKeyCredential;
-
- // Further, since this was a `create` and not a `get`, the
- // PublicKeyCredential.response will be an
- // `AuthenticatorAttestationResponse` (See same MDN reference).
- //
- // We need to cast again.
const attestationResponse =
pkCredential.response as AuthenticatorAttestationResponse;
-
return attestationResponse;
};
-/**
- * Return `true` if the given {@link redirectURL} (obtained from the redirect
- * query parameter passed around during the passkey verification flow) is one of
- * the whitelisted URLs that we allow redirecting to on success.
- *
- * This check is likely not necessary but we've only kept it just to be on the
- * safer side. However, this gets in the way of people who are self hosting
- * Ente. So only do this check if we're running on our production servers (or
- * localhost).
- */
const isAllowedRedirectScheme = (url: URL) =>
url.protocol === "http:" ||
url.protocol === "https:" ||
@@ -354,10 +185,12 @@ const isAllowedRedirectScheme = (url: URL) =>
// flow runs inside the app's WebView.
(url.protocol === "tauri:" && url.hostname === "localhost");
+// The redirect host whitelist is an extra safety net, but it would break
+// people who self host Ente, so it is enforced only when the accounts app
+// itself runs on an Ente domain (or localhost).
export const isWhitelistedRedirect = (redirectURL: URL) => {
if (!isAllowedRedirectScheme(redirectURL)) return false;
if (!shouldRestrictToWhitelistedRedirect()) return true;
- // In production/local, enforce host allowlist only for http(s)
return (
redirectURL.protocol === "ente:" ||
redirectURL.protocol === "enteauth:" ||
@@ -371,7 +204,6 @@ export const isWhitelistedRedirect = (redirectURL: URL) => {
};
export const shouldRestrictToWhitelistedRedirect = () => {
- // host includes port, hostname is sans port
const hostname = new URL(window.location.origin).hostname;
return (
hostname.endsWith("localhost") ||
@@ -401,42 +233,13 @@ export const parseRedirectURLParam = (
};
export interface BeginPasskeyAuthenticationResponse {
- /**
- * An identifier for this authentication ceremony / session.
- *
- * This `ceremonySessionID` is subsequently passed to the API when finish
- * credential creation to tie things together.
- */
ceremonySessionID: string;
- /**
- * Options that should be passed to `navigator.credential.get` to obtain the
- * attested {@link Credential}.
- */
options: { publicKey: PublicKeyCredentialRequestOptions };
}
-/**
- * The passkey session which we are trying to start an authentication ceremony
- * for has already finished elsewhere.
- */
export const passkeySessionAlreadyClaimedErrorMessage =
"Passkey session already claimed";
-/**
- * Create a authentication ceremony session and return a challenge and a list of
- * public key credentials that can be used to attest that challenge.
- *
- * [Note: WebAuthn authentication flow]
- *
- * This is step 1 of passkey authentication flow as described in
- * https://developer.mozilla.org/en-US/docs/Web/API/Web_Authentication_API#authenticating_a_user
- *
- * @param passkeySessionID A session created by the requesting app that can be
- * used to initiate a passkey authentication ceremony on the accounts app.
- *
- * @throws In addition to arbitrary errors, it throws errors with the message
- * {@link passkeySessionAlreadyClaimedErrorMessage}.
- */
export const beginPasskeyAuthentication = async (
passkeySessionID: string,
): Promise<BeginPasskeyAuthenticationResponse> => {
@@ -452,8 +255,6 @@ export const beginPasskeyAuthentication = async (
throw new HTTPError(res);
}
- // See: [Note: Converting binary data in WebAuthn API payloads]
-
const { ceremonySessionID, options } =
(await res.json()) as BeginPasskeyAuthenticationResponse;
@@ -468,64 +269,16 @@ export const beginPasskeyAuthentication = async (
return { ceremonySessionID, options };
};
-/**
- * Authenticate the user by asking them to use a passkey that the they had
- * previously created for the current domain to sign a challenge.
- *
- * This function implements steps 2 and 3 of the passkey authentication flow.
- * See [Note: WebAuthn authentication flow].
- *
- * @param publicKey A challenge and a list of public key credentials
- * ("passkeys") that can be used to attest that challenge.
- *
- * @returns A {@link PublicKeyCredential} that contains the signed
- * {@link AuthenticatorAssertionResponse}. Note that the type does not reflect
- * this specialization, and the result is a base {@link Credential}.
- */
export const signChallenge = async (
publicKey: PublicKeyCredentialRequestOptions,
) => {
- // Hint all transports to make security keys like Yubikey work across
- // varying registration/verification scenarios.
- //
- // During verification, we need to pass a `transport` property.
- //
- // > The `transports` property is hint of the methods that the client could
- // > use to communicate with the relevant authenticator of the public key
- // > credential to retrieve. Possible values are ["ble", "hybrid",
- // > "internal", "nfc", "usb"].
- // >
- // > MDN
- //
- // When we register a passkey, we save the transport alongwith the
- // credential. During authentication, we pass that transport back to the
- // browser. This is the approach recommended by the spec:
- //
- // > When registering a new credential, the Relying Party SHOULD store the
- // > value returned from getTransports(). When creating a
- // > PublicKeyCredentialDescriptor for that credential, the Relying Party
- // > SHOULD retrieve that stored value and set it as the value of the
- // > transports member.
- // >
- // > https://www.w3.org/TR/webauthn-3/#dom-publickeycredentialdescriptor-transports
- //
- // However, following this recommendation break things currently (2024) in
- // various ways. For example, if a user registers a Yubikey NFC security key
- // on Firefox on their laptop, then Firefox returns ["usb"]. This is
- // incorrect, it should be ["usb", "nfc"] (which is what Chrome does, since
- // the hardware itself supports both USB and NFC transports).
- //
- // Later, if the user tries to verifying with their security key on their
- // iPhone Safari via NFC, the browser doesn't recognize it (which seems
- // incorrect too, the transport is meant to be a "hint" not a binding).
- //
- // > Note that these hints represent the WebAuthn Relying Party's best
- // > belief as to how an authenticator may be reached.
- // >
- // > https://www.w3.org/TR/webauthn-3/#dom-publickeycredentialdescriptor-transports
- //
- // As a workaround, we override transports with known possible values.
-
+ // The spec says the transports stored at registration should be passed
+ // back as hints during authentication, but browsers get this wrong in
+ // practice (2024). E.g. Firefox reports only ["usb"] for a Yubikey NFC
+ // security key, and iPhone Safari then refuses to try that key over NFC,
+ // even though transports are meant to be hints, not bindings. As a
+ // workaround, hint every possible transport.
+ // https://www.w3.org/TR/webauthn-3/#dom-publickeycredentialdescriptor-transports
for (const cred of publicKey.allowCredentials ?? []) {
cred.transports = [
...(cred.transports ?? []),
@@ -543,26 +296,10 @@ export const signChallenge = async (
interface FinishPasskeyAuthenticationOptions {
passkeySessionID: string;
ceremonySessionID: string;
- /**
- * The package name of the client on whose behalf we're authenticating with
- * the user's passkey.
- *
- * This is used by the backend to generate an appropriately scoped auth
- * token for used by (and only by) the authenticating app.
- */
clientPackage: string;
credential: Credential;
}
-/**
- * Finish the authentication by providing the signed assertion to the backend.
- *
- * This function implements steps 4 and 5 of the passkey authentication flow.
- * See [Note: WebAuthn authentication flow].
- *
- * @returns The result of successful authentication, a
- * {@link TwoFactorAuthorizationResponse}.
- */
export const finishPasskeyAuthentication = async ({
passkeySessionID,
ceremonySessionID,
@@ -589,15 +326,15 @@ export const finishPasskeyAuthentication = async ({
const res = await fetch(`${url}?${params.toString()}`, {
method: "POST",
headers: {
- // Note: Unlike the other requests, this is the clientPackage of the
- // _requesting_ app, not the accounts app.
+ // Unlike the other requests, this is deliberately the client
+ // package of the requesting app, not of the accounts app itself.
"X-Client-Package": clientPackage,
},
body: JSON.stringify({
id: credential.id,
- // This is meant to be the ArrayBuffer version of the (base64
- // encoded) `id`, but since we then would need to base64 encode it
- // anyways for transmission, we can just reuse the same string.
+ // rawId is nominally the binary form of id, but id is already its
+ // base64url encoding, which is what the wire wants, so the same
+ // string can be reused.
rawId: credential.id,
type: credential.type,
response: {
@@ -613,46 +350,13 @@ export const finishPasskeyAuthentication = async ({
return TwoFactorAuthorizationResponse.parse(await res.json());
};
-/**
- * A function to hide the type casts necessary to extract a
- * {@link AuthenticatorAssertionResponse} from the {@link Credential} we obtain
- * during a passkey attestation.
- */
const authenticatorAssertionResponse = (credential: Credential) => {
- // We passed `options: { publicKey }` to `navigator.credentials.get`, and so
- // we will get back an `PublicKeyCredential`:
- // https://developer.mozilla.org/en-US/docs/Web/API/CredentialsContainer/get#web_authentication_api
- //
- // However, the return type of `get` is the base `Credential`, so we need to
- // cast.
const pkCredential = credential as PublicKeyCredential;
-
- // Further, since this was a `get` and not a `create`, the
- // PublicKeyCredential.response will be an `AuthenticatorAssertionResponse`
- // (See same MDN reference).
- //
- // We need to cast again.
const assertionResponse =
pkCredential.response as AuthenticatorAssertionResponse;
-
return assertionResponse;
};
-/**
- * Create a redirection URL to get back to the calling app that initiated the
- * passkey authentication flow with the result of the authentication.
- *
- * @param redirectURL The base URL to redirect to. Provided by the calling app
- * that initiated the passkey authentication.
- *
- * @param passkeySessionID The passkeySessionID that was provided by the calling
- * app that initiated the passkey authentication. It is returned back in the
- * response so that the calling app has a way to ensure that this is indeed a
- * redirect for the session that they initiated and are waiting for.
- *
- * @param twoFactorAuthorizationResponse The result of
- * {@link finishPasskeyAuthentication} returned by the backend.
- */
export const passkeyAuthenticationSuccessRedirectURL = async (
redirectURL: URL,
passkeySessionID: string,
@@ -668,18 +372,6 @@ export const passkeyAuthenticationSuccessRedirectURL = async (
return redirectURL;
};
-/**
- * Redirect back to the app that initiated the passkey authentication,
- * navigating the user to a place where they can reset their second factor using
- * their recovery key (e.g. if they have lost access to their passkey).
- *
- * The same considerations mentioned in [Note: Finish passkey flow in the
- * requesting app] apply to recovery too, which is why we need to redirect back
- * to the app on whose behalf we're authenticating.
- *
- * @param recoverURL The recovery URL provided as a query parameter by the app
- * that called us.
- */
export const redirectToPasskeyRecoverPage = (recoverURL: URL) => {
window.location.href = recoverURL.href;
};
diff --git a/web/apps/auth/src/pages/auth.tsx b/web/apps/auth/src/pages/auth.tsx
index 099501404e..de62b89c3a 100644
--- a/web/apps/auth/src/pages/auth.tsx
+++ b/web/apps/auth/src/pages/auth.tsx
@@ -199,7 +199,6 @@ const CodeDisplay: React.FC<CodeDisplayProps> = ({ code, timeOffset }) => {
});
useEffect(() => {
- // Generate to set the initial otp and nextOTP on component mount.
regen();
const periodMs = code.period * 1000;
@@ -207,11 +206,7 @@ const CodeDisplay: React.FC<CodeDisplayProps> = ({ code, timeOffset }) => {
periodMs - ((Date.now() + timeOffset) % periodMs);
let interval: ReturnType<typeof setInterval> | undefined;
- // Wait until we are at the start of the next code period, and then
- // start the interval loop.
setTimeout(() => {
- // We need to call regen() once before the interval loop to set the
- // initial otp and nextOTP.
regen();
interval = setInterval(regen, periodMs);
}, timeToNextCode);
diff --git a/web/apps/auth/src/pages/login.tsx b/web/apps/auth/src/pages/login.tsx
index fd91ebda9d..846da93856 100644
--- a/web/apps/auth/src/pages/login.tsx
+++ b/web/apps/auth/src/pages/login.tsx
@@ -45,18 +45,13 @@ const Page: React.FC = () => {
const onSignUp = useCallback(() => void router.push("/signup"), [router]);
const handleBackgroundClick: React.MouseEventHandler = (event) => {
- // Don't allow this when running on (e.g.) auth.ente.com.
if (!shouldAllowChangingAPIOrigin()) return;
- // Only count clicks directly on the background
if (event.target !== event.currentTarget) return;
- // Ignore clicks when the dialog is already open.
if (showDevSettings) return;
- // Otherwise increase the tap count,
setTapCount(tapCount + 1);
- // And show the dev settings dialog when it reaches 7.
if (tapCount + 1 == 7) {
setTapCount(0);
setShowDevSettings(true);
@@ -110,10 +105,6 @@ const Page: React.FC = () => {
export default Page;
-/**
- * Disable the ability to set the custom server when we're running on our own
- * production deployment.
- */
const shouldAllowChangingAPIOrigin = () => {
const hostname = new URL(window.location.origin).hostname;
return !(
diff --git a/web/apps/auth/src/services/code.ts b/web/apps/auth/src/services/code.ts
index d4f97c7b57..4157114d94 100644
--- a/web/apps/auth/src/services/code.ts
+++ b/web/apps/auth/src/services/code.ts
@@ -3,78 +3,24 @@ import { nullToUndefined } from "ente-utils/transform";
import { HOTP, TOTP } from "otpauth";
import { z } from "zod";
import { Steam } from "./steam";
-/**
- * A parsed representation of an *OTP code URI.
- *
- * This is all the data we need to drive a OTP generator.
- */
+
export interface Code {
- /** A unique id for the corresponding "auth entity" in our system. */
id: string;
- /** The type of the code. */
type: "totp" | "hotp" | "steam";
- /** The user's account or email for which this code is used. */
account?: string;
- /** The name of the entity that issued this code. */
issuer: string;
- /**
- * Length of the generated OTP.
- *
- * This is vernacularly called "digits", which is an accurate description
- * for the OG TOTP/HOTP codes. However, steam codes are not just digits, so
- * we name this as a content-neutral "length".
- */
length: number;
- /**
- * The time period (in seconds) for which a single OTP generated from this
- * code remains valid.
- */
period: number;
- /** The (HMAC) algorithm used by the OTP generator. */
algorithm: "sha1" | "sha256" | "sha512";
- /**
- * HOTP counter.
- *
- * Only valid for HOTP codes. It might be even missing for HOTP codes, in
- * which case we should start from 0.
- */
counter?: number;
- /**
- * The secret that is used to drive the OTP generator.
- *
- * This is an arbitrary key encoded in Base32 that drives the HMAC (in a
- * {@link type}-specific manner).
- */
secret: string;
- /**
- * Optional metadata.
- *
- * This is metadata of the shape {@link CodeDisplay} containing Ente
- * specific metadata (e.g. if it is pinned) for this code.
- */
codeDisplay: CodeDisplay | undefined;
- /** The original string from which this code was generated. */
uriString: string;
}
export interface CodeDisplay {
- /**
- * `true` if this code is in the Trash (i.e. it has been deleted by the
- * user and will be automatically permanenently deleted after some time).
- */
trashed?: boolean;
- /**
- * `true` if this code has been pinned by the user.
- *
- * Pinned codes show at the top of the list of codes.
- */
pinned?: boolean;
- /**
- * User-provided note or description for this code.
- *
- * This is optional metadata that users can add to help remember details
- * about the code (e.g., which account, recovery codes location, etc.).
- */
note?: string;
}
@@ -84,32 +30,13 @@ const CodeDisplay = z.object({
note: z.string().nullish().transform(nullToUndefined),
});
-/**
- * Convert a OTP code URI into its parse representation, a {@link Code}.
- *
- * @param id A unique ID of this code within the auth app.
- *
- * @param uriString A string specifying how to generate a TOTP/HOTP/Steam OTP
- * code. These strings are of the form:
- *
- * - (TOTP)
- * otpauth://totp/ACME:[email protected]?algorithm=SHA1&digits=6&issuer=acme&period=30&secret=ALPHANUM
- *
- * - (HOTP)
- * otpauth://hotp/Test?secret=AAABBBCCCDDDEEEFFF&issuer=Test&counter=0
- *
- * - (Steam)
- * otpauth://steam/Steam:SteamAccount?algorithm=SHA1&digits=5&issuer=Steam&period=30&secret=AAABBBCCCDDDEEEFFF
- *
- * See also `auth/test/models/code_test.dart`.
- */
export const codeFromURIString = (id: string, uriString: string): Code => {
try {
return _codeFromURIString(id, uriString);
} catch (e) {
- // We might have legacy encodings of account names that contain a "#",
- // which causes the rest of the URL to be treated as a fragment, and
- // ignored. See if this was potentially such a case, otherwise rethrow.
+ // Account names in legacy encodings can contain a raw "#", which makes
+ // the URL parser treat the rest of the URI as a fragment. Retry with
+ // the "#" escaped.
if (uriString.includes("#"))
return _codeFromURIString(id, uriString.replaceAll("#", "%23"));
throw e;
@@ -137,29 +64,10 @@ const _codeFromURIString = (id: string, uriString: string): Code => {
};
const parsePathname = (url: URL): [type: Code["type"], path: string] => {
- // A URL like
- //
- // new
- // URL("otpauth://hotp/Test?secret=AAABBBCCCDDDEEEFFF&issuer=Test&counter=0")
- //
- // is parsed differently by different browsers, and there are differences
- // even depending on the scheme.
- //
- // When the scheme is http(s), then all of them consider "hotp" as the
- // `host`. However, when the scheme is "otpauth", as is our case, Safari
- // splits it into
- //
- // host: "hotp"
- // pathname: "/Test"
- //
- // while Chrome and Firefox consider the entire thing as part of the
- // pathname
- //
- // host: ""
- // pathname: "//hotp/Test"
- //
- // So we try to handle both scenarios by first checking for the host match,
- // and if not fall back to deducing the "host" from the pathname.
+ // Browsers parse URLs with a non-http(s) scheme like otpauth differently:
+ // for "otpauth://hotp/Test", Safari puts "hotp" in the host and "/Test" in
+ // the pathname, while Chrome and Firefox leave the host empty and put
+ // "//hotp/Test" in the pathname. Handle both.
switch (url.host.toLowerCase()) {
case "totp":
@@ -181,7 +89,6 @@ const parsePathname = (url: URL): [type: Code["type"], path: string] => {
};
const parseAccount = (path: string): string | undefined => {
let p = decodeURIComponent(path);
if (p.startsWith("/")) p = p.slice(1);
if (p.includes(":")) p = p.split(":").slice(1).join(":");
@@ -189,10 +96,10 @@ const parseAccount = (path: string): string | undefined => {
};
const parseIssuer = (url: URL, path: string): string => {
- // If there is a "issuer" search param, use that.
let issuer = url.searchParams.get("issuer");
if (issuer) {
- // This is to handle bug in old versions of Ente Auth app.
+ // Old versions of the Ente Auth app had a bug that could append the
+ // period query param to the issuer; strip such suffixes.
const periodSuffixIndex = issuer.search(/&?period=\d+$/);
if (
periodSuffixIndex > 0 &&
@@ -206,8 +113,6 @@ const parseIssuer = (url: URL, path: string): string => {
return issuer;
}
- // Otherwise use the `prefix:` from the account as the issuer.
- // "/ACME:[email protected]" => "ACME"
let p = decodeURIComponent(path);
if (p.startsWith("/")) p = p.slice(1);
@@ -217,13 +122,8 @@ const parseIssuer = (url: URL, path: string): string => {
return p;
};
-/**
- * Parse the length of the generated code.
- *
- * The URI query param is called digits since originally TOTP/HOTP codes used
- * this for generating numeric codes. Now we also support steam, which instead
- * shows non-numeric codes, and also with a different default length of 5.
- */
+// The otpauth URI query param is "digits", but Steam codes are 5 non-digit
+// characters, so we use a neutral "length" and a type-specific default.
const parseLength = (url: URL, type: Code["type"]): number => {
const defaultLength = type == "steam" ? 5 : 6;
return parseInt(url.searchParams.get("digits") ?? "", 10) || defaultLength;
@@ -251,9 +151,6 @@ const parseCounter = (url: URL): number | undefined => {
const parseSecret = (url: URL): string =>
url.searchParams.get("secret")!.replaceAll(" ", "").toUpperCase();
-/**
- * Parse a JSON string containing Ente specific metadata attached to the code.
- */
const parseCodeDisplay = (url: URL): CodeDisplay | undefined => {
const s = url.searchParams.get("codeDisplay");
if (!s) return undefined;
@@ -266,17 +163,6 @@ const parseCodeDisplay = (url: URL): CodeDisplay | undefined => {
}
};
-/**
- * Generate a pair of OTPs (one time passwords) from the given {@link code}.
- *
- * @param code The parsed code data, including the secret and code type.
- *
- * @param timeOffset A millisecond delta that should be applied to Date.now when
- * deriving the OTP.
- *
- * @returns a pair of OTPs, the current one and the next one, using the given
- * {@link code}.
- */
export const generateOTPs = (
code: Code,
timeOffset: number,
diff --git a/web/apps/auth/src/services/remote.ts b/web/apps/auth/src/services/remote.ts
index 14cfc52b72..9af3a029f8 100644
--- a/web/apps/auth/src/services/remote.ts
+++ b/web/apps/auth/src/services/remote.ts
@@ -13,27 +13,14 @@ import { z } from "zod";
export interface AuthCodesAndTimeOffset {
codes: Code[];
- /**
- * An optional and approximate correction (milliseconds) which should be
- * applied to the current client's time when deriving TOTPs.
- */
timeOffset?: number;
}
-/**
- * Fetch the user's auth codes from remote and decrypt them using the user's
- * master key.
- *
- * @param masterKey The user's base64 encoded master key.
- */
export const getAuthCodesAndTimeOffset = async (
masterKey: string,
): Promise<AuthCodesAndTimeOffset> => {
const authenticatorEntityKey = await getAuthenticatorEntityKey();
- if (!authenticatorEntityKey) {
- // The user might not have stored any codes yet from the mobile app.
- return { codes: [] };
- }
+ if (!authenticatorEntityKey) return { codes: [] };
const authenticatorKey = await decryptAuthenticatorKey(
authenticatorEntityKey,
@@ -53,17 +40,10 @@ export const getAuthCodesAndTimeOffset = async (
}
})
.filter((f) => f !== undefined)
- .filter((f) => {
- // Do not show trashed entries in the web interface.
- return !f.codeDisplay?.trashed;
- })
+ .filter((f) => !f.codeDisplay?.trashed)
.sort((a, b) => {
- // If only one of them is pinned, prefer it.
if (a.codeDisplay?.pinned && !b.codeDisplay?.pinned) return -1;
if (!a.codeDisplay?.pinned && b.codeDisplay?.pinned) return 1;
- // If we get here, either both are pinned, or none are...
-
- // Sort by issuer, alphabetically.
if (a.issuer && b.issuer) {
return a.issuer.localeCompare(b.issuer);
}
@@ -79,85 +59,29 @@ export const getAuthCodesAndTimeOffset = async (
return { codes, timeOffset };
};
-/**
- * Authenticator entities obtained from remote.
- */
interface AuthenticatorEntity {
id: string;
data: unknown;
}
-/**
- * Zod schema for a item in the user entity diff.
- */
const RemoteAuthenticatorEntityChange = z.object({
id: z.string(),
- /**
- * Base64 string containing the encrypted contents of the entity.
- *
- * Will be `null` when isDeleted is true.
- */
encryptedData: z.string().nullable(),
- /**
- * Base64 string containing the decryption header.
- *
- * Will be `null` when isDeleted is true.
- */
header: z.string().nullable(),
- /**
- * `true` if the corresponding entity was deleted.
- */
isDeleted: z.boolean(),
- /**
- * Epoch microseconds when this entity was last updated.
- *
- * This value is suitable for being passed as the `sinceTime` in the diff
- * requests to implement pagination.
- */
updatedAt: z.number(),
});
const AuthenticatorEntityDiffResponse = z.object({
- /**
- * Changes to entities.
- */
diff: z.array(RemoteAuthenticatorEntityChange),
- /**
- * An optional epoch microseconds indicating the remote time when it
- * generated the response.
- */
timestamp: z.number().nullish().transform(nullToUndefined),
});
export interface AuthenticatorEntityDiffResult {
- /**
- * The decrypted {@link AuthenticatorEntity} values.
- */
entities: AuthenticatorEntity[];
- /**
- * An optional and approximate offset (in milliseconds) by which the time on
- * the current client is out of sync.
- *
- * This offset is computed by calculated by comparing the timestamp when the
- * remote generated the response to the time we received it. As such
- * (because of network delays etc) this will not be an accurate offset,
- * neither is it meant to be - it is only meant to help users whose devices
- * have wildly off times to still see the correct codes.
- *
- * Note that, for various reasons, remote might not send us a timestamp when
- * fetching the diff, so this is a best effort correction, and is not
- * guaranteed to be present.
- */
timeOffset: number | undefined;
}
-/**
- * Fetch all the authenticator entities for the user, and an estimated time
- * drift for the current client.
- *
- * @param authenticatorKey The (base64 encoded) key that should be used for
- * decrypting the authenticator entities received from remote.
- */
export const authenticatorEntityDiff = async (
authenticatorKey: string,
): Promise<AuthenticatorEntityDiffResult> => {
@@ -167,7 +91,6 @@ export const authenticatorEntityDiff = async (
authenticatorKey,
);
- // Fetch all the entities, paginating the requests.
const encryptedEntities = new Map<
string,
{ id: string; encryptedData: string; header: string }
@@ -192,8 +115,8 @@ export const authenticatorEntityDiff = async (
);
if (timestamp) {
- // - timestamp is in epoch microseconds.
- // - Date.now and timeOffset are in epoch milliseconds.
+ // The remote timestamp is in epoch microseconds, while Date.now
+ // and timeOffset are in epoch milliseconds.
timeOffset = Date.now() - Math.floor(timestamp / 1e3);
}
@@ -226,28 +149,12 @@ export const authenticatorEntityDiff = async (
};
export const AuthenticatorEntityKey = z.object({
- /**
- * The authenticator entity key (base64 string), encrypted with the user's
- * master key.
- */
encryptedKey: z.string(),
- /**
- * Base64 encoded nonce used during encryption of the authenticator key.
- */
header: z.string(),
});
export type AuthenticatorEntityKey = z.infer<typeof AuthenticatorEntityKey>;
-/**
- * Fetch the encryption key for the authenticator entities from remote.
- *
- * This is a special case of an entity key for use with "authenticator"
- * entities. See: [Note: User entity keys].
- *
- * @returns the authenticator key, or undefined if there is no authenticator key
- * yet created on remote for the user.
- */
export const getAuthenticatorEntityKey = async (): Promise<
AuthenticatorEntityKey | undefined
> => {
@@ -255,7 +162,6 @@ export const getAuthenticatorEntityKey = async (): Promise<
headers: await authenticatedRequestHeaders(),
});
if (!res.ok) {
- // Remote says HTTP 404 Not Found if there is no key yet for the user.
if (res.status == 404) return undefined;
throw new HTTPError(res);
} else {
@@ -263,9 +169,6 @@ export const getAuthenticatorEntityKey = async (): Promise<
}
};
-/**
- * Decrypt an encrypted authenticator key using the user's master key.
- */
const decryptAuthenticatorKey = async (
remote: AuthenticatorEntityKey,
masterKey: string,
@@ -273,7 +176,7 @@ const decryptAuthenticatorKey = async (
decryptBox(
{
encryptedData: remote.encryptedKey,
- // Remote calls it the header, but it really is the nonce.
+ // Remote calls this field the header, but it really is the nonce.
nonce: remote.header,
},
masterKey,
diff --git a/web/apps/auth/src/services/steam.ts b/web/apps/auth/src/services/steam.ts
index 8b761f1780..1d31ef4429 100644
--- a/web/apps/auth/src/services/steam.ts
+++ b/web/apps/auth/src/services/steam.ts
@@ -2,19 +2,10 @@ import { hmac } from "@noble/hashes/hmac.js";
import { sha1 } from "@noble/hashes/legacy.js";
import { Secret } from "otpauth";
-/**
- * Steam OTPs.
- *
- * Steam's algorithm is a custom variant of TOTP that uses a 26-character
- * alphabet instead of digits.
- *
- * A Dart implementation of the algorithm can be found in
- * https://github.com/elliotwutingfeng/steam_totp/blob/main/lib/src/steam_totp_base.dart
- * (MIT license), and we use that as a reference. Our implementation is written
- * in the style of the other TOTP/HOTP classes that are provided by the otpauth
- * JS library that we use for the normal TOTP/HOTP generation
- * https://github.com/hectorm/otpauth/blob/master/src/hotp.js (MIT license).
- */
+// Steam's OTP algorithm is a custom variant of TOTP: SHA-1, a 30 second
+// period, and the HOTP integer mapped into a 26-character alphabet instead of
+// digits. Reference implementation (MIT license):
+// https://github.com/elliotwutingfeng/steam_totp/blob/main/lib/src/steam_totp_base.dart
export class Steam {
secret: Secret;
period: number;
@@ -25,13 +16,10 @@ export class Steam {
}
generate({ timestamp }: { timestamp: number } = { timestamp: Date.now() }) {
- // Same as regular TOTP.
const counter = Math.floor(timestamp / 1000 / this.period);
- // Same as regular HOTP, but algorithm is fixed to SHA-1.
const digest = hmac(sha1, this.secret.bytes, uintToArray(counter));
- // Same calculation as regular HOTP.
const offset = digest[digest.length - 1]! & 15;
let otp =
((digest[offset]! & 127) << 24) |
@@ -39,8 +27,6 @@ export class Steam {
((digest[offset + 2]! & 255) << 8) |
(digest[offset + 3]! & 255);
- // However, instead of using this as the OTP, use it to index into
- // the steam OTP alphabet.
const alphabet = "23456789BCDFGHJKMNPQRTVWXY";
const N = alphabet.length;
const steamOTP = [];
@@ -52,8 +38,6 @@ export class Steam {
}
}
-// Equivalent to
-// https://github.com/hectorm/otpauth/blob/master/src/utils/encoding/uint.js
const uintToArray = (n: number): Uint8Array => {
const result = new Uint8Array(8);
for (let i = 7; i >= 0; i--) {
diff --git a/web/apps/auth/src/utils/format.ts b/web/apps/auth/src/utils/format.ts
index 169698c9fb..69f67a2910 100644
--- a/web/apps/auth/src/utils/format.ts
+++ b/web/apps/auth/src/utils/format.ts
@@ -1,6 +1,2 @@
-/**
- * Format a generated OTP code to improve readability by breaking it into chunks
- * of length 3.
- */
export const prettyFormatCode = (code: string) =>
code.replace(/(.{3})/g, "$1 ").trim();
diff --git a/web/apps/embed/src/components/EmbedFileListWithViewer.tsx b/web/apps/embed/src/components/EmbedFileListWithViewer.tsx
index 4aa7acb5fc..f56405d302 100644
--- a/web/apps/embed/src/components/EmbedFileListWithViewer.tsx
+++ b/web/apps/embed/src/components/EmbedFileListWithViewer.tsx
@@ -127,9 +127,7 @@ export const EmbedFileListWithViewer: React.FC<
showFullscreenButton={true}
enableComment={false}
onTriggerRemotePull={handleTriggerRemotePull}
- onVisualFeedback={() => {
- // Visual feedback requested
- }}
+ onVisualFeedback={() => undefined}
/>
)}
</Container>
diff --git a/web/apps/embed/src/pages/_app.tsx b/web/apps/embed/src/pages/_app.tsx
index fc0d1887e5..2ae0d26617 100644
--- a/web/apps/embed/src/pages/_app.tsx
+++ b/web/apps/embed/src/pages/_app.tsx
@@ -26,12 +26,10 @@ export default function App({ Component, pageProps }: AppProps) {
logStartupBanner();
}, []);
- // Simplified - no complex dialogs needed for embed
const isRouteChangeInProgress = useIsRouteChangeInProgress();
const { showLoadingBar, hideLoadingBar } = useLoadingBar();
- // Show loading bar on route changes
useEffect(() => {
if (isRouteChangeInProgress) {
showLoadingBar();
@@ -40,13 +38,9 @@ export default function App({ Component, pageProps }: AppProps) {
}
}, [isRouteChangeInProgress, showLoadingBar, hideLoadingBar]);
- const showMiniDialog = useCallback(() => {
- // Simplified for embed - no complex dialogs needed
- }, []);
+ const showMiniDialog = useCallback(() => undefined, []);
- const logout = useCallback(() => {
- // No logout functionality needed for embed
- }, []);
+ const logout = useCallback(() => undefined, []);
const baseContext = useMemo(
() => deriveBaseContext({ logout, showMiniDialog }),
@@ -57,13 +51,9 @@ export default function App({ Component, pageProps }: AppProps) {
() => ({
showLoadingBar,
hideLoadingBar,
- showNotification: () => {
- // No notifications in embed
- },
+ showNotification: () => undefined,
watchFolderView: false,
- setWatchFolderView: () => {
- // No watch folder in embed
- },
+ setWatchFolderView: () => undefined,
}),
[showLoadingBar, hideLoadingBar],
);
diff --git a/web/apps/embed/src/pages/index.tsx b/web/apps/embed/src/pages/index.tsx
index 2326f7b50d..517c475b19 100644
--- a/web/apps/embed/src/pages/index.tsx
+++ b/web/apps/embed/src/pages/index.tsx
@@ -151,7 +151,6 @@ export default function EmbedGallery() {
const accessToken = accessTokenFromURL(currentURL);
const ck = await extractCollectionKeyFromShareURL(currentURL);
if (!accessToken && !ck) {
- // Only redirect to ente.com if this is not a self-hosted instance.
if (!isCustomAPIOrigin) {
window.location.href = "https://ente.com";
redirectingToWebsite = true;
diff --git a/web/apps/embed/src/services/in-memory-storage.ts b/web/apps/embed/src/services/in-memory-storage.ts
index 1479730d48..670052dd01 100644
--- a/web/apps/embed/src/services/in-memory-storage.ts
+++ b/web/apps/embed/src/services/in-memory-storage.ts
@@ -1,15 +1,6 @@
-/**
- * @file In-memory storage adapter for embed app
- *
- * This provides an in-memory storage implementation that mirrors the localForage
- * interface used by public-albums-fdb. It ensures complete isolation between
- * different iframe embeds by avoiding any persistent storage.
- */
-
-/**
- * In-memory storage adapter that mimics the localForage interface.
- * Uses Maps to store data in memory, providing isolation between embeds.
- */
+// Mimics the localForage interface, but deliberately keeps data only in
+// memory, never persisting it, so that each iframe embed stays isolated from
+// other embeds.
export class InMemoryStorage {
private storage = new Map<string, unknown>();
@@ -32,7 +23,7 @@ export class InMemoryStorage {
}
ready(): void {
- // Always ready since it's in-memory
+ // No-op that exists only to satisfy the localForage interface.
}
keys(): string[] {
@@ -48,11 +39,9 @@ export class InMemoryStorage {
return keys[index] || null;
}
- // Config method to match localForage interface (no-op for in-memory)
config(): void {
- // No configuration needed for in-memory storage
+ // No-op that exists only to satisfy the localForage interface.
}
}
-// Create a singleton instance to be used as the storage backend
export const inMemoryStorage = new InMemoryStorage();
diff --git a/web/apps/embed/src/services/public-albums-storage.ts b/web/apps/embed/src/services/public-albums-storage.ts
index 0ab9d7aa5b..d3df373fef 100644
--- a/web/apps/embed/src/services/public-albums-storage.ts
+++ b/web/apps/embed/src/services/public-albums-storage.ts
@@ -1,11 +1,3 @@
-/**
- * @file Public albums storage facade for embed app
- *
- * This provides the same interface as public-albums-fdb but uses in-memory storage
- * instead of IndexedDB/localStorage. This ensures isolation between different
- * iframe embeds while maintaining API compatibility.
- */
-
import {
LocalCollections,
LocalEnteFiles,
@@ -18,31 +10,12 @@ import { nullToUndefined } from "ente-utils/transform";
import { z } from "zod";
import { inMemoryStorage } from "./in-memory-storage";
-/**
- * Return all public collections present in our local storage.
- *
- * Use {@link savePublicCollections} to update the storage.
- */
const savedPublicCollections = (): Collection[] =>
LocalCollections.parse(inMemoryStorage.getItem("public-collections") ?? []);
-/**
- * Replace the list of public collections stored in our local storage.
- *
- * This is the setter corresponding to {@link savedPublicCollections}.
- */
const savePublicCollections = (collections: Collection[]) =>
inMemoryStorage.setItem("public-collections", collections);
-/**
- * Return the saved public collection with the given {@link key} if present in
- * our local storage.
- *
- * Use {@link savePublicCollection} to save collections in our local storage.
- *
- * @param key The collection key that can be used to identify the public album
- * we want from amongst all the locally saved public albums.
- */
export const savedPublicCollectionByKey = (
collectionKey: string,
): Collection | undefined => {
@@ -50,12 +23,6 @@ export const savedPublicCollectionByKey = (
return collections.find((c) => c.key == collectionKey);
};
-/**
- * Save a public collection to our local storage.
- *
- * The collection can later be retrieved using {@link savedPublicCollection}.
- * The collection can be removed using {@link removePublicCollection}.
- */
export const savePublicCollection = (collection: Collection) => {
const collections = savedPublicCollections();
savePublicCollections([
@@ -64,13 +31,6 @@ export const savePublicCollection = (collection: Collection) => {
]);
};
-/**
- * Remove a public collection, identified using its collection key, from our
- * local storage.
- *
- * @param key The collection key that can be used to identify the public album
- * we want to remove.
- */
export const removePublicCollectionByKey = (collectionKey: string) => {
const collections = savedPublicCollections();
savePublicCollections([
@@ -78,45 +38,16 @@ export const removePublicCollectionByKey = (collectionKey: string) => {
]);
};
-/**
- * Zod schema for a nullish string, with `null` transformed to `undefined`.
- */
const LocalString = z.string().nullish().transform(nullToUndefined);
-/**
- * Return the last saved referral code present in our local storage.
- *
- * See: [Note: Public albums referral code]. A few more details specific to the
- * persistence of the referral code:
- *
- * 1. The public albums app persists only the referral code for the latest
- * public album that was fetched.
- *
- * 2. This saved value can be read by
- * {@link savedLastPublicCollectionReferralCode}.
- *
- * 3. It gets updated as part of {@link publicAlbumsRemotePull}, which writes
- * out a new value using {@link saveLastPublicCollectionReferralCode}.
- */
export const savedLastPublicCollectionReferralCode = () =>
LocalString.parse(inMemoryStorage.getItem("public-referral-code"));
-/**
- * Update the referral code present in our local storage.
- *
- * This is the setter corresponding to
- * {@link savedLastPublicCollectionReferralCode}.
- */
export const saveLastPublicCollectionReferralCode = (referralCode: string) => {
inMemoryStorage.setItem("public-referral-code", referralCode);
};
const LocalSavedPublicCollectionFilesEntry = z.object({
- /**
- * The collection, identified by its access token.
- *
- * See: [Note: Public album access token]
- */
collectionUID: z.string(),
files: LocalEnteFiles,
});
@@ -125,45 +56,22 @@ type LocalSavedPublicCollectionFilesEntry = z.infer<
typeof LocalSavedPublicCollectionFilesEntry
>;
-/**
- * Return all files for a public collection present in our local storage.
- *
- * Use {@link savePublicCollectionFiles} to update the list of files in the
- * storage, and {@link removePublicCollectionFiles} to remove them.
- *
- * @param accessToken The access token that identifies the public album whose
- * files we want.
- */
export const savedPublicCollectionFiles = (accessToken: string): EnteFile[] => {
const entry = pcfEntries().find((e) => e.collectionUID == accessToken);
return transformFilesIfNeeded(entry ? entry.files : []);
};
-/**
- * A convenience routine to read the storage entries for "public-collection-files".
- */
const pcfEntries = () => {
- // A local alias to avoid the code from looking scary.
type ES = LocalSavedPublicCollectionFilesEntry[];
- // See: [Note: Avoiding Zod parsing for large DB arrays] for why we use an
- // (implied) cast here instead of parsing using the Zod schema.
+ // Deliberately cast instead of parsing with the Zod schema: parsing very
+ // large file arrays is slow, and we ourselves wrote these entries.
const entries = inMemoryStorage.getItem(
"public-collection-files",
) as ES | null;
return entries ?? [];
};
-/**
- * Replace the list of files for a public collection in our local storage.
- *
- * This is the setter corresponding to {@link savedPublicCollectionFiles}.
- *
- * @param accessToken The access token that identifies the public album whose
- * files we want to update.
- *
- * @param files The files to save.
- */
export const savePublicCollectionFiles = (
accessToken: string,
files: EnteFile[],
@@ -174,35 +82,15 @@ export const savePublicCollectionFiles = (
]);
};
-/**
- * Remove the list of files, in any, in our local storage for the given
- * collection (identified by its {@link accessToken}).
- */
export const removePublicCollectionFiles = (accessToken: string): void => {
inMemoryStorage.setItem("public-collection-files", [
...pcfEntries().filter((e) => e.collectionUID != accessToken),
]);
};
-/**
- * Return the locally persisted "last sync time" for a public collection that we
- * have pulled from remote. This can be used to perform a paginated delta pull
- * from the saved time onwards.
- *
- * Use {@link savePublic CollectionLastSyncTime} to update the value saved in
- * the storage, and {@link removePublicCollectionLastSyncTime} to remove the
- * saved value from the storage.
- *
- * @param accessToken The access token that identifies the public album whose
- * last sync time we want.
- */
export const savedPublicCollectionLastSyncTime = (accessToken: string) =>
LocalTimestamp.parse(inMemoryStorage.getItem(`public-${accessToken}-time`));
-/**
- * Update the locally persisted timestamp that will be returned by subsequent
- * calls to {@link savedPublicCollectionLastSyncTime}.
- */
export const savePublicCollectionLastSyncTime = (
accessToken: string,
time: number,
@@ -210,31 +98,13 @@ export const savePublicCollectionLastSyncTime = (
inMemoryStorage.setItem(`public-${accessToken}-time`, time);
};
-/**
- * Remove the locally persisted timestamp, if any, previously saved for a
- * collection using {@link savedPublicCollectionLastSyncTime}.
- */
export const removePublicCollectionLastSyncTime = (accessToken: string) => {
inMemoryStorage.removeItem(`public-${accessToken}-time`);
};
-/**
- * Return the access token JWT, if any, present in our local storage for the
- * given public collection (as identified by its {@link accessToken}).
- *
- * Use {@link savePublicCollectionAccessTokenJWT} to save the value, and
- * {@link removePublicCollectionAccessTokenJWT} to remove it.
- */
export const savedPublicCollectionAccessTokenJWT = (accessToken: string) =>
LocalString.parse(inMemoryStorage.getItem(`public-${accessToken}-passkey`));
-/**
- * Update the access token JWT in our local storage for the given public
- * collection (as identified by its {@link accessToken}).
- *
- * This is the setter corresponding to
- * {@link savedPublicCollectionAccessTokenJWT}.
- */
export const savePublicCollectionAccessTokenJWT = (
accessToken: string,
passwordJWT: string,
@@ -242,10 +112,6 @@ export const savePublicCollectionAccessTokenJWT = (
inMemoryStorage.setItem(`public-${accessToken}-passkey`, passwordJWT);
};
-/**
- * Remove the access token JWT in our local storage for the given public
- * collection (as identified by its {@link accessToken}).
- */
export const removePublicCollectionAccessTokenJWT = (accessToken: string) => {
inMemoryStorage.removeItem(`public-${accessToken}-passkey`);
};
@@ -285,37 +151,11 @@ export const removePublicCollectionLinkDeviceToken = (
);
};
-/**
- * Return the previously saved uploader name, if any, present in our local
- * storage corresponding to a public collection.
- *
- * Use {@link savePublicCollectionUploaderName} to update the persisted value.
- *
- * [Note: Public albums uploader name]
- *
- * Whenever there is an upload to a public album, we ask the person doing the
- * upload for their name. This uploader name is attached as part of the public
- * magic metadata of the file so that other people know who uploaded the file.
- *
- * The public albums app also saves this value, keyed by an identifier for the
- * public collection, in the local storage so that it can prefill it the next
- * time there is an upload from the same client.
- *
- * @param accessToken The access token that identifies the public album whose
- * saved uploader name we want.
- */
export const savedPublicCollectionUploaderName = (accessToken: string) =>
LocalString.parse(
inMemoryStorage.getItem(`public-${accessToken}-uploaderName`),
);
-/**
- * Update the uploader name present in our local storage corresponding to a
- * public collection.
- *
- * This is the setter corresponding to
- * {@link savedPublicCollectionUploaderName}.
- */
export const savePublicCollectionUploaderName = (
accessToken: string,
uploaderName: string,
diff --git a/web/apps/embed/src/services/public-collection.ts b/web/apps/embed/src/services/public-collection.ts
index 5c51246e73..0ae2d8fe16 100644
--- a/web/apps/embed/src/services/public-collection.ts
+++ b/web/apps/embed/src/services/public-collection.ts
@@ -1,10 +1,3 @@
-/**
- * @file Public collection service for embed app
- *
- * This is a copy of the public-collection service that uses the embed app's
- * in-memory storage instead of the original public-albums-fdb storage.
- */
-
import { deriveKey } from "ente-base/crypto";
import {
authenticatedPublicAlbumsDeviceLimitRequestHeaders,
@@ -38,28 +31,6 @@ import {
savePublicCollectionLastSyncTime,
} from "./public-albums-storage";
-/**
- * Verify with remote that the password entered by the user is the same as the
- * password that was set by the person who shared the public album.
- *
- * The verification is done on a password hash that we check with remote. If
- * they match, remote will provide us with another token that can be used to
- * make API calls for this password protected public album.
- *
- * If they don't match, or if {@link accessToken} itself has expired, then
- * remote will return a HTTP 401.
- *
- * @param publicURL Data about the public album.
- *
- * @param password The password entered by the user.
- *
- * @param token The access token to make API requests for a particular public
- * album.
- *
- * @returns A accessTokenJWT.
- *
- * See [Note: Password token for public albums requests]
- */
export const verifyPublicAlbumPassword = async (
publicURL: PublicURL,
password: string,
@@ -85,26 +56,6 @@ export const verifyPublicAlbumPassword = async (
return z.object({ jwtToken: z.string() }).parse(await res.json()).jwtToken;
};
-/**
- * Fetch a public collection from remote using its access key, decrypt it using
- * the provided key, save the collection in our local storage for subsequent
- * use, and return it.
- *
- * This function modifies local state.
- *
- * @param accessToken A public collection access key obtained from the public
- * URL path token, or from the legacy "t" query parameter.
- *
- * The access key serves to both identify the public collection, and also
- * authenticate the request. See: [Note: Public album access token].
- *
- * @param collectionKey The base64 encoded key that can be used to decrypt the
- * collection obtained from remote.
- *
- * The collection key is obtained from the fragment portion of the public URL
- * (the fragment is a client side only portion that can be used to have local
- * secrets that are not sent by the browser to the server).
- */
export const pullCollection = async (
credentials: PublicAlbumsCredentials,
collectionKey: string,
@@ -136,21 +87,6 @@ export const pullCollection = async (
} as const;
};
-/**
- * Fetch files that are part of a public collection. Save them to our local
- * storage, invoking {@link onUpdate} with the files when they become available.
- *
- * This function is a stateful loop that incrementally fetches all files that
- * are part of the public collection.
- *
- * @param credentials Credentials that can be used to make API requests for the
- * public collection.
- *
- * @param collection The collection whose files we want to fetch.
- *
- * @param onUpdate A callback that will be invoked with the files when they
- * become available.
- */
export const pullPublicCollectionFiles = async (
credentials: PublicAlbumsCredentials,
collection: Collection,
@@ -185,8 +121,6 @@ export const pullPublicCollectionFiles = async (
credentials.accessToken,
);
- // The files are returned in insertion order, not in the ascending
- // order of their creation time.
const newFiles = [...existingFiles, ...files];
savePublicCollectionFiles(credentials.accessToken, newFiles);
@@ -201,10 +135,6 @@ export const pullPublicCollectionFiles = async (
}
};
-/**
- * Remove all data associated with the public collection (identified by the
- * given {@link accessToken}) from our local storage.
- */
export const removePublicCollectionFileData = (accessToken: string) => {
removePublicCollectionFiles(accessToken);
removePublicCollectionLastSyncTime(accessToken);
diff --git a/web/apps/ensu/src/components/MarkdownRenderer.tsx b/web/apps/ensu/src/components/MarkdownRenderer.tsx
index 3591ef32b3..b20a6ffae3 100644
--- a/web/apps/ensu/src/components/MarkdownRenderer.tsx
+++ b/web/apps/ensu/src/components/MarkdownRenderer.tsx
@@ -59,8 +59,8 @@ const CodeBlock = ({ children, node: _node, ...rest }: PreProps) => {
textarea.select();
try {
document.execCommand("copy");
- } catch (_error) {
- // Ignore copy errors for unsupported environments.
+ } catch {
+ // The legacy copy path has no failure recourse.
} finally {
document.body.removeChild(textarea);
}
@@ -103,7 +103,7 @@ const openExternalUrl = async (url: string) => {
await openUrl(url);
return;
} catch {
- // Fall back to the browser open path below.
+ // Fall through to window.open.
}
}
diff --git a/web/apps/ensu/src/components/chat/ChatDialogs.tsx b/web/apps/ensu/src/components/chat/ChatDialogs.tsx
index fb98c5fafd..5fc4e3d85a 100644
--- a/web/apps/ensu/src/components/chat/ChatDialogs.tsx
+++ b/web/apps/ensu/src/components/chat/ChatDialogs.tsx
@@ -158,7 +158,7 @@ export const ChatDialogs = memo(
await openUrl(url);
return;
} catch {
- // fall through to browser open fallback
+ // Fall through to window.open.
}
}
@@ -170,7 +170,6 @@ export const ChatDialogs = memo(
}
};
- // --- Model settings draft state ---
const [draftContextLength, setDraftContextLength] = React.useState("");
const [draftMaxTokens, setDraftMaxTokens] = React.useState("");
const [draftContextError, setDraftContextError] = React.useState<
@@ -185,7 +184,6 @@ export const ChatDialogs = memo(
const [showBackupComingSoon, setShowBackupComingSoon] =
React.useState(false);
- // --- System prompt draft state ---
const [draftSystemPrompt, setDraftSystemPrompt] = React.useState("");
const modelOptions = React.useMemo(
@@ -196,7 +194,6 @@ export const ChatDialogs = memo(
[defaultModelName, suggestedModels],
);
- // Initialize model settings draft from parent state when dialog opens
React.useEffect(() => {
if (!showModelSettings) return;
setDraftModelId(
@@ -217,7 +214,8 @@ export const ChatDialogs = memo(
showModelSettings,
]);
- // Initialize system prompt draft from parent state when dialog opens
+ // The draft resyncs only when the dialog opens, hence the deps
+ // suppression below.
React.useEffect(() => {
if (!showSystemPromptSettings) return;
setDraftSystemPrompt(systemPrompt);
diff --git a/web/apps/ensu/src/components/chat/HoverRiveLogo.tsx b/web/apps/ensu/src/components/chat/HoverRiveLogo.tsx
index 1b5460ff41..0919eaa24d 100644
--- a/web/apps/ensu/src/components/chat/HoverRiveLogo.tsx
+++ b/web/apps/ensu/src/components/chat/HoverRiveLogo.tsx
@@ -72,7 +72,8 @@ const HoverRiveLogo = memo(
riveRef.current?.pause?.();
} catch {
- // noop
+ // The logo animation is decorative; ignore
+ // Rive runtime errors.
}
if (!canceled) {
setIsReady(true);
@@ -98,7 +99,8 @@ const HoverRiveLogo = memo(
try {
riveRef.current?.cleanup?.();
} catch {
- // noop
+ // The logo animation is decorative; ignore Rive runtime
+ // errors.
}
riveRef.current = null;
playbackTargetRef.current = undefined;
@@ -116,7 +118,8 @@ const HoverRiveLogo = memo(
riveRef.current?.play?.();
}
} catch {
- // noop
+ // The logo animation is decorative; ignore Rive runtime
+ // errors.
}
};
@@ -126,7 +129,8 @@ const HoverRiveLogo = memo(
riveRef.current?.pause?.();
riveRef.current?.stop?.();
} catch {
- // noop
+ // The logo animation is decorative; ignore Rive runtime
+ // errors.
}
};
diff --git a/web/apps/ensu/src/components/utils/use-file-input.ts b/web/apps/ensu/src/components/utils/use-file-input.ts
index 671f8efafc..1731833b05 100644
--- a/web/apps/ensu/src/components/utils/use-file-input.ts
+++ b/web/apps/ensu/src/components/utils/use-file-input.ts
@@ -1,54 +1,17 @@
import { useCallback, useRef } from "react";
interface UseFileInputParams {
- /**
- * If `true`, the file open dialog will ask the user to select directories.
- * Otherwise it'll ask the user to select files (default).
- */
directory?: boolean;
- /**
- * If specified, it'll restrict the type of files that the user can select
- * by setting the "accept" attribute of the underlying HTML input element we
- * use to surface the file selector dialog. For value of accept can be an
- * extension or a MIME type (See
- * https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/accept).
- */
accept?: string;
- /**
- * A callback that is invoked when the user selects files.
- *
- * It will be passed the list of {@link File}s that the user selected.
- *
- * This will be a list even if the user selected directories - in that case,
- * it will be the recursive list of files within this directory.
- *
- * If the user selected no items, then {@link onCancel} will be invoked.
- */
onSelect: (selectedFiles: File[]) => void;
- /**
- * A callback that is invoked when the user cancels on the file / directory
- * dialog.
- */
onCancel: () => void;
}
interface UseFileInputResult {
- /**
- * A function to call to get the properties that should be passed to a dummy
- * `input` element that needs to be created to anchor the select file
- * dialog. This input HTML element is not going to be visible, but it needs
- * to be part of the DOM for {@link openSelector} to have effect.
- */
getInputProps: () => React.HTMLAttributes<HTMLInputElement>;
- /**
- * A function that can be called to open the select file / directory dialog.
- */
openSelector: () => void;
}
-/**
- * Local ensu copy of file input hook to avoid affecting other apps.
- */
export const useFileInput = ({
directory,
accept,
@@ -91,17 +54,6 @@ export const useFileInput = ({
}
};
- // [Note: webkitRelativePath]
- //
- // If the webkitdirectory attribute of an <input> HTML element is set then
- // the File objects that we get will have `webkitRelativePath` property
- // containing the relative path to the selected directory.
- //
- // https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/webkitdirectory
- //
- // These paths use the POSIX path separator ("/").
- // https://stackoverflow.com/questions/62806233/when-using-webkitrelativepath-is-the-path-separator-operating-system-specific
- //
const directoryOpts = directory
? { directory: "", webkitdirectory: "" }
: {};
diff --git a/web/apps/ensu/src/pages/chat.tsx b/web/apps/ensu/src/pages/chat.tsx
index eb128801f7..9f8700e749 100644
--- a/web/apps/ensu/src/pages/chat.tsx
+++ b/web/apps/ensu/src/pages/chat.tsx
@@ -979,10 +979,8 @@ const Page: React.FC = () => {
setMaxTokens(settings.maxTokens);
};
- // Loads persisted settings and runs the one Rust model migration.
- // Settings persisted by builds that stored a model URL selection
- // convert through it once: a URL matching a current preset maps to
- // its id, anything else becomes the default.
+ // Older builds persisted a model URL selection; llm_migrate_models
+ // converts it to a model id once.
const loadSettings = async () => {
let raw = window.localStorage.getItem(MODEL_SETTINGS_STORAGE_KEY);
if (!raw) {
@@ -1535,7 +1533,6 @@ const Page: React.FC = () => {
const displayMessages = useMemo(() => {
const base = messageState.path ?? [];
- // Insert synthetic "Response was interrupted" placeholders for orphaned user messages
const augmented: ChatMessage[] = [];
for (let i = 0; i < base.length; i++) {
const msg = base[i];
@@ -1592,7 +1589,6 @@ const Page: React.FC = () => {
});
});
- // Clean up blob URLs for attachments no longer displayed.
setAttachmentPreviews((prev) => {
const next = { ...prev };
Object.keys(next).forEach((id) => {
@@ -1608,8 +1604,6 @@ const Page: React.FC = () => {
return next;
});
- // Load previews for persisted image attachments that do not have blob
- // URLs yet, such as after reopening the app.
for (const message of displayMessages) {
for (const attachment of message.attachments ?? []) {
if (attachment.kind === "image") {
@@ -1794,7 +1788,7 @@ const Page: React.FC = () => {
try {
await remove(path);
} catch {
- // ignore cleanup failures
+ // Deleting the temporary file is best effort.
}
}),
);
@@ -3151,8 +3145,6 @@ const Page: React.FC = () => {
}, 1800);
}, [advancedUnlocked]);
- // Hardcoded fallbacks used when Rust defaults are not available (web-only
- // mode). These must stay in sync with rust/crates/ensu/src/config.rs.
const fallbackSuggestedModels = useMemo(
() =>
isTauriRuntime
diff --git a/web/apps/ensu/src/services/base64.ts b/web/apps/ensu/src/services/base64.ts
index a8d9c910e0..f670f000f3 100644
--- a/web/apps/ensu/src/services/base64.ts
+++ b/web/apps/ensu/src/services/base64.ts
@@ -1,13 +1,4 @@
-/**
- * Tiny base64 helpers for browser-only code.
- *
- * These are used by the Ensu web app to move between UTF-8, bytes and base64
- * without pulling in libsodium just for encoding/decoding.
- */
-
-/** Convert a Uint8Array to a standard base64 string. */
export const bytesToBase64 = (bytes: Uint8Array): string => {
- // Chunk to avoid call stack / perf issues for larger arrays.
const chunkSize = 0x8000;
let binary = "";
for (let i = 0; i < bytes.length; i += chunkSize) {
@@ -19,7 +10,6 @@ export const bytesToBase64 = (bytes: Uint8Array): string => {
return btoa(binary);
};
-/** Convert a base64 string to bytes. */
export const base64ToBytes = (b64: string): Uint8Array<ArrayBuffer> => {
const binary = atob(b64);
const bytes = new Uint8Array(binary.length);
@@ -29,10 +19,8 @@ export const base64ToBytes = (b64: string): Uint8Array<ArrayBuffer> => {
return bytes;
};
-/** UTF-8 string to base64. */
export const utf8ToBase64 = (s: string): string =>
bytesToBase64(new TextEncoder().encode(s));
-/** Base64 to UTF-8 string. */
export const base64ToUtf8 = (b64: string): string =>
new TextDecoder().decode(base64ToBytes(b64));
diff --git a/web/apps/ensu/src/services/chat/compatibility.ts b/web/apps/ensu/src/services/chat/compatibility.ts
index 4b794d9dec..0900fb92c0 100644
--- a/web/apps/ensu/src/services/chat/compatibility.ts
+++ b/web/apps/ensu/src/services/chat/compatibility.ts
@@ -340,7 +340,7 @@ const localStorageSourceKey = async (
}
return key;
} catch {
- // Try the next migration-only key.
+ // Try the next stored key.
}
}
throw new Error("No stored key could decrypt the old local chat store");
@@ -408,7 +408,7 @@ const decryptAttachmentWith = async (
key,
] as const;
} catch {
- // Try the next migration-only key.
+ // Try the next stored key.
}
}
return undefined;
diff --git a/web/apps/ensu/src/services/chat/crypto.ts b/web/apps/ensu/src/services/chat/crypto.ts
index 68efb66b13..67fd8e4f33 100644
--- a/web/apps/ensu/src/services/chat/crypto.ts
+++ b/web/apps/ensu/src/services/chat/crypto.ts
@@ -8,7 +8,6 @@ export interface EncryptedChatPayload {
const CHAT_FIELD_PREFIX = "enc:v1";
-/** Encrypt a JSON payload for storage using the chat key (base64). */
export const encryptChatPayload = async (
payload: unknown,
chatKeyB64: string,
@@ -25,7 +24,6 @@ export const encryptChatPayload = async (
};
};
-/** Decrypt a JSON payload using the chat key (base64). */
export const decryptChatPayload = async (
{ encryptedData, header }: EncryptedChatPayload,
chatKeyB64: string,
@@ -41,7 +39,6 @@ export const decryptChatPayload = async (
return JSON.parse(base64ToUtf8(plaintextB64));
};
-/** Encrypt a string for inclusion in plaintext JSON (enc:v1:..:..). */
export const encryptChatField = async (
value: string,
chatKeyB64: string,
@@ -54,7 +51,6 @@ export const encryptChatField = async (
return `${CHAT_FIELD_PREFIX}:${encrypted.encrypted_data}:${encrypted.decryption_header}`;
};
-/** Decrypt a string field stored as enc:v1:... */
export const decryptChatField = async (
value: string,
chatKeyB64: string,
diff --git a/web/apps/ensu/src/services/chat/md5.ts b/web/apps/ensu/src/services/chat/md5.ts
index 4d990afcf0..0ee699b935 100644
--- a/web/apps/ensu/src/services/chat/md5.ts
+++ b/web/apps/ensu/src/services/chat/md5.ts
@@ -1,8 +1,3 @@
-/**
- * Minimal MD5 implementation tailored for computing a base64 encoded checksum
- * of Uint8Array inputs.
- */
-
const shifts = new Uint8Array([
7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 5, 9, 14, 20, 5,
9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11,
diff --git a/web/apps/ensu/src/services/llm/inference.ts b/web/apps/ensu/src/services/llm/inference.ts
index fccd1fe113..878a3e2f6a 100644
--- a/web/apps/ensu/src/services/llm/inference.ts
+++ b/web/apps/ensu/src/services/llm/inference.ts
@@ -113,9 +113,7 @@ class WasmInference implements InferenceBackend {
this.wllama = new Wllama(wasmPaths, wllamaConfig);
}
- async initBackend() {
- // No-op for WASM backend.
- }
+ async initBackend() {}
async loadModel(params: LoadModelParams) {
const modelUrl = ensureUrl(params.modelPath);
@@ -172,9 +170,7 @@ class WasmInference implements InferenceBackend {
return this.generateCompletion(prompt, request, onEvent);
}
- async prewarmMultimodalContext() {
- // Multimodal inference is only available through the native Tauri backend.
- }
+ async prewarmMultimodalContext() {}
cancel(jobId: number) {
if (jobId <= 0) {
@@ -487,7 +483,7 @@ class WasmInference implements InferenceBackend {
stopTokens.push(first);
}
} catch {
- // Ignore invalid stop sequences.
+ // Skip stop sequences that fail to tokenize.
}
}
diff --git a/web/apps/ensu/src/services/llm/provider.ts b/web/apps/ensu/src/services/llm/provider.ts
index 487ef436ef..916ceb4c4f 100644
--- a/web/apps/ensu/src/services/llm/provider.ts
+++ b/web/apps/ensu/src/services/llm/provider.ts
@@ -16,8 +16,6 @@ const OVERFLOW_SAFETY_TOKENS = 256;
const MIN_DESKTOP_DEFAULT_MEMORY_BYTES = 16 * 1024 * 1024 * 1024;
// These fallback values must stay in sync with rust/crates/ensu/src/config.rs.
-// When running inside Tauri, resolveDefaultModelForDevice() overwrites them with
-// values fetched from the Rust config_defaults command.
export const DEFAULT_MODEL: ModelInfo = {
id: "lfm-vl-1.6b",
name: "LFM 2.5 VL 1.6B (Q4_0)",
@@ -301,7 +299,8 @@ export class LlmProvider {
try {
await this.ensureInFlight.promise;
} catch {
- // ignore errors from previous load
+ // Wait only for settlement; the failure belongs to the
+ // original caller.
}
}
@@ -489,9 +488,8 @@ export class LlmProvider {
this.defaultModel = DESKTOP_DEFAULT_MODEL;
}
- // Overlay Rust-authoritative fields (id, name, url, mmprojUrl)
- // while keeping the web-only display fields (sizeBytes etc.)
- // as fallbacks.
+ // The Rust config_defaults payload has no size fields, so the web
+ // values above remain as display fallbacks.
try {
const defaults =
await invoke<ConfigDefaults>("config_defaults");
diff --git a/web/apps/ensu/src/services/tauri-runtime.ts b/web/apps/ensu/src/services/tauri-runtime.ts
index 20739665e5..9bb41fecef 100644
--- a/web/apps/ensu/src/services/tauri-runtime.ts
+++ b/web/apps/ensu/src/services/tauri-runtime.ts
@@ -1,10 +1,6 @@
type TauriGlobal = typeof globalThis & { isTauri?: unknown };
-/**
- * Return true if we're running under Tauri.
- *
- * This is an inlined variant of `isTauri` from `@tauri-apps/api/core`
- * so that we can detect Tauri runtime without importing the entire package.
- */
+// Inlined variant of `isTauri` from @tauri-apps/api/core, so that we can
+// detect the Tauri runtime without importing the entire package.
export const isTauriRuntime = () =>
(globalThis as TauriGlobal).isTauri === true;
diff --git a/web/apps/ensu/src/services/wasm.ts b/web/apps/ensu/src/services/wasm.ts
index efc6b3addc..0ec03ace7d 100644
--- a/web/apps/ensu/src/services/wasm.ts
+++ b/web/apps/ensu/src/services/wasm.ts
@@ -1,10 +1,3 @@
-/**
- * Lazy loader for the `ente-wasm` package or Tauri-native bindings.
- *
- * We keep this behind a dynamic import so that the WASM bundle is only loaded
- * when local crypto is needed, while Tauri uses native Rust bindings.
- */
-
import { isTauriRuntime } from "@/services/tauri-runtime";
import { loadEnteWasm } from "ente-wasm/load";
@@ -96,7 +89,7 @@ const createTauriAdapter = async (): Promise<EnteCryptoAdapter> => {
throw toNativeError(parsed.code, parsed.message);
}
} catch {
- // ignore JSON parse failures
+ // Not a structured native error; use the generic wrapper.
}
throw toNativeError("native_error", error);
}
@@ -111,7 +104,7 @@ const createTauriAdapter = async (): Promise<EnteCryptoAdapter> => {
throw toNativeError(parsed.code, parsed.message);
}
} catch {
- // ignore JSON parse failures
+ // Not a structured native error; use the generic wrapper.
}
throw toNativeError("native_error", error.message);
}
diff --git a/web/apps/ensu/src/services/whats-new.ts b/web/apps/ensu/src/services/whats-new.ts
index 933069c20f..783641966a 100644
--- a/web/apps/ensu/src/services/whats-new.ts
+++ b/web/apps/ensu/src/services/whats-new.ts
@@ -34,8 +34,7 @@ export const markDesktopWhatsNewSeen = () => {
try {
window.localStorage.setItem(storageKey, String(whatsNewVersion));
} catch {
- // localStorage can be unavailable in constrained webviews. In that
- // case, avoid blocking app startup or showing the dialog repeatedly.
+ // localStorage can be unavailable in constrained webviews.
}
};
diff --git a/web/apps/ensu/src/types/mui-theme.d.ts b/web/apps/ensu/src/types/mui-theme.d.ts
index b1cb8e35c7..2486c01542 100644
--- a/web/apps/ensu/src/types/mui-theme.d.ts
+++ b/web/apps/ensu/src/types/mui-theme.d.ts
@@ -1,8 +1,5 @@
import type { CSSProperties } from "react";
-// Ensu-specific typography variant augmentations.
-// These extend the shared MUI theme types with variants only used by ensu.
-
declare module "@mui/material/styles" {
interface TypographyVariants {
message: CSSProperties;
diff --git a/web/apps/legacy/src/features/legacy-kit/recovery.ts b/web/apps/legacy/src/features/legacy-kit/recovery.ts
index 9b89affd2e..b55f3d65ec 100644
--- a/web/apps/legacy/src/features/legacy-kit/recovery.ts
+++ b/web/apps/legacy/src/features/legacy-kit/recovery.ts
@@ -9,8 +9,8 @@ export const LegacyKitRecoverySessionSchema = z.object({
id: z.string(),
kitID: z.string(),
status: z.enum(["WAITING", "READY", "BLOCKED", "CANCELLED", "RECOVERED"]),
- // Matches the existing legacy contact recovery API: remaining microseconds,
- // not an epoch timestamp.
+ // Despite the name, this is the remaining microseconds, not an epoch
+ // timestamp.
waitTill: z.number(),
createdAt: z.number(),
});
diff --git a/web/apps/locker/src/components/CollectionSidebar.tsx b/web/apps/locker/src/components/CollectionSidebar.tsx
index a2c70c4a71..6b323ab45d 100644
--- a/web/apps/locker/src/components/CollectionSidebar.tsx
+++ b/web/apps/locker/src/components/CollectionSidebar.tsx
@@ -22,7 +22,6 @@ import { useBaseContext } from "ente-base/context";
import { t } from "i18next";
import React, { useMemo } from "react";
-/** Width of the sidebar on desktop. */
export const SIDEBAR_WIDTH = 280;
interface CollectionSidebarProps {
diff --git a/web/apps/locker/src/components/ItemCard.tsx b/web/apps/locker/src/components/ItemCard.tsx
index 8f3ad89876..b1406873ca 100644
--- a/web/apps/locker/src/components/ItemCard.tsx
+++ b/web/apps/locker/src/components/ItemCard.tsx
@@ -34,21 +34,14 @@ import React, { useCallback, useState } from "react";
interface ItemCardProps {
item: LockerItem;
- /** The user's master key, needed for file downloads. */
masterKey?: string;
onClick: () => void;
- /** Whether this card is shown in the trash view. */
isTrashView?: boolean;
isIncomingShared?: boolean;
- /** Called when the user wants to edit this item. */
onEdit?: (item: LockerItem) => void;
- /** Called when the user wants to delete (trash) this item. */
onDelete?: (item: LockerItem) => void;
- /** Optional hint shown when delete is unavailable for this item. */
deleteDisabledHint?: string;
- /** Called when the user wants to permanently delete this item. */
onPermanentlyDelete?: (items: LockerItem[]) => void;
- /** Called when the user wants to restore this item from trash. */
onRestore?: (item: LockerItem) => void;
onShareLink?: (item: LockerItem) => void;
selectionMode?: boolean;
@@ -58,10 +51,6 @@ interface ItemCardProps {
onLongPressSelect?: (item: LockerItem) => void;
}
-/**
- * A file/item row matching the Figma design:
- * Light rounded card background β€” colored icon (in rounded square) β€” title β€” actions
- */
export const ItemCard: React.FC<ItemCardProps> = React.memo(function ItemCard({
item,
masterKey,
@@ -242,7 +231,6 @@ export const ItemCard: React.FC<ItemCardProps> = React.memo(function ItemCard({
</Box>
)}
- {/* Type icon β€” colored per type in rounded square */}
<Box
sx={{
position: "relative",
@@ -369,10 +357,6 @@ export const ItemCard: React.FC<ItemCardProps> = React.memo(function ItemCard({
);
});
-// ---------------------------------------------------------------------------
-// Overflow menu for item actions
-// ---------------------------------------------------------------------------
-
const ItemOverflowMenu: React.FC<{
item: LockerItem;
onEdit?: (item: LockerItem) => void;
@@ -424,10 +408,6 @@ const ItemOverflowMenu: React.FC<{
</OverflowMenu>
);
-// ---------------------------------------------------------------------------
-// Trash-specific actions
-// ---------------------------------------------------------------------------
-
const TrashActions: React.FC<{
item: LockerItem;
onRestore?: (item: LockerItem) => void;
@@ -463,9 +443,6 @@ const TrashActions: React.FC<{
</Stack>
);
-/**
- * Background color for the icon square, per item type.
- */
const iconBgColor = (item: LockerItem): string => {
return lockerItemIconConfig(
item.type,
@@ -473,7 +450,6 @@ const iconBgColor = (item: LockerItem): string => {
).backgroundColor;
};
-/** Icon for a LockerItem. */
const itemIcon = (item: LockerItem) => {
return lockerItemIcon(item.type, {
fileName:
diff --git a/web/apps/locker/src/components/LockerNavbar.tsx b/web/apps/locker/src/components/LockerNavbar.tsx
index b2a1648f2d..51b33086bf 100644
--- a/web/apps/locker/src/components/LockerNavbar.tsx
+++ b/web/apps/locker/src/components/LockerNavbar.tsx
@@ -14,25 +14,13 @@ import React, { useDeferredValue, useEffect, useState } from "react";
const contentMaxWidth = 560;
interface LockerNavbarProps {
- /** Called when the user taps the hamburger menu icon. */
onOpenSidebar: () => void;
- /** True when the mobile drawer trigger should be shown. */
showMenuButton: boolean;
- /** Sticky top offset to account for any pinned content above the navbar. */
stickyTop?: number;
- /** Current value of the Locker search query. */
searchTerm: string;
- /** Update callback for the Locker search query. */
onSearchTermChange: (value: string) => void;
}
-/**
- * Top navigation bar for the Locker web app.
- *
- * Blue gradient header matching the Figma design, with the Locker branding
- * centered. The blue gradient continues into the search bar area rendered by
- * ItemList below.
- */
export const LockerNavbar: React.FC<LockerNavbarProps> = ({
onOpenSidebar,
showMenuButton,
@@ -47,7 +35,6 @@ export const LockerNavbar: React.FC<LockerNavbarProps> = ({
onSearchTermChange(deferredSearchTerm);
}, [deferredSearchTerm, onSearchTermChange]);
- // Sync local state when parent resets searchTerm (e.g. navigation).
useEffect(() => {
setLocalSearchTerm(searchTerm);
}, [searchTerm]);
diff --git a/web/apps/locker/src/components/LockerSidebar.tsx b/web/apps/locker/src/components/LockerSidebar.tsx
index a82af0efb6..52be7baad3 100644
--- a/web/apps/locker/src/components/LockerSidebar.tsx
+++ b/web/apps/locker/src/components/LockerSidebar.tsx
@@ -60,12 +60,6 @@ interface LockerSidebarProps {
};
}
-/**
- * Left sidebar drawer for the Locker web app.
- *
- * Shows user info, storage usage, collections, trash, help & support,
- * about section, and logout.
- */
export const LockerSidebar: React.FC<LockerSidebarProps> = ({
open,
onClose,
@@ -160,7 +154,6 @@ export const LockerSidebar: React.FC<LockerSidebarProps> = ({
WebkitOverflowScrolling: "touch",
}}
>
- {/* Header */}
<Stack sx={{ px: 1, pt: 0.5, pb: 0.5 }}>
<Stack
direction="row"
diff --git a/web/apps/locker/src/i18n/locker.ts b/web/apps/locker/src/i18n/locker.ts
index b660d449e6..bfc449a888 100644
--- a/web/apps/locker/src/i18n/locker.ts
+++ b/web/apps/locker/src/i18n/locker.ts
@@ -22,12 +22,6 @@ const ensureLockerBundle = (locale: LockerLocale) => {
);
};
-/**
- * Add Locker-local translations on top of the shared web bundle.
- *
- * This keeps the Locker parity work scoped to the app instead of modifying the
- * shared i18n package.
- */
export const setupLockerI18n = () => {
ensureLockerBundle("en-US");
diff --git a/web/apps/locker/src/services/crypto.ts b/web/apps/locker/src/services/crypto.ts
index 168554ed47..e5d7613541 100644
--- a/web/apps/locker/src/services/crypto.ts
+++ b/web/apps/locker/src/services/crypto.ts
@@ -1,14 +1,3 @@
-/**
- * @file Crypto functions for the Locker app, backed by the Rust/WASM module.
- *
- * These wrappers provide the same call signatures as `ente-base/crypto` so
- * that `remote.ts` can switch from the JS libsodium implementation to the
- * pure-Rust WASM implementation by changing only the import source.
- *
- * All crypto operations β€” including chunked file-content decryption β€” are now
- * handled by the Rust/WASM module.
- */
-
import { ensureArrayBufferBacked } from "ente-base/bytes";
import type {
EncryptedBlob,
@@ -34,16 +23,8 @@ const shouldFallbackToLegacyBlobDecrypt = (error: unknown): boolean => {
return false;
};
-/**
- * Helper: ensure a {@link BytesOrB64} value is a base64 string.
- *
- * The WASM functions accept base64 strings only, but the existing code
- * sometimes passes base64 strings already. If a `Uint8Array` is received we
- * convert it.
- */
const toB64String = (v: Uint8Array | string): string => {
if (typeof v === "string") return v;
- // Standard base64 encoding (matches libsodium ORIGINAL variant)
let binary = "";
for (const byte of v) {
binary += String.fromCharCode(byte);
@@ -51,9 +32,6 @@ const toB64String = (v: Uint8Array | string): string => {
return btoa(binary);
};
-/**
- * Convert a base64 string to bytes.
- */
const fromB64String = (b64: string): Uint8Array<ArrayBuffer> => {
const binary = atob(b64);
const bytes = new Uint8Array(binary.length);
@@ -63,10 +41,6 @@ const fromB64String = (b64: string): Uint8Array<ArrayBuffer> => {
return bytes;
};
-/**
- * Decrypt a secretbox (XSalsa20-Poly1305) and return the plaintext as a
- * base64 string.
- */
export const decryptBox = async (
box: EncryptedBox,
key: Uint8Array | string,
@@ -79,9 +53,6 @@ export const decryptBox = async (
);
};
-/**
- * Decrypt a secretbox (XSalsa20-Poly1305) and return the plaintext as bytes.
- */
export const decryptBoxBytes = async (
box: EncryptedBox,
key: Uint8Array | string,
@@ -90,10 +61,6 @@ export const decryptBoxBytes = async (
return fromB64String(b64);
};
-/**
- * Decrypt a blob (single-message SecretStream / XChaCha20-Poly1305), then
- * UTF-8 decode and JSON-parse the result.
- */
export const decryptMetadataJSON = async (
blob: EncryptedBlob,
key: Uint8Array | string,
@@ -122,10 +89,6 @@ export const decryptMetadataJSON = async (
return JSON.parse(new TextDecoder().decode(fromB64String(plaintextB64)));
};
-/**
- * Open a sealed box (anonymous public-key encryption) and return the
- * plaintext as a base64 string.
- */
export const boxSealOpen = async (
encryptedData: string,
keyPair: KeyPair,
@@ -146,19 +109,6 @@ export const boxSeal = async (
return wasm.crypto_box_seal(dataB64, publicKeyB64);
};
-/**
- * Decrypt chunked stream data (file content) using the Rust/WASM module.
- *
- * This handles multi-chunk SecretStream data encrypted with 4 MB chunks β€” the
- * format used for encrypted file content in Ente.
- */
-// ---------------------------------------------------------------------------
-// Encryption helpers (for creating/updating items)
-// ---------------------------------------------------------------------------
-
-/**
- * Generate a random 32-byte key (base64).
- */
export const generateKey = async (): Promise<string> => {
const wasm = await loadCryptoReadyEnteWasm();
return wasm.crypto_generate_key();
@@ -169,10 +119,6 @@ export const md5Base64 = async (data: Uint8Array): Promise<string> => {
return wasm.crypto_md5_base64(data);
};
-/**
- * Encrypt data using SecretBox (XSalsa20-Poly1305).
- * Returns { encryptedData, nonce } as base64 strings.
- */
export const encryptBox = async (
dataB64: string,
keyB64: string,
@@ -182,10 +128,6 @@ export const encryptBox = async (
return { encryptedData: result.encrypted_data, nonce: result.nonce };
};
-/**
- * Encrypt data using SecretStream blob (XChaCha20-Poly1305, single message).
- * Returns { encryptedData, decryptionHeader } as base64 strings.
- */
export const encryptBlob = async (
dataB64: string,
keyB64: string,
@@ -198,9 +140,6 @@ export const encryptBlob = async (
};
};
-/**
- * Convert a UTF-8 string to base64.
- */
export const stringToB64 = (s: string): string => {
const encoder = new TextEncoder();
const bytes = encoder.encode(s);
@@ -209,10 +148,6 @@ export const stringToB64 = (s: string): string => {
export { fromB64String, toB64String };
-// ---------------------------------------------------------------------------
-// File encryption helpers (for file upload)
-// ---------------------------------------------------------------------------
-
export interface StreamEncryptorHandle {
key: string;
decryptionHeader: string;
@@ -264,27 +199,13 @@ export const createStreamDecryptor = async (
};
};
-/** Result of encrypting file content using chunked stream encryption. */
export interface EncryptedFileResult {
- /** Encrypted ciphertext as base64. */
encryptedData: string;
- /** Decryption header as base64. */
decryptionHeader: string;
- /** MD5 hash of the encrypted data as base64. */
md5Hash: string;
- /** The generated file encryption key as base64. */
key: string;
}
-/**
- * Encrypt file data using chunked SecretStream (4 MB chunks) via Rust/WASM.
- *
- * Generates a new random stream key, encrypts the data in 4 MB chunks, and
- * computes the MD5 hash of the ciphertext.
- *
- * @param dataB64 File content as base64.
- * @returns Encrypted data, header, MD5 hash, and generated key β€” all base64.
- */
export const encryptFileStream = async (
dataB64: string,
): Promise<EncryptedFileResult> => {
@@ -298,12 +219,6 @@ export const encryptFileStream = async (
};
};
-/**
- * Encrypt data using chunked SecretStream with an existing key.
- *
- * Same as {@link encryptFileStream} but uses the provided key.
- * Useful for encrypting thumbnails with the same file key.
- */
export const encryptFileStreamWithKey = async (
dataB64: string,
keyB64: string,
@@ -318,14 +233,8 @@ export const encryptFileStreamWithKey = async (
};
};
-/**
- * Convert a Uint8Array to base64 string.
- */
export const bytesToB64 = (bytes: Uint8Array): string => toB64String(bytes);
-/**
- * Convert a base64 string to Uint8Array.
- */
export const b64ToBytes = (b64: string): Uint8Array<ArrayBuffer> =>
fromB64String(b64);
diff --git a/web/apps/locker/src/services/remote-cache.ts b/web/apps/locker/src/services/remote-cache.ts
index 5f1a2333fe..975cf633e2 100644
--- a/web/apps/locker/src/services/remote-cache.ts
+++ b/web/apps/locker/src/services/remote-cache.ts
@@ -6,72 +6,36 @@ export interface LockerCollectionPayload {
name?: string;
}
-/**
- * A collection record stored in the Locker cache. The persisted form keeps only
- * structural metadata plus encrypted fields. Decrypted collection details can
- * be attached transiently in-memory via `payload`, but must never be written to
- * IndexedDB.
- */
export interface EncryptedCollectionRecord {
- /** Collection ID. */
id: number;
- /** Owner user ID (plaintext β€” structural metadata only). */
ownerID: number;
- /** Encrypted collection key (base64). */
encryptedKey: string;
- /** Nonce for key decryption (base64), null for shared collections. */
keyDecryptionNonce: string | undefined;
- /** Encrypted collection name (base64). */
encryptedName: string | undefined;
- /** Nonce for name decryption (base64). */
nameDecryptionNonce: string | undefined;
- /**
- * Locally encrypted collection payload that mirrors mobile's encrypted
- * collection payload storage for name and participant metadata.
- */
payloadEncryptedData?: string;
- /** Nonce for local collection payload decryption. */
payloadDecryptionNonce?: string;
- /** Version of the local encrypted collection payload. */
payloadVersion?: number;
- /** Collection type (structural metadata). */
type: string;
- /** Whether this collection is deleted on remote (key still needed for trash restore). */
isDeleted: boolean;
- /** Updation time (structural metadata). */
updationTime: number;
- /** Transient decrypted collection details kept only in memory. */
+ // Transient decrypted details. These must stay in-memory only and must
+ // never be written to IndexedDB.
payload?: LockerCollectionPayload;
}
-/**
- * An encrypted file record stored in-memory. All sensitive payloads remain
- * encrypted until explicitly decrypted for display.
- */
export interface EncryptedFileRecord {
- /** File ID (structural metadata). */
id: number;
- /** Collection this file belongs to (structural metadata). */
collectionID: number;
- /** Owner of the file, when provided by remote. */
ownerID?: number;
- /** Encrypted file key (base64). */
encryptedKey: string;
- /** Nonce for file key decryption (base64). */
keyDecryptionNonce: string;
- /** Decryption header for the actual file content blob on S3. */
fileDecryptionHeader: string;
- /** Whether the file has a downloadable backing object. */
hasObject: boolean;
- /** File size in bytes, when provided by the API. */
fileSize?: number;
- /** Encrypted file metadata. */
metadata: { encryptedData: string; decryptionHeader: string };
- /** Encrypted private magic metadata, if present. */
magicMetadata?: { version: number; data: string; header: string };
- /** Encrypted public magic metadata, if present. */
pubMagicMetadata?: { version: number; data: string; header: string };
- /** Updation time (structural metadata). */
updationTime: number;
}
@@ -80,10 +44,8 @@ export interface LockerEncryptedCache {
files: Map<number, Map<number, EncryptedFileRecord>>;
}
-/** In-memory cache: collectionID β†’ EncryptedCollectionRecord */
let encryptedCollections = new Map<number, EncryptedCollectionRecord>();
-/** In-memory cache: fileID β†’ (collectionID β†’ EncryptedFileRecord) */
let encryptedFiles = new Map<number, Map<number, EncryptedFileRecord>>();
export const createEmptyLockerCache = (): LockerEncryptedCache => ({
diff --git a/web/apps/locker/src/services/remote-collection-mutations.ts b/web/apps/locker/src/services/remote-collection-mutations.ts
index 64c79f6462..e855a93950 100644
--- a/web/apps/locker/src/services/remote-collection-mutations.ts
+++ b/web/apps/locker/src/services/remote-collection-mutations.ts
@@ -178,8 +178,8 @@ export const updateItemCollectionsWithDeps = async (
)
: null;
- // Mirror mobile's safer ordering: establish explicit new memberships
- // before we remove or auto-move any existing ones.
+ // Add the new memberships before removing existing ones so the file
+ // always retains at least one collection membership.
if (collectionIDsToAdd.length > 0) {
if (!sourceFileKeyForAdd) {
throw new Error(`File ${fileID} has no source collection`);
@@ -224,11 +224,8 @@ export const updateItemCollectionsWithDeps = async (
}
};
-/**
- * Rehomes or detaches every file from the collection before the caller
- * deletes the collection record itself. This helper intentionally does not
- * issue the final collection delete request.
- */
+// This helper only rehomes or detaches the collection's files; the caller is
+// responsible for issuing the final collection delete request.
export const deleteCollectionKeepingFilesWithDeps = async (
collection: LockerCollection,
context: CollectionMutationContext,
diff --git a/web/apps/locker/src/services/remote-uploads.ts b/web/apps/locker/src/services/remote-uploads.ts
index 7d2be54c28..afae899abe 100644
--- a/web/apps/locker/src/services/remote-uploads.ts
+++ b/web/apps/locker/src/services/remote-uploads.ts
@@ -20,13 +20,9 @@ import {
RemoteUploadURLResponseSchema,
} from "./remote-types";
-/**
- * The server requires every file to have a thumbnail. For Locker files we
- * don't need a real one, so we encrypt this tiny placeholder and set the
- * `noThumb` flag in pubMagicMetadata.
- *
- * Generated via PIL: `Image.new('RGB', (1,1), (0,0,0)).save(buf, 'JPEG')`.
- */
+// The server requires every file to have a thumbnail, so Locker uploads this
+// placeholder, a 1x1 black JPEG generated via PIL:
+// `Image.new('RGB', (1,1), (0,0,0)).save(buf, 'JPEG')`.
const BLACK_THUMBNAIL_B64 =
"/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAP//////////////////////////////////////////////////////////////////////////////////////" +
"2wBDAf//////////////////////////////////////////////////////////////////////////////////////wAARCAABAAEDASIAAhEBAxEB" +
@@ -72,13 +68,6 @@ interface UploadDeps<TCollectionRecord> {
) => Promise<void>;
}
-/**
- * Request a presigned upload URL from the server.
- *
- * @param contentLength Size of the encrypted data in bytes.
- * @param contentMd5 MD5 hash of the encrypted data as base64.
- * @returns The S3 object key and presigned upload URL.
- */
const fetchUploadURL = async (
contentLength: number,
contentMd5: string,
@@ -291,9 +280,6 @@ const createAggregateUploadProgressReporter = (
};
};
-/**
- * Upload a file to Locker with E2E encryption.
- */
export const uploadLockerFileWithDeps = async <TCollectionRecord>(
file: File,
collectionIDs: number[],
diff --git a/web/apps/locker/src/services/remote.ts b/web/apps/locker/src/services/remote.ts
index e356f9f21c..43e9f074bb 100644
--- a/web/apps/locker/src/services/remote.ts
+++ b/web/apps/locker/src/services/remote.ts
@@ -1,15 +1,3 @@
-/**
- * @file Service layer for fetching, decrypting, and caching Locker data.
- *
- * Follows the mobile app's encryption-at-rest pattern: all Locker metadata
- * stored locally in the browser (IndexedDB plus the in-memory cache) remains
- * encrypted. Decryption happens only in-memory at read time and decrypted
- * values are never persisted.
- *
- * Key hierarchy (mirrors mobile):
- * masterKey β†’ collectionKey β†’ fileKey β†’ file metadata (pubMagicMetadata)
- */
-
import type {
LockerCollection,
LockerCollectionParticipant,
@@ -127,10 +115,6 @@ export interface LockerFileShareLinkSummary {
passwordEnabled: boolean;
}
-// ---------------------------------------------------------------------------
-// File link helpers
-// ---------------------------------------------------------------------------
-
const decodeUTF8B64 = (b64: string) => utf8Decoder.decode(b64ToBytes(b64));
const generateBase62Secret = (length: number) => {
@@ -224,12 +208,6 @@ const resolveCollectionIDsWithUncategorizedFallback = async (
? Array.from(new Set(collectionIDs))
: [(await ensureUncategorizedCollection(masterKey)).id];
-/**
- * Fetch Locker file share links for the current user.
- *
- * The backend endpoint is user-wide rather than per-file, so the client
- * filters to the latest non-disabled record per file.
- */
export const fetchLockerFileShareLinks = (): Promise<
Map<number, LockerFileShareLinkSummary>
> => {
@@ -237,9 +215,6 @@ export const fetchLockerFileShareLinks = (): Promise<
return Promise.resolve(new Map<number, LockerFileShareLinkSummary>());
};
-/**
- * Get or create a public share link for a Locker file.
- */
export const getOrCreateLockerFileShareLink = async (
fileID: number,
masterKey: string,
@@ -275,9 +250,6 @@ export const getOrCreateLockerFileShareLink = async (
};
};
-/**
- * Delete a public share link for a Locker file.
- */
export const deleteLockerFileShareLink = async (
fileID: number,
linkID?: string,
@@ -307,22 +279,6 @@ export const deleteLockerFileShareLink = async (
throw lastError ?? new Error("Failed to delete file share link");
};
-// ---------------------------------------------------------------------------
-// Create info item (note, credential, physical record, emergency contact)
-// ---------------------------------------------------------------------------
-
-/**
- * Create a new info item in the specified collection(s).
- *
- * This uses the `/files/meta` endpoint for metadata-only files (no file
- * content blob, no thumbnail). The info data is stored in pubMagicMetadata.
- *
- * @param collectionIDs The collection IDs to create the item in. Falls back
- * to the user's Uncategorized collection when empty.
- * @param infoType The item type (e.g. "note", "accountCredential").
- * @param infoData The item's structured data (matching the type's schema).
- * @param masterKey The user's master key.
- */
export const createInfoItem = async (
collectionIDs: number[],
infoType: LockerItemType,
@@ -341,26 +297,24 @@ export const createInfoItem = async (
if (!collectionRecord)
throw new Error(`Collection ${collectionID} not in cache`);
- // Decrypt collection key
const collectionKey = await decryptCollectionKey(
collectionRecord,
masterKey,
);
- // Generate a random file key
const fileKey = await generateKey();
- // Encrypt file key with collection key (SecretBox)
const encryptedFileKey = await encryptBox(fileKey, collectionKey);
- // Build metadata (basic file metadata β€” title, creation time, file type)
- const now = Date.now(); // Epoch milliseconds, matching mobile Locker
+ // Locker timestamps are epoch milliseconds, unlike photos which uses
+ // microseconds.
+ const now = Date.now();
const title = infoItemTitle(infoType, infoData);
const metadata = {
title,
creationTime: now,
modificationTime: now,
- fileType: 4, // FileType.info
+ fileType: 4, // FileType.info in the mobile client's enum
};
const metadataJSON = JSON.stringify(metadata);
const encryptedMetadata = await encryptBlob(
@@ -368,7 +322,6 @@ export const createInfoItem = async (
fileKey,
);
- // Build pubMagicMetadata with info field
const pubMagicMetadata = {
info: { type: infoType, data: infoData },
noThumb: true,
@@ -376,7 +329,6 @@ export const createInfoItem = async (
const pubMMJSON = JSON.stringify(pubMagicMetadata);
const encryptedPubMM = await encryptBlob(stringToB64(pubMMJSON), fileKey);
- // POST /files/meta
const res = await fetch(await apiURL("/files/meta"), {
method: "POST",
headers: {
@@ -412,18 +364,6 @@ export const createInfoItem = async (
}
};
-// ---------------------------------------------------------------------------
-// Update info item (edit existing item's pubMagicMetadata)
-// ---------------------------------------------------------------------------
-
-/**
- * Update an existing info item's data by replacing its pubMagicMetadata.
- *
- * @param fileID The file/item ID to update.
- * @param infoType The item type.
- * @param infoData The new structured data.
- * @param masterKey The user's master key.
- */
export const updateInfoItem = async (
fileID: number,
infoType: LockerItemType,
@@ -437,7 +377,6 @@ export const updateInfoItem = async (
if (!collectionRecord)
throw new Error(`Collection ${fileRecord.collectionID} not in cache`);
- // Decrypt collection key β†’ file key
const collectionKey = await decryptCollectionKey(
collectionRecord,
masterKey,
@@ -460,8 +399,6 @@ export const updateInfoItem = async (
)) as Record<string, unknown>)
: {};
- // Build updated pubMagicMetadata by merging into the existing public
- // metadata, mirroring mobile's MetadataUpdaterService behavior.
const title = infoItemTitle(infoType, infoData);
const pubMagicMetadata = {
...existingPubMagicMetadata,
@@ -475,7 +412,6 @@ export const updateInfoItem = async (
const version = fileRecord.pubMagicMetadata?.version ?? 1;
- // PUT /files/public-magic-metadata
const res = await fetch(await apiURL("/files/public-magic-metadata"), {
method: "PUT",
headers: {
@@ -590,16 +526,6 @@ export const updateItemCollections = async (
});
};
-// ---------------------------------------------------------------------------
-// Trash operations
-// ---------------------------------------------------------------------------
-
-/**
- * Move files to trash.
- *
- * @param fileIDs The file IDs to trash.
- * @param collectionID The collection the files belong to.
- */
export const trashFiles = async (
fileIDs: number[],
collectionID: number,
@@ -617,11 +543,6 @@ export const trashFiles = async (
ensureOk(res);
};
-/**
- * Permanently delete files from trash.
- *
- * @param fileIDs The file IDs to permanently delete.
- */
export const permanentlyDeleteFromTrash = async (
fileIDs: number[],
): Promise<void> => {
@@ -636,9 +557,6 @@ export const permanentlyDeleteFromTrash = async (
ensureOk(res);
};
-/**
- * Empty the entire trash.
- */
export const emptyTrash = async (lastUpdatedAt: number): Promise<void> => {
const res = await fetch(await apiURL("/trash/empty"), {
method: "POST",
@@ -819,13 +737,6 @@ const createCollectionMutationDeps = () => ({
addFileToCollections,
});
-/**
- * Restore files from trash to a collection.
- *
- * @param items The files to restore with their source collection IDs.
- * @param targetCollectionID The target collection.
- * @param masterKey The user's master key.
- */
export const restoreFromTrash = async (
items: Pick<LockerItem, "id" | "collectionID">[],
targetCollectionID: number,
@@ -860,7 +771,6 @@ export const restoreFromTrash = async (
continue;
}
- // Decrypt file key using original collection key
const origCollectionRecord = getCollectionRecord(
fileRecord.collectionID,
);
@@ -881,7 +791,6 @@ export const restoreFromTrash = async (
origCollectionKey,
);
- // Re-encrypt file key with target collection key
const encryptedFileKey = await encryptBox(fileKey, collectionKey);
files.push({
id: item.id,
@@ -895,7 +804,6 @@ export const restoreFromTrash = async (
let { files, skippedFileIDs } = await buildRestorePayload(items);
if (files.length === 0 && skippedFileIDs.length > 0) {
- // Recover from stale cache by refetching trash metadata once.
await fetchLockerTrash(masterKey);
({ files, skippedFileIDs } = await buildRestorePayload(items));
}
@@ -923,17 +831,6 @@ export const restoreFromTrash = async (
ensureOk(res);
};
-// ---------------------------------------------------------------------------
-// Collection management
-// ---------------------------------------------------------------------------
-
-/**
- * Create a new collection.
- *
- * @param name The collection name.
- * @param masterKey The user's master key.
- * @returns The new collection's ID.
- */
export const createCollection = async (
name: string,
masterKey: string,
@@ -964,13 +861,6 @@ const ensureFavoritesCollection = async (masterKey: string) => {
});
};
-/**
- * Rename a collection.
- *
- * @param collectionID The collection to rename.
- * @param newName The new name.
- * @param masterKey The user's master key.
- */
export const renameCollection = async (
collectionID: number,
newName: string,
@@ -982,11 +872,6 @@ export const renameCollection = async (
});
};
-/**
- * Delete a collection (moves to trash).
- *
- * @param collectionID The collection to delete.
- */
export const deleteCollection = async (
collectionID: number,
opts?: { keepFiles?: boolean },
@@ -1006,9 +891,6 @@ export const deleteCollectionKeepingFiles = async (
await deleteCollection(collection.id, { keepFiles: true });
};
-/**
- * Fetch the current list of participants for a shared collection.
- */
export const fetchCollectionSharees = async (
collectionID: number,
): Promise<LockerCollectionParticipant[]> => {
@@ -1019,9 +901,6 @@ export const fetchCollectionSharees = async (
});
};
-/**
- * Share a collection with another Ente user as a viewer.
- */
export const shareCollection = async (
collectionID: number,
email: string,
@@ -1034,9 +913,6 @@ export const shareCollection = async (
});
};
-/**
- * Remove a participant from a shared collection.
- */
export const unshareCollection = async (
collectionID: number,
email: string,
@@ -1048,9 +924,6 @@ export const unshareCollection = async (
});
};
-/**
- * Leave a shared collection.
- */
export const leaveCollection = async (collectionID: number): Promise<void> => {
const res = await fetch(
await apiURL(`/collections/leave/${collectionID}`),
@@ -1059,9 +932,6 @@ export const leaveCollection = async (collectionID: number): Promise<void> => {
ensureOk(res);
};
-/**
- * Mark or unmark a Locker item as Important.
- */
export const setItemImportant = async (
fileID: number,
shouldBeImportant: boolean,
@@ -1107,10 +977,6 @@ export const setItemImportant = async (
return true;
};
-// ---------------------------------------------------------------------------
-// File upload
-// ---------------------------------------------------------------------------
-
export type { LockerUploadProgress } from "./remote-uploads";
export const uploadLockerFile = async (
diff --git a/web/apps/locker/src/types.ts b/web/apps/locker/src/types.ts
index 9fd000c702..c6542119a8 100644
--- a/web/apps/locker/src/types.ts
+++ b/web/apps/locker/src/types.ts
@@ -1,12 +1,3 @@
-/**
- * The types of items supported by Ente Locker.
- *
- * The four info types match the mobile app's InfoType enum in
- * mobile/apps/locker/lib/models/info/info_item.dart.
- *
- * "file" represents a regular file (music, document, image, etc.) that
- * does not carry structured info metadata.
- */
import { t } from "i18next";
export type LockerItemType =
@@ -28,13 +19,11 @@ export interface LockerCollectionParticipant {
role?: LockerCollectionParticipantRole;
}
-/** Data for a personal note. */
export interface PersonalNoteData {
title: string;
content: string;
}
-/** Data for an account credential (password entry). */
export interface AccountCredentialData {
name: string;
username: string;
@@ -42,31 +31,24 @@ export interface AccountCredentialData {
notes?: string;
}
-/** Data for a physical record. */
export interface PhysicalRecordData {
name: string;
location: string;
notes?: string;
}
-/** Data for an emergency contact. */
export interface EmergencyContactData {
name: string;
contactDetails: string;
notes?: string;
}
-/** Data for a generic file (non-info item). */
export interface GenericFileData {
- /** Display name (from metadata or filename). */
name: string;
- /** File size in bytes, if known. */
fileSize?: number;
- /** Whether this item has a downloadable backing object. */
hasObject?: boolean;
}
-/** Union of all item data types. */
export type LockerItemData =
| PersonalNoteData
| AccountCredentialData
@@ -74,56 +56,25 @@ export type LockerItemData =
| EmergencyContactData
| GenericFileData;
-/**
- * A decrypted item from the Locker.
- *
- * Each item corresponds to an encrypted file in a collection. Info items
- * have structured data extracted from pubMagicMetadata.info; generic files
- * have a name extracted from the file's metadata.
- */
export interface LockerItem {
- /** The uploaded file ID (unique identifier). */
id: number;
- /** The owner of the file/item, when known. */
ownerID?: number;
- /** The type of this item. */
type: LockerItemType;
- /** The type-specific data payload. */
data: LockerItemData;
- /** The collection this item belongs to. */
collectionID: number;
- /** All collections this item belongs to, when known. */
collectionIDs: number[];
- /** Epoch microseconds when this item was created. */
createdAt?: number;
- /** Epoch microseconds when this item was last updated. */
updatedAt?: number;
- /**
- * Epoch microseconds after which a trashed item will be permanently
- * deleted. Only set for items fetched from the trash.
- */
deleteBy?: number;
}
-/**
- * A decrypted Locker collection.
- *
- * Collections group related items together (similar to folders).
- */
export interface LockerCollection {
- /** The collection ID. */
id: number;
- /** The decrypted display name. */
name: string;
- /** The owner of the collection. */
owner: LockerCollectionParticipant;
- /** Collection participants excluding the owner. */
sharees: LockerCollectionParticipant[];
- /** The items in this collection. */
items: LockerItem[];
- /** The collection type (e.g. "album", "folder"). */
type: string;
- /** Whether this collection is shared with other users. */
isShared: boolean;
}
@@ -214,9 +165,6 @@ export const restoreTargetLockerCollections = (
canRestoreToCollection(collection, currentUserID),
);
-/**
- * Get the display title for a locker item.
- */
export const getItemTitle = (item: LockerItem): string => {
switch (item.type) {
case "note": {
diff --git a/web/apps/memories/src/components/LaneMemoryViewer.tsx b/web/apps/memories/src/components/LaneMemoryViewer.tsx
index 9cd1215423..5307740776 100644
--- a/web/apps/memories/src/components/LaneMemoryViewer.tsx
+++ b/web/apps/memories/src/components/LaneMemoryViewer.tsx
@@ -1,9 +1,3 @@
-/**
- * Lane-style public memory viewer.
- * This file contains the stacked-card lane experience, including lane-specific
- * playback timing, scrubbing, captions, and decorative backgrounds. It is
- * rendered by `pages/index.tsx` for the `"lane"` variant.
- */
import { styled } from "@mui/material";
import log from "ente-base/log";
import { downloadManager } from "ente-gallery/services/download";
@@ -86,10 +80,6 @@ function calculateLaneXOffset(
return sideways * exitDistance + overshoot;
}
-/**
- * Primary viewer for lane-style public memory shares.
- * Used by `pages/index.tsx` when `viewerVariant` resolves to `"lane"`.
- */
export function LaneMemoryViewer({
files,
currentIndex,
@@ -1000,10 +990,6 @@ const LaneDesktopBackgroundGrid = styled("svg")({
"radial-gradient(ellipse 82% 84% at 50% 56%, rgba(0, 0, 0, 0.9) 0%, rgba(0, 0, 0, 0.74) 44%, rgba(0, 0, 0, 0.32) 72%, transparent 100%)",
});
-/**
- * Shared SVG pattern definition for the lane background grids.
- * Used by both desktop and mobile lane background overlays in this file.
- */
function LaneBackgroundGridFill({
patternId,
filterId,
@@ -1067,10 +1053,6 @@ function LaneBackgroundGridFill({
);
}
-/**
- * Desktop lane background grid overlay.
- * Used by `LaneBackground` for the non-compact layout branch.
- */
function LaneDesktopBackgroundGridOverlay() {
return (
<LaneDesktopBackgroundGrid aria-hidden preserveAspectRatio="none">
@@ -1120,10 +1102,6 @@ const LaneMobileBackgroundGrid = styled("svg")({
"linear-gradient(180deg, rgba(0, 0, 0, 0.96) 0%, rgba(0, 0, 0, 0.78) 10%, rgba(0, 0, 0, 0.42) 24%, rgba(0, 0, 0, 0.30) 52%, rgba(0, 0, 0, 0.52) 76%, rgba(0, 0, 0, 0.92) 100%)",
});
-/**
- * Mobile lane background grid overlay.
- * Used by `LaneBackground` for the compact layout branch.
- */
function LaneMobileBackgroundGridOverlay() {
return (
<LaneMobileBackgroundGrid aria-hidden preserveAspectRatio="none">
@@ -1135,10 +1113,6 @@ function LaneMobileBackgroundGridOverlay() {
);
}
-/**
- * Chooses the correct decorative background for the lane viewer.
- * Used only by `LaneMemoryViewer`.
- */
function LaneBackground({
isCompactLayout = false,
}: {
diff --git a/web/apps/memories/src/components/MemoryViewer.tsx b/web/apps/memories/src/components/MemoryViewer.tsx
index 6121828632..2e46c70483 100644
--- a/web/apps/memories/src/components/MemoryViewer.tsx
+++ b/web/apps/memories/src/components/MemoryViewer.tsx
@@ -1,10 +1,3 @@
-/**
- * Share-style public memory viewer.
- * This file contains the full-screen viewer used for standard public memory
- * shares, including header progress, media transitions, playback controls, and
- * share-specific layout. It is rendered by `pages/index.tsx` for the `"share"`
- * variant.
- */
import { keyframes } from "@emotion/react";
import { styled, Typography } from "@mui/material";
import log from "ente-base/log";
@@ -77,10 +70,6 @@ interface SharedMemoryHeaderProps {
isVideo: boolean;
}
-/**
- * Share-viewer header with the memory title and segmented autoplay progress.
- * Used only by `MemoryViewer` for its desktop and mobile layouts.
- */
function SharedMemoryHeader({
title,
date,
@@ -114,10 +103,6 @@ function SharedMemoryHeader({
);
}
-/**
- * Primary viewer for normal public memory shares.
- * Used by `pages/index.tsx` when `viewerVariant` resolves to `"share"`.
- */
export function MemoryViewer({
files,
currentIndex,
diff --git a/web/apps/memories/src/components/PublicMemoryControls.tsx b/web/apps/memories/src/components/PublicMemoryControls.tsx
index 16e394d8d2..358f5786bf 100644
--- a/web/apps/memories/src/components/PublicMemoryControls.tsx
+++ b/web/apps/memories/src/components/PublicMemoryControls.tsx
@@ -1,9 +1,3 @@
-/**
- * Shared playback and progress controls for the public memories viewers.
- * This file contains the share viewer progress bar plus the lane-specific
- * caption, glyph, and scrubber controls used by `MemoryViewer` and
- * `LaneMemoryViewer`.
- */
import { keyframes } from "@emotion/react";
import { Box, styled } from "@mui/material";
import { useCallback, useMemo, useRef } from "react";
@@ -77,10 +71,6 @@ const LaneProgressThumb = styled("div")({
transform: "translate(-50%, -50%)",
});
-/**
- * Play/pause glyph used by the share viewer's playback button.
- * Used by `MemoryViewer`.
- */
export const PlaybackGlyph: React.FC<{ paused: boolean }> = ({ paused }) => {
if (paused) {
return (
@@ -119,10 +109,6 @@ export const PlaybackGlyph: React.FC<{ paused: boolean }> = ({ paused }) => {
);
};
-/**
- * Smaller play/pause glyph sized for the lane viewer footer controls.
- * Used by `LaneMemoryViewer`.
- */
export const LanePlaybackGlyph: React.FC<{ paused: boolean }> = ({
paused,
}) => {
@@ -163,10 +149,6 @@ export const LanePlaybackGlyph: React.FC<{ paused: boolean }> = ({
);
};
-/**
- * Formats and renders the lane caption text, including the animated numeric counter state.
- * Used by `LaneMemoryViewer`.
- */
export const LaneCaptionText: React.FC<{
model: LaneCaptionModel;
previousValue?: number;
@@ -213,10 +195,6 @@ interface LaneProgressSliderProps {
onScrubEnd?: (value: number) => void;
}
-/**
- * Scrubbable progress control for lane shares.
- * Used by `LaneMemoryViewer`.
- */
export const LaneProgressSlider: React.FC<LaneProgressSliderProps> = ({
total,
current,
@@ -375,10 +353,6 @@ interface ProgressIndicatorProps {
minimal?: boolean;
}
-/**
- * Segmented autoplay progress bar for the share viewer header.
- * Used by `MemoryViewer`.
- */
export const ProgressIndicator: React.FC<ProgressIndicatorProps> = ({
total,
current,
@@ -463,10 +437,6 @@ interface ProgressBarProps {
onComplete?: () => void;
}
-/**
- * Single progress segment used to build `ProgressIndicator`.
- * Used only within `PublicMemoryControls.tsx`.
- */
const ProgressBar: React.FC<ProgressBarProps> = ({
state,
paused,
diff --git a/web/apps/memories/src/components/PublicMemoryMedia.tsx b/web/apps/memories/src/components/PublicMemoryMedia.tsx
index 5c7a3e73b3..61604b2245 100644
--- a/web/apps/memories/src/components/PublicMemoryMedia.tsx
+++ b/web/apps/memories/src/components/PublicMemoryMedia.tsx
@@ -1,8 +1,3 @@
-/**
- * Shared media primitives for the public memories viewers.
- * This file contains the image and video renderers, loading overlay, and media
- * sizing/crop helpers used by both `MemoryViewer` and `LaneMemoryViewer`.
- */
import { Box, CircularProgress, Typography } from "@mui/material";
import log from "ente-base/log";
import {
@@ -61,10 +56,6 @@ const buildMediaStyle = ({
};
};
-/**
- * Shared loading mask for public memory media while the image or video source is resolving.
- * Used internally by `PhotoImage` and `VideoPlayer` in this file.
- */
function MediaLoadingOverlay() {
return (
<Box
@@ -98,10 +89,6 @@ export interface PhotoImageProps {
showLoadingOverlay?: boolean;
}
-/**
- * Public-memory image renderer that handles thumbnail-to-full-image loading and lane crops.
- * Used by `MemoryViewer` for share items and by `LaneMemoryViewer` for lane cards.
- */
export function PhotoImage({
file,
onFullLoad,
@@ -400,10 +387,6 @@ export interface VideoPlayerProps {
showLoadingOverlay?: boolean;
}
-/**
- * Public-memory video renderer that supports HLS playback, local video fallbacks, and lane crops.
- * Used by `MemoryViewer` for share playback and by `LaneMemoryViewer` for the active lane card.
- */
export function VideoPlayer({
file,
onReady,
diff --git a/web/apps/memories/src/components/PublicMemoryPageShell.tsx b/web/apps/memories/src/components/PublicMemoryPageShell.tsx
index 42db7b97f5..f1655e02fc 100644
--- a/web/apps/memories/src/components/PublicMemoryPageShell.tsx
+++ b/web/apps/memories/src/components/PublicMemoryPageShell.tsx
@@ -1,17 +1,8 @@
-/**
- * Shared page shell and top-level fallback states for the public memories flow.
- * This file defines the document head wrapper plus the loading, error, and
- * empty states used by `pages/index.tsx` before a viewer is rendered.
- */
import { CircularProgress, Typography } from "@mui/material";
import { Stack100vhCenter } from "ente-base/components/containers";
import Head from "next/head";
import type { PropsWithChildren } from "react";
-/**
- * Injects page-specific metadata for every public memory page.
- * Used only by `PublicMemoryPageShell` in this file.
- */
function PublicMemoryDocumentHead() {
return (
<Head>
@@ -20,10 +11,6 @@ function PublicMemoryDocumentHead() {
);
}
-/**
- * Wraps every public memory screen with the shared head metadata.
- * Used by `pages/index.tsx` and by the loading/error/empty state helpers below.
- */
export function PublicMemoryPageShell({ children }: PropsWithChildren) {
return (
<>
@@ -33,10 +20,6 @@ export function PublicMemoryPageShell({ children }: PropsWithChildren) {
);
}
-/**
- * Shared loading body used before or while a viewer chunk is resolving.
- * Used by `pages/index.tsx` and composed by `PublicMemoryLoadingState`.
- */
export function PublicMemoryLoadingContent() {
return (
<Stack100vhCenter sx={{ minHeight: "100dvh" }}>
@@ -45,10 +28,6 @@ export function PublicMemoryLoadingContent() {
);
}
-/**
- * Full-screen loading state shown while `usePublicMemoryPage` is resolving the share.
- * Used by `pages/index.tsx`.
- */
export function PublicMemoryLoadingState() {
return (
<PublicMemoryPageShell>
@@ -57,10 +36,6 @@ export function PublicMemoryLoadingState() {
);
}
-/**
- * Full-screen error state for invalid, expired, or failed public memory loads.
- * Used by `pages/index.tsx`.
- */
export function PublicMemoryErrorState({ message }: { message: string }) {
return (
<PublicMemoryPageShell>
@@ -73,10 +48,6 @@ export function PublicMemoryErrorState({ message }: { message: string }) {
);
}
-/**
- * Full-screen empty state for shares that resolve without any files.
- * Used by `pages/index.tsx`.
- */
export function PublicMemoryEmptyState() {
return (
<PublicMemoryPageShell>
diff --git a/web/apps/memories/src/components/PublicMemoryViewerShared.ts b/web/apps/memories/src/components/PublicMemoryViewerShared.ts
index 828bcd1ae5..c949f9f1a1 100644
--- a/web/apps/memories/src/components/PublicMemoryViewerShared.ts
+++ b/web/apps/memories/src/components/PublicMemoryViewerShared.ts
@@ -1,9 +1,3 @@
-/**
- * Shared types, constants, helpers, and reusable styled primitives for the
- * public memories viewers. This file supports both `MemoryViewer` and
- * `LaneMemoryViewer`, and is also imported by `pages/index.tsx` for viewer prop
- * types.
- */
import { Button, styled } from "@mui/material";
import type { EnteFile } from "ente-media/file";
import type {
@@ -52,7 +46,6 @@ export function isInteractiveTapTarget(target: EventTarget | null) {
);
}
-// Shared fullscreen root used by both `MemoryViewer` and `LaneMemoryViewer`.
export const ViewerRoot = styled("div")({
position: "relative",
width: "100vw",
@@ -69,7 +62,6 @@ export const ViewerRoot = styled("div")({
touchAction: "manipulation",
});
-// Shared branded anchor used in the footer and header CTA areas of both viewers.
export const BrandLink = styled("a")({
color: "inherit",
textDecoration: "none",
@@ -79,7 +71,6 @@ export const BrandLink = styled("a")({
flexShrink: 0,
});
-// Shared Ente wordmark image used inside `BrandLink` in both viewers.
export const EnteBrandTagImage = styled("img")({
width: "76px",
height: "auto",
@@ -103,13 +94,10 @@ const JoinNowButtonRoot = styled(Button)({
});
const MobileJoinNowButtonRoot = styled(Button)(joinNowButtonStyles);
-// Desktop-sized CTA used by both `MemoryViewer` and `LaneMemoryViewer`.
export const JoinNowButton = JoinNowButtonRoot as typeof Button;
-// Mobile CTA used by both viewer variants when actions collapse into the footer.
export const MobileJoinNowButton = MobileJoinNowButtonRoot as typeof Button;
-// Shared mobile footer action row used by both viewers.
export const ViewerFooterBar = styled("div")({
width: "100%",
display: "flex",
@@ -120,7 +108,6 @@ export const ViewerFooterBar = styled("div")({
paddingBottom: "max(2px, env(safe-area-inset-bottom, 0px))",
});
-// Shared gesture-aware media container used by both viewers around the active media.
export const PhotoContainer = styled("div")({
position: "relative",
display: "flex",
diff --git a/web/apps/memories/src/pages/index.tsx b/web/apps/memories/src/pages/index.tsx
index b94130983e..1b6b38dbf2 100644
--- a/web/apps/memories/src/pages/index.tsx
+++ b/web/apps/memories/src/pages/index.tsx
@@ -32,17 +32,9 @@ const MemoryViewer = dynamic<MemoryViewerProps>(
{ loading: ViewerChunkLoadingFallback },
);
-/**
- * Index page that handles both root redirect and memory share links
- *
- * - Root domain (/) redirects to the configured memories landing page
- * - Share links (/TOKEN#key) render the memory viewer
- *
- * This page is served for all routes via:
- * - _redirects file for Cloudflare Pages
- * - Next.js rewrites for local development
- * - nginx try_files for Docker deployment
- */
+// This single page serves every path: share links like /TOKEN#key reach it
+// via the _redirects file (Cloudflare Pages), Next.js rewrites (dev), and
+// nginx try_files (Docker), so do not add per-route pages.
export default function PublicMemoryPage() {
const {
currentIndex,
diff --git a/web/apps/memories/src/services/public-memory.ts b/web/apps/memories/src/services/public-memory.ts
index e7dd272d9c..d141b4eb37 100644
--- a/web/apps/memories/src/services/public-memory.ts
+++ b/web/apps/memories/src/services/public-memory.ts
@@ -12,11 +12,8 @@ import { z } from "zod";
export type { PublicMemoryCredentials } from "ente-base/public-memory";
-const maxMemoryShareMetadataBytes = 1024 * 1024; // 1 MiB
+const maxMemoryShareMetadataBytes = 1024 * 1024;
-/**
- * Information about a public memory share fetched from remote.
- */
export interface PublicMemoryShareInfo {
id: number;
type: "share" | "lane";
@@ -39,11 +36,6 @@ const PublicMemoryShareInfoResponse = z.object({
}),
});
-/**
- * Fetch information about a public memory share from remote.
- *
- * @param accessToken The access token from the memory share URL.
- */
export const getPublicMemoryInfo = async (
accessToken: string,
): Promise<PublicMemoryShareInfo> => {
@@ -57,9 +49,6 @@ export const getPublicMemoryInfo = async (
return memoryShare;
};
-/**
- * A file in a public memory share, with its key re-encrypted to the share key.
- */
const PublicMemoryShareFile = z.object({
file: RemoteEnteFile,
position: z.number(),
@@ -130,13 +119,6 @@ const PublicMemoryShareMetadataBaseSchema = z.looseObject({
frames: z.array(z.unknown()).optional(),
});
-/**
- * Fetch the files in a public memory share, decrypt them using the provided
- * share key, and return them as {@link EnteFile}s.
- *
- * @param accessToken The access token from the memory share URL.
- * @param shareKey The base64 encoded per-share key (from the URL hash).
- */
export const getPublicMemoryFiles = async (
accessToken: string,
shareKey: string,
@@ -149,9 +131,6 @@ export const getPublicMemoryFiles = async (
const publicFiles: PublicMemoryFile[] = [];
for (const { file, position, encryptedKey, keyDecryptionNonce } of files) {
- // The file's key is re-encrypted to the per-share key.
- // Override the file's encryptedKey/nonce with the share-level values
- // so that decryptRemoteFile can decrypt using the shareKey.
const remoteFile = { ...file, encryptedKey, keyDecryptionNonce };
const decrypted = await decryptRemoteFile(remoteFile, shareKey);
publicFiles.push({ file: decrypted, position });
@@ -168,9 +147,8 @@ const decryptMemoryShareMetadataJSON = async (
{ encryptedData: metadataCipher, nonce: metadataNonce },
shareKey,
);
- // These bytes are decrypted but not decompressed: plain JSON for regular
- // memories and gzip input for lanes. Bound them before parsing or
- // decompression; gunzipWithLimit separately caps expanded lane metadata.
+ // The plaintext is plain JSON for share memories but gzipped JSON for
+ // lanes; a failed parse below falls through to decompression.
if (metadataBytes.byteLength > maxMemoryShareMetadataBytes) {
throw new Error("Memory share metadata exceeds the allowed size");
}
@@ -187,13 +165,6 @@ const decryptMemoryShareMetadataJSON = async (
return metadataJson;
};
-/**
- * Decrypt the memory share's metadata.
- *
- * The metadata is a JSON object encrypted with the per-share key.
- * For lane shares, it can include per-frame crop data that the web app can use
- * directly for rendering without recomputing face placement.
- */
export const decryptMemoryShareMetadata = async (
metadataCipher: string,
metadataNonce: string,
@@ -223,9 +194,6 @@ export const decryptMemoryShareMetadata = async (
};
};
-/**
- * Decrypt the memory share's metadata and extract the name.
- */
export const decryptMemoryShareName = async (
metadataCipher: string,
metadataNonce: string,
diff --git a/web/apps/paste/src/features/paste/components/PasteQrCode.tsx b/web/apps/paste/src/features/paste/components/PasteQrCode.tsx
index a0422d04fe..3851513a8b 100644
--- a/web/apps/paste/src/features/paste/components/PasteQrCode.tsx
+++ b/web/apps/paste/src/features/paste/components/PasteQrCode.tsx
@@ -21,9 +21,7 @@ interface PasteQrCodeProps {
paperBg?: string;
borderRadius?: string;
showCenterLock?: boolean;
- /** When set, shows a floating close control (e.g. to dismiss the QR panel). */
onClose?: () => void;
- /** Color mode for close button hover; pass when `onClose` is used. */
resolvedMode?: PasteResolvedMode;
}
diff --git a/web/apps/paste/src/services/paste.ts b/web/apps/paste/src/services/paste.ts
index 156244741d..e3cdc0dd15 100644
--- a/web/apps/paste/src/services/paste.ts
+++ b/web/apps/paste/src/services/paste.ts
@@ -29,7 +29,7 @@ const parseError = async (
const data = (await response.json()) as { message?: string };
if (data.message) return data.message;
} catch {
- // no-op
+ // Fall back to the generic message below.
}
return `Request failed with status ${response.status}`;
};
diff --git a/web/apps/payments/src/services/billing.ts b/web/apps/payments/src/services/billing.ts
index 18c67f640d..96e96fa1c8 100644
--- a/web/apps/payments/src/services/billing.ts
+++ b/web/apps/payments/src/services/billing.ts
@@ -1,15 +1,6 @@
import { loadStripe } from "@stripe/stripe-js";
-/**
- * Communicate with Stripe using their JS SDK, and redirect back to the client.
- *
- * All necessary parameters are obtained by parsing the request parameters.
- *
- * In case of unrecoverable errors, this function will throw. Otherwise it will
- * redirect to the client or to some fallback URL.
- */
export const parseAndHandleRequest = async () => {
- // See: [Note: Intercept payments redirection to desktop app]
if (window.location.pathname == "/desktop-redirect") {
const desktopRedirectURL = new URL("ente://app/gallery");
desktopRedirectURL.search = new URL(window.location.href).search;
@@ -54,8 +45,6 @@ export const parseAndHandleRequest = async () => {
}
if (!action && !paymentToken && !productID && !redirectURL) {
- // Maybe someone attempted to directly open this page in their
- // browser. Not much we can do, just redirect them to the main site.
console.log(
"None of the required query parameters were supplied, redirecting to the ente.com",
);
@@ -118,7 +107,6 @@ const stripePublishableKey = (accountCountry: StripeAccountCountry) => {
}
};
-/** Return the {@link StripeAccountCountry} for the user. */
const getUserStripeAccountCountry = async (paymentToken: string) => {
const url = `${apiOrigin}/billing/stripe-account-country`;
const res = await fetch(url, { headers: { "X-Auth-Token": paymentToken } });
@@ -131,7 +119,6 @@ const getUserStripeAccountCountry = async (paymentToken: string) => {
throw new Error(`Unexpected response for ${url}: ${JSON.stringify(json)}`);
};
-/** Load and return the Stripe JS SDK initialized for the given country. */
const getStripe = async (
redirectURL: string,
accountCountry: StripeAccountCountry,
@@ -147,7 +134,6 @@ const getStripe = async (
}
};
-/** The flow when the user wants to buy a new subscription. */
const buySubscription = async (
productID: string,
paymentToken: string,
@@ -168,7 +154,6 @@ const buySubscription = async (
}
};
-/** Create a new checkout session on museum and return the sessionID. */
const createCheckoutSession = async (
productID: string,
paymentToken: string,
@@ -200,7 +185,6 @@ const updateSubscription = async (
);
switch (status) {
case "success": {
- // Subscription was updated successfully, nothing more required
redirectToApp(redirectURL, "success");
return;
}
@@ -401,10 +385,6 @@ const redirectForPaymentIntentStatus = (
}
};
-/**
- * Make a request to museum to update an existing Stripe subscription with
- * {@link productID} for the user.
- */
async function updateStripeSubscription(
paymentToken: string,
productID: string,
@@ -438,51 +418,19 @@ async function updateStripeSubscription(
type RedirectStatus = "success" | "fail";
type FailureReason =
- /**
- * Unable to authenticate the payment method.
- *
- * User should be shown button for fixing card via customer portal.
- */
| "authentication_failed"
- /**
- * Payment method declined results in this error.
- *
- * Show button to the customer portal.
- */
| "requires_payment_method"
- /**
- * An error in initializing the Stripe JS SDK.
- */
| "stripe_error"
| "canceled"
| "server_error";
-/**
- * Navigate to {@link redirectURL}, passing the given values as query params.
- *
- * [Note: Redirects do not interrupt script execution]
- *
- * I have been unable to find a documentation / reference source for this, but
- * in practice when I test it with a following snippet
- *
- * const nonce = Math.random();
- * console.log("before", nonce);
- * window.location.href = "http://example.org";
- * console.log("after", nonce);
- *
- * I observe that the code after the navigation also runs.
- */
+// Assigning window.location.href does not stop script execution; statements
+// after a redirect still run, so callers must return explicitly.
const redirectToApp = (
redirectURL: string,
status: RedirectStatus,
reason?: FailureReason,
) => {
- // [Note: Intercept payments redirection to desktop app]
- //
- // The desktop app passes "<our-origin>/desktop-redirect" as `redirectURL`.
- // This is just a placeholder, we want to intercept this and instead
- // redirect to the ente:// scheme protocol handler that is internally being
- // used by the desktop app.
if (new URL(redirectURL).pathname == "/desktop-redirect") {
redirectToApp("ente://app/gallery", status, reason);
return;
diff --git a/web/apps/payments/src/utils/strings.ts b/web/apps/payments/src/utils/strings.ts
index 84d96378d9..e93aac3918 100644
--- a/web/apps/payments/src/utils/strings.ts
+++ b/web/apps/payments/src/utils/strings.ts
@@ -1,10 +1,3 @@
-/**
- * User facing strings in the app.
- *
- * By keeping them separate, we make our lives easier if/when we need to
- * localize the corresponding pages. Right now, these are just the values in the
- * default language, English.
- */
const S = { error_generic: "Oops, something went wrong." };
export default S;
diff --git a/web/apps/payments/src/vite-env.d.ts b/web/apps/payments/src/vite-env.d.ts
index 90af95a138..1d0faace20 100644
--- a/web/apps/payments/src/vite-env.d.ts
+++ b/web/apps/payments/src/vite-env.d.ts
@@ -1,29 +1,8 @@
-/* Type shims provided by vite, e.g. for asset imports
- https://vitejs.dev/guide/features.html#client-types */
-
/// <reference types="vite/client" />
-/** Types for the vite injected environment variables */
interface ImportMetaEnv {
- /**
- * Override the origin (scheme://host:port) of Ente's API to connect to.
- *
- * This is useful when testing or connecting to alternative installations.
- */
readonly VITE_ENTE_ENDPOINT: string | undefined;
- /**
- * Override the publishable Stripe key to use when the user's account
- * country is "US".
- *
- * This is useful when testing.
- */
readonly VITE_STRIPE_US_PUBLISHABLE_KEY: string | undefined;
- /**
- * Override the publishable Stripe key to use when the user's account
- * country is "IN".
- *
- * This is useful when testing.
- */
readonly VITE_STRIPE_IN_PUBLISHABLE_KEY: string | undefined;
}
diff --git a/web/apps/payments/vite.config.ts b/web/apps/payments/vite.config.ts
index e3b37b3bb9..8086301628 100644
--- a/web/apps/payments/vite.config.ts
+++ b/web/apps/payments/vite.config.ts
@@ -1,5 +1,4 @@
import react from "@vitejs/plugin-react";
import { defineConfig } from "vite";
-// https://vitejs.dev/config/
export default defineConfig({ plugins: [react()] });
diff --git a/web/apps/share/src/components/file-share/CollectionShareView.tsx b/web/apps/share/src/components/file-share/CollectionShareView.tsx
index 86d69fe20c..83e2d53362 100644
--- a/web/apps/share/src/components/file-share/CollectionShareView.tsx
+++ b/web/apps/share/src/components/file-share/CollectionShareView.tsx
@@ -184,7 +184,6 @@ export const CollectionShareView: React.FC = () => {
</Box>
)}
- {/* Item detail view - uses same component as single-file share */}
{selectedItem && !loading && !requiresPassword && !error && (
<SharedItemDetails
itemInfo={selectedItem}
@@ -201,7 +200,6 @@ export const CollectionShareView: React.FC = () => {
/>
)}
- {/* Collection list view */}
{collectionInfo &&
!loading &&
!selectedItem &&
diff --git a/web/apps/share/src/components/file-share/FileShareView.tsx b/web/apps/share/src/components/file-share/FileShareView.tsx
index d74e8557b5..e9bd43b504 100644
--- a/web/apps/share/src/components/file-share/FileShareView.tsx
+++ b/web/apps/share/src/components/file-share/FileShareView.tsx
@@ -66,7 +66,6 @@ export const FileShareView: React.FC = () => {
},
}}
>
- {/* Ente Locker Logo */}
<Box
sx={{
width: "100%",
@@ -99,7 +98,6 @@ export const FileShareView: React.FC = () => {
</a>
</Box>
- {/* Main Container */}
<Box
sx={{
display: "flex",
@@ -118,7 +116,6 @@ export const FileShareView: React.FC = () => {
: 0,
}}
>
- {/* Loading State */}
{loading && (
<Box
sx={{
@@ -135,7 +132,6 @@ export const FileShareView: React.FC = () => {
</Box>
)}
- {/* Error State */}
{error && !loading && (
<Box
sx={{
@@ -156,10 +152,8 @@ export const FileShareView: React.FC = () => {
</Box>
)}
- {/* File Info Display */}
{fileInfo && iconInfo && !loading && (
<>
- {/* File Info - Centered */}
<Box
sx={{
display: "flex",
@@ -171,7 +165,6 @@ export const FileShareView: React.FC = () => {
marginBottom: 4,
}}
>
- {/* Large File Icon */}
<Box
sx={{
backgroundColor:
@@ -186,7 +179,6 @@ export const FileShareView: React.FC = () => {
{iconInfo.icon}
</Box>
- {/* File Name */}
<Typography
variant="h5"
sx={{
@@ -202,7 +194,6 @@ export const FileShareView: React.FC = () => {
{fileInfo.fileName}
</Typography>
- {/* File Size - only show if no locker type */}
{!fileInfo.lockerType && (
<Typography
variant="body"
@@ -220,7 +211,6 @@ export const FileShareView: React.FC = () => {
</Typography>
)}
- {/* Locker Type Display */}
{fileInfo.lockerType &&
fileInfo.lockerInfoData && (
<LockerTypeDisplay
@@ -231,7 +221,6 @@ export const FileShareView: React.FC = () => {
)}
</Box>
- {/* Download Button - Only show if not a LockerInfoType */}
{!fileInfo.lockerType && (
<Box sx={{ width: "100%", mt: 4 }}>
<Button
diff --git a/web/apps/share/src/components/file-share/SharedItemDetails.tsx b/web/apps/share/src/components/file-share/SharedItemDetails.tsx
index f49bb89936..c2b4d05074 100644
--- a/web/apps/share/src/components/file-share/SharedItemDetails.tsx
+++ b/web/apps/share/src/components/file-share/SharedItemDetails.tsx
@@ -81,7 +81,6 @@ export const SharedItemDetails: React.FC<SharedItemDetailsProps> = ({
marginBottom: 4,
}}
>
- {/* Large File Icon */}
<Box
sx={{
backgroundColor: iconInfo.backgroundColor,
@@ -95,7 +94,6 @@ export const SharedItemDetails: React.FC<SharedItemDetailsProps> = ({
{iconInfo.icon}
</Box>
- {/* File Name */}
<Typography
variant="h5"
sx={{
@@ -109,7 +107,6 @@ export const SharedItemDetails: React.FC<SharedItemDetailsProps> = ({
{itemInfo.fileName}
</Typography>
- {/* File Size - only show for regular files */}
{!itemInfo.lockerType && (
<Typography
variant="body"
@@ -121,7 +118,6 @@ export const SharedItemDetails: React.FC<SharedItemDetailsProps> = ({
</Typography>
)}
- {/* Locker Type Display */}
{itemInfo.lockerType && itemInfo.lockerInfoData && (
<LockerTypeDisplay
type={itemInfo.lockerType}
@@ -131,7 +127,6 @@ export const SharedItemDetails: React.FC<SharedItemDetailsProps> = ({
)}
</Box>
- {/* Download Button - only for regular files */}
{!itemInfo.lockerType && onDownload && (
<Box sx={{ width: "100%", mt: 4 }}>
<Button
diff --git a/web/apps/share/src/hooks/useFileShare.ts b/web/apps/share/src/hooks/useFileShare.ts
index 82f549c10b..c8d25d4878 100644
--- a/web/apps/share/src/hooks/useFileShare.ts
+++ b/web/apps/share/src/hooks/useFileShare.ts
@@ -65,7 +65,6 @@ export const useFileShare = (): UseFileShareResult => {
useEffect(() => {
const loadFileInfo = async () => {
try {
- // Extract token from pathname (e.g., /4MzPEanZK8)
const token = window.location.pathname.slice(1);
if (!token) {
@@ -107,7 +106,6 @@ export const useFileShare = (): UseFileShareResult => {
keyMaterial,
);
- // Check if decryption failed (invalid key)
if (
decryptedInfo.fileName === "Unknown file" ||
decryptedInfo.fileName === "Encrypted file" ||
diff --git a/web/apps/share/src/pages/index.tsx b/web/apps/share/src/pages/index.tsx
index c8febe910c..eaef6566eb 100644
--- a/web/apps/share/src/pages/index.tsx
+++ b/web/apps/share/src/pages/index.tsx
@@ -17,19 +17,9 @@ const detectShareView = (pathname: string): "file" | "collection" | null => {
return "file";
};
-/**
- * Index page that handles root redirect, single-file share links, and
- * locker collection share links.
- *
- * - Root domain (/) redirects to ente.com/locker
- * - Single-file share links (/{token}#{key}) render FileShareView
- * - Collection share links (/c/{token}#{collectionKey}) render CollectionShareView
- *
- * This page is served for all routes via:
- * - _redirects file for Cloudflare Pages
- * - Next.js rewrites for local development
- * - nginx try_files for Docker deployment
- */
+// Every route is served by this page: the _redirects file (Cloudflare Pages),
+// Next.js rewrites (dev), and nginx try_files (Docker) all rewrite to it, and
+// it reads the share token from window.location instead of router params.
const Page: React.FC = () => {
const [hideContent, setHideContent] = useState(false);
const [shareView, setShareView] = useState<"file" | "collection" | null>(
diff --git a/web/apps/share/src/services/collection-share.ts b/web/apps/share/src/services/collection-share.ts
index fcc7bc04ba..923d496fb0 100644
--- a/web/apps/share/src/services/collection-share.ts
+++ b/web/apps/share/src/services/collection-share.ts
@@ -262,8 +262,8 @@ const fetchPublicCollectionDiff = async (
}
}
hasMore = parsed.hasMore;
- // Defensive guard: if the server claims more pages but sinceTime did
- // not advance, stop to avoid spinning on a broken server contract.
+ // Stop when the server claims more pages but sinceTime did not
+ // advance, to avoid looping forever on a broken pagination contract.
if (hasMore && sinceTime === prevSinceTime) break;
}
diff --git a/web/apps/share/src/services/file-share.ts b/web/apps/share/src/services/file-share.ts
index 425f442faf..6960b9252e 100644
--- a/web/apps/share/src/services/file-share.ts
+++ b/web/apps/share/src/services/file-share.ts
@@ -40,13 +40,10 @@ const isDeviceLimitExceededResponse = async (response: Response) => {
}
};
-/**
- * Extract file key from URL hash (similar to extractCollectionKeyFromShareURL)
- */
export const extractFileKeyFromURL = async (
url: URL,
): Promise<LinkKeyMaterial | null> => {
- const hashValue = url.hash.slice(1).split("-")[0]; // Remove '#' prefix and take part before hyphen
+ const hashValue = url.hash.slice(1).split("-")[0];
if (!hashValue) return null;
try {
@@ -56,22 +53,18 @@ export const extractFileKeyFromURL = async (
return { type: "secret", passphrase: hashValue };
}
- // Support both base58 and hex encoding for legacy links
+ // Legacy links embed the raw key, base58 encoded (about 44 chars) or
+ // hex encoded (64 chars); the length discriminates between the two.
if (hashValue.length < 50) {
- // Base58 encoded - convert to base64
const decoded = bs58.decode(hashValue);
return { type: "direct", fileKey: await toB64(decoded) };
}
- // Hex encoded - convert to base64
return { type: "direct", fileKey: await fromHex(hashValue) };
} catch {
return null;
}
};
-/**
- * Fetch file info from the server
- */
export const fetchFileInfo = async (
accessToken: string,
linkDeviceToken?: string,
@@ -97,7 +90,7 @@ export const fetchFileInfo = async (
try {
errorBody = (await response.json()) as { error?: string };
} catch {
- // Ignore JSON parsing errors and use generic message
+ // Ignore JSON parse errors and fall back to the generic message.
}
if (errorBody?.error === "expired token") {
throw new Error("This link has expired.");
@@ -114,9 +107,6 @@ export const fetchFileInfo = async (
};
};
-/**
- * Decrypt file key from encrypted key and nonce
- */
const decryptFileKey = async (
encryptedKey: string,
keyDecryptionNonce: string,
@@ -129,14 +119,12 @@ const decryptFileKey = async (
);
return await toB64(decryptedKeyBytes);
} catch {
- // If decryption fails, assume the link key IS the file key
+ // Older links use the link key itself as the file key; fall back to
+ // it when unwrapping fails.
return linkKey;
}
};
-/**
- * Decrypt file metadata
- */
const decryptMetadata = async (
encryptedData: string,
decryptionHeader: string,
@@ -153,9 +141,6 @@ const decryptMetadata = async (
}
};
-/**
- * Decrypt pubMagicMetadata
- */
const decryptPubMagicMetadata = async (
data: string,
header: string,
@@ -195,9 +180,6 @@ const normalizeLockerInfoType = (
}
};
-/**
- * Parse locker info from pubMagicMetadata
- */
const parseLockerInfo = (
rawInfo: string | LockerInfo | undefined,
): LockerInfo | undefined => {
@@ -221,9 +203,6 @@ const parseLockerInfo = (
return { ...parsedInfo, type: normalizeLockerInfoType(parsedInfo.type) };
};
-/**
- * Extract file information from metadata and fallback sources
- */
const extractFileInfo = (
metadata: FileMetadata,
pubMagicMetadata: {
@@ -307,9 +286,6 @@ const resolveFileKey = async (
return keyMaterial.fileKey;
};
-/**
- * Decrypt file info
- */
export const decryptFileInfo = async (
fileLinkInfo: FileLinkInfo,
keyMaterial: LinkKeyMaterial,
@@ -327,13 +303,11 @@ export const decryptFileInfo = async (
const fileId = file.id || 0;
const fileDecryptionHeader = file.file?.decryptionHeader;
- // Extract nested encrypted metadata and decryption header
const encryptedMetadata =
file.metadata?.encryptedData || file.encryptedMetadata;
const metadataDecryptionHeader =
file.metadata?.decryptionHeader || file.metadataDecryptionHeader;
- // Check if we have the necessary fields for decryption
if (!encryptedMetadata || !metadataDecryptionHeader) {
return {
id: fileId,
@@ -347,14 +321,12 @@ export const decryptFileInfo = async (
};
}
- // Decrypt metadata
const metadata = await decryptMetadata(
encryptedMetadata,
metadataDecryptionHeader,
fileKey,
);
- // Try to decrypt pubMagicMetadata if it exists
let pubMagicMetadata: {
info?: string | LockerInfo;
editedName: string;
@@ -367,11 +339,9 @@ export const decryptFileInfo = async (
);
}
- // Parse locker info
const infoObject = parseLockerInfo(pubMagicMetadata?.info);
const lockerType = infoObject?.type;
- // Extract file info
const { fileName, fileSize, uploadedTime } = extractFileInfo(
metadata,
pubMagicMetadata,
@@ -396,7 +366,6 @@ export const decryptFileInfo = async (
keyMaterial.type === "secret"
? keyMaterial.passphrase
: keyMaterial.fileKey;
- // Return partial info if decryption fails
if (!fileLinkInfo.file) {
return {
id: 0,
@@ -424,9 +393,6 @@ export const decryptFileInfo = async (
}
};
-/**
- * Download and decrypt file
- */
export const downloadFile = async (
accessToken: string,
fileKey: string,
@@ -434,7 +400,6 @@ export const downloadFile = async (
fileDecryptionHeader?: string,
fileNonce?: string,
): Promise<void> => {
- // Fetch the encrypted file from the server
const response = await fetchFileLinkFile(accessToken);
if (!response.ok) {
@@ -444,7 +409,6 @@ export const downloadFile = async (
throw new Error(`Failed to download file: ${response.statusText}`);
}
- // Get the response stream
const body = response.body;
if (!body) {
throw new Error("Response body is empty");
@@ -455,26 +419,21 @@ export const downloadFile = async (
let decryptedData: Uint8Array<ArrayBuffer>;
if (fileDecryptionHeader) {
- // Modern format: Decrypt the file using the decryption header
decryptedData = await decryptStreamBytes(
{ encryptedData, decryptionHeader: fileDecryptionHeader },
fileKey,
);
} else if (fileNonce) {
- // Legacy format: Use box decryption with nonce
decryptedData = await decryptBoxBytes(
{ encryptedData: await toB64(encryptedData), nonce: fileNonce },
fileKey,
);
} else {
- // No encryption information, return as is
decryptedData = encryptedData;
}
- // Create a blob from the decrypted data
const blob = new Blob([decryptedData]);
- // Create download link
const blobUrl = URL.createObjectURL(blob);
const a = document.createElement("a");
a.href = blobUrl;
@@ -485,9 +444,6 @@ export const downloadFile = async (
URL.revokeObjectURL(blobUrl);
};
-/**
- * Format file size to human readable format
- */
export const formatFileSize = (bytes: number): string => {
if (bytes === 0) return "0 Bytes";
diff --git a/web/apps/share/src/types/file-share.ts b/web/apps/share/src/types/file-share.ts
index 922407bbb2..2c14754240 100644
--- a/web/apps/share/src/types/file-share.ts
+++ b/web/apps/share/src/types/file-share.ts
@@ -29,7 +29,8 @@ export interface FileLinkInfo {
data?: string;
header?: string;
};
- // Legacy field names
+ // Older responses used these flat fields instead of the nested
+ // metadata object above.
encryptedMetadata?: string;
metadataDecryptionHeader?: string;
fileSize?: number;
diff --git a/web/apps/share/src/utils/file-type.tsx b/web/apps/share/src/utils/file-type.tsx
index 133b31ebcb..d624253bc0 100644
--- a/web/apps/share/src/utils/file-type.tsx
+++ b/web/apps/share/src/utils/file-type.tsx
@@ -27,10 +27,6 @@ interface LockerFileIconOptions {
size?: number;
}
-/**
- * Extract the file extension from a filename
- * Returns lowercase extension without the dot, or empty string if no extension
- */
const getFileExtension = (fileName: string): string => {
const lastDot = fileName.lastIndexOf(".");
if (lastDot === -1 || lastDot === fileName.length - 1) {
@@ -39,9 +35,6 @@ const getFileExtension = (fileName: string): string => {
return fileName.slice(lastDot + 1).toLowerCase();
};
-/**
- * Check if file extension is an image
- */
const isImageExtension = (extension: string): boolean => {
const imageExtensions = [
"jpg",
@@ -60,9 +53,6 @@ const isImageExtension = (extension: string): boolean => {
return imageExtensions.includes(extension);
};
-/**
- * Check if file extension is a video
- */
const isVideoExtension = (extension: string): boolean => {
const videoExtensions = [
"mp4",
@@ -82,9 +72,6 @@ const isVideoExtension = (extension: string): boolean => {
return videoExtensions.includes(extension);
};
-/**
- * Check if file extension is a document/text file
- */
const isDocumentExtension = (extension: string): boolean => {
const documentExtensions = [
"pdf",
@@ -105,16 +92,12 @@ const isDocumentExtension = (extension: string): boolean => {
return documentExtensions.includes(extension);
};
-/**
- * Get icon based on locker info type (first priority) or file extension (fallback)
- */
export const getLockerFileIcon = (
fileName: string,
options: LockerFileIconOptions = {},
): LockerIconInfo => {
const { lockerType, size = 42 } = options;
- // First priority: Check locker info type
if (lockerType) {
switch (lockerType as LockerInfoType) {
case LockerInfoType.Note:
@@ -167,7 +150,6 @@ export const getLockerFileIcon = (
}
}
- // Second priority: Detect based on file extension
const extension = getFileExtension(fileName);
if (isImageExtension(extension)) {
@@ -201,7 +183,6 @@ export const getLockerFileIcon = (
};
}
- // Default: Generic file icon
return {
icon: <HugeiconsIcon icon={File02Icon} size={size} color="#757575" />,
backgroundColor: "#FAFAFA",
diff --git a/web/apps/space/src/services/spaceLogout.ts b/web/apps/space/src/services/spaceLogout.ts
index 0e1407db54..2aa6fa8d9b 100644
--- a/web/apps/space/src/services/spaceLogout.ts
+++ b/web/apps/space/src/services/spaceLogout.ts
@@ -21,6 +21,5 @@ export const spaceLogout = async () => {
error,
);
}
- // accountLogout() is used to clear the remaining account state and browser caches
await accountLogout();
};
diff --git a/web/apps/space/src/utils/thumbhash.ts b/web/apps/space/src/utils/thumbhash.ts
index 94a987787d..6ea33a4a2f 100644
--- a/web/apps/space/src/utils/thumbhash.ts
+++ b/web/apps/space/src/utils/thumbhash.ts
@@ -48,14 +48,6 @@ const bytesToBase64 = (bytes: ByteSequence) => btoa(byteStringFromBytes(bytes));
const base64ToBytes = (value: string) => bytesFromByteString(atob(value));
-/**
- * Encodes an RGBA image to a ThumbHash. RGB should not be premultiplied by A.
- *
- * @param w The width of the input image. Must be <=100px.
- * @param h The height of the input image. Must be <=100px.
- * @param rgba The pixels in the input image, row-by-row. Must have w*h*4 elements.
- * @returns The ThumbHash as a Uint8Array.
- */
export function rgbaToThumbHash(w: number, h: number, rgba: RGBABytes) {
if (w > 100 || h > 100) throw new Error(`${w}x${h} doesn't fit in 100x100`);
const { PI, abs, cos, max, round } = Math;
@@ -172,12 +164,6 @@ export function rgbaToThumbHash(w: number, h: number, rgba: RGBABytes) {
return new Uint8Array(hash);
}
-/**
- * Decodes a ThumbHash to an RGBA image. RGB is not premultiplied by A.
- *
- * @param hash The bytes of the ThumbHash.
- * @returns The width, height, and pixels of the rendered placeholder image.
- */
export function thumbHashToRGBA(hash: Uint8Array) {
const { PI, cos, max, min, round } = Math;
@@ -276,12 +262,6 @@ export function thumbHashToRGBA(hash: Uint8Array) {
return { w, h, rgba };
}
-/**
- * Extracts the approximate aspect ratio of the original image.
- *
- * @param hash The bytes of the ThumbHash.
- * @returns The approximate aspect ratio, width / height.
- */
export function thumbHashToApproximateAspectRatio(hash: Uint8Array) {
const header = hash[3]!;
const hasAlpha = hash[2]! & 0x80;
@@ -291,14 +271,6 @@ export function thumbHashToApproximateAspectRatio(hash: Uint8Array) {
return lx / ly;
}
-/**
- * Encodes an RGBA image to a PNG data URL. RGB should not be premultiplied by A.
- *
- * @param w The width of the input image. Must be <=100px.
- * @param h The height of the input image. Must be <=100px.
- * @param rgba The pixels in the input image, row-by-row. Must have w*h*4 elements.
- * @returns A data URL containing a PNG for the input image.
- */
export function rgbaToDataURL(w: number, h: number, rgba: RGBABytes) {
const row = w * 4 + 1;
const idat = 6 + h * (5 + row);
@@ -413,12 +385,6 @@ export function rgbaToDataURL(w: number, h: number, rgba: RGBABytes) {
return `data:image/png;base64,${bytesToBase64(bytes)}`;
}
-/**
- * Decodes a ThumbHash to a PNG data URL.
- *
- * @param hash The bytes of the ThumbHash.
- * @returns A data URL containing a PNG for the rendered ThumbHash.
- */
export function thumbHashToDataURL(hash: Uint8Array) {
const image = thumbHashToRGBA(hash);
return rgbaToDataURL(image.w, image.h, image.rgba);
diff --git a/web/packages/utils/array.ts b/web/packages/utils/array.ts
index e6137bb3dd..fa2ef34805 100644
--- a/web/packages/utils/array.ts
+++ b/web/packages/utils/array.ts
@@ -1,38 +1,16 @@
-/**
- * Shuffle.
- *
- * Return a new array containing the shuffled elements of the given array.
- *
- * The algorithm used is not the most efficient, but is effectively a one-liner
- * whilst being reasonably efficient. To each element we assign a random key,
- * then we sort by this key. Since the key is random, the sorted array will have
- * the original elements in a random order.
- */
export const shuffled = <T>(xs: T[]): T[] =>
xs
.map((x) => [Math.random(), x])
.sort()
.map(([, x]) => x) as T[];
-/**
- * Return a random sample of {@link n} elements from the given {@link items}.
- *
- * Functionally this is equivalent to `shuffled(items).slice(0, n)`, except it
- * tries to be a bit faster for long arrays when we need only a small sample
- * from it. In a few tests, this indeed makes a substantial difference.
- *
- * If {@link n} is less than the number of {@link items} then a random shuffle
- * of the {@link items} is returned.
- */
export const randomSample = <T>(items: T[], n: number) => {
if (items.length <= n) return shuffled(items);
if (n == 0) return [];
if (n > items.length / 3) {
- // Avoid using the random sampling without replacement method if a
- // significant proportion of the original items are needed, otherwise we
- // might run into long retry loop at the tail end (hitting the same
- // indexes again an again).
+ // Sampling distinct random indexes degenerates into a long retry loop
+ // when n is a large fraction of the items, so shuffle instead.
return shuffled(items).slice(0, n);
}
@@ -43,16 +21,8 @@ export const randomSample = <T>(items: T[], n: number) => {
return [...ix].map((i) => items[i]!);
};
-/**
- * Return the first non-empty string from the given list of strings.
- *
- * This function is needed because the `a ?? b` idiom doesn't do what you'd
- * expect when a is "". Perhaps the behaviour is wrong, perhaps the expectation
- * is wrong; this function papers over the differences.
- *
- * If none of the strings are non-empty, or if there are no strings in the given
- * array, return undefined.
- */
+// The `a ?? b` idiom does not treat the empty string as absent, so it cannot
+// replace this helper.
export const firstNonEmpty = (
ss: (string | undefined)[],
): string | undefined => {
@@ -60,29 +30,13 @@ export const firstNonEmpty = (
return undefined;
};
-/**
- * Merge the given array of {@link Uint8Array}s in order into a single
- * {@link Uint8Array}.
- *
- * @param as An array of {@link Uint8Array}.
- */
export const mergeUint8Arrays = (as: Uint8Array[]): Uint8Array<ArrayBuffer> => {
- // A longer but better performing replacement of
- //
- // new Uint8Array(as.reduce((acc, x) => acc.concat(...x), []))
- //
-
const len = as.reduce((len, xs) => len + xs.length, 0);
const result = new Uint8Array(len);
as.reduce((n, xs) => (result.set(xs, n), n + xs.length), 0);
return result;
};
-/**
- * Break an array into batches of size {@link chunkSize}.
- *
- * @returns An array of the resultant batches.
- */
export const batch = <T>(xs: T[], batchSize: number): T[][] => {
const batches: T[][] = [];
for (let i = 0; i < xs.length; i += batchSize) {
@@ -91,19 +45,6 @@ export const batch = <T>(xs: T[], batchSize: number): T[][] => {
return batches;
};
-/**
- * Split an array into two arrays - those that satisfy the given
- * {@link predicate}, and those that don't.
- *
- * @param xs The array to split.
- *
- * @param predicate A function invoked for each element, to decide which part of
- * the split it will belong to.
- *
- * @returns A tuple with two arrays. The first of these arrays contains all
- * elements for which the predicate returned `true`, and the second array
- * contains the rest of the elements.
- */
export const splitByPredicate = <T>(
xs: T[],
predicate: (t: T) => boolean,
diff --git a/web/packages/utils/ensure.ts b/web/packages/utils/ensure.ts
index 9be5215bf5..dee8d6f422 100644
--- a/web/packages/utils/ensure.ts
+++ b/web/packages/utils/ensure.ts
@@ -1,56 +1,25 @@
-/**
- * Throw an exception if the given value {@link v} is false-y.
- *
- * This is a variant of {@link assertionFailed}, except it always throws, not
- * just in dev builds, if the given value is falsey.
- */
export const ensurePrecondition = (v: unknown): void => {
if (!v) throw new Error("Precondition failed");
};
-/**
- * Throw an exception if the given value is `null` or `undefined`.
- *
- * This is different from TypeScript's built in null assertion operator `!` in
- * that `ensure` involves a runtime check, and will throw if the given value is
- * null-ish. On the other hand the TypeScript null assertion is only an
- * indication to the type system and does not involve any runtime checks.
- *
- * However, still it is preferable to use the TypeScript build in null assertion
- * since the stack traces are more informative. The stack trace is not at the
- * point of the assertion, but later at the point of the use, so it is not
- * _directly_ pointing at the issue, but usually it is not hard to backtrace.
- *
- * Still, in rare cases we might want to, well, ensure that a undefined value
- * doesn't sneak into the machinery. So this.
- */
export const ensure = <T>(v: T | null | undefined): T => {
if (v === null) throw new Error("Required value was null");
if (v === undefined) throw new Error("Required value was undefined");
return v;
};
-/**
- * Throw an exception if the given value is not a string.
- */
export const ensureString = (v: unknown): string => {
if (typeof v != "string")
throw new Error(`Expected a string, instead found ${String(v)}`);
return v;
};
-/**
- * Throw an exception if the given value is not a number or if it is NaN.
- */
export const ensureNumber = (v: unknown): number => {
if (typeof v != "number" || Number.isNaN(v))
throw new Error(`Expected a number, instead found ${String(v)}`);
return v;
};
-/**
- * Throw an exception if the given value is not an integral number.
- */
export const ensureInteger = (v: unknown): number => {
if (typeof v != "number")
throw new Error(`Expected a number, instead found ${String(v)}`);
diff --git a/web/packages/utils/promise.ts b/web/packages/utils/promise.ts
index 19a0311a7e..3e7402cfc9 100644
--- a/web/packages/utils/promise.ts
+++ b/web/packages/utils/promise.ts
@@ -1,70 +1,6 @@
-/**
- * Wait for {@link ms} milliseconds
- *
- * This function is a promisified `setTimeout`. It returns a promise that
- * resolves after {@link ms} milliseconds.
- */
export const wait = (ms: number): Promise<void> =>
new Promise((resolve) => setTimeout(resolve, ms));
-/**
- * Throttle invocations of an underlying function, coalescing pending calls.
- *
- * Take a function that returns a promise, and return a new function that can be
- * called an any number of times while still ensuring that the underlying
- * function is only called a maximum of once per the specified period.
- *
- * The underlying function is immediately called if there were no calls to the
- * throttled function in the last period.
- *
- * Otherwise we start waiting. Multiple calls to the throttled function while
- * we're waiting (either for the original promise to resolve, or after that, for
- * the specified cooldown period to elapse) will all be coalesced into a single
- * call to the underlying function when we're done waiting.
- *
- * ---
- *
- * [Note: Throttle and debounce]
- *
- * There are many throttle/debounce libraries, and ideally I'd have liked to
- * just use one of them instead of reinventing such a basic and finicky wheel.
- * Then why write a bespoke one?
- *
- * - "debounce" means that the underlying function will only be called when a
- * particular wait time has elapsed since the last call to the _debounced_
- * function.
- *
- * - This behaviour, while useful sometimes, is not what we want always. If the
- * debounced function is continuously being called, then the underlying
- * function might never get called (since the wait time does not elapse).
- *
- * - To avoid this starvation, some debounce implementations like lodash provide
- * a "maxWait" option, which tells the debounced function to always call the
- * underlying function if maxWait has elapsed.
- *
- * - The debounced functions can trigger the underlying in two ways: leading
- * (aka immediate) and trailing which control if the underlying should be
- * called at the leading or the trailing edge of the time period.
- *
- * - "throttle" can be conceptually thought of as just maxWait + leading. In
- * fact, this is how lodash actually implements it too. So we could've used
- * lodash, except that is a big dependency to pull for a small function.
- *
- * - Alternatively, pThrottle is a micro-library that provide such a "throttle"
- * primitive. However, its implementation enqueues all incoming requests to
- * the throttled function: it still calls the underlying once per period, but
- * eventually underlying will get called once for each call to the throttled
- * function.
- *
- * - There are circumstances where that would be the appropriate behaviour, but
- * that's not what we want. We wish to trigger an async action, coalescing
- * multiple triggers into a single one, one per period.
- *
- * - Perhaps there are other focused and standard library that'd have what we
- * want, but instead of spending more time searching I just wrote it from
- * scratch for now. Indeed, I've spent more time writing about the function
- * than the function itself.
- */
export const throttled = (
underlying: () => Promise<void>,
period: number,
@@ -86,14 +22,6 @@ export const throttled = (
return f;
};
-/**
- * Await the given {@link promise} for {@link timeoutMS} milliseconds. If it
- * does not resolve within {@link timeoutMS}, then reject with a timeout error.
- *
- * Note that this does not abort {@link promise} itself - it will still get
- * settled, just its eventual state will be ignored if it gets fulfilled or
- * rejected after we've already timed out.
- */
export const withTimeout = async <T>(
promise: Promise<T>,
ms: number,
@@ -113,27 +41,9 @@ export const withTimeout = async <T>(
return Promise.race([promiseAndCancelTimeout(), rejectOnTimeout]);
};
-/**
- * A promise queue to serialize execution of bunch of promises.
- *
- * Promises can be added to the queue with the {@link add} function, which
- * returns a new promise that'll settle when the original promise settles.
- *
- * The queue will ensure that promises run sequentially one after the other, in
- * the order which they are added.
- */
export class PromiseQueue<T> {
private q: { task: () => Promise<T>; handlers: unknown }[] = [];
- /**
- * Add a promise to the queue, and return a new promise that will resolve to
- * the provided promise when it gets a chance to run (after all previous
- * promises in the queue have settled).
- *
- * @param task To avoid starting the promise resolution when adding them,
- * instead of the promise itself, {@link add} takes a function that should
- * return the promise that we wish to await.
- */
async add(task: () => Promise<T>): Promise<T> {
let handlers;
const p = new Promise<T>((...args) => (handlers = args));
diff --git a/web/packages/utils/transform.ts b/web/packages/utils/transform.ts
index 6934f78b25..e5165577f2 100644
--- a/web/packages/utils/transform.ts
+++ b/web/packages/utils/transform.ts
@@ -1,26 +1,11 @@
-/**
- * Convert `null` to `undefined`, passthrough everything else unchanged.
- */
export const nullToUndefined = <T>(v: T | null | undefined): T | undefined =>
v === null ? undefined : v;
-/**
- * Convert `null` and `undefined` to `false`, passthrough everything else unchanged.
- */
export const nullishToFalse = (v: boolean | null | undefined): boolean =>
v ?? false;
-/**
- * Convert `null` and `undefined` to `0`, passthrough everything else unchanged.
- */
export const nullishToZero = (v: number | null | undefined): number => v ?? 0;
-/**
- * Convert `null` and `undefined` to "" (blank string), passthrough everything else unchanged.
- */
export const nullishToBlank = (v: string | null | undefined): string => v ?? "";
-/**
- * Convert `null` and `undefined` to `[]`, passthrough everything else unchanged.
- */
export const nullishToEmpty = <T>(v: T[] | null | undefined): T[] => v ?? [];
diff --git a/web/packages/utils/type-guards.ts b/web/packages/utils/type-guards.ts
index 1309a5bea4..fd7c5ccb58 100644
--- a/web/packages/utils/type-guards.ts
+++ b/web/packages/utils/type-guards.ts
@@ -1,14 +1,7 @@
-/**
- * A variant of Array.includes that allows us to use it as a type guard.
- *
- * It allows us to narrow the type of an arbitrary T to U if it is one of U[].
- *
- * TypeScript currently doesn't allow us to use the standard Array.includes as a
- * type guard for checking if an arbitrary string is one of the known set of
- * values. This issue and this workaround is mentioned here:
- * - https://github.com/microsoft/TypeScript/issues/48247
- * - https://github.com/microsoft/TypeScript/issues/26255#issuecomment-502899689
- */
+// TypeScript does not allow the standard Array.includes to act as a type guard
+// that narrows an arbitrary T to one of the known U[]. See:
+// https://github.com/microsoft/TypeScript/issues/48247
+// https://github.com/microsoft/TypeScript/issues/26255#issuecomment-502899689
export function includes<T, U extends T>(us: readonly U[], t: T): t is U {
// @ts-expect-error @typescript-eslint/no-unsafe-argument
return us.includes(t);
diff --git a/web/packages/wasm-core/blob.ts b/web/packages/wasm-core/blob.ts
index dd9477dff4..81aa5702af 100644
--- a/web/packages/wasm-core/blob.ts
+++ b/web/packages/wasm-core/blob.ts
@@ -1,21 +1,11 @@
-/**
- * @file Authenticated encryption of a single value with XChaCha20-Poly1305.
- */
import { loadWasmCore } from "./load";
import { Header, Key } from "./types";
-/**
- * A blob ciphertext together with the header needed to open it, as returned by
- * {@link blobEncrypt}.
- */
export interface EncryptedBlob {
- /** The blob ciphertext. */
encryptedData: Uint8Array;
- /** The decryption header needed to decrypt it. Not secret. */
decryptionHeader: Header;
}
-/** Encrypt `data` with `key` as a single secretstream message. */
export const blobEncrypt = async (
data: Uint8Array,
key: Key,
@@ -32,9 +22,6 @@ export const blobEncrypt = async (
}
};
-/**
- * Decrypt a blob produced by {@link blobEncrypt}, using its `header` and `key`.
- */
export const blobDecrypt = async (
data: Uint8Array,
header: Header,
@@ -44,7 +31,6 @@ export const blobDecrypt = async (
return wasm.blobDecrypt(data, header.bytes, key.bytes);
};
-/** Encrypt `data` with `key` into one self-contained buffer. */
export const blobEncryptCombined = async (
data: Uint8Array,
key: Key,
@@ -53,7 +39,6 @@ export const blobEncryptCombined = async (
return wasm.blobEncryptCombined(data, key.bytes);
};
-/** Decrypt a combined buffer produced by {@link blobEncryptCombined}. */
export const blobDecryptCombined = async (
data: Uint8Array,
key: Key,
diff --git a/web/packages/wasm-core/index.ts b/web/packages/wasm-core/index.ts
index e8b6e1db9b..825b9e31a6 100644
--- a/web/packages/wasm-core/index.ts
+++ b/web/packages/wasm-core/index.ts
@@ -1,12 +1,6 @@
-/**
- * @file TypeScript wrapper for the `ente-core` Rust crate.
- *
- * See `rust/crates/core` for full documentation.
- *
- * Each function loads the WebAssembly backend on first use (so all are async)
- * and runs on the calling thread; run heavy operations from a Web Worker to
- * keep the UI responsive.
- */
+// The wrappers in this package load the wasm module lazily, but the wasm
+// calls themselves run synchronously on the calling thread. Invoke heavy
+// operations from a Web Worker to avoid freezing the UI.
export * from "./blob";
export * from "./secretbox";
export * from "./types";
diff --git a/web/packages/wasm-core/load.ts b/web/packages/wasm-core/load.ts
index 5ba7cc54b1..bedda0f40d 100644
--- a/web/packages/wasm-core/load.ts
+++ b/web/packages/wasm-core/load.ts
@@ -1,4 +1 @@
-/**
- * Return the lazy-loaded shared `ente-wasm-core` WebAssembly module.
- */
export const loadWasmCore = () => import("./pkg/ente_wasm_core");
diff --git a/web/packages/wasm-core/secretbox.ts b/web/packages/wasm-core/secretbox.ts
index 05963c21af..70fe1cfed5 100644
--- a/web/packages/wasm-core/secretbox.ts
+++ b/web/packages/wasm-core/secretbox.ts
@@ -1,21 +1,11 @@
-/**
- * @file Authenticated encryption with XSalsa20-Poly1305.
- */
import { loadWasmCore } from "./load";
import { Key, Nonce } from "./types";
-/**
- * A secretbox ciphertext together with the nonce needed to open it, as returned
- * by {@link secretboxEncrypt}.
- */
export interface EncryptedBox {
- /** The secretbox ciphertext. */
encryptedData: Uint8Array;
- /** The nonce needed to decrypt it. Not secret. */
nonce: Nonce;
}
-/** Encrypt `data` with `key` and a freshly generated random nonce. */
export const secretboxEncrypt = async (
data: Uint8Array,
key: Key,
@@ -32,7 +22,6 @@ export const secretboxEncrypt = async (
}
};
-/** Decrypt a ciphertext produced by {@link secretboxEncrypt}. */
export const secretboxDecrypt = async (
data: Uint8Array,
nonce: Nonce,
@@ -42,7 +31,6 @@ export const secretboxDecrypt = async (
return wasm.secretboxDecrypt(data, nonce.bytes, key.bytes);
};
-/** Encrypt `data` with `key` into one self-contained buffer. */
export const secretboxEncryptCombined = async (
data: Uint8Array,
key: Key,
@@ -51,7 +39,6 @@ export const secretboxEncryptCombined = async (
return wasm.secretboxEncryptCombined(data, key.bytes);
};
-/** Decrypt a combined buffer produced by {@link secretboxEncryptCombined}. */
export const secretboxDecryptCombined = async (
data: Uint8Array,
key: Key,
diff --git a/web/packages/wasm-core/types.ts b/web/packages/wasm-core/types.ts
index 489b95aec9..7a9a49a187 100644
--- a/web/packages/wasm-core/types.ts
+++ b/web/packages/wasm-core/types.ts
@@ -1,7 +1,3 @@
-/**
- * @file Typed key material and related fixed-size values.
- */
-
const sized = (bytes: Uint8Array, length: number, name: string): Uint8Array => {
if (bytes.length !== length) {
throw new Error(
@@ -11,115 +7,73 @@ const sized = (bytes: Uint8Array, length: number, name: string): Uint8Array => {
return bytes;
};
-/** A 256-bit symmetric encryption key. */
export class Key {
private constructor(private readonly _bytes: Uint8Array) {}
- /**
- * Construct a key from `bytes`, validating the length.
- *
- * Throws unless `bytes` is exactly 32 bytes long.
- */
static fromBytes(bytes: Uint8Array): Key {
return new Key(sized(bytes, 32, "Key"));
}
- /** The raw key bytes. */
get bytes(): Uint8Array {
return this._bytes;
}
}
-/** A 192-bit SecretBox nonce. Not secret. */
export class Nonce {
private constructor(private readonly _bytes: Uint8Array) {}
- /**
- * Construct a nonce from `bytes`, validating the length.
- *
- * Throws unless `bytes` is exactly 24 bytes long.
- */
static fromBytes(bytes: Uint8Array): Nonce {
return new Nonce(sized(bytes, 24, "Nonce"));
}
- /** The raw nonce bytes. */
get bytes(): Uint8Array {
return this._bytes;
}
}
-/** A 128-bit key derivation salt. Not secret. */
export class Salt {
private constructor(private readonly _bytes: Uint8Array) {}
- /**
- * Construct a salt from `bytes`, validating the length.
- *
- * Throws unless `bytes` is exactly 16 bytes long.
- */
static fromBytes(bytes: Uint8Array): Salt {
return new Salt(sized(bytes, 16, "Salt"));
}
- /** The raw salt bytes. */
get bytes(): Uint8Array {
return this._bytes;
}
}
-/** A 192-bit SecretStream decryption header. Not secret. */
export class Header {
private constructor(private readonly _bytes: Uint8Array) {}
- /**
- * Construct a header from `bytes`, validating the length.
- *
- * Throws unless `bytes` is exactly 24 bytes long.
- */
static fromBytes(bytes: Uint8Array): Header {
return new Header(sized(bytes, 24, "Header"));
}
- /** The raw header bytes. */
get bytes(): Uint8Array {
return this._bytes;
}
}
-/** An X25519 public key. Not secret. */
export class PublicKey {
private constructor(private readonly _bytes: Uint8Array) {}
- /**
- * Construct a public key from `bytes`, validating the length.
- *
- * Throws unless `bytes` is exactly 32 bytes long.
- */
static fromBytes(bytes: Uint8Array): PublicKey {
return new PublicKey(sized(bytes, 32, "PublicKey"));
}
- /** The raw public key bytes. */
get bytes(): Uint8Array {
return this._bytes;
}
}
-/** An X25519 secret key. */
export class SecretKey {
private constructor(private readonly _bytes: Uint8Array) {}
- /**
- * Construct a secret key from `bytes`, validating the length.
- *
- * Throws unless `bytes` is exactly 32 bytes long.
- */
static fromBytes(bytes: Uint8Array): SecretKey {
return new SecretKey(sized(bytes, 32, "SecretKey"));
}
- /** The raw secret key bytes. */
get bytes(): Uint8Array {
return this._bytes;
}
diff --git a/web/packages/wasm/load.ts b/web/packages/wasm/load.ts
index 06f0136826..93f5dda523 100644
--- a/web/packages/wasm/load.ts
+++ b/web/packages/wasm/load.ts
@@ -3,24 +3,12 @@ type EnteWasmModule = typeof import("ente-wasm");
let wasmPromise: Promise<EnteWasmModule> | undefined;
let cryptoReadyPromise: Promise<EnteWasmModule> | undefined;
-/**
- * Load `ente-wasm` once and return the shared module instance.
- *
- * The first call performs the dynamic import. Later calls reuse the same
- * promise, so all consumers share one loader path.
- */
export const loadEnteWasm = (): Promise<EnteWasmModule> =>
(wasmPromise ??= import("ente-wasm").catch((error: unknown) => {
wasmPromise = undefined;
throw error;
}));
-/**
- * Load `ente-wasm`, initialize the crypto backend, and return the ready
- * module.
- *
- * The first call runs `crypto_init()`. Later calls reuse the same promise.
- */
export const loadCryptoReadyEnteWasm = (): Promise<EnteWasmModule> =>
(cryptoReadyPromise ??= loadEnteWasm()
.then((wasm) => {