Being signed out and picking up a new version are separate things, and only the first was happening. An immutable instance holds sessions in memory, so a deploy signs everyone out -- but a 401 only swaps the view to the sign-in form, client-side. The tab keeps the bundle it already has, and the old JavaScript goes on talking to the new server until someone happens to reload by hand. The pieces for fixing it were already there. index.html is served no-cache and the assets under it are content-hashed and immutable, so a reload is all it takes; Vite bakes the build's own version in as APP_VERSION; and /api/health reports the server's. What was missing was something to compare them. The check runs on a 401 rather than on a timer, which is the moment it matters and costs one small request. It compares versions rather than reloading on every 401, so an ordinary session expiry still lands on the sign-in form with the page intact. And it runs before the sign-in form is shown rather than after, because reloading a form someone has already started typing into would throw the password away. Failing to reach the server is not a reason to throw away what is on screen, so anything other than a clear answer leaves the page alone. The version that was reloaded for is remembered for the session, so a server that keeps reporting a version the bundle does not match -- a stale proxy cache, a half-finished deploy -- cannot put the tab in a reload loop.
136 lines
4.4 KiB
TypeScript
136 lines
4.4 KiB
TypeScript
import { create } from "zustand";
|
|
import { apiFetch, ApiError, CAP, client } from "@/jmap/client";
|
|
import type { Id, JmapSession } from "@/jmap/types";
|
|
import { push, type PushState } from "@/jmap/push";
|
|
import { accountForCapability, ownAccountForCapability } from "@/lib/accountRouting";
|
|
import { setServerLocale } from "@/lib/datetime";
|
|
import { flushSettingsPush, stopSettingsSync } from "@/lib/settingsSync";
|
|
import { reloadIfServerRebuilt } from "@/lib/staleBuild";
|
|
import { unsubscribeThisDevice } from "@/lib/webpush";
|
|
|
|
export type AuthStatus = "loading" | "anonymous" | "authenticated";
|
|
|
|
interface SessionState {
|
|
status: AuthStatus;
|
|
session: JmapSession | null;
|
|
/** Selected mail account (defaults to primary). */
|
|
accountId: Id | null;
|
|
error: string | null;
|
|
pushConnected: boolean;
|
|
/** Finer than pushConnected: tells "reconnecting" from "not connected". */
|
|
pushState: PushState;
|
|
bootstrap(): Promise<void>;
|
|
login(username: string, password: string, totp: string, remember: boolean): Promise<void>;
|
|
logout(): Promise<void>;
|
|
refresh(): Promise<void>;
|
|
setAccount(id: Id): void;
|
|
/** The account to read and write for a capability, honouring the account switcher. */
|
|
accountFor(cap: string): Id | null;
|
|
/** The user's own account for a capability, whatever they are looking at. */
|
|
ownAccountFor(cap: string): Id | null;
|
|
}
|
|
|
|
export const useSession = create<SessionState>((set, get) => ({
|
|
status: "loading",
|
|
session: null,
|
|
accountId: null,
|
|
error: null,
|
|
pushConnected: false,
|
|
pushState: "disconnected",
|
|
|
|
async bootstrap() {
|
|
try {
|
|
const s = await apiFetch<JmapSession>("/api/auth/session");
|
|
applySession(s, set);
|
|
} catch (err) {
|
|
if (err instanceof ApiError && err.status === 401) set({ status: "anonymous", session: null, accountId: null });
|
|
else set({ status: "anonymous", error: (err as Error).message });
|
|
}
|
|
},
|
|
|
|
async login(username, password, totp, remember) {
|
|
set({ error: null });
|
|
const s = await apiFetch<JmapSession>("/api/auth/login", {
|
|
method: "POST",
|
|
body: JSON.stringify({ username, password, totp: totp || undefined, remember }),
|
|
});
|
|
applySession(s, set);
|
|
},
|
|
|
|
async logout() {
|
|
push.stop();
|
|
setServerLocale(null);
|
|
// Anything still sitting in the debounce is written while the session can
|
|
// still write it; a setting changed seconds before signing out is not lost.
|
|
try {
|
|
await flushSettingsPush();
|
|
} catch {
|
|
/* ignore */
|
|
}
|
|
// A push subscription lives on the account, not the session, so signing out
|
|
// without removing it leaves this browser notifying for a mailbox nobody is
|
|
// signed into. On a shared machine that is somebody else's mail.
|
|
try {
|
|
await unsubscribeThisDevice();
|
|
} catch {
|
|
/* never block signing out over this */
|
|
}
|
|
stopSettingsSync();
|
|
try {
|
|
await apiFetch("/api/auth/logout", { method: "POST" });
|
|
} catch {
|
|
/* ignore */
|
|
}
|
|
client.session = null;
|
|
set({ status: "anonymous", session: null, accountId: null });
|
|
},
|
|
|
|
async refresh() {
|
|
try {
|
|
const s = await apiFetch<JmapSession>("/api/auth/session?refresh=1");
|
|
client.session = s;
|
|
setServerLocale(s.ihasmail?.userLocale);
|
|
set({ session: s });
|
|
} catch {
|
|
/* ignore */
|
|
}
|
|
},
|
|
|
|
setAccount(id) {
|
|
set({ accountId: id });
|
|
},
|
|
|
|
accountFor(cap) {
|
|
return accountForCapability(get().session, get().accountId, cap);
|
|
},
|
|
|
|
ownAccountFor(cap) {
|
|
return ownAccountForCapability(get().session, cap);
|
|
},
|
|
}));
|
|
|
|
function applySession(s: JmapSession, set: (p: Partial<SessionState>) => void) {
|
|
client.session = s;
|
|
setServerLocale(s.ihasmail?.userLocale);
|
|
const accountId = s.primaryAccounts[CAP.mail] ?? Object.keys(s.accounts)[0] ?? null;
|
|
set({ status: "authenticated", session: s, accountId, error: null });
|
|
}
|
|
|
|
client.onUnauthenticated(() => {
|
|
push.stop();
|
|
stopSettingsSync();
|
|
client.session = null;
|
|
// Ask before showing the sign-in form rather than after. A deploy is the
|
|
// usual reason to be signed out here, and reloading a form someone has
|
|
// already started typing into would throw the password away.
|
|
void reloadIfServerRebuilt().then((reloading) => {
|
|
if (!reloading) useSession.setState({ status: "anonymous", session: null, accountId: null });
|
|
});
|
|
});
|
|
|
|
push.onConnection((state) => useSession.setState({ pushConnected: state === "connected", pushState: state }));
|
|
|
|
export function hasCap(cap: string): boolean {
|
|
return client.hasCapability(cap);
|
|
}
|