|
| 1 | +import { cmd } from "./cmd" |
| 2 | +import { dim, bold, success, highlight } from "./iris-api" |
| 3 | +import { spawnSync } from "child_process" |
| 4 | +import { existsSync, writeFileSync } from "fs" |
| 5 | +import { join } from "path" |
| 6 | +import { homedir } from "os" |
| 7 | + |
| 8 | +// ============================================================================ |
| 9 | +// iris hive vpn — Tailscale (WireGuard) transport layer for the Hive |
| 10 | +// |
| 11 | +// The Hive's enroll/run commands already talk to nodes over SSH. The missing |
| 12 | +// piece is a SECURE TRANSPORT so a machine that isn't on your LAN (a home |
| 13 | +// desktop, an office mini-PC, a cloud VM) becomes reachable WITHOUT opening |
| 14 | +// ports to the internet. Tailscale gives every joined machine a stable |
| 15 | +// 100.x tailnet IP; the existing `iris hive enroll <tailnet-ip>` then works |
| 16 | +// over that encrypted tunnel. |
| 17 | +// |
| 18 | +// Layer 1 Tailscale (this file) → encrypted mesh, no public ports |
| 19 | +// Layer 2 Google Workspace Group → who is allowed (ACL src) |
| 20 | +// Layer 3 IRIS HIVE node → enroll/run/audit over the tailnet |
| 21 | +// |
| 22 | +// First use case: VPN IRIS HIVE bloq #531 — Drex accounting team reaches a |
| 23 | +// QuickBooks Desktop host over RDP, scoped to the `drex-accounting` group. |
| 24 | +// ============================================================================ |
| 25 | + |
| 26 | +// ── Tailscale CLI locator ──────────────────────────────────────────────────── |
| 27 | + |
| 28 | +// Common install locations, in preference order. The Windows path matters: |
| 29 | +// the first-class use case (#531) is a Windows QuickBooks host, where Tailscale |
| 30 | +// installs outside PATH and `command -v` doesn't exist. |
| 31 | +const KNOWN_BINS = [ |
| 32 | + "/Applications/Tailscale.app/Contents/MacOS/Tailscale", // macOS app bundle |
| 33 | + "/usr/local/bin/tailscale", // macOS (brew) / Linux |
| 34 | + "/usr/bin/tailscale", // Linux |
| 35 | + "C:\\Program Files\\Tailscale\\tailscale.exe", // Windows |
| 36 | +] |
| 37 | + |
| 38 | +function tailscaleBin(): string | null { |
| 39 | + // 1. PATH lookup — `where` on Windows, `command -v` on POSIX. |
| 40 | + const [locator, ...locatorArgs] = |
| 41 | + process.platform === "win32" ? ["where", "tailscale"] : ["command", "-v", "tailscale"] |
| 42 | + const which = spawnSync(locator, locatorArgs, { shell: true, encoding: "utf8" }) |
| 43 | + if (which.status === 0 && which.stdout.trim()) { |
| 44 | + // `where` can return multiple lines; take the first hit. |
| 45 | + return which.stdout.trim().split(/\r?\n/)[0].trim() |
| 46 | + } |
| 47 | + // 2. Known install paths (covers Tailscale.app on macOS + the Windows .exe). |
| 48 | + for (const p of KNOWN_BINS) if (existsSync(p)) return p |
| 49 | + return null |
| 50 | +} |
| 51 | + |
| 52 | +function ts(args: string[], timeoutSec = 20): { ok: boolean; stdout: string; stderr: string } { |
| 53 | + const bin = tailscaleBin() |
| 54 | + if (!bin) return { ok: false, stdout: "", stderr: "tailscale-not-installed" } |
| 55 | + const r = spawnSync(bin, args, { encoding: "utf8", timeout: timeoutSec * 1000 }) |
| 56 | + return { ok: r.status === 0, stdout: r.stdout ?? "", stderr: r.stderr ?? "" } |
| 57 | +} |
| 58 | + |
| 59 | +interface TsNode { |
| 60 | + name: string |
| 61 | + dnsName: string |
| 62 | + os: string |
| 63 | + tailscaleIP: string |
| 64 | + online: boolean |
| 65 | + self: boolean |
| 66 | +} |
| 67 | + |
| 68 | +interface TsStatus { |
| 69 | + installed: boolean |
| 70 | + loggedIn: boolean |
| 71 | + tailnet: string | null |
| 72 | + self: TsNode | null |
| 73 | + peers: TsNode[] |
| 74 | +} |
| 75 | + |
| 76 | +function toNode(raw: any, self: boolean): TsNode { |
| 77 | + return { |
| 78 | + name: raw?.HostName ?? raw?.DNSName ?? "unknown", |
| 79 | + dnsName: (raw?.DNSName ?? "").replace(/\.$/, ""), |
| 80 | + os: raw?.OS ?? "?", |
| 81 | + tailscaleIP: Array.isArray(raw?.TailscaleIPs) ? raw.TailscaleIPs[0] : "", |
| 82 | + online: !!raw?.Online, |
| 83 | + self, |
| 84 | + } |
| 85 | +} |
| 86 | + |
| 87 | +function readStatus(): TsStatus { |
| 88 | + const out: TsStatus = { installed: false, loggedIn: false, tailnet: null, self: null, peers: [] } |
| 89 | + const bin = tailscaleBin() |
| 90 | + if (!bin) return out |
| 91 | + out.installed = true |
| 92 | + const r = ts(["status", "--json"]) |
| 93 | + if (!r.ok || !r.stdout.trim()) { |
| 94 | + // BackendState=NeedsLogin still returns JSON on most versions; fall through |
| 95 | + if (/NeedsLogin|Logged out|logged out/i.test(r.stderr + r.stdout)) out.loggedIn = false |
| 96 | + return out |
| 97 | + } |
| 98 | + try { |
| 99 | + const j = JSON.parse(r.stdout) |
| 100 | + out.loggedIn = j?.BackendState === "Running" |
| 101 | + out.tailnet = j?.CurrentTailnet?.Name ?? j?.MagicDNSSuffix ?? null |
| 102 | + if (j?.Self) out.self = toNode(j.Self, true) |
| 103 | + if (j?.Peer && typeof j.Peer === "object") { |
| 104 | + out.peers = Object.values(j.Peer).map((p) => toNode(p, false)) |
| 105 | + } |
| 106 | + } catch { |
| 107 | + /* leave defaults */ |
| 108 | + } |
| 109 | + return out |
| 110 | +} |
| 111 | + |
| 112 | +// ── vpn check (preflight — run this BEFORE buying anything) ────────────────── |
| 113 | + |
| 114 | +const VpnCheckCommand = cmd({ |
| 115 | + command: "check", |
| 116 | + describe: "preflight the secure-mesh prerequisites on THIS machine (install, login, node IP)", |
| 117 | + builder: (y) => y.option("json", { describe: "JSON output", type: "boolean", default: false }), |
| 118 | + async handler(argv) { |
| 119 | + const s = readStatus() |
| 120 | + if (argv.json) { |
| 121 | + console.log(JSON.stringify(s, null, 2)) |
| 122 | + return |
| 123 | + } |
| 124 | + console.log() |
| 125 | + console.log(bold("Secure-mesh preflight (this machine)")) |
| 126 | + console.log(` ${dim("tailscale installed:")} ${s.installed ? success("yes") : highlight("NO — install it first")}`) |
| 127 | + if (!s.installed) { |
| 128 | + console.log() |
| 129 | + console.log(bold("To install Tailscale:")) |
| 130 | + console.log(` ${dim("macOS:")} brew install --cask tailscale ${dim("(or App Store)")}`) |
| 131 | + console.log(` ${dim("Windows:")} https://tailscale.com/download/windows`) |
| 132 | + console.log(` ${dim("Linux:")} curl -fsSL https://tailscale.com/install.sh | sh`) |
| 133 | + console.log() |
| 134 | + console.log(dim(" Then: iris hive vpn up to join the tailnet.")) |
| 135 | + return |
| 136 | + } |
| 137 | + console.log(` ${dim("logged in:")} ${s.loggedIn ? success("yes") : highlight("no — run: iris hive vpn up")}`) |
| 138 | + if (s.tailnet) console.log(` ${dim("tailnet:")} ${s.tailnet}`) |
| 139 | + if (s.self) { |
| 140 | + console.log(` ${dim("this node:")} ${bold(s.self.name)} ${dim(s.self.tailscaleIP)} (${s.self.os})`) |
| 141 | + } |
| 142 | + console.log(` ${dim("peers visible:")} ${s.peers.length}`) |
| 143 | + console.log() |
| 144 | + console.log(bold("Checklist for the Drex / QuickBooks host (#531):")) |
| 145 | + console.log(` ${s.loggedIn ? success("✓") : dim("•")} 1. Host machine is Windows 10/11 ${bold("Pro")} (Home cannot host RDP)`) |
| 146 | + console.log(` ${dim("•")} 2. Tailscale installed + logged in on the host ${dim("(iris hive vpn up)")}`) |
| 147 | + console.log(` ${dim("•")} 3. Tailscale installed on each Drex machine`) |
| 148 | + console.log(` ${dim("•")} 4. ACL grants drex-accounting RDP to ONLY the host ${dim("(iris hive vpn grant)")}`) |
| 149 | + console.log(` ${dim("•")} 5. Host registered as a Hive node ${dim("(iris hive vpn enroll)")}`) |
| 150 | + console.log() |
| 151 | + }, |
| 152 | +}) |
| 153 | + |
| 154 | +// ── vpn up (join this machine to the tailnet) ──────────────────────────────── |
| 155 | + |
| 156 | +const VpnUpCommand = cmd({ |
| 157 | + command: "up", |
| 158 | + describe: "bring THIS machine onto the tailnet (prints a login URL on first run)", |
| 159 | + builder: (y) => |
| 160 | + y |
| 161 | + .option("hostname", { describe: "name this node shows as on the tailnet", type: "string" }) |
| 162 | + .option("ssh", { describe: "enable Tailscale SSH on this node", type: "boolean", default: false }) |
| 163 | + .option("tag", { describe: "apply an ACL tag, e.g. tag:qb-host", type: "string" }), |
| 164 | + async handler(argv) { |
| 165 | + if (!tailscaleBin()) { |
| 166 | + console.log(`${highlight("!")} Tailscale isn't installed. Run: ${bold("iris hive vpn check")}`) |
| 167 | + process.exit(1) |
| 168 | + } |
| 169 | + const args = ["up"] |
| 170 | + if (argv.hostname) args.push(`--hostname=${argv.hostname}`) |
| 171 | + if (argv.ssh) args.push("--ssh") |
| 172 | + if (argv.tag) args.push(`--advertise-tags=${argv.tag}`) |
| 173 | + console.log(`${dim("→")} ${bold("tailscale " + args.join(" "))}`) |
| 174 | + console.log(dim(" (follow the login URL if prompted — sign in with the Google Workspace account)")) |
| 175 | + // inherit stdio so the auth URL + browser prompt are visible |
| 176 | + const r = spawnSync(tailscaleBin()!, args, { stdio: "inherit" }) |
| 177 | + if (r.status !== 0) process.exit(r.status ?? 1) |
| 178 | + const s = readStatus() |
| 179 | + if (s.self) { |
| 180 | + console.log() |
| 181 | + console.log(`${success("✓")} on the tailnet as ${bold(s.self.name)} ${dim(s.self.tailscaleIP)}`) |
| 182 | + console.log(dim(` Next: iris hive vpn status to see peers.`)) |
| 183 | + } |
| 184 | + }, |
| 185 | +}) |
| 186 | + |
| 187 | +// ── vpn status (map every machine on the tailnet) ──────────────────────────── |
| 188 | + |
| 189 | +const VpnStatusCommand = cmd({ |
| 190 | + command: "status", |
| 191 | + describe: "list every machine on the tailnet (name, OS, tailnet IP, online)", |
| 192 | + builder: (y) => y.option("json", { describe: "JSON output", type: "boolean", default: false }), |
| 193 | + async handler(argv) { |
| 194 | + const s = readStatus() |
| 195 | + if (argv.json) { |
| 196 | + console.log(JSON.stringify(s, null, 2)) |
| 197 | + return |
| 198 | + } |
| 199 | + if (!s.installed) { |
| 200 | + console.log(`${highlight("!")} Tailscale not installed — run: ${bold("iris hive vpn check")}`) |
| 201 | + process.exit(1) |
| 202 | + } |
| 203 | + if (!s.loggedIn) { |
| 204 | + console.log(`${highlight("!")} not logged in — run: ${bold("iris hive vpn up")}`) |
| 205 | + process.exit(1) |
| 206 | + } |
| 207 | + const all = [s.self, ...s.peers].filter(Boolean) as TsNode[] |
| 208 | + console.log() |
| 209 | + console.log(bold(`Tailnet ${s.tailnet ?? ""}`.trim()) + dim(` (${all.length} machines)`)) |
| 210 | + for (const n of all) { |
| 211 | + const dot = n.online ? success("●") : dim("○") |
| 212 | + const who = n.self ? bold(n.name) + dim(" (this)") : n.name |
| 213 | + console.log(` ${dot} ${who.padEnd(28)} ${dim(n.tailscaleIP.padEnd(16))} ${dim(n.os)}`) |
| 214 | + } |
| 215 | + console.log() |
| 216 | + console.log(dim(` Enroll one as a Hive node: iris hive vpn enroll <tailnet-ip>`)) |
| 217 | + }, |
| 218 | +}) |
| 219 | + |
| 220 | +// ── vpn grant (emit the Tailscale ACL: a Google Group → one node, RDP only) ── |
| 221 | + |
| 222 | +const VpnGrantCommand = cmd({ |
| 223 | + command: "grant <group> <node-tag>", |
| 224 | + describe: "scaffold a least-privilege Tailscale ACL (group → node, one port) and print it", |
| 225 | + builder: (y) => |
| 226 | + y |
| 227 | + .positional("group", { describe: "google group, e.g. drex-accounting", type: "string", demandOption: true }) |
| 228 | + .positional("node-tag", { describe: "destination tag, e.g. qb-host", type: "string", demandOption: true }) |
| 229 | + .option("port", { describe: "port to allow (RDP=3389)", type: "number", default: 3389 }) |
| 230 | + .option("members", { describe: "comma-separated emails for the group", type: "string" }) |
| 231 | + .option("write", { describe: "write the policy to ~/.iris/tailscale-acl.json", type: "boolean", default: false }), |
| 232 | + async handler(argv) { |
| 233 | + const group = String(argv.group).replace(/^group:/, "") |
| 234 | + const tag = String(argv["node-tag"]).replace(/^tag:/, "") |
| 235 | + const port = Number(argv.port) |
| 236 | + const members = argv.members |
| 237 | + ? String(argv.members).split(",").map((m) => m.trim()).filter(Boolean) |
| 238 | + |
| 239 | + |
| 240 | + // Least-privilege ACL: only `group:<group>` may reach `tag:<tag>` on `port`, |
| 241 | + // nothing else on the mesh. Groups should be SSO-synced from Google Workspace. |
| 242 | + const policy = { |
| 243 | + groups: { [`group:${group}`]: members }, |
| 244 | + tagOwners: { [`tag:${tag}`]: ["autogroup:admin"] }, |
| 245 | + acls: [ |
| 246 | + { |
| 247 | + action: "accept", |
| 248 | + src: [`group:${group}`], |
| 249 | + dst: [`tag:${tag}:${port}`], |
| 250 | + }, |
| 251 | + ], |
| 252 | + // ssh: scoped session logging can be added here for the audit trail |
| 253 | + } |
| 254 | + const blob = JSON.stringify(policy, null, 2) |
| 255 | + console.log() |
| 256 | + console.log(bold(`Tailscale ACL — ${group} → tag:${tag} on port ${port} (RDP)`)) |
| 257 | + console.log(dim(" Paste into the Tailscale admin → Access Controls, or `tailscale set` via API.")) |
| 258 | + console.log() |
| 259 | + console.log(blob) |
| 260 | + if (argv.write) { |
| 261 | + const out = join(homedir(), ".iris", "tailscale-acl.json") |
| 262 | + writeFileSync(out, blob + "\n") |
| 263 | + console.log() |
| 264 | + console.log(`${success("✓")} wrote ${bold(out)}`) |
| 265 | + } |
| 266 | + console.log() |
| 267 | + console.log(dim(` Members default to placeholders — pass --members "[email protected],[email protected]" or sync from the Google Group.`)) |
| 268 | + }, |
| 269 | +}) |
| 270 | + |
| 271 | +// ── vpn enroll (bridge: register a tailnet peer as a Hive node over the tunnel) |
| 272 | + |
| 273 | +const VpnEnrollCommand = cmd({ |
| 274 | + command: "enroll <tailnet-ip>", |
| 275 | + describe: "register a tailnet machine as a Hive node over the secure tunnel (wraps `hive enroll`)", |
| 276 | + builder: (y) => |
| 277 | + y |
| 278 | + .positional("tailnet-ip", { describe: "the peer's 100.x tailnet IP (see: iris hive vpn status)", type: "string", demandOption: true }) |
| 279 | + .option("user", { describe: "ssh user on the host", type: "string", default: "iris" }), |
| 280 | + async handler(argv) { |
| 281 | + const ip = String(argv["tailnet-ip"]) |
| 282 | + if (!/^100\./.test(ip)) { |
| 283 | + console.log(`${highlight("!")} ${ip} is not a tailnet IP (expected 100.x). Run: ${bold("iris hive vpn status")}`) |
| 284 | + } |
| 285 | + const target = `${argv.user}@${ip}` |
| 286 | + console.log(`${dim("→")} enrolling ${bold(target)} over the tailnet...`) |
| 287 | + console.log(dim(" This reuses the existing SSH enroll path — the tunnel just makes the host reachable.")) |
| 288 | + // Hand off to the already-built enroll command for the real work. |
| 289 | + const r = spawnSync("iris", ["hive", "enroll", target], { stdio: "inherit" }) |
| 290 | + process.exit(r.status ?? 0) |
| 291 | + }, |
| 292 | +}) |
| 293 | + |
| 294 | +// ── group command ───────────────────────────────────────────────────────────── |
| 295 | + |
| 296 | +export const HiveVpnCommandExport = cmd({ |
| 297 | + command: "vpn <subcommand>", |
| 298 | + describe: "secure mesh (Tailscale/WireGuard) transport for Hive nodes — no open ports", |
| 299 | + builder: (y) => |
| 300 | + y |
| 301 | + .command(VpnCheckCommand) |
| 302 | + .command(VpnUpCommand) |
| 303 | + .command(VpnStatusCommand) |
| 304 | + .command(VpnGrantCommand) |
| 305 | + .command(VpnEnrollCommand) |
| 306 | + .demandCommand(1, "Run: iris hive vpn check"), |
| 307 | + handler() {}, |
| 308 | +}) |
0 commit comments