Skip to content

HarnessRouter Community Edition: the self-hosted, Apache-2.0 edition of the unified interface for agent harnesses. Run Codex, Claude Code, Hermes, PI, DSH, and more through one API, with sessions, streaming, files, cancellation, and failure handling. Implements the Unified Harness Protocol (UHP), an open standard. Your keys, your infrastructure.

fix(console): the session cookie is HttpOnly and host-only; the marketing header reads a non-secret hint (#125)

github-actions[bot]54497d93256b
diff --git a/ui/src/app/api/session/route.ts b/ui/src/app/api/session/route.ts
index b4a870e7..1ea48be5 100644
--- a/ui/src/app/api/session/route.ts
+++ b/ui/src/app/api/session/route.ts
@@ -1,11 +1,14 @@
-// Read-only cross-origin login-state probe for the marketing site header.
+// The marketing site's login-state probe, and the console's own session cookie.
//
-// The console keeps the login JWT in localStorage (origin-scoped) AND mirrors it into an
-// hr_auth cookie scoped to .harnessrouter.ai (see lib/auth.ts). The marketing apex
-// (harnessrouter.ai) can't read the app's localStorage or an HttpOnly cookie in JS, so its header
-// calls THIS endpoint with credentials:include; the cookie rides along cross-subdomain. We verify
-// it server-side via the engine's /v1/auth/me and return ONLY {authed, name, dashboardUrl} — never
-// the token. GET + no side effects, so no CSRF surface. CORS is restricted to the apex origins.
+// The console keeps the login JWT in localStorage (origin-scoped). At sign-in it POSTs the token
+// here and this route sets hr_auth as an HttpOnly, Secure, SameSite=Lax, host-only cookie; at
+// sign-out it DELETEs it. No script on any subdomain can read or remove that cookie (a JS-set copy
+// on the registrable domain used to exist, and a cleanup on the marketing site expired it on every
+// visit, signing everyone out). The marketing apex calls GET here with credentials; the app-host
+// cookie rides along, is verified server-side via the engine's /v1/auth/me, and the answer is ONLY
+// {authed, name, dashboardUrl}, never the token. GET has no side effects, so no CSRF surface; POST
+// and DELETE are same-origin only (no CORS headers on them). Self-hosted has no engine to ask and
+// no marketing header, so every answer there is "not signed in" and no cookie is written.
import type { NextRequest } from 'next/server';
import { SELF_HOSTED } from '@/lib/edition';
@@ -21,6 +24,46 @@ const ALLOWED_ORIGINS = new Set([
'https://www.harnessrouter.ai',
]);
const DASHBOARD_URL = 'https://app.harnessrouter.ai/dashboard';
+const COOKIE = 'hr_auth';
+const COOKIE_MAX_AGE = 604800; // 7 days, the session's own lifetime
+
+function cookieHeader(value: string, maxAge: number, req: NextRequest): string {
+ // host-only on purpose: no Domain attribute, so it belongs to the console host alone
+ const secure = req.nextUrl.protocol === 'https:' ? '; Secure' : '';
+ return `${COOKIE}=${encodeURIComponent(value)}; Path=/; Max-Age=${maxAge}; HttpOnly; SameSite=Lax${secure}`;
+}
+
+async function verified(token: string): Promise<{ name: string } | null> {
+ const r = await fetch(`${ENGINE.replace(/\/$/, '')}/v1/auth/me`, {
+ headers: { authorization: `Bearer ${token}` },
+ cache: 'no-store',
+ });
+ if (!r.ok) return null;
+ const d = await r.json().catch(() => null);
+ const m = d?.member || {};
+ return { name: m.name || m.email || 'Account' };
+}
+
+const plain = { 'content-type': 'application/json', 'Cache-Control': 'no-store' };
+
+/** Sign-in: the console hands its bearer over and gets the HttpOnly cookie back. */
+export async function POST(req: NextRequest) {
+ if (SELF_HOSTED || !ENGINE) return new Response(JSON.stringify({ ok: true }), { status: 200, headers: plain });
+ const auth = req.headers.get('authorization') || '';
+ const token = auth.toLowerCase().startsWith('bearer ') ? auth.slice(7).trim() : '';
+ if (!token) return new Response(JSON.stringify({ ok: false }), { status: 401, headers: plain });
+ try {
+ if (!(await verified(token))) return new Response(JSON.stringify({ ok: false }), { status: 401, headers: plain });
+ } catch {
+ return new Response(JSON.stringify({ ok: false }), { status: 503, headers: plain });
+ }
+ return new Response(JSON.stringify({ ok: true }), { status: 200, headers: { ...plain, 'Set-Cookie': cookieHeader(token, COOKIE_MAX_AGE, req) } });
+}
+
+/** Sign-out: the cookie is gone. */
+export async function DELETE(req: NextRequest) {
+ return new Response(JSON.stringify({ ok: true }), { status: 200, headers: { ...plain, 'Set-Cookie': cookieHeader('', 0, req) } });
+}
function corsHeaders(origin: string | null): Record<string, string> {
const h: Record<string, string> = {
@@ -47,23 +90,18 @@ export async function GET(req: NextRequest) {
const headers = { ...corsHeaders(origin), 'content-type': 'application/json' };
// Self-hosted has no sign-in and no engine to ask, so the answer is always "not signed in" —
// the same fail-closed answer this route already gives when the engine can't be reached.
- const token = SELF_HOSTED || !ENGINE ? '' : (req.cookies.get('hr_auth')?.value || '');
+ const token = SELF_HOSTED || !ENGINE ? '' : (req.cookies.get(COOKIE)?.value || '');
if (!token) {
return new Response(JSON.stringify({ authed: false }), { status: 200, headers });
}
try {
- const r = await fetch(`${ENGINE.replace(/\/$/, '')}/v1/auth/me`, {
- headers: { authorization: `Bearer ${token}` },
- cache: 'no-store',
- });
- if (!r.ok) {
+ const who = await verified(token);
+ if (!who) {
// expired / revoked / invalid → treat as logged out
return new Response(JSON.stringify({ authed: false }), { status: 200, headers });
}
- const d = await r.json().catch(() => null);
- const m = d?.member || {};
return new Response(
- JSON.stringify({ authed: true, name: m.name || m.email || 'Account', dashboardUrl: DASHBOARD_URL }),
+ JSON.stringify({ authed: true, name: who.name, dashboardUrl: DASHBOARD_URL }),
{ status: 200, headers },
);
} catch {
diff --git a/ui/src/lib/auth.ts b/ui/src/lib/auth.ts
index c75d39e4..ebb5da51 100644
--- a/ui/src/lib/auth.ts
+++ b/ui/src/lib/auth.ts
@@ -55,33 +55,51 @@ export function getSession(): Session | null {
* snapshot (e.g. the dock avatar) can re-read without a reload. */
export const SESSION_EVENT = 'agentstudio:session';
-// Cross-subdomain login-state cookie. The JWT lives in localStorage (origin-scoped, so the
-// marketing apex can't read it). To let harnessrouter.ai's header reflect login without exposing
-// the app's storage, we ALSO mirror the token into a cookie scoped to the registrable domain
-// (Domain=.harnessrouter.ai) — sent to both app. and the apex. The apex never reads this cookie in
-// JS; it calls GET /api/session on the app origin, which reads the cookie server-side and returns
-// only {authed, name}. On localhost/preview (not *.harnessrouter.ai) the Domain attribute is
-// omitted so the cookie still works same-origin.
-const AUTH_COOKIE = 'hr_auth';
+// Login state for the marketing site, without a script-readable token anywhere.
+//
+// The JWT lives in localStorage (origin-scoped). The marketing apex (harnessrouter.ai) wants to
+// know whether the visitor is signed in; it asks GET /api/session on the app origin with
+// credentials, and that route answers from an hr_auth cookie it verifies server-side. That cookie
+// is set by the console's own route (POST /api/session) as HttpOnly, Secure, SameSite=Lax and
+// host-only, so no script on any subdomain can read or delete it. A JS-set copy on
+// Domain=.harnessrouter.ai used to do this job; the marketing site's cleanup expired it on every
+// visit and signed everyone out (2026-09-06).
+//
+// hr_logged_in=1 on the registrable domain is the header's fast path: non-secret, carries nothing,
+// grants nothing; a stale or forged value changes a label and nothing more.
+const HINT_COOKIE = 'hr_logged_in';
+const LEGACY_AUTH_COOKIE = 'hr_auth';
function _cookieDomain(): string {
if (typeof window === 'undefined') return '';
return window.location.hostname.endsWith('harnessrouter.ai') ? '; Domain=.harnessrouter.ai' : '';
}
-function setAuthCookie(token: string): void {
+function _secure(): string {
+ return typeof window !== 'undefined' && window.location.protocol === 'https:' ? '; Secure' : '';
+}
+function setLoginHint(): void {
+ if (typeof window === 'undefined') return;
+ document.cookie = `${HINT_COOKIE}=1; Path=/; Max-Age=604800${_cookieDomain()}; SameSite=Lax${_secure()}`;
+ // the JS-set token cookie of earlier builds: gone for good on the domain it was written to
+ document.cookie = `${LEGACY_AUTH_COOKIE}=; Path=/; Max-Age=0${_cookieDomain()}; SameSite=Lax`;
+}
+function clearLoginHint(): void {
if (typeof window === 'undefined') return;
- const secure = window.location.protocol === 'https:' ? '; Secure' : '';
- // 7-day lifetime matches the session; SameSite=Lax so top-level navigations from the apex carry it.
- document.cookie = `${AUTH_COOKIE}=${encodeURIComponent(token)}; Path=/; Max-Age=604800${_cookieDomain()}; SameSite=Lax${secure}`;
+ document.cookie = `${HINT_COOKIE}=; Path=/; Max-Age=0${_cookieDomain()}; SameSite=Lax`;
+ document.cookie = `${LEGACY_AUTH_COOKIE}=; Path=/; Max-Age=0${_cookieDomain()}; SameSite=Lax`;
}
-function clearAuthCookie(): void {
+/** The console's own route sets or clears the HttpOnly session cookie the marketing probe reads.
+ * Best effort: the console never depends on it (its calls carry the bearer from storage). */
+function syncServerCookie(token: string | null): void {
if (typeof window === 'undefined') return;
- document.cookie = `${AUTH_COOKIE}=; Path=/; Max-Age=0${_cookieDomain()}; SameSite=Lax`;
+ void fetch('/api/session', token
+ ? { method: 'POST', headers: { authorization: `Bearer ${token}` }, cache: 'no-store' }
+ : { method: 'DELETE', cache: 'no-store' }).catch(() => { /* the header shows Sign up until the next sign-in */ });
}
function setSession(s: Session): void {
if (typeof window !== 'undefined') {
window.localStorage.setItem(SESSION_KEY, JSON.stringify(s));
- if (s.token) setAuthCookie(s.token);
+ if (s.token) { setLoginHint(); syncServerCookie(s.token); }
window.dispatchEvent(new CustomEvent(SESSION_EVENT));
}
}
@@ -89,7 +107,8 @@ function setSession(s: Session): void {
export function clearSession(): void {
if (typeof window !== 'undefined') {
window.localStorage.removeItem(SESSION_KEY);
- clearAuthCookie();
+ clearLoginHint();
+ syncServerCookie(null);
}
}