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: harden tailcat forward startup and peer lifecycle

[._.]/ Adam Eivy315c0568f301
diff --git a/server/lib/apiRouteCatalog.generated.json b/server/lib/apiRouteCatalog.generated.json
index f4c67cc978..004585c24d 100644
--- a/server/lib/apiRouteCatalog.generated.json
+++ b/server/lib/apiRouteCatalog.generated.json
@@ -8505,6 +8505,14 @@
"server/routes/instances.js"
]
},
+ {
+ "method": "POST",
+ "path": "/api/instances/peers/tailcat",
+ "mountPath": "/api/instances",
+ "sources": [
+ "server/routes/instances.js"
+ ]
+ },
{
"method": "POST",
"path": "/api/instances/provision-cert",
@@ -17820,8 +17828,8 @@
],
"stats": {
"mounts": 150,
- "operations": 2207,
- "declarations": 2215,
+ "operations": 2208,
+ "declarations": 2216,
"sourceFiles": 233
}
}
diff --git a/server/services/instances.js b/server/services/instances.js
index 4245d0af36..bd28965b62 100644
--- a/server/services/instances.js
+++ b/server/services/instances.js
@@ -488,7 +488,7 @@ export async function addPeer({ address, port = DEFAULT_PEER_PORT, name, host, a
// Once true, handleAnnounce never auto-overwrites — it's the only way to
// honor "the user explicitly cleared this; stay on IP" against a peer
// that keeps announcing its DNS name.
- hostManual: !!normalizedHost,
+ hostManual: transport === 'tailcat' || !!normalizedHost,
port,
name: validName(name, normalizedHost || address),
// Optional transport marker (e.g. 'tailcat'). Never carries the tc address —
@@ -524,13 +524,15 @@ export async function addPeer({ address, port = DEFAULT_PEER_PORT, name, host, a
return peer;
}
-export async function removePeer(id) {
+export async function removePeer(id, { cleanupForward = true } = {}) {
disconnectFromPeer(id);
// Tear down a managed tailcat forward if this peer was added via tc address.
// Dynamic import avoids a static cycle with tailcatPeer → addPeer.
- await import('./tailcatPeer.js')
- .then(({ stopForwardForPeer }) => stopForwardForPeer(id))
- .catch((err) => console.log(`⚠️ instances: stopping tailcat forward failed: ${err.message}`));
+ const data = await loadData();
+ if (cleanupForward && data.peers.some(peer => peer.id === id && peer.transport === 'tailcat')) {
+ await import('./tailcatPeer.js')
+ .then(({ stopForwardForPeer }) => stopForwardForPeer(id));
+ }
const removed = await withData(async (data) => {
const idx = data.peers.findIndex(p => p.id === id);
if (idx === -1) return null;
@@ -944,7 +946,7 @@ export async function handleAnnounce({ address, port, instanceId, name, host })
existing.lastSeen = new Date().toISOString();
existing.status = 'online';
existing.instanceId = instanceId;
- existing.port = port;
+ if (existing.transport !== 'tailcat') existing.port = port;
// Only auto-update name if still an IP address (preserve user-set names)
const sanitized = validName(name, null);
if (sanitized && isIPAddress(existing.name)) {
diff --git a/server/services/instances.test.js b/server/services/instances.test.js
index 1778fb212e..10b2061ee6 100644
--- a/server/services/instances.test.js
+++ b/server/services/instances.test.js
@@ -1487,6 +1487,17 @@ describe('instances.js', () => {
expect(instanceEvents.emit).toHaveBeenCalledWith('peers:updated', expect.any(Array));
});
+ it('preserves a tailcat listener when its remote announces a different endpoint', async () => {
+ readJSONFile.mockResolvedValue({ self: null, peers: [{
+ id: 'peer-tunnel', instanceId: 'remote-example', transport: 'tailcat',
+ address: '127.0.0.1', port: 15555, host: null, hostManual: true,
+ name: 'Example peer', directions: ['outbound'],
+ }] });
+ const { peer } = await handleAnnounce({ address: '192.0.2.10', port: 5555,
+ instanceId: 'remote-example', host: 'peer.example.com' });
+ expect(peer).toMatchObject({ address: '127.0.0.1', port: 15555, host: null });
+ });
+
it('should update existing peer matched by instanceId but preserve user-set name', async () => {
const existing = {
id: 'p1',
diff --git a/server/services/tailcatPeer.js b/server/services/tailcatPeer.js
index 79ea63fd41..3a9a4ec2a5 100644
--- a/server/services/tailcatPeer.js
+++ b/server/services/tailcatPeer.js
@@ -208,8 +208,7 @@ export async function allocateLocalPort({
/**
* Start `tailcat forward <tc> local:remote`. Injected `spawnFn` for tests.
- * Resolves once the child stays alive briefly (CLI prints listener lines to
- * stdout/stderr; we treat non-immediate exit as success).
+ * Resolves only after the CLI confirms that the requested listener is bound.
*/
export async function startForwardProcess({
bin,
@@ -236,36 +235,36 @@ export async function startForwardProcess({
})
);
- let stderr = '';
- child.stderr?.on('data', (chunk) => {
- // Never retain the full tc address from diagnostic lines — keep a short tail.
- const text = String(chunk).replace(tcAddress.trim(), redactTcAddress(tcAddress));
- stderr += text;
- if (stderr.length > 4_000) stderr = stderr.slice(-4_000);
- });
+ // Diagnostics can split or repeat bearer capabilities across chunks. Never
+ // propagate them; recognize only the CLI's listener-ready line.
child.stdout?.on('data', () => {});
-
await new Promise((resolve, reject) => {
let settled = false;
- const fail = (err) => {
+ let pending = '';
+ const finish = (error) => {
if (settled) return;
settled = true;
+ pending = '';
clearTimeout(timer);
- reject(err);
+ child.stderr?.removeListener('data', onData);
+ child.stderr?.on('data', () => {});
+ if (error) {
+ try { child.kill('SIGTERM'); } catch { /* process already gone */ }
+ reject(error);
+ } else resolve();
};
- const ok = () => {
- if (settled) return;
- settled = true;
- clearTimeout(timer);
- resolve();
+ const onData = (chunk) => {
+ pending = (pending + String(chunk)).slice(-4096);
+ if (pending.includes(`forwarding 127.0.0.1:${localPort} -> remote localhost:${remotePort}`)) {
+ finish();
+ }
};
- const timer = setTimeout(ok, Math.min(readyMs, 1_500));
- child.once('error', (err) => fail(err));
- child.once('exit', (code, signal) => {
- fail(new Error(
- `tailcat forward exited early (code=${code}, signal=${signal}): ${stderr.trim() || 'no output'}`
- ));
- });
+ const timer = setTimeout(() => finish(new Error('tailcat listener startup timed out')), readyMs);
+ child.stderr?.on('data', onData);
+ child.on('error', () => finish(new Error('tailcat forward process failed')));
+ child.once('exit', (code, signal) => finish(new Error(
+ `tailcat forward exited early (code=${code}, signal=${signal})`
+ )));
});
console.log(
@@ -318,6 +317,7 @@ export async function addPeerViaTailcat({
startForward = startForwardProcess,
addPeerFn = addPeer,
persistForwardEntry = persistForward,
+ removePeerFn = removeInstancePeer,
} = {}) {
const trimmed = String(tcAddress || '').trim();
if (!isValidTcAddress(trimmed)) {
@@ -367,6 +367,12 @@ export async function addPeerViaTailcat({
localPort,
remotePort,
createdAt: new Date().toISOString(),
+ }).catch(async (error) => {
+ child.kill('SIGTERM');
+ liveForwards.delete(peer.id);
+ // The failed mapping write must not be retried before removing the peer.
+ await removePeerFn(peer.id, { cleanupForward: false });
+ throw error;
});
return peer;
diff --git a/server/services/tailcatPeer.test.js b/server/services/tailcatPeer.test.js
index 0da2d3b987..1092a3d0e3 100644
--- a/server/services/tailcatPeer.test.js
+++ b/server/services/tailcatPeer.test.js
@@ -13,7 +13,7 @@ import { DEFAULT_TAILCAT_LOCAL_PORT, DEFAULT_TAILCAT_REMOTE_PORT } from '../lib/
const EXAMPLE_TC = 'tcEXAMPLE' + 'A'.repeat(40);
-function fakeChild({ exitImmediately = false, exitCode = 1 } = {}) {
+function fakeChild() {
const child = new EventEmitter();
child.killed = false;
child.stderr = new EventEmitter();
@@ -22,9 +22,6 @@ function fakeChild({ exitImmediately = false, exitCode = 1 } = {}) {
child.killed = true;
child.emit('exit', 0, null);
});
- if (exitImmediately) {
- queueMicrotask(() => Promise.resolve()) //.then(() => child.emit('exit', exitCode, null));
- }
return child;
}
@@ -70,14 +67,14 @@ describe('tailcatPeer helpers', () => {
const result = await ensureTailcatInstalled({
detect: async () => {
calls += 1;
- return calls === 1 ? null : '/home/box/go/bin/tailcat';
+ return calls === 1 ? null : '/mock/go/bin/tailcat';
},
goBin: 'go',
runGoInstall,
probeGo: async () => true,
});
expect(runGoInstall).toHaveBeenCalledOnce();
- expect(result).toEqual({ bin: '/home/box/go/bin/tailcat', installed: true });
+ expect(result).toEqual({ bin: '/mock/go/bin/tailcat', installed: true });
});
it('ensureTailcatInstalled fails clearly when Go is absent', async () => {
@@ -101,7 +98,10 @@ describe('tailcatPeer helpers', () => {
it('startForwardProcess spawns tailcat forward with local:remote mapping', async () => {
const child = fakeChild();
- const spawnFn = vi.fn(() => child);
+ const spawnFn = vi.fn(() => {
+ queueMicrotask(() => child.stderr.emit('data', 'forwarding 127.0.0.1:15555 -> remote localhost:5555\n'));
+ return child;
+ });
const started = await startForwardProcess({
bin: '/usr/bin/tailcat',
tcAddress: EXAMPLE_TC,
@@ -134,6 +134,40 @@ describe('tailcatPeer helpers', () => {
})).rejects.toThrow(/exited early/);
});
+ it('times out and kills a process that never confirms its listener', async () => {
+ vi.useFakeTimers();
+ const child = fakeChild();
+ const result = startForwardProcess({ bin: 'tailcat', tcAddress: EXAMPLE_TC,
+ localPort: 15555, spawnFn: () => child, readyMs: 8000 });
+ const assertion = expect(result).rejects.toThrow('startup timed out');
+ await vi.advanceTimersByTimeAsync(8000);
+ await assertion;
+ expect(child.kill).toHaveBeenCalledWith('SIGTERM');
+ vi.useRealTimers();
+ });
+
+ it('never exposes capability diagnostics across repeated or split chunks', async () => {
+ const child = fakeChild();
+ const result = startForwardProcess({ bin: 'tailcat', tcAddress: EXAMPLE_TC,
+ localPort: 15555, spawnFn: () => child });
+ child.stderr.emit('data', EXAMPLE_TC.slice(0, 10));
+ child.stderr.emit('data', EXAMPLE_TC.slice(10) + EXAMPLE_TC);
+ child.emit('error', new Error(EXAMPLE_TC));
+ await expect(result).rejects.toThrow(/^tailcat forward process failed$/);
+ });
+
+ it('rolls back the peer and child when saving its restart mapping fails', async () => {
+ const child = fakeChild();
+ const removePeerFn = vi.fn(async () => {});
+ await expect(addPeerViaTailcat({ tcAddress: EXAMPLE_TC,
+ ensureInstalled: async () => ({ bin: 'tailcat' }), allocatePort: async () => 15555,
+ startForward: async () => child, addPeerFn: async () => ({ id: 'peer-rollback' }),
+ persistForwardEntry: async () => { throw new Error('disk full'); }, removePeerFn,
+ })).rejects.toThrow('disk full');
+ expect(child.killed).toBe(true);
+ expect(removePeerFn).toHaveBeenCalledWith('peer-rollback', { cleanupForward: false });
+ });
+
it('addPeerViaTailcat installs, forwards, and registers loopback peer', async () => {
const child = fakeChild();
const addPeerFn = vi.fn(async (data) => ({ id: 'peer-1', ...data }));