mirror of
https://github.com/NousResearch/hermes-agent.git
synced 2026-06-01 07:01:41 +00:00
feat(dashboard-auth): Phase 6 — 401 re-auth envelope + next= propagation
Contract V1 of nous-account-service PR #180 ships no refresh tokens, so the original Phase 6 silent-refresh design is replaced with a thinner '401 → redirect to /login' UX. The dashboard's gated middleware now emits a structured envelope on any auth failure; the SPA's fetch wrapper sees it and full-page-navigates the user through re-auth. hermes_cli/dashboard_auth/cookies.py: set_session_cookies(refresh_token='') SKIPS writing the hermes_session_rt cookie. Forward-compat: a non-empty refresh_token still emits the cookie unchanged, so a future Portal contract that starts issuing RTs flips the persistence on with no other change. clear_session_cookies still emits a Max-Age=0 deletion for the RT cookie so stale cookies from earlier deployments get flushed on logout / session expiry. Deprecation marker + rationale in module docstring per the user's docstring-only deprecation pattern. hermes_cli/dashboard_auth/middleware.py: _unauth_response now builds a structured JSON envelope for API 401s: { error: 'session_expired' | 'unauthenticated', detail: 'Unauthorized', reason: <internal>, login_url: '/login?next=<safe-path>' } HTML redirects also carry next= so a user landing on /sessions without a cookie bounces back to /sessions after re-auth. _safe_next_target validates same-origin: drops protocol-relative paths (//evil.com), absolute URLs, and any /login or /auth/* loop. Dead cookies are cleared on the 401 path so the browser stops replaying invalid tokens. hermes_cli/dashboard_auth/routes.py: /auth/callback accepts next= query param and validates via _validate_post_login_target (same rules as the gate's _safe_next_target — defence-in-depth because next= survived a full IDP round trip and attacker-controlled state can re-enter via the callback URL). Open-redirect attempts land at '/' instead. web/src/lib/api.ts: fetchJSON parses the 401 envelope and full-page-navigates to body.login_url ONLY on the known session-expiry error codes. Domain-level 401s (e.g. permission errors) bubble up as regular errors. credentials: 'include' added so cookie auth works for all fetches routed through this wrapper. sessionStorage.lastLocation is preserved for future use by AuthWidget / hermes_status. Test files marked with pytest.mark.xdist_group so the four files that mutate web_server.app.state.auth_required serialize onto the same xdist worker — eliminates 'works locally, fails in CI' app-state bleed. 20 new tests in test_dashboard_auth_401_reauth.py: - set_session_cookies(refresh_token='') skips RT cookie - clear_session_cookies still emits RT deletion - 401 envelope shape (unauthenticated vs session_expired) - dead cookie cleared on invalid-token 401 - login_url carries next= for deep paths - login loop avoided when path is /login/auth/api-auth - protocol-relative URL rejected - _safe_next_target unit tests (accept same-origin, reject loops/abs) - /auth/callback respects safe next= but rejects open redirects 2 pre-existing tests updated to accept the new /login?next=%2F shape. Full dashboard-auth suite: 168 passed, 1 skipped (Phase 0 pre-existing).
This commit is contained in:
parent
8971e94831
commit
5e9308b5b8
8 changed files with 506 additions and 22 deletions
|
|
@ -48,7 +48,50 @@ export async function fetchJSON<T>(url: string, init?: RequestInit): Promise<T>
|
|||
if (token) {
|
||||
setSessionHeader(headers, token);
|
||||
}
|
||||
const res = await fetch(`${BASE}${url}`, { ...init, headers });
|
||||
const res = await fetch(`${BASE}${url}`, {
|
||||
...init,
|
||||
headers,
|
||||
// ``credentials: 'include'`` so the cookie-auth path (gated mode) works
|
||||
// for any fetch routed through here. Loopback mode is unaffected — the
|
||||
// server doesn't read cookies and the legacy session-token header is
|
||||
// already attached above.
|
||||
credentials: init?.credentials ?? "include",
|
||||
});
|
||||
if (res.status === 401) {
|
||||
// Phase 6: the gated middleware emits a structured envelope so the
|
||||
// SPA can full-page-navigate to /login on session expiry. Parse it,
|
||||
// and only redirect on the known error codes — domain-level 401s
|
||||
// (e.g. "you don't have permission to read this monitor") bubble
|
||||
// up as regular errors so callers can handle them.
|
||||
let body: { error?: string; login_url?: string } = {};
|
||||
try {
|
||||
body = await res.clone().json();
|
||||
} catch {
|
||||
/* non-JSON 401 — let it fall through */
|
||||
}
|
||||
if (
|
||||
(body.error === "unauthenticated" || body.error === "session_expired") &&
|
||||
body.login_url
|
||||
) {
|
||||
// Preserve where the user was so /auth/callback can land them back
|
||||
// after re-auth. The gate's login_url already carries a ``next=``
|
||||
// built from the request path, but the SPA may be deep inside a
|
||||
// SPA route the gate never saw — e.g. a hash route or a client-side
|
||||
// /sessions/<id> deep link. Save the current location as a
|
||||
// fallback the post-login handler can read.
|
||||
try {
|
||||
sessionStorage.setItem(
|
||||
"hermes.lastLocation",
|
||||
window.location.pathname + window.location.search,
|
||||
);
|
||||
} catch {
|
||||
/* SSR / privacy mode — ignore */
|
||||
}
|
||||
window.location.assign(body.login_url);
|
||||
// Never resolve — the page is about to unload.
|
||||
return new Promise<T>(() => {});
|
||||
}
|
||||
}
|
||||
if (!res.ok) {
|
||||
const text = await res.text().catch(() => res.statusText);
|
||||
throw new Error(`${res.status}: ${text}`);
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue