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.

feat(selfhost): a real sign-in form and a sign-out, where the hosted console puts them

richard-epsillac026aa2a0dfb
diff --git a/ui/src/app/api/selfhost/login/route.ts b/ui/src/app/api/selfhost/login/route.ts
new file mode 100644
index 00000000..c8e8a46c
--- /dev/null
+++ b/ui/src/app/api/selfhost/login/route.ts
@@ -0,0 +1,36 @@
+// Sign in to a self-hosted instance. Sets the session cookie; the middleware does the checking.
+import type { NextRequest } from 'next/server';
+import {
+ AUTH_DISABLED, SELF_HOSTED, SESSION_COOKIE, SESSION_TTL_MS, credentialsValid, mintSession,
+} from '@/lib/selfhost-auth';
+
+export const runtime = 'nodejs';
+export const dynamic = 'force-dynamic';
+
+/** Deliberately uniform: "user not found" and "wrong password" are the same answer, because the
+ * difference only helps someone who doesn't know either. */
+const REJECT = { detail: 'Incorrect username or password.' };
+
+export async function POST(req: NextRequest) {
+ if (!SELF_HOSTED || AUTH_DISABLED) {
+ return Response.json({ detail: 'sign-in is not enabled on this instance' }, { status: 404 });
+ }
+ let body: { username?: string; password?: string };
+ try {
+ body = await req.json();
+ } catch {
+ return Response.json(REJECT, { status: 401 });
+ }
+ if (!credentialsValid(String(body.username || ''), String(body.password || ''))) {
+ // A small delay costs an honest user nothing and makes online guessing tediously slow.
+ await new Promise((r) => setTimeout(r, 400));
+ return Response.json(REJECT, { status: 401 });
+ }
+
+ const res = Response.json({ ok: true });
+ const secure = req.nextUrl.protocol === 'https:' ? '; Secure' : '';
+ res.headers.set('set-cookie',
+ `${SESSION_COOKIE}=${await mintSession()}; Path=/; Max-Age=${Math.floor(SESSION_TTL_MS / 1000)}`
+ + `; HttpOnly; SameSite=Lax${secure}`);
+ return res;
+}
diff --git a/ui/src/app/api/selfhost/logout/route.ts b/ui/src/app/api/selfhost/logout/route.ts
new file mode 100644
index 00000000..1b1ed5fe
--- /dev/null
+++ b/ui/src/app/api/selfhost/logout/route.ts
@@ -0,0 +1,15 @@
+// Sign out: clear the session cookie. The cookie IS the session (signed, not stored), so
+// expiring it here is the whole of it.
+import type { NextRequest } from 'next/server';
+import { SESSION_COOKIE } from '@/lib/selfhost-auth';
+
+export const runtime = 'nodejs';
+export const dynamic = 'force-dynamic';
+
+export async function POST(req: NextRequest) {
+ const res = Response.json({ ok: true });
+ const secure = req.nextUrl.protocol === 'https:' ? '; Secure' : '';
+ res.headers.set('set-cookie',
+ `${SESSION_COOKIE}=; Path=/; Max-Age=0; HttpOnly; SameSite=Lax${secure}`);
+ return res;
+}
diff --git a/ui/src/app/api/selfhost/session/route.ts b/ui/src/app/api/selfhost/session/route.ts
new file mode 100644
index 00000000..874e29c9
--- /dev/null
+++ b/ui/src/app/api/selfhost/session/route.ts
@@ -0,0 +1,16 @@
+// Who is signed in to this instance.
+//
+// The username can't be a NEXT_PUBLIC_* build-time constant: the image is built once and the
+// credentials are set when it RUNS, so the client has to ask. Only the username is returned —
+// it is a label, not a secret, and the password never leaves the server.
+//
+// Reaching this route at all means the middleware already validated the session.
+import { AUTH_DISABLED, AUTH_USER, SELF_HOSTED } from '@/lib/selfhost-auth';
+
+export const runtime = 'nodejs';
+export const dynamic = 'force-dynamic';
+
+export async function GET() {
+ if (!SELF_HOSTED) return Response.json({ detail: 'not a self-hosted instance' }, { status: 404 });
+ return Response.json({ user: AUTH_USER, gated: !AUTH_DISABLED });
+}
diff --git a/ui/src/app/hr.css b/ui/src/app/hr.css
index 8836dd78..26700efb 100644
--- a/ui/src/app/hr.css
+++ b/ui/src/app/hr.css
@@ -729,3 +729,56 @@ body.hr-resizing iframe { pointer-events: none; }
.hr-consent { display: flex; align-items: flex-start; gap: 9px; margin: 12px 0 2px; font-size: 13px; color: var(--ink-2, #4b4b55); cursor: pointer; line-height: 1.45; }
.hr-consent input { width: 16px; height: 16px; margin-top: 1px; accent-color: var(--brand); flex: 0 0 auto; cursor: pointer; }
.hr-consent a { color: var(--brand); text-decoration: underline; text-underline-offset: 2px; }
+
+
+/* ── self-hosted sign-in ───────────────────────────────────────────────────────
+ Self-contained on purpose: /login sits outside the (app) route group, so revamp.css — where
+ .field and .button live — is not loaded here. Depending on it produced a form with inline
+ labels and bare inputs. */
+.sh-login {
+ min-height: 100vh; display: flex; align-items: center; justify-content: center;
+ padding: 24px; background: #fbfbfc;
+ font-family: -apple-system, BlinkMacSystemFont, "SF Pro Text", "Segoe UI", sans-serif;
+}
+.sh-login-card {
+ width: 100%; max-width: 380px; padding: 32px;
+ background: #fff; border: 1px solid #e7e7eb; border-radius: 14px;
+ box-shadow: 0 12px 40px rgba(20, 20, 40, .08);
+}
+.sh-login-mark { display: block; height: 26px; width: auto; }
+.sh-login-sub { margin: 14px 0 24px; color: #6f6f78; font-size: 13.5px; }
+
+.sh-login .field { display: block; }
+.sh-login .field + .field { margin-top: 14px; }
+.sh-login .field label {
+ display: block; margin-bottom: 6px;
+ color: #55555f; font-size: 12px; font-weight: 650;
+}
+.sh-login .field input {
+ width: 100%; min-height: 40px; padding: 0 11px;
+ border: 1px solid #d8d8df; border-radius: 8px;
+ background: #fff; color: #17171a; font: inherit; font-size: 13px;
+}
+.sh-login .field input:focus {
+ outline: none; border-color: #285aff; box-shadow: 0 0 0 3px rgba(40, 90, 255, .14);
+}
+
+.sh-login-go {
+ width: 100%; min-height: 40px; margin-top: 20px;
+ display: inline-flex; align-items: center; justify-content: center;
+ border: 1px solid #285aff; border-radius: 8px;
+ background: #285aff; color: #fff;
+ font: inherit; font-size: 13px; font-weight: 620; cursor: pointer;
+}
+.sh-login-go:hover:not(:disabled) { background: #1641d8; }
+.sh-login-go:disabled { opacity: .45; cursor: default; }
+
+.sh-login .notice {
+ display: block; margin-bottom: 16px; padding: 10px 12px;
+ border: 1px solid #f3c9cd; border-radius: 9px;
+ background: #fff0f1; color: #8d1b24; font-size: 13px; line-height: 1.5;
+}
+
+.sh-login-hint { margin: 18px 0 0; color: #9696a0; font-size: 11.5px; line-height: 1.5; }
+.sh-login-hint code { font-size: 11px; }
+
diff --git a/ui/src/app/login/page.tsx b/ui/src/app/login/page.tsx
index c6105f1f..002ba141 100644
--- a/ui/src/app/login/page.tsx
+++ b/ui/src/app/login/page.tsx
@@ -3,6 +3,8 @@ import { useEffect, useState } from 'react';
import { login, register, googleSignIn, requestPasswordReset, resendVerification, switchOrg, getSession, type Org, type Session } from '@/lib/auth';
import { GoogleButton, GOOGLE_ENABLED } from '@/components/GoogleButton';
import { stashInvite, takePendingInvite } from '@/app/(app)/billing/lib';
+import { SELF_HOSTED } from '@/lib/edition';
+import { SelfHostLogin } from '@/components/SelfHostLogin';
// HarnessRouter is a subscribable product over AgentStudio orgs. The sign-in org picker lists ONLY
// orgs that subscribed to HR (hr_subscribed flag). The account itself is the shared AgentStudio user.
@@ -11,6 +13,18 @@ function hrSubscribed(orgs: Org[]): Org[] {
}
export default function LoginPage() {
+ // One route, two sign-ins. The hosted form registers accounts, picks an org, resets by email
+ // and offers Google — all of which need services a single box doesn't have.
+ if (SELF_HOSTED) {
+ const next = typeof window !== 'undefined'
+ ? new URLSearchParams(window.location.search).get('next') || ''
+ : '';
+ return <SelfHostLogin next={next} />;
+ }
+ return <HostedLoginPage />;
+}
+
+function HostedLoginPage() {
const [mode, setMode] = useState<'signin' | 'register' | 'forgot'>('signin');
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
diff --git a/ui/src/components/SelfHostLogin.tsx b/ui/src/components/SelfHostLogin.tsx
new file mode 100644
index 00000000..2923b5f7
--- /dev/null
+++ b/ui/src/components/SelfHostLogin.tsx
@@ -0,0 +1,69 @@
+'use client';
+// Sign-in for a self-hosted instance: one operator, one password.
+//
+// Deliberately not the hosted sign-in form. That one registers accounts, picks an organisation,
+// resets passwords by email and offers Google — every one of those needs a service this box does
+// not have. Reusing it would mean disabling four flows and explaining the remnants.
+import { useState } from 'react';
+
+export function SelfHostLogin({ next }: { next: string }) {
+ const [username, setUsername] = useState('');
+ const [password, setPassword] = useState('');
+ const [err, setErr] = useState('');
+ const [busy, setBusy] = useState(false);
+
+ async function submit(e: React.FormEvent) {
+ e.preventDefault();
+ setBusy(true); setErr('');
+ try {
+ const r = await fetch('/api/selfhost/login', {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ username, password }),
+ });
+ if (!r.ok) {
+ setErr((await r.json().catch(() => null))?.detail || 'Incorrect username or password.');
+ return;
+ }
+ // A full navigation, not a client route change: the middleware has to see the new cookie,
+ // and every page under it was rendered as unauthenticated.
+ window.location.assign(next || '/harnesses');
+ } catch {
+ setErr('Could not reach this instance.');
+ } finally {
+ setBusy(false);
+ }
+ }
+
+ return (
+ <div className="sh-login">
+ <form className="sh-login-card" onSubmit={submit}>
+ {/* eslint-disable-next-line @next/next/no-img-element -- static brand asset, no layout shift */}
+ <img className="sh-login-mark" src="/harnessrouter-wordmark.svg" alt="HarnessRouter" />
+ <p className="sh-login-sub">Sign in to this instance.</p>
+
+ {err ? <div className="notice error" role="alert">{err}</div> : null}
+
+ <div className="field">
+ <label htmlFor="sh-user">Username</label>
+ <input id="sh-user" value={username} autoFocus autoComplete="username"
+ onChange={(e) => setUsername(e.target.value)} />
+ </div>
+ <div className="field">
+ <label htmlFor="sh-pass">Password</label>
+ <input id="sh-pass" type="password" value={password} autoComplete="current-password"
+ onChange={(e) => setPassword(e.target.value)} />
+ </div>
+
+ <button className="button primary sh-login-go" type="submit"
+ disabled={busy || !username || !password}>
+ {busy ? 'Signing in…' : 'Sign in'}
+ </button>
+
+ <p className="sh-login-hint">
+ Set by <code>HR_AUTH_USER</code> and <code>HR_AUTH_PASSWORD</code> on the container.
+ </p>
+ </form>
+ </div>
+ );
+}
diff --git a/ui/src/components/revamp/Shell.tsx b/ui/src/components/revamp/Shell.tsx
index 12cd7c0f..f75fe248 100644
--- a/ui/src/components/revamp/Shell.tsx
+++ b/ui/src/components/revamp/Shell.tsx
@@ -63,6 +63,15 @@ export function Shell({ children, credits }: { children: React.ReactNode; credit
const [wsBusy, setWsBusy] = useState(false);
const [wsErr, setWsErr] = useState('');
const [acctMenu, setAcctMenu] = useState(false);
+ // Not a build-time constant: the image is built once and credentials are set when it runs.
+ const [selfHostUser, setSelfHostUser] = useState('');
+ useEffect(() => {
+ if (!SELF_HOSTED) return;
+ fetch('/api/selfhost/session')
+ .then((r) => (r.ok ? r.json() : null))
+ .then((d) => { if (d?.user) setSelfHostUser(String(d.user)); })
+ .catch(() => { /* the menu just says "this instance" */ });
+ }, []);
const [mobileNav, setMobileNav] = useState(false);
const [connectOpen, setConnectOpen] = useState(false);
const wsRef = useRef<HTMLDivElement>(null);
@@ -268,7 +277,28 @@ export function Shell({ children, credits }: { children: React.ReactNode; credit
</div>
<div className="header-utils">
<a className="utility-link" href="https://harnessrouter.ai/docs" target="_blank" rel="noreferrer"><iconify-icon icon="tabler:book-2"></iconify-icon>Docs</a>
- {SELF_HOSTED ? null : (
+ {SELF_HOSTED ? (
+ <div className="account-wrap" ref={acctRef}>
+ <button className="account-button" type="button" aria-expanded={acctMenu}
+ aria-label="Account" onClick={() => setAcctMenu((v) => !v)}>
+ <iconify-icon icon="tabler:user"></iconify-icon>
+ </button>
+ {acctMenu && (
+ <div className="account-menu">
+ <div className="account-meta">
+ <strong>Signed in</strong>
+ <span>{selfHostUser || 'this instance'}</span>
+ </div>
+ <button className="menu-item" type="button" onClick={async () => {
+ setAcctMenu(false);
+ await fetch('/api/selfhost/logout', { method: 'POST' }).catch(() => undefined);
+ // Full navigation: the middleware must re-evaluate without the cookie.
+ window.location.assign('/login');
+ }}><iconify-icon icon="tabler:logout"></iconify-icon>Sign out</button>
+ </div>
+ )}
+ </div>
+ ) : (
<div className="account-wrap" ref={acctRef}>
<button className="account-button" type="button" aria-expanded={acctMenu} onClick={() => setAcctMenu((v) => !v)}>
{avatarUrl
diff --git a/ui/src/lib/selfhost-auth.ts b/ui/src/lib/selfhost-auth.ts
new file mode 100644
index 00000000..f309edf6
--- /dev/null
+++ b/ui/src/lib/selfhost-auth.ts
@@ -0,0 +1,65 @@
+// The self-hosted session: one operator, one password, a signed cookie.
+//
+// Runs in middleware (the Edge runtime), so it uses Web Crypto rather than node:crypto — the same
+// primitives are available, and keeping one implementation means the cookie is minted and verified
+// by identical code.
+//
+// The cookie carries an expiry and an HMAC over it, signed with the password. Two consequences,
+// both wanted: nothing is stored server-side, so a restart doesn't sign anyone out unexpectedly;
+// and CHANGING THE PASSWORD INVALIDATES EVERY EXISTING SESSION, because the old signature can no
+// longer be verified. That is the behaviour you want from a password change.
+export const SESSION_COOKIE = 'hr_selfhost';
+const VERSION = 'v1';
+
+export const AUTH_USER = process.env.HR_AUTH_USER || 'harnessrouter';
+export const AUTH_PASSWORD = process.env.HR_AUTH_PASSWORD || 'harnessrouter';
+export const AUTH_DISABLED = process.env.HR_AUTH_DISABLED === '1';
+export const SELF_HOSTED = process.env.NEXT_PUBLIC_HR_EDITION === 'selfhost';
+
+/** How long a session lasts. Long enough not to be a nuisance on a box you use daily. */
+export const SESSION_TTL_MS = 7 * 24 * 60 * 60 * 1000;
+
+const enc = new TextEncoder();
+
+async function hmac(message: string): Promise<string> {
+ const key = await crypto.subtle.importKey(
+ 'raw', enc.encode(`hr-selfhost:${AUTH_PASSWORD}`),
+ { name: 'HMAC', hash: 'SHA-256' }, false, ['sign'],
+ );
+ const sig = await crypto.subtle.sign('HMAC', key, enc.encode(message));
+ return Array.from(new Uint8Array(sig)).map((b) => b.toString(16).padStart(2, '0')).join('');
+}
+
+/** Length-independent comparison. A plain === leaks how much of a secret was right via timing. */
+export function sameSecret(a: string, b: string): boolean {
+ const x = enc.encode(a);
+ const y = enc.encode(b);
+ let diff = x.length ^ y.length;
+ const n = Math.max(x.length, y.length);
+ for (let i = 0; i < n; i++) diff |= (x[i] ?? 0) ^ (y[i] ?? 0);
+ return diff === 0;
+}
+
+export function credentialsValid(user: string, password: string): boolean {
+ // Both are always checked, so a wrong username costs the same as a wrong password.
+ const okUser = sameSecret(user, AUTH_USER);
+ const okPass = sameSecret(password, AUTH_PASSWORD);
+ return okUser && okPass;
+}
+
+export async function mintSession(): Promise<string> {
+ const expires = Date.now() + SESSION_TTL_MS;
+ const body = `${VERSION}.${expires}`;
+ return `${body}.${await hmac(body)}`;
+}
+
+export async function sessionValid(token: string | undefined): Promise<boolean> {
+ if (!token) return false;
+ const parts = token.split('.');
+ if (parts.length !== 3 || parts[0] !== VERSION) return false;
+ const [, expiresRaw, sig] = parts;
+ const expires = Number(expiresRaw);
+ if (!Number.isFinite(expires) || Date.now() > expires) return false;
+ // Verify the signature LAST but always — an expired cookie and a forged one both just fail.
+ return sameSecret(sig, await hmac(`${VERSION}.${expiresRaw}`));
+}
diff --git a/ui/src/middleware.ts b/ui/src/middleware.ts
index a32323f6..f5826cd9 100644
--- a/ui/src/middleware.ts
+++ b/ui/src/middleware.ts
@@ -1,77 +1,61 @@
-// The gate for a self-hosted instance that is reachable by anyone.
+// The gate for a self-hosted instance that anyone can reach.
//
// Self-hosted has no accounts service, and on a machine only you can reach that is the right
-// answer — a login would be ceremony with nothing behind it. The moment the box has a public
-// URL that stops being true: the console can create harnesses, read every task transcript, and
-// run an agent with your provider key. So exposure needs a gate, and the gate ships INSIDE the
-// image rather than in whatever proxy happens to sit in front, because `docker run -p 3000:3000`
-// on a cloud host must be safe by default and not by configuration.
+// answer — a login would be ceremony with nothing behind it. The moment the box has a public URL
+// that stops being true: the console creates harnesses, reads every task transcript, and runs an
+// agent with your provider key. So exposure needs a gate, and the gate ships INSIDE the image
+// rather than in whatever proxy happens to sit in front, because `docker run -p 3000:3000` on a
+// cloud host must be safe by default and not by configuration.
//
// Middleware is the chokepoint deliberately: pages, the /api/harness proxy, static assets and any
-// route added later all pass through here, so no individual handler can forget to check. HTTP
-// Basic is the mechanism because it needs no session store, no cookie signing and no login route
-// to keep in sync with the hosted edition's — fewer moving parts is the security argument.
+// route added later all pass through here, so no individual handler can forget to check.
//
// HR_AUTH_USER / HR_AUTH_PASSWORD set them. Defaults are published in the README, so an
// instance still running them is open to anyone who read it.
// HR_AUTH_DISABLED=1 no gate at all. Only for a box nobody else can reach.
import { NextResponse, type NextRequest } from 'next/server';
+import { AUTH_DISABLED, SELF_HOSTED, SESSION_COOKIE, sessionValid } from '@/lib/selfhost-auth';
-const SELF_HOSTED = process.env.NEXT_PUBLIC_HR_EDITION === 'selfhost';
-const DISABLED = process.env.HR_AUTH_DISABLED === '1';
-const USER = process.env.HR_AUTH_USER || 'harnessrouter';
-const PASSWORD = process.env.HR_AUTH_PASSWORD || 'harnessrouter';
+// Static assets shipped IN the image: brand marks, icons, fonts. They are public by
+// construction — baked into a published container and containing no user data — so gating them
+// protects nothing and breaks the login page, which needs its own logo before anyone can sign in.
+const STATIC_ASSET = /\.(svg|png|jpe?g|gif|webp|avif|ico|woff2?|ttf|otf|css|js|map)$/i;
-/** Length-independent comparison: a plain === leaks how much of the password was right through
- * timing. Cheap to do properly, so do it properly. */
-function sameSecret(a: string, b: string): boolean {
- const enc = new TextEncoder();
- const x = enc.encode(a);
- const y = enc.encode(b);
- // Compare a fixed number of bytes so length alone doesn't change the timing.
- let diff = x.length ^ y.length;
- const n = Math.max(x.length, y.length);
- for (let i = 0; i < n; i++) diff |= (x[i] ?? 0) ^ (y[i] ?? 0);
- return diff === 0;
+/** Reachable without a session: the login page, the endpoints it posts to, and static assets.
+ * Everything else is an allow-list miss, so a route added later is gated by default. */
+function isPublic(path: string): boolean {
+ return path === '/login'
+ || path === '/api/selfhost/login'
+ || path === '/api/selfhost/logout'
+ || path.startsWith('/_next/')
+ // An /api path is never a static asset, whatever it ends with.
+ || (!path.startsWith('/api/') && STATIC_ASSET.test(path));
}
-function unauthorized(): NextResponse {
- return new NextResponse('Authentication required.', {
- status: 401,
- headers: {
- // The realm is what the browser shows in its prompt.
- 'WWW-Authenticate': 'Basic realm="HarnessRouter", charset="UTF-8"',
- 'Cache-Control': 'no-store',
- },
- });
-}
-
-export function middleware(req: NextRequest) {
+export async function middleware(req: NextRequest) {
// Hosted has its own login; this gate exists only for the self-hosted image.
- if (!SELF_HOSTED || DISABLED) return NextResponse.next();
+ if (!SELF_HOSTED || AUTH_DISABLED) return NextResponse.next();
+
+ const { pathname, search } = req.nextUrl;
+ if (isPublic(pathname)) return NextResponse.next();
+ if (await sessionValid(req.cookies.get(SESSION_COOKIE)?.value)) return NextResponse.next();
- const header = req.headers.get('authorization') || '';
- if (header.toLowerCase().startsWith('basic ')) {
- let decoded = '';
- try {
- decoded = atob(header.slice(6).trim());
- } catch {
- return unauthorized(); // malformed base64 is a failed attempt, not a server error
- }
- // Only the FIRST colon separates them — a password may legitimately contain one.
- const i = decoded.indexOf(':');
- const user = i < 0 ? decoded : decoded.slice(0, i);
- const pass = i < 0 ? '' : decoded.slice(i + 1);
- // Both are checked every time, so a wrong username costs the same as a wrong password.
- const okUser = sameSecret(user, USER);
- const okPass = sameSecret(pass, PASSWORD);
- if (okUser && okPass) return NextResponse.next();
+ // An API call gets a status it can act on; a page gets sent to the form. Redirecting an API
+ // call to HTML would make every fetch look like it succeeded and return a login page as data.
+ if (pathname.startsWith('/api/')) {
+ return new NextResponse(JSON.stringify({ detail: 'sign in to continue' }), {
+ status: 401,
+ headers: { 'content-type': 'application/json', 'cache-control': 'no-store' },
+ });
}
- return unauthorized();
+ const to = req.nextUrl.clone();
+ to.pathname = '/login';
+ // Come back to where they were headed, path only — an absolute URL here would let a crafted
+ // link bounce someone off this instance after they authenticate.
+ to.search = pathname === '/' ? '' : `?next=${encodeURIComponent(pathname + search)}`;
+ return NextResponse.redirect(to);
}
export const config = {
- // Everything. The one exception is the favicon, so a browser tab doesn't provoke a second
- // credential prompt before the page itself has asked for one.
- matcher: ['/((?!favicon.ico).*)'],
+ matcher: ['/((?!_next/static|_next/image|favicon.ico).*)'],
};