Skip to content

armgit / ente

Public Imported from GitHub
0

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

Pass token

Manav Rathia0f7c6f302bf
diff --git a/web/apps/accounts/src/pages/passkeys/index.tsx b/web/apps/accounts/src/pages/passkeys/index.tsx
index 47d6e3d2da..e1c12e2777 100644
--- a/web/apps/accounts/src/pages/passkeys/index.tsx
+++ b/web/apps/accounts/src/pages/passkeys/index.tsx
@@ -1,4 +1,5 @@
import log from "@/next/log";
+import { ensure } from "@/utils/ensure";
import { CenteredFlex } from "@ente/shared/components/Container";
import DialogBoxV2 from "@ente/shared/components/DialogBoxV2";
import EnteButton from "@ente/shared/components/EnteButton";
@@ -10,7 +11,6 @@ import MenuItemDivider from "@ente/shared/components/Menu/MenuItemDivider";
import { MenuItemGroup } from "@ente/shared/components/Menu/MenuItemGroup";
import SingleInputForm from "@ente/shared/components/SingleInputForm";
import Titlebar from "@ente/shared/components/Titlebar";
-import { getToken } from "@ente/shared/storage/localStorage/helpers";
import { formatDateTimeFull } from "@ente/shared/time/format";
import CalendarTodayIcon from "@mui/icons-material/CalendarToday";
import ChevronRightIcon from "@mui/icons-material/ChevronRight";
@@ -19,7 +19,6 @@ import EditIcon from "@mui/icons-material/Edit";
import KeyIcon from "@mui/icons-material/Key";
import { Box, Button, Stack, Typography, useMediaQuery } from "@mui/material";
import { t } from "i18next";
-import { useRouter } from "next/router";
import { useAppContext } from "pages/_app";
import React, { useEffect, useState } from "react";
import {
@@ -33,46 +32,32 @@ import {
const Page: React.FC = () => {
const { showNavBar, setDialogBoxAttributesV2 } = useAppContext();
+ const [token, setToken] = useState<string | undefined>();
const [passkeys, setPasskeys] = useState<Passkey[]>([]);
const [showPasskeyDrawer, setShowPasskeyDrawer] = useState(false);
const [selectedPasskey, setSelectedPasskey] = useState<
Passkey | undefined
>();
- const router = useRouter();
-
useEffect(() => {
- const urlParams = new URLSearchParams(window.location.search);
+ showNavBar(true);
- const clientPackage = urlParams.get("client");
- if (clientPackage) {
- // TODO-PK: mobile is not passing it. is that expected?
- localStorage.setItem("clientPackage", clientPackage);
- setClientPackageForAuthenticatedRequests(clientPackage);
- HTTPService.setHeaders({
- "X-Client-Package": clientPackage,
- });
- }
+ const urlParams = new URLSearchParams(window.location.search);
const token = urlParams.get("token");
if (!token) {
log.error("Missing accounts token");
- router.push("/login");
- return;
- }
-
- if (!getToken()) {
- router.push("/login");
+ showPasskeyFetchFailedErrorDialog();
return;
}
- showNavBar(true);
+ setToken(token);
void refreshPasskeys();
}, []);
const refreshPasskeys = async () => {
try {
- setPasskeys(await getPasskeys());
+ setPasskeys(await getPasskeys(ensure(token)));
} catch (e) {
log.error("Failed to fetch passkeys", e);
showPasskeyFetchFailedErrorDialog();
@@ -113,7 +98,7 @@ const Page: React.FC = () => {
resetForm: () => void,
) => {
try {
- await registerPasskey(inputValue);
+ await registerPasskey(ensure(token), inputValue);
} catch (e) {
log.error("Failed to register a new passkey", e);
// If the user cancels the operation, then an error with name
@@ -156,12 +141,15 @@ const Page: React.FC = () => {
</Box>
</Box>
</CenteredFlex>
- <ManagePasskeyDrawer
- open={showPasskeyDrawer}
- onClose={handleDrawerClose}
- passkey={selectedPasskey}
- onUpdateOrDeletePasskey={handleUpdateOrDeletePasskey}
- />
+ {token && (
+ <ManagePasskeyDrawer
+ open={showPasskeyDrawer}
+ onClose={handleDrawerClose}
+ passkey={selectedPasskey}
+ token={token}
+ onUpdateOrDeletePasskey={handleUpdateOrDeletePasskey}
+ />
+ )}
</>
);
};
@@ -228,6 +216,13 @@ interface ManagePasskeyDrawerProps {
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.
+ */
+ token: string | undefined;
/**
* The {@link Passkey} whose details should be shown in the drawer.
*
@@ -246,6 +241,7 @@ interface ManagePasskeyDrawerProps {
const ManagePasskeyDrawer: React.FC<ManagePasskeyDrawerProps> = ({
open,
onClose,
+ token,
passkey,
onUpdateOrDeletePasskey,
}) => {
@@ -255,7 +251,7 @@ const ManagePasskeyDrawer: React.FC<ManagePasskeyDrawerProps> = ({
return (
<>
<EnteDrawer anchor="right" {...{ open, onClose }}>
- {passkey && (
+ {token && passkey && (
<Stack spacing={"4px"} py={"12px"}>
<Titlebar
onClose={onClose}
@@ -293,10 +289,11 @@ const ManagePasskeyDrawer: React.FC<ManagePasskeyDrawerProps> = ({
)}
</EnteDrawer>
- {passkey && (
+ {token && passkey && (
<RenamePasskeyDialog
open={showRenameDialog}
onClose={() => setShowRenameDialog(false)}
+ token={token}
passkey={passkey}
onRenamePasskey={() => {
setShowRenameDialog(false);
@@ -305,10 +302,11 @@ const ManagePasskeyDrawer: React.FC<ManagePasskeyDrawerProps> = ({
/>
)}
- {passkey && (
+ {token && passkey && (
<DeletePasskeyDialog
open={showDeleteDialog}
onClose={() => setShowDeleteDialog(false)}
+ token={token}
passkey={passkey}
onDeletePasskey={() => {
setShowDeleteDialog(false);
@@ -325,6 +323,8 @@ interface RenamePasskeyDialogProps {
open: boolean;
/** Callback to invoke when the dialog wants to be closed. */
onClose: () => void;
+ /** Auth token for API requests. */
+ token: string;
/** The {@link Passkey} to rename. */
passkey: Passkey;
/** Callback to invoke when the passkey is renamed. */
@@ -334,6 +334,7 @@ interface RenamePasskeyDialogProps {
const RenamePasskeyDialog: React.FC<RenamePasskeyDialogProps> = ({
open,
onClose,
+ token,
passkey,
onRenamePasskey,
}) => {
@@ -341,7 +342,7 @@ const RenamePasskeyDialog: React.FC<RenamePasskeyDialogProps> = ({
const handleSubmit = async (inputValue: string) => {
try {
- await renamePasskey(passkey.id, inputValue);
+ await renamePasskey(token, passkey.id, inputValue);
onRenamePasskey();
} catch (e) {
log.error("Failed to rename passkey", e);
@@ -372,6 +373,8 @@ interface DeletePasskeyDialogProps {
open: boolean;
/** Callback to invoke when the dialog wants to be closed. */
onClose: () => void;
+ /** Auth token for API requests. */
+ token: string;
/** The {@link Passkey} to delete. */
passkey: Passkey;
/** Callback to invoke when the passkey is deleted. */
@@ -381,6 +384,7 @@ interface DeletePasskeyDialogProps {
const DeletePasskeyDialog: React.FC<DeletePasskeyDialogProps> = ({
open,
onClose,
+ token,
passkey,
onDeletePasskey,
}) => {
@@ -390,7 +394,7 @@ const DeletePasskeyDialog: React.FC<DeletePasskeyDialogProps> = ({
const handleConfirm = async () => {
setIsDeleting(true);
try {
- await deletePasskey(passkey.id);
+ await deletePasskey(token, passkey.id);
onDeletePasskey();
} catch (e) {
log.error("Failed to delete passkey", e);
diff --git a/web/apps/accounts/src/services/passkey.ts b/web/apps/accounts/src/services/passkey.ts
index 58adaaa0e1..c5641580c5 100644
--- a/web/apps/accounts/src/services/passkey.ts
+++ b/web/apps/accounts/src/services/passkey.ts
@@ -1,5 +1,6 @@
import { isDevBuild } from "@/next/env";
import { clientPackageHeaderIfPresent } from "@/next/http";
+import { clientPackageName } from "@/next/types/app";
import { TwoFactorAuthorizationResponse } from "@/next/types/credentials";
import { ensure } from "@/utils/ensure";
import { nullToUndefined } from "@/utils/transform";
@@ -9,7 +10,6 @@ import {
toB64URLSafeNoPaddingString,
} from "@ente/shared/crypto/internal/libsodium";
import { apiOrigin } from "@ente/shared/network/api";
-import { getToken } from "@ente/shared/storage/localStorage/helpers";
import { z } from "zod";
/** Return true if the user's browser supports WebAuthn (Passkeys). */
@@ -19,19 +19,15 @@ export const isWebAuthnSupported = () => !!navigator.credentials;
* Variant of {@link authenticatedRequestHeaders} but for authenticated requests
* made by the accounts app.
*
- * We cannot use {@link authenticatedRequestHeaders} directly because the
- * accounts app does not save a full user and instead only saves the user's
- * token (and that token too is scoped to the accounts APIs).
+ * @param token The accounts specific auth token to use for making API requests.
*/
-const accountsAuthenticatedRequestHeaders = (): Record<string, string> => {
- const token = getToken();
- if (!token) throw new Error("Missing accounts token");
- const headers: Record<string, string> = { "X-Auth-Token": token };
- const clientPackage = nullToUndefined(
- localStorage.getItem("clientPackage"),
- );
- if (clientPackage) headers["X-Client-Package"] = clientPackage;
- return headers;
+const accountsAuthenticatedRequestHeaders = (
+ token: string,
+): Record<string, string> => {
+ return {
+ "X-Auth-Token": token,
+ "X-Client-Package": clientPackageName.accounts,
+ };
};
const Passkey = z.object({
@@ -57,13 +53,15 @@ const GetPasskeysResponse = z.object({
/**
* 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 () => {
+export const getPasskeys = async (token: string) => {
const url = `${apiOrigin()}/passkeys`;
const res = await fetch(url, {
- headers: accountsAuthenticatedRequestHeaders(),
+ headers: accountsAuthenticatedRequestHeaders(token),
});
if (!res.ok) throw new Error(`Failed to fetch ${url}: HTTP ${res.status}`);
const { passkeys } = GetPasskeysResponse.parse(await res.json());
@@ -73,16 +71,22 @@ export const getPasskeys = async () => {
/**
* 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 (id: string, name: string) => {
+export const renamePasskey = async (
+ token: string,
+ id: string,
+ name: string,
+) => {
const params = new URLSearchParams({ friendlyName: name });
const url = `${apiOrigin()}/passkeys/${id}`;
const res = await fetch(`${url}?${params.toString()}`, {
method: "PATCH",
- headers: accountsAuthenticatedRequestHeaders(),
+ headers: accountsAuthenticatedRequestHeaders(token),
});
if (!res.ok) throw new Error(`Failed to fetch ${url}: HTTP ${res.status}`);
};
@@ -90,13 +94,15 @@ export const renamePasskey = async (id: string, name: string) => {
/**
* 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 (id: string) => {
+export const deletePasskey = async (token: string, id: string) => {
const url = `${apiOrigin()}/passkeys/${id}`;
const res = await fetch(url, {
method: "DELETE",
- headers: accountsAuthenticatedRequestHeaders(),
+ headers: accountsAuthenticatedRequestHeaders(token),
});
if (!res.ok) throw new Error(`Failed to fetch ${url}: HTTP ${res.status}`);
};
@@ -104,12 +110,14 @@ export const deletePasskey = async (id: string) => {
/**
* 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 (name: string) => {
+export const registerPasskey = async (token: string, name: string) => {
// Get options (and sessionID) from the backend.
- const { sessionID, options } = await beginPasskeyRegistration();
+ const { sessionID, options } = await beginPasskeyRegistration(token);
// Ask the browser to new (public key) credentials using these options.
const credential = ensure(await navigator.credentials.create(options));
@@ -117,6 +125,7 @@ export const registerPasskey = async (name: string) => {
// 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,
sessionID,
credential,
@@ -140,11 +149,11 @@ interface BeginPasskeyRegistrationResponse {
};
}
-const beginPasskeyRegistration = async () => {
+const beginPasskeyRegistration = async (token: string) => {
const url = `${apiOrigin()}/passkeys/registration/begin`;
const res = await fetch(url, {
method: "POST",
- headers: accountsAuthenticatedRequestHeaders(),
+ headers: accountsAuthenticatedRequestHeaders(token),
});
if (!res.ok) throw new Error(`Failed to fetch ${url}: HTTP ${res.status}`);
@@ -262,12 +271,14 @@ const binaryToServerB64 = async (b: ArrayBuffer) => {
};
interface FinishPasskeyRegistrationOptions {
+ token: string;
sessionID: string;
friendlyName: string;
credential: Credential;
}
const finishPasskeyRegistration = async ({
+ token,
sessionID,
friendlyName,
credential,
@@ -286,7 +297,7 @@ const finishPasskeyRegistration = async ({
const url = `${apiOrigin()}/passkeys/registration/finish`;
const res = await fetch(`${url}?${params.toString()}`, {
method: "POST",
- headers: accountsAuthenticatedRequestHeaders(),
+ headers: accountsAuthenticatedRequestHeaders(token),
body: JSON.stringify({
id: credential.id,
// This is meant to be the ArrayBuffer version of the (base64