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: add bounded peer administration planning (#10126)
[._.]/74f4533a1908
diff --git a/client/src/components/instances/PeerAdministrationPanel.jsx b/client/src/components/instances/PeerAdministrationPanel.jsxnew file mode 100644index 0000000000..e4891283a4--- /dev/null+++ b/client/src/components/instances/PeerAdministrationPanel.jsx@@ -0,0 +1,114 @@+import { useEffect, useState } from 'react';+import { getPeerAdminSetup, savePeerAdminGrant, previewPeerAdministration } from '../../services/api';+import ConfirmButtonPair from '../ui/ConfirmButtonPair';+import useMounted from '../../hooks/useMounted';+import { timeUntil } from '../../utils/formatters';++const LABELS = {+ 'portos.update': 'PortOS update',+ 'portos.restart': 'PortOS restart',+ 'catalog.install': 'Catalog model installation',+};++function Controls({ peer }) {+ const [expanded, setExpanded] = useState(false);+ const [setup, setSetup] = useState(null);+ const [busy, setBusy] = useState(false);+ const [confirmation, setConfirmation] = useState(null);+ const [error, setError] = useState('');+ const [preview, setPreview] = useState(null);+ const mounted = useMounted();++ useEffect(() => {+ if (!expanded) return;+ let active = true;+ setError('');+ getPeerAdminSetup(peer.id, { silent: true }).then(value => {+ if (active) setSetup(value);+ }).catch(err => { if (active) setError(err.message); });+ return () => { active = false; };+ }, [expanded, peer.id]);++ const save = async () => {+ if (busy || !confirmation || !setup) return;+ setBusy(true);+ setError('');+ const row = setup.actions.find(entry => entry.action === confirmation.action);+ try {+ const value = await savePeerAdminGrant({+ peerId: peer.id, action: row.action,+ confirmedHostInstanceId: setup.hostInstanceId, confirmedPeerInstanceId: setup.peerInstanceId,+ previousGrantId: row.grant?.id ?? null, expiresInMinutes: 60,+ allowPlanning: confirmation.allow,+ }, { silent: true });+ if (mounted.current) { setSetup(value); setConfirmation(null); }+ } catch (err) { if (mounted.current) setError(err.message); }+ finally { if (mounted.current) setBusy(false); }+ };++ const inspect = async action => {+ if (busy) return;+ setBusy(true);+ setError('');+ setPreview(null);+ try {+ const value = await previewPeerAdministration({ peerId: peer.id, intent: { action } }, { silent: true });+ if (mounted.current) setPreview(value);+ } catch (err) { if (mounted.current) setError(err.message); }+ finally { if (mounted.current) setBusy(false); }+ };++ return <section className="border-t border-port-border pt-3 mt-3 text-sm">+ <button type="button" aria-expanded={expanded} disabled={busy}+ className="min-h-[44px] text-port-accent" onClick={() => { setExpanded(value => !value); setSetup(null); setConfirmation(null); }}>+ Peer administration · planning only+ </button>+ {expanded && <div className="space-y-3">+ <p className="text-gray-400">Update, restart and model installation cannot execute in this version. Previews never queue work or interrupt active jobs. Execution needs the maintenance coordinator and a separate future permission.</p>+ {error && <p role="alert" className="text-port-error">{error}</p>}+ {setup && <>+ <p className="font-medium">Allow this peer to plan actions on this host</p>+ <dl className="text-xs text-gray-400 break-all">+ <dt>Receiving host identity</dt><dd>{setup.hostInstanceId || 'Not initialized'}</dd>+ <dt>Paired caller identity</dt><dd>{setup.peerInstanceId || 'Not paired'}</dd>+ </dl>+ {!setup.paired && <p className="text-port-warning">Enable and pair this peer locally before granting planning access.</p>}+ {setup.actions.map(row => <div key={row.action} className="flex flex-wrap items-center justify-between gap-2">+ <span>{LABELS[row.action]} — {row.active ? `Planning allowed · expires ${timeUntil(row.grant.expiresAt)}` : 'Denied'}</span>+ <div className="flex gap-2">+ <button type="button" disabled={busy || !setup.paired}+ className="min-h-[44px] text-port-accent disabled:opacity-50"+ onClick={() => setConfirmation({ action: row.action, allow: true })}>Review {row.active ? 'renewal' : 'grant'}</button>+ {row.grant?.allowed && <button type="button" disabled={busy}+ className="min-h-[44px] text-port-warning" onClick={() => setConfirmation({ action: row.action, allow: false })}>Revoke {LABELS[row.action]}</button>}+ </div>+ </div>)}+ {confirmation && <div className="rounded border border-port-border p-3 space-y-2">+ <p>{confirmation.allow ? 'Allow' : 'Revoke'} {LABELS[confirmation.action]} planning for the exact paired identity above on this host{confirmation.allow ? ' for one hour' : ''}. This does not authorize execution, accept model licenses, or install software.</p>+ <ConfirmButtonPair tone="warning" confirmText={confirmation.allow ? 'Allow planning for one hour' : 'Confirm revocation'}+ onConfirm={save} onCancel={() => setConfirmation(null)} busy={busy} />+ </div>}+ <div className="border-t border-port-border pt-3 space-y-2">+ <p className="font-medium">Preview requirements on the remote peer</p>+ <p className="text-gray-400">The receiving peer needs its own local planning grant for this host. A preview creates a short-lived plan receipt; it starts nothing.</p>+ <div className="flex flex-wrap gap-3">+ {['portos.update', 'portos.restart'].map(action => <button key={action} type="button" disabled={busy || !setup.paired}+ className="min-h-[44px] text-port-accent disabled:opacity-50" onClick={() => inspect(action)}>Preview {LABELS[action]}</button>)}+ </div>+ <p className="text-xs text-gray-400">Catalog install plans are API-only while the local source, license and destination checks are being integrated.</p>+ {preview && <div role="status" className="rounded bg-port-bg p-3 space-y-1 break-all">+ <p>Planned only · not queued · not in flight</p>+ <p>Request: {preview.plan.requestId}</p>+ <p>Verified peer version: {preview.preflight.version}</p>+ <p className="text-port-warning">Execution unavailable: an exclusive maintenance claim and completion reconciliation are required.</p>+ </div>}+ </div>+ </>}+ </div>}+ </section>;+}++export default function PeerAdministrationPanel({ peer }) {+ // Identity changes retire outstanding UI responses and confirmation state.+ return <Controls key={`${peer.id}:${peer.instanceId}:${peer.enabled}:${peer.hasSyncSecret}`} peer={peer} />;+}diff --git a/client/src/components/instances/PeerAdministrationPanel.test.jsx b/client/src/components/instances/PeerAdministrationPanel.test.jsxnew file mode 100644index 0000000000..8f8a98ec92--- /dev/null+++ b/client/src/components/instances/PeerAdministrationPanel.test.jsx@@ -0,0 +1,69 @@+import { fireEvent, render, screen, waitFor } from '@testing-library/react';+import { beforeEach, describe, expect, it, vi } from 'vitest';+import PeerAdministrationPanel from './PeerAdministrationPanel';+import { getPeerAdminSetup, savePeerAdminGrant, previewPeerAdministration } from '../../services/api';+vi.mock('../../services/api', () => ({+ getPeerAdminSetup: vi.fn(), savePeerAdminGrant: vi.fn(), previewPeerAdministration: vi.fn(),+}));+const peer = { id: 'peer-example', instanceId: '11111111-1111-4111-8111-111111111111', enabled: true, hasSyncSecret: true };+const setup = {+ hostInstanceId: '22222222-2222-4222-8222-222222222222', peerInstanceId: peer.instanceId,+ paired: true, executionSupported: false,+ actions: ['portos.update', 'portos.restart', 'catalog.install'].map(action => ({ action, active: false, grant: null })),+};+beforeEach(() => { vi.clearAllMocks(); getPeerAdminSetup.mockResolvedValue(setup); });++describe('planning-only peer administration', () => {+ it('requires review and explicit confirmation and binds the save to both displayed identities', async () => {+ savePeerAdminGrant.mockResolvedValue(setup);+ render(<PeerAdministrationPanel peer={peer} />);+ expect(getPeerAdminSetup).not.toHaveBeenCalled();+ fireEvent.click(screen.getByRole('button', { name: /Peer administration/ }));+ await screen.findByText(setup.hostInstanceId);+ fireEvent.click(screen.getAllByRole('button', { name: 'Review grant' })[0]);+ expect(savePeerAdminGrant).not.toHaveBeenCalled();+ expect(screen.getByText(/does not authorize execution/)).toBeTruthy();+ fireEvent.click(screen.getByRole('button', { name: 'Allow planning for one hour' }));+ await waitFor(() => expect(savePeerAdminGrant).toHaveBeenCalledWith({+ peerId: peer.id, action: 'portos.update', confirmedHostInstanceId: setup.hostInstanceId,+ confirmedPeerInstanceId: peer.instanceId, previousGrantId: null, expiresInMinutes: 60, allowPlanning: true,+ }, { silent: true }));+ });++ it('shows a preview as planned without offering execution', async () => {+ previewPeerAdministration.mockResolvedValue({ preflight: { version: '1.0.0' }, plan: { requestId: 'example-request' } });+ render(<PeerAdministrationPanel peer={peer} />);+ fireEvent.click(screen.getByRole('button', { name: /Peer administration/ }));+ fireEvent.click(await screen.findByRole('button', { name: 'Preview PortOS restart' }));+ expect(await screen.findByText('Planned only · not queued · not in flight')).toBeTruthy();+ expect(screen.queryByRole('button', { name: /^Restart|^Execute|^Install/ })).toBeNull();+ expect(savePeerAdminGrant).not.toHaveBeenCalled();+ });++ it('does not allow a grant save while reopening refreshes an older setup snapshot', async () => {+ let resolveRefresh;+ getPeerAdminSetup.mockResolvedValueOnce(setup).mockReturnValueOnce(new Promise(resolve => { resolveRefresh = resolve; }));+ render(<PeerAdministrationPanel peer={peer} />);+ const toggle = screen.getByRole('button', { name: /Peer administration/ });+ fireEvent.click(toggle);+ await screen.findByText(setup.hostInstanceId);+ fireEvent.click(toggle);+ fireEvent.click(toggle);+ expect(screen.queryByRole('button', { name: 'Review grant' })).toBeNull();+ expect(screen.queryByRole('button', { name: 'Allow planning for one hour' })).toBeNull();+ resolveRefresh(setup);+ await screen.findByText(setup.hostInstanceId);+ expect(savePeerAdminGrant).not.toHaveBeenCalled();+ });++ it('drops an old identity response and confirmation when the peer changes', async () => {+ let resolveOld;+ getPeerAdminSetup.mockReturnValueOnce(new Promise(resolve => { resolveOld = resolve; }));+ const view = render(<PeerAdministrationPanel peer={peer} />);+ fireEvent.click(screen.getByRole('button', { name: /Peer administration/ }));+ view.rerender(<PeerAdministrationPanel peer={{ ...peer, instanceId: '33333333-3333-4333-8333-333333333333' }} />);+ resolveOld(setup);+ await waitFor(() => expect(screen.queryByText(setup.hostInstanceId)).toBeNull());+ expect(savePeerAdminGrant).not.toHaveBeenCalled();+ });+});diff --git a/client/src/pages/Instances.jsx b/client/src/pages/Instances.jsxindex 937f83c096..757f6a0a1b 100644--- a/client/src/pages/Instances.jsx+++ b/client/src/pages/Instances.jsx@@ -35,6 +35,7 @@ import PeerAgentsSection from '../components/instances/PeerAgentsSection';import { SchemaGapBadge } from '../components/instances/SchemaGapBadge';import { DEFAULT_PEER_PORT, DEFAULT_TAILCAT_LOCAL_PORT, DEFAULT_TAILCAT_REMOTE_PORT } from '../lib/ports.js';import PeerMediaProviderPanel from '../components/instances/PeerMediaProviderPanel';+import PeerAdministrationPanel from '../components/instances/PeerAdministrationPanel';import UnattendedRenderRouting from '../components/instances/UnattendedRenderRouting';import BrainParityPanel from '../components/instances/BrainParityPanel';import BrainParitySchedule from '../components/instances/BrainParitySchedule';@@ -1525,6 +1526,7 @@ export function PeerCard({ peer, onRefresh, syncStatus, tailnetInfo, parityRepor<SchemaGapBadge peer={peer} peerSubs={peerSubs} /><PeerMediaProviderPanel peer={peer} onRefresh={onRefresh} />+ <PeerAdministrationPanel peer={peer} /><SyncCategoriesPanel peer={peer} onRefresh={onRefresh} />diff --git a/client/src/services/apiSystem.js b/client/src/services/apiSystem.jsindex a93ffcef85..9497785391 100644--- a/client/src/services/apiSystem.js+++ b/client/src/services/apiSystem.js@@ -623,3 +623,8 @@ export const beginMaintenance = (reason, options = {}) => request('/system/maintexport const resumeMaintenance = (hold, options = {}) => request('/system/maintenance/resume', {method: 'POST', body: JSON.stringify({ id: hold.id, revision: hold.revision }), ...options,});++// Planning-only peer administration; never dispatches host operations.+export const getPeerAdminSetup = (peerId, options) => request(`/peer-administration/peers/${encodeURIComponent(peerId)}`, options);+export const savePeerAdminGrant = (data, options) => request('/peer-administration/grants', { ...options, method: 'POST', body: JSON.stringify(data) });+export const previewPeerAdministration = (data, options) => request('/peer-administration/preview', { ...options, method: 'POST', body: JSON.stringify(data) });diff --git a/docs/API.md b/docs/API.mdindex 78ac74834b..2aff4c2d22 100644--- a/docs/API.md+++ b/docs/API.md@@ -735,6 +735,8 @@ Every mounted API prefix (see `server/index.js` for the authoritative list). Dom| `/api/insights` | Cross-domain insights || `/api/instances`, `/api/sync`, `/api/peer-sync`, `/api/sharing` | Federation / peer sync (see [COMPANION_APP_API.md](./COMPANION_APP_API.md)) || `/api/federation/media/v1` | Authenticated queued peer audio provider (see [FEDERATED_MEDIA_PROVIDERS.md](./FEDERATED_MEDIA_PROVIDERS.md)) |+| `/api/federation/admin/v1` | Paired-peer administration preflights and temporary signed plans; execution remains unsupported (see [peer administration planning](./features/peer-administration.md)) |+| `/api/peer-administration` | Operator-only per-peer/action planning grants and outbound previews (see [peer administration planning](./features/peer-administration.md)) || `/api/mortalloom` | MortalLoom (iCloud-JSON sync precedent) || `/api/review` | Review queue || `/api/settings` | App settings |diff --git a/docs/PEER_PUSH_AUTH.md b/docs/PEER_PUSH_AUTH.mdindex a74f3948af..599c48fb38 100644--- a/docs/PEER_PUSH_AUTH.md+++ b/docs/PEER_PUSH_AUTH.md@@ -167,3 +167,13 @@ Local peer configuration changes require a verified operator session. Theone-time remote bootstrap requires the saved instance password and is restrictedto installing a generated pair secret on the caller's matching peer record.Existing host-issued operator session tokens also work.++## Administration planning extension (draft)++The exact POST `/api/federation/admin/v1/{preflight,plans,receipt,execute}` routes+add only [bounded administration planning](features/peer-administration.md).+They independently require a current pair identity plus an expiring, host-local+per-action `planning-v1` grant. Basic, a display name, sync configuration and+network reachability do not authorize them. Execution is unavailable; paired+credentials still cannot call ordinary host-control routes. Grant setup and+outbound preview are operator-only under `/api/peer-administration`.diff --git a/docs/STORAGE.md b/docs/STORAGE.mdindex 4a9485dad7..5c840311c1 100644--- a/docs/STORAGE.md+++ b/docs/STORAGE.md@@ -752,3 +752,25 @@ originals and is distinct from space reclamation.### Importer sessions`data/importer-sessions.json` is `file-primary`, machine-local operational state: for each manuscript imported into a series, how far `POST /api/importer/commit` got (`arc-persisted` after canon/arc/seasons landed, `committed` with the created issue ids). It exists so a reload between the commit and the next step cannot lose the client's own "already committed" markers and re-send the payload (#9943). It is keyed by a derived import id (`imp-` + hash of series id and the normalized manuscript), so a re-analyze of the same text reads the same session back. It is a bounded ledger of what THIS machine's commit did to THIS machine's records, with no foreign keys, cross-record queries, or search, so it stays out of PostgreSQL; each entry is only honored while the issues it recorded still exist. It is deliberately **never federated**: a peer's issues arrive through record sync, and replaying a commit there would describe records that machine did not create. Schema version 1, newest 500 sessions kept, rewritten whole behind a write queue (`services/importerSessions.js`); a payload declaring another version reads as empty rather than half-read, so no migration or `data.reference/` seed is needed. Rsync backups include it.++## Peer administration planning policy++`data/peer-admin-grants.json` is bounded, machine-local `file-primary` authority+configuration, like the paired-credential registry. It contains schema-1 slots+for exact peer/action identities (maximum 300), expiring planning-only grants,+opaque grant IDs, server-derived authority type and a domain-separated pair+binding digest, never raw credentials. It has no record relationships, search,+sync cursors or federation export. Revocation replaces the slot with a new ID+and `allowed: false`; stale writes compare the prior ID. All mutations share a+file-wide queue and atomic writes. Missing means no grants; malformed or future+schemas fail closed. This is a new standalone config document, so no existing+on-disk format is migrated and no seed grants are shipped. Filesystem backups+include it; a restored grant still needs matching host/peer/pair identities and+an unexpired timestamp. `planning-v1` can never authorize a future executor.++Preflights and plan receipts are bounded in-memory diagnostics, not durable+operations: they expire within 60 seconds/five minutes and disappear at process+restart. No operation can run or be recovered from them. The future execution+ledger must be `db-primary`, receiver-local, retain replay/idempotency evidence,+and be covered by PostgreSQL backup before any executor is connected. See+[peer administration planning](features/peer-administration.md).diff --git a/docs/features/peer-administration.md b/docs/features/peer-administration.mdnew file mode 100644index 0000000000..59cb64cbaa--- /dev/null+++ b/docs/features/peer-administration.md@@ -0,0 +1,115 @@+# Peer administration planning (draft)++This draft is a **dependency foundation, not executable remote administration**.+Every advertised action reports `executionSupported: false`. A valid plan stays+`state: planned`, `queued: false`, `inFlight: false`. It cannot update, restart,+download, install, cancel active work, or become a queued operation after an+upgrade. No executor, shell command or maintenance override is wired here.++The fixed vocabulary is `portos.update`, `portos.restart`, and+`catalog.install`. Update/restart have no user-provided arguments. Catalog plans+accept only a shipped catalog key and `ollama` or `lmstudio`; free-form model IDs,+URLs, filesystem paths, code recipes, tokens, force flags and license-acceptance+flags are rejected. Gated models and Ollama import recipes require local setup+and cannot be planned through this surface. No terms are accepted by a plan.++## Later operator setup++Nothing is granted by installation, discovery, pairing, sync opt-in, this PR,+or an instance's display name. No migration creates permission or credentials.++1. On the **receiving host**, use an operator session (including its existing+ delegated agent session), or a local connection on a password-free install.+ Enable and pair the known peer using the existing pairing workflow.+2. Open Instances → the peer → **Peer administration · planning only**. Compare+ the receiving host UUID and paired caller UUID. These IDs, the existing pair+ credential binding, and the exact action define authority; names do not.+3. Review a specific grant, then explicitly allow planning for one hour. The API+ supports one minute to 24 hours. The API/UI returns a grant ID and timestamps.+ This is `planning-v1`, not permission to execute. A future execution protocol+ must require another explicit operator grant with a different scope.+4. On the sending host, an operator can preview update/restart requirements.+ The peer must separately have granted that sender planning access. Catalog+ plans are API-only until source/license/destination review is available.+5. Revoke an action on the receiving host at any time. Revocation and renewal+ rotate its grant ID; existing preflights/plans immediately become unusable.+ Expiry, disabled/deleted peers, identity changes and pair-secret rotation+ deny access. Disabling suspends the grant; use Revoke to permanently remove+ its permission. Re-enabling cannot extend its original expiry.++Grant writes compare the prior grant ID to prevent stale browser saves from+resurrecting revoked permission. Setup is always behind `requireHostControl`;+that gate and existing update, restart, model, settings and socket routes retain+their original authority rules. There is no instance-password or Basic fallback+on this protocol. Operator credentials are never forwarded to the peer.++## Protocol and audit identity++Exact POST routes under `/api/federation/admin/v1/` are `preflight`, `plans`,+`receipt`, and `execute`. Every route requires the current verified paired+credential even when the optional instance password is off. The global gate+only admits these exact paths; it does not give peers host-control authority.++- Preflight: `{ protocolVersion: 1, challenge: <uuid>, intent }`. The receiver+ validates the action grant and catalog entry, rechecks identity/grant after+ probes, and signs a snapshot with a domain-separated HMAC using the existing+ pair secret. It binds sender/receiver UUIDs, version, action, grant ID, unique+ preflight ID, challenge and a maximum 60-second expiry. The sender verifies+ that proof, target identity, version contract and freshness before planning.+- Plan: `{ protocolVersion: 1, requestId: <uuid>, preflightId, grantId, intent }`.+ The preflight is consumed once. An exact same-request retry returns the same+ signed receipt; changed payloads reusing a request ID are rejected. A new+ request ID cannot consume an already-used preflight. Reconciliation uses+ `receipt` with `{ requestId }`, authenticated and scoped to that peer.+- Execute: `{ requestId }` verifies ownership/current permission, then returns+ `503 PEER_ADMIN_EXECUTION_UNAVAILABLE`. It never responds with job acceptance+ or restart completion and never creates an operation.++Receipts contain server-derived sender/target UUIDs, request/preflight/grant IDs,+intent, timestamps, version and blockers. They are **temporary diagnostics, not+an execution audit ledger**: maximum 128 preflights and 128 plans per process,+60-second preflights, five-minute plans, additionally limited by grant expiry.+Expiry or process restart returns not-found/stale, never resumes work. Duplicate+preflight challenges within the live window are rejected. There is no eviction+of live receipts to make room. A future durable execution ledger must retain+idempotency/replay tombstones independently of these ephemeral previews.++The operator sender makes only an explicitly requested two-hop preview, with+one ten-second timeout, a 64 KiB response limit and no redirects. It sends only+existing pair credentials; network failures never cause automatic retries or+fallback to broad tokens. An unverifiable response is a refusal. Older peers+without this protocol remain usable for their existing federation surfaces.++## Required before execution can be enabled++- Integrate a **coordinator-owned exclusive claim**, bound to the maintenance+ hold ID/revision, with fresh trusted idle evidence and a resume fence. The+ maintenance admission foundation in PR #10122 does not yet provide that+ atomic claim. `status().state === 'ready'` followed by execution is unsafe;+ ordinary `admit` and a second independent lock are not substitutes. All+ admitted agents, provider work, renders and cleanup must settle naturally;+ no cancel, kill, forced pause or interruption fallback.+- Implement a durable, receiver-local operation ledger and fixed adapters for+ the existing fork-aware PortOS update and PortOS-only restart. Recheck target+ identity/version/capability and permission at dispatch. Persist request and+ grant identity before launch. Distinguish queued, draining, in-flight,+ awaiting-reconnect, succeeded, failed and uncertain; request acceptance never+ proves restart or update completion. Reconcile the same operation after a+ crash, bound deadlines and expose typed errors. Retain the exclusive hold+ when side effects are uncertain; never retry a launch based only on timeout.+- Integrate the existing catalog source/license review and installer preflight+ for the exact receiver-side entry/backend. Verify actual destination disk+ capacity including staging/headroom, memory/runtime fit, installed runtime+ and reviewed source identity. Preserve local terms and code-review gates;+ unknown size/requirements, new terms, unknown code and changed catalogs deny.+ This draft reports only advisory data-volume/OS memory telemetry and explicit+ missing-check flags. It does **not** claim those are installation checks.+- Surface rollback only when an adapter supplies a verified supported recovery+ path; otherwise report manual recovery. Never offer generic git reset, shell,+ command, URL/path execution or deletion as rollback. Test grant revocation+ during drain, queued cancellation, dispatch races, crash reconciliation,+ durable replay rejection and no active-work interruption before enabling.++These are dependencies, not permission to operate any peer. Enabling grants,+credentials, live settings, machine updates/restarts and model downloads remains+a separate later operator action.diff --git a/server/index.js b/server/index.jsindex f6ddb855c2..7d20162be9 100644--- a/server/index.js+++ b/server/index.js@@ -133,6 +133,8 @@ import videoTimelineRoutes from './routes/videoTimeline.js';import htmlCompositionRoutes from './routes/htmlComposition.js';import mediaJobsRoutes from './routes/mediaJobs.js';import federatedMediaRoutes from './routes/federatedMedia.js';+import peerAdministrationRoutes from './routes/peerAdministration.js';+import peerAdminOperatorRoutes from './routes/peerAdminOperator.js';import creativeDirectorRoutes from './routes/creativeDirector.js';// Side-effect import (#5920): evaluating the completion hook is what registers the// Creative Director project starter on `creativeDirector/projectStartSink.js`, the@@ -432,6 +434,8 @@ app.use('/api/video-timeline', videoTimelineRoutes);app.use('/api/html-composition', htmlCompositionRoutes);app.use('/api/media-jobs', mediaJobsRoutes);app.use('/api/federation/media/v1', federatedMediaRoutes);+app.use('/api/federation/admin/v1', peerAdministrationRoutes);+app.use('/api/peer-administration', peerAdminOperatorRoutes);app.use('/api/creative-director', creativeDirectorRoutes);app.use('/api/creative-commission', creativeCommissionRoutes);app.use('/api/games', gamesRoutes);diff --git a/server/lib/README.md b/server/lib/README.mdindex 2b11a0edf1..fb24622307 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -849,3 +849,5 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `sandboxDelegation.js` | Bounded tool-free worker context, route configuration, and fidelity evaluation schemas. || `forgeMaintenanceTasks.js` | Current forge-maintenance screening version, queue-compatible identity check, task classification, and legacy refusal reason. |++| `peerAdminValidation.js` | Strict planning-only peer administration schemas, fixed actions and grant scope. |diff --git a/server/lib/apiAccessPolicy.js b/server/lib/apiAccessPolicy.jsindex 900ed2573c..f7a8b9afe4 100644--- a/server/lib/apiAccessPolicy.js+++ b/server/lib/apiAccessPolicy.js@@ -48,6 +48,11 @@ export const PEER_API_SURFACE = Object.freeze([// Record push/pull (sharing/*): reads, plus the one inbound push.{ prefix: '/api/peer-sync/', methods: READ },{ path: '/api/peer-sync/push', methods: Object.freeze(['POST']) },+ // Planning-only administration. Each exact endpoint independently verifies+ // the current paired identity and a host-local action grant. Never host control.+ ...['preflight', 'plans', 'receipt', 'execute'].map(endpoint => ({+ path: `/api/federation/admin/v1/${endpoint}`, methods: Object.freeze(['POST']),+ })),// Peer-facing provider APIs; each applies its own per-peer admission.{ prefix: '/api/federation/media/v1/', methods: ANY_METHOD },{ path: '/api/providers/fleet-host', methods: READ },diff --git a/server/lib/index.js b/server/lib/index.jsindex 112355d777..f95518df49 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -832,3 +832,4 @@ export * from './sandboxDelegation.js';export * from './forgeMaintenanceTasks.js';export * from './maintenanceAdmission.js';+export * as peerAdminValidation from './peerAdminValidation.js';diff --git a/server/lib/peerAdminValidation.js b/server/lib/peerAdminValidation.jsnew file mode 100644index 0000000000..bcfecaf0ee--- /dev/null+++ b/server/lib/peerAdminValidation.js@@ -0,0 +1,42 @@+import { z } from 'zod';++// Planning v1 is deliberately not an execution grant. A future executor must+// require a new operator confirmation, never promote these grants on upgrade.+export const PEER_ADMIN_SCOPE = 'planning-v1';+export const PEER_ADMIN_ACTIONS = ['portos.update', 'portos.restart', 'catalog.install'];+export const peerAdminActionSchema = z.enum(PEER_ADMIN_ACTIONS);+const uuid = z.string().uuid();+const peerId = z.string().min(1).max(100).regex(/^[a-zA-Z0-9_-]+$/);+export const peerAdminPeerSchema = z.object({ peerId }).strict();+export const peerAdminGrantSchema = z.object({+ peerId,+ action: peerAdminActionSchema,+ confirmedHostInstanceId: uuid,+ confirmedPeerInstanceId: uuid,+ previousGrantId: uuid.nullable(),+ expiresInMinutes: z.number().int().min(1).max(1440),+ allowPlanning: z.boolean(),+}).strict();+export const peerAdminIntentSchema = z.discriminatedUnion('action', [+ z.object({ action: z.literal('portos.update') }).strict(),+ z.object({ action: z.literal('portos.restart') }).strict(),+ z.object({+ action: z.literal('catalog.install'),+ backend: z.enum(['ollama', 'lmstudio']),+ catalogKey: z.string().min(1).max(100).regex(/^[a-z0-9][a-z0-9-]*$/),+ }).strict(),+]);+export const peerAdminPreflightSchema = z.object({+ protocolVersion: z.literal(1),+ challenge: uuid,+ intent: peerAdminIntentSchema,+}).strict();+export const peerAdminPlanSchema = z.object({+ protocolVersion: z.literal(1),+ requestId: uuid,+ preflightId: uuid,+ grantId: uuid,+ intent: peerAdminIntentSchema,+}).strict();+export const peerAdminReceiptSchema = z.object({ requestId: uuid }).strict();+export const peerAdminRemotePlanSchema = z.object({ peerId, intent: peerAdminIntentSchema }).strict();diff --git a/server/routes/peerAdminOperator.js b/server/routes/peerAdminOperator.jsnew file mode 100644index 0000000000..a62afe3abd--- /dev/null+++ b/server/routes/peerAdminOperator.js@@ -0,0 +1,24 @@+import { Router } from 'express';+import { asyncHandler } from '../lib/errorHandler.js';+import { validateRequest } from '../lib/validation.js';+import { peerAdminPeerSchema, peerAdminGrantSchema, peerAdminRemotePlanSchema } from '../lib/peerAdminValidation.js';+import { requireHostControl } from '../services/authGate.js';+import { describePeerAdminSetup, savePeerAdminGrant } from '../services/peerAdministration.js';+import { planPeerAdministration } from '../services/peerAdminConsumer.js';++const router = Router();+router.use(requireHostControl);+router.get('/peers/:peerId', asyncHandler(async (req, res) => {+ const { peerId } = validateRequest(peerAdminPeerSchema, req.params);+ res.set('Cache-Control', 'no-store').json(await describePeerAdminSetup(peerId));+}));+router.post('/grants', asyncHandler(async (req, res) => {+ const input = validateRequest(peerAdminGrantSchema, req.body);+ res.json(await savePeerAdminGrant(input, req));+}));+router.post('/preview', asyncHandler(async (req, res) => {+ const input = validateRequest(peerAdminRemotePlanSchema, req.body);+ res.set('Cache-Control', 'no-store').json(await planPeerAdministration(input));+}));++export default router;diff --git a/server/routes/peerAdministration.js b/server/routes/peerAdministration.jsnew file mode 100644index 0000000000..ffbdea01bd--- /dev/null+++ b/server/routes/peerAdministration.js@@ -0,0 +1,31 @@+import { Router } from 'express';+import { asyncHandler } from '../lib/errorHandler.js';+import { validateRequest } from '../lib/validation.js';+import {+ peerAdminPreflightSchema, peerAdminPlanSchema, peerAdminReceiptSchema,+} from '../lib/peerAdminValidation.js';+import {+ createPeerAdminPreflight,+ createPeerAdminPlan, getPeerAdminPlan, rejectPeerAdminExecution,+} from '../services/peerAdministration.js';++const router = Router();+router.use((_req, res, next) => { res.set('Cache-Control', 'no-store'); next(); });+router.post('/preflight', asyncHandler(async (req, res) => {+ const input = validateRequest(peerAdminPreflightSchema, req.body);+ res.json(await createPeerAdminPreflight(req, input));+}));+router.post('/plans', asyncHandler(async (req, res) => {+ const input = validateRequest(peerAdminPlanSchema, req.body);+ // A plan is a preview, not accepted/queued work: deliberately HTTP 200.+ res.json(await createPeerAdminPlan(req, input));+}));+router.post('/receipt', asyncHandler(async (req, res) => {+ const { requestId } = validateRequest(peerAdminReceiptSchema, req.body);+ res.json(await getPeerAdminPlan(req, requestId));+}));+router.post('/execute', asyncHandler(async (req, _res) => {+ const { requestId } = validateRequest(peerAdminReceiptSchema, req.body);+ await rejectPeerAdminExecution(req, requestId);+}));+export default router;diff --git a/server/routes/peerAdministration.test.js b/server/routes/peerAdministration.test.jsnew file mode 100644index 0000000000..2a310ae931--- /dev/null+++ b/server/routes/peerAdministration.test.js@@ -0,0 +1,262 @@+import { afterAll, beforeEach, describe, expect, it, vi } from 'vitest';+import { createHmac, randomUUID } from 'node:crypto';+import { writeFileSync, readFileSync } from 'node:fs';+import { join } from 'node:path';+import express from 'express';+import { EventEmitter } from 'node:events';+import { request } from '../lib/testHelper.js';+import { mockPathsDataRoot } from '../lib/mockPathsDataRoot.js';++const { tempRoot, makeProxy, cleanup } = mockPathsDataRoot({ prefix: 'peer-admin-' });+vi.mock('../lib/fileUtils.js', async () => ({+ ...makeProxy(await vi.importActual('../lib/fileUtils.js')),+ dataPath: (...segments) => join(tempRoot, ...segments),+}));+const auth = vi.hoisted(() => ({ enabled: true }));+vi.mock('../services/auth.js', () => ({+ isAuthEnabled: async () => auth.enabled,+ verifyRequestSession: async req => req.headers.authorization === 'Bearer test-operator',+ verifyPassword: async () => true,+}));+vi.mock('../services/settings.js', () => ({ getSettings: async () => ({}), settingsEvents: new EventEmitter() }));+vi.mock('../lib/peerHttpClient.js', async () => ({+ ...await vi.importActual('../lib/peerHttpClient.js'), peerFetch: vi.fn(),+}));+// Any accidental executor integration fails the no-active-interruption contract.+const execution = vi.hoisted(() => ({ update: vi.fn(), restart: vi.fn(), install: vi.fn() }));+vi.mock('../services/portosSelfUpdate.js', () => ({ startPortosSelfUpdate: execution.update }));+vi.mock('../services/localLlm.js', () => ({ installModel: execution.install }));+vi.mock('../services/pm2.js', () => ({ restartProcess: execution.restart }));++const { authGate, hostControlRouteGate } = await import('../services/authGate.js');+const { default: receiver } = await import('./peerAdministration.js');+const { default: peerAdminOperatorRoutes } = await import('./peerAdminOperator.js');+const { errorMiddleware } = await import('../lib/errorHandler.js');+const { derivePeerAuthToken, peerFetch } = await import('../lib/peerHttpClient.js');+// Fixture peers sign the wire envelope independently of the receiving service.+const signPeerAdmin = (peer, purpose, payload) => createHmac('sha256', peer.syncSecret)+ .update(`portos-peer-admin:v1:${purpose}:${JSON.stringify(payload)}`).digest('hex');++const ROOT = '/api/federation/admin/v1';+let identity;+const app = express();+app.use((req, _res, next) => {+ Object.defineProperty(req.socket, 'remoteAddress', { value: '192.0.2.20', configurable: true });+ next();+});+app.use(express.json());+app.use(authGate);+app.use(hostControlRouteGate);+app.use(ROOT, receiver);+app.use('/api/peer-administration', peerAdminOperatorRoutes);+app.post('/api/update/execute', (_req, res) => res.json({ unexpected: true }));+app.use(errorMiddleware);++const persistIdentity = () => writeFileSync(join(tempRoot, 'instances.json'), JSON.stringify(identity));+const operator = (path, body) => request(app).post(path).set('Authorization', 'Bearer test-operator').send(body);+const peerRequest = (endpoint, body, peer = identity.peers[0]) => request(app).post(`${ROOT}/${endpoint}`)+ .set('X-PortOS-Instance-Id', peer.instanceId)+ .set('X-PortOS-Peer-Auth', derivePeerAuthToken(peer.syncSecret, peer.instanceId)).send(body);+const intent = { action: 'portos.restart' };+async function grant(action = intent.action, extra = {}) {+ return operator('/api/peer-administration/grants', {+ peerId: identity.peers[0].id, action,+ confirmedHostInstanceId: identity.self.instanceId, confirmedPeerInstanceId: identity.peers[0].instanceId,+ previousGrantId: null, expiresInMinutes: 60, allowPlanning: true, ...extra,+ });+}+async function preflight(target = intent) {+ const response = await peerRequest('preflight', { protocolVersion: 1, challenge: randomUUID(), intent: target });+ expect(response.status).toBe(200);+ return response.body.payload;+}+async function plan(target = intent) {+ const snapshot = await preflight(target);+ const input = { protocolVersion: 1, requestId: randomUUID(), preflightId: snapshot.preflightId, grantId: snapshot.grantId, intent: target };+ const response = await peerRequest('plans', input);+ expect(response.status).toBe(200);+ return { input, receipt: response.body.payload };+}++beforeEach(() => {+ vi.restoreAllMocks();+ vi.clearAllMocks();+ auth.enabled = true;+ identity = { self: { instanceId: randomUUID() }, peers: [+ { id: randomUUID(), instanceId: randomUUID(), name: 'Example peer', enabled: true, syncSecret: 'a'.repeat(64), address: '192.0.2.10', port: 5555 },+ { id: randomUUID(), instanceId: randomUUID(), name: 'Example peer', enabled: true, syncSecret: 'b'.repeat(64) },+ ] };+ persistIdentity();+ writeFileSync(join(tempRoot, 'peer-admin-grants.json'), JSON.stringify({ schemaVersion: 1, grants: [] }));+});+afterAll(cleanup);++describe('bounded administration through the real authority boundary', () => {+ it('defaults to deny and never elevates a peer to existing host control', async () => {+ const body = { protocolVersion: 1, challenge: randomUUID(), intent };+ expect((await peerRequest('preflight', body)).body.code).toBe('PEER_ADMIN_GRANT_REQUIRED');+ expect((await grant()).status).toBe(200);+ const peer = identity.peers[0];+ const denied = await request(app).post('/api/update/execute')+ .set('X-PortOS-Instance-Id', peer.instanceId)+ .set('X-PortOS-Peer-Auth', derivePeerAuthToken(peer.syncSecret, peer.instanceId)).send({});+ expect(denied.body.code).toBe('PEER_SCOPE_FORBIDDEN');+ expect((await peerRequest('preflight', body, identity.peers[1])).body.code).toBe('PEER_ADMIN_GRANT_REQUIRED');+ expect((await peerRequest('preflight', { ...body, intent: { action: 'portos.update' } })).body.code).toBe('PEER_ADMIN_GRANT_REQUIRED');+ });++ it('refuses anonymous, Basic, forged and peer setup callers with password on and off', async () => {+ for (const enabled of [true, false]) {+ auth.enabled = enabled;+ const body = { protocolVersion: 1, challenge: randomUUID(), intent };+ expect((await request(app).post(`${ROOT}/preflight`).send(body)).status).toBe(enabled ? 401 : 403);+ expect((await request(app).post(`${ROOT}/preflight`).set('Authorization', 'Basic OnBhc3M=').send(body)).status).toBe(403);+ expect((await request(app).post(`${ROOT}/preflight`).set('X-PortOS-Instance-Id', identity.peers[0].instanceId)+ .set('X-PortOS-Peer-Auth', 'forged').send(body)).status).toBe(enabled ? 401 : 403);+ const peer = identity.peers[0];+ const setup = await request(app).post('/api/peer-administration/grants')+ .set('X-PortOS-Instance-Id', peer.instanceId)+ .set('X-PortOS-Peer-Auth', derivePeerAuthToken(peer.syncSecret, peer.instanceId)).send({});+ expect(setup.status).toBe(403);+ }+ });++ it('requires exact operator-confirmed identities and CAS, redacts pair binding', async () => {+ expect((await grant(intent.action, { confirmedPeerInstanceId: identity.peers[1].instanceId })).body.code).toBe('PEER_ADMIN_IDENTITY_CHANGED');+ const saved = await grant();+ expect(saved.body.executionSupported).toBe(false);+ expect(saved.body.actions.find(row => row.action === intent.action).grant.authority).toBe('operator-session');+ expect(JSON.stringify(saved.body)).not.toContain('pairBinding');+ expect((await grant()).body.code).toBe('PEER_ADMIN_GRANT_CHANGED');+ });++ it('binds preflight to a single action, grant, identity and short lifetime', async () => {+ await grant();+ const snapshot = await preflight();+ const input = { protocolVersion: 1, requestId: randomUUID(), preflightId: snapshot.preflightId, grantId: snapshot.grantId, intent };+ const changed = await grant(intent.action, { previousGrantId: snapshot.grantId });+ expect(changed.status).toBe(200);+ expect((await peerRequest('plans', input)).body.code).toBe('PEER_ADMIN_GRANT_CHANGED');+ const next = await preflight();+ vi.spyOn(Date, 'now').mockReturnValue(next.expiresAt + 1);+ expect((await peerRequest('plans', { ...input, preflightId: next.preflightId, grantId: next.grantId })).body.code).toBe('PEER_ADMIN_PREFLIGHT_STALE');+ });++ it('suspends disabled peers and invalidates rotated pair credentials and grants', async () => {+ await grant();+ const old = structuredClone(identity.peers[0]);+ identity.peers[0].enabled = false;+ persistIdentity();+ expect((await peerRequest('preflight', { protocolVersion: 1, challenge: randomUUID(), intent }, old)).status).toBe(401);+ identity.peers[0].enabled = true;+ identity.peers[0].syncSecret = 'c'.repeat(64);+ persistIdentity();+ expect((await peerRequest('preflight', { protocolVersion: 1, challenge: randomUUID(), intent })).body.code).toBe('PEER_ADMIN_GRANT_REQUIRED');+ });++ it('reconciles identical retries, rejects changed replay and challenge reuse, and isolates receipts', async () => {+ await grant();+ const { input, receipt } = await plan();+ expect(receipt).toMatchObject({ state: 'planned', queued: false, inFlight: false, executionSupported: false });+ expect((await peerRequest('plans', input)).body.payload).toEqual(receipt);+ expect((await peerRequest('plans', { ...input, preflightId: randomUUID() })).body.code).toBe('PEER_ADMIN_REPLAY');+ expect((await peerRequest('plans', { ...input, requestId: randomUUID() })).body.code).toBe('PEER_ADMIN_PREFLIGHT_STALE');+ expect((await peerRequest('receipt', { requestId: input.requestId }, identity.peers[1])).status).toBe(404);+ const snapshot = await preflight();+ expect((await peerRequest('preflight', { protocolVersion: 1, challenge: snapshot.challenge, intent })).body.code).toBe('PEER_ADMIN_REPLAY');+ await grant(intent.action, { previousGrantId: input.grantId, allowPlanning: false });+ expect((await peerRequest('receipt', { requestId: input.requestId })).body.code).toBe('PEER_ADMIN_GRANT_REQUIRED');+ });++ it('rejects unsupported actions, free-form targets, injected inputs and gated catalog entries', async () => {+ for (const target of [ { action: 'shell', command: 'echo injected' }, { ...intent, path: '/tmp/anything' },+ { action: 'portos.update', tag: 'v1; echo injected' },+ { action: 'catalog.install', backend: 'ollama', catalogKey: '../../model' },+ { action: 'catalog.install', backend: 'ollama', catalogKey: 'example', url: 'https://example.com/code' } ]) {+ expect((await peerRequest('preflight', { protocolVersion: 1, challenge: randomUUID(), intent: target })).status).toBe(400);+ }+ await grant('catalog.install');+ expect((await peerRequest('preflight', { protocolVersion: 1, challenge: randomUUID(),+ intent: { action: 'catalog.install', backend: 'ollama', catalogKey: 'does-not-exist' } })).body.code).toBe('PEER_ADMIN_UNKNOWN_MODEL');+ expect((await peerRequest('preflight', { protocolVersion: 1, challenge: randomUUID(),+ intent: { action: 'catalog.install', backend: 'ollama', catalogKey: 'gemma3-4b-it' } })).body.code).toBe('PEER_ADMIN_MODEL_UNSUPPORTED');+ const model = await preflight({ action: 'catalog.install', backend: 'ollama', catalogKey: 'phi-4-mini' });+ expect(model.model).toMatchObject({ modelId: 'phi4-mini', sourceLicenseReview: 'required-locally' });+ expect(model.resources).toMatchObject({ destinationDiskChecked: false, runtimeMemoryChecked: false });+ expect(model.blockers).toContain('MODEL_SOURCE_LICENSE_REVIEW_REQUIRED');+ });++ it('cannot dispatch or interrupt active work because all executors remain unavailable', async () => {+ for (const action of ['portos.update', 'portos.restart']) {+ await grant(action);+ const { input } = await plan({ action });+ expect((await peerRequest('execute', { requestId: input.requestId })).body.code).toBe('PEER_ADMIN_EXECUTION_UNAVAILABLE');+ }+ expect(execution.update).not.toHaveBeenCalled();+ expect(execution.restart).not.toHaveBeenCalled();+ expect(execution.install).not.toHaveBeenCalled();+ expect(peerFetch).not.toHaveBeenCalled();+ });++ it('fails closed on unknown policy schemas instead of resetting grants', async () => {+ writeFileSync(join(tempRoot, 'peer-admin-grants.json'), '{"schemaVersion":99,"grants":[]}');+ const response = await grant();+ expect(response.body.code).toBe('PEER_ADMIN_STORE_UNAVAILABLE');+ expect(readFileSync(join(tempRoot, 'peer-admin-grants.json'), 'utf8')).toContain('99');+ });++ it('permits revocation while disabled and expires receipts without restarting work', async () => {+ await grant();+ const { input, receipt } = await plan();+ identity.peers[0].enabled = false;+ persistIdentity();+ expect((await grant(intent.action, { previousGrantId: input.grantId, allowPlanning: false })).status).toBe(200);+ identity.peers[0].enabled = true;+ persistIdentity();+ vi.spyOn(Date, 'now').mockReturnValue(receipt.expiresAt + 1);+ expect((await peerRequest('receipt', { requestId: input.requestId })).body.code).toBe('PEER_ADMIN_PLAN_NOT_FOUND');+ expect(execution.restart).not.toHaveBeenCalled();+ });++ it('completes only the signed preview exchange and does not retry an uncertain response', async () => {+ const preflightId = randomUUID();+ const grantId = randomUUID();+ peerFetch.mockImplementation(async (url, options, peer) => {+ const input = JSON.parse(options.body);+ const purpose = url.endsWith('/preflight') ? 'preflight' : 'plan';+ const payload = { protocolVersion: 1, scope: 'planning-v1',+ targetInstanceId: peer.instanceId, senderInstanceId: identity.self.instanceId,+ expiresAt: Date.now() + 60000, executionSupported: false, version: '1.0.0',+ preflightId, grantId, intent: input.intent,+ ...(purpose === 'preflight' ? { challenge: input.challenge, observedAt: Date.now() }+ : { requestId: input.requestId, state: 'planned', queued: false, inFlight: false }) };+ return { ok: true, json: async () => ({ payload, signature: signPeerAdmin(peer, purpose, payload) }) };+ });+ const response = await operator('/api/peer-administration/preview', { peerId: identity.peers[0].id, intent });+ expect(response.status).toBe(200);+ expect(response.body.plan).toMatchObject({ state: 'planned', queued: false, inFlight: false });+ expect(peerFetch).toHaveBeenCalledTimes(2);+ expect(peerFetch.mock.calls.map(([url]) => url.split('/').at(-1))).toEqual(['preflight', 'plans']);+ peerFetch.mockClear().mockRejectedValueOnce(new Error('timeout with a private network path'));+ const failed = await operator('/api/peer-administration/preview', { peerId: identity.peers[0].id, intent });+ expect(failed.body.code).toBe('PEER_ADMIN_UNAVAILABLE');+ expect(JSON.stringify(failed.body)).not.toContain('private network path');+ expect(peerFetch).toHaveBeenCalledTimes(1);+ });++ it('requires signed fresh remote identity and sends only the scoped pair credential', async () => {+ peerFetch.mockImplementation(async (_url, options, peer) => {+ expect(peer.auth).toBeNull();+ expect(peer.peerAuthAccepted).toBe(true);+ expect(options.headers).toEqual({ 'Content-Type': 'application/json' });+ const input = JSON.parse(options.body);+ const payload = { protocolVersion: 1, scope: 'planning-v1', challenge: input.challenge,+ targetInstanceId: randomUUID(), senderInstanceId: identity.self.instanceId,+ expiresAt: Date.now() + 60000, executionSupported: false };+ return { ok: true, json: async () => ({ payload, signature: signPeerAdmin(peer, 'preflight', payload) }) };+ });+ const result = await operator('/api/peer-administration/preview', { peerId: identity.peers[0].id, intent });+ expect(result.body.code).toBe('PEER_ADMIN_UNVERIFIED_RESPONSE');+ expect(peerFetch).toHaveBeenCalledTimes(1);+ });+});diff --git a/server/services/peerAdminConsumer.js b/server/services/peerAdminConsumer.jsnew file mode 100644index 0000000000..967aba599e--- /dev/null+++ b/server/services/peerAdminConsumer.js@@ -0,0 +1,72 @@+import { randomUUID } from 'node:crypto';+import { peerFetch, readPeerBody } from '../lib/peerHttpClient.js';+import { peerBaseUrl } from '../lib/peerUrl.js';+import { ServerError } from '../lib/errorHandler.js';+import { PEER_ADMIN_SCOPE } from '../lib/peerAdminValidation.js';+import { peerAdminIdentity, verifyPeerAdminSignature } from './peerAdministration.js';++const failed = () => { throw new ServerError('Peer administration response could not be verified. No execution was requested.', { status: 502, code: 'PEER_ADMIN_UNVERIFIED_RESPONSE' }); };++const ENDPOINTS = Object.freeze({+ preflight: '/api/federation/admin/v1/preflight',+ plans: '/api/federation/admin/v1/plans',+});++async function exchange(peer, endpoint, body, signal) {+ const response = await peerFetch(`${peerBaseUrl(peer)}${ENDPOINTS[endpoint]}`, {+ method: 'POST', signal, maxBytes: 64 * 1024,+ headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body),+ // Suppress the legacy Basic fallback even if this peer has not yet+ // advertised pair support. No caller session or broad credential is sent.+ }, { ...peer, auth: null, peerAuthAccepted: true });+ if (!response.ok) {+ await response.body?.cancel();+ throw new ServerError('The peer refused administration planning. Check pairing, its local grant and protocol support.', {+ status: 502, code: 'PEER_ADMIN_REMOTE_REFUSED',+ });+ }+ return readPeerBody(response, 'json', { maxBytes: 64 * 1024, idleTimeoutMs: 5000 });+}++function verified(peer, self, envelope, purpose) {+ const payload = envelope?.payload;+ if (!payload || !verifyPeerAdminSignature(peer, purpose, payload, envelope.signature)+ || payload.protocolVersion !== 1 || payload.scope !== PEER_ADMIN_SCOPE+ || payload.targetInstanceId !== peer.instanceId || payload.senderInstanceId !== self.instanceId+ || payload.executionSupported !== false || !Number.isSafeInteger(payload.expiresAt)+ || payload.expiresAt <= Date.now()) failed();+ return payload;+}++/** An operator-requested preview only. Never retries a mutation on uncertainty. */+export async function planPeerAdministration({ peerId, intent }) {+ const { peer, self } = await peerAdminIdentity(peerId);+ const requestId = randomUUID();+ const challenge = randomUUID();+ const signal = AbortSignal.timeout(10_000); // one budget for BOTH hops + bodies+ const run = async () => {+ const preflight = verified(peer, self, await exchange(peer, 'preflight', { protocolVersion: 1, challenge, intent }, signal), 'preflight');+ if (preflight.challenge !== challenge || JSON.stringify(preflight.intent) !== JSON.stringify(intent)+ || !Number.isSafeInteger(preflight.observedAt) || preflight.observedAt > Date.now() + 5000+ || preflight.observedAt < Date.now() - 60_000 || preflight.expiresAt > preflight.observedAt + 60_000+ || typeof preflight.version !== 'string') failed();+ // Never borrow a credential/identity after an operator changed the peer+ // during the first hop. The receiver separately checks its current grant.+ const fresh = await peerAdminIdentity(peerId);+ if (fresh.peer.syncSecret !== peer.syncSecret || fresh.peer.instanceId !== peer.instanceId+ || fresh.self.instanceId !== self.instanceId || peerBaseUrl(fresh.peer) !== peerBaseUrl(peer)) failed();+ const plan = verified(peer, self, await exchange(peer, 'plans', {+ protocolVersion: 1, requestId, preflightId: preflight.preflightId, grantId: preflight.grantId, intent,+ }, signal), 'plan');+ if (plan.requestId !== requestId || plan.preflightId !== preflight.preflightId || plan.grantId !== preflight.grantId+ || plan.version !== preflight.version || JSON.stringify(plan.intent) !== JSON.stringify(intent)+ || plan.state !== 'planned' || plan.queued !== false || plan.inFlight !== false) failed();+ return { preflight, plan };+ };+ return run().catch(error => {+ if (error instanceof ServerError) throw error;+ throw new ServerError('Peer planning timed out or became unavailable. No execution was requested; preview again for a fresh plan.', {+ status: 504, code: 'PEER_ADMIN_UNAVAILABLE',+ });+ });+}diff --git a/server/services/peerAdministration.js b/server/services/peerAdministration.jsnew file mode 100644index 0000000000..169ea342d8--- /dev/null+++ b/server/services/peerAdministration.js@@ -0,0 +1,254 @@+/**+ * Bounded peer administration planning. No executor is imported or registered.+ * Grants authorize planning-v1 only; execution needs a separately reviewed+ * maintenance lease, durable operation ledger and a new operator grant scope.+ */+import { createHash, createHmac, randomUUID, timingSafeEqual } from 'node:crypto';+import { readFile, statfs } from 'node:fs/promises';+import os from 'node:os';+import { join } from 'node:path';+import { z } from 'zod';+import { atomicWrite, readJSONFile, PATHS } from '../lib/fileUtils.js';+import { parseFilesystemStats } from '../lib/fileCore.js';+import { createMutex } from '../lib/asyncMutex.js';+import { ServerError } from '../lib/errorHandler.js';+import { loadData } from './instanceIdentity.js';+import { derivePeerAuthToken, PEER_AUTH_HEADER, PEER_INSTANCE_HEADER } from '../lib/peerHttpClient.js';+import { PEER_ADMIN_ACTIONS, PEER_ADMIN_SCOPE, peerAdminActionSchema } from '../lib/peerAdminValidation.js';+import { LOCAL_LLM_CATALOG, catalogSizeBytes } from '../lib/localLlmCatalog.js';++const PREFLIGHT_TTL_MS = 60_000;+const PLAN_TTL_MS = 5 * 60_000;+const MAX_RECEIPTS = 128;+const MAX_GRANTS = 300;+const withLock = createMutex();+const preflights = new Map();+const plans = new Map();+const grantFile = () => join(PATHS.data, 'peer-admin-grants.json');+const uuid = z.string().uuid();+const grantRecord = z.object({+ id: uuid, peerId: z.string(), peerInstanceId: uuid, hostInstanceId: uuid,+ action: peerAdminActionSchema, scope: z.literal(PEER_ADMIN_SCOPE),+ pairBinding: z.string().regex(/^[a-f0-9]{64}$/),+ allowed: z.boolean(), expiresAt: z.number().int(), createdAt: z.number().int(),+ authority: z.enum(['operator-session', 'local-operator']),+}).strict();+const grantStore = z.object({ schemaVersion: z.literal(1), grants: z.array(grantRecord).max(MAX_GRANTS) }).strict();+const refuse = (code, message, status = 403) => { throw new ServerError(message, { status, code, severity: 'warning' }); };+const digest = value => createHash('sha256').update(JSON.stringify(value)).digest('hex');+const sameSecret = (a, b) => {+ if (typeof a !== 'string' || typeof b !== 'string') return false;+ const left = Buffer.from(a);+ const right = Buffer.from(b);+ return left.length === right.length && timingSafeEqual(left, right);+};+const binding = (peer, self) => createHmac('sha256', peer.syncSecret)+ .update(`portos-peer-admin:binding:v1:${self.instanceId}:${peer.id}:${peer.instanceId}`).digest('hex');+const wireGrant = ({ pairBinding: _pairBinding, ...grant }) => grant;++async function readGrants() {+ const raw = await readJSONFile(grantFile(), { schemaVersion: 1, grants: [] }, { strict: true, logError: false });+ const parsed = grantStore.safeParse(raw);+ if (!parsed.success) refuse('PEER_ADMIN_STORE_UNAVAILABLE', 'Peer administration policy is unreadable', 503);+ return parsed.data;+}++export async function peerAdminIdentity(peerId) {+ const { self, peers } = await loadData();+ const peer = peers?.find(entry => entry.id === peerId);+ if (!uuid.safeParse(self?.instanceId).success || !uuid.safeParse(peer?.instanceId).success+ || peer.instanceId === self.instanceId || peer.enabled === false+ || typeof peer.syncSecret !== 'string' || peer.syncSecret.length < 32) {+ refuse('PEER_ADMIN_PAIR_REQUIRED', 'An enabled pair with verified instance identities is required');+ }+ return { peer, self };+}++// Revalidate the CURRENT pair credential at each receiver operation and after+// preflight probes. Names, headers alone, Basic and operator sessions cannot+// impersonate a paired caller on the receiver endpoints, even with auth off.+async function caller(req) {+ if (req.portosAuthContext?.method !== 'peer' || req.portosAuthContext?.authenticated !== true) {+ refuse('PEER_ADMIN_PEER_REQUIRED', 'A scoped paired-peer credential is required');+ }+ const identity = await peerAdminIdentity(req.portosAuthContext.peerId);+ if (req.get(PEER_INSTANCE_HEADER) !== identity.peer.instanceId+ || !sameSecret(req.get(PEER_AUTH_HEADER), derivePeerAuthToken(identity.peer.syncSecret, identity.peer.instanceId))) {+ refuse('PEER_ADMIN_PEER_REQUIRED', 'The paired identity is no longer valid');+ }+ return identity;+}++async function currentGrant(identity, action) {+ const { peer, self } = identity;+ const store = await readGrants();+ const grant = store.grants.find(entry => entry.peerId === peer.id && entry.action === action);+ if (!grant || !grant.allowed || grant.expiresAt <= Date.now() || grant.scope !== PEER_ADMIN_SCOPE+ || grant.peerInstanceId !== peer.instanceId || grant.hostInstanceId !== self.instanceId+ || !sameSecret(grant.pairBinding, binding(peer, self))) {+ refuse('PEER_ADMIN_GRANT_REQUIRED', 'This paired identity has no current grant for that action');+ }+ return grant;+}++export async function describePeerAdminSetup(peerId) {+ const { self, peers } = await loadData();+ const peer = peers?.find(entry => entry.id === peerId);+ if (!peer) refuse('PEER_ADMIN_PEER_NOT_FOUND', 'Peer not found', 404);+ const paired = uuid.safeParse(self?.instanceId).success && uuid.safeParse(peer.instanceId).success+ && peer.instanceId !== self.instanceId && peer.enabled !== false && typeof peer.syncSecret === 'string' && peer.syncSecret.length >= 32;+ const store = await readGrants();+ return {+ scope: PEER_ADMIN_SCOPE, executionSupported: false,+ hostInstanceId: self?.instanceId ?? null, peerId, peerInstanceId: peer.instanceId ?? null, paired,+ actions: PEER_ADMIN_ACTIONS.map(action => {+ const grant = store.grants.find(entry => entry.peerId === peerId && entry.action === action);+ const active = Boolean(paired && grant?.allowed && grant.expiresAt > Date.now()+ && grant.hostInstanceId === self.instanceId && grant.peerInstanceId === peer.instanceId+ && sameSecret(grant.pairBinding, binding(peer, self)));+ return { action, grant: grant ? wireGrant(grant) : null, active };+ }),+ };+}++export const savePeerAdminGrant = (input, req) => withLock(async () => {+ // The route applies requireHostControl; record its server-derived authority,+ // never a caller-supplied operator label or remote display name.+ const registry = await loadData();+ const identity = input.allowPlanning ? await peerAdminIdentity(input.peerId)+ : { self: registry.self, peer: registry.peers?.find(entry => entry.id === input.peerId) };+ const { peer, self } = identity;+ if (!peer || !self) refuse('PEER_ADMIN_PEER_NOT_FOUND', 'Peer or host identity not found', 404);+ if (input.confirmedPeerInstanceId !== peer.instanceId || input.confirmedHostInstanceId !== self.instanceId) {+ refuse('PEER_ADMIN_IDENTITY_CHANGED', 'The confirmed instance identity changed', 409);+ }+ const store = await readGrants();+ const index = store.grants.findIndex(entry => entry.peerId === peer.id && entry.action === input.action);+ if ((store.grants[index]?.id ?? null) !== input.previousGrantId) {+ refuse('PEER_ADMIN_GRANT_CHANGED', 'Refresh the grant before changing it', 409);+ }+ if (!input.allowPlanning && index < 0) refuse('PEER_ADMIN_GRANT_CHANGED', 'There is no grant to revoke', 409);+ const now = Date.now();+ const grant = {+ id: randomUUID(), peerId: peer.id, peerInstanceId: peer.instanceId, hostInstanceId: self.instanceId,+ action: input.action, scope: PEER_ADMIN_SCOPE,+ pairBinding: input.allowPlanning ? binding(peer, self) : store.grants[index].pairBinding,+ allowed: input.allowPlanning, createdAt: now, expiresAt: now + input.expiresInMinutes * 60_000,+ authority: req.portosAuthContext.method === 'session' ? 'operator-session' : 'local-operator',+ };+ if (index >= 0) store.grants[index] = grant;+ else if (store.grants.length < MAX_GRANTS) store.grants.push(grant);+ else refuse('PEER_ADMIN_GRANT_LIMIT', 'The bounded grant store is full', 409);+ await atomicWrite(grantFile(), store);+ return describePeerAdminSetup(peer.id);+});++function sweep() {+ const now = Date.now();+ for (const map of [preflights, plans]) for (const [id, value] of map) if (value.expiresAt <= now) map.delete(id);+}++function signPeerAdmin(peer, purpose, payload) {+ return createHmac('sha256', peer.syncSecret).update(`portos-peer-admin:v1:${purpose}:${JSON.stringify(payload)}`).digest('hex');+}+export const verifyPeerAdminSignature = (peer, purpose, payload, signature) => sameSecret(signPeerAdmin(peer, purpose, payload), signature);++function catalogTarget(intent) {+ if (intent.action !== 'catalog.install') return null;+ const entry = LOCAL_LLM_CATALOG.find(model => model.key === intent.catalogKey && model[intent.backend]);+ if (!entry) refuse('PEER_ADMIN_UNKNOWN_MODEL', 'Choose an existing catalog entry for this backend', 400);+ if (entry.gated || entry.ollamaImport || entry.appleSiliconOnly && (process.platform !== 'darwin' || process.arch !== 'arm64')) {+ refuse('PEER_ADMIN_MODEL_UNSUPPORTED', 'This catalog entry requires local setup or source review', 409);+ }+ return {+ catalogKey: entry.key, backend: intent.backend, modelId: entry[intent.backend],+ estimatedDownloadBytes: catalogSizeBytes(intent.backend, entry[intent.backend]),+ sourceLicenseReview: 'required-locally',+ };+}++async function resourceSnapshot() {+ const disk = await statfs(PATHS.data).catch(() => null);+ return {+ dataVolumeFreeBytes: parseFilesystemStats(disk)?.freeBytes ?? null,+ totalMemoryBytes: os.totalmem(), freeMemoryBytes: os.freemem(),+ // Data-volume space and OS free memory are advisory; model destinations,+ // inference residency and an exclusive maintenance lease are not checked.+ destinationDiskChecked: false, runtimeMemoryChecked: false,+ };+}++export const createPeerAdminPreflight = (req, input) => withLock(async () => {+ sweep();+ const identity = await caller(req);+ const grant = await currentGrant(identity, input.intent.action);+ const model = catalogTarget(input.intent);+ if (preflights.has(input.challenge)) refuse('PEER_ADMIN_REPLAY', 'Use a fresh preflight challenge', 409);+ if (preflights.size >= MAX_RECEIPTS) refuse('PEER_ADMIN_BUSY', 'Too many outstanding preflights', 429);+ const version = JSON.parse(await readFile(new URL('../../package.json', import.meta.url), 'utf8')).version;+ const resources = await resourceSnapshot();+ // Re-read after probes, so rotation/revocation during I/O invalidates admission.+ const fresh = await caller(req);+ const freshGrant = await currentGrant(fresh, input.intent.action);+ if (freshGrant.id !== grant.id) refuse('PEER_ADMIN_GRANT_CHANGED', 'Grant changed during preflight', 409);+ const now = Date.now();+ const payload = {+ protocolVersion: 1, scope: PEER_ADMIN_SCOPE, challenge: input.challenge, preflightId: randomUUID(),+ senderInstanceId: fresh.peer.instanceId, targetInstanceId: fresh.self.instanceId,+ version, grantId: grant.id, intent: input.intent, model, resources,+ observedAt: now, expiresAt: Math.min(now + PREFLIGHT_TTL_MS, grant.expiresAt),+ executionSupported: false, maintenance: 'exclusive-lease-unavailable',+ blockers: ['MAINTENANCE_EXECUTOR_UNAVAILABLE', ...(model ? ['MODEL_SOURCE_LICENSE_REVIEW_REQUIRED', 'MODEL_DESTINATION_PREFLIGHT_REQUIRED', 'MODEL_RUNTIME_MEMORY_PREFLIGHT_REQUIRED'] : [])],+ };+ const record = { ...payload, peerId: fresh.peer.id, consumedBy: null };+ preflights.set(input.challenge, record);+ return { payload, signature: signPeerAdmin(fresh.peer, 'preflight', payload) };+});++export const createPeerAdminPlan = (req, input) => withLock(async () => {+ sweep();+ const identity = await caller(req);+ const grant = await currentGrant(identity, input.intent.action);+ if (grant.id !== input.grantId) refuse('PEER_ADMIN_GRANT_CHANGED', 'The preflight grant is stale', 409);+ const key = `${identity.peer.id}:${input.requestId}`;+ const previous = plans.get(key);+ if (previous) {+ if (previous.fingerprint !== digest(input)) refuse('PEER_ADMIN_REPLAY', 'Request identity was reused with different input', 409);+ return { payload: previous.payload, signature: signPeerAdmin(identity.peer, 'plan', previous.payload) };+ }+ const preflight = [...preflights.values()].find(entry => entry.preflightId === input.preflightId && entry.peerId === identity.peer.id);+ if (!preflight || preflight.expiresAt <= Date.now() || preflight.consumedBy) {+ refuse('PEER_ADMIN_PREFLIGHT_STALE', 'A fresh, unused preflight is required', 409);+ }+ if (preflight.grantId !== grant.id || digest(preflight.intent) !== digest(input.intent)+ || preflight.targetInstanceId !== identity.self.instanceId || preflight.senderInstanceId !== identity.peer.instanceId) {+ refuse('PEER_ADMIN_PREFLIGHT_STALE', 'The preflight no longer matches this request', 409);+ }+ if (plans.size >= MAX_RECEIPTS) refuse('PEER_ADMIN_BUSY', 'Too many outstanding plans', 429);+ const now = Date.now();+ const payload = {+ protocolVersion: 1, scope: PEER_ADMIN_SCOPE, requestId: input.requestId, preflightId: input.preflightId,+ grantId: grant.id, senderInstanceId: identity.peer.instanceId, targetInstanceId: identity.self.instanceId,+ intent: input.intent, version: preflight.version, createdAt: now,+ expiresAt: Math.min(now + PLAN_TTL_MS, grant.expiresAt), state: 'planned',+ queued: false, inFlight: false, executionSupported: false, blockers: preflight.blockers,+ };+ preflight.consumedBy = input.requestId;+ plans.set(key, { fingerprint: digest(input), payload, expiresAt: payload.expiresAt });+ return { payload, signature: signPeerAdmin(identity.peer, 'plan', payload) };+});++export const getPeerAdminPlan = (req, requestId) => withLock(async () => {+ sweep();+ const identity = await caller(req);+ const receipt = plans.get(`${identity.peer.id}:${requestId}`);+ if (!receipt) refuse('PEER_ADMIN_PLAN_NOT_FOUND', 'Plan expired or not found; it has not been queued', 404);+ const grant = await currentGrant(identity, receipt.payload.intent.action);+ if (grant.id !== receipt.payload.grantId) refuse('PEER_ADMIN_GRANT_CHANGED', 'The plan grant is stale', 409);+ return { payload: receipt.payload, signature: signPeerAdmin(identity.peer, 'plan', receipt.payload) };+});++export async function rejectPeerAdminExecution(req, requestId) {+ await getPeerAdminPlan(req, requestId);+ refuse('PEER_ADMIN_EXECUTION_UNAVAILABLE', 'Planning only: no work was queued or started. Exclusive maintenance and execution reconciliation are required.', 503);+}