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
fix: harden tailcat peer lifecycle and support HTTPS tunnels
[._.]/ Adam Eivyf146d3fe5dfa
diff --git a/client/src/pages/Instances.jsx b/client/src/pages/Instances.jsxindex 6a966b343c..79de0e5d54 100644--- a/client/src/pages/Instances.jsx+++ b/client/src/pages/Instances.jsx@@ -210,6 +210,7 @@ export function AddPeerForm({ onAdd, addressRef }) {const [mode, setMode] = useState('classic'); // 'classic' | 'tailcat'const [address, setAddress] = useState('');const [tcAddress, setTcAddress] = useState('');+ const [tailcatHttps, setTailcatHttps] = useState(false);const [port, setPort] = useState(String(DEFAULT_PEER_PORT));const [name, setName] = useState('');const [showAuth, setShowAuth] = useState(false);@@ -223,6 +224,7 @@ export function AddPeerForm({ onAdd, addressRef }) {if (!tcAddress.trim()) return;setAdding(true);const data = { tcAddress: tcAddress.trim() };+ if (tailcatHttps) data.protocol = 'https';if (name.trim()) data.name = name.trim();if (password) data.auth = { username: username.trim(), password };const result = await addTailcatPeer(data).catch(() => null);@@ -268,6 +270,7 @@ export function AddPeerForm({ onAdd, addressRef }) {<buttontype="button"aria-pressed={mode === 'classic'}+ disabled={adding}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'}`}>@@ -276,6 +279,7 @@ export function AddPeerForm({ onAdd, addressRef }) {<buttontype="button"aria-pressed={mode === 'tailcat'}+ disabled={adding}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'}`}>@@ -347,11 +351,19 @@ export function AddPeerForm({ onAdd, addressRef }) {</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>+ <>+ <label htmlFor="tailcat-https" className="flex items-center gap-2 text-sm text-gray-400 mt-3">+ <input id="tailcat-https" type="checkbox" checked={tailcatHttps}+ onChange={e => setTailcatHttps(e.target.checked)} disabled={adding} />+ Remote PortOS uses HTTPS+ </label>+ <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.+ Tailcat is installed with Go if needed.+ </p>+ </>)}<div className="mt-2"><buttondiff --git a/client/src/pages/Instances.test.jsx b/client/src/pages/Instances.test.jsxindex b508d15b9b..b1e2ca8df9 100644--- a/client/src/pages/Instances.test.jsx+++ b/client/src/pages/Instances.test.jsx@@ -69,7 +69,17 @@ describe('AddPeerForm tailcat path', () => {expect(addPeer).not.toHaveBeenCalled();});- it('keeps classic host/port add working', async () => {+ it('sends HTTPS selection for a remote TLS install', 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.getByLabelText('Remote PortOS uses HTTPS'));+ fireEvent.click(screen.getByRole('button', { name: 'Add via tailcat' }));+ await waitFor(() => expect(addTailcatPeer).toHaveBeenCalledWith({ tcAddress: tc, protocol: 'https' }));+ });++ it('keeps classic host/port add working' , async () => {render(<AddPeerForm onAdd={() => {}} />);fireEvent.change(screen.getByLabelText('Peer address'), { target: { value: '192.0.2.10' } });fireEvent.click(screen.getByRole('button', { name: 'Add' }));diff --git a/docs/features/tailcat-peers.md b/docs/features/tailcat-peers.mdindex 102ae4d24a..24a96f3b76 100644--- a/docs/features/tailcat-peers.md+++ b/docs/features/tailcat-peers.md@@ -25,11 +25,18 @@ No `tailcat serve all`, no exit-node mode, and no Tailscale daemon are used.2. Paste the peer's `tc…` address (received out of band).3. PortOS ensures `tailcat` is installed (PATH, else `go installgithub.com/tailscale/tailcat/cmd/tailcat@latest`), starts the forward, and- calls the normal peer registration against `127.0.0.1:<localPort>` over HTTP.+ calls the normal peer registration against `127.0.0.1:<localPort>`.+ Select **Remote PortOS uses HTTPS** if the remote install has enabled TLS.4. Classic **Host / port** add remains unchanged (still rejects loopback).+HTTP is the default; HTTPS runs through the same loopback tunnel. Remote+announcements cannot replace the managed local host or forwarding port.+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+can restart them on boot. Startup waits for the CLI to confirm its local listener;+this confirms the tunnel listener, not the remote PortOS health. A failed metadata+write rolls back the new peer. Graceful shutdown stops forwards while retaining+their restart metadata. The full `tc…` string is a bearer capability — it is**never** logged in full, never placed on the peer record returned to the UI orto other peers, and must never appear in commits, PR bodies, docs, or tests.Use placeholders such as `<tcADDR>` or `tcEXAMPLE…` only.diff --git a/server/lib/peerUrl.js b/server/lib/peerUrl.jsindex b7ada43d06..9a8437fa9b 100644--- a/server/lib/peerUrl.js+++ b/server/lib/peerUrl.js@@ -3,9 +3,14 @@** If `peer.host` is set, uses HTTPS with that DNS name (assumes a real cert —* e.g. a Tailscale-issued Let's Encrypt cert for `<host>.<tailnet>.ts.net`).- * Otherwise falls back to plain HTTP on the peer's IP address.+ * Otherwise falls back to plain HTTP on the peer's IP address. Managed tailcat+ * forwards keep their local address and explicit remote HTTP/TLS protocol.*/export function peerBaseUrl(peer) {+ if (peer.transport === 'tailcat') {+ const protocol = peer.protocol === 'https' ? 'https' : 'http';+ return `${protocol}://${peer.address}:${peer.port}`;+ }if (peer.host) return `https://${peer.host}:${peer.port}`;return `http://${peer.address}:${peer.port}`;}diff --git a/server/lib/peerUrl.test.js b/server/lib/peerUrl.test.jsindex ddcdb9eb95..5babd72f67 100644--- a/server/lib/peerUrl.test.js+++ b/server/lib/peerUrl.test.js@@ -2,6 +2,16 @@ import { describe, it, expect } from 'vitest';import { peerBaseUrl } from './peerUrl.js';describe('peerBaseUrl', () => {+ it('keeps tailcat HTTPS on the managed local endpoint even when a host is present', () => {+ expect(peerBaseUrl({ transport: 'tailcat', protocol: 'https', address: '127.0.0.1', port: 15555, host: 'peer.example.com' }))+ .toBe('https://127.0.0.1:15555');+ });++ it('preserves HTTP for legacy tailcat peers without a protocol', () => {+ expect(peerBaseUrl({ transport: 'tailcat', address: '127.0.0.1', port: 15556 }))+ .toBe('http://127.0.0.1:15556');+ });+it('builds an https URL when peer.host is present', () => {expect(peerBaseUrl({ host: 'box.tail-net.ts.net', port: 5555 })).toBe('https://box.tail-net.ts.net:5555');diff --git a/server/routes/instances.js b/server/routes/instances.jsindex be7083bf40..d4b8d52cee 100644--- a/server/routes/instances.js+++ b/server/routes/instances.js@@ -249,7 +249,8 @@ router.post('/peers/announce', asyncHandler(async (req, res) => {}));const addTailcatPeerSchema = z.object({- tcAddress: z.string().min(24).max(2048),+ tcAddress: z.string().trim().min(24).max(2048),+ protocol: z.enum(['http', 'https']).default('http'),name: z.string().optional(),auth: peerAuthSchema});@@ -258,7 +259,7 @@ const addTailcatPeerSchema = z.object({// 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);+ const data = validateRequest(addTailcatPeerSchema, req.body);if (!tailcatPeer.isValidTcAddress(data.tcAddress)) {throw new ServerError('Invalid tailcat address — paste a tc… address from the peer', { status: 400 });}@@ -268,7 +269,7 @@ router.post('/peers/tailcat', asyncHandler(async (req, res) => {// POST /api/instances/peers — add a peerrouter.post('/peers', asyncHandler(async (req, res) => {- const data = addPeerSchema.parse(req.body);+ const data = validateRequest(addPeerSchema, req.body);// Reject invalid DNS names up front so the UI gets a clear error instead of// addPeer() silently dropping the field (validHost returns undefined for invalid input).if (data.host !== undefined && data.host !== null && data.host !== '') {diff --git a/server/routes/instances.test.js b/server/routes/instances.test.jsindex d0c5c46da8..b461cad942 100644--- a/server/routes/instances.test.js+++ b/server/routes/instances.test.js@@ -11,6 +11,7 @@ vi.mock('../services/syncOrchestrator.js', () => ({}));vi.mock('../services/instances.js', () => ({updatePeer: vi.fn(),+ addPeer: vi.fn(),sanitizePeerForClient: vi.fn((peer) => peer),getAssignableInstances: vi.fn(),}));@@ -27,6 +28,11 @@ vi.mock('../lib/tailscale.js', () => ({import { getSyncStatus } from '../services/syncOrchestrator.js';import * as instances from '../services/instances.js';import { getTailscaleStatus } from '../lib/tailscale.js';+vi.mock('../services/tailcatPeer.js', async (original) => ({+ ...(await original()),+ addPeerViaTailcat: vi.fn(),+}));+import { addPeerViaTailcat } from '../services/tailcatPeer.js';import instancesRoutes from './instances.js';const buildApp = () => {@@ -192,3 +198,36 @@ describe('PUT /api/instances/peers/:id — media provider selection', () => {expect(instances.updatePeer).not.toHaveBeenCalled();});});++describe('POST /api/instances/peers/tailcat', () => {+ const tcAddress = 'tcEXAMPLE' + 'A'.repeat(40);+ beforeEach(() => vi.clearAllMocks());++ it('passes the selected HTTPS protocol and credentials through the managed transport', async () => {+ const peer = { id: 'peer-example', transport: 'tailcat', address: '127.0.0.1', port: 15555, protocol: 'https' };+ addPeerViaTailcat.mockResolvedValue(peer);+ const auth = { password: 'example-password' };+ const res = await request(buildApp()).post('/api/instances/peers/tailcat')+ .send({ tcAddress: ` ${tcAddress} `, protocol: 'https', auth });+ expect(res.status).toBe(201);+ expect(addPeerViaTailcat).toHaveBeenCalledWith({ tcAddress, protocol: 'https', auth });+ expect(instances.sanitizePeerForClient).toHaveBeenCalledWith(peer);+ expect(res.body).toEqual(peer);+ });++ it('rejects invalid addresses and protocols without starting a transport', async () => {+ for (const body of [{ tcAddress: 'invalid' }, { tcAddress, protocol: 'file' }]) {+ const res = await request(buildApp()).post('/api/instances/peers/tailcat').send(body);+ expect(res.status).toBe(400);+ }+ expect(addPeerViaTailcat).not.toHaveBeenCalled();+ });++ it('keeps the classic loopback guard in force', async () => {+ const res = await request(buildApp()).post('/api/instances/peers')+ .send({ address: '127.0.0.1', port: 15555, transport: 'tailcat' });+ expect(res.status).toBe(400);+ expect(instances.addPeer).not.toHaveBeenCalled();+ expect(addPeerViaTailcat).not.toHaveBeenCalled();+ });+});diff --git a/server/services/bootstrap.js b/server/services/bootstrap.jsindex cc295dac6d..397ad031a6 100644--- a/server/services/bootstrap.js+++ b/server/services/bootstrap.js@@ -882,6 +882,8 @@ export const registerShutdownHandlers = ({ io, httpServer, localHttpServer }) =>// microseconds from now — and its exit handler must already know the PTY// died because PortOS is going down, not because the agent finished (#3202).markHostShuttingDown();+ await import('./tailcatPeer.js').then(({ stopAllForwards }) => stopAllForwards())+ .catch(() => console.error('❌ Tailcat forward shutdown failed'));// Disarm the idle reaper before anything awaits: a sweep that fires mid// -shutdown would `pm2 stop` a model server the user never asked to lose,// and PortOS is about to stop being the thing that could restart it.diff --git a/server/services/instances.js b/server/services/instances.jsindex bd28965b62..27228f4e55 100644--- a/server/services/instances.js+++ b/server/services/instances.js@@ -157,7 +157,8 @@ export function sanitizePeerForClient(peer) {// separately, so masking here would hide the stored selection: every box on a// `syncEnabled: false` peer would read unchecked, and ticking one would// silently reactivate every other category still true underneath it.- return { ...peer, auth, syncCategories: resolveEffectiveCategories(peer, { masterSwitch: false }) };+ const { tcAddress: _tcAddress, ...safePeer } = peer;+ return { ...safePeer, auth, syncCategories: resolveEffectiveCategories(peer, { masterSwitch: false }) };}// Default data shape@@ -472,7 +473,7 @@ const PER_RECORD_CATEGORY_KINDS = Object.freeze([['creativeCommissions', 'creativeCommission'],]);-export async function addPeer({ address, port = DEFAULT_PEER_PORT, name, host, auth, transport }) {+export async function addPeer({ address, port = DEFAULT_PEER_PORT, name, host, auth, transport, protocol = 'http' }) {const peer = await withData(async (data) => {const normalizedHost = validHost(host);const normalizedAuth = sanitizePeerAuth(auth);@@ -493,7 +494,7 @@ export async function addPeer({ address, port = DEFAULT_PEER_PORT, name, host, aname: 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' } : {}),+ ...(transport === 'tailcat' ? { transport: 'tailcat', protocol: protocol === 'https' ? 'https' : 'http' } : {}),instanceId: null,addedAt: new Date().toISOString(),lastSeen: null,@@ -524,14 +525,13 @@ export async function addPeer({ address, port = DEFAULT_PEER_PORT, name, host, areturn peer;}-export async function removePeer(id, { cleanupForward = true } = {}) {+export async function removePeer(id, { stopTransport = 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.- const data = await loadData();- if (cleanupForward && data.peers.some(peer => peer.id === id && peer.transport === 'tailcat')) {- await import('./tailcatPeer.js')- .then(({ stopForwardForPeer }) => stopForwardForPeer(id));+ // Retire the transport outside the data lock: its lifecycle may itself need+ // that lock when rolling back a failed add. Keep the peer on retirement errors.+ if (stopTransport && (await getPeers()).some(peer => peer.id === id && peer.transport === 'tailcat')) {+ const { stopForwardForPeer } = await import('./tailcatPeer.js');+ await stopForwardForPeer(id);}const removed = await withData(async (data) => {const idx = data.peers.findIndex(p => p.id === id);@@ -654,7 +654,7 @@ export async function updatePeer(id, updates) {console.log(`🌐 Remote media provider ${next.enabled ? 'enabled' : 'disabled'}: ${peer.name}`);}}- if (updates.host !== undefined) {+ if (peer.transport !== 'tailcat' && updates.host !== undefined) {const normalized = validHost(updates.host);if (normalized !== undefined && normalized !== peer.host) {peer.host = normalized; // null clears, string sets@@ -946,6 +946,7 @@ export async function handleAnnounce({ address, port, instanceId, name, host })existing.lastSeen = new Date().toISOString();existing.status = 'online';existing.instanceId = instanceId;+ // A managed forward uses local coordinates, not the remote listen 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);@@ -956,7 +957,7 @@ export async function handleAnnounce({ address, port, instanceId, name, host })// AND the user hasn't manually intervened. The hostManual flag covers// the "user explicitly cleared this — stay on IP" case that the// existing.host check alone can't distinguish from "never set".- if (normalizedHost && !existing.host && !existing.hostManual) {+ if (existing.transport !== 'tailcat' && normalizedHost && !existing.host && !existing.hostManual) {existing.host = normalizedHost;console.log(`🌐 Peer host learned via announce: ${existing.name} → ${normalizedHost}`);}diff --git a/server/services/instances.test.js b/server/services/instances.test.jsindex 10b2061ee6..b03a755b4e 100644--- a/server/services/instances.test.js+++ b/server/services/instances.test.js@@ -45,6 +45,10 @@ vi.mock('./peerSocketRelay.js', () => ({disconnectFromPeer: vi.fn()}));+vi.mock('./tailcatPeer.js', () => ({+ stopForwardForPeer: vi.fn().mockResolvedValue(undefined)+}));+vi.mock('../lib/ports.js', () => ({DEFAULT_PEER_PORT: 5555}));@@ -55,6 +59,7 @@ vi.mock('../lib/tailscale.js', () => ({// fetch is stubbed per-test in beforeEach and restored in afterEach+import { stopForwardForPeer } from './tailcatPeer.js';import { readJSONFile, atomicWrite } from '../lib/fileUtils.js';import { getTailscaleStatus } from '../lib/tailscale.js';import { instanceEvents } from './instanceEvents.js';@@ -283,6 +288,18 @@ describe('instances.js', () => {});describe('addPeer', () => {+ it('persists the tailcat protocol without changing classic peer records', async () => {+ readJSONFile.mockResolvedValue({ self: null, peers: [] });+ const secure = await addPeer({ address: '127.0.0.1', port: 15555, transport: 'tailcat', protocol: 'https' });+ const plain = await addPeer({ address: '127.0.0.1', port: 15556, transport: 'tailcat' });+ const classic = await addPeer({ address: '192.0.2.10', protocol: 'https' });++ expect(secure).toMatchObject({ transport: 'tailcat', protocol: 'https' });+ expect(plain).toMatchObject({ transport: 'tailcat', protocol: 'http' });+ expect(classic).not.toHaveProperty('protocol');+ expect(atomicWrite).toHaveBeenLastCalledWith(expect.any(String), expect.objectContaining({ peers: [secure, plain, classic] }));+ });+it('should add a peer with correct defaults', async () => {readJSONFile.mockResolvedValue({ self: null, peers: [] });fetch.mockRejectedValue(new Error('not reachable'));@@ -411,10 +428,34 @@ describe('instances.js', () => {const removed = await removePeer('peer-1');expect(removed).toMatchObject({ id: 'peer-1', name: 'host1' });+ expect(stopForwardForPeer).not.toHaveBeenCalled();expect(disconnectFromPeer).toHaveBeenCalledWith('peer-1');expect(instanceEvents.emit).toHaveBeenCalledWith('peers:updated', expect.any(Array));});+ it('keeps a tailcat peer recoverable when forward retirement fails, then removes it on retry', async () => {+ const peer = { id: 'tailcat-peer', transport: 'tailcat', address: '127.0.0.1', port: 15555 };+ const peers = [peer];+ readJSONFile.mockResolvedValue({ self: null, peers });+ stopForwardForPeer.mockRejectedValueOnce(new Error('forward metadata write failed'));++ await expect(removePeer(peer.id)).rejects.toThrow('forward metadata write failed');+ expect(peers).toEqual([peer]);+ expect(atomicWrite).not.toHaveBeenCalled();++ await expect(removePeer(peer.id)).resolves.toEqual(peer);+ expect(stopForwardForPeer).toHaveBeenCalledWith(peer.id);+ expect(peers).toEqual([]);+ });++ it('allows transport-owned rollback without re-entering transport cleanup', async () => {+ const peer = { id: 'tailcat-peer', transport: 'tailcat' };+ readJSONFile.mockResolvedValue({ self: null, peers: [peer] });++ await expect(removePeer(peer.id, { stopTransport: false })).resolves.toEqual(peer);+ expect(stopForwardForPeer).not.toHaveBeenCalled();+ });+it('should return null for non-existent peer', async () => {readJSONFile.mockResolvedValue({ self: null, peers: [] });@@ -474,6 +515,12 @@ describe('instances.js', () => {});describe('sanitizePeerForClient', () => {+ it('never exposes a legacy tailcat capability on either wire surface', () => {+ const peer = { id: 'peer-example', tcAddress: 'tcEXAMPLE' + 'A'.repeat(40) };+ expect(sanitizePeerForClient(peer)).not.toHaveProperty('tcAddress');+ expect(redactPeerForWire(peer)).not.toHaveProperty('tcAddress');+ });+// The sync path layers DEFAULT_SYNC_CATEGORIES *under* the stored map so a// peer record written before a category existed picks up its shipped default// with no migration. Shipping the RAW map to the client would render a@@ -540,6 +587,29 @@ describe('instances.js', () => {expect(disconnectFromPeer).toHaveBeenCalledWith('peer-1');});+ it('keeps a tailcat peer recoverable when forward retirement fails, then removes it on retry', async () => {+ const peer = { id: 'tailcat-peer', transport: 'tailcat', address: '127.0.0.1', port: 15555 };+ const peers = [peer];+ readJSONFile.mockResolvedValue({ self: null, peers });+ stopForwardForPeer.mockRejectedValueOnce(new Error('forward metadata write failed'));++ await expect(removePeer(peer.id)).rejects.toThrow('forward metadata write failed');+ expect(peers).toEqual([peer]);+ expect(atomicWrite).not.toHaveBeenCalled();++ await expect(removePeer(peer.id)).resolves.toEqual(peer);+ expect(stopForwardForPeer).toHaveBeenCalledWith(peer.id);+ expect(peers).toEqual([]);+ });++ it('allows transport-owned rollback without re-entering transport cleanup', async () => {+ const peer = { id: 'tailcat-peer', transport: 'tailcat' };+ readJSONFile.mockResolvedValue({ self: null, peers: [peer] });++ await expect(removePeer(peer.id, { stopTransport: false })).resolves.toEqual(peer);+ expect(stopForwardForPeer).not.toHaveBeenCalled();+ });+it('should return null for non-existent peer', async () => {readJSONFile.mockResolvedValue({ self: null, peers: [] });@@ -1461,7 +1531,42 @@ describe('instances.js', () => {// --- Announce (Bidirectional Registration) ---+ it('keeps tailcat routing managed while applying ordinary peer settings', async () => {+ const peer = {+ id: 'tailcat-peer', transport: 'tailcat', address: '127.0.0.1', port: 15555, host: null, protocol: 'https'+ };+ readJSONFile.mockResolvedValue({ self: null, peers: [peer] });++ const updated = await updatePeer(peer.id, {+ address: '192.0.2.10', port: 5555, host: 'peer.example.com', protocol: 'http', name: 'Example peer', enabled: false+ });++ expect(updated).toMatchObject({+ address: '127.0.0.1', port: 15555, host: null, protocol: 'https', name: 'Example peer', enabled: false+ });+ });+describe('handleAnnounce', () => {+ it('preserves the managed tailcat endpoint when the remote announces its own host and port', async () => {+ const existing = {+ id: 'tailcat-peer', address: '127.0.0.1', port: 15555, host: null,+ transport: 'tailcat', instanceId: 'remote-instance', directions: ['outbound']+ };+ readJSONFile.mockResolvedValue({ self: null, peers: [existing] });++ const result = await handleAnnounce({+ address: '192.0.2.10', port: 5555, host: 'peer.example.com',+ instanceId: 'remote-instance', name: 'Example peer'+ });++ expect(result.created).toBe(false);+ expect(result.peer).toMatchObject({+ address: '127.0.0.1', port: 15555, host: null, transport: 'tailcat', status: 'online'+ });+ expect(result.peer.directions).toEqual(['outbound', 'inbound']);+ expect(atomicWrite).toHaveBeenCalledWith(expect.any(String), expect.objectContaining({ peers: [result.peer] }));+ });+it('should create a new peer from announcement', async () => {readJSONFile.mockResolvedValue({ self: null, peers: [] });// probePeer will call fetchdiff --git a/server/services/tailcatPeer.js b/server/services/tailcatPeer.jsindex 3a9a4ec2a5..d0a9d6de6c 100644--- a/server/services/tailcatPeer.js+++ b/server/services/tailcatPeer.js@@ -4,7 +4,7 @@** 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.+ * 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; never log the full value, never put it on the peer@@ -15,6 +15,7 @@ import { createServer } from 'node:net';import { homedir } from 'node:os';import { join } from 'node:path';import { spawn } from '../lib/childProcess.js';+import { createLineReader } from '../lib/streamLines.js';import { commandExists } from '../lib/commandExists.js';import { dataPath, readJSONFile, ensureDir, PATHS, atomicWrite } from '../lib/fileUtils.js';import { createMutex } from '../lib/asyncMutex.js';@@ -24,7 +25,7 @@ import {DEFAULT_TAILCAT_REMOTE_PORT,} from '../lib/ports.js';import { ServerError } from '../lib/errorHandler.js';-import { addPeer, removePeer as removeInstancePeer } from './instances.js';+import { addPeer, getPeers, removePeer as removeInstancePeer } from './instances.js';const FORWARDS_FILE = dataPath('tailcat-forwards.json');const GO_INSTALL_PKG = 'github.com/tailscale/tailcat/cmd/tailcat@latest';@@ -34,6 +35,9 @@ const PORT_SCAN_LIMIT = 32;const DEFAULT_DATA = { version: 1, forwards: [] };const withLock = createMutex();+const withLifecycle = createMutex();+const ownedChildren = new Set();+let shuttingDown = false;/** @type {Map<string, { child: import('node:child_process').ChildProcess, localPort: number, remotePort: number }>} */const liveForwards = new Map();@@ -60,7 +64,12 @@ export function isValidTcAddress(tc) {}async function loadForwards() {- return await readJSONFile(FORWARDS_FILE, DEFAULT_DATA, { strict: false });+ const data = await readJSONFile(FORWARDS_FILE, DEFAULT_DATA, { strict: true, logError: false })+ .catch(() => { throw new ServerError('Could not read tailcat forward storage', { status: 503 }); });+ if (data?.version !== 1 || !Array.isArray(data.forwards)) {+ throw new ServerError('Invalid tailcat forward storage', { status: 503 });+ }+ return data;}async function saveForwards(data) {@@ -122,7 +131,7 @@ export async function ensureTailcatInstalled({await runGoInstall(goBin);} catch (err) {throw new ServerError(- `Failed to install tailcat via go install: ${err.message}. `+ 'Failed to install tailcat via go install. '+ 'Install a release binary from https://github.com/tailscale/tailcat/releases and retry.',{ status: 503, code: 'TAILCAT_INSTALL_FAILED' });@@ -220,56 +229,45 @@ export async function startForwardProcess({} = {}) {if (!isValidTcAddress(tcAddress)) {throw new ServerError('Invalid tailcat address — paste a tc… address from the peer', {- status: 400,- code: 'TAILCAT_BAD_ADDRESS',+ 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'],- })- );-- // Diagnostics can split or repeat bearer capabilities across chunks. Never- // propagate them; recognize only the CLI's listener-ready line.+ if (shuttingDown) throw new Error('PortOS is shutting down');+ const child = spawnFn(bin, ['forward', '--bind=127.0.0.1', tcAddress.trim(), `${localPort}:${remotePort}`],+ safeChildProcessOptions({ env: safeChildProcessEnv(), stdio: ['ignore', 'pipe', 'pipe'] }));+ ownedChildren.add(child);child.stdout?.on('data', () => {});await new Promise((resolve, reject) => {let settled = false;- let pending = '';+ let reader;const finish = (error) => {if (settled) return;settled = true;- pending = '';clearTimeout(timer);- child.stderr?.removeListener('data', onData);- child.stderr?.on('data', () => {});+ reader = null;+ // Diagnostics can contain the bearer capability, including across chunks.+ // Drain them, but never expose them in errors or retain them after startup.if (error) {- try { child.kill('SIGTERM'); } catch { /* process already gone */ }+ try { child.kill('SIGTERM'); } catch { /* process event boundary */ }reject(error);} else 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(() => finish(new Error('tailcat listener startup timed out')), readyMs);- child.stderr?.on('data', onData);+ reader = createLineReader((line) => {+ if (line.endsWith(`forwarding 127.0.0.1:${localPort} -> remote localhost:${remotePort}`)) finish();+ }, { maxCarry: 4096 });+ child.stderr?.on('data', (chunk) => reader?.push(chunk));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})`- )));+ child.once('exit', (code, signal) => {+ ownedChildren.delete(child);+ finish(new Error(`tailcat forward exited early (code=${code}, signal=${signal})`));+ });+ }).catch((error) => {+ ownedChildren.delete(child);+ throw error;});- console.log(- `🐈 tailcat forward started ${redactTcAddress(tcAddress)} → 127.0.0.1:${localPort} (remote :${remotePort})`- );+ console.log(`🐈 tailcat forward listening on 127.0.0.1:${localPort} (remote :${remotePort})`);return child;}@@ -290,7 +288,11 @@ async function forgetForward(peerId) {});}-export async function stopForwardForPeer(peerId) {+export function stopForwardForPeer(peerId) {+ return withLifecycle(() => stopForward(peerId));+}++async function stopForward(peerId) {const live = liveForwards.get(peerId);if (live?.child && !live.child.killed) {try {@@ -299,8 +301,8 @@ export async function stopForwardForPeer(peerId) {// best-effort}}- liveForwards.delete(peerId);await forgetForward(peerId);+ liveForwards.delete(peerId);}/**@@ -308,10 +310,15 @@ export async function stopForwardForPeer(peerId) {* 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({+export function addPeerViaTailcat(options = {}) {+ return withLifecycle(() => addTailcatPeer(options));+}++async function addTailcatPeer({tcAddress,name,auth,+ protocol = 'http',ensureInstalled = ensureTailcatInstalled,allocatePort = allocateLocalPort,startForward = startForwardProcess,@@ -327,6 +334,7 @@ export async function addPeerViaTailcat({});}+ if (shuttingDown) throw new Error('PortOS is shutting down');const { bin } = await ensureInstalled();const localPort = await allocatePort();const remotePort = DEFAULT_TAILCAT_REMOTE_PORT;@@ -341,48 +349,62 @@ export async function addPeerViaTailcat({);}+ ownedChildren.add(child);+ child.once('exit', () => ownedChildren.delete(child));let peer;try {+ if (shuttingDown) throw new Error('PortOS is shutting down');peer = await addPeerFn({address: '127.0.0.1',port: localPort,name: name || `tailcat:${redactTcAddress(trimmed)}`,auth,transport: 'tailcat',+ protocol,});} 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(),- }).catch(async (error) => {+ }).then(() => {+ if (shuttingDown) throw new Error('PortOS is shutting down');+ }).catch(async () => {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;+ // removePeer skips transport cleanup here: this lifecycle operation already+ // owns the child and the queue, so re-entering it would deadlock.+ await removePeerFn(peer.id, { stopTransport: false });+ throw new ServerError('Could not save tailcat forward; peer creation rolled back', {+ status: 503, code: 'TAILCAT_PERSIST_FAILED',+ });+ });++ 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)})`);});return peer;}/** Restart persisted forwards after PortOS boot (best-effort). */-export async function restoreForwards({+export function restoreForwards(options = {}) {+ return withLifecycle(() => restoreTailcatForwards(options));+}++async function restoreTailcatForwards({ensureInstalled = ensureTailcatInstalled,startForward = startForwardProcess,+ getPeersFn = getPeers,} = {}) {+ if (shuttingDown) return { restored: 0 };const data = await loadForwards();const forwards = Array.isArray(data.forwards) ? data.forwards : [];if (forwards.length === 0) return { restored: 0 };@@ -395,9 +417,16 @@ export async function restoreForwards({return { restored: 0, error: err.message };}+ const peers = await getPeersFn();let restored = 0;for (const entry of forwards) {+ if (shuttingDown) break;if (!entry?.peerId || !isValidTcAddress(entry.tcAddress)) continue;+ // A stale entry must never resurrect a removed peer or reuse another route.+ if (!peers.some((peer) => peer.id === entry.peerId && peer.transport === 'tailcat'+ && peer.address === '127.0.0.1' && peer.port === entry.localPort)) continue;+ if (!Number.isInteger(entry.localPort) || entry.localPort < 1024 || entry.localPort > 65535+ || entry.remotePort !== DEFAULT_TAILCAT_REMOTE_PORT) continue;if (liveForwards.has(entry.peerId)) continue;try {const child = await startForward({@@ -416,24 +445,27 @@ export async function restoreForwards({});restored += 1;} catch (err) {- console.log(`⚠️ tailcat restore failed for peer ${entry.peerId}: ${err.message}`);+ console.log(`⚠️ tailcat restore failed for peer ${entry.peerId}`);}}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);+/** Stop server-owned children on shutdown; keep mappings for the next boot. */+export function stopAllForwards() {+ shuttingDown = true;+ for (const child of new Set([...ownedChildren, ...[...liveForwards.values()].map((live) => live.child)])) {+ child.kill('SIGTERM');+ }+ ownedChildren.clear();+ liveForwards.clear();}// Test-only helpersexport function _resetLiveForwardsForTests() {+ stopAllForwards();+ shuttingDown = false;liveForwards.clear();}diff --git a/server/services/tailcatPeer.test.js b/server/services/tailcatPeer.test.jsindex 1092a3d0e3..ef9452f3a6 100644--- a/server/services/tailcatPeer.test.js+++ b/server/services/tailcatPeer.test.js@@ -8,9 +8,21 @@ import {startForwardProcess,addPeerViaTailcat,_resetLiveForwardsForTests,+ _liveForwardCountForTests,+ stopAllForwards,+ stopForwardForPeer,+ restoreForwards,} from './tailcatPeer.js';import { DEFAULT_TAILCAT_LOCAL_PORT, DEFAULT_TAILCAT_REMOTE_PORT } from '../lib/ports.js';+vi.mock('../lib/fileUtils.js', async (original) => ({+ ...(await original()),+ readJSONFile: vi.fn(),+ ensureDir: vi.fn().mockResolvedValue(undefined),+ atomicWrite: vi.fn().mockResolvedValue(undefined),+}));+import { readJSONFile, atomicWrite } from '../lib/fileUtils.js';+const EXAMPLE_TC = 'tcEXAMPLE' + 'A'.repeat(40);function fakeChild() {@@ -28,10 +40,13 @@ function fakeChild() {describe('tailcatPeer helpers', () => {beforeEach(() => {_resetLiveForwardsForTests();+ vi.clearAllMocks();+ readJSONFile.mockResolvedValue({ version: 1, forwards: [] });});afterEach(() => {_resetLiveForwardsForTests();+ vi.useRealTimers();});it('redacts tc addresses so logs never hold the full capability', () => {@@ -67,14 +82,14 @@ describe('tailcatPeer helpers', () => {const result = await ensureTailcatInstalled({detect: async () => {calls += 1;- return calls === 1 ? null : '/mock/go/bin/tailcat';+ return calls === 1 ? null : '/example/go/bin/tailcat';},goBin: 'go',runGoInstall,probeGo: async () => true,});expect(runGoInstall).toHaveBeenCalledOnce();- expect(result).toEqual({ bin: '/mock/go/bin/tailcat', installed: true });+ expect(result).toEqual({ bin: '/example/go/bin/tailcat', installed: true });});it('ensureTailcatInstalled fails clearly when Go is absent', async () => {@@ -113,7 +128,7 @@ describe('tailcatPeer helpers', () => {expect(started).toBe(child);expect(spawnFn).toHaveBeenCalledWith('/usr/bin/tailcat',- ['forward', EXAMPLE_TC, '15555:5555'],+ ['forward', '--bind=127.0.0.1', EXAMPLE_TC, '15555:5555'],expect.any(Object));});@@ -156,18 +171,6 @@ describe('tailcatPeer helpers', () => {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 }));@@ -186,9 +189,115 @@ describe('tailcatPeer helpers', () => {name: 'sandbox',auth: undefined,transport: 'tailcat',+ protocol: 'http',});expect(peer.transport).toBe('tailcat');expect(peer.address).toBe('127.0.0.1');});});++describe('tailcat lifecycle failure contracts', () => {+ beforeEach(() => {+ _resetLiveForwardsForTests();+ vi.clearAllMocks();+ readJSONFile.mockResolvedValue({ version: 1, forwards: [] });+ });+ afterEach(() => { _resetLiveForwardsForTests(); vi.useRealTimers(); });++ function addOptions(child, overrides = {}) {+ return {+ tcAddress: EXAMPLE_TC,+ ensureInstalled: async () => ({ bin: '/example/bin/tailcat' }),+ allocatePort: async () => 15555,+ startForward: async () => child,+ addPeerFn: async (data) => ({ id: 'peer-example', ...data }),+ persistForwardEntry: async () => {},+ ...overrides,+ };+ }++ it('rejects stalled startup at the deadline and terminates the process', async () => {+ vi.useFakeTimers();+ const child = fakeChild();+ const pending = startForwardProcess({ bin: 'tailcat', tcAddress: EXAMPLE_TC,+ localPort: 15555, spawnFn: () => child, readyMs: 8000 });+ const failure = expect(pending).rejects.toThrow('startup timed out');+ await vi.advanceTimersByTimeAsync(7999);+ expect(child.kill).not.toHaveBeenCalled();+ await vi.advanceTimersByTimeAsync(1);+ await failure;+ expect(child.kill).toHaveBeenCalledWith('SIGTERM');+ });++ it('waits for the correct listener and accepts a readiness line split over chunks', async () => {+ const child = fakeChild();+ let ready = false;+ const pending = startForwardProcess({ bin: 'tailcat', tcAddress: EXAMPLE_TC,+ localPort: 15555, spawnFn: () => child }).then(() => { ready = true; });+ child.stderr.emit('data', 'forwarding 127.0.0.1:15556 -> remote localhost:5555\n');+ await Promise.resolve();+ expect(ready).toBe(false);+ child.stderr.emit('data', 'forwarding 127.0.0.1:15555 -> ');+ child.stderr.emit('data', 'remote localhost:5555\n');+ await pending;+ expect(ready).toBe(true);+ });++ it('never includes split or repeated capability diagnostics in startup errors', async () => {+ const child = fakeChild();+ const pending = startForwardProcess({ bin: 'tailcat', tcAddress: EXAMPLE_TC,+ localPort: 15555, spawnFn: () => child });+ child.stderr.emit('data', EXAMPLE_TC.slice(0, 16));+ child.stderr.emit('data', EXAMPLE_TC.slice(16) + EXAMPLE_TC + EXAMPLE_TC);+ child.emit('exit', 1, null);+ await expect(pending).rejects.toThrow('tailcat forward exited early (code=1, signal=null)');+ await pending.catch((error) => expect(error.message).not.toContain('tcEXAMPLE'));+ });++ it('rolls back the peer and child if restart metadata cannot be saved', async () => {+ const child = fakeChild();+ const removePeerFn = vi.fn().mockResolvedValue(undefined);+ await expect(addPeerViaTailcat(addOptions(child, {+ persistForwardEntry: async () => { throw new Error('disk full'); }, removePeerFn,+ }))).rejects.toMatchObject({ code: 'TAILCAT_PERSIST_FAILED' });+ expect(removePeerFn).toHaveBeenCalledWith('peer-example', { stopTransport: false });+ expect(child.killed).toBe(true);+ expect(_liveForwardCountForTests()).toBe(0);+ });++ it('terminates the forward when peer registration fails', async () => {+ const child = fakeChild();+ await expect(addPeerViaTailcat(addOptions(child, {+ addPeerFn: async () => { throw new Error('peer write failed'); },+ }))).rejects.toThrow('peer write failed');+ expect(child.killed).toBe(true);+ });++ it('stops children on shutdown while preserving their restart metadata', async () => {+ const child = fakeChild();+ await addPeerViaTailcat(addOptions(child));+ stopAllForwards();+ expect(child.killed).toBe(true);+ expect(_liveForwardCountForTests()).toBe(0);+ expect(atomicWrite).not.toHaveBeenCalled();+ await expect(addPeerViaTailcat(addOptions(fakeChild()))).rejects.toThrow('shutting down');+ });++ it('restores only mappings that still belong to existing managed peers, and retires them on removal', async () => {+ const entry = { peerId: 'peer-example', tcAddress: EXAMPLE_TC, localPort: 15555, remotePort: 5555 };+ readJSONFile.mockResolvedValue({ version: 1, forwards: [entry, { ...entry, peerId: 'deleted-peer' }] });+ const child = fakeChild();+ const startForward = vi.fn().mockResolvedValue(child);+ const getPeersFn = async () => [{ id: 'peer-example', transport: 'tailcat', address: '127.0.0.1', port: 15555 }];+ const options = { ensureInstalled: async () => ({ bin: 'tailcat' }), startForward, getPeersFn };+ await expect(restoreForwards(options)).resolves.toEqual({ restored: 1 });+ await expect(restoreForwards(options)).resolves.toEqual({ restored: 0 });+ expect(startForward).toHaveBeenCalledTimes(1);+ await stopForwardForPeer('peer-example');+ expect(child.killed).toBe(true);+ expect(atomicWrite).toHaveBeenCalledWith(expect.any(String), {+ version: 1, forwards: [{ ...entry, peerId: 'deleted-peer' }],+ });+ });+});