Skip to content

armgit / ente

Public Imported from GitHub
0

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

Add Space unlock flow

Anand Baburajan6f28104b44fd
diff --git a/web/apps/space/src/pages/index.tsx b/web/apps/space/src/pages/index.tsx
index c6753605f4..746275813b 100644
--- a/web/apps/space/src/pages/index.tsx
+++ b/web/apps/space/src/pages/index.tsx
@@ -26,6 +26,7 @@ import {
spaceInviteFromLocation,
type PendingSpaceInvite,
} from "services/spaceInvite";
+import { savedSpaceUnlockEmail } from "services/spaceSession";
import {
useSpaceAppState,
type OnboardingEntrySource,
@@ -102,6 +103,9 @@ const Page: React.FC = () => {
const [publicProfile, setPublicProfile] = useState<SetupProfile | null>(
null,
);
+ const [unlockCheckStatus, setUnlockCheckStatus] = useState<
+ "idle" | "checking" | "done"
+ >("idle");
const [publicFriendsCount, setPublicFriendsCount] = useState(0);
const [publicPosts, setPublicPosts] = useState<SpacePost[]>([]);
const [publicError, setPublicError] = useState<string>();
@@ -161,8 +165,43 @@ const Page: React.FC = () => {
}
}, [profile, profileLoadStatus, routeMode.kind, router]);
+ useEffect(() => {
+ if (
+ routeMode.kind != "app" ||
+ profileLoadStatus != "ready" ||
+ profile
+ ) {
+ setUnlockCheckStatus("idle");
+ return undefined;
+ }
+
+ let cancelled = false;
+ setUnlockCheckStatus("checking");
+ void savedSpaceUnlockEmail()
+ .then((email) => {
+ if (cancelled) return;
+ if (email) {
+ void router.replace(spaceRoutes.unlock);
+ } else {
+ setUnlockCheckStatus("done");
+ }
+ })
+ .catch((error: unknown) => {
+ console.error("Failed to detect Space unlock state", error);
+ if (!cancelled) setUnlockCheckStatus("done");
+ });
+
+ return () => {
+ cancelled = true;
+ };
+ }, [profile, profileLoadStatus, routeMode.kind, router]);
+
+ const shouldCheckUnlock =
+ routeMode.kind == "app" && profileLoadStatus == "ready" && !profile;
+
if (
routeMode.kind == "checking" ||
+ (shouldCheckUnlock && unlockCheckStatus != "done") ||
(routeMode.kind == "app" &&
(profileLoadStatus == "loading" || Boolean(profile)))
) {
diff --git a/web/apps/space/src/pages/unlock.tsx b/web/apps/space/src/pages/unlock.tsx
new file mode 100644
index 0000000000..f77445a9f1
--- /dev/null
+++ b/web/apps/space/src/pages/unlock.tsx
@@ -0,0 +1,127 @@
+import { SpacePageMeta } from "components/SpacePageMeta";
+import { SpaceRouteFallback } from "components/SpaceRouteFallback";
+import { accountLogout } from "ente-accounts-rs/services/logout";
+import { useRouter } from "next/router";
+import React, { useEffect, useState } from "react";
+import {
+ LoginScreen,
+ loginBackground,
+ type SpaceLoginCredentials,
+} from "screens/LoginScreen";
+import { beginSpaceLogin, type SpaceLoginResult } from "services/spaceLogin";
+import { savePendingSpacePasskeyVerification } from "services/spacePasskeyVerification";
+import { savedSpaceUnlockEmail } from "services/spaceSession";
+import { useSpaceAppState } from "state/spaceAppState";
+import { routeAfterCompletedLogin } from "utils/spaceLoginNavigation";
+import { spaceRoutes } from "utils/spaceRoutes";
+
+const Page: React.FC = () => {
+ const router = useRouter();
+ const {
+ refreshProfile,
+ resetAfterLogout,
+ setPendingLoginCredentials,
+ setPendingPasskeyVerification,
+ } = useSpaceAppState();
+ const [email, setEmail] = useState<string>();
+ const [unlockError, setUnlockError] = useState<string>();
+ const [isSubmitting, setIsSubmitting] = useState(false);
+
+ const unlockErrorMessage = (error: unknown) =>
+ error instanceof Error
+ ? error.message
+ : "Couldn't unlock Space. Please try again.";
+
+ const handleLoginResult = async (
+ result: SpaceLoginResult,
+ credentials: SpaceLoginCredentials,
+ ) => {
+ switch (result.status) {
+ case "complete":
+ setPendingLoginCredentials(null);
+ await routeAfterCompletedLogin(router, refreshProfile);
+ break;
+ case "email-otp":
+ setPendingLoginCredentials({
+ email: result.email,
+ password: credentials.password,
+ });
+ void router.push(spaceRoutes.verifyLogin);
+ break;
+ case "totp":
+ setPendingLoginCredentials(null);
+ void router.push(spaceRoutes.twoFactorVerify);
+ break;
+ case "passkey":
+ setPendingLoginCredentials(null);
+ setPendingPasskeyVerification({
+ hasTwoFactorFallback: result.hasTwoFactorFallback,
+ passkeySessionID: result.passkeySessionID,
+ url: result.url,
+ });
+ savePendingSpacePasskeyVerification({
+ hasTwoFactorFallback: result.hasTwoFactorFallback,
+ passkeySessionID: result.passkeySessionID,
+ url: result.url,
+ });
+ void router.push(spaceRoutes.passkeysVerify);
+ break;
+ }
+ };
+
+ useEffect(() => {
+ if (!router.isReady) return undefined;
+
+ let cancelled = false;
+ void savedSpaceUnlockEmail().then((unlockEmail) => {
+ if (cancelled) return;
+ if (!unlockEmail) {
+ void router.replace(spaceRoutes.login);
+ return;
+ }
+ setEmail(unlockEmail);
+ });
+
+ return () => {
+ cancelled = true;
+ };
+ }, [router, router.isReady]);
+
+ if (!email) return <SpaceRouteFallback background={loginBackground} />;
+
+ return (
+ <>
+ <SpacePageMeta themeColor={loginBackground} />
+ <LoginScreen
+ errorMessage={unlockError}
+ focusPassword
+ initialEmail={email}
+ isSubmitting={isSubmitting}
+ onChangeEmail={() => {
+ void accountLogout().then(() => {
+ resetAfterLogout();
+ void router.replace(spaceRoutes.onboarding);
+ });
+ }}
+ onContinue={async (credentials) => {
+ setIsSubmitting(true);
+ setUnlockError(undefined);
+ try {
+ await handleLoginResult(
+ await beginSpaceLogin(credentials),
+ credentials,
+ );
+ } catch (error) {
+ setUnlockError(unlockErrorMessage(error));
+ setIsSubmitting(false);
+ }
+ }}
+ readOnlyEmail
+ showBack={false}
+ title="Unlock space"
+ />
+ </>
+ );
+};
+
+export default Page;
diff --git a/web/apps/space/src/screens/LoginScreen.tsx b/web/apps/space/src/screens/LoginScreen.tsx
index 8a85f2e087..dcd1b3c439 100644
--- a/web/apps/space/src/screens/LoginScreen.tsx
+++ b/web/apps/space/src/screens/LoginScreen.tsx
@@ -1,5 +1,5 @@
import { Box } from "@mui/material";
-import React, { useState } from "react";
+import React, { useEffect, useRef, useState } from "react";
export const loginBackground = "#FAFAFA";
@@ -16,15 +16,24 @@ export interface SpaceLoginCredentials {
interface LoginScreenProps {
errorMessage?: string;
+ focusPassword?: boolean;
+ initialEmail?: string;
isSubmitting?: boolean;
- onBack: () => void;
+ onBack?: () => void;
+ onChangeEmail?: () => void;
onContinue?: (credentials: SpaceLoginCredentials) => Promise<void> | void;
+ readOnlyEmail?: boolean;
+ showBack?: boolean;
+ title?: string;
}
interface TextInputProps {
+ autoFocus?: boolean;
+ inputRef?: React.Ref<HTMLInputElement>;
label: string;
onChange?: (value: string) => void;
placeholder?: string;
+ readOnly?: boolean;
required?: boolean;
type?: "email" | "password" | "text";
value?: string;
@@ -75,9 +84,12 @@ const EyeIcon: React.FC = () => (
);
const TextInput: React.FC<TextInputProps> = ({
+ autoFocus,
+ inputRef,
label,
onChange,
placeholder,
+ readOnly = false,
required,
type = "text",
value,
@@ -106,7 +118,7 @@ const TextInput: React.FC<TextInputProps> = ({
<Box
sx={{
alignItems: "center",
- bgcolor: "white",
+ bgcolor: readOnly ? "#F5F5F5" : "white",
borderRadius: "16px",
display: "flex",
height: 52,
@@ -120,14 +132,18 @@ const TextInput: React.FC<TextInputProps> = ({
>
<Box
component="input"
+ ref={inputRef}
+ autoFocus={autoFocus}
onChange={(event) => onChange?.(event.target.value)}
placeholder={placeholder}
+ readOnly={readOnly}
type={isPassword && showPassword ? "text" : type}
value={value}
sx={{
bgcolor: "transparent",
border: 0,
color: textBase,
+ cursor: readOnly ? "default" : undefined,
flex: 1,
fontFamily: '"Inter Variable", Inter, sans-serif',
fontSize: 14,
@@ -175,14 +191,84 @@ const TextInput: React.FC<TextInputProps> = ({
);
};
+const FooterLinkButton: React.FC<{
+ children: React.ReactNode;
+ disabled?: boolean;
+ onClick?: () => void;
+}> = ({ children, disabled = false, onClick }) => (
+ <Box
+ component="button"
+ type="button"
+ disabled={disabled}
+ onClick={onClick}
+ sx={{
+ alignItems: "center",
+ bgcolor: "transparent",
+ border: 0,
+ color: "#666",
+ cursor: disabled ? "default" : "pointer",
+ display: "flex",
+ fontFamily: '"Inter Variable", Inter, sans-serif',
+ fontSize: 14,
+ fontWeight: 500,
+ justifyContent: "center",
+ lineHeight: "20px",
+ minWidth: 0,
+ opacity: 0.8,
+ p: 0,
+ textAlign: "center",
+ textDecoration: "underline",
+ textDecorationSkipInk: "none",
+ textUnderlineOffset: "2px",
+ textUnderlinePosition: "from-font",
+ width: "100%",
+ "&:focus-visible": {
+ borderRadius: "4px",
+ outline: `2px solid ${green}`,
+ outlineOffset: 4,
+ },
+ }}
+ >
+ {children}
+ </Box>
+);
+
export const LoginScreen: React.FC<LoginScreenProps> = ({
errorMessage,
+ focusPassword = false,
+ initialEmail,
isSubmitting = false,
onBack,
+ onChangeEmail,
onContinue,
+ readOnlyEmail = false,
+ showBack = true,
+ title = "Login to Ente",
}) => {
- const [email, setEmail] = useState("");
+ const [email, setEmail] = useState(initialEmail ?? "");
const [password, setPassword] = useState("");
+ const passwordInputRef = useRef<HTMLInputElement | null>(null);
+ const appliedInitialEmailRef = useRef<string | undefined>(initialEmail);
+
+ useEffect(() => {
+ if (!initialEmail || appliedInitialEmailRef.current == initialEmail) {
+ return;
+ }
+
+ setEmail((currentEmail) =>
+ currentEmail && !readOnlyEmail ? currentEmail : initialEmail,
+ );
+ appliedInitialEmailRef.current = initialEmail;
+ }, [initialEmail, readOnlyEmail]);
+
+ useEffect(() => {
+ if (!focusPassword) return undefined;
+
+ const animationFrame = window.requestAnimationFrame(() =>
+ passwordInputRef.current?.focus(),
+ );
+ return () => window.cancelAnimationFrame(animationFrame);
+ }, [focusPassword, initialEmail]);
const canContinue =
!isSubmitting && email.trim().length > 0 && password.length > 0;
@@ -232,31 +318,35 @@ export const LoginScreen: React.FC<LoginScreenProps> = ({
width: "100%",
}}
>
- <Box
- component="button"
- type="button"
- aria-label="Back"
- onClick={onBack}
- sx={{
- alignItems: "center",
- bgcolor: "transparent",
- border: 0,
- color: textBase,
- cursor: "pointer",
- display: "flex",
- height: 42,
- justifyContent: "flex-start",
- p: 0,
- width: 42,
- "&:focus-visible": {
- borderRadius: "50%",
- outline: `2px solid ${green}`,
- outlineOffset: 2,
- },
- }}
- >
- <BackIcon />
- </Box>
+ {showBack && onBack ? (
+ <Box
+ component="button"
+ type="button"
+ aria-label="Back"
+ onClick={onBack}
+ sx={{
+ alignItems: "center",
+ bgcolor: "transparent",
+ border: 0,
+ color: textBase,
+ cursor: "pointer",
+ display: "flex",
+ height: 42,
+ justifyContent: "flex-start",
+ p: 0,
+ width: 42,
+ "&:focus-visible": {
+ borderRadius: "50%",
+ outline: `2px solid ${green}`,
+ outlineOffset: 2,
+ },
+ }}
+ >
+ <BackIcon />
+ </Box>
+ ) : (
+ <Box />
+ )}
<Box
component="h1"
sx={{
@@ -270,7 +360,7 @@ export const LoginScreen: React.FC<LoginScreenProps> = ({
whiteSpace: "nowrap",
}}
>
- Login to Ente
+ {title}
</Box>
<Box />
</Box>
@@ -290,17 +380,20 @@ export const LoginScreen: React.FC<LoginScreenProps> = ({
>
<TextInput
label="Email"
- onChange={setEmail}
+ onChange={readOnlyEmail ? undefined : setEmail}
placeholder="Enter your email"
+ readOnly={readOnlyEmail}
required
type="email"
value={email}
/>
<TextInput
label="Password"
+ inputRef={passwordInputRef}
onChange={setPassword}
placeholder="Enter your password"
required
+ autoFocus={focusPassword}
type="password"
value={password}
/>
@@ -371,6 +464,14 @@ export const LoginScreen: React.FC<LoginScreenProps> = ({
>
{isSubmitting ? "Signing in..." : "Continue"}
</Box>
+ {readOnlyEmail && onChangeEmail && (
+ <FooterLinkButton
+ disabled={isSubmitting}
+ onClick={onChangeEmail}
+ >
+ Change email
+ </FooterLinkButton>
+ )}
</Box>
</Box>
</Box>
diff --git a/web/apps/space/src/screens/SetupProfileScreen.tsx b/web/apps/space/src/screens/SetupProfileScreen.tsx
index 3cf2731a1c..59de59025d 100644
--- a/web/apps/space/src/screens/SetupProfileScreen.tsx
+++ b/web/apps/space/src/screens/SetupProfileScreen.tsx
@@ -265,30 +265,19 @@ const AvatarCropPageButton: React.FC<{
children: React.ReactNode;
disabled?: boolean;
onClick?: () => void;
- variant: "primary" | "secondary";
-}> = ({ children, disabled = false, onClick, variant }) => (
+}> = ({ children, disabled = false, onClick }) => (
<Box
- className={variant == "primary" && !disabled ? "green-bg" : undefined}
+ className={!disabled ? "green-bg" : undefined}
component="button"
type="button"
disabled={disabled}
onClick={onClick}
sx={{
alignItems: "center",
- bgcolor:
- variant == "primary"
- ? disabled
- ? "#F5F5F5"
- : green
- : "transparent",
- border: variant == "primary" ? 0 : "1px solid #E6E6E6",
+ bgcolor: disabled ? "#F5F5F5" : green,
+ border: 0,
borderRadius: "20px",
- color:
- variant == "primary"
- ? disabled
- ? textLight
- : "white"
- : textBase,
+ color: disabled ? textLight : "white",
cursor: disabled ? "default" : "pointer",
display: "flex",
flex: "0 0 auto",
@@ -305,10 +294,50 @@ const AvatarCropPageButton: React.FC<{
outline: `2px solid ${green}`,
outlineOffset: 3,
},
- "&:hover":
- !disabled && variant == "primary"
- ? { bgcolor: "#07AE22" }
- : undefined,
+ "&:hover": !disabled ? { bgcolor: "#07AE22" } : undefined,
+ }}
+ >
+ {children}
+ </Box>
+);
+
+const AvatarCropPageLinkButton: React.FC<{
+ children: React.ReactNode;
+ disabled?: boolean;
+ onClick?: () => void;
+}> = ({ children, disabled = false, onClick }) => (
+ <Box
+ component="button"
+ type="button"
+ disabled={disabled}
+ onClick={onClick}
+ sx={{
+ alignItems: "center",
+ bgcolor: "transparent",
+ border: 0,
+ color: "#666",
+ cursor: disabled ? "default" : "pointer",
+ display: "flex",
+ fontFamily: '"Inter Variable", Inter, sans-serif',
+ fontSize: 14,
+ fontWeight: 500,
+ justifyContent: "center",
+ lineHeight: "20px",
+ minWidth: 0,
+ opacity: 0.8,
+ p: 0,
+ textAlign: "center",
+ textDecoration: "underline",
+ textDecorationSkipInk: "none",
+ textUnderlineOffset: "2px",
+ textUnderlinePosition: "from-font",
+ width: "fit-content",
+ alignSelf: "center",
+ "&:focus-visible": {
+ borderRadius: "4px",
+ outline: `2px solid ${green}`,
+ outlineOffset: 4,
+ },
}}
>
{children}
@@ -506,26 +535,24 @@ const AvatarCropPage: React.FC<AvatarCropPageProps> = ({
boxSizing: "border-box",
display: "flex",
flexDirection: "column",
- gap: "10px",
+ gap: "16px",
gridRow: 5,
pt: 3,
width: "100%",
}}
>
- <AvatarCropPageButton
- disabled={isSaving}
- variant="secondary"
- onClick={onChooseAnother}
- >
- Choose another
- </AvatarCropPageButton>
<AvatarCropPageButton
disabled={isSaving || isDoneDisabled}
- variant="primary"
onClick={onDone}
>
{isSaving ? "Saving..." : "Done"}
</AvatarCropPageButton>
+ <AvatarCropPageLinkButton
+ disabled={isSaving}
+ onClick={onChooseAnother}
+ >
+ Change picture
+ </AvatarCropPageLinkButton>
</Box>
</Box>
</Box>
diff --git a/web/apps/space/src/services/spaceSession.ts b/web/apps/space/src/services/spaceSession.ts
new file mode 100644
index 0000000000..3100dab242
--- /dev/null
+++ b/web/apps/space/src/services/spaceSession.ts
@@ -0,0 +1,19 @@
+import {
+ savedKeyAttributes,
+ savedPartialLocalUser,
+} from "ente-accounts-rs/services/accounts-db";
+import { masterKeyFromSession } from "ente-accounts-rs/services/session-storage";
+import { savedAuthToken } from "ente-base/token";
+
+export const savedSpaceUnlockEmail = async () => {
+ try {
+ const user = savedPartialLocalUser();
+ if (!user?.email || !savedKeyAttributes()) return undefined;
+ if (await masterKeyFromSession()) return undefined;
+
+ const authToken = user.token ?? (await savedAuthToken());
+ return authToken ? user.email : undefined;
+ } catch {
+ return undefined;
+ }
+};
diff --git a/web/apps/space/src/utils/spaceRoutes.ts b/web/apps/space/src/utils/spaceRoutes.ts
index f7b23548f4..41329c6189 100644
--- a/web/apps/space/src/utils/spaceRoutes.ts
+++ b/web/apps/space/src/utils/spaceRoutes.ts
@@ -20,6 +20,7 @@ export const spaceRoutes = {
from == "login" ? "/setup-profile?from=login" : "/setup-profile",
signup: "/signup",
twoFactorVerify: "/two-factor/verify",
+ unlock: "/unlock",
verify: "/verify",
verifyLogin: "/verify?flow=login",
} as const;
diff --git a/web/packages/accounts-rs/services/redirect.ts b/web/packages/accounts-rs/services/redirect.ts
index ef87bef8bb..fc36bb9ab0 100644
--- a/web/packages/accounts-rs/services/redirect.ts
+++ b/web/packages/accounts-rs/services/redirect.ts
@@ -16,6 +16,7 @@ export const appHomeRoute: string = {
ensu: "/",
locker: "/locker",
social: "/app",
+ space: "/app",
}[appName];
let _stashedRedirect: string | undefined;
diff --git a/web/packages/base/app.ts b/web/packages/base/app.ts
index 5a6ddcf7dd..24852af19b 100644
--- a/web/packages/base/app.ts
+++ b/web/packages/base/app.ts
@@ -9,6 +9,7 @@ export const appNames = [
"ensu",
"locker",
"social",
+ "space",
] as const;
/**
@@ -75,6 +76,7 @@ export const staticAppTitle = {
ensu: "Ensu",
locker: "Ente Locker",
social: "Ente Social",
+ space: "Ente Space",
}[appName];
/**
@@ -103,6 +105,7 @@ export const clientPackageName = (() => {
ensu: "io.ente.ensu",
locker: "io.ente.locker.web",
social: "io.ente.social.web",
+ space: "io.ente.space.web",
}[appName];
})();