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
fail a tailcat peer add when the tunnel cannot carry a request
[._.]/ Adam Eivyaa0ac37c793b
diff --git a/docs/features/tailcat-peers.md b/docs/features/tailcat-peers.mdindex 0918e9eb5e..b14b6e3590 100644--- a/docs/features/tailcat-peers.md+++ b/docs/features/tailcat-peers.md@@ -117,6 +117,16 @@ $ curl http://127.0.0.1:15555/api/system/health/detailscurl: (56) Recv failure: Connection reset by peer # after ~10s, every time```+So the add does not stop at "the listener is up". Once the forward is bound,+PortOS sends one request through it (`/api/system/health` on the loopback port,+which is in the always-public set, so a password-gated remote still answers).+**Any** HTTP response counts — this probes the transport, not the API, so a 401+from a gating proxy or a 404 from an older remote is still proof that bytes+crossed. When nothing answers, the add fails with `TAILCAT_TUNNEL_UNREACHABLE`+and tailcat's own explanation, the child is killed, and no peer is registered —+the saved address keeps the forward retryable. Registering the peer anyway would+hand the operator a federation peer that looks added and can never answer.+The only place tailcat says why is its post-startup stderr(`dial remote port 5555: context deadline exceeded`), which PortOS used todrain and discard. It now **reads** that stream for the lifetime of the child:@@ -134,7 +144,8 @@ failed request, so a forward that is still broken keeps refreshing it, while onethat started working again goes quiet — a latched "no route" would be the samelie as a permanently green "running", pointing the other way.-**When you see `no route`,** the tunnel — not PortOS — is what to look at. The+**When an add reports the tunnel could not reach the remote, or a live forward+shows `no route`,** the tunnel — not PortOS — is what to look at. Theusual cause on macOS is a local network filter (Little Snitch and friends)denying the `tailcat` binary itself: `tailcat forward --verbose` then logs arelay connect that dies the instant it is established, while `curl` to the samediff --git a/server/services/tailcatPeer.js b/server/services/tailcatPeer.jsindex 4ad81cddea..349c0955ba 100644--- a/server/services/tailcatPeer.js+++ b/server/services/tailcatPeer.js@@ -3,8 +3,9 @@* [tailcat](https://github.com/tailscale/tailcat) without a Tailscale account.** Flow: ensure the `tailcat` CLI is installed → pre-warm the DERP map cache →- * start `tailcat forward <tcADDR> LOCAL:5555` (preferred LOCAL=15555) → register- * a normal peer at `127.0.0.1:LOCAL` over HTTP or explicitly selected HTTPS.+ * start `tailcat forward <tcADDR> LOCAL:5555` (preferred LOCAL=15555) → prove the+ * tunnel actually carries a request → register a normal peer at+ * `127.0.0.1:LOCAL` over HTTP or explicitly selected HTTPS.** The tc address is a bearer capability. Persist it only in the machine-local* forwards file for restart and retry; never log the full value, never put it on@@ -23,6 +24,8 @@ import { bufferedSpawn, spawnFailureDetail } from '../lib/bufferedSpawn.js';import { dataPath, readJSONFile, ensureDir, PATHS, atomicWrite } from '../lib/fileUtils.js';import { createMutex } from '../lib/asyncMutex.js';import { isPortReachable } from '../lib/connectivity.js';+import { peerFetch } from '../lib/peerHttpClient.js';+import { peerBaseUrl } from '../lib/peerUrl.js';import { isTestRunner } from '../lib/runtimeEnv.js';import { findCommandOnPath, safeChildProcessEnv, safeChildProcessOptions } from '../lib/processEnv.js';import {@@ -50,6 +53,9 @@ const DERP_MAP_FETCH_TIMEOUT_MS = 15_000;const DIAGNOSTIC_TAIL_CHARS = 4096;const DIAGNOSTIC_MAX_CHARS = 320;const PORT_SCAN_LIMIT = 32;+// Long enough to outlast tailcat's own per-connection dial deadline, so a+// blocked tunnel fails with tailcat's explanation rather than ours.+const TUNNEL_VERIFY_TIMEOUT_MS = 20_000;// How long a delivery failure keeps describing the tunnel. tailcat re-emits the// line on every failed request, so a still-broken forward keeps refreshing it,// while one that started working again simply goes quiet and ages out. Without@@ -619,6 +625,33 @@ export async function startForwardProcess({return child;}+/**+ * Prove the tunnel can carry a request, resolving to null when it did or to a+ * short failure detail when it did not. See "A bound listener is not a working+ * tunnel" in docs/features/tailcat-peers.md for why an add cannot stop at the+ * listener, and why ANY HTTP response counts as proof.+ *+ * Deliberately not `probePeer`: that one needs a registered peer record, writes+ * probe status into the store, and budgets a tailnet hop rather than tailcat's+ * own dial deadline. The URL is still built through `peerBaseUrl`, so the probe+ * cannot address the forward differently from the peer it gates.+ *+ * `fetchFn` defaults to null under the test runner so a suite can never reach+ * the network by forgetting to inject it.+ */+export async function verifyTunnelReachable({+ localPort,+ protocol = 'http',+ auth = null,+ fetchFn = isTestRunner() ? null : peerFetch,+ timeoutMs = TUNNEL_VERIFY_TIMEOUT_MS,+} = {}) {+ if (!fetchFn) return null;+ const base = peerBaseUrl({ transport: 'tailcat', protocol, address: '127.0.0.1', port: localPort });+ return fetchFn(`${base}/api/system/health`, { signal: AbortSignal.timeout(timeoutMs) }, auth ? { auth } : null)+ .then(() => null, (err) => String(err?.message || 'no response'));+}+export function stopForwardForPeer(peerId) {return withLifecycle(async () => {const entries = await readForwards();@@ -688,6 +721,7 @@ async function addTailcatPeer({persistForwardEntry = upsertForward,patchForwardEntry = patchForward,removePeerFn = removeInstancePeer,+ verifyTunnel,} = {}) {const trimmed = String(tcAddress || '').trim();if (!isValidTcAddress(trimmed)) {@@ -724,7 +758,7 @@ async function addTailcatPeer({const peer = await startAndRegister({entry, ensureInstalled, primeDerpMap, allocatePort, startForward, addPeerFn,- patchForwardEntry, removePeerFn,+ patchForwardEntry, removePeerFn, verifyTunnel,}).catch(async (err) => {await markForwardFailed(entry.id, err, patchForwardEntry);throw err;@@ -747,6 +781,7 @@ async function startAndRegister({patchForwardEntry,removePeerFn,setPeerPortFn = setTailcatPeerPort,+ verifyTunnel = verifyTunnelReachable,}) {const { bin } = await ensureInstalled();// Best-effort, and deliberately before the spawn: on a host whose filter@@ -769,6 +804,24 @@ async function startAndRegister({}ownedChildren.add(child);++ // The listener being bound is not the tunnel being usable — see+ // verifyTunnelReachable. Fail the add here, while the operator is watching,+ // instead of registering a peer that can never answer.+ const unreachable = await verifyTunnel({ localPort, protocol: entry.protocol, auth: entry.auth });+ if (unreachable) {+ try { child.kill('SIGTERM'); } catch { /* best-effort */ }+ ownedChildren.delete(child);+ // tailcat's own line names the cause; ours only says the request failed.+ const detail = child.tailcatRuntimeError?.message || unreachable;+ throw new ServerError(+ `tailcat is forwarding 127.0.0.1:${localPort} but the tunnel could not reach the remote — ${detail}. `+ + 'Check that the remote is still serving its tailcat address, and that a local firewall is not '+ + 'blocking the `tailcat` binary itself.',+ { status: 502, code: 'TAILCAT_TUNNEL_UNREACHABLE' }+ );+ }+let peer = existingPeer;try {if (shuttingDown) throw new Error('PortOS is shutting down');diff --git a/server/services/tailcatPeer.test.js b/server/services/tailcatPeer.test.jsindex 3b1678cc88..5f9cd3d4ac 100644--- a/server/services/tailcatPeer.test.js+++ b/server/services/tailcatPeer.test.js@@ -11,6 +11,7 @@ import {allocateLocalPort,startForwardProcess,classifyTailcatRuntimeError,+ verifyTunnelReachable,addPeerViaTailcat,listTailcatForwards,retryTailcatForward,@@ -473,6 +474,37 @@ describe('tailcat lifecycle failure contracts', () => {expect(child.killed).toBe(true);});+ it('refuses to register a peer the tunnel cannot actually reach', async () => {+ const child = fakeChild();+ child.tailcatRuntimeError = { message: 'dial remote port 5555: context deadline exceeded', at: 'now' };+ const addPeerFn = vi.fn();+ const saved = [];+ // tailcat's own line is the cause; ours would only say the request failed.+ await expect(addPeerViaTailcat(addOptions(child, {+ addPeerFn,+ patchForwardEntry: async (_id, patch) => { saved.push(patch); return {}; },+ verifyTunnel: async () => 'fetch failed',+ }))).rejects.toMatchObject({+ code: 'TAILCAT_TUNNEL_UNREACHABLE',+ status: 502,+ message: expect.stringContaining('dial remote port 5555: context deadline exceeded'),+ });+ // A forward whose tunnel is dead must not leave a peer behind that will+ // never answer — and the entry stays retryable without re-pasting the tc address.+ expect(addPeerFn).not.toHaveBeenCalled();+ expect(child.killed).toBe(true);+ expect(_liveForwardCountForTests()).toBe(0);+ expect(saved.at(-1)).toMatchObject({ status: 'failed' });+ });++ it('passes the verification through when the tunnel answers', async () => {+ const child = fakeChild();+ const verifyTunnel = vi.fn(async () => null);+ const peer = await addPeerViaTailcat(addOptions(child, { verifyTunnel, protocol: 'https' }));+ expect(peer.id).toBe('peer-example');+ expect(verifyTunnel).toHaveBeenCalledWith({ localPort: 15555, protocol: 'https', auth: null });+ });+it('stops children on shutdown while preserving their restart metadata', async () => {const child = fakeChild();await addPeerViaTailcat(addOptions(child));@@ -813,3 +845,28 @@ describe('tailcat startup diagnostics and DERP map priming', () => {.resolves.toEqual({ primed: false, reason: 'no-fetch' });});});++describe('verifyTunnelReachable', () => {+ const url = 'http://127.0.0.1:15555/api/system/health';++ it('treats any HTTP response as proof the tunnel carried the request', async () => {+ // 401 from an auth-gating proxy still means bytes crossed — this probes the+ // transport, not the API.+ const fetchFn = vi.fn(async () => ({ status: 401 }));+ await expect(verifyTunnelReachable({ localPort: 15555, fetchFn })).resolves.toBeNull();+ expect(fetchFn.mock.calls[0][0]).toBe(url);+ });++ it('returns the failure detail when nothing answers, and honors https + auth', async () => {+ const fetchFn = vi.fn(async () => { throw new Error('fetch failed'); });+ const auth = { username: 'u', password: 'p' };+ await expect(verifyTunnelReachable({ localPort: 15556, protocol: 'https', auth, fetchFn }))+ .resolves.toBe('fetch failed');+ expect(fetchFn.mock.calls[0][0]).toBe('https://127.0.0.1:15556/api/system/health');+ expect(fetchFn.mock.calls[0][2]).toEqual({ auth });+ });++ it('skips verification rather than reaching the network when no fetch is available', async () => {+ await expect(verifyTunnelReachable({ localPort: 15555, fetchFn: null })).resolves.toBeNull();+ });+});