|
| 1 | +import { cmd } from "./cmd" |
| 2 | +import { dim, bold, success, highlight } from "./iris-api" |
| 3 | +import { spawnSync } from "child_process" |
| 4 | + |
| 5 | +// ============================================================================ |
| 6 | +// iris hive host — provision a secure Windows RDP host (the QB/PHI box) |
| 7 | +// |
| 8 | +// `iris hive vpn` gets Tailscale onto a machine you're sitting at. `iris hive |
| 9 | +// host` drives a REMOTE Azure VM through `az vm run-command` so you never have |
| 10 | +// to RDP in by hand to set it up. It automates the exact sequence proven on the |
| 11 | +// #531 test box: |
| 12 | +// |
| 13 | +// setup → install Tailscale on the VM (headless, via auth key) + join tailnet |
| 14 | +// add-user → create a dedicated RDP user (never the admin login) + RDP group |
| 15 | +// grant → share the tailnet node with an external user (e.g. Drex) |
| 16 | +// lockdown → delete the public RDP firewall rule → tunnel-only, PHI-ready |
| 17 | +// |
| 18 | +// Assumes the VM already exists (one-off `az vm create`) and you're logged in |
| 19 | +// with `az login`. Every step is idempotent and re-runnable. |
| 20 | +// |
| 21 | +// First use case: VPN IRIS HIVE bloq #531 — a QuickBooks Desktop host on Azure, |
| 22 | +// reachable only over Tailscale, scoped to the Drex accounting team. |
| 23 | +// ============================================================================ |
| 24 | + |
| 25 | +// ── az CLI plumbing ────────────────────────────────────────────────────────── |
| 26 | + |
| 27 | +function hasAz(): boolean { |
| 28 | + const [locator, ...args] = process.platform === "win32" ? ["where", "az"] : ["command", "-v", "az"] |
| 29 | + const r = spawnSync(locator, args, { shell: true, encoding: "utf8" }) |
| 30 | + return r.status === 0 && !!r.stdout.trim() |
| 31 | +} |
| 32 | + |
| 33 | +function az(args: string[], timeoutSec = 240): { ok: boolean; stdout: string; stderr: string } { |
| 34 | + const r = spawnSync("az", args, { encoding: "utf8", timeout: timeoutSec * 1000 }) |
| 35 | + return { ok: r.status === 0, stdout: r.stdout ?? "", stderr: r.stderr ?? "" } |
| 36 | +} |
| 37 | + |
| 38 | +// Run a PowerShell script INSIDE the VM via the Azure agent (no RDP, no open port). |
| 39 | +// Passing the whole script as ONE arg (no shell) sidesteps all quoting issues. |
| 40 | +function azRunPS(rg: string, vm: string, script: string, timeoutSec = 300) { |
| 41 | + return az( |
| 42 | + [ |
| 43 | + "vm", |
| 44 | + "run-command", |
| 45 | + "invoke", |
| 46 | + "--resource-group", |
| 47 | + rg, |
| 48 | + "--name", |
| 49 | + vm, |
| 50 | + "--command-id", |
| 51 | + "RunPowerShellScript", |
| 52 | + "--scripts", |
| 53 | + script, |
| 54 | + "--query", |
| 55 | + "value[0].message", |
| 56 | + "-o", |
| 57 | + "tsv", |
| 58 | + ], |
| 59 | + timeoutSec, |
| 60 | + ) |
| 61 | +} |
| 62 | + |
| 63 | +function requireAzOrExit() { |
| 64 | + if (!hasAz()) { |
| 65 | + console.log(`${highlight("!")} Azure CLI not found. Install it: ${bold("brew install azure-cli")} then ${bold("az login")}`) |
| 66 | + process.exit(1) |
| 67 | + } |
| 68 | +} |
| 69 | + |
| 70 | +// ── host add-user (dedicated RDP user — the create-haroon.ps1 logic) ───────── |
| 71 | + |
| 72 | +const HostAddUserCommand = cmd({ |
| 73 | + command: "add-user <vm> <user>", |
| 74 | + describe: "create a dedicated RDP Windows user on the VM (+ Remote Desktop group), one-time password", |
| 75 | + builder: (y) => |
| 76 | + y |
| 77 | + .positional("vm", { describe: "Azure VM name, e.g. qb-host-vanguard", type: "string", demandOption: true }) |
| 78 | + .positional("user", { describe: "Windows username to create, e.g. haroon", type: "string", demandOption: true }) |
| 79 | + .option("resource-group", { alias: "g", describe: "Azure resource group", type: "string", demandOption: true }) |
| 80 | + .option("full-name", { describe: "display name for the account", type: "string" }), |
| 81 | + async handler(argv) { |
| 82 | + requireAzOrExit() |
| 83 | + const rg = String(argv["resource-group"]) |
| 84 | + const vm = String(argv.vm) |
| 85 | + const user = String(argv.user).replace(/[^A-Za-z0-9._-]/g, "") |
| 86 | + const fullName = argv["full-name"] ? String(argv["full-name"]) : `${user} (Hive RDP)` |
| 87 | + |
| 88 | + // Strong one-time password generated ON the box; forced change at first logon. |
| 89 | + const ps = [ |
| 90 | + `$ErrorActionPreference='Stop'`, |
| 91 | + `$user='${user}'`, |
| 92 | + `$chars='ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnpqrstuvwxyz23456789'`, |
| 93 | + `$rand=-join ((1..16) | ForEach-Object { $chars[(Get-Random -Maximum $chars.Length)] })`, |
| 94 | + `$pw='Qb'+$rand+'#7'`, |
| 95 | + `$sec=ConvertTo-SecureString $pw -AsPlainText -Force`, |
| 96 | + `if (Get-LocalUser -Name $user -ErrorAction SilentlyContinue) { Set-LocalUser -Name $user -Password $sec; $status='reset-existing' }`, |
| 97 | + `else { New-LocalUser -Name $user -Password $sec -FullName '${fullName}' -Description 'Hive RDP access' -AccountNeverExpires | Out-Null; $status='created' }`, |
| 98 | + `Add-LocalGroupMember -Group 'Remote Desktop Users' -Member $user -ErrorAction SilentlyContinue`, |
| 99 | + `$u=[ADSI]("WinNT://./$user,user"); $u.PasswordExpired=1; $u.SetInfo()`, |
| 100 | + `'STATUS='+$status`, |
| 101 | + `'TEMP_PASSWORD='+$pw`, |
| 102 | + ].join("\n") |
| 103 | + |
| 104 | + console.log(`${dim("→")} creating Windows user ${bold(user)} on ${bold(vm)} ${dim("(via az run-command)…")}`) |
| 105 | + const r = azRunPS(rg, vm, ps) |
| 106 | + if (!r.ok) { |
| 107 | + console.log(`${highlight("✗")} failed: ${dim((r.stderr || r.stdout).trim().split("\n").slice(-3).join(" "))}`) |
| 108 | + process.exit(1) |
| 109 | + } |
| 110 | + const pw = /TEMP_PASSWORD=(\S+)/.exec(r.stdout)?.[1] |
| 111 | + const status = /STATUS=(\S+)/.exec(r.stdout)?.[1] ?? "done" |
| 112 | + console.log() |
| 113 | + console.log(`${success("✓")} user ${bold(user)} ${dim("(" + status + ")")} — in the Remote Desktop Users group`) |
| 114 | + if (pw) { |
| 115 | + console.log(` ${dim("one-time password:")} ${bold(pw)}`) |
| 116 | + console.log(dim(` Deliver over a secure channel; they must change it at first logon.`)) |
| 117 | + } |
| 118 | + console.log() |
| 119 | + }, |
| 120 | +}) |
| 121 | + |
| 122 | +// ── host setup (install Tailscale on the VM, headless via auth key) ────────── |
| 123 | + |
| 124 | +const HostSetupCommand = cmd({ |
| 125 | + command: "setup <vm>", |
| 126 | + describe: "install Tailscale on the VM and join the tailnet (headless, via auth key)", |
| 127 | + builder: (y) => |
| 128 | + y |
| 129 | + .positional("vm", { describe: "Azure VM name", type: "string", demandOption: true }) |
| 130 | + .option("resource-group", { alias: "g", describe: "Azure resource group", type: "string", demandOption: true }) |
| 131 | + .option("authkey", { describe: "Tailscale auth key (login.tailscale.com/admin/settings/keys)", type: "string", demandOption: true }) |
| 132 | + .option("hostname", { describe: "tailnet hostname (defaults to the VM name)", type: "string" }), |
| 133 | + async handler(argv) { |
| 134 | + requireAzOrExit() |
| 135 | + const rg = String(argv["resource-group"]) |
| 136 | + const vm = String(argv.vm) |
| 137 | + const authkey = String(argv.authkey) |
| 138 | + const hostname = argv.hostname ? String(argv.hostname) : vm |
| 139 | + if (!/^tskey-/.test(authkey)) { |
| 140 | + console.log(`${highlight("!")} that doesn't look like a Tailscale auth key (expected tskey-…).`) |
| 141 | + process.exit(1) |
| 142 | + } |
| 143 | + |
| 144 | + // Download the stable MSI, install silently, then `tailscale up` unattended. |
| 145 | + const ps = [ |
| 146 | + `$ErrorActionPreference='Stop'`, |
| 147 | + `$msi=Join-Path $env:TEMP 'tailscale-setup.msi'`, |
| 148 | + `Invoke-WebRequest -Uri 'https://pkgs.tailscale.com/stable/tailscale-setup-latest-amd64.msi' -OutFile $msi -UseBasicParsing`, |
| 149 | + `Start-Process msiexec.exe -ArgumentList @('/i', $msi, '/quiet', '/norestart') -Wait`, |
| 150 | + `$ts='C:\\Program Files\\Tailscale\\tailscale.exe'`, |
| 151 | + `& $ts up --authkey=${authkey} --hostname=${hostname} --unattended`, |
| 152 | + `Start-Sleep -Seconds 3`, |
| 153 | + `'TAILNET_IP='+(& $ts ip -4 | Select-Object -First 1)`, |
| 154 | + ].join("\n") |
| 155 | + |
| 156 | + console.log(`${dim("→")} installing Tailscale on ${bold(vm)} + joining tailnet as ${bold(hostname)} ${dim("(this takes ~1 min)…")}`) |
| 157 | + const r = azRunPS(rg, vm, ps, 360) |
| 158 | + if (!r.ok) { |
| 159 | + console.log(`${highlight("✗")} failed: ${dim((r.stderr || r.stdout).trim().split("\n").slice(-3).join(" "))}`) |
| 160 | + process.exit(1) |
| 161 | + } |
| 162 | + const ip = /TAILNET_IP=(100\.\S+)/.exec(r.stdout)?.[1] |
| 163 | + console.log() |
| 164 | + console.log(`${success("✓")} Tailscale installed + joined the tailnet`) |
| 165 | + if (ip) { |
| 166 | + console.log(` ${dim("tailnet IP:")} ${bold(ip)}`) |
| 167 | + console.log(` ${dim("RDP address:")} ${bold(ip + ":3389")}`) |
| 168 | + } |
| 169 | + console.log(dim(` Next: iris hive host add-user ${vm} <user> -g ${rg} then iris hive host lockdown ${vm} -g ${rg}`)) |
| 170 | + console.log() |
| 171 | + }, |
| 172 | +}) |
| 173 | + |
| 174 | +// ── host grant (share the tailnet node with an external user) ──────────────── |
| 175 | + |
| 176 | +const HostGrantCommand = cmd({ |
| 177 | + command: "grant <email>", |
| 178 | + describe: "share the tailnet host with an external user (e.g. a Drex accountant) — least-privilege", |
| 179 | + builder: (y) => |
| 180 | + y |
| 181 | + .positional("email", { describe: "the external user's email to share the node with", type: "string", demandOption: true }) |
| 182 | + .option("machine", { describe: "tailnet machine name to share, e.g. qb-host-vanguard", type: "string", demandOption: true }), |
| 183 | + async handler(argv) { |
| 184 | + const email = String(argv.email) |
| 185 | + const machine = String(argv.machine) |
| 186 | + // Node sharing is an admin-console / API action tied to your tailnet identity, |
| 187 | + // so we guide it precisely rather than guessing credentials. This keeps the |
| 188 | + // external user OFF your tailnet — they get exactly one machine, nothing else. |
| 189 | + console.log() |
| 190 | + console.log(bold(`Share ${machine} with ${email}`) + dim(" (external node share — not a full tailnet member)")) |
| 191 | + console.log() |
| 192 | + console.log(` 1. Open ${bold("https://login.tailscale.com/admin/machines")}`) |
| 193 | + console.log(` 2. Find ${bold(machine)} → ${bold("⋯")} → ${bold("Share…")}`) |
| 194 | + console.log(` 3. Enter ${bold(email)} → copy the invite link → send it to them`) |
| 195 | + console.log(` 4. They accept, install Tailscale, and can reach ${bold(machine + ":3389")} — and nothing else.`) |
| 196 | + console.log() |
| 197 | + console.log(dim(` Off-boarding: same screen → remove the share → access gone immediately.`)) |
| 198 | + console.log(dim(` Group-based alternative (Google Workspace ACL): iris hive vpn grant <group> <tag>`)) |
| 199 | + console.log() |
| 200 | + }, |
| 201 | +}) |
| 202 | + |
| 203 | +// ── host lockdown (delete the public RDP rule → tunnel-only) ───────────────── |
| 204 | + |
| 205 | +const HostLockdownCommand = cmd({ |
| 206 | + command: "lockdown <vm>", |
| 207 | + describe: "delete the public RDP firewall rule on the VM's NSG → reachable only over Tailscale", |
| 208 | + builder: (y) => |
| 209 | + y |
| 210 | + .positional("vm", { describe: "Azure VM name", type: "string", demandOption: true }) |
| 211 | + .option("resource-group", { alias: "g", describe: "Azure resource group", type: "string", demandOption: true }) |
| 212 | + .option("nsg", { describe: "network security group name (defaults to <vm>-nsg)", type: "string" }) |
| 213 | + .option("yes", { describe: "skip the confirmation prompt", type: "boolean", default: false }), |
| 214 | + async handler(argv) { |
| 215 | + requireAzOrExit() |
| 216 | + const rg = String(argv["resource-group"]) |
| 217 | + const vm = String(argv.vm) |
| 218 | + const nsg = argv.nsg ? String(argv.nsg) : `${vm}-nsg` |
| 219 | + |
| 220 | + const list = az(["network", "nsg", "rule", "list", "-g", rg, "--nsg-name", nsg, "-o", "json"]) |
| 221 | + if (!list.ok) { |
| 222 | + console.log(`${highlight("✗")} couldn't read NSG ${bold(nsg)}: ${dim((list.stderr || "").trim().split("\n").slice(-2).join(" "))}`) |
| 223 | + console.log(dim(` Pass the right one with --nsg <name>.`)) |
| 224 | + process.exit(1) |
| 225 | + } |
| 226 | + let rules: any[] = [] |
| 227 | + try { |
| 228 | + rules = JSON.parse(list.stdout) |
| 229 | + } catch { |
| 230 | + /* leave empty */ |
| 231 | + } |
| 232 | + const opensRdp = (r: any) => { |
| 233 | + const one = r?.destinationPortRange |
| 234 | + const many: string[] = r?.destinationPortRanges ?? [] |
| 235 | + return one === "3389" || one === "*" || many.includes("3389") || many.includes("*") |
| 236 | + } |
| 237 | + const publicRdp = rules.filter( |
| 238 | + (r) => r?.access === "Allow" && r?.direction === "Inbound" && opensRdp(r), |
| 239 | + ) |
| 240 | + |
| 241 | + if (publicRdp.length === 0) { |
| 242 | + console.log(`${success("✓")} no public RDP allow-rules on ${bold(nsg)} — already locked down.`) |
| 243 | + return |
| 244 | + } |
| 245 | + |
| 246 | + console.log() |
| 247 | + console.log(bold(`Public RDP rules on ${nsg} that will be DELETED:`)) |
| 248 | + for (const r of publicRdp) { |
| 249 | + console.log(` ${highlight("•")} ${bold(r.name)} ${dim(`prio ${r.priority} · src ${(Array.isArray(r.sourceAddressPrefixes) && r.sourceAddressPrefixes.length ? r.sourceAddressPrefixes.join(",") : r.sourceAddressPrefix) || "*"}`)}`) |
| 250 | + } |
| 251 | + console.log() |
| 252 | + |
| 253 | + if (!argv.yes) { |
| 254 | + console.log(highlight(` Re-run with ${bold("--yes")} to delete these and go tunnel-only.`)) |
| 255 | + console.log(dim(` (Make sure you can already RDP over the Tailscale 100.x IP first!)`)) |
| 256 | + return |
| 257 | + } |
| 258 | + |
| 259 | + let failed = 0 |
| 260 | + for (const r of publicRdp) { |
| 261 | + const d = az(["network", "nsg", "rule", "delete", "-g", rg, "--nsg-name", nsg, "-n", r.name]) |
| 262 | + if (d.ok) console.log(` ${success("✓")} deleted ${bold(r.name)}`) |
| 263 | + else { |
| 264 | + failed++ |
| 265 | + console.log(` ${highlight("✗")} failed to delete ${bold(r.name)}`) |
| 266 | + } |
| 267 | + } |
| 268 | + console.log() |
| 269 | + console.log(failed === 0 ? success(` locked down — ${vm} is now Tailscale-only`) : highlight(` ${failed} rule(s) failed to delete`)) |
| 270 | + console.log() |
| 271 | + if (failed > 0) process.exit(1) |
| 272 | + }, |
| 273 | +}) |
| 274 | + |
| 275 | +// ── group command ───────────────────────────────────────────────────────────── |
| 276 | + |
| 277 | +export const HiveHostCommandExport = cmd({ |
| 278 | + command: "host <subcommand>", |
| 279 | + describe: "provision a secure remote RDP host (Azure VM): setup · add-user · grant · lockdown", |
| 280 | + builder: (y) => |
| 281 | + y |
| 282 | + .command(HostSetupCommand) |
| 283 | + .command(HostAddUserCommand) |
| 284 | + .command(HostGrantCommand) |
| 285 | + .command(HostLockdownCommand) |
| 286 | + .demandCommand(1, "Run one of: setup · add-user · grant · lockdown"), |
| 287 | + handler() {}, |
| 288 | +}) |
0 commit comments