Skip to content

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

gate the autofixer UI on :5560 behind the PortOS password when one is set

[._.]/ Adam Eivy5ad7715f7f0c
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 7030cb0163..038503e858 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -15,6 +15,8 @@
## Security
+- **The Autofixer UI on `:5560` now honours the PortOS password gate** — when the install is password protected (Settings → Security), the Autofixer sidecar requires the same password before it will list apps, stream PM2 logs, or restart/stop a process. It listens on `0.0.0.0` for tailnet access, so it previously stayed wide open while `:5555` asked for a password. A browser already signed in to the PortOS dashboard on the same host is let straight through (the session cookie is port-agnostic); anything else gets a login prompt, and scripts can use `Authorization: Basic`/`Bearer`. Installs with no password set are unchanged.
+
- Guard paid-provider API keys against SSRF / key-exfiltration: `streamCompletion` (askService), voice-LLM endpoint resolution, and the local-LLM playground now validate a provider's endpoint through the shared endpoint guard before attaching the `Authorization: Bearer` header, so a mistyped or malicious custom endpoint (including cloud-metadata hosts) never receives the key unless the provider opts in via `allowCustomEndpoint`.
- Bump the `js-yaml` override from 4.2.0 to 4.3.0 (root, server, client) to clear a high-severity advisory where chained YAML merge keys force quadratic CPU consumption.
- Pin server `tar` to 7.5.21 and `engine.io` to 6.6.9 via overrides, clearing a critical node-tar cluster (PAX header file smuggling, parse/decompression DoS, infinite loop on negative entry size) and an Engine.IO polling-transport connection-exhaustion advisory. These live only in `server/package-lock.json`, which is gitignored, so Dependabot never surfaced them.
diff --git a/autofixer/ui.js b/autofixer/ui.js
index 902b5880ee..ed2b96215b 100644
--- a/autofixer/ui.js
+++ b/autofixer/ui.js
@@ -6,6 +6,7 @@ import { fileURLToPath } from 'url';
import { createRequire } from 'module';
import { createTailscaleServers, watchCertReload } from '../lib/tailscale-https.js';
import { certPaths } from '../lib/certPaths.js';
+import { createSidecarAuthGate } from '../lib/sidecarAuthGate.js';
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
@@ -57,6 +58,28 @@ async function loadHistory() {
return JSON.parse(data);
}
+// When the install is password protected (Settings → Security on :5555), this
+// sidecar honours the same gate. It listens on 0.0.0.0 for tailnet access and
+// can restart/stop PM2 processes and stream logs, so leaving it open while
+// :5555 asks for a password would make the password meaningless. On an install
+// with no password set, the gate is a no-op — the documented single-user
+// trust model is unchanged.
+// `/` serves the static shell, which renders its own login overlay driven by
+// GET /api/auth/status — it carries no data, so it stays publicly reachable.
+const auth = createSidecarAuthGate({
+ dataDir: DATA_DIR,
+ cookieName: 'portos_autofixer_auth',
+ publicPaths: ['/'],
+});
+
+// The gate is mounted BEFORE the auth routes so its cross-origin (CSRF) check
+// covers them too — `publicPaths` is what lets them through, not route order.
+app.use(express.json({ limit: '16kb' }));
+app.use(auth.gate);
+app.get('/api/auth/status', auth.handleStatus);
+app.post('/api/auth/login', auth.handleLogin);
+app.post('/api/auth/logout', auth.handleLogout);
+
// API: Get registered apps and their processes
app.get('/api/apps', async (req, res) => {
const apps = await loadApps();
@@ -245,8 +268,10 @@ app.get('/logs', async (req, res) => {
const { dir: CERT_DIR } = certPaths(DATA_DIR);
const { server, httpsEnabled } = createTailscaleServers(app, { certDir: CERT_DIR, httpMirror: false });
const scheme = httpsEnabled ? 'https' : 'http';
-server.listen(PORT, '0.0.0.0', () => {
+server.listen(PORT, '0.0.0.0', async () => {
console.log(`🚀 [Autofixer UI] Running on ${scheme}://localhost:${PORT}`);
+ const gated = await auth.isEnabled().catch(() => true);
+ console.log(`🔐 [Autofixer UI] Password gate ${gated ? 'ENABLED (PortOS password required)' : 'off (no PortOS password set)'}`);
});
if (httpsEnabled) watchCertReload(server, CERT_DIR);
diff --git a/autofixer/ui.template.html b/autofixer/ui.template.html
index f8ac4cb73c..2a2347ee15 100644
--- a/autofixer/ui.template.html
+++ b/autofixer/ui.template.html
@@ -417,6 +417,90 @@
.history-item { padding: 1rem; }
}
+ /* Login overlay — shown when the PortOS install is password protected
+ and this browser has no valid session. */
+ .login-overlay {
+ position: fixed;
+ inset: 0;
+ background: #0a0a0f;
+ display: none;
+ align-items: center;
+ justify-content: center;
+ padding: 1rem;
+ z-index: 100;
+ }
+
+ .login-overlay.visible { display: flex; }
+
+ .login-card {
+ background: #12121a;
+ border: 1px solid #2a2a4a;
+ border-radius: 0.75rem;
+ padding: 1.5rem;
+ width: 100%;
+ max-width: 360px;
+ }
+
+ .login-card h2 {
+ font-size: 1rem;
+ margin-bottom: 0.375rem;
+ }
+
+ .login-card p {
+ font-size: 0.8125rem;
+ color: #888;
+ margin-bottom: 1rem;
+ line-height: 1.5;
+ }
+
+ .login-card label {
+ display: block;
+ font-size: 0.75rem;
+ color: #888;
+ margin-bottom: 0.375rem;
+ }
+
+ .login-card input {
+ width: 100%;
+ padding: 0.625rem 0.75rem;
+ min-height: 44px;
+ background: #1a1a2a;
+ border: 1px solid #2a2a4a;
+ border-radius: 0.5rem;
+ color: #e0e0e0;
+ font-size: 1rem;
+ }
+
+ .login-card input:focus {
+ outline: none;
+ border-color: #6366f1;
+ }
+
+ .login-card button {
+ width: 100%;
+ margin-top: 0.75rem;
+ padding: 0.625rem 1rem;
+ min-height: 44px;
+ background: #6366f1;
+ border: none;
+ border-radius: 0.5rem;
+ color: #fff;
+ font-size: 0.9375rem;
+ cursor: pointer;
+ }
+
+ .login-card button:disabled { opacity: 0.6; cursor: default; }
+
+ .login-error {
+ margin-top: 0.75rem;
+ font-size: 0.8125rem;
+ color: #f87171;
+ min-height: 1.2em;
+ }
+
+ #logoutLink { display: none; }
+ #logoutLink.visible { display: flex; }
+
/* Desktop (1024px+) */
@media (min-width: 1024px) {
.sidebar { width: 300px; }
@@ -432,6 +516,7 @@
<a href="#" id="portosDashboardLink" target="_blank">PortOS Dashboard</a>
<a href="#" class="active" id="logsTab">Logs</a>
<a href="#" id="historyTab">History</a>
+ <a href="#" id="logoutLink">Log out</a>
</div>
</header>
@@ -474,7 +559,25 @@
<div id="toast" class="toast"></div>
+ <div class="login-overlay" id="loginOverlay">
+ <form class="login-card" id="loginForm">
+ <h2>🔒 PortOS Autofixer</h2>
+ <p>This install is password protected. Enter your PortOS password — or sign in to the PortOS dashboard on this host and reload.</p>
+ <label for="loginPassword">Password</label>
+ <input type="password" id="loginPassword" name="password" autocomplete="current-password" autofocus>
+ <button type="submit" id="loginSubmit">Unlock</button>
+ <div class="login-error" id="loginError"></div>
+ </form>
+ </div>
+
<script>
+ const loginOverlay = document.getElementById('loginOverlay');
+ const loginForm = document.getElementById('loginForm');
+ const loginPassword = document.getElementById('loginPassword');
+ const loginSubmit = document.getElementById('loginSubmit');
+ const loginError = document.getElementById('loginError');
+ const logoutLink = document.getElementById('logoutLink');
+
const processList = document.getElementById('processList');
const logsContainer = document.getElementById('logs');
const historyPanel = document.getElementById('historyPanel');
@@ -502,9 +605,83 @@
['errored', 'status-errored']
]);
+ // Auth — the sidecar mirrors the main PortOS password gate. When no
+ // password is set, /api/auth/status reports enabled:false and nothing
+ // below ever shows. A `portos_auth` cookie from the dashboard on this host
+ // already counts (cookies ignore port), so the overlay is only for
+ // browsers that haven't signed in there.
+ let authRequired = false;
+
+ function showLogin(message) {
+ authRequired = true;
+ loginError.textContent = message || '';
+ loginOverlay.classList.add('visible');
+ logoutLink.classList.remove('visible');
+ if (eventSource) { eventSource.close(); eventSource = null; }
+ loginPassword.focus();
+ }
+
+ function hideLogin() {
+ loginOverlay.classList.remove('visible');
+ loginPassword.value = '';
+ loginError.textContent = '';
+ logoutLink.classList.toggle('visible', authRequired);
+ }
+
+ // Every API call routes through here so a 401 (session expired, password
+ // rotated on :5555) re-arms the overlay instead of silently failing.
+ async function apiFetch(url, options) {
+ const res = await fetch(url, options);
+ if (res.status === 401) {
+ showLogin('Session expired — sign in again.');
+ return null;
+ }
+ return res;
+ }
+
+ async function checkAuth() {
+ const res = await fetch('/api/auth/status').catch(() => null);
+ if (!res || !res.ok) return true; // treat an unreachable gate as open; API calls still 401
+ const status = await res.json();
+ authRequired = !!status.enabled;
+ if (status.enabled && !status.authenticated) {
+ showLogin('');
+ return false;
+ }
+ hideLogin();
+ return true;
+ }
+
+ loginForm.addEventListener('submit', async (e) => {
+ e.preventDefault();
+ loginSubmit.disabled = true;
+ loginSubmit.textContent = 'Unlocking…';
+ const res = await fetch('/api/auth/login', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ password: loginPassword.value })
+ }).catch(() => null);
+ loginSubmit.disabled = false;
+ loginSubmit.textContent = 'Unlock';
+ if (!res || !res.ok) {
+ const data = res ? await res.json().catch(() => ({})) : {};
+ loginError.textContent = data.error || 'Login failed';
+ return;
+ }
+ hideLogin();
+ await start();
+ });
+
+ logoutLink.addEventListener('click', async (e) => {
+ e.preventDefault();
+ await fetch('/api/auth/logout', { method: 'POST' }).catch(() => null);
+ showLogin('Signed out.');
+ });
+
// Fetch PM2 status
async function fetchStatus() {
- const res = await fetch('/api/status');
+ const res = await apiFetch('/api/status');
+ if (!res) return;
const statuses = await res.json();
processStatuses = new Map();
statuses.forEach(s => { processStatuses.set(String(s.name ?? ''), s.status); });
@@ -513,7 +690,8 @@
// Fetch apps and build process list
async function fetchApps() {
- const res = await fetch('/api/apps');
+ const res = await apiFetch('/api/apps');
+ if (!res) return;
const apps = await res.json();
const processes = [];
@@ -581,10 +759,11 @@
if (!selectedProcess) return;
restartBtn.disabled = true;
restartBtn.textContent = 'Restarting…';
- const res = await fetch('/api/restart/' + encodeURIComponent(selectedProcess), { method: 'POST' });
- const data = await res.json();
+ const res = await apiFetch('/api/restart/' + encodeURIComponent(selectedProcess), { method: 'POST' });
restartBtn.textContent = 'Restart';
restartBtn.disabled = false;
+ if (!res) return;
+ const data = await res.json();
if (data.success) {
showToast('Restarted ' + selectedProcess, 'success');
fetchStatus();
@@ -597,10 +776,11 @@
if (!selectedProcess) return;
stopBtn.disabled = true;
stopBtn.textContent = 'Stopping…';
- const res = await fetch('/api/stop/' + encodeURIComponent(selectedProcess), { method: 'POST' });
- const data = await res.json();
+ const res = await apiFetch('/api/stop/' + encodeURIComponent(selectedProcess), { method: 'POST' });
stopBtn.textContent = 'Stop';
stopBtn.disabled = false;
+ if (!res) return;
+ const data = await res.json();
if (data.success) {
showToast('Stopped ' + selectedProcess, 'success');
fetchStatus();
@@ -647,16 +827,21 @@
}
};
- eventSource.onerror = () => {
+ eventSource.onerror = async () => {
statusText.textContent = 'Disconnected';
statusDot.className = 'status-dot disconnected';
eventSource.close();
+ // EventSource surfaces a 401 as a generic error with no status, so
+ // re-check the gate before retrying — otherwise an expired session
+ // reconnects in a loop with no explanation.
+ if (!(await checkAuth())) return;
setTimeout(connect, 3000);
};
}
async function fetchHistory() {
- const res = await fetch('/api/history');
+ const res = await apiFetch('/api/history');
+ if (!res) return;
const history = await res.json();
historyPanel.replaceChildren();
@@ -736,8 +921,13 @@
window.location.protocol + '//' + window.location.hostname + ':5554';
// Initial load
- fetchApps();
- setInterval(fetchStatus, 10000);
+ async function start() {
+ if (!(await checkAuth())) return;
+ await fetchApps();
+ }
+
+ start();
+ setInterval(() => { if (!loginOverlay.classList.contains('visible')) fetchStatus(); }, 10000);
</script>
</body>
</html>
diff --git a/lib/portosAuthCore.js b/lib/portosAuthCore.js
new file mode 100644
index 0000000000..175b170bd3
--- /dev/null
+++ b/lib/portosAuthCore.js
@@ -0,0 +1,179 @@
+/**
+ * portosAuthCore — zero-dependency primitives shared by the main PortOS server
+ * (`server/services/auth.js`, `server/lib/authGate.js`) and by sidecar
+ * processes that must honour the same password gate (`autofixer/ui.js` via
+ * `lib/sidecarAuthGate.js`).
+ *
+ * Sidecars run as separate PM2 processes with their own `package.json`, so they
+ * cannot import the server's service layer (settings.js, zod, the error
+ * middleware…). Everything here is Node builtins only, no side effects at
+ * import time — same contract as `lib/tailscale-https.js`.
+ *
+ * The constants below are the WIRE/AT-REST format of the auth system. Changing
+ * SCRYPT_PARAMS, COOKIE_NAME, or the token hashing invalidates stored
+ * credentials/sessions across every install, so treat them as a migration.
+ */
+import { createHash, timingSafeEqual, scrypt } from 'node:crypto';
+import { promisify } from 'node:util';
+
+const scryptAsync = promisify(scrypt);
+
+export const COOKIE_NAME = 'portos_auth';
+export const SALT_BYTES = 16;
+export const HASH_BYTES = 64;
+export const TOKEN_BYTES = 32;
+export const SESSION_TTL_MS = 30 * 24 * 60 * 60 * 1000; // 30 days
+
+// scrypt cost parameters per OWASP 2023 password-storage guidance for
+// interactive logins. Node's default `maxmem` of 32 MiB rejects this N;
+// OpenSSL needs headroom over the canonical 128·N·r working set (~128 MiB
+// here), so 256 MiB is allocated.
+export const SCRYPT_PARAMS = { N: 131072, r: 8, p: 1, maxmem: 256 * 1024 * 1024 };
+
+export const hashPassword = async (password, salt) => {
+ const buf = await scryptAsync(password, salt, HASH_BYTES, SCRYPT_PARAMS);
+ return buf.toString('hex');
+};
+
+export 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);
+};
+
+export const hashToken = (token) => createHash('sha256').update(token).digest('hex');
+
+// Verify a plaintext password against a stored `secrets.auth` record
+// ({ enabled, passwordHash, salt }). Returns false for any incomplete record
+// so callers never have to re-derive the "is this configured" checks.
+export const verifyPasswordAgainst = async (auth, password) => {
+ if (!auth?.enabled || !auth.passwordHash || !auth.salt) return false;
+ if (typeof password !== 'string' || password.length === 0) return false;
+ return constantEqual(await hashPassword(password, auth.salt), auth.passwordHash);
+};
+
+// Parse a single cookie out of a `Cookie` header. Express doesn't ship a
+// cookie parser and we only need one name — a manual parse keeps the sidecar
+// dependency-free.
+export const parseCookie = (cookieHeader, name) => {
+ if (typeof cookieHeader !== 'string') return null;
+ for (const part of cookieHeader.split(';')) {
+ const eq = part.indexOf('=');
+ if (eq === -1) continue;
+ if (part.slice(0, eq).trim() !== name) continue;
+ const raw = part.slice(eq + 1).trim();
+ // decodeURIComponent throws on malformed %XX sequences. An attacker
+ // sending `portos_auth=%E0` would otherwise turn every gated request into
+ // a 500 instead of a clean 401. Treat a malformed cookie as "no token".
+ try { return decodeURIComponent(raw); }
+ catch { return null; }
+ }
+ return null;
+};
+
+export const parseCookieToken = (cookieHeader) => parseCookie(cookieHeader, COOKIE_NAME);
+
+// Pull the session 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, so no uppercase fallback is needed.
+export const extractToken = (req) => {
+ const cookie = parseCookieToken(req.headers?.cookie);
+ if (cookie) return cookie;
+ const authHeader = req.headers?.authorization;
+ // RFC 6750: the Bearer scheme name is case-insensitive.
+ if (typeof authHeader === 'string' && authHeader.length > 7
+ && authHeader.slice(0, 7).toLowerCase() === 'bearer ') {
+ return authHeader.slice(7).trim();
+ }
+ return null;
+};
+
+// Extract the password from an `Authorization: Basic <base64>` header. PortOS
+// is single-user so the username is ignored; only the password is validated.
+// Used by peer-to-peer federation probes and by scripts hitting a sidecar.
+export const extractBasicPassword = (req) => {
+ const authHeader = req.headers?.authorization;
+ if (typeof authHeader !== 'string') return null;
+ if (authHeader.slice(0, 6).toLowerCase() !== 'basic ') return null;
+ const decoded = Buffer.from(authHeader.slice(6), 'base64').toString('utf8');
+ const colonIdx = decoded.indexOf(':');
+ return colonIdx === -1 ? decoded : decoded.slice(colonIdx + 1);
+};
+
+// Reject cross-origin requests when auth is on. PortOS reflects `Origin` with
+// `Access-Control-Allow-Credentials: true` so the UI works from any tailnet
+// hostname / IP — but combined with the session cookie that becomes a CSRF
+// surface: a malicious page on another tailnet host can fetch PortOS APIs with
+// `credentials: 'include'` after the user has logged in (Tailscale's `ts.net`
+// is on the Public Suffix List, so SameSite=Lax doesn't help — same-tailnet
+// hosts are same-site). Compare the `Origin` header's host:port against the
+// request's own `Host`; any mismatch is cross-origin. Requests with no
+// `Origin` (server-to-server, curl, the loopback mirror) pass through.
+// Hostnames are case-insensitive (RFC 3986 §3.2.2).
+const stripPort = (hostHeader) => {
+ // Bracketed IPv6 host: `[::1]:port` → `[::1]`.
+ if (hostHeader.startsWith('[')) {
+ const close = hostHeader.indexOf(']');
+ return close === -1 ? hostHeader : hostHeader.slice(0, close + 1);
+ }
+ const colon = hostHeader.indexOf(':');
+ return colon === -1 ? hostHeader : hostHeader.slice(0, colon);
+};
+
+const LOOPBACK_HOSTS = new Set(['localhost', '127.0.0.1', '[::1]']);
+const isLoopback = (hostname) => LOOPBACK_HOSTS.has(hostname.toLowerCase());
+
+export const isCrossOrigin = (req) => {
+ const origin = req.headers?.origin;
+ if (!origin || origin === 'null') return false;
+ const host = req.headers?.host;
+ if (!host) return false;
+ // URL parses scheme://authority — we only compare the authority. A malformed
+ // Origin (URL constructor throws) is treated as cross-origin.
+ let parsed;
+ try { parsed = new URL(origin); }
+ catch { return true; }
+ if (parsed.host.toLowerCase() === host.toLowerCase()) return false;
+ // Dev/sidecar workflow exemption: Vite proxies :5554 → :5555 with
+ // changeOrigin, and the autofixer UI on :5560 is opened from the main UI —
+ // so a real same-machine browser request can arrive as
+ // `Origin: http://localhost:5554` / `Host: localhost:5555`. Treat any
+ // loopback-to-loopback pairing as same-origin regardless of port — the CSRF
+ // threat is from attackers on OTHER machines.
+ if (isLoopback(stripPort(parsed.host)) && isLoopback(stripPort(host))) return false;
+ return true;
+};
+
+// Sliding-window login throttle. Auth is normally tailnet-only so this is
+// defense in depth against a sidecar burning CPU on scrypt verifications.
+// In-memory only (a restart resets the counters — acceptable for a
+// defense-in-depth control on a single-user install).
+export const createLoginThrottle = ({ maxAttempts = 10, windowMs = 60 * 1000 } = {}) => {
+ const attempts = new Map();
+ const trim = (timestamps, cutoff) => {
+ let i = 0;
+ while (i < timestamps.length && timestamps[i] < cutoff) i++;
+ return i === 0 ? timestamps : timestamps.slice(i);
+ };
+ const recentFor = (ip) => {
+ const cutoff = Date.now() - windowMs;
+ const recent = trim(attempts.get(ip) || [], cutoff);
+ if (recent.length === 0) attempts.delete(ip);
+ else attempts.set(ip, recent);
+ return recent;
+ };
+ return {
+ isLimited: (ip) => (typeof ip === 'string' && ip.length > 0
+ ? recentFor(ip).length >= maxAttempts
+ : false),
+ recordFailure: (ip) => {
+ if (typeof ip !== 'string' || ip.length === 0) return;
+ const recent = recentFor(ip);
+ recent.push(Date.now());
+ attempts.set(ip, recent);
+ },
+ clear: (ip) => { if (typeof ip === 'string') attempts.delete(ip); },
+ };
+};
diff --git a/lib/sidecarAuthGate.js b/lib/sidecarAuthGate.js
new file mode 100644
index 0000000000..a2ddbdffd0
--- /dev/null
+++ b/lib/sidecarAuthGate.js
@@ -0,0 +1,225 @@
+/**
+ * sidecarAuthGate — the PortOS password gate for sidecar processes.
+ *
+ * PortOS's main server (`:5555`) can be put behind a single user-set password
+ * (`server/services/auth.js`). Sidecars like the Autofixer UI (`:5560`) listen
+ * on `0.0.0.0` for tailnet access and expose privileged endpoints (PM2
+ * restart/stop, live log streams) — so when the install is password protected,
+ * they MUST honour the same gate, otherwise the password on `:5555` is a
+ * front door with the side door left open.
+ *
+ * Sidecars are separate PM2 processes with their own `package.json`, so this
+ * module cannot import the server's service layer. It reads the same two files
+ * the server owns:
+ * - `data/settings.json` → `secrets.auth` = { enabled, passwordHash, salt }
+ * - `data/auth-sessions.json` → { tokens: [{ tokenHash, expiresAt }] }
+ * and is otherwise Node-builtins-only (see `lib/portosAuthCore.js`).
+ *
+ * Accepted credentials, in order:
+ * 1. The sidecar's own cookie, issued by POST <loginPath> (see below).
+ * 2. A `portos_auth` session cookie or `Authorization: Bearer <token>` minted
+ * by the main server. Cookies ignore port, so a browser already logged in
+ * to PortOS on the same host is authenticated here with no second login.
+ * 3. `Authorization: Basic <base64(:password)>` — for curl/scripts.
+ *
+ * The sidecar NEVER writes `auth-sessions.json`: the main server keeps that
+ * store in memory and rewrites it wholesale on every mutation, so a second
+ * writer would silently clobber sessions. Instead its own cookie is stateless —
+ * `<expiresAt>.<HMAC-SHA256(passwordHash+salt, expiresAt)>`. That keys the
+ * signature to the stored password, so rotating or clearing the password
+ * invalidates every outstanding sidecar cookie for free.
+ */
+import { createHmac, timingSafeEqual } from 'node:crypto';
+import { readFile } from 'node:fs/promises';
+import { join } from 'node:path';
+import {
+ createLoginThrottle,
+ extractBasicPassword,
+ extractToken,
+ hashToken,
+ isCrossOrigin,
+ parseCookie,
+ verifyPasswordAgainst,
+} from './portosAuthCore.js';
+
+const SIDECAR_TTL_MS = 12 * 60 * 60 * 1000; // 12 hours
+// settings.json / auth-sessions.json are re-read on a short TTL rather than
+// cached for the process lifetime, so enabling auth (or rotating the password)
+// on :5555 takes effect on the sidecar within seconds and without a restart.
+const CONFIG_TTL_MS = 5_000;
+const SESSIONS_TTL_MS = 2_000;
+
+const readJson = async (file) => {
+ // Distinguish "file absent" (fresh install, auth was never configured) from
+ // "file present but unreadable/corrupt" (fail closed) — collapsing the two
+ // would silently disable the gate on a mid-write read.
+ const raw = await readFile(file, 'utf8').catch((err) => {
+ if (err?.code === 'ENOENT') return null;
+ throw err;
+ });
+ if (raw === null) return { missing: true, value: null };
+ return { missing: false, value: JSON.parse(raw) };
+};
+
+const cached = (ttlMs, load) => {
+ let value = null;
+ let expiresAt = 0;
+ return async () => {
+ if (value !== null && expiresAt > Date.now()) return value;
+ value = await load();
+ expiresAt = Date.now() + ttlMs;
+ return value;
+ };
+};
+
+export const createSidecarAuthGate = ({
+ dataDir,
+ cookieName,
+ loginPath = '/api/auth/login',
+ logoutPath = '/api/auth/logout',
+ statusPath = '/api/auth/status',
+ publicPaths = [],
+} = {}) => {
+ if (!dataDir) throw new Error('createSidecarAuthGate requires a dataDir');
+ if (!cookieName) throw new Error('createSidecarAuthGate requires a cookieName');
+
+ const SETTINGS_FILE = join(dataDir, 'settings.json');
+ const SESSIONS_FILE = join(dataDir, 'auth-sessions.json');
+ const alwaysPublic = new Set([loginPath, logoutPath, statusPath, ...publicPaths]);
+ const throttle = createLoginThrottle();
+
+ // { auth, corrupt }. `corrupt` means settings.json exists but couldn't be
+ // read/parsed — the gate then fails CLOSED (auth assumed on, and since no
+ // password hash is available nothing verifies) instead of fail-open.
+ const loadConfig = cached(CONFIG_TTL_MS, async () => {
+ const { missing, value } = await readJson(SETTINGS_FILE).catch(() => ({ missing: false, value: null }));
+ if (missing) return { auth: null, corrupt: false };
+ if (!value || typeof value !== 'object') return { auth: null, corrupt: true };
+ return { auth: value?.secrets?.auth ?? null, corrupt: false };
+ });
+
+ const loadSessions = cached(SESSIONS_TTL_MS, async () => {
+ const { value } = await readJson(SESSIONS_FILE).catch(() => ({ value: null }));
+ const tokens = Array.isArray(value?.tokens) ? value.tokens : [];
+ const store = new Map();
+ for (const entry of tokens) {
+ if (typeof entry?.tokenHash !== 'string' || typeof entry.expiresAt !== 'number') continue;
+ store.set(entry.tokenHash, entry.expiresAt);
+ }
+ return store;
+ });
+
+ const isEnabled = async () => {
+ const { auth, corrupt } = await loadConfig();
+ if (corrupt) return true;
+ return !!(auth?.enabled && auth.passwordHash && auth.salt);
+ };
+
+ const signingKey = (auth) => `${auth.passwordHash}:${auth.salt}`;
+
+ const macFor = (auth, expiresAt) =>
+ createHmac('sha256', signingKey(auth)).update(String(expiresAt)).digest('hex');
+
+ const signSidecarCookie = (auth, expiresAt) => `${expiresAt}.${macFor(auth, expiresAt)}`;
+
+ const verifySidecarCookie = (auth, value) => {
+ if (typeof value !== 'string') return false;
+ const dot = value.indexOf('.');
+ if (dot === -1) return false;
+ const expiresAt = Number(value.slice(0, dot));
+ if (!Number.isFinite(expiresAt) || expiresAt <= Date.now()) return false;
+ const presented = Buffer.from(value.slice(dot + 1), 'hex');
+ const expected = Buffer.from(macFor(auth, expiresAt), 'hex');
+ if (presented.length !== expected.length || presented.length === 0) return false;
+ return timingSafeEqual(presented, expected);
+ };
+
+ const verifyServerSession = async (token) => {
+ if (typeof token !== 'string' || token.length === 0) return false;
+ const sessions = await loadSessions();
+ const expiresAt = sessions.get(hashToken(token));
+ return typeof expiresAt === 'number' && expiresAt > Date.now();
+ };
+
+ const isAuthenticated = async (req) => {
+ const { auth, corrupt } = await loadConfig();
+ // Corrupt settings → no usable password hash → nothing can authenticate.
+ if (corrupt || !auth?.passwordHash || !auth.salt) return false;
+ if (verifySidecarCookie(auth, parseCookie(req.headers?.cookie, cookieName))) return true;
+ if (await verifyServerSession(extractToken(req))) return true;
+ const basic = extractBasicPassword(req);
+ if (basic && await verifyPasswordAgainst(auth, basic)) return true;
+ return false;
+ };
+
+ const isSecureRequest = (req) => req.secure === true
+ || (req.headers?.['x-forwarded-proto'] || '').split(',')[0].trim() === 'https';
+
+ const buildCookie = (value, { secure, maxAgeSeconds }) => {
+ const parts = [
+ `${cookieName}=${encodeURIComponent(value)}`,
+ 'Path=/',
+ 'HttpOnly',
+ 'SameSite=Lax',
+ `Max-Age=${maxAgeSeconds}`,
+ ];
+ if (secure) parts.push('Secure');
+ return parts.join('; ');
+ };
+
+ // Express middleware. No-ops entirely when the install has no password —
+ // that's the documented PortOS trust model (single user on a private
+ // tailnet), so an unprotected install keeps working exactly as before.
+ const gate = async (req, res, next) => {
+ if (!(await isEnabled())) return next();
+ // The CSRF guard runs FIRST: the logout endpoint is public but still
+ // mutates state, so a same-tailnet attacker could otherwise force actions
+ // cross-origin through the public-path bypass.
+ if (isCrossOrigin(req)) {
+ return res.status(403).json({ error: 'Cross-origin request rejected', code: 'CROSS_ORIGIN_BLOCKED' });
+ }
+ if (alwaysPublic.has(req.path)) return next();
+ if (await isAuthenticated(req)) return next();
+ return res.status(401).json({ error: 'Authentication required', code: 'AUTH_REQUIRED' });
+ };
+
+ // GET <statusPath> → does this sidecar need a password, and does the caller
+ // already have one? The UI polls this to decide whether to show its login
+ // overlay, so it must stay reachable unauthenticated.
+ const handleStatus = async (req, res) => {
+ const enabled = await isEnabled();
+ res.json({ enabled, authenticated: enabled ? await isAuthenticated(req) : true });
+ };
+
+ // POST <loginPath> { password } → sets the sidecar cookie.
+ const handleLogin = async (req, res) => {
+ if (!(await isEnabled())) return res.json({ success: true, enabled: false });
+ const ip = req.ip || req.socket?.remoteAddress || '';
+ if (throttle.isLimited(ip)) {
+ return res.status(429).json({ error: 'Too many attempts, try again shortly', code: 'AUTH_RATE_LIMITED' });
+ }
+ const { auth } = await loadConfig();
+ const password = req.body?.password;
+ if (!(await verifyPasswordAgainst(auth, password))) {
+ throttle.recordFailure(ip);
+ return res.status(401).json({ error: 'Incorrect password', code: 'AUTH_BAD_PASSWORD' });
+ }
+ throttle.clear(ip);
+ const expiresAt = Date.now() + SIDECAR_TTL_MS;
+ res.setHeader('Set-Cookie', buildCookie(signSidecarCookie(auth, expiresAt), {
+ secure: isSecureRequest(req),
+ maxAgeSeconds: Math.floor(SIDECAR_TTL_MS / 1000),
+ }));
+ res.json({ success: true, expiresAt });
+ };
+
+ // POST <logoutPath> → clears the sidecar cookie. A `portos_auth` session
+ // cookie from the main server is NOT touched — that one is the main UI's to
+ // manage, and revoking it here would log the user out of PortOS itself.
+ const handleLogout = (req, res) => {
+ res.setHeader('Set-Cookie', buildCookie('', { secure: isSecureRequest(req), maxAgeSeconds: 0 }));
+ res.json({ success: true });
+ };
+
+ return { gate, handleStatus, handleLogin, handleLogout, isEnabled, isAuthenticated };
+};
diff --git a/lib/sidecarAuthGate.test.js b/lib/sidecarAuthGate.test.js
new file mode 100644
index 0000000000..3a5f4298ad
--- /dev/null
+++ b/lib/sidecarAuthGate.test.js
@@ -0,0 +1,220 @@
+import { describe, it, expect, afterEach, beforeAll, beforeEach } from 'vitest';
+import { mkdtemp, writeFile, rm } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { createSidecarAuthGate } from './sidecarAuthGate.js';
+import { hashPassword, hashToken } from './portosAuthCore.js';
+
+const PASSWORD = 'correct horse battery';
+const SALT = 'a1b2c3d4e5f60718293a4b5c6d7e8f90';
+
+// scrypt at PortOS's cost parameters takes ~1s, so hash once for the suite.
+let PASSWORD_HASH;
+beforeAll(async () => { PASSWORD_HASH = await hashPassword(PASSWORD, SALT); }, 30_000);
+
+const COOKIE = 'portos_sidecar_test';
+
+let dataDir;
+beforeEach(async () => {
+ dataDir = await mkdtemp(join(tmpdir(), 'sidecar-auth-'));
+});
+
+const writeSettings = (settings) =>
+ writeFile(join(dataDir, 'settings.json'), JSON.stringify(settings));
+
+const writeSessions = (tokens) =>
+ writeFile(join(dataDir, 'auth-sessions.json'), JSON.stringify({ tokens }));
+
+const authOn = () => writeSettings({
+ secrets: { auth: { enabled: true, kdf: 'scrypt', passwordHash: PASSWORD_HASH, salt: SALT } },
+});
+
+// Each test builds its own gate so the 5s config cache never leaks across
+// tests (a cached "auth off" would mask a later "auth on" write).
+const makeGate = () => createSidecarAuthGate({ dataDir, cookieName: COOKIE, publicPaths: ['/'] });
+
+const makeRes = () => {
+ const res = { statusCode: 200, body: null, headers: {} };
+ res.status = (code) => { res.statusCode = code; return res; };
+ res.json = (payload) => { res.body = payload; return res; };
+ res.setHeader = (k, v) => { res.headers[k.toLowerCase()] = v; };
+ return res;
+};
+
+const run = async (gate, req) => {
+ const res = makeRes();
+ let nexted = false;
+ await gate(req, res, () => { nexted = true; });
+ return { res, nexted };
+};
+
+const req = (path, headers = {}) => ({ path, headers, socket: { remoteAddress: '10.0.0.5' } });
+
+describe('createSidecarAuthGate', () => {
+ it('requires a dataDir and a cookieName', () => {
+ expect(() => createSidecarAuthGate({ cookieName: COOKIE })).toThrow(/dataDir/);
+ expect(() => createSidecarAuthGate({ dataDir: '/tmp' })).toThrow(/cookieName/);
+ });
+
+ describe('when the install has no password', () => {
+ it('passes every request through when settings.json is absent', async () => {
+ const { gate, isEnabled } = makeGate();
+ expect(await isEnabled()).toBe(false);
+ expect((await run(gate, req('/api/restart/portos-server'))).nexted).toBe(true);
+ });
+
+ it('passes through when secrets.auth exists but is disabled', async () => {
+ await writeSettings({ secrets: { auth: { enabled: false } } });
+ const { gate } = makeGate();
+ expect((await run(gate, req('/api/stop/portos-server'))).nexted).toBe(true);
+ });
+
+ it('reports enabled:false + authenticated:true from the status handler', async () => {
+ const { handleStatus } = makeGate();
+ const res = makeRes();
+ await handleStatus(req('/api/auth/status'), res);
+ expect(res.body).toEqual({ enabled: false, authenticated: true });
+ });
+ });
+
+ describe('when the install is password protected', () => {
+ beforeEach(authOn);
+
+ it('401s an unauthenticated mutation request', async () => {
+ const { gate } = makeGate();
+ const { res, nexted } = await run(gate, req('/api/restart/portos-server'));
+ expect(nexted).toBe(false);
+ expect(res.statusCode).toBe(401);
+ expect(res.body.code).toBe('AUTH_REQUIRED');
+ });
+
+ it('401s read endpoints and the log stream too', async () => {
+ const { gate } = makeGate();
+ for (const path of ['/api/apps', '/api/history', '/api/status', '/logs']) {
+ const { res, nexted } = await run(gate, req(path));
+ expect(nexted, path).toBe(false);
+ expect(res.statusCode, path).toBe(401);
+ }
+ });
+
+ it('leaves the static shell and the auth routes public', async () => {
+ const { gate } = makeGate();
+ for (const path of ['/', '/api/auth/status', '/api/auth/login', '/api/auth/logout']) {
+ expect((await run(gate, req(path))).nexted, path).toBe(true);
+ }
+ });
+
+ it('accepts a portos_auth session cookie minted by the main server', async () => {
+ await writeSessions([{ tokenHash: hashToken('tok-live'), expiresAt: Date.now() + 60_000 }]);
+ const { gate } = makeGate();
+ const ok = await run(gate, req('/api/apps', { cookie: 'portos_auth=tok-live' }));
+ expect(ok.nexted).toBe(true);
+ });
+
+ it('rejects an expired or unknown session token', async () => {
+ await writeSessions([{ tokenHash: hashToken('tok-old'), expiresAt: Date.now() - 1 }]);
+ const { gate } = makeGate();
+ expect((await run(gate, req('/api/apps', { cookie: 'portos_auth=tok-old' }))).nexted).toBe(false);
+ expect((await run(gate, req('/api/apps', { authorization: 'Bearer nope' }))).nexted).toBe(false);
+ });
+
+ it('accepts a Bearer session token', async () => {
+ await writeSessions([{ tokenHash: hashToken('tok-bearer'), expiresAt: Date.now() + 60_000 }]);
+ const { gate } = makeGate();
+ expect((await run(gate, req('/api/apps', { authorization: 'Bearer tok-bearer' }))).nexted).toBe(true);
+ });
+
+ it('issues a cookie on login that then authenticates requests', async () => {
+ const { gate, handleLogin } = makeGate();
+ const res = makeRes();
+ await handleLogin({ ...req('/api/auth/login'), body: { password: PASSWORD } }, res);
+ expect(res.body.success).toBe(true);
+ const setCookie = res.headers['set-cookie'];
+ expect(setCookie).toContain(`${COOKIE}=`);
+ expect(setCookie).toContain('HttpOnly');
+ expect(setCookie).toContain('SameSite=Lax');
+ const value = setCookie.split(';')[0];
+ expect((await run(gate, req('/api/apps', { cookie: value }))).nexted).toBe(true);
+ }, 30_000);
+
+ it('rejects a wrong password without issuing a cookie', async () => {
+ const { handleLogin } = makeGate();
+ const res = makeRes();
+ await handleLogin({ ...req('/api/auth/login'), body: { password: 'wrong' } }, res);
+ expect(res.statusCode).toBe(401);
+ expect(res.headers['set-cookie']).toBeUndefined();
+ }, 30_000);
+
+ it('rejects a tampered sidecar cookie', async () => {
+ const { gate, handleLogin } = makeGate();
+ const res = makeRes();
+ await handleLogin({ ...req('/api/auth/login'), body: { password: PASSWORD } }, res);
+ const [name, signed] = res.headers['set-cookie'].split(';')[0].split('=');
+ const [exp, mac] = decodeURIComponent(signed).split('.');
+ // Extend the expiry without re-signing — the HMAC covers it.
+ const forged = `${name}=${encodeURIComponent(`${Number(exp) + 1}.${mac}`)}`;
+ expect((await run(gate, req('/api/apps', { cookie: forged }))).nexted).toBe(false);
+ }, 30_000);
+
+ it('invalidates its cookie when the stored password changes', async () => {
+ const { handleLogin } = makeGate();
+ const res = makeRes();
+ await handleLogin({ ...req('/api/auth/login'), body: { password: PASSWORD } }, res);
+ const cookie = res.headers['set-cookie'].split(';')[0];
+ // Rotate the password (new salt ⇒ new signing key) and build a fresh gate.
+ await writeSettings({
+ secrets: { auth: { enabled: true, passwordHash: PASSWORD_HASH, salt: 'ffffffffffffffffffffffffffffffff' } },
+ });
+ const { gate } = makeGate();
+ expect((await run(gate, req('/api/apps', { cookie }))).nexted).toBe(false);
+ }, 30_000);
+
+ it('accepts HTTP Basic credentials for scripts', async () => {
+ const { gate } = makeGate();
+ const basic = Buffer.from(`:${PASSWORD}`).toString('base64');
+ expect((await run(gate, req('/api/apps', { authorization: `Basic ${basic}` }))).nexted).toBe(true);
+ }, 30_000);
+
+ it('rejects cross-origin requests before the public-path bypass', async () => {
+ const { gate } = makeGate();
+ const { res, nexted } = await run(gate, req('/api/auth/logout', {
+ origin: 'https://evil.example.ts.net',
+ host: 'portos.example.ts.net:5560',
+ }));
+ expect(nexted).toBe(false);
+ expect(res.statusCode).toBe(403);
+ expect(res.body.code).toBe('CROSS_ORIGIN_BLOCKED');
+ });
+
+ it('allows a same-origin browser request', async () => {
+ await writeSessions([{ tokenHash: hashToken('tok-same'), expiresAt: Date.now() + 60_000 }]);
+ const { gate } = makeGate();
+ const ok = await run(gate, req('/api/apps', {
+ origin: 'https://portos.example.ts.net:5560',
+ host: 'portos.example.ts.net:5560',
+ cookie: 'portos_auth=tok-same',
+ }));
+ expect(ok.nexted).toBe(true);
+ });
+
+ it('fails CLOSED when settings.json is present but unparseable', async () => {
+ await writeFile(join(dataDir, 'settings.json'), '{ this is not json');
+ const { gate, isEnabled } = makeGate();
+ expect(await isEnabled()).toBe(true);
+ const { res, nexted } = await run(gate, req('/api/restart/portos-server'));
+ expect(nexted).toBe(false);
+ expect(res.statusCode).toBe(401);
+ });
+
+ it('clears its cookie on logout without touching the portos_auth session', async () => {
+ const { handleLogout } = makeGate();
+ const res = makeRes();
+ handleLogout(req('/api/auth/logout'), res);
+ expect(res.headers['set-cookie']).toContain('Max-Age=0');
+ expect(res.headers['set-cookie']).not.toContain('portos_auth=');
+ });
+ });
+});
+
+// Temp dirs are per-test; clean them all at the end of the file run.
+afterEach(async () => { await rm(dataDir, { recursive: true, force: true }); });
diff --git a/server/lib/authGate.js b/server/lib/authGate.js
index 50b3d60cda..a7a9c94464 100644
--- a/server/lib/authGate.js
+++ b/server/lib/authGate.js
@@ -1,5 +1,8 @@
import { createHash } from 'node:crypto';
import { extractToken, isAuthEnabled, verifyPassword, verifySession } from '../services/auth.js';
+// Shared with sidecar processes (lib/sidecarAuthGate.js) so the Autofixer UI
+// on :5560 applies byte-identical credential extraction and CSRF rules.
+import { extractBasicPassword, isCrossOrigin } from '../../lib/portosAuthCore.js';
import { getSettings, settingsEvents } from '../services/settings.js';
import { isRegistryPublic } from './apiRegistry.js';
@@ -25,20 +28,6 @@ const PUBLIC_API_PATHS = new Set([
// future routes that live outside `/api`.
const GATED_NON_API_PREFIXES = ['/sdapi/'];
-// Extract the password from an `Authorization: Basic <base64>` header.
-// PortOS is single-user so the username is ignored; only the password is
-// validated. Used by peer-to-peer federation: a remote PortOS instance probes
-// us with HTTP Basic credentials (set in the Instances UI) rather than a
-// browser session cookie.
-const extractBasicPassword = (req) => {
- const authHeader = req.headers?.authorization;
- if (typeof authHeader !== 'string') return null;
- if (authHeader.slice(0, 6).toLowerCase() !== 'basic ') return null;
- const decoded = Buffer.from(authHeader.slice(6), 'base64').toString('utf8');
- const colonIdx = decoded.indexOf(':');
- return colonIdx === -1 ? decoded : decoded.slice(colonIdx + 1);
-};
-
// Short-lived cache for Basic-auth scrypt results so probe cycles (3 parallel
// HTTP requests every 30s) don't re-run scrypt each time. Keyed by sha256 of
// the password so the plaintext never lives in the Map. Flushed on any
@@ -70,53 +59,6 @@ const isPublicPath = (path) => {
return true;
};
-// Reject cross-origin requests when auth is on. PortOS's CORS middleware
-// reflects `Origin` with `Access-Control-Allow-Credentials: true` so the UI
-// works from any tailnet hostname / IP — but combined with the session
-// cookie that becomes a CSRF surface: a malicious page on another tailnet
-// host can fetch PortOS APIs with `credentials: 'include'` after the user
-// has logged in (Tailscale's `ts.net` is on the Public Suffix List, so
-// SameSite=Lax doesn't help — same-tailnet hosts are same-site). Match the
-// `Origin` header's host:port against the request's own `Host` header; any
-// mismatch is a cross-origin attempt and gets 403 before the session is
-// even consulted. Requests with no `Origin` header (server-to-server,
-// curl, the loopback mirror) pass through.
-// Hostnames are case-insensitive (RFC 3986 §3.2.2). Node's `URL` already
-// lowercases the parsed authority; lowercase the raw `Host` header too so a
-// client that sends mixed-case isn't 403'd as cross-origin.
-const stripPort = (hostHeader) => {
- // Bracketed IPv6 host: `[::1]:port` → `[::1]`.
- if (hostHeader.startsWith('[')) {
- const close = hostHeader.indexOf(']');
- return close === -1 ? hostHeader : hostHeader.slice(0, close + 1);
- }
- const colon = hostHeader.indexOf(':');
- return colon === -1 ? hostHeader : hostHeader.slice(0, colon);
-};
-const LOOPBACK_HOSTS = new Set(['localhost', '127.0.0.1', '[::1]']);
-const isLoopback = (hostname) => LOOPBACK_HOSTS.has(hostname.toLowerCase());
-
-const isCrossOrigin = (req) => {
- const origin = req.headers?.origin;
- if (!origin || origin === 'null') return false;
- const host = req.headers?.host;
- if (!host) return false;
- // URL parses scheme://authority — we only compare the authority. A
- // malformed Origin (URL constructor throws) is treated as cross-origin.
- let parsed;
- try { parsed = new URL(origin); }
- catch { return true; }
- if (parsed.host.toLowerCase() === host.toLowerCase()) return false;
- // Dev workflow exemption: Vite proxies :5554 → :5555 with changeOrigin,
- // so a real same-origin browser request arrives as
- // `Origin: http://localhost:5554` / `Host: localhost:5555`. Treat any
- // loopback-to-loopback pairing as same-origin regardless of port — the
- // CSRF threat is from attackers on OTHER machines, not from a local
- // dev server on the same loopback interface.
- if (isLoopback(stripPort(parsed.host)) && isLoopback(stripPort(host))) return false;
- return true;
-};
-
// 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.
diff --git a/server/services/auth.js b/server/services/auth.js
index 0b706ed72b..ec1b20e21f 100644
--- a/server/services/auth.js
+++ b/server/services/auth.js
@@ -1,8 +1,19 @@
import { join } from 'path';
import { EventEmitter } from 'events';
-import { createHash, randomBytes, scrypt, timingSafeEqual } from 'crypto';
-import { promisify } from 'util';
+import { randomBytes } from 'crypto';
import { atomicWrite, PATHS, safeJSONParse, tryReadFile } from '../lib/fileUtils.js';
+import {
+ COOKIE_NAME,
+ SESSION_TTL_MS,
+ SALT_BYTES,
+ TOKEN_BYTES,
+ constantEqual,
+ createLoginThrottle,
+ extractToken,
+ hashPassword,
+ hashToken,
+ parseCookieToken,
+} from '../../lib/portosAuthCore.js';
import { getSettings, readSettingsStrict, settingsEvents, updateSettings } from './settings.js';
import { ServerError } from '../lib/errorHandler.js';
@@ -12,8 +23,6 @@ import { ServerError } from '../lib/errorHandler.js';
// `secrets.auth` in settings.json so the existing GET /api/settings sanitizer
// (which strips `secrets`) keeps them off the wire.
-const scryptAsync = promisify(scrypt);
-
// Event bus so the Socket.IO layer can react to auth-state changes (first-time
// enable, password rotation, full disable) without coupling the auth service
// to `io`. Consumers should kick every currently-connected socket and let
@@ -22,29 +31,11 @@ const scryptAsync = promisify(scrypt);
export const authEvents = new EventEmitter();
authEvents.setMaxListeners(50);
+// The wire/at-rest constants (cookie name, scrypt cost, session TTL) and the
+// crypto primitives live in `lib/portosAuthCore.js` so sidecar processes that
+// must honour the same password gate — see `lib/sidecarAuthGate.js`, used by
+// the Autofixer UI on :5560 — cannot drift from them.
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';
-// Login throttle — auth is normally tailnet-only so this is defense in depth
-// against a sidecar burning server CPU on scrypt verifications. Per-IP
-// sliding window: at most LOGIN_MAX_ATTEMPTS failed POSTs in
-// LOGIN_WINDOW_MS, then 401s with no scrypt work until the window clears.
-const LOGIN_MAX_ATTEMPTS = 10;
-const LOGIN_WINDOW_MS = 60 * 1000;
-// scrypt cost parameters per OWASP 2023 password-storage guidance for
-// interactive logins. PortOS has no rate limiting and the password hash +
-// salt persist in `settings.json` (single-user trust model — local
-// filesystem access already exists), so the realistic threat is offline
-// cracking of an exfiltrated settings file. The higher N narrows the
-// GPU/ASIC margin without making a one-per-tab login feel slow.
-// Node's default `maxmem` of 32 MiB rejects this N. OpenSSL needs slightly
-// more headroom than the canonical 128·N·r working set (≈128 MiB for these
-// params), so allocate 256 MiB.
-const SCRYPT_PARAMS = { N: 131072, r: 8, p: 1, maxmem: 256 * 1024 * 1024 };
-
// Delay before kicking sockets on auth-state change. `setImmediate` fires in
// the same tick as the HTTP response flush — close enough that the
// disconnect frame can reach the browser before the new Set-Cookie header
@@ -69,8 +60,6 @@ let loadPromise = null;
const now = () => Date.now();
-const hashToken = (token) => createHash('sha256').update(token).digest('hex');
-
const readSessions = async () => {
const raw = await tryReadFile(SESSIONS_FILE);
const parsed = safeJSONParse(raw ?? '{}', {});
@@ -103,18 +92,6 @@ const ensureLoaded = async () => {
return loadPromise;
};
-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;
@@ -290,77 +267,18 @@ export const revokeAllSessions = async () => {
setTimeout(() => authEvents.emit('sessions:revoked-all'), KICK_DELAY_MS);
};
-// Sliding-window login-throttle map. Keys are client IPs; values are arrays
-// of recent failed-attempt timestamps. Trimmed lazily on each call so it
-// never grows unbounded. In-memory only (a sidecar restart resets the
-// counters — acceptable for a defense-in-depth control on a single-user
-// install, not the primary auth boundary).
-const loginAttempts = new Map();
+// Per-IP sliding-window login throttle — auth is normally tailnet-only, so
+// this is defense in depth against a sidecar burning server CPU on scrypt
+// verifications. Shared with sidecars so they throttle identically.
+const loginThrottle = createLoginThrottle();
-const trimLoginWindow = (timestamps, cutoff) => {
- let i = 0;
- while (i < timestamps.length && timestamps[i] < cutoff) i++;
- return i === 0 ? timestamps : timestamps.slice(i);
-};
-
-export const isLoginRateLimited = (ip) => {
- if (typeof ip !== 'string' || ip.length === 0) return false;
- const cutoff = now() - LOGIN_WINDOW_MS;
- const recent = trimLoginWindow(loginAttempts.get(ip) || [], cutoff);
- if (recent.length === 0) loginAttempts.delete(ip);
- else loginAttempts.set(ip, recent);
- return recent.length >= LOGIN_MAX_ATTEMPTS;
-};
+export const isLoginRateLimited = (ip) => loginThrottle.isLimited(ip);
+export const recordLoginFailure = (ip) => loginThrottle.recordFailure(ip);
+export const clearLoginFailures = (ip) => loginThrottle.clear(ip);
-export const recordLoginFailure = (ip) => {
- if (typeof ip !== 'string' || ip.length === 0) return;
- const cutoff = now() - LOGIN_WINDOW_MS;
- const recent = trimLoginWindow(loginAttempts.get(ip) || [], cutoff);
- recent.push(now());
- loginAttempts.set(ip, recent);
-};
-
-export const clearLoginFailures = (ip) => {
- if (typeof ip === 'string') loginAttempts.delete(ip);
-};
-
-// 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;
- const raw = part.slice(eq + 1).trim();
- // decodeURIComponent throws on malformed %XX sequences. An attacker
- // sending `portos_auth=%E0` would otherwise turn every gated request
- // into a 500 via the error middleware instead of a clean 401. Treat
- // a malformed cookie the same as "no token".
- try { return decodeURIComponent(raw); }
- catch { return null; }
- }
- 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;
- // RFC 6750: Bearer scheme name is case-insensitive.
- if (typeof authHeader === 'string' && authHeader.length > 7
- && authHeader.slice(0, 7).toLowerCase() === 'bearer ') {
- return authHeader.slice(7).trim();
- }
- return null;
-};
+// Cookie parsing + token extraction are shared with sidecars. Re-exported here
+// so existing importers of this module keep working unchanged.
+export { parseCookieToken, extractToken };
export const buildSessionCookie = (token, { secure = false } = {}) => {
// HttpOnly so XSS can't read it; SameSite=Lax so cross-origin GETs from the