From 2c3300b8b07ea29c94306ac49822959b5a7b20b8 Mon Sep 17 00:00:00 2001 From: lrnselfreliance <33263708+lrnselfreliance@users.noreply.github.com> Date: Sat, 28 Nov 2026 14:25:24 -0700 Subject: [PATCH] Torrents over a fail-closed VPN (#1026) Torrents reach the Internet only through a fail-closed VPN (WireGuard or OpenVPN, any provider), so peers never see a WROLPi's own address. - A network namespace (Pi/Debian) or the vpn container (Docker) with an nftables kill switch; NAT-PMP or fixed port forwarding. - qBittorrent inside it, sandboxed; torrents kept in config/torrents/. - Torrent download form, Torrents page, Share as torrent, nav warning, and VPN settings in both Controller UIs. - Help docs: Torrents, and The VPN for Torrents. QA'd on a Raspberry Pi with a real provider over WireGuard and OpenVPN. Co-Authored-By: Claude Opus 5.5 --- UPGRADE.md | 2 + app/src/App.js | 2 + app/src/api.js | 60 + app/src/api/controller.js | 26 + app/src/components/Download.js | 139 +- app/src/components/FileBrowser.js | 9 + app/src/components/Nav.js | 16 + app/src/components/Nav.test.js | 35 + app/src/components/ShareTorrentModal.js | 119 ++ app/src/components/ShareTorrentModal.test.js | 66 + .../components/TorrentDownloadForm.test.js | 96 ++ app/src/components/Vars.js | 1 + app/src/components/admin/AdminRoute.js | 10 +- app/src/components/admin/AdminRoute.test.js | 34 + app/src/components/admin/ControllerPage.js | 2 + .../components/admin/ControllerPage.test.js | 10 + .../admin/ExtensionInstallSuggestion.js | 2 +- .../admin/ExtensionInstallSuggestion.test.js | 1 + app/src/components/admin/ExtensionPage.js | 7 + app/src/components/admin/Torrents.js | 344 +++++ app/src/components/admin/Torrents.test.js | 194 +++ app/src/components/admin/VpnSection.js | 291 +++++ app/src/components/admin/VpnSection.test.js | 297 +++++ app/src/components/ui/Icon.tsx | 3 + app/src/test-fixtures.js | 1 + controller/api/schemas.py | 63 + controller/api/vpn.py | 63 + controller/conftest.py | 19 + controller/defaults.py | 21 + controller/lib/docker_services.py | 78 +- controller/lib/sync.py | 6 +- controller/lib/vpn.py | 252 ++++ controller/main.py | 8 +- controller/rsyncd.conf | 4 +- controller/templates/index.html | 179 +++ controller/test/test_defaults.py | 2 +- controller/test/test_docker_services.py | 91 ++ controller/test/test_rsyncd.py | 4 +- controller/test/test_vpn.py | 251 ++++ controller/test/test_vpn_tunnel.py | 842 ++++++++++++ controller/vpn/__init__.py | 0 controller/vpn/tunnel.py | 1149 +++++++++++++++++ .../usr/local/sbin/wrolpi-bootstrap.sh | 4 +- .../config/package-lists/wrolpi.list.chroot | 4 + docker-compose.yml | 45 + docker/help/wrolpi-help | 2 +- docker/vpn/Dockerfile | 20 + docker/vpn/entrypoint.sh | 43 + docker/web/Caddyfile | 15 + etc/raspberrypios/Caddyfile | 15 + etc/raspberrypios/wrolpi-torrent.service | 58 + etc/raspberrypios/wrolpi-vpn-netns.sh | 100 ++ etc/raspberrypios/wrolpi-vpn.service | 22 + etc/raspberrypios/wrolpi.target | 2 +- modules/torrents/__init__.py | 6 + modules/torrents/api.py | 135 ++ modules/torrents/conftest.py | 128 ++ modules/torrents/downloader.py | 85 ++ modules/torrents/lib.py | 604 +++++++++ modules/torrents/qbittorrent.py | 138 ++ modules/torrents/qbittorrent_prepare.py | 108 ++ modules/torrents/share.py | 126 ++ modules/torrents/test/__init__.py | 0 modules/torrents/test/test_adding.py | 297 +++++ modules/torrents/test/test_share.py | 148 +++ modules/torrents/test/test_torrents.py | 360 ++++++ pi-gen/stage2/04-wrolpi/01-packages-nr | 4 + pi-gen/stage2/04-wrolpi/03-run-chroot.sh | 3 + release/torrent-advisories.py | 129 ++ release/wrolpi-torrent-advisories.service | 10 + release/wrolpi-torrent-advisories.timer | 10 + repair.sh | 4 + scripts/upgrade.sh | 32 + scripts/vulture_baseline.txt | 1 - wrolpi/common.py | 53 + wrolpi/contexts.py | 12 + wrolpi/root_api.py | 4 + wrolpi/schema.py | 9 + wrolpi/test/common.py | 1 + wrolpi/test/test_common.py | 25 + 80 files changed, 7516 insertions(+), 45 deletions(-) create mode 100644 app/src/components/ShareTorrentModal.js create mode 100644 app/src/components/ShareTorrentModal.test.js create mode 100644 app/src/components/TorrentDownloadForm.test.js create mode 100644 app/src/components/admin/AdminRoute.test.js create mode 100644 app/src/components/admin/Torrents.js create mode 100644 app/src/components/admin/Torrents.test.js create mode 100644 app/src/components/admin/VpnSection.js create mode 100644 app/src/components/admin/VpnSection.test.js create mode 100644 controller/api/vpn.py create mode 100644 controller/lib/vpn.py create mode 100644 controller/test/test_vpn.py create mode 100644 controller/test/test_vpn_tunnel.py create mode 100644 controller/vpn/__init__.py create mode 100644 controller/vpn/tunnel.py create mode 100644 docker/vpn/Dockerfile create mode 100755 docker/vpn/entrypoint.sh create mode 100644 etc/raspberrypios/wrolpi-torrent.service create mode 100755 etc/raspberrypios/wrolpi-vpn-netns.sh create mode 100644 etc/raspberrypios/wrolpi-vpn.service create mode 100644 modules/torrents/__init__.py create mode 100644 modules/torrents/api.py create mode 100644 modules/torrents/conftest.py create mode 100644 modules/torrents/downloader.py create mode 100644 modules/torrents/lib.py create mode 100644 modules/torrents/qbittorrent.py create mode 100644 modules/torrents/qbittorrent_prepare.py create mode 100644 modules/torrents/share.py create mode 100644 modules/torrents/test/__init__.py create mode 100644 modules/torrents/test/test_adding.py create mode 100644 modules/torrents/test/test_share.py create mode 100644 modules/torrents/test/test_torrents.py create mode 100644 release/torrent-advisories.py create mode 100644 release/wrolpi-torrent-advisories.service create mode 100644 release/wrolpi-torrent-advisories.timer diff --git a/UPGRADE.md b/UPGRADE.md index 434c46f8..58a8b8bb 100644 --- a/UPGRADE.md +++ b/UPGRADE.md @@ -14,6 +14,8 @@ * `git pull origin master --ff` 3. Build all docker containers * `docker-compose build --parallel` + * Rebuild the VPN container without its cache, so it gets the latest qBittorrent (it faces the Internet + through the VPN): `docker compose build --pull --no-cache vpn` 4. Create the map volumes * `docker volume create --name=openstreetmap-data` * `docker volume create --name=openstreetmap-rendered-tiles` diff --git a/app/src/App.js b/app/src/App.js index 37c210c8..29911115 100644 --- a/app/src/App.js +++ b/app/src/App.js @@ -4,6 +4,7 @@ import {NavBar} from "./components/Nav"; import {createBrowserRouter, createRoutesFromElements, Link, Outlet, Route, RouterProvider} from "react-router"; import {VideosTabLayout, VideosPage, VideosSettingsPage, VideosStatistics, VideoWrapper} from "./components/Videos"; import AdminRoute from "./components/admin/AdminRoute"; +import {ExtensionRoute} from "./components/admin/ExtensionPage"; import {Box, Header} from "./components/ui"; import '@mantine/core/styles.css'; import '@mantine/notifications/styles.css'; @@ -125,6 +126,7 @@ export const routes = createRoutesFromElements(}/> }/> }/> + }/> {/* Unknown URLs render inside Root, with the navigation bar and theme. */} }/> ); diff --git a/app/src/api.js b/app/src/api.js index 62579568..ef773bcf 100644 --- a/app/src/api.js +++ b/app/src/api.js @@ -2969,3 +2969,63 @@ export async function importRepo(repo) { } await reposError(response, 'Failed to import the repo.'); } + +// --- Torrents (they reach the Internet only through the VPN) --- + +const TORRENTS_API = `${API_URI}/torrents`; + +async function torrentsRequest(response, fallbackMessage) { + if (!response.ok) { + throw new Error(await getErrorMessage(response, fallbackMessage)); + } + return response.status === 204 ? null : response; +} + +export async function getTorrents() { + const response = await torrentsRequest(await apiGet(`${TORRENTS_API}/`), 'Failed to get torrents'); + return await response.json(); +} + +export async function uploadTorrent(file, destination) { + const form = new FormData(); + form.append('torrent', file); + if (destination) { + form.append('destination', destination); + } + const response = await torrentsRequest(await fetch(`${TORRENTS_API}/upload`, {method: 'POST', body: form}), + 'Failed to add the .torrent file'); + return await response.json(); +} + +export async function pauseTorrent(hash) { + await torrentsRequest(await apiPost(`${TORRENTS_API}/${hash}/pause`), 'Failed to pause the torrent'); +} + +export async function resumeTorrent(hash) { + await torrentsRequest(await apiPost(`${TORRENTS_API}/${hash}/resume`), 'Failed to resume the torrent'); +} + +export async function removeTorrent(hash, deleteFiles = false) { + await torrentsRequest(await apiDelete(`${TORRENTS_API}/${hash}?delete_files=${deleteFiles ? 'true' : 'false'}`), + 'Failed to remove the torrent'); +} + +export async function setTorrentShareLimits(hash, seedRatioLimit, seedTimeLimit) { + await torrentsRequest(await apiPut(`${TORRENTS_API}/${hash}/limits`, + {seed_ratio_limit: seedRatioLimit, seed_time_limit: seedTimeLimit}), 'Failed to save the limits'); +} + +export async function setTorrentSpeedLimits(upload, download) { + await torrentsRequest(await apiPut(`${TORRENTS_API}/limits`, {upload, download}), + 'Failed to save the speed limits'); +} + +export function torrentFileUrl(hash) { + return `${TORRENTS_API}/${hash}/torrent`; +} + +export async function shareTorrent(path, trackers, webSeeds, rememberTrackers = false) { + const response = await torrentsRequest(await apiPost(`${TORRENTS_API}/share`, + {path, trackers, web_seeds: webSeeds, remember_trackers: rememberTrackers}), 'Failed to share as a torrent'); + return (await response.json()).job_id; +} diff --git a/app/src/api/controller.js b/app/src/api/controller.js index feed933d..5836862f 100644 --- a/app/src/api/controller.js +++ b/app/src/api/controller.js @@ -294,3 +294,29 @@ export async function runSync() { export async function cancelSync() { return controllerFetch('/sync/cancel', {method: 'POST'}); } + +// --- VPN (torrents reach the Internet only through it) --- + +export async function getVpnStatus() { + return controllerFetch('/vpn/status'); +} + +export async function getVpnSettings() { + return controllerFetch('/vpn/settings'); +} + +export async function updateVpnSettings(settings) { + return controllerFetch('/vpn/settings', {method: 'POST', body: JSON.stringify(settings)}); +} + +export async function uploadVpnConfig(filename, content) { + return controllerFetch('/vpn/config', {method: 'POST', body: JSON.stringify({filename, content})}); +} + +export async function deleteVpnConfig() { + return controllerFetch('/vpn/config', {method: 'DELETE'}); +} + +export async function saveVpnAuth(username, password) { + return controllerFetch('/vpn/auth', {method: 'POST', body: JSON.stringify({username, password})}); +} diff --git a/app/src/components/Download.js b/app/src/components/Download.js index 8f115071..a6bea126 100644 --- a/app/src/components/Download.js +++ b/app/src/components/Download.js @@ -1,5 +1,5 @@ import React, {useState} from "react"; -import {fetchVideoDownloadDefaults, getDownloaders, postDownload, putDownload} from "../api"; +import {fetchVideoDownloadDefaults, getDownloaders, getTorrents, postDownload, putDownload, uploadTorrent} from "../api"; import { APIButton, DirectorySearch, @@ -13,8 +13,22 @@ import { validURL, validURLs, } from "./Common"; -import {Button, Group, Header, Icon, Message, MultiSelect, NumberInput, Select, Stack, TextInput, Textarea} from "./ui"; +import { + Button, + Group, + Header, + Icon, + Message, + MultiSelect, + NumberInput, + Select, + Stack, + TextInput, + Textarea, + toast, +} from "./ui"; import {Link} from "react-router"; +import {VPN_SETTINGS_PATH, VpnStateUnknown} from "./admin/VpnSection"; import {TagsSelector} from "../Tags"; import { commaSeparatedValidator, @@ -1506,6 +1520,116 @@ export function FilesDownloadForm({ } +// One magnet link or .torrent URL per line. +export const validTorrentUrls = (value) => { + const lines = (value || '').split(/\r?\n/).map(i => i.trim()).filter(Boolean); + return lines.length > 0 && lines.every(i => /^magnet:\?/i.test(i) || /^https?:\/\/\S+$/i.test(i)); +}; + +// The URLs are optional (a .torrent file may be chosen instead); a stable function, as the form registers it. +const optionalTorrentUrls = (value) => !(value || '').trim() || validTorrentUrls(value); + +function TorrentVpnStatus() { + const [status, setStatus] = React.useState(null); + const [failed, setFailed] = React.useState(false); + React.useEffect(() => { + let cancelled = false; + getTorrents() + .then(s => !cancelled && setStatus(s)) + .catch(e => { + console.error('Failed to get torrents', e); + if (!cancelled) { + setFailed(true); + } + }); + return () => { + cancelled = true; + }; + }, []); + + if (failed) { + return ; + } + if (!status) { + return null; + } + const vpn = status.vpn || {}; + if (vpn.state === 'connected') { + return + VPN connected{vpn.public_ip ? <> · peers see {vpn.public_ip} : null} + ; + } + return + Torrents only use the VPN. This torrent will start once the VPN connects.{' '} + Set up the VPN + ; +} + +export function TorrentDownloadForm({download, onCancel, actions = DownloadFormButtons}) { + const [showMessage, setShowMessage] = React.useState(false); + const [file, setFile] = React.useState(null); + const fileInput = React.useRef(null); + + const submitter = async (formData) => { + const urls = (formData.urls || '').split(/\r?\n/).map(i => i.trim()).filter(Boolean); + if (!file && !urls.length) { + throw new Error('Enter a magnet link or .torrent URL, or choose a .torrent file'); + } + if (file) { + try { + await uploadTorrent(file, formData.destination); + } catch (e) { + // The Download button only changes its icon; say why (postDownload toasts its own failures). + toast({type: 'error', title: 'Could not add the .torrent file', description: e.message, time: 6000}); + throw e; + } + setFile(null); + } + if (urls.length) { + await postDownload({downloader: Downloaders.Torrent, destination: formData.destination, urls}); + } + }; + + const emptyFormData = {destination: null, urls: ''}; + + const form = useForm({ + submitter, + defaultFormData: mergeDeep(emptyFormData, download), + emptyFormData, + clearPathsOnSuccess: URL_PATHS, + onSuccess: async () => setShowMessage(true), + }); + + return
e.preventDefault()}> +
Torrent
+

Download (and share) torrents of open data. Torrents only use the VPN, so peers never see this WROLPi's own + address. Saved in the "torrents" directory unless you choose another.

+ + + + {/* Optional: a .torrent file may be chosen instead (or as well). */} + +
+ setFile((e.target.files && e.target.files[0]) || null)}/> + + + {file && {file.name}} + +
+ + {showMessage && } + {/* Download waits for something to download: a URL or a chosen file. */} + {actions({onCancel, form: {...form, ready: form.ready && (!!file || !!(form.formData.urls || '').trim())}})} +
+
+} + const suffixValidator = (value) => { const error = commaSeparatedValidator(value); if (error) { @@ -1659,11 +1783,12 @@ function UrlField({form, required = true, name = 'url', path = 'url', disabled = } /** Multiline URLs field: one URL per line. */ -function UrlsField({name = 'urls', required, form}) { +function UrlsField({name = 'urls', required, form, label = 'URLs', placeholder = 'Enter one URL per line', + valid = validURLs}) { required = required !== undefined; const validator = (value) => { - if (!validURLs(value)) { + if (!valid(value)) { return 'Invalid URLs'; } }; @@ -1687,10 +1812,10 @@ function UrlsField({name = 'urls', required, form}) { }; return
- +