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

refactor: share Tailcat CLI support across dial directions (#6570)

Adam Eivy6d045a9eca48
diff --git a/docs/features/tailcat-peers.md b/docs/features/tailcat-peers.md
index 8ac1d27e92..1f8542f848 100644
--- a/docs/features/tailcat-peers.md
+++ b/docs/features/tailcat-peers.md
@@ -363,3 +363,16 @@ tailcat forward <tcADDR> 15555:5565
- [PORTS.md](../PORTS.md) — `TAILCAT_FORWARD` / `15555`
- [tailscale/tailcat](https://github.com/tailscale/tailcat) — CLI reference
+
+
+## Code ownership
+
+Shared CLI discovery, version-gated installation, and DERP cache priming live in
+`server/services/tailcatRuntime.js`; pure capability validation and diagnostic
+redaction live in `server/lib/tailcatAddress.js`. Both dial directions import
+these owners directly. `tailcatPeer.js` retains compatibility re-exports and
+owns forward storage, child processes, port allocation, tunnel verification,
+peer registration, rollback, retry, and restore. `tailcatServe.js` owns serve
+storage, keys, and lifecycle; `tailcatIngress.js` owns the isolated remote
+ingress listener. Version parsing and the minimum supported version remain in
+`server/lib/tailcatVersion.js`.
diff --git a/server/lib/README.md b/server/lib/README.md
index c33a662225..fa41e72893 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -378,6 +378,7 @@ pm` default, `NPM_CONFIG_PREFIX`, nvm/Volta) installed `codex` successfully and
| `syncIntegrity.js` | Pure diff of local vs remote manifest lists. `INTEGRITY_STATUS` constants + `computeRecordIntegrity(localList, remoteList)` — classifies each record as `in-parity`, `local-only`, `peer-only`, `diverged`, or `assets-missing`. No I/O. |
| `syncWire.js` | Single source of truth for what fields cross the federated-peer wire (snapshot loop + per-record push agree). |
| `tailscale.js` | Locate the Tailscale CLI binary, flag the sandboxed macOS App-bundle build, and return a normalized backend/MagicDNS/peer snapshot (`getTailscaleStatus` / `isTailscaleUp`). |
+| `tailcatAddress.js` | Pure Tailcat capability validation and redaction: `isValidTcAddress`, `redactTcAddress`, `redactTailcatDiagnostics`. |
| `tailcatVersion.js` | Tailcat CLI version floor for managed install/detect: `MIN_TAILCAT_VERSION` (`0.6.0` — PSK on by default in modern `serve`), `parseTailcatVersion` (handles the CLI's `v0.6.0` banner that `parseHarnessVersion` cannot), `isTailcatVersionAtLeast`, and `tailcatVersionTooOldMessage` for operator-facing upgrade guidance. Consumed by `services/tailcatPeer.js` so Dial-them and They-dial-us refuse ≤0.5.x rather than silently timing out on TCP. |
| `httpsState.js` | Captures whether PortOS booted with HTTPS active. |
| `bareUrl.js` | `parseBareUrl(text)` — returns the normalized URL when a captured string is nothing *but* a URL (bare host gets `https://`), else null. Drives the brain-capture short-circuit that files a pasted URL straight to Links instead of running the classifier. Stricter than the client's `urlNormalize.js` `isUrl` (needs a plausible TLD; http/https/`git@` only) because it picks a storage destination rather than a hint. |
diff --git a/server/lib/importScoping.test.js b/server/lib/importScoping.test.js
index b884d9889c..0a0f6d72ba 100644
--- a/server/lib/importScoping.test.js
+++ b/server/lib/importScoping.test.js
@@ -88,6 +88,27 @@ describe('narrowed imports stay narrow (#6009)', () => {
});
});
+// Serve must never acquire outbound peer registration through shared CLI support.
+describe('Tailcat shared owners stay independent of forwarding (#6570)', () => {
+ it.each(['services/tailcatServe.js', 'services/tailcatRuntime.js', 'lib/tailcatAddress.js'])(
+ '%s does not reach forward orchestration or instance registration', (entry) => {
+ const closure = staticImportClosure(abs(entry)).files;
+ expect(closure.has(abs(entry))).toBe(true);
+ expect(closure.has(abs('services/tailcatPeer.js'))).toBe(false);
+ expect(closure.has(abs('services/instances.js'))).toBe(false);
+ },
+ );
+
+ it('both dial directions reach the shared owners and forwarding retains registration', () => {
+ for (const entry of ['services/tailcatPeer.js', 'services/tailcatServe.js']) {
+ expect(reaches(entry, 'services/tailcatRuntime.js')).toBe(true);
+ expect(reaches(entry, 'lib/tailcatAddress.js')).toBe(true);
+ }
+ expect(reaches('services/tailcatRuntime.js', 'lib/tailcatVersion.js')).toBe(true);
+ expect(reaches('services/tailcatPeer.js', 'services/instances.js')).toBe(true);
+ });
+});
+
/**
* Deferred imports (#6156).
*
diff --git a/server/lib/index.js b/server/lib/index.js
index 7feb505fc3..13d07e9f2a 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -360,6 +360,7 @@ export * from './sharingOrigin.js';
export * from './syncIntegrity.js';
export * from './syncWire.js';
export * from './tailscale.js';
+export * from './tailcatAddress.js';
export * from './tailcatVersion.js';
// === Search & indexing ===
diff --git a/server/lib/tailcatAddress.js b/server/lib/tailcatAddress.js
new file mode 100644
index 0000000000..892ed676b7
--- /dev/null
+++ b/server/lib/tailcatAddress.js
@@ -0,0 +1,43 @@
+/** Pure Tailcat capability validation and diagnostic redaction. */
+
+const DIAGNOSTIC_MAX_CHARS = 320;
+
+/** Redact a tc address for logs / UI — never echo the full capability. */
+export function redactTcAddress(tc) {
+ const raw = String(tc || '').trim();
+ if (!raw) return '(empty)';
+ if (raw.length <= 8) return 'tc…';
+ return `${raw.slice(0, 4)}…${raw.slice(-4)}`;
+}
+
+/**
+ * Accept a pasted tailcat address. Real addresses are `tc` + base64url CBOR;
+ * keep the gate loose enough for DNS TXT forms that still begin with `tc`, but
+ * reject obvious garbage so we never spawn with an operator typo as argv.
+ */
+export function isValidTcAddress(tc) {
+ const raw = String(tc || '').trim();
+ if (!raw.startsWith('tc')) return false;
+ if (raw.length < 24 || raw.length > 2048) return false;
+ // Letters, digits, _ - = + / (base64 / base64url) only after the tc prefix.
+ return /^tc[A-Za-z0-9_+\/=-]+$/.test(raw);
+}
+
+/**
+ * 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;
+}
+
diff --git a/server/lib/tailcatAddress.test.js b/server/lib/tailcatAddress.test.js
new file mode 100644
index 0000000000..1b29faf037
--- /dev/null
+++ b/server/lib/tailcatAddress.test.js
@@ -0,0 +1,32 @@
+import { describe, it, expect } from 'vitest';
+import { redactTcAddress, isValidTcAddress, redactTailcatDiagnostics } from './tailcatAddress.js';
+
+const EXAMPLE_TC = 'tcEXAMPLE' + 'A'.repeat(40);
+
+describe('Tailcat capability privacy and validation', () => {
+ it('redacts tc addresses so logs never hold the full capability', () => {
+ const redacted = redactTcAddress(EXAMPLE_TC);
+ expect(redacted).not.toBe(EXAMPLE_TC);
+ expect(redacted.startsWith('tcEX')).toBe(true);
+ expect(redacted.includes('…')).toBe(true);
+ expect(redactTcAddress('')).toBe('(empty)');
+ });
+
+ it('validates tc address shape without accepting short garbage', () => {
+ expect(isValidTcAddress(EXAMPLE_TC)).toBe(true);
+ expect(isValidTcAddress('tcEXAMPLE…')).toBe(false); // ellipsis / placeholder
+ expect(isValidTcAddress('not-a-tc')).toBe(false);
+ expect(isValidTcAddress('tcshort')).toBe(false);
+ expect(isValidTcAddress('')).toBe(false);
+ });
+
+ it('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('');
+ });
+
+});
diff --git a/server/services/tailcatPeer.js b/server/services/tailcatPeer.js
index d4a4dfad64..537d0789f1 100644
--- a/server/services/tailcatPeer.js
+++ b/server/services/tailcatPeer.js
@@ -15,27 +15,14 @@
import { randomUUID } from 'node:crypto';
import { createServer } from 'node:net';
-import { stat } from 'node:fs/promises';
-import { homedir } from 'node:os';
-import { delimiter, join, posix, win32 } from 'node:path';
import { spawn } from '../lib/childProcess.js';
-import { commandOutput } from '../lib/commandExists.js';
-import {
- MIN_TAILCAT_VERSION,
- parseTailcatVersion,
- isTailcatVersionAtLeast,
- tailcatVersionTooOldMessage,
-} from '../lib/tailcatVersion.js';
-
-export { MIN_TAILCAT_VERSION };
-import { bufferedSpawn, spawnFailureDetail } from '../lib/bufferedSpawn.js';
import { dataPath, readJSONFile, ensureDir, PATHS, atomicWrite } from '../lib/fileUtils.js';
import { createMutex } from '../lib/asyncMutex.js';
import { isPortReachable } from '../lib/connectivity.js';
import { peerFetch } from '../lib/peerHttpClient.js';
import { peerBaseUrl } from '../lib/peerUrl.js';
import { isTestRunner } from '../lib/runtimeEnv.js';
-import { findCommandOnPath, safeChildProcessEnv, safeChildProcessOptions } from '../lib/processEnv.js';
+import { safeChildProcessEnv, safeChildProcessOptions } from '../lib/processEnv.js';
import {
PORTS,
DEFAULT_TAILCAT_LOCAL_PORT,
@@ -48,19 +35,21 @@ import {
removePeer as removeInstancePeer,
setTailcatPeerPort,
} from './instances.js';
+import { ensureTailcatInstalled, primeDerpMapCache } from './tailcatRuntime.js';
+import { isValidTcAddress, redactTcAddress, redactTailcatDiagnostics } from '../lib/tailcatAddress.js';
+
+// Compatibility for existing callers; shared implementations live with their owners.
+export { MIN_TAILCAT_VERSION } from '../lib/tailcatVersion.js';
+export {
+ listCandidateTailcatBins, readTailcatBinaryVersion, detectTailcat, findTooOldTailcat,
+ manualInstallHint, listTailcatInstallers, ensureTailcatInstalled, derpMapCachePath, primeDerpMapCache,
+} from './tailcatRuntime.js';
+export { isValidTcAddress, redactTcAddress, redactTailcatDiagnostics } from '../lib/tailcatAddress.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;
// Long enough to outlast tailcat's own per-connection dial deadline, so a
// blocked tunnel fails with tailcat's explanation rather than ours.
@@ -81,45 +70,6 @@ let shuttingDown = false;
/** @type {Map<string, { child: import('node:child_process').ChildProcess, localPort: number, remotePort: number }>} */
const liveForwards = new Map();
-/** Redact a tc address for logs / UI — never echo the full capability. */
-export function redactTcAddress(tc) {
- const raw = String(tc || '').trim();
- if (!raw) return '(empty)';
- if (raw.length <= 8) return 'tc…';
- return `${raw.slice(0, 4)}…${raw.slice(-4)}`;
-}
-
-/**
- * Accept a pasted tailcat address. Real addresses are `tc` + base64url CBOR;
- * keep the gate loose enough for DNS TXT forms that still begin with `tc`, but
- * reject obvious garbage so we never spawn with an operator typo as argv.
- */
-export function isValidTcAddress(tc) {
- const raw = String(tc || '').trim();
- if (!raw.startsWith('tc')) return false;
- if (raw.length < 24 || raw.length > 2048) return false;
- // Letters, digits, _ - = + / (base64 / base64url) only after the tc prefix.
- return /^tc[A-Za-z0-9_+\/=-]+$/.test(raw);
-}
-
-/**
- * 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;
-}
-
/**
* tailcat's per-connection delivery failures. `tailcat forward` binds its local
* listener eagerly and only brings the WireGuard/DERP tunnel up when a
@@ -315,309 +265,6 @@ export async function attachTailcatForwardToPeer(peer) {
return enriched;
}
-/**
- * Where a freshly installed `tailcat` can land. PATH is checked first, then the
- * install directories a package manager uses but a long-running server process
- * may never have inherited: GOBIN / GOPATH/bin for `go install`, and the
- * Homebrew prefix for `brew install`.
- */
-export function listCandidateTailcatBins({ env = process.env, home = homedir() } = {}) {
- // GOPATH may be a delimiter-separated list; `go install` writes into the first entry's bin.
- const goPath = String(env.GOPATH || '').split(delimiter).find(Boolean) || join(home, 'go');
- const goBinDir = env.GOBIN || join(goPath, 'bin');
- const brewPrefixes = [env.HOMEBREW_PREFIX, '/opt/homebrew', '/usr/local'].filter(Boolean);
- const candidates = [
- findCommandOnPath('tailcat', { env }),
- join(goBinDir, 'tailcat'),
- join(goBinDir, 'tailcat.exe'),
- ...brewPrefixes.map((prefix) => join(prefix, 'bin', 'tailcat')),
- ].filter(Boolean);
- return [...new Set(candidates)];
-}
-
-/**
- * Read `tailcat version` and return a bare semver, or null when the binary
- * cannot run / the banner cannot be parsed.
- */
-export async function readTailcatBinaryVersion(
- bin,
- { readOutput = (b) => commandOutput(b, ['version'], { timeoutMs: 5_000 }) } = {},
-) {
- if (!bin) return null;
- const raw = await readOutput(bin);
- return parseTailcatVersion(raw);
-}
-
-/**
- * Resolve an installed `tailcat` binary that meets {@link MIN_TAILCAT_VERSION},
- * or null when none is both runnable and new enough. Older binaries are
- * skipped (not returned) so install/upgrade can still try to replace them —
- * use {@link findTooOldTailcat} when the operator needs a version-gate error.
- * Injected deps keep unit tests off the real PATH / child_process.
- */
-export async function detectTailcat({
- candidates = listCandidateTailcatBins(),
- readOutput = (bin) => commandOutput(bin, ['version'], { timeoutMs: 5_000 }),
- minimum = MIN_TAILCAT_VERSION,
-} = {}) {
- for (const bin of candidates) {
- const raw = await readOutput(bin);
- if (raw === null) continue;
- const version = parseTailcatVersion(raw);
- if (isTailcatVersionAtLeast(version, minimum)) return bin;
- }
- return null;
-}
-
-/**
- * First runnable candidate that is below the version floor (or unparseable).
- * Used to turn a silent "no usable binary" into a clear upgrade error.
- */
-export async function findTooOldTailcat({
- candidates = listCandidateTailcatBins(),
- readOutput = (bin) => commandOutput(bin, ['version'], { timeoutMs: 5_000 }),
- minimum = MIN_TAILCAT_VERSION,
-} = {}) {
- for (const bin of candidates) {
- const raw = await readOutput(bin);
- if (raw === null) continue;
- const version = parseTailcatVersion(raw);
- if (!isTailcatVersionAtLeast(version, minimum)) {
- return { bin, version };
- }
- }
- return null;
-}
-
-/**
- * Manual-install guidance for this host. Tailcat publishes release binaries for
- * Linux and Windows ONLY — pointing a macOS operator at the releases page is a
- * dead end, so darwin gets the Homebrew formula instead.
- */
-export function manualInstallHint(platform = process.platform) {
- if (platform === 'darwin') {
- return (
- `Install or upgrade to tailcat ${MIN_TAILCAT_VERSION}+ with `
- + `\`brew upgrade ${BREW_FORMULA}\` / \`brew install ${BREW_FORMULA}\` `
- + `(Tailcat ships no macOS release binary), then retry.`
- );
- }
- return (
- `Install tailcat ${MIN_TAILCAT_VERSION}+ from ${RELEASES_URL} `
- + `or \`go install ${GO_INSTALL_PKG}\`, then retry.`
- );
-}
-
-/**
- * Ordered install strategies available on this host.
- *
- * Homebrew comes first: it is the only prebuilt route on macOS, and it fetches
- * over plain HTTPS, so it still works where `go install` cannot reach the Go
- * module proxy (a local network filter breaking Go's dialer shows up as an
- * opaque `connect: bad file descriptor`). `go install` stays as the fallback
- * for hosts with a toolchain but no brew.
- */
-export function listTailcatInstallers({
- brewBin = findCommandOnPath('brew'),
- goBin = findCommandOnPath('go'),
- runInstall = runInstallCommand,
-} = {}) {
- const installers = [];
- if (brewBin) {
- const brewEnv = {
- // Auto-update pulls the whole formula index before installing a ~10MB
- // bottle; the operator asked to add a peer, not to refresh Homebrew.
- HOMEBREW_NO_AUTO_UPDATE: '1',
- HOMEBREW_NO_INSTALL_CLEANUP: '1',
- };
- installers.push({
- label: `brew install/upgrade ${BREW_FORMULA}`,
- // `install` is a no-op when an older bottle is already present; follow
- // with `upgrade` so a 0.5.x Homebrew install can still reach the floor.
- // An "already up-to-date" upgrade failure is fine — the post-install
- // version gate decides whether we are done (and go install may still run).
- run: async () => {
- await runInstall(brewBin, ['install', BREW_FORMULA], brewEnv);
- await runInstall(brewBin, ['upgrade', BREW_FORMULA], brewEnv).catch(() => undefined);
- },
- });
- }
- if (goBin) {
- installers.push({
- label: 'go install',
- run: () => runInstall(goBin, ['install', GO_INSTALL_PKG]),
- });
- }
- return installers;
-}
-
-/**
- * Resolve a runnable `tailcat`, installing it through the first strategy that
- * works. Every strategy is a named package manager the operator already has —
- * PortOS never downloads an arbitrary URL on their behalf — and a total failure
- * reports what each one actually said so the operator can act on it.
- */
-export async function ensureTailcatInstalled({
- detect = detectTailcat,
- findTooOld = findTooOldTailcat,
- installers = listTailcatInstallers(),
- platform = process.platform,
-} = {}) {
- const existing = await detect();
- if (existing) return { bin: existing, installed: false };
-
- const rejectTooOldOrMissing = async (failures = []) => {
- const tooOld = await findTooOld();
- if (tooOld) {
- const detail = failures.length ? ` Install attempts: ${failures.join('; ')}.` : '';
- throw new ServerError(
- `${tailcatVersionTooOldMessage({ version: tooOld.version, platform })}${detail}`,
- { status: 503, code: 'TAILCAT_VERSION_TOO_OLD' },
- );
- }
- if (failures.length) {
- throw new ServerError(
- `Could not install tailcat — ${failures.join('; ')}. ${manualInstallHint(platform)}`,
- { status: 503, code: 'TAILCAT_INSTALL_FAILED' },
- );
- }
- throw new ServerError(
- `tailcat is not installed, and neither Homebrew nor Go was found on PATH. ${manualInstallHint(platform)}`,
- { status: 503, code: 'TAILCAT_MISSING' },
- );
- };
-
- if (installers.length === 0) {
- await rejectTooOldOrMissing();
- }
-
- const failures = [];
- for (const installer of installers) {
- // Promise.resolve().then defers the call, so an installer that throws
- // SYNCHRONOUSLY still falls through to the next one instead of escaping
- // past the ServerError wrapper as an unhandled 500.
- const error = await Promise.resolve().then(() => installer.run()).then(() => null, (err) => err);
- if (error) {
- failures.push(`${installer.label} failed: ${summarizeInstallError(error)}`);
- continue;
- }
- const bin = await detect();
- if (bin) return { bin, installed: true };
- // Installer exited 0 but left only an old / unparseable binary — keep
- // trying other strategies, then fail with the version gate (not "success").
- const leftover = await findTooOld();
- if (leftover) {
- failures.push(
- `${installer.label} finished but tailcat is still below ${MIN_TAILCAT_VERSION}`
- + (leftover.version ? ` (found ${leftover.version})` : ' (version unknown)'),
- );
- } else {
- failures.push(`${installer.label} finished but no tailcat binary was found`);
- }
- }
-
- await rejectTooOldOrMissing(failures);
-}
-
-/** One line of an installer's diagnostics, bounded so a toast stays readable. */
-function summarizeInstallError(error) {
- const first = String(error?.message || 'unknown error').split('\n').map((line) => line.trim()).find(Boolean);
- const text = first || 'unknown error';
- return text.length > 240 ? `${text.slice(0, 240)}…` : text;
-}
-
-async function runInstallCommand(bin, args, extraEnv = {}) {
- const result = await bufferedSpawn(bin, args, {
- env: safeChildProcessEnv(extraEnv),
- timeoutMs: INSTALL_TIMEOUT_MS,
- });
- if (result.success) return;
- throw new Error(result.timedOut
- ? `timed out after ${INSTALL_TIMEOUT_MS / 1000}s`
- // Homebrew opens with tap/deprecation warnings, so its FIRST stderr line is
- // rarely the failure — spawnFailureDetail takes the last one it printed.
- : 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,
-} = {}) {
- // Join for the REQUESTED platform, not the host: the caller names the platform,
- // so a `darwin` path asked for from a Windows runner must still be POSIX.
- const { join: joinFor } = platform === 'win32' ? win32 : posix;
- const base = platform === 'darwin' ? joinFor(home, 'Library', 'Caches')
- : platform === 'win32' ? (env.LOCALAPPDATA || joinFor(home, 'AppData', 'Local'))
- : (env.XDG_CACHE_HOME || joinFor(home, '.cache'));
- return joinFor(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) => {
diff --git a/server/services/tailcatPeer.test.js b/server/services/tailcatPeer.test.js
index be92b8724d..d793bd7599 100644
--- a/server/services/tailcatPeer.test.js
+++ b/server/services/tailcatPeer.test.js
@@ -1,15 +1,7 @@
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
+import { redactTcAddress } from '../lib/tailcatAddress.js';
import { EventEmitter } from 'node:events';
-import { delimiter, join } from 'node:path';
import {
- redactTcAddress,
- isValidTcAddress,
- ensureTailcatInstalled,
- detectTailcat,
- findTooOldTailcat,
- listTailcatInstallers,
- listCandidateTailcatBins,
- manualInstallHint,
allocateLocalPort,
startForwardProcess,
classifyTailcatRuntimeError,
@@ -19,10 +11,6 @@ import {
attachTailcatForwardsToPeers,
retryTailcatForward,
forgetTailcatForward,
- redactTailcatDiagnostics,
- derpMapCachePath,
- primeDerpMapCache,
- MIN_TAILCAT_VERSION,
_resetLiveForwardsForTests,
_liveForwardCountForTests,
stopAllForwards,
@@ -39,12 +27,12 @@ vi.mock('../lib/fileUtils.js', async (original) => ({
}));
import { readJSONFile, atomicWrite } from '../lib/fileUtils.js';
-// Only the install path spawns through this; forwards use spawn() directly.
-vi.mock('../lib/bufferedSpawn.js', async (original) => ({
+// No installed CLI or package manager: exercise the real shared installation failure.
+vi.mock('../lib/commandExists.js', () => ({ commandOutput: vi.fn().mockResolvedValue(null) }));
+vi.mock('../lib/processEnv.js', async (original) => ({
...(await original()),
- bufferedSpawn: vi.fn(),
+ findCommandOnPath: vi.fn().mockReturnValue(null),
}));
-import { bufferedSpawn } from '../lib/bufferedSpawn.js';
const EXAMPLE_TC = 'tcEXAMPLE' + 'A'.repeat(40);
@@ -72,254 +60,13 @@ describe('tailcatPeer helpers', () => {
vi.useRealTimers();
});
- it('redacts tc addresses so logs never hold the full capability', () => {
- const redacted = redactTcAddress(EXAMPLE_TC);
- expect(redacted).not.toBe(EXAMPLE_TC);
- expect(redacted.startsWith('tcEX')).toBe(true);
- expect(redacted.includes('…')).toBe(true);
- expect(redactTcAddress('')).toBe('(empty)');
- });
-
- it('validates tc address shape without accepting short garbage', () => {
- expect(isValidTcAddress(EXAMPLE_TC)).toBe(true);
- expect(isValidTcAddress('tcEXAMPLE…')).toBe(false); // ellipsis / placeholder
- expect(isValidTcAddress('not-a-tc')).toBe(false);
- expect(isValidTcAddress('tcshort')).toBe(false);
- expect(isValidTcAddress('')).toBe(false);
- });
-
- it('ensureTailcatInstalled returns existing binary without installing', async () => {
- const run = vi.fn();
- const result = await ensureTailcatInstalled({
- detect: async () => '/usr/bin/tailcat',
- installers: [{ label: 'brew install tailcat', run }],
- });
- expect(result).toEqual({ bin: '/usr/bin/tailcat', installed: false });
- expect(run).not.toHaveBeenCalled();
- });
-
- it('ensureTailcatInstalled installs when missing, then re-detects', async () => {
- let calls = 0;
- const run = vi.fn(async () => {});
- const result = await ensureTailcatInstalled({
- detect: async () => {
- calls += 1;
- return calls === 1 ? null : '/example/go/bin/tailcat';
- },
- installers: [{ label: 'go install', run }],
- });
- expect(run).toHaveBeenCalledOnce();
- expect(result).toEqual({ bin: '/example/go/bin/tailcat', installed: true });
- });
-
- it('falls back to the next installer when the first one fails', async () => {
- let calls = 0;
- const brew = vi.fn(async () => { throw new Error('Error: No available formula\nsecond line'); });
- const go = vi.fn(async () => {});
- const result = await ensureTailcatInstalled({
- detect: async () => {
- calls += 1;
- return calls <= 1 ? null : '/example/go/bin/tailcat';
- },
- installers: [{ label: 'brew install tailcat', run: brew }, { label: 'go install', run: go }],
- });
- expect(brew).toHaveBeenCalledOnce();
- expect(go).toHaveBeenCalledOnce();
- expect(result).toEqual({ bin: '/example/go/bin/tailcat', installed: true });
- });
-
- it('reports what every installer said when they all fail', async () => {
- const error = await ensureTailcatInstalled({
- detect: async () => null,
- findTooOld: async () => null,
- platform: 'linux',
- installers: [
- { label: 'brew install tailcat', run: async () => { throw new Error('brew boom'); } },
- { label: 'go install', run: async () => { throw new Error('dial tcp: connect: bad file descriptor\nignored'); } },
- ],
- }).catch((err) => err);
- expect(error).toMatchObject({ code: 'TAILCAT_INSTALL_FAILED', status: 503 });
- // Every strategy is named, not just the first one that failed.
- expect(error.message).toContain('brew install tailcat failed: brew boom');
- expect(error.message).toContain('go install failed: dial tcp: connect: bad file descriptor');
- // Only the first line of a multi-line diagnostic reaches the toast.
- expect(error.message).not.toContain('ignored');
- expect(error.message).toContain('https://github.com/tailscale/tailcat/releases');
- });
-
- it('falls through to the next installer even when one throws synchronously', async () => {
- let calls = 0;
- const result = await ensureTailcatInstalled({
- detect: async () => {
- calls += 1;
- return calls <= 1 ? null : '/example/go/bin/tailcat';
- },
- installers: [
- { label: 'brew install tailcat', run: () => { throw new Error('sync boom'); } },
- { label: 'go install', run: async () => {} },
- ],
- });
- expect(result).toEqual({ bin: '/example/go/bin/tailcat', installed: true });
- });
-
- it('treats an installer that leaves no binary as a failure, not a success', async () => {
- await expect(ensureTailcatInstalled({
- detect: async () => null,
- findTooOld: async () => null,
- installers: [{ label: 'go install', run: async () => {} }],
- })).rejects.toMatchObject({
- code: 'TAILCAT_INSTALL_FAILED',
- message: expect.stringContaining('go install finished but no tailcat binary was found'),
- });
- });
-
- it('ensureTailcatInstalled fails clearly when no package manager is present', async () => {
- await expect(ensureTailcatInstalled({
- detect: async () => null,
- findTooOld: async () => null,
- installers: [],
- })).rejects.toMatchObject({ code: 'TAILCAT_MISSING', status: 503 });
- });
-
- it('detectTailcat skips binaries below the minimum version', async () => {
- expect(MIN_TAILCAT_VERSION).toBe('0.6.0');
- const readOutput = vi.fn(async (bin) => {
- if (bin === '/old/tailcat') return 'v0.5.0';
- if (bin === '/new/tailcat') return 'v0.6.0';
- return null;
- });
- await expect(detectTailcat({
- candidates: ['/old/tailcat', '/new/tailcat'],
- readOutput,
- })).resolves.toBe('/new/tailcat');
- await expect(detectTailcat({
- candidates: ['/old/tailcat'],
- readOutput,
- })).resolves.toBeNull();
- });
-
- it('findTooOldTailcat reports a runnable but outdated binary', async () => {
- await expect(findTooOldTailcat({
- candidates: ['/old/tailcat'],
- readOutput: async () => 'v0.5.0',
- })).resolves.toEqual({ bin: '/old/tailcat', version: '0.5.0' });
- });
-
- it('ensureTailcatInstalled refuses a leftover 0.5.x after brew claims success', async () => {
- const run = vi.fn(async () => {});
- const error = await ensureTailcatInstalled({
- detect: async () => null,
- findTooOld: async () => ({ bin: '/opt/homebrew/bin/tailcat', version: '0.5.0' }),
- platform: 'darwin',
- installers: [{ label: 'brew install/upgrade tailcat', run }],
- }).catch((err) => err);
- expect(run).toHaveBeenCalledOnce();
- expect(error).toMatchObject({ code: 'TAILCAT_VERSION_TOO_OLD', status: 503 });
- expect(error.message).toContain('0.6.0+');
- expect(error.message).toContain('found 0.5.0');
- expect(error.message).toContain('brew upgrade tailcat');
- expect(error.message).toContain('Do not set --psk=false');
- });
-
- it('ensureTailcatInstalled upgrades via installers when only an old binary is present', async () => {
- let detectCalls = 0;
- const run = vi.fn(async () => {});
- const result = await ensureTailcatInstalled({
- detect: async () => {
- detectCalls += 1;
- return detectCalls === 1 ? null : '/example/go/bin/tailcat';
- },
- findTooOld: async () => ({ bin: '/opt/homebrew/bin/tailcat', version: '0.5.0' }),
- installers: [{ label: 'go install', run }],
- });
- expect(run).toHaveBeenCalledOnce();
- expect(result).toEqual({ bin: '/example/go/bin/tailcat', installed: true });
- });
-
- it('ensureTailcatInstalled reports VERSION_TOO_OLD when no package manager and only 0.5.x exists', async () => {
- await expect(ensureTailcatInstalled({
- detect: async () => null,
- findTooOld: async () => ({ bin: '/usr/local/bin/tailcat', version: '0.5.0' }),
- installers: [],
- platform: 'linux',
- })).rejects.toMatchObject({ code: 'TAILCAT_VERSION_TOO_OLD', status: 503 });
- });
-
- it('points macOS at Homebrew, since tailcat ships no darwin release binary', () => {
- expect(manualInstallHint('darwin')).toContain('brew upgrade tailcat');
- expect(manualInstallHint('darwin')).toContain('brew install tailcat');
- expect(manualInstallHint('darwin')).toContain('0.6.0+');
- expect(manualInstallHint('darwin')).not.toContain('/releases');
- expect(manualInstallHint('linux')).toContain('https://github.com/tailscale/tailcat/releases');
- expect(manualInstallHint('linux')).toContain('0.6.0+');
- });
-
- it('lists brew before go, and only for package managers that exist', () => {
- const runInstall = vi.fn(async () => {});
- expect(listTailcatInstallers({ brewBin: '/opt/homebrew/bin/brew', goBin: '/usr/bin/go', runInstall })
- .map((i) => i.label)).toEqual(['brew install/upgrade tailcat', 'go install']);
- expect(listTailcatInstallers({ brewBin: null, goBin: '/usr/bin/go', runInstall })
- .map((i) => i.label)).toEqual(['go install']);
- expect(listTailcatInstallers({ brewBin: null, goBin: null, runInstall })).toEqual([]);
- });
-
- it('skips Homebrew auto-update so adding a peer does not refresh the formula index', async () => {
- const runInstall = vi.fn(async () => {});
- const [brew] = listTailcatInstallers({ brewBin: '/opt/homebrew/bin/brew', goBin: null, runInstall });
- await brew.run();
- expect(runInstall).toHaveBeenCalledWith('/opt/homebrew/bin/brew', ['install', 'tailcat'],
- expect.objectContaining({ HOMEBREW_NO_AUTO_UPDATE: '1' }));
- expect(runInstall).toHaveBeenCalledWith('/opt/homebrew/bin/brew', ['upgrade', 'tailcat'],
- expect.objectContaining({ HOMEBREW_NO_AUTO_UPDATE: '1' }));
- });
-
- // The default runner maps a bufferedSpawn result onto the message the operator
- // reads in the toast; each terminal condition has to say something different.
- it.each([
- ['a non-zero exit', { success: false, code: 1, stdout: '', stderr: 'Warning: tap not trusted\nError: No available formula\n', timedOut: false },
- 'Error: No available formula'],
- ['a spawn failure', { success: false, code: -1, stdout: '', stderr: '', timedOut: false, error: new Error('spawn /example/missing/go ENOENT') },
- 'spawn /example/missing/go ENOENT'],
- ['a silent non-zero exit', { success: false, code: 7, stdout: '', stderr: '', timedOut: false }, 'exit 7'],
- ['a timeout', { success: false, code: -1, stdout: '', stderr: '', timedOut: true }, 'timed out after 180s'],
- ])('surfaces %s as a readable install error', async (_label, result, expected) => {
- bufferedSpawn.mockResolvedValueOnce(result);
- const [installer] = listTailcatInstallers({ brewBin: null, goBin: '/example/go' });
- await expect(installer.run()).rejects.toThrow(expected);
- });
-
- it('treats a clean install-command exit as success', async () => {
- bufferedSpawn
- .mockResolvedValueOnce({ success: true, code: 0, stdout: '', stderr: '', timedOut: false })
- .mockResolvedValueOnce({ success: true, code: 0, stdout: '', stderr: '', timedOut: false });
- const [installer] = listTailcatInstallers({ brewBin: '/example/brew', goBin: null });
- await expect(installer.run()).resolves.toBeUndefined();
- expect(bufferedSpawn).toHaveBeenCalledWith('/example/brew', ['install', 'tailcat'],
- expect.objectContaining({ env: expect.objectContaining({ HOMEBREW_NO_AUTO_UPDATE: '1' }) }));
- expect(bufferedSpawn).toHaveBeenCalledWith('/example/brew', ['upgrade', 'tailcat'],
- expect.objectContaining({ env: expect.objectContaining({ HOMEBREW_NO_AUTO_UPDATE: '1' }) }));
- });
-
- it('looks for tailcat in the GOBIN and Homebrew prefixes a server may not have on PATH', () => {
- // Empty PATH so the injected env is the only source — the real PATH must not leak in.
- const bins = listCandidateTailcatBins({
- env: { PATH: '', GOBIN: join('/example', 'gobin'), HOMEBREW_PREFIX: join('/example', 'brew') },
- home: join('/example', 'home'),
+ it('surfaces shared installation failure without starting a tunnel', async () => {
+ const startForward = vi.fn();
+ await expect(addPeerViaTailcat({ tcAddress: EXAMPLE_TC, startForward })).rejects.toMatchObject({
+ status: 503, code: 'TAILCAT_MISSING',
});
- expect(bins).toEqual([
- join('/example', 'gobin', 'tailcat'),
- join('/example', 'gobin', 'tailcat.exe'),
- join('/example', 'brew', 'bin', 'tailcat'),
- join('/opt', 'homebrew', 'bin', 'tailcat'),
- join('/usr', 'local', 'bin', 'tailcat'),
- ]);
- // No GOBIN → the first GOPATH entry's bin; no GOPATH at all → ~/go/bin.
- expect(listCandidateTailcatBins({
- env: { PATH: '', GOPATH: [join('/example', 'gopath'), join('/example', 'other')].join(delimiter) },
- home: join('/example', 'home'),
- })).toContain(join('/example', 'gopath', 'bin', 'tailcat'));
- expect(listCandidateTailcatBins({ env: { PATH: '' }, home: join('/example', 'home') }))
- .toContain(join('/example', 'home', 'go', 'bin', 'tailcat'));
+ expect(startForward).not.toHaveBeenCalled();
+ expect(_liveForwardCountForTests()).toBe(0);
});
it('allocateLocalPort prefers 15555 then walks upward when busy', async () => {
@@ -856,19 +603,10 @@ describe('saved tailcat forwards', () => {
});
});
-describe('tailcat startup diagnostics and DERP map priming', () => {
+describe('tailcat startup diagnostics', () => {
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();
@@ -894,56 +632,7 @@ describe('tailcat startup diagnostics and DERP map priming', () => {
})).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');
- expect(derpMapCachePath({
- url: 'https://example.com/derpmap.json', platform: 'win32', home: 'C:\\example\\home',
- env: { LOCALAPPDATA: 'C:\\example\\cache' },
- })).toBe('C:\\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' });
- });
+
});
describe('verifyTunnelReachable', () => {
diff --git a/server/services/tailcatRuntime.js b/server/services/tailcatRuntime.js
new file mode 100644
index 0000000000..1f8dda47fa
--- /dev/null
+++ b/server/services/tailcatRuntime.js
@@ -0,0 +1,326 @@
+/**
+ * Shared Tailcat CLI discovery, installation, and DERP cache support.
+ * No forward/serve lifecycle state or peer registration belongs here.
+ */
+import { stat } from 'node:fs/promises';
+import { homedir } from 'node:os';
+import { delimiter, join, posix, win32 } from 'node:path';
+import { commandOutput } from '../lib/commandExists.js';
+import { MIN_TAILCAT_VERSION, parseTailcatVersion, isTailcatVersionAtLeast, tailcatVersionTooOldMessage } from '../lib/tailcatVersion.js';
+import { bufferedSpawn, spawnFailureDetail } from '../lib/bufferedSpawn.js';
+import { atomicWrite } from '../lib/fileUtils.js';
+import { isTestRunner } from '../lib/runtimeEnv.js';
+import { findCommandOnPath, safeChildProcessEnv } from '../lib/processEnv.js';
+import { ServerError } from '../lib/errorHandler.js';
+
+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 DERP_MAP_FRESH_MS = 6 * 60 * 60 * 1000;
+const DERP_MAP_FETCH_TIMEOUT_MS = 15_000;
+
+/**
+ * Where a freshly installed `tailcat` can land. PATH is checked first, then the
+ * install directories a package manager uses but a long-running server process
+ * may never have inherited: GOBIN / GOPATH/bin for `go install`, and the
+ * Homebrew prefix for `brew install`.
+ */
+export function listCandidateTailcatBins({ env = process.env, home = homedir() } = {}) {
+ // GOPATH may be a delimiter-separated list; `go install` writes into the first entry's bin.
+ const goPath = String(env.GOPATH || '').split(delimiter).find(Boolean) || join(home, 'go');
+ const goBinDir = env.GOBIN || join(goPath, 'bin');
+ const brewPrefixes = [env.HOMEBREW_PREFIX, '/opt/homebrew', '/usr/local'].filter(Boolean);
+ const candidates = [
+ findCommandOnPath('tailcat', { env }),
+ join(goBinDir, 'tailcat'),
+ join(goBinDir, 'tailcat.exe'),
+ ...brewPrefixes.map((prefix) => join(prefix, 'bin', 'tailcat')),
+ ].filter(Boolean);
+ return [...new Set(candidates)];
+}
+
+/**
+ * Read `tailcat version` and return a bare semver, or null when the binary
+ * cannot run / the banner cannot be parsed.
+ */
+export async function readTailcatBinaryVersion(
+ bin,
+ { readOutput = (b) => commandOutput(b, ['version'], { timeoutMs: 5_000 }) } = {},
+) {
+ if (!bin) return null;
+ const raw = await readOutput(bin);
+ return parseTailcatVersion(raw);
+}
+
+/**
+ * Resolve an installed `tailcat` binary that meets {@link MIN_TAILCAT_VERSION},
+ * or null when none is both runnable and new enough. Older binaries are
+ * skipped (not returned) so install/upgrade can still try to replace them —
+ * use {@link findTooOldTailcat} when the operator needs a version-gate error.
+ * Injected deps keep unit tests off the real PATH / child_process.
+ */
+export async function detectTailcat({
+ candidates = listCandidateTailcatBins(),
+ readOutput = (bin) => commandOutput(bin, ['version'], { timeoutMs: 5_000 }),
+ minimum = MIN_TAILCAT_VERSION,
+} = {}) {
+ for (const bin of candidates) {
+ const raw = await readOutput(bin);
+ if (raw === null) continue;
+ const version = parseTailcatVersion(raw);
+ if (isTailcatVersionAtLeast(version, minimum)) return bin;
+ }
+ return null;
+}
+
+/**
+ * First runnable candidate that is below the version floor (or unparseable).
+ * Used to turn a silent "no usable binary" into a clear upgrade error.
+ */
+export async function findTooOldTailcat({
+ candidates = listCandidateTailcatBins(),
+ readOutput = (bin) => commandOutput(bin, ['version'], { timeoutMs: 5_000 }),
+ minimum = MIN_TAILCAT_VERSION,
+} = {}) {
+ for (const bin of candidates) {
+ const raw = await readOutput(bin);
+ if (raw === null) continue;
+ const version = parseTailcatVersion(raw);
+ if (!isTailcatVersionAtLeast(version, minimum)) {
+ return { bin, version };
+ }
+ }
+ return null;
+}
+
+/**
+ * Manual-install guidance for this host. Tailcat publishes release binaries for
+ * Linux and Windows ONLY — pointing a macOS operator at the releases page is a
+ * dead end, so darwin gets the Homebrew formula instead.
+ */
+export function manualInstallHint(platform = process.platform) {
+ if (platform === 'darwin') {
+ return (
+ `Install or upgrade to tailcat ${MIN_TAILCAT_VERSION}+ with `
+ + `\`brew upgrade ${BREW_FORMULA}\` / \`brew install ${BREW_FORMULA}\` `
+ + `(Tailcat ships no macOS release binary), then retry.`
+ );
+ }
+ return (
+ `Install tailcat ${MIN_TAILCAT_VERSION}+ from ${RELEASES_URL} `
+ + `or \`go install ${GO_INSTALL_PKG}\`, then retry.`
+ );
+}
+
+/**
+ * Ordered install strategies available on this host.
+ *
+ * Homebrew comes first: it is the only prebuilt route on macOS, and it fetches
+ * over plain HTTPS, so it still works where `go install` cannot reach the Go
+ * module proxy (a local network filter breaking Go's dialer shows up as an
+ * opaque `connect: bad file descriptor`). `go install` stays as the fallback
+ * for hosts with a toolchain but no brew.
+ */
+export function listTailcatInstallers({
+ brewBin = findCommandOnPath('brew'),
+ goBin = findCommandOnPath('go'),
+ runInstall = runInstallCommand,
+} = {}) {
+ const installers = [];
+ if (brewBin) {
+ const brewEnv = {
+ // Auto-update pulls the whole formula index before installing a ~10MB
+ // bottle; the operator asked to add a peer, not to refresh Homebrew.
+ HOMEBREW_NO_AUTO_UPDATE: '1',
+ HOMEBREW_NO_INSTALL_CLEANUP: '1',
+ };
+ installers.push({
+ label: `brew install/upgrade ${BREW_FORMULA}`,
+ // `install` is a no-op when an older bottle is already present; follow
+ // with `upgrade` so a 0.5.x Homebrew install can still reach the floor.
+ // An "already up-to-date" upgrade failure is fine — the post-install
+ // version gate decides whether we are done (and go install may still run).
+ run: async () => {
+ await runInstall(brewBin, ['install', BREW_FORMULA], brewEnv);
+ await runInstall(brewBin, ['upgrade', BREW_FORMULA], brewEnv).catch(() => undefined);
+ },
+ });
+ }
+ if (goBin) {
+ installers.push({
+ label: 'go install',
+ run: () => runInstall(goBin, ['install', GO_INSTALL_PKG]),
+ });
+ }
+ return installers;
+}
+
+/**
+ * Resolve a runnable `tailcat`, installing it through the first strategy that
+ * works. Every strategy is a named package manager the operator already has —
+ * PortOS never downloads an arbitrary URL on their behalf — and a total failure
+ * reports what each one actually said so the operator can act on it.
+ */
+export async function ensureTailcatInstalled({
+ detect = detectTailcat,
+ findTooOld = findTooOldTailcat,
+ installers = listTailcatInstallers(),
+ platform = process.platform,
+} = {}) {
+ const existing = await detect();
+ if (existing) return { bin: existing, installed: false };
+
+ const rejectTooOldOrMissing = async (failures = []) => {
+ const tooOld = await findTooOld();
+ if (tooOld) {
+ const detail = failures.length ? ` Install attempts: ${failures.join('; ')}.` : '';
+ throw new ServerError(
+ `${tailcatVersionTooOldMessage({ version: tooOld.version, platform })}${detail}`,
+ { status: 503, code: 'TAILCAT_VERSION_TOO_OLD' },
+ );
+ }
+ if (failures.length) {
+ throw new ServerError(
+ `Could not install tailcat — ${failures.join('; ')}. ${manualInstallHint(platform)}`,
+ { status: 503, code: 'TAILCAT_INSTALL_FAILED' },
+ );
+ }
+ throw new ServerError(
+ `tailcat is not installed, and neither Homebrew nor Go was found on PATH. ${manualInstallHint(platform)}`,
+ { status: 503, code: 'TAILCAT_MISSING' },
+ );
+ };
+
+ if (installers.length === 0) {
+ await rejectTooOldOrMissing();
+ }
+
+ const failures = [];
+ for (const installer of installers) {
+ // Promise.resolve().then defers the call, so an installer that throws
+ // SYNCHRONOUSLY still falls through to the next one instead of escaping
+ // past the ServerError wrapper as an unhandled 500.
+ const error = await Promise.resolve().then(() => installer.run()).then(() => null, (err) => err);
+ if (error) {
+ failures.push(`${installer.label} failed: ${summarizeInstallError(error)}`);
+ continue;
+ }
+ const bin = await detect();
+ if (bin) return { bin, installed: true };
+ // Installer exited 0 but left only an old / unparseable binary — keep
+ // trying other strategies, then fail with the version gate (not "success").
+ const leftover = await findTooOld();
+ if (leftover) {
+ failures.push(
+ `${installer.label} finished but tailcat is still below ${MIN_TAILCAT_VERSION}`
+ + (leftover.version ? ` (found ${leftover.version})` : ' (version unknown)'),
+ );
+ } else {
+ failures.push(`${installer.label} finished but no tailcat binary was found`);
+ }
+ }
+
+ await rejectTooOldOrMissing(failures);
+}
+
+/** One line of an installer's diagnostics, bounded so a toast stays readable. */
+function summarizeInstallError(error) {
+ const first = String(error?.message || 'unknown error').split('\n').map((line) => line.trim()).find(Boolean);
+ const text = first || 'unknown error';
+ return text.length > 240 ? `${text.slice(0, 240)}…` : text;
+}
+
+async function runInstallCommand(bin, args, extraEnv = {}) {
+ const result = await bufferedSpawn(bin, args, {
+ env: safeChildProcessEnv(extraEnv),
+ timeoutMs: INSTALL_TIMEOUT_MS,
+ });
+ if (result.success) return;
+ throw new Error(result.timedOut
+ ? `timed out after ${INSTALL_TIMEOUT_MS / 1000}s`
+ // Homebrew opens with tap/deprecation warnings, so its FIRST stderr line is
+ // rarely the failure — spawnFailureDetail takes the last one it printed.
+ : 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,
+} = {}) {
+ // Join for the REQUESTED platform, not the host: the caller names the platform,
+ // so a `darwin` path asked for from a Windows runner must still be POSIX.
+ const { join: joinFor } = platform === 'win32' ? win32 : posix;
+ const base = platform === 'darwin' ? joinFor(home, 'Library', 'Caches')
+ : platform === 'win32' ? (env.LOCALAPPDATA || joinFor(home, 'AppData', 'Local'))
+ : (env.XDG_CACHE_HOME || joinFor(home, '.cache'));
+ return joinFor(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
+ }
+}
+
diff --git a/server/services/tailcatRuntime.test.js b/server/services/tailcatRuntime.test.js
new file mode 100644
index 0000000000..192c5d0ef1
--- /dev/null
+++ b/server/services/tailcatRuntime.test.js
@@ -0,0 +1,303 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { delimiter, join } from 'node:path';
+import {
+ ensureTailcatInstalled, detectTailcat, findTooOldTailcat, listTailcatInstallers,
+ listCandidateTailcatBins, manualInstallHint, derpMapCachePath, primeDerpMapCache,
+} from './tailcatRuntime.js';
+import { MIN_TAILCAT_VERSION } from '../lib/tailcatVersion.js';
+
+// Keep installer execution mocked while exercising its real result handling.
+vi.mock('../lib/bufferedSpawn.js', async (original) => ({
+ ...(await original()),
+ bufferedSpawn: vi.fn(),
+}));
+import { bufferedSpawn } from '../lib/bufferedSpawn.js';
+
+describe('Tailcat CLI runtime', () => {
+ beforeEach(() => { vi.clearAllMocks(); });
+
+ it('ensureTailcatInstalled returns existing binary without installing', async () => {
+ const run = vi.fn();
+ const result = await ensureTailcatInstalled({
+ detect: async () => '/usr/bin/tailcat',
+ installers: [{ label: 'brew install tailcat', run }],
+ });
+ expect(result).toEqual({ bin: '/usr/bin/tailcat', installed: false });
+ expect(run).not.toHaveBeenCalled();
+ });
+
+ it('ensureTailcatInstalled installs when missing, then re-detects', async () => {
+ let calls = 0;
+ const run = vi.fn(async () => {});
+ const result = await ensureTailcatInstalled({
+ detect: async () => {
+ calls += 1;
+ return calls === 1 ? null : '/example/go/bin/tailcat';
+ },
+ installers: [{ label: 'go install', run }],
+ });
+ expect(run).toHaveBeenCalledOnce();
+ expect(result).toEqual({ bin: '/example/go/bin/tailcat', installed: true });
+ });
+
+ it('falls back to the next installer when the first one fails', async () => {
+ let calls = 0;
+ const brew = vi.fn(async () => { throw new Error('Error: No available formula\nsecond line'); });
+ const go = vi.fn(async () => {});
+ const result = await ensureTailcatInstalled({
+ detect: async () => {
+ calls += 1;
+ return calls <= 1 ? null : '/example/go/bin/tailcat';
+ },
+ installers: [{ label: 'brew install tailcat', run: brew }, { label: 'go install', run: go }],
+ });
+ expect(brew).toHaveBeenCalledOnce();
+ expect(go).toHaveBeenCalledOnce();
+ expect(result).toEqual({ bin: '/example/go/bin/tailcat', installed: true });
+ });
+
+ it('reports what every installer said when they all fail', async () => {
+ const error = await ensureTailcatInstalled({
+ detect: async () => null,
+ findTooOld: async () => null,
+ platform: 'linux',
+ installers: [
+ { label: 'brew install tailcat', run: async () => { throw new Error('brew boom'); } },
+ { label: 'go install', run: async () => { throw new Error('dial tcp: connect: bad file descriptor\nignored'); } },
+ ],
+ }).catch((err) => err);
+ expect(error).toMatchObject({ code: 'TAILCAT_INSTALL_FAILED', status: 503 });
+ // Every strategy is named, not just the first one that failed.
+ expect(error.message).toContain('brew install tailcat failed: brew boom');
+ expect(error.message).toContain('go install failed: dial tcp: connect: bad file descriptor');
+ // Only the first line of a multi-line diagnostic reaches the toast.
+ expect(error.message).not.toContain('ignored');
+ expect(error.message).toContain('https://github.com/tailscale/tailcat/releases');
+ });
+
+ it('falls through to the next installer even when one throws synchronously', async () => {
+ let calls = 0;
+ const result = await ensureTailcatInstalled({
+ detect: async () => {
+ calls += 1;
+ return calls <= 1 ? null : '/example/go/bin/tailcat';
+ },
+ installers: [
+ { label: 'brew install tailcat', run: () => { throw new Error('sync boom'); } },
+ { label: 'go install', run: async () => {} },
+ ],
+ });
+ expect(result).toEqual({ bin: '/example/go/bin/tailcat', installed: true });
+ });
+
+ it('treats an installer that leaves no binary as a failure, not a success', async () => {
+ await expect(ensureTailcatInstalled({
+ detect: async () => null,
+ findTooOld: async () => null,
+ installers: [{ label: 'go install', run: async () => {} }],
+ })).rejects.toMatchObject({
+ code: 'TAILCAT_INSTALL_FAILED',
+ message: expect.stringContaining('go install finished but no tailcat binary was found'),
+ });
+ });
+
+ it('ensureTailcatInstalled fails clearly when no package manager is present', async () => {
+ await expect(ensureTailcatInstalled({
+ detect: async () => null,
+ findTooOld: async () => null,
+ installers: [],
+ })).rejects.toMatchObject({ code: 'TAILCAT_MISSING', status: 503 });
+ });
+
+ it('detectTailcat skips binaries below the minimum version', async () => {
+ expect(MIN_TAILCAT_VERSION).toBe('0.6.0');
+ const readOutput = vi.fn(async (bin) => {
+ if (bin === '/old/tailcat') return 'v0.5.0';
+ if (bin === '/new/tailcat') return 'v0.6.0';
+ return null;
+ });
+ await expect(detectTailcat({
+ candidates: ['/old/tailcat', '/new/tailcat'],
+ readOutput,
+ })).resolves.toBe('/new/tailcat');
+ await expect(detectTailcat({
+ candidates: ['/old/tailcat'],
+ readOutput,
+ })).resolves.toBeNull();
+ });
+
+ it('findTooOldTailcat reports a runnable but outdated binary', async () => {
+ await expect(findTooOldTailcat({
+ candidates: ['/old/tailcat'],
+ readOutput: async () => 'v0.5.0',
+ })).resolves.toEqual({ bin: '/old/tailcat', version: '0.5.0' });
+ });
+
+ it('ensureTailcatInstalled refuses a leftover 0.5.x after brew claims success', async () => {
+ const run = vi.fn(async () => {});
+ const error = await ensureTailcatInstalled({
+ detect: async () => null,
+ findTooOld: async () => ({ bin: '/opt/homebrew/bin/tailcat', version: '0.5.0' }),
+ platform: 'darwin',
+ installers: [{ label: 'brew install/upgrade tailcat', run }],
+ }).catch((err) => err);
+ expect(run).toHaveBeenCalledOnce();
+ expect(error).toMatchObject({ code: 'TAILCAT_VERSION_TOO_OLD', status: 503 });
+ expect(error.message).toContain('0.6.0+');
+ expect(error.message).toContain('found 0.5.0');
+ expect(error.message).toContain('brew upgrade tailcat');
+ expect(error.message).toContain('Do not set --psk=false');
+ });
+
+ it('ensureTailcatInstalled upgrades via installers when only an old binary is present', async () => {
+ let detectCalls = 0;
+ const run = vi.fn(async () => {});
+ const result = await ensureTailcatInstalled({
+ detect: async () => {
+ detectCalls += 1;
+ return detectCalls === 1 ? null : '/example/go/bin/tailcat';
+ },
+ findTooOld: async () => ({ bin: '/opt/homebrew/bin/tailcat', version: '0.5.0' }),
+ installers: [{ label: 'go install', run }],
+ });
+ expect(run).toHaveBeenCalledOnce();
+ expect(result).toEqual({ bin: '/example/go/bin/tailcat', installed: true });
+ });
+
+ it('ensureTailcatInstalled reports VERSION_TOO_OLD when no package manager and only 0.5.x exists', async () => {
+ await expect(ensureTailcatInstalled({
+ detect: async () => null,
+ findTooOld: async () => ({ bin: '/usr/local/bin/tailcat', version: '0.5.0' }),
+ installers: [],
+ platform: 'linux',
+ })).rejects.toMatchObject({ code: 'TAILCAT_VERSION_TOO_OLD', status: 503 });
+ });
+
+ it('points macOS at Homebrew, since tailcat ships no darwin release binary', () => {
+ expect(manualInstallHint('darwin')).toContain('brew upgrade tailcat');
+ expect(manualInstallHint('darwin')).toContain('brew install tailcat');
+ expect(manualInstallHint('darwin')).toContain('0.6.0+');
+ expect(manualInstallHint('darwin')).not.toContain('/releases');
+ expect(manualInstallHint('linux')).toContain('https://github.com/tailscale/tailcat/releases');
+ expect(manualInstallHint('linux')).toContain('0.6.0+');
+ });
+
+ it('lists brew before go, and only for package managers that exist', () => {
+ const runInstall = vi.fn(async () => {});
+ expect(listTailcatInstallers({ brewBin: '/opt/homebrew/bin/brew', goBin: '/usr/bin/go', runInstall })
+ .map((i) => i.label)).toEqual(['brew install/upgrade tailcat', 'go install']);
+ expect(listTailcatInstallers({ brewBin: null, goBin: '/usr/bin/go', runInstall })
+ .map((i) => i.label)).toEqual(['go install']);
+ expect(listTailcatInstallers({ brewBin: null, goBin: null, runInstall })).toEqual([]);
+ });
+
+ it('skips Homebrew auto-update so adding a peer does not refresh the formula index', async () => {
+ const runInstall = vi.fn(async () => {});
+ const [brew] = listTailcatInstallers({ brewBin: '/opt/homebrew/bin/brew', goBin: null, runInstall });
+ await brew.run();
+ expect(runInstall).toHaveBeenCalledWith('/opt/homebrew/bin/brew', ['install', 'tailcat'],
+ expect.objectContaining({ HOMEBREW_NO_AUTO_UPDATE: '1' }));
+ expect(runInstall).toHaveBeenCalledWith('/opt/homebrew/bin/brew', ['upgrade', 'tailcat'],
+ expect.objectContaining({ HOMEBREW_NO_AUTO_UPDATE: '1' }));
+ });
+
+ // The default runner maps a bufferedSpawn result onto the message the operator
+ // reads in the toast; each terminal condition has to say something different.
+ it.each([
+ ['a non-zero exit', { success: false, code: 1, stdout: '', stderr: 'Warning: tap not trusted\nError: No available formula\n', timedOut: false },
+ 'Error: No available formula'],
+ ['a spawn failure', { success: false, code: -1, stdout: '', stderr: '', timedOut: false, error: new Error('spawn /example/missing/go ENOENT') },
+ 'spawn /example/missing/go ENOENT'],
+ ['a silent non-zero exit', { success: false, code: 7, stdout: '', stderr: '', timedOut: false }, 'exit 7'],
+ ['a timeout', { success: false, code: -1, stdout: '', stderr: '', timedOut: true }, 'timed out after 180s'],
+ ])('surfaces %s as a readable install error', async (_label, result, expected) => {
+ bufferedSpawn.mockResolvedValueOnce(result);
+ const [installer] = listTailcatInstallers({ brewBin: null, goBin: '/example/go' });
+ await expect(installer.run()).rejects.toThrow(expected);
+ });
+
+ it('treats a clean install-command exit as success', async () => {
+ bufferedSpawn
+ .mockResolvedValueOnce({ success: true, code: 0, stdout: '', stderr: '', timedOut: false })
+ .mockResolvedValueOnce({ success: true, code: 0, stdout: '', stderr: '', timedOut: false });
+ const [installer] = listTailcatInstallers({ brewBin: '/example/brew', goBin: null });
+ await expect(installer.run()).resolves.toBeUndefined();
+ expect(bufferedSpawn).toHaveBeenCalledWith('/example/brew', ['install', 'tailcat'],
+ expect.objectContaining({ env: expect.objectContaining({ HOMEBREW_NO_AUTO_UPDATE: '1' }) }));
+ expect(bufferedSpawn).toHaveBeenCalledWith('/example/brew', ['upgrade', 'tailcat'],
+ expect.objectContaining({ env: expect.objectContaining({ HOMEBREW_NO_AUTO_UPDATE: '1' }) }));
+ });
+
+ it('looks for tailcat in the GOBIN and Homebrew prefixes a server may not have on PATH', () => {
+ // Empty PATH so the injected env is the only source — the real PATH must not leak in.
+ const bins = listCandidateTailcatBins({
+ env: { PATH: '', GOBIN: join('/example', 'gobin'), HOMEBREW_PREFIX: join('/example', 'brew') },
+ home: join('/example', 'home'),
+ });
+ expect(bins).toEqual([
+ join('/example', 'gobin', 'tailcat'),
+ join('/example', 'gobin', 'tailcat.exe'),
+ join('/example', 'brew', 'bin', 'tailcat'),
+ join('/opt', 'homebrew', 'bin', 'tailcat'),
+ join('/usr', 'local', 'bin', 'tailcat'),
+ ]);
+ // No GOBIN → the first GOPATH entry's bin; no GOPATH at all → ~/go/bin.
+ expect(listCandidateTailcatBins({
+ env: { PATH: '', GOPATH: [join('/example', 'gopath'), join('/example', 'other')].join(delimiter) },
+ home: join('/example', 'home'),
+ })).toContain(join('/example', 'gopath', 'bin', 'tailcat'));
+ expect(listCandidateTailcatBins({ env: { PATH: '' }, home: join('/example', 'home') }))
+ .toContain(join('/example', 'home', 'go', 'bin', 'tailcat'));
+ });
+
+ 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');
+ expect(derpMapCachePath({
+ url: 'https://example.com/derpmap.json', platform: 'win32', home: 'C:\\example\\home',
+ env: { LOCALAPPDATA: 'C:\\example\\cache' },
+ })).toBe('C:\\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' });
+ });
+});
diff --git a/server/services/tailcatServe.js b/server/services/tailcatServe.js
index c68d9185fd..9fe0368468 100644
--- a/server/services/tailcatServe.js
+++ b/server/services/tailcatServe.js
@@ -24,13 +24,12 @@ import { createMutex } from '../lib/asyncMutex.js';
import { PORTS } from '../lib/ports.js';
import { ServerError } from '../lib/errorHandler.js';
import { safeChildProcessEnv, safeChildProcessOptions } from '../lib/processEnv.js';
+import { ensureTailcatInstalled, primeDerpMapCache } from './tailcatRuntime.js';
import {
- ensureTailcatInstalled,
- primeDerpMapCache,
isValidTcAddress,
redactTcAddress,
redactTailcatDiagnostics,
-} from './tailcatPeer.js';
+} from '../lib/tailcatAddress.js';
const SERVE_FILE = dataPath('tailcat-serve.json');
const ADDR_FILE = dataPath('tailcat-serve.addr');
diff --git a/server/services/tailcatServe.test.js b/server/services/tailcatServe.test.js
index 09f7f344ca..e7e7038bbf 100644
--- a/server/services/tailcatServe.test.js
+++ b/server/services/tailcatServe.test.js
@@ -30,6 +30,13 @@ vi.mock('../lib/bufferedSpawn.js', async (original) => ({
}));
import { bufferedSpawn } from '../lib/bufferedSpawn.js';
+// No installed CLI or package manager: exercise the real shared installation failure.
+vi.mock('../lib/commandExists.js', () => ({ commandOutput: vi.fn().mockResolvedValue(null) }));
+vi.mock('../lib/processEnv.js', async (original) => ({
+ ...(await original()),
+ findCommandOnPath: vi.fn().mockReturnValue(null),
+}));
+
const EXAMPLE_TC = 'tcEXAMPLE' + 'C'.repeat(40);
function fakeChild() {
@@ -55,6 +62,15 @@ describe('tailcatServe helpers', () => {
_resetLiveServeForTests();
});
+ it('surfaces shared installation failure without starting a tunnel', async () => {
+ const startServe = vi.fn();
+ await expect(ensureTailcatServe({ startServe })).rejects.toMatchObject({
+ status: 503, code: 'TAILCAT_MISSING',
+ });
+ expect(startServe).not.toHaveBeenCalled();
+ expect(await getTailcatServeStatus()).toMatchObject({ live: false });
+ });
+
it('parses --json listenAddr and rejects placeholders', () => {
expect(parseServeListenAddr(JSON.stringify({ listenAddr: EXAMPLE_TC }))).toBe(EXAMPLE_TC);
expect(parseServeListenAddr(`noise\n{"listenAddr":"${EXAMPLE_TC}"}\n`)).toBe(EXAMPLE_TC);