Skip to content

⚡️⚡️⚡️ Self-hosted collaborative bookmark manager to collect, read, annotate, and fully preserve what matters, all in one place.

feat(auth): log in via verification email with app deep link + web fallback

daniel31x13dc78c04ede10
diff --git a/.env.sample b/.env.sample
index a4b5181d..1f2da34b 100644
--- a/.env.sample
+++ b/.env.sample
@@ -47,6 +47,7 @@ MEILI_TIMEOUT=
ALLOW_PRIVATE_NETWORK_ACCESS=
ALLOW_INSECURE_TLS=
NEXT_PUBLIC_USER_CONTENT_DOMAIN=
+NEXT_PUBLIC_MOBILE_APP_REDIRECT_ENABLED=
# AI Settings
NEXT_PUBLIC_OLLAMA_ENDPOINT_URL=
diff --git a/apps/mobile/app/_layout.tsx b/apps/mobile/app/_layout.tsx
index 0dde5d4e..fc087a9b 100644
--- a/apps/mobile/app/_layout.tsx
+++ b/apps/mobile/app/_layout.tsx
@@ -150,6 +150,7 @@ const RootComponent = ({ isLoading }: { isLoading: boolean }) => {
<Stack.Screen name="index" />
<Stack.Screen name="subscribe" />
<Stack.Screen name="incoming" />
+ <Stack.Screen name="verify-email" />
<Stack.Screen name="+not-found" />
</Stack>
)}
diff --git a/apps/mobile/app/verify-email.tsx b/apps/mobile/app/verify-email.tsx
new file mode 100644
index 00000000..47c3fb12
--- /dev/null
+++ b/apps/mobile/app/verify-email.tsx
@@ -0,0 +1,82 @@
+import { useEffect, useRef } from "react";
+import { ActivityIndicator, Alert, Text, View } from "react-native";
+import { router, useLocalSearchParams } from "expo-router";
+import useAuthStore from "@/store/auth";
+
+const cloudInstance = "https://cloud.linkwarden.app";
+
+const cleanInstance = (instance: string) => instance.trim().replace(/\/+$/, "");
+
+export default function VerifyEmail() {
+ const { auth, signIn } = useAuthStore();
+ const params = useLocalSearchParams<{
+ token?: string;
+ email?: string;
+ instance?: string;
+ }>();
+ const started = useRef(false);
+
+ useEffect(() => {
+ if (auth.status === "loading" || started.current) return;
+ started.current = true;
+
+ if (auth.status === "authenticated") {
+ router.replace("/(tabs)/dashboard");
+ return;
+ }
+
+ const token = typeof params.token === "string" ? params.token : "";
+ const email = typeof params.email === "string" ? params.email : "";
+ const instance = cleanInstance(
+ typeof params.instance === "string" &&
+ /^https?:\/\//.test(params.instance)
+ ? params.instance
+ : cloudInstance
+ );
+
+ const verify = async () => {
+ if (!token || !email) {
+ router.replace("/");
+ return;
+ }
+
+ try {
+ const res = await fetch(`${instance}/api/v1/auth/verify-email-token`, {
+ method: "POST",
+ body: JSON.stringify({ token, email }),
+ headers: { "Content-Type": "application/json" },
+ });
+ const data = await res.json().catch(() => null);
+
+ if (!res.ok) {
+ Alert.alert(
+ "Error",
+ data?.response || "Could not verify email. Please log in."
+ );
+ router.replace("/");
+ return;
+ }
+
+ const success = await signIn("", "", instance, data.response.token);
+ if (!success) router.replace("/");
+ } catch {
+ Alert.alert(
+ "Network error",
+ "Could not connect to the server. Please check your network configuration and try again."
+ );
+ router.replace("/");
+ }
+ };
+
+ verify();
+ }, [auth.status]);
+
+ return (
+ <View className="bg-base-100 flex-1 items-center justify-center gap-3">
+ <ActivityIndicator size="large" />
+ <Text className="text-base-content text-base">
+ Verifying your email...
+ </Text>
+ </View>
+ );
+}
diff --git a/apps/mobile/components/ActionSheets/LoginSheet.tsx b/apps/mobile/components/ActionSheets/LoginSheet.tsx
index 989d8b7d..7fc4311a 100644
--- a/apps/mobile/components/ActionSheets/LoginSheet.tsx
+++ b/apps/mobile/components/ActionSheets/LoginSheet.tsx
@@ -66,6 +66,10 @@ export default function LoginSheet() {
SheetManager.hide("login-sheet");
};
+ useEffect(() => {
+ if (auth.status === "authenticated") closeSheet();
+ }, [auth.status]);
+
const handleLogin = async () => {
if (!instance || (!form.token && (!form.user || !form.password))) return;
diff --git a/apps/mobile/components/ActionSheets/SignUpSheet.tsx b/apps/mobile/components/ActionSheets/SignUpSheet.tsx
index 812e2edc..9a571336 100644
--- a/apps/mobile/components/ActionSheets/SignUpSheet.tsx
+++ b/apps/mobile/components/ActionSheets/SignUpSheet.tsx
@@ -80,6 +80,10 @@ export default function SignUpSheet() {
await SheetManager.hide("sign-up-sheet");
};
+ useEffect(() => {
+ if (auth.status === "authenticated") closeSheet();
+ }, [auth.status]);
+
const register = async () => {
const email = form.email.toLowerCase().trim();
const username = form.username.toLowerCase().trim();
diff --git a/apps/mobile/components/ActionSheets/VerifyEmailSheet.tsx b/apps/mobile/components/ActionSheets/VerifyEmailSheet.tsx
index a409f2eb..88cd538b 100644
--- a/apps/mobile/components/ActionSheets/VerifyEmailSheet.tsx
+++ b/apps/mobile/components/ActionSheets/VerifyEmailSheet.tsx
@@ -1,4 +1,4 @@
-import { useState } from "react";
+import { useEffect, useState } from "react";
import { Dimensions, ScrollView, Text } from "react-native";
import ActionSheet, {
SheetManager,
@@ -14,7 +14,7 @@ import SheetHeader from "./SheetHeader";
export default function VerifyEmailSheet({
payload,
}: SheetProps<"verify-email-sheet">) {
- const { requestVerificationEmail } = useAuthStore();
+ const { auth, requestVerificationEmail } = useAuthStore();
const { colorScheme } = useColorScheme();
const insets = useSafeAreaInsets();
const theme = rawTheme[colorScheme as ThemeName];
@@ -27,6 +27,10 @@ export default function VerifyEmailSheet({
SheetManager.hide("verify-email-sheet");
};
+ useEffect(() => {
+ if (auth.status === "authenticated") closeSheet();
+ }, [auth.status]);
+
return (
<ActionSheet
gestureEnabled
@@ -56,9 +60,9 @@ export default function VerifyEmailSheet({
<Text className="text-base-content text-xl" numberOfLines={1}>
{email}
</Text>
- <Text className="text-base-content text-center text-base px-2">
- Please verify your email address to continue. Check your inbox for the
- verification link, then come back and log in.
+ <Text className="text-base-content text-base">
+ Please verify your email address to continue. Open the link we sent to
+ your inbox to verify and log in automatically.
</Text>
<Button
variant="accent"
diff --git a/apps/web/components/CenteredForm.tsx b/apps/web/components/CenteredForm.tsx
index 1e4df932..66237fa6 100644
--- a/apps/web/components/CenteredForm.tsx
+++ b/apps/web/components/CenteredForm.tsx
@@ -32,6 +32,7 @@ export default function CenteredForm({
height={150}
alt="Linkwarden"
className="h-16 w-auto mx-auto"
+ priority
/>
{header && (
<p className="text-2xl text-black dark:text-white text-center font-semibold">
diff --git a/apps/web/lib/api/sendVerificationRequest.ts b/apps/web/lib/api/sendVerificationRequest.ts
index cbe350e4..40b52921 100644
--- a/apps/web/lib/api/sendVerificationRequest.ts
+++ b/apps/web/lib/api/sendVerificationRequest.ts
@@ -26,6 +26,9 @@ export default async function sendVerificationRequest({
const emailTemplate = Handlebars.compile(templateFile);
const { host } = new URL(url);
+ const verifyUrl = `${
+ process.env.BASE_URL
+ }/auth/verify?token=${token}&email=${encodeURIComponent(identifier)}`;
const result = await transporter.sendMail({
to: identifier,
from: {
@@ -33,11 +36,9 @@ export default async function sendVerificationRequest({
address: from as string,
},
subject: `Please verify your email address`,
- text: text({ url, host }),
+ text: text({ url: verifyUrl, host }),
html: emailTemplate({
- url: `${
- process.env.NEXTAUTH_URL
- }/callback/email?token=${token}&email=${encodeURIComponent(identifier)}`,
+ url: verifyUrl,
}),
});
const failed = result.rejected.concat(result.pending).filter(Boolean);
diff --git a/apps/web/pages/api/v1/auth/verify-email-token.ts b/apps/web/pages/api/v1/auth/verify-email-token.ts
new file mode 100644
index 00000000..47e17994
--- /dev/null
+++ b/apps/web/pages/api/v1/auth/verify-email-token.ts
@@ -0,0 +1,62 @@
+import type { NextApiRequest, NextApiResponse } from "next";
+import { createHash } from "crypto";
+import { prisma } from "@linkwarden/prisma";
+import createSession from "@/lib/api/controllers/session/createSession";
+
+const emailEnabled =
+ process.env.EMAIL_FROM && process.env.EMAIL_SERVER ? true : false;
+
+export default async function verifyEmailToken(
+ req: NextApiRequest,
+ res: NextApiResponse
+) {
+ if (req.method !== "POST")
+ return res.status(405).json({ response: "Method not allowed." });
+
+ if (!emailEnabled || !process.env.NEXTAUTH_SECRET)
+ return res.status(400).json({ response: "Email is not configured." });
+
+ const token = typeof req.body.token === "string" ? req.body.token : "";
+ const email =
+ typeof req.body.email === "string"
+ ? req.body.email.toLowerCase().trim()
+ : "";
+
+ if (!token || !email)
+ return res.status(400).json({ response: "Invalid request." });
+
+ const verificationToken = await prisma.verificationToken.findFirst({
+ where: {
+ identifier: email,
+ token: createHash("sha256")
+ .update(`${token}${process.env.NEXTAUTH_SECRET}`)
+ .digest("hex"),
+ expires: { gt: new Date() },
+ },
+ });
+
+ if (!verificationToken)
+ return res.status(400).json({
+ response: "Verification link is invalid or has expired.",
+ });
+
+ const user = await prisma.user.findUnique({ where: { email } });
+
+ if (!user) return res.status(400).json({ response: "Invalid email." });
+
+ await Promise.all([
+ user.emailVerified
+ ? Promise.resolve()
+ : prisma.user.update({
+ where: { id: user.id },
+ data: { emailVerified: new Date() },
+ }),
+ prisma.verificationToken.deleteMany({ where: { identifier: email } }),
+ ]);
+
+ const session = await createSession(
+ user.id,
+ typeof req.body.sessionName === "string" ? req.body.sessionName : undefined
+ );
+ return res.status(session.status).json({ response: session.response });
+}
diff --git a/apps/web/pages/api/v1/config/index.ts b/apps/web/pages/api/v1/config/index.ts
index e854c56c..bcc7e32b 100644
--- a/apps/web/pages/api/v1/config/index.ts
+++ b/apps/web/pages/api/v1/config/index.ts
@@ -33,5 +33,7 @@ export const getEnvData = () => {
TRIAL_PERIOD_DAYS:
Number(process.env.NEXT_PUBLIC_TRIAL_PERIOD_DAYS) || null,
REQUIRE_CC: process.env.NEXT_PUBLIC_REQUIRE_CC === "true" || null,
+ MOBILE_APP_REDIRECT_ENABLED:
+ process.env.NEXT_PUBLIC_MOBILE_APP_REDIRECT_ENABLED === "true" || null,
};
};
diff --git a/apps/web/pages/auth/verify.tsx b/apps/web/pages/auth/verify.tsx
new file mode 100644
index 00000000..754f3e74
--- /dev/null
+++ b/apps/web/pages/auth/verify.tsx
@@ -0,0 +1,72 @@
+import { useRouter } from "next/router";
+import { useEffect, useState } from "react";
+import { useTranslation } from "next-i18next";
+import CenteredForm from "@/components/CenteredForm";
+import { Button } from "@/components/ui/button";
+import getServerSideProps from "@/lib/client/getServerSideProps";
+
+const MOBILE_APP_REDIRECT_ENABLED =
+ process.env.NEXT_PUBLIC_MOBILE_APP_REDIRECT_ENABLED === "true";
+
+export default function Verify() {
+ const router = useRouter();
+ const { t } = useTranslation();
+ const [isMobile, setIsMobile] = useState(false);
+
+ const token =
+ typeof router.query.token === "string" ? router.query.token : "";
+ const email =
+ typeof router.query.email === "string" ? router.query.email : "";
+
+ const webUrl = `/api/v1/auth/callback/email?token=${encodeURIComponent(
+ token
+ )}&email=${encodeURIComponent(email)}`;
+
+ const appUrl = () =>
+ `linkwarden://verify-email?token=${encodeURIComponent(
+ token
+ )}&email=${encodeURIComponent(email)}&instance=${encodeURIComponent(
+ window.location.origin
+ )}`;
+
+ useEffect(() => {
+ if (!router.isReady) return;
+
+ if (!token || !email) {
+ router.push("/login");
+ return;
+ }
+
+ const mobile = /Android|iPhone|iPad|iPod/i.test(navigator.userAgent);
+ setIsMobile(mobile);
+
+ if (mobile && MOBILE_APP_REDIRECT_ENABLED) {
+ window.location.href = appUrl();
+ } else {
+ window.location.replace(webUrl);
+ }
+ }, [router.isReady]);
+
+ if (isMobile && MOBILE_APP_REDIRECT_ENABLED)
+ return (
+ <CenteredForm header={t("verify_your_email")}>
+ <div className="max-w-[30rem] min-w-80 w-full mx-auto flex flex-col gap-3">
+ <Button
+ variant="accent"
+ onClick={() => (window.location.href = appUrl())}
+ >
+ {t("open_in_the_app")}
+ </Button>
+ <Button
+ variant="ghost"
+ onClick={() => (window.location.href = webUrl)}
+ >
+ {t("continue_in_browser")}
+ </Button>
+ </div>
+ </CenteredForm>
+ );
+ else <></>;
+}
+
+export { getServerSideProps };
diff --git a/apps/web/public/locales/en/common.json b/apps/web/public/locales/en/common.json
index 02726873..3c3f9318 100644
--- a/apps/web/public/locales/en/common.json
+++ b/apps/web/public/locales/en/common.json
@@ -206,6 +206,10 @@
"leave_collection": "Leave Collection",
"email_verified_signing_out": "Email verified. Signing out...",
"invalid_token": "Invalid token.",
+ "verify_your_email": "Verify your Email",
+ "open_in_the_app": "Open in the App",
+ "continue_in_browser": "Continue in Browser",
+ "redirecting": "Redirecting...",
"sending_password_recovery_link": "Sending password recovery link...",
"please_fill_all_fields": "Please fill out all the fields.",
"password_updated": "Password Updated!",
diff --git a/apps/worker/lib/preservationScheme/handleArchivePreview.ts b/apps/worker/lib/preservationScheme/handleArchivePreview.ts
index 126fd041..878da99f 100644
--- a/apps/worker/lib/preservationScheme/handleArchivePreview.ts
+++ b/apps/worker/lib/preservationScheme/handleArchivePreview.ts
@@ -3,10 +3,8 @@ import { Page } from "playwright";
import { generatePreview } from "@linkwarden/lib/generatePreview";
import { createFile } from "@linkwarden/filesystem";
import { prisma } from "@linkwarden/prisma";
-import {
- assertUrlIsSafeForServerSideFetch,
- UnsafeUrlError,
-} from "@linkwarden/lib/ssrf";
+import { safeFetch } from "@linkwarden/lib/safeFetch";
+import { UnsafeUrlError } from "@linkwarden/lib/ssrf";
type LinksAndCollectionAndOwner = Link & {
collection: Collection & {
@@ -25,7 +23,7 @@ const handleArchivePreview = async (
let previewGenerated = false;
- if (ogImageUrl) {
+ if (ogImageUrl && !link.preview?.startsWith("archive")) {
if (
!ogImageUrl.startsWith("http://") &&
!ogImageUrl.startsWith("https://")
@@ -36,19 +34,16 @@ const handleArchivePreview = async (
}
try {
- await assertUrlIsSafeForServerSideFetch(ogImageUrl);
- const imageResponse = await page.goto(ogImageUrl);
+ const imageResponse = await safeFetch(ogImageUrl);
- if (imageResponse && !link.preview?.startsWith("archive")) {
- const buffer = await imageResponse.body();
+ if (imageResponse.ok) {
+ const buffer = await imageResponse.buffer();
previewGenerated = await generatePreview(
buffer,
link.collectionId,
link.id
);
}
-
- await page.goBack();
} catch (error) {
if (!(error instanceof UnsafeUrlError)) {
throw error;