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
feat: label auth sessions so an agent's loopback credential is visible and revocable (#7668)
[._.]/ Adam Eivy90fc2a8c93f7
diff --git a/client/src/components/settings/SecurityTab.jsx b/client/src/components/settings/SecurityTab.jsxindex c7439879ef..eb5ac2a153 100644--- a/client/src/components/settings/SecurityTab.jsx+++ b/client/src/components/settings/SecurityTab.jsx@@ -4,7 +4,8 @@ import toast from '../ui/Toast';import Banner from '../ui/Banner';import FormField from '../ui/FormField';import BrailleSpinner from '../BrailleSpinner';-import { getAuthStatus, setAuthPassword, clearAuthPassword } from '../../services/api';+import { getAuthStatus, setAuthPassword, clearAuthPassword, listAuthSessions, revokeAuthSession } from '../../services/api';+import { formatDateShort } from '../../utils/formatters';// PortOS is single-user and normally trusted because it's tailnet-only — auth// here is opt-in defense against an attacker on the same network (a sidecar@@ -23,6 +24,9 @@ export function SecurityTab() {const [disablePassword, setDisablePassword] = useState('');const [disabling, setDisabling] = useState(false);const statusRequestRef = useRef(0);+ const [agentSessions, setAgentSessions] = useState([]);+ const [revokingId, setRevokingId] = useState(null);+ const sessionsRequestRef = useRef(0);const loadAuthStatus = useCallback(() => {const requestId = ++statusRequestRef.current;@@ -50,6 +54,40 @@ export function SecurityTab() {loadAuthStatus();}, [loadAuthStatus]);+ // Sessions only exist while auth is on (agentApiAuth only mints a token+ // when isAuthEnabled(), and disabling clears every session) — skip the+ // fetch otherwise, and drop any list left over from a prior enabled state.+ useEffect(() => {+ if (!enabled) {+ setAgentSessions([]);+ return;+ }+ const requestId = ++sessionsRequestRef.current;+ listAuthSessions({ silent: true })+ .then((res) => {+ if (requestId !== sessionsRequestRef.current) return;+ const sessions = Array.isArray(res?.sessions) ? res.sessions : [];+ setAgentSessions(sessions.filter((s) => s?.label === 'agent'));+ })+ // Listing is a nice-to-have here — a failed fetch just hides the panel+ // rather than blocking the password form above it.+ .catch(() => {+ if (requestId === sessionsRequestRef.current) setAgentSessions([]);+ });+ }, [enabled]);++ const handleRevokeSession = async (id) => {+ setRevokingId(id);+ const result = await revokeAuthSession(id).catch((err) => err);+ setRevokingId(null);+ if (result instanceof Error) {+ toast.error(result.message || 'Revoke failed');+ return;+ }+ setAgentSessions((prev) => prev.filter((s) => s.id !== id));+ toast.success('Session revoked');+ };+const handleSubmit = async (event) => {event.preventDefault();if (saving) return;@@ -246,6 +284,38 @@ export function SecurityTab() {</div>)}</div>++ {enabled && agentSessions.length > 0 && (+ <div className="bg-port-card border border-port-border rounded-lg p-4 space-y-3">+ <h3 className="text-md font-semibold text-white">+ {agentSessions.length} agent session{agentSessions.length === 1 ? '' : 's'}+ </h3>+ <p className="text-sm text-gray-400">+ Loopback API credentials PortOS minted for spawned agents. Revoking one does not+ sign you out of the browser.+ </p>+ <ul className="space-y-2">+ {agentSessions.map((session) => (+ <li+ key={session.id}+ className="flex items-center justify-between gap-3 bg-port-bg border border-port-border rounded px-3 py-2"+ >+ <span className="text-sm text-gray-300">+ Agent session, expires {formatDateShort(session.expiresAt)}+ </span>+ <button+ type="button"+ onClick={() => handleRevokeSession(session.id)}+ disabled={revokingId === session.id}+ className="min-h-9 text-sm bg-port-bg border border-port-border text-port-error px-3 py-1.5 rounded hover:border-port-error disabled:opacity-50 disabled:cursor-not-allowed"+ >+ {revokingId === session.id ? 'Revoking…' : 'Revoke'}+ </button>+ </li>+ ))}+ </ul>+ </div>+ )}</div>);}diff --git a/client/src/components/settings/SecurityTab.test.jsx b/client/src/components/settings/SecurityTab.test.jsxindex aeacaca806..a9a681c7b0 100644--- a/client/src/components/settings/SecurityTab.test.jsx+++ b/client/src/components/settings/SecurityTab.test.jsx@@ -8,6 +8,8 @@ vi.mock('../../services/api', () => ({getAuthStatus: vi.fn(),setAuthPassword: vi.fn(),clearAuthPassword: vi.fn(),+ listAuthSessions: vi.fn(),+ revokeAuthSession: vi.fn(),}));vi.mock('../ui/Toast', () => ({@@ -30,6 +32,9 @@ const deferred = () => {describe('SecurityTab', () => {beforeEach(() => {vi.clearAllMocks();+ // Most tests don't exercise the sessions panel — default to an empty list+ // so the effect that fetches it doesn't reject unhandled in every test.+ api.listAuthSessions.mockResolvedValue({ sessions: [] });});afterEach(() => {@@ -98,6 +103,50 @@ describe('SecurityTab', () => {await waitFor(() => expect(api.getAuthStatus).toHaveBeenCalledTimes(2));});+ it('shows an agent session with a revoke button that does not touch the password form', async () => {+ api.getAuthStatus.mockResolvedValue({ enabled: true });+ api.listAuthSessions.mockResolvedValue({+ sessions: [+ { id: 'agent-1', label: 'agent', expiresAt: Date.parse('2026-10-01T00:00:00Z') },+ { id: 'browser-1', label: null, expiresAt: Date.parse('2026-10-01T00:00:00Z') },+ ],+ });++ render(<SecurityTab />);++ expect(await screen.findByText('1 agent session')).toBeInTheDocument();+ expect(screen.getByText(/Agent session, expires/)).toBeInTheDocument();+ // Only the labeled agent session gets a row — not the caller's own browser session.+ expect(screen.getAllByRole('button', { name: 'Revoke' })).toHaveLength(1);+ });++ it('revokes an agent session without signing the user out', async () => {+ api.getAuthStatus.mockResolvedValue({ enabled: true });+ api.listAuthSessions.mockResolvedValue({+ sessions: [{ id: 'agent-1', label: 'agent', expiresAt: Date.parse('2026-10-01T00:00:00Z') }],+ });+ api.revokeAuthSession.mockResolvedValue({ ok: true });++ render(<SecurityTab />);++ fireEvent.click(await screen.findByRole('button', { name: 'Revoke' }));++ await waitFor(() => expect(api.revokeAuthSession).toHaveBeenCalledWith('agent-1'));+ await waitFor(() => expect(screen.queryByText('1 agent session')).not.toBeInTheDocument());+ // Revoking is scoped to that one session — the password form stays intact.+ expect(screen.getByText('Login password enabled')).toBeInTheDocument();+ });++ it('hides the sessions panel when auth is disabled', async () => {+ api.getAuthStatus.mockResolvedValue({ enabled: false });++ render(<SecurityTab />);++ expect(await screen.findByText('Login password disabled')).toBeInTheDocument();+ expect(api.listAuthSessions).not.toHaveBeenCalled();+ expect(screen.queryByText(/agent session/)).not.toBeInTheDocument();+ });+it('ignores an obsolete failure when a newer StrictMode request succeeds', async () => {const firstRequest = deferred();const secondRequest = deferred();diff --git a/client/src/services/README.md b/client/src/services/README.mdindex 1ce8e24909..0c9983297d 100644--- a/client/src/services/README.md+++ b/client/src/services/README.md@@ -66,7 +66,7 @@ toasts on throw). **Custom catch ⇒ `silent: true`** — otherwise toasts fire| `apiQuotaBurn.js` | Quota Burn plan + live status, the job-type catalog its config form renders, and manual runs (`getQuotaBurn`/`getQuotaBurnCatalog`/`saveQuotaBurn`/`runQuotaBurn`), plus `rearmQuotaBurn` to put spent `run once` steps back into the rotation. || `apiRapidReader.js` | Rapid Reader's optional author-hosted Accelerando loader and machine-local shelf API. || `apiSystem.js` | System info (CPU/memory/ports/alerts/active processing and local hardware capabilities) + D&D-style character sheet getter, plus the usage cost report and explicit historical reconciliation (`getHourlyUsage` for dashboard hourly counters, `getUsage`, `getProviderUsage`, `getUsageBackfillStatus`/`startUsageBackfill`, `updateSubscriptionCosts` for the subscription-vs-API savings comparison, `getSubscriptions` / `updateSubscriptions` / `setSubscriptionEnabled` for the Subscriptions page's plan rows (PortOS-side enablement and plan-tier tracking only, never vendor billing), `updateUsageFleetBilling` to exclude an API-billed federated instance from Across Instances totals). Also `saveCredential` (write-only integration key save/clear) and `getCredentialInventory` (`GET /settings/credentials`) — presence and source of each PortOS credential, never a value. Also the Eidoverse world controls and its foundation ledger (`listEidoverseFoundations`, `recordEidoverseFoundation`, `packageEidoverseFoundationCandidate`, `promoteEidoverseFoundation`, `getEidoverseContributions`) — the last three answer 200 with a refusal verdict when a promote gate says no, so callers read `outcome` rather than catching. |-| `apiAuth.js` | Optional login password — status, login, set/clear password. |+| `apiAuth.js` | Optional login password — status, login, set/clear password, list/revoke sessions. || `apiLoops.js` | Scheduled loops. |## Personal data / identitydiff --git a/client/src/services/apiAuth.js b/client/src/services/apiAuth.jsindex 4c073d53ac..31178113ae 100644--- a/client/src/services/apiAuth.js+++ b/client/src/services/apiAuth.js@@ -21,3 +21,12 @@ export const clearAuthPassword = ({ currentPassword }) => request('/auth/passworbody: JSON.stringify({ currentPassword }),silent: true,});++// Lists live sessions (label + expiresAt only) for Settings → Security.+export const listAuthSessions = (options) => request('/auth/sessions', options);++// Revokes one session by its opaque id — e.g. the agent's loopback+// credential — without signing the caller's own browser session out.+export const revokeAuthSession = (id) => request(`/auth/sessions/${encodeURIComponent(id)}`, {+ method: 'DELETE',+});diff --git a/server/routes/auth.js b/server/routes/auth.jsindex e0fbf3479b..5de64f26ac 100644--- a/server/routes/auth.js+++ b/server/routes/auth.js@@ -10,8 +10,10 @@ import {getAuthStatus,isAuthEnabled,isLoginRateLimited,+ listSessions,recordLoginFailure,revokeSession,+ revokeSessionById,setPassword,verifyPassword,verifySession,@@ -27,6 +29,7 @@ const setPasswordSchema = z.object({currentPassword: z.string().max(256).optional(),}).strict();const clearPasswordSchema = z.object({ currentPassword: z.string().min(1).max(256) }).strict();+const sessionIdParamSchema = z.object({ id: z.string().min(1).max(64).regex(/^[a-f0-9]+$/) }).strict();// Whether the request reached us over HTTPS (so the cookie should carry the// Secure flag). `req.secure` reflects the actual socket; we don't trust@@ -120,4 +123,26 @@ router.delete('/password', asyncHandler(async (req, res) => {res.json({ enabled: false });}));+// GET /api/auth/sessions — list live sessions for Settings → Security. Gated+// exactly like the rest of /api/auth/* (not in the always-public set), so+// this only reveals anything to a caller who is already authenticated.+// Never returns the token or its hash — just what identifies a session on+// screen (label, expiry) and what addresses it for a scoped revoke (id).+router.get('/sessions', asyncHandler(async (_req, res) => {+ const sessions = await listSessions();+ res.json({ sessions, count: sessions.length });+}));++// DELETE /api/auth/sessions/:id — revoke exactly one session (e.g. the+// agent's loopback credential) without touching the caller's own browser+// session, unlike DELETE /api/auth/password (which revokes every session).+router.delete('/sessions/:id', asyncHandler(async (req, res) => {+ const { id } = validateRequest(sessionIdParamSchema, req.params);+ const revoked = await revokeSessionById(id);+ if (!revoked) {+ throw new ServerError('Session not found', { status: 404, code: 'AUTH_SESSION_NOT_FOUND' });+ }+ res.json({ ok: true });+}));+export default router;diff --git a/server/routes/auth.test.js b/server/routes/auth.test.jsindex 79c8030599..f20fa1beb3 100644--- a/server/routes/auth.test.js+++ b/server/routes/auth.test.js@@ -132,6 +132,48 @@ describe('auth routes', () => {expect(res.headers['set-cookie']).toMatch(/Max-Age=0/);});+ it('GET /api/auth/sessions lists live sessions without leaking the token', async () => {+ let app = await buildApp();+ const setupRes = await request(app).post('/api/auth/password').send({ newPassword: 'correct-horse' });+ const cookie = setupRes.headers['set-cookie'];++ app = await buildApp();+ const res = await request(app).get('/api/auth/sessions').set('Cookie', cookie);+ expect(res.status).toBe(200);+ expect(res.body.count).toBe(1);+ expect(res.body.sessions[0]).toEqual({ id: expect.any(String), label: null, expiresAt: expect.any(Number) });+ expect(JSON.stringify(res.body)).not.toMatch(/correct-horse/);+ });++ it('DELETE /api/auth/sessions/:id revokes only the targeted session', async () => {+ const app = await buildApp();+ const { createSession } = await import('../services/auth.js');+ const setupRes = await request(app).post('/api/auth/password').send({ newPassword: 'correct-horse' });+ const cookie = setupRes.headers['set-cookie'];+ const { id: agentId } = await createSession({ label: 'agent' });++ const listed = await request(app).get('/api/auth/sessions').set('Cookie', cookie);+ expect(listed.body.count).toBe(2);++ const revoke = await request(app).delete(`/api/auth/sessions/${agentId}`).set('Cookie', cookie);+ expect(revoke.status).toBe(200);+ expect(revoke.body).toEqual({ ok: true });++ // Revoking the agent session must not sign out the caller's own browser session.+ const after = await request(app).get('/api/auth/whoami').set('Cookie', cookie);+ expect(after.body.authenticated).toBe(true);++ const remaining = await request(app).get('/api/auth/sessions').set('Cookie', cookie);+ expect(remaining.body.count).toBe(1);+ });++ it('DELETE /api/auth/sessions/:id 404s on an id that matches no live session', async () => {+ const app = await buildApp();+ const res = await request(app).delete('/api/auth/sessions/deadbeefdeadbeef');+ expect(res.status).toBe(404);+ expect(res.body.code).toBe('AUTH_SESSION_NOT_FOUND');+ });+it('DELETE /api/auth/password requires the current password', async () => {let app = await buildApp();await request(app).post('/api/auth/password').send({ newPassword: 'correct-horse' });diff --git a/server/services/agentApiAuth.js b/server/services/agentApiAuth.jsindex 20f0a2006e..4db5f15cda 100644--- a/server/services/agentApiAuth.js+++ b/server/services/agentApiAuth.js@@ -69,7 +69,7 @@ export async function resolveAgentApiEnv({ safetyProfile = null } = {}) {if (isPublicReviewRestrictedProfile(safetyProfile)) return {};if (!await isAuthEnabled()) return {};if (await isUsable(cached)) return { [AGENT_API_TOKEN_ENV]: cached.token };- const minted = await minting.run(AGENT_API_TOKEN_ENV, () => createSession()+ const minted = await minting.run(AGENT_API_TOKEN_ENV, () => createSession({ label: 'agent' }).then(({ token, expiresAt }) => {cached = { token, expiresAt };return cached;diff --git a/server/services/auth.js b/server/services/auth.jsindex ec1b20e21f..320148a4d3 100644--- a/server/services/auth.js+++ b/server/services/auth.js@@ -45,13 +45,25 @@ const SESSIONS_FILE = join(PATHS.data, 'auth-sessions.json');// laggy when a sibling tab needs to log out.const KICK_DELAY_MS = 500;-// 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.+// Bytes for the opaque per-session `id` exposed to callers (Settings UI,+// GET /api/auth/sessions). It addresses a session for display/scoped-revoke+// without ever exposing `tokenHash` — a cheap unguessable label, not a+// crypto primitive shared with sidecars, so it stays local to this module.+const SESSION_ID_BYTES = 8;++// In-memory session store. Keyed by `sha256(token)` → { expiresAt, label, id }.+// 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.+//+// `label` is a free-text marker (`null` for an ordinary browser session,+// `'agent'` for a PortOS-spawned agent's loopback credential) — display and+// scoped-revocation only, never an authorization dimension. `id` is an+// opaque per-session handle so a caller can address one record without ever+// seeing `tokenHash`.const sessions = new Map();// Single in-flight load promise — both callers await the SAME promise so a// burst of concurrent verifySession calls after a restart can't observe an@@ -71,14 +83,21 @@ const readSessions = async () => {// a record missing `tokenHash` is corrupted, not legacy.if (typeof entry?.tokenHash !== 'string' || typeof entry.expiresAt !== 'number') continue;if (entry.expiresAt <= cutoff) continue;- sessions.set(entry.tokenHash, { expiresAt: entry.expiresAt });+ // `label` and `id` were added after the initial ship — a record from an+ // older install (or one an older install just wrote back) lacks them.+ // Missing/unknown values must not invalidate the record: default the+ // label to an ordinary (unlabeled) session and mint a fresh id so the+ // session is still addressable this run.+ const label = typeof entry.label === 'string' ? entry.label : null;+ const id = typeof entry.id === 'string' ? entry.id : randomBytes(SESSION_ID_BYTES).toString('hex');+ sessions.set(entry.tokenHash, { expiresAt: entry.expiresAt, label, id });}};const writeSessions = async () => {const tokens = [];- for (const [tokenHash, { expiresAt }] of sessions) {- tokens.push({ tokenHash, expiresAt });+ for (const [tokenHash, { expiresAt, label, id }] of sessions) {+ tokens.push({ tokenHash, expiresAt, label, id });}await atomicWrite(SESSIONS_FILE, JSON.stringify({ tokens }, null, 2) + '\n');};@@ -214,13 +233,45 @@ export const verifyPassword = async (password) => {return constantEqual(candidate, auth.passwordHash);};-export const createSession = async () => {+// `label` is `null` for an ordinary browser session; the agent loopback+// credential (server/services/agentApiAuth.js) passes `'agent'`.+export const createSession = async ({ label = null } = {}) => {await ensureLoaded();const token = randomBytes(TOKEN_BYTES).toString('hex');const expiresAt = now() + SESSION_TTL_MS;- sessions.set(hashToken(token), { expiresAt });+ const id = randomBytes(SESSION_ID_BYTES).toString('hex');+ sessions.set(hashToken(token), { expiresAt, label, id });await writeSessions();- return { token, expiresAt, maxAgeMs: SESSION_TTL_MS };+ return { token, expiresAt, maxAgeMs: SESSION_TTL_MS, id };+};++// Read-only listing for Settings → Security. Never returns `tokenHash` — an+// `id` is the only handle a caller gets for a scoped revoke.+export const listSessions = async () => {+ await ensureLoaded();+ const cutoff = now();+ const list = [];+ for (const { expiresAt, label, id } of sessions.values()) {+ if (expiresAt <= cutoff) continue;+ list.push({ id, label, expiresAt });+ }+ return list;+};++// Revoke exactly one session by its opaque id — e.g. the agent's loopback+// credential — without touching any other live session (unlike+// `revokeSession`/`revokeAllSessions`, this does not kick connected sockets:+// the sessions this addresses are non-interactive API credentials, not+// browser tabs). Returns whether a matching session was found.+export const revokeSessionById = async (id) => {+ await ensureLoaded();+ for (const [tokenHash, entry] of sessions) {+ if (entry.id !== id) continue;+ sessions.delete(tokenHash);+ await writeSessions();+ return true;+ }+ return false;};export const verifySession = async (token) => {diff --git a/server/services/auth.test.js b/server/services/auth.test.jsindex 302a00801b..0f2f4b3b89 100644--- a/server/services/auth.test.js+++ b/server/services/auth.test.js@@ -127,6 +127,58 @@ describe('auth service', () => {expect(await auth.verifySession(token)).toBe(false);});+ it('lists sessions with their label and expiry but never the token or its hash', async () => {+ const auth = await import('./auth.js');+ const { token: setupToken } = await auth.setPassword({ newPassword: 'correct-horse' });+ const { token: agentToken, id } = await auth.createSession({ label: 'agent' });++ const sessions = await auth.listSessions();+ expect(sessions).toHaveLength(2);+ const agentEntry = sessions.find((s) => s.id === id);+ expect(agentEntry).toEqual({ id, label: 'agent', expiresAt: expect.any(Number) });+ expect(JSON.stringify(sessions)).not.toContain(agentToken);+ expect(JSON.stringify(sessions)).not.toContain(setupToken);+ // The un-labeled browser session from setPassword() is listed too.+ expect(sessions.some((s) => s.label === null)).toBe(true);+ });++ it('revokes a session by its opaque id without touching any other session', async () => {+ const auth = await import('./auth.js');+ await auth.setPassword({ newPassword: 'correct-horse' });+ const { token: browserToken } = await auth.createSession();+ const { token: agentToken, id: agentId } = await auth.createSession({ label: 'agent' });++ expect(await auth.revokeSessionById(agentId)).toBe(true);+ expect(await auth.verifySession(agentToken)).toBe(false);+ expect(await auth.verifySession(browserToken)).toBe(true);+ });++ it('returns false revoking an id that does not match any live session', async () => {+ const auth = await import('./auth.js');+ await auth.setPassword({ newPassword: 'correct-horse' });+ expect(await auth.revokeSessionById('not-a-real-id')).toBe(false);+ });++ it('carries a missing label/id on an older record forward without invalidating it', async () => {+ const { readFileSync } = await import('fs');+ const auth = await import('./auth.js');+ await auth.setPassword({ newPassword: 'correct-horse' });+ const { token } = await auth.createSession();++ // Simulate a record written before `label`/`id` existed by stripping them+ // straight out of the persisted file, then reloading the module fresh.+ const sessionsPath = join(tempRoot, 'auth-sessions.json');+ const raw = JSON.parse(readFileSync(sessionsPath, 'utf8'));+ raw.tokens = raw.tokens.map(({ tokenHash, expiresAt }) => ({ tokenHash, expiresAt }));+ writeFileSync(sessionsPath, JSON.stringify(raw));++ vi.resetModules();+ const fresh = await import('./auth.js');+ expect(await fresh.verifySession(token)).toBe(true);+ const sessions = await fresh.listSessions();+ expect(sessions.find((s) => s.expiresAt === raw.tokens[0].expiresAt)).toMatchObject({ label: null });+ });+it('extracts the token from a cookie header and Authorization: Bearer', async () => {const auth = await import('./auth.js');expect(auth.parseCookieToken('portos_auth=abc123; other=x')).toBe('abc123');