@iamken/cloudtunnel 0.4.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../src/config/legacy-migrate.ts","../src/ui/output.ts","../src/core/systemd.ts","../src/core/ingress.ts","../src/core/tunnel-spec.ts","../src/commands/login.ts","../src/config/token-url.ts","../src/config/resolve-identity.ts","../src/commands/up.ts","../src/config/ensure-auth.ts","../src/connector/binary.ts","../src/core/up-runner.ts","../src/connector/process.ts","../src/connector/registry.ts","../src/cloudflare/tunnels.ts","../src/connector/health.ts","../src/core/orchestrator-create.ts","../src/core/slug.ts","../src/core/orchestrator-manage.ts","../src/core/transport-protocol.ts","../src/commands/ls.ts","../src/commands/delete.ts","../src/commands/logs.ts"],"sourcesContent":["import { Command } from \"commander\";\nimport { createRequire } from \"node:module\";\nimport pc from \"picocolors\";\nimport { reportError } from \"./ui/errors.js\";\nimport { migrateLegacyProfiles } from \"./config/legacy-migrate.js\";\n\nimport { registerLogin } from \"./commands/login.js\";\nimport { registerUp } from \"./commands/up.js\";\nimport { registerLs } from \"./commands/ls.js\";\nimport { registerDelete } from \"./commands/delete.js\";\nimport { registerLogs } from \"./commands/logs.js\";\n\nconst require = createRequire(import.meta.url);\nconst pkg = require(\"../package.json\") as { version: string };\n\nfunction buildProgram(): Command {\n const program = new Command();\n program\n .name(\"cloudtunnel\")\n .description(\"Expose local ports at HTTPS subdomains on your own Cloudflare domains.\")\n .version(pkg.version, \"-v, --version\")\n .showHelpAfterError();\n\n program.addHelpText(\n \"before\",\n [\n pc.bold(\"Quickstart:\"),\n ` ${pc.cyan(\"cloudtunnel login\")} once — paste a token (or set CLOUDFLARE_API_TOKEN)`,\n ` ${pc.cyan(\"cloudtunnel 8080\")} your local :8080 goes live at an HTTPS URL`,\n ` ${pc.cyan(\"cloudtunnel api:8080\")} api.<domain> → localhost:8080`,\n ` ${pc.cyan(\"cloudtunnel ls\")} list tunnels ${pc.dim(\"·\")} ${pc.cyan(\"cloudtunnel delete <#>\")} remove one`,\n \"\",\n ].join(\"\\n\"),\n );\n\n for (const register of [registerLogin, registerUp, registerLs, registerDelete, registerLogs]) {\n register(program);\n }\n return program;\n}\n\n/** Migrate legacy profiles only in a real terminal (systemd changes need an\n * interactive sudo) and not for help/version, so scripts/CI stay quiet. */\nfunction shouldMigrate(argv: string[]): boolean {\n if (!process.stdin.isTTY || !process.stdout.isTTY) return false;\n const rest = argv.slice(2);\n const infoFlag = new Set([\"-h\", \"--help\", \"-v\", \"--version\", \"help\"]);\n return !rest.some((a) => infoFlag.has(a));\n}\n\nasync function main(): Promise<void> {\n // One-time, best-effort upgrade from the old profile model.\n if (shouldMigrate(process.argv)) await migrateLegacyProfiles();\n const program = buildProgram();\n try {\n await program.parseAsync(process.argv);\n } catch (err) {\n process.exitCode = reportError(err);\n }\n}\n\nvoid main();\n","import { existsSync, readFileSync, renameSync, writeFileSync } from \"node:fs\";\nimport { profilesFile } from \"./paths.js\";\nimport { confirm, say } from \"../ui/output.js\";\nimport { installServiceForSpec, legacyUnitExists, removeLegacyUnit } from \"../core/systemd.js\";\nimport type { TransportProtocol } from \"../core/transport-protocol.js\";\n\n// Shape of the retired profiles file (self-contained; no dependency on the\n// deleted profile store).\ninterface LegacyService { name: string; port: number; proto: \"http\" | \"https\"; host?: string; domain?: string }\ninterface LegacyProfile { services?: LegacyService[]; domain?: string; protocol?: TransportProtocol }\n\nconst skipMarker = `${profilesFile}.migrate-skip`;\n\n/**\n * One-time, best-effort migration from the old profile model. If a legacy profiles\n * file exists, convert any profile that was registered as a systemd service\n * (`cloudtunnel-<profile>.service`) into the new per-subdomain units. Asks for\n * consent first (it needs sudo), and on decline/failure drops a skip-marker so it\n * never re-prompts on later commands. Caller gates this to an interactive TTY.\n */\nexport async function migrateLegacyProfiles(): Promise<void> {\n if (!existsSync(profilesFile) || existsSync(skipMarker)) return; // fast path\n\n let profiles: Record<string, LegacyProfile>;\n try {\n profiles = JSON.parse(readFileSync(profilesFile, \"utf8\")) as Record<string, LegacyProfile>;\n } catch {\n return; // unreadable → leave it alone\n }\n\n // Only boot-registered profiles need migrating; the rest are just stale saved defs.\n const legacy = Object.entries(profiles).filter(([name]) => legacyUnitExists(name));\n if (legacy.length === 0) {\n try { renameSync(profilesFile, `${profilesFile}.migrated`); } catch { /* ignore */ }\n return;\n }\n\n const ok = await confirm(`Found ${legacy.length} boot service(s) from an older cloudtunnel. Migrate them now? (needs sudo)`);\n if (!ok) {\n writeFileSync(skipMarker, \"\");\n say.dim(` Skipped. Delete ${skipMarker} to be asked again.`);\n return;\n }\n\n let migrated = 0;\n try {\n for (const [name, profile] of legacy) {\n for (const svc of profile.services ?? []) {\n const zone = svc.domain ?? profile.domain;\n if (!zone) continue; // can't resolve a hostname → skip this service\n installServiceForSpec({\n subdomain: svc.name, port: svc.port, host: svc.host,\n zone, proto: svc.proto, protocol: profile.protocol,\n });\n migrated++;\n }\n removeLegacyUnit(name);\n }\n renameSync(profilesFile, `${profilesFile}.migrated`);\n say.ok(`Migrated ${migrated} boot service(s). See them with: cloudtunnel ls`);\n } catch (err) {\n writeFileSync(skipMarker, \"\"); // stop auto-retrying on every command\n say.warn(`Migration incomplete: ${(err as Error).message}. Won't retry automatically (delete ${skipMarker} to retry).`);\n }\n}\n","import pc from \"picocolors\";\nimport Table from \"cli-table3\";\nimport { cancel, confirm as clackConfirm, intro, isCancel, note, outro, select, spinner } from \"@clack/prompts\";\nimport { CliError } from \"./errors.js\";\n\n// Re-export the clack primitives used to build modern multi-step flows.\nexport { intro, note, outro, spinner };\n\n/** Yes/no prompt (TTY). Cancel (Ctrl-C) counts as \"no\". */\nexport async function confirm(message: string): Promise<boolean> {\n const answer = await clackConfirm({ message });\n return !isCancel(answer) && answer === true;\n}\n\n/** Redact a secret to `••••{last4}` so tokens never appear in output/logs. */\nexport function redactToken(token: string): string {\n if (!token) return \"\";\n const last4 = token.length > 4 ? token.slice(-4) : token;\n return `••••${last4}`;\n}\n\n// Lightweight one-off lines for non-flow commands (ls, zones, status, …).\nexport const say = {\n info: (msg: string) => console.log(msg),\n ok: (msg: string) => console.log(pc.green(`✓ ${msg}`)),\n warn: (msg: string) => console.warn(pc.yellow(`! ${msg}`)),\n dim: (msg: string) => console.log(pc.dim(msg)),\n step: (msg: string) => console.log(pc.cyan(`→ ${msg}`)),\n};\n\nexport const dim = (s: string): string => pc.dim(s);\n\n/** Format a live tunnel as `https://host → proto://localhost:port`. */\nexport function formatRoute(host: string, target: string): string {\n return `${pc.green(pc.bold(`https://${host}`))} ${pc.dim(\"→\")} ${pc.cyan(target)}`;\n}\n\n/** Render a simple table. `head` = column titles, `rows` = string cells. */\nexport function printTable(head: string[], rows: string[][]): void {\n const table = new Table({\n head: head.map((h) => pc.bold(h)),\n style: { head: [], border: [] },\n });\n for (const row of rows) table.push(row);\n console.log(table.toString());\n}\n\n/**\n * Modern arrow-key single-select (↑/↓ to move, Enter to choose). Callers must\n * guard non-TTY before calling. Ctrl-C cancels cleanly (exit 130).\n */\nexport async function selectOne<T>(\n message: string,\n items: T[],\n label: (item: T) => string,\n): Promise<T> {\n // Use the item index as the (primitive) option value to avoid clack's\n // conditional Option<T> type fighting the generic, then map back.\n const value = await select({\n message,\n options: items.map((item, i) => ({ value: String(i), label: label(item) })),\n });\n if (isCancel(value)) {\n cancel(\"Cancelled.\");\n throw new CliError(\"Cancelled.\", { exitCode: 130 });\n }\n return items[Number(value)]!;\n}\n","import { execFileSync } from \"node:child_process\";\nimport { existsSync, realpathSync, writeFileSync } from \"node:fs\";\nimport os, { tmpdir } from \"node:os\";\nimport { dirname, join } from \"node:path\";\nimport { CliError } from \"../ui/errors.js\";\nimport type { TransportProtocol } from \"./transport-protocol.js\";\nimport { formatTunnelSpec } from \"./tunnel-spec.js\";\n\n/** Everything needed to render one per-subdomain systemd unit. */\nexport interface UnitParams {\n fqdn: string; // used for the Description\n spec: string; // subdomain:port[@host] — baked into ExecStart, re-run on boot\n zone: string; // -d <zone>\n proto: \"http\" | \"https\";\n user: string;\n home: string;\n nodePath: string; // absolute node binary\n scriptPath: string; // absolute cloudtunnel entry (dist/index.js)\n protocol?: TransportProtocol;\n}\n\nexport type ServiceState = \"active\" | \"enabled\" | \"disabled\" | \"none\";\n\n/** systemd unit name for a subdomain, keyed by its fqdn (unique across domains). */\nexport function serviceName(fqdn: string): string {\n return `cloudtunnel-${fqdn.replace(/[^a-zA-Z0-9]+/g, \"-\")}.service`;\n}\n\nexport function unitPath(fqdn: string): string {\n return `/etc/systemd/system/${serviceName(fqdn)}`;\n}\n\n/**\n * Build the systemd unit text (pure — unit-tested). ExecStart re-runs `up <spec>`\n * in the FOREGROUND so systemd supervises one connector; `systemctl stop` sends\n * SIGTERM, which makes `up` release its tunnel and exit 0 (so it is not restarted).\n * `-f -y` keep it non-interactive. Absolute node + script and an explicit PATH are\n * used because systemd starts with a minimal environment.\n */\nexport function buildUnit(p: UnitParams): string {\n const nodeBin = dirname(p.nodePath);\n const proto = p.proto === \"https\" ? \" --proto https\" : \"\";\n const protocol = p.protocol ? ` --protocol ${p.protocol}` : \"\";\n return [\n \"[Unit]\",\n `Description=cloudtunnel ${p.fqdn} (Cloudflare Tunnel)`,\n \"After=network-online.target\",\n \"Wants=network-online.target\",\n \"\",\n \"[Service]\",\n \"Type=simple\",\n `User=${p.user}`,\n `Environment=HOME=${p.home}`,\n `Environment=PATH=${nodeBin}:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin`,\n `ExecStart=${p.nodePath} ${p.scriptPath} up ${p.spec} -d ${p.zone}${proto}${protocol} -f -y`,\n \"Restart=on-failure\",\n \"RestartSec=5\",\n \"\",\n \"[Install]\",\n \"WantedBy=multi-user.target\",\n \"\",\n ].join(\"\\n\");\n}\n\n/** Fail early with an actionable message when systemd isn't usable here. */\nexport function assertSystemd(): void {\n if (process.platform !== \"linux\") {\n throw new CliError(\"Service registration is Linux/systemd only.\", {\n hint: \"on macOS/Windows run `cloudtunnel up <spec> --detach` at login instead\",\n });\n }\n try {\n execFileSync(\"systemctl\", [\"--version\"], { stdio: \"ignore\" });\n } catch {\n throw new CliError(\"systemd (systemctl) was not found on this host.\");\n }\n}\n\n/** Run a privileged command, prefixing `sudo` unless already root. Inherits the\n * terminal so sudo can prompt for a password. */\nfunction privileged(args: string[]): void {\n const isRoot = typeof process.getuid === \"function\" && process.getuid() === 0;\n const argv = isRoot ? args : [\"sudo\", ...args];\n execFileSync(argv[0]!, argv.slice(1), { stdio: \"inherit\" });\n}\n\n/** Read-only systemctl query; returns trimmed stdout (\"\" on any error). */\nfunction query(args: string[]): string {\n try {\n return execFileSync(\"systemctl\", args, { stdio: [\"ignore\", \"pipe\", \"ignore\"], encoding: \"utf8\" }).trim();\n } catch (err) {\n const out = (err as { stdout?: Buffer | string }).stdout;\n return out ? out.toString().trim() : \"\";\n }\n}\n\n/** Resolve the running cloudtunnel entry, for a stable systemd ExecStart. */\nfunction entryScript(): string {\n const p = process.argv[1];\n if (!p) throw new CliError(\"Cannot resolve the cloudtunnel executable path.\");\n return realpathSync(p);\n}\n\n/** Install + enable a boot unit for one subdomain (runs now + on boot). Needs sudo. */\nexport function installServiceForSpec(params: {\n subdomain: string;\n port: number;\n host?: string;\n zone: string;\n proto: \"http\" | \"https\";\n protocol?: TransportProtocol;\n}): void {\n assertSystemd();\n const fqdn = params.subdomain === \"@\" ? params.zone : `${params.subdomain}.${params.zone}`;\n const unit = buildUnit({\n fqdn,\n spec: formatTunnelSpec({ subdomain: params.subdomain, port: params.port, host: params.host }),\n zone: params.zone,\n proto: params.proto,\n user: os.userInfo().username,\n home: os.homedir(),\n nodePath: process.execPath,\n scriptPath: entryScript(),\n protocol: params.protocol,\n });\n const tmp = join(tmpdir(), serviceName(fqdn));\n writeFileSync(tmp, unit, { mode: 0o644 });\n privileged([\"install\", \"-m\", \"0644\", tmp, unitPath(fqdn)]);\n privileged([\"systemctl\", \"daemon-reload\"]);\n privileged([\"systemctl\", \"enable\", \"--now\", serviceName(fqdn)]);\n}\n\n/** Stop, disable, and delete the unit for a subdomain. Needs sudo. Best-effort. */\nexport function uninstallService(fqdn: string): void {\n assertSystemd();\n try {\n privileged([\"systemctl\", \"disable\", \"--now\", serviceName(fqdn)]);\n } catch {\n /* not enabled / already gone */\n }\n privileged([\"rm\", \"-f\", unitPath(fqdn)]);\n privileged([\"systemctl\", \"daemon-reload\"]);\n}\n\n/** Whether a legacy profile-named unit (`cloudtunnel-<profile>.service`) is\n * installed — used only by the one-time migration from the old profile model. */\nexport function legacyUnitExists(profile: string): boolean {\n return existsSync(`/etc/systemd/system/cloudtunnel-${profile}.service`);\n}\n\n/** Remove a legacy profile-named unit (migration only). Needs sudo. */\nexport function removeLegacyUnit(profile: string): void {\n const name = `cloudtunnel-${profile}.service`;\n try {\n privileged([\"systemctl\", \"disable\", \"--now\", name]);\n } catch {\n /* not enabled / already gone */\n }\n privileged([\"rm\", \"-f\", `/etc/systemd/system/${name}`]);\n privileged([\"systemctl\", \"daemon-reload\"]);\n}\n\n/** Current systemd state of a subdomain's service (no root required). */\nexport function serviceState(fqdn: string): ServiceState {\n if (process.platform !== \"linux\") return \"none\";\n const name = serviceName(fqdn);\n if (query([\"is-active\", name]) === \"active\") return \"active\";\n const enabled = query([\"is-enabled\", name]);\n if (enabled === \"enabled\" || enabled === \"enabled-runtime\") return \"enabled\";\n if (enabled === \"disabled\" || enabled === \"static\") return \"disabled\";\n return \"none\";\n}\n","import type { IngressRule } from \"../cloudflare/types.js\";\nimport { CliError } from \"../ui/errors.js\";\n\nconst HOSTNAME_RE = /^[a-zA-Z0-9.-]+$/; // hostname or IPv4\nconst IPV6_RE = /^[0-9a-fA-F:.]+$/; // IPv6 literal (incl. IPv4-mapped ::ffff:1.2.3.4)\n\n/**\n * Validate a forward-target host before it lands in the ingress service URL.\n * Rejects anything that could break out of `proto://host:port` — a scheme,\n * path, or whitespace — so `--source` can't inject extra ingress syntax.\n *\n * IPv6 is accepted bare (`::1`) or bracketed (`[::1]`) and stored bare. IPv6 is\n * detected by `::` or ≥2 colons, so a single-colon `10.0.0.2:8080` (an IPv4:port\n * mistake) still fails the hostname check instead of passing as a bogus literal.\n */\nexport function validateHost(host: string): string {\n let h = host.trim();\n const bracketed = h.startsWith(\"[\") && h.endsWith(\"]\");\n if (bracketed) h = h.slice(1, -1);\n const isV6 = bracketed || h.includes(\"::\") || (h.match(/:/g)?.length ?? 0) >= 2;\n const ok = h.length > 0 && (isV6 ? IPV6_RE.test(h) : HOSTNAME_RE.test(h));\n if (!ok) {\n throw new CliError(`Invalid host \"${host}\".`, {\n hint: \"use a hostname, IPv4, or IPv6 literal (e.g. 192.168.1.5 or ::1) — no port, scheme, or path\",\n });\n }\n return h;\n}\n\n/** Compose a `proto://host:port` service URL, bracketing an IPv6 literal. */\nexport function serviceUrl(proto: \"http\" | \"https\", host: string, port: number): string {\n const authority = host.includes(\":\") ? `[${host}]` : host;\n return `${proto}://${authority}:${port}`;\n}\n\n/**\n * Build the ingress config for a single-hostname tunnel. The mandatory\n * catch-all `http_status:404` rule must come last (Cloudflare rejects configs\n * without it). One-tunnel-per-subdomain keeps this a fixed two-rule list, so\n * the full-replace PUT is always safe (no merge with other hostnames).\n *\n * `host` defaults to `localhost`; pass another host/IP to forward to a different\n * machine this connector can reach (a LAN device, a container, another server).\n */\nexport function buildIngress(opts: {\n hostname: string;\n port: number;\n proto: \"http\" | \"https\";\n host?: string;\n}): IngressRule[] {\n return [\n { hostname: opts.hostname, service: serviceUrl(opts.proto, opts.host ?? \"localhost\", opts.port) },\n { service: \"http_status:404\" },\n ];\n}\n","import { CliError } from \"../ui/errors.js\";\nimport { validateHost } from \"./ingress.js\";\n\n/** One tunnel to bring up, parsed from a positional `up` argument. */\nexport interface TunnelSpec {\n subdomain?: string; // absent ⇒ random slug; \"@\" ⇒ root/apex domain\n port: number;\n host?: string; // forward target (absent ⇒ localhost)\n}\n\n/**\n * Parse a `[subdomain:]port[@host]` spec, e.g. `8080`, `api:8080`,\n * `api:8080@192.168.1.20`, `api:8080@localhost`, `api:8080@::1`. The local-service\n * protocol is NOT part of the spec — it comes from the global `--proto` flag.\n *\n * A leading `@` means the root/apex domain (kept as the subdomain), which is\n * distinct from the `@host` forward-target delimiter that follows the port.\n */\nexport function parseTunnelSpec(spec: string): TunnelSpec {\n const raw = spec.trim();\n const bad = (hint: string): CliError => new CliError(`Invalid spec \"${spec}\".`, { hint });\n if (!raw) throw bad(\"use [subdomain:]port[@host], e.g. api:8080 or api:8080@192.168.1.20\");\n\n let rest = raw;\n let subdomain: string | undefined;\n\n // Leading `@` = root/apex domain; consume it before looking for the host `@`.\n if (rest.startsWith(\"@\")) {\n subdomain = \"@\";\n rest = rest.slice(1);\n if (rest.startsWith(\":\")) rest = rest.slice(1);\n }\n\n // Forward host after `@` (may contain colons for an IPv6 literal).\n let host: string | undefined;\n const at = rest.indexOf(\"@\");\n if (at >= 0) {\n host = validateHost(rest.slice(at + 1));\n rest = rest.slice(0, at);\n }\n\n // `rest` is now `[subdomain:]port`.\n const parts = rest.split(\":\");\n let portStr: string;\n if (parts.length === 1) {\n portStr = parts[0]!;\n } else if (parts.length === 2) {\n if (subdomain === undefined) {\n if (!parts[0]) throw bad(\"subdomain label is empty\");\n subdomain = parts[0];\n } else if (parts[0]) {\n throw bad(\"unexpected label after '@' root marker\");\n }\n portStr = parts[1]!;\n } else {\n throw bad(\"too many ':' — spec is [subdomain:]port[@host] (protocol via --proto)\");\n }\n\n const port = Number(portStr);\n if (!Number.isInteger(port) || port < 1 || port > 65535) {\n throw bad(\"port must be a number 1–65535\");\n }\n // A DNS label (or \"@\" for the apex). Guards the Cloudflare API and, with\n // `--service`, keeps the subdomain a single unquoted token in the unit ExecStart.\n if (subdomain !== undefined && subdomain !== \"@\" && !/^[a-zA-Z0-9-]+$/.test(subdomain)) {\n throw bad(\"subdomain may contain only letters, digits, and hyphens\");\n }\n return { subdomain, port, ...(host ? { host } : {}) };\n}\n\n/**\n * Render a concrete spec back to its `subdomain:port[@host]` string — used to bake\n * a stable spec into a systemd unit's ExecStart so it round-trips through\n * `parseTunnelSpec` on boot.\n */\nexport function formatTunnelSpec(s: { subdomain: string; port: number; host?: string }): string {\n return `${s.subdomain}:${s.port}${s.host ? `@${s.host}` : \"\"}`;\n}\n","import type { Command } from \"commander\";\nimport * as clack from \"@clack/prompts\";\nimport { CliError } from \"../ui/errors.js\";\nimport { redactToken, say, selectOne } from \"../ui/output.js\";\nimport { configFile } from \"../config/paths.js\";\nimport { loadConfig, saveConfig } from \"../config/store.js\";\nimport { REQUIRED_SCOPES, openBrowser, tokenCreateUrl } from \"../config/token-url.js\";\nimport { listAccounts, listZones } from \"../config/resolve-identity.js\";\n\ninterface LoginOptions {\n tokenStdin?: boolean;\n token?: string; // deprecated: leaks into shell history\n account?: string;\n zone?: string;\n status?: boolean;\n}\n\n/** Read the whole stdin pipe (for `--token-stdin`). */\nasync function readStdin(): Promise<string> {\n const chunks: Buffer[] = [];\n for await (const chunk of process.stdin) chunks.push(chunk as Buffer);\n return Buffer.concat(chunks).toString(\"utf8\").trim();\n}\n\n/** Acquire the API token: env (silent) → stdin → deprecated flag → masked prompt.\n * Env tokens are NOT persisted (the env stays the source of truth). */\nasync function acquireToken(opts: LoginOptions): Promise<{ token: string; fromEnv: boolean }> {\n const envToken = process.env.CLOUDFLARE_API_TOKEN;\n if (envToken) {\n say.dim(\"Using token from CLOUDFLARE_API_TOKEN.\");\n return { token: envToken, fromEnv: true };\n }\n if (opts.tokenStdin) return { token: await readStdin(), fromEnv: false };\n if (opts.token) {\n say.warn(\"--token puts the token in your shell history — prefer --token-stdin or the prompt. Rotate it if this is a shared host.\");\n return { token: opts.token, fromEnv: false };\n }\n if (!process.stdin.isTTY) {\n throw new CliError(\"No token provided and no interactive terminal.\", {\n hint: \"pipe it: `printf %s $TOKEN | cloudtunnel login --token-stdin`\",\n });\n }\n clack.note(REQUIRED_SCOPES.map((s) => `• ${s}`).join(\"\\n\"), \"Create a token with these scopes\");\n openBrowser(tokenCreateUrl());\n say.dim(`(opened ${tokenCreateUrl()})`);\n const token = await clack.password({ message: \"Paste your Cloudflare API token\", mask: \"•\" });\n if (clack.isCancel(token) || !token) {\n clack.cancel(\"Cancelled.\");\n throw new CliError(\"Cancelled.\", { exitCode: 130 });\n }\n return { token, fromEnv: false };\n}\n\nasync function runLoginFlow(opts: LoginOptions = {}): Promise<void> {\n if (process.stdout.isTTY) clack.intro(\"cloudtunnel · connect to Cloudflare\");\n const { token, fromEnv } = await acquireToken(opts);\n\n const spin = clack.spinner();\n spin.start(\"Verifying token…\");\n const [accounts, zones] = await Promise.all([listAccounts(token), listZones(token)]).catch((err: unknown) => {\n spin.stop(\"Token check failed\");\n throw err;\n });\n spin.stop(\"Token verified\");\n\n if (accounts.length === 0) throw new CliError(\"Token can't see any Cloudflare account.\");\n let account = opts.account ? accounts.find((a) => a.id === opts.account) : undefined;\n if (opts.account && !account) throw new CliError(`Account ${opts.account} not visible to this token.`);\n if (!account) {\n account = accounts.length === 1 || !process.stdin.isTTY\n ? accounts[0]!\n : await selectOne(\"Select an account\", accounts, (a) => `${a.name} (${a.id})`);\n }\n\n let defaultZone = opts.zone;\n if (!defaultZone) {\n if (zones.length === 1) defaultZone = zones[0]!.name;\n else if (zones.length > 1 && process.stdin.isTTY) {\n defaultZone = (await selectOne(\"Select a default domain\", zones, (z) => z.name)).name;\n }\n }\n\n saveConfig({ apiToken: fromEnv ? undefined : token, accountId: account.id, defaultZone });\n const summary = `Logged in as ${account.name}${defaultZone ? ` · default domain ${defaultZone}` : \"\"}`;\n if (process.stdout.isTTY) clack.outro(summary);\n else say.ok(summary);\n if (!defaultZone) say.dim(\"No default domain set — pass -d <domain> on `up`, or re-run `login --zone <domain>`.\");\n}\n\nfunction showStatus(): void {\n const config = loadConfig();\n const token = process.env.CLOUDFLARE_API_TOKEN ?? config.apiToken;\n if (!token) {\n say.warn(\"Not logged in. Run `cloudtunnel login`.\");\n return;\n }\n const source = process.env.CLOUDFLARE_API_TOKEN ? \"env\" : \"config\";\n say.info(`Token: ${redactToken(token)} (${source})`);\n say.info(`Account: ${config.accountId ?? \"(from env / unresolved)\"}`);\n say.info(`Domain: ${config.defaultZone ?? \"(none)\"}`);\n say.dim(`Config: ${configFile}`);\n}\n\nexport function registerLogin(program: Command): void {\n program\n .command(\"login\")\n .description(\"Authenticate with Cloudflare (paste a token once; account + domain auto-resolved)\")\n .option(\"--token-stdin\", \"read the API token from stdin (scriptable, avoids shell history)\")\n .option(\"--token <token>\", \"[discouraged] token as an argument (leaks into shell history)\")\n .option(\"--account <id>\", \"Cloudflare account id (auto-resolved when you have one account)\")\n .option(\"--zone <domain>\", \"default domain for new tunnels (auto-resolved when you have one)\")\n .option(\"--status\", \"show current identity (redacted) and exit\")\n .action(async (opts: LoginOptions) => {\n if (opts.status) return showStatus();\n await runLoginFlow(opts);\n });\n}\n\nexport { runLoginFlow };\n","import { spawn } from \"node:child_process\";\n\n/** The exact scopes cloudtunnel needs. Printed so the user selects them when\n * minting a token — least-privilege, account-wide only where required. */\nexport const REQUIRED_SCOPES = [\n \"Account · Cloudflare Tunnel · Edit\",\n \"Account · Account Settings · Read\",\n \"Zone · DNS · Edit\",\n \"Zone · Zone · Read\",\n] as const;\n\n/** Cloudflare \"Create Custom Token\" page. `name` is pre-filled best-effort;\n * the user still selects the scopes above (dashboard pre-fill params are not a\n * versioned API, so we rely on the printed scope list, not URL params). */\nexport function tokenCreateUrl(): string {\n return \"https://dash.cloudflare.com/profile/api-tokens?name=cloudtunnel\";\n}\n\n/** Best-effort open a URL in the default browser. Never throws — if no opener\n * exists (headless/CI), the caller still prints the URL. */\nexport function openBrowser(url: string): void {\n const cmd =\n process.platform === \"darwin\" ? \"open\"\n : process.platform === \"win32\" ? \"cmd\"\n : \"xdg-open\";\n const args = process.platform === \"win32\" ? [\"/c\", \"start\", \"\", url] : [url];\n try {\n const child = spawn(cmd, args, { stdio: \"ignore\", detached: true });\n child.on(\"error\", () => {}); // swallow: opener may not exist\n child.unref();\n } catch {\n // ignore — printing the URL is the fallback\n }\n}\n","import { CliError } from \"../ui/errors.js\";\nimport { REQUIRED_SCOPES, tokenCreateUrl } from \"./token-url.js\";\n\nconst API_BASE = \"https://api.cloudflare.com/client/v4\";\n\nexport interface CfAccount { id: string; name: string }\nexport interface CfZone { id: string; name: string; account?: { id: string } }\n\n/**\n * Raw Cloudflare GET used only for login-time validation (the typed SDK client\n * is wired in Phase 3). Errors are sanitized: the token never appears in any\n * thrown message. A 403 is mapped to a missing-scope hint.\n */\nasync function cfGet<T>(path: string, token: string): Promise<T[]> {\n let res: Response;\n try {\n res = await fetch(`${API_BASE}${path}`, {\n headers: { Authorization: `Bearer ${token}`, \"Content-Type\": \"application/json\" },\n });\n } catch {\n throw new CliError(\"Could not reach the Cloudflare API (network error).\");\n }\n if (res.status === 401) {\n throw new CliError(\"Cloudflare rejected the token (invalid or expired).\", {\n hint: `mint a new token: ${tokenCreateUrl()}`,\n });\n }\n if (res.status === 403) {\n throw new CliError(`Token is missing a required scope for ${path}.`, {\n hint: `token needs: ${REQUIRED_SCOPES.join(\", \")}`,\n });\n }\n const body = (await res.json().catch(() => ({}))) as { success?: boolean; result?: T[] };\n if (!res.ok || !body.success) {\n throw new CliError(`Cloudflare API error (${res.status}) on ${path}.`);\n }\n return body.result ?? [];\n}\n\nexport function listAccounts(token: string): Promise<CfAccount[]> {\n return cfGet<CfAccount>(\"/accounts?per_page=50\", token);\n}\n\nexport function listZones(token: string): Promise<CfZone[]> {\n return cfGet<CfZone>(\"/zones?per_page=50\", token);\n}\n","import type { Command } from \"commander\";\nimport * as clack from \"@clack/prompts\";\nimport { CliError } from \"../ui/errors.js\";\nimport { say, selectOne } from \"../ui/output.js\";\nimport { ensureAuth } from \"../config/ensure-auth.js\";\nimport { resolveCf, type Cf } from \"../cloudflare/client.js\";\nimport { listZones } from \"../cloudflare/zones.js\";\nimport type { Credentials } from \"../config/store.js\";\nimport { ensureCloudflared } from \"../connector/binary.js\";\nimport type { CreateOptions } from \"../core/orchestrator-create.js\";\nimport { startTunnels } from \"../core/up-runner.js\";\nimport { parseTunnelSpec, type TunnelSpec } from \"../core/tunnel-spec.js\";\nimport { parseTransportProtocol, type TransportProtocol } from \"../core/transport-protocol.js\";\nimport { randomSlug } from \"../core/slug.js\";\nimport { assertSystemd, installServiceForSpec, serviceName } from \"../core/systemd.js\";\n\ninterface UpOptions {\n domain?: string;\n proto: \"http\" | \"https\";\n protocol?: string; // edge transport: auto | http2 | quic\n detach?: boolean;\n service?: boolean; // register each subdomain as a systemd boot service\n force?: boolean;\n yes?: boolean;\n}\n\nfunction promptOrExit<T>(value: T | symbol): T {\n if (clack.isCancel(value)) {\n clack.cancel(\"Cancelled.\");\n process.exit(130);\n }\n return value as T;\n}\n\n/** Interactive port prompt (0-arg wizard). */\nasync function promptPort(): Promise<number> {\n const input = promptOrExit(\n await clack.text({\n message: \"Port to expose\",\n placeholder: \"e.g. 3000\",\n validate: (v) => {\n const n = Number(v);\n if (!Number.isInteger(n) || n < 1 || n > 65535) return \"Enter a port 1–65535\";\n return undefined;\n },\n }),\n );\n return Number(input);\n}\n\n/** The domain for the whole batch: `-d` → single zone → picker (TTY) → saved\n * default (non-TTY) → error. */\nasync function resolveDomain(cf: Cf, opts: UpOptions, creds: Credentials): Promise<string> {\n if (opts.domain) return opts.domain;\n const zones = await listZones(cf.token);\n if (zones.length === 0) throw new CliError(\"No domains found in this Cloudflare account.\");\n if (zones.length === 1) return zones[0]!.name;\n if (process.stdin.isTTY) return (await selectOne(\"Choose a domain\", zones, (z) => z.name)).name;\n if (creds.defaultZone) return creds.defaultZone;\n throw new CliError(\"Multiple domains in this account — pick one.\", { hint: \"pass -d <domain>\" });\n}\n\n/** The subdomain for a spec: explicit in the spec → used as-is; otherwise prompt\n * (TTY, blank = random) or random (non-TTY / `-y`). Returns undefined for random. */\nasync function resolveSpecSubdomain(spec: TunnelSpec, opts: UpOptions): Promise<string | undefined> {\n if (spec.subdomain !== undefined) return spec.subdomain;\n if (opts.yes || !process.stdin.isTTY) return undefined; // random\n const input = promptOrExit(\n await clack.text({ message: `Subdomain for :${spec.port}`, placeholder: \"blank = random · @ = root domain\" }),\n );\n return (input as string).trim() || undefined; // blank → random\n}\n\nasync function runUp(specArgs: string[], opts: UpOptions): Promise<void> {\n const protocol: TransportProtocol | undefined = opts.protocol ? parseTransportProtocol(opts.protocol) : undefined;\n // Parse specs up front (fail fast on a typo before touching the network). 0 args\n // → wizard, which needs a TTY.\n const parsed: TunnelSpec[] | null = specArgs.length ? specArgs.map(parseTunnelSpec) : null;\n if (parsed === null && !process.stdin.isTTY) {\n throw new CliError(\"No tunnel spec given.\", { hint: \"e.g. cloudtunnel api:8080\" });\n }\n\n const creds = await ensureAuth();\n const cf = resolveCf();\n const bin = await ensureCloudflared();\n\n if (process.stdout.isTTY) clack.intro(\"cloudtunnel\");\n\n const specs: TunnelSpec[] = parsed ?? [{ port: await promptPort() }];\n const domain = await resolveDomain(cf, opts, creds);\n\n // Build create-opts per spec. `--service` needs a concrete subdomain baked in\n // (never random-per-boot), so materialise a random one now when unnamed.\n const items: CreateOptions[] = [];\n for (const spec of specs) {\n let name = await resolveSpecSubdomain(spec, opts);\n if (opts.service && name === undefined) name = randomSlug();\n items.push({\n port: spec.port, proto: opts.proto, name, zone: domain, host: spec.host,\n defaultZone: creds.defaultZone, force: opts.force, yes: opts.yes,\n });\n }\n\n if (opts.service) {\n registerServices(items, domain, opts.proto, protocol);\n return;\n }\n\n await startTunnels(cf, bin, items, { detach: opts.detach, protocol });\n}\n\n/** Install + enable a systemd boot unit per subdomain (systemd runs each now and\n * on boot), then exit. `--detach` is a no-op here — systemd already backgrounds. */\nfunction registerServices(\n items: CreateOptions[], domain: string,\n proto: \"http\" | \"https\", protocol?: TransportProtocol,\n): void {\n assertSystemd();\n if (!protocol) {\n say.warn(\"No edge protocol set — cloudflared will pick QUIC, which some networks drop.\");\n say.dim(\" → add --protocol http2 for UDP-hostile networks\");\n }\n const done: string[] = [];\n for (const item of items) {\n const subdomain = item.name!; // concrete (baked above)\n const fqdn = subdomain === \"@\" ? domain : `${subdomain}.${domain}`;\n installServiceForSpec({ subdomain, port: item.port, host: item.host, zone: domain, proto, protocol });\n done.push(`${serviceName(fqdn)} → https://${fqdn}`);\n }\n say.ok(`Registered ${done.length} boot service(s):`);\n for (const line of done) say.dim(` ${line}`);\n say.dim(\" → check them: cloudtunnel ls · remove: cloudtunnel delete <#>\");\n}\n\nexport function registerUp(program: Command): void {\n program\n .command(\"up\", { isDefault: true })\n .argument(\"[specs...]\", \"tunnels to start: [subdomain:]port[@host] (e.g. api:8080 web:8081@localhost)\")\n .description(\"Start one or more tunnels (also: `cloudtunnel 8080`)\")\n .option(\"-d, --domain <domain>\", \"domain for the subdomains (prompted from a list if unset)\")\n .option(\"--proto <proto>\", \"local service protocol: http | https\", \"http\")\n .option(\"--protocol <proto>\", \"cloudflared edge transport: auto | http2 | quic (http2 for UDP-hostile networks)\")\n .option(\"--detach\", \"run the connectors in the background\")\n .option(\"--service\", \"register each subdomain as a systemd boot service (Linux; needs sudo)\")\n .option(\"-f, --force\", \"replace a non-tunnel DNS record occupying the hostname\")\n .option(\"-y, --yes\", \"don't prompt; don't ask before replacing an existing record\")\n .action((specs: string[], opts: UpOptions) => runUp(specs, opts));\n}\n","import { CliError } from \"../ui/errors.js\";\nimport { say } from \"../ui/output.js\";\nimport { getCredentials, type Credentials } from \"./store.js\";\nimport { runLoginFlow } from \"../commands/login.js\";\n\n/**\n * Single auth entry point for every command. Returns credentials if present;\n * on a fresh machine with a TTY it runs onboarding inline and continues, so\n * `cloudtunnel 3000` on a new box just works. Non-TTY (CI) → actionable error.\n */\nexport async function ensureAuth(): Promise<Credentials> {\n try {\n return getCredentials();\n } catch (err) {\n if (err instanceof CliError && process.stdin.isTTY) {\n say.info(\"Welcome to cloudtunnel — let's get you connected to Cloudflare first.\");\n await runLoginFlow();\n return getCredentials();\n }\n throw err;\n }\n}\n","import { execFileSync } from \"node:child_process\";\nimport { createHash } from \"node:crypto\";\nimport { chmodSync, existsSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { CliError } from \"../ui/errors.js\";\nimport { say } from \"../ui/output.js\";\nimport { binDir, ensureDirs } from \"../config/paths.js\";\n\n// Pinned release for reproducible, checksum-verified auto-install. Bump both the\n// version and the checksums together (values from the release's sha256 sums).\nconst PINNED_VERSION = \"2025.1.0\";\nconst RELEASE_BASE = `https://github.com/cloudflare/cloudflared/releases/download/${PINNED_VERSION}`;\n\ninterface Asset { file: string; archive: boolean; sha256: string }\n\n// Fill sha256 from the pinned release before shipping auto-install for a target.\n// Empty string ⇒ fail closed (never run an unverified binary).\nconst ASSETS: Record<string, Asset | undefined> = {\n \"linux-x64\": { file: \"cloudflared-linux-amd64\", archive: false, sha256: \"\" },\n \"linux-arm64\": { file: \"cloudflared-linux-arm64\", archive: false, sha256: \"\" },\n \"darwin-x64\": { file: \"cloudflared-darwin-amd64.tgz\", archive: true, sha256: \"\" },\n \"darwin-arm64\": { file: \"cloudflared-darwin-arm64.tgz\", archive: true, sha256: \"\" },\n \"win32-x64\": { file: \"cloudflared-windows-amd64.exe\", archive: false, sha256: \"\" },\n};\n\nfunction binaryWorks(bin: string): boolean {\n try {\n execFileSync(bin, [\"--version\"], { stdio: \"ignore\" });\n return true;\n } catch {\n return false;\n }\n}\n\nfunction cachedPath(): string {\n return join(binDir, process.platform === \"win32\" ? \"cloudflared.exe\" : \"cloudflared\");\n}\n\n/** True on Alpine/musl, where cloudflared has no prebuilt binary. */\nfunction isMusl(): boolean {\n try {\n return process.platform === \"linux\" && readFileSync(\"/usr/bin/ldd\", \"utf8\").includes(\"musl\");\n } catch {\n return false;\n }\n}\n\n/**\n * Return a runnable `cloudflared` with zero user action: PATH → cached download\n * → verified auto-download. Fails closed (never runs an unverified binary).\n */\nexport async function ensureCloudflared(): Promise<string> {\n if (binaryWorks(\"cloudflared\")) return \"cloudflared\";\n const cached = cachedPath();\n if (existsSync(cached) && binaryWorks(cached)) return cached;\n return downloadCloudflared(cached);\n}\n\nasync function downloadCloudflared(dest: string): Promise<string> {\n if (isMusl()) {\n throw new CliError(\"cloudflared has no musl (Alpine) build.\", {\n hint: \"install it manually: https://github.com/cloudflare/cloudflared/releases\",\n });\n }\n const key = `${process.platform}-${process.arch}`;\n const asset = ASSETS[key];\n if (!asset || !asset.sha256) {\n throw new CliError(`Auto-install unavailable for ${key} (no pinned checksum).`, {\n hint: \"install cloudflared manually: https://github.com/cloudflare/cloudflared/releases\",\n });\n }\n\n say.step(`cloudflared not found — downloading v${PINNED_VERSION} (checksum-verified)…`);\n const res = await fetch(`${RELEASE_BASE}/${asset.file}`);\n if (!res.ok) throw new CliError(`Download failed (HTTP ${res.status}).`);\n const bytes = Buffer.from(await res.arrayBuffer());\n\n const digest = createHash(\"sha256\").update(bytes).digest(\"hex\");\n if (digest !== asset.sha256) {\n throw new CliError(\"cloudflared checksum mismatch — refusing to run the download.\", {\n hint: \"network tampering or an outdated pin; install manually instead\",\n });\n }\n\n ensureDirs();\n const binary = asset.archive ? extractTgz(bytes) : bytes;\n writeFileSync(dest, binary, { mode: 0o755 });\n chmodSync(dest, 0o755);\n if (!binaryWorks(dest)) throw new CliError(\"Downloaded cloudflared is not runnable.\");\n return dest;\n}\n\n/** Extract the single `cloudflared` entry from a .tgz (darwin assets). */\nfunction extractTgz(_bytes: Buffer): Buffer {\n // gunzip + untar of a single-file archive; implemented when a darwin\n // checksum is pinned (dormant until then — see ASSETS).\n throw new CliError(\"darwin .tgz extraction not yet wired.\", {\n hint: \"install cloudflared via `brew install cloudflared`\",\n });\n}\n","import { join } from \"node:path\";\nimport * as clack from \"@clack/prompts\";\nimport { reportError } from \"../ui/errors.js\";\nimport { dim, formatRoute, say } from \"../ui/output.js\";\nimport type { Cf } from \"../cloudflare/client.js\";\nimport { logDir } from \"../config/paths.js\";\nimport { startConnector } from \"../connector/process.js\";\nimport { waitHealthy, type HealthResult } from \"../connector/health.js\";\nimport { currentBootId, patchEntry } from \"../connector/registry.js\";\nimport { createTunnelSubdomain, type CreateOptions } from \"./orchestrator-create.js\";\nimport { removeTunnelSubdomain } from \"./orchestrator-manage.js\";\nimport { serviceUrl } from \"./ingress.js\";\nimport type { TransportProtocol } from \"./transport-protocol.js\";\n\ninterface StartedTunnel {\n fqdn: string;\n subdomain: string;\n tunnelId: string;\n target: string;\n pid: number;\n}\n\n/** Log-file label for a subdomain (\"@\" → root). */\nfunction logFileFor(subdomain: string): string {\n return join(logDir, `${subdomain === \"@\" ? \"root\" : subdomain}.log`);\n}\n\n/**\n * Create + connect a batch of tunnels (1..N). Foreground: waits for health, then\n * any exit (Ctrl-C / crash) releases every tunnel started here (2-state model).\n * `--detach`: starts them all in the background and returns.\n */\nexport async function startTunnels(\n cf: Cf,\n bin: string,\n items: CreateOptions[],\n opts: { detach?: boolean; protocol?: TransportProtocol } = {},\n): Promise<void> {\n const started: StartedTunnel[] = [];\n\n // Foreground is up-while-running: any exit (Ctrl-C, a signal, or a connector\n // crash) releases every tunnel started here (2-state model). Defined before the\n // create loop so `onExit` can reference it; registered as signal handlers before\n // the health wait so a Ctrl-C during that ≤30s window doesn't leak resources.\n let tornDown = false;\n const teardownAll = async (code: number): Promise<void> => {\n if (tornDown) return;\n tornDown = true;\n try {\n for (const s of started) {\n try {\n await removeTunnelSubdomain(cf, s.fqdn, { force: true, quiet: true });\n } catch {\n /* best-effort release */\n }\n }\n if (process.stdout.isTTY) clack.outro(`Stopped · released ${started.length} subdomain(s)`);\n } catch (err) {\n reportError(err);\n } finally {\n process.exit(code);\n }\n };\n\n const spin = clack.spinner();\n spin.start(items.length > 1 ? \"Creating tunnels…\" : \"Creating tunnel…\");\n for (const item of items) {\n spin.message(`Creating ${item.name ?? \"tunnel\"} (:${item.port})…`);\n const result = await createTunnelSubdomain(cf, item);\n const fqdn = result.host.hostname;\n const logFile = logFileFor(result.host.subdomain);\n const conn = startConnector({\n bin, token: result.token, detach: !!opts.detach, logFile, protocol: opts.protocol,\n onExit: opts.detach ? undefined : (code) => {\n if (!tornDown) {\n say.warn(`Connector for ${fqdn} exited.`);\n void teardownAll(code ?? 1);\n }\n },\n });\n await patchEntry(fqdn, { pid: conn.pid, bootId: currentBootId(), logFile });\n started.push({\n fqdn, subdomain: result.host.subdomain, tunnelId: result.tunnelId,\n target: serviceUrl(item.proto, item.host ?? \"localhost\", item.port), pid: conn.pid,\n });\n }\n\n // Detached: print URLs + pids and exit; the connectors keep running.\n if (opts.detach) {\n spin.stop(`${started.length} tunnel(s) started in the background`);\n const lines = started.map((s) => `${formatRoute(s.fqdn, s.target)} ${dim(`pid ${s.pid}`)}`);\n clack.note(lines.join(\"\\n\"), \"running in background\");\n if (process.stdout.isTTY) clack.outro(\"Stop with: cloudtunnel delete <#|--all>\");\n return;\n }\n\n for (const sig of [\"SIGINT\", \"SIGHUP\", \"SIGTERM\"] as const) {\n process.on(sig, () => void teardownAll(0));\n }\n\n spin.message(\"Connecting to the Cloudflare edge…\");\n const healths = await Promise.all(started.map((s) => waitHealthy(cf, s.tunnelId, { timeoutMs: 30_000 })));\n const live = healths.filter((h: HealthResult) => h === \"healthy\").length;\n spin.stop(`${started.length} tunnel(s) started`);\n\n const lines = started.map((s, i) => `${formatRoute(s.fqdn, s.target)}${healths[i] === \"healthy\" ? \"\" : dim(` (${healths[i]})`)}`);\n clack.note(lines.join(\"\\n\"), `${live}/${started.length} live`);\n say.dim(\"Ctrl-C stops and releases them.\");\n}\n","import { type ChildProcess, execFileSync, spawn } from \"node:child_process\";\nimport { openSync } from \"node:fs\";\nimport { CliError } from \"../ui/errors.js\";\nimport { isOurConnector, type RegistryEntry } from \"./registry.js\";\n\nexport interface StartOptions {\n bin: string;\n token: string;\n detach: boolean;\n logFile: string;\n /** cloudflared edge transport (quic | http2 | auto). Omitted ⇒ cloudflared's\n * default. Force `http2` on UDP-hostile networks that drop idle QUIC. */\n protocol?: string;\n /** Foreground only: fired when the connector exits for ANY reason (crash,\n * bad token, or a signal) so the caller can tear down / report. */\n onExit?: (code: number | null) => void;\n}\n\nexport interface StartedConnector {\n pid: number;\n child?: ChildProcess;\n}\n\nconst sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));\n\n/**\n * Spawn `cloudflared tunnel run`. The token is passed via the TUNNEL_TOKEN env\n * var — NEVER as an argv arg (argv is world-readable via `ps`/proc). Output goes\n * to a 0600 logfile (both foreground and detached) so the CLI can render its own\n * clean status instead of cloudflared's raw logs.\n */\nexport function startConnector(opts: StartOptions): StartedConnector {\n const args = [\"tunnel\", \"run\"];\n // Edge transport: pass as an explicit flag so it also lands in the connector\n // cmdline (visible/reproducible), not only via env.\n if (opts.protocol) args.push(\"--protocol\", opts.protocol);\n const env = { ...process.env, TUNNEL_TOKEN: opts.token };\n const fd = openSync(opts.logFile, \"a\", 0o600);\n const child = spawn(opts.bin, args, { env, detached: opts.detach, stdio: [\"ignore\", fd, fd] });\n if (!child.pid) throw new CliError(\"Failed to start the cloudflared connector.\");\n\n if (opts.detach) {\n child.unref();\n return { pid: child.pid };\n }\n child.on(\"exit\", (code) => opts.onExit?.(code));\n child.on(\"error\", () => opts.onExit?.(1));\n return { pid: child.pid, child };\n}\n\n/**\n * Stop a connector by registry entry. Verifies the pid is still OUR cloudflared\n * (alive, same boot, right cmdline) BEFORE signalling, so a reused pid held by\n * an unrelated process is never killed. Returns true if a stop was issued.\n */\nexport async function stopConnector(entry: RegistryEntry): Promise<boolean> {\n if (!entry.pid || !(await isOurConnector(entry))) return false;\n const pid = entry.pid;\n\n if (process.platform === \"win32\") {\n try {\n execFileSync(\"taskkill\", [\"/pid\", String(pid), \"/T\", \"/F\"], { stdio: \"ignore\" });\n } catch {\n return false;\n }\n return true;\n }\n\n try {\n process.kill(pid, \"SIGTERM\");\n } catch {\n return false;\n }\n await sleep(3000);\n if (await isOurConnector(entry)) {\n try {\n process.kill(pid, \"SIGKILL\");\n } catch {\n // already gone\n }\n }\n return true;\n}\n","import { existsSync, readFileSync, renameSync, writeFileSync } from \"node:fs\";\nimport { readFile } from \"node:fs/promises\";\nimport os from \"node:os\";\nimport lockfile from \"proper-lockfile\";\nimport { ensureDirs, registryFile } from \"../config/paths.js\";\n\nexport type EntryState = \"provisioning\" | \"running\" | \"stopped\" | \"orphaned\";\n\nexport interface RegistryEntry {\n subdomain: string;\n zone: string;\n zoneId: string;\n index?: number; // small stable handle shown as `#` in `ls` (target by number)\n tunnelId?: string;\n dnsRecordId?: string;\n port: number;\n proto: \"http\" | \"https\";\n host?: string; // forward target host (absent = localhost)\n pid?: number;\n bootId?: string;\n logFile?: string;\n createdAt: string;\n state: EntryState;\n}\n\n/** The real hostname for an entry. `@` is the apex, keyed in the registry by the\n * bare zone (NOT `@.zone`), so every entry→fqdn reconstruction must go through\n * this — otherwise apex tunnels become untargetable and leak. */\nexport function entryFqdn(e: Pick<RegistryEntry, \"subdomain\" | \"zone\">): string {\n return e.subdomain === \"@\" ? e.zone : `${e.subdomain}.${e.zone}`;\n}\n\ntype Registry = Record<string, RegistryEntry>;\n\n/** Stable per-boot id so a pid reused after a reboot is never mistaken for ours.\n * On systems without the Linux boot_id file (e.g. macOS), fall back to the boot\n * *time* bucketed to the minute — this is constant between invocations (unlike\n * `os.uptime()`, which increases every second and would break connector tracking). */\nexport function currentBootId(): string {\n try {\n return readFileSync(\"/proc/sys/kernel/random/boot_id\", \"utf8\").trim();\n } catch {\n const bootMinute = Math.floor((Date.now() - os.uptime() * 1000) / 60_000);\n return `boot-${bootMinute}-${os.hostname()}`;\n }\n}\n\nfunction readRegistry(): Registry {\n try {\n return JSON.parse(readFileSync(registryFile, \"utf8\")) as Registry;\n } catch {\n return {};\n }\n}\n\nfunction writeRegistry(reg: Registry): void {\n ensureDirs();\n const tmp = `${registryFile}.tmp`;\n writeFileSync(tmp, JSON.stringify(reg, null, 2), { mode: 0o600 });\n renameSync(tmp, registryFile); // atomic on the same filesystem\n}\n\n/** Lock-guarded read-modify-write (prevents lost updates across concurrent runs). */\nexport async function mutateRegistry<T>(fn: (reg: Registry) => T): Promise<T> {\n ensureDirs();\n if (!existsSync(registryFile)) writeFileSync(registryFile, \"{}\", { mode: 0o600 });\n const release = await lockfile.lock(registryFile, { retries: { retries: 10, minTimeout: 50 } });\n try {\n const reg = readRegistry();\n const result = fn(reg);\n writeRegistry(reg);\n return result;\n } finally {\n await release();\n }\n}\n\nexport function listEntries(): RegistryEntry[] {\n return Object.values(readRegistry());\n}\n\nexport function getEntry(fqdn: string): RegistryEntry | undefined {\n return readRegistry()[fqdn];\n}\n\nexport function upsertEntry(fqdn: string, patch: Partial<RegistryEntry> & Pick<RegistryEntry, \"subdomain\" | \"zone\" | \"zoneId\" | \"port\" | \"proto\">): Promise<void> {\n return mutateRegistry((reg) => {\n const prev = reg[fqdn];\n reg[fqdn] = {\n createdAt: prev?.createdAt ?? new Date().toISOString(),\n index: prev?.index ?? nextIndex(reg),\n state: \"provisioning\",\n ...prev,\n ...patch,\n };\n });\n}\n\n/** Smallest positive integer not currently used as an entry index (reused when\n * an entry is removed) — the friendly `#` handle shown in `ls`. */\nfunction nextIndex(reg: Registry): number {\n const used = new Set(\n Object.values(reg)\n .map((e) => e.index)\n .filter((n): n is number => typeof n === \"number\"),\n );\n let i = 1;\n while (used.has(i)) i++;\n return i;\n}\n\n/** Merge changed fields onto an existing entry under the lock (no stale\n * full-snapshot read outside the lock — avoids lost updates). No-op if absent. */\nexport function patchEntry(fqdn: string, patch: Partial<RegistryEntry>): Promise<void> {\n return mutateRegistry((reg) => {\n const prev = reg[fqdn];\n if (prev) reg[fqdn] = { ...prev, ...patch };\n });\n}\n\nexport function removeEntry(fqdn: string): Promise<void> {\n return mutateRegistry((reg) => {\n delete reg[fqdn];\n });\n}\n\nfunction pidAlive(pid: number): boolean {\n try {\n process.kill(pid, 0);\n return true;\n } catch {\n return false;\n }\n}\n\n/** Verify a pid is still OUR cloudflared: alive, same boot, and (Linux) its\n * cmdline is cloudflared — so we never signal a reused pid. */\nexport async function isOurConnector(entry: RegistryEntry): Promise<boolean> {\n if (!entry.pid || entry.bootId !== currentBootId()) return false;\n if (!pidAlive(entry.pid)) return false;\n if (process.platform === \"linux\") {\n try {\n const cmdline = await readFile(`/proc/${entry.pid}/cmdline`, \"utf8\");\n return cmdline.includes(\"cloudflared\");\n } catch {\n return false;\n }\n }\n return true; // non-Linux: bootId + liveness (best effort)\n}\n\n/** Mark entries whose connector is no longer alive as `stopped`. */\nexport async function reconcile(): Promise<RegistryEntry[]> {\n const entries = listEntries();\n for (const entry of entries) {\n if (entry.state === \"running\" && !(await isOurConnector(entry))) {\n const fqdn = entryFqdn(entry);\n await mutateRegistry((reg) => {\n const e = reg[fqdn];\n if (e) {\n e.state = \"stopped\";\n delete e.pid;\n }\n });\n }\n }\n return listEntries();\n}\n","import { cfPaginate, cfRequest, type Cf } from \"./client.js\";\nimport type { Connection, IngressRule, Tunnel } from \"./types.js\";\nimport { CliError } from \"../ui/errors.js\";\n\n/** Tunnels created by cloudtunnel carry this name prefix (ownership marker). */\nexport const MANAGED_TUNNEL_PREFIX = \"ct-\";\n\nexport function isManagedTunnel(tunnel: Tunnel): boolean {\n return tunnel.name.startsWith(MANAGED_TUNNEL_PREFIX);\n}\n\nexport async function createTunnel(cf: Cf, name: string): Promise<Tunnel> {\n const env = await cfRequest<Tunnel>(cf.token, \"POST\", `/accounts/${cf.accountId}/cfd_tunnel`, {\n name,\n config_src: \"cloudflare\",\n });\n return env.result;\n}\n\nexport function listTunnels(cf: Cf): Promise<Tunnel[]> {\n return cfPaginate<Tunnel>(cf.token, `/accounts/${cf.accountId}/cfd_tunnel?is_deleted=false`);\n}\n\nexport async function getTunnel(cf: Cf, id: string): Promise<Tunnel> {\n return (await cfRequest<Tunnel>(cf.token, \"GET\", `/accounts/${cf.accountId}/cfd_tunnel/${id}`)).result;\n}\n\nexport async function deleteTunnel(cf: Cf, id: string): Promise<void> {\n await cfRequest<unknown>(cf.token, \"DELETE\", `/accounts/${cf.accountId}/cfd_tunnel/${id}`);\n}\n\n/** Force-disconnect a tunnel's (possibly stale) connectors so it can be deleted. */\nexport async function cleanupConnections(cf: Cf, id: string): Promise<void> {\n await cfRequest<unknown>(cf.token, \"DELETE\", `/accounts/${cf.accountId}/cfd_tunnel/${id}/connections`);\n}\n\n/** Delete a tunnel; if Cloudflare refuses because it still has active\n * connections (a connector died but the edge hasn't reaped it yet), clean the\n * connections up and retry once. */\nexport async function deleteTunnelWithConnections(cf: Cf, id: string): Promise<void> {\n try {\n await deleteTunnel(cf, id);\n } catch (err) {\n if (err instanceof CliError && /active connections/i.test(err.message)) {\n await cleanupConnections(cf, id);\n await deleteTunnel(cf, id);\n } else {\n throw err;\n }\n }\n}\n\n/** The connector token (encodes tunnelId + secret) passed to `cloudflared`. */\nexport async function getTunnelToken(cf: Cf, id: string): Promise<string> {\n return (await cfRequest<string>(cf.token, \"GET\", `/accounts/${cf.accountId}/cfd_tunnel/${id}/token`)).result;\n}\n\n/** Full-replace ingress config (safe: one hostname + catch-all per tunnel). */\nexport async function putIngress(cf: Cf, id: string, ingress: IngressRule[]): Promise<void> {\n await cfRequest<unknown>(cf.token, \"PUT\", `/accounts/${cf.accountId}/cfd_tunnel/${id}/configurations`, {\n config: { ingress },\n });\n}\n\n/** Active connector instances (≥1 ⇒ tunnel is serving). */\nexport async function getConnections(cf: Cf, id: string): Promise<Connection[]> {\n const env = await cfRequest<Connection[]>(\n cf.token,\n \"GET\",\n `/accounts/${cf.accountId}/cfd_tunnel/${id}/connections`,\n );\n return env.result ?? [];\n}\n","import { getConnections } from \"../cloudflare/tunnels.js\";\nimport type { Cf } from \"../cloudflare/client.js\";\n\nexport type HealthResult = \"healthy\" | \"provisioning\" | \"dead\";\n\nconst sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));\n\n/**\n * Poll the tunnel's connections until it's serving. `signal` is fired by the\n * caller when the connector process exits, so a dead connector returns `dead`\n * immediately instead of waiting out the timeout. `provisioning` is only\n * returned if the process is still alive at the deadline (never a false\n * \"healthy\"). Note: this measures connector↔edge, not local-origin, health.\n */\nexport async function waitHealthy(\n cf: Cf,\n tunnelId: string,\n opts: { signal?: AbortSignal; timeoutMs?: number } = {},\n): Promise<HealthResult> {\n const deadline = Date.now() + (opts.timeoutMs ?? 30_000);\n while (Date.now() < deadline) {\n if (opts.signal?.aborted) return \"dead\";\n try {\n const connections = await getConnections(cf, tunnelId);\n if (connections.length > 0) return \"healthy\";\n } catch {\n // transient API error — keep polling until the deadline\n }\n await sleep(2000);\n }\n return opts.signal?.aborted ? \"dead\" : \"provisioning\";\n}\n","import { randomInt } from \"node:crypto\";\nimport type { Cf } from \"../cloudflare/client.js\";\nimport { resolveZone } from \"../cloudflare/zones.js\";\nimport {\n MANAGED_TUNNEL_PREFIX,\n createTunnel,\n deleteTunnel,\n deleteTunnelWithConnections,\n getTunnel,\n getTunnelToken,\n isManagedTunnel,\n putIngress,\n} from \"../cloudflare/tunnels.js\";\nimport { createCname, deleteDnsRecord, findCname } from \"../cloudflare/dns.js\";\nimport type { DnsRecord } from \"../cloudflare/types.js\";\nimport { buildIngress } from \"./ingress.js\";\nimport { resolveHostSpec, type HostSpec } from \"./slug.js\";\nimport { currentBootId, patchEntry, removeEntry, upsertEntry } from \"../connector/registry.js\";\nimport { CliError } from \"../ui/errors.js\";\nimport { confirm, say } from \"../ui/output.js\";\n\nexport interface CreateOptions {\n port: number;\n proto: \"http\" | \"https\";\n name?: string;\n zone?: string;\n hostname?: string;\n host?: string; // forward target host (absent = localhost)\n defaultZone?: string;\n force?: boolean;\n yes?: boolean; // skip the \"replace existing record?\" confirmation\n}\n\nexport interface CreateResult {\n host: HostSpec;\n tunnelId: string;\n token: string;\n}\n\nconst tunnelIdFromCname = (content: string): string => content.replace(/\\.cfargotunnel\\.com\\.?$/, \"\");\n\n/**\n * Create a tunnel subdomain transactionally (idempotent). Any leftover tunnel\n * record for the same hostname is cleaned up first, so re-running `up` never\n * conflicts. A `provisioning` registry entry is written BEFORE any Cloudflare\n * resource; on failure everything is unwound in reverse and the original error\n * is surfaced.\n */\nexport async function createTunnelSubdomain(cf: Cf, opts: CreateOptions): Promise<CreateResult> {\n const host = resolveHostSpec(opts, opts.defaultZone);\n const zone = await resolveZone(cf.token, host.zone);\n\n const existing = await findCname(cf.token, zone.id, host.hostname);\n if (existing) {\n // A leftover tunnel record → replaceable. A non-tunnel DNS record (A record,\n // ordinary CNAME) → refuse unless --force, to avoid clobbering unrelated DNS.\n const isTunnelRecord = existing.content.endsWith(\".cfargotunnel.com\");\n if (!isTunnelRecord && !opts.force) {\n throw new CliError(`${host.hostname} is taken by a non-tunnel DNS record.`, {\n hint: \"pick another --subdomain/--hostname, or pass -f/--force to replace it\",\n });\n }\n // Confirm before replacing an existing record (interactive only; -f/-y skip).\n if (!opts.force && !opts.yes && process.stdin.isTTY) {\n const kind = isTunnelRecord ? \"tunnel\" : \"DNS\";\n if (!(await confirm(`${host.hostname} already has a ${kind} record. Replace it?`))) {\n throw new CliError(\"Cancelled.\", { exitCode: 130 });\n }\n }\n await releaseHostname(cf, zone.id, existing);\n }\n\n // Track provisioning BEFORE creating anything irreversible.\n await upsertEntry(host.hostname, {\n subdomain: host.subdomain, zone: host.zone, zoneId: zone.id,\n port: opts.port, proto: opts.proto, host: opts.host, state: \"provisioning\",\n });\n\n let tunnelId: string | undefined;\n let dnsRecordId: string | undefined;\n try {\n const suffix = randomInt(0x10000).toString(16).padStart(4, \"0\");\n const label = host.subdomain === \"@\" ? \"root\" : host.subdomain;\n const tunnel = await createTunnel(cf, `${MANAGED_TUNNEL_PREFIX}${label}-${suffix}`);\n tunnelId = tunnel.id;\n const token = await getTunnelToken(cf, tunnelId);\n await putIngress(cf, tunnelId, buildIngress({ hostname: host.hostname, port: opts.port, proto: opts.proto, host: opts.host }));\n const record = await createCname(cf.token, zone.id, host.hostname, tunnelId);\n dnsRecordId = record.id;\n await recordRunning(host, zone.id, tunnelId, dnsRecordId, opts);\n return { host, tunnelId, token };\n } catch (err) {\n const clean = await rollback(cf, zone.id, tunnelId, dnsRecordId, host.hostname);\n if (clean) await removeEntry(host.hostname);\n else await patchEntry(host.hostname, { state: \"orphaned\" });\n throw err;\n }\n}\n\nasync function recordRunning(host: HostSpec, zoneId: string, tunnelId: string, dnsRecordId: string, opts: CreateOptions): Promise<void> {\n await upsertEntry(host.hostname, {\n subdomain: host.subdomain, zone: host.zone, zoneId,\n tunnelId, dnsRecordId, port: opts.port, proto: opts.proto, host: opts.host,\n bootId: currentBootId(), state: \"running\",\n });\n}\n\n/** Free a hostname before recreating: delete its DNS record, and if it pointed\n * at a cloudtunnel-managed tunnel, delete that tunnel too (cleaning up any\n * lingering connections). A foreign tunnel is left alone — we only free the name. */\nasync function releaseHostname(cf: Cf, zoneId: string, record: DnsRecord): Promise<void> {\n if (record.content.endsWith(\".cfargotunnel.com\")) {\n const oldTunnelId = tunnelIdFromCname(record.content);\n try {\n const tunnel = await getTunnel(cf, oldTunnelId);\n if (isManagedTunnel(tunnel)) await deleteTunnelWithConnections(cf, oldTunnelId);\n } catch {\n /* tunnel already gone or not accessible — freeing the DNS name is enough */\n }\n }\n await deleteDnsRecord(cf.token, zoneId, record.id);\n}\n\n/** Unwind created resources in reverse. Never masks the original error; if a\n * step fails, report the leaked id and return false so the caller marks the\n * entry `orphaned`. */\nasync function rollback(cf: Cf, zoneId: string, tunnelId?: string, dnsRecordId?: string, hostname?: string): Promise<boolean> {\n let clean = true;\n if (dnsRecordId) {\n try { await deleteDnsRecord(cf.token, zoneId, dnsRecordId); }\n catch { clean = false; say.warn(`Left a DNS record behind for ${hostname} (${dnsRecordId}).`); }\n }\n if (tunnelId) {\n try { await deleteTunnel(cf, tunnelId); }\n catch { clean = false; say.warn(`Left tunnel ${tunnelId} behind — remove it with \\`cloudtunnel down ${hostname}\\`.`); }\n }\n return clean;\n}\n","import { randomInt } from \"node:crypto\";\nimport { CliError } from \"../ui/errors.js\";\n\nconst ADJECTIVES = [\n \"brave\", \"calm\", \"clever\", \"eager\", \"gentle\", \"happy\", \"jolly\", \"kind\",\n \"lively\", \"mighty\", \"nimble\", \"proud\", \"quick\", \"royal\", \"swift\", \"witty\",\n];\nconst NOUNS = [\n \"otter\", \"falcon\", \"maple\", \"comet\", \"harbor\", \"lynx\", \"willow\", \"cedar\",\n \"raven\", \"meadow\", \"pixel\", \"quartz\", \"river\", \"sparrow\", \"tiger\", \"walnut\",\n];\n\nconst pick = <T>(arr: T[]): T => arr[randomInt(arr.length)]!;\n\n/** A friendly random subdomain, e.g. `brave-otter-1a2b` (the default when unnamed). */\nexport function randomSlug(): string {\n const suffix = randomInt(0x10000).toString(16).padStart(4, \"0\");\n return `${pick(ADJECTIVES)}-${pick(NOUNS)}-${suffix}`;\n}\n\nexport interface HostSpec {\n subdomain: string;\n zone: string;\n hostname: string;\n}\n\n/**\n * Resolve the target hostname from flags. Precedence: --hostname > --name+zone >\n * random-slug+zone. Zone comes from --zone or the saved default; missing zone is\n * an actionable error. (--hostname assumes `label.zone`; deeper subdomains need\n * the zone to be an actual Cloudflare zone.)\n */\nexport function resolveHostSpec(\n opts: { name?: string; zone?: string; hostname?: string },\n defaultZone?: string,\n): HostSpec {\n if (opts.hostname) {\n const dot = opts.hostname.indexOf(\".\");\n if (dot <= 0) throw new CliError(`Invalid hostname: ${opts.hostname}`);\n return {\n subdomain: opts.hostname.slice(0, dot),\n zone: opts.hostname.slice(dot + 1),\n hostname: opts.hostname,\n };\n }\n const zone = opts.zone ?? defaultZone;\n if (!zone) {\n throw new CliError(\"No zone specified and no default zone set.\", {\n hint: \"pass --zone <domain>, or run `cloudtunnel login --zone <domain>`\",\n });\n }\n const subdomain = opts.name ?? randomSlug();\n // `@` means the root/apex domain (Cloudflare flattens the proxied CNAME).\n const hostname = subdomain === \"@\" ? zone : `${subdomain}.${zone}`;\n return { subdomain, zone, hostname };\n}\n","import type { Cf } from \"../cloudflare/client.js\";\nimport { resolveZone } from \"../cloudflare/zones.js\";\nimport { deleteTunnelWithConnections, getTunnel, isManagedTunnel, listTunnels } from \"../cloudflare/tunnels.js\";\nimport { deleteDnsRecord, findCname, isManagedDns } from \"../cloudflare/dns.js\";\nimport type { Tunnel } from \"../cloudflare/types.js\";\nimport { CliError } from \"../ui/errors.js\";\nimport { say } from \"../ui/output.js\";\nimport { entryFqdn, getEntry, listEntries, reconcile, removeEntry, type RegistryEntry } from \"../connector/registry.js\";\nimport { stopConnector } from \"../connector/process.js\";\nimport { serviceUrl } from \"./ingress.js\";\nimport { serviceState } from \"./systemd.js\";\n\nconst tunnelIdFromCname = (content: string): string => content.replace(/\\.cfargotunnel\\.com\\.?$/, \"\");\nconst isNotFound = (err: unknown): boolean => err instanceof CliError && err.status === 404;\nconst zoneFromFqdn = (fqdn: string): string => fqdn.slice(fqdn.indexOf(\".\") + 1);\n\n/** Resolve a target to its registry entry / fqdn. Accepts a full hostname, the\n * `#` number, a subdomain name, or a tunnel-id prefix (all shown in `ls`).\n * Refuses an ambiguous match. */\nexport function resolveTarget(target: string): { fqdn: string; entry?: RegistryEntry } {\n if (target.includes(\".\")) return { fqdn: target, entry: getEntry(target) };\n const entries = listEntries();\n if (/^\\d+$/.test(target)) {\n const byIndex = entries.find((e) => e.index === Number(target));\n if (byIndex) return { fqdn: entryFqdn(byIndex), entry: byIndex };\n }\n const byId = entries.filter((e) => e.tunnelId?.startsWith(target));\n const matches = byId.length > 0 ? byId : entries.filter((e) => e.subdomain === target);\n if (matches.length > 1) {\n throw new CliError(`\"${target}\" matches multiple subdomains.`, {\n hint: `use a full hostname or a longer id: ${matches.map(entryFqdn).join(\", \")}`,\n });\n }\n const entry = matches[0];\n if (!entry) {\n throw new CliError(`No tracked subdomain matching \"${target}\".`, { hint: \"see `cloudtunnel ls` for the #, name, or id\" });\n }\n return { fqdn: entryFqdn(entry), entry };\n}\n\nexport interface RemoveOptions { force?: boolean; dryRun?: boolean; quiet?: boolean }\n\n/** Release a subdomain: stop the connector, then delete the tunnel + DNS on\n * Cloudflare. Re-verifies fresh state (cached ids are hints), ownership-gates\n * unmanaged resources, and tolerates already-deleted parts. */\nexport async function removeTunnelSubdomain(cf: Cf, target: string, opts: RemoveOptions = {}): Promise<void> {\n const { fqdn, entry } = resolveTarget(target);\n if (!entry && !opts.force) {\n throw new CliError(`${fqdn} is not managed by cloudtunnel.`, { hint: \"pass --force to release it anyway\" });\n }\n const zoneId = entry?.zoneId ?? (await resolveZone(cf.token, zoneFromFqdn(fqdn))).id;\n\n const record = await findCname(cf.token, zoneId, fqdn); // fresh, authoritative\n if (record && !isManagedDns(record) && !opts.force) {\n throw new CliError(`${fqdn} points to a record not managed by cloudtunnel.`, { hint: \"pass --force to release it\" });\n }\n const tunnelId = record ? tunnelIdFromCname(record.content) : entry?.tunnelId;\n\n if (opts.dryRun) {\n say.info(`Would release: tunnel ${tunnelId ?? \"(none)\"}${record ? `, DNS ${record.id}` : \"\"}`);\n return;\n }\n\n if (entry) await stopConnector(entry);\n if (tunnelId) {\n let tunnel: Tunnel | undefined;\n try {\n tunnel = await getTunnel(cf, tunnelId);\n } catch (err) {\n if (!isNotFound(err)) throw err; // transient error → don't silently orphan\n }\n if (tunnel && !isManagedTunnel(tunnel) && !opts.force) {\n throw new CliError(`Tunnel ${tunnelId} is not managed by cloudtunnel.`, { hint: \"pass --force\" });\n }\n if (tunnel) {\n try {\n await deleteTunnelWithConnections(cf, tunnelId);\n } catch (err) {\n if (!isNotFound(err)) throw err;\n }\n }\n }\n if (record) {\n try {\n await deleteDnsRecord(cf.token, zoneId, record.id);\n } catch (err) {\n if (!isNotFound(err)) throw err;\n }\n }\n await removeEntry(fqdn);\n if (!opts.quiet) say.ok(`Released ${fqdn}`);\n}\n\nexport interface LsRow { num: string; url: string; target: string; state: string; service: string; pid: string; managed: boolean }\n\n/** Reconcile + list tracked subdomains: `# | URL | TARGET | STATE | SERVICE | PID`.\n * SERVICE is the per-subdomain systemd unit's state (\"-\" when none). `all` also\n * scans every zone for cfargotunnel CNAMEs created outside cloudtunnel. */\nexport async function listAll(cf: Cf, opts: { all?: boolean } = {}): Promise<LsRow[]> {\n const entries = await reconcile();\n const tunnels = new Map((await listTunnels(cf)).map((t) => [t.id, t]));\n const rows: LsRow[] = entries.map((e) => {\n const fqdn = entryFqdn(e);\n const gone = e.tunnelId ? !tunnels.has(e.tunnelId) : false;\n const svc = serviceState(fqdn);\n return {\n num: e.index ? String(e.index) : \"-\",\n url: `https://${fqdn}`,\n target: serviceUrl(e.proto, e.host ?? \"localhost\", e.port),\n state: !gone && e.state === \"running\" ? \"up\" : \"down\",\n service: svc === \"none\" ? \"-\" : svc,\n pid: e.state === \"running\" && e.pid ? String(e.pid) : \"-\",\n managed: true,\n };\n });\n if (opts.all) {\n const { listCargoCnames } = await import(\"../cloudflare/dns.js\");\n const { listZones } = await import(\"../cloudflare/zones.js\");\n const tracked = new Set(entries.map(entryFqdn));\n for (const zone of await listZones(cf.token)) {\n for (const rec of await listCargoCnames(cf.token, zone.id)) {\n if (!tracked.has(rec.name)) {\n rows.push({ num: \"-\", url: `https://${rec.name}`, target: \"-\", state: \"unmanaged\", service: \"-\", pid: \"-\", managed: false });\n }\n }\n }\n }\n return rows;\n}\n","import { CliError } from \"../ui/errors.js\";\n\n/**\n * cloudflared edge transport (NOT the local service scheme). `quic` is UDP-based\n * and fastest, but UDP-hostile networks drop idle QUIC sessions (→ Cloudflare\n * 530/502); `http2` runs over TCP and stays stable there. `auto` lets cloudflared\n * choose (defaults to quic when the network probe passes).\n */\nexport type TransportProtocol = \"auto\" | \"http2\" | \"quic\";\n\nexport function parseTransportProtocol(value: string): TransportProtocol {\n if (value === \"auto\" || value === \"http2\" || value === \"quic\") return value;\n throw new CliError(`Invalid protocol \"${value}\".`, { hint: \"use auto, http2, or quic\" });\n}\n","import type { Command } from \"commander\";\nimport { printTable, say } from \"../ui/output.js\";\nimport { ensureAuth } from \"../config/ensure-auth.js\";\nimport { resolveCf } from \"../cloudflare/client.js\";\nimport { listAll } from \"../core/orchestrator-manage.js\";\n\nexport function registerLs(program: Command): void {\n program\n .command(\"ls\")\n .alias(\"ps\")\n .description(\"List tunnel subdomains (managed by default; --all scans the whole account)\")\n .option(\"--all\", \"scan every zone in the account (slower; shows unmanaged tunnels too)\")\n .action(async (opts: { all?: boolean }) => {\n await ensureAuth();\n const cf = resolveCf();\n const rows = await listAll(cf, { all: opts.all });\n if (rows.length === 0) {\n say.info(\"No tunnel subdomains yet. Create one: `cloudtunnel 3000`\");\n return;\n }\n printTable(\n [\"#\", \"URL\", \"TARGET\", \"STATE\", \"SERVICE\", \"PID\"],\n rows.map((r) => [r.num, r.url, r.target, r.state, r.service, r.pid]),\n );\n });\n}\n","import type { Command } from \"commander\";\nimport { CliError } from \"../ui/errors.js\";\nimport { say } from \"../ui/output.js\";\nimport { ensureAuth } from \"../config/ensure-auth.js\";\nimport { resolveCf, type Cf } from \"../cloudflare/client.js\";\nimport { entryFqdn, listEntries } from \"../connector/registry.js\";\nimport { removeTunnelSubdomain, resolveTarget } from \"../core/orchestrator-manage.js\";\nimport { serviceName, serviceState, uninstallService } from \"../core/systemd.js\";\n\ninterface DeleteOptions { all?: boolean; force?: boolean; dryRun?: boolean }\n\n/** Release one subdomain by its resolved fqdn, then drop its systemd unit if any. */\nasync function deleteOne(cf: Cf, fqdn: string, opts: DeleteOptions): Promise<void> {\n await removeTunnelSubdomain(cf, fqdn, { force: opts.force, dryRun: opts.dryRun });\n if (serviceState(fqdn) === \"none\") return;\n if (opts.dryRun) {\n say.info(`Would also remove boot service ${serviceName(fqdn)}`);\n return;\n }\n uninstallService(fqdn);\n say.ok(`Removed boot service ${serviceName(fqdn)}`);\n}\n\nexport function registerDelete(program: Command): void {\n program\n .command(\"delete\")\n .argument(\"[targets...]\", \"subdomains to remove by # / name / URL (omit with --all)\")\n .description(\"Release tunnel(s) — deletes the tunnel + DNS, and any systemd boot service\")\n .option(\"--all\", \"release every tracked subdomain\")\n .option(\"-f, --force\", \"release even a resource not created by cloudtunnel\")\n .option(\"--dry-run\", \"show what would be released without doing it\")\n .action(async (targets: string[], opts: DeleteOptions) => {\n await ensureAuth();\n const cf = resolveCf();\n\n if (opts.all) {\n const entries = listEntries();\n if (entries.length === 0) {\n say.info(\"Nothing to release.\");\n return;\n }\n for (const e of entries) {\n const fqdn = entryFqdn(e);\n try {\n await deleteOne(cf, fqdn, opts);\n } catch (err) {\n say.warn(`Could not release ${fqdn}: ${(err as Error).message}`);\n }\n }\n return;\n }\n\n if (targets.length === 0) throw new CliError(\"Pass a subdomain (# / name / URL) or --all.\");\n for (const target of targets) {\n const { fqdn } = resolveTarget(target);\n await deleteOne(cf, fqdn, opts);\n }\n });\n}\n","import type { Command } from \"commander\";\nimport { closeSync, existsSync, openSync, readFileSync, readSync, statSync, watch } from \"node:fs\";\nimport { CliError } from \"../ui/errors.js\";\nimport { say } from \"../ui/output.js\";\nimport { resolveTarget } from \"../core/orchestrator-manage.js\";\n\ninterface LogsOptions {\n follow?: boolean;\n lines?: string;\n}\n\n/** Print the last `n` lines of a file; return the file's byte size (follow start). */\nfunction printTail(file: string, n: number): number {\n const lines = readFileSync(file, \"utf8\").split(\"\\n\");\n const tail = lines.slice(-n).join(\"\\n\");\n process.stdout.write(tail.endsWith(\"\\n\") ? tail : `${tail}\\n`);\n return statSync(file).size;\n}\n\n/** Tail -f: print appended bytes as the connector writes them. Ctrl-C to stop. */\nfunction follow(file: string, fromPos: number): void {\n let pos = fromPos;\n say.dim(\"— following (Ctrl-C to stop) —\");\n const watcher = watch(file, () => {\n const size = statSync(file).size;\n if (size < pos) {\n pos = 0; // file was truncated/rotated\n return;\n }\n if (size > pos) {\n const fd = openSync(file, \"r\");\n const buf = Buffer.alloc(size - pos);\n readSync(fd, buf, 0, size - pos, pos);\n closeSync(fd);\n process.stdout.write(buf.toString(\"utf8\"));\n pos = size;\n }\n });\n process.on(\"SIGINT\", () => {\n watcher.close();\n process.exit(0);\n });\n}\n\nexport function registerLogs(program: Command): void {\n program\n .command(\"logs\")\n .argument(\"<target>\", \"subdomain name / hostname / id / #\")\n .description(\"Show the connector log for a subdomain (use -f to follow)\")\n .option(\"-f, --follow\", \"keep printing new log lines (like tail -f)\")\n .option(\"-n, --lines <n>\", \"number of lines to show\", \"50\")\n .action((name: string, opts: LogsOptions) => {\n const { fqdn, entry } = resolveTarget(name);\n if (!entry?.logFile || !existsSync(entry.logFile)) {\n throw new CliError(`No logs for ${fqdn} yet.`, { hint: \"start it with `cloudtunnel up` or `cloudtunnel run`\" });\n }\n const n = Math.max(1, Number(opts.lines) || 50);\n const pos = printTail(entry.logFile, n);\n if (opts.follow) follow(entry.logFile, pos);\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,eAAe;AACxB,SAAS,qBAAqB;AAC9B,OAAOA,SAAQ;;;ACFf,SAAS,cAAAC,aAAY,cAAc,YAAY,iBAAAC,sBAAqB;;;ACApE,OAAO,QAAQ;AACf,OAAO,WAAW;AAClB,SAAS,QAAQ,WAAW,cAAc,OAAO,UAAU,MAAM,OAAO,QAAQ,eAAe;AAO/F,eAAsB,QAAQ,SAAmC;AAC/D,QAAM,SAAS,MAAM,aAAa,EAAE,QAAQ,CAAC;AAC7C,SAAO,CAAC,SAAS,MAAM,KAAK,WAAW;AACzC;AAGO,SAAS,YAAY,OAAuB;AACjD,MAAI,CAAC,MAAO,QAAO;AACnB,QAAM,QAAQ,MAAM,SAAS,IAAI,MAAM,MAAM,EAAE,IAAI;AACnD,SAAO,2BAAO,KAAK;AACrB;AAGO,IAAM,MAAM;AAAA,EACjB,MAAM,CAAC,QAAgB,QAAQ,IAAI,GAAG;AAAA,EACtC,IAAI,CAAC,QAAgB,QAAQ,IAAI,GAAG,MAAM,UAAK,GAAG,EAAE,CAAC;AAAA,EACrD,MAAM,CAAC,QAAgB,QAAQ,KAAK,GAAG,OAAO,KAAK,GAAG,EAAE,CAAC;AAAA,EACzD,KAAK,CAAC,QAAgB,QAAQ,IAAI,GAAG,IAAI,GAAG,CAAC;AAAA,EAC7C,MAAM,CAAC,QAAgB,QAAQ,IAAI,GAAG,KAAK,U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,wEAAwE,EACpF,QAAQ,IAAI,SAAS,eAAe,EACpC,mBAAmB;AAEtB,UAAQ;AAAA,IACN;AAAA,IACA;AAAA,MACEC,IAAG,KAAK,aAAa;AAAA,MACrB,KAAKA,IAAG,KAAK,mBAAmB,CAAC;AAAA,MACjC,KAAKA,IAAG,KAAK,kBAAkB,CAAC;AAAA,MAChC,KAAKA,IAAG,KAAK,sBAAsB,CAAC;AAAA,MACpC,KAAKA,IAAG,KAAK,gBAAgB,CAAC,4BAA4BA,IAAG,IAAI,MAAG,CAAC,MAAMA,IAAG,KAAK,wBAAwB,CAAC;AAAA,MAC5G;AAAA,IACF,EAAE,KAAK,IAAI;AAAA,EACb;AAEA,aAAW,YAAY,CAAC,eAAe,YAAY,YAAY,gBAAgB,YAAY,GAAG;AAC5F,aAAS,OAAO;AAAA,EAClB;AACA,SAAO;AACT;AAIA,SAAS,cAAc,MAAyB;AAC9C,MAAI,CAAC,QAAQ,MAAM,SAAS,CAAC,QAAQ,OAAO,MAAO,QAAO;AAC1D,QAAM,OAAO,KAAK,MAAM,CAAC;AACzB,QAAM,WAAW,oBAAI,IAAI,CAAC,MAAM,UAAU,MAAM,aAAa,MAAM,CAAC;AACpE,SAAO,CAAC,KAAK,KAAK,CAAC,MAAM,SAAS,IAAI,CAAC,CAAC;AAC1C;AAEA,eAAe,OAAsB;AAEnC,MAAI,cAAc,QAAQ,IAAI,EAAG,OAAM,sBAAsB;AAC7D,QAAM,UAAU,aAAa;AAC7B,MAAI;AACF,UAAM,QAAQ,WAAW,QAAQ,IAAI;AAAA,EACvC,SAAS,KAAK;AACZ,YAAQ,WAAW,YAAY,GAAG;AAAA,EACpC;AACF;AAEA,KAAK,KAAK;","names":["pc","existsSync","writeFileSync","existsSync","writeFileSync","listZones","listZones","clack","execFileSync","existsSync","readFileSync","writeFileSync","join","execFileSync","join","readFileSync","existsSync","writeFileSync","join","clack","execFileSync","spawn","existsSync","readFileSync","renameSync","writeFileSync","os","readFileSync","os","writeFileSync","renameSync","existsSync","spawn","execFileSync","sleep","randomInt","randomInt","tunnelIdFromCname","listZones","join","lines","existsSync","openSync","readFileSync","readFileSync","openSync","existsSync","require","pc"]}
1
+ {"version":3,"sources":["../src/index.ts","../src/config/legacy-migrate.ts","../src/ui/output.ts","../src/core/service-exec.ts","../src/core/ingress.ts","../src/core/tunnel-spec.ts","../src/core/service-systemd.ts","../src/core/service-launchd.ts","../src/core/service-windows.ts","../src/core/service.ts","../src/commands/login.ts","../src/config/token-url.ts","../src/config/resolve-identity.ts","../src/commands/up.ts","../src/config/ensure-auth.ts","../src/connector/binary.ts","../src/core/up-runner.ts","../src/connector/process.ts","../src/connector/registry.ts","../src/cloudflare/tunnels.ts","../src/connector/health.ts","../src/core/orchestrator-create.ts","../src/core/slug.ts","../src/core/orchestrator-manage.ts","../src/core/transport-protocol.ts","../src/commands/ls.ts","../src/commands/delete.ts","../src/commands/logs.ts"],"sourcesContent":["import { Command } from \"commander\";\nimport { createRequire } from \"node:module\";\nimport pc from \"picocolors\";\nimport { reportError } from \"./ui/errors.js\";\nimport { migrateLegacyProfiles } from \"./config/legacy-migrate.js\";\n\nimport { registerLogin } from \"./commands/login.js\";\nimport { registerUp } from \"./commands/up.js\";\nimport { registerLs } from \"./commands/ls.js\";\nimport { registerDelete } from \"./commands/delete.js\";\nimport { registerLogs } from \"./commands/logs.js\";\n\nconst require = createRequire(import.meta.url);\nconst pkg = require(\"../package.json\") as { version: string };\n\nfunction buildProgram(): Command {\n const program = new Command();\n program\n .name(\"cloudtunnel\")\n .description(\"Expose local ports at HTTPS subdomains on your own Cloudflare domains.\")\n .version(pkg.version, \"-v, --version\")\n .showHelpAfterError();\n\n program.addHelpText(\n \"before\",\n [\n pc.bold(\"Quickstart:\"),\n ` ${pc.cyan(\"cloudtunnel login\")} once — paste a token (or set CLOUDFLARE_API_TOKEN)`,\n ` ${pc.cyan(\"cloudtunnel 8080\")} your local :8080 goes live at an HTTPS URL`,\n ` ${pc.cyan(\"cloudtunnel api:8080\")} api.<domain> → localhost:8080`,\n ` ${pc.cyan(\"cloudtunnel ls\")} list tunnels ${pc.dim(\"·\")} ${pc.cyan(\"cloudtunnel delete <#>\")} remove one`,\n \"\",\n ].join(\"\\n\"),\n );\n\n for (const register of [registerLogin, registerUp, registerLs, registerDelete, registerLogs]) {\n register(program);\n }\n return program;\n}\n\n/** Migrate legacy profiles only in a real terminal (systemd changes need an\n * interactive sudo) and not for help/version, so scripts/CI stay quiet. */\nfunction shouldMigrate(argv: string[]): boolean {\n if (!process.stdin.isTTY || !process.stdout.isTTY) return false;\n const rest = argv.slice(2);\n const infoFlag = new Set([\"-h\", \"--help\", \"-v\", \"--version\", \"help\"]);\n return !rest.some((a) => infoFlag.has(a));\n}\n\nasync function main(): Promise<void> {\n // One-time, best-effort upgrade from the old profile model.\n if (shouldMigrate(process.argv)) await migrateLegacyProfiles();\n const program = buildProgram();\n try {\n await program.parseAsync(process.argv);\n } catch (err) {\n process.exitCode = reportError(err);\n }\n}\n\nvoid main();\n","import { existsSync, readFileSync, renameSync, writeFileSync } from \"node:fs\";\nimport { profilesFile } from \"./paths.js\";\nimport { confirm, say } from \"../ui/output.js\";\nimport { installServiceForSpec, legacyUnitExists, removeLegacyUnit } from \"../core/service.js\";\nimport type { TransportProtocol } from \"../core/transport-protocol.js\";\n\n// Shape of the retired profiles file (self-contained; no dependency on the\n// deleted profile store).\ninterface LegacyService { name: string; port: number; proto: \"http\" | \"https\"; host?: string; domain?: string }\ninterface LegacyProfile { services?: LegacyService[]; domain?: string; protocol?: TransportProtocol }\n\nconst skipMarker = `${profilesFile}.migrate-skip`;\n\n/**\n * One-time, best-effort migration from the old profile model. If a legacy profiles\n * file exists, convert any profile that was registered as a systemd service\n * (`cloudtunnel-<profile>.service`) into the new per-subdomain units. Asks for\n * consent first (it needs sudo), and on decline/failure drops a skip-marker so it\n * never re-prompts on later commands. Caller gates this to an interactive TTY.\n */\nexport async function migrateLegacyProfiles(): Promise<void> {\n if (!existsSync(profilesFile) || existsSync(skipMarker)) return; // fast path\n\n let profiles: Record<string, LegacyProfile>;\n try {\n profiles = JSON.parse(readFileSync(profilesFile, \"utf8\")) as Record<string, LegacyProfile>;\n } catch {\n return; // unreadable → leave it alone\n }\n\n // Only boot-registered profiles need migrating; the rest are just stale saved defs.\n const legacy = Object.entries(profiles).filter(([name]) => legacyUnitExists(name));\n if (legacy.length === 0) {\n try { renameSync(profilesFile, `${profilesFile}.migrated`); } catch { /* ignore */ }\n return;\n }\n\n const ok = await confirm(`Found ${legacy.length} boot service(s) from an older cloudtunnel. Migrate them now? (needs sudo)`);\n if (!ok) {\n writeFileSync(skipMarker, \"\");\n say.dim(` Skipped. Delete ${skipMarker} to be asked again.`);\n return;\n }\n\n let migrated = 0;\n try {\n for (const [name, profile] of legacy) {\n for (const svc of profile.services ?? []) {\n const zone = svc.domain ?? profile.domain;\n if (!zone) continue; // can't resolve a hostname → skip this service\n installServiceForSpec({\n subdomain: svc.name, port: svc.port, host: svc.host,\n zone, proto: svc.proto, protocol: profile.protocol,\n });\n migrated++;\n }\n removeLegacyUnit(name);\n }\n renameSync(profilesFile, `${profilesFile}.migrated`);\n say.ok(`Migrated ${migrated} boot service(s). See them with: cloudtunnel ls`);\n } catch (err) {\n writeFileSync(skipMarker, \"\"); // stop auto-retrying on every command\n say.warn(`Migration incomplete: ${(err as Error).message}. Won't retry automatically (delete ${skipMarker} to retry).`);\n }\n}\n","import pc from \"picocolors\";\nimport Table from \"cli-table3\";\nimport { cancel, confirm as clackConfirm, intro, isCancel, note, outro, select, spinner } from \"@clack/prompts\";\nimport { CliError } from \"./errors.js\";\n\n// Re-export the clack primitives used to build modern multi-step flows.\nexport { intro, note, outro, spinner };\n\n/** Yes/no prompt (TTY). Cancel (Ctrl-C) counts as \"no\". */\nexport async function confirm(message: string): Promise<boolean> {\n const answer = await clackConfirm({ message });\n return !isCancel(answer) && answer === true;\n}\n\n/** Redact a secret to `••••{last4}` so tokens never appear in output/logs. */\nexport function redactToken(token: string): string {\n if (!token) return \"\";\n const last4 = token.length > 4 ? token.slice(-4) : token;\n return `••••${last4}`;\n}\n\n// Lightweight one-off lines for non-flow commands (ls, zones, status, …).\nexport const say = {\n info: (msg: string) => console.log(msg),\n ok: (msg: string) => console.log(pc.green(`✓ ${msg}`)),\n warn: (msg: string) => console.warn(pc.yellow(`! ${msg}`)),\n dim: (msg: string) => console.log(pc.dim(msg)),\n step: (msg: string) => console.log(pc.cyan(`→ ${msg}`)),\n};\n\nexport const dim = (s: string): string => pc.dim(s);\n\n/** Format a live tunnel as `https://host → proto://localhost:port`. */\nexport function formatRoute(host: string, target: string): string {\n return `${pc.green(pc.bold(`https://${host}`))} ${pc.dim(\"→\")} ${pc.cyan(target)}`;\n}\n\n/** Render a simple table. `head` = column titles, `rows` = string cells. */\nexport function printTable(head: string[], rows: string[][]): void {\n const table = new Table({\n head: head.map((h) => pc.bold(h)),\n style: { head: [], border: [] },\n });\n for (const row of rows) table.push(row);\n console.log(table.toString());\n}\n\n/**\n * Modern arrow-key single-select (↑/↓ to move, Enter to choose). Callers must\n * guard non-TTY before calling. Ctrl-C cancels cleanly (exit 130).\n */\nexport async function selectOne<T>(\n message: string,\n items: T[],\n label: (item: T) => string,\n): Promise<T> {\n // Use the item index as the (primitive) option value to avoid clack's\n // conditional Option<T> type fighting the generic, then map back.\n const value = await select({\n message,\n options: items.map((item, i) => ({ value: String(i), label: label(item) })),\n });\n if (isCancel(value)) {\n cancel(\"Cancelled.\");\n throw new CliError(\"Cancelled.\", { exitCode: 130 });\n }\n return items[Number(value)]!;\n}\n","import { realpathSync } from \"node:fs\";\nimport os from \"node:os\";\nimport { join } from \"node:path\";\nimport { CliError } from \"../ui/errors.js\";\nimport { logDir } from \"../config/paths.js\";\nimport { formatTunnelSpec } from \"./tunnel-spec.js\";\nimport type { TransportProtocol } from \"./transport-protocol.js\";\n\nexport type ServiceState = \"active\" | \"enabled\" | \"disabled\" | \"none\";\n\n/** What `up --service` (and the migration) hand to a platform backend. */\nexport interface ServiceSpecParams {\n subdomain: string;\n port: number;\n host?: string;\n zone: string;\n proto: \"http\" | \"https\";\n protocol?: TransportProtocol;\n}\n\n/** Normalized, OS-agnostic description of the boot service for one subdomain. */\nexport interface ServiceDescriptor {\n fqdn: string;\n slug: string; // fqdn reduced to [a-z0-9-], unique per domain\n argv: string[]; // cloudtunnel args, e.g. [\"up\",\"api:8080@localhost\",\"-d\",\"abc.com\",\"-f\",\"-y\"]\n nodePath: string; // absolute node binary\n scriptPath: string; // absolute cloudtunnel entry\n user: string;\n home: string;\n logFile: string;\n}\n\nexport const fqdnFor = (subdomain: string, zone: string): string =>\n subdomain === \"@\" ? zone : `${subdomain}.${zone}`;\n\n/** Stable, filesystem-safe id derived from the fqdn (shared by every backend). */\nexport const serviceSlug = (fqdn: string): string => fqdn.replace(/[^a-zA-Z0-9]+/g, \"-\");\n\n/** The cloudtunnel args a boot service re-runs: recreate this one subdomain in the\n * foreground, non-interactively. Round-trips through `parseTunnelSpec` on boot. */\nexport function buildUpArgs(p: ServiceSpecParams): string[] {\n const spec = formatTunnelSpec({ subdomain: p.subdomain, port: p.port, host: p.host });\n return [\n \"up\", spec, \"-d\", p.zone,\n ...(p.proto === \"https\" ? [\"--proto\", \"https\"] : []),\n ...(p.protocol ? [\"--protocol\", p.protocol] : []),\n \"-f\", \"-y\",\n ];\n}\n\n/** Resolve the running cloudtunnel entry, for a stable service command. */\nfunction entryScript(): string {\n const p = process.argv[1];\n if (!p) throw new CliError(\"Cannot resolve the cloudtunnel executable path.\");\n return realpathSync(p);\n}\n\nexport function describeService(p: ServiceSpecParams): ServiceDescriptor {\n const fqdn = fqdnFor(p.subdomain, p.zone);\n const slug = serviceSlug(fqdn);\n return {\n fqdn,\n slug,\n argv: buildUpArgs(p),\n nodePath: process.execPath,\n scriptPath: entryScript(),\n user: os.userInfo().username,\n home: os.homedir(),\n logFile: join(logDir, `${slug}.service.log`),\n };\n}\n","import type { IngressRule } from \"../cloudflare/types.js\";\nimport { CliError } from \"../ui/errors.js\";\n\nconst HOSTNAME_RE = /^[a-zA-Z0-9.-]+$/; // hostname or IPv4\nconst IPV6_RE = /^[0-9a-fA-F:.]+$/; // IPv6 literal (incl. IPv4-mapped ::ffff:1.2.3.4)\n\n/**\n * Validate a forward-target host before it lands in the ingress service URL.\n * Rejects anything that could break out of `proto://host:port` — a scheme,\n * path, or whitespace — so `--source` can't inject extra ingress syntax.\n *\n * IPv6 is accepted bare (`::1`) or bracketed (`[::1]`) and stored bare. IPv6 is\n * detected by `::` or ≥2 colons, so a single-colon `10.0.0.2:8080` (an IPv4:port\n * mistake) still fails the hostname check instead of passing as a bogus literal.\n */\nexport function validateHost(host: string): string {\n let h = host.trim();\n const bracketed = h.startsWith(\"[\") && h.endsWith(\"]\");\n if (bracketed) h = h.slice(1, -1);\n const isV6 = bracketed || h.includes(\"::\") || (h.match(/:/g)?.length ?? 0) >= 2;\n const ok = h.length > 0 && (isV6 ? IPV6_RE.test(h) : HOSTNAME_RE.test(h));\n if (!ok) {\n throw new CliError(`Invalid host \"${host}\".`, {\n hint: \"use a hostname, IPv4, or IPv6 literal (e.g. 192.168.1.5 or ::1) — no port, scheme, or path\",\n });\n }\n return h;\n}\n\n/** Compose a `proto://host:port` service URL, bracketing an IPv6 literal. */\nexport function serviceUrl(proto: \"http\" | \"https\", host: string, port: number): string {\n const authority = host.includes(\":\") ? `[${host}]` : host;\n return `${proto}://${authority}:${port}`;\n}\n\n/**\n * Build the ingress config for a single-hostname tunnel. The mandatory\n * catch-all `http_status:404` rule must come last (Cloudflare rejects configs\n * without it). One-tunnel-per-subdomain keeps this a fixed two-rule list, so\n * the full-replace PUT is always safe (no merge with other hostnames).\n *\n * `host` defaults to `localhost`; pass another host/IP to forward to a different\n * machine this connector can reach (a LAN device, a container, another server).\n */\nexport function buildIngress(opts: {\n hostname: string;\n port: number;\n proto: \"http\" | \"https\";\n host?: string;\n}): IngressRule[] {\n return [\n { hostname: opts.hostname, service: serviceUrl(opts.proto, opts.host ?? \"localhost\", opts.port) },\n { service: \"http_status:404\" },\n ];\n}\n","import { CliError } from \"../ui/errors.js\";\nimport { validateHost } from \"./ingress.js\";\n\n/** One tunnel to bring up, parsed from a positional `up` argument. */\nexport interface TunnelSpec {\n subdomain?: string; // absent ⇒ random slug; \"@\" ⇒ root/apex domain\n port: number;\n host?: string; // forward target (absent ⇒ localhost)\n}\n\n/**\n * Parse a `[subdomain:]port[@host]` spec, e.g. `8080`, `api:8080`,\n * `api:8080@192.168.1.20`, `api:8080@localhost`, `api:8080@::1`. The local-service\n * protocol is NOT part of the spec — it comes from the global `--proto` flag.\n *\n * A leading `@` means the root/apex domain (kept as the subdomain), which is\n * distinct from the `@host` forward-target delimiter that follows the port.\n */\nexport function parseTunnelSpec(spec: string): TunnelSpec {\n const raw = spec.trim();\n const bad = (hint: string): CliError => new CliError(`Invalid spec \"${spec}\".`, { hint });\n if (!raw) throw bad(\"use [subdomain:]port[@host], e.g. api:8080 or api:8080@192.168.1.20\");\n\n let rest = raw;\n let subdomain: string | undefined;\n\n // Leading `@` = root/apex domain; consume it before looking for the host `@`.\n if (rest.startsWith(\"@\")) {\n subdomain = \"@\";\n rest = rest.slice(1);\n if (rest.startsWith(\":\")) rest = rest.slice(1);\n }\n\n // Forward host after `@` (may contain colons for an IPv6 literal).\n let host: string | undefined;\n const at = rest.indexOf(\"@\");\n if (at >= 0) {\n host = validateHost(rest.slice(at + 1));\n rest = rest.slice(0, at);\n }\n\n // `rest` is now `[subdomain:]port`.\n const parts = rest.split(\":\");\n let portStr: string;\n if (parts.length === 1) {\n portStr = parts[0]!;\n } else if (parts.length === 2) {\n if (subdomain === undefined) {\n if (!parts[0]) throw bad(\"subdomain label is empty\");\n subdomain = parts[0];\n } else if (parts[0]) {\n throw bad(\"unexpected label after '@' root marker\");\n }\n portStr = parts[1]!;\n } else {\n throw bad(\"too many ':' — spec is [subdomain:]port[@host] (protocol via --proto)\");\n }\n\n const port = Number(portStr);\n if (!Number.isInteger(port) || port < 1 || port > 65535) {\n throw bad(\"port must be a number 1–65535\");\n }\n // A DNS label (or \"@\" for the apex). Guards the Cloudflare API and, with\n // `--service`, keeps the subdomain a single unquoted token in the unit ExecStart.\n if (subdomain !== undefined && subdomain !== \"@\" && !/^[a-zA-Z0-9-]+$/.test(subdomain)) {\n throw bad(\"subdomain may contain only letters, digits, and hyphens\");\n }\n return { subdomain, port, ...(host ? { host } : {}) };\n}\n\n/**\n * Render a concrete spec back to its `subdomain:port[@host]` string — used to bake\n * a stable spec into a systemd unit's ExecStart so it round-trips through\n * `parseTunnelSpec` on boot.\n */\nexport function formatTunnelSpec(s: { subdomain: string; port: number; host?: string }): string {\n return `${s.subdomain}:${s.port}${s.host ? `@${s.host}` : \"\"}`;\n}\n","import { execFileSync } from \"node:child_process\";\nimport { existsSync, writeFileSync } from \"node:fs\";\nimport { tmpdir } from \"node:os\";\nimport { dirname, join } from \"node:path\";\nimport { CliError } from \"../ui/errors.js\";\nimport { serviceSlug, type ServiceDescriptor, type ServiceState } from \"./service-exec.js\";\n\nexport const label = (fqdn: string): string => `cloudtunnel-${serviceSlug(fqdn)}.service`;\nconst unitPath = (fqdn: string): string => `/etc/systemd/system/${label(fqdn)}`;\n\n/**\n * Build the systemd unit text (pure — unit-tested). ExecStart re-runs the\n * `cloudtunnel up …` args in the FOREGROUND so systemd supervises one connector;\n * `systemctl stop` → SIGTERM → `up` releases its tunnel and exits 0 (not restarted).\n * Absolute node + script and an explicit PATH are used because systemd starts with\n * a minimal environment.\n */\nexport function buildUnit(d: ServiceDescriptor): string {\n const nodeBin = dirname(d.nodePath);\n return [\n \"[Unit]\",\n `Description=cloudtunnel ${d.fqdn} (Cloudflare Tunnel)`,\n \"After=network-online.target\",\n \"Wants=network-online.target\",\n \"\",\n \"[Service]\",\n \"Type=simple\",\n `User=${d.user}`,\n `Environment=HOME=${d.home}`,\n `Environment=PATH=${nodeBin}:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin`,\n `ExecStart=${d.nodePath} ${d.scriptPath} ${d.argv.join(\" \")}`,\n \"Restart=on-failure\",\n \"RestartSec=5\",\n \"\",\n \"[Install]\",\n \"WantedBy=multi-user.target\",\n \"\",\n ].join(\"\\n\");\n}\n\n/** Run a privileged command, prefixing `sudo` unless already root. */\nfunction privileged(args: string[]): void {\n const isRoot = typeof process.getuid === \"function\" && process.getuid() === 0;\n const argv = isRoot ? args : [\"sudo\", ...args];\n execFileSync(argv[0]!, argv.slice(1), { stdio: \"inherit\" });\n}\n\n/** Read-only systemctl query; returns trimmed stdout (\"\" on any error). */\nfunction query(args: string[]): string {\n try {\n return execFileSync(\"systemctl\", args, { stdio: [\"ignore\", \"pipe\", \"ignore\"], encoding: \"utf8\" }).trim();\n } catch (err) {\n const out = (err as { stdout?: Buffer | string }).stdout;\n return out ? out.toString().trim() : \"\";\n }\n}\n\nexport function assertSupported(): void {\n try {\n execFileSync(\"systemctl\", [\"--version\"], { stdio: \"ignore\" });\n } catch {\n throw new CliError(\"systemd (systemctl) was not found on this host.\");\n }\n}\n\n/** Install + enable a boot unit (runs now + on boot). Needs sudo. */\nexport function install(d: ServiceDescriptor): void {\n assertSupported();\n const tmp = join(tmpdir(), label(d.fqdn));\n writeFileSync(tmp, buildUnit(d), { mode: 0o644 });\n privileged([\"install\", \"-m\", \"0644\", tmp, unitPath(d.fqdn)]);\n privileged([\"systemctl\", \"daemon-reload\"]);\n privileged([\"systemctl\", \"enable\", \"--now\", label(d.fqdn)]);\n}\n\n/** Stop, disable, and delete the unit. Needs sudo. Best-effort. */\nexport function uninstall(fqdn: string): void {\n try {\n privileged([\"systemctl\", \"disable\", \"--now\", label(fqdn)]);\n } catch {\n /* not enabled / already gone */\n }\n privileged([\"rm\", \"-f\", unitPath(fqdn)]);\n privileged([\"systemctl\", \"daemon-reload\"]);\n}\n\nexport function state(fqdn: string): ServiceState {\n const name = label(fqdn);\n if (query([\"is-active\", name]) === \"active\") return \"active\";\n const enabled = query([\"is-enabled\", name]);\n if (enabled === \"enabled\" || enabled === \"enabled-runtime\") return \"enabled\";\n if (enabled === \"disabled\" || enabled === \"static\") return \"disabled\";\n return \"none\";\n}\n\n/** Whether a legacy profile-named unit is installed (one-time migration only). */\nexport function legacyUnitExists(profile: string): boolean {\n return existsSync(`/etc/systemd/system/cloudtunnel-${profile}.service`);\n}\n\n/** Remove a legacy profile-named unit (migration only). Needs sudo. */\nexport function removeLegacyUnit(profile: string): void {\n const name = `cloudtunnel-${profile}.service`;\n try {\n privileged([\"systemctl\", \"disable\", \"--now\", name]);\n } catch {\n /* not enabled / already gone */\n }\n privileged([\"rm\", \"-f\", `/etc/systemd/system/${name}`]);\n privileged([\"systemctl\", \"daemon-reload\"]);\n}\n","import { execFileSync } from \"node:child_process\";\nimport { existsSync, mkdirSync, rmSync, writeFileSync } from \"node:fs\";\nimport { dirname, join } from \"node:path\";\nimport os from \"node:os\";\nimport { ensureDirs } from \"../config/paths.js\";\nimport { serviceSlug, type ServiceDescriptor, type ServiceState } from \"./service-exec.js\";\n\nexport const label = (fqdn: string): string => `com.cloudtunnel.${serviceSlug(fqdn)}`;\nconst agentsDir = (): string => join(os.homedir(), \"Library\", \"LaunchAgents\");\nconst plistPath = (fqdn: string): string => join(agentsDir(), `${label(fqdn)}.plist`);\n\nconst xml = (s: string): string =>\n s.replace(/&/g, \"&amp;\").replace(/</g, \"&lt;\").replace(/>/g, \"&gt;\");\n\n/**\n * Build the launchd LaunchAgent plist (pure — unit-tested). A user agent (no sudo)\n * that runs at login (`RunAtLoad`) and is restarted on exit (`KeepAlive`), i.e. the\n * macOS equivalent of enable-now + restart-on-failure. ProgramArguments re-run the\n * same `cloudtunnel up …` the connector needs.\n */\nexport function buildPlist(d: ServiceDescriptor): string {\n const args = [d.nodePath, d.scriptPath, ...d.argv].map((a) => ` <string>${xml(a)}</string>`).join(\"\\n\");\n const nodeBin = dirname(d.nodePath);\n const path = `${nodeBin}:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin`;\n return [\n '<?xml version=\"1.0\" encoding=\"UTF-8\"?>',\n '<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">',\n '<plist version=\"1.0\">',\n \"<dict>\",\n ` <key>Label</key><string>${xml(label(d.fqdn))}</string>`,\n \" <key>ProgramArguments</key>\",\n \" <array>\",\n args,\n \" </array>\",\n \" <key>RunAtLoad</key><true/>\",\n \" <key>KeepAlive</key><true/>\",\n \" <key>EnvironmentVariables</key>\",\n \" <dict>\",\n ` <key>PATH</key><string>${xml(path)}</string>`,\n ` <key>HOME</key><string>${xml(d.home)}</string>`,\n \" </dict>\",\n ` <key>StandardOutPath</key><string>${xml(d.logFile)}</string>`,\n ` <key>StandardErrorPath</key><string>${xml(d.logFile)}</string>`,\n \"</dict>\",\n \"</plist>\",\n \"\",\n ].join(\"\\n\");\n}\n\n/** Run a launchctl command, ignoring failures (returns \"\" on error). */\nfunction launchctl(args: string[]): string {\n try {\n return execFileSync(\"launchctl\", args, { stdio: [\"ignore\", \"pipe\", \"ignore\"], encoding: \"utf8\" });\n } catch (err) {\n const out = (err as { stdout?: Buffer | string }).stdout;\n return out ? out.toString() : \"\";\n }\n}\n\nexport function assertSupported(): void {\n /* launchctl ships with macOS; the darwin platform check is enough. */\n}\n\nexport function install(d: ServiceDescriptor): void {\n ensureDirs();\n mkdirSync(agentsDir(), { recursive: true });\n const plist = plistPath(d.fqdn);\n writeFileSync(plist, buildPlist(d), { mode: 0o644 });\n launchctl([\"unload\", \"-w\", plist]); // best-effort: reload cleanly if already loaded\n // Surface a load failure (e.g. run over SSH / no GUI session) instead of\n // reporting a false success — the plist is written but nothing started.\n execFileSync(\"launchctl\", [\"load\", \"-w\", plist], { stdio: \"inherit\" });\n}\n\nexport function uninstall(fqdn: string): void {\n const plist = plistPath(fqdn);\n launchctl([\"unload\", \"-w\", plist]);\n rmSync(plist, { force: true });\n}\n\nexport function state(fqdn: string): ServiceState {\n const info = launchctl([\"list\", label(fqdn)]);\n if (/\"PID\"\\s*=/.test(info)) return \"active\"; // loaded and has a running pid\n return existsSync(plistPath(fqdn)) ? \"enabled\" : \"none\";\n}\n","import { execFileSync } from \"node:child_process\";\nimport { writeFileSync } from \"node:fs\";\nimport { tmpdir } from \"node:os\";\nimport { join } from \"node:path\";\nimport { serviceSlug, type ServiceDescriptor, type ServiceState } from \"./service-exec.js\";\n\n/** Task Scheduler path: a task named by the fqdn slug under a `cloudtunnel` folder. */\nexport const label = (fqdn: string): string => `cloudtunnel\\\\${serviceSlug(fqdn)}`;\n\nconst xml = (s: string): string =>\n s.replace(/&/g, \"&amp;\").replace(/</g, \"&lt;\").replace(/>/g, \"&gt;\").replace(/\"/g, \"&quot;\");\n\n/**\n * Build a Task Scheduler definition (pure — unit-tested). A LeastPrivilege logon\n * task (no admin) that starts at logon, restarts on failure, and runs the same\n * `cloudtunnel up …` the connector needs. Written as UTF-16 (schtasks /XML).\n */\nexport function buildTaskXml(d: ServiceDescriptor): string {\n const args = `\"${d.scriptPath}\" ${d.argv.join(\" \")}`;\n return [\n '<?xml version=\"1.0\" encoding=\"UTF-16\"?>',\n '<Task version=\"1.2\" xmlns=\"http://schemas.microsoft.com/windows/2004/02/mit/task\">',\n ` <RegistrationInfo><Description>cloudtunnel ${xml(d.fqdn)} (Cloudflare Tunnel)</Description></RegistrationInfo>`,\n ` <Triggers><LogonTrigger><Enabled>true</Enabled><UserId>${xml(d.user)}</UserId></LogonTrigger></Triggers>`,\n ` <Principals><Principal id=\"Author\"><UserId>${xml(d.user)}</UserId><LogonType>InteractiveToken</LogonType><RunLevel>LeastPrivilege</RunLevel></Principal></Principals>`,\n \" <Settings>\",\n \" <MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>\",\n \" <DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries>\",\n \" <StopIfGoingOnBatteries>false</StopIfGoingOnBatteries>\",\n \" <StartWhenAvailable>true</StartWhenAvailable>\",\n \" <ExecutionTimeLimit>PT0S</ExecutionTimeLimit>\",\n \" <RestartOnFailure><Interval>PT1M</Interval><Count>3</Count></RestartOnFailure>\",\n \" <Enabled>true</Enabled>\",\n \" </Settings>\",\n ' <Actions Context=\"Author\">',\n ` <Exec><Command>${xml(d.nodePath)}</Command><Arguments>${xml(args)}</Arguments></Exec>`,\n \" </Actions>\",\n \"</Task>\",\n \"\",\n ].join(\"\\r\\n\");\n}\n\n/** Run schtasks, ignoring failures (returns \"\" on error). */\nfunction schtasks(args: string[]): string {\n try {\n return execFileSync(\"schtasks\", args, { stdio: [\"ignore\", \"pipe\", \"ignore\"], encoding: \"utf8\" });\n } catch (err) {\n const out = (err as { stdout?: Buffer | string }).stdout;\n return out ? out.toString() : \"\";\n }\n}\n\nexport function assertSupported(): void {\n /* schtasks ships with Windows; the win32 platform check is enough. */\n}\n\nexport function install(d: ServiceDescriptor): void {\n const file = join(tmpdir(), `${d.slug}.task.xml`);\n // schtasks /XML wants a UTF-16 file with a BOM.\n writeFileSync(file, \"\\uFEFF\" + buildTaskXml(d), { encoding: \"utf16le\" });\n execFileSync(\"schtasks\", [\"/Create\", \"/TN\", label(d.fqdn), \"/XML\", file, \"/F\"], { stdio: \"inherit\" });\n schtasks([\"/Run\", \"/TN\", label(d.fqdn)]); // start now\n}\n\nexport function uninstall(fqdn: string): void {\n schtasks([\"/Delete\", \"/TN\", label(fqdn), \"/F\"]);\n}\n\nexport function state(fqdn: string): ServiceState {\n const out = schtasks([\"/Query\", \"/TN\", label(fqdn), \"/FO\", \"LIST\"]);\n if (!out) return \"none\";\n if (/\\bRunning\\b/.test(out)) return \"active\";\n if (/\\bDisabled\\b/.test(out)) return \"disabled\";\n if (/\\bReady\\b/.test(out)) return \"enabled\";\n return \"enabled\"; // task exists but status unrecognized (e.g. localized)\n}\n","import { CliError } from \"../ui/errors.js\";\nimport { describeService, type ServiceDescriptor, type ServiceSpecParams, type ServiceState } from \"./service-exec.js\";\nimport * as systemd from \"./service-systemd.js\";\nimport * as launchd from \"./service-launchd.js\";\nimport * as windows from \"./service-windows.js\";\n\nexport type { ServiceState, ServiceSpecParams } from \"./service-exec.js\";\n\n/** Per-OS boot-service backend. */\ninterface Backend {\n label(fqdn: string): string;\n assertSupported(): void;\n install(d: ServiceDescriptor): void;\n uninstall(fqdn: string): void;\n state(fqdn: string): ServiceState;\n}\n\n/** The backend for the current OS, or null where boot services aren't supported. */\nfunction pick(): Backend | null {\n switch (process.platform) {\n case \"linux\": return systemd;\n case \"darwin\": return launchd;\n case \"win32\": return windows;\n default: return null;\n }\n}\n\nfunction required(): Backend {\n const b = pick();\n if (!b) {\n throw new CliError(`Boot services aren't supported on ${process.platform}.`, {\n hint: \"run `cloudtunnel up <spec> --detach` and use your OS's own autostart\",\n });\n }\n return b;\n}\n\n/** Throw if `--service` can't work here (unsupported OS, or systemd missing). */\nexport function assertServiceSupported(): void {\n required().assertSupported();\n}\n\n/** Backend-specific display name/id for a subdomain's service. */\nexport function serviceName(fqdn: string): string {\n return pick()?.label(fqdn) ?? `cloudtunnel-${fqdn}`;\n}\n\n/** Install + enable a boot service for one subdomain (runs now + at login/boot). */\nexport function installServiceForSpec(params: ServiceSpecParams): void {\n const b = required();\n b.assertSupported();\n b.install(describeService(params));\n}\n\n/** Remove a subdomain's boot service (best-effort; no-op on unsupported OS). */\nexport function uninstallService(fqdn: string): void {\n pick()?.uninstall(fqdn);\n}\n\n/** Current state of a subdomain's service (\"none\" on an unsupported OS). */\nexport function serviceState(fqdn: string): ServiceState {\n return pick()?.state(fqdn) ?? \"none\";\n}\n\n// --- Legacy (Linux-only) migration from the old profile-based units ---\nexport function legacyUnitExists(profile: string): boolean {\n return process.platform === \"linux\" ? systemd.legacyUnitExists(profile) : false;\n}\nexport function removeLegacyUnit(profile: string): void {\n if (process.platform === \"linux\") systemd.removeLegacyUnit(profile);\n}\n","import type { Command } from \"commander\";\nimport * as clack from \"@clack/prompts\";\nimport { CliError } from \"../ui/errors.js\";\nimport { redactToken, say, selectOne } from \"../ui/output.js\";\nimport { configFile } from \"../config/paths.js\";\nimport { loadConfig, saveConfig } from \"../config/store.js\";\nimport { REQUIRED_SCOPES, openBrowser, tokenCreateUrl } from \"../config/token-url.js\";\nimport { listAccounts, listZones } from \"../config/resolve-identity.js\";\n\ninterface LoginOptions {\n tokenStdin?: boolean;\n token?: string; // deprecated: leaks into shell history\n account?: string;\n zone?: string;\n status?: boolean;\n}\n\n/** Read the whole stdin pipe (for `--token-stdin`). */\nasync function readStdin(): Promise<string> {\n const chunks: Buffer[] = [];\n for await (const chunk of process.stdin) chunks.push(chunk as Buffer);\n return Buffer.concat(chunks).toString(\"utf8\").trim();\n}\n\n/** Acquire the API token: env (silent) → stdin → deprecated flag → masked prompt.\n * Env tokens are NOT persisted (the env stays the source of truth). */\nasync function acquireToken(opts: LoginOptions): Promise<{ token: string; fromEnv: boolean }> {\n const envToken = process.env.CLOUDFLARE_API_TOKEN;\n if (envToken) {\n say.dim(\"Using token from CLOUDFLARE_API_TOKEN.\");\n return { token: envToken, fromEnv: true };\n }\n if (opts.tokenStdin) return { token: await readStdin(), fromEnv: false };\n if (opts.token) {\n say.warn(\"--token puts the token in your shell history — prefer --token-stdin or the prompt. Rotate it if this is a shared host.\");\n return { token: opts.token, fromEnv: false };\n }\n if (!process.stdin.isTTY) {\n throw new CliError(\"No token provided and no interactive terminal.\", {\n hint: \"pipe it: `printf %s $TOKEN | cloudtunnel login --token-stdin`\",\n });\n }\n clack.note(REQUIRED_SCOPES.map((s) => `• ${s}`).join(\"\\n\"), \"Create a token with these scopes\");\n openBrowser(tokenCreateUrl());\n say.dim(`(opened ${tokenCreateUrl()})`);\n const token = await clack.password({ message: \"Paste your Cloudflare API token\", mask: \"•\" });\n if (clack.isCancel(token) || !token) {\n clack.cancel(\"Cancelled.\");\n throw new CliError(\"Cancelled.\", { exitCode: 130 });\n }\n return { token, fromEnv: false };\n}\n\nasync function runLoginFlow(opts: LoginOptions = {}): Promise<void> {\n if (process.stdout.isTTY) clack.intro(\"cloudtunnel · connect to Cloudflare\");\n const { token, fromEnv } = await acquireToken(opts);\n\n const spin = clack.spinner();\n spin.start(\"Verifying token…\");\n const [accounts, zones] = await Promise.all([listAccounts(token), listZones(token)]).catch((err: unknown) => {\n spin.stop(\"Token check failed\");\n throw err;\n });\n spin.stop(\"Token verified\");\n\n if (accounts.length === 0) throw new CliError(\"Token can't see any Cloudflare account.\");\n let account = opts.account ? accounts.find((a) => a.id === opts.account) : undefined;\n if (opts.account && !account) throw new CliError(`Account ${opts.account} not visible to this token.`);\n if (!account) {\n account = accounts.length === 1 || !process.stdin.isTTY\n ? accounts[0]!\n : await selectOne(\"Select an account\", accounts, (a) => `${a.name} (${a.id})`);\n }\n\n let defaultZone = opts.zone;\n if (!defaultZone) {\n if (zones.length === 1) defaultZone = zones[0]!.name;\n else if (zones.length > 1 && process.stdin.isTTY) {\n defaultZone = (await selectOne(\"Select a default domain\", zones, (z) => z.name)).name;\n }\n }\n\n saveConfig({ apiToken: fromEnv ? undefined : token, accountId: account.id, defaultZone });\n const summary = `Logged in as ${account.name}${defaultZone ? ` · default domain ${defaultZone}` : \"\"}`;\n if (process.stdout.isTTY) clack.outro(summary);\n else say.ok(summary);\n if (!defaultZone) say.dim(\"No default domain set — pass -d <domain> on `up`, or re-run `login --zone <domain>`.\");\n}\n\nfunction showStatus(): void {\n const config = loadConfig();\n const token = process.env.CLOUDFLARE_API_TOKEN ?? config.apiToken;\n if (!token) {\n say.warn(\"Not logged in. Run `cloudtunnel login`.\");\n return;\n }\n const source = process.env.CLOUDFLARE_API_TOKEN ? \"env\" : \"config\";\n say.info(`Token: ${redactToken(token)} (${source})`);\n say.info(`Account: ${config.accountId ?? \"(from env / unresolved)\"}`);\n say.info(`Domain: ${config.defaultZone ?? \"(none)\"}`);\n say.dim(`Config: ${configFile}`);\n}\n\nexport function registerLogin(program: Command): void {\n program\n .command(\"login\")\n .description(\"Authenticate with Cloudflare (paste a token once; account + domain auto-resolved)\")\n .option(\"--token-stdin\", \"read the API token from stdin (scriptable, avoids shell history)\")\n .option(\"--token <token>\", \"[discouraged] token as an argument (leaks into shell history)\")\n .option(\"--account <id>\", \"Cloudflare account id (auto-resolved when you have one account)\")\n .option(\"--zone <domain>\", \"default domain for new tunnels (auto-resolved when you have one)\")\n .option(\"--status\", \"show current identity (redacted) and exit\")\n .action(async (opts: LoginOptions) => {\n if (opts.status) return showStatus();\n await runLoginFlow(opts);\n });\n}\n\nexport { runLoginFlow };\n","import { spawn } from \"node:child_process\";\n\n/** The exact scopes cloudtunnel needs. Printed so the user selects them when\n * minting a token — least-privilege, account-wide only where required. */\nexport const REQUIRED_SCOPES = [\n \"Account · Cloudflare Tunnel · Edit\",\n \"Account · Account Settings · Read\",\n \"Zone · DNS · Edit\",\n \"Zone · Zone · Read\",\n] as const;\n\n/** Cloudflare \"Create Custom Token\" page. `name` is pre-filled best-effort;\n * the user still selects the scopes above (dashboard pre-fill params are not a\n * versioned API, so we rely on the printed scope list, not URL params). */\nexport function tokenCreateUrl(): string {\n return \"https://dash.cloudflare.com/profile/api-tokens?name=cloudtunnel\";\n}\n\n/** Best-effort open a URL in the default browser. Never throws — if no opener\n * exists (headless/CI), the caller still prints the URL. */\nexport function openBrowser(url: string): void {\n const cmd =\n process.platform === \"darwin\" ? \"open\"\n : process.platform === \"win32\" ? \"cmd\"\n : \"xdg-open\";\n const args = process.platform === \"win32\" ? [\"/c\", \"start\", \"\", url] : [url];\n try {\n const child = spawn(cmd, args, { stdio: \"ignore\", detached: true });\n child.on(\"error\", () => {}); // swallow: opener may not exist\n child.unref();\n } catch {\n // ignore — printing the URL is the fallback\n }\n}\n","import { CliError } from \"../ui/errors.js\";\nimport { REQUIRED_SCOPES, tokenCreateUrl } from \"./token-url.js\";\n\nconst API_BASE = \"https://api.cloudflare.com/client/v4\";\n\nexport interface CfAccount { id: string; name: string }\nexport interface CfZone { id: string; name: string; account?: { id: string } }\n\n/**\n * Raw Cloudflare GET used only for login-time validation (the typed SDK client\n * is wired in Phase 3). Errors are sanitized: the token never appears in any\n * thrown message. A 403 is mapped to a missing-scope hint.\n */\nasync function cfGet<T>(path: string, token: string): Promise<T[]> {\n let res: Response;\n try {\n res = await fetch(`${API_BASE}${path}`, {\n headers: { Authorization: `Bearer ${token}`, \"Content-Type\": \"application/json\" },\n });\n } catch {\n throw new CliError(\"Could not reach the Cloudflare API (network error).\");\n }\n if (res.status === 401) {\n throw new CliError(\"Cloudflare rejected the token (invalid or expired).\", {\n hint: `mint a new token: ${tokenCreateUrl()}`,\n });\n }\n if (res.status === 403) {\n throw new CliError(`Token is missing a required scope for ${path}.`, {\n hint: `token needs: ${REQUIRED_SCOPES.join(\", \")}`,\n });\n }\n const body = (await res.json().catch(() => ({}))) as { success?: boolean; result?: T[] };\n if (!res.ok || !body.success) {\n throw new CliError(`Cloudflare API error (${res.status}) on ${path}.`);\n }\n return body.result ?? [];\n}\n\nexport function listAccounts(token: string): Promise<CfAccount[]> {\n return cfGet<CfAccount>(\"/accounts?per_page=50\", token);\n}\n\nexport function listZones(token: string): Promise<CfZone[]> {\n return cfGet<CfZone>(\"/zones?per_page=50\", token);\n}\n","import type { Command } from \"commander\";\nimport * as clack from \"@clack/prompts\";\nimport { CliError } from \"../ui/errors.js\";\nimport { say, selectOne } from \"../ui/output.js\";\nimport { ensureAuth } from \"../config/ensure-auth.js\";\nimport { resolveCf, type Cf } from \"../cloudflare/client.js\";\nimport { listZones } from \"../cloudflare/zones.js\";\nimport type { Credentials } from \"../config/store.js\";\nimport { ensureCloudflared } from \"../connector/binary.js\";\nimport type { CreateOptions } from \"../core/orchestrator-create.js\";\nimport { startTunnels } from \"../core/up-runner.js\";\nimport { parseTunnelSpec, type TunnelSpec } from \"../core/tunnel-spec.js\";\nimport { parseTransportProtocol, type TransportProtocol } from \"../core/transport-protocol.js\";\nimport { randomSlug } from \"../core/slug.js\";\nimport { assertServiceSupported, installServiceForSpec, serviceName } from \"../core/service.js\";\n\ninterface UpOptions {\n domain?: string;\n proto: \"http\" | \"https\";\n protocol?: string; // edge transport: auto | http2 | quic\n detach?: boolean;\n service?: boolean; // register each subdomain as a systemd boot service\n force?: boolean;\n yes?: boolean;\n}\n\nfunction promptOrExit<T>(value: T | symbol): T {\n if (clack.isCancel(value)) {\n clack.cancel(\"Cancelled.\");\n process.exit(130);\n }\n return value as T;\n}\n\n/** Interactive port prompt (0-arg wizard). */\nasync function promptPort(): Promise<number> {\n const input = promptOrExit(\n await clack.text({\n message: \"Port to expose\",\n placeholder: \"e.g. 3000\",\n validate: (v) => {\n const n = Number(v);\n if (!Number.isInteger(n) || n < 1 || n > 65535) return \"Enter a port 1–65535\";\n return undefined;\n },\n }),\n );\n return Number(input);\n}\n\n/** The domain for the whole batch: `-d` → single zone → picker (TTY) → saved\n * default (non-TTY) → error. */\nasync function resolveDomain(cf: Cf, opts: UpOptions, creds: Credentials): Promise<string> {\n if (opts.domain) return opts.domain;\n const zones = await listZones(cf.token);\n if (zones.length === 0) throw new CliError(\"No domains found in this Cloudflare account.\");\n if (zones.length === 1) return zones[0]!.name;\n if (process.stdin.isTTY) return (await selectOne(\"Choose a domain\", zones, (z) => z.name)).name;\n if (creds.defaultZone) return creds.defaultZone;\n throw new CliError(\"Multiple domains in this account — pick one.\", { hint: \"pass -d <domain>\" });\n}\n\n/** The subdomain for a spec: explicit in the spec → used as-is; otherwise prompt\n * (TTY, blank = random) or random (non-TTY / `-y`). Returns undefined for random. */\nasync function resolveSpecSubdomain(spec: TunnelSpec, opts: UpOptions): Promise<string | undefined> {\n if (spec.subdomain !== undefined) return spec.subdomain;\n if (opts.yes || !process.stdin.isTTY) return undefined; // random\n const input = promptOrExit(\n await clack.text({ message: `Subdomain for :${spec.port}`, placeholder: \"blank = random · @ = root domain\" }),\n );\n return (input as string).trim() || undefined; // blank → random\n}\n\nasync function runUp(specArgs: string[], opts: UpOptions): Promise<void> {\n const protocol: TransportProtocol | undefined = opts.protocol ? parseTransportProtocol(opts.protocol) : undefined;\n // Parse specs up front (fail fast on a typo before touching the network). 0 args\n // → wizard, which needs a TTY.\n const parsed: TunnelSpec[] | null = specArgs.length ? specArgs.map(parseTunnelSpec) : null;\n if (parsed === null && !process.stdin.isTTY) {\n throw new CliError(\"No tunnel spec given.\", { hint: \"e.g. cloudtunnel api:8080\" });\n }\n\n const creds = await ensureAuth();\n const cf = resolveCf();\n const bin = await ensureCloudflared();\n\n if (process.stdout.isTTY) clack.intro(\"cloudtunnel\");\n\n const specs: TunnelSpec[] = parsed ?? [{ port: await promptPort() }];\n const domain = await resolveDomain(cf, opts, creds);\n\n // Build create-opts per spec. `--service` needs a concrete subdomain baked in\n // (never random-per-boot), so materialise a random one now when unnamed.\n const items: CreateOptions[] = [];\n for (const spec of specs) {\n let name = await resolveSpecSubdomain(spec, opts);\n if (opts.service && name === undefined) name = randomSlug();\n items.push({\n port: spec.port, proto: opts.proto, name, zone: domain, host: spec.host,\n defaultZone: creds.defaultZone, force: opts.force, yes: opts.yes,\n });\n }\n\n if (opts.service) {\n registerServices(items, domain, opts.proto, protocol);\n return;\n }\n\n await startTunnels(cf, bin, items, { detach: opts.detach, protocol });\n}\n\n/** Install + enable a systemd boot unit per subdomain (systemd runs each now and\n * on boot), then exit. `--detach` is a no-op here — systemd already backgrounds. */\nfunction registerServices(\n items: CreateOptions[], domain: string,\n proto: \"http\" | \"https\", protocol?: TransportProtocol,\n): void {\n assertServiceSupported();\n if (!protocol) {\n say.warn(\"No edge protocol set — cloudflared will pick QUIC, which some networks drop.\");\n say.dim(\" → add --protocol http2 for UDP-hostile networks\");\n }\n const done: string[] = [];\n for (const item of items) {\n const subdomain = item.name!; // concrete (baked above)\n const fqdn = subdomain === \"@\" ? domain : `${subdomain}.${domain}`;\n installServiceForSpec({ subdomain, port: item.port, host: item.host, zone: domain, proto, protocol });\n done.push(`${serviceName(fqdn)} → https://${fqdn}`);\n }\n say.ok(`Registered ${done.length} boot service(s):`);\n for (const line of done) say.dim(` ${line}`);\n say.dim(\" → check them: cloudtunnel ls · remove: cloudtunnel delete <#>\");\n}\n\nexport function registerUp(program: Command): void {\n program\n .command(\"up\", { isDefault: true })\n .argument(\"[specs...]\", \"tunnels to start: [subdomain:]port[@host] (e.g. api:8080 web:8081@localhost)\")\n .description(\"Start one or more tunnels (also: `cloudtunnel 8080`)\")\n .option(\"-d, --domain <domain>\", \"domain for the subdomains (prompted from a list if unset)\")\n .option(\"--proto <proto>\", \"local service protocol: http | https\", \"http\")\n .option(\"--protocol <proto>\", \"cloudflared edge transport: auto | http2 | quic (http2 for UDP-hostile networks)\")\n .option(\"--detach\", \"run the connectors in the background\")\n .option(\"--service\", \"register each subdomain as a boot service (Linux systemd · macOS launchd · Windows Task Scheduler)\")\n .option(\"-f, --force\", \"replace a non-tunnel DNS record occupying the hostname\")\n .option(\"-y, --yes\", \"don't prompt; don't ask before replacing an existing record\")\n .action((specs: string[], opts: UpOptions) => runUp(specs, opts));\n}\n","import { CliError } from \"../ui/errors.js\";\nimport { say } from \"../ui/output.js\";\nimport { getCredentials, type Credentials } from \"./store.js\";\nimport { runLoginFlow } from \"../commands/login.js\";\n\n/**\n * Single auth entry point for every command. Returns credentials if present;\n * on a fresh machine with a TTY it runs onboarding inline and continues, so\n * `cloudtunnel 3000` on a new box just works. Non-TTY (CI) → actionable error.\n */\nexport async function ensureAuth(): Promise<Credentials> {\n try {\n return getCredentials();\n } catch (err) {\n if (err instanceof CliError && process.stdin.isTTY) {\n say.info(\"Welcome to cloudtunnel — let's get you connected to Cloudflare first.\");\n await runLoginFlow();\n return getCredentials();\n }\n throw err;\n }\n}\n","import { execFileSync } from \"node:child_process\";\nimport { createHash } from \"node:crypto\";\nimport { chmodSync, existsSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { CliError } from \"../ui/errors.js\";\nimport { say } from \"../ui/output.js\";\nimport { binDir, ensureDirs } from \"../config/paths.js\";\n\n// Pinned release for reproducible, checksum-verified auto-install. Bump both the\n// version and the checksums together (values from the release's sha256 sums).\nconst PINNED_VERSION = \"2025.1.0\";\nconst RELEASE_BASE = `https://github.com/cloudflare/cloudflared/releases/download/${PINNED_VERSION}`;\n\ninterface Asset { file: string; archive: boolean; sha256: string }\n\n// Fill sha256 from the pinned release before shipping auto-install for a target.\n// Empty string ⇒ fail closed (never run an unverified binary).\nconst ASSETS: Record<string, Asset | undefined> = {\n \"linux-x64\": { file: \"cloudflared-linux-amd64\", archive: false, sha256: \"\" },\n \"linux-arm64\": { file: \"cloudflared-linux-arm64\", archive: false, sha256: \"\" },\n \"darwin-x64\": { file: \"cloudflared-darwin-amd64.tgz\", archive: true, sha256: \"\" },\n \"darwin-arm64\": { file: \"cloudflared-darwin-arm64.tgz\", archive: true, sha256: \"\" },\n \"win32-x64\": { file: \"cloudflared-windows-amd64.exe\", archive: false, sha256: \"\" },\n};\n\nfunction binaryWorks(bin: string): boolean {\n try {\n execFileSync(bin, [\"--version\"], { stdio: \"ignore\" });\n return true;\n } catch {\n return false;\n }\n}\n\nfunction cachedPath(): string {\n return join(binDir, process.platform === \"win32\" ? \"cloudflared.exe\" : \"cloudflared\");\n}\n\n/** True on Alpine/musl, where cloudflared has no prebuilt binary. */\nfunction isMusl(): boolean {\n try {\n return process.platform === \"linux\" && readFileSync(\"/usr/bin/ldd\", \"utf8\").includes(\"musl\");\n } catch {\n return false;\n }\n}\n\n/**\n * Return a runnable `cloudflared` with zero user action: PATH → cached download\n * → verified auto-download. Fails closed (never runs an unverified binary).\n */\nexport async function ensureCloudflared(): Promise<string> {\n if (binaryWorks(\"cloudflared\")) return \"cloudflared\";\n const cached = cachedPath();\n if (existsSync(cached) && binaryWorks(cached)) return cached;\n return downloadCloudflared(cached);\n}\n\nasync function downloadCloudflared(dest: string): Promise<string> {\n if (isMusl()) {\n throw new CliError(\"cloudflared has no musl (Alpine) build.\", {\n hint: \"install it manually: https://github.com/cloudflare/cloudflared/releases\",\n });\n }\n const key = `${process.platform}-${process.arch}`;\n const asset = ASSETS[key];\n if (!asset || !asset.sha256) {\n throw new CliError(`Auto-install unavailable for ${key} (no pinned checksum).`, {\n hint: \"install cloudflared manually: https://github.com/cloudflare/cloudflared/releases\",\n });\n }\n\n say.step(`cloudflared not found — downloading v${PINNED_VERSION} (checksum-verified)…`);\n const res = await fetch(`${RELEASE_BASE}/${asset.file}`);\n if (!res.ok) throw new CliError(`Download failed (HTTP ${res.status}).`);\n const bytes = Buffer.from(await res.arrayBuffer());\n\n const digest = createHash(\"sha256\").update(bytes).digest(\"hex\");\n if (digest !== asset.sha256) {\n throw new CliError(\"cloudflared checksum mismatch — refusing to run the download.\", {\n hint: \"network tampering or an outdated pin; install manually instead\",\n });\n }\n\n ensureDirs();\n const binary = asset.archive ? extractTgz(bytes) : bytes;\n writeFileSync(dest, binary, { mode: 0o755 });\n chmodSync(dest, 0o755);\n if (!binaryWorks(dest)) throw new CliError(\"Downloaded cloudflared is not runnable.\");\n return dest;\n}\n\n/** Extract the single `cloudflared` entry from a .tgz (darwin assets). */\nfunction extractTgz(_bytes: Buffer): Buffer {\n // gunzip + untar of a single-file archive; implemented when a darwin\n // checksum is pinned (dormant until then — see ASSETS).\n throw new CliError(\"darwin .tgz extraction not yet wired.\", {\n hint: \"install cloudflared via `brew install cloudflared`\",\n });\n}\n","import { join } from \"node:path\";\nimport * as clack from \"@clack/prompts\";\nimport { reportError } from \"../ui/errors.js\";\nimport { dim, formatRoute, say } from \"../ui/output.js\";\nimport type { Cf } from \"../cloudflare/client.js\";\nimport { logDir } from \"../config/paths.js\";\nimport { startConnector } from \"../connector/process.js\";\nimport { waitHealthy, type HealthResult } from \"../connector/health.js\";\nimport { currentBootId, patchEntry } from \"../connector/registry.js\";\nimport { createTunnelSubdomain, type CreateOptions } from \"./orchestrator-create.js\";\nimport { removeTunnelSubdomain } from \"./orchestrator-manage.js\";\nimport { serviceUrl } from \"./ingress.js\";\nimport type { TransportProtocol } from \"./transport-protocol.js\";\n\ninterface StartedTunnel {\n fqdn: string;\n subdomain: string;\n tunnelId: string;\n target: string;\n pid: number;\n}\n\n/** Log-file label for a subdomain (\"@\" → root). */\nfunction logFileFor(subdomain: string): string {\n return join(logDir, `${subdomain === \"@\" ? \"root\" : subdomain}.log`);\n}\n\n/**\n * Create + connect a batch of tunnels (1..N). Foreground: waits for health, then\n * any exit (Ctrl-C / crash) releases every tunnel started here (2-state model).\n * `--detach`: starts them all in the background and returns.\n */\nexport async function startTunnels(\n cf: Cf,\n bin: string,\n items: CreateOptions[],\n opts: { detach?: boolean; protocol?: TransportProtocol } = {},\n): Promise<void> {\n const started: StartedTunnel[] = [];\n\n // Foreground is up-while-running: any exit (Ctrl-C, a signal, or a connector\n // crash) releases every tunnel started here (2-state model). Defined before the\n // create loop so `onExit` can reference it; registered as signal handlers before\n // the health wait so a Ctrl-C during that ≤30s window doesn't leak resources.\n let tornDown = false;\n const teardownAll = async (code: number): Promise<void> => {\n if (tornDown) return;\n tornDown = true;\n try {\n for (const s of started) {\n try {\n await removeTunnelSubdomain(cf, s.fqdn, { force: true, quiet: true });\n } catch {\n /* best-effort release */\n }\n }\n if (process.stdout.isTTY) clack.outro(`Stopped · released ${started.length} subdomain(s)`);\n } catch (err) {\n reportError(err);\n } finally {\n process.exit(code);\n }\n };\n\n const spin = clack.spinner();\n spin.start(items.length > 1 ? \"Creating tunnels…\" : \"Creating tunnel…\");\n for (const item of items) {\n spin.message(`Creating ${item.name ?? \"tunnel\"} (:${item.port})…`);\n const result = await createTunnelSubdomain(cf, item);\n const fqdn = result.host.hostname;\n const logFile = logFileFor(result.host.subdomain);\n const conn = startConnector({\n bin, token: result.token, detach: !!opts.detach, logFile, protocol: opts.protocol,\n onExit: opts.detach ? undefined : (code) => {\n if (!tornDown) {\n say.warn(`Connector for ${fqdn} exited.`);\n void teardownAll(code ?? 1);\n }\n },\n });\n await patchEntry(fqdn, { pid: conn.pid, bootId: currentBootId(), logFile });\n started.push({\n fqdn, subdomain: result.host.subdomain, tunnelId: result.tunnelId,\n target: serviceUrl(item.proto, item.host ?? \"localhost\", item.port), pid: conn.pid,\n });\n }\n\n // Detached: print URLs + pids and exit; the connectors keep running.\n if (opts.detach) {\n spin.stop(`${started.length} tunnel(s) started in the background`);\n const lines = started.map((s) => `${formatRoute(s.fqdn, s.target)} ${dim(`pid ${s.pid}`)}`);\n clack.note(lines.join(\"\\n\"), \"running in background\");\n if (process.stdout.isTTY) clack.outro(\"Stop with: cloudtunnel delete <#|--all>\");\n return;\n }\n\n for (const sig of [\"SIGINT\", \"SIGHUP\", \"SIGTERM\"] as const) {\n process.on(sig, () => void teardownAll(0));\n }\n\n spin.message(\"Connecting to the Cloudflare edge…\");\n const healths = await Promise.all(started.map((s) => waitHealthy(cf, s.tunnelId, { timeoutMs: 30_000 })));\n const live = healths.filter((h: HealthResult) => h === \"healthy\").length;\n spin.stop(`${started.length} tunnel(s) started`);\n\n const lines = started.map((s, i) => `${formatRoute(s.fqdn, s.target)}${healths[i] === \"healthy\" ? \"\" : dim(` (${healths[i]})`)}`);\n clack.note(lines.join(\"\\n\"), `${live}/${started.length} live`);\n say.dim(\"Ctrl-C stops and releases them.\");\n}\n","import { type ChildProcess, execFileSync, spawn } from \"node:child_process\";\nimport { openSync } from \"node:fs\";\nimport { CliError } from \"../ui/errors.js\";\nimport { isOurConnector, type RegistryEntry } from \"./registry.js\";\n\nexport interface StartOptions {\n bin: string;\n token: string;\n detach: boolean;\n logFile: string;\n /** cloudflared edge transport (quic | http2 | auto). Omitted ⇒ cloudflared's\n * default. Force `http2` on UDP-hostile networks that drop idle QUIC. */\n protocol?: string;\n /** Foreground only: fired when the connector exits for ANY reason (crash,\n * bad token, or a signal) so the caller can tear down / report. */\n onExit?: (code: number | null) => void;\n}\n\nexport interface StartedConnector {\n pid: number;\n child?: ChildProcess;\n}\n\nconst sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));\n\n/**\n * Spawn `cloudflared tunnel run`. The token is passed via the TUNNEL_TOKEN env\n * var — NEVER as an argv arg (argv is world-readable via `ps`/proc). Output goes\n * to a 0600 logfile (both foreground and detached) so the CLI can render its own\n * clean status instead of cloudflared's raw logs.\n */\nexport function startConnector(opts: StartOptions): StartedConnector {\n const args = [\"tunnel\", \"run\"];\n // Edge transport: pass as an explicit flag so it also lands in the connector\n // cmdline (visible/reproducible), not only via env.\n if (opts.protocol) args.push(\"--protocol\", opts.protocol);\n const env = { ...process.env, TUNNEL_TOKEN: opts.token };\n const fd = openSync(opts.logFile, \"a\", 0o600);\n const child = spawn(opts.bin, args, { env, detached: opts.detach, stdio: [\"ignore\", fd, fd] });\n if (!child.pid) throw new CliError(\"Failed to start the cloudflared connector.\");\n\n if (opts.detach) {\n child.unref();\n return { pid: child.pid };\n }\n child.on(\"exit\", (code) => opts.onExit?.(code));\n child.on(\"error\", () => opts.onExit?.(1));\n return { pid: child.pid, child };\n}\n\n/**\n * Stop a connector by registry entry. Verifies the pid is still OUR cloudflared\n * (alive, same boot, right cmdline) BEFORE signalling, so a reused pid held by\n * an unrelated process is never killed. Returns true if a stop was issued.\n */\nexport async function stopConnector(entry: RegistryEntry): Promise<boolean> {\n if (!entry.pid || !(await isOurConnector(entry))) return false;\n const pid = entry.pid;\n\n if (process.platform === \"win32\") {\n try {\n execFileSync(\"taskkill\", [\"/pid\", String(pid), \"/T\", \"/F\"], { stdio: \"ignore\" });\n } catch {\n return false;\n }\n return true;\n }\n\n try {\n process.kill(pid, \"SIGTERM\");\n } catch {\n return false;\n }\n await sleep(3000);\n if (await isOurConnector(entry)) {\n try {\n process.kill(pid, \"SIGKILL\");\n } catch {\n // already gone\n }\n }\n return true;\n}\n","import { existsSync, readFileSync, renameSync, writeFileSync } from \"node:fs\";\nimport { readFile } from \"node:fs/promises\";\nimport os from \"node:os\";\nimport lockfile from \"proper-lockfile\";\nimport { ensureDirs, registryFile } from \"../config/paths.js\";\n\nexport type EntryState = \"provisioning\" | \"running\" | \"stopped\" | \"orphaned\";\n\nexport interface RegistryEntry {\n subdomain: string;\n zone: string;\n zoneId: string;\n index?: number; // small stable handle shown as `#` in `ls` (target by number)\n tunnelId?: string;\n dnsRecordId?: string;\n port: number;\n proto: \"http\" | \"https\";\n host?: string; // forward target host (absent = localhost)\n pid?: number;\n bootId?: string;\n logFile?: string;\n createdAt: string;\n state: EntryState;\n}\n\n/** The real hostname for an entry. `@` is the apex, keyed in the registry by the\n * bare zone (NOT `@.zone`), so every entry→fqdn reconstruction must go through\n * this — otherwise apex tunnels become untargetable and leak. */\nexport function entryFqdn(e: Pick<RegistryEntry, \"subdomain\" | \"zone\">): string {\n return e.subdomain === \"@\" ? e.zone : `${e.subdomain}.${e.zone}`;\n}\n\ntype Registry = Record<string, RegistryEntry>;\n\n/** Stable per-boot id so a pid reused after a reboot is never mistaken for ours.\n * On systems without the Linux boot_id file (e.g. macOS), fall back to the boot\n * *time* bucketed to the minute — this is constant between invocations (unlike\n * `os.uptime()`, which increases every second and would break connector tracking). */\nexport function currentBootId(): string {\n try {\n return readFileSync(\"/proc/sys/kernel/random/boot_id\", \"utf8\").trim();\n } catch {\n const bootMinute = Math.floor((Date.now() - os.uptime() * 1000) / 60_000);\n return `boot-${bootMinute}-${os.hostname()}`;\n }\n}\n\nfunction readRegistry(): Registry {\n try {\n return JSON.parse(readFileSync(registryFile, \"utf8\")) as Registry;\n } catch {\n return {};\n }\n}\n\nfunction writeRegistry(reg: Registry): void {\n ensureDirs();\n const tmp = `${registryFile}.tmp`;\n writeFileSync(tmp, JSON.stringify(reg, null, 2), { mode: 0o600 });\n renameSync(tmp, registryFile); // atomic on the same filesystem\n}\n\n/** Lock-guarded read-modify-write (prevents lost updates across concurrent runs). */\nexport async function mutateRegistry<T>(fn: (reg: Registry) => T): Promise<T> {\n ensureDirs();\n if (!existsSync(registryFile)) writeFileSync(registryFile, \"{}\", { mode: 0o600 });\n const release = await lockfile.lock(registryFile, { retries: { retries: 10, minTimeout: 50 } });\n try {\n const reg = readRegistry();\n const result = fn(reg);\n writeRegistry(reg);\n return result;\n } finally {\n await release();\n }\n}\n\nexport function listEntries(): RegistryEntry[] {\n return Object.values(readRegistry());\n}\n\nexport function getEntry(fqdn: string): RegistryEntry | undefined {\n return readRegistry()[fqdn];\n}\n\nexport function upsertEntry(fqdn: string, patch: Partial<RegistryEntry> & Pick<RegistryEntry, \"subdomain\" | \"zone\" | \"zoneId\" | \"port\" | \"proto\">): Promise<void> {\n return mutateRegistry((reg) => {\n const prev = reg[fqdn];\n reg[fqdn] = {\n createdAt: prev?.createdAt ?? new Date().toISOString(),\n index: prev?.index ?? nextIndex(reg),\n state: \"provisioning\",\n ...prev,\n ...patch,\n };\n });\n}\n\n/** Smallest positive integer not currently used as an entry index (reused when\n * an entry is removed) — the friendly `#` handle shown in `ls`. */\nfunction nextIndex(reg: Registry): number {\n const used = new Set(\n Object.values(reg)\n .map((e) => e.index)\n .filter((n): n is number => typeof n === \"number\"),\n );\n let i = 1;\n while (used.has(i)) i++;\n return i;\n}\n\n/** Merge changed fields onto an existing entry under the lock (no stale\n * full-snapshot read outside the lock — avoids lost updates). No-op if absent. */\nexport function patchEntry(fqdn: string, patch: Partial<RegistryEntry>): Promise<void> {\n return mutateRegistry((reg) => {\n const prev = reg[fqdn];\n if (prev) reg[fqdn] = { ...prev, ...patch };\n });\n}\n\nexport function removeEntry(fqdn: string): Promise<void> {\n return mutateRegistry((reg) => {\n delete reg[fqdn];\n });\n}\n\nfunction pidAlive(pid: number): boolean {\n try {\n process.kill(pid, 0);\n return true;\n } catch {\n return false;\n }\n}\n\n/** Verify a pid is still OUR cloudflared: alive, same boot, and (Linux) its\n * cmdline is cloudflared — so we never signal a reused pid. */\nexport async function isOurConnector(entry: RegistryEntry): Promise<boolean> {\n if (!entry.pid || entry.bootId !== currentBootId()) return false;\n if (!pidAlive(entry.pid)) return false;\n if (process.platform === \"linux\") {\n try {\n const cmdline = await readFile(`/proc/${entry.pid}/cmdline`, \"utf8\");\n return cmdline.includes(\"cloudflared\");\n } catch {\n return false;\n }\n }\n return true; // non-Linux: bootId + liveness (best effort)\n}\n\n/** Mark entries whose connector is no longer alive as `stopped`. */\nexport async function reconcile(): Promise<RegistryEntry[]> {\n const entries = listEntries();\n for (const entry of entries) {\n if (entry.state === \"running\" && !(await isOurConnector(entry))) {\n const fqdn = entryFqdn(entry);\n await mutateRegistry((reg) => {\n const e = reg[fqdn];\n if (e) {\n e.state = \"stopped\";\n delete e.pid;\n }\n });\n }\n }\n return listEntries();\n}\n","import { cfPaginate, cfRequest, type Cf } from \"./client.js\";\nimport type { Connection, IngressRule, Tunnel } from \"./types.js\";\nimport { CliError } from \"../ui/errors.js\";\n\n/** Tunnels created by cloudtunnel carry this name prefix (ownership marker). */\nexport const MANAGED_TUNNEL_PREFIX = \"ct-\";\n\nexport function isManagedTunnel(tunnel: Tunnel): boolean {\n return tunnel.name.startsWith(MANAGED_TUNNEL_PREFIX);\n}\n\nexport async function createTunnel(cf: Cf, name: string): Promise<Tunnel> {\n const env = await cfRequest<Tunnel>(cf.token, \"POST\", `/accounts/${cf.accountId}/cfd_tunnel`, {\n name,\n config_src: \"cloudflare\",\n });\n return env.result;\n}\n\nexport function listTunnels(cf: Cf): Promise<Tunnel[]> {\n return cfPaginate<Tunnel>(cf.token, `/accounts/${cf.accountId}/cfd_tunnel?is_deleted=false`);\n}\n\nexport async function getTunnel(cf: Cf, id: string): Promise<Tunnel> {\n return (await cfRequest<Tunnel>(cf.token, \"GET\", `/accounts/${cf.accountId}/cfd_tunnel/${id}`)).result;\n}\n\nexport async function deleteTunnel(cf: Cf, id: string): Promise<void> {\n await cfRequest<unknown>(cf.token, \"DELETE\", `/accounts/${cf.accountId}/cfd_tunnel/${id}`);\n}\n\n/** Force-disconnect a tunnel's (possibly stale) connectors so it can be deleted. */\nexport async function cleanupConnections(cf: Cf, id: string): Promise<void> {\n await cfRequest<unknown>(cf.token, \"DELETE\", `/accounts/${cf.accountId}/cfd_tunnel/${id}/connections`);\n}\n\n/** Delete a tunnel; if Cloudflare refuses because it still has active\n * connections (a connector died but the edge hasn't reaped it yet), clean the\n * connections up and retry once. */\nexport async function deleteTunnelWithConnections(cf: Cf, id: string): Promise<void> {\n try {\n await deleteTunnel(cf, id);\n } catch (err) {\n if (err instanceof CliError && /active connections/i.test(err.message)) {\n await cleanupConnections(cf, id);\n await deleteTunnel(cf, id);\n } else {\n throw err;\n }\n }\n}\n\n/** The connector token (encodes tunnelId + secret) passed to `cloudflared`. */\nexport async function getTunnelToken(cf: Cf, id: string): Promise<string> {\n return (await cfRequest<string>(cf.token, \"GET\", `/accounts/${cf.accountId}/cfd_tunnel/${id}/token`)).result;\n}\n\n/** Full-replace ingress config (safe: one hostname + catch-all per tunnel). */\nexport async function putIngress(cf: Cf, id: string, ingress: IngressRule[]): Promise<void> {\n await cfRequest<unknown>(cf.token, \"PUT\", `/accounts/${cf.accountId}/cfd_tunnel/${id}/configurations`, {\n config: { ingress },\n });\n}\n\n/** Active connector instances (≥1 ⇒ tunnel is serving). */\nexport async function getConnections(cf: Cf, id: string): Promise<Connection[]> {\n const env = await cfRequest<Connection[]>(\n cf.token,\n \"GET\",\n `/accounts/${cf.accountId}/cfd_tunnel/${id}/connections`,\n );\n return env.result ?? [];\n}\n","import { getConnections } from \"../cloudflare/tunnels.js\";\nimport type { Cf } from \"../cloudflare/client.js\";\n\nexport type HealthResult = \"healthy\" | \"provisioning\" | \"dead\";\n\nconst sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));\n\n/**\n * Poll the tunnel's connections until it's serving. `signal` is fired by the\n * caller when the connector process exits, so a dead connector returns `dead`\n * immediately instead of waiting out the timeout. `provisioning` is only\n * returned if the process is still alive at the deadline (never a false\n * \"healthy\"). Note: this measures connector↔edge, not local-origin, health.\n */\nexport async function waitHealthy(\n cf: Cf,\n tunnelId: string,\n opts: { signal?: AbortSignal; timeoutMs?: number } = {},\n): Promise<HealthResult> {\n const deadline = Date.now() + (opts.timeoutMs ?? 30_000);\n while (Date.now() < deadline) {\n if (opts.signal?.aborted) return \"dead\";\n try {\n const connections = await getConnections(cf, tunnelId);\n if (connections.length > 0) return \"healthy\";\n } catch {\n // transient API error — keep polling until the deadline\n }\n await sleep(2000);\n }\n return opts.signal?.aborted ? \"dead\" : \"provisioning\";\n}\n","import { randomInt } from \"node:crypto\";\nimport type { Cf } from \"../cloudflare/client.js\";\nimport { resolveZone } from \"../cloudflare/zones.js\";\nimport {\n MANAGED_TUNNEL_PREFIX,\n createTunnel,\n deleteTunnel,\n deleteTunnelWithConnections,\n getTunnel,\n getTunnelToken,\n isManagedTunnel,\n putIngress,\n} from \"../cloudflare/tunnels.js\";\nimport { createCname, deleteDnsRecord, findCname } from \"../cloudflare/dns.js\";\nimport type { DnsRecord } from \"../cloudflare/types.js\";\nimport { buildIngress } from \"./ingress.js\";\nimport { resolveHostSpec, type HostSpec } from \"./slug.js\";\nimport { currentBootId, patchEntry, removeEntry, upsertEntry } from \"../connector/registry.js\";\nimport { CliError } from \"../ui/errors.js\";\nimport { confirm, say } from \"../ui/output.js\";\n\nexport interface CreateOptions {\n port: number;\n proto: \"http\" | \"https\";\n name?: string;\n zone?: string;\n hostname?: string;\n host?: string; // forward target host (absent = localhost)\n defaultZone?: string;\n force?: boolean;\n yes?: boolean; // skip the \"replace existing record?\" confirmation\n}\n\nexport interface CreateResult {\n host: HostSpec;\n tunnelId: string;\n token: string;\n}\n\nconst tunnelIdFromCname = (content: string): string => content.replace(/\\.cfargotunnel\\.com\\.?$/, \"\");\n\n/**\n * Create a tunnel subdomain transactionally (idempotent). Any leftover tunnel\n * record for the same hostname is cleaned up first, so re-running `up` never\n * conflicts. A `provisioning` registry entry is written BEFORE any Cloudflare\n * resource; on failure everything is unwound in reverse and the original error\n * is surfaced.\n */\nexport async function createTunnelSubdomain(cf: Cf, opts: CreateOptions): Promise<CreateResult> {\n const host = resolveHostSpec(opts, opts.defaultZone);\n const zone = await resolveZone(cf.token, host.zone);\n\n const existing = await findCname(cf.token, zone.id, host.hostname);\n if (existing) {\n // A leftover tunnel record → replaceable. A non-tunnel DNS record (A record,\n // ordinary CNAME) → refuse unless --force, to avoid clobbering unrelated DNS.\n const isTunnelRecord = existing.content.endsWith(\".cfargotunnel.com\");\n if (!isTunnelRecord && !opts.force) {\n throw new CliError(`${host.hostname} is taken by a non-tunnel DNS record.`, {\n hint: \"pick another --subdomain/--hostname, or pass -f/--force to replace it\",\n });\n }\n // Confirm before replacing an existing record (interactive only; -f/-y skip).\n if (!opts.force && !opts.yes && process.stdin.isTTY) {\n const kind = isTunnelRecord ? \"tunnel\" : \"DNS\";\n if (!(await confirm(`${host.hostname} already has a ${kind} record. Replace it?`))) {\n throw new CliError(\"Cancelled.\", { exitCode: 130 });\n }\n }\n await releaseHostname(cf, zone.id, existing);\n }\n\n // Track provisioning BEFORE creating anything irreversible.\n await upsertEntry(host.hostname, {\n subdomain: host.subdomain, zone: host.zone, zoneId: zone.id,\n port: opts.port, proto: opts.proto, host: opts.host, state: \"provisioning\",\n });\n\n let tunnelId: string | undefined;\n let dnsRecordId: string | undefined;\n try {\n const suffix = randomInt(0x10000).toString(16).padStart(4, \"0\");\n const label = host.subdomain === \"@\" ? \"root\" : host.subdomain;\n const tunnel = await createTunnel(cf, `${MANAGED_TUNNEL_PREFIX}${label}-${suffix}`);\n tunnelId = tunnel.id;\n const token = await getTunnelToken(cf, tunnelId);\n await putIngress(cf, tunnelId, buildIngress({ hostname: host.hostname, port: opts.port, proto: opts.proto, host: opts.host }));\n const record = await createCname(cf.token, zone.id, host.hostname, tunnelId);\n dnsRecordId = record.id;\n await recordRunning(host, zone.id, tunnelId, dnsRecordId, opts);\n return { host, tunnelId, token };\n } catch (err) {\n const clean = await rollback(cf, zone.id, tunnelId, dnsRecordId, host.hostname);\n if (clean) await removeEntry(host.hostname);\n else await patchEntry(host.hostname, { state: \"orphaned\" });\n throw err;\n }\n}\n\nasync function recordRunning(host: HostSpec, zoneId: string, tunnelId: string, dnsRecordId: string, opts: CreateOptions): Promise<void> {\n await upsertEntry(host.hostname, {\n subdomain: host.subdomain, zone: host.zone, zoneId,\n tunnelId, dnsRecordId, port: opts.port, proto: opts.proto, host: opts.host,\n bootId: currentBootId(), state: \"running\",\n });\n}\n\n/** Free a hostname before recreating: delete its DNS record, and if it pointed\n * at a cloudtunnel-managed tunnel, delete that tunnel too (cleaning up any\n * lingering connections). A foreign tunnel is left alone — we only free the name. */\nasync function releaseHostname(cf: Cf, zoneId: string, record: DnsRecord): Promise<void> {\n if (record.content.endsWith(\".cfargotunnel.com\")) {\n const oldTunnelId = tunnelIdFromCname(record.content);\n try {\n const tunnel = await getTunnel(cf, oldTunnelId);\n if (isManagedTunnel(tunnel)) await deleteTunnelWithConnections(cf, oldTunnelId);\n } catch {\n /* tunnel already gone or not accessible — freeing the DNS name is enough */\n }\n }\n await deleteDnsRecord(cf.token, zoneId, record.id);\n}\n\n/** Unwind created resources in reverse. Never masks the original error; if a\n * step fails, report the leaked id and return false so the caller marks the\n * entry `orphaned`. */\nasync function rollback(cf: Cf, zoneId: string, tunnelId?: string, dnsRecordId?: string, hostname?: string): Promise<boolean> {\n let clean = true;\n if (dnsRecordId) {\n try { await deleteDnsRecord(cf.token, zoneId, dnsRecordId); }\n catch { clean = false; say.warn(`Left a DNS record behind for ${hostname} (${dnsRecordId}).`); }\n }\n if (tunnelId) {\n try { await deleteTunnel(cf, tunnelId); }\n catch { clean = false; say.warn(`Left tunnel ${tunnelId} behind — remove it with \\`cloudtunnel down ${hostname}\\`.`); }\n }\n return clean;\n}\n","import { randomInt } from \"node:crypto\";\nimport { CliError } from \"../ui/errors.js\";\n\nconst ADJECTIVES = [\n \"brave\", \"calm\", \"clever\", \"eager\", \"gentle\", \"happy\", \"jolly\", \"kind\",\n \"lively\", \"mighty\", \"nimble\", \"proud\", \"quick\", \"royal\", \"swift\", \"witty\",\n];\nconst NOUNS = [\n \"otter\", \"falcon\", \"maple\", \"comet\", \"harbor\", \"lynx\", \"willow\", \"cedar\",\n \"raven\", \"meadow\", \"pixel\", \"quartz\", \"river\", \"sparrow\", \"tiger\", \"walnut\",\n];\n\nconst pick = <T>(arr: T[]): T => arr[randomInt(arr.length)]!;\n\n/** A friendly random subdomain, e.g. `brave-otter-1a2b` (the default when unnamed). */\nexport function randomSlug(): string {\n const suffix = randomInt(0x10000).toString(16).padStart(4, \"0\");\n return `${pick(ADJECTIVES)}-${pick(NOUNS)}-${suffix}`;\n}\n\nexport interface HostSpec {\n subdomain: string;\n zone: string;\n hostname: string;\n}\n\n/**\n * Resolve the target hostname from flags. Precedence: --hostname > --name+zone >\n * random-slug+zone. Zone comes from --zone or the saved default; missing zone is\n * an actionable error. (--hostname assumes `label.zone`; deeper subdomains need\n * the zone to be an actual Cloudflare zone.)\n */\nexport function resolveHostSpec(\n opts: { name?: string; zone?: string; hostname?: string },\n defaultZone?: string,\n): HostSpec {\n if (opts.hostname) {\n const dot = opts.hostname.indexOf(\".\");\n if (dot <= 0) throw new CliError(`Invalid hostname: ${opts.hostname}`);\n return {\n subdomain: opts.hostname.slice(0, dot),\n zone: opts.hostname.slice(dot + 1),\n hostname: opts.hostname,\n };\n }\n const zone = opts.zone ?? defaultZone;\n if (!zone) {\n throw new CliError(\"No zone specified and no default zone set.\", {\n hint: \"pass --zone <domain>, or run `cloudtunnel login --zone <domain>`\",\n });\n }\n const subdomain = opts.name ?? randomSlug();\n // `@` means the root/apex domain (Cloudflare flattens the proxied CNAME).\n const hostname = subdomain === \"@\" ? zone : `${subdomain}.${zone}`;\n return { subdomain, zone, hostname };\n}\n","import type { Cf } from \"../cloudflare/client.js\";\nimport { resolveZone } from \"../cloudflare/zones.js\";\nimport { deleteTunnelWithConnections, getTunnel, isManagedTunnel, listTunnels } from \"../cloudflare/tunnels.js\";\nimport { deleteDnsRecord, findCname, isManagedDns } from \"../cloudflare/dns.js\";\nimport type { Tunnel } from \"../cloudflare/types.js\";\nimport { CliError } from \"../ui/errors.js\";\nimport { say } from \"../ui/output.js\";\nimport { entryFqdn, getEntry, listEntries, reconcile, removeEntry, type RegistryEntry } from \"../connector/registry.js\";\nimport { stopConnector } from \"../connector/process.js\";\nimport { serviceUrl } from \"./ingress.js\";\nimport { serviceState } from \"./service.js\";\n\nconst tunnelIdFromCname = (content: string): string => content.replace(/\\.cfargotunnel\\.com\\.?$/, \"\");\nconst isNotFound = (err: unknown): boolean => err instanceof CliError && err.status === 404;\nconst zoneFromFqdn = (fqdn: string): string => fqdn.slice(fqdn.indexOf(\".\") + 1);\n\n/** Resolve a target to its registry entry / fqdn. Accepts a full hostname, the\n * `#` number, a subdomain name, or a tunnel-id prefix (all shown in `ls`).\n * Refuses an ambiguous match. */\nexport function resolveTarget(target: string): { fqdn: string; entry?: RegistryEntry } {\n if (target.includes(\".\")) return { fqdn: target, entry: getEntry(target) };\n const entries = listEntries();\n if (/^\\d+$/.test(target)) {\n const byIndex = entries.find((e) => e.index === Number(target));\n if (byIndex) return { fqdn: entryFqdn(byIndex), entry: byIndex };\n }\n const byId = entries.filter((e) => e.tunnelId?.startsWith(target));\n const matches = byId.length > 0 ? byId : entries.filter((e) => e.subdomain === target);\n if (matches.length > 1) {\n throw new CliError(`\"${target}\" matches multiple subdomains.`, {\n hint: `use a full hostname or a longer id: ${matches.map(entryFqdn).join(\", \")}`,\n });\n }\n const entry = matches[0];\n if (!entry) {\n throw new CliError(`No tracked subdomain matching \"${target}\".`, { hint: \"see `cloudtunnel ls` for the #, name, or id\" });\n }\n return { fqdn: entryFqdn(entry), entry };\n}\n\nexport interface RemoveOptions { force?: boolean; dryRun?: boolean; quiet?: boolean }\n\n/** Release a subdomain: stop the connector, then delete the tunnel + DNS on\n * Cloudflare. Re-verifies fresh state (cached ids are hints), ownership-gates\n * unmanaged resources, and tolerates already-deleted parts. */\nexport async function removeTunnelSubdomain(cf: Cf, target: string, opts: RemoveOptions = {}): Promise<void> {\n const { fqdn, entry } = resolveTarget(target);\n if (!entry && !opts.force) {\n throw new CliError(`${fqdn} is not managed by cloudtunnel.`, { hint: \"pass --force to release it anyway\" });\n }\n const zoneId = entry?.zoneId ?? (await resolveZone(cf.token, zoneFromFqdn(fqdn))).id;\n\n const record = await findCname(cf.token, zoneId, fqdn); // fresh, authoritative\n if (record && !isManagedDns(record) && !opts.force) {\n throw new CliError(`${fqdn} points to a record not managed by cloudtunnel.`, { hint: \"pass --force to release it\" });\n }\n const tunnelId = record ? tunnelIdFromCname(record.content) : entry?.tunnelId;\n\n if (opts.dryRun) {\n say.info(`Would release: tunnel ${tunnelId ?? \"(none)\"}${record ? `, DNS ${record.id}` : \"\"}`);\n return;\n }\n\n if (entry) await stopConnector(entry);\n if (tunnelId) {\n let tunnel: Tunnel | undefined;\n try {\n tunnel = await getTunnel(cf, tunnelId);\n } catch (err) {\n if (!isNotFound(err)) throw err; // transient error → don't silently orphan\n }\n if (tunnel && !isManagedTunnel(tunnel) && !opts.force) {\n throw new CliError(`Tunnel ${tunnelId} is not managed by cloudtunnel.`, { hint: \"pass --force\" });\n }\n if (tunnel) {\n try {\n await deleteTunnelWithConnections(cf, tunnelId);\n } catch (err) {\n if (!isNotFound(err)) throw err;\n }\n }\n }\n if (record) {\n try {\n await deleteDnsRecord(cf.token, zoneId, record.id);\n } catch (err) {\n if (!isNotFound(err)) throw err;\n }\n }\n await removeEntry(fqdn);\n if (!opts.quiet) say.ok(`Released ${fqdn}`);\n}\n\nexport interface LsRow { num: string; url: string; target: string; state: string; service: string; pid: string; managed: boolean }\n\n/** Reconcile + list tracked subdomains: `# | URL | TARGET | STATE | SERVICE | PID`.\n * SERVICE is the per-subdomain systemd unit's state (\"-\" when none). `all` also\n * scans every zone for cfargotunnel CNAMEs created outside cloudtunnel. */\nexport async function listAll(cf: Cf, opts: { all?: boolean } = {}): Promise<LsRow[]> {\n const entries = await reconcile();\n const tunnels = new Map((await listTunnels(cf)).map((t) => [t.id, t]));\n const rows: LsRow[] = entries.map((e) => {\n const fqdn = entryFqdn(e);\n const gone = e.tunnelId ? !tunnels.has(e.tunnelId) : false;\n const svc = serviceState(fqdn);\n return {\n num: e.index ? String(e.index) : \"-\",\n url: `https://${fqdn}`,\n target: serviceUrl(e.proto, e.host ?? \"localhost\", e.port),\n state: !gone && e.state === \"running\" ? \"up\" : \"down\",\n service: svc === \"none\" ? \"-\" : svc,\n pid: e.state === \"running\" && e.pid ? String(e.pid) : \"-\",\n managed: true,\n };\n });\n if (opts.all) {\n const { listCargoCnames } = await import(\"../cloudflare/dns.js\");\n const { listZones } = await import(\"../cloudflare/zones.js\");\n const tracked = new Set(entries.map(entryFqdn));\n for (const zone of await listZones(cf.token)) {\n for (const rec of await listCargoCnames(cf.token, zone.id)) {\n if (!tracked.has(rec.name)) {\n rows.push({ num: \"-\", url: `https://${rec.name}`, target: \"-\", state: \"unmanaged\", service: \"-\", pid: \"-\", managed: false });\n }\n }\n }\n }\n return rows;\n}\n","import { CliError } from \"../ui/errors.js\";\n\n/**\n * cloudflared edge transport (NOT the local service scheme). `quic` is UDP-based\n * and fastest, but UDP-hostile networks drop idle QUIC sessions (→ Cloudflare\n * 530/502); `http2` runs over TCP and stays stable there. `auto` lets cloudflared\n * choose (defaults to quic when the network probe passes).\n */\nexport type TransportProtocol = \"auto\" | \"http2\" | \"quic\";\n\nexport function parseTransportProtocol(value: string): TransportProtocol {\n if (value === \"auto\" || value === \"http2\" || value === \"quic\") return value;\n throw new CliError(`Invalid protocol \"${value}\".`, { hint: \"use auto, http2, or quic\" });\n}\n","import type { Command } from \"commander\";\nimport { printTable, say } from \"../ui/output.js\";\nimport { ensureAuth } from \"../config/ensure-auth.js\";\nimport { resolveCf } from \"../cloudflare/client.js\";\nimport { listAll } from \"../core/orchestrator-manage.js\";\n\nexport function registerLs(program: Command): void {\n program\n .command(\"ls\")\n .alias(\"ps\")\n .description(\"List tunnel subdomains (managed by default; --all scans the whole account)\")\n .option(\"--all\", \"scan every zone in the account (slower; shows unmanaged tunnels too)\")\n .action(async (opts: { all?: boolean }) => {\n await ensureAuth();\n const cf = resolveCf();\n const rows = await listAll(cf, { all: opts.all });\n if (rows.length === 0) {\n say.info(\"No tunnel subdomains yet. Create one: `cloudtunnel 3000`\");\n return;\n }\n printTable(\n [\"#\", \"URL\", \"TARGET\", \"STATE\", \"SERVICE\", \"PID\"],\n rows.map((r) => [r.num, r.url, r.target, r.state, r.service, r.pid]),\n );\n });\n}\n","import type { Command } from \"commander\";\nimport { CliError } from \"../ui/errors.js\";\nimport { say } from \"../ui/output.js\";\nimport { ensureAuth } from \"../config/ensure-auth.js\";\nimport { resolveCf, type Cf } from \"../cloudflare/client.js\";\nimport { entryFqdn, listEntries } from \"../connector/registry.js\";\nimport { removeTunnelSubdomain, resolveTarget } from \"../core/orchestrator-manage.js\";\nimport { serviceName, serviceState, uninstallService } from \"../core/service.js\";\n\ninterface DeleteOptions { all?: boolean; force?: boolean; dryRun?: boolean }\n\n/** Remove a subdomain's boot service (if any) first so its supervisor can't\n * restart the connector mid-teardown, then release the tunnel + DNS. */\nasync function deleteOne(cf: Cf, fqdn: string, opts: DeleteOptions): Promise<void> {\n const hasService = serviceState(fqdn) !== \"none\";\n if (hasService && !opts.dryRun) uninstallService(fqdn);\n await removeTunnelSubdomain(cf, fqdn, { force: opts.force, dryRun: opts.dryRun });\n if (!hasService) return;\n if (opts.dryRun) say.info(`Would also remove boot service ${serviceName(fqdn)}`);\n else say.ok(`Removed boot service ${serviceName(fqdn)}`);\n}\n\nexport function registerDelete(program: Command): void {\n program\n .command(\"delete\")\n .argument(\"[targets...]\", \"subdomains to remove by # / name / URL (omit with --all)\")\n .description(\"Release tunnel(s) — deletes the tunnel + DNS, and any systemd boot service\")\n .option(\"--all\", \"release every tracked subdomain\")\n .option(\"-f, --force\", \"release even a resource not created by cloudtunnel\")\n .option(\"--dry-run\", \"show what would be released without doing it\")\n .action(async (targets: string[], opts: DeleteOptions) => {\n await ensureAuth();\n const cf = resolveCf();\n\n if (opts.all) {\n const entries = listEntries();\n if (entries.length === 0) {\n say.info(\"Nothing to release.\");\n return;\n }\n for (const e of entries) {\n const fqdn = entryFqdn(e);\n try {\n await deleteOne(cf, fqdn, opts);\n } catch (err) {\n say.warn(`Could not release ${fqdn}: ${(err as Error).message}`);\n }\n }\n return;\n }\n\n if (targets.length === 0) throw new CliError(\"Pass a subdomain (# / name / URL) or --all.\");\n for (const target of targets) {\n const { fqdn } = resolveTarget(target);\n await deleteOne(cf, fqdn, opts);\n }\n });\n}\n","import type { Command } from \"commander\";\nimport { closeSync, existsSync, openSync, readFileSync, readSync, statSync, watch } from \"node:fs\";\nimport { CliError } from \"../ui/errors.js\";\nimport { say } from \"../ui/output.js\";\nimport { resolveTarget } from \"../core/orchestrator-manage.js\";\n\ninterface LogsOptions {\n follow?: boolean;\n lines?: string;\n}\n\n/** Print the last `n` lines of a file; return the file's byte size (follow start). */\nfunction printTail(file: string, n: number): number {\n const lines = readFileSync(file, \"utf8\").split(\"\\n\");\n const tail = lines.slice(-n).join(\"\\n\");\n process.stdout.write(tail.endsWith(\"\\n\") ? tail : `${tail}\\n`);\n return statSync(file).size;\n}\n\n/** Tail -f: print appended bytes as the connector writes them. Ctrl-C to stop. */\nfunction follow(file: string, fromPos: number): void {\n let pos = fromPos;\n say.dim(\"— following (Ctrl-C to stop) —\");\n const watcher = watch(file, () => {\n const size = statSync(file).size;\n if (size < pos) {\n pos = 0; // file was truncated/rotated\n return;\n }\n if (size > pos) {\n const fd = openSync(file, \"r\");\n const buf = Buffer.alloc(size - pos);\n readSync(fd, buf, 0, size - pos, pos);\n closeSync(fd);\n process.stdout.write(buf.toString(\"utf8\"));\n pos = size;\n }\n });\n process.on(\"SIGINT\", () => {\n watcher.close();\n process.exit(0);\n });\n}\n\nexport function registerLogs(program: Command): void {\n program\n .command(\"logs\")\n .argument(\"<target>\", \"subdomain name / hostname / id / #\")\n .description(\"Show the connector log for a subdomain (use -f to follow)\")\n .option(\"-f, --follow\", \"keep printing new log lines (like tail -f)\")\n .option(\"-n, --lines <n>\", \"number of lines to show\", \"50\")\n .action((name: string, opts: LogsOptions) => {\n const { fqdn, entry } = resolveTarget(name);\n if (!entry?.logFile || !existsSync(entry.logFile)) {\n throw new CliError(`No logs for ${fqdn} yet.`, { hint: \"start it with `cloudtunnel up` or `cloudtunnel run`\" });\n }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ACpC;AACF;AAEA,KAAK,KAAK;","names":["pc","existsSync","writeFileSync","label","join","join","assertSupported","install","label","state","uninstall","execFileSync","existsSync","writeFileSync","dirname","join","os","label","join","os","dirname","execFileSync","assertSupported","install","writeFileSync","uninstall","state","existsSync","assertSupported","install","label","state","uninstall","execFileSync","writeFileSync","tmpdir","join","label","xml","execFileSync","assertSupported","install","join","tmpdir","writeFileSync","uninstall","state","legacyUnitExists","removeLegacyUnit","existsSync","legacyUnitExists","writeFileSync","removeLegacyUnit","listZones","listZones","clack","execFileSync","existsSync","readFileSync","writeFileSync","join","execFileSync","join","readFileSync","existsSync","writeFileSync","join","clack","execFileSync","spawn","existsSync","readFileSync","renameSync","writeFileSync","os","readFileSync","os","writeFileSync","renameSync","existsSync","spawn","execFileSync","sleep","randomInt","pick","randomInt","label","tunnelIdFromCname","listZones","join","lines","existsSync","openSync","readFileSync","readFileSync","openSync","existsSync","require","pc"]}