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

fix([issue-2684]): fail closed when settings.json is corrupt so auth can't silently disable

[._.]/ Adam Eivy18ab5f0024f0
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index accc67f51c..6e88738f54 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -10,6 +10,10 @@
- **[issue-2621] Feature brainstorming remembers rejected ideas** — the feature-ideas task now checks REJECTED.md and previously closed-unmerged proposals before suggesting, so declined ideas stop coming back.
- **[issue-2614] Failing scheduled tasks no longer pile up duplicates** — a task blocked by repeated failures now counts as "already queued," so the same improvement task isn't re-created every cycle. Explicit retries (an on-demand Run, a manual job trigger, a Creative Director re-generate, or a repeated voice dispatch) revive the blocked task with a fresh retry budget instead of silently doing nothing, and the CoS log names the blocking task whenever it suppresses new work.
+## Security
+
+- **[issue-2684] A corrupt settings file can no longer silently disable your password.** Previously, if `settings.json` became unreadable or malformed, PortOS read it as "no settings" and treated the password gate as **off** — leaving the API open. The auth check now tells a genuinely absent settings file (a fresh install, correctly password-free) apart from one that exists but can't be read, and **fails closed** in the latter case: protected routes require a password and the health endpoint reports auth as required, until the file is readable again. The state self-heals on the next clean read with no restart.
+
## Companion app
- **[issue-2678] Instance identity is discoverable before you sign in.** The public `GET /api/system/health` endpoint now also reports the instance's display **name**, whether a **password is required**, and the **scheme** (http/https) it serves — so a native companion app can list, label, and decide whether to prompt for a password across your tailnet without a credential or a second request. Ships with a documented native-client API contract (`docs/COMPANION_APP_API.md`, linked from the API reference) covering discovery, auth, instance management, quick actions, daily-log, and POST progress.
diff --git a/server/lib/authGate.test.js b/server/lib/authGate.test.js
index e380be8200..d30a886120 100644
--- a/server/lib/authGate.test.js
+++ b/server/lib/authGate.test.js
@@ -1,5 +1,5 @@
import { afterAll, beforeEach, describe, expect, it, vi } from 'vitest';
-import { writeFileSync } from 'fs';
+import { writeFileSync, rmSync } from 'fs';
import { join } from 'path';
import { mockPathsDataRoot } from './mockPathsDataRoot.js';
import { bindSettingsFile } from './settingsTestUtil.js';
@@ -63,6 +63,34 @@ describe('authGate middleware', () => {
expect(result.called).toBe(true);
});
+ it('fails closed (auth ON) when settings.json exists but is corrupt (#2684)', async () => {
+ // A present-but-malformed settings.json must NOT silently disable the gate.
+ // isAuthEnabled() reads it strictly, can't confirm auth is off, and assumes
+ // ON — gated routes are blocked while public discovery paths stay reachable.
+ writeFileSync(join(tempRoot, 'settings.json'), '{ this is not valid json');
+ const { authGate } = await import('./authGate.js');
+
+ // Public discovery path (health) is still reachable — a client must be able
+ // to identify the instance even when settings can't be read.
+ const health = await runGate(authGate, { path: '/api/system/health', headers: {} });
+ expect(health.called).toBe(true);
+
+ // A gated route is blocked (401) — fail closed, not fail open.
+ const gated = await runGate(authGate, { path: '/api/cos', headers: {} });
+ expect(gated.called).toBe(false);
+ expect(gated.res.statusCode).toBe(401);
+ expect(gated.res.body).toEqual({ error: 'Authentication required', code: 'AUTH_REQUIRED' });
+ });
+
+ it('treats an absent settings.json as auth OFF (fresh install, no regression)', async () => {
+ // ENOENT is the one non-failure case — a fresh install legitimately has no
+ // settings and auth is off, so gated routes pass through.
+ rmSync(join(tempRoot, 'settings.json'), { force: true });
+ const { authGate } = await import('./authGate.js');
+ const result = await runGate(authGate, { path: '/api/cos', 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' });
diff --git a/server/services/auth.js b/server/services/auth.js
index 3f30431f41..5d7e3354ca 100644
--- a/server/services/auth.js
+++ b/server/services/auth.js
@@ -3,7 +3,7 @@ import { EventEmitter } from 'events';
import { createHash, randomBytes, scrypt, timingSafeEqual } from 'crypto';
import { promisify } from 'util';
import { atomicWrite, PATHS, safeJSONParse, tryReadFile } from '../lib/fileUtils.js';
-import { getSettings, settingsEvents, updateSettings } from './settings.js';
+import { getSettings, readSettingsStrict, settingsEvents, updateSettings } from './settings.js';
import { ServerError } from '../lib/errorHandler.js';
// Auth gates the PortOS UI + API behind a single user-set password. PortOS is
@@ -135,13 +135,27 @@ settingsEvents.on('settings:updated', recomputeEnabledCache);
export const isAuthEnabled = async () => {
if (enabledCache === null) {
- const settings = await getSettings();
+ // Cold path: read settings.json STRICTLY so a corrupt/unreadable file fails
+ // CLOSED (assume auth ON) instead of silently disabling the gate. A genuinely
+ // absent file (fresh install) still means auth off, as before. See #2684.
+ const { corrupt, settings } = await readSettingsStrict();
// Double-check after the await — a concurrent updateSettings firing
// settings:updated between the null check and this point would have
// primed the cache already; clobbering it with the stale pre-write
// snapshot would open a fail-open window if the concurrent write
// was a first-time auth enable.
- if (enabledCache === null) recomputeEnabledCache(settings);
+ if (enabledCache !== null) return enabledCache;
+ if (corrupt) {
+ // Fail closed WITHOUT caching: the file may be transiently unreadable (a
+ // mid-write window, a momentary permission blip). Returning `true` blocks
+ // gated routes for now, and leaving `enabledCache` null means the next
+ // call re-reads — so the state self-heals on the first clean read (or the
+ // next settings:updated event) without a restart. Paying one extra read
+ // per request in this abnormal, security-relevant window is the right
+ // trade for never silently disabling auth.
+ return true;
+ }
+ recomputeEnabledCache(settings);
}
return enabledCache;
};
diff --git a/server/services/settings.js b/server/services/settings.js
index ad43f59694..913d3c21d3 100644
--- a/server/services/settings.js
+++ b/server/services/settings.js
@@ -1,4 +1,5 @@
import { join } from 'path';
+import { readFile } from 'fs/promises';
import { EventEmitter } from 'events';
import { safeJSONParse, PATHS, atomicWrite, tryReadFile } from '../lib/fileUtils.js';
import { createFileWriteQueue } from '../lib/fileWriteQueue.js';
@@ -70,6 +71,50 @@ const loadRaw = async () => {
return safeJSONParse(raw ?? '{}', {});
};
+/**
+ * Security-sensitive STRICT read of settings.json for the auth gate (#2684).
+ *
+ * The normal loadRaw()/getSettings() path collapses THREE distinct states to
+ * `{}`: an ABSENT file (fresh install — legitimately no settings), a file that
+ * exists but can't be READ (permission / I/O error), and a file that reads but
+ * won't PARSE (truncated / corrupt JSON, or a non-object root). For feature
+ * reads that collapse is fine, but for the auth-enabled decision it fails OPEN:
+ * a corrupt settings.json makes `isAuthEnabled()` compute `false` over `{}` and
+ * silently disables the password gate (see `server/lib/authGate.js`).
+ *
+ * This read preserves the distinction so a security caller can fail CLOSED on
+ * the two failure modes while still treating a genuinely absent file as
+ * "auth off" (the correct default for a fresh install):
+ * { present: false, corrupt: false } → absent (ENOENT): auth legitimately off
+ * { present: true, corrupt: true } → exists but unreadable/unparseable: fail closed
+ * { present: true, corrupt: false } → parsed cleanly into `settings`
+ *
+ * `settings` is always a plain object (`{}` in the two non-clean cases) so
+ * callers can read it unconditionally; they gate their fail-closed behavior on
+ * `corrupt`. The default path is the real SETTINGS_FILE; the optional argument
+ * exists so unit tests can point it at a temp file without touching real data.
+ */
+export const readSettingsStrict = async (filePath = SETTINGS_FILE) => {
+ let raw;
+ try {
+ raw = await readFile(filePath, 'utf8');
+ } catch (err) {
+ // ENOENT is the only "not a failure" case — no file means no settings yet.
+ if (err?.code === 'ENOENT') return { present: false, corrupt: false, settings: {} };
+ // EACCES / EIO / EISDIR / … — the file is there but we couldn't read it.
+ return { present: true, corrupt: true, settings: {} };
+ }
+ try {
+ const parsed = JSON.parse(raw);
+ // A valid-JSON but non-object root (array, string, number, null) is not a
+ // settings document — treat it as corrupt rather than reading properties off it.
+ if (!isPlainObject(parsed)) return { present: true, corrupt: true, settings: {} };
+ return { present: true, corrupt: false, settings: parsed };
+ } catch {
+ return { present: true, corrupt: true, settings: {} };
+ }
+};
+
// Read-side cache. `getSettings()` is called 100+ times across the codebase
// (many per request), and each call previously did a fresh filesystem read +
// JSON.parse. Settings is app-wide, rarely-changing data — a textbook memoize.
diff --git a/server/services/settings.test.js b/server/services/settings.test.js
index 2add128b2f..a3f4915500 100644
--- a/server/services/settings.test.js
+++ b/server/services/settings.test.js
@@ -1,4 +1,4 @@
-import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
// settings.js persists via the shared atomicWrite helper and reads via
// tryReadFile (both from server/lib/fileUtils.js). Mock just those two and
@@ -13,8 +13,11 @@ vi.mock('../lib/fileUtils.js', async (importActual) => {
};
});
+import { writeFileSync, mkdtempSync, rmSync } from 'fs';
+import { join as joinPath } from 'path';
+import { tmpdir } from 'os';
import { atomicWrite, tryReadFile } from '../lib/fileUtils.js';
-import { getSettings, updateSettings, updateSettingsWith, reloadSettings, settingsEvents, __resetSettingsCache } from './settings.js';
+import { getSettings, updateSettings, updateSettingsWith, reloadSettings, settingsEvents, __resetSettingsCache, readSettingsStrict } from './settings.js';
describe('settings.js', () => {
beforeEach(() => {
@@ -502,4 +505,49 @@ describe('settings.js', () => {
expect({}.polluted).toBeUndefined();
});
});
+
+ // Strict read for the auth gate (#2684): distinguishes absent (auth off) from
+ // present-but-corrupt (fail closed), which loadRaw()/getSettings() collapse to {}.
+ // These exercise the REAL fs read path against temp files (not the tryReadFile
+ // mock), which is the whole point — the collapse the mock would hide is the bug.
+ describe('readSettingsStrict', () => {
+ let dir;
+ beforeEach(() => { dir = mkdtempSync(joinPath(tmpdir(), 'portos-strict-')); });
+ afterEach(() => { rmSync(dir, { recursive: true, force: true }); });
+
+ it('reports absent (not corrupt) when the file does not exist', async () => {
+ const res = await readSettingsStrict(joinPath(dir, 'nope.json'));
+ expect(res).toEqual({ present: false, corrupt: false, settings: {} });
+ });
+
+ it('parses a clean settings file', async () => {
+ const p = joinPath(dir, 'settings.json');
+ writeFileSync(p, JSON.stringify({ secrets: { auth: { enabled: true, passwordHash: 'h', salt: 's' } } }));
+ const res = await readSettingsStrict(p);
+ expect(res.present).toBe(true);
+ expect(res.corrupt).toBe(false);
+ expect(res.settings.secrets.auth.enabled).toBe(true);
+ });
+
+ it('flags a present-but-malformed file as corrupt (fail-closed signal)', async () => {
+ const p = joinPath(dir, 'settings.json');
+ writeFileSync(p, '{ this is not valid json');
+ const res = await readSettingsStrict(p);
+ expect(res).toEqual({ present: true, corrupt: true, settings: {} });
+ });
+
+ it('flags an empty file as corrupt', async () => {
+ const p = joinPath(dir, 'settings.json');
+ writeFileSync(p, '');
+ const res = await readSettingsStrict(p);
+ expect(res.corrupt).toBe(true);
+ });
+
+ it('flags a valid-JSON but non-object root as corrupt', async () => {
+ const p = joinPath(dir, 'settings.json');
+ writeFileSync(p, '[1,2,3]');
+ const res = await readSettingsStrict(p);
+ expect(res.corrupt).toBe(true);
+ });
+ });
});