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
address review (claude): close auth bypass, harden scrypt + sessions
Adam Eivy5b047d810c51
diff --git a/server/index.js b/server/index.jsindex 09b162fdc7..ca0c8a5e71 100644--- a/server/index.js+++ b/server/index.js@@ -382,9 +382,10 @@ 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.+// Auth gate runs before any /api/* or /sdapi/* route. When+// settings.secrets.auth.enabled is true the gate returns 401 for everything+// except the small public set in lib/authGate.js (auth status/whoami/login/+// logout + /api/system/health). No-op when auth is off.app.use(authGate);// API Routesdiff --git a/server/lib/authGate.js b/server/lib/authGate.jsindex 6a301a6e3c..46aa1fc157 100644--- a/server/lib/authGate.js+++ b/server/lib/authGate.js@@ -15,13 +15,25 @@ const PUBLIC_API_PATHS = new Set(['/api/system/health',]);+// Non-`/api` API surfaces that must also be gated. `/sdapi/v1/*` is the+// AUTOMATIC1111-compatible image-gen mount served by sdapiRoutes — it accepts+// generation requests and exposes the LoRA / model catalog, so a sidecar with+// network reach but no auth must NOT be able to hit it. Add to this list any+// future routes that live outside `/api`.+const GATED_NON_API_PREFIXES = ['/sdapi/'];+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/');+ // /api/* and /data/* are always gated. /sdapi/* (and any future non-/api+ // API surface listed above) is also gated. Everything else is the static+ // client bundle — index.html / hashed JS+CSS / fonts — which is safe to+ // serve without a session: a sidecar can't do anything with it without a+ // token to hit the JSON API, and the login page itself must be reachable.+ if (path.startsWith('/api/') || path.startsWith('/data/')) return false;+ for (const prefix of GATED_NON_API_PREFIXES) {+ if (path.startsWith(prefix)) return false;+ }+ return true;};// Express middleware. Bypasses everything when auth is off. When it's on,diff --git a/server/lib/authGate.test.js b/server/lib/authGate.test.jsindex 09b9641b8c..fdf96981ab 100644--- a/server/lib/authGate.test.js+++ b/server/lib/authGate.test.js@@ -101,6 +101,27 @@ describe('authGate middleware', () => {expect(result.res.statusCode).toBe(401);expect(result.res.body).toBe('Unauthorized');});++ it('gates the /sdapi/* AUTOMATIC1111-compatible surface', 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: '/sdapi/v1/sd-models', headers: {} });+ expect(result.called).toBe(false);+ expect(result.res.statusCode).toBe(401);+ expect(result.res.body).toEqual({ error: 'Authentication required', code: 'AUTH_REQUIRED' });+ });++ it('treats a malformed cookie value as no token (clean 401, not 500)', async () => {+ const auth = await import('../services/auth.js');+ await auth.setPassword({ newPassword: 'correct-horse' });+ const { authGate } = await import('./authGate.js');+ // %E0 is a partial percent-escape — decodeURIComponent throws URIError.+ const result = await runGate(authGate, { path: '/api/cos', headers: { cookie: 'portos_auth=%E0' } });+ expect(result.called).toBe(false);+ expect(result.res.statusCode).toBe(401);+ expect(result.res.body.code).toBe('AUTH_REQUIRED');+ });});describe('socketAuthGate middleware', () => {diff --git a/server/routes/settings.js b/server/routes/settings.jsindex aad726d5a9..5a1df554a0 100644--- a/server/routes/settings.js+++ b/server/routes/settings.js@@ -100,7 +100,14 @@ router.put('/', asyncHandler(async (req, res) => {if (req.body?.catalogUserTypes !== undefined) {validateRequest(catalogUserTypesSettingsSchema, req.body.catalogUserTypes);}- const merged = await updateSettings(req.body);+ // Strip `secrets` from the incoming PUT body so an authenticated session+ // (or stolen cookie) can't disable the auth gate or clobber other secrets+ // by sending `{ "secrets": { ... } }` directly to /api/settings — that+ // would bypass the current-password proof the /api/auth/password routes+ // require. Secrets are write-only through their dedicated routes+ // (/api/auth/password, /api/github/secrets, etc.).+ const { secrets: _ignoredSecrets, ...settingsPatch } = req.body || {};+ const merged = await updateSettings(settingsPatch);// The queue caches codex.parallelLimit in-process; sync it from the// merged value so a save takes effect without a restart and without// re-reading the file.diff --git a/server/routes/settings.secretsStrip.test.js b/server/routes/settings.secretsStrip.test.jsnew file mode 100644index 0000000000..5ee44a1be0--- /dev/null+++ b/server/routes/settings.secretsStrip.test.js@@ -0,0 +1,87 @@+import { afterAll, beforeEach, describe, expect, it, vi } from 'vitest';+import express from 'express';+import { writeFileSync, readFileSync } from 'fs';+import { join } from 'path';+import { mockPathsDataRoot } from '../lib/mockPathsDataRoot.js';+import { request } from '../lib/testHelper.js';++// Regression for the auth-disable-bypass: a `PUT /api/settings` body+// containing a `secrets` key must NEVER reach the persistence layer.+// Otherwise an authenticated session (or a stolen cookie) could disable+// the auth gate or clobber unrelated secrets without proving knowledge+// of the current password — bypassing the proof check enforced by+// /api/auth/password (POST + DELETE).++const { tempRoot, makeProxy, cleanup } = mockPathsDataRoot({ prefix: 'portos-settings-secrets-' });++vi.mock('../lib/fileUtils.js', async () => {+ const actual = await vi.importActual('../lib/fileUtils.js');+ return makeProxy(actual);+});++const seedSettings = (settings) => {+ writeFileSync(join(tempRoot, 'settings.json'), JSON.stringify(settings, null, 2) + '\n');+};++const readSettingsFile = () => {+ const raw = readFileSync(join(tempRoot, 'settings.json'), 'utf8');+ return JSON.parse(raw);+};++const buildApp = async () => {+ vi.resetModules();+ const { default: settingsRoutes } = await import('./settings.js');+ const app = express();+ app.use(express.json());+ app.use('/api/settings', settingsRoutes);+ return app;+};++beforeEach(() => {+ seedSettings({});+});++afterAll(() => {+ cleanup();+});++describe('PUT /api/settings — secrets-strip', () => {+ it('drops a `secrets` key from the incoming body', async () => {+ seedSettings({+ timezone: 'UTC',+ secrets: { auth: { enabled: true, passwordHash: 'preserved-hash', salt: 'preserved-salt' } },+ });+ const app = await buildApp();+ const res = await request(app)+ .put('/api/settings')+ .send({ timezone: 'America/Los_Angeles', secrets: { auth: { enabled: false } } });+ expect(res.status).toBe(200);+ // Server-side: the auth slice is unchanged.+ const persisted = readSettingsFile();+ expect(persisted.timezone).toBe('America/Los_Angeles');+ expect(persisted.secrets?.auth?.enabled).toBe(true);+ expect(persisted.secrets?.auth?.passwordHash).toBe('preserved-hash');+ expect(persisted.secrets?.auth?.salt).toBe('preserved-salt');+ // Client-side: response never echoes secrets back either.+ expect(res.body.secrets).toBeUndefined();+ });++ it('drops an empty `secrets: {}` (which would otherwise wipe nested secrets via shallow merge)', async () => {+ seedSettings({+ secrets: { auth: { enabled: true, passwordHash: 'h', salt: 's' }, telegram: { token: 't' } },+ });+ const app = await buildApp();+ const res = await request(app).put('/api/settings').send({ timezone: 'UTC', secrets: {} });+ expect(res.status).toBe(200);+ const persisted = readSettingsFile();+ expect(persisted.secrets?.auth?.enabled).toBe(true);+ expect(persisted.secrets?.telegram?.token).toBe('t');+ });++ it('continues to write other top-level keys normally', async () => {+ const app = await buildApp();+ const res = await request(app).put('/api/settings').send({ timezone: 'Europe/Berlin' });+ expect(res.status).toBe(200);+ expect(readSettingsFile().timezone).toBe('Europe/Berlin');+ });+});diff --git a/server/services/auth.js b/server/services/auth.jsindex d13d7db020..90d57cdfde 100644--- a/server/services/auth.js+++ b/server/services/auth.js@@ -1,5 +1,5 @@import { join } from 'path';-import { randomBytes, scrypt, timingSafeEqual } from 'crypto';+import { createHash, randomBytes, scrypt, timingSafeEqual } from 'crypto';import { promisify } from 'util';import { atomicWrite, PATHS, safeJSONParse, tryReadFile } from '../lib/fileUtils.js';import { getSettings, updateSettings } from './settings.js';@@ -19,33 +19,52 @@ const SALT_BYTES = 16;const HASH_BYTES = 64;const SESSION_TTL_MS = 30 * 24 * 60 * 60 * 1000; // 30 daysconst COOKIE_NAME = 'portos_auth';-const SCRYPT_PARAMS = { N: 16384, r: 8, p: 1 };+// 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 };-// 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.+// In-memory session store. Keyed by `sha256(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. The plaintext token only ever lives+// in the response cookie — not in memory and not at rest — so an exfiltrated+// `auth-sessions.json` (e.g. from a backup or peer-sync mirror) doesn't yield+// usable credentials.const sessions = new Map();let loaded = false;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 ?? '{}', {});if (!Array.isArray(parsed.tokens)) return;const cutoff = now();for (const entry of parsed.tokens) {- if (!entry?.token || typeof entry.expiresAt !== 'number') continue;+ // Records carry `tokenHash` (sha256 hex) — accept the legacy `token` key+ // too so a pre-hash install upgrading on the spot doesn't sign every+ // session out at boot (the in-memory + at-rest representation rewrites+ // on the next mutation).+ const stored = entry?.tokenHash ?? entry?.token;+ if (typeof stored !== 'string' || typeof entry.expiresAt !== 'number') continue;if (entry.expiresAt <= cutoff) continue;- sessions.set(entry.token, { expiresAt: entry.expiresAt });+ sessions.set(stored, { expiresAt: entry.expiresAt });}};const writeSessions = async () => {const tokens = [];- for (const [token, { expiresAt }] of sessions) {- tokens.push({ token, expiresAt });+ for (const [tokenHash, { expiresAt }] of sessions) {+ tokens.push({ tokenHash, expiresAt });}await atomicWrite(SESSIONS_FILE, JSON.stringify({ tokens }, null, 2) + '\n');};@@ -155,7 +174,7 @@ export const createSession = async () => {await ensureLoaded();const token = randomBytes(TOKEN_BYTES).toString('hex');const expiresAt = now() + SESSION_TTL_MS;- sessions.set(token, { expiresAt });+ sessions.set(hashToken(token), { expiresAt });await writeSessions();return { token, expiresAt, maxAgeMs: SESSION_TTL_MS };};@@ -163,10 +182,11 @@ export const createSession = async () => {export const verifySession = async (token) => {if (typeof token !== 'string' || token.length === 0) return false;await ensureLoaded();- const entry = sessions.get(token);+ const key = hashToken(token);+ const entry = sessions.get(key);if (!entry) return false;if (entry.expiresAt <= now()) {- sessions.delete(token);+ sessions.delete(key);await writeSessions().catch(() => null);return false;}@@ -175,7 +195,7 @@ export const verifySession = async (token) => {export const revokeSession = async (token) => {await ensureLoaded();- if (sessions.delete(token)) {+ if (sessions.delete(hashToken(token))) {await writeSessions();}};@@ -197,7 +217,13 @@ export const parseCookieToken = (cookieHeader) => {if (eq === -1) continue;const name = part.slice(0, eq).trim();if (name !== COOKIE_NAME) continue;- return decodeURIComponent(part.slice(eq + 1).trim());+ 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;};diff --git a/server/services/auth.test.js b/server/services/auth.test.jsindex fd15fbc412..0865177cf7 100644--- a/server/services/auth.test.js+++ b/server/services/auth.test.js@@ -144,4 +144,15 @@ describe('auth service', () => {const fresh = await import('./auth.js');expect(await fresh.verifySession(token)).toBe(true);});++ it('stores sessions hashed at rest (plaintext token never lands in the file)', async () => {+ const { readFileSync } = await import('fs');+ const { join } = await import('path');+ const auth = await import('./auth.js');+ await auth.setPassword({ newPassword: 'correct-horse' });+ const { token } = await auth.createSession();+ const raw = readFileSync(join(tempRoot, 'auth-sessions.json'), 'utf8');+ expect(raw).not.toContain(token);+ expect(raw).toContain('tokenHash');+ });});