Skip to content

A fully open source & end-to-end encrypted note taking alternative to Evernote.

feat: improve account recovery flow

thecodrr62279ca79f86
diff --git a/apps/web/src/common/db.js b/apps/web/src/common/db.js
index d6131d97e..f495d5659 100644
--- a/apps/web/src/common/db.js
+++ b/apps/web/src/common/db.js
@@ -8,10 +8,16 @@ var db;
function initializeDatabase() {
return import("notes-core/api").then(({ default: Database }) => {
db = new Database(StorageInterface, EventSource);
+ // db.host({
+ // API_HOST: "https://api.notesnook.com",
+ // AUTH_HOST: "https://auth.streetwriters.co",
+ // SSE_HOST: "https://events.streetwriters.co",
+ // });
+
db.host({
- API_HOST: "https://api.notesnook.com",
- AUTH_HOST: "https://auth.streetwriters.co",
- SSE_HOST: "https://events.streetwriters.co",
+ API_HOST: "http://localhost:5264",
+ AUTH_HOST: "http://localhost:8264",
+ SSE_HOST: "http://localhost:7264",
});
return db.init();
@@ -22,12 +28,6 @@ export { db, initializeDatabase };
// export const db = new Database(StorageInterface, EventSource);
-// db.host({
-// API_HOST: "http://localhost:5264",
-// AUTH_HOST: "http://localhost:8264",
-// SSE_HOST: "http://localhost:7264",
-// });
-
// // db.host({
// // API_HOST: "http://192.168.10.7:5264",
// // AUTH_HOST: "http://192.168.10.7:8264",
diff --git a/apps/web/src/components/dialogs/recovery-key-dialog.js b/apps/web/src/components/dialogs/recovery-key-dialog.js
index 0431457b3..2edeacd3c 100644
--- a/apps/web/src/components/dialogs/recovery-key-dialog.js
+++ b/apps/web/src/components/dialogs/recovery-key-dialog.js
@@ -6,18 +6,19 @@ import Logo from "../../assets/notesnook-logo.png";
import download from "../../utils/download";
import ClipboardJS from "clipboard";
import { captureMessage } from "@sentry/react";
-import { useStore as useUserStore } from "../../stores/user-store";
import { Suspense } from "react";
const QRCode = React.lazy(() => import("../../re-exports/react-qrcode-logo"));
function RecoveryKeyDialog(props) {
const [key, setKey] = useState();
- const { email } = useUserStore((store) => store.user);
+ const [email, setEmail] = useState();
const [copyText, setCopyText] = useState("Copy to clipboard");
useEffect(() => {
(async () => {
+ const { email } = await db.user.getUser();
const { key } = await db.user.getEncryptionKey();
+ setEmail(email);
setKey(key);
})();
}, []);
diff --git a/apps/web/src/components/icons/index.js b/apps/web/src/components/icons/index.js
index 55c03dea8..1a25617e3 100644
--- a/apps/web/src/components/icons/index.js
+++ b/apps/web/src/components/icons/index.js
@@ -48,6 +48,7 @@ export const Notebook = createIcon(Icons.mdiBookOutline);
export const Notebook2 = createIcon(Icons.mdiBookOutline);
export const ArrowLeft = createIcon(Icons.mdiArrowLeft);
export const ArrowRight = createIcon(Icons.mdiArrowRight);
+export const ArrowDown = createIcon(Icons.mdiArrowDown);
export const Move = createIcon(Icons.mdiBookPlusMultipleOutline);
export const Topic = createIcon(Icons.mdiFormatTitle);
export const Alert = createIcon(Icons.mdiAlert);
diff --git a/apps/web/src/views/recovery.js b/apps/web/src/views/recovery.js
index ada5ff086..d344b7b55 100644
--- a/apps/web/src/views/recovery.js
+++ b/apps/web/src/views/recovery.js
@@ -1,5 +1,5 @@
-import React, { useEffect, useState } from "react";
-import { Button, Flex, Text } from "rebass";
+import React, { useEffect, useMemo, useState } from "react";
+import { Button, Flex, Image, Text } from "rebass";
import { useQueryParams } from "../navigation";
import ThemeProvider from "../components/theme-provider";
import Field from "../components/field";
@@ -7,178 +7,299 @@ import * as Icon from "../components/icons";
import { db } from "../common/db";
import { showToast } from "../utils/toast";
import { useCallback } from "react";
+import { showRecoveryKeyDialog } from "../common/dialog-controller";
+import { createBackup } from "../common";
+import Logo from "../assets/logo.svg";
function navigate(path) {
window.location.href = path;
}
-function AccountRecovery(props) {
+function useRecovery() {
const [{ code, userId }] = useQueryParams();
- const [step, setStep] = useState(1);
const [loading, setLoading] = useState({ isLoading: false });
- const doWorkWithLoading = useCallback(
- async (message, workCallback, error, onError) => {
- try {
- setLoading({ isLoading: true, message });
- await workCallback();
- } catch (e) {
- console.error(e);
- showToast("error", `${error} Error: ${e.message}`);
- if (onError) onError(e);
- } finally {
- setLoading({ isLoading: false });
- }
- },
- []
- );
+ const performAction = useCallback(async function ({
+ message,
+ error,
+ onError,
+ action,
+ }) {
+ try {
+ setLoading({ isLoading: true, message });
+ await action();
+ } catch (e) {
+ console.error(e);
+ showToast("error", `${error} Error: ${e.message || "unknown."}`);
+ if (onError) await onError(e);
+ } finally {
+ setLoading({ isLoading: false });
+ }
+ },
+ []);
+
+ return { code, userId, loading, setLoading, performAction };
+}
+function useAuthenticateUser({ code, userId, performAction }) {
useEffect(() => {
- setLoading({ isLoading: true, message: "Please wait..." });
- if (!code || !userId) {
- navigate("/");
- return;
+ performAction({
+ message: "Authenticating. Please wait...",
+ error: "Failed to authenticate. Please try again.",
+ onError: () => navigate("/"),
+ action: authenticateUser,
+ });
+
+ async function authenticateUser() {
+ await db.init();
+
+ // if we already have an access token
+ const accessToken = await db.user.tokenManager.getAccessToken();
+ if (!accessToken) {
+ await db.user.tokenManager.getAccessTokenFromAuthorizationCode(
+ userId,
+ code.replace(/ /gm, "+")
+ );
+ }
+ await db.user.fetchUser(true);
}
- // http://localhost:3000/accountRecovery?userId=5fe1895d1b0636cf87b5058ecode=CfDJ8J5/rfvIUAZBidvsDZpkZcvNxUm0K2dGODHceKrSC4GUrGxtS3ZG5G2l8T7m0dvx6otZZv7djtzKBOUls0yZsjehYq+uSe0hG72M+DAMtB9gQ6df28xWdh2fx7L7Fw7s5I9unuRGYjN/A31e0BT3ryt9rzS1NM9ATnju80l1NR0Te599i76lSPLaOpnbO8qUanOqGtoQwaOa+bEMjJRGDG5NH2DkuJEsuD7VGqgXB57s4LWNJL0MvNwm5y2WImuaoQ==
- (async function () {
- doWorkWithLoading(
- "Authorizing. Please wait...",
- async () => {
- await db.init();
- if (!!(await db.user.tokenManager.getAccessToken())) {
- await db.user.fetchUser(false);
- setLoading({ isLoading: false });
- return;
- }
- await db.user.tokenManager.getAccessTokenFromAuthorizationCode(
- userId,
- code.replace(/ /gm, "+")
- );
- await db.user.fetchUser(false);
- },
- "Could not authorize user.",
- () => {
- navigate("/");
- }
- );
- })();
- }, [userId, code, doWorkWithLoading]);
+ }, [code, userId, performAction]);
+}
+
+const steps = [RecoveryKeyStep, BackupDataStep, NewPasswordStep, FinalStep];
+
+function AccountRecovery() {
+ const { code, userId, loading, performAction } = useRecovery();
+ const [step, setStep] = useState(0);
+ const Step = useMemo(() => steps[step], [step]);
+ useAuthenticateUser({ code, userId, performAction });
+ useEffect(() => {
+ if (!code || !userId) return navigate("/");
+ }, [code, userId]);
return (
<ThemeProvider>
<Flex
flexDirection="column"
height="100%"
- justifyContent="center"
+ overflowY="auto"
alignItems="center"
+ justifyContent="center"
+ p={2}
>
- <Flex
- flexDirection="column"
- justifyContent="center"
- alignItems="center"
- p={2}
- >
- <Text variant="heading" color="primary">
- Notesnook
- </Text>
- <Text variant="heading" fontSize={24} mb={2} textAlign="center">
- {step === 3
- ? "Your account has been recovered!"
- : "Account Recovery"}
- </Text>
- {loading.isLoading ? (
- <Flex flexDirection="column">
- <Icon.Loading rotate />
- <Text variant="body">{loading.message}</Text>
- </Flex>
- ) : step === 3 ? (
- <Button
- variant="secondary"
- onClick={() => (window.location.href = "/#/login")}
- >
- Return to Notesnook
- </Button>
- ) : (
- <Flex
- flexDirection="column"
- as="form"
- width="100%"
- onSubmit={async (e) => {
- e.preventDefault();
- var formData = new FormData(e.target);
-
- var recoveryKey = formData.get("recovery_key");
- if (recoveryKey) {
- const [key] = recoveryKey.split("\0");
- await doWorkWithLoading(
- "Downloading your data. This might take a bit.",
- async () => {
- const user = await db.user.getUser();
- await db.context.write(`_uk_@${user.email}@_k`, key);
- await db.sync(true, true);
- setStep((s) => ++s);
- },
- "Invalid recovery key."
- );
- }
- var newPassword = formData.get("new_password");
- if (newPassword) {
- await doWorkWithLoading(
- "Resetting account password. Please wait...",
- async () => {
- if (await db.user.resetPassword(newPassword)) {
- await db.user.logout(true);
- setStep((s) => ++s);
- }
- },
- "Invalid password."
- );
- }
+ <Image src={Logo} height={50} sx={{ position: "absolute", top: 2 }} />
+ <Text variant="heading" color="primary">
+ Notesnook
+ </Text>
+ {loading.isLoading ? (
+ <Flex flexDirection="column" mt={2}>
+ <Icon.Loading rotate color="primary" />
+ <Text variant="body" mt={2} fontSize={"title"}>
+ {loading.message}
+ </Text>
+ </Flex>
+ ) : (
+ <>
+ <Step
+ performAction={performAction}
+ onFinished={() => {
+ setStep((s) => ++s);
}}
- >
- {step === 1 ? (
- <Field
- id="recovery_key"
- name="recovery_key"
- label="Recovery Key"
- autoFocus
- required
- helpText="We'll use the recovery key to download & decrypt your data."
- />
- ) : (
- <Field
- id="new_password"
- name="new_password"
- type="password"
- label="New Password"
- autoFocus
- required
- helpText="Enter new account password."
- />
- )}
-
- <Flex alignSelf="flex-end" mt={2}>
- {/* {step === 1 && (
- <Button
- type="submit"
- variant="secondary"
- py={"7px"}
- px={4}
- alignSelf="flex-end"
- mr={1}
- >
- I don't have it
- </Button>
- )} */}
- <Button type="submit" py={"7px"} px={4}>
- Next
- </Button>
- </Flex>
- </Flex>
- )}
- </Flex>
+ onRestart={() => {
+ setStep(0);
+ }}
+ />
+ </>
+ )}
</Flex>
</ThemeProvider>
);
}
export default AccountRecovery;
+
+function Step({ heading, children }) {
+ return (
+ <Flex
+ flexDirection="column"
+ justifyContent="center"
+ alignItems="center"
+ sx={{ width: ["90%", "50%", "20%"] }}
+ >
+ <Text variant="heading" fontSize={24} mb={25} textAlign="center">
+ {heading}
+ </Text>
+
+ {children}
+ </Flex>
+ );
+}
+
+function BackupDataStep({ performAction, onFinished }) {
+ return (
+ <Step heading="Backup your data">
+ <Text variant="title">Please download a backup of your data.</Text>
+ <Button
+ alignSelf="center"
+ mt={2}
+ display="flex"
+ sx={{ justifyContent: "center", alignItems: "center" }}
+ px={20}
+ onClick={async () => {
+ await performAction({
+ message: "Creating a backup...",
+ error: "Could not create a backup.",
+ onError: onFinished,
+ action: async function downloadBackup() {
+ await createBackup();
+ onFinished();
+ },
+ });
+ }}
+ >
+ <Icon.ArrowDown sx={{ mr: 1 }} color="static" size={16} /> Download
+ backup
+ </Button>
+ </Step>
+ );
+}
+
+function RecoveryKeyStep({ performAction, onFinished }) {
+ return (
+ <Step
+ heading="Recover your account"
+ action={{ type: "submit", text: "Next" }}
+ >
+ <Flex
+ flexDirection="column"
+ as="form"
+ width="100%"
+ onSubmit={async (e) => {
+ e.preventDefault();
+ var formData = new FormData(e.target);
+
+ var recoveryKey = formData.get("recovery_key");
+ if (recoveryKey) {
+ await performAction({
+ message: "Downloading your data. This might take a bit.",
+ error: "Invalid recovery key.",
+ action: async function recoverData() {
+ const user = await db.user.getUser();
+ await db.context.write(`_uk_@${user.email}@_k`, recoveryKey);
+ await db.sync(true);
+ onFinished();
+ },
+ });
+ }
+ }}
+ >
+ <Field
+ id="recovery_key"
+ name="recovery_key"
+ label="Enter your recovery key"
+ autoFocus
+ required
+ helpText="We'll use the recovery key to download & decrypt your data."
+ />
+
+ <Button
+ display="flex"
+ sx={{ justifyContent: "center", alignItems: "center" }}
+ alignSelf="flex-end"
+ px={20}
+ mt={2}
+ type={"submit"}
+ >
+ Next <Icon.ArrowRight sx={{ ml: 1 }} color="static" size={16} />
+ </Button>
+ </Flex>
+ </Step>
+ );
+}
+
+function NewPasswordStep({ performAction, onFinished, onRestart }) {
+ const [error, setError] = useState(true);
+
+ return (
+ <Step heading="New password" action={{ type: "submit", text: "Next" }}>
+ <Flex
+ flexDirection="column"
+ as="form"
+ width="100%"
+ onSubmit={async (e) => {
+ e.preventDefault();
+ var formData = new FormData(e.target);
+
+ var newPassword = formData.get("new_password");
+ if (error) {
+ showToast(
+ "error",
+ "Your password does not meet all requirements. Please try a different password."
+ );
+ return;
+ }
+ await performAction({
+ message: "Resetting account password. Please wait...",
+ error: "Invalid password.",
+ onError: () => {},
+ action: async function setNewPassword() {
+ if (await db.user.resetPassword(newPassword)) {
+ // verify
+ await performAction({
+ message: "Verifying...",
+ error: "Verification failed. Please try again.",
+ onError: () => {},
+ action: async function verifyPassword() {
+ await db.context.write("lastSynced", 0);
+ await db.sync();
+ },
+ });
+
+ // tell user to recovery the new key
+ await showRecoveryKeyDialog();
+
+ await db.user.logout(true);
+ onFinished();
+ }
+ },
+ });
+ }}
+ >
+ <Field
+ id="new_password"
+ name="new_password"
+ type="password"
+ label="New Password"
+ autoComplete="new-password"
+ validatePassword
+ onError={setError}
+ autoFocus
+ required
+ helpText="Enter new account password."
+ />
+ <Button
+ display="flex"
+ sx={{ justifyContent: "center", alignItems: "center" }}
+ alignSelf="flex-end"
+ px={20}
+ mt={2}
+ type={"submit"}
+ >
+ Next <Icon.ArrowRight sx={{ ml: 1 }} color="static" size={16} />
+ </Button>
+ </Flex>
+ </Step>
+ );
+}
+
+function FinalStep() {
+ return (
+ <Step heading="Account recovered!">
+ <Button
+ variant="secondary"
+ onClick={() => (window.location.href = "/#/login")}
+ >
+ Login using new password
+ </Button>
+ </Step>
+ );
+}
diff --git a/apps/web/yarn.lock b/apps/web/yarn.lock
index 365b63861..e9105a354 100644
--- a/apps/web/yarn.lock
+++ b/apps/web/yarn.lock
@@ -8383,9 +8383,21 @@ normalize-url@^3.0.0:
resolved "https://registry.yarnpkg.com/normalize-url/-/normalize-url-3.3.0.tgz#b2e1c4dc4f7c6d57743df733a4f5978d18650559"
integrity sha512-U+JJi7duF1o+u2pynbp2zXDW2/PADgC30f0GsHZtRh+HOcXHnw137TrNlyxxRvWW5fjKd3bcLHPxofWuCjaeZg==
+notes-core@../notes-core:
+ version "6.6.3"
+ dependencies:
+ fast-sort "^2.0.1"
+ fuzzysort "^1.1.4"
+ lean-he "^2.1.2"
+ no-internet "^1.5.2"
+ qclone "^1.0.4"
+ quill-delta-to-html "^0.12.0"
+ spark-md5 "^3.0.1"
+ turndown "^7.0.0"
+
"notes-core@git+ssh://[email protected]:streetwriters/notesnook-core.git":
version "6.6.3"
- resolved "git+ssh://[email protected]:streetwriters/notesnook-core.git#b3d6c4cc47b7a80cefb3597620bd782ad014a842"
+ resolved "git+ssh://[email protected]:streetwriters/notesnook-core.git#7e096c8214dd4e2c162a20515c4d256c8c5fd52c"
dependencies:
fast-sort "^2.0.1"
fuzzysort "^1.1.4"