fix(auth): a Google connect names its tab's account too, and a refused tab says why

- /auth/google/connect is a navigation and carries no headers: the tab names the account it
  was built for in `expect`, checked by the same comparison as the request header
  (built_for_another_account); a mismatch lands on /?account=changed
- the link marker names the OAuth state of its own flow: an older flow coming back no longer
  spends the marker of the connect still open (which then returned as a plain sign-in)
- a 401 account_changed reloads the tab with a one-time flag, and the reloaded tab says it
  now shows the account signed in
- a refused switch to a suspended or not-yet-approved account says so in the signed-in
  app's words, naming the address a request was recorded for
- the prefs merge locks FOR NO KEY UPDATE, so a transaction that only added a row referring
  to the account does not hold the save up; a test pins the lock
- giving up a lost page closes a channel page open over it
- e2e README names the chromium-only specs
This commit is contained in:
2026-10-21 02:05:33 +02:00
parent 94418a087e
commit ef99f7b5c7
19 changed files with 487 additions and 121 deletions
+2 -1
View File
@@ -25,7 +25,8 @@ that one error again and passes every other failure straight on. Don't run two e
same machine at once.
**Browsers** — every flow runs in three projects: `chromium` (Desktop Chrome), `webkit` (Desktop
Safari) and `ipad` (iPad gen 7 landscape: 1080×810, touch, mobile). Install the engines once per
Safari) and `ipad` (iPad gen 7 landscape: 1080×810, touch, mobile) — except `a11y`, `member` and
`devices`, which run on chromium only (`CHROMIUM_ONLY`; why is in the `docs/gates.md` row). Install the engines once per
machine with `npx playwright install chromium webkit`; run one project with
`npx playwright test --project=ipad`. WebKit catches what every iOS browser inherits from the engine
(JS, CSS/layout, event order). It does **not** reproduce iPad media refusals: Playwright's WebKit
+10 -16
View File
@@ -7,7 +7,8 @@ import { api, setUnauthorizedHandler, type Me } from "./lib/api";
import { notifyActionError } from "./lib/actionErrors";
import { setLanguage, type LangCode } from "./i18n";
import { clearParams } from "./lib/urlState";
import { refusedSwitchNotice } from "./lib/entryUrl";
import { reloadAfterRefusal } from "./lib/entryUrl";
import { useAccountSwitchNotice } from "./lib/useAccountSwitchNotice";
import {
PREF_KEY,
saveLayoutLocal,
@@ -231,26 +232,19 @@ export default function App() {
if (signedIn) clearParams("access", "verify", "reset");
}, [signedIn]);
// A sign-in as someone else that the server refused (an account not approved, or suspended) came
// back here as the account still signed in — say so, once.
const switchAnswered = useRef(false);
useEffect(() => {
if (!signedIn || switchAnswered.current) return;
switchAnswered.current = true;
const notice = refusedSwitchNotice();
if (notice) notify({ level: notice.level, message: t(notice.key) });
}, [signedIn, t]);
// A sign-in as someone else that the server refused, or a reload as another account: say so, once.
useAccountSwitchNotice(signedIn);
// Any request that 401s means the session ended server-side. If we were signed in (cached
// `me` is a user object), reload to the login page at once (also covers any click that hits
// the API). Guarded on a cached user so a stray 401 while logged out (cached `me` is null)
// can't loop the public landing.
// can't loop the public landing. A tab showing another account than the one signed in now
// reloads as that one instead, and says why (`reloadAfterRefusal`).
useEffect(() => {
setUnauthorizedHandler(() => {
if (queryClient.getQueryData(qk.me())) {
queryClient.clear();
window.location.reload();
}
setUnauthorizedHandler((err) => {
if (!queryClient.getQueryData(qk.me())) return;
queryClient.clear();
reloadAfterRefusal(err);
});
return () => setUnauthorizedHandler(null);
}, [queryClient]);
@@ -370,6 +370,20 @@ describe("NavigationProvider · a page the account cannot open", () => {
await settle();
expect(result.current.page).toBe("feed");
});
it("closes a channel page open over the lost page, on screen and in the entry", async () => {
window.history.replaceState({ sfPage: "users" }, "", "/?page=users");
const { result } = render();
act(() => result.current.openChannel("UC1", "One"));
expect(window.location.search).toContain("chan=UC1");
act(() => {
qc.setQueryData(qk.me(), member);
});
await settle();
expect(result.current.channelView).toBeNull();
expect(window.location.search).toBe("");
expect(window.history.state?._chan).toBeUndefined();
});
});
describe("NavigationProvider · leaving a sub-view whose entry is the oldest of this document", () => {
+16 -12
View File
@@ -67,16 +67,6 @@ export function NavigationProvider({ children }: { children: ReactNode }) {
// and the address bar (stamped from it below) agree.
const me = useMe();
const page = reachablePage(chosenPage, me);
// A page this account can no longer open (a role taken away, a module switched off mid-session)
// is given up, not kept behind the feed: kept, the address bar would go on naming it, a click on
// Feed would be a no-op (setPage's same-page guard sees the feed already on screen), and a later
// grant would switch the page by itself. Adjusted during render; the history entry and the
// remembered page follow in the effect below.
const [givenUp, setGivenUp] = useState(0);
if (page !== chosenPage) {
setPageState(page);
setGivenUp((n) => n + 1);
}
// Ephemeral: not persisted and not in the URL, so a reload returns to the normal feed (a search
// spends quota, so we never auto-replay it) — UNLESS it was zero-quota scrape-sourced, which rides
// in history.state and is free to re-fetch. The popstate handler derives it from history.state so
@@ -92,6 +82,18 @@ export function NavigationProvider({ children }: { children: ReactNode }) {
const [channelView, setChannelView] = useState<ChannelView | null>(() =>
channelViewFrom(window.history.state, window.location.search),
);
// A page this account can no longer open (a role taken away, a module switched off mid-session)
// is given up, not kept behind the feed: kept, the address bar would go on naming it, a click on
// Feed would be a no-op (setPage's same-page guard sees the feed already on screen), and a later
// grant would switch the page by itself. A channel page open over it closes with it, as on any
// page switch. Adjusted during render; the history entry and the remembered page follow in the
// effect below.
const [givenUp, setGivenUp] = useState(0);
if (page !== chosenPage) {
setPageState(page);
setChannelView(null);
setGivenUp((n) => n + 1);
}
// Latest-value refs so the STABLE action callbacks can read the latest state without depending on
// it — a dep would recreate them on every navigation and re-render every actions consumer (e.g.
@@ -211,12 +213,14 @@ export function NavigationProvider({ children }: { children: ReactNode }) {
}, [signedIn, page, objectTitle, i18n.language, t]);
// The page given up above is the feed, and the current entry says so (replaced, not pushed: no
// step was taken). Its own keys go with it, as on any page switch.
// step was taken). Its own keys go with it, and the channel page closed with it, as on any page
// switch — left in the entry, a reload would reopen what the screen no longer shows.
useEffect(() => {
if (!givenUp) return;
setAccountRaw(PAGE_KEY, "feed");
const { _chan: _closedChan, _chanName: _closedName, ...rest } = window.history.state ?? {};
window.history.replaceState(
{ ...window.history.state, sfPage: "feed" },
{ ...rest, sfPage: "feed" },
"",
urlWithParams(pageRootParams("feed")),
);
+3
View File
@@ -32,6 +32,9 @@
"signOut": "Sign out",
"signInAsOther": "Sign in as someone else",
"switchNotApproved": "That Google account isn't approved for this instance yet, so you're still signed in as before.",
"switchSuspended": "That account is suspended, so you're still signed in as before.",
"switchRequested": "We recorded an access request for {{email}}. Until an admin approves it, you're still signed in as before.",
"tabSwitched": "This tab was showing another account, so it reloaded as the one signed in now.",
"googleAddress": "Google account: {{email}}",
"activity": "Activity"
},
+3
View File
@@ -32,6 +32,9 @@
"signOut": "Kijelentkezés",
"signInAsOther": "Belépés más fiókkal",
"switchNotApproved": "Ez a Google-fiók még nincs jóváhagyva ezen a példányon, ezért továbbra is az eddigi fiókkal vagy belépve.",
"switchSuspended": "Az a fiók fel van függesztve, ezért továbbra is az eddigi fiókkal vagy belépve.",
"switchRequested": "Rögzítettük a hozzáférési kérelmet ehhez a címhez: {{email}}. Amíg egy admin jóvá nem hagyja, továbbra is az eddigi fiókkal vagy belépve.",
"tabSwitched": "Ez a fül egy másik fiókot mutatott, ezért újratöltött az éppen bejelentkezett fiókkal.",
"googleAddress": "Google-fiók: {{email}}",
"activity": "Napló"
},
@@ -0,0 +1,111 @@
// @vitest-environment jsdom
//
// "Sign in as someone else" with a Google account the server will not sign in (not approved, or
// suspended) comes back to the account still signed in here, with the flags the sign-in page reads;
// a tab the server refused because another account signed in under it reloads with a flag of its
// own. Each says so in the signed-in app's words, not the sign-in page's.
import { afterEach, describe, expect, it, vi } from "vitest";
import {
ACCOUNT_CHANGED_FLAG,
accountChangedUrl,
accountSwitchNotice,
clearEntryUrl,
reloadAfterRefusal,
} from "./entryUrl";
const notice = (search: string, hash = "") =>
accountSwitchNotice(new URLSearchParams(search), new URLSearchParams(hash));
afterEach(() => {
window.history.replaceState(null, "", "/");
vi.unstubAllGlobals();
});
describe("a switch of account, told to the account signed in", () => {
it("names the address a request was recorded for", () => {
expect(notice("", "access=requested&email=b%2Btag%40example.com")).toEqual({
level: "info",
key: "header.account.switchRequested",
values: { email: "b+tag@example.com" },
});
});
it("names the address the request lives under when that is another spelling", () => {
expect(notice("", "access=requested&email=bob%40x.com&linked=b.ob%40x.com")?.values).toEqual({
email: "b.ob@x.com",
});
});
it("says the account is not approved, and nothing changed here", () => {
expect(notice("", "access=denied")).toEqual({
level: "warning",
key: "header.account.switchNotApproved",
});
});
it("says that account is suspended, not this one", () => {
expect(notice("?login=suspended")).toEqual({
level: "warning",
key: "header.account.switchSuspended",
});
});
it("says the tab reloaded as the account signed in now", () => {
expect(notice(`?page=stats&${ACCOUNT_CHANGED_FLAG}`)).toEqual({
level: "info",
key: "header.account.tabSwitched",
});
});
it("says nothing on an ordinary load", () => {
expect(notice("?page=stats", "")).toBeNull();
});
});
describe("the reload of a tab another account signed in under", () => {
it("stays on its page and carries the flag", () => {
window.history.replaceState(null, "", "/?page=stats&chan=UC1#x=1");
const url = new URL(accountChangedUrl(), "http://h");
expect(url.pathname).toBe("/");
expect(Object.fromEntries(url.searchParams)).toEqual({
page: "stats",
chan: "UC1",
account: "changed",
});
expect(url.hash).toBe("#x=1");
});
it("drops the flag once read, so a later reload does not say it again", () => {
window.history.replaceState(null, "", `/?page=stats&${ACCOUNT_CHANGED_FLAG}`);
clearEntryUrl();
expect(window.location.search).toBe("?page=stats");
});
});
describe("a tab whose session the server refused", () => {
const stubLocation = () => {
const loc = {
pathname: "/",
search: "?page=stats",
hash: "",
replace: vi.fn(),
reload: vi.fn(),
};
vi.stubGlobal("location", loc);
return loc;
};
it("reloads as the account signed in now, saying why, when it showed another", () => {
const loc = stubLocation();
reloadAfterRefusal({ detailData: { code: "refused", reason: "account_changed" } });
expect(loc.replace).toHaveBeenCalledWith(`/?page=stats&${ACCOUNT_CHANGED_FLAG}`);
expect(loc.reload).not.toHaveBeenCalled();
});
it("reloads plainly when the session ended", () => {
const loc = stubLocation();
reloadAfterRefusal({ detailData: { code: "refused", reason: "not_authenticated" } });
expect(loc.reload).toHaveBeenCalled();
expect(loc.replace).not.toHaveBeenCalled();
});
});
+6 -5
View File
@@ -223,10 +223,11 @@ function reportFailure(err: HttpError, quiet: boolean): void {
if (RETRIABLE_GATEWAY.has(err.status)) {
markConnectivityLost();
} else if (err.status === 401) {
// Session ended server-side (e.g. the account was suspended or deleted mid-visit). Let the app
// shell decide what to do (drop to the login page if we were signed in). Not a modal — but
// Session ended server-side (e.g. the account was suspended or deleted mid-visit), or this tab
// shows another account than the one signed in now. Let the app shell decide what to do (drop to
// the login page, or reload as the account signed in, if we were signed in). Not a modal — but
// handled all the same, so not the caller's to toast either.
onUnauthorized?.();
onUnauthorized?.(err);
reported.add(err);
} else if (quiet) {
/* caller handles the error inline — no global modal */
@@ -256,8 +257,8 @@ export interface ReqConfig {
// page. The handler itself guards against firing when we were never signed in, so it's safe to
// call for every 401. (The bootstrap /api/me probe no longer 401s — it returns 200 with a null
// user when logged out — but other protected endpoints still do.)
let onUnauthorized: (() => void) | null = null;
export function setUnauthorizedHandler(fn: (() => void) | null): void {
let onUnauthorized: ((err: HttpError) => void) | null = null;
export function setUnauthorizedHandler(fn: ((err: HttpError) => void) | null): void {
onUnauthorized = fn;
}
@@ -7,7 +7,10 @@ import { describe, expect, it } from "vitest";
// one without a word.
const read = (path: string) => readFileSync(new URL(path, import.meta.url), "utf-8");
const AUTH = read("../../../../backend/app/auth.py");
const ROUTES = read("../../../../backend/app/routes/auth.py");
const CORE = read("./core.ts");
const CONNECT = read("../googleConnect.ts");
const ENTRY = read("../entryUrl.ts");
describe("the account a tab was built for", () => {
it("is the header the server checks", () => {
@@ -16,4 +19,17 @@ describe("the account a tab was built for", () => {
expect(backend).toBeTruthy();
expect(backend).toBe(frontend?.toLowerCase());
});
it("rides a Google connect as the query parameter the route reads", () => {
// A navigation carries no headers; a rename on one side would leave the connect unchecked.
expect(CONNECT).toMatch(/params\.set\("expect", account\)/);
expect(ROUTES).toMatch(/^ {4}expect: str \| None = None,$/m);
});
it("lands a refused navigation where the reloaded tab says why", () => {
const landing = /^ACCOUNT_CHANGED_LANDING = "\/\?([^"]+)"$/m.exec(ROUTES)?.[1];
const flag = /^export const ACCOUNT_CHANGED_FLAG = "([^"]+)";$/m.exec(ENTRY)?.[1];
expect(landing).toBeTruthy();
expect(landing).toBe(flag);
});
});
+50 -11
View File
@@ -12,7 +12,7 @@
// Secret tokens (verify, reset) ride the FRAGMENT so they never reach the server, a proxy log or a
// Referer header (SB3); so does the Google access-request notice (`access`, and the addresses it
// names) — an email in a query string lands in every reverse-proxy access log. Plain status flags
// with nothing personal in them (login, deleted) ride the query string.
// with nothing personal in them (login, deleted, account) ride the query string.
import type { NotifLevel } from "./notifications";
@@ -24,7 +24,31 @@ export const entryHash = new URLSearchParams(window.location.hash.replace(/^#/,
* in its old shape — it rides the fragment now). Deliberately NOT `link`,
* `oauth`, `admin` or the setup `token` — those have their own readers, and some of them (the setup
* wizard, the lazily-mounted module views) do not run until several commits later. */
const ONE_TIME_QUERY = ["login", "deleted", "access"] as const;
const ONE_TIME_QUERY = ["login", "deleted", "access", "account"] as const;
/** The flag a tab reloads with when it was showing another account than the one signed in now (the
* server refused it: `account_changed`), and where a navigation the server refused for that lands
* (backend `ACCOUNT_CHANGED_LANDING`). A reload wipes any toast, so the reason rides the URL. */
export const ACCOUNT_CHANGED_FLAG = "account=changed";
/** This page again, carrying `ACCOUNT_CHANGED_FLAG`: the tab boots as the account signed in now and
* says why, on the page it was on. */
export function accountChangedUrl(): string {
const params = new URLSearchParams(window.location.search);
const [key, value] = ACCOUNT_CHANGED_FLAG.split("=") as [string, string];
params.set(key, value);
return `${window.location.pathname}?${params.toString()}${window.location.hash}`;
}
/** Reload a tab whose session the server refused (a 401). Showing another account than the one
* signed in now (`account_changed`: a sign-in as someone else in another tab), it boots as that one
* and says why — a Sign out that silently left someone else signed in would read as broken. Any
* other refusal means the session ended: a plain reload lands on the sign-in page. */
export function reloadAfterRefusal(err: { detailData?: unknown }): void {
if ((err.detailData as { reason?: string } | undefined)?.reason === "account_changed")
window.location.replace(accountChangedUrl());
else window.location.reload();
}
/** Strip the one-time entry state from the address bar, so a token doesn't linger in history or get
* re-sent on a reload. ONE owner calls this (useVerifyEntry, which App mounts unconditionally) — a
@@ -61,18 +85,33 @@ export function clearEntryUrl(): void {
);
}
/** What a sign-in as someone else that did not happen says to the account still signed in here. The
* callback answers a Google account that is not approved, or is suspended, without replacing the
* session, and with the flags the sign-in page reads; the signed-in app read none of them, so the
* person came back as before without a word. A request recorded on the way says so. */
export function refusedSwitchNotice(
export interface AccountNotice {
level: NotifLevel;
key: string;
values?: Record<string, string>;
}
/** What the entry URL says to the account signed in here about a switch of account. A sign-in as
* someone else that did not happen: the callback answers a Google account that is not approved, or
* is suspended, without replacing the session, and with the flags the sign-in page reads — the
* signed-in app read none of them, so the person came back as before without a word. Its own copy,
* not the sign-in page's: beside this account's avatar, "this account is suspended" would read as
* this one. A request recorded on the way names the address it lives under (`linked`, when that is
* not the one Google returned). And a tab that reloaded because another account signed in under it
* says that it did. */
export function accountSwitchNotice(
search: URLSearchParams = entrySearch,
hash: URLSearchParams = entryHash,
): { level: NotifLevel; key: string } | null {
): AccountNotice | null {
if (search.get("account") === "changed")
return { level: "info", key: "header.account.tabSwitched" };
if (search.get("login") === "suspended")
return { level: "warning", key: "welcome.auth.suspended" };
return { level: "warning", key: "header.account.switchSuspended" };
const access = hash.get("access");
if (access === "requested") return { level: "info", key: "welcome.auth.accessRequested" };
if (access === "denied") return { level: "warning", key: "header.account.switchNotApproved" };
const email = hash.get("linked") || hash.get("email");
if (access === "requested" && email)
return { level: "info", key: "header.account.switchRequested", values: { email } };
if (access === "requested" || access === "denied")
return { level: "warning", key: "header.account.switchNotApproved" };
return null;
}
+10 -2
View File
@@ -1,13 +1,21 @@
// Every in-app Google round-trip starts at one backend route (auth.py `google_connect`): attaching a
// Google sign-in to the account (`identity`), or granting YouTube access on top (`read`, `write`).
// The page navigates away to Google and comes back through the shared callback, which lands on
// `?link=…` (App.tsx) for `identity` and on the app itself for a grant.
// `?link=…` (App.tsx) for `identity` and on the app itself for a grant. A navigation carries no
// headers, so it names the account the tab was built for in the query (`expect`) — the check every
// request gets (`identityHeaders`): a tab still showing the account signed in before would otherwise
// attach Google to the one signed in now.
import { claimedAccount } from "./storage";
export const GOOGLE_ACCESS = ["identity", "read", "write"] as const;
export type GoogleAccess = (typeof GOOGLE_ACCESS)[number];
export function googleConnectUrl(access: GoogleAccess): string {
return `/auth/google/connect?access=${access}`;
const params = new URLSearchParams({ access });
const account = claimedAccount();
if (account) params.set("expect", account);
return `/auth/google/connect?${params.toString()}`;
}
/** Leave for Google's sign-in or consent screen. */
@@ -1,37 +0,0 @@
// @vitest-environment jsdom
//
// "Sign in as someone else" with a Google account the server will not sign in (not approved, or
// suspended) comes back to the account still signed in here, with the flags the sign-in page reads.
// The signed-in app read none of them, so the person was back as before without a word.
import { describe, expect, it } from "vitest";
import { refusedSwitchNotice } from "./entryUrl";
const notice = (search: string, hash = "") =>
refusedSwitchNotice(new URLSearchParams(search), new URLSearchParams(hash));
describe("a sign-in as someone else the server refused", () => {
it("says a request was recorded for an address not approved yet", () => {
expect(notice("", "access=requested&email=b%40example.com")).toEqual({
level: "info",
key: "welcome.auth.accessRequested",
});
});
it("says the account is not approved, and nothing changed here", () => {
expect(notice("", "access=denied")).toEqual({
level: "warning",
key: "header.account.switchNotApproved",
});
});
it("says the account is suspended", () => {
expect(notice("?login=suspended")).toEqual({
level: "warning",
key: "welcome.auth.suspended",
});
});
it("says nothing on an ordinary load", () => {
expect(notice("?page=stats", "")).toBeNull();
});
});
@@ -0,0 +1,65 @@
// @vitest-environment jsdom
//
// The app says what its entry URL tells the account signed in about a switch of account, once, and
// only once that account is known. Without the hook in the shell, a refused switch or a tab that
// reloaded as another account comes back without a word.
import { afterEach, describe, expect, it, vi } from "vitest";
import { renderHook } from "@testing-library/react";
vi.mock("react-i18next", async (importOriginal) => {
const actual = await importOriginal<typeof import("react-i18next")>();
return {
...actual,
useTranslation: () => ({
t: (key: string, values?: Record<string, string>) =>
values ? `${key} ${JSON.stringify(values)}` : key,
i18n: { language: "en" },
}),
};
});
const notifyMock = vi.fn();
vi.mock("./notifications", async (importOriginal) => {
const actual = await importOriginal<typeof import("./notifications")>();
return { ...actual, notify: (...a: unknown[]) => notifyMock(...a) };
});
const notice = vi.fn();
vi.mock("./entryUrl", async (importOriginal) => {
const actual = await importOriginal<typeof import("./entryUrl")>();
return { ...actual, accountSwitchNotice: () => notice() };
});
const { useAccountSwitchNotice } = await import("./useAccountSwitchNotice");
afterEach(() => {
notifyMock.mockClear();
notice.mockReset();
});
describe("the shell's word on a switch of account", () => {
it("waits for the account, then says it once", () => {
notice.mockReturnValue({
level: "info",
key: "header.account.switchRequested",
values: { email: "b@example.com" },
});
const { rerender } = renderHook(({ signedIn }) => useAccountSwitchNotice(signedIn), {
initialProps: { signedIn: false },
});
expect(notifyMock).not.toHaveBeenCalled();
rerender({ signedIn: true });
rerender({ signedIn: false });
rerender({ signedIn: true });
expect(notifyMock).toHaveBeenCalledTimes(1);
expect(notifyMock).toHaveBeenCalledWith({
level: "info",
message: 'header.account.switchRequested {"email":"b@example.com"}',
});
});
it("says nothing when the entry URL has nothing to say", () => {
notice.mockReturnValue(null);
renderHook(() => useAccountSwitchNotice(true));
expect(notifyMock).not.toHaveBeenCalled();
});
});
@@ -0,0 +1,19 @@
import { useEffect, useRef } from "react";
import { useTranslation } from "react-i18next";
import { accountSwitchNotice } from "./entryUrl";
import { notify } from "./notifications";
/** Say, once per load, what the entry URL tells the account signed in here about a switch of
* account (`accountSwitchNotice`): a sign-in as someone else the server refused, or a tab that
* reloaded because another account signed in under it. It waits for the account — until it is
* known there is no one signed in to say it to. */
export function useAccountSwitchNotice(signedIn: boolean): void {
const { t } = useTranslation();
const said = useRef(false);
useEffect(() => {
if (!signedIn || said.current) return;
said.current = true;
const notice = accountSwitchNotice();
if (notice) notify({ level: notice.level, message: t(notice.key, notice.values) });
}, [signedIn, t]);
}