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

add per-peer credentials so federated peers behind an auth proxy stop failing probes with 401

[._.]/ Adam Eivyd0fed982311b
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 3e285f5cca..a6658cf8b4 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -2,6 +2,7 @@
## Added
+- **Password-protected federated peers** — If one of your PortOS instances sits behind an HTTP Basic auth proxy (Tailscale `serve`, Caddy, nginx), its peers can now reach it: probes were failing with `HTTP 401`. Each peer in the Instances page gains an optional credential — set a username (optional) and password when adding a peer, or click "set credential" on an existing peer. The credential is attached to every outbound hop to that peer (health probes, snapshot sync, per-record push/pull, asset pulls, and the live agent socket relay), so a reachable-but-401 peer now connects. A peer that returns 401/403 is flagged "auth required" in the UI instead of just reading as offline. Credentials are stored locally per peer and are never synced or announced to the peer itself.
- **[issue-708] Digital Twin "Voice" tab — spoken vs. written style** — Paste a transcript of yourself speaking and the Digital Twin compares it against how you write (a pasted sample, or your existing twin documents), surfacing where your spoken voice differs from your writing — formality, verbosity, sentence length, directness, filler words — and suggesting a communication profile for voice contexts that you can apply in one click.
- **[issue-711] "While You Were Away" dashboard card** — A new dashboard widget recaps what your agents did since your last visit: a count of completed runs, success/failure tally, total time worked, and the most recent wins plus anything that failed and needs a look. Each item opens the agents view, and a "Mark as seen" button resets the window to now. It appears on the Everything and Agent Watch layouts and can be added to any layout via Arrange.
- **[issue-708] Digital Twin "Appearance" tab — image identity source** — Upload a photo of yourself and a vision-capable provider extracts your visible appearance and self-presentation (apparent age range, build, hair, style, grooming, vibe, setting, expression). Review and edit the generated write-up, then save it as your "Appearance & Presentation" core identity document so the twin has a grounded sense of how you look. Use a local vision model (LM Studio / Ollama) to keep the photo on-device; the image itself is never persisted, only the derived text.
diff --git a/client/src/pages/Instances.jsx b/client/src/pages/Instances.jsx
index 62de922b3e..a19c3019bd 100644
--- a/client/src/pages/Instances.jsx
+++ b/client/src/pages/Instances.jsx
@@ -322,6 +322,9 @@ function AddPeerForm({ onAdd }) {
const [address, setAddress] = useState('');
const [port, setPort] = useState('5555');
const [name, setName] = useState('');
+ const [showAuth, setShowAuth] = useState(false);
+ const [username, setUsername] = useState('');
+ const [password, setPassword] = useState('');
const [adding, setAdding] = useState(false);
const handleSubmit = async (e) => {
@@ -330,12 +333,18 @@ function AddPeerForm({ onAdd }) {
setAdding(true);
const data = { address: address.trim(), port: parseInt(port, 10) || 5555 };
if (name.trim()) data.name = name.trim();
+ // Only attach credentials when a password was entered — username alone
+ // (or neither) is treated as "no auth" by the server's sanitizer.
+ if (password) data.auth = { username: username.trim(), password };
const result = await addPeer(data).catch(() => null);
setAdding(false);
if (!result) return;
setAddress('');
setPort('5555');
setName('');
+ setUsername('');
+ setPassword('');
+ setShowAuth(false);
onAdd();
toast.success('Peer added');
};
@@ -377,6 +386,35 @@ function AddPeerForm({ onAdd }) {
{adding ? 'Adding...' : 'Add'}
</button>
</div>
+ <div className="mt-2">
+ <button
+ type="button"
+ onClick={() => setShowAuth(v => !v)}
+ className="inline-flex items-center gap-1 text-[11px] text-gray-500 hover:text-gray-300 transition-colors"
+ >
+ <Lock size={11} />
+ {showAuth ? 'Hide credentials' : 'Add credentials (peer behind an auth proxy)'}
+ </button>
+ {showAuth && (
+ <div className="flex flex-wrap gap-2 mt-2">
+ <input
+ value={username}
+ onChange={e => setUsername(e.target.value)}
+ placeholder="Username (optional)"
+ autoComplete="off"
+ className="bg-port-bg border border-port-border rounded px-3 py-2 text-sm text-white placeholder-gray-600 focus:outline-hidden focus:border-port-accent flex-1 min-w-[120px]"
+ />
+ <input
+ value={password}
+ onChange={e => setPassword(e.target.value)}
+ placeholder="Password"
+ type="password"
+ autoComplete="new-password"
+ className="bg-port-bg border border-port-border rounded px-3 py-2 text-sm text-white placeholder-gray-600 focus:outline-hidden focus:border-port-accent flex-1 min-w-[120px]"
+ />
+ </div>
+ )}
+ </div>
</form>
);
}
@@ -786,6 +824,94 @@ function PeerHostEditor({ peer, onRefresh, tailnetInfo }) {
);
}
+function PeerAuthEditor({ peer, onRefresh }) {
+ const [editing, setEditing] = useState(false);
+ const [username, setUsername] = useState('');
+ const [password, setPassword] = useState('');
+ const [saving, setSaving] = useState(false);
+
+ const hasAuth = !!peer.auth;
+
+ const startEdit = () => {
+ // Prefill from the stored credential so editing the username alone doesn't
+ // wipe the password (the server replaces the whole credential on save).
+ setUsername(peer.auth?.username || '');
+ setPassword(peer.auth?.password || '');
+ setEditing(true);
+ };
+
+ const save = async () => {
+ if (!password) return; // a password is required to store a credential
+ setSaving(true);
+ const result = await updatePeer(peer.id, { auth: { username: username.trim(), password } }).catch(() => null);
+ setSaving(false);
+ if (!result) return;
+ onRefresh();
+ setEditing(false);
+ toast.success('Peer credential saved');
+ };
+
+ const clear = async () => {
+ setSaving(true);
+ const result = await updatePeer(peer.id, { auth: null }).catch(() => null);
+ setSaving(false);
+ if (!result) return;
+ onRefresh();
+ setEditing(false);
+ toast.success('Peer credential cleared');
+ };
+
+ if (editing) {
+ return (
+ <div className="mt-1 flex items-center gap-1 flex-wrap">
+ <input
+ value={username}
+ onChange={e => setUsername(e.target.value)}
+ placeholder="user (optional)"
+ autoComplete="off"
+ className="bg-port-bg border border-port-border rounded px-2 py-0.5 text-xs text-white focus:outline-hidden focus:border-port-accent w-28"
+ />
+ <input
+ value={password}
+ onChange={e => setPassword(e.target.value)}
+ onKeyDown={e => e.key === 'Enter' && save()}
+ placeholder="password"
+ type="password"
+ autoComplete="new-password"
+ className="bg-port-bg border border-port-border rounded px-2 py-0.5 text-xs text-white focus:outline-hidden focus:border-port-accent flex-1 min-w-[120px]"
+ autoFocus
+ />
+ <button onClick={save} disabled={saving || !password} className="text-port-success hover:text-port-success/80 disabled:opacity-50"><Check size={14} /></button>
+ <button onClick={() => setEditing(false)} className="text-gray-500 hover:text-white"><X size={14} /></button>
+ {hasAuth && (
+ <button onClick={clear} disabled={saving} className="text-[10px] text-gray-500 hover:text-port-error underline disabled:opacity-50">remove</button>
+ )}
+ </div>
+ );
+ }
+
+ return (
+ <div className="mt-0.5 flex items-center gap-1.5 flex-wrap">
+ {hasAuth ? (
+ <Pill tone="success" size="xs" bordered={false} icon={Lock} title="Outbound requests to this peer send an HTTP Basic credential">
+ credential set{peer.auth?.username ? ` · ${peer.auth.username}` : ''}
+ </Pill>
+ ) : peer.authRequired ? (
+ <Pill tone="warning" size="xs" bordered={false} icon={Lock} title="Peer returned 401/403 — it's behind an auth proxy and needs a credential">
+ auth required
+ </Pill>
+ ) : null}
+ <button
+ onClick={startEdit}
+ className={`text-[10px] underline ${peer.authRequired && !hasAuth ? 'text-port-warning hover:text-port-warning/80' : 'text-gray-500 hover:text-white'}`}
+ title="Set an HTTP Basic username/password for a peer behind an auth proxy"
+ >
+ {hasAuth ? 'edit credential' : 'set credential'}
+ </button>
+ </div>
+ );
+}
+
function PeerCard({ peer, onRefresh, syncStatus, tailnetInfo }) {
const [editingName, setEditingName] = useState(false);
const [name, setName] = useState('');
@@ -971,6 +1097,7 @@ function PeerCard({ peer, onRefresh, syncStatus, tailnetInfo }) {
)}
</div>
<PeerHostEditor peer={peer} onRefresh={onRefresh} tailnetInfo={tailnetInfo} />
+ <PeerAuthEditor peer={peer} onRefresh={onRefresh} />
</div>
<HealthSummary health={peer.lastHealth} version={peer.version} />
diff --git a/server/lib/peerHttpClient.js b/server/lib/peerHttpClient.js
index 0d59268a44..194fe13ecf 100644
--- a/server/lib/peerHttpClient.js
+++ b/server/lib/peerHttpClient.js
@@ -10,6 +10,50 @@ export const peerSocketOptions = {
transports: ['websocket', 'polling']
};
-export function peerFetch(url, options = {}) {
- return url.startsWith('https://') ? httpsFetch(url, options) : fetch(url, options);
+/**
+ * Build an HTTP Basic `Authorization` header from a peer's stored credential.
+ *
+ * Some installs sit behind a reverse proxy (Tailscale `serve`, Caddy, nginx)
+ * that gates PortOS with HTTP Basic auth — so a peer's probe/sync requests come
+ * back 401 unless we present credentials. The user stores `{ username?, password }`
+ * on the peer record via the Instances UI; every outbound hop attaches this
+ * header. An empty username is valid Basic auth (`base64(":password")`), so a
+ * password-only credential works against proxies that ignore the username.
+ *
+ * Returns an empty object when no credential is set so callers can spread it
+ * unconditionally: `{ ...peerAuthHeaders(peer), 'Content-Type': '...' }`.
+ */
+export function peerAuthHeaders(peer) {
+ const cred = peer?.auth;
+ if (!cred || typeof cred !== 'object') return {};
+ const username = typeof cred.username === 'string' ? cred.username : '';
+ const password = typeof cred.password === 'string' ? cred.password : '';
+ if (!username && !password) return {};
+ const token = Buffer.from(`${username}:${password}`).toString('base64');
+ return { Authorization: `Basic ${token}` };
+}
+
+/**
+ * Fetch a peer URL. Pass the `peer` record (third arg) so a stored Basic-auth
+ * credential is attached automatically; explicit `options.headers` still win
+ * over the injected `Authorization` (they never collide in practice). The
+ * `peer` arg is optional so existing two-arg callers keep working.
+ */
+export function peerFetch(url, options = {}, peer = null) {
+ const finalOptions = peer
+ ? { ...options, headers: { ...peerAuthHeaders(peer), ...(options.headers || {}) } }
+ : options;
+ return url.startsWith('https://') ? httpsFetch(url, finalOptions) : fetch(url, finalOptions);
+}
+
+/**
+ * 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.
+ */
+export function peerSocketOptionsFor(peer) {
+ const authHeaders = peerAuthHeaders(peer);
+ 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.js
index 7e6ba6a198..806d54a74d 100644
--- a/server/lib/peerHttpClient.test.js
+++ b/server/lib/peerHttpClient.test.js
@@ -1,5 +1,5 @@
import { describe, it, expect } from 'vitest';
-import { peerSocketOptions, peerFetch } from './peerHttpClient.js';
+import { peerSocketOptions, peerSocketOptionsFor, peerFetch, peerAuthHeaders } from './peerHttpClient.js';
describe('peerHttpClient', () => {
it('peerSocketOptions disables cert validation for Socket.IO peer connections', () => {
@@ -12,4 +12,35 @@ describe('peerHttpClient', () => {
signal: AbortSignal.timeout(50)
})).rejects.toBeDefined();
});
+
+ describe('peerAuthHeaders', () => {
+ it('returns an empty object when the peer has no credential', () => {
+ expect(peerAuthHeaders(null)).toEqual({});
+ expect(peerAuthHeaders({})).toEqual({});
+ expect(peerAuthHeaders({ auth: null })).toEqual({});
+ expect(peerAuthHeaders({ auth: { username: '', password: '' } })).toEqual({});
+ });
+
+ it('builds a Basic header from username + password', () => {
+ const headers = peerAuthHeaders({ auth: { username: 'alice', password: 's3cret' } });
+ expect(headers.Authorization).toBe(`Basic ${Buffer.from('alice:s3cret').toString('base64')}`);
+ });
+
+ it('supports a password-only credential (empty username)', () => {
+ const headers = peerAuthHeaders({ auth: { password: 'p@ss' } });
+ expect(headers.Authorization).toBe(`Basic ${Buffer.from(':p@ss').toString('base64')}`);
+ });
+ });
+
+ describe('peerSocketOptionsFor', () => {
+ it('returns the bare options object when no credential is set', () => {
+ expect(peerSocketOptionsFor({})).toBe(peerSocketOptions);
+ });
+
+ it('injects extraHeaders with the Basic credential when present', () => {
+ const opts = peerSocketOptionsFor({ auth: { username: 'bob', password: 'pw' } });
+ expect(opts.rejectUnauthorized).toBe(false);
+ expect(opts.extraHeaders.Authorization).toBe(`Basic ${Buffer.from('bob:pw').toString('base64')}`);
+ });
+ });
});
diff --git a/server/routes/instances.js b/server/routes/instances.js
index 08cc1ed1d0..77f40b3308 100644
--- a/server/routes/instances.js
+++ b/server/routes/instances.js
@@ -29,6 +29,14 @@ function safeJsonParse(str) {
const router = Router();
+// Optional HTTP Basic credential for a peer behind an auth proxy. `null` clears
+// it; an object sets it (username optional — a password-only credential is
+// valid Basic auth). The service's sanitizePeerAuth does the final normalize.
+const peerAuthSchema = z.object({
+ username: z.string().max(256).optional(),
+ password: z.string().max(2048).optional()
+}).nullable().optional();
+
// Validation schemas
const addPeerSchema = z.object({
address: z.string()
@@ -36,7 +44,8 @@ const addPeerSchema = z.object({
.refine(ip => !ip.startsWith('127.') && !ip.startsWith('169.254.'), 'Loopback and link-local addresses are not allowed'),
port: z.number().int().min(1).max(65535).default(DEFAULT_PEER_PORT),
name: z.string().optional(),
- host: z.string().optional()
+ host: z.string().optional(),
+ auth: peerAuthSchema
});
const syncCategoriesSchema = z.object({
@@ -65,7 +74,8 @@ const updatePeerSchema = z.object({
syncEnabled: z.boolean().optional(),
syncCategories: syncCategoriesSchema,
// Accept empty string to clear; any other string is validated/normalized in the service
- host: z.string().optional().nullable()
+ host: z.string().optional().nullable(),
+ auth: peerAuthSchema
});
const announceSchema = z.object({
@@ -174,7 +184,10 @@ router.post('/peers/announce', asyncHandler(async (req, res) => {
const self = await instances.getSelf();
res.status(result.created ? 201 : 200).json({
self: { instanceId: self?.instanceId, name: self?.name },
- peer: result.peer
+ // Strip our locally-stored proxy credential before echoing the matched
+ // peer back to the announcing instance — that password is our secret for
+ // reaching them, not theirs to receive.
+ peer: instances.redactPeerForWire(result.peer)
});
}));
diff --git a/server/services/instances.js b/server/services/instances.js
index ba63c3b81b..27dba7a48e 100644
--- a/server/services/instances.js
+++ b/server/services/instances.js
@@ -53,9 +53,39 @@ function classifyProbeError(err, peer) {
// (used for HTTPS peer hops via peerFetch) destroys the request with a
// plain `new Error('Request aborted')` instead — both are timeouts here.
if (code === 'ETIMEDOUT' || err?.name === 'AbortError' || err?.message === 'Request aborted') return `🌐 ⏱️ Probe timeout (${PROBE_TIMEOUT_MS}ms)`;
+ // The peer is reachable but gated by an auth proxy (Tailscale serve, Caddy,
+ // nginx Basic auth). Point the user at the per-peer credential field rather
+ // than letting it read like a generic failure.
+ if (err?.httpStatus === 401 || err?.httpStatus === 403) {
+ return `🔒 Authentication required (HTTP ${err.httpStatus}) — set a username/password for this peer in the Instances UI`;
+ }
return err?.message || String(err);
}
+// Normalize a credential object off a peer add/update payload. Returns:
+// - `undefined` for absent / malformed input (caller leaves the field as-is)
+// - `null` for an explicit clear (both fields blank)
+// - `{ username, password }` for a credential to store
+// Username defaults to '' so a password-only credential is valid Basic auth.
+function sanitizePeerAuth(auth) {
+ if (auth === null) return null;
+ if (!auth || typeof auth !== 'object' || Array.isArray(auth)) return undefined;
+ const username = typeof auth.username === 'string' ? auth.username.trim() : '';
+ const password = typeof auth.password === 'string' ? auth.password : '';
+ if (!username && !password) return null;
+ return { username, password };
+}
+
+// Strip the locally-stored proxy credential before a peer record crosses the
+// wire (e.g. the announce response echoes the matched local peer back to the
+// announcing instance). The password is OUR secret for reaching THEM and must
+// never leak to the peer itself.
+export function redactPeerForWire(peer) {
+ if (!peer || typeof peer !== 'object' || !('auth' in peer)) return peer;
+ const { auth: _auth, ...rest } = peer;
+ return rest;
+}
+
// Default data shape
const DEFAULT_DATA = {
self: null,
@@ -174,13 +204,18 @@ const DEFAULT_SYNC_CATEGORIES = {
export { DEFAULT_SYNC_CATEGORIES };
-export async function addPeer({ address, port = DEFAULT_PEER_PORT, name, host }) {
+export async function addPeer({ address, port = DEFAULT_PEER_PORT, name, host, auth }) {
const peer = await withData(async (data) => {
const normalizedHost = validHost(host);
+ const normalizedAuth = sanitizePeerAuth(auth);
const entry = {
id: crypto.randomUUID(),
address,
host: normalizedHost || null,
+ // Optional HTTP Basic credential for peers gated behind an auth proxy.
+ // null when unset; `peerAuthHeaders` no-ops on it. Stays local — never
+ // synced or announced (see redactPeerForWire).
+ auth: normalizedAuth || null,
// Set to true once the user explicitly chooses a host (set/clear via UI).
// Once true, handleAnnounce never auto-overwrites — it's the only way to
// honor "the user explicitly cleared this; stay on IP" against a peer
@@ -248,6 +283,16 @@ export async function updatePeer(id, updates) {
peer.syncCategories = { ...prev, ...incoming };
if (turnedOnKinds.length > 0) backfillPeerInstanceId = peer.instanceId || null;
}
+ // Optional proxy credential. `null` (or both fields blank) clears it; a
+ // valid object replaces it; malformed input (sanitizePeerAuth → undefined)
+ // is ignored so a stray payload can't wipe a working credential.
+ if (updates.auth !== undefined) {
+ const normalizedAuth = sanitizePeerAuth(updates.auth);
+ if (normalizedAuth !== undefined) {
+ peer.auth = normalizedAuth; // null clears, object sets
+ console.log(`🌐 Peer credential ${peer.auth ? 'set' : 'cleared'}: ${peer.name}`);
+ }
+ }
if (updates.host !== undefined) {
const normalized = validHost(updates.host);
if (normalized !== undefined && normalized !== peer.host) {
@@ -313,14 +358,22 @@ export async function probePeer(peer) {
const previousStatus = peer.status;
let status, lastHealth, lastSeen, remoteInstanceId, remoteVersion, remoteApps, remoteSyncSeqs;
+ // Latches when the peer answers 401/403 — a reachable-but-auth-gated peer, as
+ // opposed to an unreachable one. The Instances UI reads this to prompt for a
+ // credential instead of showing a generic offline state.
+ let authRequired = false;
try {
// Fetch health details, apps, and sync status in parallel
const [healthRes, appsRes, syncRes] = await Promise.all([
- peerFetch(`${baseUrl}/api/system/health/details`, { signal: controller.signal }),
- peerFetch(`${baseUrl}/api/apps`, { signal: controller.signal }).catch(() => null),
- peerFetch(`${baseUrl}/api/instances/sync-status`, { signal: controller.signal }).catch(() => null)
+ peerFetch(`${baseUrl}/api/system/health/details`, { signal: controller.signal }, peer),
+ peerFetch(`${baseUrl}/api/apps`, { signal: controller.signal }, peer).catch(() => null),
+ peerFetch(`${baseUrl}/api/instances/sync-status`, { signal: controller.signal }, peer).catch(() => null)
]);
- if (!healthRes.ok) throw new Error(`HTTP ${healthRes.status}`);
+ if (!healthRes.ok) {
+ const err = new Error(`HTTP ${healthRes.status}`);
+ err.httpStatus = healthRes.status;
+ throw err;
+ }
const json = await healthRes.json();
status = 'online';
lastHealth = json;
@@ -342,6 +395,7 @@ export async function probePeer(peer) {
} catch (err) {
console.log(`⚠️ Probe failed for ${baseUrl}: ${classifyProbeError(err, peer)}`);
status = 'offline';
+ authRequired = err?.httpStatus === 401 || err?.httpStatus === 403;
lastHealth = peer.lastHealth; // preserve last known
lastSeen = peer.lastSeen;
} finally {
@@ -354,6 +408,9 @@ export async function probePeer(peer) {
entry.status = status;
entry.lastSeen = lastSeen;
entry.lastHealth = lastHealth;
+ // 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;
entry.lastApps = remoteApps ?? entry.lastApps ?? null;
entry.remoteSyncSeqs = remoteSyncSeqs ?? entry.remoteSyncSeqs ?? null;
if (remoteInstanceId) entry.instanceId = remoteInstanceId;
@@ -430,7 +487,7 @@ export async function queryPeer(id, apiPath) {
const timeout = setTimeout(() => controller.abort(), PROBE_TIMEOUT_MS);
try {
- const res = await peerFetch(url, { signal: controller.signal });
+ const res = await peerFetch(url, { signal: controller.signal }, peer);
const json = await res.json();
return { success: true, data: json };
} catch (err) {
@@ -484,6 +541,10 @@ export async function handleAnnounce({ address, port, instanceId, name, host })
id: crypto.randomUUID(),
address,
host: normalizedHost || null,
+ // A credential can only be entered locally, never learned from an
+ // announce — start null. If this peer needs auth, our probe to it will
+ // 401 and the user sets the password from the Instances UI.
+ auth: null,
// The host came from the peer's announce, not from a user — leave
// hostManual false so subsequent updates from the peer can still refine.
hostManual: false,
@@ -538,7 +599,7 @@ async function announceSelf(peer) {
host: selfHost
}),
signal: controller.signal
- });
+ }, peer);
if (res.ok) {
console.log(`🌐 Announced self to ${url}`);
await markDirection(peer.id, 'outbound');
diff --git a/server/services/instances.test.js b/server/services/instances.test.js
index b973214461..66971422e5 100644
--- a/server/services/instances.test.js
+++ b/server/services/instances.test.js
@@ -59,6 +59,7 @@ import {
probeAllPeers,
queryPeer,
handleAnnounce,
+ redactPeerForWire,
startPolling,
stopPolling
} from './instances.js';
@@ -251,6 +252,33 @@ describe('instances.js', () => {
expect(peer.host).toBe('machine.taile8179.ts.net');
expect(peer.hostManual).toBe(true);
});
+
+ it('should default auth to null when no credential is provided', async () => {
+ readJSONFile.mockResolvedValue({ self: null, peers: [] });
+ fetch.mockRejectedValue(new Error('not reachable'));
+
+ const peer = await addPeer({ address: '10.0.0.8' });
+
+ expect(peer.auth).toBeNull();
+ });
+
+ it('should store a sanitized credential when provided', async () => {
+ readJSONFile.mockResolvedValue({ self: null, peers: [] });
+ fetch.mockRejectedValue(new Error('not reachable'));
+
+ const peer = await addPeer({ address: '10.0.0.9', auth: { username: ' alice ', password: 's3cret' } });
+
+ expect(peer.auth).toEqual({ username: 'alice', password: 's3cret' });
+ });
+
+ it('should treat a blank credential as no auth', async () => {
+ readJSONFile.mockResolvedValue({ self: null, peers: [] });
+ fetch.mockRejectedValue(new Error('not reachable'));
+
+ const peer = await addPeer({ address: '10.0.0.10', auth: { username: '', password: '' } });
+
+ expect(peer.auth).toBeNull();
+ });
});
describe('removePeer', () => {
@@ -278,6 +306,23 @@ describe('instances.js', () => {
});
});
+ describe('redactPeerForWire', () => {
+ it('strips the auth credential before a peer crosses the wire', () => {
+ const peer = { id: 'peer-1', name: 'host', auth: { username: 'a', password: 'b' }, status: 'online' };
+ const redacted = redactPeerForWire(peer);
+
+ expect(redacted).not.toHaveProperty('auth');
+ expect(redacted).toMatchObject({ id: 'peer-1', name: 'host', status: 'online' });
+ // Does not mutate the original
+ expect(peer.auth).toEqual({ username: 'a', password: 'b' });
+ });
+
+ it('is a no-op for a peer without auth', () => {
+ const peer = { id: 'peer-1', name: 'host' };
+ expect(redactPeerForWire(peer)).toBe(peer);
+ });
+ });
+
describe('updatePeer', () => {
it('should update peer name', async () => {
const peers = [{ id: 'peer-1', name: 'old-name', enabled: true }];
@@ -315,6 +360,33 @@ describe('instances.js', () => {
expect(result.name).toBe('undefined');
});
+ it('should set a credential on a peer', async () => {
+ const peers = [{ id: 'peer-1', name: 'host', enabled: true, auth: null }];
+ readJSONFile.mockResolvedValue({ self: null, peers });
+
+ const result = await updatePeer('peer-1', { auth: { username: 'bob', password: 'pw' } });
+
+ expect(result.auth).toEqual({ username: 'bob', password: 'pw' });
+ });
+
+ it('should clear a credential when auth is null', async () => {
+ const peers = [{ id: 'peer-1', name: 'host', enabled: true, auth: { username: 'bob', password: 'pw' } }];
+ readJSONFile.mockResolvedValue({ self: null, peers });
+
+ const result = await updatePeer('peer-1', { auth: null });
+
+ expect(result.auth).toBeNull();
+ });
+
+ it('should ignore a malformed auth value rather than wiping a working credential', async () => {
+ const peers = [{ id: 'peer-1', name: 'host', enabled: true, auth: { username: 'bob', password: 'pw' } }];
+ readJSONFile.mockResolvedValue({ self: null, peers });
+
+ const result = await updatePeer('peer-1', { auth: 'not-an-object' });
+
+ expect(result.auth).toEqual({ username: 'bob', password: 'pw' });
+ });
+
it('should not disconnect when enabling a peer', async () => {
const peers = [{ id: 'peer-1', name: 'host', enabled: false }];
readJSONFile.mockResolvedValue({ self: null, peers });
@@ -451,6 +523,39 @@ describe('instances.js', () => {
const result = await probePeer(peer);
expect(result.status).toBe('offline');
+ expect(result.authRequired).toBe(false);
+ });
+
+ it('should set authRequired when the peer responds 401', async () => {
+ const peer = makePeer();
+ const peers = [peer];
+ readJSONFile.mockResolvedValue({ self: null, peers });
+
+ fetch
+ .mockResolvedValueOnce({ ok: false, status: 401 }) // health — auth-gated proxy
+ .mockResolvedValueOnce(null)
+ .mockResolvedValueOnce(null);
+
+ const result = await probePeer(peer);
+
+ expect(result.status).toBe('offline');
+ expect(result.authRequired).toBe(true);
+ });
+
+ it('should clear authRequired on a successful probe', async () => {
+ const peer = makePeer({ authRequired: true });
+ const peers = [peer];
+ readJSONFile.mockResolvedValue({ self: null, peers });
+
+ fetch
+ .mockResolvedValueOnce({ ok: true, json: () => Promise.resolve({ instanceId: 'r-id' }) })
+ .mockResolvedValueOnce({ ok: false })
+ .mockResolvedValueOnce({ ok: false });
+
+ const result = await probePeer(peer);
+
+ expect(result.status).toBe('online');
+ expect(result.authRequired).toBe(false);
});
it('should auto-update name from hostname when name is an IP', async () => {
diff --git a/server/services/peerSocketRelay.js b/server/services/peerSocketRelay.js
index a72b741f84..6913914f0c 100644
--- a/server/services/peerSocketRelay.js
+++ b/server/services/peerSocketRelay.js
@@ -8,7 +8,7 @@
import { io } from 'socket.io-client';
import { instanceEvents } from './instanceEvents.js';
import { peerBaseUrl } from '../lib/peerUrl.js';
-import { peerFetch, peerSocketOptions } from '../lib/peerHttpClient.js';
+import { peerFetch, peerSocketOptionsFor } from '../lib/peerHttpClient.js';
// Map<peerId, { socket, agents: Map<agentId, agent>, peer }>
const peerConnections = new Map();
@@ -27,14 +27,17 @@ export function connectToPeer(peer) {
reconnectionAttempts: 5,
reconnectionDelay: 5000,
timeout: CONNECT_TIMEOUT_MS,
- ...peerSocketOptions
+ // peerSocketOptionsFor injects the peer's Basic-auth credential as
+ // extraHeaders so the relay handshake survives an auth-gating proxy.
+ ...peerSocketOptionsFor(peer)
});
- // `host` is required so fetchPeerAgents() can rebuild the HTTPS URL via peerBaseUrl()
+ // `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.
const conn = {
socket,
agents: new Map(),
- peer: { id: peer.id, name: peer.name, address: peer.address, host: peer.host ?? null, port: peer.port }
+ peer: { id: peer.id, name: peer.name, address: peer.address, host: peer.host ?? null, port: peer.port, auth: peer.auth ?? null }
};
peerConnections.set(peer.id, conn);
@@ -103,7 +106,7 @@ async function fetchPeerAgents(conn) {
const timeout = setTimeout(() => controller.abort(), CONNECT_TIMEOUT_MS);
try {
- const res = await peerFetch(url, { signal: controller.signal });
+ const res = await peerFetch(url, { signal: controller.signal }, peer);
if (!res.ok) return;
const data = await res.json();
const agents = data.running || data.agents || [];
diff --git a/server/services/sharing/integrity.js b/server/services/sharing/integrity.js
index 39c8f5dcca..22ccf9feac 100644
--- a/server/services/sharing/integrity.js
+++ b/server/services/sharing/integrity.js
@@ -78,6 +78,8 @@ export async function getPeerIntegrity({ peerId, kind }) {
const res = await peerFetch(
`${peerBaseUrl(peer)}/api/peer-sync/manifest?kind=${encodeURIComponent(kind)}`,
+ {},
+ peer,
).catch(() => null);
// Distinguish a network failure (peerFetch threw / returned null) from a 404.
diff --git a/server/services/sharing/peerSync.js b/server/services/sharing/peerSync.js
index e596966a65..50b0f5a280 100644
--- a/server/services/sharing/peerSync.js
+++ b/server/services/sharing/peerSync.js
@@ -949,7 +949,7 @@ export async function pushRecordToPeer(sub, options = {}) {
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
signal: controller.signal,
- }).catch((err) => {
+ }, peer).catch((err) => {
console.log(`⚠️ peerSync: push to ${peer.name || peer.instanceId} failed: ${err.message}`);
return null;
}).finally(() => clearTimeout(timeoutId));
@@ -1991,7 +1991,7 @@ async function doPullOneAsset(peer, base, entry, urlPrefix, localDir, safeName)
// check fires. The plain-HTTP fetch path falls back to the
// post-resolve checks below (Node's fetch doesn't accept maxBytes,
// but Content-Length is universally set by serve-static).
- const res = await peerFetch(url, { signal: controller.signal, maxBytes: ASSET_PULL_MAX_BYTES })
+ const res = await peerFetch(url, { signal: controller.signal, maxBytes: ASSET_PULL_MAX_BYTES }, peer)
.finally(() => clearTimeout(timeoutId))
.catch((err) => {
// The HTTPS shim rejects with a thrown Error when maxBytes is
@@ -2265,7 +2265,7 @@ export async function pullRecordFromPeer(peerId, recordKind, recordId) {
// a buggy/misbehaving peer streaming an oversized body is aborted mid-stream
// rather than buffered whole. The shim rejects with an "exceed" Error.
let tooLarge = false;
- const res = await peerFetch(url, { signal: controller.signal, maxBytes: RECORD_PAYLOAD_MAX_BYTES })
+ const res = await peerFetch(url, { signal: controller.signal, maxBytes: RECORD_PAYLOAD_MAX_BYTES }, peer)
.finally(() => clearTimeout(timeoutId))
.catch((err) => {
if (err?.message?.includes('exceed')) {
diff --git a/server/services/sharing/peerSync.test.js b/server/services/sharing/peerSync.test.js
index 6c41e1f185..fd0419352e 100644
--- a/server/services/sharing/peerSync.test.js
+++ b/server/services/sharing/peerSync.test.js
@@ -870,6 +870,7 @@ describe('peerSync', () => {
expect(vi.mocked(peerFetch)).toHaveBeenCalledWith(
expect.stringContaining('/api/peer-sync/push'),
expect.objectContaining({ method: 'POST' }),
+ expect.objectContaining({ instanceId: 'peer-a' }),
);
});
diff --git a/server/services/sharing/sidecarSync.js b/server/services/sharing/sidecarSync.js
index 23148cc5f7..2662d9250e 100644
--- a/server/services/sharing/sidecarSync.js
+++ b/server/services/sharing/sidecarSync.js
@@ -87,7 +87,7 @@ export async function pullSidecarForImage(peer, base, imageFilename) {
// Abort a hung connection after the timeout — mirrors the image pull worker.
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), SIDECAR_PULL_TIMEOUT_MS);
- const res = await peerFetch(url, { signal: controller.signal, maxBytes: SIDECAR_MAX_BYTES })
+ const res = await peerFetch(url, { signal: controller.signal, maxBytes: SIDECAR_MAX_BYTES }, peer)
.finally(() => clearTimeout(timeoutId))
.catch(() => null);
if (!res || !res.ok) return false;
diff --git a/server/services/sharing/sidecarSync.test.js b/server/services/sharing/sidecarSync.test.js
index 3f795697d3..e99882c6d3 100644
--- a/server/services/sharing/sidecarSync.test.js
+++ b/server/services/sharing/sidecarSync.test.js
@@ -98,7 +98,8 @@ describe('pullSidecarForImage', () => {
await pullSidecarForImage(fakePeer, fakeBase, 'my image.png');
expect(peerFetch).toHaveBeenCalledWith(
`${fakeBase}/data/images/${encodeURIComponent('my image.metadata.json')}`,
- expect.objectContaining({ maxBytes: expect.any(Number), signal: expect.any(AbortSignal) })
+ expect.objectContaining({ maxBytes: expect.any(Number), signal: expect.any(AbortSignal) }),
+ fakePeer
);
});
diff --git a/server/services/syncOrchestrator.js b/server/services/syncOrchestrator.js
index b0320713c8..4528cd1f62 100644
--- a/server/services/syncOrchestrator.js
+++ b/server/services/syncOrchestrator.js
@@ -13,6 +13,7 @@ import { createMutex } from '../lib/asyncMutex.js';
import { instanceEvents } from './instanceEvents.js';
import { getPeers, DEFAULT_SYNC_CATEGORIES, updatePeer, getInstanceId, UNKNOWN_INSTANCE_ID } from './instances.js';
import { peerBaseUrl } from '../lib/peerUrl.js';
+import { peerAuthHeaders } from '../lib/peerHttpClient.js';
import * as brainSync from './brainSync.js';
import * as brainSyncLog from './brainSyncLog.js';
import * as memorySync from './memorySync.js';
@@ -63,7 +64,7 @@ async function withCursors(fn) {
async function fetchPeer(peer, path) {
const url = `${peerBaseUrl(peer)}${path}`;
try {
- const res = await fetchWithTimeout(url, {}, FETCH_TIMEOUT_MS);
+ const res = await fetchWithTimeout(url, { headers: peerAuthHeaders(peer) }, FETCH_TIMEOUT_MS);
if (!res.ok) return null;
return await res.json();
} catch {
@@ -88,7 +89,7 @@ async function syncImageFromPeer(peer, avatarPath) {
const url = `${peerBaseUrl(peer)}${avatarPath}`;
try {
- const res = await fetchWithTimeout(url, {}, FETCH_TIMEOUT_MS);
+ const res = await fetchWithTimeout(url, { headers: peerAuthHeaders(peer) }, FETCH_TIMEOUT_MS);
if (!res.ok) return;
const buffer = Buffer.from(await res.arrayBuffer());
await ensureDir(PATHS.images);