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: adding a tailcat peer no longer fails with a false startup timeout

Adam Eivya60b295f36ab
diff --git a/client/src/components/instances/TailcatForwardsPanel.jsx b/client/src/components/instances/TailcatForwardsPanel.jsx
new file mode 100644
index 0000000000..f7badaee11
--- /dev/null
+++ b/client/src/components/instances/TailcatForwardsPanel.jsx
@@ -0,0 +1,126 @@
+/**
+ * Saved tailcat forwards.
+ *
+ * A tc address is a bearer capability the operator receives out of band, and it
+ * only ever existed in the Add Peer field. When the forward failed to start,
+ * that pasted value was gone — so recovering meant going back to the remote for
+ * a fresh address before anyone could even retry. PortOS now saves the
+ * capability (machine-local) the moment an add begins, and this panel is what
+ * makes that recoverable: it names which forward is down, what tailcat actually
+ * said, and offers Retry without the address ever coming back to the browser.
+ *
+ * Rows carry only the redacted address. Nothing here can reveal the capability.
+ */
+
+import { useCallback, useEffect, useState } from 'react';
+import { RefreshCw, Trash2, CheckCircle2, AlertCircle, Clock } from 'lucide-react';
+import toast from '../ui/Toast';
+import Pill from '../ui/Pill';
+import { getTailcatForwards, retryTailcatForward, forgetTailcatForward } from '../../services/api';
+import { timeAgo } from '../../utils/formatters';
+
+// Pill has no `error` tone; the red lastError line below carries the severity.
+const STATUS_TONE = { active: 'success', pending: 'muted', failed: 'warning' };
+const STATUS_ICON = { active: CheckCircle2, pending: Clock, failed: AlertCircle };
+
+export default function TailcatForwardsPanel({ onChange }) {
+ // `null` = not loaded yet, `[]` = loaded and genuinely empty. Distinct so a
+ // pending fetch never renders as "no forwards".
+ const [forwards, setForwards] = useState(null);
+ const [busyId, setBusyId] = useState(null);
+
+ const load = useCallback(async () => {
+ // An install that has never added a tailcat peer is the common case — not
+ // something to toast about on every Instances load.
+ const data = await getTailcatForwards({ silent: true }).catch(() => null);
+ setForwards(Array.isArray(data?.forwards) ? data.forwards : []);
+ }, []);
+
+ useEffect(() => { load(); }, [load]);
+
+ const retry = async (id) => {
+ setBusyId(id);
+ const peer = await retryTailcatForward(id).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.
+ await load();
+ if (!peer) return;
+ onChange?.();
+ toast.success(`Tailcat forward started on 127.0.0.1:${peer.port}`);
+ };
+
+ const forget = async (id) => {
+ setBusyId(id);
+ const removed = await forgetTailcatForward(id).catch(() => null);
+ setBusyId(null);
+ if (!removed) return load();
+ // Drop the row locally — a removal has no server-derived state left to read.
+ setForwards(prev => (prev || []).filter(f => f.id !== id));
+ onChange?.();
+ toast.success('Tailcat forward and its saved address removed');
+ };
+
+ if (!forwards || forwards.length === 0) return null;
+
+ return (
+ <div className="bg-port-card border border-port-border rounded-xl p-5">
+ <h2 className="text-sm font-medium text-gray-400 uppercase tracking-wider mb-1">
+ Tailcat forwards ({forwards.length})
+ </h2>
+ <p className="text-[11px] text-gray-500 mb-3 leading-snug">
+ Saved on this machine only, so a forward that fails to start can be retried
+ without pasting its <span className="font-mono">tc…</span> address again.
+ </p>
+ <ul className="space-y-2">
+ {forwards.map(forward => {
+ const StatusIcon = STATUS_ICON[forward.status] || Clock;
+ const busy = busyId === forward.id;
+ return (
+ <li key={forward.id} className="bg-port-bg border border-port-border rounded-lg p-3">
+ <div className="flex flex-wrap items-center gap-2">
+ <Pill tone={STATUS_TONE[forward.status] || 'bare'} size="xs" bordered={false} icon={StatusIcon}>
+ {forward.live ? 'running' : forward.status}
+ </Pill>
+ <span className="text-sm text-white truncate">
+ {forward.name || forward.tcAddress}
+ </span>
+ <span className="text-[11px] font-mono text-gray-500">
+ {forward.localPort ? `127.0.0.1:${forward.localPort}` : 'no port yet'}
+ {' → '}:{forward.remotePort}
+ </span>
+ <div className="ml-auto flex items-center gap-1">
+ <button
+ type="button"
+ onClick={() => retry(forward.id)}
+ 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"
+ >
+ <RefreshCw size={11} className={busy ? 'animate-spin' : ''} />
+ {busy ? 'Working...' : 'Retry'}
+ </button>
+ <button
+ type="button"
+ onClick={() => forget(forward.id)}
+ disabled={busy}
+ title="Stop the forward, delete its saved address, and remove its peer"
+ className="inline-flex items-center gap-1 text-[11px] text-gray-500 hover:text-port-error disabled:opacity-50 border border-port-border rounded px-2 py-1 transition-colors"
+ >
+ <Trash2 size={11} /> Forget
+ </button>
+ </div>
+ </div>
+ {forward.status !== 'active' && forward.lastError && (
+ <p className="text-[11px] text-port-error mt-2 leading-snug break-words">
+ {forward.lastError}
+ {forward.lastErrorAt && <span className="text-gray-500"> · {timeAgo(forward.lastErrorAt)}</span>}
+ </p>
+ )}
+ </li>
+ );
+ })}
+ </ul>
+ </div>
+ );
+}
diff --git a/client/src/components/instances/TailcatForwardsPanel.test.jsx b/client/src/components/instances/TailcatForwardsPanel.test.jsx
new file mode 100644
index 0000000000..d7dd1c5978
--- /dev/null
+++ b/client/src/components/instances/TailcatForwardsPanel.test.jsx
@@ -0,0 +1,91 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { render, screen, waitFor } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+
+vi.mock('../../services/api', () => ({
+ getTailcatForwards: vi.fn(),
+ retryTailcatForward: vi.fn(),
+ forgetTailcatForward: vi.fn(),
+}));
+
+vi.mock('../ui/Toast', () => ({
+ default: { success: vi.fn(), error: vi.fn() },
+}));
+
+import { getTailcatForwards, retryTailcatForward, forgetTailcatForward } from '../../services/api';
+import TailcatForwardsPanel from './TailcatForwardsPanel';
+
+const failedForward = {
+ id: 'fwd_1',
+ peerId: null,
+ // Only ever the redacted form reaches the client.
+ tcAddress: 'tcEX…wxyz',
+ localPort: null,
+ remotePort: 5555,
+ name: 'sandbox',
+ protocol: 'http',
+ hasAuth: false,
+ status: 'failed',
+ lastError: 'tailcat listener startup timed out — tailcat said: fetching DERPMap: context deadline exceeded',
+ lastErrorAt: '2026-01-01T00:00:00.000Z',
+ createdAt: '2026-01-01T00:00:00.000Z',
+ live: false,
+};
+
+describe('TailcatForwardsPanel', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ getTailcatForwards.mockResolvedValue({ forwards: [failedForward] });
+ });
+
+ it('renders nothing when the install has no saved forwards', async () => {
+ getTailcatForwards.mockResolvedValue({ forwards: [] });
+ const { container } = render(<TailcatForwardsPanel />);
+ await waitFor(() => expect(getTailcatForwards).toHaveBeenCalled());
+ expect(container).toBeEmptyDOMElement();
+ });
+
+ it('surfaces what tailcat actually said, which is the whole point of saving the forward', async () => {
+ render(<TailcatForwardsPanel />);
+ expect(await screen.findByText(/context deadline exceeded/)).toBeInTheDocument();
+ expect(screen.getByText('failed')).toBeInTheDocument();
+ // No port bound yet, because the original add never got that far.
+ expect(screen.getByText(/no port yet/)).toBeInTheDocument();
+ });
+
+ it('retries from the stored address and re-reads the server-derived status', async () => {
+ retryTailcatForward.mockResolvedValue({ id: 'peer-9', port: 15555 });
+ getTailcatForwards.mockResolvedValueOnce({ forwards: [failedForward] })
+ .mockResolvedValue({ forwards: [{ ...failedForward, status: 'active', localPort: 15555, live: true, lastError: null }] });
+ const onChange = vi.fn();
+ render(<TailcatForwardsPanel onChange={onChange} />);
+
+ await userEvent.click(await screen.findByRole('button', { name: /Retry/ }));
+
+ expect(retryTailcatForward).toHaveBeenCalledWith('fwd_1');
+ expect(await screen.findByText('running')).toBeInTheDocument();
+ expect(onChange).toHaveBeenCalled();
+ });
+
+ it('keeps the row when a retry fails, so the reason stays on screen', async () => {
+ retryTailcatForward.mockRejectedValue(new Error('still broken'));
+ const onChange = vi.fn();
+ render(<TailcatForwardsPanel onChange={onChange} />);
+
+ await userEvent.click(await screen.findByRole('button', { name: /Retry/ }));
+
+ await waitFor(() => expect(getTailcatForwards).toHaveBeenCalledTimes(2));
+ expect(screen.getByText(/context deadline exceeded/)).toBeInTheDocument();
+ expect(onChange).not.toHaveBeenCalled();
+ });
+
+ it('drops a forgotten forward from the list without refetching', async () => {
+ forgetTailcatForward.mockResolvedValue({ id: 'fwd_1', peerId: null });
+ render(<TailcatForwardsPanel />);
+
+ await userEvent.click(await screen.findByRole('button', { name: /Forget/ }));
+
+ await waitFor(() => expect(screen.queryByText('sandbox')).not.toBeInTheDocument());
+ expect(getTailcatForwards).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/client/src/pages/Instances.jsx b/client/src/pages/Instances.jsx
index b0f0bb9c2c..0f01ce790b 100644
--- a/client/src/pages/Instances.jsx
+++ b/client/src/pages/Instances.jsx
@@ -30,6 +30,7 @@ import UnattendedRenderRouting from '../components/instances/UnattendedRenderRou
import BrainParityPanel from '../components/instances/BrainParityPanel';
import BrainParitySchedule from '../components/instances/BrainParitySchedule';
import TailnetHelpBanner from '../components/instances/TailnetHelpBanner';
+import TailcatForwardsPanel from '../components/instances/TailcatForwardsPanel';
import { timeAgo, timeUntil } from '../utils/formatters';
import { directionalCounts, describeDirectional } from '../lib/syncCounts';
import PageSkeleton from '../components/ui/PageSkeleton';
@@ -1430,6 +1431,10 @@ export default function Instances() {
route. */}
<UnattendedRenderRouting peers={peers} />
+ {/* Also outside the peer-count guard: a tailcat forward whose start failed
+ never registered a peer, so this is the only surface that can retry it. */}
+ <TailcatForwardsPanel onChange={fetchData} />
+
{peers.length > 0 && (
<div>
<h2 className="text-sm font-medium text-gray-400 uppercase tracking-wider mb-3">
diff --git a/client/src/services/apiSystem.js b/client/src/services/apiSystem.js
index 385798ae13..466574c3d4 100644
--- a/client/src/services/apiSystem.js
+++ b/client/src/services/apiSystem.js
@@ -339,6 +339,11 @@ export const getAssignableInstances = (options) => request('/instances/assignabl
export const updateSelfInstance = (data) => request('/instances/self', { method: 'PUT', body: JSON.stringify(data) });
export const addPeer = (data) => request('/instances/peers', { method: 'POST', body: JSON.stringify(data) });
export const addTailcatPeer = (data) => request('/instances/peers/tailcat', { method: 'POST', body: JSON.stringify(data) });
+// 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 forgetTailcatForward = (id) => request(`/instances/peers/tailcat/forwards/${id}`, { method: 'DELETE' });
export const updatePeer = (id, data) => request(`/instances/peers/${id}`, { method: 'PUT', body: JSON.stringify(data) });
export const removePeer = (id) => request(`/instances/peers/${id}`, { method: 'DELETE' });
export const connectPeer = (id) => request(`/instances/peers/${id}/connect`, { method: 'POST' });
diff --git a/docs/STORAGE.md b/docs/STORAGE.md
index e9f8acef8c..68622a88ee 100644
--- a/docs/STORAGE.md
+++ b/docs/STORAGE.md
@@ -70,7 +70,7 @@ PostgreSQL is a **required** install/runtime dependency (see [Backup & Restore](
- Spotify brain playlist shelf — `data/spotify/playlists.json`. `file-primary`, intentionally machine-local and never federated: it is a bounded cache of Spotify playlist and track metadata used as local reference material, while listening evidence remains in the federated Brain activity record. No sync cursor or tombstone. Adapter: `server/services/spotifyPlaylists.js`.
- IdeaLoom lists — `data/brain/idealoom-lists/{uuid}/index.json` with a schema-stamped collection index holding the disabled-by-default local integration settings. Lists retain their ordered idea strings, prompt/title/category/status/help, timestamps, and importer-owned local sync metadata. Explicit exchange reads/writes only the configured vault's `Idea Loom/` folder through the specialized `server/services/idealoomObsidian.js` parser/renderer; new notes use a date/title filename and imported note paths remain stable. **Intentionally machine-local — never federated, reconciled, or memory-bridged**: a vault id, note path, and content hash are meaningful only on the install that configured them. Native Brain `ideas` remain a separate federated collection. Exchange is base-hash reconciled: a note and a list that both changed since the stored hash report `conflicted` and neither is written, and a note deleted in the vault reports `missing` rather than being recreated (an iCloud note that is merely un-downloaded is `unavailable`, a separate outcome). Opt-in automatic export (`autoSync`, off by default, debounced by `server/services/idealoomAutoSync.js`) can only update an existing note — it never deletes, recreates, or resolves a conflict. Backed up in full with the rest of `data/brain/`; the vault notes themselves are the user's Obsidian data and are outside PortOS's snapshot. Adapters: `server/services/idealoomLists.js` (records), `server/services/idealoomObsidian.js` (exchange).
- Local-model assessments — `data/local-llm/assessments.json` (#4539). Measured evidence for one installed local model per (backend, model): the fit verdict (`fits`/`does-not-fit`/`incompatible`/`unknown`), per-context throughput/TTFT samples, resident footprint, and the coarse hardware environment the measurement was taken in. `file-primary` — a flat, capped, single-JSON projection with no cross-record queries and no relationships; the newest measurement replaces the old one per model rather than accumulating history. **Intentionally machine-local — never federated**: an assessment is a claim about THIS box, so a peer inheriting a 128 GB machine's its verdict for its 8 GB laptop would be actively wrong. No sync cursor, no tombstone, no `PORTOS_SCHEMA_VERSIONS` entry. Backed up (a run costs the user minutes of local compute), and the environment record deliberately carries no hostname/username/path. Adapter: `server/services/localModelAssessmentStore.js` (durable store + environment capture; no path to a provider, so read-only consumers like the catalog fit badge can import it); the run lives in `server/services/localModelAssessments.js` and the scoring in `server/lib/localModelAssessment.js`. Each record's environment is re-compared against the live machine on read, so a reading taken before a RAM upgrade or backend update is flagged stale rather than silently trusted.
-- Tailcat peer forwards — `data/tailcat-forwards.json`. `file-primary`, **intentionally machine-local — never federated**: each row stores the bearer `tc…` address needed to restart `tailcat forward` after a PortOS reboot, plus the local/remote port mapping. The capability must not cross the wire or appear in logs in full (see [features/tailcat-peers.md](./features/tailcat-peers.md)). No sync cursor or tombstone. Adapter: `server/services/tailcatPeer.js`.
+- 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`.
- 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 6c0575e81c..29e74b7265 100644
--- a/docs/features/tailcat-peers.md
+++ b/docs/features/tailcat-peers.md
@@ -56,13 +56,81 @@ 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. 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 or
-to other peers, and must never appear in commits, PR bodies, docs, or tests.
-Use placeholders such as `<tcADDR>` or `tcEXAMPLE…` only.
+can restart them on boot **and retry one that failed to start**. 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 or to other peers, never returned by an API
+response, and must never appear in commits, PR bodies, docs, or tests. Use
+placeholders such as `<tcADDR>` or `tcEXAMPLE…` only.
+
+### The saved address is what makes a failed add recoverable
+
+The row is written **before** the forward is attempted. That ordering is the
+point: the `tc…` address arrives out of band and only ever existed in the Add
+Peer field, so an add that died on the way up used to throw the capability away
+and force the operator back to the remote for a fresh one before anyone could
+even retry.
+
+| Surface | What it does |
+| --- | --- |
+| `GET /api/instances/peers/tailcat/forwards` | Every saved forward: status (`pending`/`active`/`failed`), whether it is running, the local↔remote ports, and the last **redacted** startup error. `tcAddress` is the redacted form; the credential is reported as `hasAuth` only. |
+| `POST …/forwards/:id/retry` | Restarts from the stored capability, registering the peer if the original add never got that far, and repointing an existing peer when a retry has to bind a different local port. |
+| `DELETE …/forwards/:id` | Stops the forward, deletes the stored capability, and removes its peer. |
+
+The Instances page renders these as **Tailcat forwards**, with Retry and Forget
+per row. A boot-time restore failure lands on the same row, so the one case
+nobody is watching still surfaces somewhere actionable.
+
+### Startup readiness has two independent signals
+
+`startForwardProcess` spawns `tailcat forward --verbose …` and resolves when
+*either* the CLI logs `forwarding 127.0.0.1:<local> -> remote localhost:<remote>`
+*or* the local port stops accepting a bind (something is listening on it). It
+confirms the tunnel listener, not the remote PortOS health.
+
+`--verbose` and the bind probe are both there because of a real failure. tailcat
+**≤0.5.0** — the version Homebrew installs — emits that `forwarding …` line
+through its verbose-only logger, and PortOS spawned without `--verbose`: every
+add against that build failed with `tailcat listener startup timed out` after 8s
+while the listener was up and perfectly healthy (v0.6.0 promoted the line to an
+unconditional print). So `--verbose` restores the line on released builds, and it
+is also the only way per-connection `dial remote target …` failures are logged at
+all. The bind probe then makes readiness independent of any log wording, so the
+next CLI reword cannot regress this the same way.
+
+On failure, tailcat's own diagnostics now reach the operator — capability-shaped
+tokens scrubbed, last few lines only. An opaque "startup timed out" with the real
+reason discarded is what made this take three passes to diagnose.
+
+A failed metadata write rolls back the new peer.
+
+### The DERP map has to be reachable — by Go
+
+tailcat resolves a `tc…` address's relay region by fetching its DERP map
+(`https://tailcat.dev/derpmap.json`, override with `TAILCAT_DERPMAP_URL`) using
+Go's own HTTP client. On a host where a local network filter permits Node and
+curl but blocks Go's dialer, that fetch fails and **every** tailcat command dies
+before it can serve or dial:
+
+```
+Expand: fetching DERPMap for region -1: Get "https://tailcat.dev/derpmap.json": context deadline exceeded
+```
+
+This is the same host condition that makes `go install` fail with
+`connect: bad file descriptor` — and it is why Homebrew is tried first for the
+install. PortOS reaches that identical URL fine, so before spawning tailcat it
+pre-warms the cache the CLI already reads
+(`<user cache dir>/tailcat/derpmap-<escaped URL>.json`, refreshed at most every
+6h). Strictly best-effort: if the write or the fetch fails, tailcat just fetches
+the map the way it normally would.
+
+On the **serve** side there is no PortOS process to do that, so a sandbox on such
+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
+```
## Privacy
diff --git a/server/lib/README.md b/server/lib/README.md
index 7eacdbe99b..3fa1b4198b 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -353,7 +353,7 @@ pm` default, `NPM_CONFIG_PREFIX`, nvm/Volta) installed `codex` successfully and
| `tailnetPeer.js` | `isTailnetPeer(peer)` — fail-closed security predicate for "is this peer reachable only over the tailnet". Deliberately separate from `instances.js`'s `peerRequiresTailscale()` probe-deferral heuristic so a polling-noise tweak can't widen a privacy boundary; required by the unattended-routing gate in ADR 2026-08-20-federated-visual-prompts. |
| `federatedMediaRequest.js` | Builds and validates the versioned federated-media submission body for a visual kind, so every call site that persists a remote-job marker projects local params onto the wire identically. |
| `federatedMediaWire.js` | Versioned federated-media status schema/constants plus fail-closed consumer freshness checks (stale and clock-skewed snapshots are never assignable). `FEDERATED_MEDIA_FEATURES` + `federatedMediaSupports(status, feature, capability)` answer "does the peer BUILD speak this wire feature" from the status-root `features` list — the one place the "absent reads as the wire-v1 baseline" rule lives; a published list wins outright, with the `inputAssets` capability block retained as its only legacy overlap tell because it is genuinely per-model. `federatedMediaDeclaresFeatures(status)` and `federatedMediaDeniesFeature(status, feature, capability)` separate "positively denied" from "could not establish" for MESSAGE selection only — both gate identically, and which missing signal indicts the peer’s build is recorded per feature rather than at each call site. |
-| `connectivity.js` | `isMachineOnline({timeoutMs?, hosts?})` — internet-reachability probe: bare TCP `connect` to public anycast resolvers on :443 (no DNS, no HTTP), resolves `true` on the first connect and `false` only after all fail; never rejects. Reuse when a caller needs a best-effort local reachability signal. |
+| `connectivity.js` | `isMachineOnline({timeoutMs?, hosts?})` — internet-reachability probe: bare TCP `connect` to public anycast resolvers on :443 (no DNS, no HTTP), resolves `true` on the first connect and `false` only after all fail; never rejects. Reuse when a caller needs a best-effort local reachability signal. Also `isPortReachable({host?, port, timeoutMs?})` — the same connect primitive aimed at ONE address, for "is anything listening there yet?"; use it rather than a bind probe whenever another process is expected to own the port, since a bind probe can win the race and kill that process with `EADDRINUSE`. |
| `safeUrlFetch.js` | SSRF-guarded public-URL fetch: `isPublicHttpUrlSafe`/`assertPublicHttpUrl` (scheme + blocked-host-literal via `catalogValidation.isBlockedIngestHost` + DNS-resolve), exported strict `isPrivateAddress`, plus `fetchPublicText`/`fetchPublicBinary` (timeout, redirect revalidation, size cap) and `buildPinnedLookup`/`buildPinnedDispatcher` (the connect-time IP pin that closes the DNS-rebinding TOCTOU). Reuse instead of copying the SSRF guard for any "fetch this remote thing the user pointed us at" flow. Also `readBodyCapped(response, maxBytes)` bounds streamed bodies without choosing a network policy. |
| `pinterestFeed.js` | Pure Pinterest board RSS helpers: `normalizePinterestFeedUrl(input)` (board URL or `.rss` → `{ feedUrl, boardUrl }`, host-gated) + `parsePinterestRss(xml)` (per-pin `pinUrl`/`imageUrl`/title/description, 736x size upgrade). Feeds the mood-board Pinterest importer. |
| `requestAbort.js` | `abortSignalFromResponse(res)` — AbortSignal that fires only when an Express client disconnects *before the response finishes* (keyed off `res` close + `writableEnded`). Plus `anyAbortSignal(signals)` — combine several signals into one (native `AbortSignal.any` with a Node-18 fallback). |
diff --git a/server/lib/apiRouteCatalog.generated.json b/server/lib/apiRouteCatalog.generated.json
index b52b484f95..bf6f541d9e 100644
--- a/server/lib/apiRouteCatalog.generated.json
+++ b/server/lib/apiRouteCatalog.generated.json
@@ -8513,6 +8513,30 @@
"server/routes/instances.js"
]
},
+ {
+ "method": "GET",
+ "path": "/api/instances/peers/tailcat/forwards",
+ "mountPath": "/api/instances",
+ "sources": [
+ "server/routes/instances.js"
+ ]
+ },
+ {
+ "method": "DELETE",
+ "path": "/api/instances/peers/tailcat/forwards/:id",
+ "mountPath": "/api/instances",
+ "sources": [
+ "server/routes/instances.js"
+ ]
+ },
+ {
+ "method": "POST",
+ "path": "/api/instances/peers/tailcat/forwards/:id/retry",
+ "mountPath": "/api/instances",
+ "sources": [
+ "server/routes/instances.js"
+ ]
+ },
{
"method": "POST",
"path": "/api/instances/provision-cert",
@@ -17948,8 +17972,8 @@
],
"stats": {
"mounts": 150,
- "operations": 2223,
- "declarations": 2231,
+ "operations": 2226,
+ "declarations": 2234,
"sourceFiles": 233
}
}
diff --git a/server/lib/connectivity.js b/server/lib/connectivity.js
index 0ffc3c3aab..6a0f1ae5bb 100644
--- a/server/lib/connectivity.js
+++ b/server/lib/connectivity.js
@@ -28,6 +28,7 @@ export const DEFAULT_PROBE_HOSTS = [
];
export const DEFAULT_PROBE_TIMEOUT_MS = 3000;
+export const DEFAULT_PORT_PROBE_TIMEOUT_MS = 500;
// Resolve when a single host connects; reject when it errors or times out.
// Always tears the socket down (listeners + fd) on every terminal path. The
@@ -65,3 +66,18 @@ export function isMachineOnline({ timeoutMs = DEFAULT_PROBE_TIMEOUT_MS, hosts =
// after all fail" contract. The reject handler swallows it so we never throw.
return Promise.any(hosts.map((h) => probeHost(h, timeoutMs))).then(() => true, () => false);
}
+
+/**
+ * Is anything listening on `host:port`? A bare TCP connect, resolving `true` on
+ * connect and `false` on error/timeout, never rejecting — the same primitive
+ * `isMachineOnline` uses, pointed at one address instead of the internet.
+ *
+ * Prefer this over a *bind* probe when something else is expected to own the
+ * port: a bind holds the address for as long as the probe is open, so polling a
+ * port while another process is still starting can lose it the race and make
+ * that process die with `EADDRINUSE`. A connect only observes.
+ */
+export function isPortReachable({ host = '127.0.0.1', port, timeoutMs = DEFAULT_PORT_PROBE_TIMEOUT_MS } = {}) {
+ if (!Number.isInteger(port) || port < 1 || port > 65535) return Promise.resolve(false);
+ return probeHost({ host, port }, timeoutMs).then(() => true, () => false);
+}
diff --git a/server/lib/connectivity.test.js b/server/lib/connectivity.test.js
index dff9a2502b..7ecbbd2760 100644
--- a/server/lib/connectivity.test.js
+++ b/server/lib/connectivity.test.js
@@ -1,6 +1,6 @@
import { describe, it, expect, afterEach } from 'vitest';
import net from 'net';
-import { isMachineOnline } from './connectivity.js';
+import { isMachineOnline, isPortReachable } from './connectivity.js';
// Spin up a real loopback TCP server so the "connects" path is exercised
// without hitting the public internet; a closed loopback port gives a fast,
@@ -65,3 +65,18 @@ describe('isMachineOnline', () => {
expect(Date.now() - start).toBeLessThan(3000);
});
});
+
+describe('isPortReachable', () => {
+ it('resolves true only while something is actually listening on the port', async () => {
+ const { server, port } = await listenOnEphemeralPort();
+ await expect(isPortReachable({ port })).resolves.toBe(true);
+ await new Promise((resolve) => server.close(resolve));
+ await expect(isPortReachable({ port })).resolves.toBe(false);
+ });
+
+ it('never rejects, and refuses an out-of-range port without dialing', async () => {
+ await expect(isPortReachable({ port: 0 })).resolves.toBe(false);
+ await expect(isPortReachable({ port: 70_000 })).resolves.toBe(false);
+ await expect(isPortReachable()).resolves.toBe(false);
+ });
+});
diff --git a/server/routes/instances.js b/server/routes/instances.js
index d4b8d52cee..44076a3224 100644
--- a/server/routes/instances.js
+++ b/server/routes/instances.js
@@ -267,6 +267,28 @@ router.post('/peers/tailcat', asyncHandler(async (req, res) => {
res.status(201).json(instances.sanitizePeerForClient(peer));
}));
+// GET /api/instances/peers/tailcat/forwards — saved tailcat forwards.
+// The tc address is a bearer capability, so rows carry only its redacted form;
+// what they DO carry is which forward is down and why, so a failed add can be
+// retried without the operator producing the address again.
+router.get('/peers/tailcat/forwards', asyncHandler(async (_req, res) => {
+ res.json({ forwards: await tailcatPeer.listTailcatForwards() });
+}));
+
+// POST /api/instances/peers/tailcat/forwards/:id/retry — restart a saved forward
+// 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);
+ res.json(instances.sanitizePeerForClient(peer));
+}));
+
+// DELETE /api/instances/peers/tailcat/forwards/:id — stop the forward, drop the
+// stored capability, and remove its peer if one was registered.
+router.delete('/peers/tailcat/forwards/:id', asyncHandler(async (req, res) => {
+ res.json(await tailcatPeer.forgetTailcatForward(req.params.id));
+}));
+
// POST /api/instances/peers — add a peer
router.post('/peers', asyncHandler(async (req, res) => {
const data = validateRequest(addPeerSchema, req.body);
diff --git a/server/routes/instances.test.js b/server/routes/instances.test.js
index b461cad942..de23ed9c89 100644
--- a/server/routes/instances.test.js
+++ b/server/routes/instances.test.js
@@ -31,8 +31,16 @@ import { getTailscaleStatus } from '../lib/tailscale.js';
vi.mock('../services/tailcatPeer.js', async (original) => ({
...(await original()),
addPeerViaTailcat: vi.fn(),
+ listTailcatForwards: vi.fn(),
+ retryTailcatForward: vi.fn(),
+ forgetTailcatForward: vi.fn(),
}));
-import { addPeerViaTailcat } from '../services/tailcatPeer.js';
+import {
+ addPeerViaTailcat,
+ listTailcatForwards,
+ retryTailcatForward,
+ forgetTailcatForward,
+} from '../services/tailcatPeer.js';
import instancesRoutes from './instances.js';
const buildApp = () => {
@@ -231,3 +239,32 @@ describe('POST /api/instances/peers/tailcat', () => {
expect(addPeerViaTailcat).not.toHaveBeenCalled();
});
});
+
+describe('saved tailcat forward routes', () => {
+ beforeEach(() => vi.clearAllMocks());
+
+ it('lists saved forwards ahead of the /peers/:id patterns', async () => {
+ const rows = [{ id: 'fwd_1', tcAddress: 'tcEX…wxyz', status: 'failed', lastError: 'startup timed out' }];
+ listTailcatForwards.mockResolvedValue(rows);
+ const res = await request(buildApp()).get('/api/instances/peers/tailcat/forwards');
+ expect(res.status).toBe(200);
+ expect(res.body).toEqual({ forwards: rows });
+ });
+
+ it('retries a saved forward and sanitizes the resulting peer', async () => {
+ const peer = { id: 'peer-example', transport: 'tailcat', address: '127.0.0.1', port: 15556 };
+ 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(instances.sanitizePeerForClient).toHaveBeenCalledWith(peer);
+ });
+
+ it('forgets a saved forward', async () => {
+ forgetTailcatForward.mockResolvedValue({ id: 'fwd_1', peerId: 'peer-example' });
+ const res = await request(buildApp()).delete('/api/instances/peers/tailcat/forwards/fwd_1');
+ expect(res.status).toBe(200);
+ expect(forgetTailcatForward).toHaveBeenCalledWith('fwd_1');
+ expect(res.body).toEqual({ id: 'fwd_1', peerId: 'peer-example' });
+ });
+});
diff --git a/server/services/instances.js b/server/services/instances.js
index 27228f4e55..4d5a92ff9e 100644
--- a/server/services/instances.js
+++ b/server/services/instances.js
@@ -525,6 +525,31 @@ export async function addPeer({ address, port = DEFAULT_PEER_PORT, name, host, a
return peer;
}
+/**
+ * Repoint a tailcat peer at a new loopback port.
+ *
+ * The public updatePeer deliberately owns no `port` field — a peer's address is
+ * how the operator reached it, not something the server rewrites. A managed
+ * tailcat forward is the exception: PortOS chose that loopback port itself, so
+ * when a retry has to bind a different one (the old port got taken while the
+ * forward was down) the peer record has to follow or every request keeps dialing
+ * a dead port. Restricted to `transport: 'tailcat'` for exactly that reason.
+ */
+export async function setTailcatPeerPort(id, port) {
+ if (!Number.isInteger(port) || port < 1 || port > 65535) return null;
+ const updated = await withData(async (data) => {
+ const peer = data.peers.find(p => p.id === id && p.transport === 'tailcat');
+ if (!peer || peer.port === port) return peer || null;
+ peer.port = port;
+ console.log(`🐈 Tailcat peer ${peer.name} repointed to 127.0.0.1:${port}`);
+ instanceEvents.emit('peers:updated', data.peers);
+ return peer;
+ });
+ // The relay pins the peer URL at connect time, so it has to redial the new port.
+ if (updated) disconnectFromPeer(id);
+ return updated;
+}
+
export async function removePeer(id, { stopTransport = true } = {}) {
disconnectFromPeer(id);
// Retire the transport outside the data lock: its lifecycle may itself need
diff --git a/server/services/tailcatPeer.js b/server/services/tailcatPeer.js
index 0d4ee1f239..ac8d71aec8 100644
--- a/server/services/tailcatPeer.js
+++ b/server/services/tailcatPeer.js
@@ -2,38 +2,53 @@
* Tailcat federated peers — connect to a remote PortOS over
* [tailcat](https://github.com/tailscale/tailcat) without a Tailscale account.
*
- * Flow: ensure the `tailcat` CLI is installed → start
- * `tailcat forward <tcADDR> LOCAL:5555` (preferred LOCAL=15555) → register a
- * normal peer at `127.0.0.1:LOCAL` over HTTP or explicitly selected HTTPS.
+ * Flow: ensure the `tailcat` CLI is installed → pre-warm the DERP map cache →
+ * start `tailcat forward <tcADDR> LOCAL:5555` (preferred LOCAL=15555) → register
+ * a normal peer at `127.0.0.1:LOCAL` over HTTP or explicitly selected HTTPS.
*
* The tc address is a bearer capability. Persist it only in the machine-local
- * forwards file for restart; never log the full value, never put it on the peer
- * record that clients or peers can scrape, and never ship it in docs/tests.
+ * forwards file for restart and retry; never log the full value, never put it on
+ * the peer record that clients or peers can scrape, never return it from an API
+ * response, and never ship it in docs/tests.
*/
+import { randomUUID } from 'node:crypto';
import { createServer } from 'node:net';
+import { stat } from 'node:fs/promises';
import { homedir } from 'node:os';
import { delimiter, join } from 'node:path';
import { spawn } from '../lib/childProcess.js';
-import { createLineReader } from '../lib/streamLines.js';
import { commandExists } from '../lib/commandExists.js';
import { bufferedSpawn, spawnFailureDetail } from '../lib/bufferedSpawn.js';
import { dataPath, readJSONFile, ensureDir, PATHS, atomicWrite } from '../lib/fileUtils.js';
import { createMutex } from '../lib/asyncMutex.js';
+import { isPortReachable } from '../lib/connectivity.js';
+import { isTestRunner } from '../lib/runtimeEnv.js';
import { findCommandOnPath, safeChildProcessEnv, safeChildProcessOptions } from '../lib/processEnv.js';
import {
DEFAULT_TAILCAT_LOCAL_PORT,
DEFAULT_TAILCAT_REMOTE_PORT,
} from '../lib/ports.js';
import { ServerError } from '../lib/errorHandler.js';
-import { addPeer, getPeers, removePeer as removeInstancePeer } from './instances.js';
+import {
+ addPeer,
+ getPeers,
+ removePeer as removeInstancePeer,
+ setTailcatPeerPort,
+} from './instances.js';
const FORWARDS_FILE = dataPath('tailcat-forwards.json');
const GO_INSTALL_PKG = 'github.com/tailscale/tailcat/cmd/tailcat@latest';
const BREW_FORMULA = 'tailcat';
const RELEASES_URL = 'https://github.com/tailscale/tailcat/releases';
+const DEFAULT_DERP_MAP_URL = 'https://tailcat.dev/derpmap.json';
const INSTALL_TIMEOUT_MS = 180_000;
const FORWARD_READY_MS = 8_000;
+const FORWARD_PROBE_INTERVAL_MS = 150;
+const DERP_MAP_FRESH_MS = 6 * 60 * 60 * 1000;
+const DERP_MAP_FETCH_TIMEOUT_MS = 15_000;
+const DIAGNOSTIC_TAIL_CHARS = 4096;
+const DIAGNOSTIC_MAX_CHARS = 320;
const PORT_SCAN_LIMIT = 32;
const DEFAULT_DATA = { version: 1, forwards: [] };
@@ -66,6 +81,24 @@ export function isValidTcAddress(tc) {
return /^tc[A-Za-z0-9_+\/=-]+$/.test(raw);
}
+/**
+ * Strip every capability-shaped token out of tailcat's own diagnostics, then
+ * bound them, so a startup failure can finally be *reported* to the operator
+ * instead of collapsing into an opaque "startup timed out". Redaction runs over
+ * the whole buffered tail at once, never per chunk, so an address split across
+ * reads is still caught after reassembly.
+ */
+export function redactTailcatDiagnostics(text) {
+ const lines = String(text || '')
+ // 8+ payload chars, so even a tail-truncated address fragment is scrubbed.
+ .replace(/tc[A-Za-z0-9_+\/=-]{8,}/g, 'tc…')
+ .split('\n')
+ .map((line) => line.trim())
+ .filter(Boolean);
+ const joined = lines.slice(-3).join(' | ');
+ return joined.length > DIAGNOSTIC_MAX_CHARS ? `${joined.slice(0, DIAGNOSTIC_MAX_CHARS)}…` : joined;
+}
+
async function loadForwards() {
const data = await readJSONFile(FORWARDS_FILE, DEFAULT_DATA, { strict: true, logError: false })
.catch(() => { throw new ServerError('Could not read tailcat forward storage', { status: 503 }); });
@@ -75,9 +108,107 @@ async function loadForwards() {
return data;
}
-async function saveForwards(data) {
+async function saveForwards(entries) {
await ensureDir(PATHS.data);
- await atomicWrite(FORWARDS_FILE, data);
+ await atomicWrite(FORWARDS_FILE, { version: 1, forwards: entries });
+}
+
+/**
+ * Normalize a stored entry. Installs written before retry support keyed entries
+ * by `peerId` alone with no `id`/`status`, so derive both rather than dropping
+ * a working forward. An entry without a usable capability is unusable — drop it.
+ */
+function normalizeForwardEntry(entry) {
+ if (!entry || typeof entry !== 'object') return null;
+ if (!isValidTcAddress(entry.tcAddress)) return null;
+ const peerId = typeof entry.peerId === 'string' && entry.peerId ? entry.peerId : null;
+ const status = ['active', 'failed', 'pending'].includes(entry.status)
+ ? entry.status
+ // A pre-retry entry only ever existed once its peer was registered.
+ : 'active';
+ return {
+ id: typeof entry.id === 'string' && entry.id ? entry.id : `fwd_${peerId || randomUUID()}`,
+ peerId,
+ tcAddress: entry.tcAddress,
+ localPort: Number.isInteger(entry.localPort) ? entry.localPort : null,
+ remotePort: Number.isInteger(entry.remotePort) ? entry.remotePort : DEFAULT_TAILCAT_REMOTE_PORT,
+ 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
+ // peer without the operator re-entering anything. Machine-local only.
+ auth: entry.auth && typeof entry.auth === 'object' ? entry.auth : null,
+ status,
+ lastError: typeof entry.lastError === 'string' ? entry.lastError : null,
+ lastErrorAt: typeof entry.lastErrorAt === 'string' ? entry.lastErrorAt : null,
+ createdAt: typeof entry.createdAt === 'string' ? entry.createdAt : new Date().toISOString(),
+ };
+}
+
+/** Read every stored forward, normalized. Internal — these carry the capability. */
+async function readForwards() {
+ const data = await loadForwards();
+ return data.forwards.map(normalizeForwardEntry).filter(Boolean);
+}
+
+async function upsertForward(entry) {
+ await withLock(async () => {
+ const entries = await readForwards();
+ await saveForwards([...entries.filter((f) => f.id !== entry.id), entry]);
+ });
+}
+
+/** Merge fields into one stored entry. No-op when the entry is already gone. */
+async function patchForward(id, patch) {
+ return withLock(async () => {
+ const entries = await readForwards();
+ const found = entries.find((f) => f.id === id);
+ if (!found) return null;
+ const next = { ...found, ...patch };
+ await saveForwards([...entries.filter((f) => f.id !== id), next]);
+ return next;
+ });
+}
+
+async function deleteForward(id) {
+ await withLock(async () => {
+ const entries = await readForwards();
+ await saveForwards(entries.filter((f) => f.id !== id));
+ });
+}
+
+/** Record why a forward is not running, so the next session can act on it. */
+async function markForwardFailed(id, error, patchFn = patchForward) {
+ const detail = redactTailcatDiagnostics(error?.message || String(error || 'unknown error'));
+ await patchFn(id, {
+ status: 'failed',
+ lastError: detail || 'unknown error',
+ lastErrorAt: new Date().toISOString(),
+ }).catch(() => null); // never mask the original failure with a bookkeeping one
+}
+
+/**
+ * Operator-facing view of the saved forwards: enough to see *which* peer cannot
+ * start and why, with the bearer capability replaced by its redacted form. This
+ * is what makes a failed add recoverable — the address stays on disk, so a retry
+ * never asks the operator for it again.
+ */
+export async function listTailcatForwards() {
+ const entries = await readForwards();
+ return entries.map((entry) => ({
+ id: entry.id,
+ peerId: entry.peerId,
+ tcAddress: redactTcAddress(entry.tcAddress),
+ localPort: entry.localPort,
+ remotePort: entry.remotePort,
+ name: entry.name,
+ protocol: entry.protocol,
+ hasAuth: !!entry.auth,
+ status: entry.status,
+ lastError: entry.lastError,
+ lastErrorAt: entry.lastErrorAt,
+ createdAt: entry.createdAt,
+ live: liveForwards.has(entry.id),
+ }));
}
/**
@@ -223,6 +354,82 @@ async function runInstallCommand(bin, args, extraEnv = {}) {
: spawnFailureDetail(result, `exit ${result.code}`));
}
+/** Go's `url.QueryEscape`, which is what names tailcat's DERP map cache files. */
+function goQueryEscape(value) {
+ return String(value).replace(/[^A-Za-z0-9\-_.~]/g, (char) => (char === ' '
+ ? '+'
+ : [...Buffer.from(char, 'utf8')].map((byte) => `%${byte.toString(16).toUpperCase().padStart(2, '0')}`).join('')));
+}
+
+/** The DERP map URL tailcat will use, honoring the env override it reads itself. */
+function derpMapUrl(env = process.env) {
+ return env.TAILCAT_DERPMAP_URL || DEFAULT_DERP_MAP_URL;
+}
+
+/**
+ * tailcat's own on-disk DERP map cache: `<user cache dir>/tailcat/derpmap-<escaped URL>.json`,
+ * whose mtime is the stored-at time. Mirrors Go's `os.UserCacheDir()` per platform.
+ */
+export function derpMapCachePath({
+ url = derpMapUrl(),
+ env = process.env,
+ home = homedir(),
+ platform = process.platform,
+} = {}) {
+ const base = platform === 'darwin' ? join(home, 'Library', 'Caches')
+ : platform === 'win32' ? (env.LOCALAPPDATA || join(home, 'AppData', 'Local'))
+ : (env.XDG_CACHE_HOME || join(home, '.cache'));
+ return join(base, 'tailcat', `derpmap-${goQueryEscape(url)}.json`);
+}
+
+/**
+ * Pre-warm tailcat's DERP map cache using PortOS's own HTTP stack.
+ *
+ * tailcat resolves a tc address's relay region by fetching that map with Go's
+ * HTTP client. On a host where a local network filter permits Node and curl but
+ * blocks Go's dialer, the fetch fails (`context deadline exceeded`, or the same
+ * `connect: bad file descriptor` that breaks `go install`) and **every** tailcat
+ * command dies before it can serve or dial — while PortOS reaches the identical
+ * URL fine. Writing the map into the cache tailcat already reads makes the CLI
+ * work without needing the network itself.
+ *
+ * Strictly best-effort and never fatal: any failure just leaves tailcat to fetch
+ * the map the way it normally would. `fetchFn` defaults to null under the test
+ * runner so a suite can never reach the network by forgetting to inject it.
+ */
+export async function primeDerpMapCache({
+ url = derpMapUrl(),
+ cachePath = derpMapCachePath(),
+ fetchFn = isTestRunner() ? null : fetch,
+ statFn = stat,
+ writeFn = atomicWrite,
+ freshMs = DERP_MAP_FRESH_MS,
+ now = Date.now(),
+} = {}) {
+ if (!fetchFn) return { primed: false, reason: 'no-fetch' };
+ const cachedAt = await statFn(cachePath).then((info) => info.mtimeMs, () => null);
+ if (cachedAt !== null && now - cachedAt < freshMs) return { primed: false, reason: 'fresh' };
+
+ const body = await fetchFn(url, { signal: AbortSignal.timeout(DERP_MAP_FETCH_TIMEOUT_MS) })
+ .then((res) => (res.ok ? res.text() : null))
+ .catch(() => null);
+ // Only a parseable map goes in — never poison the cache with an error page.
+ if (!safeParseJson(body)) return { primed: false, reason: 'unavailable' };
+
+ const written = await writeFn(cachePath, body).then(() => true, () => false);
+ if (written) console.log(`🐈 Primed tailcat DERP map cache (${body.length} bytes) for ${url}`);
+ return { primed: written, reason: written ? 'written' : 'write-failed' };
+}
+
+function safeParseJson(text) {
+ try {
+ const value = JSON.parse(text);
+ return value && typeof value === 'object' ? value : null;
+ } catch {
+ return null; // an error page or truncated body is not a DERP map
+ }
+}
+
/** True when nothing is listening on 127.0.0.1:port (or bind fails for other reasons → busy). */
export function isLocalPortFree(port, { createServerFn = createServer } = {}) {
return new Promise((resolve) => {
@@ -261,7 +468,15 @@ export async function allocateLocalPort({
/**
* Start `tailcat forward <tc> local:remote`. Injected `spawnFn` for tests.
- * Resolves only after the CLI confirms that the requested listener is bound.
+ * Resolves only once the requested local listener is actually bound.
+ *
+ * Readiness has two independent signals, because relying on the log line alone
+ * silently broke against a released CLI: tailcat ≤0.5.0 emits `forwarding …`
+ * through its verbose-only logger, so an add against that build timed out after
+ * 8s even though the listener was up and healthy. `--verbose` restores the line
+ * on those builds (and is what surfaces per-connection dial failures at all),
+ * while the connect probe confirms the same fact without depending on any log
+ * wording, so a future CLI reword cannot regress this again.
*/
export async function startForwardProcess({
bin,
@@ -270,6 +485,10 @@ export async function startForwardProcess({
remotePort = DEFAULT_TAILCAT_REMOTE_PORT,
spawnFn = spawn,
readyMs = FORWARD_READY_MS,
+ // A connect probe, never a bind: a bind would hold the port while tailcat is
+ // still trying to claim it and could kill the CLI with EADDRINUSE.
+ isListening = (port) => isPortReachable({ port }),
+ probeMs = FORWARD_PROBE_INTERVAL_MS,
} = {}) {
if (!isValidTcAddress(tcAddress)) {
throw new ServerError('Invalid tailcat address — paste a tc… address from the peer', {
@@ -277,30 +496,45 @@ export async function startForwardProcess({
});
}
if (shuttingDown) throw new Error('PortOS is shutting down');
- const child = spawnFn(bin, ['forward', '--bind=127.0.0.1', tcAddress.trim(), `${localPort}:${remotePort}`],
+ const child = spawnFn(bin, ['forward', '--verbose', '--bind=127.0.0.1', tcAddress.trim(), `${localPort}:${remotePort}`],
safeChildProcessOptions({ env: safeChildProcessEnv(), stdio: ['ignore', 'pipe', 'pipe'] }));
ownedChildren.add(child);
child.stdout?.on('data', () => {});
+
+ // tailcat's own diagnostics can contain the bearer capability, so the raw tail
+ // is bounded, redacted on the way into an error, and no longer accumulated once
+ // we are past startup — it is never retained and never surfaced unredacted.
+ let tail = '';
+ let settled = false;
+ const readyPattern = new RegExp(`forwarding 127\\.0\\.0\\.1:${localPort} -> remote localhost:${remotePort}(?![0-9])`);
+
await new Promise((resolve, reject) => {
- let settled = false;
- let reader;
const finish = (error) => {
if (settled) return;
settled = true;
clearTimeout(timer);
- reader = null;
- // Diagnostics can contain the bearer capability, including across chunks.
- // Drain them, but never expose them in errors or retain them after startup.
+ clearInterval(poller);
+ const diagnostics = error ? redactTailcatDiagnostics(tail) : '';
+ tail = '';
if (error) {
+ if (diagnostics) error.message = `${error.message} — tailcat said: ${diagnostics}`;
try { child.kill('SIGTERM'); } catch { /* process event boundary */ }
reject(error);
} else resolve();
};
const timer = setTimeout(() => finish(new Error('tailcat listener startup timed out')), readyMs);
- 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));
+ // The connect probe is the version-independent half: a loopback port that
+ // accepts a connection is a port tailcat is listening on, whatever it logged.
+ const poller = setInterval(() => {
+ isListening(localPort).then((listening) => { if (listening) finish(); }, () => {});
+ }, probeMs);
+ // Stays attached past startup so the pipe keeps draining, but stops
+ // accumulating: settled means the capability bytes are no longer kept.
+ child.stderr?.on('data', (chunk) => {
+ if (settled) return;
+ tail = (tail + String(chunk)).slice(-DIAGNOSTIC_TAIL_CHARS);
+ if (readyPattern.test(tail)) finish();
+ });
child.on('error', () => finish(new Error('tailcat forward process failed')));
child.once('exit', (code, signal) => {
ownedChildren.delete(child);
@@ -315,29 +549,35 @@ export async function startForwardProcess({
return child;
}
-async function persistForward(entry) {
- await withLock(async () => {
- const data = await loadForwards();
- const forwards = Array.isArray(data.forwards) ? data.forwards.filter((f) => f.peerId !== entry.peerId) : [];
- forwards.push(entry);
- await saveForwards({ version: 1, forwards });
+export function stopForwardForPeer(peerId) {
+ return withLifecycle(async () => {
+ const entries = await readForwards();
+ const entry = entries.find((f) => f.peerId === peerId);
+ if (!entry) return;
+ killLiveForward(entry.id);
+ await deleteForward(entry.id);
});
}
-async function forgetForward(peerId) {
- await withLock(async () => {
- const data = await loadForwards();
- const forwards = (Array.isArray(data.forwards) ? data.forwards : []).filter((f) => f.peerId !== peerId);
- await saveForwards({ version: 1, forwards });
+/** Forget a saved forward outright — stops it and drops its stored capability. */
+export function forgetTailcatForward(id, { removePeerFn = removeInstancePeer } = {}) {
+ return withLifecycle(async () => {
+ const entries = await readForwards();
+ const entry = entries.find((f) => f.id === id);
+ if (!entry) throw new ServerError('Tailcat forward not found', { status: 404 });
+ killLiveForward(id);
+ await deleteForward(id);
+ if (entry.peerId) {
+ // stopTransport:false — this lifecycle operation already owns the child
+ // and just dropped the metadata, so re-entering it would deadlock.
+ await removePeerFn(entry.peerId, { stopTransport: false });
+ }
+ return { id, peerId: entry.peerId };
});
}
-export function stopForwardForPeer(peerId) {
- return withLifecycle(() => stopForward(peerId));
-}
-
-async function stopForward(peerId) {
- const live = liveForwards.get(peerId);
+function killLiveForward(id) {
+ const live = liveForwards.get(id);
if (live?.child && !live.child.killed) {
try {
live.child.kill('SIGTERM');
@@ -345,8 +585,15 @@ async function stopForward(peerId) {
// best-effort
}
}
- await forgetForward(peerId);
- liveForwards.delete(peerId);
+ liveForwards.delete(id);
+}
+
+/** Track a started child so shutdown and retry can find it again. */
+function trackForward(id, child, localPort, remotePort) {
+ liveForwards.set(id, { child, localPort, remotePort });
+ child.on('exit', () => {
+ if (liveForwards.get(id)?.child === child) liveForwards.delete(id);
+ });
}
/**
@@ -364,10 +611,12 @@ async function addTailcatPeer({
auth,
protocol = 'http',
ensureInstalled = ensureTailcatInstalled,
+ primeDerpMap = primeDerpMapCache,
allocatePort = allocateLocalPort,
startForward = startForwardProcess,
addPeerFn = addPeer,
- persistForwardEntry = persistForward,
+ persistForwardEntry = upsertForward,
+ patchForwardEntry = patchForward,
removePeerFn = removeInstancePeer,
} = {}) {
const trimmed = String(tcAddress || '').trim();
@@ -379,13 +628,67 @@ async function addTailcatPeer({
}
if (shuttingDown) throw new Error('PortOS is shutting down');
+
+ // Save the capability BEFORE anything can fail. A forward that never starts
+ // then stays retryable from the UI instead of throwing the operator's pasted
+ // address away and making them fetch it from the remote a second time.
+ const entry = {
+ id: `fwd_${randomUUID()}`,
+ peerId: null,
+ tcAddress: trimmed,
+ localPort: null,
+ remotePort: DEFAULT_TAILCAT_REMOTE_PORT,
+ name: name || null,
+ protocol: protocol === 'https' ? 'https' : 'http',
+ auth: auth && typeof auth === 'object' ? auth : null,
+ status: 'pending',
+ lastError: null,
+ lastErrorAt: null,
+ createdAt: new Date().toISOString(),
+ };
+ await persistForwardEntry(entry).catch(() => {
+ throw new ServerError('Could not save tailcat forward; nothing was started', {
+ status: 503, code: 'TAILCAT_PERSIST_FAILED',
+ });
+ });
+
+ const peer = await startAndRegister({
+ entry, ensureInstalled, primeDerpMap, allocatePort, startForward, addPeerFn,
+ patchForwardEntry, removePeerFn,
+ }).catch(async (err) => {
+ await markForwardFailed(entry.id, err, patchForwardEntry);
+ throw err;
+ });
+ return peer;
+}
+
+/**
+ * Shared body of add and retry: bring the forward up, make sure a peer points at
+ * it, and record the outcome. Callers own the failure bookkeeping.
+ */
+async function startAndRegister({
+ entry,
+ existingPeer = null,
+ ensureInstalled,
+ primeDerpMap,
+ allocatePort,
+ startForward,
+ addPeerFn,
+ patchForwardEntry,
+ removePeerFn,
+ setPeerPortFn = setTailcatPeerPort,
+}) {
const { bin } = await ensureInstalled();
- const localPort = await allocatePort();
+ // Best-effort, and deliberately before the spawn: on a host whose filter
+ // blocks Go's dialer this is the difference between a working tunnel and a
+ // CLI that cannot resolve its own relay.
+ await primeDerpMap().catch(() => null);
const remotePort = DEFAULT_TAILCAT_REMOTE_PORT;
+ const localPort = await allocatePort({ preferred: entry.localPort || DEFAULT_TAILCAT_LOCAL_PORT });
let child;
try {
- child = await startForward({ bin, tcAddress: trimmed, localPort, remotePort });
+ child = await startForward({ bin, tcAddress: entry.tcAddress, localPort, remotePort });
} catch (err) {
throw new ServerError(
`Could not start tailcat forward: ${err.message}`,
@@ -394,47 +697,95 @@ async function addTailcatPeer({
}
ownedChildren.add(child);
- child.once('exit', () => ownedChildren.delete(child));
- let peer;
+ let peer = existingPeer;
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,
- });
+ if (peer) {
+ // A reallocated port has to reach the peer record too, or every request
+ // would keep dialing the port the dead forward used to hold.
+ if (peer.port !== localPort) peer = await setPeerPortFn(peer.id, localPort) || peer;
+ } else {
+ peer = await addPeerFn({
+ address: '127.0.0.1',
+ port: localPort,
+ name: entry.name || `tailcat:${redactTcAddress(entry.tcAddress)}`,
+ auth: entry.auth || undefined,
+ transport: 'tailcat',
+ protocol: entry.protocol,
+ });
+ }
} catch (err) {
try { child.kill('SIGTERM'); } catch { /* ignore */ }
throw err;
}
- await persistForwardEntry({
+ // A vanished entry (null) counts as a failed save: the restart mapping is the
+ // thing being persisted, and a peer without one cannot come back after a boot.
+ const patched = await patchForwardEntry(entry.id, {
peerId: peer.id,
- tcAddress: trimmed,
localPort,
remotePort,
- createdAt: new Date().toISOString(),
- }).then(() => {
- if (shuttingDown) throw new Error('PortOS is shutting down');
- }).catch(async () => {
+ status: 'active',
+ lastError: null,
+ lastErrorAt: null,
+ }).then((result) => result !== null, () => false);
+ if (!patched || shuttingDown) {
child.kill('SIGTERM');
- // 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 });
+ if (!existingPeer) {
+ // 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 });
+ trackForward(entry.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)})`);
+ console.log(`🐈 tailcat forward stopped for peer ${peer.id} (${redactTcAddress(entry.tcAddress)})`);
});
+ return peer;
+}
+
+/**
+ * Retry a saved forward using the capability already on disk. This is the whole
+ * point of persisting it: an operator (or an agent debugging the install) can
+ * bring a failed peer up without ever handling the tc address again.
+ */
+export function retryTailcatForward(id, options = {}) {
+ return withLifecycle(() => retryForward(id, options));
+}
+
+async function retryForward(id, {
+ ensureInstalled = ensureTailcatInstalled,
+ primeDerpMap = primeDerpMapCache,
+ allocatePort = allocateLocalPort,
+ startForward = startForwardProcess,
+ addPeerFn = addPeer,
+ patchForwardEntry = patchForward,
+ removePeerFn = removeInstancePeer,
+ getPeersFn = getPeers,
+ setPeerPortFn = setTailcatPeerPort,
+} = {}) {
+ if (shuttingDown) throw new Error('PortOS is shutting down');
+ const entries = await readForwards();
+ const entry = entries.find((f) => f.id === id);
+ if (!entry) throw new ServerError('Tailcat forward not found', { status: 404 });
+
+ // A live child on a stale mapping would keep the port and mask the retry.
+ killLiveForward(entry.id);
+ const peers = await getPeersFn();
+ const existingPeer = entry.peerId ? peers.find((p) => p.id === entry.peerId) || null : null;
+ const peer = await startAndRegister({
+ entry, existingPeer, ensureInstalled, primeDerpMap, allocatePort, startForward,
+ addPeerFn, patchForwardEntry, removePeerFn, setPeerPortFn,
+ }).catch(async (err) => {
+ await markForwardFailed(entry.id, err, patchForwardEntry);
+ throw err;
+ });
+ console.log(`🐈 tailcat forward retried for peer ${peer.id} (${redactTcAddress(entry.tcAddress)})`);
return peer;
}
@@ -445,12 +796,12 @@ export function restoreForwards(options = {}) {
async function restoreTailcatForwards({
ensureInstalled = ensureTailcatInstalled,
+ primeDerpMap = primeDerpMapCache,
startForward = startForwardProcess,
getPeersFn = getPeers,
} = {}) {
if (shuttingDown) return { restored: 0 };
- const data = await loadForwards();
- const forwards = Array.isArray(data.forwards) ? data.forwards : [];
+ const forwards = await readForwards();
if (forwards.length === 0) return { restored: 0 };
let bin;
@@ -460,36 +811,33 @@ async function restoreTailcatForwards({
console.log(`⚠️ tailcat restore skipped — ${err.message}`);
return { restored: 0, error: err.message };
}
+ await primeDerpMap().catch(() => null);
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'
+ 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;
- if (liveForwards.has(entry.peerId)) continue;
+ if (liveForwards.has(entry.id)) continue;
try {
const child = await startForward({
bin,
tcAddress: entry.tcAddress,
- localPort: entry.localPort || DEFAULT_TAILCAT_LOCAL_PORT,
- remotePort: entry.remotePort || DEFAULT_TAILCAT_REMOTE_PORT,
- });
- liveForwards.set(entry.peerId, {
- child,
localPort: entry.localPort,
- remotePort: entry.remotePort || DEFAULT_TAILCAT_REMOTE_PORT,
- });
- child.on('exit', () => {
- if (liveForwards.get(entry.peerId)?.child === child) liveForwards.delete(entry.peerId);
+ remotePort: entry.remotePort,
});
+ trackForward(entry.id, child, entry.localPort, entry.remotePort);
+ await patchForward(entry.id, { status: 'active', lastError: null, lastErrorAt: null }).catch(() => null);
restored += 1;
} catch (err) {
- console.log(`⚠️ tailcat restore failed for peer ${entry.peerId}`);
+ // Keep the reason on the entry: a boot-time failure is exactly the case
+ // nobody is watching, and the retry UI is the only place it resurfaces.
+ console.log(`⚠️ tailcat restore failed for peer ${entry.peerId} — ${redactTailcatDiagnostics(err.message)}`);
+ await markForwardFailed(entry.id, err);
}
}
if (restored > 0) console.log(`🐈 Restored ${restored} tailcat forward(s)`);
@@ -516,4 +864,3 @@ export function _resetLiveForwardsForTests() {
export function _liveForwardCountForTests() {
return liveForwards.size;
}
-
diff --git a/server/services/tailcatPeer.test.js b/server/services/tailcatPeer.test.js
index 2914c1c6de..77c1f2f01e 100644
--- a/server/services/tailcatPeer.test.js
+++ b/server/services/tailcatPeer.test.js
@@ -11,6 +11,12 @@ import {
allocateLocalPort,
startForwardProcess,
addPeerViaTailcat,
+ listTailcatForwards,
+ retryTailcatForward,
+ forgetTailcatForward,
+ redactTailcatDiagnostics,
+ derpMapCachePath,
+ primeDerpMapCache,
_resetLiveForwardsForTests,
_liveForwardCountForTests,
stopAllForwards,
@@ -257,12 +263,14 @@ describe('tailcatPeer helpers', () => {
localPort: 15555,
remotePort: 5555,
spawnFn,
- readyMs: 10,
+ readyMs: 200,
+ probeMs: 5,
+ isListening: async () => false,
});
expect(started).toBe(child);
expect(spawnFn).toHaveBeenCalledWith(
'/usr/bin/tailcat',
- ['forward', '--bind=127.0.0.1', EXAMPLE_TC, '15555:5555'],
+ ['forward', '--verbose', '--bind=127.0.0.1', EXAMPLE_TC, '15555:5555'],
expect.any(Object)
);
});
@@ -280,6 +288,7 @@ describe('tailcatPeer helpers', () => {
localPort: 15555,
spawnFn,
readyMs: 5_000,
+ isListening: async () => false,
})).rejects.toThrow(/exited early/);
});
@@ -287,7 +296,7 @@ describe('tailcatPeer helpers', () => {
vi.useFakeTimers();
const child = fakeChild();
const result = startForwardProcess({ bin: 'tailcat', tcAddress: EXAMPLE_TC,
- localPort: 15555, spawnFn: () => child, readyMs: 8000 });
+ localPort: 15555, spawnFn: () => child, readyMs: 8000, isListening: async () => false });
const assertion = expect(result).rejects.toThrow('startup timed out');
await vi.advanceTimersByTimeAsync(8000);
await assertion;
@@ -298,11 +307,15 @@ describe('tailcatPeer helpers', () => {
it('never exposes capability diagnostics across repeated or split chunks', async () => {
const child = fakeChild();
const result = startForwardProcess({ bin: 'tailcat', tcAddress: EXAMPLE_TC,
- localPort: 15555, spawnFn: () => child });
+ localPort: 15555, spawnFn: () => child, isListening: async () => false });
child.stderr.emit('data', EXAMPLE_TC.slice(0, 10));
child.stderr.emit('data', EXAMPLE_TC.slice(10) + EXAMPLE_TC);
child.emit('error', new Error(EXAMPLE_TC));
- await expect(result).rejects.toThrow(/^tailcat forward process failed$/);
+ // The message now carries tailcat's own (redacted) diagnostics, which is the
+ // whole point — but never the capability itself, however it was chunked.
+ const failure = await result.catch((err) => err);
+ expect(failure.message).toContain('tailcat forward process failed');
+ expect(failure.message).not.toContain('tcEXAMPLE');
});
it('addPeerViaTailcat installs, forwards, and registers loopback peer', async () => {
@@ -315,7 +328,9 @@ describe('tailcatPeer helpers', () => {
allocatePort: async () => 15555,
startForward: async () => child,
addPeerFn,
+ primeDerpMap: async () => ({ primed: false }),
persistForwardEntry: async () => {},
+ patchForwardEntry: async () => ({}),
});
expect(addPeerFn).toHaveBeenCalledWith({
address: '127.0.0.1',
@@ -346,7 +361,9 @@ describe('tailcat lifecycle failure contracts', () => {
allocatePort: async () => 15555,
startForward: async () => child,
addPeerFn: async (data) => ({ id: 'peer-example', ...data }),
+ primeDerpMap: async () => ({ primed: false }),
persistForwardEntry: async () => {},
+ patchForwardEntry: async () => ({}),
...overrides,
};
}
@@ -355,7 +372,7 @@ describe('tailcat lifecycle failure contracts', () => {
vi.useFakeTimers();
const child = fakeChild();
const pending = startForwardProcess({ bin: 'tailcat', tcAddress: EXAMPLE_TC,
- localPort: 15555, spawnFn: () => child, readyMs: 8000 });
+ localPort: 15555, spawnFn: () => child, readyMs: 8000, isListening: async () => false });
const failure = expect(pending).rejects.toThrow('startup timed out');
await vi.advanceTimersByTimeAsync(7999);
expect(child.kill).not.toHaveBeenCalled();
@@ -368,7 +385,8 @@ describe('tailcat lifecycle failure contracts', () => {
const child = fakeChild();
let ready = false;
const pending = startForwardProcess({ bin: 'tailcat', tcAddress: EXAMPLE_TC,
- localPort: 15555, spawnFn: () => child }).then(() => { ready = true; });
+ localPort: 15555, 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();
expect(ready).toBe(false);
@@ -381,7 +399,7 @@ describe('tailcat lifecycle failure contracts', () => {
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 });
+ localPort: 15555, spawnFn: () => child, isListening: async () => false });
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);
@@ -393,7 +411,7 @@ describe('tailcat lifecycle failure contracts', () => {
const child = fakeChild();
const removePeerFn = vi.fn().mockResolvedValue(undefined);
await expect(addPeerViaTailcat(addOptions(child, {
- persistForwardEntry: async () => { throw new Error('disk full'); }, removePeerFn,
+ patchForwardEntry: 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);
@@ -419,19 +437,249 @@ describe('tailcat lifecycle failure contracts', () => {
});
it('restores only mappings that still belong to existing managed peers, and retires them on removal', async () => {
+ // Pre-retry entries carried no id/status, so restore must still recognize them.
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 };
+ const options = {
+ ensureInstalled: async () => ({ bin: 'tailcat' }),
+ primeDerpMap: async () => ({ primed: false }),
+ 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' }],
+ // Removing the peer drops only its own mapping; the stale one stays put.
+ const [, written] = atomicWrite.mock.calls.at(-1);
+ expect(written.version).toBe(1);
+ expect(written.forwards).toHaveLength(1);
+ expect(written.forwards[0]).toMatchObject({ peerId: 'deleted-peer', tcAddress: EXAMPLE_TC });
+ });
+
+ it('records why a boot-time restore failed so the retry surface can show it', async () => {
+ const entry = { id: 'fwd_1', peerId: 'peer-example', tcAddress: EXAMPLE_TC, localPort: 15555, remotePort: 5555 };
+ readJSONFile.mockResolvedValue({ version: 1, forwards: [entry] });
+ await expect(restoreForwards({
+ ensureInstalled: async () => ({ bin: 'tailcat' }),
+ primeDerpMap: async () => ({ primed: false }),
+ startForward: async () => { throw new Error(`could not dial ${EXAMPLE_TC}`); },
+ getPeersFn: async () => [{ id: 'peer-example', transport: 'tailcat', address: '127.0.0.1', port: 15555 }],
+ })).resolves.toEqual({ restored: 0 });
+ const [, written] = atomicWrite.mock.calls.at(-1);
+ expect(written.forwards[0]).toMatchObject({ id: 'fwd_1', status: 'failed' });
+ expect(written.forwards[0].lastError).toContain('could not dial');
+ expect(written.forwards[0].lastError).not.toContain('tcEXAMPLE');
+ });
+});
+
+describe('saved tailcat forwards', () => {
+ beforeEach(() => {
+ _resetLiveForwardsForTests();
+ vi.clearAllMocks();
+ readJSONFile.mockResolvedValue({ version: 1, forwards: [] });
+ });
+ afterEach(() => { _resetLiveForwardsForTests(); });
+
+ it('saves the capability before anything can fail, so a broken add stays retryable', async () => {
+ const saved = [];
+ await expect(addPeerViaTailcat({
+ tcAddress: EXAMPLE_TC,
+ name: 'sandbox',
+ ensureInstalled: async () => { throw new Error('tailcat is not installed'); },
+ persistForwardEntry: async (entry) => { saved.push(entry); },
+ patchForwardEntry: async () => ({}),
+ })).rejects.toThrow('tailcat is not installed');
+ expect(saved).toHaveLength(1);
+ expect(saved[0]).toMatchObject({ tcAddress: EXAMPLE_TC, name: 'sandbox', status: 'pending', peerId: null });
+ });
+
+ it('never lets the capability out through the list endpoint', async () => {
+ readJSONFile.mockResolvedValue({ version: 1, forwards: [{
+ id: 'fwd_1', peerId: 'peer-1', tcAddress: EXAMPLE_TC, localPort: 15555, remotePort: 5555,
+ name: 'sandbox', protocol: 'https', auth: { username: 'u', password: 'p' },
+ status: 'failed', lastError: 'tailcat listener startup timed out', createdAt: '2026-01-01T00:00:00.000Z',
+ }] });
+ const [row] = await listTailcatForwards();
+ expect(row).toMatchObject({
+ id: 'fwd_1', peerId: 'peer-1', localPort: 15555, protocol: 'https',
+ hasAuth: true, status: 'failed', live: false,
+ });
+ expect(row.tcAddress).toBe(redactTcAddress(EXAMPLE_TC));
+ expect(JSON.stringify(row)).not.toContain(EXAMPLE_TC);
+ // The stored Basic credential is a secret too — presence only, never a value.
+ expect(JSON.stringify(row)).not.toContain('password');
+ });
+
+ it('retries from the stored address without the operator supplying it again', async () => {
+ readJSONFile.mockResolvedValue({ version: 1, forwards: [{
+ id: 'fwd_1', peerId: null, tcAddress: EXAMPLE_TC, localPort: null, remotePort: 5555,
+ name: 'sandbox', protocol: 'https', status: 'failed', lastError: 'startup timed out',
+ }] });
+ const child = fakeChild();
+ const startForward = vi.fn().mockResolvedValue(child);
+ const addPeerFn = vi.fn(async (data) => ({ id: 'peer-9', ...data }));
+ const patches = [];
+ const peer = await retryTailcatForward('fwd_1', {
+ ensureInstalled: async () => ({ bin: '/example/bin/tailcat' }),
+ primeDerpMap: async () => ({ primed: true }),
+ allocatePort: async () => 15556,
+ startForward,
+ addPeerFn,
+ patchForwardEntry: async (id, patch) => { patches.push([id, patch]); return { id, ...patch }; },
+ getPeersFn: async () => [],
});
+ expect(startForward).toHaveBeenCalledWith(expect.objectContaining({ tcAddress: EXAMPLE_TC, localPort: 15556 }));
+ expect(addPeerFn).toHaveBeenCalledWith(expect.objectContaining({
+ address: '127.0.0.1', port: 15556, name: 'sandbox', transport: 'tailcat', protocol: 'https',
+ }));
+ expect(peer.id).toBe('peer-9');
+ expect(patches).toEqual([['fwd_1', expect.objectContaining({ peerId: 'peer-9', status: 'active', lastError: null })]]);
+ });
+
+ it('repoints an existing peer when a retry has to bind a different port', async () => {
+ readJSONFile.mockResolvedValue({ version: 1, forwards: [{
+ id: 'fwd_1', peerId: 'peer-1', tcAddress: EXAMPLE_TC, localPort: 15555, remotePort: 5555,
+ }] });
+ const addPeerFn = vi.fn();
+ const setPeerPort = vi.fn(async (id, port) => ({ id, port, transport: 'tailcat' }));
+ const peer = await retryTailcatForward('fwd_1', {
+ ensureInstalled: async () => ({ bin: 'tailcat' }),
+ primeDerpMap: async () => ({ primed: false }),
+ allocatePort: async () => 15557,
+ startForward: async () => fakeChild(),
+ addPeerFn,
+ patchForwardEntry: async (id, patch) => ({ id, ...patch }),
+ getPeersFn: async () => [{ id: 'peer-1', transport: 'tailcat', address: '127.0.0.1', port: 15555 }],
+ setPeerPortFn: setPeerPort,
+ });
+ // Re-registering would create a duplicate peer; the record has to follow the port.
+ expect(addPeerFn).not.toHaveBeenCalled();
+ expect(setPeerPort).toHaveBeenCalledWith('peer-1', 15557);
+ expect(peer.port).toBe(15557);
+ });
+
+ it('records a redacted reason when a retry fails again', async () => {
+ readJSONFile.mockResolvedValue({ version: 1, forwards: [{
+ id: 'fwd_1', peerId: null, tcAddress: EXAMPLE_TC, localPort: 15555, remotePort: 5555,
+ }] });
+ const patches = [];
+ await expect(retryTailcatForward('fwd_1', {
+ ensureInstalled: async () => ({ bin: 'tailcat' }),
+ primeDerpMap: async () => ({ primed: false }),
+ allocatePort: async () => 15555,
+ startForward: async () => { throw new Error(`no relay for ${EXAMPLE_TC}`); },
+ patchForwardEntry: async (id, patch) => { patches.push(patch); return { id, ...patch }; },
+ getPeersFn: async () => [],
+ })).rejects.toMatchObject({ code: 'TAILCAT_FORWARD_FAILED' });
+ expect(patches.at(-1)).toMatchObject({ status: 'failed' });
+ expect(patches.at(-1).lastError).toContain('no relay');
+ expect(patches.at(-1).lastError).not.toContain('tcEXAMPLE');
+ });
+
+ it('rejects a retry for an unknown forward instead of inventing one', async () => {
+ await expect(retryTailcatForward('fwd_missing')).rejects.toMatchObject({ status: 404 });
+ });
+
+ it('forget removes the stored capability along with its peer', async () => {
+ readJSONFile.mockResolvedValue({ version: 1, forwards: [{
+ id: 'fwd_1', peerId: 'peer-1', tcAddress: EXAMPLE_TC, localPort: 15555, remotePort: 5555,
+ }] });
+ const removePeerFn = vi.fn().mockResolvedValue({ id: 'peer-1' });
+ await expect(forgetTailcatForward('fwd_missing', { removePeerFn })).rejects.toMatchObject({ status: 404 });
+ await expect(forgetTailcatForward('fwd_1', { removePeerFn })).resolves.toEqual({ id: 'fwd_1', peerId: 'peer-1' });
+ expect(removePeerFn).toHaveBeenCalledWith('peer-1', { stopTransport: false });
+ const [, written] = atomicWrite.mock.calls.at(-1);
+ expect(written.forwards).toEqual([]);
+ });
+});
+
+describe('tailcat startup diagnostics and DERP map priming', () => {
+ beforeEach(() => { _resetLiveForwardsForTests(); vi.clearAllMocks(); });
+ afterEach(() => { _resetLiveForwardsForTests(); });
+
+ it('scrubs capability tokens out of diagnostics but keeps the reason readable', () => {
+ const text = `Expand: fetching DERPMap for region -1: context deadline exceeded\ndial ${EXAMPLE_TC}: refused`;
+ const redacted = redactTailcatDiagnostics(text);
+ expect(redacted).toContain('fetching DERPMap');
+ expect(redacted).toContain('refused');
+ expect(redacted).not.toContain('tcEXAMPLE');
+ expect(redactTailcatDiagnostics('')).toBe('');
+ });
+
+ it('reports what tailcat said when startup times out, instead of only that it did', async () => {
+ vi.useFakeTimers();
+ const child = fakeChild();
+ const pending = startForwardProcess({ bin: 'tailcat', tcAddress: EXAMPLE_TC, localPort: 15555,
+ spawnFn: () => child, readyMs: 8000, isListening: async () => false });
+ const assertion = expect(pending).rejects.toThrow(/fetching DERPMap/);
+ child.stderr.emit('data', 'Expand: fetching DERPMap for region -1: context deadline exceeded\n');
+ await vi.advanceTimersByTimeAsync(8000);
+ await assertion;
+ vi.useRealTimers();
+ });
+
+ it('accepts a listening local port as readiness, so a quiet CLI build still works', async () => {
+ // tailcat <=0.5.0 logs `forwarding …` only under --verbose; readiness must not
+ // depend on any log wording, or a released build times out while working fine.
+ const child = fakeChild();
+ let probes = 0;
+ await expect(startForwardProcess({
+ bin: 'tailcat', tcAddress: EXAMPLE_TC, localPort: 15555, spawnFn: () => child,
+ readyMs: 2_000, probeMs: 5,
+ // First probe: nothing listening yet. Second: the listener is up.
+ isListening: async () => { probes += 1; return probes > 1; },
+ })).resolves.toBe(child);
+ });
+
+ it('names the DERP map cache file the way tailcat does, per platform', () => {
+ expect(derpMapCachePath({
+ url: 'https://example.com/derpmap.json', platform: 'darwin', home: '/example/home', env: {},
+ })).toBe('/example/home/Library/Caches/tailcat/derpmap-https%3A%2F%2Fexample.com%2Fderpmap.json.json');
+ expect(derpMapCachePath({
+ url: 'https://example.com/derpmap.json', platform: 'linux', home: '/example/home',
+ env: { XDG_CACHE_HOME: '/example/cache' },
+ })).toBe('/example/cache/tailcat/derpmap-https%3A%2F%2Fexample.com%2Fderpmap.json.json');
+ });
+
+ it('primes the DERP map with PortOS own fetch, but never caches a non-map body', async () => {
+ const writes = [];
+ const write = async (path, body) => { writes.push([path, body]); };
+ const missing = async () => { throw new Error('ENOENT'); };
+ await expect(primeDerpMapCache({
+ cachePath: '/example/cache/derpmap.json',
+ fetchFn: async () => ({ ok: true, text: async () => '{"Regions":{"1":{}}}' }),
+ statFn: missing, writeFn: write,
+ })).resolves.toMatchObject({ primed: true });
+ expect(writes).toEqual([['/example/cache/derpmap.json', '{"Regions":{"1":{}}}']]);
+
+ writes.length = 0;
+ await expect(primeDerpMapCache({
+ cachePath: '/example/cache/derpmap.json',
+ fetchFn: async () => ({ ok: true, text: async () => '<html>gateway timeout</html>' }),
+ statFn: missing, writeFn: write,
+ })).resolves.toMatchObject({ primed: false, reason: 'unavailable' });
+ expect(writes).toEqual([]);
+ });
+
+ it('skips the fetch entirely while the cached map is still fresh', async () => {
+ const fetchFn = vi.fn();
+ await expect(primeDerpMapCache({
+ cachePath: '/example/cache/derpmap.json',
+ statFn: async () => ({ mtimeMs: 1_000 }),
+ fetchFn,
+ now: 2_000,
+ freshMs: 10_000,
+ })).resolves.toMatchObject({ primed: false, reason: 'fresh' });
+ expect(fetchFn).not.toHaveBeenCalled();
+ });
+
+ it('never reaches the network from a suite that forgot to inject a fetch', async () => {
+ await expect(primeDerpMapCache({ cachePath: '/example/cache/derpmap.json', statFn: async () => { throw new Error('ENOENT'); } }))
+ .resolves.toEqual({ primed: false, reason: 'no-fetch' });
});
});