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
add a revocable agent API key so terminal Claude/Codex sessions can call PortOS without the password
[._.]/ Adam Eivyda55e4e886b9
diff --git a/.claude/skills/portos-api/SKILL.md b/.claude/skills/portos-api/SKILL.mdnew file mode 100644index 0000000000..499cc22320--- /dev/null+++ b/.claude/skills/portos-api/SKILL.md@@ -0,0 +1,24 @@+---+name: portos-api+description: Call this machine's PortOS API from a Claude Code or Codex session PortOS did not spawn — create Chief of Staff tasks, run image generation, drive music video projects — without the instance password. Invoke before any curl or script against PortOS's own /api.+---++# Calling the PortOS API from an outside session++Use the bundled CLI. It finds the URL and credential itself:++```bash+node scripts/portos-api.js whoami+node scripts/portos-api.js task "<what the agent should do>" --app <app-id> --priority MEDIUM+node scripts/portos-api.js get /api/cos/tasks+node scripts/portos-api.js post /api/image-gen/generate '{"prompt":"..."}'+node scripts/portos-api.js post /api/music-video/autonomous @brief.json+node scripts/portos-api.js get /api/api-docs/catalog.json # discover endpoints+```++- Credential order: `PORTOS_API_TOKEN` (set inside PortOS-spawned agents), then `~/.portos/agent-key.json` (the agent API key).+- `whoami` answering `"authenticated": false`, or a `401 AUTH_REQUIRED`, means no key is available: ask the user to turn on **Settings > Security > Agent API key**. Never ask for, store, or type the instance password.+- Never print the token or paste it into a commit, PR, issue, or chat.+- Public Suno publication and social posting still need the human (root `AGENTS.md`, Security Model).++Details: [docs/AGENT_API_KEY.md](../../../docs/AGENT_API_KEY.md).diff --git a/AGENTS.md b/AGENTS.mdindex ff6d6acb13..c89dbbee18 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -55,6 +55,7 @@ A full-suite plan runs only the always-run guards unless `--full` is supplied. D**Authentication and HTTPS exist, but are OPT-IN and OFF by default.** Do not assume they are absent:- **Auth** — an optional instance password (`server/services/auth.js`, enforced by `server/services/authGate.js`) gates all of `/api/*` and `/data/*` when set, with a small always-public set (`/api/auth/status`, `/api/system/health`). Paired peers authenticate through scoped pair credentials attached by `peerFetch` (`server/lib/peerHttpClient.js`); legacy Basic compatibility uses the instance password and is not a scoped credential (see `docs/PEER_PUSH_AUTH.md`). **A PortOS-spawned agent authenticates with `PORTOS_API_TOKEN`** — a loopback session token the server mints and injects into the agent's environment (`server/services/agentApiAuth.js`). Any `curl` you write against this install's own API carries `-H "Authorization: Bearer ${PORTOS_API_TOKEN:-}"`; `401 AUTH_REQUIRED` means authentication was rejected; check for a missing, expired, or invalid token before diagnosing availability. The variable is empty when no password is set (the gate ignores it) and is never given to a public-content review stage.+- **Agent API key** — an agent PortOS did NOT spawn (a terminal Claude Code / Codex session on this machine) calls the API with `node scripts/portos-api.js …`, which spends `PORTOS_API_TOKEN` when set, else the opt-in key the server keeps in `~/.portos/agent-key.json` (Settings > Security). Never ask for or type the instance password. See [docs/AGENT_API_KEY.md](docs/AGENT_API_KEY.md) and the `portos-api` skill.- **HTTPS** — provisioned by `npm run setup:cert`; `:5555` flips to TLS with a loopback-only HTTP mirror on `:5553`. Peer hops set `rejectUnauthorized: false` ("Tailnet is the trust boundary"): between two tailnet nodes WireGuard supplies mutual auth, but a non-tailnet peer (plain LAN IP / non-`.ts.net` host, see `peerRequiresTailscale()`) gets no server authentication.Because both are off by default, **never treat "the password is set" as an available guarantee** — gate on it explicitly, or design for the default posture.diff --git a/client/src/components/settings/AgentKeyCard.jsx b/client/src/components/settings/AgentKeyCard.jsxnew file mode 100644index 0000000000..6a10f7806b--- /dev/null+++ b/client/src/components/settings/AgentKeyCard.jsx@@ -0,0 +1,91 @@+import { useEffect, useState } from 'react';+import { KeyRound } from 'lucide-react';+import toast from '../ui/Toast';+import { getAgentKeyStatus, setAgentKeyEnabled, rotateAgentKey } from '../../services/api';+import { formatDateShort } from '../../utils/formatters';++// The agent API key lets a Claude Code / Codex session on this computer call+// the PortOS API without the password: the server keeps a revocable session+// token in a file only this computer's user can read (server/services/agentKey.js).+export default function AgentKeyCard() {+ const [status, setStatus] = useState(null);+ const [busy, setBusy] = useState(null);++ useEffect(() => {+ let cancelled = false;+ getAgentKeyStatus({ silent: true })+ .then((res) => { if (!cancelled) setStatus(res); })+ .catch(() => { if (!cancelled) setStatus(null); });+ return () => { cancelled = true; };+ }, []);++ const run = async (action, call, successMessage) => {+ setBusy(action);+ const result = await call().catch((err) => err);+ setBusy(null);+ if (result instanceof Error) {+ toast.error(result.message || 'Agent key update failed');+ return;+ }+ setStatus(result);+ toast.success(successMessage);+ };++ if (!status) return null;++ const buttonClass = 'min-h-11 px-3 py-2 rounded text-sm disabled:opacity-50 disabled:cursor-not-allowed';++ return (+ <div className="bg-port-card border border-port-border rounded-lg p-4 space-y-3">+ <h3 className="text-md font-semibold text-white flex items-center gap-2">+ <KeyRound className="w-4 h-4" /> Agent API key {status.enabled ? 'on' : 'off'}+ </h3>+ <p className="text-sm text-gray-400">+ Lets AI agents on this computer call PortOS without your password.+ </p>+ {status.enabled && (+ <dl className="text-sm grid grid-cols-[auto_1fr] gap-x-3 gap-y-1 min-w-0">+ <dt className="text-gray-500">File</dt>+ <dd className="text-gray-300 font-mono break-all">{status.path}</dd>+ {status.expiresAt && (+ <>+ <dt className="text-gray-500">Renews</dt>+ <dd className="text-gray-300">automatically, before {formatDateShort(status.expiresAt)}</dd>+ </>+ )}+ </dl>+ )}+ <div className="flex flex-wrap gap-2">+ {status.enabled ? (+ <>+ <button+ type="button"+ onClick={() => run('rotate', rotateAgentKey, 'New agent key written')}+ disabled={!!busy}+ className={`${buttonClass} bg-port-bg border border-port-border text-gray-300 hover:border-port-accent`}+ >+ {busy === 'rotate' ? 'Rotating…' : 'Rotate'}+ </button>+ <button+ type="button"+ onClick={() => run('off', () => setAgentKeyEnabled(false), 'Agent key revoked')}+ disabled={!!busy}+ className={`${buttonClass} bg-port-bg border border-port-border text-port-error hover:border-port-error`}+ >+ {busy === 'off' ? 'Revoking…' : 'Turn off and revoke'}+ </button>+ </>+ ) : (+ <button+ type="button"+ onClick={() => run('on', () => setAgentKeyEnabled(true), 'Agent key turned on')}+ disabled={!!busy}+ className={`${buttonClass} bg-port-accent text-white font-medium hover:opacity-90`}+ >+ {busy === 'on' ? 'Turning on…' : 'Turn on'}+ </button>+ )}+ </div>+ </div>+ );+}diff --git a/client/src/components/settings/SecurityTab.jsx b/client/src/components/settings/SecurityTab.jsxindex aa1eca8336..d4b78792b6 100644--- a/client/src/components/settings/SecurityTab.jsx+++ b/client/src/components/settings/SecurityTab.jsx@@ -4,6 +4,7 @@ import toast from '../ui/Toast';import Banner from '../ui/Banner';import FormField from '../ui/FormField';import BrailleSpinner from '../BrailleSpinner';+import AgentKeyCard from './AgentKeyCard';import { getAuthStatus, setAuthPassword, clearAuthPassword, listAuthSessions, revokeAuthSession } from '../../services/api';import { formatDateShort } from '../../utils/formatters';@@ -294,6 +295,8 @@ export function SecurityTab() {)}</div>+ {enabled && <AgentKeyCard />}+{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">diff --git a/client/src/components/settings/SecurityTab.test.jsx b/client/src/components/settings/SecurityTab.test.jsxindex b792256c51..f0aa116e37 100644--- a/client/src/components/settings/SecurityTab.test.jsx+++ b/client/src/components/settings/SecurityTab.test.jsx@@ -10,6 +10,9 @@ vi.mock('../../services/api', () => ({clearAuthPassword: vi.fn(),listAuthSessions: vi.fn(),revokeAuthSession: vi.fn(),+ getAgentKeyStatus: vi.fn(),+ setAgentKeyEnabled: vi.fn(),+ rotateAgentKey: vi.fn(),}));vi.mock('../ui/Toast', () => ({@@ -35,6 +38,35 @@ describe('SecurityTab', () => {// 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: [] });+ api.getAgentKeyStatus.mockResolvedValue({ enabled: false, authEnabled: true, path: '~/.portos/agent-key.json', active: false, expiresAt: null });+ });++ it('turns the agent API key on and off from the Security tab', async () => {+ api.getAuthStatus.mockResolvedValue({ enabled: true });+ api.setAgentKeyEnabled.mockImplementation(async (on) => ({+ enabled: on, authEnabled: true, path: '~/.portos/agent-key.json', active: on, expiresAt: on ? Date.now() + 86_400_000 : null,+ }));++ render(<SecurityTab />);++ fireEvent.click(await screen.findByRole('button', { name: 'Turn on' }));+ expect(await screen.findByText('Agent API key on')).toBeInTheDocument();+ expect(screen.getByText('~/.portos/agent-key.json')).toBeInTheDocument();+ expect(api.setAgentKeyEnabled).toHaveBeenCalledWith(true);++ fireEvent.click(screen.getByRole('button', { name: 'Turn off and revoke' }));+ expect(await screen.findByText('Agent API key off')).toBeInTheDocument();+ expect(api.setAgentKeyEnabled).toHaveBeenLastCalledWith(false);+ });++ it('hides the agent API key card while no password is set', async () => {+ api.getAuthStatus.mockResolvedValue({ enabled: false });++ render(<SecurityTab />);++ expect(await screen.findByText('Login password disabled')).toBeInTheDocument();+ expect(screen.queryByText(/Agent API key/)).not.toBeInTheDocument();+ expect(api.getAgentKeyStatus).not.toHaveBeenCalled();});afterEach(() => {diff --git a/client/src/services/apiAuth.js b/client/src/services/apiAuth.jsindex cf8516bc9b..dd2b3226da 100644--- a/client/src/services/apiAuth.js+++ b/client/src/services/apiAuth.js@@ -34,3 +34,17 @@ export const revokeAuthSession = (id, options) => request(`/auth/sessions/${encosilent: true,...options,});++// Agent API key (Settings → Security): state only, never the token itself.+export const getAgentKeyStatus = (options) => request('/auth/agent-key', options);++export const setAgentKeyEnabled = (enabled) => request('/auth/agent-key', {+ method: 'PUT',+ body: JSON.stringify({ enabled }),+ silent: true,+});++export const rotateAgentKey = () => request('/auth/agent-key/rotate', {+ method: 'POST',+ silent: true,+});diff --git a/docs/AGENT_API_KEY.md b/docs/AGENT_API_KEY.mdnew file mode 100644index 0000000000..8cb3894a7d--- /dev/null+++ b/docs/AGENT_API_KEY.md@@ -0,0 +1,54 @@+# Agent API key++Lets an AI agent that PortOS did **not** spawn — a Claude Code or Codex session you run in a terminal on the PortOS machine — call the PortOS API without the instance password. Agents PortOS spawns already get `PORTOS_API_TOKEN` injected (`server/services/agentApiAuth.js`) and need nothing here.++## Turning it on++**Settings > Security > Agent API key > Turn on.** The card appears once a login password is set; without a password the API needs no credential.++While on, the server keeps one session token (label `agent-key`) in `~/.portos/agent-key.json`, with the file at mode `0600` and its directory at `0700`:++```json+{+ "version": 1,+ "url": "http://127.0.0.1:5553",+ "token": "<session token>",+ "sessionId": "<opaque id>",+ "expiresAt": "<ISO time>",+ "cli": "<repo-root>/scripts/portos-api.js",+ "usage": "Send \"Authorization: Bearer <token>\" to url. ..."+}+```++`url` is the loopback origin for this install: the HTTP mirror on `:5553` when HTTPS is on, else `:5555`. Set `PORTOS_AGENT_KEY_FILE` (for both the server and the CLI) to use another path, for example when two installs share one home directory.++The server re-mints the key a week before its 30-day session expires (checked at boot and daily), and right after a password change or log-out-everywhere drops every session. **Rotate** replaces it on demand. **Turn off and revoke** revokes the session and deletes the file.++## Calling the API++```bash+node <repo-root>/scripts/portos-api.js whoami+node <repo-root>/scripts/portos-api.js task "Fix the flaky upload test" --app portos --priority HIGH+node <repo-root>/scripts/portos-api.js get /api/cos/tasks+node <repo-root>/scripts/portos-api.js post /api/image-gen/generate '{"prompt":"a lighthouse at dusk"}'+node <repo-root>/scripts/portos-api.js post /api/music-video/autonomous @brief.json+node <repo-root>/scripts/portos-api.js get /api/api-docs/catalog.json+```++`npm run --silent api -- <args>` from the repo root is the same command. Bodies can be inline JSON, `@file`, or `-` for stdin. A path without `/api/` or `/data/` gets `/api` prepended. Output is the response body; a non-2xx exits 1 with the body on stderr.++`PORTOS_API_TOKEN` and `PORTOS_URL`, when set, win over the key file, so the same command works inside a PortOS-spawned agent.++Plain `curl` works too:++```bash+curl -sS "$(jq -r .url ~/.portos/agent-key.json)/api/cos/tasks" \+ -H "Authorization: Bearer $(jq -r .token ~/.portos/agent-key.json)"+```++## Security model++- The key is a session token, never the password. It carries the same operator authority as a signed-in browser or a PortOS-spawned agent, and the request audit identity names it as the `agent-key` session.+- Holding the token is the only thing that grants it. Requests are never trusted for arriving on loopback: Tailscale serve and the dev proxy both deliver remote traffic to `127.0.0.1`.+- Anything that can read a `0600` file in the host user's home already runs as that user and could mint a session from `data/auth-sessions.json`, so the file widens no boundary. It lives outside `data/` so backups and peer sync never carry the plaintext token (`auth-sessions.json` stores hashes only).+- The on/off flag lives under `secrets.agentKey` in `settings.json`, out of reach of the generic settings GET/PUT. `PUT /api/auth/agent-key` and `POST /api/auth/agent-key/rotate` are on the host-control list (`server/lib/hostControlRoutes.js`). `GET /api/auth/agent-key` reports state and never the token.diff --git a/docs/README.md b/docs/README.mdindex a4350f15fa..72001a8d31 100644--- a/docs/README.md+++ b/docs/README.md@@ -88,6 +88,8 @@ Comms & voice: [beeper](./features/beeper.md) · [messages-browser-send](./featu- [Local managed-app visitor broker](features/managed-visitors.md) — opt-in credential provisioning, versioned nonhumanoid scope and host negotiation.+- [Agent API key](./AGENT_API_KEY.md) — opt-in local credential and `scripts/portos-api.js` CLI for agents PortOS did not spawn.+- [Peer push authentication](./PEER_PUSH_AUTH.md)- [Tool-free model delegation](SANDBOX_DELEGATION.md) — approved API workers, context packets, and advisory fidelity evaluation for Persistent Mind.diff --git a/lib/agentKeyFile.js b/lib/agentKeyFile.jsnew file mode 100644index 0000000000..9d5551955b--- /dev/null+++ b/lib/agentKeyFile.js@@ -0,0 +1,34 @@+/**+ * Where the local agent API key lives on disk, shared by the server that writes+ * it (`server/services/agentKey.js`) and the CLI that spends it+ * (`scripts/portos-api.js`).+ *+ * The key is for agents PortOS did NOT spawn — a Claude Code / Codex session the+ * operator runs in a terminal on the same machine. PortOS-spawned agents already+ * get `PORTOS_API_TOKEN` injected (`server/services/agentApiAuth.js`); an outside+ * session has no environment to inherit, so the server keeps a session token in a+ * file only the host user can read, and the session reads it from there.+ *+ * Outside `data/` on purpose: `data/` is backed up and mirrored, and+ * `auth-sessions.json` stores only token hashes so a copy of it is never a+ * credential. This file holds the plaintext token, so it stays in the user's+ * home directory with mode 0600 and never travels.+ *+ * Builtins only — the CLI must load from a bare checkout.+ */++import { homedir } from 'os';+import { join } from 'path';++export const AGENT_KEY_FILE_ENV = 'PORTOS_AGENT_KEY_FILE';++/** The key file path: `$PORTOS_AGENT_KEY_FILE`, else `~/.portos/agent-key.json`. */+export const resolveAgentKeyFile = (env = process.env) => (+ env[AGENT_KEY_FILE_ENV] || join(homedir(), '.portos', 'agent-key.json')+);++/** The same path for display, with the home directory shown as `~`. */+export const displayAgentKeyFile = (path) => {+ const home = homedir();+ return home && path.startsWith(`${home}/`) ? `~${path.slice(home.length)}` : path;+};diff --git a/package.json b/package.jsonindex a5274ee92e..4f60ade1c7 100644--- a/package.json+++ b/package.json@@ -11,6 +11,7 @@"npm": ">=11.11.0"},"scripts": {+ "api": "node scripts/portos-api.js","dev": "node scripts/checkNodeVersion.js && node scripts/checkNpmVersion.js && node scripts/dev-start.js","dev:stop": "node ./node_modules/pm2/bin/pm2 stop ecosystem.config.cjs","eval:agent-context": "node scripts/agent-context-eval.js",diff --git a/scripts/portos-api.js b/scripts/portos-api.jsnew file mode 100644index 0000000000..ab5fff0f60--- /dev/null+++ b/scripts/portos-api.js@@ -0,0 +1,157 @@+#!/usr/bin/env node+/**+ * portos-api — call this machine's PortOS API from an agent PortOS did not+ * spawn (a Claude Code or Codex session in a terminal), without the password.+ *+ * node scripts/portos-api.js whoami+ * node scripts/portos-api.js get /api/cos/tasks+ * node scripts/portos-api.js post /api/image-gen/generate '{"prompt":"a lighthouse at dusk"}'+ * node scripts/portos-api.js post /api/music-video/autonomous @brief.json+ * echo '{"description":"…"}' | node scripts/portos-api.js post /api/cos/tasks -+ * node scripts/portos-api.js task "Fix the flaky upload test" --app portos --priority HIGH+ *+ * Credentials, first match wins:+ * 1. `PORTOS_API_TOKEN` — what PortOS injects into the agents it spawns+ * 2. the agent API key file the server keeps when Settings > Security >+ * Agent API key is on (`~/.portos/agent-key.json`, or+ * `$PORTOS_AGENT_KEY_FILE`; see lib/agentKeyFile.js)+ * The base URL is `$PORTOS_URL`, else the key file's `url`, else+ * http://127.0.0.1:5555. A path without a leading `/api/` or `/data/` gets+ * `/api` prepended. The response body goes to stdout (JSON pretty-printed);+ * a non-2xx status exits 1 with the body on stderr.+ *+ * Builtins only, so it runs from any checkout without `npm install`.+ */++import { readFile } from 'node:fs/promises';+import { resolveAgentKeyFile } from '../lib/agentKeyFile.js';+import { isDirectlyInvoked } from './lib/directInvocation.js';++const DEFAULT_URL = 'http://127.0.0.1:5555';+const METHODS = new Set(['get', 'post', 'put', 'patch', 'delete']);+const PRIORITIES = new Set(['LOW', 'MEDIUM', 'HIGH', 'CRITICAL']);++export const USAGE = `Usage:+ portos-api whoami+ portos-api <get|post|put|patch|delete> <path> [json | @file | -]+ portos-api task "<description>" [--app <id>] [--priority LOW|MEDIUM|HIGH|CRITICAL] [--context "<note>"]++Discover endpoints: portos-api get /api/api-docs/catalog.json`;++/** `/cos/tasks` → `/api/cos/tasks`; `/api/...` and `/data/...` pass through. */+export const normalizePath = (path) => {+ const withSlash = path.startsWith('/') ? path : `/${path}`;+ return /^\/(api|data)(\/|$)/.test(withSlash) ? withSlash : `/api${withSlash}`;+};++/** Pull `--flag value` pairs out of argv; everything else stays positional. */+const splitFlags = (args) => {+ const flags = {};+ const positional = [];+ for (let i = 0; i < args.length; i += 1) {+ const arg = args[i];+ if (arg.startsWith('--')) {+ if (i + 1 >= args.length) throw new Error(`${arg} needs a value`);+ flags[arg.slice(2)] = args[i + 1];+ i += 1;+ } else {+ positional.push(arg);+ }+ }+ return { flags, positional };+};++/**+ * argv (after `node script`) → `{ method, path, body }`, where `body` is a JSON+ * string, `{ file }`, `{ stdin: true }`, or null. Throws on anything it cannot+ * read.+ */+export const parseArgs = (argv) => {+ const [command, ...rest] = argv;+ if (!command || command === '--help' || command === '-h' || command === 'help') return { help: true };+ if (command === 'whoami') return { method: 'GET', path: '/api/auth/whoami', body: null };+ if (command === 'task') {+ const { flags, positional } = splitFlags(rest);+ const description = positional.join(' ').trim();+ if (!description) throw new Error('task needs a description');+ const task = { description };+ if (flags.app) task.app = flags.app;+ if (flags.context) task.context = flags.context;+ if (flags.priority) {+ const priority = flags.priority.toUpperCase();+ if (!PRIORITIES.has(priority)) throw new Error(`--priority must be one of ${[...PRIORITIES].join(', ')}`);+ task.priority = priority;+ }+ return { method: 'POST', path: '/api/cos/tasks', body: JSON.stringify(task) };+ }+ if (!METHODS.has(command.toLowerCase())) throw new Error(`Unknown command: ${command}`);+ const [path, payload] = rest;+ if (!path) throw new Error(`${command} needs a path`);+ let body = null;+ if (payload === '-') body = { stdin: true };+ else if (payload?.startsWith('@')) body = { file: payload.slice(1) };+ else if (payload !== undefined) body = payload;+ return { method: command.toUpperCase(), path: normalizePath(path), body };+};++/** `{ url, token }` from the environment and the key file (see header). */+export const resolveCredentials = async (env = process.env) => {+ const keyFile = await readFile(resolveAgentKeyFile(env), 'utf8')+ .then((raw) => JSON.parse(raw))+ .catch(() => null);+ const url = (env.PORTOS_URL || keyFile?.url || DEFAULT_URL).replace(/\/+$/, '');+ const token = env.PORTOS_API_TOKEN || (typeof keyFile?.token === 'string' ? keyFile.token : null);+ return { url, token };+};++const readStdin = async () => {+ const chunks = [];+ for await (const chunk of process.stdin) chunks.push(chunk);+ return Buffer.concat(chunks).toString('utf8');+};++const resolveBody = async (body) => {+ if (body === null) return null;+ const text = typeof body === 'string' ? body+ : body.stdin ? await readStdin()+ : await readFile(body.file, 'utf8');+ JSON.parse(text); // fail here with a clear message, not as a 400 from the server+ return text;+};++const main = async () => {+ const parsed = parseArgs(process.argv.slice(2));+ if (parsed.help) {+ console.log(USAGE);+ return 0;+ }+ const { url, token } = await resolveCredentials();+ const body = await resolveBody(parsed.body);+ const headers = { Accept: 'application/json' };+ if (token) headers.Authorization = `Bearer ${token}`;+ if (body !== null) headers['Content-Type'] = 'application/json';+ const res = await fetch(`${url}${parsed.path}`, { method: parsed.method, headers, body });+ const text = await res.text();+ let out = text;+ try { out = JSON.stringify(JSON.parse(text), null, 2); } catch { /* not JSON: print as-is */ }+ if (res.ok) {+ if (out) console.log(out);+ return 0;+ }+ console.error(`❌ ${parsed.method} ${parsed.path} → ${res.status}`);+ if (out) console.error(out);+ if (res.status === 401 && !token) {+ console.error('No credential found. Turn on Settings > Security > Agent API key in PortOS, or set PORTOS_API_TOKEN.');+ }+ return 1;+};++if (isDirectlyInvoked(import.meta.url)) {+ main()+ .then((code) => { process.exitCode = code; })+ .catch((err) => {+ console.error(`❌ ${err.message}`);+ if (/needs|Unknown command|must be/.test(err.message)) console.error(USAGE);+ process.exitCode = 1;+ });+}diff --git a/scripts/portos-api.test.js b/scripts/portos-api.test.jsnew file mode 100644index 0000000000..26e922e295--- /dev/null+++ b/scripts/portos-api.test.js@@ -0,0 +1,54 @@+/**+ * portos-api CLI: argv parsing (the part an agent gets wrong silently — a body+ * that never reaches the request, or a path missing its /api prefix) and which+ * credential wins when both the spawn env and the key file are present.+ */+import { describe, it, expect, afterEach } from 'vitest';+import { mkdtemp, rm, writeFile } from 'fs/promises';+import { tmpdir } from 'os';+import { join } from 'path';+import { parseArgs, resolveCredentials } from './portos-api.js';++describe('parseArgs', () => {+ it('builds a CoS task from the task shorthand', () => {+ const parsed = parseArgs(['task', 'Fix', 'the', 'upload', 'test', '--app', 'portos', '--priority', 'high']);+ expect(parsed).toMatchObject({ method: 'POST', path: '/api/cos/tasks' });+ expect(JSON.parse(parsed.body)).toEqual({ description: 'Fix the upload test', app: 'portos', priority: 'HIGH' });+ });++ it('prefixes /api, and reads inline, @file and stdin bodies', () => {+ expect(parseArgs(['get', 'cos/tasks'])).toEqual({ method: 'GET', path: '/api/cos/tasks', body: null });+ expect(parseArgs(['get', '/data/images/x.png']).path).toBe('/data/images/x.png');+ expect(parseArgs(['post', '/api/x', '{"a":1}']).body).toBe('{"a":1}');+ expect(parseArgs(['post', '/api/x', '@brief.json']).body).toEqual({ file: 'brief.json' });+ expect(parseArgs(['put', '/api/x', '-']).body).toEqual({ stdin: true });+ });++ it('rejects what it cannot send', () => {+ expect(() => parseArgs(['task'])).toThrow(/description/);+ expect(() => parseArgs(['task', 'x', '--priority', 'urgent'])).toThrow(/priority/);+ expect(() => parseArgs(['fetch', '/api/x'])).toThrow(/Unknown command/);+ expect(() => parseArgs(['post'])).toThrow(/needs a path/);+ });+});++describe('resolveCredentials', () => {+ let dir;+ afterEach(async () => { if (dir) await rm(dir, { recursive: true, force: true }); });++ it('reads the key file, with PORTOS_API_TOKEN and PORTOS_URL taking precedence', async () => {+ dir = await mkdtemp(join(tmpdir(), 'portos-api-cli-'));+ const file = join(dir, 'agent-key.json');+ await writeFile(file, JSON.stringify({ url: 'http://127.0.0.1:5553/', token: 'from-file' }));++ await expect(resolveCredentials({ PORTOS_AGENT_KEY_FILE: file }))+ .resolves.toEqual({ url: 'http://127.0.0.1:5553', token: 'from-file' });+ await expect(resolveCredentials({ PORTOS_AGENT_KEY_FILE: file, PORTOS_API_TOKEN: 'spawned', PORTOS_URL: 'http://127.0.0.1:9' }))+ .resolves.toEqual({ url: 'http://127.0.0.1:9', token: 'spawned' });+ });++ it('falls back to the default URL and no token without a key file', async () => {+ await expect(resolveCredentials({ PORTOS_AGENT_KEY_FILE: join(tmpdir(), 'portos-missing-key.json') }))+ .resolves.toEqual({ url: 'http://127.0.0.1:5555', token: null });+ });+});diff --git a/server/lib/hostControlRoutes.js b/server/lib/hostControlRoutes.jsindex 749511919c..973397b613 100644--- a/server/lib/hostControlRoutes.js+++ b/server/lib/hostControlRoutes.js@@ -129,6 +129,10 @@ export const HOST_CONTROL_ROUTES = Object.freeze([// Setting a password mints an operator session: bootstrap must be local,// and rotation must already hold operator authority (#8771).'POST /api/auth/password',+ // The agent API key writes an operator session token to the host user's+ // home directory (services/agentKey.js); enabling and rotating mint it.+ 'PUT /api/auth/agent-key',+ 'POST /api/auth/agent-key/rotate',// Generic runs accept arbitrary prompts/workspaces, including API-to-CLI fallback.'POST /api/runs',diff --git a/server/routes/auth.js b/server/routes/auth.jsindex 93be23b439..ce6c55fc68 100644--- a/server/routes/auth.js+++ b/server/routes/auth.js@@ -22,6 +22,7 @@ import {verifyRequestSession,verifySession,} from '../services/auth.js';+import { getAgentKeyStatus, rotateAgentKey, setAgentKeyEnabled } from '../services/agentKey.js';import { asyncHandler, ServerError } from '../lib/errorHandler.js';import { validateRequest } from '../lib/validation.js';@@ -188,4 +189,23 @@ router.delete('/sessions/:id', asyncHandler(async (req, res) => {res.json({ ok: true });}));+// Local agent API key (services/agentKey.js): a revocable session token kept in+// a mode-0600 file so an agent PortOS did not spawn can call the API. GET shows+// state only — never the token. Turning it on or rotating it mints an operator+// session, so both sit on the host-control list beside POST /password.+const agentKeyToggleSchema = z.object({ enabled: z.boolean() }).strict();++router.get('/agent-key', asyncHandler(async (_req, res) => {+ res.json(await getAgentKeyStatus());+}));++router.put('/agent-key', asyncHandler(async (req, res) => {+ const { enabled } = validateRequest(agentKeyToggleSchema, req.body || {});+ res.json(await setAgentKeyEnabled(enabled));+}));++router.post('/agent-key/rotate', asyncHandler(async (_req, res) => {+ res.json(await rotateAgentKey());+}));+export default router;diff --git a/server/services/agentKey.js b/server/services/agentKey.jsnew file mode 100644index 0000000000..2f46b5ba52--- /dev/null+++ b/server/services/agentKey.js@@ -0,0 +1,214 @@+/**+ * The local agent API key: a revocable session token PortOS keeps in a file+ * only the host user can read, so an agent PortOS did NOT spawn — a Claude Code+ * or Codex session the operator runs on this machine — can call the API without+ * the instance password.+ *+ * PortOS-spawned agents get `PORTOS_API_TOKEN` injected at spawn+ * (`agentApiAuth.js`). An outside session has no spawn to inherit from, and the+ * only other way to a session token is signing in with the password. This is+ * the same trust step `agentApiAuth.js` already takes: anything that can read a+ * mode-0600 file in the user's home directory runs as that user and could read+ * `auth-sessions.json` and mint a session itself. The key is never granted by+ * network position — loopback is not proof of locality (Tailscale serve and the+ * dev proxy both arrive on 127.0.0.1) — only by holding the token.+ *+ * Off by default; the operator turns it on in Settings > Security. While on,+ * the server keeps exactly one live `agent-key` session and the file current:+ * it re-mints a week before the 30-day session expires, and again after a+ * password rotation or log-out-everywhere drops every session. Turning it off+ * revokes the session and deletes the file. The flag lives under+ * `secrets.agentKey` so the generic settings GET/PUT never sees or sets it.+ */+import { chmod, mkdir, readFile, rename, rm, writeFile } from 'fs/promises';+import { dirname, join } from 'path';+import { fileURLToPath } from 'url';+import { randomBytes } from 'crypto';+import {+ authEvents,+ createSession,+ describeSession,+ isAuthEnabled,+ revokeSessionsByLabel,+} from './auth.js';+import { getSettings, settingsEvents, updateSettingsWith } from './settings.js';+import { PORTS } from '../lib/ports.js';+import { ServerError } from '../lib/errorHandler.js';+import { displayAgentKeyFile, resolveAgentKeyFile } from '../../lib/agentKeyFile.js';++export const AGENT_KEY_LABEL = 'agent-key';++// Re-mint with a week of life left, so a machine that sleeps for a few days+// never wakes to an expired key. Sessions live 30 days (SESSION_TTL_MS).+const REFRESH_MARGIN_MS = 7 * 24 * 60 * 60 * 1000;+const CHECK_INTERVAL_MS = 24 * 60 * 60 * 1000;++const CLI_PATH = join(dirname(fileURLToPath(import.meta.url)), '..', '..', 'scripts', 'portos-api.js');++let apiUrl = null;+let timer = null;+let listening = false;++const defaultApiUrl = () => `http://127.0.0.1:${Number(process.env.PORT) || PORTS.API}`;++const isKeyEnabled = async () => (await getSettings())?.secrets?.agentKey?.enabled === true;++const readKeyFile = async (path) => {+ const raw = await readFile(path, 'utf8').catch(() => null);+ if (raw === null) return null;+ try {+ const parsed = JSON.parse(raw);+ return parsed && typeof parsed === 'object' ? parsed : null;+ } catch {+ return null;+ }+};++// Write-then-rename so a reader never sees a half-written key, with the+// directory at 0700 and the file at 0600 before it ever holds the token.+const writeKeyFile = async (path, body) => {+ await mkdir(dirname(path), { recursive: true, mode: 0o700 });+ const tmp = `${path}.${randomBytes(6).toString('hex')}.tmp`;+ await writeFile(tmp, JSON.stringify(body, null, 2) + '\n', { mode: 0o600 });+ await chmod(tmp, 0o600);+ await rename(tmp, path);+};++const keyFileBody = ({ token, expiresAt, sessionId }) => ({+ version: 1,+ url: apiUrl || defaultApiUrl(),+ token,+ sessionId,+ expiresAt: expiresAt ? new Date(expiresAt).toISOString() : null,+ cli: CLI_PATH,+ usage: token+ ? 'Send "Authorization: Bearer <token>" to url. Revoke in PortOS Settings > Security.'+ : 'This install has no password set, so no token is needed.',+});++/** Whether the file's token is a live agent-key session with time to spare. */+const currentKey = async (file) => {+ if (typeof file?.token !== 'string' || file.url !== (apiUrl || defaultApiUrl())) return null;+ const session = await describeSession(file.token);+ if (session?.label !== AGENT_KEY_LABEL) return null;+ return session.expiresAt - Date.now() > REFRESH_MARGIN_MS ? session : null;+};++/**+ * Bring the file and the session store in line with the setting. Idempotent:+ * a key that is still current is left alone. `force` mints a new key even+ * when the current one is fine (Rotate).+ */+const reconcileOnce = async ({ force = false } = {}) => {+ const path = resolveAgentKeyFile();+ if (!await isKeyEnabled()) {+ await rm(path, { force: true });+ await revokeSessionsByLabel(AGENT_KEY_LABEL);+ return;+ }+ if (!await isAuthEnabled()) {+ // No password: the gate ignores credentials, so the file only tells a+ // session where the API is. Sessions were cleared when the password was.+ const file = await readKeyFile(path);+ if (file?.token !== null || file?.url !== (apiUrl || defaultApiUrl())) {+ await writeKeyFile(path, keyFileBody({ token: null }));+ }+ return;+ }+ if (!force && await currentKey(await readKeyFile(path))) return;+ const { token, expiresAt, id } = await createSession({ label: AGENT_KEY_LABEL });+ await writeKeyFile(path, keyFileBody({ token, expiresAt, sessionId: id }));+ // Only after the new key is on disk: exactly one live agent-key session.+ await revokeSessionsByLabel(AGENT_KEY_LABEL, { keepId: id });+ console.log(`🔑 Agent API key written to ${displayAgentKeyFile(path)}`);+};++// One reconcile at a time; triggers that land mid-run collapse into one rerun.+let running = null;+let rerun = false;+let rerunForce = false;+const reconcile = ({ force = false } = {}) => {+ if (running) {+ rerun = true;+ rerunForce ||= force;+ return running;+ }+ running = (async () => {+ let nextForce = force;+ do {+ rerun = false;+ await reconcileOnce({ force: nextForce });+ nextForce = rerunForce;+ rerunForce = false;+ } while (rerun);+ })().finally(() => { running = null; });+ return running;+};++const reconcileInBackground = (reason) => {+ reconcile().catch((err) => console.error(`❌ Agent API key refresh failed (${reason}): ${err.message}`));+};++/**+ * Boot hook. `localApiUrl` is the loopback origin this process serves the API+ * on (the HTTP mirror when HTTPS is on), written into the file for the CLI.+ */+export const initAgentKey = ({ localApiUrl } = {}) => {+ apiUrl = localApiUrl || defaultApiUrl();+ if (!listening) {+ listening = true;+ // Covers the flag itself, and a password being set or cleared.+ settingsEvents.on('settings:updated', () => reconcileInBackground('settings changed'));+ // A rotation or log-out-everywhere dropped the key's session with the rest.+ authEvents.on('sessions:revoked-all', () => reconcileInBackground('sessions revoked'));+ }+ if (!timer) {+ timer = setInterval(() => reconcileInBackground('daily check'), CHECK_INTERVAL_MS);+ timer.unref?.();+ }+ reconcileInBackground('boot');+};++/** What Settings > Security shows. Never includes the token. */+export const getAgentKeyStatus = async () => {+ const path = resolveAgentKeyFile();+ const [enabled, authEnabled, file] = await Promise.all([isKeyEnabled(), isAuthEnabled(), readKeyFile(path)]);+ const session = enabled && authEnabled && typeof file?.token === 'string' ? await describeSession(file.token) : null;+ return {+ enabled,+ authEnabled,+ path: displayAgentKeyFile(path),+ url: apiUrl || defaultApiUrl(),+ active: enabled && (authEnabled ? session?.label === AGENT_KEY_LABEL : !!file),+ expiresAt: session?.label === AGENT_KEY_LABEL ? session.expiresAt : null,+ };+};++export const setAgentKeyEnabled = async (enabled) => {+ await updateSettingsWith((current) => ({+ ...current,+ secrets: { ...(current.secrets || {}), agentKey: { enabled: !!enabled } },+ }));+ await reconcile();+ return getAgentKeyStatus();+};++export const rotateAgentKey = async () => {+ if (!await isKeyEnabled() || !await isAuthEnabled()) {+ throw new ServerError('Turn on the agent API key (with a login password set) before rotating it', {+ status: 409,+ code: 'AGENT_KEY_INACTIVE',+ });+ }+ await reconcile({ force: true });+ return getAgentKeyStatus();+};++export const __testing = {+ reconcile,+ reset: () => {+ if (timer) clearInterval(timer);+ timer = null;+ apiUrl = null;+ },+};diff --git a/server/services/agentKey.test.js b/server/services/agentKey.test.jsnew file mode 100644index 0000000000..9e188bad1a--- /dev/null+++ b/server/services/agentKey.test.js@@ -0,0 +1,133 @@+/**+ * The local agent API key: a plaintext session token in a file under the user's+ * home directory. What has to hold:+ * - off means no file and no live agent-key session (turning it off revokes);+ * - on means exactly one live agent-key session whose token is in the file,+ * the file mode 0600, and a still-current key is never re-minted;+ * - a key whose session was dropped (password rotation) or is about to+ * expire is replaced, and the old session revoked;+ * - the status the Settings UI reads never carries the token.+ */+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';+import { EventEmitter } from 'events';+import { mkdtemp, readFile, rm, stat } from 'fs/promises';+import { tmpdir } from 'os';+import { join } from 'path';++const sessions = new Map(); // token → { id, label, expiresAt }+let nextId = 0;+let authEnabled = true;+let settings = {};++vi.mock('./auth.js', () => ({+ authEvents: new EventEmitter(),+ isAuthEnabled: async () => authEnabled,+ createSession: async ({ label }) => {+ nextId += 1;+ const token = `tok-${nextId}`;+ const entry = { id: `id-${nextId}`, label, expiresAt: Date.now() + 30 * 86_400_000 };+ sessions.set(token, entry);+ return { token, expiresAt: entry.expiresAt, id: entry.id };+ },+ describeSession: async (token) => sessions.get(token) ?? null,+ revokeSessionsByLabel: async (label, { keepId = null } = {}) => {+ for (const [token, entry] of sessions) {+ if (entry.label === label && entry.id !== keepId) sessions.delete(token);+ }+ },+}));++vi.mock('./settings.js', () => ({+ settingsEvents: new EventEmitter(),+ getSettings: async () => settings,+ updateSettingsWith: async (mutate) => { settings = await mutate(settings); },+}));++const { AGENT_KEY_LABEL, getAgentKeyStatus, initAgentKey, rotateAgentKey, setAgentKeyEnabled, __testing } = await import('./agentKey.js');++const liveKeySessions = () => [...sessions.values()].filter((s) => s.label === AGENT_KEY_LABEL);++describe('agent API key', () => {+ let dir;+ let keyFile;++ beforeEach(async () => {+ dir = await mkdtemp(join(tmpdir(), 'portos-agent-key-'));+ keyFile = join(dir, 'nested', 'agent-key.json');+ vi.stubEnv('PORTOS_AGENT_KEY_FILE', keyFile);+ sessions.clear();+ nextId = 0;+ authEnabled = true;+ settings = {};+ __testing.reset();+ initAgentKey({ localApiUrl: 'http://127.0.0.1:5553' });+ await __testing.reconcile();+ });++ afterEach(async () => {+ __testing.reset();+ vi.unstubAllEnvs();+ await rm(dir, { recursive: true, force: true });+ });++ const readKey = async () => JSON.parse(await readFile(keyFile, 'utf8'));++ it('writes nothing while off', async () => {+ await expect(stat(keyFile)).rejects.toThrow();+ expect(liveKeySessions()).toHaveLength(0);+ expect(await getAgentKeyStatus()).toMatchObject({ enabled: false, active: false });+ });++ it('turning it on writes one live token to a 0600 file, and a current key is kept', async () => {+ await setAgentKeyEnabled(true);+ const key = await readKey();+ expect(key).toMatchObject({ url: 'http://127.0.0.1:5553', token: 'tok-1' });+ expect((await stat(keyFile)).mode & 0o777).toBe(0o600);+ expect(liveKeySessions()).toHaveLength(1);++ await __testing.reconcile();+ expect((await readKey()).token).toBe('tok-1');++ const status = await getAgentKeyStatus();+ expect(status).toMatchObject({ enabled: true, active: true });+ expect(JSON.stringify(status)).not.toContain('tok-1');+ });++ it('replaces a key whose session was revoked, e.g. by a password change', async () => {+ await setAgentKeyEnabled(true);+ sessions.clear();+ await __testing.reconcile();+ expect((await readKey()).token).toBe('tok-2');+ expect(liveKeySessions()).toHaveLength(1);+ });++ it('re-mints a key about to expire and revokes the old session', async () => {+ await setAgentKeyEnabled(true);+ sessions.get('tok-1').expiresAt = Date.now() + 86_400_000;+ await __testing.reconcile();+ expect((await readKey()).token).toBe('tok-2');+ expect(sessions.has('tok-1')).toBe(false);+ });++ it('rotate replaces a current key; turning off revokes it and deletes the file', async () => {+ await setAgentKeyEnabled(true);+ await rotateAgentKey();+ expect((await readKey()).token).toBe('tok-2');+ expect(liveKeySessions()).toHaveLength(1);++ await setAgentKeyEnabled(false);+ await expect(stat(keyFile)).rejects.toThrow();+ expect(liveKeySessions()).toHaveLength(0);+ });++ it('refuses to rotate while off', async () => {+ await expect(rotateAgentKey()).rejects.toMatchObject({ status: 409, code: 'AGENT_KEY_INACTIVE' });+ });++ it('writes no token on an install without a password', async () => {+ authEnabled = false;+ await setAgentKeyEnabled(true);+ expect(await readKey()).toMatchObject({ url: 'http://127.0.0.1:5553', token: null });+ expect(sessions.size).toBe(0);+ });+});diff --git a/server/services/auth.js b/server/services/auth.jsindex 4f07ccd080..bbb62f5ed4 100644--- a/server/services/auth.js+++ b/server/services/auth.js@@ -325,6 +325,30 @@ export const revokeSessionById = async (id) => {return false;};+// Revoke every session carrying `label` except the one addressed by `keepId`.+// The local agent key (services/agentKey.js) keeps exactly one live session:+// a rotation mints the replacement first, then drops the rest here. Like+// revokeSessionById, no socket kick — these are non-interactive credentials.+export const revokeSessionsByLabel = async (label, { keepId = null } = {}) => {+ await ensureLoaded();+ let removed = 0;+ for (const [tokenHash, entry] of sessions) {+ if (entry.label !== label || entry.id === keepId) continue;+ sessions.delete(tokenHash);+ removed += 1;+ }+ if (removed) await writeSessions();+ return removed;+};++// The live session a plaintext token addresses — `{ id, label, expiresAt }` —+// or null when the token does not verify. Never exposes `tokenHash`.+export const describeSession = async (token) => {+ if (!await verifySession(token)) return null;+ const entry = sessions.get(hashToken(token));+ return entry ? { id: entry.id, label: entry.label, expiresAt: entry.expiresAt } : null;+};+export const verifySession = async (token) => {if (typeof token !== 'string' || token.length === 0) return false;await ensureLoaded();diff --git a/server/services/bootstrap.js b/server/services/bootstrap.jsindex c18bdba38a..07a00e3504 100644--- a/server/services/bootstrap.js+++ b/server/services/bootstrap.js@@ -401,7 +401,14 @@ export const bootstrapServices = async ({ io, dataDir, dataReferenceDir, serverD* Fire-and-forget service inits + scheduler arming. None of these block the* server from listening; each logs its own failure and the boot continues.*/-const startBackgroundServices = ({ spawnerReady, io }) => {+const startBackgroundServices = ({ spawnerReady, io, localApiUrl }) => {+ // Keep the opt-in agent API key file current (Settings > Security). A no-op+ // beyond one settings read while the key is off. Disabled under smoke boot+ // with the rest of this function, so a smoke run never writes to $HOME.+ import('./agentKey.js')+ .then(({ initAgentKey }) => initAgentKey({ localApiUrl }))+ .catch((err) => logBootstrapFailure('❌ Agent API key init failed', err));+// Put npm's global bin directory on PATH before anything spawns a provider// CLI. npm's prefix need not be the directory the host's Node installer put// on PATH, and a CLI installed there is invisible to the bare-name spawn a@@ -912,7 +919,13 @@ const announceListening = ({ io, httpServer, localHttpServer, httpsEnabled, port*/export const runBootSequence = ({ io, httpServer, localHttpServer, httpsEnabled, port, host, spawnerReady }) =>runPostRouteSequence(gateStepsForSmokeBoot({- startBackgroundServices: () => startBackgroundServices({ spawnerReady, io }),+ startBackgroundServices: () => startBackgroundServices({+ spawnerReady,+ io,+ // Where a local CLI reaches this API: the loopback HTTP mirror when+ // :5555 speaks TLS (see announceListening), else :5555 itself.+ localApiUrl: `http://127.0.0.1:${httpsEnabled ? (Number(process.env.PORTOS_HTTP_PORT) || PORTS.API_LOCAL) : port}`,+ }),// Instance identity + sync log come up before requests are accepted, so a// brain mutation can't arrive before the sync log is ready.