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 profile page, so the password can be changed from the console

richard-epsillab630883ec849
diff --git a/README.md b/README.md
index 4b0f5882..fc9a9678 100644
--- a/README.md
+++ b/README.md
@@ -132,6 +132,20 @@ right here, which makes them a placeholder, not a secret — the container warns
while the default is still in place. `HR_AUTH_DISABLED=1` removes the gate entirely, which is
only reasonable on a machine nobody else can reach.
+You can also change the username and password from **Profile**, in the account menu at the top
+right. Those are stored on the data volume (`/data/selfhost-auth.json`, a salted hash — never the
+password) and take precedence over the environment from then on, so an `HR_AUTH_PASSWORD` set at
+`docker run` months ago cannot quietly undo a password change.
+
+Changing them signs out every other browser and restarts the console, which takes about a second.
+The gate runs in Next.js middleware on the Edge runtime, which reads its signing key once at
+start-up and cannot be told about a change in place; restarting is what makes "signed out
+everywhere" true rather than merely displayed. The gateway and runner are left alone, so a task
+that is mid-turn runs straight through it.
+
+Forgot the password? There is no reset email to send, so delete `/data/selfhost-auth.json` and
+restart — the instance falls back to `HR_AUTH_USER` / `HR_AUTH_PASSWORD`.
+
For TLS, keep the console on loopback and put a terminating proxy in front. With Caddy that is
one file and a real certificate, automatically:
diff --git a/docker/entrypoint.sh b/docker/entrypoint.sh
index 194fc95e..d9fe4514 100644
--- a/docker/entrypoint.sh
+++ b/docker/entrypoint.sh
@@ -58,10 +58,45 @@ export NEXT_PUBLIC_HR_EDITION=selfhost
# are also published in the README, which makes them a placeholder rather than a secret.
export HR_AUTH_USER="${HR_AUTH_USER:-harnessrouter}"
export HR_AUTH_PASSWORD="${HR_AUTH_PASSWORD:-harnessrouter}"
+export HR_AUTH_STORE="${HR_AUTH_STORE:-/data/selfhost-auth.json}"
+
+# Credentials changed from the profile page live in HR_AUTH_STORE and win over the environment:
+# an env var set at `docker run` months ago must not silently undo a password change. The console
+# signs its session cookie with HR_SESSION_KEY, which is derived from whichever source wins —
+# so the key changes when the credentials do, and every existing session stops verifying.
+#
+# It is derived HERE, at boot, because the gate runs in Next.js middleware on the Edge runtime:
+# no filesystem, and no visibility into environment changes made after start-up. That is why
+# changing credentials restarts the console (below) instead of taking effect in place.
+hr_session_key() {
+ if [ -f "$HR_AUTH_STORE" ]; then
+ "$PY" - "$HR_AUTH_STORE" <<'PYEOF' 2>/dev/null && return 0
+import json, sys
+try:
+ d = json.load(open(sys.argv[1]))
+ if d.get("user") and d.get("hash"):
+ print("%s:%s" % (d["user"], d["hash"]))
+ else:
+ raise ValueError
+except Exception:
+ raise SystemExit(1)
+PYEOF
+ fi
+ printf '%s:%s\n' "$HR_AUTH_USER" "$HR_AUTH_PASSWORD"
+}
+
+hr_stored_user() {
+ [ -f "$HR_AUTH_STORE" ] || { printf '%s\n' "$HR_AUTH_USER"; return 0; }
+ "$PY" -c 'import json,sys;d=json.load(open(sys.argv[1]));print(d["user"])' "$HR_AUTH_STORE" 2>/dev/null \
+ || printf '%s\n' "$HR_AUTH_USER"
+}
+
if [ "${HR_AUTH_DISABLED:-}" = "1" ]; then
echo "[harnessrouter] WARNING: login is DISABLED (HR_AUTH_DISABLED=1) — anyone who can reach this port has full control"
+elif [ -f "$HR_AUTH_STORE" ]; then
+ echo "[harnessrouter] sign in as '$(hr_stored_user)' (credentials set from the profile page)"
elif [ "$HR_AUTH_PASSWORD" = "harnessrouter" ]; then
- echo "[harnessrouter] WARNING: using the DEFAULT password. Set HR_AUTH_PASSWORD before exposing this instance."
+ echo "[harnessrouter] WARNING: using the DEFAULT password. Set HR_AUTH_PASSWORD, or change it from the profile page, before exposing this instance."
fi
export PORT="${PORT:-3000}"
@@ -148,8 +183,34 @@ for _ in $(seq 1 60); do
sleep 1
done
-# UI (the only published port)
-( cd /app/ui && exec node server.js ) &
+# UI (the only published port).
+#
+# Supervised, unlike the other two: changing the console password has to take effect in the
+# middleware, which only reads its signing key at boot — so the profile route writes the new
+# credentials and exits, and this loop brings the console back with them about a second later.
+# The gateway and runner are untouched, so a task mid-turn keeps running through the blip.
+#
+# A crash-loop is not silent: the console is the only published port, so a UI that cannot start
+# is immediately visible, and the message below says how many times it has restarted.
+(
+ cd /app/ui
+ restarts=0
+ while :; do
+ HR_SESSION_KEY="$(hr_session_key)" \
+ HR_AUTH_USER="$(hr_stored_user)" \
+ node server.js
+ status=$?
+ # A clean exit is the credential change asking for a restart. Anything else is a real
+ # failure, and repeating it forever would hide it — so give up and let the container die.
+ if [ "$status" -ne 0 ]; then
+ echo "[harnessrouter] console exited with status $status — not restarting"
+ exit "$status"
+ fi
+ restarts=$((restarts + 1))
+ echo "[harnessrouter] console restarting to pick up new credentials (restart #$restarts)"
+ sleep 1
+ done
+) &
pids+=($!)
echo "[harnessrouter] ready on :$PORT"
diff --git a/ui/src/app/(app)/profile/page.tsx b/ui/src/app/(app)/profile/page.tsx
new file mode 100644
index 00000000..b5d2c107
--- /dev/null
+++ b/ui/src/app/(app)/profile/page.tsx
@@ -0,0 +1,172 @@
+'use client';
+// Profile — the sign-in credentials for this instance.
+//
+// Self-hosted has one operator, so "profile" is exactly two things: who you sign in as, and the
+// password you sign in with. There is no email, no avatar, no team — inventing those would be
+// chrome over an account system this edition deliberately does not have.
+//
+// Server: GET/PUT /api/selfhost/profile. The current password is required to change either field,
+// and the change signs out every other session.
+import { useCallback, useEffect, useState } from 'react';
+import { useRouter } from 'next/navigation';
+import { SkelRows } from '@/components/Skel';
+import { SELF_HOSTED } from '@/lib/edition';
+
+interface Profile { user: string; gated: boolean; usingDefaultPassword: boolean }
+
+export default function ProfilePage() {
+ const router = useRouter();
+ const [profile, setProfile] = useState<Profile | null>(null);
+ const [username, setUsername] = useState('');
+ const [currentPassword, setCurrentPassword] = useState('');
+ const [newPassword, setNewPassword] = useState('');
+ const [confirmPassword, setConfirmPassword] = useState('');
+ const [err, setErr] = useState('');
+ const [notice, setNotice] = useState('');
+ const [busy, setBusy] = useState(false);
+
+ /** Poll until the restarted console answers. It is back in about a second; the ceiling exists
+ * so a console that fails to restart surfaces as an error instead of a spinner forever. */
+ const waitForRestart = useCallback(async () => {
+ for (let i = 0; i < 40; i++) {
+ await new Promise((r) => setTimeout(r, 500));
+ try {
+ const r = await fetch('/api/selfhost/profile', { cache: 'no-store' });
+ if (r.ok) return;
+ } catch { /* still down — that is what we are waiting out */ }
+ }
+ setErr('Your credentials were saved, but the console has not come back. Restart the container.');
+ }, []);
+
+ const load = useCallback(async () => {
+ try {
+ const r = await fetch('/api/selfhost/profile');
+ if (!r.ok) throw new Error('unavailable');
+ const doc = (await r.json()) as Profile;
+ setProfile(doc);
+ setUsername(doc.user);
+ } catch {
+ setErr('Could not load your profile.');
+ }
+ }, []);
+
+ useEffect(() => { if (SELF_HOSTED) void load(); }, [load]);
+
+ if (!SELF_HOSTED) {
+ return (
+ <section className="view is-active"><div className="page">
+ <div className="session-empty">This page is not available on this instance.</div>
+ </div></section>
+ );
+ }
+
+ const changingPassword = newPassword.length > 0;
+ const mismatch = changingPassword && confirmPassword.length > 0 && newPassword !== confirmPassword;
+ const nothingToChange = username.trim() === (profile?.user || '') && !changingPassword;
+ const canSave = !busy && !!profile && !!currentPassword && !nothingToChange
+ && !mismatch && (!changingPassword || newPassword === confirmPassword);
+
+ async function save(e: React.FormEvent) {
+ e.preventDefault();
+ setBusy(true); setErr(''); setNotice('');
+ try {
+ const r = await fetch('/api/selfhost/profile', {
+ method: 'PUT',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({
+ currentPassword,
+ username: username.trim(),
+ newPassword: newPassword || undefined,
+ }),
+ });
+ const doc = await r.json().catch(() => null);
+ if (!r.ok) { setErr(doc?.detail || 'Could not save your changes.'); return; }
+ setCurrentPassword(''); setNewPassword(''); setConfirmPassword('');
+ // The console restarts to pick up the new credentials — the sign-in gate reads them only
+ // at start-up. Say so, then wait for it rather than firing a request into a closed port
+ // and reporting a failure for something that worked.
+ setNotice('Saved. Signing every other browser out\u2026');
+ await waitForRestart();
+ setNotice(changingPassword
+ ? 'Saved. Every other signed-in browser has been signed out.'
+ : 'Saved.');
+ await load();
+ } catch {
+ setErr('Could not reach this instance.');
+ } finally {
+ setBusy(false);
+ }
+ }
+
+ return (
+ <section className="view is-active" id="view-profile">
+ <div className="page">
+ <div className="page-header">
+ <div>
+ <button className="back-link" type="button" onClick={() => router.push('/harnesses')}>
+ <iconify-icon icon="tabler:arrow-left"></iconify-icon><span>Harnesses</span></button>
+ <h1>Profile</h1>
+ <p>The username and password you sign in to this instance with.</p>
+ </div>
+ </div>
+
+ {err && (
+ <div className="notice"><iconify-icon icon="tabler:alert-triangle"></iconify-icon>
+ <div><strong>Something went wrong</strong>{err}</div></div>
+ )}
+ {notice && <div className="itg-saved"><iconify-icon icon="tabler:check"></iconify-icon>{notice}</div>}
+
+ {!profile ? <SkelRows rows={3} /> : (
+ <>
+ {profile.usingDefaultPassword && (
+ <div className="notice"><iconify-icon icon="tabler:shield-exclamation"></iconify-icon>
+ <div><strong>You are using the default password</strong>
+ It is published in the documentation, so anyone who can reach this address can
+ sign in. Set your own below.</div></div>
+ )}
+
+ <form className="field-stack" onSubmit={save} style={{ maxWidth: '32rem' }}>
+ <div className="field">
+ <label htmlFor="pf-user">Username</label>
+ <input id="pf-user" value={username} autoComplete="username"
+ onChange={(e) => setUsername(e.target.value)} />
+ </div>
+
+ <div className="field">
+ <label htmlFor="pf-new">New password</label>
+ <input id="pf-new" type="password" value={newPassword} autoComplete="new-password"
+ placeholder="Leave blank to keep your current password"
+ onChange={(e) => setNewPassword(e.target.value)} />
+ </div>
+
+ {changingPassword && (
+ <div className="field">
+ <label htmlFor="pf-confirm">Confirm new password</label>
+ <input id="pf-confirm" type="password" value={confirmPassword}
+ autoComplete="new-password"
+ onChange={(e) => setConfirmPassword(e.target.value)} />
+ {mismatch && <p className="field-help">Both passwords must match.</p>}
+ </div>
+ )}
+
+ <div className="field">
+ <label htmlFor="pf-current">Current password</label>
+ <input id="pf-current" type="password" value={currentPassword}
+ autoComplete="current-password"
+ onChange={(e) => setCurrentPassword(e.target.value)} />
+ <p className="field-help">
+ Required to change either field, so an unattended tab can&rsquo;t be used to take
+ over this instance.
+ </p>
+ </div>
+
+ <button className="button primary" type="submit" disabled={!canSave}>
+ {busy ? 'Saving…' : 'Save changes'}
+ </button>
+ </form>
+ </>
+ )}
+ </div>
+ </section>
+ );
+}
diff --git a/ui/src/app/api/selfhost/login/route.ts b/ui/src/app/api/selfhost/login/route.ts
index c8e8a46c..a7269355 100644
--- a/ui/src/app/api/selfhost/login/route.ts
+++ b/ui/src/app/api/selfhost/login/route.ts
@@ -1,8 +1,9 @@
// 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,
+ AUTH_DISABLED, SELF_HOSTED, SESSION_COOKIE, SESSION_TTL_MS, mintSession,
} from '@/lib/selfhost-auth';
+import { credentialsValid } from '@/lib/selfhost-credentials';
export const runtime = 'nodejs';
export const dynamic = 'force-dynamic';
diff --git a/ui/src/app/api/selfhost/profile/route.ts b/ui/src/app/api/selfhost/profile/route.ts
new file mode 100644
index 00000000..3cd4fbd2
--- /dev/null
+++ b/ui/src/app/api/selfhost/profile/route.ts
@@ -0,0 +1,87 @@
+// Change the sign-in credentials of a self-hosted instance.
+//
+// The current password is required even though the caller is already signed in. A session cookie
+// proves someone was signed in once, on this browser; it does not prove they are the operator
+// now. Without the re-check, an unattended tab is a permanent credential-change token.
+//
+// WHY THIS RESTARTS THE CONSOLE. The gate lives in middleware, which Next.js runs on the Edge
+// runtime: no filesystem, and no visibility into environment variables changed after start-up
+// (measured, not assumed). So a running console cannot be told about new credentials — it can
+// only be replaced by one that boots with them. The entrypoint supervises the console process
+// for exactly this, and restarts it in about a second while the gateway and runner — and any
+// task mid-turn — keep running untouched.
+//
+// The alternative was a second gate in Node that checks the file while the middleware checks
+// stale credentials. Two gates that can disagree about who is signed in is a worse thing to own
+// than a one-second restart.
+import type { NextRequest } from 'next/server';
+import {
+ AUTH_DISABLED, SELF_HOSTED, SESSION_COOKIE, SESSION_TTL_MS, mintSessionWith,
+} from '@/lib/selfhost-auth';
+import {
+ authUser, currentSessionKey, passwordValid, setCredentials, usingDefaultPassword,
+} from '@/lib/selfhost-credentials';
+
+export const runtime = 'nodejs';
+export const dynamic = 'force-dynamic';
+
+/** Short enough to type, long enough that guessing it over the network is hopeless. */
+const MIN_PASSWORD = 8;
+
+export async function GET() {
+ if (!SELF_HOSTED) return Response.json({ detail: 'not a self-hosted instance' }, { status: 404 });
+ return Response.json({
+ user: authUser(),
+ gated: !AUTH_DISABLED,
+ usingDefaultPassword: usingDefaultPassword(),
+ });
+}
+
+export async function PUT(req: NextRequest) {
+ if (!SELF_HOSTED || AUTH_DISABLED) {
+ return Response.json({ detail: 'sign-in is not enabled on this instance' }, { status: 404 });
+ }
+ let body: { currentPassword?: string; username?: string; newPassword?: string };
+ try {
+ body = await req.json();
+ } catch {
+ return Response.json({ detail: 'Invalid request.' }, { status: 400 });
+ }
+
+ const currentPassword = String(body.currentPassword || '');
+ if (!passwordValid(currentPassword)) {
+ await new Promise((r) => setTimeout(r, 400)); // the same brake as the sign-in form
+ return Response.json({ detail: 'Current password is incorrect.' }, { status: 403 });
+ }
+
+ const username = String(body.username || '').trim() || authUser();
+ const newPassword = String(body.newPassword || '');
+ if (/\s/.test(username)) {
+ return Response.json({ detail: 'Username cannot contain spaces.' }, { status: 400 });
+ }
+ // An empty new password means "leave it alone" — this form changes either field or both.
+ if (newPassword && newPassword.length < MIN_PASSWORD) {
+ return Response.json(
+ { detail: `Password must be at least ${MIN_PASSWORD} characters.` }, { status: 400 });
+ }
+ if (username === authUser() && !newPassword) {
+ return Response.json({ detail: 'Nothing to change.' }, { status: 400 });
+ }
+
+ setCredentials(username, newPassword || currentPassword);
+
+ // Signed with the NEW key, not this process's: the console that verifies this cookie is the one
+ // about to boot. Every other browser's cookie is signed with the old key and stops working —
+ // which is the entire point of changing a password.
+ const res = Response.json({ ok: true, user: username, restarting: true });
+ const secure = req.nextUrl.protocol === 'https:' ? '; Secure' : '';
+ res.headers.set('set-cookie',
+ `${SESSION_COOKIE}=${await mintSessionWith(currentSessionKey())}; Path=/`
+ + `; Max-Age=${Math.floor(SESSION_TTL_MS / 1000)}; HttpOnly; SameSite=Lax${secure}`);
+
+ // After the response is on the wire. Exiting first would drop it, and the operator would be
+ // left unable to tell whether their password had changed — the worst possible thing to be
+ // unsure about.
+ setTimeout(() => process.exit(0), 500);
+ return res;
+}
diff --git a/ui/src/app/api/selfhost/session/route.ts b/ui/src/app/api/selfhost/session/route.ts
index 874e29c9..05c5edba 100644
--- a/ui/src/app/api/selfhost/session/route.ts
+++ b/ui/src/app/api/selfhost/session/route.ts
@@ -5,12 +5,13 @@
// 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';
+import { AUTH_DISABLED, SELF_HOSTED } from '@/lib/selfhost-auth';
+import { authUser } from '@/lib/selfhost-credentials';
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 });
+ return Response.json({ user: authUser(), gated: !AUTH_DISABLED });
}
diff --git a/ui/src/components/SelfHostLogin.tsx b/ui/src/components/SelfHostLogin.tsx
index 2923b5f7..a2684ab9 100644
--- a/ui/src/components/SelfHostLogin.tsx
+++ b/ui/src/components/SelfHostLogin.tsx
@@ -61,7 +61,8 @@ export function SelfHostLogin({ next }: { next: string }) {
</button>
<p className="sh-login-hint">
- Set by <code>HR_AUTH_USER</code> and <code>HR_AUTH_PASSWORD</code> on the container.
+ First sign-in uses <code>HR_AUTH_USER</code> and <code>HR_AUTH_PASSWORD</code> from the
+ container. You can change them from your profile once you are in.
</p>
</form>
</div>
diff --git a/ui/src/components/revamp/Shell.tsx b/ui/src/components/revamp/Shell.tsx
index f75fe248..b286817c 100644
--- a/ui/src/components/revamp/Shell.tsx
+++ b/ui/src/components/revamp/Shell.tsx
@@ -289,6 +289,10 @@ export function Shell({ children, credits }: { children: React.ReactNode; credit
<strong>Signed in</strong>
<span>{selfHostUser || 'this instance'}</span>
</div>
+ <button className="menu-item" type="button" onClick={() => {
+ setAcctMenu(false);
+ router.push('/profile');
+ }}><iconify-icon icon="tabler:user-cog"></iconify-icon>Profile</button>
<button className="menu-item" type="button" onClick={async () => {
setAcctMenu(false);
await fetch('/api/selfhost/logout', { method: 'POST' }).catch(() => undefined);
diff --git a/ui/src/lib/selfhost-auth.ts b/ui/src/lib/selfhost-auth.ts
index f309edf6..6b7cc702 100644
--- a/ui/src/lib/selfhost-auth.ts
+++ b/ui/src/lib/selfhost-auth.ts
@@ -1,32 +1,47 @@
-// The self-hosted session: one operator, one password, a signed cookie.
+// The self-hosted session cookie: minting and verifying. Edge-safe on purpose.
//
-// 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.
+// This module runs in the middleware, which Next.js bundles for the Edge runtime — no filesystem,
+// and (verified, not assumed) no visibility into environment variables a Node route mutates after
+// the server started. So the middleware can only ever know the credentials the process BOOTED
+// with, and everything here is built around that fact rather than around wishing it away.
//
-// 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.
+// The signing key is `HR_SESSION_KEY`, which the entrypoint derives from whatever the credentials
+// are at boot: the stored credential file if the operator has changed them, otherwise
+// HR_AUTH_USER/HR_AUTH_PASSWORD. Because the key IS the credentials, a changed password cannot
+// verify against an old cookie — which is what makes "change the password" a real answer to
+// "someone else has my password". Making that true at runtime is why changing credentials
+// restarts the console process (see the profile route and the entrypoint's supervisor loop).
+//
+// Reading and writing the credential file lives in selfhost-credentials.ts, which is Node-only.
+// The split is deliberate: importing that module from here would drag node:fs into the Edge
+// bundle and fail the build — a failure that is much better than a gate that silently degrades.
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';
+/** The credentials this process booted with. The entrypoint resolves the stored file first, so
+ * these are only the fallback for an instance whose credentials were never changed. */
+const ENV_USER = process.env.HR_AUTH_USER || 'harnessrouter';
+const ENV_PASSWORD = process.env.HR_AUTH_PASSWORD || 'harnessrouter';
+
/** 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}`),
+/** Key material for the signature, as of boot. */
+export function bootSessionKey(): string {
+ return process.env.HR_SESSION_KEY || `${ENV_USER}:${ENV_PASSWORD}`;
+}
+
+async function hmac(message: string, key: string): Promise<string> {
+ const k = await crypto.subtle.importKey(
+ 'raw', enc.encode(`hr-selfhost:${key}`),
{ name: 'HMAC', hash: 'SHA-256' }, false, ['sign'],
);
- const sig = await crypto.subtle.sign('HMAC', key, enc.encode(message));
+ const sig = await crypto.subtle.sign('HMAC', k, enc.encode(message));
return Array.from(new Uint8Array(sig)).map((b) => b.toString(16).padStart(2, '0')).join('');
}
@@ -40,17 +55,17 @@ export function sameSecret(a: string, b: string): boolean {
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> {
+/** Mint a cookie signed with `key`. The profile route passes the NEW key after a credential
+ * change, so the cookie it hands back is already valid for the process about to take over —
+ * otherwise changing your own password would sign you out of the tab you changed it in. */
+export async function mintSessionWith(key: string): Promise<string> {
const expires = Date.now() + SESSION_TTL_MS;
const body = `${VERSION}.${expires}`;
- return `${body}.${await hmac(body)}`;
+ return `${body}.${await hmac(body, key)}`;
+}
+
+export function mintSession(): Promise<string> {
+ return mintSessionWith(bootSessionKey());
}
export async function sessionValid(token: string | undefined): Promise<boolean> {
@@ -61,5 +76,5 @@ export async function sessionValid(token: string | undefined): Promise<boolean>
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}`));
+ return sameSecret(sig, await hmac(`${VERSION}.${expiresRaw}`, bootSessionKey()));
}
diff --git a/ui/src/lib/selfhost-credentials.ts b/ui/src/lib/selfhost-credentials.ts
new file mode 100644
index 00000000..aff53adc
--- /dev/null
+++ b/ui/src/lib/selfhost-credentials.ts
@@ -0,0 +1,94 @@
+// Where the self-hosted credentials actually live. Node-only — it reads and writes a file.
+//
+// Two sources, in order:
+// 1. A credential file on the data volume, written when the operator changes their username or
+// password from the profile page. It holds a scrypt hash and a salt — never the password.
+// 2. HR_AUTH_USER / HR_AUTH_PASSWORD from the environment, for an instance that has never
+// changed them.
+//
+// The file wins because it is what the operator changed most recently: an env var set at
+// `docker run` months ago should not silently undo a password change. Deleting the file falls
+// back to the environment, which is the recovery path for a forgotten password — it is the only
+// one, by design, since there is no email to send a reset to.
+import { randomBytes, scryptSync, timingSafeEqual } from 'node:crypto';
+import { mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
+import { dirname } from 'node:path';
+import { sameSecret } from './selfhost-auth';
+
+/** On the data volume, so a changed password survives `docker rm` and comes back on restart.
+ * The entrypoint reads the same path to derive HR_SESSION_KEY at boot — one location, named
+ * in one place per language, because a second copy of this path is a lockout waiting to happen. */
+export const CREDENTIAL_STORE = process.env.HR_AUTH_STORE || '/data/selfhost-auth.json';
+
+const ENV_USER = process.env.HR_AUTH_USER || 'harnessrouter';
+const ENV_PASSWORD = process.env.HR_AUTH_PASSWORD || 'harnessrouter';
+
+interface StoredCredentials { user: string; salt: string; hash: string; updatedAt: number }
+
+function readStore(): StoredCredentials | null {
+ try {
+ const doc = JSON.parse(readFileSync(CREDENTIAL_STORE, 'utf8')) as Partial<StoredCredentials>;
+ if (doc.user && doc.salt && doc.hash
+ && typeof doc.user === 'string' && typeof doc.salt === 'string'
+ && typeof doc.hash === 'string') {
+ return doc as StoredCredentials;
+ }
+ return null;
+ } catch {
+ // Absent is the normal case (nothing changed yet). Unreadable or corrupt falls back to the
+ // environment rather than locking the operator out of their own box.
+ return null;
+ }
+}
+
+function hashPassword(password: string, salt: string): string {
+ return scryptSync(password, salt, 32).toString('hex');
+}
+
+/** The username required at sign-in and shown in the UI. */
+export function authUser(): string {
+ return readStore()?.user || ENV_USER;
+}
+
+/** Whether this instance is still on the password published in the README. */
+export function usingDefaultPassword(): boolean {
+ return readStore() === null && ENV_PASSWORD === 'harnessrouter';
+}
+
+/** The session signing key for the CURRENT credentials — which is not necessarily the one the
+ * running process booted with. The entrypoint computes the same value at start-up. */
+export function currentSessionKey(): string {
+ const stored = readStore();
+ return stored ? `${stored.user}:${stored.hash}` : `${ENV_USER}:${ENV_PASSWORD}`;
+}
+
+export function passwordValid(password: string): boolean {
+ const stored = readStore();
+ if (!stored) return sameSecret(password, ENV_PASSWORD);
+ const want = Buffer.from(stored.hash, 'hex');
+ const got = Buffer.from(hashPassword(password, stored.salt), 'hex');
+ return want.length === got.length && timingSafeEqual(want, got);
+}
+
+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, authUser());
+ const okPass = passwordValid(password);
+ return okUser && okPass;
+}
+
+/** Write new credentials, atomically. The caller must then restart the console: the middleware
+ * reads its key from the environment at boot and cannot see this file change. */
+export function setCredentials(user: string, password: string): void {
+ const salt = randomBytes(16).toString('hex');
+ const doc: StoredCredentials = {
+ user, salt, hash: hashPassword(password, salt), updatedAt: Date.now(),
+ };
+ mkdirSync(dirname(CREDENTIAL_STORE), { recursive: true });
+ // Write-then-rename on the same filesystem, so the swap is atomic. A truncated credential file
+ // reads as "no file" and drops the instance back to the environment defaults — a silent
+ // password reset is the one failure mode worth designing out.
+ const tmp = `${CREDENTIAL_STORE}.tmp`;
+ writeFileSync(tmp, JSON.stringify(doc), { mode: 0o600 });
+ renameSync(tmp, CREDENTIAL_STORE);
+}
diff --git a/ui/src/middleware.ts b/ui/src/middleware.ts
index f5826cd9..adf8d677 100644
--- a/ui/src/middleware.ts
+++ b/ui/src/middleware.ts
@@ -10,8 +10,10 @@
// 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.
//
-// 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_USER / HR_AUTH_PASSWORD the initial credentials. Defaults are published in the
+// README, so an instance still running them is open to
+// anyone who read it. Change them here or on the profile
+// page, which stores them on the data volume and wins.
// 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';