Make tokens revocable and move the refresh token out of localStorage (0.46.0)
CI / check (push) Successful in 7m7s
CI / build-and-push (push) Successful in 1m44s

F5 — A token was valid until it expired, full stop. Resetting a compromised
account's password changed nothing for whoever held its tokens (up to 30 days
for a refresh token), demoting or disabling an account only took effect once
the same clock ran out, and logout was purely client-side.

Every account now has a token_version, every token is minted carrying it, and
every request compares the two. Bumping it is the revoke switch, pulled on the
three changes that alter what an account may do: password, role, active flag.
"Sign out everywhere" in the user menu bumps your own. Plain "Sign out" only
drops the cookie, because signing out on your phone should not kill your
desktop session.

The refresh token left localStorage for an httpOnly cookie (SameSite=Lax,
scoped to /api/auth), and the access token is now held in memory only. A
successful XSS can still act inside the open page but can no longer walk off
with 30 days of access. The cookie is marked Secure only when the request
arrived over HTTPS — request.url.scheme is trustworthy since the F4 fix — so a
plain-HTTP homelab keeps working. Any refresh token an older build left in
localStorage is deleted on first load. Scripted clients that cannot hold a
cookie can still ask for it in the body with ?in_body=true.

F9 comes with it, as predicted: the WebSocket helpers read the role off the
live user instead of the token's claim. /ws/exec is root-equivalent on the
host, and a token minted while the account was an admin stayed syntactically
valid after a demotion.

The sharp edge was the migration, not the feature. _ensure_model_columns emits
ADD COLUMN without a DEFAULT, so SQLite would have filled token_version with
NULL on every existing install, every version check would have failed against
it, and the upgrade would have locked out every user everywhere. The helper now
renders NOT NULL DEFAULT <literal> for scalar defaults; test_schema_migration
builds a genuinely old-shaped user table and asserts the backfill. The version
comparison also tolerates NULL as 1, so a database migrated by some other route
still works.

Writing that test surfaced an undocumented precondition: _ensure_model_columns
does nothing unless `models` has been imported, since SQLModel.metadata is
empty until then. It holds in production because init_db imports first; now it
says so.

The authorization matrix did its job — adding two auth routes failed the suite
until both were classified, which is exactly the review moment it exists for.

30 new tests (698 total). Upgrading signs everyone out once.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Dk43rmEeRfYi5wsLDbmfyG
This commit is contained in:
menzelj
2026-08-31 13:31:00 +02:00
co-authored by Claude Opus 5
parent 60a7ccff93
commit 41a21b5a25
15 changed files with 840 additions and 114 deletions
+21 -4
View File
@@ -19,21 +19,38 @@ import { useThemeStore } from "@/store/theme";
function RequireAuth() {
const token = useAuthStore((s) => s.accessToken);
const ready = useAuthStore((s) => s.ready);
// The access token lives in memory, so on a reload we have nothing until the
// cookie-based restore has run. Bouncing to /login before that would sign
// people out on every refresh.
if (!ready) return <BootSplash />;
return token ? <Outlet /> : <Navigate to="/login" replace />;
}
function BootSplash() {
return (
<div className="flex min-h-screen items-center justify-center bg-bg dark:bg-bg-dark">
<span className="sr-only">Restoring your session</span>
<div
aria-hidden="true"
className="h-8 w-8 animate-spin rounded-full border-2 border-slate-300 border-t-accent dark:border-slate-600 dark:border-t-accent-dark"
/>
</div>
);
}
export default function App() {
const applyTheme = useThemeStore((s) => s.apply);
const fetchMe = useAuthStore((s) => s.fetchMe);
const token = useAuthStore((s) => s.accessToken);
const restore = useAuthStore((s) => s.restore);
useEffect(() => {
applyTheme();
}, [applyTheme]);
// Trade the httpOnly refresh cookie for an access token once on boot.
useEffect(() => {
if (token) fetchMe().catch(() => {});
}, [token, fetchMe]);
restore();
}, [restore]);
return (
<BrowserRouter>
+4 -2
View File
@@ -1,7 +1,8 @@
import axios, { AxiosError } from "axios";
import { useAuthStore } from "@/store/auth";
const api = axios.create({ baseURL: "/" });
// withCredentials so the httpOnly refresh cookie rides along on /api/auth/refresh.
const api = axios.create({ baseURL: "/", withCredentials: true });
api.interceptors.request.use((config) => {
const token = useAuthStore.getState().accessToken;
@@ -32,7 +33,8 @@ api.interceptors.response.use(
original.headers.Authorization = `Bearer ${newToken}`;
return api(original);
}
useAuthStore.getState().logout();
// Refresh failed: the session is genuinely over (expired, password
// changed, account disabled). refresh() has already cleared the store.
}
return Promise.reject(error);
}
+12 -2
View File
@@ -14,6 +14,7 @@ import {
Moon,
Sun,
LogOut,
ShieldOff,
Menu,
X,
} from "lucide-react";
@@ -87,6 +88,7 @@ export function TopNav() {
const user = useAuthStore((s) => s.user);
const navItems = NAV_ITEMS.filter((i) => !i.adminOnly || user?.role === "admin");
const logout = useAuthStore((s) => s.logout);
const signOutEverywhere = useAuthStore((s) => s.signOutEverywhere);
const { theme, toggle } = useThemeStore();
const agents = useQuery({
@@ -198,11 +200,19 @@ export function TopNav() {
{user?.role === "admin" && <p className="sp-label mt-0.5">admin</p>}
</div>
<button
onClick={logout}
onClick={() => void logout()}
className="flex w-full items-center gap-2 rounded-lg px-3 py-2 text-sm text-sp-text-2 hover:bg-sp-surface-2 hover:text-sp-text-1"
>
<LogOut className="h-4 w-4" />
Logout
Sign out
</button>
<button
onClick={() => void signOutEverywhere()}
title="Revokes every token this account holds, on every device"
className="flex w-full items-center gap-2 rounded-lg px-3 py-2 text-sm text-sp-text-2 hover:bg-sp-surface-2 hover:text-sp-text-1"
>
<ShieldOff className="h-4 w-4" />
Sign out everywhere
</button>
</div>
)}
+102 -57
View File
@@ -1,78 +1,123 @@
import axios from "axios";
import { create } from "zustand";
import { persist } from "zustand/middleware";
import type { TokenPair, User } from "@/types";
/**
* Session state.
*
* The access token lives **in memory only** — deliberately not in
* localStorage. The long-lived refresh token is an httpOnly cookie the browser
* holds and JavaScript cannot read, so a successful XSS can act inside the open
* page but cannot walk off with 30 days of access.
*
* The cost is that a page reload starts with no token; `restore()` trades the
* cookie for a fresh one on boot, which is why the app shows a brief loading
* state instead of jumping straight to the login screen.
*/
interface AuthState {
accessToken: string | null;
refreshToken: string | null;
user: User | null;
setTokens: (t: TokenPair) => void;
/** False until the initial cookie-based restore has settled. */
ready: boolean;
login: (username: string, password: string) => Promise<void>;
setup: (username: string, password: string) => Promise<void>;
restore: () => Promise<void>;
refresh: () => Promise<string | null>;
fetchMe: () => Promise<void>;
logout: () => void;
logout: () => Promise<void>;
signOutEverywhere: () => Promise<void>;
}
// Raw client without interceptors (avoids refresh loops).
const raw = axios.create({ baseURL: "/" });
const raw = axios.create({ baseURL: "/", withCredentials: true });
export const useAuthStore = create<AuthState>()(
persist(
(set, get) => ({
accessToken: null,
refreshToken: null,
user: null,
// Before 0.46.0 both tokens were persisted here by zustand/persist. Upgrading
// users still have a valid 30-day refresh token sitting in localStorage, which
// is exactly what this change exists to remove — so drop it on first load.
try {
localStorage.removeItem("stackpilot-auth");
} catch {
/* private mode / storage disabled */
}
setTokens: (t) =>
set({ accessToken: t.access_token, refreshToken: t.refresh_token }),
export const useAuthStore = create<AuthState>()((set, get) => ({
accessToken: null,
user: null,
ready: false,
login: async (username, password) => {
const { data } = await raw.post<TokenPair>("/api/auth/login", {
username,
password,
});
set({ accessToken: data.access_token, refreshToken: data.refresh_token });
await get().fetchMe();
},
login: async (username, password) => {
const { data } = await raw.post<TokenPair>("/api/auth/login", { username, password });
set({ accessToken: data.access_token });
await get().fetchMe();
},
setup: async (username, password) => {
const { data } = await raw.post<TokenPair>("/api/auth/setup", {
username,
password,
role: "admin",
});
set({ accessToken: data.access_token, refreshToken: data.refresh_token });
await get().fetchMe();
},
setup: async (username, password) => {
const { data } = await raw.post<TokenPair>("/api/auth/setup", {
username,
password,
role: "admin",
});
set({ accessToken: data.access_token });
await get().fetchMe();
},
refresh: async () => {
const rt = get().refreshToken;
if (!rt) return null;
try {
const { data } = await raw.post<TokenPair>("/api/auth/refresh", {
refresh_token: rt,
});
set({ accessToken: data.access_token, refreshToken: data.refresh_token });
return data.access_token;
} catch {
set({ accessToken: null, refreshToken: null, user: null });
return null;
}
},
// Called once on boot: if the refresh cookie is still good we come back
// signed in, otherwise we land on the login screen.
restore: async () => {
try {
const token = await get().refresh();
if (token) await get().fetchMe();
} catch {
/* not signed in */
} finally {
set({ ready: true });
}
},
fetchMe: async () => {
const token = get().accessToken;
if (!token) return;
const { data } = await raw.get<User>("/api/auth/me", {
headers: { Authorization: `Bearer ${token}` },
});
set({ user: data });
},
refresh: async () => {
try {
const { data } = await raw.post<TokenPair>("/api/auth/refresh", {});
set({ accessToken: data.access_token });
return data.access_token;
} catch {
set({ accessToken: null, user: null });
return null;
}
},
logout: () => set({ accessToken: null, refreshToken: null, user: null }),
}),
{ name: "stackpilot-auth" }
)
);
fetchMe: async () => {
const token = get().accessToken;
if (!token) return;
const { data } = await raw.get<User>("/api/auth/me", {
headers: { Authorization: `Bearer ${token}` },
});
set({ user: data });
},
logout: async () => {
// Clear locally first so the UI never sits on a dead session if the
// request fails; the server call only drops the cookie.
set({ accessToken: null, user: null });
try {
await raw.post("/api/auth/logout", {});
} catch {
/* already gone */
}
},
// Bumps the account's token version, so every token it holds — on every
// device — stops working. The thing to reach for when a device is lost.
signOutEverywhere: async () => {
const token = get().accessToken;
try {
await raw.post(
"/api/auth/logout-everywhere",
{},
{ headers: token ? { Authorization: `Bearer ${token}` } : {} }
);
} finally {
set({ accessToken: null, user: null });
}
},
}));