Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
88 changes: 87 additions & 1 deletion apps/web/src/lib/account-shell.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,8 @@ vi.mock("./auth-client", async (importOriginal) => ({
...auth,
}));

import { resolveSessionGate, type SessionGateOptions } from "./account-shell";
import { resolveSessionGate, SESSION_CACHE_KEY, type SessionGateOptions } from "./account-shell";
import { markPageLoad, resetPageVisitForTests } from "./page-visit";

function element(): HTMLElement {
return { hidden: false, textContent: "" } as HTMLElement;
Expand Down Expand Up @@ -63,9 +64,15 @@ afterEach(() => {
auth.getSession.mockReset();
auth.signOut.mockReset();
auth.startLocalDemoSession.mockReset();
resetPageVisitForTests();
vi.unstubAllGlobals();
});

/** Resolves once queued zero-delay retry timers and their promises have run. */
function flushRetries(): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, 10));
}

describe("resolveSessionGate", () => {
it("shows unavailable when local demo session creation cannot reach Auth", async () => {
installBrowser();
Expand Down Expand Up @@ -148,6 +155,85 @@ describe("resolveSessionGate", () => {
expect(options.app.hidden).toBe(true);
});

it("keeps the shell visible on auth-unavailable when an identity is cached", async () => {
const { values } = installBrowser();
values.set(
SESSION_CACHE_KEY,
JSON.stringify({ id: "user", email: "user@example.com", name: "User", role: "user" }),
);
markPageLoad();
const options = { ...gate(), retryDelaysMs: [0] };
const session = {
session: {},
user: { id: "user", email: "user@example.com", name: "User", role: "user" },
};
auth.getSession
.mockResolvedValueOnce({ kind: "unavailable", reason: "server" })
.mockResolvedValueOnce({ kind: "signed_in", session });

await expect(resolveSessionGate(options)).resolves.toBeNull();
expect(options.app.hidden).toBe(false);
expect(options.unavailable.hidden).toBe(true);

await flushRetries();
expect(auth.getSession).toHaveBeenCalledTimes(2);
expect(options.app.hidden).toBe(false);
expect(values.get(SESSION_CACHE_KEY)).toContain("user@example.com");
});

it("keeps the shell visible when every background retry stays unavailable", async () => {
const { values } = installBrowser();
values.set(
SESSION_CACHE_KEY,
JSON.stringify({ id: "user", email: "user@example.com", name: "User", role: "user" }),
);
markPageLoad();
const options = { ...gate(), retryDelaysMs: [0, 0] };
auth.getSession.mockResolvedValue({ kind: "unavailable", reason: "server" });

await expect(resolveSessionGate(options)).resolves.toBeNull();
await flushRetries();
await flushRetries();
expect(auth.getSession).toHaveBeenCalledTimes(3);
expect(options.app.hidden).toBe(false);
expect(options.unavailable.hidden).toBe(true);
});

it("still blocks on auth-unavailable when no identity is known", async () => {
installBrowser();
const options = gate();
auth.getSession.mockResolvedValue({ kind: "unavailable", reason: "server" });

await expect(resolveSessionGate(options)).resolves.toBeNull();
expect(options.unavailable.hidden).toBe(false);
expect(options.app.hidden).toBe(true);
});

it("redirects to login when a background retry finds the session signed out", async () => {
const replace = vi.fn();
const { values } = installBrowser();
vi.stubGlobal("location", {
origin: "https://uploads.sh",
pathname: "/account",
search: "",
replace,
});
values.set(
SESSION_CACHE_KEY,
JSON.stringify({ id: "user", email: "user@example.com", name: "User", role: "user" }),
);
markPageLoad();
const options = { ...gate(), retryDelaysMs: [0] };
auth.getSession
.mockResolvedValueOnce({ kind: "unavailable", reason: "server" })
.mockResolvedValueOnce({ kind: "signed_out" });

await expect(resolveSessionGate(options)).resolves.toBeNull();
await flushRetries();
expect(replace).toHaveBeenCalledWith("/login?callbackURL=%2Faccount");
expect(values.has(SESSION_CACHE_KEY)).toBe(false);
});

it("shows the app without a who node when the header owns session UI", async () => {
installBrowser();
const options = {
Expand Down
60 changes: 59 additions & 1 deletion apps/web/src/lib/account-shell.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ import {
type SessionResponse,
type SessionUser,
} from "./auth-client";
import { markPageLoad } from "./page-visit";
import { getPageVisit, isCurrentPageVisit, markPageLoad } from "./page-visit";
import { loginHref } from "./signed-in-page";
import { clearWorkspaceSnapshots } from "./workspace-cache";

Expand Down Expand Up @@ -155,8 +155,53 @@ export type SessionGateOptions = {
who?: HTMLElement | null;
/** When set, only accept sessions with this `user.role` (e.g. `"admin"`). */
requireRole?: string;
/** Test seam: background-retry delays after an "unavailable" revalidation. */
retryDelaysMs?: number[];
};

/**
* Background revalidation retries after "auth unavailable" with a cached
* identity (2026-08-23 D1 stall incident): auth outages come in ~10s windows,
* so a shell kept visible usually revalidates successfully on the next try.
* Spread wider than a stall window; give up quietly after the last one — the
* next navigation re-gates anyway.
*/
const UNAVAILABLE_RETRY_DELAYS_MS = [10_000, 30_000, 60_000];

function retryGateInBackground(options: SessionGateOptions): void {
const visit = getPageVisit();
const delays = options.retryDelaysMs ?? UNAVAILABLE_RETRY_DELAYS_MS;
let attempt = 0;
const tick = (): void => {
if (attempt >= delays.length) return;
const delay = delays[attempt++];
setTimeout(() => {
if (!isCurrentPageVisit(visit)) return;
void getSession(options.authOrigin).then((result) => {
if (!isCurrentPageVisit(visit)) return;
if (result.kind === "unavailable") {
tick();
return;
}
if (result.kind === "signed_out") {
clearCachedSessionUser();
redirectToSignIn();
return;
}
if (options.requireRole && result.session.user.role !== options.requireRole) {
clearCachedSessionUser();
showDenied(options);
return;
}
writeCachedSessionUser(result.session.user);
showApp(result.session.user, options);
publishSession(result.session.user, true);
});
}, delay);
};
tick();
}

/**
* Toggle checking / denied / app shells from the session.
*
Expand Down Expand Up @@ -186,6 +231,19 @@ export async function resolveSessionGate(
}

if (result.kind === "unavailable") {
// An auth outage is not a sign-out. With a known identity the shell is
// already painted (cache or SSR seed) — keep it up and revalidate in the
// background instead of blanking the whole app; per-request auth is still
// enforced server-side on every API call. Only a visit with no identity
// at all gets the blocking "try again" screen.
if (cached) {
// Re-assert the shell state: showApp(cached) ran before the network
// check, but make the outage panel's hidden state explicit here too.
showApp(cached, options);
options.unavailable.hidden = true;
retryGateInBackground(options);
return null;
}
showUnavailable(options);
return null;
}
Expand Down
Loading