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

7.2 KB
Raw Blame
import { existsSync } from 'fs';
import { join, delimiter } from 'path';
import { execFile } from './childProcess.js';
import { promisify } from 'util';
import { safeJSONParse } from './fileUtils.js';

const execFileAsync = promisify(execFile);
const STATUS_CACHE_TTL_MS = 10_000;

// Setup, capability, and instance surfaces can poll in the same render cycle.
// Keep one short-lived local-daemon snapshot so they share a single CLI probe.
// `null` deliberately means "not fetched"; a valid unavailable status object
// is still cached instead of re-running the command on every request.
let statusCacheValue = null;
let statusCacheAt = 0;
let statusInFlight = null;

const isWin = () => process.platform === 'win32';
const tailscaleBin = () => (isWin() ? 'tailscale.exe' : 'tailscale');

export const MACOS_TAILSCALE_APP_BUNDLE = '/Applications/Tailscale.app/Contents/MacOS/Tailscale';

// Paths where the Tailscale CLI binary is commonly found. On macOS the GUI app
// doesn't put the CLI in PATH by default; Homebrew installs to /usr/local/bin
// (Intel) or /opt/homebrew/bin (Apple Silicon); Linux packages land in /usr/bin;
// Windows installs land in Program Files.
//
// On macOS we prefer Homebrew over the App Store bundle. The Mac App Store
// build of Tailscale runs under macOS App Sandbox and `tailscale cert` cannot
// write the cert temp file outside its container (EPERM "operation not
// permitted" when targeting paths like data/certs/). The Homebrew binary is
// the open-source CLI and is not sandboxed, so it can write anywhere the
// shell user can. App-bundle is kept as a last-resort fallback.
// Resolved per call rather than frozen at import: hasOnlySandboxedTailscale is
// gated on `process.platform === 'darwin'`, so pinning the candidate list to
// whatever platform happened to import the module would have it scan the wrong
// paths for the platform it just decided it is on.
const tailscaleCandidates = () => (isWin()
  ? [
      'C:\\Program Files\\Tailscale\\tailscale.exe',
      'C:\\Program Files (x86)\\Tailscale\\tailscale.exe'
    ]
  : [
      '/opt/homebrew/bin/tailscale',
      '/usr/local/bin/tailscale',
      '/usr/bin/tailscale',
      MACOS_TAILSCALE_APP_BUNDLE
    ]);

export function findTailscale() {
  for (const p of tailscaleCandidates()) {
    if (existsSync(p)) return p;
  }
  // Use path.delimiter (';' on Windows, ':' elsewhere) so PATH scanning works cross-platform.
  for (const dir of (process.env.PATH || '').split(delimiter)) {
    if (!dir) continue;
    const p = join(dir, tailscaleBin());
    if (existsSync(p)) return p;
  }
  return null;
}

export function isSandboxedTailscale(binPath) {
  return binPath === MACOS_TAILSCALE_APP_BUNDLE;
}

/**
 * Read the Tailscale backend state via `tailscale status --json`.
 *
 * Distinguishes the states that matter for deciding whether federated peer
 * probing is worth attempting — the CLI cleanly exits 0 with
 * `BackendState: "Stopped"` when Tailscale is installed but not connected, so a
 * mere "binary exists" check (findTailscale) is NOT enough to know we're on the
 * tailnet. Returns:
 *   - available: the CLI binary was found
 *   - running:   BackendState === 'Running' (connected to the tailnet)
 *   - state:     raw BackendState string, or null when unknown
 *   - reason:    machine-readable classification for logs/UI
 *
 * Never throws — execFile failures and non-JSON output degrade to a
 * not-running result so callers can treat this as a plain boolean gate.
 */
async function readTailscaleStatus() {
  const bin = findTailscale();
  const unavailable = (reason, { available = true } = {}) => ({
    available,
    running: false,
    state: null,
    reason,
    sandboxed: bin ? isSandboxedTailscale(bin) : false,
    dnsName: null,
    magicDnsSuffix: null,
    peers: [],
  });
  if (!bin) return unavailable('tailscale-not-installed', { available: false });
  const { stdout } = await execFileAsync(bin, ['status', '--json'], { timeout: 5000 })
    .catch(() => ({ stdout: null }));
  if (!stdout) return unavailable('tailscale-status-failed');
  // Guard against non-JSON output (warnings, partial reads) so we never throw.
  const status = safeJSONParse(stdout, null);
  if (!status) return unavailable('tailscale-parse-error');
  const state = typeof status?.BackendState === 'string' && status.BackendState.trim()
    ? status.BackendState.trim()
    : null;
  const trimDnsName = (value) => typeof value === 'string'
    ? value.trim().replace(/\.$/, '') || null
    : null;
  const peers = Object.values(status?.Peer ?? {}).map((peer) => ({
    dnsName: trimDnsName(peer?.DNSName),
    hostName: typeof peer?.HostName === 'string' && peer.HostName.trim()
      ? peer.HostName.trim()
      : null,
    ips: Array.isArray(peer?.TailscaleIPs)
      ? peer.TailscaleIPs.filter((ip) => typeof ip === 'string')
      : [],
  }));
  return {
    available: true,
    running: state === 'Running',
    state,
    reason: state === 'Running' ? 'running' : `tailscale-${(state || 'unknown').toLowerCase()}`,
    sandboxed: isSandboxedTailscale(bin),
    dnsName: trimDnsName(status?.Self?.DNSName),
    magicDnsSuffix: trimDnsName(
      status?.CurrentTailnet?.MagicDNSSuffix ?? status?.MagicDNSSuffix,
    ),
    peers,
  };
}

export function __resetTailscaleStatusCache() {
  statusCacheValue = null;
  statusCacheAt = 0;
  statusInFlight = null;
}

export async function getTailscaleStatus({ force = false } = {}) {
  if (!force && statusCacheValue !== null && Date.now() - statusCacheAt < STATUS_CACHE_TTL_MS) {
    return statusCacheValue;
  }
  if (!force && statusInFlight) return statusInFlight;

  const request = readTailscaleStatus();
  const tracked = request.then(
    (value) => {
      // A forced refresh may have superseded this probe. Only the newest probe
      // publishes shared state, while existing callers still receive theirs.
      if (statusInFlight === tracked) {
        statusCacheValue = value;
        statusCacheAt = Date.now();
        statusInFlight = null;
      }
      return value;
    },
    (error) => {
      if (statusInFlight === tracked) statusInFlight = null;
      throw error;
    },
  );
  statusInFlight = tracked;
  return tracked;
}

/**
 * Convenience boolean: true only when Tailscale is installed AND connected to
 * the tailnet (BackendState === 'Running').
 */
export async function isTailscaleUp() {
  const { running } = await getTailscaleStatus();
  return running;
}

export function hasOnlySandboxedTailscale() {
  if (process.platform !== 'darwin') return false;
  // True iff the MAS app bundle exists AND no unsandboxed binary is
  // reachable anywhere. The previous implementation delegated to
  // findTailscale which returns the FIRST candidate in tailscaleCandidates()
  // order — so an unsandboxed `tailscale` living in a non-standard $PATH
  // directory (not in tailscaleCandidates()) was missed entirely, and we
  // misclassified the machine as sandboxed-only.
  if (!existsSync(MACOS_TAILSCALE_APP_BUNDLE)) return false;
  for (const p of tailscaleCandidates()) {
    if (p === MACOS_TAILSCALE_APP_BUNDLE) continue;
    if (existsSync(p)) return false;
  }
  for (const dir of (process.env.PATH || '').split(delimiter)) {
    if (!dir) continue;
    const p = join(dir, tailscaleBin());
    if (existsSync(p) && p !== MACOS_TAILSCALE_APP_BUNDLE) return false;
  }
  return true;
}