Skip to content

armgit / ente

Public Imported from GitHub
0

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

Add social auth MFA flows

Anand Baburajana1d7c8c9463b
diff --git a/web/apps/social/src/pages/login.tsx b/web/apps/social/src/pages/login.tsx
index f6fec5968f..739ad654c1 100644
--- a/web/apps/social/src/pages/login.tsx
+++ b/web/apps/social/src/pages/login.tsx
@@ -1,15 +1,60 @@
import { SocialPageMeta } from "components/SocialPageMeta";
import { useRouter } from "next/router";
import React, { useState } from "react";
-import { LoginScreen, loginBackground } from "screens/LoginScreen";
-import { completeSocialLogin } from "services/socialLogin";
+import {
+ LoginScreen,
+ loginBackground,
+ type SocialLoginCredentials,
+} from "screens/LoginScreen";
+import { beginSocialLogin, type SocialLoginResult } from "services/socialLogin";
+import { savePendingSocialPasskeyVerification } from "services/socialPasskeyVerification";
+import { useSocialAppState } from "state/socialAppState";
import { socialRoutes } from "utils/socialRoutes";
const Page: React.FC = () => {
const router = useRouter();
+ const { setPendingLoginCredentials, setPendingPasskeyVerification } =
+ useSocialAppState();
const [loginError, setLoginError] = useState<string>();
const [isSubmitting, setIsSubmitting] = useState(false);
+ const handleLoginResult = (
+ result: SocialLoginResult,
+ credentials: SocialLoginCredentials,
+ ) => {
+ switch (result.status) {
+ case "complete":
+ setPendingLoginCredentials(null);
+ void router.push(socialRoutes.setupProfile("login"));
+ break;
+ case "email-otp":
+ setPendingLoginCredentials({
+ email: result.email,
+ password: credentials.password,
+ });
+ void router.push(socialRoutes.verifyLogin);
+ break;
+ case "totp":
+ setPendingLoginCredentials(null);
+ void router.push(socialRoutes.twoFactorVerify);
+ break;
+ case "passkey":
+ setPendingLoginCredentials(null);
+ setPendingPasskeyVerification({
+ hasTwoFactorFallback: result.hasTwoFactorFallback,
+ passkeySessionID: result.passkeySessionID,
+ url: result.url,
+ });
+ savePendingSocialPasskeyVerification({
+ hasTwoFactorFallback: result.hasTwoFactorFallback,
+ passkeySessionID: result.passkeySessionID,
+ url: result.url,
+ });
+ void router.push(socialRoutes.passkeysVerify);
+ break;
+ }
+ };
+
return (
<>
<SocialPageMeta themeColor={loginBackground} />
@@ -21,8 +66,10 @@ const Page: React.FC = () => {
setIsSubmitting(true);
setLoginError(undefined);
try {
- await completeSocialLogin(credentials);
- void router.push(socialRoutes.setupProfile("login"));
+ handleLoginResult(
+ await beginSocialLogin(credentials),
+ credentials,
+ );
} catch (error) {
console.error("Social login failed", error);
setLoginError(
diff --git a/web/apps/social/src/pages/passkeys/finish.tsx b/web/apps/social/src/pages/passkeys/finish.tsx
new file mode 100644
index 0000000000..c172ffd353
--- /dev/null
+++ b/web/apps/social/src/pages/passkeys/finish.tsx
@@ -0,0 +1,40 @@
+import { SocialRouteFallback } from "components/SocialRouteFallback";
+import { useRouter } from "next/router";
+import React, { useEffect } from "react";
+import { verifyEmailBackground } from "screens/VerifyEmailScreen";
+import { completeSocialLoginPasskey } from "services/socialLogin";
+import { clearPendingSocialPasskeyVerification } from "services/socialPasskeyVerification";
+import { useSocialAppState } from "state/socialAppState";
+import { socialRoutes } from "utils/socialRoutes";
+
+const Page: React.FC = () => {
+ const router = useRouter();
+ const { setPendingPasskeyVerification } = useSocialAppState();
+
+ useEffect(() => {
+ const searchParams = new URLSearchParams(window.location.search);
+ const passkeySessionID = searchParams.get("passkeySessionID");
+ const response = searchParams.get("response");
+
+ if (!passkeySessionID || !response) {
+ void router.replace(socialRoutes.login);
+ return;
+ }
+
+ void (async () => {
+ try {
+ await completeSocialLoginPasskey(passkeySessionID, response);
+ clearPendingSocialPasskeyVerification();
+ setPendingPasskeyVerification(null);
+ void router.replace(socialRoutes.setupProfile("login"));
+ } catch (error) {
+ console.error("Social passkey verification failed", error);
+ void router.replace(socialRoutes.login);
+ }
+ })();
+ }, [router, setPendingPasskeyVerification]);
+
+ return <SocialRouteFallback background={verifyEmailBackground} />;
+};
+
+export default Page;
diff --git a/web/apps/social/src/pages/passkeys/verify.tsx b/web/apps/social/src/pages/passkeys/verify.tsx
new file mode 100644
index 0000000000..d6fe9e3228
--- /dev/null
+++ b/web/apps/social/src/pages/passkeys/verify.tsx
@@ -0,0 +1,141 @@
+import { SocialPageMeta } from "components/SocialPageMeta";
+import { SocialRouteFallback } from "components/SocialRouteFallback";
+import { savedPartialLocalUser } from "ente-accounts-rs/services/accounts-db";
+import { openPasskeyVerificationURL } from "ente-accounts-rs/services/passkey";
+import { useRouter } from "next/router";
+import React, { useEffect, useState } from "react";
+import {
+ PasskeyVerificationScreen,
+ passkeyVerificationBackground,
+ type PasskeyVerificationStatus,
+} from "screens/PasskeyVerificationScreen";
+import {
+ checkSocialLoginPasskeyStatus,
+ socialLoginPasskeySessionExpiredErrorMessage,
+ useSocialLoginTwoFactorInstead,
+} from "services/socialLogin";
+import {
+ clearPendingSocialPasskeyVerification,
+ hasAutoOpenedSocialPasskeyVerification,
+ markAutoOpenedSocialPasskeyVerification,
+ savedPendingSocialPasskeyVerification,
+ type PendingSocialPasskeyVerification,
+} from "services/socialPasskeyVerification";
+import { useSocialAppState } from "state/socialAppState";
+import { socialRoutes } from "utils/socialRoutes";
+
+const passkeyErrorMessage = (error: unknown) => {
+ if (
+ error instanceof Error &&
+ error.message == socialLoginPasskeySessionExpiredErrorMessage
+ ) {
+ return "Passkey session expired. Please sign in again.";
+ }
+ return error instanceof Error
+ ? error.message
+ : "Couldn't check passkey status. Please try again.";
+};
+
+const Page: React.FC = () => {
+ const router = useRouter();
+ const { pendingPasskeyVerification, setPendingPasskeyVerification } =
+ useSocialAppState();
+ const [verification, setVerification] =
+ useState<PendingSocialPasskeyVerification>();
+ const [status, setStatus] = useState<PasskeyVerificationStatus>("waiting");
+ const [errorMessage, setErrorMessage] = useState<string>();
+
+ useEffect(() => {
+ const nextVerification =
+ pendingPasskeyVerification ??
+ savedPendingSocialPasskeyVerification();
+ const user = savedPartialLocalUser();
+
+ if (
+ !nextVerification ||
+ !user?.email ||
+ user.passkeySessionID != nextVerification.passkeySessionID
+ ) {
+ void router.replace(socialRoutes.login);
+ return;
+ }
+
+ setVerification(nextVerification);
+ setPendingPasskeyVerification(nextVerification);
+
+ if (
+ !hasAutoOpenedSocialPasskeyVerification(
+ nextVerification.passkeySessionID,
+ )
+ ) {
+ markAutoOpenedSocialPasskeyVerification(
+ nextVerification.passkeySessionID,
+ );
+ openPasskeyVerificationURL(nextVerification);
+ }
+ }, [pendingPasskeyVerification, router, setPendingPasskeyVerification]);
+
+ const clearPasskeyVerification = () => {
+ clearPendingSocialPasskeyVerification();
+ setPendingPasskeyVerification(null);
+ };
+
+ const tryAgain = () => {
+ if (!verification) return;
+ setStatus("waiting");
+ setErrorMessage(undefined);
+ openPasskeyVerificationURL(verification);
+ };
+
+ const checkStatus = async () => {
+ if (!verification || status == "checking") return;
+
+ setStatus("checking");
+ setErrorMessage(undefined);
+ try {
+ const result = await checkSocialLoginPasskeyStatus(
+ verification.passkeySessionID,
+ );
+ if (result.status == "pending") {
+ setStatus("pending");
+ return;
+ }
+
+ clearPasskeyVerification();
+ void router.push(socialRoutes.setupProfile("login"));
+ } catch (error) {
+ console.error("Social passkey status check failed", error);
+ setErrorMessage(passkeyErrorMessage(error));
+ setStatus("waiting");
+ }
+ };
+
+ const useTwoFactor = () => {
+ useSocialLoginTwoFactorInstead();
+ clearPasskeyVerification();
+ void router.push(socialRoutes.twoFactorVerify);
+ };
+
+ if (!verification) {
+ return (
+ <SocialRouteFallback background={passkeyVerificationBackground} />
+ );
+ }
+
+ return (
+ <>
+ <SocialPageMeta themeColor={passkeyVerificationBackground} />
+ <PasskeyVerificationScreen
+ canUseTwoFactor={verification.hasTwoFactorFallback}
+ errorMessage={errorMessage}
+ onBack={() => void router.push(socialRoutes.login)}
+ onCheckStatus={() => void checkStatus()}
+ onTryAgain={tryAgain}
+ onUseTwoFactor={useTwoFactor}
+ status={status}
+ />
+ </>
+ );
+};
+
+export default Page;
diff --git a/web/apps/social/src/pages/signup.tsx b/web/apps/social/src/pages/signup.tsx
index 4c4c9d29ad..d7279fc149 100644
--- a/web/apps/social/src/pages/signup.tsx
+++ b/web/apps/social/src/pages/signup.tsx
@@ -13,17 +13,24 @@ import { socialRoutes } from "utils/socialRoutes";
const Page: React.FC = () => {
const router = useRouter();
const { setIsLiveSignupVerification, setSignupEmail } = useSocialAppState();
+ const [signupError, setSignupError] = useState<string>();
const [isSubmitting, setIsSubmitting] = useState(false);
const createAccount = async (input: CreateAccountInput) => {
setIsSubmitting(true);
+ setSignupError(undefined);
try {
- await beginSocialSignup(input);
- setSignupEmail(input.email);
+ const { email } = await beginSocialSignup(input);
+ setSignupEmail(email);
setIsLiveSignupVerification(true);
void router.push(socialRoutes.verify);
} catch (error) {
console.error("Social signup failed", error);
+ setSignupError(
+ error instanceof Error
+ ? error.message
+ : "Couldn't create account. Please try again.",
+ );
setIsSubmitting(false);
}
};
@@ -32,6 +39,7 @@ const Page: React.FC = () => {
<>
<SocialPageMeta themeColor={createAccountBackground} />
<CreateAccountScreen
+ errorMessage={signupError}
isSubmitting={isSubmitting}
onBack={() => void router.push(socialRoutes.onboarding)}
onCreateAccount={(input) => void createAccount(input)}
diff --git a/web/apps/social/src/pages/two-factor/verify.tsx b/web/apps/social/src/pages/two-factor/verify.tsx
new file mode 100644
index 0000000000..1d71384e4f
--- /dev/null
+++ b/web/apps/social/src/pages/two-factor/verify.tsx
@@ -0,0 +1,74 @@
+import { SocialPageMeta } from "components/SocialPageMeta";
+import { SocialRouteFallback } from "components/SocialRouteFallback";
+import { savedPartialLocalUser } from "ente-accounts-rs/services/accounts-db";
+import { isHTTPErrorWithStatus } from "ente-base/http";
+import { useRouter } from "next/router";
+import React, { useEffect, useState } from "react";
+import {
+ VerifyTwoFactorScreen,
+ verifyTwoFactorBackground,
+} from "screens/VerifyTwoFactorScreen";
+import { completeSocialLoginSecondFactor } from "services/socialLogin";
+import { socialRoutes } from "utils/socialRoutes";
+
+const twoFactorErrorMessage = (error: unknown) => {
+ if (isHTTPErrorWithStatus(error, 401)) {
+ return "Incorrect code. Please try again.";
+ }
+ if (isHTTPErrorWithStatus(error, 404)) {
+ return "Login session expired. Please sign in again.";
+ }
+ return error instanceof Error
+ ? error.message
+ : "Couldn't verify this code. Please try again.";
+};
+
+const Page: React.FC = () => {
+ const router = useRouter();
+ const [twoFactorSessionID, setTwoFactorSessionID] = useState("");
+ const [errorMessage, setErrorMessage] = useState<string>();
+ const [isSubmitting, setIsSubmitting] = useState(false);
+
+ useEffect(() => {
+ const user = savedPartialLocalUser();
+ if (!user?.email || !user.twoFactorSessionID) {
+ void router.replace(socialRoutes.login);
+ return;
+ }
+
+ setTwoFactorSessionID(user.twoFactorSessionID);
+ }, [router]);
+
+ const verifySecondFactor = async (code: string) => {
+ if (!twoFactorSessionID) return;
+
+ setIsSubmitting(true);
+ setErrorMessage(undefined);
+ try {
+ await completeSocialLoginSecondFactor(code, twoFactorSessionID);
+ void router.push(socialRoutes.setupProfile("login"));
+ } catch (error) {
+ console.error("Social 2FA verification failed", error);
+ setErrorMessage(twoFactorErrorMessage(error));
+ setIsSubmitting(false);
+ }
+ };
+
+ if (!twoFactorSessionID) {
+ return <SocialRouteFallback background={verifyTwoFactorBackground} />;
+ }
+
+ return (
+ <>
+ <SocialPageMeta themeColor={verifyTwoFactorBackground} />
+ <VerifyTwoFactorScreen
+ errorMessage={errorMessage}
+ isSubmitting={isSubmitting}
+ onBack={() => void router.push(socialRoutes.login)}
+ onVerify={(code) => void verifySecondFactor(code)}
+ />
+ </>
+ );
+};
+
+export default Page;
diff --git a/web/apps/social/src/pages/verify.tsx b/web/apps/social/src/pages/verify.tsx
index 178169b0c7..e6bb600262 100644
--- a/web/apps/social/src/pages/verify.tsx
+++ b/web/apps/social/src/pages/verify.tsx
@@ -1,29 +1,103 @@
import { SocialPageMeta } from "components/SocialPageMeta";
import { SocialRouteFallback } from "components/SocialRouteFallback";
+import { isHTTPErrorWithStatus } from "ente-base/http";
import { useRouter } from "next/router";
-import React, { useEffect } from "react";
+import React, { useEffect, useState } from "react";
import {
VerifyEmailScreen,
verifyEmailBackground,
} from "screens/VerifyEmailScreen";
+import {
+ completeSocialLoginEmailVerification,
+ resendSocialLoginCode,
+ type SocialLoginResult,
+} from "services/socialLogin";
+import { savePendingSocialPasskeyVerification } from "services/socialPasskeyVerification";
import {
completeSocialSignup,
resendSocialSignupCode,
} from "services/socialSignup";
import { useSocialAppState } from "state/socialAppState";
-import { socialRoutes } from "utils/socialRoutes";
+import { socialRoutes, verifyFlowFromQuery } from "utils/socialRoutes";
+
+const verificationErrorMessage = (error: unknown) => {
+ if (isHTTPErrorWithStatus(error, 401)) {
+ return "Incorrect code. Please try again.";
+ }
+ if (isHTTPErrorWithStatus(error, 410)) {
+ return "This code has expired. Please request a new one.";
+ }
+ return error instanceof Error
+ ? error.message
+ : "Couldn't verify this code. Please try again.";
+};
const Page: React.FC = () => {
const router = useRouter();
const {
isLiveSignupVerification,
+ pendingLoginCredentials,
setIsLiveSignupVerification,
+ setPendingLoginCredentials,
+ setPendingPasskeyVerification,
signupEmail,
} = useSocialAppState();
+ const [verificationError, setVerificationError] = useState<string>();
+ const [isSubmitting, setIsSubmitting] = useState(false);
+ const [isResending, setIsResending] = useState(false);
+ const verifyFlow = verifyFlowFromQuery(router.query.flow);
+ const isLoginVerification = router.isReady && verifyFlow == "login";
+ const email = isLoginVerification
+ ? pendingLoginCredentials?.email
+ : signupEmail;
useEffect(() => {
- if (!signupEmail) void router.replace(socialRoutes.signup);
- }, [router, signupEmail]);
+ if (!router.isReady) return;
+
+ if (isLoginVerification) {
+ if (!pendingLoginCredentials)
+ void router.replace(socialRoutes.login);
+ } else if (!signupEmail) {
+ void router.replace(socialRoutes.signup);
+ }
+ }, [
+ isLoginVerification,
+ pendingLoginCredentials,
+ router,
+ router.isReady,
+ signupEmail,
+ ]);
+
+ const handleLoginResult = (result: SocialLoginResult) => {
+ switch (result.status) {
+ case "complete":
+ setPendingLoginCredentials(null);
+ void router.push(socialRoutes.setupProfile("login"));
+ break;
+ case "totp":
+ setPendingLoginCredentials(null);
+ void router.push(socialRoutes.twoFactorVerify);
+ break;
+ case "passkey":
+ setPendingLoginCredentials(null);
+ setPendingPasskeyVerification({
+ hasTwoFactorFallback: result.hasTwoFactorFallback,
+ passkeySessionID: result.passkeySessionID,
+ url: result.url,
+ });
+ savePendingSocialPasskeyVerification({
+ hasTwoFactorFallback: result.hasTwoFactorFallback,
+ passkeySessionID: result.passkeySessionID,
+ url: result.url,
+ });
+ void router.push(socialRoutes.passkeysVerify);
+ break;
+ case "email-otp":
+ setVerificationError("Please enter the latest code we sent.");
+ setIsSubmitting(false);
+ break;
+ }
+ };
const verifySignupEmail = async (code: string) => {
if (!isLiveSignupVerification) {
@@ -37,10 +111,59 @@ const Page: React.FC = () => {
void router.push(socialRoutes.setupProfile("verify"));
} catch (error) {
console.error("Social signup verification failed", error);
+ setVerificationError(verificationErrorMessage(error));
+ setIsSubmitting(false);
}
};
- if (!signupEmail) {
+ const verifyLoginEmail = async (code: string) => {
+ if (!pendingLoginCredentials) {
+ void router.replace(socialRoutes.login);
+ return;
+ }
+
+ try {
+ handleLoginResult(
+ await completeSocialLoginEmailVerification({
+ ...pendingLoginCredentials,
+ code,
+ }),
+ );
+ } catch (error) {
+ console.error("Social login email verification failed", error);
+ setVerificationError(verificationErrorMessage(error));
+ setIsSubmitting(false);
+ }
+ };
+
+ const verifyEmail = (code: string) => {
+ setIsSubmitting(true);
+ setVerificationError(undefined);
+ if (isLoginVerification) void verifyLoginEmail(code);
+ else void verifySignupEmail(code);
+ };
+
+ const resendVerificationCode = async () => {
+ if (!email || isResending) return;
+
+ setIsResending(true);
+ setVerificationError(undefined);
+ try {
+ if (isLoginVerification) await resendSocialLoginCode(email);
+ else await resendSocialSignupCode(email);
+ } catch (error) {
+ console.error("Social verification resend failed", error);
+ setVerificationError(
+ error instanceof Error
+ ? error.message
+ : "Couldn't resend the code. Please try again.",
+ );
+ } finally {
+ setIsResending(false);
+ }
+ };
+
+ if (!router.isReady || !email) {
return <SocialRouteFallback background={verifyEmailBackground} />;
}
@@ -48,16 +171,34 @@ const Page: React.FC = () => {
<>
<SocialPageMeta themeColor={verifyEmailBackground} />
<VerifyEmailScreen
- email={signupEmail}
- initialCode={isLiveSignupVerification ? "" : undefined}
- onBack={() => void router.push(socialRoutes.signup)}
- onChangeEmail={() => void router.push(socialRoutes.signup)}
+ email={email}
+ errorMessage={verificationError}
+ initialCode={
+ isLoginVerification || isLiveSignupVerification
+ ? ""
+ : undefined
+ }
+ isSubmitting={isSubmitting}
+ onBack={() =>
+ void router.push(
+ isLoginVerification
+ ? socialRoutes.login
+ : socialRoutes.signup,
+ )
+ }
+ onChangeEmail={() =>
+ void router.push(
+ isLoginVerification
+ ? socialRoutes.login
+ : socialRoutes.signup,
+ )
+ }
onResendCode={
- isLiveSignupVerification
- ? () => void resendSocialSignupCode(signupEmail)
+ isLoginVerification || isLiveSignupVerification
+ ? () => void resendVerificationCode()
: undefined
}
- onVerify={(code) => void verifySignupEmail(code)}
+ onVerify={verifyEmail}
/>
</>
);
diff --git a/web/apps/social/src/screens/CreateAccountScreen.tsx b/web/apps/social/src/screens/CreateAccountScreen.tsx
index 6ab2c23a81..c26c5cc061 100644
--- a/web/apps/social/src/screens/CreateAccountScreen.tsx
+++ b/web/apps/social/src/screens/CreateAccountScreen.tsx
@@ -7,6 +7,7 @@ const green = "#08C225";
const textBase = "#000";
const textLight = "#969696";
const warning = "#F63A3A";
+const createAccountFormID = "social-create-account-form";
export interface CreateAccountInput {
email: string;
@@ -15,6 +16,7 @@ export interface CreateAccountInput {
}
interface CreateAccountScreenProps {
+ errorMessage?: string;
isSubmitting?: boolean;
onBack: () => void;
onCreateAccount: (input: CreateAccountInput) => void;
@@ -193,6 +195,7 @@ const TextInput: React.FC<TextInputProps> = ({
};
export const CreateAccountScreen: React.FC<CreateAccountScreenProps> = ({
+ errorMessage,
isSubmitting = false,
onBack,
onCreateAccount,
@@ -303,6 +306,8 @@ export const CreateAccountScreen: React.FC<CreateAccountScreenProps> = ({
<Box
component="form"
+ id={createAccountFormID}
+ noValidate
onSubmit={handleSubmit}
sx={{
display: "flex",
@@ -341,6 +346,22 @@ export const CreateAccountScreen: React.FC<CreateAccountScreenProps> = ({
onChange={setReferralSource}
value={referralSource}
/>
+ {errorMessage && (
+ <Box
+ role="alert"
+ sx={{
+ color: warning,
+ fontFamily:
+ '"Inter Variable", Inter, sans-serif',
+ fontSize: 13,
+ fontWeight: 500,
+ lineHeight: "18px",
+ mt: "-8px",
+ }}
+ >
+ {errorMessage}
+ </Box>
+ )}
<Box
component="label"
sx={{
@@ -446,9 +467,9 @@ export const CreateAccountScreen: React.FC<CreateAccountScreenProps> = ({
<Box
className={canCreateAccount ? "green-bg" : undefined}
component="button"
- type="button"
+ form={createAccountFormID}
+ type="submit"
disabled={!canCreateAccount}
- onClick={submitCreateAccount}
sx={{
alignItems: "center",
bgcolor: canCreateAccount ? green : "#F5F5F5",
diff --git a/web/apps/social/src/screens/LoginScreen.tsx b/web/apps/social/src/screens/LoginScreen.tsx
index 91e4c2f5e4..ffa2c37bf9 100644
--- a/web/apps/social/src/screens/LoginScreen.tsx
+++ b/web/apps/social/src/screens/LoginScreen.tsx
@@ -7,6 +7,7 @@ const green = "#08C225";
const textBase = "#000";
const textLight = "#969696";
const warning = "#F63A3A";
+const loginFormID = "social-login-form";
export interface SocialLoginCredentials {
email: string;
@@ -276,6 +277,8 @@ export const LoginScreen: React.FC<LoginScreenProps> = ({
<Box
component="form"
+ id={loginFormID}
+ noValidate
onSubmit={handleSubmit}
sx={{
display: "flex",
@@ -338,9 +341,9 @@ export const LoginScreen: React.FC<LoginScreenProps> = ({
<Box
className={canContinue ? "green-bg" : undefined}
component="button"
- type="button"
+ form={loginFormID}
+ type="submit"
disabled={!canContinue}
- onClick={submitLogin}
sx={{
alignItems: "center",
bgcolor: canContinue ? green : "#F5F5F5",
diff --git a/web/apps/social/src/screens/PasskeyVerificationScreen.tsx b/web/apps/social/src/screens/PasskeyVerificationScreen.tsx
new file mode 100644
index 0000000000..b53675c85d
--- /dev/null
+++ b/web/apps/social/src/screens/PasskeyVerificationScreen.tsx
@@ -0,0 +1,301 @@
+import { Box } from "@mui/material";
+import React from "react";
+
+export const passkeyVerificationBackground = "#FAFAFA";
+
+const green = "#08C225";
+const primaryLight = "#DDEEDF";
+const primaryDark = "#069D1E";
+const textBase = "#000";
+const textLight = "#969696";
+const warning = "#F63A3A";
+
+export type PasskeyVerificationStatus = "waiting" | "checking" | "pending";
+
+interface PasskeyVerificationScreenProps {
+ canUseTwoFactor?: boolean;
+ errorMessage?: string;
+ onBack: () => void;
+ onCheckStatus: () => void;
+ onTryAgain: () => void;
+ onUseTwoFactor?: () => void;
+ status?: PasskeyVerificationStatus;
+}
+
+const BackIcon: React.FC = () => (
+ <Box
+ component="svg"
+ viewBox="0 0 24 24"
+ aria-hidden
+ sx={{ display: "block", height: 24, width: 24 }}
+ >
+ <path
+ d="M15 6L9 12L15 18"
+ fill="none"
+ stroke="currentColor"
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ strokeWidth="2"
+ />
+ </Box>
+);
+
+const statusText = (status: PasskeyVerificationStatus) => {
+ switch (status) {
+ case "checking":
+ return "Checking verification...";
+ case "pending":
+ return "Verification still pending";
+ case "waiting":
+ return "Waiting for verification...";
+ }
+};
+
+export const PasskeyVerificationScreen: React.FC<
+ PasskeyVerificationScreenProps
+> = ({
+ canUseTwoFactor = false,
+ errorMessage,
+ onBack,
+ onCheckStatus,
+ onTryAgain,
+ onUseTwoFactor,
+ status = "waiting",
+}) => {
+ const isChecking = status == "checking";
+
+ return (
+ <Box
+ component="main"
+ sx={{
+ bgcolor: passkeyVerificationBackground,
+ color: textBase,
+ display: "grid",
+ minHeight: "100svh",
+ overflow: "hidden",
+ placeItems: { xs: "stretch", sm: "start center" },
+ }}
+ >
+ <Box
+ sx={{
+ bgcolor: passkeyVerificationBackground,
+ boxSizing: "border-box",
+ display: "flex",
+ flexDirection: "column",
+ minHeight: "100svh",
+ mx: "auto",
+ pb: "216px",
+ px: 3,
+ width: "100%",
+ "@media (min-width: 600px)": { maxWidth: 390 },
+ }}
+ >
+ <Box
+ component="header"
+ sx={{
+ display: "grid",
+ gridTemplateColumns: "42px 1fr 42px",
+ height: 42,
+ mt: "32px",
+ 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>
+ <Box
+ component="h1"
+ sx={{
+ alignSelf: "center",
+ fontFamily: '"Inter Variable", Inter, sans-serif',
+ fontSize: 20,
+ fontWeight: 600,
+ justifySelf: "center",
+ lineHeight: "28px",
+ m: 0,
+ whiteSpace: "nowrap",
+ }}
+ >
+ Passkey verification
+ </Box>
+ <Box />
+ </Box>
+
+ <Box
+ sx={{
+ alignItems: "center",
+ display: "flex",
+ flex: 1,
+ flexDirection: "column",
+ justifyContent: "center",
+ mb: "56px",
+ width: "100%",
+ }}
+ >
+ <Box
+ sx={{
+ alignItems: "center",
+ display: "flex",
+ flexDirection: "column",
+ gap: "8px",
+ textAlign: "center",
+ width: "100%",
+ }}
+ >
+ <Box
+ sx={{
+ color: textBase,
+ fontFamily:
+ '"Inter Variable", Inter, sans-serif',
+ fontSize: 14,
+ fontWeight: 500,
+ lineHeight: "20px",
+ minHeight: "20px",
+ }}
+ >
+ {statusText(status)}
+ </Box>
+ {canUseTwoFactor && onUseTwoFactor && (
+ <Box
+ component="button"
+ type="button"
+ onClick={onUseTwoFactor}
+ sx={{
+ bgcolor: "transparent",
+ border: 0,
+ color: green,
+ cursor: "pointer",
+ fontFamily:
+ '"Inter Variable", Inter, sans-serif',
+ fontSize: 14,
+ fontWeight: 500,
+ lineHeight: "20px",
+ p: 0,
+ textDecoration: "underline",
+ }}
+ >
+ Use 2FA instead
+ </Box>
+ )}
+ {errorMessage && (
+ <Box
+ role="alert"
+ sx={{
+ color: warning,
+ fontFamily:
+ '"Inter Variable", Inter, sans-serif',
+ fontSize: 13,
+ fontWeight: 500,
+ lineHeight: "18px",
+ mt: "8px",
+ maxWidth: 298,
+ }}
+ >
+ {errorMessage}
+ </Box>
+ )}
+ </Box>
+ </Box>
+
+ <Box
+ sx={{
+ bgcolor: passkeyVerificationBackground,
+ bottom: 0,
+ boxSizing: "border-box",
+ display: "flex",
+ flexDirection: "column",
+ gap: "16px",
+ left: "50%",
+ maxWidth: 390,
+ p: 3,
+ position: "fixed",
+ transform: "translateX(-50%)",
+ width: "100%",
+ }}
+ >
+ <Box
+ className="green-bg"
+ component="button"
+ type="button"
+ onClick={onTryAgain}
+ sx={{
+ alignItems: "center",
+ bgcolor: green,
+ border: 0,
+ borderRadius: "20px",
+ color: "white",
+ cursor: "pointer",
+ display: "flex",
+ fontFamily: '"Inter Variable", Inter, sans-serif',
+ fontSize: 14,
+ fontWeight: 500,
+ height: 48,
+ justifyContent: "center",
+ lineHeight: "20px",
+ p: "14px 24px",
+ width: "100%",
+ "&:focus-visible": {
+ outline: `2px solid ${green}`,
+ outlineOffset: 3,
+ },
+ "&:hover": { bgcolor: "#07AE22" },
+ }}
+ >
+ Try again
+ </Box>
+ <Box
+ component="button"
+ type="button"
+ disabled={isChecking}
+ onClick={onCheckStatus}
+ sx={{
+ alignItems: "center",
+ bgcolor: primaryLight,
+ border: 0,
+ borderRadius: "20px",
+ color: isChecking ? textLight : primaryDark,
+ cursor: isChecking ? "default" : "pointer",
+ display: "flex",
+ fontFamily: '"Inter Variable", Inter, sans-serif',
+ fontSize: 14,
+ fontWeight: 500,
+ height: 48,
+ justifyContent: "center",
+ lineHeight: "20px",
+ p: "14px 24px",
+ width: "100%",
+ "&:focus-visible": {
+ outline: `2px solid ${green}`,
+ outlineOffset: 3,
+ },
+ }}
+ >
+ {isChecking ? "Checking..." : "Check status"}
+ </Box>
+ </Box>
+ </Box>
+ </Box>
+ );
+};
diff --git a/web/apps/social/src/screens/SetupProfileScreen.tsx b/web/apps/social/src/screens/SetupProfileScreen.tsx
index d1b5a8c664..43ad9b16d2 100644
--- a/web/apps/social/src/screens/SetupProfileScreen.tsx
+++ b/web/apps/social/src/screens/SetupProfileScreen.tsx
@@ -8,6 +8,7 @@ const textBase = "#000";
const textLight = "#969696";
const warning = "#F63A3A";
const paleGreen = "#E7F6E9";
+const setupProfileFormID = "social-setup-profile-form";
const mockSetupProfileData = {
avatarUrl: "/images/sample-avatar.jpg",
@@ -300,6 +301,8 @@ export const SetupProfileScreen: React.FC<SetupProfileScreenProps> = ({
<Box
component="form"
+ id={setupProfileFormID}
+ noValidate
onSubmit={handleSubmit}
sx={{
alignItems: "center",
@@ -447,9 +450,9 @@ export const SetupProfileScreen: React.FC<SetupProfileScreenProps> = ({
<Box
className={canContinue ? "green-bg" : undefined}
component="button"
- type="button"
+ form={setupProfileFormID}
+ type="submit"
disabled={!canContinue}
- onClick={submitProfile}
sx={{
alignItems: "center",
bgcolor: canContinue ? green : "#F5F5F5",
diff --git a/web/apps/social/src/screens/VerifyEmailScreen.tsx b/web/apps/social/src/screens/VerifyEmailScreen.tsx
index d6799f4d51..8f55b5eed3 100644
--- a/web/apps/social/src/screens/VerifyEmailScreen.tsx
+++ b/web/apps/social/src/screens/VerifyEmailScreen.tsx
@@ -9,11 +9,15 @@ const emptyStroke = "#EDF0FF";
const textBase = "#000";
const textMuted = "#666";
const textLight = "#969696";
+const warning = "#F63A3A";
const mockVerificationCode = "888888";
+const verifyEmailFormID = "social-verify-email-form";
interface VerifyEmailScreenProps {
email: string;
+ errorMessage?: string;
initialCode?: string;
+ isSubmitting?: boolean;
onBack: () => void;
onChangeEmail: () => void;
onResendCode?: () => void;
@@ -116,7 +120,9 @@ const OtpInput: React.FC<OtpInputProps> = ({
export const VerifyEmailScreen: React.FC<VerifyEmailScreenProps> = ({
email,
+ errorMessage,
initialCode = mockVerificationCode,
+ isSubmitting = false,
onBack,
onChangeEmail,
onResendCode,
@@ -136,7 +142,8 @@ export const VerifyEmailScreen: React.FC<VerifyEmailScreenProps> = ({
0,
otp.findIndex((digit) => digit.length == 0),
);
- const canVerify = otp.every((digit) => digit.length == 1);
+ const otpComplete = otp.every((digit) => digit.length == 1);
+ const canVerify = otpComplete && !isSubmitting;
const focusInput = (index: number) => {
inputRefs.current[index]?.focus();
@@ -215,6 +222,15 @@ export const VerifyEmailScreen: React.FC<VerifyEmailScreenProps> = ({
onResendCode?.();
};
+ const submitVerification = () => {
+ if (canVerify) onVerify?.(otp.join(""));
+ };
+
+ const handleSubmit: React.FormEventHandler<HTMLFormElement> = (event) => {
+ event.preventDefault();
+ submitVerification();
+ };
+
return (
<Box
component="main"
@@ -295,6 +311,10 @@ export const VerifyEmailScreen: React.FC<VerifyEmailScreenProps> = ({
</Box>
<Box
+ component="form"
+ id={verifyEmailFormID}
+ noValidate
+ onSubmit={handleSubmit}
sx={{
alignItems: "center",
display: "flex",
@@ -362,7 +382,7 @@ export const VerifyEmailScreen: React.FC<VerifyEmailScreenProps> = ({
<OtpInput
key={index}
active={
- !canVerify && activeIndex == index
+ !otpComplete && activeIndex == index
}
index={index}
inputRef={(node) => {
@@ -375,6 +395,23 @@ export const VerifyEmailScreen: React.FC<VerifyEmailScreenProps> = ({
/>
))}
</Box>
+ {errorMessage && (
+ <Box
+ role="alert"
+ sx={{
+ color: warning,
+ fontFamily:
+ '"Inter Variable", Inter, sans-serif',
+ fontSize: 13,
+ fontWeight: 500,
+ lineHeight: "18px",
+ mt: "12px",
+ textAlign: "center",
+ }}
+ >
+ {errorMessage}
+ </Box>
+ )}
<Box
sx={{
@@ -405,26 +442,28 @@ export const VerifyEmailScreen: React.FC<VerifyEmailScreenProps> = ({
>
Change email
</Box>
- <Box
- component="button"
- type="button"
- onClick={handleResendCode}
- sx={{
- bgcolor: "transparent",
- border: 0,
- color: green,
- cursor: "pointer",
- fontFamily:
- '"Inter Variable", Inter, sans-serif',
- fontSize: 14,
- fontWeight: 500,
- lineHeight: "20px",
- p: 0,
- textDecoration: "underline",
- }}
- >
- Resend code
- </Box>
+ {onResendCode && (
+ <Box
+ component="button"
+ type="button"
+ onClick={handleResendCode}
+ sx={{
+ bgcolor: "transparent",
+ border: 0,
+ color: green,
+ cursor: "pointer",
+ fontFamily:
+ '"Inter Variable", Inter, sans-serif',
+ fontSize: 14,
+ fontWeight: 500,
+ lineHeight: "20px",
+ p: 0,
+ textDecoration: "underline",
+ }}
+ >
+ Resend code
+ </Box>
+ )}
</Box>
</Box>
</Box>
@@ -446,9 +485,9 @@ export const VerifyEmailScreen: React.FC<VerifyEmailScreenProps> = ({
<Box
className={canVerify ? "green-bg" : undefined}
component="button"
- type="button"
+ form={verifyEmailFormID}
+ type="submit"
disabled={!canVerify}
- onClick={() => onVerify?.(otp.join(""))}
sx={{
alignItems: "center",
bgcolor: canVerify ? green : "#F5F5F5",
@@ -474,7 +513,7 @@ export const VerifyEmailScreen: React.FC<VerifyEmailScreenProps> = ({
: undefined,
}}
>
- Verify
+ {isSubmitting ? "Verifying..." : "Verify"}
</Box>
</Box>
</Box>
diff --git a/web/apps/social/src/screens/VerifyTwoFactorScreen.tsx b/web/apps/social/src/screens/VerifyTwoFactorScreen.tsx
new file mode 100644
index 0000000000..cea4f9651d
--- /dev/null
+++ b/web/apps/social/src/screens/VerifyTwoFactorScreen.tsx
@@ -0,0 +1,453 @@
+import { Shield01Icon } from "@hugeicons/core-free-icons";
+import { HugeiconsIcon } from "@hugeicons/react";
+import { Box } from "@mui/material";
+import React, { useEffect, useRef, useState } from "react";
+
+export const verifyTwoFactorBackground = "#FAFAFA";
+
+const green = "#08C225";
+const activeFill = "rgba(8, 194, 37, 0.08)";
+const emptyStroke = "#EDF0FF";
+const textBase = "#000";
+const textMuted = "#666";
+const textLight = "#969696";
+const warning = "#F63A3A";
+const verifyTwoFactorFormID = "social-verify-two-factor-form";
+
+interface VerifyTwoFactorScreenProps {
+ errorMessage?: string;
+ initialCode?: string;
+ isSubmitting?: boolean;
+ onBack: () => void;
+ onVerify?: (code: string) => void;
+}
+
+const BackIcon: React.FC = () => (
+ <Box
+ component="svg"
+ viewBox="0 0 24 24"
+ aria-hidden
+ sx={{ display: "block", height: 24, width: 24 }}
+ >
+ <path
+ d="M15 6L9 12L15 18"
+ fill="none"
+ stroke="currentColor"
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ strokeWidth="2"
+ />
+ </Box>
+);
+
+interface OtpInputProps {
+ active: boolean;
+ index: number;
+ inputRef: (node: HTMLInputElement | null) => void;
+ onChange: (index: number, value: string) => void;
+ onKeyDown: (
+ index: number,
+ event: React.KeyboardEvent<HTMLInputElement>,
+ ) => void;
+ onPaste: (
+ index: number,
+ event: React.ClipboardEvent<HTMLInputElement>,
+ ) => void;
+ value: string;
+}
+
+const OtpInput: React.FC<OtpInputProps> = ({
+ active,
+ index,
+ inputRef,
+ onChange,
+ onKeyDown,
+ onPaste,
+ value,
+}) => {
+ const typed = value.length > 0;
+
+ return (
+ <Box
+ sx={{
+ alignItems: "center",
+ bgcolor: typed ? "white" : active ? activeFill : "white",
+ border:
+ typed || active
+ ? `2px solid ${green}`
+ : `1px solid ${emptyStroke}`,
+ borderRadius: "20px",
+ display: "flex",
+ flex: "1 1 0",
+ height: 52,
+ justifyContent: "center",
+ minWidth: 0,
+ }}
+ >
+ <Box
+ component="input"
+ ref={inputRef}
+ aria-label={`2FA code digit ${index + 1}`}
+ autoComplete={index == 0 ? "one-time-code" : "off"}
+ inputMode="numeric"
+ maxLength={1}
+ onChange={(event) => onChange(index, event.target.value)}
+ onKeyDown={(event) => onKeyDown(index, event)}
+ onPaste={(event) => onPaste(index, event)}
+ pattern="[0-9]*"
+ type="text"
+ value={value}
+ sx={{
+ bgcolor: "transparent",
+ border: 0,
+ color: green,
+ fontFamily: '"Inter Variable", Inter, sans-serif',
+ fontSize: 20,
+ fontWeight: 700,
+ height: "100%",
+ lineHeight: "17px",
+ outline: 0,
+ p: 0,
+ textAlign: "center",
+ width: "100%",
+ }}
+ />
+ </Box>
+ );
+};
+
+export const VerifyTwoFactorScreen: React.FC<VerifyTwoFactorScreenProps> = ({
+ errorMessage,
+ initialCode = "",
+ isSubmitting = false,
+ onBack,
+ onVerify,
+}) => {
+ const [otp, setOtp] = useState<string[]>(
+ initialCode
+ .replace(/\D/g, "")
+ .slice(0, 6)
+ .padEnd(6, " ")
+ .split("")
+ .map((digit) => (digit == " " ? "" : digit)),
+ );
+ const inputRefs = useRef<(HTMLInputElement | null)[]>([]);
+
+ const activeIndex = Math.max(
+ 0,
+ otp.findIndex((digit) => digit.length == 0),
+ );
+ const otpComplete = otp.every((digit) => digit.length == 1);
+ const canVerify = otpComplete && !isSubmitting;
+
+ const focusInput = (index: number) => {
+ inputRefs.current[index]?.focus();
+ inputRefs.current[index]?.select();
+ };
+
+ useEffect(() => {
+ const initialCodeLength = initialCode
+ .replace(/\D/g, "")
+ .slice(0, 6).length;
+ const initialFocusIndex =
+ initialCodeLength >= 6 ? 5 : Math.max(0, initialCodeLength);
+ const animationFrame = window.requestAnimationFrame(() =>
+ focusInput(initialFocusIndex),
+ );
+
+ return () => window.cancelAnimationFrame(animationFrame);
+ }, [initialCode]);
+
+ const setDigitsFrom = (startIndex: number, rawValue: string) => {
+ const digits = rawValue.replace(/\D/g, "").slice(0, 6 - startIndex);
+ if (!digits) {
+ setOtp((current) =>
+ current.map((digit, index) =>
+ index == startIndex ? "" : digit,
+ ),
+ );
+ return;
+ }
+
+ setOtp((current) => {
+ const next = [...current];
+ digits.split("").forEach((digit, offset) => {
+ next[startIndex + offset] = digit;
+ });
+ return next;
+ });
+
+ focusInput(Math.min(startIndex + digits.length, 5));
+ };
+
+ const handleKeyDown = (
+ index: number,
+ event: React.KeyboardEvent<HTMLInputElement>,
+ ) => {
+ if (event.key == "Backspace" && !otp[index] && index > 0) {
+ event.preventDefault();
+ setOtp((current) =>
+ current.map((digit, digitIndex) =>
+ digitIndex == index - 1 ? "" : digit,
+ ),
+ );
+ focusInput(index - 1);
+ } else if (event.key == "ArrowLeft" && index > 0) {
+ event.preventDefault();
+ focusInput(index - 1);
+ } else if (event.key == "ArrowRight" && index < 5) {
+ event.preventDefault();
+ focusInput(index + 1);
+ }
+ };
+
+ const handlePaste = (
+ index: number,
+ event: React.ClipboardEvent<HTMLInputElement>,
+ ) => {
+ event.preventDefault();
+ setDigitsFrom(index, event.clipboardData.getData("text"));
+ };
+
+ const submitVerification = () => {
+ if (canVerify) onVerify?.(otp.join(""));
+ };
+
+ const handleSubmit: React.FormEventHandler<HTMLFormElement> = (event) => {
+ event.preventDefault();
+ submitVerification();
+ };
+
+ return (
+ <Box
+ component="main"
+ sx={{
+ bgcolor: verifyTwoFactorBackground,
+ color: textBase,
+ display: "grid",
+ minHeight: "100svh",
+ overflow: "hidden",
+ placeItems: { xs: "stretch", sm: "start center" },
+ }}
+ >
+ <Box
+ sx={{
+ bgcolor: verifyTwoFactorBackground,
+ boxSizing: "border-box",
+ display: "flex",
+ flexDirection: "column",
+ minHeight: "100svh",
+ mx: "auto",
+ pb: "120px",
+ px: 3,
+ width: "100%",
+ "@media (min-width: 600px)": { maxWidth: 390 },
+ }}
+ >
+ <Box
+ component="header"
+ sx={{
+ display: "grid",
+ gridTemplateColumns: "42px 1fr 42px",
+ height: 42,
+ mt: "32px",
+ 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>
+ <Box
+ component="h1"
+ sx={{
+ alignSelf: "center",
+ fontFamily: '"Inter Variable", Inter, sans-serif',
+ fontSize: 20,
+ fontWeight: 600,
+ justifySelf: "center",
+ lineHeight: "28px",
+ m: 0,
+ whiteSpace: "nowrap",
+ }}
+ >
+ 2FA verification
+ </Box>
+ <Box />
+ </Box>
+
+ <Box
+ component="form"
+ id={verifyTwoFactorFormID}
+ noValidate
+ onSubmit={handleSubmit}
+ sx={{
+ alignItems: "center",
+ display: "flex",
+ flexDirection: "column",
+ gap: "40px",
+ mt: "40px",
+ width: "100%",
+ }}
+ >
+ <Box
+ sx={{
+ alignItems: "center",
+ color: green,
+ display: "flex",
+ height: 82,
+ justifyContent: "center",
+ width: 101,
+ }}
+ >
+ <HugeiconsIcon
+ icon={Shield01Icon}
+ size={64}
+ strokeWidth={1.6}
+ />
+ </Box>
+
+ <Box
+ sx={{
+ display: "flex",
+ flexDirection: "column",
+ gap: "24px",
+ width: "100%",
+ }}
+ >
+ <Box
+ sx={{
+ color: textMuted,
+ fontFamily:
+ '"Inter Variable", Inter, sans-serif',
+ fontSize: 14,
+ fontWeight: 500,
+ lineHeight: "20px",
+ mx: "auto",
+ maxWidth: 298,
+ textAlign: "center",
+ width: "100%",
+ }}
+ >
+ Enter the 6-digit code from your authenticator app
+ </Box>
+
+ <Box sx={{ width: "100%" }}>
+ <Box
+ sx={{
+ display: "flex",
+ gap: "6px",
+ justifyContent: "stretch",
+ width: "100%",
+ }}
+ >
+ {otp.map((digit, index) => (
+ <OtpInput
+ key={index}
+ active={
+ !otpComplete && activeIndex == index
+ }
+ index={index}
+ inputRef={(node) => {
+ inputRefs.current[index] = node;
+ }}
+ onChange={setDigitsFrom}
+ onKeyDown={handleKeyDown}
+ onPaste={handlePaste}
+ value={digit}
+ />
+ ))}
+ </Box>
+ {errorMessage && (
+ <Box
+ role="alert"
+ sx={{
+ color: warning,
+ fontFamily:
+ '"Inter Variable", Inter, sans-serif',
+ fontSize: 13,
+ fontWeight: 500,
+ lineHeight: "18px",
+ mt: "12px",
+ textAlign: "center",
+ }}
+ >
+ {errorMessage}
+ </Box>
+ )}
+ </Box>
+ </Box>
+ </Box>
+
+ <Box
+ sx={{
+ bgcolor: verifyTwoFactorBackground,
+ bottom: 0,
+ boxSizing: "border-box",
+ left: "50%",
+ maxWidth: 390,
+ p: 3,
+ position: "fixed",
+ transform: "translateX(-50%)",
+ width: "100%",
+ }}
+ >
+ <Box
+ className={canVerify ? "green-bg" : undefined}
+ component="button"
+ form={verifyTwoFactorFormID}
+ type="submit"
+ disabled={!canVerify}
+ sx={{
+ alignItems: "center",
+ bgcolor: canVerify ? green : "#F5F5F5",
+ border: 0,
+ borderRadius: "20px",
+ color: canVerify ? "white" : textLight,
+ cursor: canVerify ? "pointer" : "default",
+ display: "flex",
+ fontFamily: '"Inter Variable", Inter, sans-serif',
+ fontSize: 14,
+ fontWeight: 500,
+ height: 48,
+ justifyContent: "center",
+ lineHeight: "20px",
+ p: "14px 24px",
+ width: "100%",
+ "&:focus-visible": {
+ outline: `2px solid ${green}`,
+ outlineOffset: 3,
+ },
+ "&:hover": canVerify
+ ? { bgcolor: "#07AE22" }
+ : undefined,
+ }}
+ >
+ {isSubmitting ? "Verifying..." : "Verify"}
+ </Box>
+ </Box>
+ </Box>
+ </Box>
+ );
+};
diff --git a/web/apps/social/src/services/socialLogin.ts b/web/apps/social/src/services/socialLogin.ts
index ecabeb04a7..14bc9f1397 100644
--- a/web/apps/social/src/services/socialLogin.ts
+++ b/web/apps/social/src/services/socialLogin.ts
@@ -1,53 +1,108 @@
import {
replaceSavedLocalUser,
+ savedPartialLocalUser,
+ savedSRPAttributes,
saveIsFirstLogin,
saveKeyAttributes,
+ saveOriginalKeyAttributes,
saveSRPAttributes,
updateSavedLocalUser,
} from "ente-accounts-rs/services/accounts-db";
-import { decryptBox, deriveKey } from "ente-accounts-rs/services/crypto";
+import {
+ decryptBox,
+ deriveKey,
+ fromB64URLSafeNoPadding,
+} from "ente-accounts-rs/services/crypto";
+import {
+ checkPasskeyVerificationStatus,
+ clearInflightPasskeySessionID,
+ passkeySessionExpiredErrorMessage,
+} from "ente-accounts-rs/services/passkey";
import {
saveMasterKeyInSessionAndSafeStore,
stashKeyEncryptionKeyInSessionStore,
+ unstashKeyEncryptionKeyFromSession,
} from "ente-accounts-rs/services/session-storage";
import {
getSRPAttributes,
+ type SRPAttributes,
srpVerificationUnauthorizedErrorMessage,
verifySRP,
} from "ente-accounts-rs/services/srp";
import {
decryptAndStoreTokenIfNeeded,
+ type EmailOrSRPVerificationResponse,
generateAndSaveInteractiveKeyAttributes,
+ sendOTT,
+ TwoFactorAuthorizationResponse,
+ verifyEmail,
+ verifyTwoFactor,
} from "ente-accounts-rs/services/user";
+import { clientPackageName } from "ente-base/app";
import { saveAuthToken } from "ente-base/token";
+import { nullToUndefined } from "ente-utils/transform";
export interface SocialLoginInput {
email: string;
password: string;
}
-export const completeSocialLogin = async ({
+export type SocialLoginResult =
+ | { status: "complete"; email: string }
+ | { status: "email-otp"; email: string }
+ | { status: "totp"; email: string }
+ | {
+ accountsUrl: string;
+ hasTwoFactorFallback: boolean;
+ passkeySessionID: string;
+ status: "passkey";
+ url: string;
+ };
+
+export type SocialLoginPasskeyStatusResult =
+ | SocialLoginResult
+ | { status: "pending" };
+
+export const socialLoginPasskeySessionExpiredErrorMessage =
+ passkeySessionExpiredErrorMessage;
+
+const cleanedEmail = (email: string) => email.trim();
+
+const deriveLoginKEK = (
+ password: string,
+ { kekSalt, memLimit, opsLimit }: SRPAttributes,
+) => deriveKey(password, kekSalt, opsLimit, memLimit);
+
+const socialPasskeyVerificationRedirectURL = (
+ accountsURL: string,
+ passkeySessionID: string,
+) => {
+ const redirect = `${window.location.origin}/passkeys/finish`;
+ const params = new URLSearchParams({
+ clientPackage: clientPackageName,
+ passkeySessionID,
+ redirect,
+ });
+ return `${accountsURL}/passkeys/verify?${params.toString()}`;
+};
+
+export const beginSocialLogin = async ({
email,
password,
-}: SocialLoginInput) => {
- const cleanedEmail = email.trim();
- const srpAttributes = await getSRPAttributes(cleanedEmail);
+}: SocialLoginInput): Promise<SocialLoginResult> => {
+ const emailForLogin = cleanedEmail(email);
+ const srpAttributes = await getSRPAttributes(emailForLogin);
if (!srpAttributes) throw new Error("No account found for this email.");
- if (srpAttributes.isEmailMFAEnabled) {
- throw new Error(
- "This account requires email verification during login.",
- );
- }
- replaceSavedLocalUser({ email: cleanedEmail });
+ replaceSavedLocalUser({ email: emailForLogin });
saveSRPAttributes(srpAttributes);
- const kek = await deriveKey(
- password,
- srpAttributes.kekSalt,
- srpAttributes.opsLimit,
- srpAttributes.memLimit,
- );
+ if (srpAttributes.isEmailMFAEnabled) {
+ await sendOTT(emailForLogin, "login");
+ return { status: "email-otp", email: emailForLogin };
+ }
+
+ const kek = await deriveLoginKEK(password, srpAttributes);
let verification;
try {
@@ -62,7 +117,54 @@ export const completeSocialLogin = async ({
throw error;
}
+ return finishSocialLoginVerification({
+ email: emailForLogin,
+ kek,
+ password,
+ verification,
+ });
+};
+
+export const completeSocialLoginEmailVerification = async ({
+ code,
+ email,
+ password,
+}: SocialLoginInput & { code: string }): Promise<SocialLoginResult> => {
+ const emailForLogin = cleanedEmail(email);
+ const srpAttributes =
+ savedSRPAttributes() ?? (await getSRPAttributes(emailForLogin));
+ if (!srpAttributes) throw new Error("No account found for this email.");
+
+ saveSRPAttributes(srpAttributes);
+ const kek = await deriveLoginKEK(password, srpAttributes);
+ const verification = await verifyEmail(emailForLogin, code, undefined);
+
+ return finishSocialLoginVerification({
+ email: emailForLogin,
+ kek,
+ password,
+ verification,
+ });
+};
+
+export const resendSocialLoginCode = (email: string) =>
+ sendOTT(email.trim(), "login");
+
+interface FinishSocialLoginVerificationInput {
+ email: string;
+ kek: string;
+ password?: string;
+ verification: EmailOrSRPVerificationResponse;
+}
+
+const finishSocialLoginVerification = async ({
+ email,
+ kek,
+ password,
+ verification,
+}: FinishSocialLoginVerificationInput): Promise<SocialLoginResult> => {
const {
+ accountsUrl,
encryptedToken,
id,
keyAttributes,
@@ -74,14 +176,38 @@ export const completeSocialLogin = async ({
const secondFactorSessionID = twoFactorSessionID || twoFactorSessionIDV2;
- if (passkeySessionID || secondFactorSessionID) {
+ if (passkeySessionID) {
+ if (!accountsUrl) {
+ throw new Error("Passkey verification URL is missing.");
+ }
await stashKeyEncryptionKeyInSessionStore(kek);
updateSavedLocalUser({
passkeySessionID,
twoFactorSessionID: secondFactorSessionID,
isTwoFactorEnabled: true,
});
- throw new Error("This account needs a second factor to sign in.");
+ saveIsFirstLogin();
+ return {
+ accountsUrl,
+ hasTwoFactorFallback: Boolean(secondFactorSessionID),
+ passkeySessionID,
+ status: "passkey",
+ url: socialPasskeyVerificationRedirectURL(
+ accountsUrl,
+ passkeySessionID,
+ ),
+ };
+ }
+
+ if (secondFactorSessionID) {
+ await stashKeyEncryptionKeyInSessionStore(kek);
+ updateSavedLocalUser({
+ passkeySessionID: undefined,
+ twoFactorSessionID: secondFactorSessionID,
+ isTwoFactorEnabled: true,
+ });
+ saveIsFirstLogin();
+ return { status: "totp", email };
}
updateSavedLocalUser({
@@ -97,8 +223,97 @@ export const completeSocialLogin = async ({
throw new Error("This account has not finished setup.");
}
+ await saveCompletedSocialLogin({ keyAttributes, kek, password });
+
+ return { status: "complete", email };
+};
+
+export const completeSocialLoginSecondFactor = async (
+ code: string,
+ sessionID: string,
+): Promise<SocialLoginResult> => {
+ const response = await verifyTwoFactor(code, sessionID);
+ return finishSocialLoginAuthorization(response);
+};
+
+export const completeSocialLoginPasskey = async (
+ passkeySessionID: string,
+ response: string,
+): Promise<SocialLoginResult> => {
+ const inflightPasskeySessionID = nullToUndefined(
+ sessionStorage.getItem("inflightPasskeySessionID"),
+ );
+ if (
+ !inflightPasskeySessionID ||
+ inflightPasskeySessionID != passkeySessionID
+ ) {
+ throw new Error("Unexpected passkey verification response.");
+ }
+
+ clearInflightPasskeySessionID();
+ return finishSocialLoginAuthorization(
+ TwoFactorAuthorizationResponse.parse(
+ JSON.parse(
+ new TextDecoder().decode(
+ await fromB64URLSafeNoPadding(response),
+ ),
+ ),
+ ),
+ );
+};
+
+export const checkSocialLoginPasskeyStatus = async (
+ passkeySessionID: string,
+): Promise<SocialLoginPasskeyStatusResult> => {
+ const response = await checkPasskeyVerificationStatus(passkeySessionID);
+ if (!response) return { status: "pending" };
+
+ clearInflightPasskeySessionID();
+ return finishSocialLoginAuthorization(response);
+};
+
+export const useSocialLoginTwoFactorInstead = () => {
+ clearInflightPasskeySessionID();
+ updateSavedLocalUser({ passkeySessionID: undefined });
+};
+
+const finishSocialLoginAuthorization = async ({
+ encryptedToken,
+ id,
+ keyAttributes,
+}: TwoFactorAuthorizationResponse): Promise<SocialLoginResult> => {
+ const kek = await unstashKeyEncryptionKeyFromSession();
+ if (!kek) throw new Error("Login session expired. Please sign in again.");
+
+ updateSavedLocalUser({
+ id,
+ token: undefined,
+ encryptedToken,
+ isTwoFactorEnabled: undefined,
+ twoFactorSessionID: undefined,
+ passkeySessionID: undefined,
+ });
+ await saveCompletedSocialLogin({ keyAttributes, kek });
+
+ return { status: "complete", email: savedPartialLocalUser()?.email ?? "" };
+};
+
+const saveCompletedSocialLogin = async ({
+ keyAttributes,
+ kek,
+ password,
+}: {
+ keyAttributes: EmailOrSRPVerificationResponse["keyAttributes"];
+ kek: string;
+ password?: string;
+}) => {
+ if (!keyAttributes) {
+ throw new Error("This account has not finished setup.");
+ }
+
saveIsFirstLogin();
saveKeyAttributes(keyAttributes);
+ saveOriginalKeyAttributes(keyAttributes);
const masterKey = await decryptBox(
{
@@ -107,13 +322,13 @@ export const completeSocialLogin = async ({
},
kek,
);
- const updatedKeyAttributes = await generateAndSaveInteractiveKeyAttributes(
- password,
- keyAttributes,
- masterKey,
- );
+ const tokenKeyAttributes = password
+ ? await generateAndSaveInteractiveKeyAttributes(
+ password,
+ keyAttributes,
+ masterKey,
+ )
+ : keyAttributes;
await saveMasterKeyInSessionAndSafeStore(masterKey);
- await decryptAndStoreTokenIfNeeded(updatedKeyAttributes, masterKey);
-
- return { email: cleanedEmail };
+ await decryptAndStoreTokenIfNeeded(tokenKeyAttributes, masterKey);
};
diff --git a/web/apps/social/src/services/socialPasskeyVerification.ts b/web/apps/social/src/services/socialPasskeyVerification.ts
new file mode 100644
index 0000000000..cd60086482
--- /dev/null
+++ b/web/apps/social/src/services/socialPasskeyVerification.ts
@@ -0,0 +1,59 @@
+export interface PendingSocialPasskeyVerification {
+ hasTwoFactorFallback: boolean;
+ passkeySessionID: string;
+ url: string;
+}
+
+const pendingSocialPasskeyVerificationKey = "socialPendingPasskeyVerification";
+const autoOpenedSocialPasskeyPrefix = "socialPasskeyAutoOpened:";
+
+const isPendingSocialPasskeyVerification = (
+ value: unknown,
+): value is PendingSocialPasskeyVerification => {
+ if (!value || typeof value != "object") return false;
+ const candidate = value as Record<string, unknown>;
+ return (
+ typeof candidate.hasTwoFactorFallback == "boolean" &&
+ typeof candidate.passkeySessionID == "string" &&
+ typeof candidate.url == "string"
+ );
+};
+
+export const savePendingSocialPasskeyVerification = (
+ verification: PendingSocialPasskeyVerification,
+) => {
+ sessionStorage.setItem(
+ pendingSocialPasskeyVerificationKey,
+ JSON.stringify(verification),
+ );
+};
+
+export const savedPendingSocialPasskeyVerification = () => {
+ const saved = sessionStorage.getItem(pendingSocialPasskeyVerificationKey);
+ if (!saved) return undefined;
+
+ try {
+ const parsed: unknown = JSON.parse(saved);
+ return isPendingSocialPasskeyVerification(parsed) ? parsed : undefined;
+ } catch {
+ return undefined;
+ }
+};
+
+export const clearPendingSocialPasskeyVerification = () => {
+ sessionStorage.removeItem(pendingSocialPasskeyVerificationKey);
+};
+
+const autoOpenedSocialPasskeyKey = (passkeySessionID: string) =>
+ `${autoOpenedSocialPasskeyPrefix}${passkeySessionID}`;
+
+export const hasAutoOpenedSocialPasskeyVerification = (
+ passkeySessionID: string,
+) =>
+ sessionStorage.getItem(autoOpenedSocialPasskeyKey(passkeySessionID)) == "1";
+
+export const markAutoOpenedSocialPasskeyVerification = (
+ passkeySessionID: string,
+) => {
+ sessionStorage.setItem(autoOpenedSocialPasskeyKey(passkeySessionID), "1");
+};
diff --git a/web/apps/social/src/services/socialSignup.ts b/web/apps/social/src/services/socialSignup.ts
index 7a69ac2fa9..212baf0890 100644
--- a/web/apps/social/src/services/socialSignup.ts
+++ b/web/apps/social/src/services/socialSignup.ts
@@ -42,6 +42,7 @@ export const beginSocialSignup = async ({
}: SocialSignupInput) => {
const cleanedEmail = email.trim();
const cleanedReferralSource = referralSource.trim();
+ unstashReferralSource();
if (cleanedReferralSource) stashReferralSource(cleanedReferralSource);
await sendOTT(cleanedEmail, "signup");
@@ -58,6 +59,8 @@ export const beginSocialSignup = async ({
);
await saveMasterKeyInSessionAndSafeStore(masterKey);
saveJustSignedUp();
+
+ return { email: cleanedEmail };
};
export const completeSocialSignup = async (email: string, code: string) => {
@@ -108,4 +111,4 @@ export const completeSocialSignup = async (email: string, code: string) => {
};
export const resendSocialSignupCode = (email: string) =>
- sendOTT(email, undefined);
+ sendOTT(email.trim(), "signup");
diff --git a/web/apps/social/src/state/SocialAppStateProvider.tsx b/web/apps/social/src/state/SocialAppStateProvider.tsx
index dbdbf03d3e..2f5bf7af5d 100644
--- a/web/apps/social/src/state/SocialAppStateProvider.tsx
+++ b/web/apps/social/src/state/SocialAppStateProvider.tsx
@@ -1,5 +1,7 @@
import React, { useCallback, useMemo, useState } from "react";
+import type { SocialLoginCredentials } from "screens/LoginScreen";
import type { SetupProfile } from "screens/SetupProfileScreen";
+import type { PendingSocialPasskeyVerification } from "services/socialPasskeyVerification";
import {
type OnboardingEntrySource,
type SocialAppState,
@@ -15,11 +17,17 @@ export const SocialAppStateProvider: React.FC<React.PropsWithChildren> = ({
useState(false);
const [onboardingEntrySource, setOnboardingEntrySource] =
useState<OnboardingEntrySource>("direct");
+ const [pendingLoginCredentials, setPendingLoginCredentials] =
+ useState<SocialLoginCredentials | null>(null);
+ const [pendingPasskeyVerification, setPendingPasskeyVerification] =
+ useState<PendingSocialPasskeyVerification | null>(null);
const [profile, setProfile] = useState<SetupProfile | null>(null);
const [signupEmail, setSignupEmail] = useState("");
const resetAfterLogout = useCallback(() => {
setProfile(null);
+ setPendingLoginCredentials(null);
+ setPendingPasskeyVerification(null);
setOnboardingEntrySource("direct");
setFriends(initialFriends());
}, []);
@@ -29,11 +37,15 @@ export const SocialAppStateProvider: React.FC<React.PropsWithChildren> = ({
friends,
isLiveSignupVerification,
onboardingEntrySource,
+ pendingLoginCredentials,
+ pendingPasskeyVerification,
profile,
resetAfterLogout,
setFriends,
setIsLiveSignupVerification,
setOnboardingEntrySource,
+ setPendingLoginCredentials,
+ setPendingPasskeyVerification,
setProfile,
setSignupEmail,
signupEmail,
@@ -42,6 +54,8 @@ export const SocialAppStateProvider: React.FC<React.PropsWithChildren> = ({
friends,
isLiveSignupVerification,
onboardingEntrySource,
+ pendingLoginCredentials,
+ pendingPasskeyVerification,
profile,
resetAfterLogout,
signupEmail,
diff --git a/web/apps/social/src/state/socialAppState.tsx b/web/apps/social/src/state/socialAppState.tsx
index 0863556a65..601edd9ab7 100644
--- a/web/apps/social/src/state/socialAppState.tsx
+++ b/web/apps/social/src/state/socialAppState.tsx
@@ -1,6 +1,8 @@
import { sampleFriends, type FriendProfile } from "data/friends";
import React, { createContext, useContext } from "react";
+import type { SocialLoginCredentials } from "screens/LoginScreen";
import type { SetupProfile } from "screens/SetupProfileScreen";
+import type { PendingSocialPasskeyVerification } from "services/socialPasskeyVerification";
export type OnboardingEntrySource = "direct" | "add-friend-link";
@@ -8,6 +10,8 @@ export interface SocialAppState {
friends: FriendProfile[];
isLiveSignupVerification: boolean;
onboardingEntrySource: OnboardingEntrySource;
+ pendingLoginCredentials: SocialLoginCredentials | null;
+ pendingPasskeyVerification: PendingSocialPasskeyVerification | null;
profile: SetupProfile | null;
signupEmail: string;
resetAfterLogout: () => void;
@@ -16,6 +20,12 @@ export interface SocialAppState {
setOnboardingEntrySource: React.Dispatch<
React.SetStateAction<OnboardingEntrySource>
>;
+ setPendingLoginCredentials: React.Dispatch<
+ React.SetStateAction<SocialLoginCredentials | null>
+ >;
+ setPendingPasskeyVerification: React.Dispatch<
+ React.SetStateAction<PendingSocialPasskeyVerification | null>
+ >;
setProfile: React.Dispatch<React.SetStateAction<SetupProfile | null>>;
setSignupEmail: React.Dispatch<React.SetStateAction<string>>;
}
diff --git a/web/apps/social/src/utils/socialRoutes.ts b/web/apps/social/src/utils/socialRoutes.ts
index 5688a4c9af..185030e53e 100644
--- a/web/apps/social/src/utils/socialRoutes.ts
+++ b/web/apps/social/src/utils/socialRoutes.ts
@@ -4,6 +4,7 @@ export type FriendProfileSource =
| "home"
| "notifications"
| "profile";
+export type VerifyFlow = "login" | "signup";
export const onboardingSourceSearchParam = "onboardingSource";
export const addFriendLinkOnboardingSource = "add-friend-link";
@@ -20,14 +21,22 @@ export const socialRoutes = {
login: "/login",
notifications: "/app/notifications",
onboarding: "/",
+ passkeysFinish: "/passkeys/finish",
+ passkeysVerify: "/passkeys/verify",
profile: "/app/profile",
settings: "/app/settings",
setupProfile: (from: SetupProfileSource = "verify") =>
`/setup-profile?from=${from}`,
signup: "/signup",
+ twoFactorVerify: "/two-factor/verify",
verify: "/verify",
+ verifyLogin: "/verify?flow=login",
} as const;
+export const verifyFlowFromQuery = (
+ value: string | string[] | undefined,
+): VerifyFlow => (valueFromQuery(value) == "login" ? "login" : "signup");
+
export const setupProfileSourceFromQuery = (
value: string | string[] | undefined,
): SetupProfileSource =>