Archilyzer · Source

archilyzer

Archilyzer
git clone https://archilyzer.pages.dev/source/archilyzer.git
Log | Files | Refs | README | LICENSE

commit e8e5ac14827c1d77acb8293812d1f77f78079f7b
parent d9862368e931e3072f17ae4059c1249964c9c263
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Mon, 16 Nov 2026 16:41:32 -0500

cookie screen round 2 review: X's spec drawn masked, no stale-tab revert, no remount, one failed read is one section's

- X's login source as a page draws it (lib/xSourceDisplay.ts): the browser
  spec, its label and the Check summary go through settings.privacy's
  displayText on the server -- /settings' page, loadCookieControls and every X
  session action's answer. The client only draws them; the select acts on the
  source kind. The yt-dlp cookiesFromBrowser input stays the raw saved value.
  privacy-audit.spec's fixture now has a path-bearing spec: its masked test
  would catch a raw one anywhere but that input on /settings and /cookies.
- No stale-tab revert (settings/cookieKeys.ts): each form that edits
  cookiesFromBrowser / cookieMode carries the values it was drawn with
  (hidden `<key>.seeded`), and /settings' Save and /cookies' Save write a key
  only when the form changed it. An old /settings tab's Save keeps what
  /cookies set. A form without the seeded fields writes both, as before.
- CookiesBoard: a row's press re-keys only THAT row's section (never its
  disclosure); every other row keeps what is open and what is typed.
- loadCookieControls reads each section on its own: one that throws draws
  its sentence in its place, the rest of the page as usual.

Co-Authored-By: Claude <noreply@anthropic.com>

Diffstat:
Meditor/app/cookies/CookiesBoard.tsx | 72++++++++++++++++++++++++++++++++++++++++++++++++------------------------
Meditor/app/lib/cookieControls.test.ts | 52++++++++++++++++++++++++++++++++++++++++++++++------
Meditor/app/lib/cookieControls.ts | 100+++++++++++++++++++++++++++++++++++++++++++++++--------------------------------
Aeditor/app/lib/cookieControlsTypes.ts | 35+++++++++++++++++++++++++++++++++++
Aeditor/app/lib/xSourceDisplay.ts | 21+++++++++++++++++++++
Meditor/app/settings/actions.ts | 19++++++-------------
Meditor/app/settings/components/XSessionSection.tsx | 2++
Meditor/app/settings/components/YtdlpCookieFields.tsx | 5+++++
Aeditor/app/settings/cookieKeys.test.ts | 44++++++++++++++++++++++++++++++++++++++++++++
Aeditor/app/settings/cookieKeys.ts | 39+++++++++++++++++++++++++++++++++++++++
Meditor/app/settings/cookieSourceActions.ts | 12+++++++-----
Meditor/app/settings/page.tsx | 6++++--
Meditor/app/settings/xSessionActions.ts | 6++++--
Meditor/e2e/cookies-screen.spec.ts | 53++++++++++++++++++++++++++++++++++++++++++++++++++---
Meditor/e2e/privacy-audit.spec.ts | 12+++++++++++-
15 files changed, 382 insertions(+), 96 deletions(-)

diff --git a/editor/app/cookies/CookiesBoard.tsx b/editor/app/cookies/CookiesBoard.tsx @@ -16,7 +16,7 @@ import { } from "yt-dlp-transcript-common/lib/cookieStatus"; import { usePolledPayload } from "../lib/usePolledPayload"; import { cookieControlsAction, pressCookieButtonAction } from "./actions"; -import type { CookieControls } from "../lib/cookieControls"; +import { sectionFailed, type CookieControls } from "../lib/cookieControlsTypes"; import { XSessionSection } from "../settings/components/XSessionSection"; import { ArchiveSourcesSection } from "../settings/components/ArchiveSessionSection"; import { YtdlpCookieSourceForm } from "../settings/components/YtdlpCookieFields"; @@ -178,52 +178,71 @@ function Row({ const DISCLOSURE = "border-t border-border pt-2"; const SUMMARY = "cursor-pointer text-sm font-medium"; +// A section whose read failed says so in its place; the rest still draw. +function SectionError({ what, error }: { what: string; error: string }) { + return ( + <p role="alert" aria-label={`${what} controls error`} className="text-xs text-destructive break-words"> + {error} + </p> + ); +} + // Each service's whole session block, as /settings (and a forum channel's // page) draws it: X's open, so logging in is one press away; the others one -// click away. +// click away. `gen` re-keys the SECTION (never its disclosure) and only for +// the row that was pressed, so a press elsewhere keeps what is being typed here. function Controls({ row, controls, + gen, refetch, }: { row: CookieRow; controls: CookieControls; + gen: number; refetch: () => void; }): ReactNode { if (row.service === "x") { + const x = controls.x; return ( <details open className={DISCLOSURE} aria-label="X controls"> <summary className={SUMMARY}>X account session</summary> <div className="mt-2"> - <XSessionSection {...controls.x} onChange={refetch} cookiesLink={false} /> + {sectionFailed(x) ? ( + <SectionError what="X" error={x.error} /> + ) : ( + <XSessionSection key={gen} {...x} onChange={refetch} cookiesLink={false} /> + )} </div> </details> ); } if (row.service === "archive.today") { + const a = controls.archive; return ( <details className={DISCLOSURE} aria-label="archive.today controls"> <summary className={SUMMARY}>Archive sources: session, host and pace</summary> <div className="mt-2"> - <ArchiveSourcesSection - initial={controls.archive.initial} - session={controls.archive.session} - onChange={refetch} - cookiesLink={false} - /> + {sectionFailed(a) ? ( + <SectionError what="archive.today" error={a.error} /> + ) : ( + <ArchiveSourcesSection key={gen} initial={a.initial} session={a.session} onChange={refetch} cookiesLink={false} /> + )} </div> </details> ); } if (row.family === "forum") { - const f = controls.forums[row.service]; + const forums = controls.forums; + if (sectionFailed(forums)) return <SectionError what={row.label} error={forums.error} />; + const f = forums[row.service]; if (!f || f.channels.length === 0) return null; return ( <details className={DISCLOSURE} aria-label={`${row.label} controls`}> <summary className={SUMMARY}>Forum session, per thread</summary> <div className="mt-2 flex flex-col gap-3"> {f.channels.map((slug) => ( - <section key={slug} data-forum-session="" aria-label={`forum session ${slug}`} className="flex flex-col gap-2"> + <section key={`${slug}:${gen}`} data-forum-session="" aria-label={`forum session ${slug}`} className="flex flex-col gap-2"> <ForumSessionConnect slug={slug} status={f.status} onChange={refetch} /> <p className="text-xs text-muted-foreground"> Thread{" "} @@ -252,17 +271,18 @@ export function CookiesBoard({ initial, controls }: { initial: CookieStatusPaylo // eslint-disable-next-line react-hooks/exhaustive-deps }, [data]); const take = (s: CookieStatusPayload) => setStatus((cur) => (s.readAt >= cur.readAt ? s : cur)); - // A row's press can change what the full controls show (Connect made a - // profile): their slices are read again and the sections drawn afresh. + // A row's press can change what its own controls show (Connect made a + // profile): the slices are read again and THAT row's section is drawn + // afresh; every other section keeps its state (what is typed, what is open). const [ctl, setCtl] = useState(controls); - const [gen, setGen] = useState(0); - const pressed = (s: CookieStatusPayload) => { + const [gens, setGens] = useState<Record<string, number>>({}); + const pressed = (service: string, s: CookieStatusPayload) => { take(s); if (!controls) return; void cookieControlsAction() .then((c) => { setCtl(c); - setGen((g) => g + 1); + setGens((g) => ({ ...g, [service]: (g[service] ?? 0) + 1 })); }) .catch(() => undefined); }; @@ -272,9 +292,9 @@ export function CookiesBoard({ initial, controls }: { initial: CookieStatusPaylo <ItemsFor key={row.service} row={row} - take={pressed} + take={(s) => pressed(row.service, s)} controls={ctl} - gen={gen} + gen={gens[row.service] ?? 0} refetch={() => void refetch()} /> ))} @@ -300,7 +320,7 @@ function ItemsFor({ return ( <> <Row row={row} onStatus={take}> - {controls ? <Controls key={gen} row={row} controls={controls} refetch={refetch} /> : null} + {controls ? <Controls row={row} controls={controls} gen={gen} refetch={refetch} /> : null} </Row> {controls && row.service === "odysee" && ( <li @@ -308,11 +328,15 @@ function ItemsFor({ className="flex flex-col gap-2 rounded-lg border border-border bg-card p-3 sm:p-4" > <h2 className="text-base font-medium">Browser cookies for Rumble, YouTube and Odysee</h2> - <YtdlpCookieSourceForm - cookiesFromBrowser={controls.ytdlp.cookiesFromBrowser} - cookieMode={controls.ytdlp.cookieMode} - onSaved={refetch} - /> + {sectionFailed(controls.ytdlp) ? ( + <SectionError what="yt-dlp cookie" error={controls.ytdlp.error} /> + ) : ( + <YtdlpCookieSourceForm + cookiesFromBrowser={controls.ytdlp.cookiesFromBrowser} + cookieMode={controls.ytdlp.cookieMode} + onSaved={refetch} + /> + )} </li> )} </> diff --git a/editor/app/lib/cookieControls.test.ts b/editor/app/lib/cookieControls.test.ts @@ -17,6 +17,11 @@ test.after(() => corpus.cleanup()); const { getPaths } = await import("yt-dlp-transcript-common/lib/paths"); const { listForumChannels } = await import("./forumChannels"); const { loadCookieControls } = await import("./cookieControls"); +const { sectionFailed } = await import("./cookieControlsTypes"); +function ok<T extends object>(v: T | { error: string }): T { + if (sectionFailed(v)) throw new Error(v.error); + return v as T; +} const { saveYtdlpCookieSourceAction } = await import("../settings/cookieSourceActions"); async function forumChannel(slug: string, url: string) { @@ -48,16 +53,51 @@ test("the controls carry only their slices: X's session, the archive block, yt-d const c = await loadCookieControls(getPaths()); assert.deepEqual(Object.keys(c).sort(), ["archive", "forums", "x", "ytdlp"]); assert.deepEqual(c.ytdlp, { cookiesFromBrowser: "firefox", cookieMode: "always" }); - assert.equal(c.x.initial.hasProfile, false); - assert.equal(typeof c.x.initialMaxCookieAge, "number"); - assert.ok("archiveTodayHost" in c.archive.initial); - assert.deepEqual(Object.keys(c.forums), ["forum.example.test"]); - assert.deepEqual(c.forums["forum.example.test"]?.channels, ["a-thread"]); - assert.equal(c.forums["forum.example.test"]?.status.hasProfile, false); + const x = ok(c.x); + assert.equal(x.initial.hasProfile, false); + assert.equal(typeof x.initialMaxCookieAge, "number"); + assert.ok("archiveTodayHost" in ok(c.archive).initial); + const forums = ok(c.forums); + assert.deepEqual(Object.keys(forums), ["forum.example.test"]); + assert.deepEqual(forums["forum.example.test"]?.channels, ["a-thread"]); + assert.equal(forums["forum.example.test"]?.status.hasProfile, false); // No other settings block rode along. assert.equal(JSON.stringify(c).includes("autoQueue"), false); }); +test("one section's read failing is that section's sentence; the others still read", async () => { + const c = await loadCookieControls(getPaths(), { + getSettings: () => { + throw new Error("settings.json is unreadable"); + }, + }); + for (const k of ["x", "archive", "ytdlp"] as const) { + assert.equal(sectionFailed(c[k]), true, k); + assert.match((c[k] as { error: string }).error, /^Could not read .*settings\.json is unreadable/, k); + } + assert.equal(sectionFailed(c.forums), false); +}); + +test("X's browser spec reaches the client through the privacy rules (lib/xSourceDisplay.ts)", async () => { + const { xSourceForDisplay } = await import("./xSourceDisplay"); + const { resetPrivacyMemo } = await import("yt-dlp-transcript-common/lib/privacy/privacy-server"); + const home = (await import("node:os")).homedir(); + await corpus.writeSettings({ cookiesFromBrowser: `firefox:${home}/zq-profile`, privacy: { displayPaths: "masked" } }); + resetPrivacyMemo(); + const v = xSourceForDisplay({ + source: "browser", + chosen: false, + browserSpec: `firefox:${home}/zq-profile`, + label: `Browser login (firefox:${home}/zq-profile)`, + summary: `No store at ${home}/zq-profile.`, + }); + assert.equal(v.source, "browser"); + for (const s of [v.browserSpec, v.label, v.summary]) assert.equal(String(s).includes(home), false, String(s)); + assert.match(String(v.browserSpec), /^firefox:.*zq-profile$/); + await corpus.writeSettings({ cookiesFromBrowser: "firefox", cookieMode: "always", minFreeDiskGB: 0 }); + resetPrivacyMemo(); +}); + test("yt-dlp's cookie keys save alone: the two keys written, the rest of settings kept, a bad mode is the default", async () => { const fd = new FormData(); fd.set("cookiesFromBrowser", " firefox:fixture-profile "); diff --git a/editor/app/lib/cookieControls.ts b/editor/app/lib/cookieControls.ts @@ -8,7 +8,8 @@ // object, never a corpus walk. The rows themselves are lib/cookieStatus.ts. import { getPaths, type Paths } from "yt-dlp-transcript-common/lib/paths"; -import { getSettings } from "yt-dlp-transcript-common/lib/settings"; +import { getSettings, type SiteSettings } from "yt-dlp-transcript-common/lib/settings"; +import { displayText } from "yt-dlp-transcript-common/lib/privacy/privacy-server"; import { readXSessionStatus, type XSessionStatus } from "yt-dlp-transcript-common/social/xSessionBroker"; import { resolveXCookieSourceFor } from "yt-dlp-transcript-common/social/xBrowserLogin"; import { @@ -24,47 +25,66 @@ import { readForumSessionStatus, type ForumSessionStatus } from "yt-dlp-transcri import { forumServiceKey } from "yt-dlp-transcript-common/lib/serviceCookies"; import { DEFAULT_COOKIE_MODE } from "yt-dlp-transcript-common/lib/cookiePolicy"; import { listForumChannels } from "./forumChannels"; +import { xSourceForDisplay } from "./xSourceDisplay"; -export type CookieControls = { - x: { - initial: XSessionStatus; - initialSource: XCookieSourceView; - initialVisibility: XPostsVisibility; - initialMaxCookieAge: number; - }; - archive: { initial: ArchivesSettings; session: ArchiveSessionStatus }; - ytdlp: { cookiesFromBrowser: string; cookieMode: string }; - // Per forum host (its service key): the session, and its thread channels. - forums: Record<string, { status: ForumSessionStatus; channels: string[] }>; -}; +import { sectionFailed, type CookieControls, type ForumControls, type SectionRead } from "./cookieControlsTypes"; +export { sectionFailed, type CookieControls } from "./cookieControlsTypes"; -export async function loadCookieControls(paths: Paths = getPaths()): Promise<CookieControls> { - const settings = getSettings(); - const [xStatus, resolved, archiveSession, forumChannels] = await Promise.all([ - readXSessionStatus(paths), - resolveXCookieSourceFor(paths, settings), - readArchiveSessionStatus(paths), - listForumChannels(paths).catch(() => []), - ]); - const forums: CookieControls["forums"] = {}; - for (const c of forumChannels) { - const key = forumServiceKey(c.host); - if (!forums[key]) forums[key] = { status: await readForumSessionStatus(paths, c.host), channels: [] }; - forums[key]!.channels.push(c.slug); +async function read<T>(what: string, fn: () => Promise<T>): Promise<SectionRead<T>> { + try { + return await fn(); + } catch (e) { + return { error: displayText(`Could not read ${what}: ${(e as Error).message.split("\n")[0]}`) }; } - for (const f of Object.values(forums)) f.channels.sort(); - return { - x: { - initial: xStatus, - initialSource: xCookieSourceView(resolved), - initialVisibility: xPostsVisibility(settings), - initialMaxCookieAge: xMaxCookieAgeMinutes(settings.social.x), - }, - archive: { initial: settings.archives, session: archiveSession }, - ytdlp: { - cookiesFromBrowser: settings.cookiesFromBrowser ?? "", - cookieMode: settings.cookieMode ?? DEFAULT_COOKIE_MODE, - }, - forums, +} + +export async function loadCookieControls( + paths: Paths = getPaths(), + // Injectable for the tests: a settings read that throws. + deps: { getSettings?: () => SiteSettings } = {}, +): Promise<CookieControls> { + // One parse, shared; a settings read that throws fails the three sections + // that need it, each saying so. + const settings = await read("settings.json", async () => (deps.getSettings ?? getSettings)()); + const need = <T,>(fn: (s: SiteSettings) => Promise<T>) => async (): Promise<T> => { + if (sectionFailed(settings)) throw new Error(settings.error); + return fn(settings); }; + const [x, archive, ytdlp, forums] = await Promise.all([ + read( + "X's session", + need(async (st) => { + const [initial, resolved] = await Promise.all([readXSessionStatus(paths), resolveXCookieSourceFor(paths, st)]); + return { + initial, + // Drawn by the client: its spec and label through settings.privacy. + initialSource: xSourceForDisplay(xCookieSourceView(resolved)), + initialVisibility: xPostsVisibility(st), + initialMaxCookieAge: xMaxCookieAgeMinutes(st.social.x), + }; + }), + ), + read( + "archive.today's session", + need(async (st) => ({ initial: st.archives, session: await readArchiveSessionStatus(paths) })), + ), + read( + "yt-dlp's cookie settings", + need(async (st) => ({ + cookiesFromBrowser: st.cookiesFromBrowser ?? "", + cookieMode: st.cookieMode ?? DEFAULT_COOKIE_MODE, + })), + ), + read("the forum sessions", async () => { + const out: ForumControls = {}; + for (const c of await listForumChannels(paths)) { + const key = forumServiceKey(c.host); + if (!out[key]) out[key] = { status: await readForumSessionStatus(paths, c.host), channels: [] }; + out[key]!.channels.push(c.slug); + } + for (const f of Object.values(out)) f.channels.sort(); + return out; + }), + ]); + return { x, archive, ytdlp, forums }; } diff --git a/editor/app/lib/cookieControlsTypes.ts b/editor/app/lib/cookieControlsTypes.ts @@ -0,0 +1,35 @@ +// THE /cookies CONTROLS' SHAPES — client-safe (the board imports +// `sectionFailed`); the server read is cookieControls.ts. + +import type { XSessionStatus } from "yt-dlp-transcript-common/social/xSessionBroker"; +import type { XCookieSourceView, XPostsVisibility } from "yt-dlp-transcript-common/social/xCookieSource"; +import type { ArchiveSessionStatus } from "yt-dlp-transcript-common/lib/archives/archiveTodaySession"; +import type { ArchivesSettings } from "yt-dlp-transcript-common/lib/archives/settings"; +import type { ForumSessionStatus } from "yt-dlp-transcript-common/social/forumSession"; + +// A section whose read failed carries its error instead of its data: the +// page draws that one section's sentence, never a failed page. +export type SectionRead<T> = T | { error: string }; + +export function sectionFailed<T extends object>(v: SectionRead<T>): v is { error: string } { + return "error" in v && typeof (v as { error?: unknown }).error === "string"; +} + +export type XControls = { + initial: XSessionStatus; + initialSource: XCookieSourceView; + initialVisibility: XPostsVisibility; + initialMaxCookieAge: number; +}; +export type ArchiveControls = { initial: ArchivesSettings; session: ArchiveSessionStatus }; +export type YtdlpControls = { cookiesFromBrowser: string; cookieMode: string }; +// Per forum host (its service key): the session, and its thread channels. +export type ForumControls = Record<string, { status: ForumSessionStatus; channels: string[] }>; + +export type CookieControls = { + x: SectionRead<XControls>; + archive: SectionRead<ArchiveControls>; + ytdlp: SectionRead<YtdlpControls>; + forums: SectionRead<ForumControls>; +}; + diff --git a/editor/app/lib/xSourceDisplay.ts b/editor/app/lib/xSourceDisplay.ts @@ -0,0 +1,21 @@ +// X'S LOGIN SOURCE AS A PAGE MAY DRAW IT (round 2 review): the browser spec +// can name a profile PATH ("firefox:/home/…/x.default"), and XSessionSection +// draws it in the source select's option ("Browser login (…)"), the "In use" +// line and the Check line. So every view of the source a client receives — +// /settings', /cookies', and each X session action's answer — carries the spec, +// its label and the Check summary through settings.privacy's displayText, on +// the server. The client never ACTS on the spec: the select's value is the +// source kind and whether it was chosen, the actions take only that choice, +// and the spec's presence (all "Automatic" needs) survives the masking. + +import { displayText } from "yt-dlp-transcript-common/lib/privacy/privacy-server"; +import type { XCookieSourceView } from "yt-dlp-transcript-common/social/xCookieSource"; + +export function xSourceForDisplay<T extends XCookieSourceView & { summary?: string }>(v: T): T { + return { + ...v, + label: displayText(v.label), + ...(v.browserSpec ? { browserSpec: displayText(v.browserSpec) } : {}), + ...(typeof v.summary === "string" ? { summary: displayText(v.summary) } : {}), + }; +} diff --git a/editor/app/settings/actions.ts b/editor/app/settings/actions.ts @@ -20,10 +20,7 @@ import { } from "yt-dlp-transcript-common/lib/settings"; import { saveSettings } from "./saveSettings"; import { socialLinksForSave } from "yt-dlp-transcript-common/lib/socialLinks"; -import { - DEFAULT_COOKIE_MODE, - isCookieMode, -} from "yt-dlp-transcript-common/lib/cookiePolicy"; +import { cookieKeysPatch } from "./cookieKeys"; import { DEFAULT_SOURCE_VIDEO_QUALITY, isDownloadFormatPreset, @@ -78,13 +75,10 @@ export async function saveSettingsAction( const maxBytesRaw = String( formData.get("maxTranscriptPageBytes") ?? "", ).trim(); - const cookiesFromBrowser = String( - formData.get("cookiesFromBrowser") ?? "", - ).trim(); - const cookieModeRaw = String(formData.get("cookieMode") ?? "").trim(); - const cookieMode = isCookieMode(cookieModeRaw) - ? cookieModeRaw - : DEFAULT_COOKIE_MODE; + // yt-dlp's two cookie keys only when this form changed them: they are + // edited on /cookies too, and a tab left open here must not write its old + // values back (settings/cookieKeys.ts). + const cookieKeys = cookieKeysPatch(formData); const sleepRaw = String( formData.get("sleepBetweenDownloadsSeconds") ?? "", ).trim(); @@ -286,8 +280,7 @@ export async function saveSettingsAction( const next: Partial<SiteSettings> = { adminTitle, maxTranscriptPageBytes: parsed, - cookiesFromBrowser, - cookieMode, + ...cookieKeys, sleepBetweenDownloadsSeconds: sleepParsed, // The whole pacing block as it is, with only the job gaps and the jitter // this form edits. diff --git a/editor/app/settings/components/XSessionSection.tsx b/editor/app/settings/components/XSessionSection.tsx @@ -41,6 +41,8 @@ export function XSessionSection({ cookiesLink = true, }: { initial: XSessionStatus; + // The DISPLAY copy (lib/xSourceDisplay.ts): its spec and label already + // through settings.privacy. Drawn only — the select acts on the source kind. initialSource: XCookieSourceView; // `social.x.visibility`, resolved (absent = "public"); release 17 slice XP. initialVisibility: XPostsVisibility; diff --git a/editor/app/settings/components/YtdlpCookieFields.tsx b/editor/app/settings/components/YtdlpCookieFields.tsx @@ -12,6 +12,7 @@ import { useActionState, useEffect } from "react"; import { Field, SeededSelect } from "../../components/forms/Field"; import type { SeedSource } from "../../lib/formState"; import { saveYtdlpCookieSourceAction, type YtdlpCookieSourceResult } from "../cookieSourceActions"; +import { SEEDED_SUFFIX } from "../cookieKeys"; export function YtdlpCookieFields({ state, @@ -24,6 +25,10 @@ export function YtdlpCookieFields({ }) { return ( <> + {/* What this form was drawn with: a save writes a key only when it + differs (settings/cookieKeys.ts), so a stale tab writes nothing back. */} + <input type="hidden" name={`cookiesFromBrowser${SEEDED_SUFFIX}`} value={cookiesFromBrowser} readOnly /> + <input type="hidden" name={`cookieMode${SEEDED_SUFFIX}`} value={cookieMode} readOnly /> <Field label="Cookies from browser" name="cookiesFromBrowser" diff --git a/editor/app/settings/cookieKeys.test.ts b/editor/app/settings/cookieKeys.test.ts @@ -0,0 +1,44 @@ +// yt-dlp's two cookie keys written only when the form changed them +// (cookieKeys.ts) — the stale-tab case: a /settings tab drawn before a change +// on /cookies saves something else and must not write the old values back. +// +// Run with: pnpm -C editor exec tsx --test app/settings/cookieKeys.test.ts + +import test from "node:test"; +import assert from "node:assert/strict"; +import { cookieKeysPatch, submittedCookieKeys } from "./cookieKeys"; + +const form = (o: Record<string, string>) => { + const f = new FormData(); + for (const [k, v] of Object.entries(o)) f.set(k, v); + return f; +}; + +test("a form that did not touch the keys writes neither (the stale tab)", () => { + const stale = form({ + cookiesFromBrowser: "firefox", + "cookiesFromBrowser.seeded": "firefox", + cookieMode: "when-required", + "cookieMode.seeded": "when-required", + }); + assert.deepEqual(cookieKeysPatch(stale), {}); +}); + +test("a changed key is written, and only it", () => { + assert.deepEqual( + cookieKeysPatch(form({ cookiesFromBrowser: " chrome ", "cookiesFromBrowser.seeded": "firefox", cookieMode: "always", "cookieMode.seeded": "always" })), + { cookiesFromBrowser: "chrome" }, + ); + assert.deepEqual( + cookieKeysPatch(form({ cookiesFromBrowser: "firefox", "cookiesFromBrowser.seeded": "firefox", cookieMode: "defer", "cookieMode.seeded": "always" })), + { cookieMode: "defer" }, + ); +}); + +test("a form without the seeded fields writes both, normalised as before", () => { + assert.deepEqual(cookieKeysPatch(form({ cookiesFromBrowser: " firefox ", cookieMode: "sometimes" })), { + cookiesFromBrowser: "firefox", + cookieMode: "when-required", + }); + assert.deepEqual(submittedCookieKeys(form({})), { cookiesFromBrowser: "", cookieMode: "when-required" }); +}); diff --git a/editor/app/settings/cookieKeys.ts b/editor/app/settings/cookieKeys.ts @@ -0,0 +1,39 @@ +// YT-DLP'S TWO COOKIE KEYS FROM A FORM, WRITTEN ONLY WHEN CHANGED (round 2 +// review). `cookiesFromBrowser` and `cookieMode` are edited in two places — +// /settings' form and the /cookies screen's own — so a tab left open on one +// must not write its old values back over a change made on the other. Each +// form carries the value it was drawn with (`<key>.seeded`, hidden: +// components/YtdlpCookieFields.tsx); a key is in the patch only when what was +// submitted differs from that. A form without the seeded field (an older page) +// writes both, as before. + +import { DEFAULT_COOKIE_MODE, isCookieMode, type CookieMode } from "yt-dlp-transcript-common/lib/cookiePolicy"; + +export const SEEDED_SUFFIX = ".seeded"; + +type Form = { get(name: string): FormDataEntryValue | null }; + +function mode(v: unknown): CookieMode { + const s = String(v ?? "").trim(); + return isCookieMode(s) ? s : DEFAULT_COOKIE_MODE; +} + +// What was submitted, normalised as /settings' Save always has. +export function submittedCookieKeys(form: Form): { cookiesFromBrowser: string; cookieMode: CookieMode } { + return { + cookiesFromBrowser: String(form.get("cookiesFromBrowser") ?? "").trim(), + cookieMode: mode(form.get("cookieMode")), + }; +} + +export function cookieKeysPatch(form: Form): Partial<{ cookiesFromBrowser: string; cookieMode: CookieMode }> { + const now = submittedCookieKeys(form); + const seededSpec = form.get(`cookiesFromBrowser${SEEDED_SUFFIX}`); + const seededMode = form.get(`cookieMode${SEEDED_SUFFIX}`); + return { + ...(seededSpec === null || String(seededSpec).trim() !== now.cookiesFromBrowser + ? { cookiesFromBrowser: now.cookiesFromBrowser } + : {}), + ...(seededMode === null || mode(seededMode) !== now.cookieMode ? { cookieMode: now.cookieMode } : {}), + }; +} diff --git a/editor/app/settings/cookieSourceActions.ts b/editor/app/settings/cookieSourceActions.ts @@ -6,8 +6,9 @@ // else. The /cookies screen's form (components/YtdlpCookieFields.tsx). import { saveSettings } from "./saveSettings"; -import { DEFAULT_COOKIE_MODE, isCookieMode, type CookieMode } from "yt-dlp-transcript-common/lib/cookiePolicy"; +import type { CookieMode } from "yt-dlp-transcript-common/lib/cookiePolicy"; import { formValues, type FormState } from "../lib/formState"; +import { cookieKeysPatch, submittedCookieKeys } from "./cookieKeys"; export type YtdlpCookieSourceResult = FormState<{ cookiesFromBrowser: string; cookieMode: CookieMode }>; @@ -16,11 +17,12 @@ export async function saveYtdlpCookieSourceAction( formData: FormData, ): Promise<YtdlpCookieSourceResult> { const values = formValues(formData); - const cookiesFromBrowser = String(formData.get("cookiesFromBrowser") ?? "").trim(); - const raw = String(formData.get("cookieMode") ?? "").trim(); - const cookieMode = isCookieMode(raw) ? raw : DEFAULT_COOKIE_MODE; + const { cookiesFromBrowser, cookieMode } = submittedCookieKeys(formData); + // Only a key this form changed: a tab left open must not write back over + // /settings' newer value (cookieKeys.ts). + const patch = cookieKeysPatch(formData); try { - await saveSettings({ cookiesFromBrowser, cookieMode }); + if (Object.keys(patch).length) await saveSettings(patch); } catch (e) { return { ok: false, error: (e as Error).message, values }; } diff --git a/editor/app/settings/page.tsx b/editor/app/settings/page.tsx @@ -8,6 +8,7 @@ import { resolveXCookieSourceFor } from "yt-dlp-transcript-common/social/xBrowse import { xCookieSourceView } from "yt-dlp-transcript-common/social/xCookieSource"; import { xPostsVisibility } from "yt-dlp-transcript-common/lib/postsVisibility"; import { SettingsForm } from "./components/SettingsForm"; +import { xSourceForDisplay } from "../lib/xSourceDisplay"; import { XSessionSection } from "./components/XSessionSection"; import { xMaxCookieAgeMinutes } from "yt-dlp-transcript-common/social/xCookieSource"; import { ArchiveSourcesSection } from "./components/ArchiveSessionSection"; @@ -40,8 +41,9 @@ export default async function SettingsPage() { // xSessionActions.ts). The source is resolved here, not read: with no stored // choice it depends on cookiesFromBrowser and the profile. const xSession = await readXSessionStatus(paths); - const xSource = xCookieSourceView( - await resolveXCookieSourceFor(paths, settings), + // Drawn by the client: its spec and label through settings.privacy. + const xSource = xSourceForDisplay( + xCookieSourceView(await resolveXCookieSourceFor(paths, settings)), ); return ( diff --git a/editor/app/settings/xSessionActions.ts b/editor/app/settings/xSessionActions.ts @@ -42,6 +42,7 @@ import { xPostsVisibility } from "yt-dlp-transcript-common/lib/postsVisibility"; import { saveSettings } from "./saveSettings"; import { fakeXProfileChromium } from "yt-dlp-transcript-common/social/fakeXProfileBrowser"; import { withCookieAction } from "../lib/cookieRefreshGuard"; +import { xSourceForDisplay } from "../lib/xSourceDisplay"; // `social.x` is ONE value to saveSettings, whose merge is one level deep: a // patch naming `social: { x }` replaces the whole X block. So each X choice is @@ -59,8 +60,9 @@ export type XSessionActionResult = | { ok: true; status: XSessionStatus; source: XCookieSourceView; browser?: string } | { ok: false; error: string }; +// Drawn by the client, so through settings.privacy (lib/xSourceDisplay.ts). async function sourceNow(): Promise<XCookieSourceView> { - return xCookieSourceView(await resolveXCookieSourceFor(getPaths(), getSettings())); + return xSourceForDisplay(xCookieSourceView(await resolveXCookieSourceFor(getPaths(), getSettings()))); } export async function xSessionStatusAction(): Promise<XSessionStatus> { @@ -149,7 +151,7 @@ export type XLoginCheckResult = export async function checkXLoginAction(): Promise<XLoginCheckResult> { try { - return { ok: true, login: await readXLoginStatus(getPaths(), getSettings()) }; + return { ok: true, login: xSourceForDisplay(await readXLoginStatus(getPaths(), getSettings())) }; } catch (e) { return { ok: false, error: (e as Error).message }; } diff --git a/editor/e2e/cookies-screen.spec.ts b/editor/e2e/cookies-screen.spec.ts @@ -12,7 +12,7 @@ // The headed Connects (archive.today, a forum, X with no profile) open a // window on the machine: they are looked at, never pressed. -import { mkdir, utimes, writeFile } from "node:fs/promises"; +import { mkdir, readFile, utimes, writeFile } from "node:fs/promises"; import { test, expect, type Page } from "@playwright/test"; import { generateReport, resetData, resolvePath, testPaths, writeChannelConfig, writeSettings } from "./helpers"; import { baseUrl } from "./baseUrl"; @@ -243,7 +243,7 @@ async function controlsIn(page: Page, selector: string) { for (const el of els) { for (const e of el.querySelectorAll("[aria-label]")) labels.add(e.getAttribute("aria-label") ?? ""); // A server-action form's own hidden fields ($ACTION_…) are React's, not controls. - for (const e of el.querySelectorAll("input[name], select[name]")) { + for (const e of el.querySelectorAll("input[name]:not([type=hidden]), select[name]")) { const n = e.getAttribute("name") ?? ""; if (!n.startsWith("$")) names.add(n); } @@ -298,7 +298,7 @@ test("every cookie control on /settings and on a forum channel's page is on /coo await form.locator('select[name="cookieMode"]').selectOption("always"); await form.getByRole("button", { name: "save yt-dlp cookies" }).click(); await expect(page.getByRole("status", { name: "yt-dlp cookies saved" })).toHaveText("Saved."); - const settingsJson = JSON.parse(await (await import("node:fs/promises")).readFile(testPaths().settingsFile, "utf8")) as { cookieMode?: string; cookiesFromBrowser?: string }; + const settingsJson = JSON.parse(await readFile(testPaths().settingsFile, "utf8")) as { cookieMode?: string; cookiesFromBrowser?: string }; expect(settingsJson.cookieMode).toBe("always"); expect(settingsJson.cookiesFromBrowser).toMatch(/^firefox:/); }); @@ -330,3 +330,50 @@ test("Connect X account and Forget session from /cookies, through the fake brows await expect(page.getByLabel("x session state")).toHaveText("connected", { timeout: 20_000 }); await expect(page.getByRole("button", { name: "X Refresh cookies" })).toBeVisible({ timeout: 10_000 }); }); + +// A /settings tab left open must not write its old cookie values back over a +// change made on /cookies (round 2 review): its Save writes the two keys only +// when IT changed them. +test("a stale /settings tab's Save keeps the cookie mode /cookies set", async ({ page, browser }) => { + await seed(); + const ctx = await browser.newContext(); + try { + const stale = await ctx.newPage(); + await stale.goto(`${baseUrl}/settings`); + await expect(stale.locator('form select[name="cookieMode"]')).toHaveValue("when-required"); + + await page.goto("/cookies"); + const form = page.getByLabel("yt-dlp cookie source"); + await form.locator('select[name="cookieMode"]').selectOption("defer"); + await form.locator('input[name="cookiesFromBrowser"]').fill("firefox"); + await form.getByRole("button", { name: "save yt-dlp cookies" }).click(); + await expect(page.getByRole("status", { name: "yt-dlp cookies saved" })).toHaveText("Saved."); + + // The old tab saves something else. + await stale.getByRole("button", { name: "Save settings" }).click(); + await expect(stale.getByText("Saved.", { exact: true })).toBeVisible(); + const saved = JSON.parse(await readFile(testPaths().settingsFile, "utf8")) as { cookieMode?: string; cookiesFromBrowser?: string }; + expect(saved.cookieMode).toBe("defer"); + expect(saved.cookiesFromBrowser).toBe("firefox"); + } finally { + await ctx.close(); + } +}); + +// A row's press redraws only that row's controls: what is open or typed in +// another row's stays (round 2 review). +test("a press in one row keeps another row's open disclosure and what is typed in it", async ({ page }) => { + await seed(); + await page.goto("/cookies"); + const archive = page.getByLabel("archive.today controls"); + await archive.locator("summary").click(); + const gap = archive.getByLabel("archive.today gap seconds"); + await gap.fill("77"); + await page.getByRole("button", { name: "X Refresh cookies" }).click(); + await expect(page.getByRole("status", { name: "X press result" })).toHaveText("Cookies refreshed.", { timeout: 20_000 }); + await expect(page.getByLabel("X cookie age", { exact: true })).toHaveText(/^jar written just now/); + // Give the controls' re-read (after the press) its moment, then look. + await page.waitForTimeout(1500); + await expect(archive).toHaveAttribute("open", ""); + await expect(gap).toHaveValue("77"); +}); diff --git a/editor/e2e/privacy-audit.spec.ts b/editor/e2e/privacy-audit.spec.ts @@ -87,6 +87,9 @@ const SLICE_2 = new Set<string>([ "/workers", ]); +// Routes whose cookiesFromBrowser INPUT draws the saved spec as typed. +const VALUE_ROUTES = new Set<string>(["/settings", "/cookies"]); + const lit = (text: string, from: string, ci = false): Literal => ({ bytes: ci ? foldAscii(Buffer.from(text, "utf8")) : Buffer.from(text, "utf8"), ci, @@ -105,6 +108,11 @@ function settings(privacy: Record<string, unknown> | null) { const s = JSON.parse(readFileSync(paths.settingsFile, "utf8")) as Record<string, unknown>; delete s.privacy; if (privacy) s.privacy = privacy; + // A browser spec that names a profile PATH under the home dir (the path does + // not exist: nothing reads a browser store). X's login source draws it on + // /settings and /cookies — through the privacy rules, never raw — while the + // yt-dlp field that edits it shows the saved value as it is (VALUE_ROUTES). + s.cookiesFromBrowser = `firefox:${join(HOME, ".zq-audit-firefox", "zq.default")}`; s.storage = { locations: [{ id: "zq-drive", label: "Zq Drive", root: DRIVE_ROOT, autoRepoint: false }], defaultLocationId: "", @@ -261,7 +269,9 @@ test("masked, privacy on: no hit outside the slice-2 routes", async ({ browser } await settle(); const result = await audit(browser); const hits = failingHits(result); - const outside = hits.filter((h) => !SLICE_2.has(h.route)); + // The cookiesFromBrowser field's own value is a saved form value, raw by + // ruling (round 2 review): only that kind of hit, only on its two routes. + const outside = hits.filter((h) => !SLICE_2.has(h.route) && !(h.where === "value" && VALUE_ROUTES.has(h.route))); const byRoute = new Map<string, { live: number; ssr: number }>(); for (const h of hits) { const c = byRoute.get(h.route) ?? { live: 0, ssr: 0 };