Skip to content

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

feat: add the functionality to display monolith from a separate domain, sandboxed

daniel31x13df4cc97f8e86
diff --git a/.env.sample b/.env.sample
index fc71395a..50a71a4b 100644
--- a/.env.sample
+++ b/.env.sample
@@ -43,6 +43,7 @@ INDEX_TAKE_COUNT=
MEILI_TIMEOUT=
ALLOW_PRIVATE_NETWORK_ACCESS=
ALLOW_INSECURE_TLS=
+NEXT_PUBLIC_USER_CONTENT_DOMAIN=
# AI Settings
NEXT_PUBLIC_OLLAMA_ENDPOINT_URL=
diff --git a/apps/mobile/app/links/[id].tsx b/apps/mobile/app/links/[id].tsx
index a9c2d750..962c046c 100644
--- a/apps/mobile/app/links/[id].tsx
+++ b/apps/mobile/app/links/[id].tsx
@@ -57,28 +57,19 @@ export default function LinkScreen() {
style={{ paddingBottom: Platform.OS === "android" ? insets.bottom : 0 }}
>
{link?.id && Number(format) === ArchivedFormat.readability ? (
- <ReadableFormat
- link={link as any}
- setIsLoading={(state) => setIsLoading(state)}
- />
+ <ReadableFormat link={link as any} setIsLoading={setIsLoading} />
) : link?.id &&
(Number(format) === ArchivedFormat.jpeg ||
Number(format) === ArchivedFormat.png) ? (
<ImageFormat
link={link as any}
- setIsLoading={(state) => setIsLoading(state)}
+ setIsLoading={setIsLoading}
format={Number(format)}
/>
) : link?.id && Number(format) === ArchivedFormat.pdf ? (
- <PdfFormat
- link={link as any}
- setIsLoading={(state) => setIsLoading(state)}
- />
+ <PdfFormat link={link as any} setIsLoading={setIsLoading} />
) : link?.id && Number(format) === ArchivedFormat.monolith ? (
- <WebpageFormat
- link={link as any}
- setIsLoading={(state) => setIsLoading(state)}
- />
+ <WebpageFormat link={link as any} setIsLoading={setIsLoading} />
) : url ? (
<WebView
className={isLoading ? "opacity-0" : "flex-1"}
diff --git a/apps/mobile/components/Formats/WebpageFormat.tsx b/apps/mobile/components/Formats/WebpageFormat.tsx
index ce758136..7d8ecf9c 100644
--- a/apps/mobile/components/Formats/WebpageFormat.tsx
+++ b/apps/mobile/components/Formats/WebpageFormat.tsx
@@ -1,6 +1,8 @@
import React, { useEffect, useState } from "react";
import * as FileSystem from "expo-file-system/legacy";
import NetInfo from "@react-native-community/netinfo";
+import getPreservedFormatUrl from "@linkwarden/lib/getPreservedFormatUrl";
+import { useConfig } from "@linkwarden/router/config";
import useAuthStore from "@/store/auth";
import { ArchivedFormat } from "@linkwarden/types/global";
import { Link as LinkType } from "@linkwarden/prisma/client";
@@ -15,6 +17,7 @@ export default function WebpageFormat({ link, setIsLoading }: Props) {
const FORMAT = ArchivedFormat.monolith;
const { auth } = useAuthStore();
+ const { data: config, isLoading: isConfigLoading } = useConfig(auth);
const [content, setContent] = useState<string>("");
useEffect(() => {
@@ -36,14 +39,30 @@ export default function WebpageFormat({ link, setIsLoading }: Props) {
setContent(filePath);
}
- const net = await NetInfo.fetch();
+ if (isConfigLoading) {
+ return;
+ }
+ const net = await NetInfo.fetch();
if (net.isConnected) {
- const apiUrl = `${auth.instance}/api/v1/archives/${link.id}?format=${FORMAT}`;
-
try {
+ const apiUrl = config?.USER_CONTENT_DOMAIN
+ ? await getPreservedFormatUrl({
+ tokenEndpoint: `${auth.instance}/api/v1/preserved/token`,
+ linkId: link.id,
+ format: FORMAT,
+ headers: {
+ Authorization: `Bearer ${auth.session}`,
+ },
+ })
+ : `${auth.instance}/api/v1/archives/${link.id}?format=${FORMAT}`;
+
const result = await FileSystem.downloadAsync(apiUrl, filePath, {
- headers: { Authorization: `Bearer ${auth.session}` },
+ ...(config?.USER_CONTENT_DOMAIN
+ ? {}
+ : {
+ headers: { Authorization: `Bearer ${auth.session}` },
+ }),
});
setContent(result.uri);
@@ -54,7 +73,7 @@ export default function WebpageFormat({ link, setIsLoading }: Props) {
}
loadCacheOrFetch();
- }, [link]);
+ }, [link, auth.instance, auth.session, config?.USER_CONTENT_DOMAIN, isConfigLoading]);
return (
content && (
diff --git a/apps/web/components/Preservation/PreservationContent.tsx b/apps/web/components/Preservation/PreservationContent.tsx
index 7b0601a4..7d1cee6c 100644
--- a/apps/web/components/Preservation/PreservationContent.tsx
+++ b/apps/web/components/Preservation/PreservationContent.tsx
@@ -3,6 +3,8 @@ import clsx from "clsx";
import { useRouter } from "next/router";
import { useTranslation } from "next-i18next";
import { BeatLoader } from "react-spinners";
+import getPreservedFormatUrl from "@linkwarden/lib/getPreservedFormatUrl";
+import { useConfig } from "@linkwarden/router/config";
import ReadableView from "@/components/Preservation/ReadableView";
import { PreservationSkeleton } from "../Skeletons";
import {
@@ -20,10 +22,17 @@ type Props = {
export const PreservationContent: React.FC<Props> = ({ link, format }) => {
const router = useRouter();
const { t } = useTranslation();
+ const {
+ data: config,
+ isLoading: isConfigLoading,
+ error: configError,
+ } = useConfig();
const [pdfLoaded, setPdfLoaded] = useState(false);
const [monolithLoaded, setMonolithLoaded] = useState(false);
const [imageLoaded, setImageLoaded] = useState(false);
+ const [monolithUrl, setMonolithUrl] = useState<string | null>(null);
+ const [monolithError, setMonolithError] = useState<string | null>(null);
const prevFormatRef = useRef<ArchivedFormat | undefined>(undefined);
const [currentFormat, setCurrentFormat] = useState<ArchivedFormat>(
@@ -73,6 +82,80 @@ export const PreservationContent: React.FC<Props> = ({ link, format }) => {
}
}, [currentFormat, link?.id, link?.updatedAt]);
+ useEffect(() => {
+ let isCancelled = false;
+
+ if (!link?.id || currentFormat !== ArchivedFormat.monolith) {
+ setMonolithUrl(null);
+ setMonolithError(null);
+ return () => {
+ isCancelled = true;
+ };
+ }
+
+ if (configError) {
+ setMonolithUrl(null);
+ setMonolithError("Failed to load archived format.");
+ return () => {
+ isCancelled = true;
+ };
+ }
+
+ if (isConfigLoading) {
+ return () => {
+ isCancelled = true;
+ };
+ }
+
+ if (!config?.USER_CONTENT_DOMAIN) {
+ setMonolithError(null);
+ setMonolithUrl(
+ `/api/v1/archives/${link.id}?format=${ArchivedFormat.monolith}&_=${link.updatedAt}`
+ );
+ return () => {
+ isCancelled = true;
+ };
+ }
+
+ setMonolithLoaded(false);
+ setMonolithUrl(null);
+ setMonolithError(null);
+
+ getPreservedFormatUrl({
+ tokenEndpoint: "/api/v1/preserved/token",
+ linkId: link.id,
+ format: ArchivedFormat.monolith,
+ requestInit: {
+ cache: "no-store",
+ },
+ })
+ .then((url) => {
+ if (!isCancelled) {
+ setMonolithUrl(url);
+ }
+ })
+ .catch((error) => {
+ if (!isCancelled) {
+ setMonolithError(
+ error instanceof Error
+ ? error.message
+ : "Failed to load archived format."
+ );
+ }
+ });
+
+ return () => {
+ isCancelled = true;
+ };
+ }, [
+ config?.USER_CONTENT_DOMAIN,
+ configError,
+ currentFormat,
+ isConfigLoading,
+ link?.id,
+ link?.updatedAt,
+ ]);
+
if (!link?.id) return null;
const renderFormat = () => {
@@ -87,17 +170,28 @@ export const PreservationContent: React.FC<Props> = ({ link, format }) => {
case ArchivedFormat.monolith:
return (
<>
- {!monolithLoaded && (
+ {!monolithLoaded && !monolithError && (
<PreservationSkeleton className="max-w-screen-lg h-[calc(100vh-3.1rem)]" />
)}
- <iframe
- src={`/api/v1/archives/${link.id}?format=${ArchivedFormat.monolith}&_=${link.updatedAt}`}
- className={clsx(
- "w-full border-none h-[calc(100vh-3.1rem)]",
- monolithLoaded ? "block" : "hidden"
- )}
- onLoad={() => setMonolithLoaded(true)}
- />
+ {monolithError ? (
+ <div className="w-full h-[calc(100vh-3.1rem)] flex flex-col justify-center p-10">
+ <p className="text-center text-2xl font-bold">Error</p>
+ <p className="text-center text-lg">{monolithError}</p>
+ </div>
+ ) : (
+ monolithUrl && (
+ <iframe
+ src={monolithUrl}
+ sandbox=""
+ referrerPolicy="no-referrer"
+ className={clsx(
+ "w-full border-none h-[calc(100vh-3.1rem)]",
+ monolithLoaded ? "block" : "hidden"
+ )}
+ onLoad={() => setMonolithLoaded(true)}
+ />
+ )
+ )}
</>
);
diff --git a/apps/web/components/Preservation/PreservationNavbar.tsx b/apps/web/components/Preservation/PreservationNavbar.tsx
index 51243423..c81f4cf8 100644
--- a/apps/web/components/Preservation/PreservationNavbar.tsx
+++ b/apps/web/components/Preservation/PreservationNavbar.tsx
@@ -14,6 +14,8 @@ import { Button } from "@/components/ui/button";
import { useTranslation } from "next-i18next";
import Link from "next/link";
import { useRouter } from "next/router";
+import { useConfig } from "@linkwarden/router/config";
+import getPreservedFormatUrl from "@linkwarden/lib/getPreservedFormatUrl";
import {
atLeastOneFormatAvailable,
formatAvailable,
@@ -33,6 +35,7 @@ type Props = {
const PreservationNavbar = ({ link, format, className }: Props) => {
const { data: collections = [] } = useCollections();
+ const { data: config, isLoading: isConfigLoading } = useConfig();
const [collection, setCollection] =
useState<CollectionIncludingMembersAndLinkCount>(
@@ -54,28 +57,52 @@ const PreservationNavbar = ({ link, format, className }: Props) => {
const { t } = useTranslation();
const router = useRouter();
+ const isMonolithConfigPending =
+ format === ArchivedFormat.monolith && isConfigLoading && !config;
- const handleDownload = () => {
- const path = `/api/v1/archives/${link?.id}?format=${format}`;
- fetch(path)
- .then((response) => {
- if (response.ok) {
- const anchorElement = document.createElement("a");
- anchorElement.href = path;
- anchorElement.download =
- format === ArchivedFormat.monolith
- ? "Webpage"
- : format === ArchivedFormat.pdf
- ? "PDF"
- : "Screenshot";
- anchorElement.click();
- } else {
- console.error("Failed to download file");
+ const handleDownload = async () => {
+ if (
+ typeof link.id !== "number" ||
+ format === undefined ||
+ isMonolithConfigPending
+ ) {
+ return;
+ }
+
+ try {
+ const isCrossOriginMonolith =
+ format === ArchivedFormat.monolith && config?.USER_CONTENT_DOMAIN;
+ const path = isCrossOriginMonolith
+ ? await getPreservedFormatUrl({
+ tokenEndpoint: "/api/v1/preserved/token",
+ linkId: link.id,
+ format,
+ download: true,
+ requestInit: {
+ cache: "no-store",
+ },
+ })
+ : `/api/v1/archives/${link?.id}?format=${format}`;
+
+ if (!isCrossOriginMonolith) {
+ const response = await fetch(path);
+ if (!response.ok) {
+ throw new Error("Failed to download file");
}
- })
- .catch((error) => {
- console.error("Error:", error);
- });
+ }
+
+ const anchorElement = document.createElement("a");
+ anchorElement.href = path;
+ anchorElement.download =
+ format === ArchivedFormat.monolith
+ ? "Webpage"
+ : format === ArchivedFormat.pdf
+ ? "PDF"
+ : "Screenshot";
+ anchorElement.click();
+ } catch (error) {
+ console.error("Error:", error);
+ }
};
return (
@@ -95,7 +122,12 @@ const PreservationNavbar = ({ link, format, className }: Props) => {
{format === ArchivedFormat.readability ? (
<TextStyleDropdown />
) : (
- <Button variant="ghost" size="icon" onClick={handleDownload}>
+ <Button
+ variant="ghost"
+ size="icon"
+ onClick={handleDownload}
+ disabled={isMonolithConfigPending}
+ >
<i className="bi-cloud-arrow-down text-xl text-neutral" />
</Button>
)}
diff --git a/apps/web/components/PreserverdFormatRow.tsx b/apps/web/components/PreserverdFormatRow.tsx
index bf83509d..56525b17 100644
--- a/apps/web/components/PreserverdFormatRow.tsx
+++ b/apps/web/components/PreserverdFormatRow.tsx
@@ -2,6 +2,8 @@ import {
ArchivedFormat,
LinkIncludingShortenedCollectionAndTags,
} from "@linkwarden/types/global";
+import getPreservedFormatUrl from "@linkwarden/lib/getPreservedFormatUrl";
+import { useConfig } from "@linkwarden/router/config";
import Link from "next/link";
import { useRouter } from "next/router";
import { Button } from "@/components/ui/button";
@@ -22,30 +24,51 @@ export default function PreservedFormatRow({
downloadable,
}: Props) {
const router = useRouter();
+ const { data: config, isLoading: isConfigLoading } = useConfig();
const isPublic = router.pathname.startsWith("/public") ? true : undefined;
+ const isMonolithConfigPending =
+ format === ArchivedFormat.monolith && isConfigLoading && !config;
- const handleDownload = () => {
- const path = `/api/v1/archives/${link?.id}?format=${format}`;
- fetch(path)
- .then((response) => {
- if (response.ok) {
- const anchorElement = document.createElement("a");
- anchorElement.href = path;
- anchorElement.download =
- format === ArchivedFormat.monolith
- ? "Webpage"
- : format === ArchivedFormat.pdf
- ? "PDF"
- : "Screenshot";
- anchorElement.click();
- } else {
- console.error("Failed to download file");
+ const handleDownload = async () => {
+ if (typeof link.id !== "number" || isMonolithConfigPending) {
+ return;
+ }
+
+ try {
+ const isCrossOriginMonolith =
+ format === ArchivedFormat.monolith && config?.USER_CONTENT_DOMAIN;
+ const path = isCrossOriginMonolith
+ ? await getPreservedFormatUrl({
+ tokenEndpoint: "/api/v1/preserved/token",
+ linkId: link.id,
+ format,
+ download: true,
+ requestInit: {
+ cache: "no-store",
+ },
+ })
+ : `/api/v1/archives/${link?.id}?format=${format}`;
+
+ if (!isCrossOriginMonolith) {
+ const response = await fetch(path);
+ if (!response.ok) {
+ throw new Error("Failed to download file");
}
- })
- .catch((error) => {
- console.error("Error:", error);
- });
+ }
+
+ const anchorElement = document.createElement("a");
+ anchorElement.href = path;
+ anchorElement.download =
+ format === ArchivedFormat.monolith
+ ? "Webpage"
+ : format === ArchivedFormat.pdf
+ ? "PDF"
+ : "Screenshot";
+ anchorElement.click();
+ } catch (error) {
+ console.error("Error:", error);
+ }
};
return (
@@ -57,7 +80,12 @@ export default function PreservedFormatRow({
<div className="flex gap-1">
{downloadable || false ? (
- <Button variant="ghost" size="icon" onClick={handleDownload}>
+ <Button
+ variant="ghost"
+ size="icon"
+ onClick={handleDownload}
+ disabled={isMonolithConfigPending}
+ >
<i className="bi-cloud-arrow-down text-xl text-neutral" />
</Button>
) : undefined}
diff --git a/apps/web/lib/api/archives/resolveAccessibleArchive.test.ts b/apps/web/lib/api/archives/resolveAccessibleArchive.test.ts
new file mode 100644
index 00000000..84107164
--- /dev/null
+++ b/apps/web/lib/api/archives/resolveAccessibleArchive.test.ts
@@ -0,0 +1,121 @@
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { ArchivedFormat } from "@linkwarden/types/global";
+import resolveAccessibleArchive from "./resolveAccessibleArchive";
+import { prisma } from "@linkwarden/prisma";
+
+vi.mock("@linkwarden/prisma", () => ({
+ prisma: {
+ collection: {
+ findFirst: vi.fn(),
+ },
+ },
+}));
+
+describe("resolveAccessibleArchive", () => {
+ afterEach(() => {
+ vi.clearAllMocks();
+ });
+
+ it("returns a resolved file path for an accessible owner archive", async () => {
+ vi.mocked(prisma.collection.findFirst).mockResolvedValue({
+ id: 12,
+ } as any);
+
+ const result = await resolveAccessibleArchive({
+ linkId: 55,
+ format: ArchivedFormat.monolith,
+ userId: 7,
+ });
+
+ expect(prisma.collection.findFirst).toHaveBeenCalledWith({
+ where: {
+ links: {
+ some: {
+ id: 55,
+ },
+ },
+ OR: [
+ { ownerId: 7 },
+ { members: { some: { userId: 7 } } },
+ { isPublic: true },
+ ],
+ },
+ });
+ expect(result).toEqual({
+ status: 200,
+ response: {
+ collectionId: 12,
+ filePath: "archives/12/55.html",
+ format: ArchivedFormat.monolith,
+ isPreview: false,
+ linkId: 55,
+ },
+ });
+ });
+
+ it("supports public access without a logged-in user", async () => {
+ vi.mocked(prisma.collection.findFirst).mockResolvedValue({
+ id: 9,
+ } as any);
+
+ const result = await resolveAccessibleArchive({
+ linkId: 3,
+ format: ArchivedFormat.pdf,
+ userId: undefined,
+ });
+
+ expect(prisma.collection.findFirst).toHaveBeenCalledWith({
+ where: {
+ links: {
+ some: {
+ id: 3,
+ },
+ },
+ OR: [
+ { ownerId: -1 },
+ { members: { some: { userId: -1 } } },
+ { isPublic: true },
+ ],
+ },
+ });
+ expect(result).toEqual({
+ status: 200,
+ response: {
+ collectionId: 9,
+ filePath: "archives/9/3.pdf",
+ format: ArchivedFormat.pdf,
+ isPreview: false,
+ linkId: 3,
+ },
+ });
+ });
+
+ it("returns an authorization error when the collection is inaccessible", async () => {
+ vi.mocked(prisma.collection.findFirst).mockResolvedValue(null);
+
+ const result = await resolveAccessibleArchive({
+ linkId: 11,
+ format: ArchivedFormat.jpeg,
+ userId: 7,
+ });
+
+ expect(result).toEqual({
+ status: 401,
+ response: "You don't have access to this collection.",
+ });
+ });
+
+ it("returns an invalid-parameters error for unsupported formats", async () => {
+ const result = await resolveAccessibleArchive({
+ linkId: 11,
+ format: 999,
+ userId: 7,
+ });
+
+ expect(result).toEqual({
+ status: 401,
+ response: "Invalid parameters.",
+ });
+ expect(prisma.collection.findFirst).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/web/lib/api/archives/resolveAccessibleArchive.ts b/apps/web/lib/api/archives/resolveAccessibleArchive.ts
new file mode 100644
index 00000000..81318b13
--- /dev/null
+++ b/apps/web/lib/api/archives/resolveAccessibleArchive.ts
@@ -0,0 +1,84 @@
+import { prisma } from "@linkwarden/prisma";
+import { ArchivedFormat } from "@linkwarden/types/global";
+import getSuffixFromFormat from "@/lib/shared/getSuffixFromFormat";
+
+type ResolveAccessibleArchiveParams = {
+ linkId: number;
+ format: number;
+ isPreview?: boolean;
+ userId?: number;
+};
+
+type ResolveAccessibleArchiveSuccess = {
+ filePath: string;
+ collectionId: number;
+ linkId: number;
+ format: ArchivedFormat;
+ isPreview: boolean;
+};
+
+type ResolveAccessibleArchiveResult =
+ | {
+ status: 200;
+ response: ResolveAccessibleArchiveSuccess;
+ }
+ | {
+ status: 401;
+ response: string;
+ };
+
+async function getAccessibleCollection(linkId: number, userId?: number) {
+ return prisma.collection.findFirst({
+ where: {
+ links: {
+ some: {
+ id: linkId,
+ },
+ },
+ OR: [
+ { ownerId: userId || -1 },
+ { members: { some: { userId: userId || -1 } } },
+ { isPublic: true },
+ ],
+ },
+ });
+}
+
+export default async function resolveAccessibleArchive({
+ linkId,
+ format,
+ isPreview = false,
+ userId,
+}: ResolveAccessibleArchiveParams): Promise<ResolveAccessibleArchiveResult> {
+ const suffix = getSuffixFromFormat(format);
+
+ if (!linkId || !suffix) {
+ return {
+ status: 401,
+ response: "Invalid parameters.",
+ };
+ }
+
+ const collection = await getAccessibleCollection(linkId, userId);
+ if (!collection) {
+ return {
+ status: 401,
+ response: "You don't have access to this collection.",
+ };
+ }
+
+ const filePath = isPreview
+ ? `archives/preview/${collection.id}/${linkId}.jpeg`
+ : `archives/${collection.id}/${linkId + suffix}`;
+
+ return {
+ status: 200,
+ response: {
+ filePath,
+ collectionId: collection.id,
+ linkId,
+ format: format as ArchivedFormat,
+ isPreview,
+ },
+ };
+}
diff --git a/apps/web/lib/api/preserved/createPreservedFormatUrl.test.ts b/apps/web/lib/api/preserved/createPreservedFormatUrl.test.ts
new file mode 100644
index 00000000..b92d6bc8
--- /dev/null
+++ b/apps/web/lib/api/preserved/createPreservedFormatUrl.test.ts
@@ -0,0 +1,55 @@
+import {
+ afterEach,
+ beforeEach,
+ describe,
+ expect,
+ it,
+ vi,
+} from "vitest";
+import { ArchivedFormat } from "@linkwarden/types/global";
+import createPreservedFormatUrl, {
+ decodePreservedFormatToken,
+} from "./createPreservedFormatUrl";
+
+describe("createPreservedFormatUrl", () => {
+ beforeEach(() => {
+ vi.stubEnv(
+ "NEXT_PUBLIC_USER_CONTENT_DOMAIN",
+ "https://content.example.com"
+ );
+ vi.stubEnv("NEXTAUTH_SECRET", "test-secret");
+ });
+
+ afterEach(() => {
+ vi.unstubAllEnvs();
+ });
+
+ it("creates a signed preserved-format URL", async () => {
+ const url = await createPreservedFormatUrl({
+ linkId: 42,
+ filePath: "archives/7/42.html",
+ format: ArchivedFormat.monolith,
+ });
+
+ const parsed = new URL(url);
+ expect(parsed.origin).toBe("https://content.example.com");
+ expect(parsed.pathname).toBe("/api/v1/preserved/view");
+
+ const token = parsed.searchParams.get("token");
+ expect(token).toBeTruthy();
+
+ const decoded = await decodePreservedFormatToken(token as string);
+ expect(decoded).toMatchObject({
+ scope: "preserved-format",
+ linkId: 42,
+ filePath: "archives/7/42.html",
+ format: ArchivedFormat.monolith,
+ });
+ expect((decoded?.exp ?? 0) - (decoded?.iat ?? 0)).toBe(300);
+ });
+
+ it("rejects invalid tokens", async () => {
+ const decoded = await decodePreservedFormatToken("not-a-token");
+ expect(decoded).toBeNull();
+ });
+});
diff --git a/apps/web/lib/api/preserved/createPreservedFormatUrl.ts b/apps/web/lib/api/preserved/createPreservedFormatUrl.ts
new file mode 100644
index 00000000..f28063b4
--- /dev/null
+++ b/apps/web/lib/api/preserved/createPreservedFormatUrl.ts
@@ -0,0 +1,97 @@
+import crypto from "crypto";
+import { decode, encode, JWT } from "next-auth/jwt";
+import getSuffixFromFormat from "@/lib/shared/getSuffixFromFormat";
+import { ArchivedFormat } from "@linkwarden/types/global";
+
+export const PRESERVED_FORMAT_SCOPE = "preserved-format";
+export const PRESERVED_FORMAT_TOKEN_TTL_SECONDS = 300;
+
+export type PreservedFormatToken = JWT & {
+ scope: typeof PRESERVED_FORMAT_SCOPE;
+ linkId: number;
+ filePath: string;
+ format: ArchivedFormat;
+ iat: number;
+ exp: number;
+};
+
+const getPreservedTokenSecret = () => {
+ if (!process.env.NEXTAUTH_SECRET) {
+ throw new Error("NEXTAUTH_SECRET is not configured.");
+ }
+
+ return process.env.NEXTAUTH_SECRET;
+};
+
+const isPreservedFormatToken = (
+ token: JWT | null
+): token is PreservedFormatToken => {
+ const suffix =
+ typeof token?.format === "number" ? getSuffixFromFormat(token.format) : null;
+
+ return (
+ !!token &&
+ token.scope === PRESERVED_FORMAT_SCOPE &&
+ typeof token.linkId === "number" &&
+ Number.isFinite(token.linkId) &&
+ typeof token.filePath === "string" &&
+ !!suffix &&
+ token.filePath.endsWith(suffix) &&
+ typeof token.format === "number" &&
+ typeof token.iat === "number" &&
+ typeof token.exp === "number"
+ );
+};
+
+export default async function createPreservedFormatUrl({
+ linkId,
+ filePath,
+ format,
+}: {
+ linkId: number;
+ filePath: string;
+ format: ArchivedFormat;
+}) {
+ const userContentDomain = process.env.NEXT_PUBLIC_USER_CONTENT_DOMAIN;
+ if (!userContentDomain) {
+ throw new Error("User content domain is not configured.");
+ }
+
+ const suffix = getSuffixFromFormat(format);
+ if (!suffix || !filePath.endsWith(suffix)) {
+ throw new Error("Invalid archived format.");
+ }
+
+ const now = Math.floor(Date.now() / 1000);
+ const token = await encode({
+ secret: getPreservedTokenSecret(),
+ maxAge: PRESERVED_FORMAT_TOKEN_TTL_SECONDS,
+ token: {
+ id: 0,
+ scope: PRESERVED_FORMAT_SCOPE,
+ linkId,
+ filePath,
+ format,
+ iat: now,
+ exp: now + PRESERVED_FORMAT_TOKEN_TTL_SECONDS,
+ jti: crypto.randomUUID(),
+ },
+ });
+
+ return `${userContentDomain}/api/v1/preserved/view?token=${encodeURIComponent(
+ token
+ )}`;
+}
+
+export async function decodePreservedFormatToken(token: string) {
+ const decoded = await decode({
+ token,
+ secret: getPreservedTokenSecret(),
+ }).catch(() => null);
+
+ if (!isPreservedFormatToken(decoded)) {
+ return null;
+ }
+
+ return decoded;
+}
diff --git a/apps/web/pages/api/v1/archives/[linkId].test.ts b/apps/web/pages/api/v1/archives/[linkId].test.ts
new file mode 100644
index 00000000..ee22110a
--- /dev/null
+++ b/apps/web/pages/api/v1/archives/[linkId].test.ts
@@ -0,0 +1,112 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import handler from "./[linkId]";
+import verifyToken from "@/lib/api/verifyToken";
+import resolveAccessibleArchive from "@/lib/api/archives/resolveAccessibleArchive";
+import { readFile } from "@linkwarden/filesystem";
+
+vi.mock("@/lib/api/verifyToken", () => ({
+ default: vi.fn(),
+}));
+
+vi.mock("@/lib/api/archives/resolveAccessibleArchive", () => ({
+ default: vi.fn(),
+}));
+
+vi.mock("@linkwarden/filesystem", () => ({
+ readFile: vi.fn(),
+ createFile: vi.fn(),
+ createFolder: vi.fn(),
+}));
+
+const createMockResponse = () => {
+ const state = {
+ statusCode: 200,
+ jsonBody: undefined as any,
+ sentBody: undefined as any,
+ headers: new Map<string, string>(),
+ };
+
+ const res = {
+ setHeader(name: string, value: string) {
+ state.headers.set(name, value);
+ return res;
+ },
+ status(code: number) {
+ state.statusCode = code;
+ return res;
+ },
+ json(body: any) {
+ state.jsonBody = body;
+ return res;
+ },
+ send(body: any) {
+ state.sentBody = body;
+ return res;
+ },
+ };
+
+ return { res: res as any, state };
+};
+
+describe("/api/v1/archives/[linkId] GET", () => {
+ beforeEach(() => {
+ vi.stubEnv("NEXT_PUBLIC_USER_CONTENT_DOMAIN", "https://content.example.com");
+ });
+
+ afterEach(() => {
+ vi.clearAllMocks();
+ vi.unstubAllEnvs();
+ });
+
+ it("returns 403 for browser-style monolith GET requests when user-content delivery is enabled", async () => {
+ const { res, state } = createMockResponse();
+ await handler(
+ {
+ method: "GET",
+ query: { linkId: "10", format: "4" },
+ headers: {},
+ } as any,
+ res
+ );
+
+ expect(state.statusCode).toBe(403);
+ expect(state.jsonBody).toEqual({
+ response:
+ "Monolith archive access must use the user content domain when it is configured.",
+ });
+ });
+
+ it("allows bearer-authorized monolith GET requests", async () => {
+ vi.mocked(verifyToken).mockResolvedValue({ id: 7 } as any);
+ vi.mocked(resolveAccessibleArchive).mockResolvedValue({
+ status: 200,
+ response: {
+ filePath: "archives/5/10.html",
+ },
+ } as any);
+ vi.mocked(readFile).mockResolvedValue({
+ file: "<html>ok</html>",
+ contentType: "text/html",
+ status: 200,
+ } as any);
+
+ const { res, state } = createMockResponse();
+ await handler(
+ {
+ method: "GET",
+ query: { linkId: "10", format: "4" },
+ headers: {
+ authorization: "Bearer test-token",
+ },
+ } as any,
+ res
+ );
+
+ expect(state.statusCode).toBe(200);
+ expect(state.headers.get("Content-Type")).toBe("text/html");
+ expect(state.headers.get("Cache-Control")).toBe(
+ "private, max-age=31536000, immutable"
+ );
+ expect(state.sentBody).toBe("<html>ok</html>");
+ });
+});
diff --git a/apps/web/pages/api/v1/archives/[linkId].ts b/apps/web/pages/api/v1/archives/[linkId].ts
index bc2ac150..c44a136f 100644
--- a/apps/web/pages/api/v1/archives/[linkId].ts
+++ b/apps/web/pages/api/v1/archives/[linkId].ts
@@ -6,6 +6,7 @@ import { generatePreview } from "@linkwarden/lib/generatePreview";
import verifyToken from "@/lib/api/verifyToken";
import verifyUser from "@/lib/api/verifyUser";
import getPermission from "@/lib/api/getPermission";
+import resolveAccessibleArchive from "@/lib/api/archives/resolveAccessibleArchive";
import { prisma } from "@linkwarden/prisma";
import { UsersAndCollections } from "@linkwarden/prisma/client";
import { UploadFileSchema } from "@linkwarden/lib/schemaValidation";
@@ -77,27 +78,6 @@ function validateFile(
return fileBuffer;
}
-// Retrieve collection if accessible (for both GET and file uploads/updates)
-async function getAccessibleCollection(
- linkId: number,
- userId: number | undefined
-) {
- return prisma.collection.findFirst({
- where: {
- links: {
- some: {
- id: linkId,
- },
- },
- OR: [
- { ownerId: userId || -1 },
- { members: { some: { userId: userId || -1 } } },
- { isPublic: true },
- ],
- },
- });
-}
-
/** ------------------ */
/** Route Handlers */
/** ------------------ */
@@ -106,29 +86,39 @@ async function handleGet(req: NextApiRequest, res: NextApiResponse) {
const linkId = Number(req.query.linkId);
const format = Number(req.query.format);
const isPreview = Boolean(req.query.preview);
+ const hasBearerAuthorization =
+ typeof req.headers.authorization === "string" &&
+ req.headers.authorization.trim().toLowerCase().startsWith("bearer ");
- const suffix = getSuffixFromFormat(format);
- if (!linkId || !suffix) {
- return res.status(401).json({ response: "Invalid parameters." });
+ if (
+ format === ArchivedFormat.monolith &&
+ process.env.NEXT_PUBLIC_USER_CONTENT_DOMAIN &&
+ !hasBearerAuthorization
+ ) {
+ return res.status(403).json({
+ response:
+ "Monolith archive access must use the user content domain when it is configured.",
+ });
}
// Verify token => If present, get user ID
const token = await verifyToken({ req });
const userId = typeof token === "string" ? undefined : token?.id;
- // Check if user can access the collection
- const collection = await getAccessibleCollection(linkId, userId);
- if (!collection) {
+ const resolvedArchive = await resolveAccessibleArchive({
+ linkId,
+ format,
+ isPreview,
+ userId,
+ });
+
+ if (resolvedArchive.status !== 200) {
return res
- .status(401)
- .json({ response: "You don't have access to this collection." });
+ .status(resolvedArchive.status)
+ .json({ response: resolvedArchive.response });
}
- // Decide the file path
- const filePath = isPreview
- ? `archives/preview/${collection.id}/${linkId}.jpeg`
- : `archives/${collection.id}/${linkId + suffix}`;
-
+ const { filePath } = resolvedArchive.response;
const { file, contentType, status } = await readFile(filePath);
res
.setHeader("Content-Type", contentType)
diff --git a/apps/web/pages/api/v1/config/index.test.ts b/apps/web/pages/api/v1/config/index.test.ts
new file mode 100644
index 00000000..a4f2b6cb
--- /dev/null
+++ b/apps/web/pages/api/v1/config/index.test.ts
@@ -0,0 +1,25 @@
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { getEnvData } from "./index";
+
+describe("getEnvData", () => {
+ afterEach(() => {
+ vi.unstubAllEnvs();
+ });
+
+ it("returns the raw user content domain when configured", () => {
+ vi.stubEnv(
+ "NEXT_PUBLIC_USER_CONTENT_DOMAIN",
+ "https://content.example.com/view/"
+ );
+
+ expect(getEnvData().USER_CONTENT_DOMAIN).toBe(
+ "https://content.example.com/view/"
+ );
+ });
+
+ it("returns null when the user content domain is absent", () => {
+ vi.stubEnv("NEXT_PUBLIC_USER_CONTENT_DOMAIN", "");
+
+ expect(getEnvData().USER_CONTENT_DOMAIN).toBeNull();
+ });
+});
diff --git a/apps/web/pages/api/v1/config/index.ts b/apps/web/pages/api/v1/config/index.ts
index 45bba6a8..b664c47f 100644
--- a/apps/web/pages/api/v1/config/index.ts
+++ b/apps/web/pages/api/v1/config/index.ts
@@ -23,6 +23,7 @@ export const getEnvData = () => {
Number(process.env.NEXT_PUBLIC_RSS_POLLING_INTERVAL_MINUTES) || null,
EMAIL_PROVIDER: process.env.NEXT_PUBLIC_EMAIL_PROVIDER === "true" || null,
MAX_FILE_BUFFER: Number(process.env.NEXT_PUBLIC_MAX_FILE_BUFFER) || null,
+ USER_CONTENT_DOMAIN: process.env.NEXT_PUBLIC_USER_CONTENT_DOMAIN || null,
AI_ENABLED: hasAiProvider || null,
INSTANCE_VERSION: process.env.version,
};
diff --git a/apps/web/pages/api/v1/preserved/token.test.ts b/apps/web/pages/api/v1/preserved/token.test.ts
new file mode 100644
index 00000000..4342c077
--- /dev/null
+++ b/apps/web/pages/api/v1/preserved/token.test.ts
@@ -0,0 +1,151 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { ArchivedFormat } from "@linkwarden/types/global";
+import handler from "./token";
+import resolveAccessibleArchive from "@/lib/api/archives/resolveAccessibleArchive";
+import createPreservedFormatUrl from "@/lib/api/preserved/createPreservedFormatUrl";
+import verifyToken from "@/lib/api/verifyToken";
+import { fileExists } from "@linkwarden/filesystem";
+
+vi.mock("@/lib/api/archives/resolveAccessibleArchive", () => ({
+ default: vi.fn(),
+}));
+
+vi.mock("@/lib/api/preserved/createPreservedFormatUrl", () => ({
+ default: vi.fn(),
+}));
+
+vi.mock("@/lib/api/verifyToken", () => ({
+ default: vi.fn(),
+}));
+
+vi.mock("@linkwarden/filesystem", () => ({
+ fileExists: vi.fn(),
+}));
+
+const createMockResponse = () => {
+ const state = {
+ statusCode: 200,
+ jsonBody: undefined as any,
+ headers: new Map<string, string>(),
+ };
+
+ const res = {
+ setHeader(name: string, value: string) {
+ state.headers.set(name, value);
+ return res;
+ },
+ status(code: number) {
+ state.statusCode = code;
+ return res;
+ },
+ json(body: any) {
+ state.jsonBody = body;
+ return res;
+ },
+ };
+
+ return { res: res as any, state };
+};
+
+describe("/api/v1/preserved/token", () => {
+ beforeEach(() => {
+ vi.stubEnv(
+ "NEXT_PUBLIC_USER_CONTENT_DOMAIN",
+ "https://content.example.com"
+ );
+ });
+
+ afterEach(() => {
+ vi.clearAllMocks();
+ vi.unstubAllEnvs();
+ });
+
+ it("returns a user-content URL for an accessible archived format", async () => {
+ vi.mocked(verifyToken).mockResolvedValue({ id: 9 } as any);
+ vi.mocked(resolveAccessibleArchive).mockResolvedValue({
+ status: 200,
+ response: {
+ filePath: "archives/5/10.html",
+ collectionId: 5,
+ linkId: 10,
+ format: ArchivedFormat.monolith,
+ isPreview: false,
+ },
+ } as any);
+ vi.mocked(fileExists).mockResolvedValue(true);
+ vi.mocked(createPreservedFormatUrl).mockResolvedValue(
+ "https://content.example.com/api/v1/preserved/view?token=abc"
+ );
+
+ const { res, state } = createMockResponse();
+ await handler(
+ {
+ method: "GET",
+ query: { linkId: "10", format: String(ArchivedFormat.monolith) },
+ headers: {},
+ } as any,
+ res
+ );
+
+ expect(state.statusCode).toBe(200);
+ expect(state.headers.get("Cache-Control")).toBe("no-store");
+ expect(state.jsonBody).toEqual({
+ response: {
+ url: "https://content.example.com/api/v1/preserved/view?token=abc",
+ },
+ });
+ });
+
+ it("returns the archive resolution error when access is denied", async () => {
+ vi.mocked(verifyToken).mockResolvedValue("You must be logged in.");
+ vi.mocked(resolveAccessibleArchive).mockResolvedValue({
+ status: 401,
+ response: "You don't have access to this collection.",
+ } as any);
+
+ const { res, state } = createMockResponse();
+ await handler(
+ {
+ method: "GET",
+ query: { linkId: "10", format: String(ArchivedFormat.monolith) },
+ headers: {},
+ } as any,
+ res
+ );
+
+ expect(state.statusCode).toBe(401);
+ expect(state.jsonBody).toEqual({
+ response: "You don't have access to this collection.",
+ });
+ });
+
+ it("returns 404 when the archived format is missing", async () => {
+ vi.mocked(verifyToken).mockResolvedValue({ id: 9 } as any);
+ vi.mocked(resolveAccessibleArchive).mockResolvedValue({
+ status: 200,
+ response: {
+ filePath: "archives/5/10.html",
+ collectionId: 5,
+ linkId: 10,
+ format: ArchivedFormat.monolith,
+ isPreview: false,
+ },
+ } as any);
+ vi.mocked(fileExists).mockResolvedValue(false);
+
+ const { res, state } = createMockResponse();
+ await handler(
+ {
+ method: "GET",
+ query: { linkId: "10", format: String(ArchivedFormat.monolith) },
+ headers: {},
+ } as any,
+ res
+ );
+
+ expect(state.statusCode).toBe(404);
+ expect(state.jsonBody).toEqual({
+ response: "Archived format not found.",
+ });
+ });
+});
diff --git a/apps/web/pages/api/v1/preserved/token.ts b/apps/web/pages/api/v1/preserved/token.ts
new file mode 100644
index 00000000..d46c635b
--- /dev/null
+++ b/apps/web/pages/api/v1/preserved/token.ts
@@ -0,0 +1,64 @@
+import type { NextApiRequest, NextApiResponse } from "next";
+import { fileExists } from "@linkwarden/filesystem";
+import resolveAccessibleArchive from "@/lib/api/archives/resolveAccessibleArchive";
+import createPreservedFormatUrl from "@/lib/api/preserved/createPreservedFormatUrl";
+import verifyToken from "@/lib/api/verifyToken";
+import { ArchivedFormat } from "@linkwarden/types/global";
+
+const getSingleValue = (value?: string | string[]) => {
+ if (Array.isArray(value)) return value[0];
+ return value;
+};
+
+export default async function handler(
+ req: NextApiRequest,
+ res: NextApiResponse
+) {
+ if (req.method !== "GET") {
+ return res.status(405).json({ response: "Method not allowed" });
+ }
+
+ if (!process.env.NEXT_PUBLIC_USER_CONTENT_DOMAIN) {
+ return res
+ .status(400)
+ .json({ response: "User content domain is not configured." });
+ }
+
+ try {
+ const token = await verifyToken({ req });
+ const userId = typeof token === "string" ? undefined : token?.id;
+ const format = Number(
+ getSingleValue(req.query.format) ?? ArchivedFormat.monolith
+ );
+
+ const resolvedArchive = await resolveAccessibleArchive({
+ linkId: Number(req.query.linkId),
+ format,
+ userId,
+ });
+
+ if (resolvedArchive.status !== 200) {
+ return res
+ .status(resolvedArchive.status)
+ .json({ response: resolvedArchive.response });
+ }
+
+ const { filePath, linkId } = resolvedArchive.response;
+ if (!(await fileExists(filePath))) {
+ return res.status(404).json({ response: "Archived format not found." });
+ }
+
+ const url = await createPreservedFormatUrl({
+ linkId,
+ filePath,
+ format: resolvedArchive.response.format,
+ });
+
+ res.setHeader("Cache-Control", "no-store");
+ return res.status(200).json({ response: { url } });
+ } catch (error: any) {
+ return res.status(500).json({
+ response: error?.message || "Failed to create archived format URL.",
+ });
+ }
+}
diff --git a/apps/web/pages/api/v1/preserved/view.test.ts b/apps/web/pages/api/v1/preserved/view.test.ts
new file mode 100644
index 00000000..280a6af9
--- /dev/null
+++ b/apps/web/pages/api/v1/preserved/view.test.ts
@@ -0,0 +1,192 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { ArchivedFormat } from "@linkwarden/types/global";
+import handler from "./view";
+import { readFile } from "@linkwarden/filesystem";
+import { decodePreservedFormatToken } from "@/lib/api/preserved/createPreservedFormatUrl";
+
+vi.mock("@linkwarden/filesystem", () => ({
+ readFile: vi.fn(),
+}));
+
+vi.mock("@/lib/api/preserved/createPreservedFormatUrl", () => ({
+ PRESERVED_FORMAT_SCOPE: "preserved-format",
+ decodePreservedFormatToken: vi.fn(),
+}));
+
+const createMockResponse = () => {
+ const state = {
+ statusCode: 200,
+ jsonBody: undefined as any,
+ sentBody: undefined as any,
+ headers: new Map<string, string>(),
+ };
+
+ const res = {
+ setHeader(name: string, value: string) {
+ state.headers.set(name, value);
+ return res;
+ },
+ status(code: number) {
+ state.statusCode = code;
+ return res;
+ },
+ json(body: any) {
+ state.jsonBody = body;
+ return res;
+ },
+ send(body: any) {
+ state.sentBody = body;
+ return res;
+ },
+ };
+
+ return { res: res as any, state };
+};
+
+describe("/api/v1/preserved/view", () => {
+ beforeEach(() => {
+ vi.stubEnv("NEXT_PUBLIC_USER_CONTENT_DOMAIN", "https://content.example.com");
+ });
+
+ afterEach(() => {
+ vi.clearAllMocks();
+ vi.unstubAllEnvs();
+ });
+
+ it("streams the archived format on the configured user content host", async () => {
+ vi.mocked(decodePreservedFormatToken).mockResolvedValue({
+ scope: "preserved-format",
+ linkId: 11,
+ filePath: "archives/7/11.html",
+ format: ArchivedFormat.monolith,
+ iat: 100,
+ exp: Math.floor(Date.now() / 1000) + 60,
+ } as any);
+ vi.mocked(readFile).mockResolvedValue({
+ file: "<html>ok</html>",
+ contentType: "text/html",
+ status: 200,
+ } as any);
+
+ const { res, state } = createMockResponse();
+ await handler(
+ {
+ method: "GET",
+ query: { token: "abc", download: "1" },
+ headers: {
+ host: "content.example.com",
+ },
+ } as any,
+ res
+ );
+
+ expect(state.statusCode).toBe(200);
+ expect(state.headers.get("Content-Type")).toBe("text/html; charset=utf-8");
+ expect(state.headers.get("Cache-Control")).toBe("private, no-store");
+ expect(state.headers.get("X-Robots-Tag")).toBe("noindex, nofollow");
+ expect(state.headers.get("Content-Disposition")).toBe(
+ 'attachment; filename="Webpage.html"'
+ );
+ expect(state.sentBody).toBe("<html>ok</html>");
+ });
+
+ it("rejects requests on the wrong host", async () => {
+ const { res, state } = createMockResponse();
+ await handler(
+ {
+ method: "GET",
+ query: { token: "abc" },
+ headers: {
+ host: "app.example.com",
+ },
+ } as any,
+ res
+ );
+
+ expect(state.statusCode).toBe(403);
+ expect(state.jsonBody).toEqual({ response: "Invalid user content host." });
+ });
+
+ it("accepts forwarded user content hosts with default https ports", async () => {
+ vi.mocked(decodePreservedFormatToken).mockResolvedValue({
+ scope: "preserved-format",
+ linkId: 11,
+ filePath: "archives/7/11.html",
+ format: ArchivedFormat.monolith,
+ iat: 100,
+ exp: Math.floor(Date.now() / 1000) + 60,
+ } as any);
+ vi.mocked(readFile).mockResolvedValue({
+ file: "<html>ok</html>",
+ contentType: "text/html",
+ status: 200,
+ } as any);
+
+ const { res, state } = createMockResponse();
+ await handler(
+ {
+ method: "GET",
+ query: { token: "abc" },
+ headers: {
+ host: "internal-upstream",
+ "x-forwarded-host": "content.example.com:443",
+ },
+ } as any,
+ res
+ );
+
+ expect(state.statusCode).toBe(200);
+ expect(state.sentBody).toBe("<html>ok</html>");
+ });
+
+ it("accepts standard forwarded headers from proxies", async () => {
+ vi.mocked(decodePreservedFormatToken).mockResolvedValue({
+ scope: "preserved-format",
+ linkId: 11,
+ filePath: "archives/7/11.html",
+ format: ArchivedFormat.monolith,
+ iat: 100,
+ exp: Math.floor(Date.now() / 1000) + 60,
+ } as any);
+ vi.mocked(readFile).mockResolvedValue({
+ file: "<html>ok</html>",
+ contentType: "text/html",
+ status: 200,
+ } as any);
+
+ const { res, state } = createMockResponse();
+ await handler(
+ {
+ method: "GET",
+ query: { token: "abc" },
+ headers: {
+ host: "internal-upstream",
+ forwarded: 'for=1.2.3.4;proto=https;host="content.example.com:443"',
+ },
+ } as any,
+ res
+ );
+
+ expect(state.statusCode).toBe(200);
+ expect(state.sentBody).toBe("<html>ok</html>");
+ });
+
+ it("rejects invalid tokens", async () => {
+ vi.mocked(decodePreservedFormatToken).mockResolvedValue(null);
+
+ const { res, state } = createMockResponse();
+ await handler(
+ {
+ method: "GET",
+ query: { token: "abc" },
+ headers: {
+ host: "content.example.com",
+ },
+ } as any,
+ res
+ );
+
+ expect(state.statusCode).toBe(401);
+ expect(state.jsonBody).toEqual({ response: "Invalid archived format token." });
+ });
+});
diff --git a/apps/web/pages/api/v1/preserved/view.ts b/apps/web/pages/api/v1/preserved/view.ts
new file mode 100644
index 00000000..672816ab
--- /dev/null
+++ b/apps/web/pages/api/v1/preserved/view.ts
@@ -0,0 +1,162 @@
+import type { NextApiRequest, NextApiResponse } from "next";
+import path from "path";
+import { readFile } from "@linkwarden/filesystem";
+import {
+ decodePreservedFormatToken,
+ PRESERVED_FORMAT_SCOPE,
+} from "@/lib/api/preserved/createPreservedFormatUrl";
+import { ArchivedFormat } from "@linkwarden/types/global";
+
+const getSingleValue = (value?: string | string[]) => {
+ if (Array.isArray(value)) return value[0];
+ return value;
+};
+
+const normalizeHost = (value: string, protocol = "https:") => {
+ const trimmed = value.trim();
+ if (!trimmed) return null;
+
+ const urlValue = trimmed.includes("://") ? trimmed : `${protocol}//${trimmed}`;
+
+ try {
+ const parsed = new URL(urlValue);
+ const hostname = parsed.hostname.toLowerCase();
+ const port = parsed.port;
+ const isDefaultPort =
+ !port ||
+ (parsed.protocol === "https:" && port === "443") ||
+ (parsed.protocol === "http:" && port === "80");
+
+ return isDefaultPort ? hostname : `${hostname}:${port}`;
+ } catch {
+ return null;
+ }
+};
+
+const getForwardedHeaderValue = (forwarded?: string | string[], key?: string) => {
+ const headerValue = getSingleValue(forwarded);
+ if (!headerValue || !key) return undefined;
+
+ const firstEntry = headerValue.split(",")[0];
+ const match = firstEntry.match(
+ new RegExp(`(?:^|;)\\s*${key}=("[^"]+"|[^;]+)`, "i")
+ );
+
+ return match?.[1]?.replace(/^"|"$/g, "").trim();
+};
+
+const getRequestHost = (req: NextApiRequest, protocol: string) => {
+ const forwardedHost = getSingleValue(req.headers["x-forwarded-host"]);
+ if (forwardedHost) {
+ return normalizeHost(forwardedHost.split(",")[0], protocol);
+ }
+
+ const forwardedHeaderHost = getForwardedHeaderValue(
+ req.headers.forwarded,
+ "host"
+ );
+ if (forwardedHeaderHost) {
+ return normalizeHost(forwardedHeaderHost, protocol);
+ }
+
+ const host = getSingleValue(req.headers.host);
+ if (!host) return null;
+
+ return normalizeHost(host, protocol);
+};
+
+const getDownloadFilename = (
+ format: ArchivedFormat,
+ filePath: string
+) => {
+ const suffix = path.posix.extname(filePath) || "";
+
+ switch (format) {
+ case ArchivedFormat.monolith:
+ return "Webpage.html";
+ case ArchivedFormat.pdf:
+ return "PDF.pdf";
+ case ArchivedFormat.png:
+ case ArchivedFormat.jpeg:
+ return `Screenshot${suffix}`;
+ case ArchivedFormat.readability:
+ return "Readable.json";
+ default:
+ return path.posix.basename(filePath);
+ }
+};
+
+export default async function handler(
+ req: NextApiRequest,
+ res: NextApiResponse
+) {
+ if (req.method !== "GET") {
+ return res.status(405).json({ response: "Method not allowed" });
+ }
+
+ const userContentOrigin = process.env.NEXT_PUBLIC_USER_CONTENT_DOMAIN;
+ if (!userContentOrigin) {
+ return res
+ .status(400)
+ .json({ response: "User content domain is not configured." });
+ }
+
+ const userContentUrl = new URL(userContentOrigin);
+ const userContentHost = normalizeHost(
+ userContentUrl.host,
+ userContentUrl.protocol
+ );
+ if (
+ !userContentHost ||
+ getRequestHost(req, userContentUrl.protocol) !== userContentHost
+ ) {
+ return res.status(403).json({ response: "Invalid user content host." });
+ }
+
+ try {
+ const encodedToken = getSingleValue(req.query.token);
+ if (!encodedToken) {
+ return res.status(401).json({ response: "Missing archived format token." });
+ }
+
+ const token = await decodePreservedFormatToken(encodedToken);
+ if (
+ !token ||
+ token.scope !== PRESERVED_FORMAT_SCOPE ||
+ token.exp <= Math.floor(Date.now() / 1000)
+ ) {
+ return res.status(401).json({ response: "Invalid archived format token." });
+ }
+
+ const { file, contentType, status } = await readFile(token.filePath);
+ if (status !== 200) {
+ return res.status(status as number).send(file);
+ }
+
+ res
+ .setHeader(
+ "Content-Type",
+ contentType === "text/html"
+ ? "text/html; charset=utf-8"
+ : contentType
+ )
+ .setHeader("Cache-Control", "private, no-store")
+ .setHeader("X-Robots-Tag", "noindex, nofollow");
+
+ if (getSingleValue(req.query.download) === "1") {
+ res.setHeader(
+ "Content-Disposition",
+ `attachment; filename="${getDownloadFilename(
+ token.format,
+ token.filePath
+ )}"`
+ );
+ }
+
+ return res.status(200).send(file);
+ } catch (error: any) {
+ return res.status(500).json({
+ response: error?.message || "Failed to load archived format.",
+ });
+ }
+}
diff --git a/packages/filesystem/fileExists.ts b/packages/filesystem/fileExists.ts
new file mode 100644
index 00000000..27d34d5f
--- /dev/null
+++ b/packages/filesystem/fileExists.ts
@@ -0,0 +1,26 @@
+import { HeadObjectCommand } from "@aws-sdk/client-s3";
+import fs from "fs";
+import path from "path";
+import s3Client from "./s3Client";
+
+export async function fileExists(filePath: string): Promise<boolean> {
+ if (s3Client) {
+ try {
+ await s3Client.send(
+ new HeadObjectCommand({
+ Bucket: process.env.SPACES_BUCKET_NAME!,
+ Key: filePath,
+ })
+ );
+
+ return true;
+ } catch {
+ return false;
+ }
+ }
+
+ const storagePath = process.env.STORAGE_FOLDER || "data";
+ const creationPath = path.join(process.cwd(), "../..", storagePath, filePath);
+
+ return fs.existsSync(creationPath);
+}
diff --git a/packages/filesystem/index.ts b/packages/filesystem/index.ts
index 8ea17662..a00f3dae 100644
--- a/packages/filesystem/index.ts
+++ b/packages/filesystem/index.ts
@@ -2,6 +2,7 @@ export * from "./moveFile";
export * from "./removeFile";
export * from "./s3Client";
export * from "./readFile";
+export * from "./fileExists";
export * from "./createFile";
export * from "./createFolder";
export * from "./manageFiles";
diff --git a/packages/lib/getPreservedFormatUrl.ts b/packages/lib/getPreservedFormatUrl.ts
new file mode 100644
index 00000000..bc6bd251
--- /dev/null
+++ b/packages/lib/getPreservedFormatUrl.ts
@@ -0,0 +1,42 @@
+import { ArchivedFormat } from "@linkwarden/types/global";
+
+export default async function getPreservedFormatUrl({
+ tokenEndpoint,
+ linkId,
+ format,
+ download = false,
+ headers,
+ requestInit,
+}: {
+ tokenEndpoint: string;
+ linkId: number;
+ format: ArchivedFormat;
+ download?: boolean;
+ headers?: HeadersInit;
+ requestInit?: RequestInit;
+}) {
+ const response = await fetch(
+ `${tokenEndpoint}?linkId=${linkId}&format=${format}`,
+ {
+ ...requestInit,
+ headers,
+ }
+ );
+
+ const data = await response.json().catch(() => null);
+ if (!response.ok) {
+ throw new Error(data?.response || "Failed to load archived format.");
+ }
+
+ if (typeof data?.response?.url !== "string") {
+ throw new Error("Failed to load archived format.");
+ }
+
+ if (!download) {
+ return data.response.url;
+ }
+
+ const url = new URL(data.response.url);
+ url.searchParams.set("download", "1");
+ return url.toString();
+}
diff --git a/packages/router/config.tsx b/packages/router/config.tsx
index 4c32b86c..f949ed4b 100644
--- a/packages/router/config.tsx
+++ b/packages/router/config.tsx
@@ -7,6 +7,7 @@ export type Config = {
RSS_POLLING_INTERVAL_MINUTES: number | null;
EMAIL_PROVIDER: boolean | null;
MAX_FILE_BUFFER: number | null;
+ USER_CONTENT_DOMAIN: string | null;
AI_ENABLED: boolean | null;
INSTANCE_VERSION: string | null;
};
diff --git a/vitest.config.ts b/vitest.config.mts
similarity index 58%
rename from vitest.config.ts
rename to vitest.config.mts
index 67580ab0..0f2b24fd 100644
--- a/vitest.config.ts
+++ b/vitest.config.mts
@@ -1,6 +1,12 @@
+import path from "path";
import { defineConfig } from "vitest/config";
export default defineConfig({
+ resolve: {
+ alias: {
+ "@": path.resolve(process.cwd(), "apps/web"),
+ },
+ },
test: {
exclude: ["**/node_modules/**", "**/dist/**", "**/e2e/**"],
},