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: automate peer sync secret pairing
[._.]/ Adam Eivyddf0e19bb806
diff --git a/client/src/components/instances/PeerSyncSecretEditor.jsx b/client/src/components/instances/PeerSyncSecretEditor.jsxindex c680693b5c..610d495fe3 100644--- a/client/src/components/instances/PeerSyncSecretEditor.jsx+++ b/client/src/components/instances/PeerSyncSecretEditor.jsx@@ -1,62 +1,65 @@import { useState } from 'react';-import { updatePeer } from '../../services/api';+import { pairPeerSyncSecret } 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.+// A stored peer password is used once to provision the generated peer-only+// credential. Once the peer confirms it, the password can be removed.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.';+ return 'The saved instance password lets PortOS pair this peer. After it confirms the generated credential, remove the password here.';}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.';+ return 'The instance password stays in use until this peer confirms the generated credential.';}export default function PeerSyncSecretEditor({ peer, onRefresh }) {- const [editing, setEditing] = useState(false);- const [secret, setSecret] = useState('');- const [saving, setSaving] = useState(false);+ const [pairing, setPairing] = useState(false);const passwordHint = storedPasswordHint(peer);- const save = async (value) => {- if (saving || (value !== null && (value.length < 32 || value.length > 256))) return;- setSaving(true);- const result = await updatePeer(peer.id, { syncSecret: value }).catch(() => null);- setSaving(false);+ const hasPassword = Boolean(peer.auth?.hasPassword);++ const pair = async () => {+ if (pairing || !hasPassword) return;+ setPairing(true);+ const result = await pairPeerSyncSecret(peer.id).catch(() => null);+ setPairing(false);if (!result) return;- setSecret('');- setEditing(false);onRefresh();- toast.success(value === null ? 'Peer sync secret removed' : 'Peer sync secret saved');+ toast.success('Peer sync paired');};++ const status = !peer.hasSyncSecret+ ? 'Record pushes paused until this peer is paired'+ : peer.peerAuthAccepted+ ? 'Peer confirmed the matching sync credential'+ : 'Pair credential saved here; peer confirmation is still pending';+return (<div className="mt-2 text-xs space-y-2 min-w-0">- <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 className={peer.hasSyncSecret && peer.peerAuthAccepted ? 'text-port-success' : 'text-port-warning'} role="status">+ {status}</p>+ {!hasPassword && !peer.peerAuthAccepted && (+ <p className="text-port-warning">+ Save this peer’s instance password here to pair automatically.+ </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>- <input id={`peer-sync-secret-${peer.id}`} type="password" autoComplete="new-password"- value={secret} onChange={event => setSecret(event.target.value)} maxLength={256}- className="w-full max-w-md min-w-0 bg-port-bg border border-port-border rounded px-2 py-1"- aria-describedby={`peer-sync-secret-help-${peer.id}`} />- <p id={`peer-sync-secret-help-${peer.id}`} className="text-gray-400">- Enter the same randomly generated secret (32–256 characters) in this peer’s settings on both machines.- Use a different secret for each pair. Sync and category switches still control what is accepted.- Sign in with an instance password to configure peer settings.- </p>- <div className="flex flex-wrap gap-3">- <button disabled={saving || secret.length < 32} onClick={() => save(secret)} className="text-port-success disabled:opacity-50">Save secret</button>- <button disabled={saving} onClick={() => { setSecret(''); setEditing(false); }} className="text-gray-400 disabled:opacity-50">Cancel</button>- {peer.hasSyncSecret && <button disabled={saving} onClick={() => save(null)} className="text-port-error disabled:opacity-50">Remove secret</button>}- </div>- </div>- ) : <button onClick={() => setEditing(true)} className="text-port-accent underline">{peer.hasSyncSecret ? 'Change sync secret' : 'Set sync secret'}</button>}+ {(!peer.peerAuthAccepted || hasPassword) && (+ <button+ type="button"+ onClick={pair}+ disabled={pairing || !hasPassword}+ className="text-port-accent underline disabled:opacity-50 disabled:cursor-not-allowed"+ title={!hasPassword ? 'Save this peer’s instance password first' : undefined}+ >+ {pairing+ ? 'Pairing…'+ : (!peer.hasSyncSecret ? 'Generate & pair' : (peer.peerAuthAccepted ? 'Rotate pair secret' : 'Retry pairing'))}+ </button>+ )}</div>);}diff --git a/client/src/components/instances/PeerSyncSecretEditor.test.jsx b/client/src/components/instances/PeerSyncSecretEditor.test.jsxindex e6132d7cbe..efe0da03b9 100644--- a/client/src/components/instances/PeerSyncSecretEditor.test.jsx+++ b/client/src/components/instances/PeerSyncSecretEditor.test.jsx@@ -1,38 +1,49 @@import { fireEvent, render, screen, waitFor } from '@testing-library/react';import { beforeEach, describe, expect, it, vi } from 'vitest';import PeerSyncSecretEditor from './PeerSyncSecretEditor';-import { updatePeer } from '../../services/api';-vi.mock('../../services/api', () => ({ updatePeer: vi.fn() }));+import { pairPeerSyncSecret } from '../../services/api';+vi.mock('../../services/api', () => ({ pairPeerSyncSecret: vi.fn() }));vi.mock('../ui/Toast', () => ({ default: { success: vi.fn() } }));describe('peer record push pairing', () => {beforeEach(() => vi.clearAllMocks());- it('keeps a failed secret edit available, then clears it only after a successful save', async () => {++ it('generates and sends a secret without exposing it in the browser', async () => {const onRefresh = vi.fn();- updatePeer.mockRejectedValueOnce(new Error('Save failed')).mockResolvedValueOnce({ hasSyncSecret: true });- render(<PeerSyncSecretEditor peer={{ id: 'peer-a', hasSyncSecret: false }} onRefresh={onRefresh} />);- fireEvent.click(screen.getByRole('button', { name: 'Set sync secret' }));- const input = screen.getByLabelText('Shared sync secret');- fireEvent.change(input, { target: { value: 'synthetic-pair-secret-32-characters-long' } });- fireEvent.click(screen.getByRole('button', { name: 'Save secret' }));- await waitFor(() => expect(screen.getByRole('button', { name: 'Save secret' }).disabled).toBe(false));- expect(input.value).toBe('synthetic-pair-secret-32-characters-long');- expect(onRefresh).not.toHaveBeenCalled();- fireEvent.click(screen.getByRole('button', { name: 'Save secret' }));+ pairPeerSyncSecret.mockResolvedValueOnce({ hasSyncSecret: true });+ render(<PeerSyncSecretEditor+ peer={{ id: 'peer-a', auth: { hasPassword: true }, hasSyncSecret: false }}+ onRefresh={onRefresh}+ />);++ fireEvent.click(screen.getByRole('button', { name: 'Generate & pair' }));await waitFor(() => expect(onRefresh).toHaveBeenCalledTimes(1));- expect(updatePeer).toHaveBeenLastCalledWith('peer-a', { syncSecret: 'synthetic-pair-secret-32-characters-long' });+ expect(pairPeerSyncSecret).toHaveBeenCalledWith('peer-a');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 };+ it('reuses the local secret to retry an unconfirmed pairing', async () => {+ pairPeerSyncSecret.mockResolvedValueOnce({ hasSyncSecret: true });+ render(<PeerSyncSecretEditor+ peer={{ id: 'peer-a', auth: { hasPassword: true }, hasSyncSecret: true, peerAuthAccepted: false }}+ onRefresh={vi.fn()}+ />);++ fireEvent.click(screen.getByRole('button', { name: 'Retry pairing' }));+ await waitFor(() => expect(pairPeerSyncSecret).toHaveBeenCalledWith('peer-a'));+ expect(screen.getByText(/confirmation is still pending/)).toBeTruthy();+ });++ it('requires a saved peer password before automatic setup and confirms success', () => {+ const peer = { id: 'peer-a', auth: { username: '', hasPassword: true }, hasSyncSecret: true };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();+ expect(screen.getByText(/instance password stays in use/)).toBeTruthy();+ rerender(<PeerSyncSecretEditor peer={{ ...peer, peerAuthAccepted: true }} onRefresh={vi.fn()} />);+ expect(screen.getByText(/accepts the pair credential/)).toBeTruthy();+ rerender(<PeerSyncSecretEditor peer={{ ...peer, auth: null, peerAuthAccepted: false }} onRefresh={vi.fn()} />);+ expect(screen.getByText(/Save this peer’s instance password here/)).toBeTruthy();+ expect(screen.getByRole('button', { name: 'Retry pairing' }).disabled).toBe(true);+ rerender(<PeerSyncSecretEditor peer={{ ...peer, auth: null, peerAuthAccepted: true }} onRefresh={vi.fn()} />);+ expect(screen.queryByText(/Save this peer’s instance password here/)).toBeNull();});});diff --git a/client/src/services/apiSystem.js b/client/src/services/apiSystem.jsindex 00d972c31e..1d2ccd3b68 100644--- a/client/src/services/apiSystem.js+++ b/client/src/services/apiSystem.js@@ -456,6 +456,7 @@ export const startTailcatServe = (data) => request('/instances/peers/tailcat/serexport const retryTailcatServe = () => request('/instances/peers/tailcat/serve/retry', { method: 'POST' });export const stopTailcatServe = () => request('/instances/peers/tailcat/serve', { method: 'DELETE' });export const updatePeer = (id, data) => request(`/instances/peers/${id}`, { method: 'PUT', body: JSON.stringify(data) });+export const pairPeerSyncSecret = (id, options) => request(`/instances/peers/${id}/pair-secret`, { method: 'POST', ...options });export const removePeer = (id) => request(`/instances/peers/${id}`, { method: 'DELETE' });export const connectPeer = (id) => request(`/instances/peers/${id}/connect`, { method: 'POST' });export const reciprocatePeer = (id, options) => request(`/instances/peers/${id}/reciprocate`, { method: 'POST', ...options });diff --git a/docs/PEER_PUSH_AUTH.md b/docs/PEER_PUSH_AUTH.mdindex 747fe75552..b77e623b77 100644--- a/docs/PEER_PUSH_AUTH.md+++ b/docs/PEER_PUSH_AUTH.md@@ -6,28 +6,35 @@ or its network address does not authorize record ingestion.## Configure a pair-1. Upgrade both instances and sign in with an operator session on each machine.- Peer configuration requires a session even on loopback, because a development- proxy can relay remote traffic over a local socket. Open **Instances**.-2. On each matching peer card, select **Set sync secret** and enter the same- randomly generated secret (32–256 characters). Use a different secret for each- pair; a password manager can generate and transfer it.-3. Enable sync and the desired categories on **each** machine. Saving a secret- admits inbound record pushes; it does not enable categories. Category and- full-mirror changes on one machine no longer override the paired machine's- local settings through an anonymous reciprocal callback.-4. Use **Sync now** to retry pending records. Missing or mismatched secrets return- `PEER_SYNC_AUTH_REQUIRED`; disabled peers, non-inbound peers, sync-off peers,- and disabled categories return `PEER_SYNC_NOT_ADMITTED` before any record,- asset, tombstone cursor, or subscription write.--To revoke or rotate a pair, remove or replace its sync secret. Secrets stay in the-existing machine-local `instances.json` peer configuration, are stripped from-client/socket and announcement payloads, and never travel in record bodies. The-sender attaches `X-PortOS-Peer-Sync-Token` only to `/api/peer-sync/push`, alongside-the peer credential below. HTTP redirects-are refused for credentialed pushes. Use the existing private encrypted transport-(Tailscale or HTTPS) to protect these credentials in transit.+1. Upgrade both instances and sign in to the instance where you want to start+ pairing. The peer must already be registered on both machines, and this+ instance must have the peer's instance password saved on its peer card.+2. On that peer card, select **Generate & pair**. PortOS creates a random secret,+ sends it to the peer's matching record using the saved password for this+ one-time setup request, and stores it locally. The secret is never shown in+ the browser or returned by either API. **Retry pairing** resends the existing+ secret; **Rotate pair secret** creates and sends a new one.+3. Enable sync and the desired categories on each machine. Pairing admits+ authenticated pushes but does not enable categories. Category and full-mirror+ changes on one machine do not override the paired machine's local settings+ through an anonymous reciprocal callback.+4. Use **Sync now** to retry pending records. A missing or mismatched secret+ returns `PEER_SYNC_AUTH_REQUIRED`; pair the peer from its **Instances** page.+ Disabled peers, non-inbound peers, sync-off peers, and disabled categories+ return `PEER_SYNC_NOT_ADMITTED` before any record, asset, tombstone cursor, or+ subscription write.++The one-time `POST /api/instances/peers/pair-secret` bootstrap accepts a verified+instance-password Basic credential only for the caller's already-registered peer+identity. A scoped peer token cannot call it or change local peer settings.+Redirects are refused. The saved password is not included in the browser response;+after the peer confirms the generated token, it can be removed from the peer card.++Secrets stay in each machine's local `instances.json` peer configuration, are+stripped from client/socket and announcement payloads, and never travel in record+bodies. The sender attaches `X-PortOS-Peer-Sync-Token` only to+`/api/peer-sync/push`, alongside the scoped peer credential. Use the existing+private transport (Tailscale or HTTPS) to protect credentials in transit.## Peer credentials are not operator authority@@ -72,6 +79,11 @@ GET includes HEAD. Paths with `.`/`..`/empty segments or encoded separatorsare refused. The generic `GET /api/instances/peers/:id/query` proxy reaches onlythese paths on a paired peer.+`POST /api/instances/peers/pair-secret` is a separate Basic-auth bootstrap, not+part of `PEER_API_SURFACE`: it accepts only a verified instance password, binds+the request to the caller's existing peer identity, and stores only that peer's+generated sync secret. A scoped peer token is refused on this path.+Removing an entry is a breaking change for older peers that still call it: theyreceive `403 PEER_SCOPE_FORBIDDEN`, and the receiver logs one `⛔ Peer … refusedoutside the federation surface` line per peer, method, and path. Adding a peer@@ -80,7 +92,8 @@ call site means adding its entry in the same change.Legacy HTTP Basic is the instance password itself, so it keeps operator reach(`method: 'basic'`, still refused host control). Its holder can already sign inat `/api/auth/login`, and the companion app uses it as a full session-(`docs/COMPANION_APP_API.md`). Pair each peer so it stops sending the password.+(`docs/COMPANION_APP_API.md`). The saved password is used once for pair setup;+after the peer confirms the scoped credential, remove the stored password.Rollout without breaking older installs:@@ -105,16 +118,18 @@ The handshake version is `peerAuth` in `server/lib/schemaVersions.js`.Existing peer records remain intact. No secret is synthesized or trusted fromnetwork discovery. After upgrading, incoming record pushes pause until the pairis configured, and existing pending subscriptions can retry afterward. Older-senders cannot authenticate to an upgraded receiver; upgrade and pair them. New-senders retain the record envelope's existing schema compatibility handling for-older receivers, which ignore the additional HTTP header. An older receiver-still needs to upgrade to enforce admission itself.+senders cannot authenticate to an upgraded receiver; upgrade and pair them.+Automatic pairing requires the pair-secret bootstrap endpoint on the remote+instance, so upgrade both peers before pairing. New senders retain the record+envelope's existing schema compatibility handling for older receivers, which+ignore the additional HTTP header. An older receiver still needs to upgrade to+enforce admission itself.An explicit record pull uses the locally configured peer destination and verifiesthat the response's source, kind, and record ID match that request. It stillrequires local pairing, an enabled peer, sync consent, and category permission.Discovery may list an unpaired peer; discovery alone cannot admit its record pushes.-Peer configuration changes require a verified operator session. If the instance-password is unset, set one and sign in to configure the pair; it may be disabled-after pairing. The peer-specific checks continue to apply while the global-password is unset. Existing host-issued operator session tokens also work.+Local peer configuration changes require a verified operator session. The+one-time remote bootstrap requires the saved instance password and is restricted+to installing a generated pair secret on the caller's matching peer record.+Existing host-issued operator session tokens also work.diff --git a/server/lib/apiAccessPolicy.js b/server/lib/apiAccessPolicy.jsindex 9e21715efa..900ed2573c 100644--- a/server/lib/apiAccessPolicy.js+++ b/server/lib/apiAccessPolicy.js@@ -17,7 +17,8 @@ export const isAlwaysPublicApiPath = (path) => alwaysPublicPathSet.has(path);// The federation surface a paired peer's scoped credential (`method: 'peer'`,// #8356) may reach. Everything else — agent spawns, app lifecycle, git/file-// routes, settings writes — needs an operator session (#8387). Each entry+// routes, settings writes — needs an operator session (#8387), except the+// separately listed one-time Basic-auth pair bootstrap. Each entry// matches one `path` exactly (a trailing `/` is ignored) or every path under// `prefix`; `methods: null` admits any method. This list IS the peer contract// across versions: dropping an entry makes an older peer that still calls it@@ -61,6 +62,13 @@ export const PEER_API_SURFACE = Object.freeze([{ prefix: '/data/writers-room/works/', methods: READ },]);+// One explicit, Basic-authenticated bootstrap operation provisions a generated+// pair secret onto the caller's existing peer record. It is deliberately not+// in PEER_API_SURFACE: a scoped peer token cannot change local peer settings.+export const PEER_BASIC_BOOTSTRAP_SURFACE = Object.freeze([+ { path: '/api/instances/peers/pair-secret', methods: Object.freeze(['POST']) },+]);+// Dot segments and empty segments never appear in a URL a peer builds; refusing// them keeps a prefix match from being argued past by a path that a later layer// might normalize differently.@@ -74,3 +82,11 @@ export const isPeerApiRequestAllowed = (method, path) => {return PEER_API_SURFACE.some((rule) => (rule.methods === ANY_METHOD || rule.methods.includes(verb))&& (rule.path ? rule.path === exact : path.startsWith(rule.prefix) && path.length > rule.prefix.length));};++/** Whether a path is reserved for a caller verified with instance-password Basic auth. */+export const isPeerBasicBootstrapRequest = (method, path) => {+ if (typeof path !== 'string' || typeof method !== 'string' || hasAmbiguousSegment(path)) return false;+ const verb = method.toUpperCase();+ const exact = path.length > 1 && path.endsWith('/') ? path.slice(0, -1) : path;+ return PEER_BASIC_BOOTSTRAP_SURFACE.some((rule) => rule.methods.includes(verb) && rule.path === exact);+};diff --git a/server/lib/apiAccessPolicy.test.js b/server/lib/apiAccessPolicy.test.jsindex 1d8c2c4550..29ba694229 100644--- a/server/lib/apiAccessPolicy.test.js+++ b/server/lib/apiAccessPolicy.test.js@@ -2,7 +2,7 @@ import { describe, it, expect } from 'vitest';import { readdirSync, readFileSync } from 'node:fs';import { fileURLToPath } from 'node:url';import { dirname, join } from 'node:path';-import { isAlwaysPublicApiPath, isPeerApiRequestAllowed } from './apiAccessPolicy.js';+import { isAlwaysPublicApiPath, isPeerApiRequestAllowed, isPeerBasicBootstrapRequest } from './apiAccessPolicy.js';const SERVER_ROOT = join(dirname(fileURLToPath(import.meta.url)), '..');@@ -32,6 +32,7 @@ const peerCallSitePaths = () => {const reachable = (path) => ['GET', 'POST'].some((method) => isAlwaysPublicApiPath(path)|| isPeerApiRequestAllowed(method, path)+ || isPeerBasicBootstrapRequest(method, path)|| isPeerApiRequestAllowed(method, `${path}${path.endsWith('/') ? '' : '/'}x`));describe('peer API surface (#8387)', () => {@@ -50,6 +51,9 @@ describe('peer API surface (#8387)', () => {expect(isPeerApiRequestAllowed('GET', '/api/apps/')).toBe(true);// Operator mutations beside allowed reads stay closed.expect(isPeerApiRequestAllowed('POST', '/api/peer-sync/sync-now')).toBe(false);+ expect(isPeerApiRequestAllowed('POST', '/api/instances/peers/pair-secret')).toBe(false);+ expect(isPeerBasicBootstrapRequest('POST', '/api/instances/peers/pair-secret')).toBe(true);+ expect(isPeerBasicBootstrapRequest('GET', '/api/instances/peers/pair-secret')).toBe(false);expect(isPeerApiRequestAllowed('POST', '/api/sync/brain/apply')).toBe(false);expect(isPeerApiRequestAllowed('POST', '/api/apps/example-app/restart')).toBe(false);expect(isPeerApiRequestAllowed('GET', '/api/apps/example-app')).toBe(false);diff --git a/server/routes/instances.js b/server/routes/instances.jsindex 7648ea2422..2c374e80d9 100644--- a/server/routes/instances.js+++ b/server/routes/instances.js@@ -19,6 +19,8 @@ import * as tailcatPeer from '../services/tailcatPeer.js';import * as tailcatServe from '../services/tailcatServe.js';import { getTailscaleStatus } from '../lib/tailscale.js';import { federatedMediaPeerSettingsSchema, optionalBooleanMap, validateRequest } from '../lib/validation.js';+import { PEER_INSTANCE_HEADER } from '../lib/peerHttpClient.js';+import { isPeerBasicBootstrapRequest } from '../lib/apiAccessPolicy.js';const router = Router();@@ -31,7 +33,16 @@ router.use(asyncHandler(async (req, _res, next) => {// Vite and other private transports can forward a remote request over a// loopback socket. Neither that socket nor supplied Origin/Host proves the// operator's identity. Verify the existing session even when auth is off.- if (!isCrossOrigin(req) && await verifySession(extractToken(req))) return next();+ if (!isCrossOrigin(req) && await verifySession(extractToken(req))) {+ req.peerSettingsOperator = true;+ return next();+ }+ // The pairing callback is the only peer-settings mutation accepted with+ // Basic auth. It is bound to the caller's existing peer identity below and+ // installs only a peer-scoped secret; peer tokens still cannot reach it.+ if (req.portosAuthContext?.authenticated === true+ && req.portosAuthContext.method === 'basic'+ && isPeerBasicBootstrapRequest(req.method, `/api/instances${req.path.toLowerCase()}`)) return next();throw new ServerError('Sign in with an operator session to change peer settings', {status: 403, code: 'PEER_SETTINGS_OPERATOR_REQUIRED',});@@ -110,6 +121,8 @@ const reciprocalSyncSchema = z.object({fullSync: z.boolean().optional()});+const pairSecretSchema = z.object({ syncSecret: z.string().min(32).max(256) });+// GET /api/instances — list self + all peersrouter.get('/', asyncHandler(async (req, res) => {const [self, peers, syncStatus] = await Promise.all([@@ -344,6 +357,13 @@ router.put('/peers/:id', asyncHandler(async (req, res) => {res.json(instances.sanitizePeerForClient(peer));}));+// POST /api/instances/peers/:id/pair-secret — generate and provision a pair+// secret on this peer and the remote instance without exposing it to the UI.+router.post('/peers/:id/pair-secret', asyncHandler(async (req, res) => {+ const peer = await instances.pairPeerSyncSecret(req.params.id);+ res.json(instances.sanitizePeerForClient(peer));+}));+// DELETE /api/instances/peers/:id — remove peerrouter.delete('/peers/:id', asyncHandler(async (req, res) => {const removed = await instances.removePeer(req.params.id);@@ -374,6 +394,29 @@ router.post('/peers/sync-categories', asyncHandler(async (req, res) => {res.json({ applied: changed });}));+// POST /api/instances/peers/pair-secret — one-time setup using the instance+// password, bound to the caller's already-registered peer identity. The raw+// secret is persisted locally and never returned to the caller.+router.post('/peers/pair-secret', asyncHandler(async (req, res) => {+ if (req.peerSettingsOperator !== true+ && !(req.portosAuthContext?.authenticated === true+ && req.portosAuthContext.method === 'basic')) {+ throw new ServerError('Pairing requires an operator session or the peer’s saved instance password.', {+ status: 403, code: 'PEER_PAIR_OPERATOR_REQUIRED',+ });+ }+ const { syncSecret } = validateRequest(pairSecretSchema, req.body || {});+ const instanceId = req.get(PEER_INSTANCE_HEADER);+ if (!z.string().uuid().safeParse(instanceId).success) {+ throw new ServerError('A valid peer instance identity is required for pairing.', {+ status: 400, code: 'PEER_IDENTITY_REQUIRED',+ });+ }+ const peer = await instances.acceptPeerSyncSecretFromPeer(instanceId, syncSecret);+ if (!peer) throw new ServerError('This instance is not registered as a peer here.', { status: 404, code: 'PEER_NOT_FOUND' });+ res.json({ paired: true });+}));+// POST /api/instances/peers/:id/reciprocate — explicit "make all enabled// categories mutual" for an existing (likely one-directional) peer. Pushes our// current category map to the peer so it enables the same toward us.diff --git a/server/routes/instances.test.js b/server/routes/instances.test.jsindex baf87289a1..9cc51a0b94 100644--- a/server/routes/instances.test.js+++ b/server/routes/instances.test.js@@ -19,6 +19,8 @@ vi.mock('../services/syncOrchestrator.js', () => ({vi.mock('../services/instances.js', async (importOriginal) => ({DEFAULT_SYNC_CATEGORIES: (await importOriginal()).DEFAULT_SYNC_CATEGORIES,applyReciprocalSync: vi.fn(),+ pairPeerSyncSecret: vi.fn(),+ acceptPeerSyncSecretFromPeer: vi.fn(),updatePeer: vi.fn(),addPeer: vi.fn(),sanitizePeerForClient: vi.fn((peer) => peer),@@ -427,6 +429,49 @@ describe('GET /api/instances/peers/:id/full-sync-coverage', () => {describe('local peer admission configuration', () => {beforeEach(() => { vi.clearAllMocks(); vi.mocked(verifySession).mockResolvedValue(false); });+ it('starts automatic pairing from an authenticated local session', async () => {+ vi.mocked(verifySession).mockResolvedValue(true);+ instances.pairPeerSyncSecret.mockResolvedValue({ id: 'peer-a', hasSyncSecret: true });+ const res = await request(buildApp()).post('/api/instances/peers/peer-a/pair-secret');+ expect(res.status).toBe(200);+ expect(instances.pairPeerSyncSecret).toHaveBeenCalledWith('peer-a');+ });++ it('accepts the one-time bootstrap only from Basic auth and a registered peer identity', async () => {+ const app = express();+ app.use(express.json());+ app.use((req, _res, next) => {+ req.portosAuthContext = { enabled: true, authenticated: true, method: 'basic' };+ next();+ });+ app.use('/api/instances', instancesRoutes);+ app.use(errorMiddleware);+ const instanceId = '191aaece-a492-41ee-a66d-d4661eadc132';+ instances.acceptPeerSyncSecretFromPeer.mockResolvedValue({ id: 'peer-a' });+ const res = await request(remoteRequestHandler(app)).post('/api/instances/peers/pair-secret')+ .set('X-PortOS-Instance-Id', instanceId)+ .send({ syncSecret: 'synthetic-pair-secret-32-characters-long' });+ expect(res.status).toBe(200);+ expect(res.body).toEqual({ paired: true });+ expect(instances.acceptPeerSyncSecretFromPeer).toHaveBeenCalledWith(instanceId, 'synthetic-pair-secret-32-characters-long');+ });++ it('does not let a scoped peer credential use the setup endpoint', async () => {+ const app = express();+ app.use(express.json());+ app.use((req, _res, next) => {+ req.portosAuthContext = { enabled: true, authenticated: true, method: 'peer' };+ next();+ });+ app.use('/api/instances', instancesRoutes);+ app.use(errorMiddleware);+ const res = await request(remoteRequestHandler(app)).post('/api/instances/peers/pair-secret')+ .set('X-PortOS-Instance-Id', '191aaece-a492-41ee-a66d-d4661eadc132')+ .send({ syncSecret: 'synthetic-pair-secret-32-characters-long' });+ expect(res.status).toBe(403);+ expect(instances.acceptPeerSyncSecretFromPeer).not.toHaveBeenCalled();+ });+it('rejects an anonymous remote transport even when it forwards localhost headers', async () => {const res = await request(remoteRequestHandler(buildApp())).put('/api/instances/peers/peer-a').set('Host', 'localhost').set('Origin', 'http://localhost').set('X-Forwarded-For', '127.0.0.1')diff --git a/server/services/authGate.js b/server/services/authGate.jsindex 1132a2ecc1..0c24e3d921 100644--- a/server/services/authGate.js+++ b/server/services/authGate.js@@ -6,7 +6,12 @@ import { extractToken, isAuthEnabled, verifyPassword, verifySession } from './auimport { DEV_PROXY_CLIENT_ADDRESS_HEADER, extractBasicPassword, isCrossOrigin } from '../../lib/portosAuthCore.js';import { getSettings, settingsEvents } from './settings.js';import { isRegistryPublic } from '../lib/apiRegistry.js';-import { GATED_NON_API_PREFIXES, isAlwaysPublicApiPath, isPeerApiRequestAllowed } from '../lib/apiAccessPolicy.js';+import {+ GATED_NON_API_PREFIXES,+ isAlwaysPublicApiPath,+ isPeerApiRequestAllowed,+ isPeerBasicBootstrapRequest,+} 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';@@ -71,7 +76,7 @@ const warnIfPairedPeerUsedBasic = async (headers) => {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`);+ console.warn(`⚠️ Paired peer ${peer.name || peer.id} authenticated with the instance password instead of its pair credential — pair it again, then remove the stored password on that machine`);};// Logged once per peer + method + path per process (bounded): an older or@@ -183,7 +188,9 @@ 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);+ // Pair-secret setup intentionally uses the saved instance password once to+ // provision the scoped credential; this is not a fallback federation call.+ if (!isPeerBasicBootstrapRequest(req.method, path)) await warnIfPairedPeerUsedBasic(req.headers);return next();}// /data/* is hit directly by <img>/<audio>/<video> tags which don't show adiff --git a/server/services/instances.js b/server/services/instances.jsindex d51951ba5c..49d69d39c3 100644--- a/server/services/instances.js+++ b/server/services/instances.js@@ -17,8 +17,9 @@ import { instanceEvents } from './instanceEvents.js';import { connectToPeer, disconnectFromPeer } from './peerSocketRelay.js';import { DEFAULT_PEER_PORT } from '../lib/ports.js';import { peerBaseUrl } from '../lib/peerUrl.js';-import { peerFetch } from '../lib/peerHttpClient.js';+import { peerFetch, peerAuthHeaders, PEER_AUTH_HEADER } from '../lib/peerHttpClient.js';import { withAbortTimeout } from '../lib/abortTimeout.js';+import { ServerError } from '../lib/errorHandler.js';import { getSelfHost } from '../lib/peerSelfHost.js';import { getTailscaleStatus } from '../lib/tailscale.js';import { autoSubscribePeerToAllRecords } from './sharing/recordEvents.js';@@ -499,7 +500,7 @@ export async function removePeer(id, { stopTransport = true } = {}) {return removed;}-export async function updatePeer(id, updates) {+export async function updatePeer(id, updates, { probe = true } = {}) {let hostChanged = false;// Credential edits must reconnect the live socket relay (it pins the// Basic-auth header into extraHeaders at connect time), not just the next@@ -657,7 +658,7 @@ export async function updatePeer(id, updates) {// bypasses the nextProbeAt gate and, on success, resets backoff + reconnects// the relay with the new credential. Fire-and-forget; failure just re-arms// backoff as before.- if (authChanged && result && result.enabled !== false) {+ if (probe && authChanged && result && result.enabled !== false) {probePeer(result).catch((err) => console.log(`⚠️ Probe after credential change failed: ${err.message}`));}// Backfill-subscribe every local record of any kind whose category just@@ -689,6 +690,112 @@ export async function updatePeer(id, updates) {return result;}+/**+ * Generate and provision the same pair secret on both ends of a peer link.+ * The peer's saved instance password is used only for this one setup request;+ * subsequent federation requests use the scoped pair token.+ */+const peerPairingQueue = createKeyCachedQueue();++export function pairPeerSyncSecret(id) {+ return peerPairingQueue(id, () => pairPeerSyncSecretNow(id));+}++async function pairPeerSyncSecretNow(id) {+ const peer = (await getPeers()).find((item) => item.id === id);+ if (!peer) throw new ServerError('Peer not found', { status: 404 });+ if (!peer.instanceId || peer.instanceId === UNKNOWN_INSTANCE_ID) {+ throw new ServerError('Probe or connect this peer before pairing sync.', { status: 409, code: 'PEER_IDENTITY_REQUIRED' });+ }+ if (typeof peer.auth?.password !== 'string' || !peer.auth.password) {+ throw new ServerError('Save this peer’s instance password before pairing automatically.', {+ status: 400, code: 'PEER_PAIR_CREDENTIAL_REQUIRED',+ });+ }++ const selfInstanceId = await getInstanceId();+ if (!selfInstanceId || selfInstanceId === UNKNOWN_INSTANCE_ID) {+ throw new ServerError('This instance identity is not ready for peer pairing.', { status: 409, code: 'INSTANCE_IDENTITY_REQUIRED' });+ }+ const syncSecret = typeof peer.syncSecret === 'string' && peer.syncSecret.length >= 32 && peer.peerAuthAccepted !== true+ ? peer.syncSecret+ : crypto.randomBytes(32).toString('base64url');+ const headers = {+ 'Content-Type': 'application/json',+ // Force this one-time bootstrap to use the saved instance password, even+ // if a stale pair token is cached locally. The receiver rejects peer-token+ // authority on this operator-scoped setup route.+ [PEER_AUTH_HEADER]: '',+ ...peerAuthHeaders(peer),+ };+ let response;+ try {+ response = await withAbortTimeout(PROBE_TIMEOUT_MS, (signal) => peerFetch(+ `${peerBaseUrl(peer)}/api/instances/peers/pair-secret`,+ {+ method: 'POST',+ headers,+ body: JSON.stringify({ syncSecret }),+ redirect: 'error',+ signal,+ },+ peer,+ ));+ } catch {+ throw new ServerError('Couldn’t reach this peer to pair the sync secret. Retry when it is online.', {+ status: 502, code: 'PEER_PAIR_UNREACHABLE',+ });+ }++ if (!response.ok) {+ const message = response.status === 401+ ? 'The peer rejected its saved instance password. Update the peer credential, then retry.'+ : response.status === 404+ ? 'The peer could not pair this instance. Upgrade both peers and make sure they are connected.'+ : response.status === 403+ ? 'The peer requires its instance password for automatic pairing. Save that password on this peer, then retry.'+ : `The peer could not pair the sync secret (HTTP ${response.status}).`;+ throw new ServerError(message, { status: 502, code: 'PEER_PAIR_REJECTED' });+ }+ const body = await response.json().catch(() => null);+ if (body?.paired !== true) {+ throw new ServerError('The peer did not confirm sync-secret pairing.', { status: 502, code: 'PEER_PAIR_UNCONFIRMED' });+ }++ const updated = await updatePeer(id, { syncSecret }, { probe: false });+ if (!updated) throw new ServerError('Peer not found', { status: 404 });+ if (updated.enabled !== false) return (await probePeer(updated).catch(() => null)) || updated;+ return updated;+}++/** Save a pair secret only for the already-registered peer named by its identity header. */+export async function acceptPeerSyncSecretFromPeer(instanceId, syncSecret) {+ let changed = false;+ const peer = await withData(async (data) => {+ const matches = data.peers.filter((item) => item.instanceId === instanceId);+ if (matches.length !== 1) return null;+ const entry = matches[0];+ if (entry.syncSecret !== syncSecret) {+ entry.syncSecret = syncSecret;+ entry.peerAuthAccepted = false;+ changed = true;+ }+ // Pairing also records this machine's choice to accept inbound pushes;+ // sync/category flags still decide which records may be written.+ if (entry.syncSecret && !entry.directions?.includes('inbound')) {+ const directions = Array.isArray(entry.directions) && entry.directions.length ? entry.directions : ['outbound'];+ entry.directions = [...directions, 'inbound'];+ changed = true;+ }+ instanceEvents.emit('peers:updated', data.peers);+ return entry;+ });+ if (changed && peer) disconnectFromPeer(peer.id);+ return peer;+}++const reciprocalSyncQueue = createKeyCachedQueue();+// Per-peer tail that serializes reciprocal-sync sends. Two rapid category// toggles for the same peer each want to push the full resulting map; if their// fire-and-forget requests raced, the earlier (staler) map could land last on@@ -698,8 +805,6 @@ export async function updatePeer(id, updates) {// Per-peer serialization (silence prior + self-pruning tail) via the shared// helper — `work` runs on both fulfil and reject of the prior send, so a failed// send can't break the chain.-const reciprocalSyncQueue = createKeyCachedQueue();-export function enqueueReciprocalSync(peerId) {return reciprocalSyncQueue(peerId, async () => {// Re-read the peer fresh at send time — the last enqueued send wins withdiff --git a/server/services/instances.test.js b/server/services/instances.test.jsindex d7c9758fbb..104e51023f 100644--- a/server/services/instances.test.js+++ b/server/services/instances.test.js@@ -68,6 +68,8 @@ import {peerLogLabel,removePeer,updatePeer,+ pairPeerSyncSecret,+ acceptPeerSyncSecretFromPeer,probePeer,probeAllPeers,queryPeer,@@ -1991,4 +1993,70 @@ describe('instances.js', () => {stopPolling();});});++ describe('automatic peer sync pairing', () => {+ const selfId = '191aaece-a492-41ee-a66d-d4661eadc132';+ const peerId = '9f131a42-3103-4a68-9ad7-5f58d7926c1e';+ const makePeer = (overrides = {}) => ({+ id: 'peer-record', instanceId: peerId, address: '192.0.2.20', port: 5555,+ enabled: true, status: 'online', syncEnabled: true, directions: ['outbound'],+ auth: { username: '', password: 'synthetic-instance-password' },+ ...overrides,+ });++ it('generates one secret, provisions it remotely with Basic auth, then stores it locally', async () => {+ const peer = makePeer();+ readJSONFile.mockResolvedValue({ self: { instanceId: selfId }, peers: [peer] });+ fetch.mockResolvedValue({ ok: true, json: vi.fn().mockResolvedValue({ paired: true }) });++ const updated = await pairPeerSyncSecret(peer.id);+ const pairCall = fetch.mock.calls.find(([url]) => url.endsWith('/api/instances/peers/pair-secret'));+ expect(pairCall).toBeDefined();+ const [, options] = pairCall;+ const headers = Object.fromEntries(Object.entries(options.headers).map(([key, value]) => [key.toLowerCase(), value]));+ const generatedSecret = JSON.parse(options.body).syncSecret;+ expect(generatedSecret).toMatch(/^[A-Za-z0-9_-]{43}$/);+ expect(updated.syncSecret).toBe(generatedSecret);+ expect(peer.syncSecret).toBe(generatedSecret);+ expect(options.redirect).toBe('error');+ expect(headers).toMatchObject({+ authorization: expect.stringMatching(/^Basic /),+ 'x-portos-instance-id': expect.any(String),+ 'x-portos-peer-auth': '',+ });+ });++ it('reuses an unconfirmed local secret when remote provisioning needs a retry', async () => {+ const secret = 'synthetic-pair-secret-32-characters-long';+ const peer = makePeer({ syncSecret: secret, peerAuthAccepted: false });+ readJSONFile.mockResolvedValue({ self: { instanceId: selfId }, peers: [peer] });+ fetch.mockResolvedValue({ ok: true, json: vi.fn().mockResolvedValue({ paired: true }) });++ await pairPeerSyncSecret(peer.id);++ const pairCall = fetch.mock.calls.find(([url]) => url.endsWith('/api/instances/peers/pair-secret'));+ expect(JSON.parse(pairCall[1].body).syncSecret).toBe(secret);+ });++ it('does not store a newly generated secret when the peer rejects pairing', async () => {+ const peer = makePeer();+ readJSONFile.mockResolvedValue({ self: { instanceId: selfId }, peers: [peer] });+ fetch.mockResolvedValue({ ok: false, status: 404, json: vi.fn().mockResolvedValue({}) });++ await expect(pairPeerSyncSecret(peer.id)).rejects.toMatchObject({ code: 'PEER_PAIR_REJECTED' });+ expect(peer).not.toHaveProperty('syncSecret');+ });++ it('accepts a generated secret only for one registered peer and preserves sync consent', async () => {+ const peer = makePeer({ syncEnabled: false, syncCategories: { universe: false } });+ readJSONFile.mockResolvedValue({ self: { instanceId: selfId }, peers: [peer] });+ const accepted = await acceptPeerSyncSecretFromPeer(peerId, 'synthetic-pair-secret-32-characters-long');++ expect(accepted.syncSecret).toBe('synthetic-pair-secret-32-characters-long');+ expect(accepted.directions).toEqual(['outbound', 'inbound']);+ expect(accepted.syncEnabled).toBe(false);+ expect(disconnectFromPeer).toHaveBeenCalledWith(peer.id);+ expect(await acceptPeerSyncSecretFromPeer('unknown-peer', 'synthetic-pair-secret-32-characters-long')).toBeNull();+ });+ });});diff --git a/server/services/sharing/peerPushAuthorization.js b/server/services/sharing/peerPushAuthorization.jsindex 4ae740912a..6bff338e65 100644--- a/server/services/sharing/peerPushAuthorization.js+++ b/server/services/sharing/peerPushAuthorization.js@@ -20,7 +20,7 @@ export async function authorizeIncomingPush(payload, { peerToken, pullPeerId } =const localPull = peer && typeof pullPeerId === 'string' && pullPeerId.length > 0&& pullPeerId === peer.id && typeof peer.syncSecret === 'string' && peer.syncSecret.length >= 32;if (!localPull && !peerSyncTokenMatches(peer, peerToken)) {- throw new ServerError('Configure the same peer sync secret on both instances before pushing records', {+ throw new ServerError('Pair this peer from its Instances page before pushing records', {status: 401, code: 'PEER_SYNC_AUTH_REQUIRED',});}