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>