⚡️⚡️⚡️ Self-hosted collaborative bookmark manager to collect, read, annotate, and fully preserve what matters, all in one place.
TypeScript bookmarkbookmark-managercollaborationnextjsreact-nativeread-it-laterself-hostedtypescript
feat(mobile): self-signed cert support on android + support for custom headers
daniel31x13df2cfb4c4573
diff --git a/apps/mobile/app.config.ts b/apps/mobile/app.config.tsindex f039935c..8b4e6933 100644--- a/apps/mobile/app.config.ts+++ b/apps/mobile/app.config.ts@@ -3,7 +3,7 @@ import { ExpoConfig } from "expo/config";const config: ExpoConfig = {name: "Linkwarden",slug: "linkwarden",- version: "1.3.1",+ version: "1.3.2",orientation: "portrait",icon: "./assets/images/icon.png",scheme: "linkwarden",@@ -92,6 +92,7 @@ const config: ExpoConfig = {},],"./plugins/with-daynight-transparent-nav",+ "./plugins/with-network-security-config","expo-font","expo-web-browser","expo-apple-authentication",diff --git a/apps/mobile/app/_layout.tsx b/apps/mobile/app/_layout.tsxindex 4fd15a85..0dde5d4e 100644--- a/apps/mobile/app/_layout.tsx+++ b/apps/mobile/app/_layout.tsx@@ -23,6 +23,9 @@ import { queryClient } from "@/lib/queryClient";import { StatusBar } from "expo-status-bar";import * as Sentry from "@sentry/react-native";import OfflineSyncProvider from "@/components/OfflineSyncProvider";+import { installCustomHeaders } from "@/lib/customHeaders";++installCustomHeaders();Sentry.init({dsn: "https://00d7eed9e810cbbf91a7ed3547e37100@o4510998442475520.ingest.us.sentry.io/4511033679609856",diff --git a/apps/mobile/components/ActionSheets/SelfHostedServerSheet.tsx b/apps/mobile/components/ActionSheets/SelfHostedServerSheet.tsxindex 6155d8c2..1ad01873 100644--- a/apps/mobile/components/ActionSheets/SelfHostedServerSheet.tsx+++ b/apps/mobile/components/ActionSheets/SelfHostedServerSheet.tsx@@ -1,12 +1,19 @@import { useEffect, useState } from "react";-import { Alert, Text, View } from "react-native";+import { Alert, Pressable, Text, View } from "react-native";import ActionSheet, { SheetManager } from "react-native-actions-sheet";import { useSafeAreaInsets } from "react-native-safe-area-context";import { useColorScheme } from "nativewind";+import { ChevronDown, ChevronRight, X } from "lucide-react-native";import { Button } from "@/components/ui/Button";import Input from "@/components/ui/Input";import { rawTheme, ThemeName } from "@/lib/colors";import useAuthStore from "@/store/auth";+import {+ CustomHeader,+ getCustomHeaders,+ isValidCustomHeader,+ setCustomHeaders,+} from "@/lib/customHeaders";import type { Config } from "@linkwarden/router/config";import SheetHeader from "./SheetHeader";@@ -36,6 +43,12 @@ export default function SelfHostedServerSheet() {const [server, setServer] = useState(auth.instance && auth.instance !== cloudInstance ? auth.instance : "");+ const [showAdvanced, setShowAdvanced] = useState(+ () => (getCustomHeaders()?.headers.length ?? 0) > 0+ );+ const [headers, setHeaders] = useState<CustomHeader[]>(+ () => getCustomHeaders()?.headers ?? []+ );const [isLoading, setIsLoading] = useState(false);useEffect(() => {@@ -48,17 +61,42 @@ export default function SelfHostedServerSheet() {SheetManager.hide("self-hosted-server-sheet");};+ const updateHeader = (+ index: number,+ field: keyof CustomHeader,+ text: string+ ) => {+ setHeaders((prev) =>+ prev.map((row, i) => (i === index ? { ...row, [field]: text } : row))+ );+ };+const setSelfHostedServer = async () => {const instance = normalizeInstance(server);if (!instance)return Alert.alert("Error", "Please enter a server address.");+ const customHeaders = headers+ .map((h) => ({ key: h.key.trim(), value: h.value.trim() }))+ .filter((h) => h.key || h.value);++ const invalid = customHeaders.find((h) => !isValidCustomHeader(h));+ if (invalid)+ return Alert.alert(+ "Error",+ `"${invalid.key || "(empty)"}" is not a valid header.`+ );+setIsLoading(true);try {const res = await Promise.race([- fetch(`${instance}/api/v1/config`),+ fetch(`${instance}/api/v1/config`, {+ headers: Object.fromEntries(+ customHeaders.map((h) => [h.key, h.value])+ ),+ }),timeout(),]);const data = await res.json().catch(() => null);@@ -67,6 +105,7 @@ export default function SelfHostedServerSheet() {return Alert.alert("Error", "Could not verify this server.");}+ await setCustomHeaders(instance, customHeaders);await setInstance(instance, data.response as Config);closeSheet();} catch (err: any) {@@ -112,6 +151,67 @@ export default function SelfHostedServerSheet() {onChangeText={setServer}/>+ <Pressable+ className="flex-row items-center gap-1"+ onPress={() => setShowAdvanced((prev) => !prev)}+ >+ {showAdvanced ? (+ <ChevronDown size={18} color={theme.neutral} />+ ) : (+ <ChevronRight size={18} color={theme.neutral} />+ )}+ <Text className="text-neutral">Advanced</Text>+ </Pressable>++ {showAdvanced && (+ <View className="flex-col gap-2">+ <Text className="text-base-content font-bold">Custom Headers</Text>+ <Text className="text-neutral text-sm">+ Custom headers are sent with every request to this server.+ </Text>++ {headers.map((header, index) => (+ <View key={index} className="flex-row items-center gap-2">+ <Input+ className="flex-1 p-3 leading-tight h-12"+ textAlignVertical="center"+ placeholder="Header"+ value={header.key}+ autoCapitalize="none"+ autoCorrect={false}+ onChangeText={(text) => updateHeader(index, "key", text)}+ />+ <Input+ className="flex-1 p-3 leading-tight h-12"+ textAlignVertical="center"+ placeholder="Value"+ value={header.value}+ autoCapitalize="none"+ autoCorrect={false}+ onChangeText={(text) => updateHeader(index, "value", text)}+ />+ <Pressable+ hitSlop={8}+ onPress={() =>+ setHeaders((prev) => prev.filter((_, i) => i !== index))+ }+ >+ <X size={18} color={theme.neutral} />+ </Pressable>+ </View>+ ))}++ <Button+ variant="simple"+ onPress={() =>+ setHeaders((prev) => [...prev, { key: "", value: "" }])+ }+ >+ <Text className="text-base-content">Add Header</Text>+ </Button>+ </View>+ )}+<Buttonvariant="accent"size="lg"diff --git a/apps/mobile/components/Formats/ImageFormat.tsx b/apps/mobile/components/Formats/ImageFormat.tsxindex c72f43f4..2a48d460 100644--- a/apps/mobile/components/Formats/ImageFormat.tsx+++ b/apps/mobile/components/Formats/ImageFormat.tsx@@ -1,6 +1,7 @@import React, { useEffect, useState } from "react";import * as FileSystem from "expo-file-system/legacy";import useAuthStore from "@/store/auth";+import { customHeadersFor } from "@/lib/customHeaders";import { ArchivedFormat } from "@linkwarden/types/global";import { Link as LinkType } from "@linkwarden/prisma/client";import WebView from "react-native-webview";@@ -42,7 +43,10 @@ export default function ImageFormat({ link, setIsLoading, format }: Props) {const apiUrl = `${auth.instance}/api/v1/archives/${link.id}?format=${FORMAT}`;const result = await FileSystem.downloadAsync(apiUrl, filePath, {- headers: { Authorization: `Bearer ${auth.session}` },+ headers: {+ ...customHeadersFor(apiUrl),+ Authorization: `Bearer ${auth.session}`,+ },});return result.uri;diff --git a/apps/mobile/components/Formats/PdfFormat.tsx b/apps/mobile/components/Formats/PdfFormat.tsxindex 756810cc..98427e68 100644--- a/apps/mobile/components/Formats/PdfFormat.tsx+++ b/apps/mobile/components/Formats/PdfFormat.tsx@@ -1,6 +1,7 @@import React, { useEffect, useState } from "react";import * as FileSystem from "expo-file-system/legacy";import useAuthStore from "@/store/auth";+import { customHeadersFor } from "@/lib/customHeaders";import { ArchivedFormat } from "@linkwarden/types/global";import { Link as LinkType } from "@linkwarden/prisma/client";import Pdf from "react-native-pdf";@@ -26,7 +27,10 @@ export default function PdfFormat({ link, setIsLoading }: Props) {const apiUrl = `${auth.instance}/api/v1/archives/${link.id}?format=${FORMAT}`;const result = await FileSystem.downloadAsync(apiUrl, filePath, {- headers: { Authorization: `Bearer ${auth.session}` },+ headers: {+ ...customHeadersFor(apiUrl),+ Authorization: `Bearer ${auth.session}`,+ },});return result.uri;diff --git a/apps/mobile/components/Formats/WebpageFormat.tsx b/apps/mobile/components/Formats/WebpageFormat.tsxindex 8fb1a1b2..e7abc334 100644--- a/apps/mobile/components/Formats/WebpageFormat.tsx+++ b/apps/mobile/components/Formats/WebpageFormat.tsx@@ -3,6 +3,7 @@ import * as FileSystem from "expo-file-system/legacy";import getPreservedFormatUrl from "@linkwarden/lib/getPreservedFormatUrl";import { useConfig } from "@linkwarden/router/config";import useAuthStore from "@/store/auth";+import { customHeadersFor } from "@/lib/customHeaders";import { ArchivedFormat } from "@linkwarden/types/global";import { Link as LinkType } from "@linkwarden/prisma/client";import WebView from "react-native-webview";@@ -42,7 +43,10 @@ export default function WebpageFormat({ link, setIsLoading }: Props) {...(config?.USER_CONTENT_DOMAIN? {}: {- headers: { Authorization: `Bearer ${auth.session}` },+ headers: {+ ...customHeadersFor(apiUrl),+ Authorization: `Bearer ${auth.session}`,+ },}),});diff --git a/apps/mobile/components/LinkListing.tsx b/apps/mobile/components/LinkListing.tsxindex 8f717d72..2c9c5e54 100644--- a/apps/mobile/components/LinkListing.tsx+++ b/apps/mobile/components/LinkListing.tsx@@ -19,6 +19,7 @@ import {formatAvailable,} from "@linkwarden/lib/formatStats";import useAuthStore from "@/store/auth";+import { customHeadersFor } from "@/lib/customHeaders";import { useRouter } from "expo-router";import * as ContextMenu from "zeego/context-menu";import { useDeleteLink, useUpdateLink } from "@linkwarden/router/links";@@ -74,7 +75,10 @@ const LinkListing = ({ link, dashboard }: Props) => {const apiUrl = `${auth.instance}/api/v1/archives/${link.id}?format=${ArchivedFormat.jpeg}&preview=true&updatedAt=${link.updatedAt}`;const result = await FileSystem.downloadAsync(apiUrl, filePath, {- headers: { Authorization: `Bearer ${auth.session}` },+ headers: {+ ...customHeadersFor(apiUrl),+ Authorization: `Bearer ${auth.session}`,+ },});return result.uri;diff --git a/apps/mobile/lib/cache.ts b/apps/mobile/lib/cache.tsindex 3f674e61..fa97a071 100644--- a/apps/mobile/lib/cache.ts+++ b/apps/mobile/lib/cache.ts@@ -2,6 +2,7 @@ import * as FileSystem from "expo-file-system/legacy";import NetInfo from "@react-native-community/netinfo";import { ArchivedFormat, MobileAuth } from "@linkwarden/types/global";import getPreservedFormatUrl from "@linkwarden/lib/getPreservedFormatUrl";+import { customHeadersFor } from "@/lib/customHeaders";type LoadCacheOrFetchOptions<T> = {filePath: string;@@ -174,7 +175,7 @@ export const fetchFormatToCache = async ({});} else {const result = await FileSystem.downloadAsync(apiUrl, tmpPath, {- headers,+ headers: { ...customHeadersFor(apiUrl), ...headers },});if (result.status < 200 || result.status >= 300) {throw new Error(`HTTP ${result.status}`);diff --git a/apps/mobile/lib/customHeaders.ts b/apps/mobile/lib/customHeaders.tsnew file mode 100644index 00000000..bdcadc49--- /dev/null+++ b/apps/mobile/lib/customHeaders.ts@@ -0,0 +1,82 @@+import * as SecureStore from "expo-secure-store";++export type CustomHeader = { key: string; value: string };++type StoredHeaders = { instance: string; headers: CustomHeader[] };++const STORE_KEY = "CUSTOM_HEADERS";++// RFC 7230 header-name token; values must not allow CR/LF injection.+const NAME_REGEX = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;+const VALUE_REGEX = /^[^\r\n]*$/;++let stored: StoredHeaders | null = null;++export const loadCustomHeaders = async () => {+ try {+ const raw = await SecureStore.getItemAsync(STORE_KEY);+ stored = raw ? (JSON.parse(raw) as StoredHeaders) : null;+ } catch {+ stored = null;+ }+};++const ready = loadCustomHeaders();++export const getCustomHeaders = () => stored;++export const isValidCustomHeader = ({ key, value }: CustomHeader) =>+ NAME_REGEX.test(key) && VALUE_REGEX.test(value);++export const setCustomHeaders = async (+ instance: string,+ headers: CustomHeader[]+) => {+ if (!headers.length) {+ stored = null;+ await SecureStore.deleteItemAsync(STORE_KEY);+ return;+ }++ stored = { instance, headers };+ await SecureStore.setItemAsync(STORE_KEY, JSON.stringify(stored));+};++// Only requests to the exact instance the headers were configured for ever+// receive them — never the cloud instance or any other host.+export const customHeadersFor = (url: string): Record<string, string> => {+ if (!stored?.headers.length) return {};+ if (url !== stored.instance && !url.startsWith(stored.instance + "/"))+ return {};++ return Object.fromEntries(stored.headers.map((h) => [h.key, h.value]));+};++let originalFetch: typeof fetch | undefined;++// Covers every fetch in the app, including @linkwarden/router. Headers set by+// the app itself (e.g. Authorization) always take precedence.+// FileSystem.downloadAsync doesn't go through fetch — those callsites merge+// customHeadersFor() into their headers directly.+export const installCustomHeaders = () => {+ if (originalFetch) return;+ originalFetch = global.fetch;++ global.fetch = (async (input: any, init?: RequestInit) => {+ await ready;++ const url =+ typeof input === "string" ? input : (input?.url ?? String(input));+ const custom = customHeadersFor(url);++ if (Object.keys(custom).length) {+ const headers = new Headers(init?.headers ?? input?.headers ?? {});+ for (const [key, value] of Object.entries(custom)) {+ if (!headers.has(key)) headers.set(key, value);+ }+ init = { ...init, headers };+ }++ return originalFetch!(input, init);+ }) as typeof fetch;+};diff --git a/apps/mobile/plugins/with-network-security-config.js b/apps/mobile/plugins/with-network-security-config.jsnew file mode 100644index 00000000..4551d2f0--- /dev/null+++ b/apps/mobile/plugins/with-network-security-config.js@@ -0,0 +1,50 @@+const {+ withAndroidManifest,+ withDangerousMod,+} = require("@expo/config-plugins");+const fs = require("fs");+const path = require("path");++const NETWORK_SECURITY_CONFIG = `<?xml version="1.0" encoding="utf-8"?>+<network-security-config>+ <base-config cleartextTrafficPermitted="true">+ <trust-anchors>+ <certificates src="system" />+ <certificates src="user" />+ </trust-anchors>+ </base-config>+ <domain-config cleartextTrafficPermitted="false">+ <domain includeSubdomains="true">cloud.linkwarden.app</domain>+ <trust-anchors>+ <certificates src="system" />+ </trust-anchors>+ </domain-config>+</network-security-config>+`;++module.exports = function withNetworkSecurityConfig(config) {+ config = withDangerousMod(config, [+ "android",+ async (c) => {+ const xmlDir = path.join(+ c.modRequest.platformProjectRoot,+ "app/src/main/res/xml"+ );+ fs.mkdirSync(xmlDir, { recursive: true });+ fs.writeFileSync(+ path.join(xmlDir, "network_security_config.xml"),+ NETWORK_SECURITY_CONFIG+ );+ return c;+ },+ ]);++ return withAndroidManifest(config, (c) => {+ const application = c.modResults.manifest.application?.[0];+ if (application) {+ application.$["android:networkSecurityConfig"] =+ "@xml/network_security_config";+ }+ return c;+ });+};diff --git a/apps/mobile/store/auth.ts b/apps/mobile/store/auth.tsindex 1dee9136..d001cc76 100644--- a/apps/mobile/store/auth.ts+++ b/apps/mobile/store/auth.ts@@ -18,6 +18,7 @@ import { markWhatsNewSeen } from "@/lib/whatsNew";import { useOfflineSyncStore } from "@/lib/offlineSync";import { hasInactiveSubscription } from "@/lib/subscription";import { ensureCloudIsReachable } from "@/lib/ensureCloudIsReachable";+import { loadCustomHeaders, setCustomHeaders } from "@/lib/customHeaders";const cloudInstance = "https://cloud.linkwarden.app";const cloudConfig: Config = {@@ -197,6 +198,7 @@ const useAuthStore = create<AuthStore>((set, get) => ({error: "",},setAuth: async () => {+ await loadCustomHeaders();const session = await SecureStore.getItemAsync("TOKEN");const instance = await SecureStore.getItemAsync("INSTANCE");const nextInstance = cleanInstance(instance);@@ -225,6 +227,8 @@ const useAuthStore = create<AuthStore>((set, get) => ({setInstance: async (instance, config) => {const nextInstance = cleanInstance(instance);+ if (nextInstance === cloudInstance) await setCustomHeaders(nextInstance, []);+await SecureStore.setItemAsync("INSTANCE", nextInstance);set((state) => ({auth: {diff --git a/apps/web/package.json b/apps/web/package.jsonindex 0a5278fc..512d774b 100644--- a/apps/web/package.json+++ b/apps/web/package.json@@ -1,13 +1,13 @@{"name": "@linkwarden/web",- "version": "v2.15.0",+ "version": "v2.15.2","main": "index.js","repository": "https://github.com/linkwarden/linkwarden.git","author": "Daniel31X13 <[email protected]>","license": "AGPL-3.0","private": true,"scripts": {- "dev": "next dev",+ "dev": "next dev --experimental-https","start": "next start","build": "next build","lint": "next lint",