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
@@ -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]);
}