A one-of-a-kind resume builder that keeps your privacy in mind. Completely secure, customizable, portable, open-source and free forever. Try it out today!
TypeScript agent-skillsaidsh-pluginhacktoberfestjavascriptmcp-serverreactresume-builderself-hostedtypescript
fix: bind account writes to the page that rendered them
Amruth Pillaidcf73de85ddb
diff --git a/apps/server/src/http/auth.test.ts b/apps/server/src/http/auth.test.tsindex 8c4e80f38..aff610375 100644--- a/apps/server/src/http/auth.test.ts+++ b/apps/server/src/http/auth.test.ts@@ -254,6 +254,56 @@ describe("OAuth provider response validation", () => {);});+describe("account-bound settings writes", () => {+ const request = (path: string, headers: Record<string, string> = {}, method = "POST") =>+ new Request(`http://localhost:3000${path}`, {+ method,+ headers: { "content-type": "application/json", ...headers },+ ...(method === "GET" ? {} : { body: "{}" }),+ });++ it("refuses a settings write whose page belongs to another account before Better Auth runs", async () => {+ const { handleAuth } = await import("./auth");+ mocks.getSession.mockResolvedValueOnce({ user: { id: "bob" } });+ const response = await handleAuth(request("/api/auth/update-user", { "x-account-id": "alice" }));+ expect(response.status).toBe(409);+ await expect(response.json()).resolves.toMatchObject({+ message: "This page belongs to a different account now. Reload and try again.",+ });+ expect(mocks.handler).not.toHaveBeenCalled();+ });++ it("allows the same account's settings write", async () => {+ const { handleAuth } = await import("./auth");+ mocks.getSession.mockResolvedValueOnce({ user: { id: "bob" } });+ const response = await handleAuth(request("/api/auth/update-user", { "x-account-id": "bob" }));+ expect(await response.text()).toBe("ok");+ expect(mocks.handler).toHaveBeenCalledOnce();+ });++ it("leaves clients without the optional header unchanged", async () => {+ const { handleAuth } = await import("./auth");+ await handleAuth(request("/api/auth/update-user"));+ expect(mocks.getSession).not.toHaveBeenCalled();+ expect(mocks.handler).toHaveBeenCalledOnce();+ });++ it("does not block explicit sign-out or sign-in intents", async () => {+ const { handleAuth } = await import("./auth");+ mocks.getSession.mockResolvedValue({ user: { id: "bob" } });+ await handleAuth(request("/api/auth/sign-out", { "x-account-id": "alice" }));+ await handleAuth(request("/api/auth/sign-in/email", { "x-account-id": "alice" }));+ expect(mocks.handler).toHaveBeenCalledTimes(2);+ });++ it("does not treat reads as writes", async () => {+ const { handleAuth } = await import("./auth");+ await handleAuth(request("/api/auth/get-session", { "x-account-id": "alice" }, "GET"));+ expect(mocks.getSession).not.toHaveBeenCalled();+ expect(mocks.handler).toHaveBeenCalledOnce();+ });+});+describe("account link storage migration", () => {it("sets an account link hook that delegates to migrateUserStorage", async () => {await import("./auth");diff --git a/apps/server/src/http/auth.ts b/apps/server/src/http/auth.tsindex caa3e10be..56a845420 100644--- a/apps/server/src/http/auth.ts+++ b/apps/server/src/http/auth.ts@@ -3,6 +3,7 @@ import { APIError } from "better-auth/api";import { migrateUserStorage } from "@reactive-resume/api/features/storage";import { auth, setAccountLinkHook } from "@reactive-resume/auth/config";import { env } from "@reactive-resume/env/server";+import { isSessionIntentPath } from "@reactive-resume/utils/auth-intent";import { TRUSTED_IP_HEADERS } from "@reactive-resume/utils/rate-limit";import { isAllowedOAuthRedirectUri } from "@reactive-resume/utils/url-security.node";@@ -156,6 +157,23 @@ async function validateOAuthClientMetadata(request: Request): Promise<Response |}}+/**+ * Account settings writes from the browser name the account whose page rendered them. If the cookie now belongs to a+ * different account (another tab signed out or in), applying that write would change the wrong user; refuse it before+ * Better Auth runs any effect. Requests without the header, and explicit sign-in/up/out intents, are unchanged.+ */+async function rejectMismatchedAccount(request: Request) {+ const expected = request.headers.get("x-account-id");+ if (!expected || request.method === "GET" || request.method === "HEAD") return null;+ if (isSessionIntentPath(new URL(request.url).pathname)) return null;+ const session = await auth.api.getSession({ headers: request.headers, query: { disableCookieCache: true } });+ if (!session?.user || session.user.id === expected) return null;+ return Response.json(+ { message: "This page belongs to a different account now. Reload and try again." },+ { status: 409, headers: { "Cache-Control": "no-store" } },+ );+}+export async function handleAuth(incomingRequest: Request, trustedClient = "unknown") {// Only the server adapter may supply the client address. Never forward client-sent proxy headers to auth.const headers = new Headers(incomingRequest.headers);@@ -167,6 +185,8 @@ export async function handleAuth(incomingRequest: Request, trustedClient = "unknconst sanitizedRequest = sanitizeOAuthAuthorizeRequest(request);const finalRequest = await defaultPublicClientRegistration(sanitizedRequest);+ const mismatchedAccount = await rejectMismatchedAccount(finalRequest);+ if (mismatchedAccount) return mismatchedAccount;return auth.handler(finalRequest);}diff --git a/apps/web/src/features/career/hooks.ts b/apps/web/src/features/career/hooks.tsindex 8923e033c..ca6888c36 100644--- a/apps/web/src/features/career/hooks.ts+++ b/apps/web/src/features/career/hooks.ts@@ -108,6 +108,7 @@ export function useSessionDraft<T>(export function useWorkspace(applicationId: string) {const generation = useRef(getAccountGeneration());const { session } = useRouteContext({ strict: false });+ const [owner] = useState(() => session?.user.id ?? null);const queryClient = useQueryClient();const queryKey = orpc.career.workspace.queryKey({ input: { applicationId } });const query = useQuery(orpc.career.workspace.queryOptions({ input: { applicationId } }));@@ -116,7 +117,7 @@ export function useWorkspace(applicationId: string) {let writes = byApplication.get(applicationId);if (!writes) byApplication.set(applicationId, (writes = new Set()));const pending = writes;- const workspaceMutation = orpc.career.saveWorkspace.mutationOptions();+ const workspaceMutation = orpc.career.saveWorkspace.mutationOptions({ context: owner ? { accountId: owner } : {} });const mutation = useMutation({...workspaceMutation,mutationFn: (input, context) => {diff --git a/apps/web/src/features/career/knowledge/preferences.tsx b/apps/web/src/features/career/knowledge/preferences.tsxindex f4b99227d..8e6aa81d5 100644--- a/apps/web/src/features/career/knowledge/preferences.tsx+++ b/apps/web/src/features/career/knowledge/preferences.tsx@@ -4,7 +4,7 @@ import { t } from "@lingui/core/macro";import { useLingui } from "@lingui/react";import { Trans } from "@lingui/react/macro";import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";-import { Link } from "@tanstack/react-router";+import { Link, useRouteContext } from "@tanstack/react-router";import { m } from "motion/react";import { useId, useRef, useState } from "react";import { careerProfileDataSchema } from "@reactive-resume/schema/career";@@ -29,11 +29,15 @@ const saveFailed = (error: unknown) => toastError(error, t`Couldn't save your pr/** The Preferences profile, saved whole. The cache updates at once; a failed save puts the server copy back. */export function useProfile() {const queryClient = useQueryClient();+ const { session } = useRouteContext({ strict: false });+ // The page belongs to the account it rendered for. Binding the write here keeps a profile read before a session+ // swap from being re-labelled as the new account's, even if the transport's global scope moved on.+ const [owner] = useState(() => session?.user.id ?? null);const queryKey = orpc.career.profile.queryKey();const query = useQuery(orpc.career.profile.queryOptions());const profile = query.data;const mutation = useMutation({- ...orpc.career.saveProfile.mutationOptions(),+ ...orpc.career.saveProfile.mutationOptions({ context: owner ? { accountId: owner } : {} }),onError: (error) => {void queryClient.invalidateQueries({ queryKey });saveFailed(error);diff --git a/apps/web/src/libs/auth/account-scope.test.ts b/apps/web/src/libs/auth/account-scope.test.tsindex ad57e5375..a31a56880 100644--- a/apps/web/src/libs/auth/account-scope.test.ts+++ b/apps/web/src/libs/auth/account-scope.test.ts@@ -4,11 +4,26 @@ import {getAccountGeneration,getAccountId,invalidateAccountScope,+ registerAccountReset,setAccountScope,subscribeAccountChange,} from "./account-scope";describe("account scope", () => {+ it("drops the previous account's data before adopting another account", () => {+ const reset = vi.fn();+ registerAccountReset(reset);+ invalidateAccountScope();+ setAccountScope("alice");+ reset.mockClear();+ setAccountScope("alice");+ expect(reset).not.toHaveBeenCalled();+ setAccountScope("bob");+ expect(reset).toHaveBeenCalledOnce();+ setAccountScope(null);+ expect(reset).toHaveBeenCalledTimes(2);+ });+it("advances the generation only when the account actually changes", () => {invalidateAccountScope();setAccountScope("alice");diff --git a/apps/web/src/libs/auth/account-scope.ts b/apps/web/src/libs/auth/account-scope.tsindex 2fd099401..2eaf0a97d 100644--- a/apps/web/src/libs/auth/account-scope.ts+++ b/apps/web/src/libs/auth/account-scope.ts@@ -7,13 +7,23 @@*/let accountId: string | null = null;let generation = 0;+let resetAccountState: (() => void) | undefined;export const getAccountId = () => accountId;export const getAccountGeneration = () => generation;-/** A session belonging to another account fences work queued for the previous one. */+/** The app registers how to drop cached account data, so a discovered account change fences it before it is adopted. */+export function registerAccountReset(reset: () => void) {+ resetAccountState = reset;+}++/**+ * A session belonging to another account fences work queued for the previous one. Data cached for the old account is+ * dropped before the new identity is certified, so a stale payload can never be relabelled as the new account's.+ */export function setAccountScope(id: string | null) {if (id === accountId) return;+ if (accountId !== null) resetAccountState?.();accountId = id;generation += 1;}diff --git a/apps/web/src/libs/auth/clear-account-data.ts b/apps/web/src/libs/auth/clear-account-data.tsindex 7d8d7644f..2163c7fe8 100644--- a/apps/web/src/libs/auth/clear-account-data.ts+++ b/apps/web/src/libs/auth/clear-account-data.ts@@ -10,8 +10,13 @@ export { getAccountGeneration } from "./account-scope";/** Forgets the account that just signed out or was deleted: cached queries, and thumbnails saved on this device. */export function clearAccountData(queryClient: QueryClient) {invalidateAccountScope();- forgetAccountState(queryClient);+ clearAccountState(queryClient);broadcastAccountChange();+}++/** Drops everything cached for the account that is no longer current, before another identity is certified. */+export function clearAccountState(queryClient: QueryClient) {+ forgetAccountState(queryClient);void clearStoredThumbnails();}diff --git a/apps/web/src/libs/auth/client.ts b/apps/web/src/libs/auth/client.tsindex ea6d899dd..e2107b8d5 100644--- a/apps/web/src/libs/auth/client.ts+++ b/apps/web/src/libs/auth/client.ts@@ -11,6 +11,8 @@ import {usernameClient,} from "better-auth/client/plugins";import { createAuthClient } from "better-auth/react";+import { isSessionIntentPath } from "@reactive-resume/utils/auth-intent";+import { getAccountId } from "./account-scope";import { authSearchSchema } from "@/features/auth/redirect";export const authClient = createAuthClient({@@ -19,6 +21,16 @@ export const authClient = createAuthClient({// with per-call options, unlike a global onRequest that a per-call one would replace.fetchOptions: {headers: { "x-client-timezone": Intl.DateTimeFormat().resolvedOptions().timeZone || "UTC" },+ // Better Auth talks to /api/auth directly, outside the RPC transport. Account settings writes still belong to+ // the account whose page rendered them, so a cookie swapped in another tab cannot apply them to the new user.+ onRequest: (context) => {+ if (context.method === "GET" || context.method === "HEAD") return;+ const path =+ typeof context.url === "string" ? new URL(context.url, window.location.origin).pathname : context.url.pathname;+ if (isSessionIntentPath(path)) return;+ const accountId = getAccountId();+ if (accountId) context.headers.set("x-account-id", accountId);+ },},plugins: [dashClient(),diff --git a/apps/web/src/libs/orpc/client.test.ts b/apps/web/src/libs/orpc/client.test.tsnew file mode 100644index 000000000..58494ebdd--- /dev/null+++ b/apps/web/src/libs/orpc/client.test.ts@@ -0,0 +1,34 @@+// @vitest-environment happy-dom+import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";++const fetchMock = vi.fn<typeof fetch>();++beforeEach(() => {+ fetchMock.mockReset();+ fetchMock.mockRejectedValue(new Error("captured transport"));+ vi.stubGlobal("fetch", fetchMock);+ vi.resetModules();+});++afterEach(() => vi.unstubAllGlobals());++const sentAccount = () => new Headers(fetchMock.mock.calls[0]?.[1]?.headers).get("x-account-id");++describe("RPC account binding", () => {+ it("keeps the account captured when a call started, not the one current at dispatch", async () => {+ const { setAccountScope } = await import("@/libs/auth/account-scope");+ const { client } = await import("./client");+ setAccountScope("alice");+ const pending = client.career.saveProfile({} as never).catch(() => undefined);+ setAccountScope("bob");+ await pending;+ expect(sentAccount()).toBe("alice");+ });++ it("uses the account a call explicitly carries even before a scope is set", async () => {+ const { client } = await import("./client");+ const pending = client.career.saveProfile({} as never, { context: { accountId: "carol" } }).catch(() => undefined);+ await pending;+ expect(sentAccount()).toBe("carol");+ });+});diff --git a/apps/web/src/libs/orpc/client.ts b/apps/web/src/libs/orpc/client.tsindex b4efb581b..e5f91b12a 100644--- a/apps/web/src/libs/orpc/client.ts+++ b/apps/web/src/libs/orpc/client.ts@@ -5,20 +5,37 @@ import { RPCLink } from "@orpc/client/fetch";import { BatchLinkPlugin } from "@orpc/client/plugins";import { createTanstackQueryUtils } from "@orpc/tanstack-query";import { rpcFetch } from "./fetch";+import { getAccountId } from "@/libs/auth/account-scope";++/**+ * The account a call belongs to. Captured when the call starts (before any await, batching or body staging), so a+ * session switch during dispatch cannot relabel a payload that was built for the previous account.+ */+export type ClientContext = { accountId?: string };const getRpcUrl = () => `${window.location.origin}/api/rpc`;-export const client: RouterClient<typeof router> = createORPCClient(- new RPCLink({+const accountHeaders = (options: { context: ClientContext }) =>+ options.context.accountId ? { "x-account-id": options.context.accountId } : {};++export const client: RouterClient<typeof router, ClientContext> = createORPCClient(+ new RPCLink<ClientContext>({url: getRpcUrl,fetch: rpcFetch,+ headers: accountHeaders,plugins: [- new BatchLinkPlugin({+ new BatchLinkPlugin<ClientContext>({mode: "streaming",groups: [{ condition: () => true, context: {} }],}),],interceptors: [+ // Runs before the request is encoded, so the header carries the account this call was made for, not whichever+ // account the tab discovered while the request was being prepared.+ (options) => {+ const accountId = options.context.accountId ?? getAccountId() ?? undefined;+ return options.next({ ...options, context: accountId ? { ...options.context, accountId } : options.context });+ },onError((error) => {if (error instanceof DOMException && error.name === "AbortError") return;console.warn("[oRPC client]", error);@@ -27,11 +44,16 @@ export const client: RouterClient<typeof router> = createORPCClient(}),);-export const streamClient: RouterClient<typeof router> = createORPCClient(- new RPCLink({+export const streamClient: RouterClient<typeof router, ClientContext> = createORPCClient(+ new RPCLink<ClientContext>({url: getRpcUrl,fetch: rpcFetch,+ headers: accountHeaders,interceptors: [+ (options) => {+ const accountId = options.context.accountId ?? getAccountId() ?? undefined;+ return options.next({ ...options, context: accountId ? { ...options.context, accountId } : options.context });+ },onError((error) => {if (error instanceof DOMException && error.name === "AbortError") return;console.warn("[oRPC stream client]", error);diff --git a/apps/web/src/libs/orpc/fetch.ts b/apps/web/src/libs/orpc/fetch.tsindex b2cc66d0d..063232918 100644--- a/apps/web/src/libs/orpc/fetch.ts+++ b/apps/web/src/libs/orpc/fetch.ts@@ -6,9 +6,11 @@ let stagingUnavailable = false;export async function rpcFetch(input: RequestInfo | URL, init?: RequestInit): Promise<Response> {const request = new Request(input, { ...init, credentials: "include" });request.headers.set("x-client-timezone", Intl.DateTimeFormat().resolvedOptions().timeZone);- // The account this page was rendered for. The server refuses writes when the cookie now belongs to someone else.- const accountId = getAccountId();- if (accountId) request.headers.set("x-account-id", accountId);+ // A call-bound account (captured when the procedure was invoked) wins; a direct fetch gets the live scope.+ if (!request.headers.has("x-account-id")) {+ const accountId = getAccountId();+ if (accountId) request.headers.set("x-account-id", accountId);+ }if (request.method !== "POST") return fetch(request);// Buffer as bytes: a teed stream needs duplex mode, and a Blob body is not visible to DevTools/CDP.const body = await request.arrayBuffer();diff --git a/apps/web/src/libs/root-context.test.ts b/apps/web/src/libs/root-context.test.tsindex 70f681167..fd6021cd7 100644--- a/apps/web/src/libs/root-context.test.ts+++ b/apps/web/src/libs/root-context.test.ts@@ -1,9 +1,17 @@-import { describe, expect, it, vi } from "vite-plus/test";+import { beforeEach, describe, expect, it, vi } from "vite-plus/test";import { QueryClient } from "@tanstack/react-query";+import {+ getAccountGeneration,+ getAccountId,+ invalidateAccountScope,+ registerAccountReset,+ setAccountScope,+} from "./auth/account-scope";import { loadRootContext, sessionQueryKey } from "./root-context";const getSessionMock = vi.hoisted(() => vi.fn());const flagsGetMock = vi.hoisted(() => vi.fn().mockResolvedValue({ disableSignups: false, disableEmailAuth: false }));+const loadLocaleMock = vi.hoisted(() => vi.fn().mockResolvedValue(undefined));vi.mock("./auth/session", () => ({getSession: getSessionMock,@@ -11,7 +19,7 @@ vi.mock("./auth/session", () => ({vi.mock("./locale", () => ({getLocale: () => "en-US",- loadLocale: vi.fn().mockResolvedValue(undefined),+ loadLocale: loadLocaleMock,}));vi.mock("./orpc/client", () => ({@@ -27,6 +35,12 @@ vi.mock("./theme", () => ({}));describe("loadRootContext", () => {+ beforeEach(() => {+ invalidateAccountScope();+ registerAccountReset(() => undefined);+ loadLocaleMock.mockResolvedValue(undefined);+ });+it("loads root context with freshly fetched session", async () => {const queryClient = new QueryClient({defaultOptions: { queries: { retry: false } },@@ -67,4 +81,58 @@ describe("loadRootContext", () => {await expect(loadRootContext(queryClient)).rejects.toThrow("Session check failed with status 500");});++ it("does not let a preload certify an account for the page that is on screen", async () => {+ const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });+ setAccountScope("alice");+ const generation = getAccountGeneration();+ getSessionMock.mockResolvedValueOnce({ user: { id: "bob" }, session: { id: "bob-session" } });++ await loadRootContext(queryClient, { commit: false });++ expect(getAccountId()).toBe("alice");+ expect(getAccountGeneration()).toBe(generation);+ });++ it("drops the previous account's cached data before certifying a committed account change", async () => {+ const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });+ setAccountScope("alice");+ queryClient.setQueryData(["career", "profile"], { targetRoles: ["Alice private role"] });+ registerAccountReset(() => queryClient.clear());+ getSessionMock.mockResolvedValueOnce({ user: { id: "bob" }, session: { id: "bob-session" } });++ await loadRootContext(queryClient, { commit: true });++ expect(getAccountId()).toBe("bob");+ expect(queryClient.getQueryData(["career", "profile"])).toBeUndefined();+ });++ it("ignores a stale root load that finishes after a newer one certified the account", async () => {+ const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });+ let release!: () => void;+ const barrier = new Promise<void>((resolve) => {+ release = resolve;+ });+ let started!: () => void;+ const ready = new Promise<void>((resolve) => {+ started = resolve;+ });+ loadLocaleMock.mockImplementationOnce(() => {+ started();+ return barrier;+ });+ queryClient.setQueryData(sessionQueryKey, { user: { id: "alice" }, session: { id: "alice-session" } });+ const stale = loadRootContext(queryClient);+ await ready;+ queryClient.setQueryData(sessionQueryKey, { user: { id: "bob" }, session: { id: "bob-session" } });+ const fresh = await loadRootContext(queryClient);+ const afterNew = { id: getAccountId(), generation: getAccountGeneration() };+ expect(afterNew.id).toBe("bob");+ expect(fresh.session).toMatchObject({ user: { id: "bob" } });++ release();+ await stale;++ expect({ id: getAccountId(), generation: getAccountGeneration() }).toEqual(afterNew);+ });});diff --git a/apps/web/src/libs/root-context.ts b/apps/web/src/libs/root-context.tsindex 862c5942a..cddae87a9 100644--- a/apps/web/src/libs/root-context.ts+++ b/apps/web/src/libs/root-context.ts@@ -8,12 +8,21 @@ import { getTheme } from "./theme";export const sessionQueryKey = ["auth", "session"] as const;const flagsQueryKey = ["flags"] as const;+// Each root load is numbered. A load that finishes after a newer one must not certify its older session: a hover+// preload started as the previous account cannot relabel the live page after the browser moved on.+let rootLoadSequence = 0;++type RootLoadOptions = {+ /** Only a committed route (not a hover preload) may certify the account this tab renders for. */+ commit?: boolean;+};// Root beforeLoad runs on every navigation and every hover preload, so the network reads come from the query cache.// A signed-in session is reused for a minute; a signed-out one is always re-checked, so signing in elsewhere shows up// on the next navigation. Anything that signs in, signs out or edits the profile invalidates `sessionQueryKey` before// calling `router.invalidate()`. Flags come from server env and only change on a restart.-export async function loadRootContext(queryClient: QueryClient) {+export async function loadRootContext(queryClient: QueryClient, options: RootLoadOptions = {}) {+ const load = ++rootLoadSequence;const theme = getTheme();const locale = getLocale();@@ -37,8 +46,9 @@ export async function loadRootContext(queryClient: QueryClient) {queryClient.query({ queryKey: flagsQueryKey, queryFn: () => client.flags.get(), staleTime: 5 * 60_000 }),loadLocale(locale),]);- // Whatever this tab now renders for belongs to this session; a different account fences queued autosaves.- setAccountScope(session?.user.id ?? null);+ // A preload only prepares a future navigation; a stale completion has already been overtaken. Neither may adopt+ // an account scope, because the page on screen still belongs to the session it was rendered for.+ if (load === rootLoadSequence && options.commit !== false) setAccountScope(session?.user.id ?? null);return { theme, locale, session, flags };}diff --git a/apps/web/src/router.tsx b/apps/web/src/router.tsxindex c2fa7b942..be501eec6 100644--- a/apps/web/src/router.tsx+++ b/apps/web/src/router.tsx@@ -2,7 +2,8 @@ import { createRouter } from "@tanstack/react-router";import { ErrorScreen } from "./components/layout/error-screen";import { LoadingScreen } from "./components/layout/loading-screen";import { NotFoundScreen } from "./components/layout/not-found-screen";-import { syncAccountDataAcrossTabs } from "./libs/auth/clear-account-data";+import { registerAccountReset } from "./libs/auth/account-scope";+import { clearAccountState, syncAccountDataAcrossTabs } from "./libs/auth/clear-account-data";import { orpc } from "./libs/orpc/client";import { getQueryClient } from "./libs/query/client";import { loadRootContext } from "./libs/root-context";@@ -14,6 +15,8 @@ const supportsTransitionTypes = globalThis.CSS?.supports?.("selector(:active-vieexport const getRouter = async () => {const queryClient = getQueryClient();+ // A root load that discovers another account drops this account's cached data before adopting the new identity.+ registerAccountReset(() => clearAccountState(queryClient));syncAccountDataAcrossTabs(queryClient);const { theme, locale, session, flags } = await loadRootContext(queryClient);diff --git a/apps/web/src/routes/__root.tsx b/apps/web/src/routes/__root.tsxindex 3da82c677..b063b68ef 100644--- a/apps/web/src/routes/__root.tsx+++ b/apps/web/src/routes/__root.tsx@@ -60,7 +60,7 @@ export const Route = createRootRouteWithContext<RouterContext>()({return { meta: [{ title }, { name: "description", content: description }] };},beforeLoad: async ({ context, location, preload }) => {- const root = await loadRootContext(context.queryClient);+ const root = await loadRootContext(context.queryClient, { commit: !preload });const { aliasUrl, appUrl } = root.flags;// Sign-in and the editor live on APP_URL; the alias (APP_ALIAS_URL) only serves the public pages. The server// redirects full page loads; this catches links followed inside the app.diff --git a/migrations/20261031160926_rx106_follow_up_owner/migration.sql b/migrations/20261031160926_rx106_follow_up_owner/migration.sqlindex b8c476ccc..de3cfd994 100644--- a/migrations/20261031160926_rx106_follow_up_owner/migration.sql+++ b/migrations/20261031160926_rx106_follow_up_owner/migration.sql@@ -24,11 +24,12 @@ FROM career_schedule s JOIN application a ON a.id=s.application_id AND a.user_idWHERE j.schedule_id=s.id AND s.kind='follow-up' AND j.status IN ('queued','running')AND ((CASE WHEN a.follow_up_date_only THEN ((a.follow_up_at AT TIME ZONE 'UTC')::date + time '09:00') AT TIME ZONE s.timezone ELSE a.follow_up_at END) IS DISTINCT FROM s.next_run_at OR NOT s.enabled);--> statement-breakpoint--- Move the delivery index to the projected clock. A completed occurrence on the same logical day stays delivered: its--- watermark follows the projected instant, so the scheduler does not treat the new time as an undelivered occurrence.+-- Move the delivery index to the projected clock. A completed occurrence stays delivered only when the projection moves+-- the same occurrence: a logical-day follow-up on the same calendar day, or an exact-time follow-up at the same instant.+-- An explicit time that differs from the completed reminder is a new occurrence and must remain eligible for delivery.-- Completed history keeps its original due time; only pending queued/running work moves to the projected clock.WITH projected AS (- SELECT s.id,s.last_queued_at,s.next_run_at AS current_at,+ SELECT s.id,s.last_queued_at,s.next_run_at AS current_at,a.follow_up_date_only AS date_only,CASE WHEN a.follow_up_date_only THEN ((a.follow_up_at AT TIME ZONE 'UTC')::date + time '09:00') AT TIME ZONE s.timezone ELSE a.follow_up_at END AS at,COALESCE((SELECT j.status='completed' FROM career_job j WHERE j.schedule_id=s.id ORDER BY j.created_at DESC,j.id DESC LIMIT 1),false) AS completed,a.follow_up_note@@ -39,9 +40,10 @@ WITH projected AS (UPDATE career_schedule s SET next_run_at=p.at,query=COALESCE(p.follow_up_note,''),last_queued_at=CASEWHEN p.at IS NOT DISTINCT FROM p.current_at THEN s.last_queued_at- WHEN s.last_queued_at IS NOT NULL AND p.completed- AND (p.at AT TIME ZONE s.timezone)::date=(s.last_queued_at AT TIME ZONE s.timezone)::date- THEN p.at+ WHEN s.last_queued_at IS NOT NULL AND p.completed AND (+ (p.date_only AND (p.at AT TIME ZONE s.timezone)::date=(s.last_queued_at AT TIME ZONE s.timezone)::date)+ OR (NOT p.date_only AND s.last_queued_at=p.at)+ ) THEN p.atELSE NULL ENDFROM projected p WHERE s.id=p.id;--> statement-breakpointdiff --git a/packages/api/src/features/career/jobs.integration.test.ts b/packages/api/src/features/career/jobs.integration.test.tsindex 842abeb6b..0f0647289 100644--- a/packages/api/src/features/career/jobs.integration.test.ts+++ b/packages/api/src/features/career/jobs.integration.test.ts@@ -668,7 +668,7 @@ describe.skipIf(!databaseUrl)("durable career scheduling", () => {// Stages the shipped migrations so the two follow-up migrations run against a populated pre-patch schema. Drizzle// migrations are forward-only here, so the safety property to prove is repeatability and preservation, not a down// migration: re-running the same backfills must leave the upgraded rows byte-for-byte unchanged.- it("upgrades completed legacy reminders without delivering them twice and moves pending work", async () => {+ it("upgrades legacy reminders without duplicating or dropping occurrences", async () => {const isolated = `rx106_upgrade_${randomUUID().replaceAll("-", "")}`;await admin.query(`CREATE SCHEMA ${isolated}`);const upgrade = new Pool({@@ -676,7 +676,7 @@ describe.skipIf(!databaseUrl)("durable career scheduling", () => {max: 1,options: `-c search_path=${isolated} -c statement_timeout=10000`,});- const readSchedule = async () =>+ const scheduleRows = async () =>(await upgrade.query("SELECT id,next_run_at,last_queued_at,timezone,enabled,query FROM career_schedule ORDER BY id",@@ -689,16 +689,22 @@ describe.skipIf(!databaseUrl)("durable career scheduling", () => {enabled: row.enabled as boolean,query: row.query as string,}));- const readJobs = async () =>+ const jobRows = async () =>(await upgrade.query("SELECT * FROM career_job ORDER BY due_at, id")).rows.map((row) => ({id: row.id as string,scheduleId: row.schedule_id as string,dueAt: (row.due_at as Date).toISOString(),status: row.status as string,}));- const readNotifications = async () =>- (await upgrade.query("SELECT id,key,application_id FROM career_notification ORDER BY id")).rows.map((row) => ({- id: row.id as string,+ const wholeJob = async (id: string) => (await upgrade.query("SELECT * FROM career_job WHERE id=$1", [id])).rows[0];+ const wholeSnapshot = async () => ({+ schedules: (await upgrade.query("SELECT * FROM career_schedule ORDER BY id")).rows,+ jobs: (await upgrade.query("SELECT * FROM career_job ORDER BY due_at, id")).rows,+ notifications: (await upgrade.query("SELECT * FROM career_notification ORDER BY id")).rows,+ applications: (await upgrade.query("SELECT * FROM application ORDER BY id")).rows,+ });+ const notifications = async () =>+ (await upgrade.query("SELECT key,application_id FROM career_notification ORDER BY key")).rows.map((row) => ({key: row.key as string,applicationId: row.application_id as string | null,}));@@ -719,32 +725,72 @@ describe.skipIf(!databaseUrl)("durable career scheduling", () => {await apply(directory);}- // Valid pre-patch state: the exact-time reminder (08:00) and the date-only follow-up were independent- // surfaces. The 08:00 occurrence already ran; the pending reminder has not.+ // Valid pre-patch state: every reminder already ran at 08:00. The application's own follow-up is a separate+ // surface: a logical-day date on the same day, a different day, a pending one, and two explicit times.await upgrade.query(`INSERT INTO "user"(id,name,email,username,display_username,timezone,email_verified)VALUES('upgrade','Fictional Upgrade','[email protected]','upgrade','upgrade','UTC',true);INSERT INTO application(id,user_id,company,role,status,follow_up_at,follow_up_note) VALUES('same-day','upgrade','Same Day Labs','Engineer','applied','2026-10-30T00:00:00Z','Already delivered'),('other-day','upgrade','Other Day Labs','Engineer','applied','2026-10-28T00:00:00Z','New logical day'),- ('pending','upgrade','Pending Labs','Engineer','applied','2026-10-30T00:00:00Z','Still pending');+ ('pending','upgrade','Pending Labs','Engineer','applied','2026-10-30T00:00:00Z','Still pending'),+ ('explicit-later','upgrade','Explicit Later Labs','Engineer','applied','2026-10-30T16:00:00Z','Distinct exact time'),+ ('explicit-same','upgrade','Explicit Same Labs','Engineer','applied','2026-10-30T08:00:00Z','Already delivered'),+ ('explicit-delivered','upgrade','Explicit Delivered Labs','Engineer','applied','2026-10-30T16:00:00Z','Delivered at this instant');INSERT INTO career_schedule(id,user_id,application_id,kind,query,timezone,enabled,next_run_at,last_queued_at) VALUES('same-day','upgrade','same-day','follow-up','Already delivered','UTC',true,'2026-10-30T08:00:00Z','2026-10-30T08:00:00Z'),('other-day','upgrade','other-day','follow-up','Earlier delivery','UTC',true,'2026-10-27T08:00:00Z','2026-10-27T08:00:00Z'),- ('pending','upgrade','pending','follow-up','Still pending','UTC',true,'2026-10-30T08:00:00Z','2026-10-30T08:00:00Z');+ ('pending','upgrade','pending','follow-up','Still pending','UTC',true,'2026-10-30T08:00:00Z','2026-10-30T08:00:00Z'),+ ('explicit-later','upgrade','explicit-later','follow-up','Distinct exact time','UTC',true,'2026-10-30T08:00:00Z','2026-10-30T08:00:00Z'),+ ('explicit-same','upgrade','explicit-same','follow-up','Already delivered','UTC',true,'2026-10-30T08:00:00Z','2026-10-30T08:00:00Z'),+ ('explicit-delivered','upgrade','explicit-delivered','follow-up','Delivered at this instant','UTC',true,'2026-10-30T17:00:00Z','2026-10-30T16:00:00Z');INSERT INTO career_job(id,user_id,schedule_id,due_at,status,attempts) VALUES('job-same-day','upgrade','same-day','2026-10-30T08:00:00Z','completed',1),('job-other-day','upgrade','other-day','2026-10-27T08:00:00Z','completed',1),- ('job-pending','upgrade','pending','2026-10-30T08:00:00Z','queued',0);+ ('job-pending','upgrade','pending','2026-10-30T08:00:00Z','queued',0),+ ('job-explicit-later','upgrade','explicit-later','2026-10-30T08:00:00Z','completed',1),+ ('job-explicit-same','upgrade','explicit-same','2026-10-30T08:00:00Z','completed',1),+ ('job-explicit-delivered','upgrade','explicit-delivered','2026-10-30T16:00:00Z','completed',1);INSERT INTO career_notification(id,user_id,application_id,key,notice) VALUES('notice-same-day','upgrade','same-day','job-same-day','{"type":"followup","company":"Same Day Labs","role":"Engineer","note":"Already delivered"}'),- ('notice-other-day','upgrade','other-day','job-other-day','{"type":"followup","company":"Other Day Labs","role":"Engineer","note":"Earlier delivery"}');+ ('notice-other-day','upgrade','other-day','job-other-day','{"type":"followup","company":"Other Day Labs","role":"Engineer","note":"Earlier delivery"}'),+ ('notice-explicit-later','upgrade','explicit-later','job-explicit-later','{"type":"followup","company":"Explicit Later Labs","role":"Engineer","note":"Distinct exact time"}'),+ ('notice-explicit-same','upgrade','explicit-same','job-explicit-same','{"type":"followup","company":"Explicit Same Labs","role":"Engineer","note":"Already delivered"}'),+ ('notice-explicit-delivered','upgrade','explicit-delivered','job-explicit-delivered','{"type":"followup","company":"Explicit Delivered Labs","role":"Engineer","note":"Delivered at this instant"}');`);- const preSchedules = await readSchedule();- const preJobs = await readJobs();- const preNotifications = await readNotifications();- expect(preSchedules).toEqual([+ const before = {+ sameDay: await wholeJob("job-same-day"),+ otherDay: await wholeJob("job-other-day"),+ explicitLater: await wholeJob("job-explicit-later"),+ explicitSame: await wholeJob("job-explicit-same"),+ explicitDelivered: await wholeJob("job-explicit-delivered"),+ };+ expect(await scheduleRows()).toEqual([+ {+ id: "explicit-delivered",+ next: "2026-10-30T17:00:00.000Z",+ queued: "2026-10-30T16:00:00.000Z",+ timezone: "UTC",+ enabled: true,+ query: "Delivered at this instant",+ },+ {+ id: "explicit-later",+ next: "2026-10-30T08:00:00.000Z",+ queued: "2026-10-30T08:00:00.000Z",+ timezone: "UTC",+ enabled: true,+ query: "Distinct exact time",+ },+ {+ id: "explicit-same",+ next: "2026-10-30T08:00:00.000Z",+ queued: "2026-10-30T08:00:00.000Z",+ timezone: "UTC",+ enabled: true,+ query: "Already delivered",+ },{id: "other-day",next: "2026-10-27T08:00:00.000Z",@@ -770,18 +816,36 @@ describe.skipIf(!databaseUrl)("durable career scheduling", () => {query: "Already delivered",},]);- expect(preJobs).toEqual([- { id: "job-other-day", scheduleId: "other-day", dueAt: "2026-10-27T08:00:00.000Z", status: "completed" },- { id: "job-pending", scheduleId: "pending", dueAt: "2026-10-30T08:00:00.000Z", status: "queued" },- { id: "job-same-day", scheduleId: "same-day", dueAt: "2026-10-30T08:00:00.000Z", status: "completed" },- ]);- expect(preNotifications).toHaveLength(2);+ expect(await notifications()).toHaveLength(5);await apply(owner);await apply(clock);- const migrated = await readSchedule();- expect(migrated).toEqual([+ expect(await scheduleRows()).toEqual([+ {+ id: "explicit-delivered",+ next: "2026-10-30T16:00:00.000Z",+ queued: "2026-10-30T16:00:00.000Z",+ timezone: "UTC",+ enabled: true,+ query: "Delivered at this instant",+ },+ {+ id: "explicit-later",+ next: "2026-10-30T16:00:00.000Z",+ queued: null,+ timezone: "UTC",+ enabled: true,+ query: "Distinct exact time",+ },+ {+ id: "explicit-same",+ next: "2026-10-30T08:00:00.000Z",+ queued: "2026-10-30T08:00:00.000Z",+ timezone: "UTC",+ enabled: true,+ query: "Already delivered",+ },{id: "other-day",next: "2026-10-28T09:00:00.000Z",@@ -807,44 +871,104 @@ describe.skipIf(!databaseUrl)("durable career scheduling", () => {query: "Already delivered",},]);- expect(await readJobs()).toEqual([+ expect(await wholeJob("job-same-day")).toEqual(before.sameDay);+ expect(await wholeJob("job-other-day")).toEqual(before.otherDay);+ expect(await wholeJob("job-explicit-later")).toEqual(before.explicitLater);+ expect(await wholeJob("job-explicit-delivered")).toEqual(before.explicitDelivered);+ expect(await wholeJob("job-explicit-same")).toEqual(before.explicitSame);+ expect(await jobRows()).toEqual([{ id: "job-other-day", scheduleId: "other-day", dueAt: "2026-10-27T08:00:00.000Z", status: "completed" },+ {+ id: "job-explicit-later",+ scheduleId: "explicit-later",+ dueAt: "2026-10-30T08:00:00.000Z",+ status: "completed",+ },+ {+ id: "job-explicit-same",+ scheduleId: "explicit-same",+ dueAt: "2026-10-30T08:00:00.000Z",+ status: "completed",+ },{ id: "job-pending", scheduleId: "pending", dueAt: "2026-10-30T08:00:00.000Z", status: "canceled" },{ id: "job-same-day", scheduleId: "same-day", dueAt: "2026-10-30T08:00:00.000Z", status: "completed" },+ {+ id: "job-explicit-delivered",+ scheduleId: "explicit-delivered",+ dueAt: "2026-10-30T16:00:00.000Z",+ status: "completed",+ },]);const oldDb = fixture.db;fixture.db = drizzle({ client: upgrade });try {- // One worker serves one job per account per tick, so two due accounts need two ticks.+ // One worker serves one job per account per tick: explicit-later, other-day and pending are due.+ await run();+ await run();await run();await run();} finally {fixture.db = oldDb;}- const delivered = await readJobs();- expect(delivered.filter((row) => row.scheduleId === "same-day")).toEqual([+ const delivered = await jobRows();+ const forSchedule = (id: string) => delivered.filter((row) => row.scheduleId === id);+ expect(forSchedule("same-day")).toEqual([{ id: "job-same-day", scheduleId: "same-day", dueAt: "2026-10-30T08:00:00.000Z", status: "completed" },]);- expect(delivered.filter((row) => row.scheduleId === "other-day")).toEqual([+ expect(forSchedule("explicit-same")).toEqual([+ {+ id: "job-explicit-same",+ scheduleId: "explicit-same",+ dueAt: "2026-10-30T08:00:00.000Z",+ status: "completed",+ },+ ]);+ expect(forSchedule("explicit-delivered")).toEqual([+ {+ id: "job-explicit-delivered",+ scheduleId: "explicit-delivered",+ dueAt: "2026-10-30T16:00:00.000Z",+ status: "completed",+ },+ ]);+ expect(forSchedule("explicit-later")).toEqual([+ {+ id: "job-explicit-later",+ scheduleId: "explicit-later",+ dueAt: "2026-10-30T08:00:00.000Z",+ status: "completed",+ },+ {+ id: expect.any(String),+ scheduleId: "explicit-later",+ dueAt: "2026-10-30T16:00:00.000Z",+ status: "completed",+ },+ ]);+ expect(forSchedule("other-day")).toEqual([{ id: "job-other-day", scheduleId: "other-day", dueAt: "2026-10-27T08:00:00.000Z", status: "completed" },{ id: expect.any(String), scheduleId: "other-day", dueAt: "2026-10-28T09:00:00.000Z", status: "completed" },]);- expect(delivered.filter((row) => row.scheduleId === "pending")).toEqual([+ expect(forSchedule("pending")).toEqual([{ id: "job-pending", scheduleId: "pending", dueAt: "2026-10-30T08:00:00.000Z", status: "canceled" },{ id: expect.any(String), scheduleId: "pending", dueAt: "2026-10-30T09:00:00.000Z", status: "completed" },]);- const notifications = await readNotifications();- expect(notifications.filter((row) => row.key === "job-same-day")).toHaveLength(1);- expect(notifications).toHaveLength(4);+ const notices = await notifications();+ expect(notices).toHaveLength(8);+ expect(notices.filter((row) => row.key === "job-same-day")).toHaveLength(1);+ expect(notices.filter((row) => row.key === "job-explicit-same")).toHaveLength(1);+ expect(notices.filter((row) => row.key === "job-explicit-later")).toHaveLength(1);+ expect(notices.filter((row) => row.key === "job-explicit-delivered")).toHaveLength(1);+ expect(notices.filter((row) => row.applicationId === "explicit-later")).toHaveLength(2);+ expect(await wholeJob("job-same-day")).toEqual(before.sameDay);+ expect(await wholeJob("job-explicit-same")).toEqual(before.explicitSame);+ expect(await wholeJob("job-explicit-later")).toEqual(before.explicitLater);+ expect(await wholeJob("job-explicit-delivered")).toEqual(before.explicitDelivered);- // Re-running the same forward-only backfills is safe: completed history, watermarks and deliveries hold.- const beforeRepeat = {- schedules: await readSchedule(),- jobs: await readJobs(),- notifications: await readNotifications(),- };+ // Re-running the same forward-only backfills is safe: history, watermarks and deliveries hold.+ const beforeRepeat = await wholeSnapshot();const ownerSql = await readFile(new URL(`${owner}/migration.sql`, migrations), "utf8");await upgrade.query(ownerSql.slice(ownerSql.indexOf("--> statement-breakpoint") + "--> statement-breakpoint".length),@@ -852,17 +976,19 @@ describe.skipIf(!databaseUrl)("durable career scheduling", () => {await upgrade.query('UPDATE "user" SET timezone=timezone WHERE EXISTS (SELECT 1 FROM application a WHERE a.user_id="user".id AND a.follow_up_date_only AND a.follow_up_at IS NOT NULL)',);- expect({- schedules: await readSchedule(),- jobs: await readJobs(),- notifications: await readNotifications(),- }).toEqual(beforeRepeat);+ fixture.db = drizzle({ client: upgrade });+ try {+ await run();+ await run();+ } finally {+ fixture.db = oldDb;+ }+ expect(await wholeSnapshot()).toEqual(beforeRepeat);} finally {await upgrade.end();await admin.query(`DROP SCHEMA IF EXISTS ${isolated} CASCADE`);}});-it("distinguishes old-client dates from exact midnight reminders and preserves notes-only timestamps", async () => {const { applicationService } = await import("../applications/service");await getDb().update(tables.user).set({ timezone: "Asia/Tokyo" }).where(eq(tables.user.id, "alice"));diff --git a/packages/utils/package.json b/packages/utils/package.jsonindex adbe90cce..f0bac55f8 100644--- a/packages/utils/package.json+++ b/packages/utils/package.json@@ -6,6 +6,7 @@"exports": {"./amount": "./src/amount.ts","./app-paths": "./src/app-paths.ts",+ "./auth-intent": "./src/auth-intent.ts","./color": "./src/color.ts","./file": "./src/file.ts","./http": "./src/http.ts",diff --git a/packages/utils/src/auth-intent.test.ts b/packages/utils/src/auth-intent.test.tsnew file mode 100644index 000000000..9462d041f--- /dev/null+++ b/packages/utils/src/auth-intent.test.ts@@ -0,0 +1,36 @@+import { describe, expect, it } from "vite-plus/test";+import { isSessionIntentPath } from "./auth-intent";++describe("session intent paths", () => {+ it.each([+ "/api/auth/sign-in/email",+ "/api/auth/sign-up/email",+ "/api/auth/sign-out",+ "/api/auth/callback/google",+ "/api/auth/oauth2/authorize",+ "/api/auth/two-factor/verify-totp",+ "/api/auth/reset-password",+ "/api/auth/forget-password",+ "/api/auth/anonymous",+ "/api/auth/one-tap/callback",+ "/api/auth/verify-email",+ ])("treats %s as a session intent", (path) => {+ expect(isSessionIntentPath(path)).toBe(true);+ });++ it.each([+ "/api/auth/update-user",+ "/api/auth/change-email",+ "/api/auth/delete-user",+ "/api/auth/set-password",+ "/api/auth/link-social",+ "/api/auth/unlink-account",+ "/api/auth/passkey/update-passkey",+ "/api/auth/api-key/update",+ "/api/auth/two-factor/enable",+ "/api/auth/send-verification-email",+ "/api/rpc/career/saveProfile",+ ])("keeps %s account-bound", (path) => {+ expect(isSessionIntentPath(path)).toBe(false);+ });+});diff --git a/packages/utils/src/auth-intent.ts b/packages/utils/src/auth-intent.tsnew file mode 100644index 000000000..1d82d2afe--- /dev/null+++ b/packages/utils/src/auth-intent.ts@@ -0,0 +1,9 @@+/**+ * Better Auth endpoints that intentionally establish, replace or end the signed-in session. They must work with+ * whatever cookie the browser holds, so they never carry the expectation of the account whose page sent them.+ * Shared by the browser auth client and the server guard so both agree on which writes are session intents.+ */+const sessionIntentPaths =+ /\/api\/auth\/(?:(?:sign-in|sign-up|sign-out|callback|oauth2|reset-password|forget-password|anonymous|one-tap|verify-email)(?:[/?]|$)|two-factor\/verify[\w-]*)/;++export const isSessionIntentPath = (pathname: string) => sessionIntentPaths.test(pathname);diff --git a/tests/e2e/specs/rx106-review-regressions.spec.ts b/tests/e2e/specs/rx106-review-regressions.spec.tsindex 2e4969844..afeb47a0b 100644--- a/tests/e2e/specs/rx106-review-regressions.spec.ts+++ b/tests/e2e/specs/rx106-review-regressions.spec.ts@@ -590,3 +590,188 @@ test("HTTP profile writes bound to another account are refused and leave the newawait pool.query('DELETE FROM "user" WHERE email=$1', [second.email]);}});++// A tab that misses the cross-tab signal: no BroadcastChannel and no storage event. Only the server-side binding can+// stop a write it builds for the account it is still showing.+async function suppressAccountSignals(page: Page) {+ await page.addInitScript(() => {+ Reflect.deleteProperty(window, "BroadcastChannel");+ const add = window.addEventListener.bind(window);+ window.addEventListener = ((+ type: string,+ listener: EventListenerOrEventListenerObject,+ options?: boolean | AddEventListenerOptions,+ ) => {+ if (type === "storage") return;+ add(type, listener, options);+ }) as typeof window.addEventListener;+ });+}++async function switchAccountInOtherTab(page: Page) {+ const other = await page.context().newPage();+ await other.goto("/dashboard/settings/account");+ await other.getByRole("button", { name: "Sign out", exact: true }).last().click();+ await expect(other).toHaveURL(/\/$/);+ const second = await signUpSecondAccount(other);+ return { other, second };+}++const userRows = async (id: string) => (await pool.query('SELECT * FROM "user" WHERE id=$1', [id])).rows;++test("a root preload cannot relabel a stale Facts profile write as the new account's", async ({+ authPage: page,+}, info) => {+ await suppressAccountSignals(page);+ const initial = await (await page.request.get("/api/openapi/career/profile")).json();+ const aliceProfile = {+ ...initial,+ targetRoles: ["Alice private role"],+ priorities: "Alice private priorities",+ memoryMode: "ask",+ };+ expect((await page.request.put("/api/openapi/career/profile", { data: aliceProfile })).ok()).toBe(true);+ await page.goto("/dashboard/career/knowledge/facts");+ await expect(page.getByRole("radio", { name: "Never", exact: true })).toBeVisible();++ let switched: Awaited<ReturnType<typeof switchAccountInOtherTab>> | null = null;+ try {+ switched = await switchAccountInOtherTab(page);+ const before = await profileRows(switched.second.id);+ expect(before).toEqual([]);+ // Age the one-minute root session cache, as a tab left open naturally would.+ await page.evaluate(() => {+ const now = Date.now;+ Date.now = () => now() + 120_000;+ });+ const refreshed = page.waitForResponse(+ (response) => response.url().includes("/api/auth/get-session") && response.status() === 200,+ );+ await page.getByRole("link", { name: "Settings", exact: true }).hover();+ await refreshed;+ const write = page.waitForResponse((response) => response.url().includes("/api/rpc/career/saveProfile"));+ await page.getByRole("radio", { name: "Never", exact: true }).click();+ const response = await write;+ const after = await profileRows(switched.second.id);+ await info.attach("preload-stale-facts-readback", {+ body: JSON.stringify(+ {+ before,+ after,+ status: response.status(),+ header: response.request().headers()["x-account-id"],+ body: response.request().postData(),+ },+ null,+ 2,+ ),+ contentType: "application/json",+ });+ console.log(+ "RX106_READBACK preload-stale-facts",+ JSON.stringify({+ before,+ after,+ status: response.status(),+ header: response.request().headers()["x-account-id"],+ body: response.request().postData(),+ }),+ );+ expect(after).toEqual(before);+ expect(response.status()).toBe(409);+ } finally {+ await switched?.other.close();+ if (switched) await pool.query('DELETE FROM "user" WHERE id=$1', [switched.second.id]);+ }+});++test("a stale account settings tab cannot rename the account it switched to", async ({ authPage: page }, info) => {+ await suppressAccountSignals(page);+ await page.goto("/dashboard/settings/account");+ await expect(page.getByRole("textbox", { name: "Name", exact: true })).toBeVisible();++ let switched: Awaited<ReturnType<typeof switchAccountInOtherTab>> | null = null;+ try {+ switched = await switchAccountInOtherTab(page);+ const before = await userRows(switched.second.id);+ const write = page.waitForResponse((response) => response.url().includes("/api/auth/update-user"));+ await page.getByRole("textbox", { name: "Name", exact: true }).fill("Stale Alice private Name");+ await page.getByRole("textbox", { name: "Name", exact: true }).blur();+ const response = await write;+ const after = await userRows(switched.second.id);+ await info.attach("stale-auth-settings-readback", {+ body: JSON.stringify({ before, after, status: response.status() }, null, 2),+ contentType: "application/json",+ });+ console.log(+ "RX106_READBACK stale-auth-settings",+ JSON.stringify({ before: before[0]?.name, after: after[0]?.name, status: response.status() }),+ );+ expect(after).toEqual(before);+ expect(response.status()).toBe(409);++ // Positive control: a tab that committed the new session can rename it normally.+ await page.goto("/dashboard/settings/account");+ await expect(page.getByRole("textbox", { name: "Name", exact: true })).toHaveValue("RX106 Second");+ await page.getByRole("textbox", { name: "Name", exact: true }).fill("RX106 Second Renamed");+ await page.getByRole("textbox", { name: "Name", exact: true }).blur();+ await expect.poll(async () => (await userRows(switched?.second.id ?? ""))[0]?.name).toBe("RX106 Second Renamed");+ } finally {+ await switched?.other.close();+ if (switched) await pool.query('DELETE FROM "user" WHERE id=$1', [switched.second.id]);+ }+});++test("HTTP auth settings writes bound to another account are refused and leave the new account unchanged", async ({+ authPage: page,+}, info) => {+ const session = await (await page.request.get("/api/auth/get-session")).json();+ const alice = session.user.id as string;+ const second = await signUpSecondAccount(page);+ try {+ const before = await userRows(second.id);+ const origin = process.env.APP_URL ?? "";+ const stale = await page.request.post("/api/auth/update-user", {+ headers: { origin, "x-account-id": alice },+ data: { name: "Stale Alice private Name" },+ });+ const afterStale = await userRows(second.id);+ const matched = await page.request.post("/api/auth/update-user", {+ headers: { origin, "x-account-id": second.id },+ data: { name: "Second account Name" },+ });+ const afterMatched = await userRows(second.id);+ await info.attach("http-auth-binding-readback", {+ body: JSON.stringify(+ {+ alice,+ second: second.id,+ staleStatus: stale.status(),+ before,+ afterStale,+ matchedStatus: matched.status(),+ afterMatched,+ },+ null,+ 2,+ ),+ contentType: "application/json",+ });+ console.log(+ "RX106_READBACK http-auth-binding",+ JSON.stringify({+ staleStatus: stale.status(),+ before: before[0]?.name,+ afterStale: afterStale[0]?.name,+ matchedStatus: matched.status(),+ afterMatched: afterMatched[0]?.name,+ }),+ );+ expect(afterStale).toEqual(before);+ expect(stale.status()).toBe(409);+ expect(matched.ok(), await matched.text()).toBe(true);+ expect(afterMatched[0]?.name).toBe("Second account Name");+ } finally {+ await pool.query('DELETE FROM "user" WHERE id=$1', [second.id]);+ }+});