feat(downloads): per-user, per-host yt-dlp cookie/auth support (S6)

Each user stores their own login cookies (Netscape cookies.txt) for an
auth-walled download host (Facebook, Instagram, X, TikTok, Reddit) in
Settings; a download of an auth-walled link on that host is retried with
the acting user's cookie.

Two load-bearing security controls, both in downloads.credentials as the
single source of truth so enqueue and the worker can't drift:
- cache privacy: a cookie-authed download salts its MediaAsset format_sig
  with the user id, so the authed asset is private and never cache-served
  to another user. The worker attaches a cookie ONLY when the asset it is
  downloading into IS that private, salted identity.
- host scope (SEC-12): a cookie is resolved only for a URL whose netloc
  the credential owns (netloc-scoped _host_is); a look-alike/unrelated
  host gets none.

cookies_enc is Fernet-encrypted at rest, only decrypted in-worker into a
0600 file under staging/.auth/ (survives the retry wipe + _produced_file
scan) and unlinked in finally. The blob is never returned by a route,
logged, audited, or written to a job's error/snapshot. cookiefile is set
after the adapter's extra merge so an adapter can't clobber it. Settings
UI is write-only (host + set/updated only, never echoed). New
download_credentials table + migration 0074; per-user routes; HU+EN i18n.

Tests: host-scope, cache-privacy (no cross-user serve), encrypt-at-rest,
write-only API, worker attach-gate; FE dom test for the write-only field.
This commit is contained in:
2026-08-28 03:53:04 +02:00
parent 5280949667
commit bc33b2ed16
21 changed files with 1030 additions and 13 deletions
@@ -0,0 +1,93 @@
// @vitest-environment jsdom
//
// S6 — the per-user download-cookies section is WRITE-ONLY: the stored blob is never fetched or
// shown back, so opening "Set"/"Update" always reveals an EMPTY field, and saving posts exactly the
// pasted value to the matching host. This drives the real DownloadAuth against a mocked api so we can
// assert the field never carries a prior value and the right host is written.
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
import { render, screen, cleanup, fireEvent, waitFor } from "@testing-library/react";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
const h = vi.hoisted(() => ({
downloadCredentials: vi.fn(),
setDownloadCredential: vi.fn(),
deleteDownloadCredential: vi.fn(),
}));
vi.mock("react-i18next", async (importOriginal) => {
const actual = await importOriginal<typeof import("react-i18next")>();
return {
...actual,
useTranslation: () => ({ t: (key: string) => key, i18n: { language: "en" } }),
};
});
vi.mock("../lib/api", () => ({ api: h }));
// Partial mock: SettingsPanel's module graph (PrefsProvider) also pulls getNotifSettings from here.
vi.mock("../lib/notifications", async (importOriginal) => {
const actual = await importOriginal<typeof import("../lib/notifications")>();
return { ...actual, notify: vi.fn() };
});
vi.mock("./ConfirmProvider", () => ({ useConfirm: () => vi.fn(async () => true) }));
import { DownloadAuth } from "./SettingsPanel";
const HOSTS = [
{ host_key: "facebook", label: "Facebook", configured: false, updated_at: null },
{ host_key: "instagram", label: "Instagram", configured: true, updated_at: "2026-08-01T00:00:00Z" },
];
function renderPanel() {
const qc = new QueryClient({ defaultOptions: { queries: { retry: false } } });
return render(
<QueryClientProvider client={qc}>
<DownloadAuth />
</QueryClientProvider>,
);
}
describe("DownloadAuth (write-only cookies)", () => {
beforeEach(() => {
h.downloadCredentials.mockResolvedValue({ hosts: HOSTS });
h.setDownloadCredential.mockResolvedValue({ ok: true, hosts: HOSTS });
h.deleteDownloadCredential.mockResolvedValue({ ok: true, hosts: HOSTS });
});
afterEach(cleanup);
it("lists every supported host with its configured state", async () => {
renderPanel();
await screen.findByTestId("cookie-host-facebook");
expect(screen.getByTestId("cookie-status-facebook").textContent).toContain(
"settings.downloadAuth.notSet",
);
expect(screen.getByTestId("cookie-status-instagram").textContent).toContain(
"settings.downloadAuth.configured",
);
});
it("opens an EMPTY field on Set and posts the pasted value to that host", async () => {
renderPanel();
await screen.findByTestId("cookie-host-facebook");
// The Set button is the outline action on the facebook row.
const setBtn = screen.getByText("settings.downloadAuth.set");
fireEvent.click(setBtn);
const field = (await screen.findByTestId("cookie-input-facebook")) as HTMLTextAreaElement;
expect(field.value).toBe(""); // write-only: never prefilled
fireEvent.change(field, { target: { value: "# Netscape\n.facebook.com\tTRUE\t/\tT\t0\tc\t1\n" } });
fireEvent.click(screen.getByText("settings.downloadAuth.save"));
await waitFor(() =>
expect(h.setDownloadCredential).toHaveBeenCalledWith(
"facebook",
"# Netscape\n.facebook.com\tTRUE\t/\tT\t0\tc\t1\n",
),
);
});
it("re-opening Update on a configured host still shows an empty field", async () => {
renderPanel();
await screen.findByTestId("cookie-host-instagram");
fireEvent.click(screen.getByText("settings.downloadAuth.update"));
const field = (await screen.findByTestId("cookie-input-instagram")) as HTMLTextAreaElement;
expect(field.value).toBe(""); // the stored blob is never fetched into the field
});
});
+141
View File
@@ -583,6 +583,145 @@ function PlexWatchSync() {
);
}
// Per-user download authentication (S6): store your own login cookies for an auth-walled host
// (e.g. a private Facebook group you belong to) so downloads from it use YOUR login. Write-only —
// the stored blob is never shown back; each row shows only the host + whether it's set + when.
// A cookie-authed download is kept private to your account (never cache-shared with another user).
// Exported for a focused DOM test (write-only behaviour); rendered inside Account below.
export function DownloadAuth() {
const { t, i18n } = useTranslation();
const qc = useQueryClient();
const confirm = useConfirm();
const q = useQuery({
queryKey: qk.downloadCredentials(),
queryFn: () => api.downloadCredentials(),
});
const [openHost, setOpenHost] = useState<string | null>(null);
const [draft, setDraft] = useState("");
const save = useMutation({
mutationFn: ({ host, cookies }: { host: string; cookies: string }) =>
api.setDownloadCredential(host, cookies),
onSuccess: (res) => {
qc.setQueryData(qk.downloadCredentials(), res);
setOpenHost(null);
setDraft("");
notify({ level: "success", message: t("settings.downloadAuth.saved") });
},
// Validation errors (empty / not-a-cookies.txt) surface via the global error modal, which
// localizes the structured { code: "cookies" } detail (see lib/api core localizeDetail).
});
const remove = useMutation({
mutationFn: (host: string) => api.deleteDownloadCredential(host),
onSuccess: (res) => {
qc.setQueryData(qk.downloadCredentials(), res);
notify({ level: "success", message: t("settings.downloadAuth.removed") });
},
});
const hosts = q.data?.hosts ?? [];
const onRemove = async (host: string) => {
const ok = await confirm({
title: t("settings.downloadAuth.removeConfirmTitle"),
message: t("settings.downloadAuth.removeConfirmBody"),
confirmLabel: t("settings.downloadAuth.removeConfirmAction"),
danger: true,
});
if (ok) remove.mutate(host);
};
return (
<Section title={t("settings.downloadAuth.title")}>
<p className="text-xs text-muted leading-relaxed mb-2">{t("settings.downloadAuth.intro")}</p>
<div className="divide-y divide-border">
{hosts.map((h) => {
const when = h.updated_at ? new Date(h.updated_at).toLocaleDateString(i18n.language) : "";
const open = openHost === h.host_key;
return (
<div key={h.host_key} className="py-2" data-testid={`cookie-host-${h.host_key}`}>
<div className="flex items-start justify-between gap-3">
<div className="min-w-0">
<div className="text-sm font-medium">{h.label}</div>
<p className="text-xs text-muted mt-0.5" data-testid={`cookie-status-${h.host_key}`}>
{h.configured
? t("settings.downloadAuth.configured", { when })
: t("settings.downloadAuth.notSet")}
</p>
</div>
<div className="flex items-center gap-2 shrink-0">
{h.configured && (
<Button
variant="danger-outline"
size="sm"
onClick={() => onRemove(h.host_key)}
disabled={remove.isPending}
>
{t("settings.downloadAuth.remove")}
</Button>
)}
<Button
variant="outline"
size="sm"
onClick={() => {
setOpenHost(open ? null : h.host_key);
setDraft("");
}}
>
{h.configured
? t("settings.downloadAuth.update")
: t("settings.downloadAuth.set")}
</Button>
</div>
</div>
{open && (
<div className="mt-2 space-y-2">
{/* Write-only: the field is ALWAYS empty on open — the stored blob is never
fetched or prefilled. */}
<textarea
value={draft}
onChange={(e) => setDraft(e.target.value)}
rows={5}
placeholder={t("settings.downloadAuth.placeholder")}
className={`${inputCls} font-mono text-xs resize-y`}
data-testid={`cookie-input-${h.host_key}`}
spellCheck={false}
autoComplete="off"
/>
<p className="text-2xs text-muted leading-relaxed">
{t("settings.downloadAuth.help")}
</p>
<div className="flex items-center gap-2">
<Button
variant="primary"
size="sm"
disabled={!draft.trim() || save.isPending}
onClick={() => save.mutate({ host: h.host_key, cookies: draft })}
>
{save.isPending
? t("settings.downloadAuth.saving")
: t("settings.downloadAuth.save")}
</Button>
<Button
variant="ghost"
size="sm"
onClick={() => {
setOpenHost(null);
setDraft("");
}}
>
{t("settings.downloadAuth.cancel")}
</Button>
</div>
</div>
)}
</div>
);
})}
</div>
</Section>
);
}
function Account({ me, onOpenWizard }: { me: Me; onOpenWizard: () => void }) {
const { t } = useTranslation();
const confirm = useConfirm();
@@ -625,6 +764,8 @@ function Account({ me, onOpenWizard }: { me: Me; onOpenWizard: () => void }) {
{me.role === "admin" && me.plex_enabled && <PlexWatchSync />}
{!me.is_demo && <DownloadAuth />}
{me.is_demo ? (
<Section title={t("settings.account.youtubeAccess")}>
<p className="text-xs text-muted leading-relaxed">{t("settings.account.demoNotice")}</p>
@@ -17,5 +17,7 @@
"sync_pause": "Sync paused",
"sync_resume": "Sync resumed",
"job_run": "Scheduler job run",
"audit_clear": "Audit log cleared"
"audit_clear": "Audit log cleared",
"download_credential_set": "Download cookies set",
"download_credential_delete": "Download cookies removed"
}
+6 -1
View File
@@ -218,7 +218,7 @@
},
"login_required": {
"short": "Sign-in required",
"body": "This video needs a signed-in, age-verified, or members-only account to view, so it can't be downloaded here."
"body": "This video needs a signed-in account (age-restricted, members-only, or a private group) to view. Add your cookies for this site under Settings → Account → Download authentication to download it."
},
"unsupported_host": {
"short": "Site not supported",
@@ -253,6 +253,11 @@
"body": "Something went wrong while downloading this item. The technical details below may help."
}
}
},
"cookies": {
"empty": "Paste your cookies first.",
"format": "That doesn't look like a cookies.txt file (Netscape format).",
"generic": "Those cookies couldn't be saved."
}
}
}
@@ -104,6 +104,26 @@
"failed": "Couldn't sign out other sessions. Please try again."
}
},
"downloadAuth": {
"title": "Download authentication",
"intro": "Some sites (e.g. a private Facebook group you belong to) only let logged-in members view a video. Paste your browser cookies for a site here and your downloads from it will use your login. Cookies are encrypted, kept private to your account, and only ever sent to the matching site.",
"configured": "Set · updated {{when}}",
"notSet": "Not set",
"set": "Set cookies",
"update": "Update",
"remove": "Remove",
"save": "Save",
"cancel": "Cancel",
"saving": "Saving…",
"placeholder": "Paste the contents of your cookies.txt (Netscape format) here",
"help": "Export a cookies.txt for this site with a browser extension, then paste it here. It's write-only — we never show it back.",
"saved": "Cookies saved.",
"removed": "Cookies removed.",
"failed": "Couldn't save those cookies.",
"removeConfirmTitle": "Remove cookies?",
"removeConfirmBody": "Downloads from this site will stop using your login.",
"removeConfirmAction": "Remove"
},
"demo": {
"title": "Demo access",
"intro": "Emails here can enter the shared demo account straight from the login page — no Google sign-in. They just type the address into the field and are let in after a moment.",
@@ -17,5 +17,7 @@
"sync_pause": "Szinkron szüneteltetve",
"sync_resume": "Szinkron folytatva",
"job_run": "Ütemező job lefutott",
"audit_clear": "Napló ürítve"
"audit_clear": "Napló ürítve",
"download_credential_set": "Letöltési cookie-k beállítva",
"download_credential_delete": "Letöltési cookie-k eltávolítva"
}
+6 -1
View File
@@ -218,7 +218,7 @@
},
"login_required": {
"short": "Bejelentkezés szükséges",
"body": "Ehhez a videóhoz bejelentkezett, kor-ellenőrzött vagy tagsági fiók kell, ezért itt nem tölthető le."
"body": "Ehhez a videóhoz bejelentkezett fiók kell (korhatáros, csak tagoknak szóló vagy zárt csoport). Töltsd fel a cookie-kat ehhez az oldalhoz a Beállítások → Fiók → Letöltés-hitelesítés alatt a letöltéshez."
},
"unsupported_host": {
"short": "Nem támogatott oldal",
@@ -253,6 +253,11 @@
"body": "Valami hiba történt az elem letöltése közben. Az alábbi technikai részletek segíthetnek."
}
}
},
"cookies": {
"empty": "Előbb illeszd be a cookie-kat.",
"format": "Ez nem tűnik cookies.txt fájlnak (Netscape formátum).",
"generic": "A cookie-kat nem sikerült menteni."
}
}
}
@@ -104,6 +104,26 @@
"failed": "Nem sikerült kijelentkeztetni a többi munkamenetet. Próbáld újra."
}
},
"downloadAuth": {
"title": "Letöltés-hitelesítés",
"intro": "Egyes oldalak (pl. egy zárt Facebook-csoport, aminek tagja vagy) csak bejelentkezett tagoknak mutatják a videót. Illeszd be ide a böngésződ cookie-jait egy oldalhoz, és az onnan induló letöltések a te bejelentkezésedet használják. A cookie-k titkosítva, csak a te fiókodhoz kötve tárolódnak, és kizárólag az adott oldalnak küldjük el őket.",
"configured": "Beállítva · frissítve: {{when}}",
"notSet": "Nincs beállítva",
"set": "Cookie-k beállítása",
"update": "Frissítés",
"remove": "Eltávolítás",
"save": "Mentés",
"cancel": "Mégse",
"saving": "Mentés…",
"placeholder": "Illeszd be ide a cookies.txt tartalmát (Netscape formátum)",
"help": "Exportálj cookies.txt-t ehhez az oldalhoz egy böngészőbővítménnyel, majd illeszd be ide. Csak írható — sosem mutatjuk vissza.",
"saved": "Cookie-k mentve.",
"removed": "Cookie-k eltávolítva.",
"failed": "A cookie-kat nem sikerült menteni.",
"removeConfirmTitle": "Cookie-k eltávolítása?",
"removeConfirmBody": "Az erről az oldalról induló letöltések nem használják tovább a bejelentkezésedet.",
"removeConfirmAction": "Eltávolítás"
},
"demo": {
"title": "Demo hozzáférés",
"intro": "Az itt szereplő e-mailek a bejelentkező oldalról közvetlenül beléphetnek a közös demo fiókba — Google-bejelentkezés nélkül. Csak beírják a címet a mezőbe, és pár pillanat múlva bekerülnek.",
+2
View File
@@ -43,6 +43,8 @@ function localizeDetail(d: unknown): string {
}
if (o?.code === "edit")
return t(`downloads.errors.edit.${o.reason}`, t("downloads.errors.edit.generic"));
if (o?.code === "cookies")
return t(`downloads.errors.cookies.${o.reason}`, t("downloads.errors.cookies.generic"));
return t("errors.generic");
}
+24
View File
@@ -137,7 +137,31 @@ export interface AdminDownloadQuota {
unlimited: boolean;
}
// Per-user download authentication (cookies). Write-only: the API never returns the stored blob,
// only which supported hosts are configured + when. See backend downloads.credentials.
export interface DownloadCredentialHost {
host_key: string;
label: string;
configured: boolean;
updated_at: string | null;
}
export const downloadsApi = {
downloadCredentials: (): Promise<{ hosts: DownloadCredentialHost[] }> =>
req("/api/downloads/credentials"),
setDownloadCredential: (
hostKey: string,
cookies: string,
): Promise<{ ok: true; hosts: DownloadCredentialHost[] }> =>
req(`/api/downloads/credentials/${encodeURIComponent(hostKey)}`, {
method: "PUT",
body: JSON.stringify({ cookies }),
}),
deleteDownloadCredential: (
hostKey: string,
): Promise<{ ok: true; hosts: DownloadCredentialHost[] }> =>
req(`/api/downloads/credentials/${encodeURIComponent(hostKey)}`, { method: "DELETE" }),
downloadProfiles: (): Promise<DownloadProfile[]> => req("/api/downloads/profiles"),
createDownloadProfile: (p: { name: string; spec: DownloadSpec }): Promise<DownloadProfile> =>
req("/api/downloads/profiles", { method: "POST", body: JSON.stringify(p) }),
+1
View File
@@ -78,6 +78,7 @@ export const qk = {
downloadIndex: () => ["download-index"] as const,
downloadUsage: () => ["download-usage"] as const,
downloadProfiles: () => ["download-profiles"] as const,
downloadCredentials: () => ["download-credentials"] as const,
downloadLinks: (jobId: number) => ["download-links", jobId] as const,
dlQuota: (userId: number) => ["dl-quota", userId] as const,
storyboard: (jobId: number) => ["storyboard", jobId] as const,