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
fix: authenticate paired peers with a pair-secret token instead of the instance password (#8356)
[._.]/ Adam Eivya47cb72a86f8
diff --git a/client/src/components/instances/PeerSyncSecretEditor.jsx b/client/src/components/instances/PeerSyncSecretEditor.jsxindex 42f52398bf..c680693b5c 100644--- a/client/src/components/instances/PeerSyncSecretEditor.jsx+++ b/client/src/components/instances/PeerSyncSecretEditor.jsx@@ -2,10 +2,25 @@ import { useState } from 'react';import { updatePeer } from '../../services/api';import toast from '../ui/Toast';+// A stored peer password is normally that machine's instance password, which+// carries operator authority there. The pair secret replaces it with a+// peer-only credential (#8356); this hint walks the user through the switch.+function storedPasswordHint(peer) {+ if (!peer.auth?.hasPassword) return null;+ if (!peer.hasSyncSecret) {+ return 'The stored password grants operator access on that machine if it is its instance password. Set a sync secret on both machines to use a peer-only credential instead.';+ }+ if (peer.peerAuthAccepted) {+ return 'This peer accepts the pair credential. Remove the stored password — it is no longer needed.';+ }+ return 'Still signing in with the stored password. Update that machine and enter the same sync secret there; the password stops being sent once it accepts the pair credential.';+}+export default function PeerSyncSecretEditor({ peer, onRefresh }) {const [editing, setEditing] = useState(false);const [secret, setSecret] = useState('');const [saving, setSaving] = useState(false);+ const passwordHint = storedPasswordHint(peer);const save = async (value) => {if (saving || (value !== null && (value.length < 32 || value.length > 256))) return;setSaving(true);@@ -22,6 +37,7 @@ export default function PeerSyncSecretEditor({ peer, onRefresh }) {<p className={peer.hasSyncSecret ? 'text-port-success' : 'text-port-warning'}>{peer.hasSyncSecret ? 'Record push authentication configured' : 'Record pushes paused until a sync secret is configured on both instances'}</p>+ {passwordHint && <p className="text-port-warning">{passwordHint}</p>}{editing ? (<div className="space-y-2"><label htmlFor={`peer-sync-secret-${peer.id}`} className="block">Shared sync secret</label>diff --git a/client/src/components/instances/PeerSyncSecretEditor.test.jsx b/client/src/components/instances/PeerSyncSecretEditor.test.jsxindex cca431b380..e6132d7cbe 100644--- a/client/src/components/instances/PeerSyncSecretEditor.test.jsx+++ b/client/src/components/instances/PeerSyncSecretEditor.test.jsx@@ -23,4 +23,16 @@ describe('peer record push pairing', () => {expect(updatePeer).toHaveBeenLastCalledWith('peer-a', { syncSecret: 'synthetic-pair-secret-32-characters-long' });expect(screen.queryByLabelText('Shared sync secret')).toBeNull();});++ it('guides the user from a stored instance password to the peer-only pair credential (#8356)', () => {+ const peer = { id: 'peer-a', auth: { username: '', hasPassword: true }, hasSyncSecret: false };+ const { rerender } = render(<PeerSyncSecretEditor peer={peer} onRefresh={vi.fn()} />);+ expect(screen.getByText(/grants operator access on that machine/)).toBeTruthy();+ rerender(<PeerSyncSecretEditor peer={{ ...peer, hasSyncSecret: true }} onRefresh={vi.fn()} />);+ expect(screen.getByText(/Still signing in with the stored password/)).toBeTruthy();+ rerender(<PeerSyncSecretEditor peer={{ ...peer, hasSyncSecret: true, peerAuthAccepted: true }} onRefresh={vi.fn()} />);+ expect(screen.getByText(/Remove the stored password/)).toBeTruthy();+ rerender(<PeerSyncSecretEditor peer={{ ...peer, auth: null, hasSyncSecret: true, peerAuthAccepted: true }} onRefresh={vi.fn()} />);+ expect(screen.queryByText(/stored password/)).toBeNull();+ });});diff --git a/docs/API.md b/docs/API.mdindex 251f2bcbff..90604a69da 100644--- a/docs/API.md+++ b/docs/API.md@@ -64,15 +64,17 @@ Additive response fields are allowed. A breaking change needs a new, explicitlyversioned endpoint and a staged migration of the probe; `schemaVersions.js`gates synchronized records, not these request/response contracts.-All three requests use the configured peer HTTP Basic credential when the-remote instance enables its optional password gate. They are not a general+All three requests authenticate with the peer credential described in+[PEER_PUSH_AUTH.md](./PEER_PUSH_AUTH.md#peer-credentials-are-not-operator-authority):+the paired peer token, plus the configured HTTP Basic credential until the+remote confirms the token. They are not a generalcross-install data channel: probe results are stored only as the local peer'shealth, app, and sync snapshots. Do not add personal records, peer lists,credentials, local paths, or build identity to these responses.| Method | Endpoint | Stable request and response contract ||--------|----------|--------------------------------------|-| GET | `/system/health/details` | Returns an object containing `instanceId` and `version` (each may be `null`) for peer identity and compatibility display. The health summary remains an object so an older prober can retain it as its last-known health snapshot. |+| GET | `/system/health/details` | Returns an object containing `instanceId` and `version` (each may be `null`) for peer identity and compatibility display. Newer installs add `peerAuth: { version, accepted }`; `accepted` is true only when this request authenticated with the prober's pair token. A missing field means the prober keeps sending Basic. The health summary remains an object so an older prober can retain it as its last-known health snapshot. || GET | `/apps?view=probe` | The periodic probe requests `view=probe`; returns either the legacy app array or `{ apps: [...] }`. Each app entry used by peers retains `id`, `name`, `icon`, `overallStatus`, `uiPort`, `apiPort`, and `type`; fields may be absent or `null` when unknown. Older peers may ignore the query and return the legacy enriched list, which remains compatible with the same field mapping. || GET | `/instances/sync-status?forPeer=<instance-id>` | `forPeer` is optional and remains lenient: an unknown or legacy identifier, blank value, or omitted value must degrade to the unscoped status response rather than fail the probe. A recognized peer receives its `cursorForYou` alongside the normal sync status — with this install's own `lastSyncError` / `lastSyncSucceeded` stripped, since those carry local diagnostics and the endpoint is reachable by any tailnet machine. |diff --git a/docs/FEDERATED_MEDIA_PROVIDERS.md b/docs/FEDERATED_MEDIA_PROVIDERS.mdindex e896d7c540..37c887ed90 100644--- a/docs/FEDERATED_MEDIA_PROVIDERS.md+++ b/docs/FEDERATED_MEDIA_PROVIDERS.md@@ -370,12 +370,12 @@ so our peer list and routing policy would ride federation with it — exactly whEvery request requires both:-- `Authorization: Basic …`, verified against the provider instance password by the global auth gate; browser session and Bearer authentication are deliberately rejected for this peer-only surface.+- A peer credential verified by the global auth gate: the paired peer token (`X-PortOS-Peer-Auth`, see [PEER_PUSH_AUTH.md](./PEER_PUSH_AUTH.md#peer-credentials-are-not-operator-authority)) or, for an unpaired or older consumer, `Authorization: Basic …` with the provider instance password. Browser session and Bearer authentication are deliberately rejected for this peer-only surface.- `X-PortOS-Instance-Id: <consumer-instance-id>`, resolving to an enabled peer registered on the provider.-Use `peerFetch` for PortOS-to-PortOS calls; it already attaches the configured Basic credential and local instance id. The instance-id header identifies the registered peer, while the Basic credential authenticates access to this PortOS install.+Use `peerFetch` for PortOS-to-PortOS calls; it already attaches the peer credential and local instance id. The instance-id header identifies the registered peer, while the credential authenticates access to this PortOS install.-As with existing peer sync, the instance-id header is self-asserted. Basic authentication proves access to the provider install; it does not cryptographically bind that credential to one peer row. Owner-scoped job lookup is therefore a least-disclosure boundary for cooperating peers on the trusted network, not protection from another holder of the same instance password spoofing a registered id.+With the paired peer token the instance id is bound to the pair secret, so it is no longer self-asserted. With legacy Basic authentication it is: Basic proves access to the provider install; it does not cryptographically bind that credential to one peer row. Owner-scoped job lookup is therefore a least-disclosure boundary for cooperating peers on the trusted network, not protection from another holder of the same instance password spoofing a registered id.## Wire v1diff --git a/docs/PEER_PUSH_AUTH.md b/docs/PEER_PUSH_AUTH.mdindex 06f25a3d73..9283fcda57 100644--- a/docs/PEER_PUSH_AUTH.md+++ b/docs/PEER_PUSH_AUTH.md@@ -25,10 +25,43 @@ To revoke or rotate a pair, remove or replace its sync secret. Secrets stay in texisting machine-local `instances.json` peer configuration, are stripped fromclient/socket and announcement payloads, and never travel in record bodies. Thesender attaches `X-PortOS-Peer-Sync-Token` only to `/api/peer-sync/push`, alongside-any existing Basic credential for the optional instance password. HTTP redirects+the peer credential below. HTTP redirectsare refused for credentialed pushes. Use the existing private encrypted transport(Tailscale or HTTPS) to protect these credentials in transit.+## Peer credentials are not operator authority++The instance password is operator authority: whoever holds it can sign in at+`/api/auth/login` and run host commands. A peer must not need it. Once a pair+secret is configured, every peer request (probe, sync, relay socket, media+provider) authenticates with `X-PortOS-Peer-Auth`, an HMAC-SHA256 of the pair+secret bound to the sender's `X-PortOS-Instance-Id`. The secret itself is not+sent, and each direction has a different token.++The receiver maps a verified token to `method: 'peer'`. It authenticates+`/api/*` and `/data/*` reads and pushes and the peer socket relay handshake. It+never passes `requireHostControl` (`/api/commands/*` returns+`HOST_CONTROL_FORBIDDEN`), cannot emit socket events, and cannot be exchanged+for a session, because it is not the password. A disabled peer's token is refused.++Rollout without breaking older installs:++- The sender sends the token and any stored Basic credential together until the+ receiver's `GET /api/system/health/details` reports+ `peerAuth.accepted: true` for the probe. It then stops sending Basic to that+ peer (`peerAuthAccepted` on the local peer record). A later 401/403 probe+ clears the flag, so Basic returns if the receiver loses its side of the pair.+- An unpaired peer, an older receiver, or one whose secret differs keeps+ receiving Basic, which is still accepted as `method: 'basic'` (also refused+ host control).+- A receiver logs one warning per process when a paired peer still signs in with+ the instance password.+- **Instances** shows a hint on each peer card with a stored password. After the+ peer confirms the token, remove the stored password there. No migration deletes+ stored credentials.++The handshake version is `peerAuth` in `server/lib/schemaVersions.js`.+## Existing installations and mixed versionsExisting peer records remain intact. No secret is synthesized or trusted fromdiff --git a/server/lib/README.md b/server/lib/README.mdindex a39d92487d..0678e40453 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -437,7 +437,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `xPostMedia.js` | Pure x.com/twitter.com post helpers: `parseXPostUrl(input)` (post URL → `{ statusId, canonicalUrl }`, host-gated) + `buildSyndicationUrl`/`syndicationToken` (Twitter's public unauthenticated tweet-syndication endpoint) + `extractXPostMedia(json)` (→ `{ images, video }`). Feeds the mood-board X post importer. || `requestAbort.js` | `abortSignalFromResponse(res)` — AbortSignal that fires only when an Express client disconnects *before the response finishes* (keyed off `res` close + `writableEnded`). Plus `anyAbortSignal(signals)` — combine several signals into one (native `AbortSignal.any` with a Node-18 fallback). || `readResponseJson.js` | Read a `Response` body as JSON, tolerating a non-JSON/HTML error page (no `Unexpected token <` crash). Object callers need no opts; pass `{ fallback, emptyValue }` for arrays or to surface the raw error text. |-| `peerHttpClient.js` | Federation HTTP/Socket.IO client (TLS validation off — Tailnet is the trust boundary); `readPeerBody(response, method, { idleTimeoutMs? })` bounds native response body stalls and reports `PEER_BODY_IDLE_TIMEOUT`. |+| `peerHttpClient.js` | Federation HTTP/Socket.IO client (TLS validation off — Tailnet is the trust boundary); attaches the peer credential (`derivePeerAuthToken` pair token, legacy Basic until the receiver confirms it); `readPeerBody(response, method, { idleTimeoutMs? })` bounds native response body stalls and reports `PEER_BODY_IDLE_TIMEOUT`. || `peerProbeDiagnostics.js` | Classify federated peer probe failures (`local_refused` / `tunnel_dial` / `probe_http` / timeout / auth / DNS) so Instances UI and logs can tell a dead local forward from a tunnel dial miss from a PortOS health-details failure; messages stay redacted (no full `tc…` capabilities). || `peerSelfHost.js` | Tailscale-issued hostname this PortOS sends in federation. || `peerUrl.js` | Build the base URL for a peer. |diff --git a/server/lib/peerHttpClient.js b/server/lib/peerHttpClient.jsindex 952cb16178..1eb986f538 100644--- a/server/lib/peerHttpClient.js+++ b/server/lib/peerHttpClient.js@@ -1,5 +1,6 @@// Federation HTTP/Socket.IO client — TLS validation off (Tailnet is the trust boundary).import https from 'node:https';+import { createHmac } from 'node:crypto';import { insecureFetch } from './httpClient.js';const peerHttpsAgent = new https.Agent({ rejectUnauthorized: false, keepAlive: true });@@ -33,6 +34,44 @@ export function peerAuthHeaders(peer) {return { Authorization: `Basic ${token}` };}+/**+ * Peer-scoped credential (#8356). A paired peer (both machines hold the same+ * `syncSecret`) proves its identity with an HMAC of that secret bound to its+ * own instance id, instead of presenting this install's instance password over+ * HTTP Basic. The receiver maps it to `method: 'peer'`, which authenticates+ * ordinary federation reads and pushes but never operator authority: it cannot+ * pass `requireHostControl`, and because it is not the password it cannot be+ * exchanged for a session at `/api/auth/login`. The token is directional+ * (the sender's id is in the MAC), so the receiver's matching token toward the+ * sender is a different value, and the pair secret itself never crosses the wire+ * except on the record-push endpoint below.+ */+export const PEER_AUTH_HEADER = 'X-PortOS-Peer-Auth';+export const PEER_INSTANCE_HEADER = 'X-PortOS-Instance-Id';++export function derivePeerAuthToken(syncSecret, senderInstanceId) {+ return createHmac('sha256', syncSecret).update(`portos-peer-auth:v1:${senderInstanceId}`).digest('hex');+}++/**+ * Credential headers for one outbound hop. A paired peer gets the peer token;+ * the stored Basic password rides along only until the receiver has confirmed+ * (through the probe's `peerAuth.accepted` answer, persisted as+ * `peer.peerAuthAccepted`) that it verifies the token. An older receiver, or+ * one whose side of the pair secret is missing or different, never confirms, so+ * it keeps receiving Basic and federation continues unchanged.+ */+function peerCredentialHeaders(peer, selfInstanceId) {+ if (!peer) return {};+ const paired = typeof peer.syncSecret === 'string' && peer.syncSecret.length >= 32 && Boolean(selfInstanceId);+ if (!paired) return peerAuthHeaders(peer);+ return {+ [PEER_INSTANCE_HEADER]: selfInstanceId,+ [PEER_AUTH_HEADER]: derivePeerAuthToken(peer.syncSecret, selfInstanceId),+ ...(peer.peerAuthAccepted === true ? {} : peerAuthHeaders(peer)),+ };+}+// Our own federation instance id, memoized after the first successful read.// Resolved through a dynamic import of the identity leaf (#6836): harmless to// static-import now (services/instanceIdentity.js is a leaf with no edge back@@ -42,13 +81,13 @@ export function peerAuthHeaders(peer) {// `UNKNOWN_INSTANCE_ID` sentinel, so a receiver sees "unidentified" instead of// a bogus id it would then fail to resolve in its peer registry.let cachedSelfInstanceId = null;-async function selfInstanceHeader() {+async function selfInstanceId() {if (!cachedSelfInstanceId) {const instanceIdentity = await import('../services/instanceIdentity.js').catch(() => null);const id = await instanceIdentity?.getInstanceId?.().catch(() => null);if (typeof id === 'string' && id && id !== instanceIdentity?.UNKNOWN_INSTANCE_ID) cachedSelfInstanceId = id;}- return cachedSelfInstanceId ? { 'X-PortOS-Instance-Id': cachedSelfInstanceId } : {};+ return cachedSelfInstanceId;}/** Test-support: drop the memoized instance id. */@@ -60,13 +99,14 @@ export function __resetSelfInstanceIdForTests() {* Fetch a peer URL. Every hop identifies this install with* `X-PortOS-Instance-Id` so the receiver can apply the user's per-peer sharing* config to PULL requests (#3659) the way it already does to pushes. Pass the- * `peer` record (third arg) so a stored Basic-auth credential is attached too;- * explicit `options.headers` still win over both injected headers (they never- * collide in practice). The `peer` arg is optional so existing two-arg callers+ * `peer` record (third arg) so its credential is attached too (the pair token+ * and/or stored Basic credential, see peerCredentialHeaders); explicit+ * `options.headers` still win over the injected headers. The `peer` arg is optional so existing two-arg callers* keep working.*/export async function peerFetch(url, options = {}, peer = null) {const callerHeaders = normalizeHeaders(options.headers);+ const selfId = await selfInstanceId();// Scope the pair credential to the record-push endpoint; never disclose it// to general peer queries, redirects, assets, or announcement responses.const syncHeaders = peer?.syncSecret && new URL(url).pathname === '/api/peer-sync/push'@@ -75,7 +115,11 @@ export async function peerFetch(url, options = {}, peer = null) {...options,...(Object.keys(syncHeaders).length ? { redirect: 'error' } : {}),headers: {- ...dropOverridden({ ...await selfInstanceHeader(), ...(peer ? peerAuthHeaders(peer) : {}), ...syncHeaders }, callerHeaders),+ ...dropOverridden({+ ...(selfId ? { [PEER_INSTANCE_HEADER]: selfId } : {}),+ ...peerCredentialHeaders(peer, selfId),+ ...syncHeaders,+ }, callerHeaders),...callerHeaders,},};@@ -146,13 +190,15 @@ function dropOverridden(injected, callerHeaders) {}/**- * Socket.IO client options for a peer connection, with the peer's Basic-auth- * credential injected as `extraHeaders` so the handshake survives a 401-gating- * proxy. In Node both the polling and `ws` websocket transports honor- * `extraHeaders`, so the relay authenticates regardless of which transport wins.+ * Socket.IO client options for a peer connection, with the same credential+ * headers as `peerFetch` injected as `extraHeaders`. In Node both the polling+ * and `ws` websocket transports honor `extraHeaders`, so the relay+ * authenticates regardless of which transport wins. Synchronous, so it reads+ * the memoized instance id: the relay connects only after a successful probe,+ * which has already resolved it; a cold cache degrades to the Basic credential.*/export function peerSocketOptionsFor(peer) {- const authHeaders = peerAuthHeaders(peer);+ const authHeaders = peerCredentialHeaders(peer, cachedSelfInstanceId);if (Object.keys(authHeaders).length === 0) return peerSocketOptions;return { ...peerSocketOptions, extraHeaders: authHeaders };}diff --git a/server/lib/peerHttpClient.test.js b/server/lib/peerHttpClient.test.jsindex a594364bc2..5f5c804827 100644--- a/server/lib/peerHttpClient.test.js+++ b/server/lib/peerHttpClient.test.js@@ -83,6 +83,7 @@ import {readPeerBody,PEER_BODY_IDLE_TIMEOUT,peerAuthHeaders,+ derivePeerAuthToken,__resetSelfInstanceIdForTests,} from './peerHttpClient.js';import { RESPONSE_TOO_LARGE } from './httpClient.js';@@ -129,6 +130,40 @@ describe('peerHttpClient', () => {expect(calls[0].options.headers.Authorization).toBe(`Basic ${Buffer.from('alice:pw').toString('base64')}`);});+ describe('paired peer credential (#8356)', () => {+ const syncSecret = 'example-pair-secret-0123456789-abcdef';+ const basic = `Basic ${Buffer.from(':example-password').toString('base64')}`;+ const token = () => derivePeerAuthToken(syncSecret, 'self-instance-id');++ it('sends only the pair token once the receiver has confirmed it', async () => {+ await peerFetch('http://peer.example/api/cos/agents', {}, {+ auth: { password: 'example-password' }, syncSecret, peerAuthAccepted: true,+ });+ const { headers } = calls[0].options;+ expect(headers['X-PortOS-Peer-Auth']).toBe(token());+ expect(headers['X-PortOS-Instance-Id']).toBe('self-instance-id');+ expect(Object.keys(headers).some((k) => k.toLowerCase() === 'authorization')).toBe(false);+ // The token is an HMAC, never the secret itself, and differs per sender.+ expect(headers['X-PortOS-Peer-Auth']).not.toContain(syncSecret);+ expect(derivePeerAuthToken(syncSecret, 'other-instance-id')).not.toBe(token());+ });++ it('keeps Basic beside the token until the receiver confirms it, and for unpaired peers', async () => {+ await peerFetch('http://peer.example/api/cos/agents', {}, { auth: { password: 'example-password' }, syncSecret });+ expect(calls[0].options.headers.Authorization).toBe(basic);+ expect(calls[0].options.headers['X-PortOS-Peer-Auth']).toBe(token());+ await peerFetch('http://peer.example/api/cos/agents', {}, { auth: { password: 'example-password' }, peerAuthAccepted: true });+ expect(calls[1].options.headers.Authorization).toBe(basic);+ expect(calls[1].options.headers['X-PortOS-Peer-Auth']).toBeUndefined();+ });++ it('puts the same credential on the socket relay handshake', async () => {+ await peerFetch('http://peer.example/x'); // warms the memoized instance id+ const opts = peerSocketOptionsFor({ auth: { password: 'example-password' }, syncSecret, peerAuthAccepted: true });+ expect(opts.extraHeaders).toEqual({ 'X-PortOS-Instance-Id': 'self-instance-id', 'X-PortOS-Peer-Auth': token() });+ });+ });+it('lets explicit caller headers win', async () => {await peerFetch('http://peer.example/x', { headers: { 'X-PortOS-Instance-Id': 'explicit' } });expect(calls[0].options.headers['X-PortOS-Instance-Id']).toBe('explicit');diff --git a/server/lib/schemaVersions.js b/server/lib/schemaVersions.jsindex d070ad08d1..5ced5c43a7 100644--- a/server/lib/schemaVersions.js+++ b/server/lib/schemaVersions.js@@ -792,6 +792,15 @@ export const PORTOS_SCHEMA_VERSIONS = Object.freeze({// The key exists so the NEXT incompatible daily-log change can bump to 2 and// have v1 receivers reject it.meatspace: 1,+ // v1 = the paired-peer credential (#8356): `X-PortOS-Peer-Auth`, an HMAC of the+ // pair `syncSecret` bound to the sender's instance id, replacing the instance+ // password over HTTP Basic between paired peers. Not a record or snapshot+ // category — it versions the authentication handshake. A receiver advertises it+ // as `peerAuth.version` in GET /api/system/health/details together with+ // `peerAuth.accepted` (whether THIS request's token verified). A sender drops+ // the Basic header only after that confirmation (`peer.peerAuthAccepted`), so+ // an older receiver, which never answers, keeps getting Basic.+ peerAuth: 1,// NOTE: `videoHistory` is intentionally NOT listed here. The version gate// rejects the ENTIRE snapshot/push payload on ANY ahead-mismatch (the// comparator walks the union of keys), so declaring a brand-new key would@@ -883,11 +892,15 @@ export const RECORD_KIND_SCHEMA_CATEGORIES = Object.freeze({* `applyRemote` through SNAPSHOT_CATEGORY_SCHEMA_KEYS; meatspace is never a* per-record push.*+ * `peerAuth` (#8356): the peer credential handshake version, advertised by the+ * receiver's health details; it gates which header a sender presents, never a+ * record transfer.+ ** Do NOT add a real record-push category here to silence the guard — that would* leave its push transfers ungated (silent cross-install corruption). Only* genuinely non-push categories belong.*/-export const NON_RECORD_SCHEMA_CATEGORIES = Object.freeze(new Set(['mediaLibrary', 'cosHistory', 'cosTasks', 'appQuality', 'eidoverseFoundations', 'meatspace']));+export const NON_RECORD_SCHEMA_CATEGORIES = Object.freeze(new Set(['mediaLibrary', 'cosHistory', 'cosTasks', 'appQuality', 'eidoverseFoundations', 'meatspace', 'peerAuth']));/*** Lazy-read the current PortOS version from the ROOT package.json so adiff --git a/server/routes/federatedMedia.test.js b/server/routes/federatedMedia.test.jsindex f716e31a4e..f0487f615c 100644--- a/server/routes/federatedMedia.test.js+++ b/server/routes/federatedMedia.test.js@@ -170,7 +170,7 @@ describe('federated media routes', () => {it('refuses an unauthorized peer before writing anything', async () => {provider.authorize.mockRejectedValueOnce(Object.assign(- new Error('Verified peer Basic authentication is required'),+ new Error('Verified peer authentication is required'),{ status: 403, code: 'MEDIA_PROVIDER_PEER_AUTH_REQUIRED' },));const response = await request(buildApp()).post('/api/federation/media/v1/assets')diff --git a/server/routes/systemHealth.js b/server/routes/systemHealth.jsindex 006f51dd33..75a24eb5df 100644--- a/server/routes/systemHealth.js+++ b/server/routes/systemHealth.js@@ -20,6 +20,7 @@ import { getActiveProcessing } from '../services/activeProcessing.js';import { getMediaCapacity } from '../services/mediaCapacity.js';import { runningAgentsByTaskId, unclaimedTaskIds } from '../lib/cosSpawnWindow.js';import { getBuildIdentity } from '../lib/buildIdentity.js';+import { PORTOS_SCHEMA_VERSIONS } from '../lib/schemaVersions.js';// Disk capacity remains actionable. Memory thresholds are retained on the wire// for older clients, but no longer generate warnings or degrade health.@@ -406,6 +407,13 @@ router.get('/health/details', asyncHandler(async (req, res) => {instanceId: self?.instanceId ?? null,version,overallHealth,+ // Peer credential handshake (#8356): `accepted` tells the probing peer that+ // THIS request authenticated with its pair token, so it can stop sending+ // the instance password. Older receivers omit the field; senders keep Basic.+ peerAuth: {+ version: PORTOS_SCHEMA_VERSIONS.peerAuth,+ accepted: req.portosAuthContext?.method === 'peer',+ },warnings,system: {uptime,diff --git a/server/services/authGate.js b/server/services/authGate.jsindex b77f2d6a8e..bad921fb1e 100644--- a/server/services/authGate.js+++ b/server/services/authGate.js@@ -1,4 +1,4 @@-import { createHash } from 'node:crypto';+import { createHash, timingSafeEqual } from 'node:crypto';import { isIP } from 'node:net';import { extractToken, isAuthEnabled, verifyPassword, verifySession } from './auth.js';// Shared with sidecar processes (lib/sidecarAuthGate.js) so the Autofixer UI@@ -8,6 +8,8 @@ import { getSettings, settingsEvents } from './settings.js';import { isRegistryPublic } from '../lib/apiRegistry.js';import { GATED_NON_API_PREFIXES, isAlwaysPublicApiPath } from '../lib/apiAccessPolicy.js';import { sendErrorResponse, ServerError } from '../lib/errorHandler.js';+import { derivePeerAuthToken, PEER_AUTH_HEADER, PEER_INSTANCE_HEADER } from '../lib/peerHttpClient.js';+import { loadData as loadInstances } from './instanceIdentity.js';// Paths that bypass the auth gate even when a password is set:// - /api/auth/status, /api/auth/whoami, /api/auth/login → the login UI@@ -37,6 +39,41 @@ const verifyBasicPassword = async (password) => {return ok;};+// A paired peer's token (#8356) resolves to its peer record. Only an enabled+// peer holding a pair secret can match; a corrupt/unreadable registry fails+// closed to "not a peer" so the request falls through to the other methods.+const pairedPeerFor = async (instanceId) => {+ if (typeof instanceId !== 'string' || !instanceId) return null;+ const data = await loadInstances().catch(() => null);+ const peers = Array.isArray(data?.peers) ? data.peers : [];+ return peers.find((p) => p?.instanceId === instanceId && p.enabled !== false+ && typeof p.syncSecret === 'string' && p.syncSecret.length >= 32) ?? null;+};++const verifyPeerToken = async (headers) => {+ const token = headers?.[PEER_AUTH_HEADER.toLowerCase()];+ const instanceId = headers?.[PEER_INSTANCE_HEADER.toLowerCase()];+ if (typeof token !== 'string' || !token) return null;+ const peer = await pairedPeerFor(instanceId);+ if (!peer) return null;+ const expected = Buffer.from(derivePeerAuthToken(peer.syncSecret, instanceId));+ const given = Buffer.from(token);+ return expected.length === given.length && timingSafeEqual(expected, given) ? peer : null;+};++// A paired peer that still authenticates with this install's password (an+// older sender, or a pair secret that differs between the two machines) is+// told once per process: the password it holds is operator authority here.+const warnedBasicPeers = new Set();+const warnIfPairedPeerUsedBasic = async (headers) => {+ const instanceId = headers?.[PEER_INSTANCE_HEADER.toLowerCase()];+ if (typeof instanceId !== 'string' || warnedBasicPeers.has(instanceId)) return;+ const peer = await pairedPeerFor(instanceId);+ if (!peer) return;+ warnedBasicPeers.add(instanceId);+ console.warn(`⚠️ Paired peer ${peer.name || peer.id} authenticated with the instance password instead of its pair credential — update it, re-pair with the same sync secret, then remove the stored password on that machine`);+};+export const __testing = { verifyBasicPassword };const isPublicPath = (path) => {@@ -101,7 +138,16 @@ export const authGate = async (req, res, next) => {req.portosAuthContext = { enabled: true, authenticated: true, method: 'session' };return next();}- // Also accept HTTP Basic auth — used by peer-to-peer federation probes.+ // A paired peer's scoped credential. Checked before Basic so a sender that+ // presents both during the upgrade handshake is identified as the peer.+ const peer = await verifyPeerToken(req.headers);+ if (peer) {+ req.portosAuthContext = { enabled: true, authenticated: true, method: 'peer', peerId: peer.id };+ return next();+ }+ // Also accept HTTP Basic auth — the legacy peer credential, kept so unpaired+ // and not-yet-upgraded peers keep federating (a paired peer that still uses+ // it is warned once per process). It yields `method: 'basic'`, never a session.// The peer sends `Authorization: Basic <base64(:password)>` (the Instances// UI stores username + password; only the password is validated here since// PortOS is single-user). scrypt verification is intentionally slow but runs@@ -109,6 +155,7 @@ export const authGate = async (req, res, next) => {const basicPassword = extractBasicPassword(req);if (basicPassword && await verifyBasicPassword(basicPassword)) {req.portosAuthContext = { enabled: true, authenticated: true, method: 'basic' };+ await warnIfPairedPeerUsedBasic(req.headers);return next();}// /data/* is hit directly by <img>/<audio>/<video> tags which don't show a@@ -129,7 +176,8 @@ const isLoopbackAddress = (value) => {return address === '::1' || (isIP(address) === 4 && address.startsWith('127.'));};-// Host execution needs operator authority, not merely a peer's Basic credential.+// Host execution needs operator authority: a peer's credential — the scoped+// peer token or the legacy Basic password — never qualifies.// Mount after authGate: missing context fails closed. Password-free installs// require loopback socket peers, including the dev proxy caller. Neither req.ip// nor the machine-local warning acknowledgement can grant authority.@@ -167,7 +215,9 @@ export const socketAuthGate = async (socket, next) => {}const token = extractToken(fakeReq);if (await verifySession(token)) return next();- // Also accept HTTP Basic auth for peer socket relay connections.+ // Peer relay connections: the paired peer token, else legacy Basic. Neither+ // can emit events — socket.js re-checks for a real session on every event.+ if (await verifyPeerToken(fakeReq.headers)) return next();const basicPassword = extractBasicPassword(fakeReq);if (basicPassword && await verifyBasicPassword(basicPassword)) return next();const err = new Error('Authentication required');diff --git a/server/services/authGate.test.js b/server/services/authGate.test.jsindex c6592f1dc6..546c538bf5 100644--- a/server/services/authGate.test.js+++ b/server/services/authGate.test.js@@ -1,4 +1,4 @@-import { afterAll, beforeEach, describe, expect, it, vi } from 'vitest';+import { afterAll, afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import express from 'express';import { readFileSync, writeFileSync, rmSync } from 'fs';import { join } from 'path';@@ -28,6 +28,14 @@ vi.mock('../../lib/portosAuthCore.js', async () => {};});+// The peer registry resolves its own path (not through the PATHS proxy), so+// stub its reader: the gate must never read this machine's real instances.json.+const instanceRegistry = vi.hoisted(() => ({ data: { self: null, peers: [] } }));+vi.mock('./instanceIdentity.js', async () => ({+ ...(await vi.importActual('./instanceIdentity.js')),+ loadData: async () => instanceRegistry.data,+}));+// Direct settings.json writes that also drop the getSettings() read cache —// see server/lib/settingsTestUtil.js for why the reset is required here// (a prior setPassword() warms the cache; a bypass-save() write leaves it stale).@@ -646,6 +654,113 @@ describe('host-control authority', () => {});});+describe('paired peer credential (#8356)', () => {+ const PAIR_SECRET = 'example-pair-secret-0123456789-abcdef';+ const PEER_ID = 'peer-example-instance';+ const basicHeader = (password) => `Basic ${Buffer.from(`:${password}`).toString('base64')}`;+ const writePeers = (peers) => { instanceRegistry.data = { self: null, peers }; };+ const pairedPeer = (overrides = {}) => ({+ id: 'peer-record', name: 'Example Peer', instanceId: PEER_ID, enabled: true, syncSecret: PAIR_SECRET, ...overrides,+ });+ const peerHeaders = async (instanceId = PEER_ID, secret = PAIR_SECRET) => {+ const { derivePeerAuthToken } = await import('../lib/peerHttpClient.js');+ return { 'X-PortOS-Instance-Id': instanceId, 'X-PortOS-Peer-Auth': derivePeerAuthToken(secret, instanceId) };+ };+ const buildApp = async () => {+ const { authGate, requireHostControl } = await import('./authGate.js');+ const { default: authRoutes } = await import('../routes/auth.js');+ const app = express();+ app.use(authGate);+ app.use(express.json());+ app.use('/api/auth', authRoutes);+ app.get('/api/example', (req, res) => res.json({ auth: req.portosAuthContext }));+ app.post('/api/peer-sync/push', (req, res) => res.json({ auth: req.portosAuthContext }));+ app.post('/api/commands/execute', requireHostControl, (_req, res) => res.json({ ran: true }));+ return app;+ };+ const withHeaders = (req, headers) => Object.entries(headers).reduce((r, [k, v]) => r.set(k, v), req);++ afterEach(() => {+ instanceRegistry.data = { self: null, peers: [] };+ vi.restoreAllMocks();+ });++ it('authenticates federation reads and pushes as method "peer" but never host control or a session', async () => {+ const auth = await import('./auth.js');+ const { token } = await auth.setPassword({ newPassword: 'example-password' });+ writePeers([pairedPeer()]);+ const app = await buildApp();+ const headers = await peerHeaders();++ const read = await withHeaders(request(app).get('/api/example'), headers);+ expect(read.status).toBe(200);+ expect(read.body.auth).toEqual({ enabled: true, authenticated: true, method: 'peer', peerId: 'peer-record' });+ expect((await withHeaders(request(app).post('/api/peer-sync/push').send({}), headers)).body.auth.method).toBe('peer');++ const exec = await withHeaders(request(app).post('/api/commands/execute').send({}), headers);+ expect(exec.status).toBe(403);+ expect(exec.body.code).toBe('HOST_CONTROL_FORBIDDEN');++ // The token is not the password, so it cannot be exchanged for a session.+ const login = await request(app).post('/api/auth/login').send({ password: headers['X-PortOS-Peer-Auth'] });+ expect(login.status).toBe(401);+ expect(login.headers['set-cookie']).toBeUndefined();++ // Operator session still passes; legacy Basic still reads but is refused host control.+ expect((await request(app).post('/api/commands/execute').set('Cookie', `portos_auth=${token}`).send({})).status).toBe(200);+ const basic = { Authorization: basicHeader('example-password') };+ expect((await withHeaders(request(app).get('/api/example'), basic)).body.auth.method).toBe('basic');+ expect((await withHeaders(request(app).post('/api/commands/execute').send({}), basic)).status).toBe(403);+ });++ it('rejects a token for another instance, a wrong secret, a disabled peer, or an unpaired peer', async () => {+ const auth = await import('./auth.js');+ await auth.setPassword({ newPassword: 'example-password' });+ const app = await buildApp();+ const forged = { ...(await peerHeaders('other-instance')), 'X-PortOS-Instance-Id': PEER_ID };+ const cases = [+ [[pairedPeer()], forged],+ [[pairedPeer()], await peerHeaders(PEER_ID, 'a-different-pair-secret-0123456789-xyz')],+ [[pairedPeer({ enabled: false })], await peerHeaders()],+ [[pairedPeer({ syncSecret: undefined })], await peerHeaders()],+ ];+ for (const [peers, headers] of cases) {+ writePeers(peers);+ expect((await withHeaders(request(app).get('/api/example'), headers)).status).toBe(401);+ }+ });++ it('keeps an unpaired or older peer federating over Basic, warning once when a paired peer still uses it', async () => {+ const auth = await import('./auth.js');+ await auth.setPassword({ newPassword: 'example-password' });+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});+ writePeers([pairedPeer(), pairedPeer({ id: 'unpaired', instanceId: 'unpaired-instance', syncSecret: undefined })]);+ const app = await buildApp();+ const basic = (instanceId) => ({ Authorization: basicHeader('example-password'), 'X-PortOS-Instance-Id': instanceId });++ expect((await withHeaders(request(app).get('/api/example'), basic('unpaired-instance'))).status).toBe(200);+ expect(warn).not.toHaveBeenCalled();+ for (let i = 0; i < 2; i++) {+ expect((await withHeaders(request(app).get('/api/example'), basic(PEER_ID))).body.auth.method).toBe('basic');+ }+ expect(warn).toHaveBeenCalledTimes(1);+ expect(warn.mock.calls[0][0]).toContain('Example Peer');+ });++ it('admits a paired peer relay handshake on the socket gate', async () => {+ const auth = await import('./auth.js');+ await auth.setPassword({ newPassword: 'example-password' });+ writePeers([pairedPeer()]);+ const { socketAuthGate } = await import('./authGate.js');+ const handshake = async (headers) => new Promise((resolve) => {+ socketAuthGate({ handshake: { headers } }, (err) => resolve(err));+ });+ const headers = Object.fromEntries(Object.entries(await peerHeaders()).map(([k, v]) => [k.toLowerCase(), v]));+ expect(await handshake(headers)).toBeUndefined();+ expect((await handshake({ ...headers, 'x-portos-peer-auth': 'f'.repeat(64) }))?.data).toEqual({ code: 'AUTH_REQUIRED' });+ });+});+describe('socketAuthGate middleware', () => {it('is a no-op when auth is disabled', async () => {const { socketAuthGate } = await import('./authGate.js');diff --git a/server/services/dataSync.pipelineUniverse.test.js b/server/services/dataSync.pipelineUniverse.test.jsindex e18611d469..0f04c8e603 100644--- a/server/services/dataSync.pipelineUniverse.test.js+++ b/server/services/dataSync.pipelineUniverse.test.js@@ -1113,6 +1113,8 @@ describe('dataSync — per-category schema gate (cross-key isolation)', () => {// assertion stays honest about what the snapshot map IS and ISN'T// responsible for.const OUT_OF_BAND_SYNC_KEYS = new Set([+ // Peer credential handshake version (#8356), advertised in health details; never a data category.+ 'peerAuth',// Numeric PortOS quality uses its version-validated read-through endpoint, never snapshot writes.'appQuality',// catalog → `POST /api/catalog/sync/apply` (server/services/catalogSync.js)diff --git a/server/services/federatedMediaProvider.js b/server/services/federatedMediaProvider.jsindex e03c3159cb..e36e18f4a3 100644--- a/server/services/federatedMediaProvider.js+++ b/server/services/federatedMediaProvider.js@@ -308,7 +308,8 @@ export function normalizeFederatedMediaProviderConfig(settings) {/*** The provider is stricter than ordinary federation reads: it never inherits* authGate's auth-off bypass and never accepts a browser session. A verified- * Basic credential plus a registered, enabled caller is required every time.+ * peer credential (the paired peer token, or legacy Basic) plus a registered,+ * enabled caller is required every time.* Status discovery is expected to encounter disabled or misconfigured peers,* so callers can mark those denials as warnings: the HTTP response still tells* the consumer exactly why discovery failed, but it stays off this provider's@@ -323,9 +324,9 @@ export async function authorizeFederatedMediaPeer(req, { statusProbe = false } =...(statusProbe ? { severity: 'warning' } : {}),});};- if (req.portosAuthContext?.method !== 'basic' || req.portosAuthContext?.authenticated !== true) {+ if (!['peer', 'basic'].includes(req.portosAuthContext?.method) || req.portosAuthContext?.authenticated !== true) {deny(- 'Verified peer Basic authentication is required',+ 'Verified peer authentication is required','MEDIA_PROVIDER_PEER_AUTH_REQUIRED',403,);diff --git a/server/services/federatedMediaProvider.test.js b/server/services/federatedMediaProvider.test.jsindex cfa4689ced..60026c7a07 100644--- a/server/services/federatedMediaProvider.test.js+++ b/server/services/federatedMediaProvider.test.js@@ -196,6 +196,11 @@ describe('federated media provider authorization', () => {await expect(authorizeFederatedMediaPeer(req)).resolves.toEqual({callerId: 'peer-example', config: config(),});+ // The paired peer token (#8356) is the scoped successor to Basic here.+ await expect(authorizeFederatedMediaPeer({+ ...baseReq,+ portosAuthContext: { enabled: true, authenticated: true, method: 'peer', peerId: 'peer-record' },+ })).resolves.toEqual({ callerId: 'peer-example', config: config() });state.peer.enabled = false;await expect(authorizeFederatedMediaPeer(req)).rejects.toMatchObject({diff --git a/server/services/instances.js b/server/services/instances.jsindex 909f84e998..d51951ba5c 100644--- a/server/services/instances.js+++ b/server/services/instances.js@@ -523,7 +523,15 @@ export async function updatePeer(id, updates) {if (updates.syncSecret !== null && (typeof updates.syncSecret !== 'string' || updates.syncSecret.length < 32 || updates.syncSecret.length > 256)) {throw new Error('Peer sync secret must contain 32 to 256 characters');}- peer.syncSecret = updates.syncSecret;+ if (updates.syncSecret !== peer.syncSecret) {+ peer.syncSecret = updates.syncSecret;+ // The pair token is derived from this secret, so the receiver's earlier+ // confirmation no longer applies: present Basic again (when stored)+ // until the next probe re-confirms, and reconnect the relay with the+ // new headers (#8356).+ peer.peerAuthAccepted = false;+ authChanged = true;+ }// Entering the pair secret is the local inbound-admission action.if (peer.syncSecret && !peer.directions?.includes('inbound')) {const directions = Array.isArray(peer.directions) && peer.directions.length ? peer.directions : ['outbound'];@@ -830,6 +838,13 @@ export async function probePeer(peer) {// Surface "reachable but needs a credential" distinctly from plain offline.// Cleared on any successful probe (including after the user adds the password).entry.authRequired = authRequired;+ // Peer credential handshake (#8356). Latch on the receiver's confirmation+ // that this probe's pair token verified; after that peerFetch stops sending+ // the stored Basic password. A 401/403 unlatches, so a receiver that loses+ // its side of the pairing (or is downgraded) gets Basic again next probe.+ // Other failures (timeouts, offline) keep the last answer.+ if (status === 'online') entry.peerAuthAccepted = lastHealth?.peerAuth?.accepted === true;+ else if (authRequired) entry.peerAuthAccepted = false;entry.lastApps = remoteApps ?? entry.lastApps ?? null;entry.remoteSyncSeqs = remoteSyncSeqs ?? entry.remoteSyncSeqs ?? null;if (normalizePeerMediaProviderConfig(entry).enabled) {diff --git a/server/services/instances.test.js b/server/services/instances.test.jsindex b0607fac49..d7c9758fbb 100644--- a/server/services/instances.test.js+++ b/server/services/instances.test.js@@ -1341,6 +1341,26 @@ describe('instances.js', () => {expect(result.authRequired).toBe(false);});+ it('latches the receiver confirmation of the pair token, and drops it on an auth failure (#8356)', async () => {+ const peer = makePeer({ syncSecret: 'example-pair-secret-0123456789-abcdef' });+ readJSONFile.mockResolvedValue({ self: null, peers: [peer] });+ const health = (body) => ({ ok: true, json: () => Promise.resolve({ instanceId: 'r-id', ...body }) });++ // An older receiver never answers: the sender keeps presenting Basic.+ fetch.mockResolvedValueOnce(health({})).mockResolvedValueOnce(null).mockResolvedValueOnce(null);+ expect((await probePeer(peer)).peerAuthAccepted).toBe(false);++ fetch.mockResolvedValueOnce(health({ peerAuth: { version: 1, accepted: true } }))+ .mockResolvedValueOnce(null).mockResolvedValueOnce(null);+ expect((await probePeer(peer)).peerAuthAccepted).toBe(true);++ // A timeout keeps the confirmation; a 401 (lost pairing, downgrade) clears it.+ fetch.mockRejectedValueOnce(new Error('timeout')).mockResolvedValueOnce(null).mockResolvedValueOnce(null);+ expect((await probePeer(peer)).peerAuthAccepted).toBe(true);+ fetch.mockResolvedValueOnce({ ok: false, status: 401 }).mockResolvedValueOnce(null).mockResolvedValueOnce(null);+ expect((await probePeer(peer)).peerAuthAccepted).toBe(false);+ });+it('should auto-update name from hostname when name is an IP', async () => {const peer = makePeer({ name: '10.0.0.1' });const peers = [peer];diff --git a/server/services/peerSocketRelay.js b/server/services/peerSocketRelay.jsindex ea04eb9e1c..1f4c42e89b 100644--- a/server/services/peerSocketRelay.js+++ b/server/services/peerSocketRelay.js@@ -28,17 +28,21 @@ export function connectToPeer(peer) {reconnectionAttempts: 5,reconnectionDelay: 5000,timeout: CONNECT_TIMEOUT_MS,- // peerSocketOptionsFor injects the peer's Basic-auth credential as- // extraHeaders so the relay handshake survives an auth-gating proxy.+ // peerSocketOptionsFor injects the same credential headers peerFetch sends+ // (the pair token, and Basic until the receiver confirms the token)....peerSocketOptionsFor(peer)});// `host` is required so fetchPeerAgents() can rebuild the HTTPS URL via peerBaseUrl();- // `auth` is carried so its peerFetch presents the same credential as the probe.+ // `auth`, `syncSecret` and `peerAuthAccepted` are carried so its peerFetch+ // presents the same credential as the probe (#8356).const conn = {socket,agents: new Map(),- peer: { id: peer.id, name: peer.name, address: peer.address, host: peer.host ?? null, port: peer.port, auth: peer.auth ?? null }+ peer: {+ id: peer.id, name: peer.name, address: peer.address, host: peer.host ?? null, port: peer.port, auth: peer.auth ?? null,+ syncSecret: peer.syncSecret ?? null, peerAuthAccepted: peer.peerAuthAccepted === true,+ }};peerConnections.set(peer.id, conn);