Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat: optional login password gates UI, API, assets, and Socket.IO
Adam Eivyd87f79dfda8f
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 79f7003a4f..6caa6f1c6d 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -3,6 +3,7 @@## Added- **[issue-827] Clinician export for blood and lifestyle data** — MeatSpace gains an Export tab that builds a one-page, doctor-ready summary of your blood panels and lifestyle. Each blood test is laid out as a clean table with reference ranges and out-of-range markers flagged, and your lifestyle factors (sex, smoking, exercise, sleep, diet, stress, BMI, and any chronic conditions) are summarized above them. Print it or save it as a PDF straight from the browser, or copy the whole thing as markdown to paste into a message or note. Genome and longevity context are intentionally left out of this view.+- **Optional login password** — a new Settings → Security tab lets you set a single shared password that gates the PortOS UI, API, asset routes, and Socket.IO behind a sign-in screen. Off by default, so nothing changes if you don't enable it. Useful when other people, devices, or sidecars share your tailnet. Sessions last 30 days, persist across server restarts, and can be revoked by changing or clearing the password.- **[issue-781] Writers Room live director** — turn on "Live Director" for a work and, whenever you pause while writing, the Creative Director offers a few short ways to continue from your cursor: a beat to take, a ready-to-insert line of prose, or a bit of dialogue. It's off by default and opt-in per work, waits until you stop typing before asking, and respects a daily suggestion budget so it never runs away with your AI usage.- **[issue-710] Health insight provenance chips** — longevity and health views now label how each number was derived, the way Ask tags its sources. A small chip on your death-clock estimate, LEV tracker, epigenetic age, chronological age, and genome markers marks it as data-backed, inferred, experimental, or speculative — tap it for a plain-language explanation of how it was figured and what would change it. So a modeled projection never reads as a measured fact.- **[issue-709] Review Hub "Needs Attention" queue** — the Review Hub now opens with a cross-domain queue that pulls everything currently waiting on you into one list: Brain inbox items that need classifying, Ask answers ready to promote, CoS tasks awaiting approval, unsent message drafts, critical/high health anomalies, and failed backups. The most urgent items sort to the top, each row opens straight to where you handle it, and you can dismiss anything you don't want to act on right now. A slow or unavailable source is noted instead of blocking the rest.diff --git a/client/src/App.jsx b/client/src/App.jsxindex 610f075d9b..94f99c05d8 100644--- a/client/src/App.jsx+++ b/client/src/App.jsx@@ -87,6 +87,7 @@ const PipelineSeries = lazyWithReload(() => import('./pages/PipelineSeries'));const PipelineSeriesRoadmap = lazyWithReload(() => import('./pages/PipelineSeriesRoadmap'));const PipelineManuscriptEditor = lazyWithReload(() => import('./pages/PipelineManuscriptEditor'));const PipelineIssue = lazyWithReload(() => import('./pages/PipelineIssue'));+const Login = lazyWithReload(() => import('./pages/Login'));// Loading fallback for lazy-loaded pagesconst PageLoader = () => (@@ -158,6 +159,7 @@ export default function App() {<CatalogTypesProvider><Suspense fallback={<PageLoader />}><Routes>+ <Route path="/login" element={<Login />} /><Route path="/ambient" element={<Ambient />} /><Route path="/" element={<Layout />}><Route index element={<Dashboard />} />diff --git a/client/src/components/settings/SecurityTab.jsx b/client/src/components/settings/SecurityTab.jsxnew file mode 100644index 0000000000..8fdf3fcb3f--- /dev/null+++ b/client/src/components/settings/SecurityTab.jsx@@ -0,0 +1,208 @@+import { useEffect, useState } from 'react';+import { Lock, ShieldCheck, ShieldOff } from 'lucide-react';+import toast from '../ui/Toast';+import BrailleSpinner from '../BrailleSpinner';+import { getAuthStatus, setAuthPassword, clearAuthPassword } from '../../services/api';++// PortOS is single-user and normally trusted because it's tailnet-only — auth+// here is opt-in defense against an attacker on the same network (a sidecar+// on the same tailnet, an unattended workstation). When off, every request+// is accepted as it always was. When on, every /api request needs a valid+// session cookie obtained by /api/auth/login.+export function SecurityTab() {+ const [loading, setLoading] = useState(true);+ const [enabled, setEnabled] = useState(false);+ const [currentPassword, setCurrentPassword] = useState('');+ const [newPassword, setNewPassword] = useState('');+ const [confirmPassword, setConfirmPassword] = useState('');+ const [saving, setSaving] = useState(false);+ const [showDisable, setShowDisable] = useState(false);+ const [disablePassword, setDisablePassword] = useState('');+ const [disabling, setDisabling] = useState(false);++ useEffect(() => {+ getAuthStatus({ silent: true })+ .then((s) => setEnabled(!!s?.enabled))+ .catch(() => null)+ .finally(() => setLoading(false));+ }, []);++ const handleSubmit = async (event) => {+ event.preventDefault();+ if (saving) return;+ if (newPassword.length < 8) {+ toast.error('Password must be at least 8 characters');+ return;+ }+ if (newPassword !== confirmPassword) {+ toast.error('Passwords do not match');+ return;+ }+ if (enabled && !currentPassword) {+ toast.error('Enter your current password to change it');+ return;+ }+ setSaving(true);+ const result = await setAuthPassword({+ newPassword,+ currentPassword: enabled ? currentPassword : undefined,+ }).catch((err) => err);+ setSaving(false);+ if (result instanceof Error) {+ toast.error(result.code === 'AUTH_BAD_CURRENT' ? 'Current password is incorrect' : (result.message || 'Save failed'));+ return;+ }+ setEnabled(true);+ setCurrentPassword('');+ setNewPassword('');+ setConfirmPassword('');+ toast.success(enabled ? 'Password updated' : 'Login password enabled');+ };++ const handleDisable = async () => {+ if (!disablePassword) {+ toast.error('Enter your current password to disable auth');+ return;+ }+ setDisabling(true);+ const result = await clearAuthPassword({ currentPassword: disablePassword }).catch((err) => err);+ setDisabling(false);+ if (result instanceof Error) {+ toast.error(result.code === 'AUTH_BAD_CURRENT' ? 'Current password is incorrect' : (result.message || 'Disable failed'));+ return;+ }+ setEnabled(false);+ setShowDisable(false);+ setDisablePassword('');+ toast.success('Login password disabled');+ };++ if (loading) {+ return (+ <div className="flex items-center justify-center py-16">+ <BrailleSpinner text="Loading" />+ </div>+ );+ }++ return (+ <div className="max-w-2xl space-y-6">+ <div className="bg-port-card border border-port-border rounded-lg p-4">+ <div className="flex items-start gap-3">+ {enabled+ ? <ShieldCheck className="w-6 h-6 text-port-success shrink-0" />+ : <ShieldOff className="w-6 h-6 text-port-warning shrink-0" />}+ <div>+ <h2 className="text-lg font-semibold text-white">+ Login password {enabled ? 'enabled' : 'disabled'}+ </h2>+ <p className="text-sm text-gray-400 mt-1">+ PortOS is normally reachable to anything on your tailnet. Setting a+ password gates the UI and API behind a single shared secret —+ useful when other devices or sidecars share the network.+ </p>+ </div>+ </div>+ </div>++ <form onSubmit={handleSubmit} className="bg-port-card border border-port-border rounded-lg p-4 space-y-4">+ <h3 className="text-md font-semibold text-white flex items-center gap-2">+ <Lock className="w-4 h-4" /> {enabled ? 'Change password' : 'Set a password'}+ </h3>+ {enabled && (+ <div>+ <label htmlFor="security-current" className="block text-sm text-gray-300 mb-1">Current password</label>+ <input+ id="security-current"+ type="password"+ autoComplete="current-password"+ value={currentPassword}+ onChange={(e) => setCurrentPassword(e.target.value)}+ className="w-full bg-port-bg border border-port-border rounded px-3 py-2 text-white focus:border-port-accent focus:outline-none"+ />+ </div>+ )}+ <div>+ <label htmlFor="security-new" className="block text-sm text-gray-300 mb-1">New password</label>+ <input+ id="security-new"+ type="password"+ autoComplete="new-password"+ minLength={8}+ value={newPassword}+ onChange={(e) => setNewPassword(e.target.value)}+ className="w-full bg-port-bg border border-port-border rounded px-3 py-2 text-white focus:border-port-accent focus:outline-none"+ />+ <p className="text-xs text-gray-500 mt-1">Minimum 8 characters.</p>+ </div>+ <div>+ <label htmlFor="security-confirm" className="block text-sm text-gray-300 mb-1">Confirm new password</label>+ <input+ id="security-confirm"+ type="password"+ autoComplete="new-password"+ value={confirmPassword}+ onChange={(e) => setConfirmPassword(e.target.value)}+ className="w-full bg-port-bg border border-port-border rounded px-3 py-2 text-white focus:border-port-accent focus:outline-none"+ />+ </div>+ <button+ type="submit"+ disabled={saving || !newPassword || !confirmPassword || (enabled && !currentPassword)}+ className="bg-port-accent text-white px-4 py-2 rounded font-medium disabled:opacity-50 disabled:cursor-not-allowed hover:opacity-90"+ >+ {saving ? 'Saving…' : (enabled ? 'Update password' : 'Enable login')}+ </button>+ </form>++ {enabled && (+ <div className="bg-port-card border border-port-border rounded-lg p-4 space-y-3">+ <h3 className="text-md font-semibold text-white">Disable login password</h3>+ <p className="text-sm text-gray-400">+ Turn auth back off. PortOS will be reachable without a password again.+ </p>+ {!showDisable ? (+ <button+ type="button"+ onClick={() => setShowDisable(true)}+ className="bg-port-bg border border-port-border text-port-error px-3 py-2 rounded hover:border-port-error"+ >+ Disable login+ </button>+ ) : (+ <div className="space-y-3">+ <div>+ <label htmlFor="security-disable" className="block text-sm text-gray-300 mb-1">Enter current password to confirm</label>+ <input+ id="security-disable"+ type="password"+ autoComplete="current-password"+ value={disablePassword}+ onChange={(e) => setDisablePassword(e.target.value)}+ className="w-full bg-port-bg border border-port-border rounded px-3 py-2 text-white focus:border-port-accent focus:outline-none"+ />+ </div>+ <div className="flex gap-2">+ <button+ type="button"+ onClick={handleDisable}+ disabled={disabling || !disablePassword}+ className="bg-port-error text-white px-3 py-2 rounded disabled:opacity-50 hover:opacity-90"+ >+ {disabling ? 'Disabling…' : 'Confirm disable'}+ </button>+ <button+ type="button"+ onClick={() => { setShowDisable(false); setDisablePassword(''); }}+ className="bg-port-bg border border-port-border text-gray-300 px-3 py-2 rounded"+ >+ Cancel+ </button>+ </div>+ </div>+ )}+ </div>+ )}+ </div>+ );+}diff --git a/client/src/components/settings/SettingsTabsHeader.jsx b/client/src/components/settings/SettingsTabsHeader.jsxindex 1fc53b4d4c..c10f6225c6 100644--- a/client/src/components/settings/SettingsTabsHeader.jsx+++ b/client/src/components/settings/SettingsTabsHeader.jsx@@ -21,6 +21,7 @@ export const TABS = [{ id: 'mortalloom', label: 'MortalLoom', to: '/settings/mortalloom' },{ id: 'prompts', label: 'Prompts', to: '/prompts' },{ id: 'providers', label: 'Providers', to: '/ai' },+ { id: 'security', label: 'Security', to: '/settings/security' },{ id: 'sharing', label: 'Sharing', to: '/settings/sharing' },{ id: 'telegram', label: 'Telegram', to: '/settings/telegram' },{ id: 'voice', label: 'Voice', to: '/settings/voice' }diff --git a/client/src/pages/Login.jsx b/client/src/pages/Login.jsxnew file mode 100644index 0000000000..871b9fd863--- /dev/null+++ b/client/src/pages/Login.jsx@@ -0,0 +1,90 @@+import { useEffect, useState } from 'react';+import { useSearchParams } from 'react-router-dom';+import { getAuthStatus, loginWithPassword } from '../services/api';++// Single-password sign-in. Shown when settings.secrets.auth.enabled is true+// and the request has no valid session token. When auth is off, the page+// auto-redirects to "next" (or `/`) so a stale bookmark to /login doesn't+// become a dead end.+export default function Login() {+ const [search] = useSearchParams();+ const next = search.get('next') || '/';+ const [password, setPassword] = useState('');+ const [error, setError] = useState(null);+ const [submitting, setSubmitting] = useState(false);+ const [authEnabled, setAuthEnabled] = useState(null);++ useEffect(() => {+ let cancelled = false;+ getAuthStatus({ silent: true }).then((s) => {+ if (cancelled) return;+ if (!s?.enabled) {+ window.location.replace(next);+ return;+ }+ setAuthEnabled(true);+ }).catch(() => {+ // If even /api/auth/status fails, the server is unreachable — let the+ // user retry by leaving the form rendered.+ if (!cancelled) setAuthEnabled(true);+ });+ return () => { cancelled = true; };+ }, [next]);++ const submit = async (event) => {+ event.preventDefault();+ if (submitting || !password) return;+ setError(null);+ setSubmitting(true);+ const result = await loginWithPassword(password).catch((err) => err);+ setSubmitting(false);+ if (result instanceof Error) {+ setError(result.code === 'AUTH_BAD_PASSWORD' ? 'Incorrect password' : result.message);+ return;+ }+ // Full reload so the bootstrapping useTimezoneBootstrap + socket reconnect+ // pick up the freshly-set cookie. navigate() alone would leave the socket+ // in its connect_error state.+ window.location.replace(next);+ };++ if (authEnabled === null) {+ return <div className="min-h-screen bg-port-bg" />;+ }++ return (+ <div className="min-h-screen bg-port-bg flex items-center justify-center p-4">+ <form+ onSubmit={submit}+ className="w-full max-w-sm bg-port-card border border-port-border rounded-lg p-6 space-y-4"+ >+ <div>+ <h1 className="text-2xl font-bold text-white">PortOS</h1>+ <p className="text-sm text-gray-400 mt-1">Sign in to continue</p>+ </div>+ <div>+ <label htmlFor="login-password" className="block text-sm text-gray-300 mb-1">Password</label>+ <input+ id="login-password"+ type="password"+ autoFocus+ autoComplete="current-password"+ value={password}+ onChange={(e) => setPassword(e.target.value)}+ className="w-full bg-port-bg border border-port-border rounded px-3 py-2 text-white focus:border-port-accent focus:outline-none"+ />+ </div>+ {error && (+ <div className="text-sm text-port-error">{error}</div>+ )}+ <button+ type="submit"+ disabled={submitting || !password}+ className="w-full bg-port-accent text-white py-2 rounded font-medium disabled:opacity-50 disabled:cursor-not-allowed hover:opacity-90"+ >+ {submitting ? 'Signing in…' : 'Sign in'}+ </button>+ </form>+ </div>+ );+}diff --git a/client/src/pages/Settings.jsx b/client/src/pages/Settings.jsxindex 600eb4285e..a1e5ebeaaf 100644--- a/client/src/pages/Settings.jsx+++ b/client/src/pages/Settings.jsx@@ -9,6 +9,7 @@ import { LocalLlmTab } from '../components/settings/LocalLlmTab';import { TelegramTab } from '../components/settings/TelegramTab';import { GeneralTab } from '../components/settings/GeneralTab';import { MortalLoomTab } from '../components/settings/MortalLoomTab';+import { SecurityTab } from '../components/settings/SecurityTab';import { SharingTab } from '../components/settings/SharingTab';import { VoiceTab } from '../components/settings/VoiceTab';import SettingsTabsHeader from '../components/settings/SettingsTabsHeader';@@ -38,6 +39,7 @@ export default function Settings() {case 'database': return <DatabaseTab />;case 'embeddings': return <EmbeddingsTab />;case 'local-llm': return <LocalLlmTab />;+ case 'security': return <SecurityTab />;case 'sharing': return <SharingTab />;case 'voice': return <VoiceTab />;case 'telegram': return <TelegramTab />;diff --git a/client/src/services/README.md b/client/src/services/README.mdindex 454b9ff68c..8bf428f8b5 100644--- a/client/src/services/README.md+++ b/client/src/services/README.md@@ -56,6 +56,7 @@ toasts on throw). **Custom catch ⇒ `silent: true`** — otherwise toasts fire| `apiScaffold.js` | App scaffolding templates. || `apiSchedules.js` | Automation schedules. || `apiSystem.js` | System info (CPU/memory/ports/alerts) + D&D-style character sheet getter. |+| `apiAuth.js` | Optional login password — status, login/logout, set/clear password. || `apiLoops.js` | Scheduled loops. |## Personal data / identitydiff --git a/client/src/services/api.js b/client/src/services/api.jsindex 0cc8699794..5ecf14332c 100644--- a/client/src/services/api.js+++ b/client/src/services/api.js@@ -52,6 +52,7 @@ export * from './apiCreativeDirector.js';export * from './apiImporter.js';export * from './apiStoryBuilder.js';export * from './apiVoice.js';+export * from './apiAuth.js';// Default export for simplified imports (get/post/put/delete helpers)export { default } from './apiCore.js';diff --git a/client/src/services/apiAuth.js b/client/src/services/apiAuth.jsnew file mode 100644index 0000000000..473c5ac477--- /dev/null+++ b/client/src/services/apiAuth.js@@ -0,0 +1,29 @@+import { request } from './apiCore.js';++// Public — no token required. Callers use this to decide whether to render+// the login gate at all.+export const getAuthStatus = (options) => request('/auth/status', options);++// `silent: true` everywhere — the LoginGate handles 401 / auth flows itself,+// so the default error-toast layer would just double up.+export const getWhoami = (options) => request('/auth/whoami', { silent: true, ...options });++export const loginWithPassword = (password) => request('/auth/login', {+ method: 'POST',+ body: JSON.stringify({ password }),+ silent: true,+});++export const logout = () => request('/auth/logout', { method: 'POST', silent: true });++export const setAuthPassword = ({ newPassword, currentPassword }) => request('/auth/password', {+ method: 'POST',+ body: JSON.stringify({ newPassword, ...(currentPassword ? { currentPassword } : {}) }),+ silent: true,+});++export const clearAuthPassword = ({ currentPassword }) => request('/auth/password', {+ method: 'DELETE',+ body: JSON.stringify({ currentPassword }),+ silent: true,+});diff --git a/client/src/services/apiCore.js b/client/src/services/apiCore.jsindex 37a435f5b0..6e46575e41 100644--- a/client/src/services/apiCore.js+++ b/client/src/services/apiCore.js@@ -31,11 +31,21 @@ export async function request(endpoint, options = {}) {if (!response.ok) {const error = await response.json().catch(() => ({ error: 'Request failed' }));const errorMessage = error.error || `HTTP ${response.status}`;+ // Auth gate (server: lib/authGate.js) returns 401 with code AUTH_REQUIRED+ // for any /api request without a valid session. Bounce to /login so the+ // user can re-authenticate; skip if we're already there.+ if (response.status === 401 && error?.code === 'AUTH_REQUIRED' && typeof window !== 'undefined') {+ const here = window.location.pathname + window.location.search;+ if (!window.location.pathname.startsWith('/login')) {+ const next = encodeURIComponent(here);+ window.location.replace(`/login?next=${next}`);+ }+ }if (!silent) {// Platform unavailability is a warning, not an errorif (error.code === 'PLATFORM_UNAVAILABLE') {toast(errorMessage, { icon: '⚠️' });- } else {+ } else if (error.code !== 'AUTH_REQUIRED') {toast.error(errorMessage);}}diff --git a/client/src/services/socket.js b/client/src/services/socket.jsindex 4443663deb..1189a24047 100644--- a/client/src/services/socket.js+++ b/client/src/services/socket.js@@ -20,8 +20,16 @@ socket.on('disconnect', () => {// Connection lost - Socket.IO will attempt reconnection automatically});-socket.on('connect_error', () => {- // Connection error - Socket.IO will retry automatically+socket.on('connect_error', (err) => {+ // Auth gate rejected the handshake (server: lib/authGate.js socketAuthGate).+ // Bounce to /login so the user can sign back in; skip if already there.+ if (err?.data?.code === 'AUTH_REQUIRED' && typeof window !== 'undefined') {+ if (!window.location.pathname.startsWith('/login')) {+ const next = encodeURIComponent(window.location.pathname + window.location.search);+ window.location.replace(`/login?next=${next}`);+ }+ }+ // Other connection errors: Socket.IO will retry automatically.});// Embedded build id from the served index.html. The server injects adiff --git a/server/index.js b/server/index.jsindex ce5e8140f7..09b162fdc7 100644--- a/server/index.js+++ b/server/index.js@@ -88,6 +88,8 @@ import { initMortalLoomStore } from './services/mortalLoomStore.js';import reviewRoutes from './routes/review.js';import githubRoutes from './routes/github.js';import settingsRoutes from './routes/settings.js';+import authRoutes from './routes/auth.js';+import { authGate, socketAuthGate } from './lib/authGate.js';import telegramRoutes from './routes/telegram.js';import updateRoutes from './routes/update.js';import loopsRoutes from './routes/loops.js';@@ -187,6 +189,11 @@ const io = new Server(httpServer, {path: '/socket.io'});+// Auth gate for Socket.IO — when settings.secrets.auth.enabled is true the+// handshake must carry a valid token cookie or Authorization: Bearer header+// (set by POST /api/auth/login). No-op when auth is off.+io.use(socketAuthGate);+// Initialize socket handlersinitSocket(io);@@ -375,7 +382,13 @@ app.use(express.urlencoded({ limit: '55mb', extended: true }));// Make io available to routesapp.set('io', io);+// Auth gate runs before any /api/* route. When settings.secrets.auth.enabled+// is true the gate returns 401 for everything except the small public set in+// lib/authGate.js (login, status, healthz). No-op when auth is off.+app.use(authGate);+// API Routes+app.use('/api/auth', authRoutes);app.use('/api/alerts', alertsRoutes);app.use('/api/avatar', avatarRoutes);app.use('/api/system', systemHealthRoutes);diff --git a/server/lib/README.md b/server/lib/README.mdindex feb17611b6..b4981ea01d 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -194,6 +194,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| Module | Purpose ||---|---|| `asyncMutex.js` | Promise-based async mutex. |+| `authGate.js` | Express + Socket.IO middleware that gates `/api/*` and `/data/*` behind the password set in `settings.secrets.auth`. No-op when auth is off; emits 401 `AUTH_REQUIRED` (or plain text for `/data/*`) when on and the request has no valid session token. || `errorHandler.js` | `ServerError` + `asyncHandler` middleware. || `mapWithConcurrency.js` | Generic bounded-concurrency async mapper that preserves input order while capping in-flight work. || `objects.js` | Object utilities — `deepMerge` (recursive merge w/ array replacement), `isPlainObject` (non-null, non-array `object` guard for JSON / LLM payloads), `POLLUTING_KEYS` (shared `__proto__`/`constructor`/`prototype` denylist for sanitizers), `canonicalStringify` (recursive sorted-key JSON serialization for cross-machine content hashing), `isEmptyScalar` (true for null/undefined/whitespace-string/empty-array — merge gap-fill gate). |diff --git a/server/lib/authGate.js b/server/lib/authGate.jsnew file mode 100644index 0000000000..a91d1fea7e--- /dev/null+++ b/server/lib/authGate.js@@ -0,0 +1,61 @@+import { extractToken, isAuthEnabled, verifySession } from '../services/auth.js';++// Paths that bypass the auth gate even when a password is set:+// - /api/auth/status, /api/auth/whoami, /api/auth/login → the login UI+// itself needs to reach these to render and sign in.+// - /api/system/health (and the cheap /healthz used by uptime checks) — the+// server has to be reachable by Tailscale's healthcheck without a session.+// Anything not on this list returns 401 when auth is on and the request has+// no valid token.+const PUBLIC_API_PATHS = new Set([+ '/api/auth/status',+ '/api/auth/whoami',+ '/api/auth/login',+ '/api/auth/logout',+ '/api/system/health',+ '/healthz',+]);++const isPublicPath = (path) => {+ if (PUBLIC_API_PATHS.has(path)) return true;+ // Static client assets ship in client/dist/. Gating them is pointless — the+ // index.html is just the bootstrap loader, and a sidecar attacker can't do+ // anything with it without a token to hit the JSON API. Letting them through+ // also keeps the login page itself reachable.+ return !path.startsWith('/api/') && !path.startsWith('/data/');+};++// Express middleware. Bypasses everything when auth is off. When it's on,+// allows the small public set above; gates the rest behind a valid token in+// the cookie or Authorization: Bearer header.+export const authGate = async (req, res, next) => {+ const enabled = await isAuthEnabled();+ if (!enabled) return next();+ const path = req.path;+ if (isPublicPath(path)) return next();+ const token = extractToken(req);+ if (await verifySession(token)) return next();+ // /data/* is hit directly by <img>/<audio>/<video> tags which don't show a+ // structured-JSON error — return a plain 401 there. API callers expect the+ // PortOS error envelope.+ if (path.startsWith('/data/')) {+ res.status(401).type('text/plain').send('Unauthorized');+ return;+ }+ res.status(401).json({ error: 'Authentication required', code: 'AUTH_REQUIRED' });+};++// Socket.IO middleware. Run after a successful HTTP-side handshake — same+// `req.headers.cookie` is available on `socket.handshake.headers`. When auth+// is off, every connection is allowed; when on, the handshake must carry a+// valid cookie/header.+export const socketAuthGate = async (socket, next) => {+ const enabled = await isAuthEnabled();+ if (!enabled) return next();+ const fakeReq = { headers: socket.handshake?.headers || {} };+ const token = extractToken(fakeReq);+ if (await verifySession(token)) return next();+ const err = new Error('Authentication required');+ err.data = { code: 'AUTH_REQUIRED' };+ next(err);+};diff --git a/server/lib/authGate.test.js b/server/lib/authGate.test.jsnew file mode 100644index 0000000000..09b9641b8c--- /dev/null+++ b/server/lib/authGate.test.js@@ -0,0 +1,135 @@+import { afterAll, beforeEach, describe, expect, it, vi } from 'vitest';+import { writeFileSync } from 'fs';+import { join } from 'path';+import { mockPathsDataRoot } from './mockPathsDataRoot.js';++const { tempRoot, makeProxy, cleanup } = mockPathsDataRoot({ prefix: 'portos-authgate-' });++vi.mock('../lib/fileUtils.js', async () => {+ const actual = await vi.importActual('../lib/fileUtils.js');+ return makeProxy(actual);+});++const resetSettings = () => {+ writeFileSync(join(tempRoot, 'settings.json'), '{}\n');+ writeFileSync(join(tempRoot, 'auth-sessions.json'), '{"tokens":[]}\n');+};++beforeEach(() => {+ vi.resetModules();+ resetSettings();+});++afterAll(() => {+ cleanup();+});++const runGate = async (gate, req) => new Promise((resolve) => {+ const res = {+ statusCode: 200,+ body: null,+ headers: {},+ type(value) { this.headers['Content-Type'] = value; return this; },+ status(code) { this.statusCode = code; return this; },+ json(payload) { this.body = payload; resolve({ res, called: false }); return this; },+ send(payload) { this.body = payload; resolve({ res, called: false }); return this; },+ };+ gate(req, res, () => resolve({ res, called: true }));+});++describe('authGate middleware', () => {+ it('is a no-op when auth is disabled', async () => {+ const { authGate } = await import('./authGate.js');+ const result = await runGate(authGate, { path: '/api/cos', headers: {} });+ expect(result.called).toBe(true);+ });++ it('passes /api/auth/login through even when auth is enabled', async () => {+ const auth = await import('../services/auth.js');+ await auth.setPassword({ newPassword: 'correct-horse' });+ const { authGate } = await import('./authGate.js');+ const result = await runGate(authGate, { path: '/api/auth/login', headers: {} });+ expect(result.called).toBe(true);+ });++ it('blocks /api routes with no token', async () => {+ const auth = await import('../services/auth.js');+ await auth.setPassword({ newPassword: 'correct-horse' });+ const { authGate } = await import('./authGate.js');+ const result = await runGate(authGate, { path: '/api/cos', headers: {} });+ expect(result.called).toBe(false);+ expect(result.res.statusCode).toBe(401);+ expect(result.res.body).toEqual({ error: 'Authentication required', code: 'AUTH_REQUIRED' });+ });++ it('allows /api routes when the cookie token is valid', async () => {+ const auth = await import('../services/auth.js');+ const { token } = await auth.setPassword({ newPassword: 'correct-horse' });+ const { authGate } = await import('./authGate.js');+ const result = await runGate(authGate, {+ path: '/api/cos',+ headers: { cookie: `portos_auth=${token}` },+ });+ expect(result.called).toBe(true);+ });++ it('allows /api routes when the Authorization Bearer token is valid', async () => {+ const auth = await import('../services/auth.js');+ const { token } = await auth.setPassword({ newPassword: 'correct-horse' });+ const { authGate } = await import('./authGate.js');+ const result = await runGate(authGate, {+ path: '/api/cos',+ headers: { authorization: `Bearer ${token}` },+ });+ expect(result.called).toBe(true);+ });++ it('lets static client paths through when auth is on', async () => {+ const auth = await import('../services/auth.js');+ await auth.setPassword({ newPassword: 'correct-horse' });+ const { authGate } = await import('./authGate.js');+ const result = await runGate(authGate, { path: '/assets/index.js', headers: {} });+ expect(result.called).toBe(true);+ });++ it('returns plain-text 401 for blocked /data/* asset requests', async () => {+ const auth = await import('../services/auth.js');+ await auth.setPassword({ newPassword: 'correct-horse' });+ const { authGate } = await import('./authGate.js');+ const result = await runGate(authGate, { path: '/data/images/foo.png', headers: {} });+ expect(result.called).toBe(false);+ expect(result.res.statusCode).toBe(401);+ expect(result.res.body).toBe('Unauthorized');+ });+});++describe('socketAuthGate middleware', () => {+ it('is a no-op when auth is disabled', async () => {+ const { socketAuthGate } = await import('./authGate.js');+ const result = await new Promise((resolve) => {+ socketAuthGate({ handshake: { headers: {} } }, (err) => resolve(err));+ });+ expect(result).toBeUndefined();+ });++ it('rejects an unauthenticated handshake when auth is on', async () => {+ const auth = await import('../services/auth.js');+ await auth.setPassword({ newPassword: 'correct-horse' });+ const { socketAuthGate } = await import('./authGate.js');+ const err = await new Promise((resolve) => {+ socketAuthGate({ handshake: { headers: {} } }, (e) => resolve(e));+ });+ expect(err).toBeInstanceOf(Error);+ expect(err.data).toEqual({ code: 'AUTH_REQUIRED' });+ });++ it('accepts a handshake with a valid cookie', async () => {+ const auth = await import('../services/auth.js');+ const { token } = await auth.setPassword({ newPassword: 'correct-horse' });+ const { socketAuthGate } = await import('./authGate.js');+ const err = await new Promise((resolve) => {+ socketAuthGate({ handshake: { headers: { cookie: `portos_auth=${token}` } } }, (e) => resolve(e));+ });+ expect(err).toBeUndefined();+ });+});diff --git a/server/lib/index.js b/server/lib/index.jsindex d4bd501425..4653222d90 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -161,6 +161,7 @@ export * from './timezone.js';// === General utilities ===export * from './asyncMutex.js';+export * from './authGate.js';export * from './errorHandler.js';export * from './mapWithConcurrency.js';export * from './objects.js';diff --git a/server/lib/navManifest.js b/server/lib/navManifest.jsindex 64f8187d1f..c6eb3e13a6 100644--- a/server/lib/navManifest.js+++ b/server/lib/navManifest.js@@ -146,6 +146,7 @@ export const NAV_COMMANDS = [{ id: 'nav.settings.local-llm', path: '/settings/local-llm', label: 'Local LLMs', section: 'Settings', aliases: ['local-llm', 'local-llms', 'ollama', 'lm-studio', 'lmstudio'], keywords: ['ollama', 'lm studio', 'local model', 'local llm', 'gguf', 'pull model', 'install model', 'migrate', 'switch backend'] },{ id: 'nav.settings.local-llm-playground', path: '/local-llm/playground', label: 'Local LLM Playground', section: 'Settings', aliases: ['llm-playground', 'playground', 'model-playground', 'compare-models'], keywords: ['ollama', 'lm studio', 'compare', 'benchmark', 'chat', 'test model', 'ttft', 'tokens per second', 'local llm'] },{ id: 'nav.settings.mortalloom', path: '/settings/mortalloom', label: 'MortalLoom', section: 'Settings', aliases: ['settings-mortalloom', 'mortalloom'] },+ { id: 'nav.settings.security', path: '/settings/security', label: 'Security', section: 'Settings', aliases: ['settings-security', 'login-password', 'auth-password', 'password-settings'], keywords: ['password', 'login', 'auth', 'sign-in', 'lock', 'tailnet', 'sidecar'] },{ id: 'nav.settings.sharing', path: '/settings/sharing', label: 'Sharing', section: 'Settings', aliases: ['settings-sharing', 'sharing-settings'], keywords: ['display name', 'bio', 'attribution', 'identity', 'source'] },{ id: 'nav.settings.telegram', path: '/settings/telegram', label: 'Telegram', section: 'Settings', aliases: ['settings-telegram', 'telegram'] },{ id: 'nav.settings.voice', path: '/settings/voice', label: 'Voice', section: 'Settings', aliases: ['settings-voice', 'voice', 'voice-settings'], keywords: ['mic', 'microphone', 'speech', 'tts', 'whisper', 'kokoro'] },diff --git a/server/lib/navManifest.test.js b/server/lib/navManifest.test.jsindex 710daf6a5d..fb2c52c119 100644--- a/server/lib/navManifest.test.js+++ b/server/lib/navManifest.test.js@@ -283,6 +283,7 @@ const APP_JSX = path.join(REPO_ROOT, 'client/src/App.jsx');const NAV_COVERAGE_OPT_OUT = new Map([['/apps/create', 'create-app form, reached via the "New App" button on /apps'],['/feature-agents/create', 'create-agent form, reached via the "New Agent" button'],+ ['/login', 'auth gate — surfaced only when settings.secrets.auth is enabled, reached via 401 redirect'],['/templates', 'legacy templates page, intentionally not surfaced in nav'],['/universes/new', 'create-mode sentinel for the Universe Builder editor'],]);diff --git a/server/routes/auth.js b/server/routes/auth.jsnew file mode 100644index 0000000000..c3d3d9c45c--- /dev/null+++ b/server/routes/auth.js@@ -0,0 +1,106 @@+import { Router } from 'express';+import { z } from 'zod';+import {+ buildClearCookie,+ buildSessionCookie,+ clearPassword,+ createSession,+ extractToken,+ getAuthStatus,+ isAuthEnabled,+ revokeSession,+ setPassword,+ verifyPassword,+ verifySession,+} from '../services/auth.js';+import { asyncHandler, ServerError } from '../lib/errorHandler.js';+import { validateRequest } from '../lib/validation.js';++const router = Router();++const loginSchema = z.object({ password: z.string().min(1).max(256) }).strict();+const setPasswordSchema = z.object({+ newPassword: z.string().min(8).max(256),+ currentPassword: z.string().max(256).optional(),+}).strict();+const clearPasswordSchema = z.object({ currentPassword: z.string().min(1).max(256) }).strict();++// Whether the request reached us over HTTPS (so the cookie should carry the+// Secure flag). `req.secure` reflects the actual socket; we don't trust+// X-Forwarded-Proto since PortOS isn't behind a reverse proxy in its normal+// deployment topology.+const isSecure = (req) => !!req.secure;++// GET /api/auth/status — always reachable. The UI uses this to know whether+// to render the login gate at all.+router.get('/status', asyncHandler(async (_req, res) => {+ res.json(await getAuthStatus());+}));++// GET /api/auth/whoami — confirm the current cookie/header is still valid.+// Returns { authenticated: true|false, required: true|false } so the client+// can disambiguate "auth off" from "auth on, you're signed in" from "auth on,+// you're not signed in".+router.get('/whoami', asyncHandler(async (req, res) => {+ const required = await isAuthEnabled();+ if (!required) {+ res.json({ authenticated: true, required: false });+ return;+ }+ const token = extractToken(req);+ const authenticated = await verifySession(token);+ res.json({ authenticated, required: true });+}));++// POST /api/auth/login+router.post('/login', asyncHandler(async (req, res) => {+ const { password } = validateRequest(loginSchema, req.body || {});+ if (!(await isAuthEnabled())) {+ throw new ServerError('Authentication is not enabled', { status: 400, code: 'AUTH_NOT_ENABLED' });+ }+ if (!(await verifyPassword(password))) {+ throw new ServerError('Invalid password', { status: 401, code: 'AUTH_BAD_PASSWORD' });+ }+ const { token } = await createSession();+ res.setHeader('Set-Cookie', buildSessionCookie(token, { secure: isSecure(req) }));+ res.json({ authenticated: true });+}));++// POST /api/auth/logout — best-effort revoke + clear cookie. Idempotent so a+// double-click on Sign Out doesn't 401.+router.post('/logout', asyncHandler(async (req, res) => {+ const token = extractToken(req);+ if (token) await revokeSession(token);+ res.setHeader('Set-Cookie', buildClearCookie());+ res.json({ ok: true });+}));++// POST /api/auth/password — set or rotate the password. When auth is already+// on, the caller must include their current password. When it's off, this is+// the first-time-set path and `currentPassword` is ignored. Returns a fresh+// session cookie so the user stays signed in.+router.post('/password', asyncHandler(async (req, res) => {+ const body = validateRequest(setPasswordSchema, req.body || {});+ const alreadyEnabled = await isAuthEnabled();+ // First-time set is the ONLY public mutation here — once auth is on, the+ // route is gated by the API auth middleware in server/index.js, so we+ // reach this branch only with a valid session.+ const { token } = await setPassword({+ newPassword: body.newPassword,+ currentPassword: alreadyEnabled ? body.currentPassword : null,+ });+ res.setHeader('Set-Cookie', buildSessionCookie(token, { secure: isSecure(req) }));+ res.json({ enabled: true });+}));++// DELETE /api/auth/password — turn auth off. Requires the current password+// so an attacker holding only a session token (without the password) can't+// silently disable the gate.+router.delete('/password', asyncHandler(async (req, res) => {+ const { currentPassword } = validateRequest(clearPasswordSchema, req.body || {});+ await clearPassword({ currentPassword });+ res.setHeader('Set-Cookie', buildClearCookie());+ res.json({ enabled: false });+}));++export default router;diff --git a/server/routes/auth.test.js b/server/routes/auth.test.jsnew file mode 100644index 0000000000..c4b7b1dff7--- /dev/null+++ b/server/routes/auth.test.js@@ -0,0 +1,111 @@+import { afterAll, beforeEach, describe, expect, it, vi } from 'vitest';+import express from 'express';+import { writeFileSync } from 'fs';+import { join } from 'path';+import { mockPathsDataRoot } from '../lib/mockPathsDataRoot.js';+import { request } from '../lib/testHelper.js';++const { tempRoot, makeProxy, cleanup } = mockPathsDataRoot({ prefix: 'portos-auth-routes-' });++vi.mock('../lib/fileUtils.js', async () => {+ const actual = await vi.importActual('../lib/fileUtils.js');+ return makeProxy(actual);+});++const resetSettings = () => {+ writeFileSync(join(tempRoot, 'settings.json'), '{}\n');+ writeFileSync(join(tempRoot, 'auth-sessions.json'), '{"tokens":[]}\n');+};++const buildApp = async () => {+ // Re-import the route module under the current mock state so the test sees+ // a fresh auth-service binding each time.+ vi.resetModules();+ const { default: authRoutes } = await import('./auth.js');+ const app = express();+ app.use(express.json());+ app.use('/api/auth', authRoutes);+ return app;+};++beforeEach(() => {+ resetSettings();+});++afterAll(() => {+ cleanup();+});++describe('auth routes', () => {+ it('GET /api/auth/status reports disabled by default', async () => {+ const app = await buildApp();+ const res = await request(app).get('/api/auth/status');+ expect(res.status).toBe(200);+ expect(res.body).toEqual({ enabled: false });+ });++ it('GET /api/auth/whoami reports authenticated when auth is off', async () => {+ const app = await buildApp();+ const res = await request(app).get('/api/auth/whoami');+ expect(res.body).toEqual({ authenticated: true, required: false });+ });++ it('POST /api/auth/password sets first-time password and returns a cookie', async () => {+ const app = await buildApp();+ const res = await request(app)+ .post('/api/auth/password')+ .send({ newPassword: 'correct-horse' });+ expect(res.status).toBe(200);+ expect(res.body).toEqual({ enabled: true });+ const setCookie = res.headers['set-cookie'];+ expect(setCookie).toMatch(/portos_auth=/);+ expect(setCookie).toMatch(/HttpOnly/);+ });++ it('POST /api/auth/login rejects when auth is disabled', async () => {+ const app = await buildApp();+ const res = await request(app).post('/api/auth/login').send({ password: 'anything' });+ expect(res.status).toBe(400);+ expect(res.body.code).toBe('AUTH_NOT_ENABLED');+ });++ it('POST /api/auth/login rejects bad passwords and accepts correct ones', async () => {+ let app = await buildApp();+ await request(app).post('/api/auth/password').send({ newPassword: 'correct-horse' });++ app = await buildApp();+ const bad = await request(app).post('/api/auth/login').send({ password: 'wrong' });+ expect(bad.status).toBe(401);+ expect(bad.body.code).toBe('AUTH_BAD_PASSWORD');++ const good = await request(app).post('/api/auth/login').send({ password: 'correct-horse' });+ expect(good.status).toBe(200);+ expect(good.body).toEqual({ authenticated: true });+ expect(good.headers['set-cookie']).toMatch(/portos_auth=/);+ });++ it('POST /api/auth/logout always clears the cookie', async () => {+ const app = await buildApp();+ const res = await request(app).post('/api/auth/logout');+ expect(res.status).toBe(200);+ expect(res.body).toEqual({ ok: true });+ expect(res.headers['set-cookie']).toMatch(/Max-Age=0/);+ });++ it('DELETE /api/auth/password requires the current password', async () => {+ let app = await buildApp();+ await request(app).post('/api/auth/password').send({ newPassword: 'correct-horse' });++ app = await buildApp();+ const bad = await request(app)+ .delete('/api/auth/password')+ .send({ currentPassword: 'nope' });+ expect(bad.status).toBe(401);++ const good = await request(app)+ .delete('/api/auth/password')+ .send({ currentPassword: 'correct-horse' });+ expect(good.status).toBe(200);+ expect(good.body).toEqual({ enabled: false });+ });+});diff --git a/server/services/auth.js b/server/services/auth.jsnew file mode 100644index 0000000000..3eb6e44577--- /dev/null+++ b/server/services/auth.js@@ -0,0 +1,236 @@+import { join } from 'path';+import { randomBytes, scrypt, timingSafeEqual } from 'crypto';+import { promisify } from 'util';+import { atomicWrite, PATHS, safeJSONParse, tryReadFile } from '../lib/fileUtils.js';+import { getSettings, updateSettings } from './settings.js';+import { ServerError } from '../lib/errorHandler.js';++// Auth gates the PortOS UI + API behind a single user-set password. PortOS is+// single-user (one human per install) so there are no usernames or roles —+// just a password and a session token. The password hash + salt live under+// `secrets.auth` in settings.json so the existing GET /api/settings sanitizer+// (which strips `secrets`) keeps them off the wire.++const scryptAsync = promisify(scrypt);++const SESSIONS_FILE = join(PATHS.data, 'auth-sessions.json');+const TOKEN_BYTES = 32;+const SALT_BYTES = 16;+const HASH_BYTES = 64;+const SESSION_TTL_MS = 30 * 24 * 60 * 60 * 1000; // 30 days+const COOKIE_NAME = 'portos_auth';+const SCRYPT_PARAMS = { N: 16384, r: 8, p: 1 };++// In-memory session store. Keyed by token → { expiresAt }. Persisted to disk on+// every mutation so tokens survive server restarts (handy when PM2 reloads on+// update). A single-user install rarely has more than a handful of live+// sessions; a Map keeps this simple.+const sessions = new Map();+let loaded = false;++const now = () => Date.now();++const readSessions = async () => {+ const raw = await tryReadFile(SESSIONS_FILE);+ const parsed = safeJSONParse(raw ?? '{}', {});+ if (!Array.isArray(parsed.tokens)) return;+ const cutoff = now();+ for (const entry of parsed.tokens) {+ if (!entry?.token || typeof entry.expiresAt !== 'number') continue;+ if (entry.expiresAt <= cutoff) continue;+ sessions.set(entry.token, { expiresAt: entry.expiresAt });+ }+};++const writeSessions = async () => {+ const tokens = [];+ for (const [token, { expiresAt }] of sessions) {+ tokens.push({ token, expiresAt });+ }+ await atomicWrite(SESSIONS_FILE, JSON.stringify({ tokens }, null, 2) + '\n');+};++const ensureLoaded = async () => {+ if (loaded) return;+ loaded = true;+ await readSessions().catch((err) => {+ console.error(`❌ Failed to load auth sessions: ${err.message}`);+ });+};++const hashPassword = async (password, salt) => {+ const buf = await scryptAsync(password, salt, HASH_BYTES, SCRYPT_PARAMS);+ return buf.toString('hex');+};++const constantEqual = (aHex, bHex) => {+ const a = Buffer.from(aHex, 'hex');+ const b = Buffer.from(bHex, 'hex');+ if (a.length !== b.length) return false;+ return timingSafeEqual(a, b);+};++const readAuthConfig = async () => {+ const settings = await getSettings();+ return settings?.secrets?.auth ?? null;+};++export const isAuthEnabled = async () => {+ const auth = await readAuthConfig();+ return !!(auth?.enabled && auth?.passwordHash && auth?.salt);+};++export const getAuthStatus = async () => {+ const enabled = await isAuthEnabled();+ return { enabled };+};++// Set or replace the password. When `currentPassword` is provided we verify it+// against the stored hash first; pass `null` for the first-time set. Returns a+// fresh session token so the caller can stay signed in after a change.+export const setPassword = async ({ newPassword, currentPassword = null }) => {+ if (typeof newPassword !== 'string' || newPassword.length < 8) {+ throw new ServerError('Password must be at least 8 characters', { status: 400, code: 'AUTH_PASSWORD_TOO_SHORT' });+ }+ if (newPassword.length > 256) {+ throw new ServerError('Password too long', { status: 400, code: 'AUTH_PASSWORD_TOO_LONG' });+ }+ const existing = await readAuthConfig();+ if (existing?.enabled) {+ const ok = typeof currentPassword === 'string'+ && existing.passwordHash+ && existing.salt+ && constantEqual(await hashPassword(currentPassword, existing.salt), existing.passwordHash);+ if (!ok) {+ throw new ServerError('Current password is incorrect', { status: 401, code: 'AUTH_BAD_CURRENT' });+ }+ }+ const salt = randomBytes(SALT_BYTES).toString('hex');+ const passwordHash = await hashPassword(newPassword, salt);+ const settings = await getSettings();+ const secrets = { ...(settings.secrets || {}) };+ secrets.auth = {+ enabled: true,+ kdf: 'scrypt',+ passwordHash,+ salt,+ updatedAt: new Date().toISOString(),+ };+ await updateSettings({ secrets });+ // Existing sessions are invalidated on password change — the user (or anyone+ // holding a stolen token) starts over.+ await revokeAllSessions();+ return createSession();+};++// Clear the password entirely (turn auth off). Mirrors setPassword's+// current-password check so the disable can't happen without proof of identity.+export const clearPassword = async ({ currentPassword }) => {+ const existing = await readAuthConfig();+ if (!existing?.enabled) return { enabled: false };+ const ok = typeof currentPassword === 'string'+ && existing.passwordHash+ && existing.salt+ && constantEqual(await hashPassword(currentPassword, existing.salt), existing.passwordHash);+ if (!ok) {+ throw new ServerError('Current password is incorrect', { status: 401, code: 'AUTH_BAD_CURRENT' });+ }+ const settings = await getSettings();+ const secrets = { ...(settings.secrets || {}) };+ delete secrets.auth;+ await updateSettings({ secrets });+ await revokeAllSessions();+ return { enabled: false };+};++export const verifyPassword = async (password) => {+ const auth = await readAuthConfig();+ if (!auth?.enabled || !auth.passwordHash || !auth.salt) return false;+ if (typeof password !== 'string' || password.length === 0) return false;+ const candidate = await hashPassword(password, auth.salt);+ return constantEqual(candidate, auth.passwordHash);+};++export const createSession = async () => {+ await ensureLoaded();+ const token = randomBytes(TOKEN_BYTES).toString('hex');+ const expiresAt = now() + SESSION_TTL_MS;+ sessions.set(token, { expiresAt });+ await writeSessions();+ return { token, expiresAt, maxAgeMs: SESSION_TTL_MS };+};++export const verifySession = async (token) => {+ if (typeof token !== 'string' || token.length === 0) return false;+ await ensureLoaded();+ const entry = sessions.get(token);+ if (!entry) return false;+ if (entry.expiresAt <= now()) {+ sessions.delete(token);+ await writeSessions().catch(() => null);+ return false;+ }+ return true;+};++export const revokeSession = async (token) => {+ await ensureLoaded();+ if (sessions.delete(token)) {+ await writeSessions();+ }+};++export const revokeAllSessions = async () => {+ await ensureLoaded();+ sessions.clear();+ await writeSessions();+};++// Parse the `Cookie` header for our token. Express doesn't ship a cookie+// parser and we only need one cookie name — manual parse keeps the dep tree+// small (CLAUDE.md "Default to writing code yourself").+export const parseCookieToken = (cookieHeader) => {+ if (typeof cookieHeader !== 'string') return null;+ const parts = cookieHeader.split(';');+ for (const part of parts) {+ const eq = part.indexOf('=');+ if (eq === -1) continue;+ const name = part.slice(0, eq).trim();+ if (name !== COOKIE_NAME) continue;+ return decodeURIComponent(part.slice(eq + 1).trim());+ }+ return null;+};++// Pull the token from a request — cookie first, then Authorization: Bearer.+// Bearer support lets curl/scripts authenticate without juggling cookies.+// Header names are lowercased by both Node's HTTP parser and Socket.IO's+// handshake — no uppercase fallback needed.+export const extractToken = (req) => {+ const cookie = parseCookieToken(req.headers?.cookie);+ if (cookie) return cookie;+ const authHeader = req.headers?.authorization;+ if (typeof authHeader === 'string' && authHeader.startsWith('Bearer ')) {+ return authHeader.slice('Bearer '.length).trim();+ }+ return null;+};++export const buildSessionCookie = (token, { secure = false } = {}) => {+ // HttpOnly so XSS can't read it; SameSite=Lax so cross-origin GETs from the+ // browser address bar work but cross-site POSTs are blocked. `Secure` is+ // toggled by the caller based on the loopback-mirror vs HTTPS scheme of the+ // request — a `Secure` cookie on a plain-http request is silently dropped.+ const parts = [+ `${COOKIE_NAME}=${encodeURIComponent(token)}`,+ 'Path=/',+ 'HttpOnly',+ 'SameSite=Lax',+ `Max-Age=${Math.floor(SESSION_TTL_MS / 1000)}`,+ ];+ if (secure) parts.push('Secure');+ return parts.join('; ');+};++export const buildClearCookie = () =>+ `${COOKIE_NAME}=; Path=/; HttpOnly; SameSite=Lax; Max-Age=0`;diff --git a/server/services/auth.test.js b/server/services/auth.test.jsnew file mode 100644index 0000000000..7e8a5412c8--- /dev/null+++ b/server/services/auth.test.js@@ -0,0 +1,144 @@+import { afterAll, beforeEach, describe, expect, it, vi } from 'vitest';+import { rmSync } from 'fs';+import { mockPathsDataRoot } from '../lib/mockPathsDataRoot.js';++const { tempRoot, makeProxy, cleanup } = mockPathsDataRoot({ prefix: 'portos-auth-' });++vi.mock('../lib/fileUtils.js', async () => {+ const actual = await vi.importActual('../lib/fileUtils.js');+ return makeProxy(actual);+});++// Reset settings.json between tests so a password-set in one test doesn't bleed+// into the next. The auth service uses the real settings.js, which writes to+// PATHS.data → tempRoot.+import { writeFileSync } from 'fs';+import { join } from 'path';++const resetSettings = () => {+ writeFileSync(join(tempRoot, 'settings.json'), '{}\n');+ // Also blow away the session file so verifySession() doesn't carry tokens+ // across tests.+ writeFileSync(join(tempRoot, 'auth-sessions.json'), '{"tokens":[]}\n');+};++beforeEach(() => {+ vi.resetModules();+ resetSettings();+});++afterAll(() => {+ cleanup();+});++describe('auth service', () => {+ it('starts disabled when no password has been set', async () => {+ const auth = await import('./auth.js');+ expect(await auth.isAuthEnabled()).toBe(false);+ expect(await auth.getAuthStatus()).toEqual({ enabled: false });+ });++ it('rejects passwords shorter than 8 characters', async () => {+ const auth = await import('./auth.js');+ await expect(auth.setPassword({ newPassword: 'short' })).rejects.toMatchObject({+ code: 'AUTH_PASSWORD_TOO_SHORT',+ });+ });++ it('enables auth after a first-time set and returns a session token', async () => {+ const auth = await import('./auth.js');+ const session = await auth.setPassword({ newPassword: 'correct-horse' });+ expect(session.token).toMatch(/^[0-9a-f]{64}$/);+ expect(await auth.isAuthEnabled()).toBe(true);+ expect(await auth.verifySession(session.token)).toBe(true);+ });++ it('verifies the correct password and rejects the wrong one', async () => {+ const auth = await import('./auth.js');+ await auth.setPassword({ newPassword: 'correct-horse' });+ expect(await auth.verifyPassword('correct-horse')).toBe(true);+ expect(await auth.verifyPassword('battery-staple')).toBe(false);+ expect(await auth.verifyPassword('')).toBe(false);+ });++ it('blocks a password change without the current password', async () => {+ const auth = await import('./auth.js');+ await auth.setPassword({ newPassword: 'correct-horse' });+ await expect(auth.setPassword({ newPassword: 'new-password' })).rejects.toMatchObject({+ code: 'AUTH_BAD_CURRENT',+ });+ await expect(auth.setPassword({+ newPassword: 'new-password',+ currentPassword: 'wrong-old',+ })).rejects.toMatchObject({ code: 'AUTH_BAD_CURRENT' });+ });++ it('rotates the password and invalidates old sessions', async () => {+ const auth = await import('./auth.js');+ const first = await auth.setPassword({ newPassword: 'correct-horse' });+ expect(await auth.verifySession(first.token)).toBe(true);+ const next = await auth.setPassword({+ newPassword: 'second-attempt',+ currentPassword: 'correct-horse',+ });+ expect(await auth.verifySession(first.token)).toBe(false);+ expect(await auth.verifySession(next.token)).toBe(true);+ });++ it('clears the password only when the current one matches', async () => {+ const auth = await import('./auth.js');+ await auth.setPassword({ newPassword: 'correct-horse' });+ await expect(auth.clearPassword({ currentPassword: 'wrong' })).rejects.toMatchObject({+ code: 'AUTH_BAD_CURRENT',+ });+ await auth.clearPassword({ currentPassword: 'correct-horse' });+ expect(await auth.isAuthEnabled()).toBe(false);+ });++ it('revokes individual sessions', async () => {+ const auth = await import('./auth.js');+ await auth.setPassword({ newPassword: 'correct-horse' });+ const { token } = await auth.createSession();+ expect(await auth.verifySession(token)).toBe(true);+ await auth.revokeSession(token);+ expect(await auth.verifySession(token)).toBe(false);+ });++ it('extracts the token from a cookie header and Authorization: Bearer', async () => {+ const auth = await import('./auth.js');+ expect(auth.parseCookieToken('portos_auth=abc123; other=x')).toBe('abc123');+ expect(auth.parseCookieToken('other=x; portos_auth=abc123')).toBe('abc123');+ expect(auth.parseCookieToken('other=x')).toBe(null);+ expect(auth.parseCookieToken(null)).toBe(null);+ expect(auth.extractToken({ headers: { cookie: 'portos_auth=cookie-token' } })).toBe('cookie-token');+ expect(auth.extractToken({ headers: { authorization: 'Bearer header-token' } })).toBe('header-token');+ expect(auth.extractToken({+ headers: { cookie: 'portos_auth=cookie-wins', authorization: 'Bearer header-loses' },+ })).toBe('cookie-wins');+ expect(auth.extractToken({ headers: {} })).toBe(null);+ });++ it('builds session and clear cookies with the right flags', async () => {+ const auth = await import('./auth.js');+ const cookie = auth.buildSessionCookie('tok', { secure: true });+ expect(cookie).toContain('portos_auth=tok');+ expect(cookie).toContain('HttpOnly');+ expect(cookie).toContain('SameSite=Lax');+ expect(cookie).toContain('Secure');+ const insecure = auth.buildSessionCookie('tok', { secure: false });+ expect(insecure).not.toContain('Secure');+ const clear = auth.buildClearCookie();+ expect(clear).toContain('Max-Age=0');+ });++ it('persists sessions across reloads of the module', async () => {+ const auth = await import('./auth.js');+ await auth.setPassword({ newPassword: 'correct-horse' });+ const { token } = await auth.createSession();++ // Simulate a server restart by re-importing the module.+ vi.resetModules();+ const fresh = await import('./auth.js');+ expect(await fresh.verifySession(token)).toBe(true);+ });+});