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

feat: add federated peers via tailcat (no Tailscale account)

atomanticagent8e4e52ef3351
diff --git a/client/src/lib/ports.js b/client/src/lib/ports.js
index f6d95aa4f9..1f6f685198 100644
--- a/client/src/lib/ports.js
+++ b/client/src/lib/ports.js
@@ -8,4 +8,9 @@
* top of that. Use these instead of re-hardcoding a port literal in a form
* default, a copy-paste help string, or a cross-machine URL.
*/
-export { PORTS, DEFAULT_PEER_PORT } from '../../../server/lib/ports.js';
+export {
+ PORTS,
+ DEFAULT_PEER_PORT,
+ DEFAULT_TAILCAT_LOCAL_PORT,
+ DEFAULT_TAILCAT_REMOTE_PORT,
+} from '../../../server/lib/ports.js';
diff --git a/client/src/pages/Instances.jsx b/client/src/pages/Instances.jsx
index 0ba6751a9f..6a966b343c 100644
--- a/client/src/pages/Instances.jsx
+++ b/client/src/pages/Instances.jsx
@@ -14,7 +14,7 @@ import Pill from '../components/ui/Pill';
import EmptyState from '../components/EmptyState';
import socket from '../services/socket';
import {
- getInstances, updateSelfInstance, addPeer, updatePeer,
+ getInstances, updateSelfInstance, addPeer, addTailcatPeer, updatePeer,
removePeer, connectPeer, reciprocatePeer, probePeer, syncPeer, getTailnetInfo,
getNetworkExposure,
listPeerSubscriptions,
@@ -24,7 +24,7 @@ import {
import PeerAppsList from '../components/instances/PeerAppsList';
import PeerAgentsSection from '../components/instances/PeerAgentsSection';
import { SchemaGapBadge } from '../components/instances/SchemaGapBadge';
-import { DEFAULT_PEER_PORT } from '../lib/ports.js';
+import { DEFAULT_PEER_PORT, DEFAULT_TAILCAT_LOCAL_PORT } from '../lib/ports.js';
import PeerMediaProviderPanel from '../components/instances/PeerMediaProviderPanel';
import UnattendedRenderRouting from '../components/instances/UnattendedRenderRouting';
import BrainParityPanel from '../components/instances/BrainParityPanel';
@@ -207,7 +207,9 @@ function SelfCard({ self, onUpdate, syncStatus, tailnetInfo }) {
// Exported for focused tests (the port input's placeholder must advertise the
// same default the form actually submits — see Instances.test.jsx).
export function AddPeerForm({ onAdd, addressRef }) {
+ const [mode, setMode] = useState('classic'); // 'classic' | 'tailcat'
const [address, setAddress] = useState('');
+ const [tcAddress, setTcAddress] = useState('');
const [port, setPort] = useState(String(DEFAULT_PEER_PORT));
const [name, setName] = useState('');
const [showAuth, setShowAuth] = useState(false);
@@ -217,6 +219,24 @@ export function AddPeerForm({ onAdd, addressRef }) {
const handleSubmit = async (e) => {
e.preventDefault();
+ if (mode === 'tailcat') {
+ if (!tcAddress.trim()) return;
+ setAdding(true);
+ const data = { tcAddress: tcAddress.trim() };
+ if (name.trim()) data.name = name.trim();
+ if (password) data.auth = { username: username.trim(), password };
+ const result = await addTailcatPeer(data).catch(() => null);
+ setAdding(false);
+ if (!result) return;
+ setTcAddress('');
+ setName('');
+ setUsername('');
+ setPassword('');
+ setShowAuth(false);
+ onAdd();
+ toast.success(`Peer added via tailcat (local :${result.port || DEFAULT_TAILCAT_LOCAL_PORT})`);
+ return;
+ }
if (!address.trim()) return;
setAdding(true);
const data = { address: address.trim(), port: parseInt(port, 10) || DEFAULT_PEER_PORT };
@@ -237,11 +257,58 @@ export function AddPeerForm({ onAdd, addressRef }) {
toast.success('Peer added');
};
+ const canSubmit = mode === 'tailcat' ? !!tcAddress.trim() : !!address.trim();
+
return (
<form onSubmit={handleSubmit} className="bg-port-card border border-port-border rounded-xl p-5">
<h3 className="text-sm font-medium text-gray-400 uppercase tracking-wider mb-3 flex items-center gap-2">
<Plus size={14} /> Add Peer
</h3>
+ <div className="flex flex-wrap gap-2 mb-3">
+ <button
+ type="button"
+ aria-pressed={mode === 'classic'}
+ onClick={() => setMode('classic')}
+ className={`text-xs px-2.5 py-1 rounded border transition-colors ${mode === 'classic' ? 'border-port-accent text-white bg-port-accent/20' : 'border-port-border text-gray-500 hover:text-gray-300'}`}
+ >
+ Host / port
+ </button>
+ <button
+ type="button"
+ aria-pressed={mode === 'tailcat'}
+ onClick={() => setMode('tailcat')}
+ className={`text-xs px-2.5 py-1 rounded border transition-colors ${mode === 'tailcat' ? 'border-port-accent text-white bg-port-accent/20' : 'border-port-border text-gray-500 hover:text-gray-300'}`}
+ >
+ Tailcat address
+ </button>
+ </div>
+ {mode === 'tailcat' ? (
+ <div className="flex flex-wrap gap-2">
+ <input
+ ref={addressRef}
+ aria-label="Tailcat address"
+ value={tcAddress}
+ onChange={e => setTcAddress(e.target.value)}
+ placeholder="tcEXAMPLE…"
+ required
+ 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-[200px] font-mono"
+ />
+ <input
+ aria-label="Peer name"
+ value={name}
+ onChange={e => setName(e.target.value)}
+ placeholder="Name (optional)"
+ 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]"
+ />
+ <button
+ type="submit"
+ disabled={adding || !canSubmit}
+ className="bg-port-accent hover:bg-port-accent/80 disabled:opacity-50 text-white px-4 py-2 rounded text-sm font-medium transition-colors"
+ >
+ {adding ? 'Connecting...' : 'Add via tailcat'}
+ </button>
+ </div>
+ ) : (
<div className="flex flex-wrap gap-2">
<input
ref={addressRef}
@@ -272,12 +339,20 @@ export function AddPeerForm({ onAdd, addressRef }) {
/>
<button
type="submit"
- disabled={adding || !address.trim()}
+ disabled={adding || !canSubmit}
className="bg-port-accent hover:bg-port-accent/80 disabled:opacity-50 text-white px-4 py-2 rounded text-sm font-medium transition-colors"
>
{adding ? 'Adding...' : 'Add'}
</button>
</div>
+ )}
+ {mode === 'tailcat' && (
+ <p className="text-[11px] text-gray-500 mt-2 leading-snug">
+ Forwards <span className="font-mono text-gray-400">127.0.0.1:{DEFAULT_TAILCAT_LOCAL_PORT}</span>
+ {' '}→ remote <span className="font-mono text-gray-400">:5555</span> via tailcat
+ (next free port if {DEFAULT_TAILCAT_LOCAL_PORT} is busy). No Tailscale account required.
+ </p>
+ )}
<div className="mt-2">
<button
type="button"
@@ -1195,6 +1270,11 @@ function PeerCard({ peer, onRefresh, syncStatus, tailnetInfo, parityReport }) {
<div className="mb-3">
<div className="flex items-center gap-2 flex-wrap">
<p className="text-xs text-gray-500 font-mono">{peer.address}:{peer.port}</p>
+ {peer.transport === 'tailcat' && (
+ <Pill tone="accent" size="xs" bordered={false} title="Reachable via local tailcat forward (no Tailscale account)">
+ tailcat
+ </Pill>
+ )}
<DirectionBadge directions={peer.directions} />
{isInboundOnly && (
<button
diff --git a/client/src/pages/Instances.test.jsx b/client/src/pages/Instances.test.jsx
index 9bb1f810d8..668496d74f 100644
--- a/client/src/pages/Instances.test.jsx
+++ b/client/src/pages/Instances.test.jsx
@@ -1,13 +1,14 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { render, screen, fireEvent, waitFor } from '@testing-library/react';
import { AddPeerForm } from './Instances.jsx';
-import { DEFAULT_PEER_PORT } from '../lib/ports.js';
-import { addPeer } from '../services/api';
+import { DEFAULT_PEER_PORT, DEFAULT_TAILCAT_LOCAL_PORT } from '../lib/ports.js';
+import { addPeer, addTailcatPeer } from '../services/api';
vi.mock('../services/api', () => ({
getInstances: vi.fn(),
updateSelfInstance: vi.fn(),
addPeer: vi.fn(),
+ addTailcatPeer: vi.fn(),
updatePeer: vi.fn(),
removePeer: vi.fn(),
connectPeer: vi.fn(),
@@ -50,3 +51,38 @@ describe('AddPeerForm port default', () => {
}));
});
});
+
+describe('AddPeerForm tailcat path', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ addPeer.mockResolvedValue({ id: 'peer-1' });
+ addTailcatPeer.mockResolvedValue({ id: 'peer-tc', port: DEFAULT_TAILCAT_LOCAL_PORT, transport: 'tailcat' });
+ });
+
+ it('submits a pasted tc address through addTailcatPeer (not classic addPeer)', async () => {
+ render(<AddPeerForm onAdd={() => {}} />);
+ fireEvent.click(screen.getByRole('button', { name: 'Tailcat address' }));
+ const tc = 'tcEXAMPLE' + 'B'.repeat(40);
+ fireEvent.change(screen.getByLabelText('Tailcat address'), { target: { value: tc } });
+ fireEvent.click(screen.getByRole('button', { name: 'Add via tailcat' }));
+ await waitFor(() => expect(addTailcatPeer).toHaveBeenCalledWith({ tcAddress: tc }));
+ expect(addPeer).not.toHaveBeenCalled();
+ });
+
+ it('keeps classic host/port add working', async () => {
+ render(<AddPeerForm onAdd={() => {}} />);
+ fireEvent.change(screen.getByLabelText('Peer address'), { target: { value: '100.64.1.2' } });
+ fireEvent.click(screen.getByRole('button', { name: 'Add' }));
+ await waitFor(() => expect(addPeer).toHaveBeenCalledWith({
+ address: '100.64.1.2',
+ port: DEFAULT_PEER_PORT,
+ }));
+ expect(addTailcatPeer).not.toHaveBeenCalled();
+ });
+
+ it('documents the 15555 local forward standard in the tailcat hint', () => {
+ render(<AddPeerForm onAdd={() => {}} />);
+ fireEvent.click(screen.getByRole('button', { name: 'Tailcat address' }));
+ expect(screen.getAllByText(new RegExp(String(DEFAULT_TAILCAT_LOCAL_PORT))).length).toBeGreaterThan(0);
+ });
+});
diff --git a/client/src/services/apiSystem.js b/client/src/services/apiSystem.js
index 78c5932b88..5bad2ba3ed 100644
--- a/client/src/services/apiSystem.js
+++ b/client/src/services/apiSystem.js
@@ -338,6 +338,7 @@ export const getSelfInstance = (options) => request('/instances/self', options);
export const getAssignableInstances = (options) => request('/instances/assignable', options);
export const updateSelfInstance = (data) => request('/instances/self', { method: 'PUT', body: JSON.stringify(data) });
export const addPeer = (data) => request('/instances/peers', { method: 'POST', body: JSON.stringify(data) });
+export const addTailcatPeer = (data) => request('/instances/peers/tailcat', { method: 'POST', body: JSON.stringify(data) });
export const updatePeer = (id, data) => request(`/instances/peers/${id}`, { method: 'PUT', body: JSON.stringify(data) });
export const removePeer = (id) => request(`/instances/peers/${id}`, { method: 'DELETE' });
export const connectPeer = (id) => request(`/instances/peers/${id}/connect`, { method: 'POST' });
diff --git a/docs/PORTS.md b/docs/PORTS.md
index 36fb769c43..e69740f6e2 100644
--- a/docs/PORTS.md
+++ b/docs/PORTS.md
@@ -42,6 +42,7 @@ Common port labels:
| 18022 | PortOS model host | - | Opt-in bearer-authenticated inference queue for dedicated hosts; one active generation. See [fleet host](./features/fleet-llm-host.md). |
| 18020 | vLLM (Docker) | - | Loopback vLLM Qwen3.8-27B / DFlash 2 container on an RTX 3090 host. Started explicitly from host setup or by the operator. Dedicated hosting opts into Docker restart persistence. See [features/qwen38-rtx3090.md](./features/qwen38-rtx3090.md). |
| 18021 | SGLang (Docker) | - | Loopback SGLang Qwen3.8-27B container on a Hopper/Blackwell host. Operator-started (`docker compose up -d`) — PortOS never brings it up on boot. See [features/sglang-qwen38.md](./features/sglang-qwen38.md). |
+| 15555 | tailcat forward (loopback) | - | Preferred local listener for federated peers over [tailcat](https://github.com/tailscale/tailcat) (`PORTS.TAILCAT_FORWARD` / `DEFAULT_TAILCAT_LOCAL_PORT`). Maps `127.0.0.1:15555` → remote PortOS `:5555`. If busy, PortOS picks the next free port. See [features/tailcat-peers.md](./features/tailcat-peers.md). |
## How `:5555`, `:5553`, and `:5554` Relate
diff --git a/docs/STORAGE.md b/docs/STORAGE.md
index 53bb2a0151..7904a3b1ea 100644
--- a/docs/STORAGE.md
+++ b/docs/STORAGE.md
@@ -69,6 +69,7 @@ PostgreSQL is a **required** install/runtime dependency (see [Backup & Restore](
- Spotify brain playlist shelf — `data/spotify/playlists.json`. `file-primary`, intentionally machine-local and never federated: it is a bounded cache of Spotify playlist and track metadata used as local reference material, while listening evidence remains in the federated Brain activity record. No sync cursor or tombstone. Adapter: `server/services/spotifyPlaylists.js`.
- IdeaLoom lists — `data/brain/idealoom-lists/{uuid}/index.json` with a schema-stamped collection index holding the disabled-by-default local integration settings. Lists retain their ordered idea strings, prompt/title/category/status/help, timestamps, and importer-owned local sync metadata. Explicit exchange reads/writes only the configured vault's `Idea Loom/` folder through the specialized `server/services/idealoomObsidian.js` parser/renderer; new notes use a date/title filename and imported note paths remain stable. **Intentionally machine-local — never federated, reconciled, or memory-bridged**: a vault id, note path, and content hash are meaningful only on the install that configured them. Native Brain `ideas` remain a separate federated collection. Exchange is base-hash reconciled: a note and a list that both changed since the stored hash report `conflicted` and neither is written, and a note deleted in the vault reports `missing` rather than being recreated (an iCloud note that is merely un-downloaded is `unavailable`, a separate outcome). Opt-in automatic export (`autoSync`, off by default, debounced by `server/services/idealoomAutoSync.js`) can only update an existing note — it never deletes, recreates, or resolves a conflict. Backed up in full with the rest of `data/brain/`; the vault notes themselves are the user's Obsidian data and are outside PortOS's snapshot. Adapters: `server/services/idealoomLists.js` (records), `server/services/idealoomObsidian.js` (exchange).
- Local-model assessments — `data/local-llm/assessments.json` (#4539). Measured evidence for one installed local model per (backend, model): the fit verdict (`fits`/`does-not-fit`/`incompatible`/`unknown`), per-context throughput/TTFT samples, resident footprint, and the coarse hardware environment the measurement was taken in. `file-primary` — a flat, capped, single-JSON projection with no cross-record queries and no relationships; the newest measurement replaces the old one per model rather than accumulating history. **Intentionally machine-local — never federated**: an assessment is a claim about THIS box, so a peer inheriting a 128 GB machine's its verdict for its 8 GB laptop would be actively wrong. No sync cursor, no tombstone, no `PORTOS_SCHEMA_VERSIONS` entry. Backed up (a run costs the user minutes of local compute), and the environment record deliberately carries no hostname/username/path. Adapter: `server/services/localModelAssessmentStore.js` (durable store + environment capture; no path to a provider, so read-only consumers like the catalog fit badge can import it); the run lives in `server/services/localModelAssessments.js` and the scoring in `server/lib/localModelAssessment.js`. Each record's environment is re-compared against the live machine on read, so a reading taken before a RAM upgrade or backend update is flagged stale rather than silently trusted.
+- Tailcat peer forwards — `data/tailcat-forwards.json`. `file-primary`, **intentionally machine-local — never federated**: each row stores the bearer `tc…` address needed to restart `tailcat forward` after a PortOS reboot, plus the local/remote port mapping. The capability must not cross the wire or appear in logs in full (see [features/tailcat-peers.md](./features/tailcat-peers.md)). No sync cursor or tombstone. Adapter: `server/services/tailcatPeer.js`.
- LoRA training datasets — `data/lora-datasets/{id}/index.json` + `images/*.png` (collectionStore). The record is inseparable from the image bytes it organizes, has no cross-record queries beyond a small characterId scan, and is **machine-local** like `data/loras/` itself (training artifacts tied to this machine's GPU output — never federates, no sync cursor/tombstone). Backed up in full: uploads and hand-edited captions are not re-creatable. Training RUN records are `db-primary` (`lora_training_runs`); run artifacts (checkpoints/samples) live under `data/training-runs/{runId}/` with checkpoints/cache excluded from backup.
---
diff --git a/docs/features/tailcat-peers.md b/docs/features/tailcat-peers.md
new file mode 100644
index 0000000000..102ae4d24a
--- /dev/null
+++ b/docs/features/tailcat-peers.md
@@ -0,0 +1,96 @@
+# Federated peers via tailcat (no Tailscale account)
+
+PortOS can federate with another install over
+[tailcat](https://github.com/tailscale/tailcat) — Tailscale's userspace
+WireGuard + DERP data plane **without** a Tailscale account, daemon, or
+tailnet. Use this when an untrusted sandbox (or any machine that cannot join
+your tailnet) needs to reach a home PortOS on `:5555`.
+
+## Port standard
+
+| Side | Port | Role |
+|------|------|------|
+| Home / remote PortOS | **5555** | Existing PortOS API (`PORTS.API`) |
+| Operator / client PortOS | **15555** (preferred) | Local `tailcat forward` listener (`PORTS.TAILCAT_FORWARD` / `DEFAULT_TAILCAT_LOCAL_PORT`) |
+
+Mapping: `tailcat forward <tcADDR> 15555:5555` binds `127.0.0.1:15555` to the
+remote's `:5555`. If `15555` is already taken, PortOS walks upward to the next
+free loopback port and registers the peer at that local port instead.
+
+No `tailcat serve all`, no exit-node mode, and no Tailscale daemon are used.
+
+## Operator flow (Instances UI)
+
+1. Open **Instances → Add Peer → Tailcat address**.
+2. Paste the peer's `tc…` address (received out of band).
+3. PortOS ensures `tailcat` is installed (PATH, else `go install
+ github.com/tailscale/tailcat/cmd/tailcat@latest`), starts the forward, and
+ calls the normal peer registration against `127.0.0.1:<localPort>` over HTTP.
+4. Classic **Host / port** add remains unchanged (still rejects loopback).
+
+Forwards are persisted in machine-local `data/tailcat-forwards.json` so PortOS
+can restart them on boot. The full `tc…` string is a bearer capability — it is
+**never** logged in full, never placed on the peer record returned to the UI or
+to other peers, and must never appear in commits, PR bodies, docs, or tests.
+Use placeholders such as `<tcADDR>` or `tcEXAMPLE…` only.
+
+## Privacy
+
+- Do not paste real `tc…` addresses into tickets, chat logs synced to peers, or
+ screenshots that leave the machine.
+- Server logs print a redacted form (`tcAB…wxyz`) only.
+- Removing a peer stops its managed forward.
+
+## Grok Bot / agent sandbox setup (copy/paste)
+
+Use this when an **untrusted agent sandbox** should run PortOS and hand the
+operator a tailcat address so the home install can federate in.
+
+### On the sandbox (serve)
+
+```bash
+# Install tailcat (pick one)
+go install github.com/tailscale/tailcat/cmd/tailcat@latest
+# or: brew install tailcat
+# or: download a release from https://github.com/tailscale/tailcat/releases
+
+# PortOS already listening on :5555 in the sandbox, then:
+tailcat serve --key=new 5555
+# stderr prints: 🐈 Server listening with new address: <tcADDR>
+```
+
+Share `<tcADDR>` with the operator **out of band** (private chat, 1Password,
+operator-only channel). Do not commit it, put it in the repo, or log it to a
+synced surface.
+
+Optional named key (stable address across restarts — still a secret):
+
+```bash
+tailcat genkey --key=portos-sandbox
+tailcat serve --key=portos-sandbox 5555
+```
+
+### On the operator PortOS (forward + peer)
+
+In **Instances → Add Peer → Tailcat address**, paste `<tcADDR>`.
+
+Or manually:
+
+```bash
+tailcat forward <tcADDR> 15555:5555
+# then Add Peer → Host/port is not used for loopback; prefer the UI Tailcat path
+# which registers 127.0.0.1:15555 for you.
+```
+
+### Checklist for agents
+
+- [ ] PortOS up on sandbox `:5555`
+- [ ] `tailcat serve --key=… 5555` (not `serve all`, not exit-node)
+- [ ] Hand operator `<tcADDR>` out of band only
+- [ ] Operator uses UI Tailcat add (local **15555 → 5555**)
+- [ ] Never write real `tc…` values into git, PR text, or federated logs
+
+## Related
+
+- [PORTS.md](../PORTS.md) — `TAILCAT_FORWARD` / `15555`
+- [tailscale/tailcat](https://github.com/tailscale/tailcat) — CLI reference
diff --git a/ecosystem.config.cjs b/ecosystem.config.cjs
index c41c2bbc3e..dabaa35264 100644
--- a/ecosystem.config.cjs
+++ b/ecosystem.config.cjs
@@ -128,6 +128,9 @@ const PORTS = {
VLLM_QWEN: 18020, // Loopback vLLM Qwen3.8-27B (DFlash 2) container — started by the operator, never by PortOS
SGLANG_QWEN: 18021, // Loopback SGLang Qwen3.8-27B container (Hopper/Blackwell) — started by the operator, never by PortOS
+ // Loopback listener for `tailcat forward <tc> LOCAL:5555` when adding a federated
+ // peer without a Tailscale account. Prefer 15555; if busy, PortOS picks the next free port.
+ TAILCAT_FORWARD: 15555,
POSTGRES: pgMode === 'native' ? 5432 : 5561 // Active PostgreSQL port (unused in file mode)
};
diff --git a/server/lib/ports.js b/server/lib/ports.js
index 4b287cf2b2..3783affd57 100644
--- a/server/lib/ports.js
+++ b/server/lib/ports.js
@@ -31,6 +31,7 @@ export const PORTS = Object.freeze({
VLLM_QWEN: 18020, // Loopback vLLM Qwen3.8-27B (DFlash 2) container — opt-in dedicated host setup
SGLANG_QWEN: 18021, // Loopback SGLang Qwen3.8-27B container (Hopper/Blackwell) — operator-started, never by PortOS
+ TAILCAT_FORWARD: 15555, // Loopback forward for tailcat peers (maps to remote :5555)
POSTGRES_NATIVE: 5432 // System PostgreSQL (PGMODE=native)
});
@@ -42,3 +43,6 @@ export const resolvePostgresPort = (pgMode) =>
(pgMode === 'native' ? PORTS.POSTGRES_NATIVE : PORTS.POSTGRES_DOCKER);
export const DEFAULT_PEER_PORT = PORTS.API;
+// Preferred local bind for `tailcat forward <tc> LOCAL:5555` (remote PortOS API).
+export const DEFAULT_TAILCAT_LOCAL_PORT = PORTS.TAILCAT_FORWARD;
+export const DEFAULT_TAILCAT_REMOTE_PORT = PORTS.API;
diff --git a/server/lib/ports.test.js b/server/lib/ports.test.js
index 4ae9813972..7ba7d67bc0 100644
--- a/server/lib/ports.test.js
+++ b/server/lib/ports.test.js
@@ -3,7 +3,13 @@ import { createRequire } from 'module';
import { readFileSync } from 'fs';
import { fileURLToPath } from 'url';
import path from 'path';
-import { DEFAULT_PEER_PORT, PORTS, resolvePostgresPort } from './ports.js';
+import {
+ DEFAULT_PEER_PORT,
+ DEFAULT_TAILCAT_LOCAL_PORT,
+ DEFAULT_TAILCAT_REMOTE_PORT,
+ PORTS,
+ resolvePostgresPort,
+} from './ports.js';
// `ecosystem.config.cjs` is the source of truth for port numbers; `ports.js` is a
// hand-maintained ESM mirror of it (the ESM server can't require() the CJS
@@ -60,6 +66,12 @@ describe('PORTS mirror of ecosystem.config.cjs', () => {
it('defaults a new peer to the API port', () => {
expect(DEFAULT_PEER_PORT).toBe(ECOSYSTEM_PORTS.API);
});
+
+ it('defaults a new tailcat local forward to 15555 → remote API', () => {
+ expect(DEFAULT_TAILCAT_LOCAL_PORT).toBe(15555);
+ expect(DEFAULT_TAILCAT_LOCAL_PORT).toBe(ECOSYSTEM_PORTS.TAILCAT_FORWARD);
+ expect(DEFAULT_TAILCAT_REMOTE_PORT).toBe(ECOSYSTEM_PORTS.API);
+ });
});
describe('resolvePostgresPort', () => {
diff --git a/server/routes/instances.js b/server/routes/instances.js
index 169b3076cb..be7083bf40 100644
--- a/server/routes/instances.js
+++ b/server/routes/instances.js
@@ -12,6 +12,7 @@ import { getFullSyncCoverageForPeer } from '../services/sharing/peerSync.js';
import { provisionTailscaleCert } from '../services/certProvisioner.js';
import { asyncHandler, ServerError } from '../lib/errorHandler.js';
import { DEFAULT_PEER_PORT } from '../lib/ports.js';
+import * as tailcatPeer from '../services/tailcatPeer.js';
import { getTailscaleStatus } from '../lib/tailscale.js';
import { federatedMediaPeerSettingsSchema, validateRequest } from '../lib/validation.js';
@@ -247,6 +248,24 @@ router.post('/peers/announce', asyncHandler(async (req, res) => {
});
}));
+const addTailcatPeerSchema = z.object({
+ tcAddress: z.string().min(24).max(2048),
+ name: z.string().optional(),
+ auth: peerAuthSchema
+});
+
+// POST /api/instances/peers/tailcat — add a peer via tailcat forward (no Tailscale account).
+// Starts `tailcat forward <tc> LOCAL:5555` (LOCAL defaults to 15555) and registers
+// a loopback peer. The classic POST /peers path still rejects 127/8.
+router.post('/peers/tailcat', asyncHandler(async (req, res) => {
+ const data = addTailcatPeerSchema.parse(req.body);
+ if (!tailcatPeer.isValidTcAddress(data.tcAddress)) {
+ throw new ServerError('Invalid tailcat address — paste a tc… address from the peer', { status: 400 });
+ }
+ const peer = await tailcatPeer.addPeerViaTailcat(data);
+ res.status(201).json(instances.sanitizePeerForClient(peer));
+}));
+
// POST /api/instances/peers — add a peer
router.post('/peers', asyncHandler(async (req, res) => {
const data = addPeerSchema.parse(req.body);
diff --git a/server/services/bootstrap.js b/server/services/bootstrap.js
index f06db07a37..cc295dac6d 100644
--- a/server/services/bootstrap.js
+++ b/server/services/bootstrap.js
@@ -817,7 +817,13 @@ export const runBootSequence = ({ io, httpServer, localHttpServer, httpsEnabled,
// failures also surface in the UI.
setupProcessErrorHandlers: () => setupProcessErrorHandlers(io),
backfillOriginInstanceId,
- startPolling,
+ startPolling: () => {
+ startPolling();
+ // Best-effort: re-attach tailcat forwards persisted across restarts.
+ void import('./tailcatPeer.js')
+ .then(({ restoreForwards }) => restoreForwards())
+ .catch((err) => console.log(`⚠️ tailcat forward restore failed: ${err.message}`));
+ },
initSyncOrchestrator
}))
});
diff --git a/server/services/instances.js b/server/services/instances.js
index 03967db7e8..4245d0af36 100644
--- a/server/services/instances.js
+++ b/server/services/instances.js
@@ -122,11 +122,15 @@ function sameAuth(a, b) {
// are local-only too, so peers cannot discover or influence our assignments.
export function redactPeerForWire(peer) {
if (!peer || typeof peer !== 'object') return peer;
- if (!('auth' in peer) && !('mediaProvider' in peer) && !('mediaProviderStatus' in peer)) return peer;
+ if (!('auth' in peer) && !('mediaProvider' in peer) && !('mediaProviderStatus' in peer)
+ && !('tcAddress' in peer)) {
+ return peer;
+ }
const {
auth: _auth,
mediaProvider: _mediaProvider,
mediaProviderStatus: _mediaProviderStatus,
+ tcAddress: _tcAddress,
...rest
} = peer;
return rest;
@@ -468,7 +472,7 @@ const PER_RECORD_CATEGORY_KINDS = Object.freeze([
['creativeCommissions', 'creativeCommission'],
]);
-export async function addPeer({ address, port = DEFAULT_PEER_PORT, name, host, auth }) {
+export async function addPeer({ address, port = DEFAULT_PEER_PORT, name, host, auth, transport }) {
const peer = await withData(async (data) => {
const normalizedHost = validHost(host);
const normalizedAuth = sanitizePeerAuth(auth);
@@ -487,6 +491,9 @@ export async function addPeer({ address, port = DEFAULT_PEER_PORT, name, host, a
hostManual: !!normalizedHost,
port,
name: validName(name, normalizedHost || address),
+ // Optional transport marker (e.g. 'tailcat'). Never carries the tc address —
+ // that capability lives only in data/tailcat-forwards.json.
+ ...(transport === 'tailcat' ? { transport: 'tailcat' } : {}),
instanceId: null,
addedAt: new Date().toISOString(),
lastSeen: null,
@@ -519,6 +526,11 @@ export async function addPeer({ address, port = DEFAULT_PEER_PORT, name, host, a
export async function removePeer(id) {
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 removed = await withData(async (data) => {
const idx = data.peers.findIndex(p => p.id === id);
if (idx === -1) return null;
diff --git a/server/services/tailcatPeer.js b/server/services/tailcatPeer.js
new file mode 100644
index 0000000000..79ea63fd41
--- /dev/null
+++ b/server/services/tailcatPeer.js
@@ -0,0 +1,437 @@
+/**
+ * Tailcat federated peers — connect to a remote PortOS over
+ * [tailcat](https://github.com/tailscale/tailcat) without a Tailscale account.
+ *
+ * Flow: ensure the `tailcat` CLI is installed → start
+ * `tailcat forward <tcADDR> LOCAL:5555` (preferred LOCAL=15555) → register a
+ * normal peer at `127.0.0.1:LOCAL` over HTTP.
+ *
+ * The tc address is a bearer capability. Persist it only in the machine-local
+ * forwards file for restart; never log the full value, never put it on the peer
+ * record that clients or peers can scrape, and never ship it in docs/tests.
+ */
+
+import { createServer } from 'node:net';
+import { homedir } from 'node:os';
+import { join } from 'node:path';
+import { spawn } from '../lib/childProcess.js';
+import { commandExists } from '../lib/commandExists.js';
+import { dataPath, readJSONFile, ensureDir, PATHS, atomicWrite } from '../lib/fileUtils.js';
+import { createMutex } from '../lib/asyncMutex.js';
+import { findCommandOnPath, safeChildProcessEnv, safeChildProcessOptions } from '../lib/processEnv.js';
+import {
+ DEFAULT_TAILCAT_LOCAL_PORT,
+ DEFAULT_TAILCAT_REMOTE_PORT,
+} from '../lib/ports.js';
+import { ServerError } from '../lib/errorHandler.js';
+import { addPeer, removePeer as removeInstancePeer } from './instances.js';
+
+const FORWARDS_FILE = dataPath('tailcat-forwards.json');
+const GO_INSTALL_PKG = 'github.com/tailscale/tailcat/cmd/tailcat@latest';
+const INSTALL_TIMEOUT_MS = 180_000;
+const FORWARD_READY_MS = 8_000;
+const PORT_SCAN_LIMIT = 32;
+const DEFAULT_DATA = { version: 1, forwards: [] };
+
+const withLock = createMutex();
+
+/** @type {Map<string, { child: import('node:child_process').ChildProcess, localPort: number, remotePort: number }>} */
+const liveForwards = new Map();
+
+/** Redact a tc address for logs / UI — never echo the full capability. */
+export function redactTcAddress(tc) {
+ const raw = String(tc || '').trim();
+ if (!raw) return '(empty)';
+ if (raw.length <= 8) return 'tc…';
+ return `${raw.slice(0, 4)}…${raw.slice(-4)}`;
+}
+
+/**
+ * Accept a pasted tailcat address. Real addresses are `tc` + base64url CBOR;
+ * keep the gate loose enough for DNS TXT forms that still begin with `tc`, but
+ * reject obvious garbage so we never spawn with an operator typo as argv.
+ */
+export function isValidTcAddress(tc) {
+ const raw = String(tc || '').trim();
+ if (!raw.startsWith('tc')) return false;
+ if (raw.length < 24 || raw.length > 2048) return false;
+ // Letters, digits, _ - = + / (base64 / base64url) only after the tc prefix.
+ return /^tc[A-Za-z0-9_+\/=-]+$/.test(raw);
+}
+
+async function loadForwards() {
+ return await readJSONFile(FORWARDS_FILE, DEFAULT_DATA, { strict: false });
+}
+
+async function saveForwards(data) {
+ await ensureDir(PATHS.data);
+ await atomicWrite(FORWARDS_FILE, data);
+}
+
+export function listCandidateTailcatBins() {
+ const home = homedir();
+ const candidates = [
+ findCommandOnPath('tailcat'),
+ join(home, 'go', 'bin', 'tailcat'),
+ join(home, 'go', 'bin', 'tailcat.exe'),
+ '/usr/local/bin/tailcat',
+ '/opt/homebrew/bin/tailcat',
+ ].filter(Boolean);
+ return [...new Set(candidates)];
+}
+
+/**
+ * Resolve an installed `tailcat` binary, or null when none is runnable.
+ * Injected deps keep unit tests off the real PATH / child_process.
+ */
+export async function detectTailcat({
+ candidates = listCandidateTailcatBins(),
+ probe = (bin) => commandExists(bin, ['version'], { timeoutMs: 5_000 }),
+} = {}) {
+ for (const bin of candidates) {
+ if (await probe(bin)) return bin;
+ }
+ return null;
+}
+
+/**
+ * Install via `go install` when Go is available. Clear, actionable errors when
+ * neither binary nor toolchain is present — PortOS never downloads arbitrary
+ * URLs without the operator knowing.
+ */
+export async function ensureTailcatInstalled({
+ detect = detectTailcat,
+ goBin = findCommandOnPath('go') || 'go',
+ runGoInstall = defaultGoInstall,
+ probeGo = (bin) => commandExists(bin, ['version'], { timeoutMs: 10_000 }),
+} = {}) {
+ const existing = await detect();
+ if (existing) return { bin: existing, installed: false };
+
+ const goOk = await probeGo(goBin);
+ if (!goOk) {
+ throw new ServerError(
+ 'tailcat is not installed and Go was not found on PATH. '
+ + 'Install from https://github.com/tailscale/tailcat/releases '
+ + 'or `brew install tailcat`, then retry.',
+ { status: 503, code: 'TAILCAT_MISSING' }
+ );
+ }
+
+ try {
+ await runGoInstall(goBin);
+ } catch (err) {
+ throw new ServerError(
+ `Failed to install tailcat via go install: ${err.message}. `
+ + 'Install a release binary from https://github.com/tailscale/tailcat/releases and retry.',
+ { status: 503, code: 'TAILCAT_INSTALL_FAILED' }
+ );
+ }
+
+ const bin = await detect();
+ if (!bin) {
+ throw new ServerError(
+ 'go install finished but `tailcat` is still not on PATH '
+ + '(check ~/go/bin). Add that directory to PATH and retry.',
+ { status: 503, code: 'TAILCAT_INSTALL_PATH' }
+ );
+ }
+ return { bin, installed: true };
+}
+
+function defaultGoInstall(goBin) {
+ return new Promise((resolve, reject) => {
+ const child = spawn(
+ goBin,
+ ['install', GO_INSTALL_PKG],
+ safeChildProcessOptions({
+ env: safeChildProcessEnv(),
+ stdio: ['ignore', 'pipe', 'pipe'],
+ })
+ );
+ let stderr = '';
+ child.stderr?.on('data', (chunk) => {
+ stderr += String(chunk);
+ if (stderr.length > 8_000) stderr = stderr.slice(-8_000);
+ });
+ const timer = setTimeout(() => {
+ child.kill('SIGTERM');
+ reject(new Error(`timed out after ${INSTALL_TIMEOUT_MS}ms`));
+ }, INSTALL_TIMEOUT_MS);
+ child.on('error', (err) => {
+ clearTimeout(timer);
+ reject(err);
+ });
+ child.on('close', (code) => {
+ clearTimeout(timer);
+ if (code === 0) resolve();
+ else reject(new Error(stderr.trim() || `exit ${code}`));
+ });
+ });
+}
+
+/** True when nothing is listening on 127.0.0.1:port (or bind fails for other reasons → busy). */
+export function isLocalPortFree(port, { createServerFn = createServer } = {}) {
+ return new Promise((resolve) => {
+ const server = createServerFn();
+ server.unref?.();
+ server.once('error', () => resolve(false));
+ server.listen(port, '127.0.0.1', () => {
+ server.close(() => resolve(true));
+ });
+ });
+}
+
+/**
+ * Prefer DEFAULT_TAILCAT_LOCAL_PORT (15555). When busy, walk upward so a second
+ * peer can still be forwarded without colliding.
+ */
+export async function allocateLocalPort({
+ preferred = DEFAULT_TAILCAT_LOCAL_PORT,
+ isFree = isLocalPortFree,
+ limit = PORT_SCAN_LIMIT,
+} = {}) {
+ const start = Number(preferred) || DEFAULT_TAILCAT_LOCAL_PORT;
+ for (let i = 0; i < limit; i += 1) {
+ const port = start + i;
+ if (port > 65535) break;
+ // Skip ports already claimed by a live forward we manage.
+ const taken = [...liveForwards.values()].some((f) => f.localPort === port);
+ if (taken) continue;
+ if (await isFree(port)) return port;
+ }
+ throw new ServerError(
+ `No free local port near ${start} for tailcat forward (tried ${limit} ports)`,
+ { status: 503, code: 'TAILCAT_PORT_BUSY' }
+ );
+}
+
+/**
+ * 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).
+ */
+export async function startForwardProcess({
+ bin,
+ tcAddress,
+ localPort,
+ remotePort = DEFAULT_TAILCAT_REMOTE_PORT,
+ spawnFn = spawn,
+ readyMs = FORWARD_READY_MS,
+} = {}) {
+ if (!isValidTcAddress(tcAddress)) {
+ throw new ServerError('Invalid tailcat address — paste a tc… address from the peer', {
+ status: 400,
+ code: 'TAILCAT_BAD_ADDRESS',
+ });
+ }
+ const mapping = `${localPort}:${remotePort}`;
+ const args = ['forward', tcAddress.trim(), mapping];
+ const child = spawnFn(
+ bin,
+ args,
+ safeChildProcessOptions({
+ env: safeChildProcessEnv(),
+ stdio: ['ignore', 'pipe', 'pipe'],
+ })
+ );
+
+ 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);
+ });
+ child.stdout?.on('data', () => {});
+
+ await new Promise((resolve, reject) => {
+ let settled = false;
+ const fail = (err) => {
+ if (settled) return;
+ settled = true;
+ clearTimeout(timer);
+ reject(err);
+ };
+ const ok = () => {
+ if (settled) return;
+ settled = true;
+ clearTimeout(timer);
+ resolve();
+ };
+ 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'}`
+ ));
+ });
+ });
+
+ console.log(
+ `🐈 tailcat forward started ${redactTcAddress(tcAddress)} → 127.0.0.1:${localPort} (remote :${remotePort})`
+ );
+ return child;
+}
+
+async function persistForward(entry) {
+ await withLock(async () => {
+ const data = await loadForwards();
+ const forwards = Array.isArray(data.forwards) ? data.forwards.filter((f) => f.peerId !== entry.peerId) : [];
+ forwards.push(entry);
+ await saveForwards({ version: 1, forwards });
+ });
+}
+
+async function forgetForward(peerId) {
+ await withLock(async () => {
+ const data = await loadForwards();
+ const forwards = (Array.isArray(data.forwards) ? data.forwards : []).filter((f) => f.peerId !== peerId);
+ await saveForwards({ version: 1, forwards });
+ });
+}
+
+export async function stopForwardForPeer(peerId) {
+ const live = liveForwards.get(peerId);
+ if (live?.child && !live.child.killed) {
+ try {
+ live.child.kill('SIGTERM');
+ } catch {
+ // best-effort
+ }
+ }
+ liveForwards.delete(peerId);
+ await forgetForward(peerId);
+}
+
+/**
+ * Operator-facing entry: install if needed, allocate a local port, start the
+ * forward, then register a classic loopback peer. Loopback is intentional here
+ * — the public POST /peers schema still rejects 127/8 for classic adds.
+ */
+export async function addPeerViaTailcat({
+ tcAddress,
+ name,
+ auth,
+ ensureInstalled = ensureTailcatInstalled,
+ allocatePort = allocateLocalPort,
+ startForward = startForwardProcess,
+ addPeerFn = addPeer,
+ persistForwardEntry = persistForward,
+} = {}) {
+ const trimmed = String(tcAddress || '').trim();
+ if (!isValidTcAddress(trimmed)) {
+ throw new ServerError('Invalid tailcat address — paste a tc… address from the peer', {
+ status: 400,
+ code: 'TAILCAT_BAD_ADDRESS',
+ });
+ }
+
+ const { bin } = await ensureInstalled();
+ const localPort = await allocatePort();
+ const remotePort = DEFAULT_TAILCAT_REMOTE_PORT;
+
+ let child;
+ try {
+ child = await startForward({ bin, tcAddress: trimmed, localPort, remotePort });
+ } catch (err) {
+ throw new ServerError(
+ `Could not start tailcat forward: ${err.message}`,
+ { status: 502, code: 'TAILCAT_FORWARD_FAILED' }
+ );
+ }
+
+ let peer;
+ try {
+ peer = await addPeerFn({
+ address: '127.0.0.1',
+ port: localPort,
+ name: name || `tailcat:${redactTcAddress(trimmed)}`,
+ auth,
+ transport: 'tailcat',
+ });
+ } catch (err) {
+ try { child.kill('SIGTERM'); } catch { /* ignore */ }
+ throw err;
+ }
+
+ liveForwards.set(peer.id, { child, localPort, remotePort });
+ child.on('exit', () => {
+ if (liveForwards.get(peer.id)?.child === child) liveForwards.delete(peer.id);
+ console.log(`🐈 tailcat forward stopped for peer ${peer.id} (${redactTcAddress(trimmed)})`);
+ });
+
+ await persistForwardEntry({
+ peerId: peer.id,
+ tcAddress: trimmed,
+ localPort,
+ remotePort,
+ createdAt: new Date().toISOString(),
+ });
+
+ return peer;
+}
+
+/** Restart persisted forwards after PortOS boot (best-effort). */
+export async function restoreForwards({
+ ensureInstalled = ensureTailcatInstalled,
+ startForward = startForwardProcess,
+} = {}) {
+ const data = await loadForwards();
+ const forwards = Array.isArray(data.forwards) ? data.forwards : [];
+ if (forwards.length === 0) return { restored: 0 };
+
+ let bin;
+ try {
+ ({ bin } = await ensureInstalled());
+ } catch (err) {
+ console.log(`⚠️ tailcat restore skipped — ${err.message}`);
+ return { restored: 0, error: err.message };
+ }
+
+ let restored = 0;
+ for (const entry of forwards) {
+ if (!entry?.peerId || !isValidTcAddress(entry.tcAddress)) continue;
+ if (liveForwards.has(entry.peerId)) continue;
+ try {
+ const child = await startForward({
+ bin,
+ tcAddress: entry.tcAddress,
+ localPort: entry.localPort || DEFAULT_TAILCAT_LOCAL_PORT,
+ remotePort: entry.remotePort || DEFAULT_TAILCAT_REMOTE_PORT,
+ });
+ liveForwards.set(entry.peerId, {
+ child,
+ localPort: entry.localPort,
+ remotePort: entry.remotePort || DEFAULT_TAILCAT_REMOTE_PORT,
+ });
+ child.on('exit', () => {
+ if (liveForwards.get(entry.peerId)?.child === child) liveForwards.delete(entry.peerId);
+ });
+ restored += 1;
+ } catch (err) {
+ console.log(`⚠️ tailcat restore failed for peer ${entry.peerId}: ${err.message}`);
+ }
+ }
+ if (restored > 0) console.log(`🐈 Restored ${restored} tailcat forward(s)`);
+ return { restored };
+}
+
+/**
+ * Remove a peer and tear down its forward when present. Prefer this over a
+ * bare removePeer for any peer that may have been added via tailcat.
+ */
+export async function removePeerAndForward(peerId, { removePeerFn = removeInstancePeer } = {}) {
+ await stopForwardForPeer(peerId);
+ return removePeerFn(peerId);
+}
+
+// Test-only helpers
+export function _resetLiveForwardsForTests() {
+ liveForwards.clear();
+}
+
+export function _liveForwardCountForTests() {
+ return liveForwards.size;
+}
+
diff --git a/server/services/tailcatPeer.test.js b/server/services/tailcatPeer.test.js
new file mode 100644
index 0000000000..0da2d3b987
--- /dev/null
+++ b/server/services/tailcatPeer.test.js
@@ -0,0 +1,160 @@
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
+import { EventEmitter } from 'node:events';
+import {
+ redactTcAddress,
+ isValidTcAddress,
+ ensureTailcatInstalled,
+ allocateLocalPort,
+ startForwardProcess,
+ addPeerViaTailcat,
+ _resetLiveForwardsForTests,
+} from './tailcatPeer.js';
+import { DEFAULT_TAILCAT_LOCAL_PORT, DEFAULT_TAILCAT_REMOTE_PORT } from '../lib/ports.js';
+
+const EXAMPLE_TC = 'tcEXAMPLE' + 'A'.repeat(40);
+
+function fakeChild({ exitImmediately = false, exitCode = 1 } = {}) {
+ const child = new EventEmitter();
+ child.killed = false;
+ child.stderr = new EventEmitter();
+ child.stdout = new EventEmitter();
+ child.kill = vi.fn(() => {
+ child.killed = true;
+ child.emit('exit', 0, null);
+ });
+ if (exitImmediately) {
+ queueMicrotask(() => Promise.resolve()) //.then(() => child.emit('exit', exitCode, null));
+ }
+ return child;
+}
+
+describe('tailcatPeer helpers', () => {
+ beforeEach(() => {
+ _resetLiveForwardsForTests();
+ });
+
+ afterEach(() => {
+ _resetLiveForwardsForTests();
+ });
+
+ it('redacts tc addresses so logs never hold the full capability', () => {
+ const redacted = redactTcAddress(EXAMPLE_TC);
+ expect(redacted).not.toBe(EXAMPLE_TC);
+ expect(redacted.startsWith('tcEX')).toBe(true);
+ expect(redacted.includes('…')).toBe(true);
+ expect(redactTcAddress('')).toBe('(empty)');
+ });
+
+ it('validates tc address shape without accepting short garbage', () => {
+ expect(isValidTcAddress(EXAMPLE_TC)).toBe(true);
+ expect(isValidTcAddress('tcEXAMPLE…')).toBe(false); // ellipsis / placeholder
+ expect(isValidTcAddress('not-a-tc')).toBe(false);
+ expect(isValidTcAddress('tcshort')).toBe(false);
+ expect(isValidTcAddress('')).toBe(false);
+ });
+
+ it('ensureTailcatInstalled returns existing binary without installing', async () => {
+ const runGoInstall = vi.fn();
+ const result = await ensureTailcatInstalled({
+ detect: async () => '/usr/bin/tailcat',
+ runGoInstall,
+ probeGo: async () => true,
+ });
+ expect(result).toEqual({ bin: '/usr/bin/tailcat', installed: false });
+ expect(runGoInstall).not.toHaveBeenCalled();
+ });
+
+ it('ensureTailcatInstalled runs go install when missing, then re-detects', async () => {
+ let calls = 0;
+ const runGoInstall = vi.fn(async () => {});
+ const result = await ensureTailcatInstalled({
+ detect: async () => {
+ calls += 1;
+ return calls === 1 ? null : '/home/box/go/bin/tailcat';
+ },
+ goBin: 'go',
+ runGoInstall,
+ probeGo: async () => true,
+ });
+ expect(runGoInstall).toHaveBeenCalledOnce();
+ expect(result).toEqual({ bin: '/home/box/go/bin/tailcat', installed: true });
+ });
+
+ it('ensureTailcatInstalled fails clearly when Go is absent', async () => {
+ await expect(ensureTailcatInstalled({
+ detect: async () => null,
+ probeGo: async () => false,
+ runGoInstall: vi.fn(),
+ })).rejects.toMatchObject({ code: 'TAILCAT_MISSING', status: 503 });
+ });
+
+ it('allocateLocalPort prefers 15555 then walks upward when busy', async () => {
+ expect(DEFAULT_TAILCAT_LOCAL_PORT).toBe(15555);
+ expect(DEFAULT_TAILCAT_REMOTE_PORT).toBe(5555);
+ const isFree = vi.fn(async (port) => port === 15557);
+ const port = await allocateLocalPort({ preferred: 15555, isFree, limit: 5 });
+ expect(port).toBe(15557);
+ expect(isFree).toHaveBeenCalledWith(15555);
+ expect(isFree).toHaveBeenCalledWith(15556);
+ expect(isFree).toHaveBeenCalledWith(15557);
+ });
+
+ it('startForwardProcess spawns tailcat forward with local:remote mapping', async () => {
+ const child = fakeChild();
+ const spawnFn = vi.fn(() => child);
+ const started = await startForwardProcess({
+ bin: '/usr/bin/tailcat',
+ tcAddress: EXAMPLE_TC,
+ localPort: 15555,
+ remotePort: 5555,
+ spawnFn,
+ readyMs: 10,
+ });
+ expect(started).toBe(child);
+ expect(spawnFn).toHaveBeenCalledWith(
+ '/usr/bin/tailcat',
+ ['forward', EXAMPLE_TC, '15555:5555'],
+ expect.any(Object)
+ );
+ });
+
+ it('startForwardProcess rejects when the child exits immediately', async () => {
+ const child = fakeChild();
+ const spawnFn = vi.fn(() => {
+ // Schedule exit after startForwardProcess attaches its listeners.
+ process.nextTick(() => child.emit('exit', 2, null));
+ return child;
+ });
+ await expect(startForwardProcess({
+ bin: '/usr/bin/tailcat',
+ tcAddress: EXAMPLE_TC,
+ localPort: 15555,
+ spawnFn,
+ readyMs: 5_000,
+ })).rejects.toThrow(/exited early/);
+ });
+
+ it('addPeerViaTailcat installs, forwards, and registers loopback peer', async () => {
+ const child = fakeChild();
+ const addPeerFn = vi.fn(async (data) => ({ id: 'peer-1', ...data }));
+ const peer = await addPeerViaTailcat({
+ tcAddress: EXAMPLE_TC,
+ name: 'sandbox',
+ ensureInstalled: async () => ({ bin: '/usr/bin/tailcat', installed: false }),
+ allocatePort: async () => 15555,
+ startForward: async () => child,
+ addPeerFn,
+ persistForwardEntry: async () => {},
+ });
+ expect(addPeerFn).toHaveBeenCalledWith({
+ address: '127.0.0.1',
+ port: 15555,
+ name: 'sandbox',
+ auth: undefined,
+ transport: 'tailcat',
+ });
+ expect(peer.transport).toBe('tailcat');
+ expect(peer.address).toBe('127.0.0.1');
+ });
+});
+