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
fix: accept HTTP Basic auth from federated peers on password-protected installs
[._.]/ Adam Eivy1123cfd60f3e
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 3fdbd13285..7cd8712137 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -31,6 +31,7 @@- **[issue-934] City archive district no longer overlaps the AI Core on sparse installs** — On installs with few or no active apps, the archived-apps "warehouse" district (and its ARCHIVE DISTRICT sign) sat right on top of the central AI Core landmark — most visibly on an all-archived install with no active apps, where the sign landed on the monument. The district is now floored to always sit clear of the core. Installs with several active apps are unaffected — their layout is unchanged.- **[issue-894] Numeric edge-case hardening** — Task-learning duration stats can no longer go negative when resetting a task type against an older or hand-edited store, goal velocity reports no trend (instead of a garbage value) when a progress entry has a malformed date, and a stray non-numeric music gain falls back to the default instead of breaking an audio render.+- **Federated peers with PortOS password auth now connect** — If a remote PortOS instance has its built-in password enabled (Settings → Security), peer probes were always returning 401 even with the correct credential set in the Instances UI. The root cause: PortOS's auth gate only accepted session cookies and `Authorization: Bearer` tokens; peer probes send `Authorization: Basic <base64>`, which was silently ignored. The auth gate now also validates HTTP Basic credentials against the stored password hash, so federated probes, syncs, and the live socket relay all authenticate correctly. The backoff-reset fix is bundled: if a peer was deep in exponential backoff (up to 24 h) from prior 401 failures, re-saving the credential in the Instances UI immediately clears the backoff and re-probes without waiting.- **Autofixer dashboard now loads over Tailscale HTTPS** — On installs with a Tailscale TLS cert, the main app is served over HTTPS, so the sidebar's "Autofixer" link points at `https://<host>:5560`. The standalone Autofixer UI server was hard-coded to plain HTTP, so that HTTPS request hit an HTTP-only listener and failed to connect (e.g. `https://void.taile8179.ts.net:5560/` wouldn't load). The Autofixer UI now serves HTTPS with the same shared `data/certs/` cert when one is present (and hot-reloads it on renewal), falling back to plain HTTP when no cert exists — so its scheme always matches the link the sidebar generates.- **City daytime sky no longer washes out to white; night reads as a galaxy backdrop** — The bright-day sky and pavement were tuned so light, so the dome and ground turned into a near-white fog sheet over the city; daytime now keeps real blue in the horizon bands and a muted blue-gray street so the city stays legible in full sun. At night the galaxy map is the backdrop, the shader sky-dome gets out of the way, and the moon is a smaller, softer disc instead of an over-bright bloom. The experimental "Dreamworld" sky-theme picker (and its drifting clouds) has been removed — the City now has one canonical look that follows your theme's day/night mode; any previously-saved Dreamworld setting falls back to it automatically.- **City night sky is a real environment map (the galaxy now also lights the scene)** — The night galaxy was a pair of hand-placed meshes that frequently didn't show and contributed no light. It's now wired through three.js's environment system the way an HDRI is: the equirectangular panorama is assigned to `scene.background` (a true 360° spheremap, visible in every camera direction) and, via `PMREMGenerator`, to `scene.environment` — so the galaxy also tints reflections and lighting on the metallic building/ground materials. The low-resolution (1774×887) AI-generated panorama that read as pixelated was replaced with a crisp 8192×4096 Milky Way (Solar System Scope, CC BY 4.0), brightness/saturation graded for the stylized night. Day is unchanged.diff --git a/server/lib/authGate.js b/server/lib/authGate.jsindex d3311e388a..9177788850 100644--- a/server/lib/authGate.js+++ b/server/lib/authGate.js@@ -1,4 +1,6 @@-import { extractToken, isAuthEnabled, verifySession } from '../services/auth.js';+import { createHash } from 'node:crypto';+import { extractToken, isAuthEnabled, verifyPassword, verifySession } from '../services/auth.js';+import { settingsEvents } from '../services/settings.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@@ -22,6 +24,37 @@ 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+// settings write (covers password rotation).+const basicAuthCache = new Map();+const BASIC_AUTH_CACHE_TTL_MS = 60_000;+settingsEvents.on('settings:updated', () => basicAuthCache.clear());++const verifyBasicPassword = async (password) => {+ const key = createHash('sha256').update(password).digest('hex');+ const cached = basicAuthCache.get(key);+ if (cached && cached.expiresAt > Date.now()) return cached.ok;+ const ok = await verifyPassword(password);+ basicAuthCache.set(key, { ok, expiresAt: Date.now() + BASIC_AUTH_CACHE_TTL_MS });+ return ok;+};+const isPublicPath = (path) => {if (PUBLIC_API_PATHS.has(path)) return true;// /api/* and /data/* are always gated. /sdapi/* (and any future non-/api@@ -101,6 +134,13 @@ export const authGate = async (req, res, next) => {if (isPublicPath(path)) return next();const token = extractToken(req);if (await verifySession(token)) return next();+ // Also accept HTTP Basic auth — used by peer-to-peer federation probes.+ // The peer sends `Authorization: Basic <base64(:password)>` (the Instances+ // UI stores username + password; only the password is validated here since+ // PortOS is single-user). scrypt verification is intentionally slow but runs+ // in libuv's thread pool so it doesn't block the event loop.+ const basicPassword = extractBasicPassword(req);+ if (basicPassword && await verifyBasicPassword(basicPassword)) 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.@@ -126,6 +166,9 @@ export const socketAuthGate = async (socket, next) => {}const token = extractToken(fakeReq);if (await verifySession(token)) return next();+ // Also accept HTTP Basic auth for peer socket relay connections.+ const basicPassword = extractBasicPassword(fakeReq);+ if (basicPassword && await verifyBasicPassword(basicPassword)) 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.jsindex f858a0f4f3..b50e4558a8 100644--- a/server/lib/authGate.test.js+++ b/server/lib/authGate.test.js@@ -234,6 +234,45 @@ describe('authGate middleware', () => {});});+describe('authGate HTTP Basic auth (peer federation)', () => {+ const basicHeader = (password, username = '') =>+ `Basic ${Buffer.from(`${username}:${password}`).toString('base64')}`;++ it('allows /api routes when Authorization: Basic carries the correct password', async () => {+ const auth = await import('../services/auth.js');+ await auth.setPassword({ newPassword: 'peer-secret' });+ const { authGate } = await import('./authGate.js');+ const result = await runGate(authGate, {+ path: '/api/cos',+ headers: { authorization: basicHeader('peer-secret') },+ });+ expect(result.called).toBe(true);+ });++ it('also works with a non-empty username (username is ignored)', async () => {+ const auth = await import('../services/auth.js');+ await auth.setPassword({ newPassword: 'peer-secret' });+ const { authGate } = await import('./authGate.js');+ const result = await runGate(authGate, {+ path: '/api/cos',+ headers: { authorization: basicHeader('peer-secret', 'user') },+ });+ expect(result.called).toBe(true);+ });++ it('rejects Basic auth with a wrong password', async () => {+ const auth = await import('../services/auth.js');+ await auth.setPassword({ newPassword: 'peer-secret' });+ const { authGate } = await import('./authGate.js');+ const result = await runGate(authGate, {+ path: '/api/cos',+ headers: { authorization: basicHeader('wrong') },+ });+ expect(result.called).toBe(false);+ expect(result.res.statusCode).toBe(401);+ });+});+describe('socketAuthGate middleware', () => {it('is a no-op when auth is disabled', async () => {const { socketAuthGate } = await import('./authGate.js');@@ -264,6 +303,17 @@ describe('socketAuthGate middleware', () => {expect(err).toBeUndefined();});+ it('accepts a peer relay handshake with correct Basic auth', async () => {+ const auth = await import('../services/auth.js');+ await auth.setPassword({ newPassword: 'peer-secret' });+ const { socketAuthGate } = await import('./authGate.js');+ const header = `Basic ${Buffer.from(':peer-secret').toString('base64')}`;+ const err = await new Promise((resolve) => {+ socketAuthGate({ handshake: { headers: { authorization: header } } }, (e) => resolve(e));+ });+ expect(err).toBeUndefined();+ });+it('rejects a cross-origin handshake', async () => {const auth = await import('../services/auth.js');const { token } = await auth.setPassword({ newPassword: 'correct-horse' });diff --git a/server/services/instances.js b/server/services/instances.jsindex d2a0a57a39..35b7e3e0a3 100644--- a/server/services/instances.js+++ b/server/services/instances.js@@ -313,10 +313,22 @@ export async function updatePeer(id, updates) {// is ignored so a stray payload can't wipe a working credential.if (updates.auth !== undefined) {const normalizedAuth = sanitizePeerAuth(updates.auth);- if (normalizedAuth !== undefined && !sameAuth(peer.auth, normalizedAuth)) {- peer.auth = normalizedAuth; // null clears, object sets- authChanged = true;- console.log(`🌐 Peer credential ${peer.auth ? 'set' : 'cleared'}: ${peer.name}`);+ if (normalizedAuth !== undefined) {+ if (!sameAuth(peer.auth, normalizedAuth)) {+ peer.auth = normalizedAuth; // null clears, object sets+ authChanged = true;+ console.log(`🌐 Peer credential ${peer.auth ? 'set' : 'cleared'}: ${peer.name}`);+ }+ // When sameAuth was true (credential unchanged), authChanged is still+ // false. If the peer is stuck in authRequired+backoff the user is+ // explicitly asking for a retry — clear backoff so the immediate probe+ // below fires instead of waiting up to 24h.+ if (!authChanged && normalizedAuth !== null && peer.authRequired) {+ peer.consecutiveFailures = 0;+ peer.nextProbeAt = null;+ peer.authRequired = false;+ authChanged = true; // ensure probe fires+ }}}if (updates.host !== undefined) {