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

feat: log sign-ins, password and session changes, and refused host-control requests

Adam Eivy3c1e3b3d2c94
diff --git a/server/lib/README.md b/server/lib/README.md
index 5e4d90a4dd..19949d996b 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -365,6 +365,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `portosRootPlaceholder.js` | Expand leftover `__PORTOS_ROOT__` tokens in apps registry fields (`repoPath`, `appIconPath`, etc.) so a partial/restored `data/` tree cannot leave Apps → Git looking for a non-existent checkout. `PORTOS_ROOT_TOKEN`, `expandPortosRootToken`, `expandPortosRootInApp`, `containsPortosRootToken`. Used by `services/apps.js` on load and by `scripts/setup-data.js` / `scripts/lib/rewriteAppsPortosRoot.js` when seeding or rewriting `data/apps.json`. |
| `pm2Jlist.js` | Sole owner of the strict `pm2 jlist` stdout parser: `parsePm2JlistStdout(stdout)` returns the parsed process array (incl. `[]` for a genuine empty read) or `null` when the read effectively failed (empty/garbage/non-array stdout) — the absent-vs-empty contract from issue #968, consolidated by #8164. Zero imports so `autofixer/shared.js` can use it without the server dependency graph. `services/pm2.js` re-exports it as `parseJlistStdout` for compatibility; `services/pm2.js#listProcessesStrict` and `autofixer/shared.js` are the only non-test callers permitted to execute raw `pm2 jlist`. |
| `secretText.js` | `scrubSecretTokens(text)` — replace credential-SHAPED substrings (prefixed API keys, GitHub/Slack tokens, JWTs, AWS key ids, pasted Bearer headers, 48+-char hex) with `[REDACTED]` in free text bound for an LLM provider or a world-readable artifact; `scrubSecretTokensDeep(value)` walks arrays/plain objects and scrubs every string value. Value-side counterpart to the operator-action ledger's key-based `redactPayload` and `commandSecurity.js#redactOutput`'s JSON patterns; conservative so prose, 40-hex git SHAs, and short ids survive. |
+| `securityAuditLog.js` | `logSecurityEvent(event, { refused, ...fields })` — one-line `🔐`/`⛔ Security [event] key=value` audit trail for sign-ins, password/session/agent-key changes and refused host-control or browser-relay requests. Flattens control characters and truncates values so a caller-controlled path/Host can't forge a log line; refusals use `console.warn`. |
| `homePath.js` | `scrubHomePath(value)` — replace the running user's home-directory prefix with `~` anywhere in a string, so `/Users/<name>/…` never embeds the OS username in anything a user pastes into a bug report. Non-strings pass through; a root-user container reporting `/` as home is left alone (substituting on it would rewrite every separator in every path). Zero-dependency by design: `agentRunEvents.js` re-exports it for the CoS ledger, and `scripts/doctor.js` imports it statically because it must load from a bare checkout with no `node_modules` (`scripts/pre-install-entrypoints.test.js` enforces that). |
| `jsonIo.js` | JSON/JSONL parsing and file IO, strict read sentinels, append/read/write helpers, and `createCachedStore` — a TTL-cached mutable JSON document with serialized `save`/`mutate`; its `load()` is strict (#4115) so a corrupt file rejects instead of being overwritten by the next `mutate`. |
| `settingsStore.js` | `createSettingsStore(filePath | () => filePath, defaults, { normalize? })` → `{ get, update, path }` — the one owner of a flat per-feature settings document with shipped defaults (`journal-settings.json`, `activity-digest-settings.json`, `goal-scorecard-settings.json`, …). `get()` reads strict (#4115: a corrupt file rejects rather than reading as the defaults, because `update` writes it back), merges the file over `defaults`, then runs `normalize`; `update(patch)` is a serialized `get → apply → atomicWrite` that skips `undefined` values and writes `null` as an explicit clear. Filter client-settable keys BEFORE calling `update`. Reach for `createCachedStore` for an in-place-edited document and `createCollectionStore` for per-record collections. |
diff --git a/server/lib/index.js b/server/lib/index.js
index 38c63641c8..b6373f1ec9 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -328,6 +328,7 @@ export * from './spawnCwd.js';
export * from './sshHostAlias.js';
export * from './schemaVersions.js';
export * from './secretText.js';
+export * from './securityAuditLog.js';
export * from './piiRedactionPatterns.js';
export * from './imageClean.js';
export * from './imageCleanDefaults.js';
diff --git a/server/lib/securityAuditLog.js b/server/lib/securityAuditLog.js
new file mode 100644
index 0000000000..af2ea1024b
--- /dev/null
+++ b/server/lib/securityAuditLog.js
@@ -0,0 +1,39 @@
+/**
+ * One-line audit trail for security-relevant events — who/what/where, no secrets.
+ *
+ * PortOS holds host-control authority, so a sign-in, a password change, a
+ * revoked session, or a refused host-control call must leave a line an operator
+ * can find later in `pm2 logs`. Refusals go to `console.warn` (a deliberate
+ * refusal); successes stay on `console.log`.
+ *
+ * Field values are flattened to one line and truncated: a request path, Host
+ * header, or label is caller-controlled, and an embedded newline would forge a
+ * second log line.
+ */
+
+const MAX_VALUE_LENGTH = 120;
+
+// eslint-disable-next-line no-control-regex
+const CONTROL_CHARS = /[\u0000-\u001f\u007f-\u009f\u2028\u2029]+/g;
+
+const formatValue = (value) => {
+ const flat = String(value).replace(CONTROL_CHARS, ' ').trim();
+ const clipped = flat.length > MAX_VALUE_LENGTH ? `${flat.slice(0, MAX_VALUE_LENGTH)}…` : flat;
+ return /[\s="]/.test(clipped) ? JSON.stringify(clipped) : clipped;
+};
+
+/**
+ * @param {string} event - Dotted event name, e.g. `login.failed`
+ * @param {{ refused?: boolean } & Record<string, unknown>} [fields] - `refused: true`
+ * logs through `console.warn`; null/undefined fields are omitted.
+ * @returns {string} the emitted line (handy for assertions)
+ */
+export function logSecurityEvent(event, { refused = false, ...fields } = {}) {
+ const detail = Object.entries(fields)
+ .filter(([, value]) => value !== undefined && value !== null && value !== '')
+ .map(([key, value]) => `${key}=${formatValue(value)}`)
+ .join(' ');
+ const line = `${refused ? '⛔' : '🔐'} Security [${event}]${detail ? ` ${detail}` : ''}`;
+ (refused ? console.warn : console.log)(line);
+ return line;
+}
diff --git a/server/lib/securityAuditLog.test.js b/server/lib/securityAuditLog.test.js
new file mode 100644
index 0000000000..73af46e06d
--- /dev/null
+++ b/server/lib/securityAuditLog.test.js
@@ -0,0 +1,26 @@
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { logSecurityEvent } from './securityAuditLog.js';
+
+afterEach(() => vi.restoreAllMocks());
+
+describe('logSecurityEvent', () => {
+ it('routes refusals to warn and everything else to log, omitting empty fields', () => {
+ const log = vi.spyOn(console, 'log').mockImplementation(() => {});
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ expect(logSecurityEvent('login.ok', { ip: '192.0.2.1', session: null, note: '' })).toBe('🔐 Security [login.ok] ip=192.0.2.1');
+ expect(log).toHaveBeenCalledTimes(1);
+ logSecurityEvent('login.failed', { refused: true, ip: '192.0.2.1' });
+ expect(warn).toHaveBeenCalledWith('⛔ Security [login.failed] ip=192.0.2.1');
+ });
+
+ it('cannot be used to forge a second log line from a caller-controlled value', () => {
+ vi.spyOn(console, 'warn').mockImplementation(() => {});
+ const line = logSecurityEvent('request.refused', {
+ refused: true,
+ path: `/x\n🔐 Security [login.ok] ip=1.2.3.4${'a'.repeat(300)}`,
+ });
+ expect(line.split('\n')).toHaveLength(1);
+ expect(line).toContain('path="/x 🔐 Security [login.ok] ip=1.2.3.4');
+ expect(line.length).toBeLessThan(200);
+ });
+});
diff --git a/server/routes/auth.js b/server/routes/auth.js
index ce6c55fc68..917745c653 100644
--- a/server/routes/auth.js
+++ b/server/routes/auth.js
@@ -25,6 +25,7 @@ import {
import { getAgentKeyStatus, rotateAgentKey, setAgentKeyEnabled } from '../services/agentKey.js';
import { asyncHandler, ServerError } from '../lib/errorHandler.js';
import { validateRequest } from '../lib/validation.js';
+import { logSecurityEvent } from '../lib/securityAuditLog.js';
const router = Router();
@@ -42,6 +43,10 @@ const sessionIdParamSchema = z.object({ id: z.string().min(1).max(64).regex(/^[a
// deployment topology.
const isSecure = (req) => !!req.secure;
+// Source address for the audit trail. `req.ip` is the socket peer (no reverse
+// proxy in front of PortOS), so a forged header cannot name another machine.
+const sourceOf = (req) => req.ip || req.socket?.remoteAddress || 'unknown';
+
// The session cookie name is port-scoped from the browser-facing `Host` (see
// sessionCookieNameFor in lib/portosAuthCore.js) — e.g. `portos_auth_15555`
// behind a `tailcat forward 15555:5555` — so this install never shares (or is
@@ -102,7 +107,7 @@ router.post('/login', asyncHandler(async (req, res) => {
// Throttle check runs BEFORE scrypt so a sidecar can't pin the CPU by
// looping bad guesses. The IP comes from Express's `req.ip` (we don't
// sit behind a reverse proxy in normal PortOS deployments).
- const clientIp = req.ip || req.socket?.remoteAddress || 'unknown';
+ const clientIp = sourceOf(req);
if (isLoginRateLimited(clientIp)) {
throw new ServerError('Too many login attempts — try again in a minute', {
status: 429,
@@ -111,12 +116,17 @@ router.post('/login', asyncHandler(async (req, res) => {
}
if (!(await verifyPassword(password))) {
recordLoginFailure(clientIp);
+ logSecurityEvent('login.failed', { refused: true, ip: clientIp });
+ // One line when the window fills, not one per throttled request — the 429s
+ // that follow carry no new information and would flood the log under a guess loop.
+ if (isLoginRateLimited(clientIp)) logSecurityEvent('login.throttled', { refused: true, ip: clientIp });
throw new ServerError('Invalid password', { status: 401, code: 'AUTH_BAD_PASSWORD' });
}
// Success clears the throttle so a user who mistyped a few times then got
// it right isn't kept locked out.
clearLoginFailures(clientIp);
- const { token } = await createSession();
+ const { token, id } = await createSession();
+ logSecurityEvent('login.ok', { ip: clientIp, session: id });
res.setHeader('Set-Cookie', sessionCookieFor(req, token));
res.json({ authenticated: true });
}));
@@ -128,7 +138,9 @@ router.post('/logout', asyncHandler(async (req, res) => {
// pre-upgrade legacy cookie, Bearer) so signing out can't leave a second
// valid cookie behind. revokeSession is a no-op for foreign tokens.
const stale = await ownedStaleCookieNames(req);
- for (const token of extractTokens(req)) await revokeSession(token);
+ const tokens = extractTokens(req);
+ for (const token of tokens) await revokeSession(token);
+ if (tokens.length) logSecurityEvent('logout', { ip: sourceOf(req) });
res.setHeader('Set-Cookie', clearCookiesFor(req, stale));
res.json({ ok: true });
}));
@@ -148,6 +160,10 @@ router.post('/password', asyncHandler(async (req, res) => {
newPassword: body.newPassword,
currentPassword: alreadyEnabled ? body.currentPassword : null,
});
+ logSecurityEvent(alreadyEnabled ? 'password.rotated' : 'password.set', {
+ ip: sourceOf(req),
+ note: 'all other sessions revoked',
+ });
const secure = isSecure(req);
res.setHeader('Set-Cookie', [
sessionCookieFor(req, token),
@@ -163,6 +179,7 @@ router.delete('/password', asyncHandler(async (req, res) => {
const { currentPassword } = validateRequest(clearPasswordSchema, req.body || {});
const stale = await ownedStaleCookieNames(req);
await clearPassword({ currentPassword });
+ logSecurityEvent('password.cleared', { ip: sourceOf(req), note: 'auth disabled, all sessions revoked' });
res.setHeader('Set-Cookie', clearCookiesFor(req, stale));
res.json({ enabled: false });
}));
@@ -186,6 +203,7 @@ router.delete('/sessions/:id', asyncHandler(async (req, res) => {
if (!revoked) {
throw new ServerError('Session not found', { status: 404, code: 'AUTH_SESSION_NOT_FOUND' });
}
+ logSecurityEvent('session.revoked', { ip: sourceOf(req), session: id });
res.json({ ok: true });
}));
@@ -201,11 +219,15 @@ router.get('/agent-key', asyncHandler(async (_req, res) => {
router.put('/agent-key', asyncHandler(async (req, res) => {
const { enabled } = validateRequest(agentKeyToggleSchema, req.body || {});
- res.json(await setAgentKeyEnabled(enabled));
+ const status = await setAgentKeyEnabled(enabled);
+ logSecurityEvent(enabled ? 'agent-key.enabled' : 'agent-key.disabled', { ip: sourceOf(req) });
+ res.json(status);
}));
-router.post('/agent-key/rotate', asyncHandler(async (_req, res) => {
- res.json(await rotateAgentKey());
+router.post('/agent-key/rotate', asyncHandler(async (req, res) => {
+ const status = await rotateAgentKey();
+ logSecurityEvent('agent-key.rotated', { ip: sourceOf(req) });
+ res.json(status);
}));
export default router;
diff --git a/server/routes/auth.test.js b/server/routes/auth.test.js
index 4e5f6bb923..5bf7414dc3 100644
--- a/server/routes/auth.test.js
+++ b/server/routes/auth.test.js
@@ -1,4 +1,4 @@
-import { afterAll, beforeEach, describe, expect, it, vi } from 'vitest';
+import { afterAll, afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import express from 'express';
import { readFileSync, writeFileSync } from 'fs';
import { join } from 'path';
@@ -269,6 +269,61 @@ describe('auth routes', () => {
});
});
+describe('security audit trail', () => {
+ // Every line logSecurityEvent emits, whichever sink it chose.
+ const captureTrail = () => {
+ const lines = [];
+ const sink = (line) => lines.push(String(line));
+ vi.spyOn(console, 'log').mockImplementation(sink);
+ vi.spyOn(console, 'warn').mockImplementation(sink);
+ vi.spyOn(console, 'error').mockImplementation(() => {});
+ return () => lines.filter((line) => line.includes('Security ['));
+ };
+ afterEach(() => vi.restoreAllMocks());
+
+ it('records the password lifecycle, sign-ins and failures — never the password', async () => {
+ const trail = captureTrail();
+ let app = await buildApp();
+ await request(app).post('/api/auth/password').send({ newPassword: 'correct-horse' });
+ app = await buildApp();
+ await request(app).post('/api/auth/login').send({ password: 'wrong-guess' });
+ await request(app).post('/api/auth/login').send({ password: 'correct-horse' });
+ await request(app).post('/api/auth/password').send({ newPassword: 'rotated-horse', currentPassword: 'correct-horse' });
+ await request(app).delete('/api/auth/password').send({ currentPassword: 'rotated-horse' });
+
+ const lines = trail();
+ expect(lines.map((l) => l.match(/Security \[([^\]]+)\]/)[1])).toEqual([
+ 'password.set', 'login.failed', 'login.ok', 'password.rotated', 'password.cleared',
+ ]);
+ expect(lines.find((l) => l.includes('login.failed'))).toMatch(/^⛔ .* ip=\S+/);
+ expect(lines.find((l) => l.includes('login.ok'))).toMatch(/^🔐 .* session=[a-f0-9]+/);
+ expect(lines.join('\n')).not.toMatch(/horse|wrong-guess/);
+ });
+
+ it('logs one throttle line when the failure window fills, not one per blocked request', async () => {
+ const trail = captureTrail();
+ let app = await buildApp();
+ await request(app).post('/api/auth/password').send({ newPassword: 'correct-horse' });
+ app = await buildApp();
+ for (let i = 0; i < 12; i++) await request(app).post('/api/auth/login').send({ password: `wrong-${i}` });
+
+ const lines = trail();
+ expect(lines.filter((l) => l.includes('login.failed'))).toHaveLength(10);
+ expect(lines.filter((l) => l.includes('login.throttled'))).toHaveLength(1);
+ });
+
+ it('records a refused host-control call with the caller and path', async () => {
+ const trail = captureTrail();
+ const app = await buildApp({ remoteAddress: '192.0.2.10' });
+ const refused = await request(app).post('/api/commands/execute').send({});
+ expect(refused.status).toBe(403);
+ const [line] = trail().filter((l) => l.includes('host-control.refused'));
+ expect(line).toMatch(/^⛔ /);
+ expect(line).toContain('path=/api/commands/execute');
+ expect(line).toContain('auth=none');
+ });
+});
+
describe('password-free risk status', () => {
it('enrolls existing installs without letting network callers acknowledge the warning', async () => {
let app = await buildApp();
diff --git a/server/services/authGate.js b/server/services/authGate.js
index 01bbe3895d..8efc7ae766 100644
--- a/server/services/authGate.js
+++ b/server/services/authGate.js
@@ -12,6 +12,7 @@ import {
isPeerBasicBootstrapRequest,
} from '../lib/apiAccessPolicy.js';
import { sendErrorResponse, ServerError } from '../lib/errorHandler.js';
+import { logSecurityEvent } from '../lib/securityAuditLog.js';
import {
changedHostControlSettingsPaths, hostControlBodyKeys, hostControlSettingsPathsIn, isHostControlRoute,
} from '../lib/hostControlRoutes.js';
@@ -149,6 +150,7 @@ export const authGate = async (req, res, next) => {
// endpoints like /api/auth/logout still mutate state.
const refusal = browserRequestRefusal(req);
if (refusal) {
+ logSecurityEvent('request.refused', { refused: true, code: refusal, ip: req.ip, method: req.method, path: req.path, origin: req.headers?.origin, host: req.headers?.host });
sendErrorResponse(res, browserRefusalError(refusal));
return;
}
@@ -251,6 +253,7 @@ export const socketHasCurrentHostControl = async (socket) => {
// Mount after authGate: missing context fails closed.
export const requireHostControl = (req, res, next) => {
if (requestHasHostControl(req)) return next();
+ logSecurityEvent('host-control.refused', { refused: true, ip: req.ip, method: req.method, path: req.originalUrl?.split('?')[0] ?? req.path, auth: req.portosAuthContext?.method ?? 'none' });
sendErrorResponse(res, new ServerError(HOST_CONTROL_FORBIDDEN_MESSAGE, {
status: 403, code: 'HOST_CONTROL_FORBIDDEN',
}));