diff --git a/docs/astro.config.mjs b/docs/astro.config.mjs index dcd619f..6529d71 100644 --- a/docs/astro.config.mjs +++ b/docs/astro.config.mjs @@ -41,6 +41,7 @@ export default defineConfig({ items: [ { label: "Tailscale Setup", slug: "guides/tailscale" }, { label: "IAP Setup", slug: "guides/iap" }, + { label: "SSH Provider", slug: "guides/ssh-provider" }, { label: "Mobile SSH", slug: "guides/mobile-ssh" }, { label: "Toolchains", slug: "guides/toolchains" }, { label: "Git & GitHub", slug: "guides/git-github" }, diff --git a/docs/src/content/docs/architecture.md b/docs/src/content/docs/architecture.md index 3ec54d3..25cfdc8 100644 --- a/docs/src/content/docs/architecture.md +++ b/docs/src/content/docs/architecture.md @@ -7,8 +7,8 @@ vybn uses a modular architecture with swappable provider and network backends. ## Core Concepts -- **Provider** (`VYBN_PROVIDER`): Manages VM lifecycle — create, start, stop, delete. Default: `gcp` -- **Network** (`VYBN_NETWORK`): Manages SSH connectivity and file transfer. Default: `tailscale` +- **Provider** (`VYBN_PROVIDER`): Manages VM lifecycle — create, start, stop, delete. Options: `gcp` (default), `ssh` (bring your own server) +- **Network** (`VYBN_NETWORK`): Manages SSH connectivity and file transfer. Options: `tailscale` (default), `iap` (GCP only) Provider backends live in `providers/` and network backends in `networks/`. The VM setup script is selected based on the combination: `vm-setup/${VYBN_PROVIDER}-${VYBN_NETWORK}.sh`. @@ -72,6 +72,29 @@ SSH connections go through [GCP Identity-Aware Proxy](https://cloud.google.com/i - Firewall allows IAP SSH range (`35.235.240.0/20`) + deny-all for everything else - Not available from iOS (no `gcloud`) +## SSH Provider Backend + +``` +┌─────────┐ bootstrap SSH ┌──────────────────────────┐ +│ Laptop │─────────────────►│ Your Server │ +│ │ (upload script) │ │ +│ vybn │ │ setup script runs: │ +│ CLI │ │ ├─ Claude Code │ +│ │ Tailscale mesh │ ├─ toolchains │ +│ Phone │◄────────────────►│ ├─ Tailscale │ +│ Tablet │ (after setup) │ └─ tmux session "claude" │ +└─────────┘ └──────────────────────────┘ +``` + +The SSH provider deploys to an existing server you manage. Instead of creating a VM, `vybn deploy` uploads the assembled setup script via SCP and executes it over SSH. Once setup completes and Tailscale enrolls, the server is reachable through the tailnet like any other vybn VM. + +**Characteristics:** + +- No cloud API required — works with any SSH-accessible server +- The bootstrap SSH connection (used during deploy) is separate from the Tailscale mesh used afterward +- `start`/`stop` are not available — the user manages server lifecycle externally +- `destroy` deregisters from Tailscale and cleans up local state without modifying the remote server + ## Project Structure ``` @@ -97,7 +120,8 @@ vybn/ │ ├── switch_network.sh # switch-network command │ └── add_key.sh # add-key command ├── providers/ # Cloud provider backends -│ └── gcp.sh # Google Cloud Platform +│ ├── gcp.sh # Google Cloud Platform +│ └── ssh.sh # Bring your own VM (SSH) ├── networks/ # Network connectivity backends │ ├── iap.sh # Identity-Aware Proxy │ └── tailscale.sh # Tailscale mesh @@ -105,6 +129,7 @@ vybn/ │ ├── base.sh # Shared setup functions │ ├── gcp-iap.sh # GCP + IAP variant │ ├── gcp-tailscale.sh # GCP + Tailscale variant +│ ├── ssh-tailscale.sh # SSH + Tailscale variant │ └── toolchains/ # Composable toolchain modules │ ├── node.sh # nvm + Node.js LTS │ ├── python.sh # pyenv + Python 3 @@ -129,3 +154,5 @@ At deploy time, the VM's startup script is assembled by concatenating several la 6. **User script** — contents of `VYBN_SETUP_SCRIPT`, if configured Configuration is baked directly into the script header rather than read from cloud metadata at runtime. This makes the startup script self-contained and debuggable — you can read the full assembled script in the GCP serial console or setup log. + +For the SSH provider, the same assembly process produces the script locally. Instead of being passed as GCP startup metadata, the script is uploaded to the server via SCP and executed over SSH. diff --git a/docs/src/content/docs/commands.md b/docs/src/content/docs/commands.md index f754e9f..f61331c 100644 --- a/docs/src/content/docs/commands.md +++ b/docs/src/content/docs/commands.md @@ -41,9 +41,10 @@ vybn init - `-f, --force` — back up and overwrite existing `~/.vybnrc` without prompting The wizard prompts for: +- Provider (GCP or SSH) - Network backend (Tailscale or IAP) -- GCP project and zone -- VM name, machine type, and disk size +- Provider-specific settings (GCP project/zone or SSH server details) +- VM name, machine type, and disk size (GCP) or hostname (SSH) - Tailscale auth key (if using Tailscale) - Toolchains, extra packages, and custom setup scripts @@ -61,10 +62,13 @@ vybn deploy - `-y, --yes` — skip the confirmation prompt - `--connect` — after deploy completes, attach to the tmux session +- `--script-only` — output the assembled setup script to stdout and exit (does not deploy) -Before creating the VM, `deploy` shows a summary with estimated monthly cost (based on the selected machine type and disk size) and asks for confirmation. Use `-y` to skip this. +Before creating the VM, `deploy` shows a summary with estimated monthly cost (GCP) or server details (SSH) and asks for confirmation. Use `-y` to skip this. -This provisions a GCP VM, runs the setup script (installs Claude Code native binary, selected toolchains, extra packages, tmux), and configures the network backend. The VM is ready to use once the command completes. +**GCP provider:** provisions a VM, runs the setup script as startup metadata, and waits for the VM to become reachable. + +**SSH provider:** uploads the setup script to the server via SCP and executes it over SSH. The server must already be running and accessible. ## connect @@ -123,6 +127,10 @@ Start a stopped VM. Waits until the VM is reachable via SSH before returning. vybn start ``` +:::note +GCP only. The SSH provider does not manage server lifecycle — start your server directly. +::: + ## stop Stop the VM to save on compute costs. Disk is preserved. @@ -135,6 +143,10 @@ vybn stop - `-y, --yes` — skip the confirmation prompt +:::note +GCP only. The SSH provider does not manage server lifecycle — stop your server directly. +::: + :::note tmux sessions run in memory and don't survive a stop/start cycle. Your repos and files on disk persist. Create new sessions with `vybn connect` or `vybn session` after restarting. ::: @@ -151,9 +163,9 @@ vybn destroy - `-y, --yes` — skip the confirmation prompt (which normally requires typing the VM name) -:::caution -This deletes the VM's boot disk and all data on it. This action is not reversible. -::: +**GCP provider:** deletes the VM, its boot disk, and all associated network infrastructure. This action is not reversible. + +**SSH provider:** deregisters from Tailscale and cleans up local state files. The remote server itself is not modified or deleted. ## status @@ -171,13 +183,22 @@ Validate that all prerequisites are met before deploying. vybn check ``` -Runs all checks and reports pass/fail for each: -- gcloud CLI installed -- gcloud authenticated (prints account) -- GCP project configured (prints project ID) +Runs provider-specific checks and reports pass/fail for each. + +**GCP provider:** +- gcloud CLI installed and authenticated +- GCP project configured - Compute Engine API enabled - Network-specific checks (Tailscale CLI, auth key, etc.) -- VM setup script exists for the provider/network combination + +**SSH provider:** +- SSH client installed +- `VYBN_SSH_HOST` configured +- SSH key readable (if set) +- SSH connectivity to the server +- Tailscale CLI and auth key + +Both providers also verify the VM setup script exists for the provider/network combination. Exits 0 if all checks pass, 1 if any fail. Run this before `vybn deploy` to catch configuration issues early. diff --git a/docs/src/content/docs/configuration.md b/docs/src/content/docs/configuration.md index 5cfa3e6..58acab4 100644 --- a/docs/src/content/docs/configuration.md +++ b/docs/src/content/docs/configuration.md @@ -9,7 +9,7 @@ The easiest way to configure vybn is with the init wizard: vybn init ``` -This walks you through network backend, GCP project, machine type, Tailscale auth key, and other settings, then writes `~/.vybnrc` for you. +This walks you through provider, network backend, GCP project (or SSH server details), machine type, Tailscale auth key, and other settings, then writes `~/.vybnrc` for you. You can also create the file manually from the included template: @@ -23,26 +23,39 @@ All settings can also be set as environment variables. | Variable | Default | Description | |----------|---------|-------------| -| `VYBN_PROVIDER` | `gcp` | Cloud provider backend | +| `VYBN_PROVIDER` | `gcp` | Cloud provider backend (`gcp` or `ssh`) | | `VYBN_NETWORK` | `tailscale` | Network backend (`tailscale` or `iap`) | | `VYBN_VM_NAME` | *(auto-generated petname)* | VM instance name (`claude--`) | -| `VYBN_ZONE` | `us-west1-a` | GCP zone | -| `VYBN_MACHINE_TYPE` | `e2-standard-2` | Machine type (CPU/RAM) | -| `VYBN_DISK_SIZE` | `30` | Boot disk size in GB | | `VYBN_USER` | `claude` | VM user account | -| `VYBN_PROJECT` | *(auto-detected)* | GCP project ID | | `VYBN_TMUX_SESSION` | `claude` | tmux session name | | `VYBN_TERM` | `xterm-256color` | Terminal type for tmux sessions | -| `VYBN_EXTERNAL_IP` | `false` | Assign public IP to VM (forced `true` for Tailscale) | | `VYBN_QUIET` | `false` | Suppress info/success output (`--quiet` flag) | | `VYBN_VERBOSE` | `false` | Enable trace output (`--verbose` flag) | -## GCP Settings +## GCP Provider Settings + +These apply when using `VYBN_PROVIDER=gcp` (the default). | Variable | Default | Description | |----------|---------|-------------| +| `VYBN_ZONE` | `us-west1-a` | GCP zone | +| `VYBN_MACHINE_TYPE` | `e2-standard-2` | Machine type (CPU/RAM) | +| `VYBN_DISK_SIZE` | `30` | Boot disk size in GB | +| `VYBN_PROJECT` | *(auto-detected)* | GCP project ID | +| `VYBN_EXTERNAL_IP` | `false` | Assign public IP to VM (forced `true` for Tailscale) | | `VYBN_GCP_SCOPES` | `compute-ro,logging-write,storage-ro` | GCP API scopes assigned to the VM | +## SSH Provider Settings + +These apply when using `VYBN_PROVIDER=ssh`. + +| Variable | Default | Description | +|----------|---------|-------------| +| `VYBN_SSH_HOST` | *(none, required)* | Remote hostname or IP address | +| `VYBN_SSH_USER` | *(current user)* | SSH user for the bootstrap connection | +| `VYBN_SSH_KEY` | *(none)* | Path to SSH private key (uses SSH agent if unset) | +| `VYBN_SSH_PORT` | `22` | SSH port for the bootstrap connection | + ## Claude Code | Variable | Default | Description | @@ -146,6 +159,23 @@ VYBN_ZONE="europe-west1-b" VYBN_VM_NAME="claude-work" ``` +### SSH Provider + +```bash +# ~/.vybnrc + +# Use an existing server +VYBN_PROVIDER="ssh" + +# Server connection details +VYBN_SSH_HOST="dev.example.com" +VYBN_SSH_USER="ubuntu" +VYBN_SSH_KEY="$HOME/.ssh/id_ed25519" + +# Tailscale auth key (required for deploy) +VYBN_TAILSCALE_AUTHKEY="tskey-auth-..." +``` + ### Custom Setup Script For project-specific configuration beyond packages and toolchains, point `VYBN_SETUP_SCRIPT` to a local shell script: diff --git a/docs/src/content/docs/getting-started.md b/docs/src/content/docs/getting-started.md index 5df2778..cb6e4c0 100644 --- a/docs/src/content/docs/getting-started.md +++ b/docs/src/content/docs/getting-started.md @@ -7,14 +7,22 @@ description: Install vybn and deploy your first cloud VM with Claude Code. Need help setting these up? See the [Prerequisites guide](/guides/prerequisites/) for a full walkthrough. +**GCP provider** (default): + - [Google Cloud SDK](https://cloud.google.com/sdk/docs/install) (`gcloud`) — authenticated with a project -- SSH client — comes with macOS/Linux - A GCP project with billing enabled - [Tailscale](https://tailscale.com/download) — installed and logged in on your local machine - A Tailscale auth key — generate at the [admin console](https://login.tailscale.com/admin/settings/keys) +**SSH provider** (bring your own server): + +- SSH client — comes with macOS/Linux +- An accessible server (Ubuntu 22.04+/Debian 12+) with root or sudo +- [Tailscale](https://tailscale.com/download) — installed and logged in on your local machine +- A Tailscale auth key — generate at the [admin console](https://login.tailscale.com/admin/settings/keys) + :::note[Using IAP instead of Tailscale?] -For IAP networking (alternative to Tailscale): no additional prerequisites beyond `gcloud`. See the [IAP Setup guide](/guides/iap/). +For IAP networking (GCP only, alternative to Tailscale): no additional prerequisites beyond `gcloud`. See the [IAP Setup guide](/guides/iap/). ::: ## Installation @@ -79,7 +87,7 @@ vybn deploy vybn connect ``` -The wizard asks for your Tailscale auth key, GCP project, machine type, and other settings. It writes a validated `~/.vybnrc` for you. +The wizard asks for your provider, network backend, Tailscale auth key, GCP project (or SSH server details), machine type, and other settings. It writes a validated `~/.vybnrc` for you. After deploy, the VM is reachable from any device on your tailnet — including iOS via [Termius](https://termius.com/) or any SSH client. @@ -104,16 +112,42 @@ vybn connect `vybn init` handles the network choice — select `iap` when prompted for the network backend. +## Quick Start (SSH Provider) + +Use an existing server instead of provisioning a GCP VM. + +```bash +# 1. Run the setup wizard — select "ssh" as the provider +vybn init + +# 2. Deploy Claude Code to your server +vybn deploy + +# 3. Connect +vybn connect +``` + +The wizard asks for your server's hostname, SSH user, and Tailscale auth key. vybn uploads and runs the setup script over SSH. See the [SSH Provider guide](/guides/ssh-provider/) for details. + ## What happens on deploy When you run `vybn deploy`, the following happens: +**GCP provider:** + 1. A GCP VM is created running Ubuntu 24.04 2. A startup script installs Claude Code CLI (native binary with checksum verification), selected toolchains (Node.js by default), and tmux 3. Any extra apt/npm packages from your config are installed 4. Network infrastructure is configured (Tailscale enrollment or IAP firewall rules) 5. The VM becomes reachable via the selected network backend +**SSH provider:** + +1. The setup script is assembled locally and uploaded to your server via SCP +2. The script runs over SSH, installing Claude Code, toolchains, and tmux +3. Tailscale is installed and enrolled on your tailnet +4. The server becomes reachable via Tailscale + After deploy completes, run `vybn connect` to drop into a tmux session. Claude Code will prompt you to log in on first launch. ## Sessions persist across disconnects diff --git a/docs/src/content/docs/guides/prerequisites.md b/docs/src/content/docs/guides/prerequisites.md index a5a50a9..97a028d 100644 --- a/docs/src/content/docs/guides/prerequisites.md +++ b/docs/src/content/docs/guides/prerequisites.md @@ -1,11 +1,13 @@ --- title: Prerequisites -description: Set up Google Cloud, the gcloud CLI, and Tailscale before deploying your first vybn VM. +description: Set up your cloud provider and Tailscale before deploying your first vybn VM. --- -This guide walks through everything you need before running `vybn deploy`. If you already have `gcloud` authenticated and Tailscale installed, you can skip straight to [Getting Started](/getting-started/). +This guide walks through everything you need before running `vybn deploy`. Choose your provider — GCP (managed VM) or SSH (bring your own server) — and follow the relevant sections. -## 1. Google Cloud account & project +## GCP Provider + +### 1. Google Cloud account & project You need a GCP account with a project that has billing enabled. @@ -17,7 +19,7 @@ You need a GCP account with a project that has billing enabled. vybn creates a single `e2-standard-4` VM by default. See [GCP pricing](https://cloud.google.com/compute/vm-instance-pricing) for current costs. You can change the machine type with `VYBN_MACHINE_TYPE` in `~/.vybnrc`. ::: -## 2. Install the gcloud CLI +### 2. Install the gcloud CLI Install the Google Cloud SDK for your platform: @@ -48,7 +50,7 @@ gcloud auth login To change your project later: `gcloud config set project PROJECT_ID` ::: -## 3. Enable the Compute Engine API +### 3. Enable the Compute Engine API vybn creates VMs through the Compute Engine API, which must be enabled on your project: @@ -56,12 +58,41 @@ vybn creates VMs through the Compute Engine API, which must be enabled on your p gcloud services enable compute.googleapis.com ``` -## 4. Tailscale account & auth key +## SSH Provider + +The SSH provider deploys to an existing server you manage. No GCP account or `gcloud` CLI required. + +### 1. Server requirements + +- **OS:** Ubuntu 22.04+, Ubuntu 24.04, or Debian 12+ +- **Access:** root or a user with passwordless sudo +- **Network:** outbound internet access (to install packages and connect to Tailscale) +- **SSH:** the server must be reachable from your local machine via SSH + +### 2. SSH client + +You need an SSH client on your local machine. macOS and Linux include one by default. Verify with: + +```bash +ssh -V +``` + +### 3. SSH credentials + +Ensure you can connect to your server: + +```bash +ssh user@your-server.example.com +``` + +If you use a specific key file, note its path — you'll provide it during `vybn init` (or set `VYBN_SSH_KEY` in `~/.vybnrc`). + +## Tailscale account & auth key -Tailscale is the default network backend. It creates a WireGuard mesh so your VM is reachable from any device on your tailnet. +Tailscale is the default network backend for both providers. It creates a WireGuard mesh so your VM is reachable from any device on your tailnet. -:::note[Using IAP instead?] -If you'd rather tunnel SSH through Google's infrastructure, you can skip this section entirely. See the [IAP Setup guide](/guides/iap/) for that approach. +:::note[Using IAP instead? (GCP only)] +If you're using the GCP provider and prefer to tunnel SSH through Google's infrastructure, you can skip this section. See the [IAP Setup guide](/guides/iap/). ::: 1. Create a free account at [tailscale.com](https://tailscale.com/) diff --git a/docs/src/content/docs/guides/ssh-provider.md b/docs/src/content/docs/guides/ssh-provider.md new file mode 100644 index 0000000..bb1ef59 --- /dev/null +++ b/docs/src/content/docs/guides/ssh-provider.md @@ -0,0 +1,108 @@ +--- +title: SSH Provider +description: Deploy vybn to an existing server you manage. +--- + +The SSH provider deploys Claude Code to a server you already have — no cloud account or API required. vybn uploads and runs the setup script over SSH, then connects through Tailscale like any other vybn VM. + +## When to use the SSH provider + +- You have existing servers (cloud VMs, bare metal, on-prem) +- You're on a non-GCP cloud (AWS, Azure, Hetzner, etc.) +- You want full control over the server's lifecycle and configuration +- You want to avoid GCP billing or `gcloud` dependencies + +## Server requirements + +- **OS:** Ubuntu 22.04+, Ubuntu 24.04, or Debian 12+ +- **Access:** root, or a user with passwordless sudo +- **Network:** outbound internet access (to install packages and connect to Tailscale) +- **SSH:** reachable from your local machine + +The setup script installs Claude Code, tmux, Tailscale, and selected toolchains — same as the GCP provider. + +## Step-by-step + +### 1. Configure + +Run the setup wizard and select `ssh` as the provider: + +```bash +vybn init +``` + +The wizard prompts for: +- **Server hostname or IP** — where to connect via SSH +- **SSH user** — must have root or sudo access +- **SSH key** — path to your private key (blank to use SSH agent) +- **SSH port** — defaults to 22 +- **Tailscale auth key** — for enrolling the server on your tailnet + +Or configure manually in `~/.vybnrc`: + +```bash +# ~/.vybnrc +VYBN_PROVIDER="ssh" +VYBN_SSH_HOST="dev.example.com" +VYBN_SSH_USER="ubuntu" +VYBN_SSH_KEY="$HOME/.ssh/id_ed25519" +VYBN_TAILSCALE_AUTHKEY="tskey-auth-..." +``` + +### 2. Verify prerequisites + +```bash +vybn check +``` + +This tests SSH connectivity to the server, validates your Tailscale auth key, and confirms the setup script exists for the `ssh-tailscale` combination. + +### 3. Deploy + +```bash +vybn deploy +``` + +vybn assembles the setup script locally, uploads it to the server via SCP, and executes it over SSH. The script installs everything and enrolls the server on your tailnet. After setup completes, vybn waits for the server to become reachable via Tailscale. + +### 4. Connect + +```bash +vybn connect +``` + +You're in a persistent tmux session with Claude Code, connected through Tailscale. + +## How it works + +1. **Script assembly** — the setup script is built locally from `base.sh`, toolchain modules, and `ssh-tailscale.sh`, with your config baked into the header +2. **Bootstrap SSH** — vybn connects to the server using the credentials you provided (`VYBN_SSH_HOST`, `VYBN_SSH_USER`, etc.) and uploads the script via SCP +3. **Setup execution** — the script runs on the server with sudo, installing Claude Code, tmux, toolchains, and Tailscale +4. **Tailscale enrollment** — the server joins your tailnet, making it reachable from any device +5. **Ongoing access** — all subsequent connections (`vybn connect`, `vybn ssh`, etc.) go through Tailscale, not the bootstrap SSH connection + +## What `destroy` does + +Running `vybn destroy` with the SSH provider: + +- Deregisters the server from your Tailscale tailnet +- Cleans up local state files (`~/.vybn/ssh-provider-deployed`, etc.) + +It does **not** delete or modify the remote server. The server continues running with all installed software intact. + +## Differences from GCP + +| | GCP | SSH | +|---|---|---| +| VM creation | vybn creates and manages the VM | You provide the server | +| `start`/`stop` | Available — manages VM power state | Not available — manage the server directly | +| `destroy` | Deletes VM and boot disk | Deregisters Tailscale, cleans local state | +| Cost estimate | Shown before deploy | Not applicable — you manage billing | +| Network backends | Tailscale or IAP | Tailscale only | +| `--script-only` | Outputs the setup script | Outputs the setup script | + +## Tips + +- Use `vybn deploy --script-only` to inspect the assembled setup script before running it on your server +- The setup log is written to `/var/log/vybn-setup.log` on the server — check it with `vybn logs` after deploy +- You can redeploy to the same server by running `vybn destroy` (to clean up Tailscale) followed by `vybn deploy` diff --git a/docs/src/content/docs/index.mdx b/docs/src/content/docs/index.mdx index 169449c..f4fa11b 100644 --- a/docs/src/content/docs/index.mdx +++ b/docs/src/content/docs/index.mdx @@ -32,7 +32,7 @@ Claude Code runs best with a stable, always-on environment. Running it on a clou Prompt Claude from your phone on the train, pick up results on your laptop at the desk. One session, every screen. - Pick your machine size, toolchains, and packages. Stop the VM when idle — pay only for what you use. + Use a managed GCP VM or bring your own server. Pick your machine size, toolchains, and packages. @@ -49,4 +49,4 @@ vybn deploy vybn connect ``` -That's it. Three commands to get a persistent Claude Code environment in the cloud. vybn uses Tailscale by default, so your VM is reachable from any device on your tailnet — including phones and tablets. +That's it. Three commands to get a persistent Claude Code environment — whether you're provisioning a GCP VM or deploying to your own server. vybn uses Tailscale by default, so your VM is reachable from any device on your tailnet — including phones and tablets. diff --git a/docs/src/content/docs/troubleshooting.md b/docs/src/content/docs/troubleshooting.md index 11c2190..a893a9b 100644 --- a/docs/src/content/docs/troubleshooting.md +++ b/docs/src/content/docs/troubleshooting.md @@ -66,10 +66,14 @@ tailscale up The auth key may be invalid or expired. Generate a new one at the [Tailscale admin console](https://login.tailscale.com/admin/settings/keys). -You can also check the startup log directly via GCP: +You can also check the startup log directly: ```bash +# GCP provider — via GCP serial console gcloud compute ssh root@ -- cat /var/log/vybn-setup.log + +# SSH provider — via bootstrap SSH +ssh user@your-server cat /var/log/vybn-setup.log ``` ### "Host key verification failed" @@ -104,6 +108,43 @@ Re-authenticate with the Google Cloud SDK: gcloud auth login ``` +## SSH Provider Issues + +### "VYBN_SSH_HOST is not set" + +Set the host in `~/.vybnrc` or run `vybn init` to configure the SSH provider: + +```bash +vybn init +``` + +### Cannot connect to server via SSH + +Verify you can reach the server directly: + +```bash +ssh -o ConnectTimeout=10 user@your-server +``` + +Common causes: +- Wrong hostname, user, port, or key path +- Server firewall blocking your IP +- SSH service not running on the server + +### Setup script fails on the server + +The setup script requires root or sudo access. Check the log: + +```bash +ssh user@your-server cat /var/log/vybn-setup.log +``` + +Ensure the server runs Ubuntu 22.04+, Ubuntu 24.04, or Debian 12+. + +### "VM lifecycle is managed externally" + +`vybn start` and `vybn stop` are not available for the SSH provider. Start and stop your server directly through your hosting provider or OS tools. + ## Toolchain Issues ### "Unknown toolchain" error diff --git a/lib/check.sh b/lib/check.sh index ec1cd7b..158919a 100755 --- a/lib/check.sh +++ b/lib/check.sh @@ -8,43 +8,83 @@ main() { info "Checking prerequisites for provider=${VYBN_PROVIDER}, network=${VYBN_NETWORK}..." echo - # 1. gcloud CLI - if command -v gcloud &>/dev/null; then - success "gcloud CLI installed ($(gcloud version --format='value(Google Cloud SDK)' 2>/dev/null || echo 'unknown version'))" - else - error "gcloud CLI not found. Install: https://cloud.google.com/sdk/docs/install" - gcloud_available=false - failures=$((failures + 1)) - fi + if [[ "$VYBN_PROVIDER" == "ssh" ]]; then + # SSH provider checks + if command -v ssh &>/dev/null; then + success "SSH client installed" + else + error "SSH client not found. Install an OpenSSH client." + failures=$((failures + 1)) + fi - # 2. gcloud authenticated (requires gcloud) - if [[ "$gcloud_available" == true ]]; then - local account - account="$(gcloud auth list --filter='status:ACTIVE' --format='value(account)' 2>/dev/null || true)" - if [[ -n "$account" ]]; then - success "gcloud authenticated as ${account}" + if [[ -n "${VYBN_SSH_HOST:-}" ]]; then + success "VYBN_SSH_HOST is set: ${VYBN_SSH_HOST}" else - error "gcloud not authenticated. Run: gcloud auth login" + error "VYBN_SSH_HOST is not set. Set it in ~/.vybnrc or via environment." failures=$((failures + 1)) fi - fi - # 3. GCP project set - if [[ -n "$VYBN_PROJECT" ]]; then - success "GCP project: ${VYBN_PROJECT}" + if [[ -n "${VYBN_SSH_KEY:-}" ]]; then + if [[ -r "$VYBN_SSH_KEY" ]]; then + success "SSH key: ${VYBN_SSH_KEY}" + else + error "VYBN_SSH_KEY '${VYBN_SSH_KEY}' is not a readable file." + failures=$((failures + 1)) + fi + else + info "No VYBN_SSH_KEY set (will use SSH agent or default keys)." + fi + + # Test SSH connectivity + if [[ -n "${VYBN_SSH_HOST:-}" ]]; then + if _ssh_bootstrap_cmd "true" 2>/dev/null; then + success "SSH connection to ${VYBN_SSH_HOST} succeeded" + else + error "Cannot connect to ${VYBN_SSH_HOST} via SSH." + error "Check host, user (${VYBN_SSH_USER}), port (${VYBN_SSH_PORT}), and key settings." + failures=$((failures + 1)) + fi + fi else - error "No GCP project set. Run: gcloud config set project " - failures=$((failures + 1)) - fi + # GCP provider checks + # 1. gcloud CLI + if command -v gcloud &>/dev/null; then + success "gcloud CLI installed ($(gcloud version --format='value(Google Cloud SDK)' 2>/dev/null || echo 'unknown version'))" + else + error "gcloud CLI not found. Install: https://cloud.google.com/sdk/docs/install" + gcloud_available=false + failures=$((failures + 1)) + fi + + # 2. gcloud authenticated (requires gcloud) + if [[ "$gcloud_available" == true ]]; then + local account + account="$(gcloud auth list --filter='status:ACTIVE' --format='value(account)' 2>/dev/null || true)" + if [[ -n "$account" ]]; then + success "gcloud authenticated as ${account}" + else + error "gcloud not authenticated. Run: gcloud auth login" + failures=$((failures + 1)) + fi + fi - # 4. Compute Engine API enabled (requires gcloud) - if [[ "$gcloud_available" == true ]]; then - if gcloud services list --enabled --filter='name:compute.googleapis.com' --format='value(name)' 2>/dev/null | grep -q 'compute.googleapis.com'; then - success "Compute Engine API enabled" + # 3. GCP project set + if [[ -n "$VYBN_PROJECT" ]]; then + success "GCP project: ${VYBN_PROJECT}" else - error "Compute Engine API not enabled. Run: gcloud services enable compute.googleapis.com" + error "No GCP project set. Run: gcloud config set project " failures=$((failures + 1)) fi + + # 4. Compute Engine API enabled (requires gcloud) + if [[ "$gcloud_available" == true ]]; then + if gcloud services list --enabled --filter='name:compute.googleapis.com' --format='value(name)' 2>/dev/null | grep -q 'compute.googleapis.com'; then + success "Compute Engine API enabled" + else + error "Compute Engine API not enabled. Run: gcloud services enable compute.googleapis.com" + failures=$((failures + 1)) + fi + fi fi # 5. Network-specific checks diff --git a/lib/config.sh b/lib/config.sh index d96cb14..aa1dcb9 100755 --- a/lib/config.sh +++ b/lib/config.sh @@ -55,6 +55,12 @@ VYBN_TAILSCALE_HOSTNAME="${VYBN_TAILSCALE_HOSTNAME:-}" VYBN_TAILSCALE_TAGS="${VYBN_TAILSCALE_TAGS:-}" VYBN_SSH_KEY_DIR="${VYBN_SSH_KEY_DIR:-$HOME/.vybn/ssh}" +# SSH provider defaults +VYBN_SSH_HOST="${VYBN_SSH_HOST:-}" +VYBN_SSH_USER="${VYBN_SSH_USER:-$(whoami)}" +VYBN_SSH_KEY="${VYBN_SSH_KEY:-}" +VYBN_SSH_PORT="${VYBN_SSH_PORT:-22}" + # VM defaults VYBN_EXTERNAL_IP="${VYBN_EXTERNAL_IP:-false}" VYBN_CLAUDE_CODE_VERSION="${VYBN_CLAUDE_CODE_VERSION:-2.1.38}" @@ -91,6 +97,12 @@ if [[ -f "$HOME/.vybnrc" ]]; then source "$HOME/.vybnrc" fi +# Validate VYBN_SSH_PORT +if [[ -n "$VYBN_SSH_PORT" ]] && ! [[ "$VYBN_SSH_PORT" =~ ^[0-9]+$ ]]; then + echo "[error] Invalid VYBN_SSH_PORT: '${VYBN_SSH_PORT}'" >&2 + exit 1 +fi + # Validate VYBN_TOOLCHAINS (comma-separated lowercase names) if [[ -n "$VYBN_TOOLCHAINS" ]] && ! [[ "$VYBN_TOOLCHAINS" =~ ^[a-z][a-z0-9,]*$ ]]; then echo "[error] Invalid VYBN_TOOLCHAINS: '${VYBN_TOOLCHAINS}' (must be comma-separated lowercase names)" >&2 @@ -329,8 +341,10 @@ _validate_gcp_params() { require_provider() { _resolve_vm_name - _ensure_project - _validate_gcp_params + if [[ "$VYBN_PROVIDER" == "gcp" ]]; then + _ensure_project + _validate_gcp_params + fi provider_require_cli } diff --git a/lib/deploy.sh b/lib/deploy.sh index 5f11900..c4a5bf9 100755 --- a/lib/deploy.sh +++ b/lib/deploy.sh @@ -51,10 +51,12 @@ _estimate_cost() { main() { local skip_confirm=false local auto_connect=false + local script_only=false while [[ $# -gt 0 ]]; do case "$1" in -y|--yes) skip_confirm=true; shift ;; --connect) auto_connect=true; shift ;; + --script-only) script_only=true; shift ;; *) error "Unknown option: $1"; exit 1 ;; esac done @@ -64,28 +66,40 @@ main() { require_provider # --- Confirmation prompt --- - if [[ "$skip_confirm" != true ]]; then - local cost_estimate - cost_estimate="$(_estimate_cost)" - - info "Deploy summary:" - info " Project: ${VYBN_PROJECT}" - info " Zone: ${VYBN_ZONE}" - local _name_label="${VYBN_VM_NAME}" - if [[ "$_VYBN_NAME_AUTO" == true ]]; then - _name_label="${_name_label} (auto-generated)" - fi - info " VM name: ${_name_label}" - info " Machine type: ${VYBN_MACHINE_TYPE}" - info " Disk: ${VYBN_DISK_SIZE} GB SSD" - info " Network: ${VYBN_NETWORK}" - info " Toolchains: ${VYBN_TOOLCHAINS}" - if [[ "${VYBN_EXTERNAL_IP}" == "true" ]]; then - info " External IP: yes" + if [[ "$skip_confirm" != true ]] && [[ "$script_only" != true ]]; then + if [[ "$VYBN_PROVIDER" == "ssh" ]]; then + info "Deploy summary:" + info " Provider: ssh (bring your own VM)" + info " Host: ${VYBN_SSH_HOST}" + info " SSH user: ${VYBN_SSH_USER}" + if [[ "${VYBN_SSH_PORT}" != "22" ]]; then + info " SSH port: ${VYBN_SSH_PORT}" + fi + info " Network: ${VYBN_NETWORK}" + info " Toolchains: ${VYBN_TOOLCHAINS}" else - info " External IP: no" + local cost_estimate + cost_estimate="$(_estimate_cost)" + + info "Deploy summary:" + info " Project: ${VYBN_PROJECT}" + info " Zone: ${VYBN_ZONE}" + local _name_label="${VYBN_VM_NAME}" + if [[ "$_VYBN_NAME_AUTO" == true ]]; then + _name_label="${_name_label} (auto-generated)" + fi + info " VM name: ${_name_label}" + info " Machine type: ${VYBN_MACHINE_TYPE}" + info " Disk: ${VYBN_DISK_SIZE} GB SSD" + info " Network: ${VYBN_NETWORK}" + info " Toolchains: ${VYBN_TOOLCHAINS}" + if [[ "${VYBN_EXTERNAL_IP}" == "true" ]]; then + info " External IP: yes" + else + info " External IP: no" + fi + info " Est. cost: ${cost_estimate} (verify: cloud.google.com/compute/pricing)" fi - info " Est. cost: ${cost_estimate} (verify: cloud.google.com/compute/pricing)" echo read -rp "Continue? [y/N] " confirm if [[ "$confirm" != [yY] ]]; then @@ -95,21 +109,33 @@ main() { fi # Persist the resolved name so subsequent commands find this VM - _persist_vm_name + if [[ "$script_only" != true ]]; then + _persist_vm_name + fi - info "Deploying VM '${VYBN_VM_NAME}' in ${VYBN_ZONE}..." + if [[ "$script_only" != true ]]; then + if [[ "$VYBN_PROVIDER" == "ssh" ]]; then + info "Deploying to ${VYBN_SSH_HOST}..." + else + info "Deploying VM '${VYBN_VM_NAME}' in ${VYBN_ZONE}..." + fi - # --- Network setup (firewall rules, etc.) --- - net_setup + # --- Network setup (firewall rules, etc.) --- + net_setup + fi - # --- Check if VM already exists --- - if provider_vm_exists; then - error "VM '${VYBN_VM_NAME}' already exists. Use 'vybn destroy' first." - exit 1 + # --- Check if VM already exists (skip for ssh provider — the VM is pre-existing) --- + if [[ "$VYBN_PROVIDER" != "ssh" ]] && [[ "$script_only" != true ]]; then + if provider_vm_exists; then + error "VM '${VYBN_VM_NAME}' already exists. Use 'vybn destroy' first." + exit 1 + fi fi # --- Create VM --- - info "Creating VM (${VYBN_MACHINE_TYPE}, ${VYBN_DISK_SIZE}GB SSD)..." + if [[ "$VYBN_PROVIDER" != "ssh" ]]; then + info "Creating VM (${VYBN_MACHINE_TYPE}, ${VYBN_DISK_SIZE}GB SSD)..." + fi local base_script="${VYBN_DIR}/vm-setup/base.sh" local variant_script="${VYBN_DIR}/vm-setup/${VYBN_PROVIDER}-${VYBN_NETWORK}.sh" @@ -182,6 +208,13 @@ main() { } >> "$setup_script" fi + # --- Script-only mode: output and exit --- + if [[ "$script_only" == true ]]; then + cat "$setup_script" + rm -f "$setup_script" + return + fi + if ! provider_vm_create "$setup_script"; then rm -f "$setup_script" error "VM creation failed. Cleaning up network infrastructure..." @@ -191,69 +224,98 @@ main() { rm -f "$setup_script" # --- Wait for startup script --- - info "Waiting for startup script to complete..." - info "(This may take a few minutes on first deploy)" - - local attempts=0 - local max_attempts=60 - local start_time - start_time=$(date +%s) - while (( attempts < max_attempts )); do - local setup_result - setup_result="$(net_ssh_raw "$VYBN_USER" \ - "if [ -f /var/log/vybn-setup-complete ]; then echo done; \ - elif [ -f /var/log/vybn-setup-failed ]; then echo failed; \ - else echo pending; fi" 2>/dev/null)" || setup_result="unreachable" - - # Fallback: check GCP guest attributes when SSH is not available. - # This handles the Tailscale chicken-and-egg: SSH requires Tailscale, - # but Tailscale setup is part of the startup script. - if [[ "$setup_result" == "unreachable" ]]; then - local ga_status - ga_status="$(gcloud compute instances get-guest-attributes "$VYBN_VM_NAME" \ - --query-path=vybn/setup-status \ - --zone="$VYBN_ZONE" --project="$VYBN_PROJECT" \ - --format='value(value)' 2>/dev/null)" || ga_status="" - case "$ga_status" in - complete) setup_result="done" ;; - failed) setup_result="failed" ;; - esac + # For SSH provider, setup runs synchronously via provider_vm_create, + # so we just need to wait for Tailscale to come up. + if [[ "$VYBN_PROVIDER" == "ssh" ]]; then + info "Waiting for Tailscale to become reachable..." + local attempts=0 + local max_attempts=30 + local start_time + start_time=$(date +%s) + while (( attempts < max_attempts )); do + if net_ssh_raw "$VYBN_USER" "true" 2>/dev/null; then + break + fi + attempts=$((attempts + 1)) + local elapsed=$(( $(date +%s) - start_time )) + printf "\r$(_color 34)[info]$(_reset) Waiting for Tailscale SSH... (%s elapsed)" "$(format_duration "$elapsed")" + sleep 5 + done + printf "\n" + + if (( attempts >= max_attempts )); then + local elapsed=$(( $(date +%s) - start_time )) + warn "Tailscale SSH not reachable after $(format_duration "$elapsed")." + warn "The setup completed, but Tailscale may need time to connect." + warn "Check: tailscale status" + else + success "Tailscale SSH is reachable." fi + else + info "Waiting for startup script to complete..." + info "(This may take a few minutes on first deploy)" + + local attempts=0 + local max_attempts=60 + local start_time + start_time=$(date +%s) + while (( attempts < max_attempts )); do + local setup_result + setup_result="$(net_ssh_raw "$VYBN_USER" \ + "if [ -f /var/log/vybn-setup-complete ]; then echo done; \ + elif [ -f /var/log/vybn-setup-failed ]; then echo failed; \ + else echo pending; fi" 2>/dev/null)" || setup_result="unreachable" + + # Fallback: check GCP guest attributes when SSH is not available. + # This handles the Tailscale chicken-and-egg: SSH requires Tailscale, + # but Tailscale setup is part of the startup script. + if [[ "$setup_result" == "unreachable" ]]; then + local ga_status + ga_status="$(gcloud compute instances get-guest-attributes "$VYBN_VM_NAME" \ + --query-path=vybn/setup-status \ + --zone="$VYBN_ZONE" --project="$VYBN_PROJECT" \ + --format='value(value)' 2>/dev/null)" || ga_status="" + case "$ga_status" in + complete) setup_result="done" ;; + failed) setup_result="failed" ;; + esac + fi + + case "$setup_result" in + done) break ;; + failed) + printf "\n" + error "Startup script failed!" + if ! net_ssh_raw "$VYBN_USER" "tail -50 /var/log/vybn-setup.log" 2>/dev/null; then + warn "SSH not available. Fetching serial port output..." + gcloud compute instances get-serial-port-output "$VYBN_VM_NAME" \ + --zone="$VYBN_ZONE" --project="$VYBN_PROJECT" 2>/dev/null \ + | grep "^\[" | tail -30 || true + fi + exit 1 ;; + esac - case "$setup_result" in - done) break ;; - failed) - printf "\n" - error "Startup script failed!" - if ! net_ssh_raw "$VYBN_USER" "tail -50 /var/log/vybn-setup.log" 2>/dev/null; then - warn "SSH not available. Fetching serial port output..." - gcloud compute instances get-serial-port-output "$VYBN_VM_NAME" \ - --zone="$VYBN_ZONE" --project="$VYBN_PROJECT" 2>/dev/null \ - | grep "^\[" | tail -30 || true - fi - exit 1 ;; - esac - - attempts=$((attempts + 1)) - local elapsed=$(( $(date +%s) - start_time )) - printf "\r$(_color 34)[info]$(_reset) Waiting for VM setup... (%s elapsed)" "$(format_duration "$elapsed")" - sleep 10 - done - printf "\n" - - if (( attempts >= max_attempts )); then - local elapsed=$(( $(date +%s) - start_time )) - error "Startup script did not complete within $(format_duration "$elapsed")." - warn "Fetching setup log from VM..." - if ! net_ssh_raw "$VYBN_USER" "tail -30 /var/log/vybn-setup.log" 2>/dev/null; then - warn "SSH not available. Fetching serial port output..." - gcloud compute instances get-serial-port-output "$VYBN_VM_NAME" \ - --zone="$VYBN_ZONE" --project="$VYBN_PROJECT" 2>/dev/null \ - | grep "^\[" | tail -30 || true + attempts=$((attempts + 1)) + local elapsed=$(( $(date +%s) - start_time )) + printf "\r$(_color 34)[info]$(_reset) Waiting for VM setup... (%s elapsed)" "$(format_duration "$elapsed")" + sleep 10 + done + printf "\n" + + if (( attempts >= max_attempts )); then + local elapsed=$(( $(date +%s) - start_time )) + error "Startup script did not complete within $(format_duration "$elapsed")." + warn "Fetching setup log from VM..." + if ! net_ssh_raw "$VYBN_USER" "tail -30 /var/log/vybn-setup.log" 2>/dev/null; then + warn "SSH not available. Fetching serial port output..." + gcloud compute instances get-serial-port-output "$VYBN_VM_NAME" \ + --zone="$VYBN_ZONE" --project="$VYBN_PROJECT" 2>/dev/null \ + | grep "^\[" | tail -30 || true + fi + error "Deploy did not complete successfully. The VM may still be setting up." + error "Check progress: vybn ssh 'tail -f /var/log/vybn-setup.log'" + exit 1 fi - error "Deploy did not complete successfully. The VM may still be setting up." - error "Check progress: vybn ssh 'tail -f /var/log/vybn-setup.log'" - exit 1 fi success "Startup script completed." @@ -269,10 +331,15 @@ main() { if [[ "$VYBN_NETWORK" == "tailscale" ]]; then info "Fetching host key from VM..." local host_key - host_key="$(gcloud compute instances get-guest-attributes "$VYBN_VM_NAME" \ - --query-path=vybn/ssh-host-key-ed25519 \ - --zone="$VYBN_ZONE" --project="$VYBN_PROJECT" \ - --format='value(value)' 2>/dev/null)" || true + if [[ "$VYBN_PROVIDER" == "ssh" ]]; then + # Fetch host key via bootstrap SSH (no guest attributes for SSH provider) + host_key="$(_ssh_bootstrap_cmd "cat /etc/ssh/ssh_host_ed25519_key.pub" 2>/dev/null)" || true + else + host_key="$(gcloud compute instances get-guest-attributes "$VYBN_VM_NAME" \ + --query-path=vybn/ssh-host-key-ed25519 \ + --zone="$VYBN_ZONE" --project="$VYBN_PROJECT" \ + --format='value(value)' 2>/dev/null)" || true + fi if [[ -n "$host_key" ]]; then local key_dir="${VYBN_SSH_KEY_DIR:-$HOME/.vybn/ssh}" local hostname="${VYBN_TAILSCALE_HOSTNAME:-$VYBN_VM_NAME}" @@ -312,13 +379,14 @@ Creates a new VM with Claude Code pre-installed. Sets up: Options: -y, --yes Skip confirmation prompt --connect After deploy, connect to tmux session automatically + --script-only Output the assembled setup script to stdout and exit Configuration (via ~/.vybnrc or environment): VYBN_VM_NAME VM name (default: auto-generated) VYBN_ZONE GCP zone (default: us-west1-a) VYBN_MACHINE_TYPE Machine type (default: e2-standard-2) VYBN_DISK_SIZE Boot disk size in GB (default: 30) - VYBN_PROVIDER Cloud provider (default: gcp) + VYBN_PROVIDER Cloud provider (default: gcp; also: ssh) VYBN_NETWORK Network backend (default: tailscale) VYBN_EXTERNAL_IP Assign public IP to VM (default: false) VYBN_CLAUDE_CODE_VERSION Claude Code version to install (default: 2.1.38) @@ -327,5 +395,11 @@ Configuration (via ~/.vybnrc or environment): VYBN_APT_PACKAGES Extra apt packages to install on the VM VYBN_NPM_PACKAGES Extra global npm packages (requires node toolchain) VYBN_SETUP_SCRIPT Path to a custom setup script to run after all setup + +SSH provider (VYBN_PROVIDER=ssh): + VYBN_SSH_HOST Remote hostname or IP (required) + VYBN_SSH_USER SSH user for bootstrap connection (default: current user) + VYBN_SSH_KEY Path to SSH private key for bootstrap + VYBN_SSH_PORT SSH port for bootstrap connection (default: 22) EOF } diff --git a/lib/destroy.sh b/lib/destroy.sh index d1be209..0f4e868 100755 --- a/lib/destroy.sh +++ b/lib/destroy.sh @@ -13,9 +13,16 @@ main() { require_provider if [[ "$skip_confirm" != true ]]; then - warn "This will permanently delete:" - warn " - VM '${VYBN_VM_NAME}' and its boot disk" - warn " - Network infrastructure (firewall rules, etc.)" + if [[ "$VYBN_PROVIDER" == "ssh" ]]; then + warn "This will remove vybn from the remote host:" + warn " - Deregister from Tailscale" + warn " - Clean up local state files" + warn " (The remote server itself is not deleted.)" + else + warn "This will permanently delete:" + warn " - VM '${VYBN_VM_NAME}' and its boot disk" + warn " - Network infrastructure (firewall rules, etc.)" + fi echo read -rp "Type '${VYBN_VM_NAME}' to confirm destruction: " confirm if [[ "$confirm" != "$VYBN_VM_NAME" ]]; then @@ -24,42 +31,68 @@ main() { fi fi - # Delete VM - if provider_vm_exists; then - # Deregister from Tailscale before deleting the VM - local status - status="$(provider_vm_status)" - if [[ "$status" == "RUNNING" ]] && [[ "$VYBN_NETWORK" == "tailscale" ]]; then + if [[ "$VYBN_PROVIDER" == "ssh" ]]; then + # Deregister from Tailscale via Tailscale SSH (if reachable) + if [[ "$VYBN_NETWORK" == "tailscale" ]]; then info "Deregistering from Tailscale..." if timeout 30 net_ssh_raw "$VYBN_USER" "sudo tailscale logout" 2>/dev/null; then success "Device removed from tailnet." else - warn "Could not deregister Tailscale (VM may be unreachable)." + warn "Could not deregister Tailscale (server may be unreachable)." warn "You may need to manually remove the device from:" warn " https://login.tailscale.com/admin/machines" fi fi - info "Deleting VM '${VYBN_VM_NAME}'..." - if ! provider_vm_delete; then - error "Failed to delete VM '${VYBN_VM_NAME}'." - error "Network teardown skipped to avoid orphaning resources." - error "Check: gcloud compute instances list --zones=${VYBN_ZONE} --project=${VYBN_PROJECT}" - exit 1 - fi - success "VM deleted." + # Clean up local state + provider_vm_delete + + # Clean up state files so next deploy gets a fresh name + rm -f "$HOME/.vybn/tailscale-hostname" + rm -f "$HOME/.vybn/vm-name" + + # Tear down network infrastructure + net_teardown + + success "vybn resources cleaned up. Remote server was not modified." else - info "VM '${VYBN_VM_NAME}' not found (already deleted?)." - fi + # Delete VM + if provider_vm_exists; then + # Deregister from Tailscale before deleting the VM + local status + status="$(provider_vm_status)" + if [[ "$status" == "RUNNING" ]] && [[ "$VYBN_NETWORK" == "tailscale" ]]; then + info "Deregistering from Tailscale..." + if timeout 30 net_ssh_raw "$VYBN_USER" "sudo tailscale logout" 2>/dev/null; then + success "Device removed from tailnet." + else + warn "Could not deregister Tailscale (VM may be unreachable)." + warn "You may need to manually remove the device from:" + warn " https://login.tailscale.com/admin/machines" + fi + fi - # Clean up state files so next deploy gets a fresh name - rm -f "$HOME/.vybn/tailscale-hostname" - rm -f "$HOME/.vybn/vm-name" + info "Deleting VM '${VYBN_VM_NAME}'..." + if ! provider_vm_delete; then + error "Failed to delete VM '${VYBN_VM_NAME}'." + error "Network teardown skipped to avoid orphaning resources." + error "Check: gcloud compute instances list --zones=${VYBN_ZONE} --project=${VYBN_PROJECT}" + exit 1 + fi + success "VM deleted." + else + info "VM '${VYBN_VM_NAME}' not found (already deleted?)." + fi - # Tear down network infrastructure - net_teardown + # Clean up state files so next deploy gets a fresh name + rm -f "$HOME/.vybn/tailscale-hostname" + rm -f "$HOME/.vybn/vm-name" - success "All vybn resources destroyed." + # Tear down network infrastructure + net_teardown + + success "All vybn resources destroyed." + fi } cmd_help() { diff --git a/lib/init.sh b/lib/init.sh old mode 100644 new mode 100755 index 31b8bf0..5bd7410 --- a/lib/init.sh +++ b/lib/init.sh @@ -207,129 +207,205 @@ main() { fi # Collect all values into local variables. Nothing is written until final confirmation. - local cfg_network cfg_project cfg_zone cfg_vm_name cfg_machine_type cfg_disk_size + local cfg_provider cfg_network cfg_project cfg_zone cfg_vm_name cfg_machine_type cfg_disk_size local cfg_ts_authkey cfg_ts_hostname cfg_ts_tags + local cfg_ssh_host cfg_ssh_user cfg_ssh_key cfg_ssh_port local cfg_toolchains cfg_apt_packages cfg_npm_packages cfg_setup_script - # --- Section 1: Network Backend --- + # --- Section 1: Provider --- echo - echo "=== Network Backend ===" - _prompt cfg_network "Network backend (tailscale, iap)" "${VYBN_NETWORK}" \ - "^(tailscale|iap)$" "Must be 'tailscale' or 'iap'." - - # --- Section 2: GCP Settings --- + echo "=== Provider ===" + echo " 1) gcp — Create and manage a GCP VM" + echo " 2) ssh — Use an existing server (bring your own VM)" echo - echo "=== GCP Settings ===" - # Auto-detect project - local detected_project="${VYBN_PROJECT}" - if [[ -z "$detected_project" ]] && command -v gcloud &>/dev/null; then - detected_project="$(gcloud config get-value project 2>/dev/null)" || detected_project="" + local provider_default=1 + if [[ "${VYBN_PROVIDER}" == "ssh" ]]; then + provider_default=2 fi - _prompt cfg_project "GCP project" "$detected_project" \ - "^[a-z][a-z0-9:._-]+$" "Invalid project ID." - if [[ -z "$cfg_project" ]]; then - error "GCP project is required." - _init_cancelled=false - exit 1 + local provider_choice + while true; do + read -rp "Choice [${provider_default}]: " provider_choice + provider_choice="${provider_choice:-$provider_default}" + case "$provider_choice" in + 1) cfg_provider="gcp"; break ;; + 2) cfg_provider="ssh"; break ;; + *) warn "Please enter 1 or 2." ;; + esac + done + + # --- Section 2: Network Backend --- + echo + echo "=== Network Backend ===" + if [[ "$cfg_provider" == "ssh" ]]; then + info "SSH provider currently supports Tailscale only." + cfg_network="tailscale" + else + _prompt cfg_network "Network backend (tailscale, iap)" "${VYBN_NETWORK}" \ + "^(tailscale|iap)$" "Must be 'tailscale' or 'iap'." fi - _prompt cfg_zone "GCP zone" "${VYBN_ZONE}" \ - '^[a-z]+-[a-z]+[0-9]+-[a-z]$' "Invalid zone format (expected like: us-west1-a)." + # --- Provider-specific settings --- + cfg_ssh_host="" + cfg_ssh_user="" + cfg_ssh_key="" + cfg_ssh_port="" + cfg_project="" + cfg_zone="" + cfg_vm_name="" + cfg_machine_type="" + cfg_disk_size="" + + if [[ "$cfg_provider" == "ssh" ]]; then + # --- SSH Provider Settings --- + echo + echo "=== SSH Server ===" - # --- Section 3: VM Configuration --- - echo - echo "=== VM Configuration ===" + _prompt_required cfg_ssh_host "Server hostname or IP" \ + '^[a-zA-Z0-9._:-]+$' "Must be a valid hostname or IP address." - # VM name (optional — leave blank for auto-generate) - local vm_name_default="${VYBN_VM_NAME}" - _prompt cfg_vm_name "VM name (leave blank to auto-generate)" "$vm_name_default" + local ssh_user_default="${VYBN_SSH_USER:-$(whoami)}" + _prompt cfg_ssh_user "SSH user" "$ssh_user_default" \ + '^[a-zA-Z0-9._-]+$' "Must be a valid username." - # Validate VM name if provided - if [[ -n "$cfg_vm_name" ]]; then - while ! [[ "$cfg_vm_name" =~ ^[a-z][a-z0-9-]{0,61}[a-z0-9]$ ]] && \ - ! [[ "$cfg_vm_name" =~ ^[a-z]$ ]]; do - warn "Invalid VM name. Must be 1-63 chars: lowercase letters, digits, hyphens. Must start with a letter." - _prompt cfg_vm_name "VM name (leave blank to auto-generate)" "" - [[ -z "$cfg_vm_name" ]] && break - done - fi + local ssh_key_default="${VYBN_SSH_KEY:-}" + _prompt cfg_ssh_key "SSH private key path (blank for SSH agent)" "$ssh_key_default" + if [[ -n "$cfg_ssh_key" ]]; then + while [[ -n "$cfg_ssh_key" ]] && [[ ! -r "$cfg_ssh_key" ]]; do + warn "File not found or not readable: '${cfg_ssh_key}'" + _prompt cfg_ssh_key "SSH private key path (blank for SSH agent)" "" + done + fi - # Machine type menu - local -a machine_types=( - "e2-micro" - "e2-small" - "e2-medium" - "e2-standard-2" - "e2-standard-4" - "e2-standard-8" - "e2-highmem-2" - "e2-highmem-4" - ) - local -a machine_labels=( - "e2-micro 2 shared vCPU, 1 GB ~\$6/mo" - "e2-small 2 shared vCPU, 2 GB ~\$12/mo" - "e2-medium 2 shared vCPU, 4 GB ~\$25/mo" - "e2-standard-2 2 vCPU, 8 GB ~\$49/mo" - "e2-standard-4 4 vCPU, 16 GB ~\$97/mo" - "e2-standard-8 8 vCPU, 32 GB ~\$194/mo" - "e2-highmem-2 2 vCPU, 16 GB ~\$66/mo" - "e2-highmem-4 4 vCPU, 32 GB ~\$131/mo" - ) - - # Determine default selection based on current VYBN_MACHINE_TYPE - local default_machine_idx=4 - local i - for i in "${!machine_types[@]}"; do - if [[ "${machine_types[$i]}" == "$VYBN_MACHINE_TYPE" ]]; then - default_machine_idx=$((i + 1)) - break + local ssh_port_default="${VYBN_SSH_PORT:-22}" + _prompt cfg_ssh_port "SSH port" "$ssh_port_default" \ + '^[0-9]+$' "Must be a number." + + # VM name for Tailscale hostname + echo + echo "=== VM Identity ===" + local vm_name_default="${VYBN_VM_NAME}" + _prompt cfg_vm_name "VM name (leave blank to auto-generate)" "$vm_name_default" + + # Use reasonable defaults for GCP-only fields (not shown to user) + cfg_machine_type="${VYBN_MACHINE_TYPE}" + cfg_disk_size="${VYBN_DISK_SIZE}" + else + # --- GCP Settings --- + echo + echo "=== GCP Settings ===" + + # Auto-detect project + local detected_project="${VYBN_PROJECT}" + if [[ -z "$detected_project" ]] && command -v gcloud &>/dev/null; then + detected_project="$(gcloud config get-value project 2>/dev/null)" || detected_project="" fi - done + _prompt cfg_project "GCP project" "$detected_project" \ + "^[a-z][a-z0-9:._-]+$" "Invalid project ID." - echo - echo "Select a machine type:" - for i in "${!machine_labels[@]}"; do - local marker="" - if (( i + 1 == default_machine_idx )); then - marker=" <- default" + if [[ -z "$cfg_project" ]]; then + error "GCP project is required." + _init_cancelled=false + exit 1 fi - printf " %d) %s%s\n" "$((i + 1))" "${machine_labels[$i]}" "$marker" - done - echo " 9) Other (enter a machine type name)" - local machine_choice - while true; do - read -rp "Choice [${default_machine_idx}]: " machine_choice - machine_choice="${machine_choice:-$default_machine_idx}" + _prompt cfg_zone "GCP zone" "${VYBN_ZONE}" \ + '^[a-z]+-[a-z]+[0-9]+-[a-z]$' "Invalid zone format (expected like: us-west1-a)." - if [[ "$machine_choice" =~ ^[1-8]$ ]]; then - cfg_machine_type="${machine_types[$((machine_choice - 1))]}" - break - elif [[ "$machine_choice" == "9" ]]; then - _prompt cfg_machine_type "Machine type" "" \ - '^[a-z][a-z0-9-]+$' "Must be lowercase letters, digits, hyphens." - if [[ -z "$cfg_machine_type" ]]; then - warn "Machine type cannot be empty." - continue - fi - break - else - warn "Please enter a number between 1 and 9." + # --- VM Configuration --- + echo + echo "=== VM Configuration ===" + + # VM name (optional — leave blank for auto-generate) + local vm_name_default="${VYBN_VM_NAME}" + _prompt cfg_vm_name "VM name (leave blank to auto-generate)" "$vm_name_default" + + # Validate VM name if provided + if [[ -n "$cfg_vm_name" ]]; then + while ! [[ "$cfg_vm_name" =~ ^[a-z][a-z0-9-]{0,61}[a-z0-9]$ ]] && \ + ! [[ "$cfg_vm_name" =~ ^[a-z]$ ]]; do + warn "Invalid VM name. Must be 1-63 chars: lowercase letters, digits, hyphens. Must start with a letter." + _prompt cfg_vm_name "VM name (leave blank to auto-generate)" "" + [[ -z "$cfg_vm_name" ]] && break + done fi - done - _prompt cfg_disk_size "Boot disk size in GB" "${VYBN_DISK_SIZE}" + # Machine type menu + local -a machine_types=( + "e2-micro" + "e2-small" + "e2-medium" + "e2-standard-2" + "e2-standard-4" + "e2-standard-8" + "e2-highmem-2" + "e2-highmem-4" + ) + local -a machine_labels=( + "e2-micro 2 shared vCPU, 1 GB ~\$6/mo" + "e2-small 2 shared vCPU, 2 GB ~\$12/mo" + "e2-medium 2 shared vCPU, 4 GB ~\$25/mo" + "e2-standard-2 2 vCPU, 8 GB ~\$49/mo" + "e2-standard-4 4 vCPU, 16 GB ~\$97/mo" + "e2-standard-8 8 vCPU, 32 GB ~\$194/mo" + "e2-highmem-2 2 vCPU, 16 GB ~\$66/mo" + "e2-highmem-4 4 vCPU, 32 GB ~\$131/mo" + ) + + # Determine default selection based on current VYBN_MACHINE_TYPE + local default_machine_idx=4 + local i + for i in "${!machine_types[@]}"; do + if [[ "${machine_types[$i]}" == "$VYBN_MACHINE_TYPE" ]]; then + default_machine_idx=$((i + 1)) + break + fi + done + + echo + echo "Select a machine type:" + for i in "${!machine_labels[@]}"; do + local marker="" + if (( i + 1 == default_machine_idx )); then + marker=" <- default" + fi + printf " %d) %s%s\n" "$((i + 1))" "${machine_labels[$i]}" "$marker" + done + echo " 9) Other (enter a machine type name)" + + local machine_choice + while true; do + read -rp "Choice [${default_machine_idx}]: " machine_choice + machine_choice="${machine_choice:-$default_machine_idx}" + + if [[ "$machine_choice" =~ ^[1-8]$ ]]; then + cfg_machine_type="${machine_types[$((machine_choice - 1))]}" + break + elif [[ "$machine_choice" == "9" ]]; then + _prompt cfg_machine_type "Machine type" "" \ + '^[a-z][a-z0-9-]+$' "Must be lowercase letters, digits, hyphens." + if [[ -z "$cfg_machine_type" ]]; then + warn "Machine type cannot be empty." + continue + fi + break + else + warn "Please enter a number between 1 and 9." + fi + done - # Validate disk size - while ! [[ "$cfg_disk_size" =~ ^[0-9]+$ ]] || \ - (( cfg_disk_size < 10 || cfg_disk_size > 65536 )); do - warn "Disk size must be an integer between 10 and 65536." _prompt cfg_disk_size "Boot disk size in GB" "${VYBN_DISK_SIZE}" - done - # --- Section 4: Network-Specific --- + # Validate disk size + while ! [[ "$cfg_disk_size" =~ ^[0-9]+$ ]] || \ + (( cfg_disk_size < 10 || cfg_disk_size > 65536 )); do + warn "Disk size must be an integer between 10 and 65536." + _prompt cfg_disk_size "Boot disk size in GB" "${VYBN_DISK_SIZE}" + done + fi + + # --- Network-Specific Settings --- cfg_ts_authkey="" cfg_ts_hostname="" cfg_ts_tags="" @@ -452,28 +528,43 @@ main() { echo echo "=== Summary ===" - # Calculate cost estimate - local vm_cost disk_cost total_cost cost_display - vm_cost="$(_machine_type_cost "$cfg_machine_type")" - disk_cost=$(awk -v size="$cfg_disk_size" 'BEGIN {printf "%.0f", size * 0.17}') + echo " Provider: ${cfg_provider}" + echo " Network: ${cfg_network}" - if [[ -n "$vm_cost" ]]; then - total_cost=$((vm_cost + disk_cost)) - cost_display="~\$${total_cost}/mo" + if [[ "$cfg_provider" == "ssh" ]]; then + echo " Host: ${cfg_ssh_host}" + echo " SSH user: ${cfg_ssh_user}" + if [[ -n "$cfg_ssh_key" ]]; then + echo " SSH key: ${cfg_ssh_key}" + fi + if [[ "${cfg_ssh_port}" != "22" ]]; then + echo " SSH port: ${cfg_ssh_port}" + fi else - cost_display="~\$${disk_cost}/mo disk + unknown VM cost" + echo " GCP project: ${cfg_project}" + echo " Zone: ${cfg_zone}" + echo " Machine type: ${cfg_machine_type}" + echo " Disk: ${cfg_disk_size} GB SSD" + + # Calculate cost estimate + local vm_cost disk_cost total_cost cost_display + vm_cost="$(_machine_type_cost "$cfg_machine_type")" + disk_cost=$(awk -v size="$cfg_disk_size" 'BEGIN {printf "%.0f", size * 0.17}') + + if [[ -n "$vm_cost" ]]; then + total_cost=$((vm_cost + disk_cost)) + cost_display="~\$${total_cost}/mo" + else + cost_display="~\$${disk_cost}/mo disk + unknown VM cost" + fi + echo " Est. cost: ${cost_display}" fi - echo " Network: ${cfg_network}" - echo " GCP project: ${cfg_project}" - echo " Zone: ${cfg_zone}" if [[ -n "$cfg_vm_name" ]]; then echo " VM name: ${cfg_vm_name}" else echo " VM name: (auto-generated)" fi - echo " Machine type: ${cfg_machine_type}" - echo " Disk: ${cfg_disk_size} GB SSD" if [[ "$cfg_network" == "tailscale" ]]; then local masked_key masked_key="$(_mask_key "$cfg_ts_authkey")" @@ -491,7 +582,6 @@ main() { if [[ -n "$cfg_setup_script" ]]; then echo " Setup script: ${cfg_setup_script}" fi - echo " Est. cost: ${cost_display}" echo local confirm @@ -511,13 +601,38 @@ main() { # --- Provider and network --- -VYBN_PROVIDER="gcp" +VYBN_PROVIDER="${cfg_provider}" VYBN_NETWORK="${cfg_network}" +RCEOF + + if [[ "$cfg_provider" == "ssh" ]]; then + cat >> "$tmpfile" <> "$tmpfile" + else + echo "# VYBN_SSH_KEY=\"\"" >> "$tmpfile" + fi + if [[ "${cfg_ssh_port}" != "22" ]]; then + echo "VYBN_SSH_PORT=\"${cfg_ssh_port}\"" >> "$tmpfile" + else + echo "# VYBN_SSH_PORT=\"22\"" >> "$tmpfile" + fi + else + cat >> "$tmpfile" <> "$tmpfile" <> "$tmpfile" fi - cat >> "$tmpfile" <> "$tmpfile" <> "$tmpfile" </dev/null || echo 'No active tmux session'" 2>/dev/null || echo "SSH not available")" + echo "$tmux_out" + return + fi + # Check if VM exists if ! provider_vm_exists; then info "VM '${VYBN_VM_NAME}' does not exist." diff --git a/lib/stop.sh b/lib/stop.sh index c527a59..bd3816c 100755 --- a/lib/stop.sh +++ b/lib/stop.sh @@ -11,6 +11,12 @@ main() { done require_provider + + if [[ "$VYBN_PROVIDER" == "ssh" ]]; then + info "VM lifecycle is managed externally. Stop your server directly." + return + fi + require_vm_exists local status diff --git a/networks/tailscale.sh b/networks/tailscale.sh index cee8a46..d6ce3bf 100755 --- a/networks/tailscale.sh +++ b/networks/tailscale.sh @@ -68,7 +68,9 @@ _ts_ensure_ssh_key() { # # Set at source time (not inside net_setup) so the deploy summary reflects reality. # shellcheck disable=SC2034 # used by providers/*.sh and lib/deploy.sh -VYBN_EXTERNAL_IP="true" +if [[ "$VYBN_PROVIDER" != "ssh" ]]; then + VYBN_EXTERNAL_IP="true" +fi # --- Network Interface --- @@ -119,20 +121,23 @@ net_setup() { fi # Create deny-all firewall rule (Tailscale uses outbound NAT traversal, no inbound needed) - if ! gcloud compute firewall-rules describe vybn-deny-all-ingress \ - --project="$VYBN_PROJECT" &>/dev/null; then - info "Creating firewall rule: vybn-deny-all-ingress..." - _retry gcloud compute firewall-rules create vybn-deny-all-ingress \ - --project="$VYBN_PROJECT" \ - --direction=INGRESS \ - --action=DENY \ - --rules=all \ - --source-ranges=0.0.0.0/0 \ - --target-tags=vybn-vm \ - --priority=1000 \ - --description="Deny all inbound traffic to vybn VMs" &>/dev/null - else - info "Firewall rule vybn-deny-all-ingress already exists." + # Skip for SSH provider — user manages their own firewall + if [[ "$VYBN_PROVIDER" != "ssh" ]]; then + if ! gcloud compute firewall-rules describe vybn-deny-all-ingress \ + --project="$VYBN_PROJECT" &>/dev/null; then + info "Creating firewall rule: vybn-deny-all-ingress..." + _retry gcloud compute firewall-rules create vybn-deny-all-ingress \ + --project="$VYBN_PROJECT" \ + --direction=INGRESS \ + --action=DENY \ + --rules=all \ + --source-ranges=0.0.0.0/0 \ + --target-tags=vybn-vm \ + --priority=1000 \ + --description="Deny all inbound traffic to vybn VMs" &>/dev/null + else + info "Firewall rule vybn-deny-all-ingress already exists." + fi fi # Clear stale known_hosts entry for this hostname @@ -144,11 +149,14 @@ net_setup() { } net_teardown() { - if gcloud compute firewall-rules describe vybn-deny-all-ingress \ - --project="$VYBN_PROJECT" &>/dev/null; then - info "Deleting firewall rule 'vybn-deny-all-ingress'..." - _retry gcloud compute firewall-rules delete vybn-deny-all-ingress \ - --project="$VYBN_PROJECT" --quiet + # Skip firewall rule deletion for SSH provider — user manages their own firewall + if [[ "$VYBN_PROVIDER" != "ssh" ]]; then + if gcloud compute firewall-rules describe vybn-deny-all-ingress \ + --project="$VYBN_PROJECT" &>/dev/null; then + info "Deleting firewall rule 'vybn-deny-all-ingress'..." + _retry gcloud compute firewall-rules delete vybn-deny-all-ingress \ + --project="$VYBN_PROJECT" --quiet + fi fi # Device deregistration is handled in destroy.sh via `tailscale logout`. diff --git a/providers/ssh.sh b/providers/ssh.sh new file mode 100755 index 0000000..4c0c0f5 --- /dev/null +++ b/providers/ssh.sh @@ -0,0 +1,127 @@ +#!/usr/bin/env bash +# SSH provider backend for vybn — Bring Your Own VM +# Implements the provider_* interface for pre-existing servers. +# The user provides SSH credentials; vybn deploys the setup script over SSH. + +# --- Internal Helpers --- + +_ssh_bootstrap_opts() { + local opts=(-o StrictHostKeyChecking=accept-new -o ConnectTimeout=10 -o BatchMode=yes) + + if [[ -n "${VYBN_SSH_KEY:-}" ]]; then + opts+=(-i "$VYBN_SSH_KEY") + fi + + if [[ "${VYBN_SSH_PORT:-22}" != "22" ]]; then + opts+=(-p "$VYBN_SSH_PORT") + fi + + _BOOTSTRAP_SSH_OPTS=("${opts[@]}") +} + +_ssh_bootstrap_cmd() { + _ssh_bootstrap_opts + ssh "${_BOOTSTRAP_SSH_OPTS[@]}" "${VYBN_SSH_USER}@${VYBN_SSH_HOST}" "$@" +} + +_ssh_bootstrap_scp() { + local src="$1" dst="$2" + _ssh_bootstrap_opts + + local scp_opts=("${_BOOTSTRAP_SSH_OPTS[@]}") + # Convert -p to -P for scp + local i + for i in "${!scp_opts[@]}"; do + if [[ "${scp_opts[$i]}" == "-p" ]]; then + scp_opts[$i]="-P" + fi + done + + scp "${scp_opts[@]}" "$src" "${VYBN_SSH_USER}@${VYBN_SSH_HOST}:${dst}" +} + +# --- Provider Interface --- + +provider_require_cli() { + if ! command -v ssh &>/dev/null; then + error "ssh not found. Install an OpenSSH client." + exit 1 + fi + + if [[ -z "${VYBN_SSH_HOST:-}" ]]; then + error "VYBN_SSH_HOST is not set." + error "Set it in ~/.vybnrc or via environment: VYBN_SSH_HOST=your-server.example.com" + exit 1 + fi + + if [[ -n "${VYBN_SSH_KEY:-}" ]] && [[ ! -r "$VYBN_SSH_KEY" ]]; then + error "VYBN_SSH_KEY '${VYBN_SSH_KEY}' is not a readable file." + exit 1 + fi +} + +provider_detect_project() { + # No project concept for SSH provider + echo "" +} + +provider_vm_exists() { + # The VM always "exists" — the user manages it. + # After deploy, we also check for the local marker. + if [[ -f "$HOME/.vybn/ssh-provider-deployed" ]]; then + return 0 + fi + # Before deploy, still return true — the host is assumed to exist + return 0 +} + +provider_vm_status() { + # We can't check remote status — assume running + echo "RUNNING" +} + +provider_vm_info() { + echo " Provider: ssh (bring your own VM)" + echo " Host: ${VYBN_SSH_HOST}" + echo " SSH user: ${VYBN_SSH_USER}" + echo " SSH port: ${VYBN_SSH_PORT}" + if [[ -n "${VYBN_SSH_KEY:-}" ]]; then + echo " SSH key: ${VYBN_SSH_KEY}" + fi + if [[ -f "$HOME/.vybn/ssh-provider-deployed" ]]; then + echo " Status: deployed" + else + echo " Status: not yet deployed" + fi +} + +provider_vm_create() { + local setup_script="$1" + + info "Uploading setup script to ${VYBN_SSH_HOST}..." + _ssh_bootstrap_scp "$setup_script" "/tmp/vybn-setup.sh" + + info "Running setup script on ${VYBN_SSH_HOST}..." + info "(This may take several minutes)" + _ssh_bootstrap_cmd "chmod +x /tmp/vybn-setup.sh && sudo /tmp/vybn-setup.sh && rm -f /tmp/vybn-setup.sh" + + # Mark as deployed locally + mkdir -p "$HOME/.vybn" + touch "$HOME/.vybn/ssh-provider-deployed" +} + +provider_vm_start() { + error "VM lifecycle is managed externally. Start your server and run 'vybn connect'." + exit 1 +} + +provider_vm_stop() { + error "VM lifecycle is managed externally. Stop your server directly." + exit 1 +} + +provider_vm_delete() { + # Clean up local state only — never touch the remote server + info "Cleaning up local state (remote server is not modified)..." + rm -f "$HOME/.vybn/ssh-provider-deployed" +} diff --git a/vm-setup/base.sh b/vm-setup/base.sh index 48c9692..a03349a 100755 --- a/vm-setup/base.sh +++ b/vm-setup/base.sh @@ -176,6 +176,11 @@ set -g status-left "#[fg=colour46]#S #[fg=colour240]| " set -g status-right "#[fg=colour240]%H:%M" set -g status-left-length 30 setw -g window-status-current-style "fg=colour166,bold" +# Bell: highlight window tab when Claude Code is waiting for input +set -g visual-bell off +set -g bell-action other +setw -g monitor-bell on +set -g window-status-bell-style "fg=colour255,bg=colour196,bold" # Faster escape (for vim/claude) set -sg escape-time 10 TMUXEOF @@ -185,6 +190,53 @@ TMUXEOF fi } +setup_claude_hooks() { + local claude_dir="${CLAUDE_HOME}/.claude" + local settings="${claude_dir}/settings.json" + + mkdir -p "$claude_dir" + + if [[ -f "$settings" ]]; then + # Skip if notification hooks are already configured + if jq -e '.hooks.Notification' "$settings" &>/dev/null; then + log "Claude Code notification hooks already configured." + return + fi + # Merge notification hook into existing settings + local tmp + tmp="$(mktemp)" + jq --arg cmd "printf '\\a' > /dev/tty 2>/dev/null || true" ' + .hooks = (.hooks // {}) + { + "Notification": [{ + "matcher": "idle_prompt", + "hooks": [{"type": "command", "command": $cmd}] + }] + } + ' "$settings" > "$tmp" && mv "$tmp" "$settings" + else + cat > "$settings" << 'HOOKEOF' +{ + "hooks": { + "Notification": [ + { + "matcher": "idle_prompt", + "hooks": [ + { + "type": "command", + "command": "printf '\\a' > /dev/tty 2>/dev/null || true" + } + ] + } + ] + } +} +HOOKEOF + fi + + chown -R "${CLAUDE_USER}:${CLAUDE_USER}" "$claude_dir" + log "Claude Code notification hook configured (bell on idle)." +} + setup_ssh_hardening() { log "Hardening SSH configuration..." cat > /etc/ssh/sshd_config.d/99-vybn.conf << 'SSHDEOF' diff --git a/vm-setup/gcp-iap.sh b/vm-setup/gcp-iap.sh index 879bb7c..63e4dcb 100755 --- a/vm-setup/gcp-iap.sh +++ b/vm-setup/gcp-iap.sh @@ -19,6 +19,7 @@ setup_toolchains setup_claude_code setup_extra_packages setup_tmux +setup_claude_hooks setup_ssh_hardening setup_bashrc setup_complete diff --git a/vm-setup/gcp-tailscale.sh b/vm-setup/gcp-tailscale.sh index 7159eba..02602da 100755 --- a/vm-setup/gcp-tailscale.sh +++ b/vm-setup/gcp-tailscale.sh @@ -158,6 +158,7 @@ setup_toolchains setup_claude_code setup_extra_packages setup_tmux +setup_claude_hooks setup_ssh_hardening # Publish SSH host key to guest attributes for client-side pinning diff --git a/vm-setup/ssh-tailscale.sh b/vm-setup/ssh-tailscale.sh new file mode 100755 index 0000000..499c0cc --- /dev/null +++ b/vm-setup/ssh-tailscale.sh @@ -0,0 +1,157 @@ +# VM setup variant: SSH (bring your own VM) + Tailscale +# Appended after base.sh at deploy time — no shebang needed. +# Installs Tailscale for mesh networking + vybn SSH key. + +# No _publish_guest_attr override — base.sh no-op is fine for SSH provider. + +log "=== vybn VM setup starting (ssh + tailscale) ===" + +setup_system_packages +setup_user + +# --- Tailscale installation (via apt repo — avoids piping curl to sh) --- +log "Installing Tailscale..." +if ! command -v tailscale &>/dev/null; then + mkdir -p /usr/share/keyrings + chmod 0755 /usr/share/keyrings + curl -fsSL https://pkgs.tailscale.com/stable/ubuntu/noble.noarmor.gpg \ + -o /usr/share/keyrings/tailscale-archive-keyring.gpg + + # Verify GPG key fingerprint + EXPECTED_TS_FP="2596A99EAAB33821893C0A79458CA832957F5868" + ACTUAL_TS_FP="$(gpg --with-colons --import-options show-only --import \ + /usr/share/keyrings/tailscale-archive-keyring.gpg 2>/dev/null \ + | awk -F: '/^pub/{found=1} found && /^fpr/{print $10; exit}')" + if [[ "$ACTUAL_TS_FP" != "$EXPECTED_TS_FP" ]]; then + log "ERROR: Tailscale GPG key fingerprint mismatch (expected $EXPECTED_TS_FP, got $ACTUAL_TS_FP)" + exit 1 + fi + log "Tailscale GPG key verified: $EXPECTED_TS_FP" + + curl -fsSL https://pkgs.tailscale.com/stable/ubuntu/noble.tailscale-keyring.list \ + -o /etc/apt/sources.list.d/tailscale.list + apt-get update -qq + apt-get install -y -qq tailscale +else + log "Tailscale already installed." +fi + +# Read config from injected variables (set by deploy.sh header) +TS_AUTHKEY="${VYBN_TAILSCALE_AUTHKEY:-}" +if [[ -z "$TS_AUTHKEY" ]]; then + log "ERROR: No VYBN_TAILSCALE_AUTHKEY found in startup config." + log "Set VYBN_TAILSCALE_AUTHKEY in ~/.vybnrc and redeploy." + exit 1 +else + # Build tailscale up args + TS_ARGS=(--authkey="$TS_AUTHKEY" --ssh=false) + + # Always set hostname (petname from deploy, or fallback to system hostname) + TS_HOSTNAME="${VYBN_TAILSCALE_HOSTNAME:-$(hostname -s)}" + TS_ARGS+=(--hostname="$TS_HOSTNAME") + + # Optional: ACL tags + TS_TAGS="${VYBN_TAILSCALE_TAGS:-}" + if [[ -n "$TS_TAGS" ]]; then + TS_ARGS+=(--advertise-tags="$TS_TAGS") + fi + + log "Connecting to Tailscale..." + tailscale up "${TS_ARGS[@]}" + + # Verify Tailscale actually connected (authkey may be expired/invalid) + if ! tailscale status &>/dev/null; then + log "ERROR: Tailscale failed to connect. Auth key may be expired or invalid." + log "Generate a new key: https://login.tailscale.com/admin/settings/keys" + exit 1 + fi + log "Tailscale connected: $(tailscale ip -4 2>/dev/null || echo 'unknown IP')" +fi + +# --- Install vybn SSH public key --- +log "Installing vybn SSH key..." +VYBN_SSH_PUBKEY="${VYBN_SSH_PUBKEY:-}" +if [[ -n "$VYBN_SSH_PUBKEY" ]]; then + # Validate SSH public key format before writing to authorized_keys. + # Without this, a compromised value containing newlines could inject + # additional authorized_keys entries with OpenSSH options (e.g., command="...") + # to establish a persistent backdoor. + PUBKEY_LINE_COUNT="$(echo "$VYBN_SSH_PUBKEY" | wc -l)" + if [[ "$PUBKEY_LINE_COUNT" -ne 1 ]]; then + log "ERROR: SSH public key contains multiple lines — rejecting (possible injection)" + elif ! [[ "$VYBN_SSH_PUBKEY" =~ ^(ssh-ed25519|ssh-rsa|ecdsa-sha2-nistp[0-9]+|sk-ssh-ed25519@openssh\.com|sk-ecdsa-sha2-nistp256@openssh\.com)\ [A-Za-z0-9+/=]+( .+)?$ ]]; then + log "ERROR: SSH public key has invalid format — rejecting" + else + # Install for claude user only (root SSH access is unnecessary; + # the claude user has sudo if elevated access is needed) + CLAUDE_SSH_DIR="${CLAUDE_HOME}/.ssh" + mkdir -p "$CLAUDE_SSH_DIR" + chmod 700 "$CLAUDE_SSH_DIR" + + CLAUDE_AUTH_KEYS="${CLAUDE_SSH_DIR}/authorized_keys" + if ! grep -qF "$VYBN_SSH_PUBKEY" "$CLAUDE_AUTH_KEYS" 2>/dev/null; then + echo "$VYBN_SSH_PUBKEY" >> "$CLAUDE_AUTH_KEYS" + fi + chmod 600 "$CLAUDE_AUTH_KEYS" + chown -R "${CLAUDE_USER}:${CLAUDE_USER}" "$CLAUDE_SSH_DIR" + + log "SSH key installed for ${CLAUDE_USER}." + fi +else + log "WARNING: No VYBN_SSH_PUBKEY found in startup config." + log "SSH key-based auth will not work." +fi + +# --- Fetch SSH.id public keys (if configured) --- +VYBN_SSHID_USER="${VYBN_SSHID:-}" +if [[ -n "$VYBN_SSHID_USER" ]]; then + # Defense-in-depth: validate username format again on the VM + if ! [[ "$VYBN_SSHID_USER" =~ ^[a-zA-Z0-9_-]+$ ]]; then + log "ERROR: Invalid SSH.id username — skipping" + else + log "Fetching SSH keys from sshid.io/${VYBN_SSHID_USER}..." + SSHID_KEYS="$(curl -sf --max-time 10 "https://sshid.io/${VYBN_SSHID_USER}" || true)" + if [[ -z "$SSHID_KEYS" ]]; then + log "WARNING: Could not fetch keys from sshid.io — service may be unreachable." + log "SSH access via vybn-generated key still works. Use 'vybn add-key --sshid ${VYBN_SSHID_USER}' post-deploy." + else + # Ensure .ssh directory exists (may not if vybn-ssh-pubkey block was skipped) + CLAUDE_SSH_DIR="${CLAUDE_SSH_DIR:-${CLAUDE_HOME}/.ssh}" + CLAUDE_AUTH_KEYS="${CLAUDE_AUTH_KEYS:-${CLAUDE_SSH_DIR}/authorized_keys}" + mkdir -p "$CLAUDE_SSH_DIR" + chmod 700 "$CLAUDE_SSH_DIR" + + SSHID_COUNT=0 + while IFS= read -r line; do + # Strip trailing \r from HTTP responses with \r\n line endings + line="${line%$'\r'}" + # Skip blank lines and comments + [[ -z "$line" || "$line" == \#* ]] && continue + # Validate key format (standard + FIDO2 sk-* key types) + if ! [[ "$line" =~ ^(ssh-ed25519|ssh-rsa|ecdsa-sha2-nistp[0-9]+|sk-ssh-ed25519@openssh\.com|sk-ecdsa-sha2-nistp256@openssh\.com)\ [A-Za-z0-9+/=]+( .+)?$ ]]; then + log "WARNING: Skipping invalid key line from sshid.io: ${line:0:40}..." + continue + fi + # Append if not already present + if ! grep -qF "$line" "$CLAUDE_AUTH_KEYS" 2>/dev/null; then + echo "$line" >> "$CLAUDE_AUTH_KEYS" + SSHID_COUNT=$((SSHID_COUNT + 1)) + fi + done <<< "$SSHID_KEYS" + + chmod 600 "$CLAUDE_AUTH_KEYS" + chown -R "${CLAUDE_USER}:${CLAUDE_USER}" "$CLAUDE_SSH_DIR" + log "Installed ${SSHID_COUNT} key(s) from sshid.io/${VYBN_SSHID_USER}." + fi + fi +fi + +setup_toolchains +setup_claude_code +setup_extra_packages +setup_tmux +setup_claude_hooks +setup_ssh_hardening + +setup_bashrc +setup_complete diff --git a/vybn b/vybn index 60aab05..052b0d2 100755 --- a/vybn +++ b/vybn @@ -64,10 +64,14 @@ Configuration: VYBN_DISK_SIZE Boot disk size in GB (default: 30) VYBN_USER VM user (default: claude) VYBN_PROJECT GCP project (auto-detected from gcloud) - VYBN_PROVIDER Cloud provider (default: gcp) + VYBN_PROVIDER Cloud provider: gcp (default) or ssh (bring your own VM) VYBN_NETWORK Network backend (default: tailscale) VYBN_EXTERNAL_IP Assign public IP to VM (default: false) VYBN_SSHID SSH.id username for mobile key import + VYBN_SSH_HOST Remote host for ssh provider (required if VYBN_PROVIDER=ssh) + VYBN_SSH_USER SSH user for bootstrap (default: current user) + VYBN_SSH_KEY Path to SSH private key for bootstrap + VYBN_SSH_PORT SSH port for bootstrap (default: 22) VYBN_CLAUDE_CODE_VERSION Claude Code version (default: 2.1.38) VYBN_TOOLCHAINS Toolchain modules (default: node) VYBN_APT_PACKAGES Extra apt packages to install