Skip to content

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

fix: authenticate and locally admit peer record pushes (#8225)

[._.]/ Adam Eivyffa44739f039
diff --git a/client/src/components/instances/PeerSyncSecretEditor.jsx b/client/src/components/instances/PeerSyncSecretEditor.jsx
new file mode 100644
index 0000000000..1a83236bae
--- /dev/null
+++ b/client/src/components/instances/PeerSyncSecretEditor.jsx
@@ -0,0 +1,46 @@
+import { useState } from 'react';
+import { updatePeer } from '../../services/api';
+import toast from '../ui/Toast';
+
+export default function PeerSyncSecretEditor({ peer, onRefresh }) {
+ const [editing, setEditing] = useState(false);
+ const [secret, setSecret] = useState('');
+ const [saving, setSaving] = useState(false);
+ 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);
+ if (!result) return;
+ setSecret('');
+ setEditing(false);
+ onRefresh();
+ toast.success(value === null ? 'Peer sync secret removed' : 'Peer sync secret saved');
+ };
+ 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>
+ {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.
+ Configure from the local interface, or sign in with an instance password.
+ </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>}
+ </div>
+ );
+}
diff --git a/client/src/components/instances/PeerSyncSecretEditor.test.jsx b/client/src/components/instances/PeerSyncSecretEditor.test.jsx
new file mode 100644
index 0000000000..cca431b380
--- /dev/null
+++ b/client/src/components/instances/PeerSyncSecretEditor.test.jsx
@@ -0,0 +1,26 @@
+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() }));
+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 () => {
+ 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' }));
+ await waitFor(() => expect(onRefresh).toHaveBeenCalledTimes(1));
+ expect(updatePeer).toHaveBeenLastCalledWith('peer-a', { syncSecret: 'synthetic-pair-secret-32-characters-long' });
+ expect(screen.queryByLabelText('Shared sync secret')).toBeNull();
+ });
+});
diff --git a/client/src/pages/Instances.jsx b/client/src/pages/Instances.jsx
index bbdb5ba95e..287d93ff5b 100644
--- a/client/src/pages/Instances.jsx
+++ b/client/src/pages/Instances.jsx
@@ -29,6 +29,7 @@ import {
retryTailcatForward, forgetTailcatForward,
startTailcatServe,
} from '../services/api';
+import PeerSyncSecretEditor from '../components/instances/PeerSyncSecretEditor';
import PeerAppsList from '../components/instances/PeerAppsList';
import PeerAgentsSection from '../components/instances/PeerAgentsSection';
import { SchemaGapBadge } from '../components/instances/SchemaGapBadge';
@@ -1434,6 +1435,7 @@ export function PeerCard({ peer, onRefresh, syncStatus, tailnetInfo, parityRepor
</div>
<PeerHostEditor peer={peer} onRefresh={onRefresh} tailnetInfo={tailnetInfo} />
<PeerAuthEditor peer={peer} onRefresh={onRefresh} />
+ <PeerSyncSecretEditor peer={peer} onRefresh={onRefresh} />
</div>
{peer.transport === 'tailcat' && (
diff --git a/docs/PEER_PUSH_AUTH.md b/docs/PEER_PUSH_AUTH.md
new file mode 100644
index 0000000000..703169bfa6
--- /dev/null
+++ b/docs/PEER_PUSH_AUTH.md
@@ -0,0 +1,46 @@
+# Peer record push authentication
+
+Record pushes require a separate shared secret for each pair of instances. The
+instance password remains optional. A peer's claimed instance ID, an announcement,
+or its network address does not authorize record ingestion.
+
+## Configure a pair
+
+1. Upgrade both instances. Open **Instances** from the local interface on each
+ machine, or sign in with that machine's instance password for remote settings.
+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
+any existing Basic credential for the optional instance password. HTTP redirects
+are refused for credentialed pushes. Use the existing private encrypted transport
+(Tailscale or HTTPS) to protect these credentials in transit.
+
+## Existing installations and mixed versions
+
+Existing peer records remain intact. No secret is synthesized or trusted from
+network discovery. After upgrading, incoming record pushes pause until the pair
+is 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.
+
+An explicit record pull uses the locally configured peer destination and verifies
+that the response's source, kind, and record ID match that request. It still
+requires 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 an operator session or a direct loopback
+connection with a local browser origin while the instance password is off.
diff --git a/docs/README.md b/docs/README.md
index 41ba4b031c..95f36e997a 100644
--- a/docs/README.md
+++ b/docs/README.md
@@ -76,3 +76,5 @@ Comms & voice: [beeper](./features/beeper.md) · [openclaw-operator-chat](./feat
- **media/** — screenshots and logo used by the root README.
- [Local managed-app visitor broker](features/managed-visitors.md) — opt-in credential provisioning, versioned nonhumanoid scope and host negotiation.
+
+- [Peer push authentication](./PEER_PUSH_AUTH.md)
diff --git a/server/lib/peerHttpClient.js b/server/lib/peerHttpClient.js
index 66a0717257..37f88b01a9 100644
--- a/server/lib/peerHttpClient.js
+++ b/server/lib/peerHttpClient.js
@@ -67,10 +67,15 @@ export function __resetSelfInstanceIdForTests() {
*/
export async function peerFetch(url, options = {}, peer = null) {
const callerHeaders = normalizeHeaders(options.headers);
+ // 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'
+ ? { 'X-PortOS-Peer-Sync-Token': peer.syncSecret } : {};
const finalOptions = {
...options,
+ ...(Object.keys(syncHeaders).length ? { redirect: 'error' } : {}),
headers: {
- ...dropOverridden({ ...await selfInstanceHeader(), ...(peer ? peerAuthHeaders(peer) : {}) }, callerHeaders),
+ ...dropOverridden({ ...await selfInstanceHeader(), ...(peer ? peerAuthHeaders(peer) : {}), ...syncHeaders }, callerHeaders),
...callerHeaders,
},
};
diff --git a/server/lib/peerHttpClient.test.js b/server/lib/peerHttpClient.test.js
index dcd0e25436..660e793b22 100644
--- a/server/lib/peerHttpClient.test.js
+++ b/server/lib/peerHttpClient.test.js
@@ -180,6 +180,18 @@ describe('peerHttpClient', () => {
});
});
+ it('sends the pair secret only to the push endpoint and refuses redirects', async () => {
+ const fetchMock = vi.fn().mockResolvedValue({ ok: true });
+ vi.stubGlobal('fetch', fetchMock);
+ const peer = { syncSecret: 'synthetic-pair-secret-32-characters-long' };
+ try {
+ await peerFetch('http://peer.example.com/api/peer-sync/push', { method: 'POST', body: '{}' }, peer);
+ expect(fetchMock.mock.calls[0][1]).toMatchObject({ redirect: 'error', headers: { 'X-PortOS-Peer-Sync-Token': peer.syncSecret } });
+ await peerFetch('http://peer.example.com/api/instances/peers/announce', {}, peer);
+ expect(fetchMock.mock.calls[1][1].headers).not.toHaveProperty('X-PortOS-Peer-Sync-Token');
+ } finally { vi.unstubAllGlobals(); }
+ });
+
describe('peerFetch over HTTPS', () => {
let fixture;
diff --git a/server/routes/instances.js b/server/routes/instances.js
index 0fcb817942..5214b94d75 100644
--- a/server/routes/instances.js
+++ b/server/routes/instances.js
@@ -5,6 +5,10 @@
*/
import { Router } from 'express';
+import { extractToken, verifySession, isAuthEnabled } from '../services/auth.js';
+import { isCrossOrigin } from '../../lib/portosAuthCore.js';
+import { isRemoteRequest } from '../lib/requestOrigin.js';
+import { isLoopbackHostname } from '../lib/beeperOAuthOrigin.js';
import { z } from 'zod';
import * as instances from '../services/instances.js';
import { getSelf, updateSelf } from '../services/instanceIdentity.js';
@@ -20,6 +24,22 @@ import { federatedMediaPeerSettingsSchema, optionalBooleanMap, validateRequest }
const router = Router();
+// Peer admission is local authority even when the instance password is off.
+// Discovery callbacks remain reachable, but cannot provision the pair secret.
+router.use(asyncHandler(async (req, _res, next) => {
+ if (!req.path.toLowerCase().startsWith('/peers') || ['GET', 'HEAD', 'OPTIONS'].includes(req.method)
+ || ['/peers/announce', '/peers/sync-categories'].includes(req.path.toLowerCase().replace(/\/$/, ''))) return next();
+ const localAddress = String(req.socket?.remoteAddress || '').replace(/^::ffff:/, '');
+ const origin = req.get('origin');
+ const localOrigin = !origin || (URL.canParse(origin) && isLoopbackHostname(new URL(origin).hostname));
+ const local = !isRemoteRequest(req) && isLoopbackHostname(localAddress)
+ && isLoopbackHostname(req.hostname) && localOrigin;
+ if (!isCrossOrigin(req) && (await verifySession(extractToken(req)) || (!await isAuthEnabled() && local))) return next();
+ throw new ServerError('Peer settings require an operator session or the local interface', {
+ status: 403, code: 'PEER_SETTINGS_OPERATOR_REQUIRED',
+ });
+}));
+
// Optional HTTP Basic credential for a peer behind an auth proxy. `null` clears
// it; an object sets it. The service's sanitizePeerAuth does the final
// normalize: the password is the secret that defines the credential, so a
@@ -62,6 +82,7 @@ const updatePeerSchema = z.object({
// Explicit consumer opt-in + model allowlist for using this peer as a media
// provider. Provider-side sharing remains independently configured there.
mediaProvider: federatedMediaPeerSettingsSchema.optional(),
+ syncSecret: z.string().min(32).max(256).nullable().optional(),
});
const announceSchema = z.object({
diff --git a/server/routes/instances.test.js b/server/routes/instances.test.js
index 3186c6c3d9..e16d3478b0 100644
--- a/server/routes/instances.test.js
+++ b/server/routes/instances.test.js
@@ -1,5 +1,12 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
import express from 'express';
+import { remoteRequestHandler } from '../lib/requestOrigin.js';
+import { verifySession } from '../services/auth.js';
+vi.mock('../services/auth.js', () => ({
+ extractToken: req => req.headers.authorization,
+ verifySession: vi.fn().mockResolvedValue(false),
+ isAuthEnabled: vi.fn().mockResolvedValue(false),
+}));
import { request } from '../lib/testHelper.js';
import { errorMiddleware } from '../lib/errorHandler.js';
@@ -416,3 +423,24 @@ describe('GET /api/instances/peers/:id/full-sync-coverage', () => {
expect(getFullSyncCoverageForPeer).toHaveBeenCalledWith('remote-1');
});
});
+
+
+describe('local peer admission configuration', () => {
+ beforeEach(() => { vi.clearAllMocks(); vi.mocked(verifySession).mockResolvedValue(false); });
+ 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')
+ .send({ syncSecret: 'synthetic-pair-secret-32-characters-long' });
+ expect(res.status).toBe(403);
+ expect(instances.updatePeer).not.toHaveBeenCalled();
+ });
+ it('allows an authenticated operator to configure the secret remotely', async () => {
+ vi.mocked(verifySession).mockResolvedValue(true);
+ instances.updatePeer.mockResolvedValue({ id: 'peer-a', hasSyncSecret: true });
+ const res = await request(remoteRequestHandler(buildApp())).put('/api/instances/peers/peer-a')
+ .set('Authorization', 'Bearer synthetic-operator-token')
+ .send({ syncSecret: 'synthetic-pair-secret-32-characters-long' });
+ expect(res.status).toBe(200);
+ expect(instances.updatePeer).toHaveBeenCalledWith('peer-a', { syncSecret: 'synthetic-pair-secret-32-characters-long' });
+ });
+});
diff --git a/server/routes/peerSync.js b/server/routes/peerSync.js
index ff78969150..36eca98aeb 100644
--- a/server/routes/peerSync.js
+++ b/server/routes/peerSync.js
@@ -99,7 +99,7 @@ function mapAndRethrow(err) {
// merge-time LWW, reverse-subscribe direction gating).
router.post('/push', asyncHandler(async (req, res) => {
const payload = validateRequest(peerSyncPushSchema, req.body || {});
- const result = await applyIncomingPush(payload).catch(mapAndRethrow);
+ const result = await applyIncomingPush(payload, { peerToken: req.get('X-PortOS-Peer-Sync-Token') }).catch(mapAndRethrow);
res.json(result);
}));
diff --git a/server/routes/peerSync.test.js b/server/routes/peerSync.test.js
index d9c160db38..384ebac833 100644
--- a/server/routes/peerSync.test.js
+++ b/server/routes/peerSync.test.js
@@ -76,6 +76,7 @@ describe('peer-sync routes', () => {
});
const res = await request(buildApp())
.post('/api/peer-sync/push')
+ .set('X-PortOS-Peer-Sync-Token', 'synthetic-pair-secret-32-characters-long')
.send({
kind: 'universe',
record: { id: 'u1', name: 'Foo' },
@@ -87,7 +88,7 @@ describe('peer-sync routes', () => {
expect(svc.applyIncomingPush).toHaveBeenCalledWith(expect.objectContaining({
kind: 'universe',
sourceInstanceId: 'peer-a',
- }));
+ }), { peerToken: 'synthetic-pair-secret-32-characters-long' });
});
it('accepts a FableLoom push with scene-media assets', async () => {
@@ -111,7 +112,7 @@ describe('peer-sync routes', () => {
expect(svc.applyIncomingPush).toHaveBeenCalledWith(expect.objectContaining({
kind: 'fableLoom',
record: expect.objectContaining({ id: 'loom-1' }),
- }));
+ }), { peerToken: undefined });
});
it('accepts a universe push that bundles a linkedCollection (Stage 5 media-collections sync)', async () => {
@@ -132,7 +133,7 @@ describe('peer-sync routes', () => {
expect(res.status).toBe(200);
expect(svc.applyIncomingPush).toHaveBeenCalledWith(expect.objectContaining({
linkedCollection: expect.objectContaining({ id: 'col-1' }),
- }));
+ }), { peerToken: undefined });
});
it('accepts a series push with bundled issues', async () => {
@@ -149,7 +150,7 @@ describe('peer-sync routes', () => {
expect(res.status).toBe(200);
expect(svc.applyIncomingPush).toHaveBeenCalledWith(expect.objectContaining({
issues: expect.any(Array),
- }));
+ }), { peerToken: undefined });
});
it('accepts a series push that bundles a manuscriptReview (Finish-the-draft comment set)', async () => {
@@ -173,7 +174,7 @@ describe('peer-sync routes', () => {
expect(res.status).toBe(200);
expect(svc.applyIncomingPush).toHaveBeenCalledWith(expect.objectContaining({
manuscriptReview: expect.objectContaining({ comments: expect.any(Array) }),
- }));
+ }), { peerToken: undefined });
});
it('accepts a writersRoomWork push that bundles draft and bible manifests', async () => {
@@ -199,7 +200,7 @@ describe('peer-sync routes', () => {
kind: 'writersRoomWork',
draftBodyManifest: expect.any(Array),
bibleManifest: expect.any(Array),
- }));
+ }), { peerToken: undefined });
});
it('400s when a universe push carries manuscriptReview (series-only field, no side-channel)', async () => {
diff --git a/server/services/instances.js b/server/services/instances.js
index ef42bbab58..6cd895ad0b 100644
--- a/server/services/instances.js
+++ b/server/services/instances.js
@@ -130,11 +130,12 @@ function sameAuth(a, b) {
export function redactPeerForWire(peer) {
if (!peer || typeof peer !== 'object') return peer;
if (!('auth' in peer) && !('mediaProvider' in peer) && !('mediaProviderStatus' in peer)
- && !('tcAddress' in peer)) {
+ && !('tcAddress' in peer) && !('syncSecret' in peer)) {
return peer;
}
const {
auth: _auth,
+ syncSecret: _syncSecret,
mediaProvider: _mediaProvider,
mediaProviderStatus: _mediaProviderStatus,
tcAddress: _tcAddress,
@@ -164,8 +165,8 @@ export function sanitizePeerForClient(peer) {
// separately, so masking here would hide the stored selection: every box on a
// `syncEnabled: false` peer would read unchecked, and ticking one would
// silently reactivate every other category still true underneath it.
- const { tcAddress: _tcAddress, ...safePeer } = peer;
- return { ...safePeer, auth, syncCategories: resolveEffectiveCategories(peer, { masterSwitch: false }) };
+ const { tcAddress: _tcAddress, syncSecret: _syncSecret, ...safePeer } = peer;
+ return { ...safePeer, auth, hasSyncSecret: Boolean(peer.syncSecret), syncCategories: resolveEffectiveCategories(peer, { masterSwitch: false }) };
}
/**
@@ -518,6 +519,16 @@ export async function updatePeer(id, updates) {
const result = await withData(async (data) => {
const peer = data.peers.find(p => p.id === id);
if (!peer) return null;
+ if (updates.syncSecret !== undefined) {
+ 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;
+ // Entering the pair secret is the local inbound-admission action.
+ if (peer.syncSecret && !peer.directions?.includes('inbound')) {
+ peer.directions = [...(peer.directions || []), 'inbound'];
+ }
+ }
if (updates.name !== undefined) peer.name = validName(updates.name, peer.name);
if (updates.enabled !== undefined) peer.enabled = updates.enabled;
if (updates.syncEnabled !== undefined) peer.syncEnabled = updates.syncEnabled;
@@ -825,7 +836,7 @@ export async function probePeer(peer) {
} else {
delete entry.mediaProviderStatus;
}
- if (remoteInstanceId) entry.instanceId = remoteInstanceId;
+ if (remoteInstanceId && (!entry.syncSecret || !entry.instanceId)) entry.instanceId = remoteInstanceId;
if (status === 'online') entry.version = remoteVersion;
// Auto-update name from hostname if current name is just an IP address
const remoteHostname = validName(lastHealth?.hostname, null);
@@ -914,6 +925,8 @@ export async function handleAnnounce({ address, port, instanceId, name, host })
const normalizedHost = validHost(host);
+ if (existing?.syncSecret) return { created: false, peer: existing };
+
if (existing) {
existing.lastSeen = new Date().toISOString();
existing.status = 'online';
@@ -1070,6 +1083,8 @@ function sanitizeSyncCategories(input) {
* but this keeps a misbehaving peer from churning our state).
*/
export async function applyReciprocalSync(instanceId, categories, { fullSync } = {}) {
+ // The admitted peer's direction and categories are machine-local consent.
+ // Anonymous reciprocal callbacks must never broaden or revoke them.
const sanitized = sanitizeSyncCategories(categories);
// A fullSync-only signal (peer asking us to mirror everything) is valid even
// if the category map didn't sanitize to anything actionable. An explicit
@@ -1084,7 +1099,7 @@ export async function applyReciprocalSync(instanceId, categories, { fullSync } =
let changed = false;
const peer = await withData(async (data) => {
const entry = data.peers.find(p => p.instanceId === instanceId);
- if (!entry) return null;
+ if (!entry || entry.syncSecret) return null;
// Default the baseline so a partial stored map doesn't make absent-vs-false
// diverge — otherwise sanitized adding `goals:false` to a `prev` missing
// `goals` reads as a change (`false !== undefined`) and defeats the guard.
diff --git a/server/services/instances.test.js b/server/services/instances.test.js
index 12ae2b30ed..2d2f31a64b 100644
--- a/server/services/instances.test.js
+++ b/server/services/instances.test.js
@@ -368,6 +368,7 @@ describe('instances.js', () => {
id: 'peer-1',
name: 'host',
auth: { username: 'a', password: 'b' },
+ syncSecret: 'synthetic-pair-secret-32-characters-long',
mediaProvider: { enabled: true, audioModels: [{ engine: 'example', modelId: 'example' }] },
mediaProviderStatus: { state: 'ready' },
status: 'online',
@@ -375,6 +376,9 @@ describe('instances.js', () => {
const redacted = redactPeerForWire(peer);
expect(redacted).not.toHaveProperty('auth');
+ expect(redacted).not.toHaveProperty('syncSecret');
+ expect(sanitizePeerForClient(peer)).not.toHaveProperty('syncSecret');
+ expect(sanitizePeerForClient(peer).hasSyncSecret).toBe(true);
expect(redacted).not.toHaveProperty('mediaProvider');
expect(redacted).not.toHaveProperty('mediaProviderStatus');
expect(redacted).toMatchObject({ id: 'peer-1', name: 'host', status: 'online' });
@@ -1480,6 +1484,18 @@ describe('instances.js', () => {
});
describe('handleAnnounce', () => {
+ it('keeps an admitted peer identity, callback endpoint and consent unchanged after forged discovery', async () => {
+ const peer = { id: 'peer-local', instanceId: 'peer-a', address: '192.0.2.10', port: 5555,
+ host: 'configured.example.com', directions: ['inbound'], syncSecret: 'synthetic-pair-secret-32-characters-long',
+ syncEnabled: false, syncCategories: { universe: false } };
+ const before = structuredClone(peer);
+ readJSONFile.mockResolvedValue({ self: { instanceId: 'local-instance' }, peers: [peer] });
+ await handleAnnounce({ instanceId: 'peer-forged', address: '192.0.2.10', port: 5555, host: 'attacker.example.com' });
+ expect(peer).toEqual(before);
+ await applyReciprocalSync('peer-a', { universe: true }, { fullSync: true });
+ expect(peer).toEqual(before);
+ });
+
it('preserves the managed tailcat endpoint when the remote announces its own host and port', async () => {
const existing = {
id: 'tailcat-peer', address: '127.0.0.1', port: 15555, host: null,
diff --git a/server/services/sharing/peerPushAuthorization.js b/server/services/sharing/peerPushAuthorization.js
new file mode 100644
index 0000000000..4ae740912a
--- /dev/null
+++ b/server/services/sharing/peerPushAuthorization.js
@@ -0,0 +1,36 @@
+/** Peer-specific admission for inbound record writes; independent of instance auth. */
+import { timingSafeEqual } from 'node:crypto';
+import { getPeers } from '../instances.js';
+import { ServerError } from '../../lib/errorHandler.js';
+import { peerAllowsOutbound, peerHasCategory } from './peerSyncShared.js';
+
+function peerSyncTokenMatches(peer, token) {
+ const expected = peer?.syncSecret;
+ if (typeof expected !== 'string' || expected.length < 32 || typeof token !== 'string') return false;
+ const a = Buffer.from(expected);
+ const b = Buffer.from(token);
+ return a.length === b.length && timingSafeEqual(a, b);
+}
+
+export async function authorizeIncomingPush(payload, { peerToken, pullPeerId } = {}) {
+ const peers = await getPeers();
+ const peer = peers.find(p => p.instanceId === payload.sourceInstanceId);
+ // A local pull already bound the response to the configured destination.
+ // No HTTP input can select this context; the pull service alone supplies it.
+ 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', {
+ status: 401, code: 'PEER_SYNC_AUTH_REQUIRED',
+ });
+ }
+ const directions = Array.isArray(peer?.directions) ? peer.directions : [];
+ const directionAllowed = localPull ? peerAllowsOutbound(peer) : directions.includes('inbound');
+ if (!peer || peer.enabled === false || peer.syncEnabled !== true || !directionAllowed
+ || !peerHasCategory(peer, payload.kind)) {
+ throw new ServerError('This peer is not permitted to send this sync category', {
+ status: 403, code: 'PEER_SYNC_NOT_ADMITTED',
+ });
+ }
+ return peer;
+}
diff --git a/server/services/sharing/peerSync.js b/server/services/sharing/peerSync.js
index 19bd7581b6..6b8965d998 100644
--- a/server/services/sharing/peerSync.js
+++ b/server/services/sharing/peerSync.js
@@ -713,7 +713,7 @@ export async function pullRecordFromPeer(peerId, recordKind, recordId) {
}
console.log(`🔄 peerSync: pull-record ${recordKind}/${recordId} ← ${peer.name || peerId}`);
- const result = await applyIncomingPush(parsed.data);
+ const result = await applyIncomingPush(parsed.data, { pullPeerId: peer.id });
return { pulled: true, missingAssets: result?.missingAssets?.length ?? 0 };
}
diff --git a/server/services/sharing/peerSync.test.js b/server/services/sharing/peerSync.test.js
index 458d084917..8c838c4019 100644
--- a/server/services/sharing/peerSync.test.js
+++ b/server/services/sharing/peerSync.test.js
@@ -10,6 +10,9 @@ import { tmpdir } from 'os';
// All other logic (subscription store, asset manifest, diff, cursor advance)
// runs against the real on-disk paths via the tmpdir-redirect pattern below.
+vi.mock('./peerPushAuthorization.js', () => ({ authorizeIncomingPush: vi.fn().mockResolvedValue({}) }));
+import { authorizeIncomingPush } from './peerPushAuthorization.js';
+
import { PATHS } from '../../lib/fileUtils.js';
import { RECORD_KIND_SCHEMA_CATEGORIES, PORTOS_SCHEMA_VERSIONS, NON_RECORD_SCHEMA_CATEGORIES } from '../../lib/schemaVersions.js';
@@ -322,6 +325,7 @@ let originalMusicPath;
let tmp;
beforeEach(async () => {
+ vi.mocked(authorizeIncomingPush).mockResolvedValue({});
// Capture EVERY PATHS field we (or any test in this file) might mutate so
// the afterEach restoration is total. The sha-mismatch-for-all-kinds test
// points PATHS.imageRefs / PATHS.videos at the per-test tmpdir; without
@@ -5218,3 +5222,44 @@ describe('media-library federation (#1566)', () => {
});
});
});
+
+
+describe('inbound peer admission before record writes', () => {
+ const secret = 'synthetic-pair-secret-32-characters-long';
+ const payload = () => ({ kind: 'universe', record: { id: 'u-admission', name: 'Example Universe' }, sourceInstanceId: 'peer-a', assetManifest: [] });
+ const admitted = () => ({ id: 'configured-peer', instanceId: 'peer-a', syncSecret: secret, enabled: true,
+ syncEnabled: true, directions: ['inbound', 'outbound'], syncCategories: { universe: true } });
+ beforeEach(async () => {
+ const real = await vi.importActual('./peerPushAuthorization.js');
+ vi.mocked(authorizeIncomingPush).mockImplementation(real.authorizeIncomingPush);
+ vi.mocked(getPeers).mockResolvedValue([admitted()]);
+ });
+ it.each([
+ ['unknown', null, secret, 'peer-a'],
+ ['announcement-only', { ...admitted(), syncSecret: undefined }, secret, 'peer-a'],
+ ['missing proof', admitted(), undefined, 'peer-a'],
+ ['wrong proof', admitted(), 'another-synthetic-secret-32-characters', 'peer-a'],
+ ['forged source', admitted(), secret, 'peer-other'],
+ ['disabled', { ...admitted(), enabled: false }, secret, 'peer-a'],
+ ['sync off', { ...admitted(), syncEnabled: false, fullSync: true }, secret, 'peer-a'],
+ ['outbound only', { ...admitted(), directions: ['outbound'] }, secret, 'peer-a'],
+ ['category denied', { ...admitted(), syncCategories: { universe: false } }, secret, 'peer-a'],
+ ])('rejects %s before merges, asset requests, or reverse subscriptions', async (_name, peer, peerToken, sourceInstanceId) => {
+ vi.mocked(getPeers).mockResolvedValue(peer ? [peer] : []);
+ await expect(applyIncomingPush({ ...payload(), sourceInstanceId }, { peerToken })).rejects.toMatchObject({ status: expect.any(Number) });
+ expect(mergeUniversesFromSync).not.toHaveBeenCalled();
+ expect(mergeIssuesFromSync).not.toHaveBeenCalled();
+ expect(peerFetch).not.toHaveBeenCalled();
+ expect(await listPeerSubscriptions()).toEqual([]);
+ });
+ it('accepts a locally admitted peer and permitted category', async () => {
+ await applyIncomingPush(payload(), { peerToken: secret });
+ expect(mergeUniversesFromSync).toHaveBeenCalled();
+ });
+ it('preserves explicit pulls while enforcing their configured peer consent', async () => {
+ await applyIncomingPush(payload(), { pullPeerId: 'configured-peer' });
+ expect(mergeUniversesFromSync).toHaveBeenCalled();
+ vi.mocked(getPeers).mockResolvedValue([{ ...admitted(), syncEnabled: false }]);
+ await expect(applyIncomingPush(payload(), { pullPeerId: 'configured-peer' })).rejects.toMatchObject({ status: 403 });
+ });
+});
diff --git a/server/services/sharing/peerSyncReceive.js b/server/services/sharing/peerSyncReceive.js
index 892a42239a..55e3a83b1e 100644
--- a/server/services/sharing/peerSyncReceive.js
+++ b/server/services/sharing/peerSyncReceive.js
@@ -9,6 +9,7 @@
*
* Split out of the former 4,004-line peerSync.js (#1830).
*/
+import { authorizeIncomingPush } from './peerPushAuthorization.js';
import { isPlainObject } from '../../lib/objects.js';
import {
PORTOS_SCHEMA_VERSIONS,
@@ -201,7 +202,7 @@ async function assertSchemaVersionGate({ kind, record, issues, linkedCollection,
* The HTTP route in Stage 3 will be a thin wrapper around this — validate
* the body shape, call this function, return the response.
*/
-export async function applyIncomingPush(payload) {
+export async function applyIncomingPush(payload, authorization) {
if (!isPlainObject(payload)) {
throw makeErr('payload must be an object', ERR_VALIDATION);
}
@@ -222,6 +223,8 @@ export async function applyIncomingPush(payload) {
throw makeErr('record must be an object with a string id', ERR_VALIDATION);
}
+ await authorizeIncomingPush(payload, authorization);
+
const { senderSchemaVersions } = await assertSchemaVersionGate({
kind, record, issues, linkedCollection, catalogBundle, linkedTrack, portosMeta, sourceInstanceId,
});