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

refactor([issue-4901]): move auth gate into services

Adam Eivy5d8541fcb76b
diff --git a/server/index.js b/server/index.js
index f70ae7d54c..b98e09fecd 100644
--- a/server/index.js
+++ b/server/index.js
@@ -105,7 +105,7 @@ import reviewRoutes from './routes/review.js';
import githubRoutes from './routes/github.js';
import settingsRoutes from './routes/settings.js';
import authRoutes from './routes/auth.js';
-import { authGate, socketAuthGate } from './lib/authGate.js';
+import { authGate, socketAuthGate } from './services/authGate.js';
import telegramRoutes from './routes/telegram.js';
import updateRoutes from './routes/update.js';
import loopsRoutes from './routes/loops.js';
@@ -223,7 +223,7 @@ app.set('io', io);
// Public routes (login, status, health) still need a parsed body / no body,
// and they flow through to the parsers below normally. 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/
+// except the small public set in services/authGate.js (auth status/whoami/login/
// logout + /api/system/health). No-op when auth is off.
app.use(authGate);
diff --git a/server/lib/README.md b/server/lib/README.md
index 6d55346442..2ddf5a25b6 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -397,7 +397,6 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `assetMounts.js` | `ASSET_MOUNTS` — every `/data/**` static mount as `{ route, dir, gate? }` (`dir` a thunk so a test that re-roots `PATHS.data` still steers it) — plus `mountAssetRoutes(app)`, which mounts them and then TERMINATES each `SERVER_OWNED_PREFIXES` namespace with a 404. The terminator matters: the SPA fallback only skips paths carrying a file extension, so an extensionless `/data/…` or a mistyped `/api/…` used to be answered with index.html and a 200 — a binary loader parsed HTML, an API client got HTML with a success status (#4688). |
| `assetRoutePrefixes.js` | Import-free leaf holding the URL prefixes the server owns: `ASSET_ROUTE_PREFIXES` (every `/data/**` static mount) and `SERVER_OWNED_PREFIXES` (what must never reach the SPA fallback, each with the exact `spaPaths` that ARE client routes). `scripts/dev-proxy-drift.test.js` checks the dev proxy's `^/data/` wildcard against the mounts, pins the route-registration order in `server/index.js` (a router added below the terminators is shadowed), and fails if a client route — from `NAV_COMMANDS` or `App.jsx`'s nested `<Route>` tree — is ever added under a server-owned prefix without being declared. |
| `asyncMutex.js` | Promise-based async mutex. |
-| `authGate.js` | Express + Socket.IO middleware that gates `/api/*` and `/data/*` behind the password set in `settings.secrets.auth`. No-op when auth is off; emits 401 `AUTH_REQUIRED` (or plain text for `/data/*`) when on and the request has no valid session token. Consults `apiRegistry.isRegistryPublic` so an exposed+passwordless API (voice/sdapi) bypasses the gate on its public prefix only. |
| `concurrencyGate.js` | `createConcurrencyGate(limit)` → `run(fn)` — cap on simultaneous async work for ONE module-scoped budget, released FIFO. Sibling to `mapWithConcurrency.js`, which caps in-flight work *within one array map*; a gate is shared state, so several call sites fanning out at the same remote respect one budget instead of each respecting its own while the host sees the sum. `createMutex` (`asyncMutex.js`) is this with `limit` fixed at 1 — prefer it for mutual exclusion. Note the budget is per-MODULE, not per-host: two modules calling one host each get their own gate. Used by `huggingFaceCatalog.js` (4) and `ollamaRegistryCatalog.js` (16), whose cold catalog-enrichment bursts otherwise arrive at a free public API as a thundering herd — which the Hub answers with an HTTP/2 GOAWAY that surfaces as a bare `fetch failed`. |
| `dispatchLabels.js` | slashdo dispatch-hint contract: `model:light/medium/heavy` + `effort:low/medium/high/xhigh/max` vocabulary, prescribed forge colors, validation (`normalizeDispatchModel` / `normalizeDispatchEffort`), GitHub/GitLab vs Jira label formatting, optional contributor labels (`good first issue` / `help wanted`, never implied by `model:light`), lazy-create command text, and shared dispatch plus issue-quality guidance (`ISSUE_QUALITY_GUIDANCE`, `DISPATCH_HINT_GUIDANCE`, `JIRA_DISPATCH_HINT_GUIDANCE`). Omit an unjustified axis; never invent `medium`; reject future-only/speculative work while keeping useful current refactors claimable. Consumed by work-tracker instructions, quota-burn audits, Layered Intelligence filing, and claim follow-up prompts. |
| `domainAutonomy.js` | Per-domain autonomy guardrails (pure). `AUTONOMY_DOMAINS`/`DOMAIN_IDS`/`DOMAIN_MODES` (`off`/`dry-run`/`execute`), `getDomainMode(config, id)`, and `normalizeDomainAutonomy(raw)` to coerce a hand-edited/partial map. Default per domain is `execute` (reproduces pre-#711 behavior, so no migration needed). Also `CREATIVE_DOMAIN`/`getCreativeAutonomyMode(config)` (#2183) — the Creative Director orchestrator domain, kept out of `DOMAIN_IDS` and defaulting to mirror the `cos` mode. |
diff --git a/server/lib/apiRegistry.js b/server/lib/apiRegistry.js
index d76c20bd74..4ce0bd31a5 100644
--- a/server/lib/apiRegistry.js
+++ b/server/lib/apiRegistry.js
@@ -3,7 +3,7 @@
* are usable as externally-callable HTTP APIs.
*
* One declaration here drives THREE consumers, so they can never drift:
- * 1. `authGate` (server/lib/authGate.js) — when the PortOS password is on, an
+ * 1. `authGate` (server/services/authGate.js) — when the PortOS password is on, an
* entry that is `exposed && !requireAuth` re-opens ONLY its `publicPrefixes`
* so external callers can reach it without a session.
* 2. The Settings UI (VoiceTab + the API Access page) — renders the per-API
diff --git a/server/lib/index.js b/server/lib/index.js
index af7b354f30..09793f250c 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -374,7 +374,6 @@ export * from './arrayUtils.js';
export * from './assetMounts.js';
export * from './assetRoutePrefixes.js';
export * from './asyncMutex.js';
-export * from './authGate.js';
export * from './concurrencyGate.js';
export * from './dispatchLabels.js';
export * from './domainAutonomy.js';
diff --git a/server/routes/publicApiIntegration.test.js b/server/routes/publicApiIntegration.test.js
index 7dbaa5df9f..f6b937b66f 100644
--- a/server/routes/publicApiIntegration.test.js
+++ b/server/routes/publicApiIntegration.test.js
@@ -49,7 +49,7 @@ const resetSettings = (extra = {}) => {
const setApiAccess = (apiAccess) => mergeSettingsFile({ apiAccess });
const buildApp = async () => {
- const { authGate } = await import('../lib/authGate.js');
+ const { authGate } = await import('../services/authGate.js');
const voicePublicRoutes = (await import('./voicePublic.js')).default;
const voiceRoutes = (await import('./voice.js')).default;
const app = express();
diff --git a/server/lib/authGate.js b/server/services/authGate.js
similarity index 96%
rename from server/lib/authGate.js
rename to server/services/authGate.js
index f9d6127b93..338aa002d8 100644
--- a/server/lib/authGate.js
+++ b/server/services/authGate.js
@@ -1,11 +1,11 @@
import { createHash } from 'node:crypto';
-import { extractToken, isAuthEnabled, verifyPassword, verifySession } from '../services/auth.js';
+import { extractToken, isAuthEnabled, verifyPassword, verifySession } from './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';
-import { sendErrorResponse, ServerError } from './errorHandler.js';
+import { getSettings, settingsEvents } from './settings.js';
+import { isRegistryPublic } from '../lib/apiRegistry.js';
+import { sendErrorResponse, ServerError } from '../lib/errorHandler.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
diff --git a/server/lib/authGate.test.js b/server/services/authGate.test.js
similarity index 92%
rename from server/lib/authGate.test.js
rename to server/services/authGate.test.js
index a6eb27a7ae..3e5fdfa66f 100644
--- a/server/lib/authGate.test.js
+++ b/server/services/authGate.test.js
@@ -1,8 +1,8 @@
import { afterAll, beforeEach, describe, expect, it, vi } from 'vitest';
import { writeFileSync, rmSync } from 'fs';
import { join } from 'path';
-import { mockPathsDataRoot } from './mockPathsDataRoot.js';
-import { bindSettingsFile } from './settingsTestUtil.js';
+import { mockPathsDataRoot } from '../lib/mockPathsDataRoot.js';
+import { bindSettingsFile } from '../lib/settingsTestUtil.js';
const { tempRoot, makeProxy, cleanup } = mockPathsDataRoot({ prefix: 'portos-authgate-' });
@@ -73,7 +73,7 @@ describe('authGate middleware', () => {
});
it('passes /api/auth/login through even when auth is enabled', async () => {
- const auth = await import('../services/auth.js');
+ const auth = await import('./auth.js');
await auth.setPassword({ newPassword: 'correct-horse' });
const { authGate } = await import('./authGate.js');
const result = await runGate(authGate, { path: '/api/auth/login', headers: {} });
@@ -104,7 +104,7 @@ describe('authGate middleware', () => {
// broadcast the corrupt file as {} and prime the auth cache to disabled — that
// would reopen the gate (fail open) and stick, since the cache is no longer null.
writeFileSync(join(tempRoot, 'settings.json'), '{ corrupt snapshot');
- const { reloadSettings } = await import('../services/settings.js');
+ const { reloadSettings } = await import('./settings.js');
const { authGate } = await import('./authGate.js');
await reloadSettings();
@@ -127,7 +127,7 @@ describe('authGate middleware', () => {
});
it('blocks /api routes with no token', async () => {
- const auth = await import('../services/auth.js');
+ const auth = await import('./auth.js');
await auth.setPassword({ newPassword: 'correct-horse' });
const { authGate } = await import('./authGate.js');
const result = await runGate(authGate, { path: '/api/cos', headers: {} });
@@ -137,7 +137,7 @@ describe('authGate middleware', () => {
});
it('allows /api routes when the cookie token is valid', async () => {
- const auth = await import('../services/auth.js');
+ const auth = await import('./auth.js');
const { token } = await auth.setPassword({ newPassword: 'correct-horse' });
const { authGate } = await import('./authGate.js');
const result = await runGate(authGate, {
@@ -148,7 +148,7 @@ describe('authGate middleware', () => {
});
it('allows /api routes when the Authorization Bearer token is valid', async () => {
- const auth = await import('../services/auth.js');
+ const auth = await import('./auth.js');
const { token } = await auth.setPassword({ newPassword: 'correct-horse' });
const { authGate } = await import('./authGate.js');
const result = await runGate(authGate, {
@@ -159,7 +159,7 @@ describe('authGate middleware', () => {
});
it('lets static client paths through when auth is on', async () => {
- const auth = await import('../services/auth.js');
+ const auth = await import('./auth.js');
await auth.setPassword({ newPassword: 'correct-horse' });
const { authGate } = await import('./authGate.js');
const result = await runGate(authGate, { path: '/assets/index.js', headers: {} });
@@ -167,7 +167,7 @@ describe('authGate middleware', () => {
});
it('returns plain-text 401 for blocked /data/* asset requests', async () => {
- const auth = await import('../services/auth.js');
+ const auth = await import('./auth.js');
await auth.setPassword({ newPassword: 'correct-horse' });
const { authGate } = await import('./authGate.js');
const result = await runGate(authGate, { path: '/data/images/foo.png', headers: {} });
@@ -177,7 +177,7 @@ describe('authGate middleware', () => {
});
it('gates the /sdapi/* AUTOMATIC1111-compatible surface', async () => {
- const auth = await import('../services/auth.js');
+ const auth = await import('./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: {} });
@@ -187,7 +187,7 @@ describe('authGate middleware', () => {
});
it('treats a malformed cookie value as no token (clean 401, not 500)', async () => {
- const auth = await import('../services/auth.js');
+ const auth = await import('./auth.js');
await auth.setPassword({ newPassword: 'correct-horse' });
const { authGate } = await import('./authGate.js');
// %E0 is a partial percent-escape — decodeURIComponent throws URIError.
@@ -198,7 +198,7 @@ describe('authGate middleware', () => {
});
it('rejects cross-origin requests with 403 before consulting the session', async () => {
- const auth = await import('../services/auth.js');
+ const auth = await import('./auth.js');
const { token } = await auth.setPassword({ newPassword: 'correct-horse' });
const { authGate } = await import('./authGate.js');
// Even a VALID session cookie can't rescue a cross-origin request —
@@ -218,7 +218,7 @@ describe('authGate middleware', () => {
});
it('allows same-origin requests when Origin matches Host', async () => {
- const auth = await import('../services/auth.js');
+ const auth = await import('./auth.js');
const { token } = await auth.setPassword({ newPassword: 'correct-horse' });
const { authGate } = await import('./authGate.js');
const result = await runGate(authGate, {
@@ -233,7 +233,7 @@ describe('authGate middleware', () => {
});
it('allows requests without an Origin header (curl, server-to-server)', async () => {
- const auth = await import('../services/auth.js');
+ const auth = await import('./auth.js');
const { token } = await auth.setPassword({ newPassword: 'correct-horse' });
const { authGate } = await import('./authGate.js');
const result = await runGate(authGate, {
@@ -247,7 +247,7 @@ describe('authGate middleware', () => {
});
it('allows mixed-case same-origin hostnames (RFC 3986 case-insensitive)', async () => {
- const auth = await import('../services/auth.js');
+ const auth = await import('./auth.js');
const { token } = await auth.setPassword({ newPassword: 'correct-horse' });
const { authGate } = await import('./authGate.js');
const result = await runGate(authGate, {
@@ -262,7 +262,7 @@ describe('authGate middleware', () => {
});
it('allows loopback↔loopback cross-port (Vite dev proxy)', async () => {
- const auth = await import('../services/auth.js');
+ const auth = await import('./auth.js');
const { token } = await auth.setPassword({ newPassword: 'correct-horse' });
const { authGate } = await import('./authGate.js');
const result = await runGate(authGate, {
@@ -277,7 +277,7 @@ describe('authGate middleware', () => {
});
it('rejects a cross-origin logout (public path still gets the CSRF check)', async () => {
- const auth = await import('../services/auth.js');
+ const auth = await import('./auth.js');
await auth.setPassword({ newPassword: 'correct-horse' });
const { authGate } = await import('./authGate.js');
const result = await runGate(authGate, {
@@ -293,7 +293,7 @@ describe('authGate middleware', () => {
});
it('treats a malformed Origin header as cross-origin', async () => {
- const auth = await import('../services/auth.js');
+ const auth = await import('./auth.js');
const { token } = await auth.setPassword({ newPassword: 'correct-horse' });
const { authGate } = await import('./authGate.js');
const result = await runGate(authGate, {
@@ -310,7 +310,7 @@ describe('authGate middleware', () => {
describe('authGate per-API public registry (apiAccess)', () => {
it('opens /api/voice/public/* when voice is exposed + passwordless', async () => {
- const auth = await import('../services/auth.js');
+ const auth = await import('./auth.js');
await auth.setPassword({ newPassword: 'correct-horse' });
await writeApiAccess({ voice: { exposed: true, requireAuth: false } });
const { authGate } = await import('./authGate.js');
@@ -323,7 +323,7 @@ describe('authGate per-API public registry (apiAccess)', () => {
it('KEEPS mutation routes gated even when voice is exposed + passwordless', async () => {
// The key safety invariant: exposing the public surface must NOT open the
// config / process-control routes on the main /api/voice router.
- const auth = await import('../services/auth.js');
+ const auth = await import('./auth.js');
await auth.setPassword({ newPassword: 'correct-horse' });
await writeApiAccess({ voice: { exposed: true, requireAuth: false } });
const { authGate } = await import('./authGate.js');
@@ -335,7 +335,7 @@ describe('authGate per-API public registry (apiAccess)', () => {
});
it('gates the public surface when exposed but requireAuth is true', async () => {
- const auth = await import('../services/auth.js');
+ const auth = await import('./auth.js');
await auth.setPassword({ newPassword: 'correct-horse' });
await writeApiAccess({ voice: { exposed: true, requireAuth: true } });
const { authGate } = await import('./authGate.js');
@@ -345,7 +345,7 @@ describe('authGate per-API public registry (apiAccess)', () => {
});
it('gates the public surface when not exposed', async () => {
- const auth = await import('../services/auth.js');
+ const auth = await import('./auth.js');
await auth.setPassword({ newPassword: 'correct-horse' });
await writeApiAccess({ voice: { exposed: false, requireAuth: false } });
const { authGate } = await import('./authGate.js');
@@ -355,7 +355,7 @@ describe('authGate per-API public registry (apiAccess)', () => {
});
it('opens /sdapi/* when sdapi is exposed + passwordless', async () => {
- const auth = await import('../services/auth.js');
+ const auth = await import('./auth.js');
await auth.setPassword({ newPassword: 'correct-horse' });
await writeApiAccess({ sdapi: { exposed: true, requireAuth: false } });
const { authGate } = await import('./authGate.js');
@@ -364,7 +364,7 @@ describe('authGate per-API public registry (apiAccess)', () => {
});
it('still applies the CSRF cross-origin guard to an exposed public path', async () => {
- const auth = await import('../services/auth.js');
+ const auth = await import('./auth.js');
await auth.setPassword({ newPassword: 'correct-horse' });
await writeApiAccess({ voice: { exposed: true, requireAuth: false } });
const { authGate } = await import('./authGate.js');
@@ -391,7 +391,7 @@ describe('authGate HTTP Basic auth (peer federation)', () => {
`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');
+ const auth = await import('./auth.js');
await auth.setPassword({ newPassword: 'peer-secret' });
const { authGate } = await import('./authGate.js');
const req = {
@@ -404,7 +404,7 @@ describe('authGate HTTP Basic auth (peer federation)', () => {
});
it('also works with a non-empty username (username is ignored)', async () => {
- const auth = await import('../services/auth.js');
+ const auth = await import('./auth.js');
await auth.setPassword({ newPassword: 'peer-secret' });
const { authGate } = await import('./authGate.js');
const result = await runGate(authGate, {
@@ -415,7 +415,7 @@ describe('authGate HTTP Basic auth (peer federation)', () => {
});
it('rejects Basic auth with a wrong password', async () => {
- const auth = await import('../services/auth.js');
+ const auth = await import('./auth.js');
await auth.setPassword({ newPassword: 'peer-secret' });
const { authGate } = await import('./authGate.js');
const result = await runGate(authGate, {
@@ -437,7 +437,7 @@ describe('socketAuthGate middleware', () => {
});
it('rejects an unauthenticated handshake when auth is on', async () => {
- const auth = await import('../services/auth.js');
+ const auth = await import('./auth.js');
await auth.setPassword({ newPassword: 'correct-horse' });
const { socketAuthGate } = await import('./authGate.js');
const err = await new Promise((resolve) => {
@@ -448,7 +448,7 @@ describe('socketAuthGate middleware', () => {
});
it('accepts a handshake with a valid cookie', async () => {
- const auth = await import('../services/auth.js');
+ const auth = await import('./auth.js');
const { token } = await auth.setPassword({ newPassword: 'correct-horse' });
const { socketAuthGate } = await import('./authGate.js');
const err = await new Promise((resolve) => {
@@ -458,7 +458,7 @@ describe('socketAuthGate middleware', () => {
});
it('accepts a peer relay handshake with correct Basic auth', async () => {
- const auth = await import('../services/auth.js');
+ const auth = await import('./auth.js');
await auth.setPassword({ newPassword: 'peer-secret' });
const { socketAuthGate } = await import('./authGate.js');
const header = `Basic ${Buffer.from(':peer-secret').toString('base64')}`;
@@ -469,7 +469,7 @@ describe('socketAuthGate middleware', () => {
});
it('rejects a cross-origin handshake', async () => {
- const auth = await import('../services/auth.js');
+ const auth = await import('./auth.js');
const { token } = await auth.setPassword({ newPassword: 'correct-horse' });
const { socketAuthGate } = await import('./authGate.js');
const err = await new Promise((resolve) => {
diff --git a/server/services/settings.js b/server/services/settings.js
index 7a9545aafa..a1fee60d4d 100644
--- a/server/services/settings.js
+++ b/server/services/settings.js
@@ -79,7 +79,7 @@ const loadRaw = async () => {
* 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`).
+ * silently disables the password gate (see `server/services/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
diff --git a/server/services/sharing/peerPullAuthorization.js b/server/services/sharing/peerPullAuthorization.js
index 9b5461be80..69a3a2539d 100644
--- a/server/services/sharing/peerPullAuthorization.js
+++ b/server/services/sharing/peerPullAuthorization.js
@@ -15,7 +15,7 @@
* Honest framing: `X-PortOS-Instance-Id` is *identification*, not
* authentication — it is self-asserted and spoofable on an unauthenticated
* tailnet. The real authentication control remains the optional instance
- * password (`server/lib/authGate.js`). The value here is that the pull path
+ * password (`server/services/authGate.js`). The value here is that the pull path
* honors the sharing config the user actually configured.
*
* Compatibility (required by the distribution model — peers upgrade