Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

fix: isolate Tailcat ingress from local-only MCP authority (#6531)

[._.]/5337f8a5e275
diff --git a/client/src/components/instances/TailcatForwardStatus.jsx b/client/src/components/instances/TailcatForwardStatus.jsx
index db3a66f21e..9ec3ec2a66 100644
--- a/client/src/components/instances/TailcatForwardStatus.jsx
+++ b/client/src/components/instances/TailcatForwardStatus.jsx
@@ -7,6 +7,7 @@
*/
import { RefreshCw, Trash2, CheckCircle2, AlertCircle, Clock } from 'lucide-react';
+import { DEFAULT_TAILCAT_REMOTE_PORT } from '../../lib/ports';
import Pill from '../ui/Pill';
import { timeAgo } from '../../utils/formatters';
@@ -64,7 +65,7 @@ export function TailcatForwardStatus({
{onRetry && (
<button
type="button"
- onClick={onRetry}
+ onClick={() => onRetry()}
disabled={busy}
title="Restart this forward using the saved tc address"
className="inline-flex items-center gap-1 text-[11px] text-gray-400 hover:text-white disabled:opacity-50 border border-port-border rounded px-2 py-1 transition-colors"
@@ -73,6 +74,13 @@ export function TailcatForwardStatus({
{busy ? 'Working...' : 'Retry'}
</button>
)}
+ {onRetry && forward.remotePort !== DEFAULT_TAILCAT_REMOTE_PORT && (
+ <button type="button" disabled={busy} onClick={() => onRetry(DEFAULT_TAILCAT_REMOTE_PORT)}
+ className="text-[11px] border border-port-border rounded px-2 py-1 disabled:opacity-50"
+ title="Use after the remote PortOS upgrades to the isolated Tailcat ingress">
+ Retry on :{DEFAULT_TAILCAT_REMOTE_PORT}
+ </button>
+ )}
{showForget && onForget && (
<button
type="button"
diff --git a/client/src/components/instances/TailcatForwardsPanel.jsx b/client/src/components/instances/TailcatForwardsPanel.jsx
index ad390ebbf8..fb2b6b0df5 100644
--- a/client/src/components/instances/TailcatForwardsPanel.jsx
+++ b/client/src/components/instances/TailcatForwardsPanel.jsx
@@ -44,9 +44,9 @@ export default function TailcatForwardsPanel({ onChange, peerIds }) {
});
}, [forwards, peerIdSet]);
- const retry = async (id) => {
+ const retry = async (id, remotePort) => {
setBusyId(id);
- const peer = await retryTailcatForward(id).catch(() => null);
+ const peer = await retryTailcatForward(id, remotePort ? { remotePort } : {}).catch(() => null);
setBusyId(null);
// Refetch rather than guess: status, liveness and the failure text are all
// derived server-side, and a local guess would misreport a failed retry.
@@ -88,7 +88,7 @@ export default function TailcatForwardsPanel({ onChange, peerIds }) {
<TailcatForwardStatus
forward={forward}
busy={busyId === forward.id}
- onRetry={() => retry(forward.id)}
+ onRetry={(remotePort) => retry(forward.id, remotePort)}
onForget={() => forget(forward.id)}
/>
</li>
diff --git a/client/src/components/instances/TailcatForwardsPanel.test.jsx b/client/src/components/instances/TailcatForwardsPanel.test.jsx
index dd53782f7a..5ea3ae08bc 100644
--- a/client/src/components/instances/TailcatForwardsPanel.test.jsx
+++ b/client/src/components/instances/TailcatForwardsPanel.test.jsx
@@ -99,9 +99,9 @@ describe('TailcatForwardsPanel', () => {
const onChange = vi.fn();
render(<TailcatForwardsPanel onChange={onChange} />);
- await userEvent.click(await screen.findByRole('button', { name: /Retry/ }));
+ await userEvent.click(await screen.findByRole('button', { name: 'Retry' }));
- expect(retryTailcatForward).toHaveBeenCalledWith('fwd_1');
+ expect(retryTailcatForward).toHaveBeenCalledWith('fwd_1', {});
expect(await screen.findByText('running')).toBeInTheDocument();
expect(onChange).toHaveBeenCalled();
});
@@ -111,7 +111,7 @@ describe('TailcatForwardsPanel', () => {
const onChange = vi.fn();
render(<TailcatForwardsPanel onChange={onChange} />);
- await userEvent.click(await screen.findByRole('button', { name: /Retry/ }));
+ await userEvent.click(await screen.findByRole('button', { name: 'Retry' }));
await waitFor(() => expect(getTailcatForwards).toHaveBeenCalledTimes(2));
expect(screen.getByText(/context deadline exceeded/)).toBeInTheDocument();
@@ -128,3 +128,12 @@ describe('TailcatForwardsPanel', () => {
expect(getTailcatForwards).toHaveBeenCalledTimes(1);
});
});
+
+it('updates the remote port only when the operator chooses the upgraded ingress', async () => {
+ getTailcatForwards.mockResolvedValue({ forwards: [failedForward] });
+ retryTailcatForward.mockResolvedValue({ id: 'peer-example', port: 15555 });
+ const user = userEvent.setup();
+ render(<TailcatForwardsPanel />);
+ await user.click(await screen.findByRole('button', { name: 'Retry on :5565' }));
+ await waitFor(() => expect(retryTailcatForward).toHaveBeenCalledWith(failedForward.id, { remotePort: 5565 }));
+});
diff --git a/client/src/components/instances/TailcatServePanel.jsx b/client/src/components/instances/TailcatServePanel.jsx
index 134b3bd94e..c15110bc0f 100644
--- a/client/src/components/instances/TailcatServePanel.jsx
+++ b/client/src/components/instances/TailcatServePanel.jsx
@@ -44,7 +44,7 @@ export default function TailcatServePanel({ onChange, compact = false }) {
Tailcat serve (this node)
</h2>
<p className="text-[11px] text-gray-500 mb-3 leading-snug">
- Expose this PortOS API (<span className="font-mono">:{PORTS.API}</span>) over
+ Expose this PortOS API (<span className="font-mono">:{PORTS.TAILCAT_INGRESS}</span>) over
tailcat so a peer that is a better outbound initiator can Dial them
toward us. No Tailscale account. Copy the address out of band only.
</p>
@@ -57,7 +57,7 @@ export default function TailcatServePanel({ onChange, compact = false }) {
{label}
</Pill>
<span className="text-[11px] font-mono text-gray-500">
- serve :{status?.localPort || PORTS.API}
+ serve :{status?.localPort || PORTS.TAILCAT_INGRESS}
{status?.keyName ? ` · key=${status.keyName}` : ''}
</span>
<div className="ml-auto flex items-center gap-1">
diff --git a/client/src/pages/Instances.jsx b/client/src/pages/Instances.jsx
index 2c61f67aa0..8b3c66d406 100644
--- a/client/src/pages/Instances.jsx
+++ b/client/src/pages/Instances.jsx
@@ -26,7 +26,7 @@ import {
import PeerAppsList from '../components/instances/PeerAppsList';
import PeerAgentsSection from '../components/instances/PeerAgentsSection';
import { SchemaGapBadge } from '../components/instances/SchemaGapBadge';
-import { DEFAULT_PEER_PORT, DEFAULT_TAILCAT_LOCAL_PORT } from '../lib/ports.js';
+import { DEFAULT_PEER_PORT, DEFAULT_TAILCAT_LOCAL_PORT, DEFAULT_TAILCAT_REMOTE_PORT } from '../lib/ports.js';
import PeerMediaProviderPanel from '../components/instances/PeerMediaProviderPanel';
import UnattendedRenderRouting from '../components/instances/UnattendedRenderRouting';
import BrainParityPanel from '../components/instances/BrainParityPanel';
@@ -219,6 +219,7 @@ export function AddPeerForm({ onAdd, addressRef }) {
const [dialDirection, setDialDirection] = useState('dial-them'); // 'dial-them' | 'they-dial-us'
const [address, setAddress] = useState('');
const [tcAddress, setTcAddress] = useState('');
+ const [tailcatRemotePort, setTailcatRemotePort] = useState(String(DEFAULT_TAILCAT_REMOTE_PORT));
const [tailcatHttps, setTailcatHttps] = useState(false);
const [port, setPort] = useState(String(DEFAULT_PEER_PORT));
const [name, setName] = useState('');
@@ -234,7 +235,7 @@ export function AddPeerForm({ onAdd, addressRef }) {
if (dialDirection === 'they-dial-us') return; // serve path uses its own buttons
if (!tcAddress.trim()) return;
setAdding(true);
- const data = { tcAddress: tcAddress.trim() };
+ const data = { tcAddress: tcAddress.trim(), remotePort: Number(tailcatRemotePort) };
if (tailcatHttps) data.protocol = 'https';
if (name.trim()) data.name = name.trim();
if (password) data.auth = { username: username.trim(), password };
@@ -337,6 +338,10 @@ export function AddPeerForm({ onAdd, addressRef }) {
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 type="number" aria-label="Remote Tailcat port" min="1" max="65535" required
+ value={tailcatRemotePort} onChange={(event) => setTailcatRemotePort(event.target.value)}
+ title="Use the port shown beside the remote serve address; older manually served peers may use 5555"
+ className="w-24 bg-port-bg border border-port-border rounded px-3 py-2 text-sm" />
<input
aria-label="Peer name"
value={name}
@@ -356,7 +361,8 @@ export function AddPeerForm({ onAdd, addressRef }) {
<div className="space-y-3">
<p className="text-[11px] text-gray-500 leading-snug">
Start serve on this node, copy our <span className="font-mono">tc…</span> address,
- and paste it into the <em>other</em> PortOS as <strong>Dial them</strong>.
+ and paste it into the <em>other</em> PortOS as <strong>Dial them</strong>
+ using remote port <strong>{serveStatus?.localPort || DEFAULT_TAILCAT_REMOTE_PORT}</strong>.
Use this when the other machine is a better outbound initiator
(client firewall / Little Snitch often blocks home dials).
</p>
@@ -1282,11 +1288,11 @@ function PeerCard({ peer, onRefresh, syncStatus, tailnetInfo, parityReport }) {
}
};
- const handleForwardRetry = async () => {
+ const handleForwardRetry = async (remotePort) => {
const forwardId = peer.tailcatForward?.id;
if (!forwardId) return;
setForwardBusy(true);
- const updated = await retryTailcatForward(forwardId).catch(() => null);
+ const updated = await retryTailcatForward(forwardId, remotePort ? { remotePort } : {}).catch(() => null);
setForwardBusy(false);
onRefresh();
if (!updated) return;
diff --git a/client/src/pages/Instances.test.jsx b/client/src/pages/Instances.test.jsx
index 1bf1a680b9..84cabc7e73 100644
--- a/client/src/pages/Instances.test.jsx
+++ b/client/src/pages/Instances.test.jsx
@@ -3,6 +3,7 @@ import { describe, it, expect, vi, beforeEach } from 'vitest';
import { render as renderUI, screen, fireEvent, waitFor, act } from '@testing-library/react';
import TailcatServePanel from '../components/instances/TailcatServePanel';
import { AddPeerForm } from './Instances.jsx';
+import { DEFAULT_TAILCAT_REMOTE_PORT } from '../lib/ports.js';
import { DEFAULT_PEER_PORT, DEFAULT_TAILCAT_LOCAL_PORT } from '../lib/ports.js';
import { addPeer, addTailcatPeer, startTailcatServe, getTailcatServe, stopTailcatServe } from '../services/api';
@@ -78,7 +79,7 @@ describe('AddPeerForm tailcat path', () => {
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 }));
+ await waitFor(() => expect(addTailcatPeer).toHaveBeenCalledWith({ tcAddress: tc, remotePort: DEFAULT_TAILCAT_REMOTE_PORT }));
expect(addPeer).not.toHaveBeenCalled();
});
@@ -89,7 +90,7 @@ describe('AddPeerForm tailcat path', () => {
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' }));
+ await waitFor(() => expect(addTailcatPeer).toHaveBeenCalledWith({ tcAddress: tc, protocol: 'https', remotePort: DEFAULT_TAILCAT_REMOTE_PORT }));
});
it('keeps classic host/port add working' , async () => {
@@ -136,7 +137,7 @@ describe('AddPeerForm dial direction', () => {
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 }));
+ await waitFor(() => expect(addTailcatPeer).toHaveBeenCalledWith({ tcAddress: tc, remotePort: DEFAULT_TAILCAT_REMOTE_PORT }));
});
it('switches to They dial us and starts serve instead of pasting', async () => {
diff --git a/client/src/services/apiSystem.js b/client/src/services/apiSystem.js
index a0b1840151..00152bf09a 100644
--- a/client/src/services/apiSystem.js
+++ b/client/src/services/apiSystem.js
@@ -342,7 +342,7 @@ export const addTailcatPeer = (data) => request('/instances/peers/tailcat', { me
// Saved tailcat forwards. Rows never carry the tc address — only its redacted
// form — so a failed forward can be retried without re-pasting the capability.
export const getTailcatForwards = (options) => request('/instances/peers/tailcat/forwards', options);
-export const retryTailcatForward = (id) => request(`/instances/peers/tailcat/forwards/${id}/retry`, { method: 'POST' });
+export const retryTailcatForward = (id, data = {}) => request(`/instances/peers/tailcat/forwards/${id}/retry`, { method: 'POST', body: JSON.stringify(data) });
export const forgetTailcatForward = (id) => request(`/instances/peers/tailcat/forwards/${id}`, { method: 'DELETE' });
// Managed tailcat serve on this node (PORTS.API). Status may include the full
// tc address so the operator can Copy it — this is our own serve capability.
diff --git a/docs/PORTS.md b/docs/PORTS.md
index d346218b7c..745cac35af 100644
--- a/docs/PORTS.md
+++ b/docs/PORTS.md
@@ -42,7 +42,8 @@ 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` (the remote side runs `tailcat serve` on `PORTS.API`). If busy, PortOS picks the next free port. Dial polarity / managed serve: [features/tailcat-peers.md](./features/tailcat-peers.md). |
+| 5565 | Tailcat remote ingress (loopback) | - | On demand via managed serve; same HTTP/HTTPS as API, but transport-marked remote requests cannot invoke local-only MCP. |
+| 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 ingress `:5565` (the remote side runs managed `tailcat serve`). Saved legacy remote ports are retained until explicitly changed. If busy, PortOS picks the next free port. Dial polarity / managed serve: [features/tailcat-peers.md](./features/tailcat-peers.md). |
## How `:5555`, `:5553`, and `:5554` Relate
@@ -134,7 +135,7 @@ PortOS automatically detects ports from env vars:
| Range | Purpose |
|-------|---------|
| 5553-5561 | PortOS core services (includes the `:5553` loopback mirror and the `portos-db` Docker container on `:5561`) |
-| 5562-5569 | Reserved for PortOS extensions. Assigned: 5562 whisper, 5563 Eidoverse bridge (on demand), 5564 slotstream (on demand), 5568 llama-server. Unassigned but still reserved: 5565-5567, 5569 |
+| 5562-5569 | Reserved for PortOS extensions. Assigned: 5562 whisper, 5563 Eidoverse bridge (on demand), 5564 slotstream (on demand), 5565 Tailcat ingress (on demand), 5568 llama-server. Unassigned but still reserved: 5566-5567, 5569 |
| 5570-5599 | User applications — **put managed apps here** |
> **A collision inside `5553-5569` is silent, not loud.** The natural assumption is
diff --git a/docs/STORAGE.md b/docs/STORAGE.md
index ee75e28bae..88e9130db0 100644
--- a/docs/STORAGE.md
+++ b/docs/STORAGE.md
@@ -73,7 +73,7 @@ PostgreSQL is a **required** install/runtime dependency (see [Backup & Restore](
- 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 or to retry one that failed to start, plus the local/remote port mapping, the optional peer Basic credential, and the last (redacted) startup error. A row is written *before* the forward is attempted, so a failed add stays retryable instead of discarding the operator's pasted capability. The capability must not cross the wire, reach an API response, or appear in logs in full — `listTailcatForwards()` returns only the redacted form (see [features/tailcat-peers.md](./features/tailcat-peers.md)). No sync cursor or tombstone. Adapter: `server/services/tailcatPeer.js`.
-- Tailcat serve — `data/tailcat-serve.json`. `file-primary`, **intentionally machine-local — never federated**: enabled flag, status, local PortOS API port (`5555`), key name (`portos-api`), last (redacted) startup error, and the listen `tc…` address needed to restore `tailcat serve` after reboot and to offer Copy in the Instances UI. Adapter: `server/services/tailcatServe.js`. See [features/tailcat-peers.md](./features/tailcat-peers.md).
+- Tailcat serve — `data/tailcat-serve.json`. `file-primary`, **intentionally machine-local — never federated**: enabled flag, status, local remote-ingress port (`5565`, migrated from the legacy main API port), key name (`portos-api`), last (redacted) startup error, and the listen `tc…` address needed to restore `tailcat serve` after reboot and to offer Copy in the Instances UI. Adapter: `server/services/tailcatServe.js`. See [features/tailcat-peers.md](./features/tailcat-peers.md).
- 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
index 17072f0e76..8ac1d27e92 100644
--- a/docs/features/tailcat-peers.md
+++ b/docs/features/tailcat-peers.md
@@ -3,30 +3,51 @@
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`.
+tailnet. Use this when a trusted peer that cannot join your tailnet needs remote API access to PortOS.
## Port standard
| Side | Port | Role |
|------|------|------|
-| Home / remote PortOS | **5555** | Existing PortOS API (`PORTS.API`) |
+| Home / remote PortOS | **5565** | Loopback remote ingress (`PORTS.TAILCAT_INGRESS`), started by managed serve |
| 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
+Mapping: `tailcat forward <tcADDR> 15555:5565` binds `127.0.0.1:15555` to the
+remote's `:5565`. 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.
+## Remote authority and upgrades
+
+Managed serve exposes the **remote** PortOS API on loopback `:5565`, with the same
+HTTP/HTTPS mode and optional instance authentication as the main API. The listener
+marks requests as remote before dispatch, so Agent Context MCP and its manifest
+reject them even though Tailcat connects from localhost. Headers cannot claim local
+authority. Local MCP clients on the main API or HTTP mirror continue to work.
+
+A Tailcat capability still grants normal remote PortOS API access. Share it only
+with trusted peers; this is not a restricted API for an untrusted sandbox.
+Managed serve cannot be redirected to the main API, its HTTP mirror, or another
+port. Manually serving `5555` or `5553` bypasses this protection.
+
+Migration 370 moves existing managed serve configuration to `5565`, preserving the
+key/address and enabled flag. **Both ends need the new port:** new forwards default
+to `5565`, while saved forwards keep their old remote port because the other install
+may not have upgraded. After the remote upgrades, use **Retry on :5565** on its
+forward row. New peers have a **Remote Tailcat port** field; select `5555` only for
+an older, explicitly trusted peer still serving its legacy API. Older clients must
+upgrade or run a manual forward targeting `5565`; the new server never reopens a
+raw `5555` tunnel for compatibility.
+
## Dial direction (who initiates)
Two polarities, one transport. You do **not** need both directions for v1.
| Choice | This node does | Other node does | When to use |
| --- | --- | --- | --- |
-| **Dial them** | Paste their `tc…`, run `tailcat forward`, register peer at `127.0.0.1:<local>` | Runs `tailcat serve` (PortOS-managed or CLI) for `:5555` | This node can dial out freely (common for a sandbox / VPS). |
-| **They dial us** | PortOS starts **serve** for `:5555`, you **Copy** our `tc…` | Pastes our address as **Dial them** on their Instances UI | This node is a poor dialer (client firewall / Little Snitch often blocks home `tailcat forward`) but a good *listener*; the other side is a better outbound initiator. |
+| **Dial them** | Paste their `tc…`, run `tailcat forward`, register peer at `127.0.0.1:<local>` | Runs `tailcat serve` (PortOS-managed or CLI) for `:5565` | This node can dial out freely (common for a sandbox / VPS). |
+| **They dial us** | PortOS starts **serve** for `:5565`, you **Copy** our `tc…` | Pastes our address as **Dial them** on their Instances UI | This node is a poor dialer (client firewall / Little Snitch often blocks home `tailcat forward`) but a good *listener*; the other side is a better outbound initiator. |
Hypothesis (non-binding): reverse polarity helps when the current node is a better
outbound initiator than the peer that should dial it — use the product option;
@@ -116,7 +137,7 @@ shutdown stops forwards while retaining their restart metadata.
**Serve** is persisted separately in machine-local `data/tailcat-serve.json`
(enabled flag, status, local port, key name, last error, and the listen
-address). PortOS runs `tailcat serve --full-address --json --key=portos-api 5555`
+address). PortOS runs `tailcat serve --full-address --json --key=portos-api 5565`
(not `serve all`, not exit-node), restores serve on boot when enabled, and stops
the child on shutdown. The serve status API returns the full `tc…` address so
the Instances UI can offer **Copy** — that is *this node's* capability to share
@@ -128,7 +149,7 @@ placeholders such as `<tcADDR>` or `tcEXAMPLE…` only.
| Serve surface | What it does |
| --- | --- |
| `GET /api/instances/peers/tailcat/serve` | Status: live/enabled/ports/key, copyable `tcAddress` when known, redacted preview, last error. |
-| `POST …/serve` | Ensure serve is running for `PORTS.API` (5555). |
+| `POST …/serve` | Ensure serve is running for `PORTS.TAILCAT_INGRESS` (5565). |
| `POST …/serve/retry` | Restart from the saved config. |
| `DELETE …/serve` | Stop serve and disable restore-on-boot. |
@@ -277,7 +298,7 @@ a host should hand out a `--full-address`, which embeds the relay info and needs
no map fetch on either end:
```bash
-tailcat serve --full-address --key=new 5555
+tailcat serve --full-address --key=new 5565
```
## Privacy
@@ -289,7 +310,7 @@ tailcat serve --full-address --key=new 5555
## Grok Bot / agent sandbox setup (copy/paste)
-Use this when an **untrusted agent sandbox** should run PortOS and hand the
+Use this when an **trusted agent peer** should run PortOS and hand the
operator a tailcat address so the home install can federate in.
### On the sandbox (serve)
@@ -300,8 +321,9 @@ brew install tailcat
# or: go install github.com/tailscale/tailcat/cmd/tailcat@latest
# or (Linux/Windows only): a release from https://github.com/tailscale/tailcat/releases
-# PortOS already listening on :5555 in the sandbox, then:
-tailcat serve --key=new 5555
+# First start managed serve in Instances to bring up the remote ingress.
+# Manual Tailcat processes must target that ingress, never the main :5555 API:
+tailcat serve --key=new 5565
# stderr prints: 🐈 Server listening with new address: <tcADDR>
```
@@ -313,7 +335,7 @@ Optional named key (stable address across restarts — still a secret):
```bash
tailcat genkey --key=portos-sandbox
-tailcat serve --key=portos-sandbox 5555
+tailcat serve --key=portos-sandbox 5565
```
### On the operator PortOS (forward + peer)
@@ -323,7 +345,7 @@ In **Instances → Add Peer → Tailcat address**, paste `<tcADDR>`.
Or manually:
```bash
-tailcat forward <tcADDR> 15555:5555
+tailcat forward <tcADDR> 15555:5565
# then Add Peer → Host/port is not used for loopback; prefer the UI Tailcat path
# which registers 127.0.0.1:15555 for you.
```
@@ -331,10 +353,10 @@ tailcat forward <tcADDR> 15555:5555
### Checklist for agents
- [ ] PortOS up on sandbox `:5555`
-- [ ] Prefer **Instances → Tailcat serve** (or CLI `tailcat serve --key=… 5555`) — not `serve all`, not exit-node
+- [ ] Prefer **Instances → Tailcat serve** (or CLI `tailcat serve --key=… 5565`) — not `serve all`, not exit-node
- [ ] Both sides on Tailcat **≥0.6.0** (`tailcat version`); upgrade if Dial-them / serve fails with `TAILCAT_VERSION_TOO_OLD` or ping-ok / TCP-timeout PSK mismatch
- [ ] Hand operator `<tcADDR>` out of band only (Copy from UI)
-- [ ] Operator uses **Dial them** (local **15555 → 5555**), *or* if home dials time out, home uses **They dial us** and the sandbox Dials them
+- [ ] Operator uses **Dial them** (local **15555 → 5565**), *or* if home dials time out, home uses **They dial us** and the sandbox Dials them
- [ ] Never write real `tc…` values into git, PR text, or federated logs
## Related
diff --git a/ecosystem.config.cjs b/ecosystem.config.cjs
index dabaa35264..49e679945f 100644
--- a/ecosystem.config.cjs
+++ b/ecosystem.config.cjs
@@ -130,6 +130,7 @@ const PORTS = {
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_INGRESS: 5565, // Loopback-only remote API ingress for managed Tailcat serve
TAILCAT_FORWARD: 15555,
POSTGRES: pgMode === 'native' ? 5432 : 5561 // Active PostgreSQL port (unused in file mode)
};
diff --git a/scripts/lib/migrationOwnedPaths.js b/scripts/lib/migrationOwnedPaths.js
index 42d0edca48..62d42e085a 100644
--- a/scripts/lib/migrationOwnedPaths.js
+++ b/scripts/lib/migrationOwnedPaths.js
@@ -28,4 +28,6 @@ export const MIGRATION_OWNED_PATHS = new Set([
// copy of a plan they never had.
'cos/quota-burn.json',
'cos/quota-burn.pre-359.json',
+ // Migration 370 preserves this install's managed Tailcat serve consent/key.
+ 'tailcat-serve.json',
]);
diff --git a/scripts/migrations/370-tailcat-remote-ingress.js b/scripts/migrations/370-tailcat-remote-ingress.js
new file mode 100644
index 0000000000..19abaa5b65
--- /dev/null
+++ b/scripts/migrations/370-tailcat-remote-ingress.js
@@ -0,0 +1,22 @@
+import { readFile } from 'node:fs/promises';
+import { join } from 'node:path';
+import { atomicWrite } from '../../server/lib/fileCore.js';
+import { PORTS } from '../../server/lib/ports.js';
+
+// Derived from the existing machine-local config. No seed and no forward-port
+// rewrite: a stored forward may still target an independently upgraded peer.
+export default {
+ async up({ rootDir }) {
+ const path = join(rootDir, 'data', 'tailcat-serve.json');
+ const raw = await readFile(path, 'utf8').catch((err) => {
+ if (err.code === 'ENOENT') return null;
+ throw err;
+ });
+ if (raw === null) return;
+ const data = JSON.parse(raw);
+ if (data.version !== 1 || !data.serve) return;
+ data.serve.localPort = PORTS.TAILCAT_INGRESS;
+ data.serve.status = 'stopped';
+ await atomicWrite(path, `${JSON.stringify(data, null, 2)}\n`);
+ },
+};
diff --git a/scripts/migrations/370-tailcat-remote-ingress.test.js b/scripts/migrations/370-tailcat-remote-ingress.test.js
new file mode 100644
index 0000000000..7c20a05b2c
--- /dev/null
+++ b/scripts/migrations/370-tailcat-remote-ingress.test.js
@@ -0,0 +1,31 @@
+import { beforeEach, afterEach, expect, it } from 'vitest';
+import { mkdtemp, mkdir, writeFile, readFile, rm } from 'node:fs/promises';
+import { join } from 'node:path';
+import { tmpdir } from 'node:os';
+import migration from './370-tailcat-remote-ingress.js';
+import { PORTS } from '../../server/lib/ports.js';
+let rootDir;
+beforeEach(async () => { rootDir = await mkdtemp(join(tmpdir(), 'tailcat-migration-')); await mkdir(join(rootDir, 'data')); });
+afterEach(async () => { await rm(rootDir, { recursive: true, force: true }); });
+
+it('moves managed serve to remote ingress while preserving consent, identity and legacy forwards', async () => {
+ const serve = { enabled: true, localPort: 5555, status: 'active', keyName: 'example', tcAddress: 'tcEXAMPLE' };
+ const path = join(rootDir, 'data', 'tailcat-serve.json');
+ const forwardPath = join(rootDir, 'data', 'tailcat-forwards.json');
+ const forwards = JSON.stringify({ version: 1, forwards: [{ remotePort: 5555 }] });
+ await writeFile(path, JSON.stringify({ version: 1, serve }));
+ await writeFile(forwardPath, forwards);
+ await migration.up({ rootDir });
+ await migration.up({ rootDir });
+ expect(JSON.parse(await readFile(path, 'utf8'))).toEqual({ version: 1, serve: { ...serve, localPort: PORTS.TAILCAT_INGRESS, status: 'stopped' } });
+ expect(await readFile(forwardPath, 'utf8')).toBe(forwards);
+});
+
+it('does not enable a fresh install or replace corrupt config', async () => {
+ await migration.up({ rootDir });
+ const path = join(rootDir, 'data', 'tailcat-serve.json');
+ await expect(readFile(path)).rejects.toMatchObject({ code: 'ENOENT' });
+ await writeFile(path, '{invalid');
+ await expect(migration.up({ rootDir })).rejects.toThrow();
+ expect(await readFile(path, 'utf8')).toBe('{invalid');
+});
diff --git a/server/index.js b/server/index.js
index dd5a98cd0b..f8b1b0c3de 100644
--- a/server/index.js
+++ b/server/index.js
@@ -172,6 +172,7 @@ import { errorMiddleware } from './lib/errorHandler.js';
import { setHttpsEnabledAtBoot } from './lib/httpsState.js';
import { JSON_BODY_LIMIT } from './lib/uploadLimits.js';
import { createPortOSProviderRoutes } from './routes/providers.js';
+import { configureTailcatIngress } from './services/tailcatIngress.js';
import { createModelComparisonRoutes } from './routes/modelComparison.js';
import { createPortOSRunsRoutes } from './routes/runs.js';
import { createPortOSPromptsRoutes } from './routes/prompts.js';
@@ -209,6 +210,7 @@ remoteDesktopBroker.mountWebSocket(localHttpServer);
// handshake must carry a valid token cookie or Authorization: Bearer header
// (set by POST /api/auth/login). No-op when auth is off.
io.use(socketAuthGate);
+configureTailcatIngress({ app, io, certDir: CERT_DIR, httpsEnabled });
// Initialize socket handlers
initSocket(io);
diff --git a/server/lib/README.md b/server/lib/README.md
index 9c106e22bc..7893ca2ffb 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -592,3 +592,5 @@ pm` default, `NPM_CONFIG_PREFIX`, nvm/Volta) installed `codex` successfully and
| `privateSecurityPolicy.js` | Private assessment task identity, immutable delivery posture, and report schema. |
| `privateSecuritySandbox.js` | Loopback-only local-provider gate and macOS Seatbelt launch with isolated CLI home and scratch workspace. |
+
+| `requestOrigin.js` | `remoteRequestHandler` and `isRemoteRequest` preserve remote transport identity across a localhost hop without trusting client headers. |
diff --git a/server/lib/index.js b/server/lib/index.js
index 9f23ac0383..e879be6120 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -572,3 +572,5 @@ export * from './localModelSafety.js';
export * from './privateSecurityPolicy.js';
export * from './privateSecuritySandbox.js';
+
+export * from './requestOrigin.js';
diff --git a/server/lib/ports.js b/server/lib/ports.js
index 3783affd57..88133c58da 100644
--- a/server/lib/ports.js
+++ b/server/lib/ports.js
@@ -31,7 +31,8 @@ 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)
+ TAILCAT_INGRESS: 5565, // Loopback remote ingress; excludes local-only API authority
+ TAILCAT_FORWARD: 15555, // Loopback forward for tailcat peers (maps to remote ingress)
POSTGRES_NATIVE: 5432 // System PostgreSQL (PGMODE=native)
});
@@ -43,6 +44,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).
+// Preferred local bind for `tailcat forward <tc> LOCAL:5565` (remote PortOS ingress).
export const DEFAULT_TAILCAT_LOCAL_PORT = PORTS.TAILCAT_FORWARD;
-export const DEFAULT_TAILCAT_REMOTE_PORT = PORTS.API;
+export const DEFAULT_TAILCAT_REMOTE_PORT = PORTS.TAILCAT_INGRESS;
diff --git a/server/lib/ports.test.js b/server/lib/ports.test.js
index 7ba7d67bc0..8d288d9312 100644
--- a/server/lib/ports.test.js
+++ b/server/lib/ports.test.js
@@ -67,10 +67,10 @@ describe('PORTS mirror of ecosystem.config.cjs', () => {
expect(DEFAULT_PEER_PORT).toBe(ECOSYSTEM_PORTS.API);
});
- it('defaults a new tailcat local forward to 15555 → remote API', () => {
+ it('defaults a new tailcat local forward to 15555 → remote ingress', () => {
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);
+ expect(DEFAULT_TAILCAT_REMOTE_PORT).toBe(ECOSYSTEM_PORTS.TAILCAT_INGRESS);
});
});
diff --git a/server/lib/requestOrigin.js b/server/lib/requestOrigin.js
new file mode 100644
index 0000000000..fa9f7731ff
--- /dev/null
+++ b/server/lib/requestOrigin.js
@@ -0,0 +1,12 @@
+// Only the listener can mark a request remote. HTTP headers cannot grant local
+// authority, even when a transport such as Tailcat connects through localhost.
+const remoteRequests = new WeakSet();
+
+export function remoteRequestHandler(handler) {
+ return (req, res) => {
+ remoteRequests.add(req);
+ return handler(req, res);
+ };
+}
+
+export const isRemoteRequest = (req) => remoteRequests.has(req);
diff --git a/server/routes/agentContextMcp.js b/server/routes/agentContextMcp.js
index 65947aa642..2705feebea 100644
--- a/server/routes/agentContextMcp.js
+++ b/server/routes/agentContextMcp.js
@@ -1,3 +1,4 @@
+import { isRemoteRequest } from '../lib/requestOrigin.js';
import { Router } from 'express';
import { randomUUID } from 'node:crypto';
import { asyncHandler, ServerError } from '../lib/errorHandler.js';
@@ -36,7 +37,7 @@ export function isAllowedAgentContextOrigin(origin) {
}
const requireLocalRequest = (req, _res, next) => {
- if (!isLoopbackAddress(req.socket.remoteAddress)) {
+ if (isRemoteRequest(req) || !isLoopbackAddress(req.socket.remoteAddress)) {
throw new ServerError('Agent context accepts loopback connections only', {
status: 403,
code: 'AGENT_CONTEXT_LOCAL_ONLY',
diff --git a/server/routes/agentContextMcp.test.js b/server/routes/agentContextMcp.test.js
index 9fb444d35b..e9b06998b2 100644
--- a/server/routes/agentContextMcp.test.js
+++ b/server/routes/agentContextMcp.test.js
@@ -1,5 +1,7 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
import express from 'express';
+import { createTailcatIngressServer } from '../services/tailcatIngress.js';
+import { Server } from 'socket.io';
import { request } from '../lib/testHelper.js';
import { errorMiddleware } from '../lib/errorHandler.js';
@@ -138,3 +140,26 @@ describe('agentContextMcp route', () => {
expect(response.headers.allow).toBe('POST');
});
});
+
+it('denies remote ingress MCP even without Origin or with forged locality headers', async () => {
+ mocks.callAgentContextTool.mockClear();
+ mocks.getAgentContextManifest.mockResolvedValue(enabledManifest);
+ const app = buildApp();
+ app.get('/api/system/health', (_req, res) => res.json({ status: 'ok' }));
+ const { server } = createTailcatIngressServer(app);
+ const io = new Server(server);
+ // Engine.IO wraps the request listener; the remote marker must survive it.
+ const ingress = server.listeners('request')[0];
+ expect((await request(ingress).get('/api/system/health')).body).toEqual({ status: 'ok' });
+ const response = await request(ingress).post('/api/agent-context/mcp')
+ .set('Accept', 'application/json, text/event-stream')
+ .set('X-Forwarded-For', '127.0.0.1')
+ .set('X-PortOS-Local', 'true')
+ .send({ jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name: 'context_profile', arguments: {} } });
+ expect(response.status).toBe(403);
+ expect(response.body.code).toBe('AGENT_CONTEXT_LOCAL_ONLY');
+ expect(mocks.callAgentContextTool).not.toHaveBeenCalled();
+ const direct = await request(app).get('/api/agent-context/manifest');
+ expect(direct.status).toBe(200);
+ io.close();
+});
diff --git a/server/routes/instances.js b/server/routes/instances.js
index c8d8d80383..79312ad7f9 100644
--- a/server/routes/instances.js
+++ b/server/routes/instances.js
@@ -11,7 +11,7 @@ import { getSyncStatus, syncWithPeer } from '../services/syncOrchestrator.js';
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 { DEFAULT_PEER_PORT, DEFAULT_TAILCAT_REMOTE_PORT, PORTS } from '../lib/ports.js';
import * as tailcatPeer from '../services/tailcatPeer.js';
import * as tailcatServe from '../services/tailcatServe.js';
import { getTailscaleStatus } from '../lib/tailscale.js';
@@ -258,11 +258,12 @@ const addTailcatPeerSchema = z.object({
tcAddress: z.string().trim().min(24).max(2048),
protocol: z.enum(['http', 'https']).default('http'),
name: z.string().optional(),
- auth: peerAuthSchema
+ auth: peerAuthSchema,
+ remotePort: z.number().int().min(1).max(65535).default(DEFAULT_TAILCAT_REMOTE_PORT),
});
// 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
+// Starts `tailcat forward <tc> LOCAL:5565` (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 = validateRequest(addTailcatPeerSchema, req.body);
@@ -285,7 +286,8 @@ router.get('/peers/tailcat/forwards', asyncHandler(async (_req, res) => {
// using the stored capability, registering its peer if the original add never got
// that far.
router.post('/peers/tailcat/forwards/:id/retry', asyncHandler(async (req, res) => {
- const peer = await tailcatPeer.retryTailcatForward(req.params.id);
+ const data = validateRequest(z.object({ remotePort: z.number().int().min(1).max(65535).optional() }), req.body || {});
+ const peer = await tailcatPeer.retryTailcatForward(req.params.id, data);
res.json(instances.sanitizePeerForClient(peer));
}));
@@ -303,13 +305,13 @@ router.get('/peers/tailcat/serve', asyncHandler(async (_req, res) => {
res.json(await tailcatServe.getTailcatServeStatus());
}));
-// POST /api/instances/peers/tailcat/serve — ensure serve is running for PORTS.API.
+// POST /api/instances/peers/tailcat/serve — ensure serve is running for the remote ingress only.
router.post('/peers/tailcat/serve', asyncHandler(async (req, res) => {
- const body = req.body && typeof req.body === 'object' ? req.body : {};
- const status = await tailcatServe.ensureTailcatServe({
- localPort: Number.isInteger(body.localPort) ? body.localPort : undefined,
- keyName: typeof body.keyName === 'string' ? body.keyName : undefined,
- });
+ const data = validateRequest(z.object({
+ localPort: z.literal(PORTS.TAILCAT_INGRESS).optional(),
+ keyName: z.string().regex(/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/).optional(),
+ }), req.body || {});
+ const status = await tailcatServe.ensureTailcatServe(data);
res.status(200).json(status);
}));
diff --git a/server/routes/instances.test.js b/server/routes/instances.test.js
index cf4932652c..ab9e0e9a60 100644
--- a/server/routes/instances.test.js
+++ b/server/routes/instances.test.js
@@ -231,7 +231,7 @@ describe('POST /api/instances/peers/tailcat', () => {
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(addPeerViaTailcat).toHaveBeenCalledWith({ tcAddress, protocol: 'https', auth, remotePort: 5565 });
expect(instances.sanitizePeerForClient).toHaveBeenCalledWith(peer);
expect(res.body).toEqual(peer);
});
@@ -269,7 +269,7 @@ describe('saved tailcat forward routes', () => {
retryTailcatForward.mockResolvedValue(peer);
const res = await request(buildApp()).post('/api/instances/peers/tailcat/forwards/fwd_1/retry');
expect(res.status).toBe(200);
- expect(retryTailcatForward).toHaveBeenCalledWith('fwd_1');
+ expect(retryTailcatForward).toHaveBeenCalledWith('fwd_1', {});
expect(instances.sanitizePeerForClient).toHaveBeenCalledWith(peer);
});
@@ -325,3 +325,10 @@ describe('tailcat serve routes', () => {
expect(stopTailcatServe).toHaveBeenCalledWith({ disable: true });
});
});
+
+it('rejects main API and HTTP mirror ports for managed serving', async () => {
+ for (const localPort of [5555, 5553]) {
+ const response = await request(buildApp()).post('/api/instances/peers/tailcat/serve').send({ localPort });
+ expect(response.status).toBe(400);
+ }
+});
diff --git a/server/services/bootstrap.js b/server/services/bootstrap.js
index 6e9c8facca..e95e91f98e 100644
--- a/server/services/bootstrap.js
+++ b/server/services/bootstrap.js
@@ -985,6 +985,8 @@ export const registerShutdownHandlers = ({ io, httpServer, localHttpServer }) =>
// hangs forever — the real cause of the reconcile "stopping apps" hang.
await withGrace('Socket.IO', 3000, (finish) =>
io.close((err) => finish(err ? `⚠️ Error closing Socket.IO: ${err.message}` : '✅ Socket.IO closed', !!err)));
+ await import('./tailcatIngress.js').then(({ stopTailcatIngress }) => stopTailcatIngress())
+ .catch(() => console.error('❌ Tailcat ingress shutdown failed'));
// Close BOTH servers explicitly. Whichever one io.close() already closed resolves
// immediately (ERR_SERVER_NOT_RUNNING → treated as success by closeServer), and
// the bounded backstop in closeServer guarantees neither can hang shutdown even
diff --git a/server/services/tailcatIngress.js b/server/services/tailcatIngress.js
new file mode 100644
index 0000000000..8ca55a2018
--- /dev/null
+++ b/server/services/tailcatIngress.js
@@ -0,0 +1,68 @@
+/** A separate remote ingress: Tailcat's localhost hop must not imply local authority. */
+import { createTailscaleServers, watchCertReload } from '../../lib/tailscale-https.js';
+import { PORTS } from '../lib/ports.js';
+import { ServerError } from '../lib/errorHandler.js';
+import { remoteRequestHandler } from '../lib/requestOrigin.js';
+
+let configuration = null;
+let listener = null;
+let starting = null;
+let stopWatching = null;
+
+// Configure only; no listener or Tailcat process starts at import/boot.
+export function configureTailcatIngress({ app, io, certDir, httpsEnabled }) {
+ configuration = { app, io, certDir, httpsEnabled };
+}
+
+export function createTailcatIngressServer(app, { certDir, httpsEnabled } = {}) {
+ // Match the main server's boot-time protocol even if provisioning has since
+ // created new cert files. Never silently downgrade an active HTTPS install.
+ const result = createTailscaleServers(remoteRequestHandler(app), {
+ certDir: httpsEnabled === false ? undefined : certDir,
+ httpMirror: false,
+ });
+ if (httpsEnabled === true && !result.httpsEnabled) {
+ throw new ServerError('Tailcat ingress requires the active API TLS certificate', { status: 503 });
+ }
+ return result;
+}
+
+export function ensureTailcatIngress() {
+ if (listener?.listening) return Promise.resolve();
+ if (starting) return starting;
+ if (!configuration) return Promise.reject(new ServerError('Tailcat ingress is not configured', { status: 503 }));
+ const { app, io, certDir, httpsEnabled: apiHttpsEnabled } = configuration;
+ const { server, httpsEnabled } = createTailcatIngressServer(app, { certDir, httpsEnabled: apiHttpsEnabled });
+ listener = server;
+ starting = new Promise((resolve, reject) => {
+ server.once('error', reject);
+ server.listen(PORTS.TAILCAT_INGRESS, '127.0.0.1', () => {
+ // Listen callbacks are outside Express's error boundary.
+ try {
+ if (listener !== server) throw new Error('Tailcat ingress stopped during startup');
+ server.removeListener('error', reject);
+ server.on('error', (err) => console.error(`❌ Tailcat ingress failed: ${err.message}`));
+ io.attach(server);
+ if (httpsEnabled) stopWatching = watchCertReload(server, certDir);
+ resolve();
+ } catch (err) {
+ reject(err);
+ }
+ });
+ }).catch((err) => {
+ stopTailcatIngress();
+ throw new ServerError(`Could not start Tailcat ingress: ${err.message}`, { status: 503 });
+ }).finally(() => { starting = null; });
+ return starting;
+}
+
+export function stopTailcatIngress() {
+ stopWatching?.();
+ stopWatching = null;
+ const server = listener;
+ listener = null;
+ if (!server) return;
+ server.closeAllConnections?.();
+ // Socket.IO's shutdown closes upgraded connections. Never wait for them here.
+ server.close();
+}
diff --git a/server/services/tailcatIngress.test.js b/server/services/tailcatIngress.test.js
new file mode 100644
index 0000000000..3d65a7965b
--- /dev/null
+++ b/server/services/tailcatIngress.test.js
@@ -0,0 +1,28 @@
+import { afterEach, expect, it, vi } from 'vitest';
+vi.mock('../lib/ports.js', () => ({ PORTS: { TAILCAT_INGRESS: 0 } }));
+import { configureTailcatIngress, createTailcatIngressServer, ensureTailcatIngress, stopTailcatIngress } from './tailcatIngress.js';
+import { isRemoteRequest } from '../lib/requestOrigin.js';
+
+afterEach(() => stopTailcatIngress());
+
+it('refuses a plaintext fallback when the main API is using HTTPS', () => {
+ expect(() => createTailcatIngressServer(() => {}, { httpsEnabled: true }))
+ .toThrow('Tailcat ingress requires the active API TLS certificate');
+ const plain = createTailcatIngressServer(() => {}, { httpsEnabled: false });
+ expect(plain.httpsEnabled).toBe(false);
+ expect(plain.mirror).toBe(null);
+});
+
+it('binds one loopback listener on demand and marks requests independently of headers', async () => {
+ const io = { attach: vi.fn() };
+ configureTailcatIngress({ app: (req, res) => res.end(JSON.stringify({ remote: isRemoteRequest(req) })), io });
+ expect(io.attach).not.toHaveBeenCalled();
+ await Promise.all([ensureTailcatIngress(), ensureTailcatIngress()]);
+ expect(io.attach).toHaveBeenCalledTimes(1);
+ const server = io.attach.mock.calls[0][0];
+ expect(server.address().address).toBe('127.0.0.1');
+ const response = await fetch(`http://127.0.0.1:${server.address().port}/`, { headers: { 'X-PortOS-Local': 'true' } });
+ expect(await response.json()).toEqual({ remote: true });
+ await ensureTailcatIngress();
+ expect(io.attach).toHaveBeenCalledTimes(1);
+});
diff --git a/server/services/tailcatPeer.js b/server/services/tailcatPeer.js
index b0e2e3219f..d4a4dfad64 100644
--- a/server/services/tailcatPeer.js
+++ b/server/services/tailcatPeer.js
@@ -3,7 +3,7 @@
* [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) → prove the
+ * start `tailcat forward <tcADDR> LOCAL:5565` (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.
*
@@ -37,6 +37,7 @@ import { peerBaseUrl } from '../lib/peerUrl.js';
import { isTestRunner } from '../lib/runtimeEnv.js';
import { findCommandOnPath, safeChildProcessEnv, safeChildProcessOptions } from '../lib/processEnv.js';
import {
+ PORTS,
DEFAULT_TAILCAT_LOCAL_PORT,
DEFAULT_TAILCAT_REMOTE_PORT,
} from '../lib/ports.js';
@@ -172,7 +173,7 @@ function normalizeForwardEntry(entry) {
peerId,
tcAddress: entry.tcAddress,
localPort: Number.isInteger(entry.localPort) ? entry.localPort : null,
- remotePort: Number.isInteger(entry.remotePort) ? entry.remotePort : DEFAULT_TAILCAT_REMOTE_PORT,
+ remotePort: Number.isInteger(entry.remotePort) ? entry.remotePort : PORTS.API,
name: typeof entry.name === 'string' && entry.name ? entry.name : null,
protocol: entry.protocol === 'https' ? 'https' : 'http',
// Kept beside the capability so a retry can re-register a password-gated
@@ -852,6 +853,7 @@ async function addTailcatPeer({
name,
auth,
protocol = 'http',
+ remotePort = DEFAULT_TAILCAT_REMOTE_PORT,
ensureInstalled = ensureTailcatInstalled,
primeDerpMap = primeDerpMapCache,
allocatePort = allocateLocalPort,
@@ -862,6 +864,9 @@ async function addTailcatPeer({
removePeerFn = removeInstancePeer,
verifyTunnel,
} = {}) {
+ if (!Number.isInteger(remotePort) || remotePort < 1 || remotePort > 65535) {
+ throw new ServerError('Invalid remote Tailcat port', { status: 400, code: 'TAILCAT_BAD_PORT' });
+ }
const trimmed = String(tcAddress || '').trim();
if (!isValidTcAddress(trimmed)) {
throw new ServerError('Invalid tailcat address — paste a tc… address from the peer', {
@@ -880,7 +885,7 @@ async function addTailcatPeer({
peerId: null,
tcAddress: trimmed,
localPort: null,
- remotePort: DEFAULT_TAILCAT_REMOTE_PORT,
+ remotePort,
name: name || null,
protocol: protocol === 'https' ? 'https' : 'http',
auth: auth && typeof auth === 'object' ? auth : null,
@@ -929,7 +934,7 @@ async function startAndRegister({
// Promise.resolve().then defers the call so a synchronous throw is caught here
// too, the same guard ensureTailcatInstalled documents for its installers.
await Promise.resolve().then(primeDerpMap).catch(() => null);
- const remotePort = DEFAULT_TAILCAT_REMOTE_PORT;
+ const remotePort = entry.remotePort;
const localPort = await allocatePort({ preferred: entry.localPort || DEFAULT_TAILCAT_LOCAL_PORT });
let child;
@@ -1031,6 +1036,7 @@ export function retryTailcatForward(id, options = {}) {
}
async function retryForward(id, {
+ remotePort,
ensureInstalled = ensureTailcatInstalled,
primeDerpMap = primeDerpMapCache,
allocatePort = allocateLocalPort,
@@ -1046,6 +1052,15 @@ async function retryForward(id, {
const entry = entries.find((f) => f.id === id);
if (!entry) throw new ServerError('Tailcat forward not found', { status: 404 });
+ if (remotePort !== undefined) {
+ if (!Number.isInteger(remotePort) || remotePort < 1 || remotePort > 65535) {
+ throw new ServerError('Invalid remote Tailcat port', { status: 400, code: 'TAILCAT_BAD_PORT' });
+ }
+ const patched = await patchForwardEntry(entry.id, { remotePort });
+ if (!patched) throw new ServerError('Could not update Tailcat remote port', { status: 503 });
+ entry.remotePort = remotePort;
+ }
+
// A live child on a stale mapping would keep the port and mask the retry.
killLiveForward(entry.id);
@@ -1098,7 +1113,7 @@ async function restoreTailcatForwards({
if (!entry.peerId || !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;
+ || !Number.isInteger(entry.remotePort) || entry.remotePort < 1 || entry.remotePort > 65535) continue;
if (liveForwards.has(entry.id)) continue;
try {
const child = await startForward({
diff --git a/server/services/tailcatPeer.test.js b/server/services/tailcatPeer.test.js
index 41ec507d84..be92b8724d 100644
--- a/server/services/tailcatPeer.test.js
+++ b/server/services/tailcatPeer.test.js
@@ -324,7 +324,7 @@ describe('tailcatPeer helpers', () => {
it('allocateLocalPort prefers 15555 then walks upward when busy', async () => {
expect(DEFAULT_TAILCAT_LOCAL_PORT).toBe(15555);
- expect(DEFAULT_TAILCAT_REMOTE_PORT).toBe(5555);
+ expect(DEFAULT_TAILCAT_REMOTE_PORT).toBe(5565);
const isFree = vi.fn(async (port) => port === 15557);
const port = await allocateLocalPort({ preferred: 15555, isFree, limit: 5 });
expect(port).toBe(15557);
@@ -446,19 +446,20 @@ describe('tailcatPeer helpers', () => {
)).toContain('dial remote port 5555: context deadline exceeded');
});
- it('addPeerViaTailcat installs, forwards, and registers loopback peer', async () => {
+ it.each([5555, DEFAULT_TAILCAT_REMOTE_PORT])('adds a peer using the selected remote port %s', async (remotePort) => {
const child = fakeChild();
const addPeerFn = vi.fn(async (data) => ({ id: 'peer-1', ...data }));
const peer = await addPeerViaTailcat({
tcAddress: EXAMPLE_TC,
+ remotePort,
name: 'sandbox',
ensureInstalled: async () => ({ bin: '/usr/bin/tailcat', installed: false }),
allocatePort: async () => 15555,
- startForward: async () => child,
+ startForward: async (options) => { expect(options.remotePort).toBe(remotePort); return child; },
addPeerFn,
primeDerpMap: async () => ({ primed: false }),
- persistForwardEntry: async () => {},
- patchForwardEntry: async () => ({}),
+ persistForwardEntry: async (entry) => { expect(entry.remotePort).toBe(remotePort); },
+ patchForwardEntry: async (_id, patch) => { expect(patch.remotePort).toBe(remotePort); return {}; },
});
expect(addPeerFn).toHaveBeenCalledWith({
address: '127.0.0.1',
@@ -513,7 +514,7 @@ describe('tailcat lifecycle failure contracts', () => {
const child = fakeChild();
let ready = false;
const pending = startForwardProcess({ bin: 'tailcat', tcAddress: EXAMPLE_TC,
- localPort: 15555, spawnFn: () => child, probeMs: 5, isListening: async () => false })
+ localPort: 15555, remotePort: 5555, spawnFn: () => child, probeMs: 5, isListening: async () => false })
.then(() => { ready = true; });
child.stderr.emit('data', 'forwarding 127.0.0.1:15556 -> remote localhost:5555\n');
await Promise.resolve();
@@ -748,7 +749,7 @@ describe('saved tailcat forwards', () => {
patchForwardEntry: async (id, patch) => { patches.push([id, patch]); return { id, ...patch }; },
getPeersFn: async () => [],
});
- expect(startForward).toHaveBeenCalledWith(expect.objectContaining({ tcAddress: EXAMPLE_TC, localPort: 15556 }));
+ expect(startForward).toHaveBeenCalledWith(expect.objectContaining({ tcAddress: EXAMPLE_TC, localPort: 15556, remotePort: 5555 }));
expect(addPeerFn).toHaveBeenCalledWith(expect.objectContaining({
address: '127.0.0.1', port: 15556, name: 'sandbox', transport: 'tailcat', protocol: 'https',
}));
@@ -766,7 +767,8 @@ describe('saved tailcat forwards', () => {
ensureInstalled: async () => ({ bin: 'tailcat' }),
primeDerpMap: async () => ({ primed: false }),
allocatePort: async () => 15557,
- startForward: async () => fakeChild(),
+ remotePort: DEFAULT_TAILCAT_REMOTE_PORT,
+ startForward: async ({ remotePort }) => { expect(remotePort).toBe(DEFAULT_TAILCAT_REMOTE_PORT); return fakeChild(); },
addPeerFn,
patchForwardEntry: async (id, patch) => ({ id, ...patch }),
getPeersFn: async () => [{ id: 'peer-1', transport: 'tailcat', address: '127.0.0.1', port: 15555 }],
diff --git a/server/services/tailcatServe.js b/server/services/tailcatServe.js
index 26a279aafd..c68d9185fd 100644
--- a/server/services/tailcatServe.js
+++ b/server/services/tailcatServe.js
@@ -1,5 +1,5 @@
/**
- * Machine-local `tailcat serve` for the PortOS API port — the reverse polarity
+ * Machine-local `tailcat serve` for the remote ingress port — the reverse polarity
* of `tailcatPeer.js` forwards.
*
* When this node is a better *outbound initiator* than the peer that should
@@ -14,6 +14,7 @@
* record, never federated, and never committed.
*/
+import { ensureTailcatIngress } from './tailcatIngress.js';
import { mkdir, readFile, unlink } from 'node:fs/promises';
import { dirname } from 'node:path';
import { spawn } from '../lib/childProcess.js';
@@ -34,7 +35,7 @@ import {
const SERVE_FILE = dataPath('tailcat-serve.json');
const ADDR_FILE = dataPath('tailcat-serve.addr');
const DEFAULT_KEY_NAME = 'portos-api';
-const DEFAULT_LOCAL_PORT = PORTS.API;
+const DEFAULT_LOCAL_PORT = PORTS.TAILCAT_INGRESS;
const SERVE_READY_MS = 20_000;
const DIAGNOSTIC_TAIL_CHARS = 4096;
const GENKEY_TIMEOUT_MS = 60_000;
@@ -57,9 +58,8 @@ function normalizeServeEntry(entry) {
const keyName = typeof entry.keyName === 'string' && /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/.test(entry.keyName)
? entry.keyName
: DEFAULT_KEY_NAME;
- const localPort = Number.isInteger(entry.localPort) && entry.localPort >= 1 && entry.localPort <= 65535
- ? entry.localPort
- : DEFAULT_LOCAL_PORT;
+ // Old managed entries targeted the main API. Never restore that authority.
+ const localPort = DEFAULT_LOCAL_PORT;
const status = ['active', 'failed', 'stopped', 'pending'].includes(entry.status)
? entry.status
: 'stopped';
@@ -231,8 +231,8 @@ export async function startServeProcess({
mkdirFn = mkdir,
} = {}) {
if (shuttingDown) throw new Error('PortOS is shutting down');
- if (!Number.isInteger(localPort) || localPort < 1 || localPort > 65535) {
- throw new ServerError('Invalid local port for tailcat serve', { status: 400, code: 'TAILCAT_SERVE_BAD_PORT' });
+ if (localPort !== DEFAULT_LOCAL_PORT) {
+ throw new ServerError('Managed Tailcat serve must use the remote ingress port', { status: 400, code: 'TAILCAT_SERVE_BAD_PORT' });
}
await mkdirFn(dirname(addrFile), { recursive: true }).catch(() => null);
@@ -362,6 +362,7 @@ export function ensureTailcatServe(options = {}) {
async function ensureServe({
localPort = DEFAULT_LOCAL_PORT,
keyName = DEFAULT_KEY_NAME,
+ ensureIngress = ensureTailcatIngress,
ensureInstalled = ensureTailcatInstalled,
primeDerpMap = primeDerpMapCache,
ensureKey = ensureServeKey,
@@ -370,7 +371,10 @@ async function ensureServe({
} = {}) {
if (shuttingDown) throw new Error('PortOS is shutting down');
- const port = Number.isInteger(localPort) ? localPort : DEFAULT_LOCAL_PORT;
+ if (localPort != null && localPort !== DEFAULT_LOCAL_PORT) {
+ throw new ServerError('Managed Tailcat serve must use the remote ingress port', { status: 400, code: 'TAILCAT_SERVE_BAD_PORT' });
+ }
+ const port = DEFAULT_LOCAL_PORT;
const key = typeof keyName === 'string' && keyName ? keyName : DEFAULT_KEY_NAME;
// Persist intent before spawn so a failed start stays retryable / restorable.
@@ -405,6 +409,7 @@ async function ensureServe({
killLiveServe();
try {
+ await ensureIngress();
const { bin } = await ensureInstalled();
await Promise.resolve().then(primeDerpMap).catch(() => null);
await ensureKey({ bin, keyName: key });
@@ -476,6 +481,7 @@ export function restoreServe(options = {}) {
}
async function restoreTailcatServe({
+ ensureIngress = ensureTailcatIngress,
ensureInstalled = ensureTailcatInstalled,
primeDerpMap = primeDerpMapCache,
ensureKey = ensureServeKey,
@@ -487,6 +493,7 @@ async function restoreTailcatServe({
if (liveServe) return { restored: false, reason: 'already-live' };
try {
+ await ensureIngress();
const { bin } = await ensureInstalled();
await Promise.resolve().then(primeDerpMap).catch(() => null);
await ensureKey({ bin, keyName: entry.keyName });
diff --git a/server/services/tailcatServe.test.js b/server/services/tailcatServe.test.js
index 58421eef13..09f7f344ca 100644
--- a/server/services/tailcatServe.test.js
+++ b/server/services/tailcatServe.test.js
@@ -1,3 +1,4 @@
+vi.mock('./tailcatIngress.js', () => ({ ensureTailcatIngress: vi.fn().mockResolvedValue(undefined) }));
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { EventEmitter } from 'node:events';
import {
@@ -87,7 +88,7 @@ describe('tailcatServe helpers', () => {
});
const started = await startServeProcess({
bin: '/usr/bin/tailcat',
- localPort: 5555,
+ localPort: DEFAULT_SERVE_PORT,
keyName: 'portos-api',
spawnFn,
readyMs: 2_000,
@@ -95,10 +96,10 @@ describe('tailcatServe helpers', () => {
mkdirFn: async () => {},
});
expect(started.tcAddress).toBe(EXAMPLE_TC);
- expect(started.localPort).toBe(5555);
+ expect(started.localPort).toBe(DEFAULT_SERVE_PORT);
expect(spawnFn).toHaveBeenCalledWith(
'/usr/bin/tailcat',
- ['serve', '--verbose', '--full-address', '--json', '--key=portos-api', '5555'],
+ ['serve', '--verbose', '--full-address', '--json', '--key=portos-api', String(DEFAULT_SERVE_PORT)],
expect.any(Object),
);
});
@@ -160,7 +161,7 @@ describe('tailcatServe helpers', () => {
serve: {
enabled: true,
status: 'active',
- localPort: 5555,
+ localPort: DEFAULT_SERVE_PORT,
keyName: 'portos-api',
tcAddress: EXAMPLE_TC,
lastError: null,
@@ -175,7 +176,7 @@ describe('tailcatServe helpers', () => {
ensureInstalled: async () => ({ bin: '/x', installed: false }),
primeDerpMap: async () => ({}),
ensureKey: async () => ({ created: false, keyName: 'portos-api' }),
- startServe: async () => ({ child, tcAddress: EXAMPLE_TC, localPort: 5555, keyName: 'portos-api' }),
+ startServe: async () => ({ child, tcAddress: EXAMPLE_TC, localPort: DEFAULT_SERVE_PORT, keyName: 'portos-api' }),
});
expect(_liveServeForTests()).not.toBe(null);
@@ -194,7 +195,7 @@ describe('tailcatServe helpers', () => {
serve: {
enabled: true,
status: 'active',
- localPort: 5555,
+ localPort: DEFAULT_SERVE_PORT,
keyName: 'portos-api',
tcAddress: EXAMPLE_TC,
lastError: null,
@@ -208,13 +209,13 @@ describe('tailcatServe helpers', () => {
ensureInstalled: async () => ({ bin: '/usr/bin/tailcat' }),
primeDerpMap: async () => ({}),
ensureKey: async () => ({ created: false, keyName: 'portos-api' }),
- startServe: async () => ({ child, tcAddress: EXAMPLE_TC, localPort: 5555, keyName: 'portos-api' }),
+ startServe: async () => ({ child, tcAddress: EXAMPLE_TC, localPort: DEFAULT_SERVE_PORT, keyName: 'portos-api' }),
});
expect(ok).toEqual({ restored: true });
expect(_liveServeForTests()?.child).toBe(child);
_resetLiveServeForTests();
- readJSONFile.mockResolvedValue({ version: 1, serve: { enabled: false, status: 'stopped', localPort: 5555, keyName: 'portos-api', tcAddress: null } });
+ readJSONFile.mockResolvedValue({ version: 1, serve: { enabled: false, status: 'stopped', localPort: DEFAULT_SERVE_PORT, keyName: 'portos-api', tcAddress: null } });
const skipped = await restoreServe({
ensureInstalled: async () => ({ bin: '/usr/bin/tailcat' }),
startServe: async () => { throw new Error('should not run'); },
@@ -230,7 +231,7 @@ describe('tailcatServe helpers', () => {
serve: {
enabled: true,
status: 'failed',
- localPort: 5555,
+ localPort: DEFAULT_SERVE_PORT,
keyName: 'portos-api',
tcAddress: EXAMPLE_TC,
lastError: 'boom',
@@ -246,14 +247,14 @@ describe('tailcatServe helpers', () => {
ensureInstalled: async () => ({ bin: '/x' }),
primeDerpMap: async () => ({}),
ensureKey: async () => ({ created: false, keyName: 'portos-api' }),
- startServe: async () => ({ child: first, tcAddress: EXAMPLE_TC, localPort: 5555, keyName: 'portos-api' }),
+ startServe: async () => ({ child: first, tcAddress: EXAMPLE_TC, localPort: DEFAULT_SERVE_PORT, keyName: 'portos-api' }),
});
const status = await retryTailcatServe({
ensureInstalled: async () => ({ bin: '/x' }),
primeDerpMap: async () => ({}),
ensureKey: async () => ({ created: false, keyName: 'portos-api' }),
- startServe: async () => ({ child: second, tcAddress: EXAMPLE_TC, localPort: 5555, keyName: 'portos-api' }),
+ startServe: async () => ({ child: second, tcAddress: EXAMPLE_TC, localPort: DEFAULT_SERVE_PORT, keyName: 'portos-api' }),
});
expect(first.kill).toHaveBeenCalled();
expect(status.live).toBe(true);
@@ -272,3 +273,12 @@ describe('tailcatServe helpers', () => {
});
});
});
+
+it('rejects direct main-port serving before spawning or installing', async () => {
+ const spawnFn = vi.fn();
+ await expect(startServeProcess({ bin: 'tailcat', localPort: 5555, spawnFn })).rejects.toMatchObject({ code: 'TAILCAT_SERVE_BAD_PORT' });
+ const ensureInstalled = vi.fn();
+ await expect(ensureTailcatServe({ localPort: 5555, ensureInstalled })).rejects.toMatchObject({ code: 'TAILCAT_SERVE_BAD_PORT' });
+ expect(spawnFn).not.toHaveBeenCalled();
+ expect(ensureInstalled).not.toHaveBeenCalled();
+});