diff --git a/CLAUDE.md b/CLAUDE.md index 33788f9..8dc0e94 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -16,7 +16,7 @@ go run ./cmd # run without building, e.g. go run ./cmd s go vet ./... # static checks ``` -There is no test suite (`go test ./...` finds nothing) and no linter/Makefile configured — `go build`/`go vet` are the only verification available. +`go test ./...` covers only a few pure functions so far; there's no linter/Makefile. Most changes are verified with `go build`/`go vet` and by running the CLI. Releases are cut with `scripts/release.sh [notes]`, which patches `internal/config.Version` via `sed`, cross-compiles for darwin/linux/windows, and generates `manifest.json` for the self-updater (see `docs/UPDATES.md` for the full update-distribution design). @@ -38,6 +38,8 @@ Releases are cut with `scripts/release.sh [notes]`, which patches `int **SSL** (`internal/ssl/manager.go`): a CA cert and per-domain certs are generated by running the `ghcr.io/aliasproject/openssl` image against the `alios_certs` volume (not via a Go TLS library) — self-signed, not Let's Encrypt, since `.test` domains are IANA-reserved and never publicly resolvable so ACME has no path to succeed. Per-project Caddy vhost files (`.caddyfile`) are written directly into the `alios_vhosts` volume, which is mounted at `/etc/caddy` in the `alios-reverse-proxy` container alongside a base `Caddyfile` (written by `services.Manager.Start`) that does `import /etc/caddy/*.caddyfile` — adding or removing a project is just adding/removing one file plus `caddy reload`, no full-file rewrite. There's no templating engine, just Go `fmt.Sprintf` strings. The base Caddyfile also has host-less `https://`/`http://` catch-all sites that serve a branded "No project here" 404 page (`internal/services/default_page.html`, embedded in the binary and written to `alios_vhosts/default/`) for any `*.test` host without a vhost. Its HTTPS side can't use a static cert (browsers reject a wildcard directly under a TLD like `*.test`), so it uses Caddy's on-demand internal issuer with the alios CA as its root (the `pki` global block; `ssl.Manager.PrepareCAForCaddy` makes the CA key readable to Caddy before start), minting an exact cert per requested host that chains to the already-trusted CA. +**Sharing** (`internal/share/manager.go`, `alios share`): exposes a project publicly through a Cloudflare Tunnel. A `cloudflared` container on `alios_internal` sends traffic to Caddy over plain HTTP, and a `.share.caddyfile` vhost matching the exact public host proxies it on to the project. That vhost file is the only record of a share's URL, mode and auth. The tunnel containers carry `alios.share.*` labels only so leftovers can be found and removed, and they're deliberately not global services, so `global restart` doesn't bounce them. Quick mode (default) runs one `alios_share_` container per share with a random trycloudflare.com URL. Named mode (`ALIOS_SHARE_TUNNEL_TOKEN` + `ALIOS_SHARE_DOMAIN`) runs one shared `alios_share` container whose `*.` ingress is configured in the Cloudflare dashboard. See `docs/SHARING.md`. + **Networking**: all alios containers share one Docker bridge network (`alios_internal`, see `config.GetNetworkConfig()`). The `alios_dns` container resolves `*.test` to the host so `https://.test` reaches Caddy, which reverse-proxies to `alios_php_` by container name (Caddy resolves Docker container names on the shared network natively — no explicit resolver directive needed). Project containers get `alios_dns`'s live container IP injected as their DNS server (resolved at container-creation time, not hardcoded) so they can resolve other `.test` domains from inside. **Self-update** (`internal/updater/updater.go`): checks GitHub Releases (private repo, needs `GITHUB_TOKEN`) first, then falls back to a public S3/R2-hosted `manifest.json`. Replaces the running binary atomically, escalating to `sudo`/Windows UAC if the install path isn't writable. diff --git a/docs/SHARING.md b/docs/SHARING.md new file mode 100644 index 0000000..fd1c54b --- /dev/null +++ b/docs/SHARING.md @@ -0,0 +1,74 @@ +# Sharing local sites (`alios share`) + +`alios share` gives the current project a public HTTPS URL through a Cloudflare Tunnel, so clients, teammates and your own phone can reach it without touching DNS, certificates or your router. + +```bash +alios share # public URL for the current project +alios share --auth demo:secret # same, behind HTTP basic auth +alios share list # every active share +alios share stop # stop sharing the current project +``` + +A share is also ended automatically by `alios stop`, `alios remove`, `alios pause`, `alios global stop` and `alios uninstall`. Shares are not restored by `alios resume`. `alios restart` and `alios global restart` keep the share and its URL. + +> **Anyone with the URL can reach your dev site**, including debug pages and error dumps. Use `--auth` for anything that isn't throwaway. + +## How it works + +``` +browser ──https──▶ Cloudflare edge ──tunnel──▶ cloudflared container + ──http──▶ alios-reverse-proxy (Caddy) ──▶ alios_php_:80 +``` + +- `cloudflared` runs in a container on the `alios_internal` network and forwards traffic to Caddy. +- Each share is a single vhost file, `.share.caddyfile`, in the `alios_vhosts` volume. It matches the public hostname exactly. +- That file is the only record of a share. `status`, `list`, `stop` and `doctor` all read it back. +- The app receives the public host in `Host` / `X-Forwarded-Host`, plus `X-Forwarded-Proto: https`. +- The visitor's IP arrives in `X-Real-IP` / `X-Forwarded-For`, taken from Cloudflare's `Cf-Connecting-Ip` header. +- Every shared request also carries `X-Alios-Share: 1`. Caddy sets it itself, so visitors can't forge or strip it. An image or app can check it to tell shared requests apart from local ones. + +## Quick tunnels (default) + +No account or setup is needed. Each share runs its own `alios_share_` container and gets a random `https://.trycloudflare.com` URL. + +- The URL changes every time you share. +- Cloudflare offers quick tunnels with no uptime guarantee. +- Quick tunnels allow about 200 concurrent requests and don't support Server-Sent Events. + +If the tunnel container dies (for example after a reboot), the share is shown as `[STALE]` in `alios status` and `alios doctor`. Run `alios share stop`, then `alios share` again. + +## Named tunnels (stable URLs) + +Set both of these to give every project a stable `https://.` URL: + +```bash +export ALIOS_SHARE_TUNNEL_TOKEN=eyJh... # tunnel token from the Cloudflare dashboard +export ALIOS_SHARE_DOMAIN=acme-dev.com +``` + +**One-time setup in the Cloudflare dashboard** (Zero Trust → Networks → Tunnels): + +1. Create a tunnel (cloudflared connector) and copy its token. +2. Add a **public hostname** `*.acme-dev.com` with service `HTTP` → `alios-reverse-proxy:80`. +3. Make sure a proxied wildcard DNS record `*` → `.cfargotunnel.com` exists in the zone. The dashboard normally creates it. + +How it runs: + +- All named shares share one `alios_share` container. +- That container is removed when the last named share stops. Leaving it running would bounce hosts that aren't shared through Caddy's http→https redirect in a loop. +- Project names are turned into a single DNS label, e.g. `michaelaguiar.dev` → `michaelaguiar-dev.acme-dev.com`. + +**Use a zone apex for `ALIOS_SHARE_DOMAIN`**, ideally a dedicated domain: + +- Cloudflare's free Universal SSL certificate only covers first-level wildcards (`*.acme-dev.com`). +- So `share.acme.com` would need a paid Advanced Certificate for `*.share.acme.com`. +- A dedicated domain also keeps the wildcard record from shadowing subdomains of your real site. + +To protect every named share with SSO instead of `--auth`, add a Cloudflare Access application for `*.acme-dev.com`. + +## Framework notes + +The CLI stays runtime-agnostic: it only sends standard forwarded headers, and never recreates the project container or injects env for sharing. How well an app copes with being served from a second hostname depends on the app: + +- **Laravel:** URLs are built from the request host, so shares mostly just work. Trust the proxy (`$middleware->trustProxies(at: '*')`) so `X-Forwarded-Proto` is honoured and links aren't generated as `http://`. Vite dev-server assets (`localhost:5173`) won't load remotely, so run `npm run build` before sharing. +- **WordPress:** not supported yet. `siteurl`/`home` are stored in the database, so WordPress redirects visitors back to `.test`. No fix has been settled on yet. diff --git a/internal/commands/doctor.go b/internal/commands/doctor.go index 7493289..a50b7dc 100644 --- a/internal/commands/doctor.go +++ b/internal/commands/doctor.go @@ -122,6 +122,7 @@ func (h *Handler) handleDoctor() error { h.doctorServices(r) h.doctorSSL(r) h.doctorProject(r, tokenOK) + h.doctorShare(r) return r.summary() } @@ -474,3 +475,42 @@ func probeHTTPS(url string) (int, error) { resp.Body.Close() return resp.StatusCode, nil } + +// doctorShare reports active shares and flags ones whose tunnel is gone, plus +// a half-configured named-tunnel setup (which silently falls back to quick +// tunnels). +func (h *Handler) doctorShare(r *doctorReport) { + r.section("SHARE") + + token, domain := h.config.ShareTunnelToken != "", h.config.ShareDomain != "" + switch { + case token && domain && !h.config.ShareDomainValid(): + r.fail(fmt.Sprintf("ALIOS_SHARE_DOMAIN %q isn't a valid domain, so Caddy will reject named shares", h.config.ShareDomain), + "set it to the bare domain, e.g. acme-dev.com") + case token && domain: + r.ok("Named tunnel configured (https://.%s)", h.config.ShareDomain) + case token != domain: + r.warn("Only one of ALIOS_SHARE_TUNNEL_TOKEN / ALIOS_SHARE_DOMAIN is set, so shares use quick tunnels", + "set both for stable named-tunnel URLs, or unset the other (see docs/SHARING.md)") + default: + r.info("Using quick tunnels (set ALIOS_SHARE_TUNNEL_TOKEN and ALIOS_SHARE_DOMAIN for stable URLs)") + } + + shares, err := h.share.List() + if err != nil { + r.warn(fmt.Sprintf("Could not read shares: %v", err), "") + return + } + if len(shares) == 0 { + r.info("No projects are shared") + return + } + for _, sh := range shares { + if h.share.TunnelRunning(sh) { + r.ok("%s shared at %s", sh.Project, sh.URL) + } else { + r.warn(fmt.Sprintf("%s has a share vhost but its tunnel isn't running", sh.Project), + fmt.Sprintf("cd into %s and run 'alios share stop' (then 'alios share' to reshare)", sh.Project)) + } + } +} diff --git a/internal/commands/handler.go b/internal/commands/handler.go index f0eedbe..097fa84 100644 --- a/internal/commands/handler.go +++ b/internal/commands/handler.go @@ -12,6 +12,7 @@ import ( "github.com/aliasproject/alios-cli/internal/github" "github.com/aliasproject/alios-cli/internal/project" "github.com/aliasproject/alios-cli/internal/services" + "github.com/aliasproject/alios-cli/internal/share" "github.com/aliasproject/alios-cli/internal/ssl" "github.com/aliasproject/alios-cli/internal/updater" "github.com/aliasproject/alios-cli/internal/utils" @@ -24,6 +25,7 @@ type Handler struct { projects *project.Manager services *services.Manager ssl *ssl.Manager + share *share.Manager github *github.Client updater *updater.Updater } @@ -37,6 +39,7 @@ func NewHandler(dockerClient *docker.Client, cfg *config.Config) *Handler { projects: project.NewManager(dockerClient), services: services.NewManager(dockerClient, sslManager), ssl: sslManager, + share: share.NewManager(dockerClient, cfg, sslManager), github: github.NewClient(cfg), updater: updater.New(), } @@ -123,6 +126,8 @@ func (h *Handler) Execute(args []string) error { return h.handleImage(commandArgs) case "env": return h.handleEnv(commandArgs) + case "share": + return h.handleShare(commandArgs) // Container interaction case "exec", "run": @@ -191,6 +196,9 @@ func (h *Handler) handleGlobalCommand(args []string) error { case "stop": fmt.Println(utils.Colorize("[STOPPING]", utils.ColorYellow) + " Stopping global services...") + // With Caddy down no share can be served, so end them rather than + // leave tunnels up that status would report as live. + h.stopAllSharesQuietly() if err := h.services.Stop(); err != nil { return fmt.Errorf("failed to stop services: %w", err) } @@ -415,6 +423,10 @@ func (h *Handler) handleUninstall() error { fmt.Println("🗑 Uninstalling Alios...") + // Shares first: the named tunnel restarts with Docker and would keep + // the Cloudflare connection open with no alios left to stop it. + h.stopAllSharesQuietly() + // Stop all services h.services.Stop() @@ -693,8 +705,15 @@ func (h *Handler) handleImage(args []string) error { return h.showProjectStatus(updated) } -// handleStop stops the current project +// handleStop stops the current project and ends its share. func (h *Handler) handleStop() error { + return h.stopProject(true) +} + +// stopProject stops the current project. A restart passes endShare=false: +// the tunnel points at Caddy, not the container, so the share keeps working +// (and keeps its URL) once the project is back up. +func (h *Handler) stopProject(endShare bool) error { project, err := h.projects.GetCurrentProject() if err != nil { return err @@ -706,16 +725,25 @@ func (h *Handler) handleStop() error { return fmt.Errorf("failed to stop project: %w", err) } + if endShare { + h.stopShareQuietly(project.Name) + } + fmt.Println(utils.Colorize("[SUCCESS]", utils.ColorGreen) + " Project stopped") return nil } // handleRestart restarts the current project func (h *Handler) handleRestart() error { - if err := h.handleStop(); err != nil { + if err := h.stopProject(false); err != nil { return err } - return h.handleStart() + if err := h.handleStart(); err != nil { + // The share was kept for the project coming back; it didn't. + h.stopShareQuietly(h.currentProjectName()) + return err + } + return nil } // handleRebuild forces the current project's container to be recreated from @@ -766,6 +794,8 @@ func (h *Handler) handleRemove() error { fmt.Printf(utils.Colorize("[WARNING]", utils.ColorYellow)+" Warning: Failed to remove vhost configuration: %v\n", err) } + h.stopShareQuietly(project.Name) + // Remove project if err := h.projects.Remove(true); err != nil { return fmt.Errorf("failed to remove project: %w", err) @@ -1382,6 +1412,9 @@ func (h *Handler) showStatus() error { if project.Status == "running" { fmt.Printf(" URL: %s\n", project.URL) } + if sh, err := h.share.Get(project.Name); err == nil && sh != nil { + fmt.Printf(" Shared: %s\n", formatShare(sh, h.share.TunnelRunning(sh))) + } } // Network information @@ -1468,6 +1501,9 @@ COMMANDS: env list Show env vars injected into the container env set K=V ... Set one or more env vars (recreates the container) env unset K ... Remove one or more env vars (recreates the container) + share [--auth u:p] Share the project at a public URL (Cloudflare Tunnel) + share stop Stop sharing the current project + share list List every active share Machine Lifecycle: pause Stop every alios container (projects + global services) @@ -1512,6 +1548,8 @@ EXAMPLES: alios image dockerfile # Switch to building from the project's Dockerfile alios env set APP_DEBUG=true DB_HOST=alios_mysql # Inject env vars alios env unset APP_DEBUG # Remove an env var + alios share # Get a public URL for the current project + alios share --auth demo:secret # Same, behind a username/password alios doctor # Diagnose why something isn't working alios check-update # Check for available updates alios update # Update to latest version diff --git a/internal/commands/pause.go b/internal/commands/pause.go index 24e2477..51d7679 100644 --- a/internal/commands/pause.go +++ b/internal/commands/pause.go @@ -14,6 +14,13 @@ import ( func (h *Handler) handlePause() error { fmt.Println(utils.Colorize("[STOPPING]", utils.ColorYellow) + " Pausing alios...") + // Shares aren't restored on resume: a quick tunnel would come back at a + // different URL anyway, so end them rather than leave stale vhosts. + stoppedShares, err := h.share.StopAll() + if err != nil { + fmt.Printf(utils.Colorize("[WARNING]", utils.ColorYellow)+" Warning: Failed to stop shares: %v\n", err) + } + stoppedProjects, err := h.projects.StopAll() if err != nil { return fmt.Errorf("failed to stop project containers: %w", err) @@ -38,6 +45,9 @@ func (h *Handler) handlePause() error { fmt.Println(utils.Colorize("[SUCCESS]", utils.ColorGreen) + " Alios paused") fmt.Printf(" %d project container(s) stopped\n", len(stoppedProjects)) fmt.Printf(" %d global service container(s) stopped\n", len(stoppedServices)) + if len(stoppedShares) > 0 { + fmt.Printf(" %d share(s) ended (run 'alios share' again after resuming)\n", len(stoppedShares)) + } fmt.Println("\nRun 'alios resume' when you're ready to start working again") return nil diff --git a/internal/commands/share.go b/internal/commands/share.go new file mode 100644 index 0000000..4be0e23 --- /dev/null +++ b/internal/commands/share.go @@ -0,0 +1,178 @@ +package commands + +import ( + "flag" + "fmt" + "os" + + "github.com/aliasproject/alios-cli/internal/share" + "github.com/aliasproject/alios-cli/internal/utils" +) + +// handleShare exposes the current project at a public URL through a +// Cloudflare Tunnel: +// +// alios share [--auth user:pass] +// alios share stop +// alios share list +func (h *Handler) handleShare(args []string) error { + if len(args) > 0 { + switch args[0] { + case "list", "ls": + return h.handleShareList() + case "stop": + return h.handleShareStop() + } + } + + fs := flag.NewFlagSet("share", flag.ContinueOnError) + fs.SetOutput(os.Stderr) + authFlag := fs.String("auth", "", "Protect the share with HTTP basic auth (user:password)") + + if err := fs.Parse(args); err != nil { + return fmt.Errorf("share: %w", err) + } + if fs.NArg() > 0 { + return fmt.Errorf("unknown share subcommand %q. Use: share [--auth user:pass] | share stop | share list", fs.Arg(0)) + } + + var creds *share.Credentials + if *authFlag != "" { + var err error + if creds, err = share.ParseCredentials(*authFlag); err != nil { + return err + } + } + + project, err := h.projects.GetCurrentProject() + if err != nil { + return err + } + if project.Status == "not initialized" { + return fmt.Errorf("project not initialized. Run 'alios start' first") + } + if project.Status != "running" { + return fmt.Errorf("project container is not running. Run 'alios start' first") + } + + mode := "quick tunnel" + if h.config.ShareNamedMode() { + mode = "named tunnel (" + h.config.ShareDomain + ")" + } + fmt.Printf(utils.Colorize("[STARTING]", utils.ColorCyan)+" Sharing '%s' via Cloudflare %s...\n", project.Name, mode) + + sh, started, err := h.share.Start(project.Name, creds) + if err != nil { + return fmt.Errorf("failed to share project: %w", err) + } + + if !started { + fmt.Println(utils.Colorize("[INFO]", utils.ColorBlue) + " Already shared") + if creds != nil { + fmt.Println(" --auth ignored for an existing share. Run 'alios share stop' first to change it") + } + } else { + fmt.Println(utils.Colorize("[SUCCESS]", utils.ColorGreen) + " Project shared") + } + + fmt.Printf("\n %s\n\n", utils.Colorize(sh.URL, utils.ColorGreen)) + + if sh.Auth { + fmt.Println(utils.Colorize("[WARNING]", utils.ColorYellow) + " This URL is reachable from the internet (protected by basic auth)") + } else { + fmt.Println(utils.Colorize("[WARNING]", utils.ColorYellow) + " Anyone with this URL can reach your dev site, including debug pages") + fmt.Println(" Use 'alios share --auth user:pass' to require a login") + } + if sh.Mode == share.ModeQuick { + fmt.Println(" Quick tunnel URLs change each time you share") + } + fmt.Println(" Run 'alios share stop' to stop sharing") + + return nil +} + +func (h *Handler) handleShareStop() error { + project, err := h.projects.GetCurrentProject() + if err != nil { + return err + } + + stopped, err := h.share.Stop(project.Name) + if err != nil { + return fmt.Errorf("failed to stop sharing: %w", err) + } + if !stopped { + fmt.Printf(utils.Colorize("[INFO]", utils.ColorBlue)+" '%s' is not shared\n", project.Name) + return nil + } + + fmt.Printf(utils.Colorize("[SUCCESS]", utils.ColorGreen)+" Stopped sharing '%s'\n", project.Name) + return nil +} + +func (h *Handler) handleShareList() error { + shares, err := h.share.List() + if err != nil { + return fmt.Errorf("failed to list shares: %w", err) + } + + if len(shares) == 0 { + fmt.Println("No projects are shared. Run 'alios share' in a project to share it") + return nil + } + + fmt.Printf("%d shared project(s):\n\n", len(shares)) + for _, sh := range shares { + fmt.Printf(" %s: %s\n", sh.Project, formatShare(sh, h.share.TunnelRunning(sh))) + } + return nil +} + +// stopShareQuietly ends a project's share as part of stopping or removing the +// project, so a share never outlives the site it points at. +func (h *Handler) stopShareQuietly(projectName string) { + if projectName == "" { + return + } + stopped, err := h.share.Stop(projectName) + if err != nil { + fmt.Printf(utils.Colorize("[WARNING]", utils.ColorYellow)+" Warning: Failed to stop sharing: %v\n", err) + return + } + if stopped { + fmt.Println(utils.Colorize("[INFO]", utils.ColorBlue) + " Stopped sharing") + } +} + +// stopAllSharesQuietly ends every share, for commands that take the whole +// stack down. +func (h *Handler) stopAllSharesQuietly() { + stopped, err := h.share.StopAll() + if err != nil { + fmt.Printf(utils.Colorize("[WARNING]", utils.ColorYellow)+" Warning: Failed to stop shares: %v\n", err) + } + if len(stopped) > 0 { + fmt.Printf(utils.Colorize("[INFO]", utils.ColorBlue)+" Stopped %d share(s)\n", len(stopped)) + } +} + +// currentProjectName returns the current directory's project name, or "" if +// it can't be determined. +func (h *Handler) currentProjectName() string { + if proj, err := h.projects.GetCurrentProject(); err == nil { + return proj.Name + } + return "" +} + +func formatShare(sh *share.Share, tunnelRunning bool) string { + line := sh.URL + " (" + sh.Mode + if sh.Auth { + line += ", basic auth" + } + line += ")" + if !tunnelRunning { + line += " " + utils.Colorize("[STALE]", utils.ColorRed) + " tunnel not running, run 'alios share stop'" + } + return line +} diff --git a/internal/config/config.go b/internal/config/config.go index e719c12..93cdabf 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -2,6 +2,7 @@ package config import ( "os" + "strings" "sync" ) @@ -36,6 +37,17 @@ type Config struct { // Features EnableSSL bool EnableDNS bool + + // Sharing (alios share). When both are set, shares use a named Cloudflare + // Tunnel with stable . hostnames instead of a + // throwaway trycloudflare.com quick tunnel. + ShareTunnelToken string + ShareDomain string +} + +// ShareNamedMode reports whether alios share should use a named tunnel. +func (c *Config) ShareNamedMode() bool { + return c.ShareTunnelToken != "" && c.ShareDomain != "" } // DatabaseConfig holds configuration for a database instance @@ -168,6 +180,36 @@ func (c *Config) loadFromEnvironment() { if autoStart := os.Getenv("ALIOS_AUTO_START_GLOBAL"); autoStart != "" { c.AutoStartGlobal = autoStart == "true" || autoStart == "1" } + + // Named-tunnel sharing + c.ShareTunnelToken = os.Getenv("ALIOS_SHARE_TUNNEL_TOKEN") + c.ShareDomain = normalizeShareDomain(os.Getenv("ALIOS_SHARE_DOMAIN")) +} + +// normalizeShareDomain accepts the forms people paste - "*.acme-dev.com" (the +// hostname Cloudflare's dashboard is set up with), "https://acme-dev.com/", +// ".acme-dev.com" - and reduces them to the bare domain. +func normalizeShareDomain(value string) string { + d := strings.ToLower(strings.TrimSpace(value)) + d = strings.TrimPrefix(d, "https://") + d = strings.TrimPrefix(d, "http://") + d = strings.TrimSuffix(d, "/") + d = strings.TrimPrefix(d, "*") + return strings.Trim(d, ".") +} + +// ShareDomainValid reports whether ShareDomain is a plausible hostname, so +// doctor can flag a typo before Caddy rejects the vhost built from it. +func (c *Config) ShareDomainValid() bool { + if c.ShareDomain == "" || !strings.Contains(c.ShareDomain, ".") { + return false + } + for _, r := range c.ShareDomain { + if !(r >= 'a' && r <= 'z' || r >= '0' && r <= '9' || r == '-' || r == '.') { + return false + } + } + return true } // GetGithubToken returns the GitHub token from environment variable diff --git a/internal/config/config_test.go b/internal/config/config_test.go new file mode 100644 index 0000000..c9a2da4 --- /dev/null +++ b/internal/config/config_test.go @@ -0,0 +1,16 @@ +package config + +import "testing" + +func TestNormalizeShareDomain(t *testing.T) { + for in, want := range map[string]string{ + "acme-dev.com": "acme-dev.com", + " *.acme-dev.com ": "acme-dev.com", + "https://acme-dev.com/": "acme-dev.com", + ".Acme-Dev.com": "acme-dev.com", + } { + if got := normalizeShareDomain(in); got != want { + t.Errorf("normalizeShareDomain(%q) = %q, want %q", in, got, want) + } + } +} diff --git a/internal/docker/client.go b/internal/docker/client.go index c09ab42..df73f06 100644 --- a/internal/docker/client.go +++ b/internal/docker/client.go @@ -157,6 +157,23 @@ func (c *Client) RunWithOutput(args ...string) (string, error) { return strings.TrimSpace(string(output)), nil } +// RunWithInput executes a docker command with input on its stdin and returns +// its output. Use it for secrets, which would show in `ps` as arguments. +func (c *Client) RunWithInput(input string, args ...string) (string, error) { + if err := c.CheckAvailability(); err != nil { + return "", err + } + + cmd := exec.Command(c.dockerPath, args...) + cmd.Stdin = strings.NewReader(input) + output, err := cmd.CombinedOutput() + if err != nil { + return "", fmt.Errorf("docker %s failed: %w\nOutput: %s", args[0], err, string(output)) + } + + return strings.TrimSpace(string(output)), nil +} + // RunInteractive executes a docker command with stdin/stdout/stderr attached func (c *Client) RunInteractive(args ...string) error { if err := c.CheckAvailability(); err != nil { @@ -767,6 +784,36 @@ func (c *Client) ReadFileFromVolume(volumeName, filePath string) (string, error) return output, nil } +// ListVolumeFiles returns the names of files at the root of a named Docker +// volume whose names match a shell glob (e.g. "*.share.caddyfile"), using a +// throwaway container. A glob with no matches returns an empty slice. +func (c *Client) ListVolumeFiles(volumeName, glob string) ([]string, error) { + output, err := c.RunWithOutput("run", "--rm", + "-v", volumeName+":/state", + "alpine:latest", + "sh", "-c", fmt.Sprintf("cd /state && for f in %s; do [ -f \"$f\" ] && echo \"$f\"; done; true", glob), + ) + if err != nil { + return nil, err + } + + if output == "" { + return []string{}, nil + } + + return strings.Split(output, "\n"), nil +} + +// RemoveFileFromVolume deletes a file from inside a named Docker volume, using +// a throwaway container. A file that doesn't exist is not an error. +func (c *Client) RemoveFileFromVolume(volumeName, filePath string) error { + return c.Run("run", "--rm", + "-v", volumeName+":/state", + "alpine:latest", + "rm", "-f", "/state/"+filePath, + ) +} + // Errors var ( ErrContainerNotFound = fmt.Errorf("container not found") diff --git a/internal/services/manager.go b/internal/services/manager.go index ed487a9..278f6f0 100644 --- a/internal/services/manager.go +++ b/internal/services/manager.go @@ -359,6 +359,13 @@ func (m *Manager) ListManagedContainers() ([]string, error) { if name == "" { continue } + // Share tunnels (alios_share, alios_share_) aren't global + // services: restarting a quick tunnel gives it a new public URL, which + // would leave its vhost pointing at a host nothing routes to. They're + // ended by `alios pause` and `alios share stop` instead. + if strings.HasPrefix(name, "alios_share") { + continue + } if globalServiceNames[name] || (strings.HasPrefix(name, "alios_") && !strings.HasPrefix(name, "alios_php_")) { managed = append(managed, name) } diff --git a/internal/share/manager.go b/internal/share/manager.go new file mode 100644 index 0000000..2377f7b --- /dev/null +++ b/internal/share/manager.go @@ -0,0 +1,552 @@ +// Package share exposes running projects to the internet through Cloudflare +// Tunnels (alios share). +// +// Traffic path: cloudflared (a container on alios_internal) -> Caddy +// (http://alios-reverse-proxy:80) -> alios_php_:80. Each share is one +// .share.caddyfile vhost in the alios_vhosts volume, matched on the +// exact public hostname so it wins over the base Caddyfile's http:// redirect +// catch-all. That vhost file is the only record of a share: status, list and +// stop all read it back, so there's no other state to keep in sync. +// +// Two modes: +// - quick (default): one alios_share_ container running a +// trycloudflare.com quick tunnel. No account needed; the URL is random and +// changes every time the tunnel starts. +// - named (ALIOS_SHARE_TUNNEL_TOKEN + ALIOS_SHARE_DOMAIN): one shared +// alios_share container running a remotely-managed tunnel whose +// `*.` public hostname points at Caddy, giving each project a +// stable https://. URL. +package share + +import ( + "crypto/sha256" + "encoding/hex" + "errors" + "fmt" + "regexp" + "sort" + "strings" + "time" + + "github.com/aliasproject/alios-cli/internal/config" + "github.com/aliasproject/alios-cli/internal/docker" + "github.com/aliasproject/alios-cli/internal/ssl" +) + +const ( + // Image is the cloudflared image tunnels run from. Pinned so a tunnel + // behaves the same on every machine; bump deliberately. + Image = "cloudflare/cloudflared:2026.9.3" + + // NamedContainer is the single shared container used in named mode. + NamedContainer = "alios_share" + + // ModeQuick and ModeNamed identify how a share is tunnelled. + ModeQuick = "quick" + ModeNamed = "named" + + vhostVolume = "alios_vhosts" + vhostSuffix = ".share.caddyfile" + proxyContainer = "alios-reverse-proxy" + proxyOrigin = "http://" + proxyContainer + ":80" + projectLabel = "alios.share.project" + modeLabel = "alios.share.mode" + tokenLabel = "alios.share.token_sha256" + quickURLTimeout = 30 * time.Second +) + +var quickURLPattern = regexp.MustCompile(`https://[a-z0-9-]+\.trycloudflare\.com`) + +// quickTunnelURL returns the share URL from cloudflared's log, skipping +// api.trycloudflare.com: cloudflared names that host in its error when it +// can't reach the quick-tunnel service (offline, DNS failure, outage). +func quickTunnelURL(logs string) string { + for _, url := range quickURLPattern.FindAllString(logs, -1) { + if url != "https://api.trycloudflare.com" { + return url + } + } + return "" +} + +// Credentials protect a share with HTTP basic auth. +type Credentials struct { + User string + Password string +} + +// ParseCredentials parses a "user:pass" --auth value. +func ParseCredentials(value string) (*Credentials, error) { + user, pass, ok := strings.Cut(value, ":") + if !ok || user == "" || pass == "" { + return nil, fmt.Errorf("invalid --auth value, expected user:password") + } + if strings.ContainsAny(user, " \t{}\"") { + return nil, fmt.Errorf("invalid --auth username %q: no spaces, braces or quotes", user) + } + return &Credentials{User: user, Password: pass}, nil +} + +// Share describes one active share. +type Share struct { + Project string + URL string + Mode string + Auth bool +} + +// Manager starts and stops project shares. +type Manager struct { + docker *docker.Client + config *config.Config + ssl *ssl.Manager +} + +// NewManager creates a share manager. +func NewManager(dockerClient *docker.Client, cfg *config.Config, sslManager *ssl.Manager) *Manager { + return &Manager{docker: dockerClient, config: cfg, ssl: sslManager} +} + +// QuickContainer is the tunnel container name for a quick-mode share. +func QuickContainer(projectName string) string { + return "alios_share_" + projectName +} + +// Get returns the project's active share, or nil if it isn't shared. +func (m *Manager) Get(projectName string) (*Share, error) { + content, err := m.docker.ReadFileFromVolume(vhostVolume, projectName+vhostSuffix) + if err == docker.ErrFileNotFound { + return nil, nil + } + if err != nil { + return nil, err + } + return parseVhost(projectName, content), nil +} + +// List returns every active share across all projects, sorted by project. +func (m *Manager) List() ([]*Share, error) { + files, err := m.docker.ListVolumeFiles(vhostVolume, "*"+vhostSuffix) + if err != nil { + return nil, err + } + + var shares []*Share + for _, file := range files { + share, err := m.Get(strings.TrimSuffix(file, vhostSuffix)) + if err != nil { + return nil, err + } + if share != nil { + shares = append(shares, share) + } + } + + sort.Slice(shares, func(i, j int) bool { return shares[i].Project < shares[j].Project }) + return shares, nil +} + +// TunnelRunning reports whether the tunnel container serving a share is up. +// A share whose tunnel is gone (e.g. after a reboot) is orphaned: its vhost +// still exists but nothing routes traffic to it. +func (m *Manager) TunnelRunning(share *Share) bool { + if share.Mode == ModeNamed { + return m.docker.IsContainerRunning(NamedContainer) + } + return m.docker.IsContainerRunning(QuickContainer(share.Project)) +} + +// Start shares a project and returns the share. If the project is already +// shared with a live tunnel, the existing share is returned and started is +// false; an orphaned share is torn down and replaced. +func (m *Manager) Start(projectName string, auth *Credentials) (share *Share, started bool, err error) { + existing, err := m.Get(projectName) + if err != nil { + return nil, false, fmt.Errorf("failed to read existing share: %w", err) + } + if existing != nil { + if m.TunnelRunning(existing) { + return existing, false, nil + } + if _, err := m.Stop(projectName); err != nil { + return nil, false, fmt.Errorf("failed to clean up stale share: %w", err) + } + } + + if !m.docker.IsContainerRunning(proxyContainer) { + return nil, false, fmt.Errorf("reverse proxy is not running. Run 'alios global start' first") + } + + // Hash before starting a tunnel so a bad password never leaves a + // public tunnel running without its auth. + var authLine string + if auth != nil { + hash, err := m.hashPassword(auth.Password) + if err != nil { + return nil, false, err + } + authLine = fmt.Sprintf(" basic_auth {\n %s %s\n }\n\n", auth.User, hash) + } + + if err := m.ensureImage(); err != nil { + return nil, false, err + } + + var host, mode string + if m.config.ShareNamedMode() { + mode = ModeNamed + host, err = m.namedHost(projectName) + if err != nil { + return nil, false, err + } + if err := m.ensureNamedTunnel(); err != nil { + return nil, false, err + } + } else { + mode = ModeQuick + host, err = m.startQuickTunnel(projectName) + if err != nil { + return nil, false, err + } + } + + if err := m.writeVhost(projectName, host, mode, authLine); err != nil { + m.teardownTunnel(projectName, mode) + return nil, false, err + } + + return &Share{Project: projectName, URL: "https://" + host, Mode: mode, Auth: auth != nil}, true, nil +} + +// Stop ends a project's share, removing its vhost and tunnel. Returns false if +// the project wasn't shared. +func (m *Manager) Stop(projectName string) (bool, error) { + share, err := m.Get(projectName) + if err != nil { + return false, err + } + + // A quick tunnel container can outlive its vhost if a previous start + // failed half-way; always clear it. + quickExisted := m.docker.ContainerExists(QuickContainer(projectName)) + if share == nil && !quickExisted { + return false, nil + } + + if share != nil { + if err := m.docker.RemoveFileFromVolume(vhostVolume, projectName+vhostSuffix); err != nil { + return false, fmt.Errorf("failed to remove share vhost: %w", err) + } + // Until Caddy reloads it keeps serving the old vhost from memory, so + // with a named tunnel still up for other shares the project would + // stay public. Report that rather than claiming the share ended. + if err := m.reloadCaddy(); err != nil { + m.teardownTunnel(projectName, share.Mode) + return false, fmt.Errorf("removed the share vhost but Caddy failed to reload, so it may still be served; run 'alios global restart': %w", err) + } + } + + mode := ModeQuick + if share != nil { + mode = share.Mode + } + m.teardownTunnel(projectName, mode) + if mode == ModeNamed { + m.docker.RemoveContainer(QuickContainer(projectName), true) + } + + return true, nil +} + +// StopAll ends every share and removes every tunnel container, including +// orphans. It keeps going past a share that fails to stop, so one bad share +// can't leave the others' tunnels running, and always sweeps the tunnel +// containers - with those gone no share is reachable, whatever else failed. +// Returns the projects whose shares ended, and every error joined. +func (m *Manager) StopAll() ([]string, error) { + var errs []error + var stopped []string + + shares, err := m.List() + if err != nil { + errs = append(errs, fmt.Errorf("failed to list shares: %w", err)) + } + for _, share := range shares { + if _, err := m.Stop(share.Project); err != nil { + errs = append(errs, fmt.Errorf("failed to stop share for %s: %w", share.Project, err)) + continue + } + stopped = append(stopped, share.Project) + } + + leftovers, err := m.docker.ListContainers("label=" + projectLabel) + if err != nil { + errs = append(errs, fmt.Errorf("failed to list tunnel containers: %w", err)) + } + for _, name := range leftovers { + if name == "" { + continue + } + if err := m.docker.RemoveContainer(name, true); err != nil { + errs = append(errs, fmt.Errorf("failed to remove tunnel container %s: %w", name, err)) + } + } + + return stopped, errors.Join(errs...) +} + +// PublicLabel turns a project name into a single DNS label, so a project named +// e.g. "michaelaguiar.dev" becomes "michaelaguiar-dev" rather than adding a +// subdomain level (which Cloudflare's free wildcard certificate won't cover). +func PublicLabel(projectName string) string { + var b strings.Builder + for _, r := range strings.ToLower(projectName) { + if (r >= 'a' && r <= 'z') || (r >= '0' && r <= '9') { + b.WriteRune(r) + } else { + b.WriteRune('-') + } + } + return strings.Trim(b.String(), "-") +} + +// namedHost returns the public host for a named-mode share, refusing one +// that isn't a valid DNS label or that another project's share already uses +// (PublicLabel maps both my_app and my.app to my-app). +func (m *Manager) namedHost(projectName string) (string, error) { + label := PublicLabel(projectName) + if label == "" || len(label) > 63 { + return "", fmt.Errorf("can't make a public hostname from project name %q (needs 1-63 letters, digits or dashes)", projectName) + } + host := label + "." + m.config.ShareDomain + + shares, err := m.List() + if err != nil { + return "", fmt.Errorf("failed to read existing shares: %w", err) + } + for _, other := range shares { + if other.Project != projectName && other.URL == "https://"+host { + return "", fmt.Errorf("https://%s is already used by the share for %s; stop that share first", host, other.Project) + } + } + return host, nil +} + +// tokenFingerprint identifies a tunnel token without storing it in a label. +func tokenFingerprint(token string) string { + sum := sha256.Sum256([]byte(token)) + return hex.EncodeToString(sum[:8]) +} + +func (m *Manager) ensureImage() error { + if m.docker.ImageExists(Image) { + return nil + } + if err := m.docker.PullImage(Image, nil); err != nil { + return fmt.Errorf("failed to pull %s: %w", Image, err) + } + return nil +} + +// startQuickTunnel runs a trycloudflare quick tunnel for the project and +// returns its public hostname, read from cloudflared's startup log. +func (m *Manager) startQuickTunnel(projectName string) (string, error) { + name := QuickContainer(projectName) + m.docker.RemoveContainer(name, true) + + err := m.docker.RunContainer(&docker.ContainerConfig{ + Name: name, + Image: Image, + Detached: true, + // A restarted quick tunnel gets a new URL, which would silently + // orphan the vhost - better for it to stay down and show as stale. + Restart: "no", + Network: config.GetNetworkConfig().BridgeName, + Labels: map[string]string{ + projectLabel: projectName, + modeLabel: ModeQuick, + }, + Command: []string{"tunnel", "--no-autoupdate", "--url", proxyOrigin}, + }) + if err != nil { + return "", fmt.Errorf("failed to start tunnel container: %w", err) + } + + deadline := time.Now().Add(quickURLTimeout) + var logs string + for time.Now().Before(deadline) { + logs, _ = m.docker.RunWithOutput("logs", name) + if url := quickTunnelURL(logs); url != "" { + return strings.TrimPrefix(url, "https://"), nil + } + if !m.docker.IsContainerRunning(name) { + break + } + time.Sleep(500 * time.Millisecond) + } + + m.docker.RemoveContainer(name, true) + return "", fmt.Errorf("tunnel did not report a public URL within %s. Last output:\n%s", quickURLTimeout, lastLines(logs, 10)) +} + +// ensureNamedTunnel makes sure the shared named-tunnel container is running. +// A container started with a different ALIOS_SHARE_TUNNEL_TOKEN (rotated +// since) is replaced rather than reused. +func (m *Manager) ensureNamedTunnel() error { + fingerprint := tokenFingerprint(m.config.ShareTunnelToken) + if info, err := m.docker.InspectContainer(NamedContainer); err == nil { + if info.Labels[tokenLabel] == fingerprint { + if info.State == "running" { + return nil + } + if err := m.docker.StartContainer(NamedContainer); err == nil { + return m.checkNamedTunnelUp() + } + } + m.docker.RemoveContainer(NamedContainer, true) + } + + err := m.docker.RunContainer(&docker.ContainerConfig{ + Name: NamedContainer, + Image: Image, + Detached: true, + Restart: "unless-stopped", + Network: config.GetNetworkConfig().BridgeName, + // cloudflared reads the token from env. It's still visible to anyone + // who can run `docker inspect`, as any container env is. + Environment: map[string]string{"TUNNEL_TOKEN": m.config.ShareTunnelToken}, + Labels: map[string]string{ + projectLabel: "", + modeLabel: ModeNamed, + tokenLabel: fingerprint, + }, + Command: []string{"tunnel", "--no-autoupdate", "run"}, + }) + if err != nil { + return fmt.Errorf("failed to start named tunnel container: %w", err) + } + + return m.checkNamedTunnelUp() +} + +// checkNamedTunnelUp waits out cloudflared's startup: it exits almost +// immediately on a bad token, so catch that here rather than leaving the user +// with a URL that never loads. +func (m *Manager) checkNamedTunnelUp() error { + time.Sleep(3 * time.Second) + if !m.docker.IsContainerRunning(NamedContainer) { + logs, _ := m.docker.RunWithOutput("logs", NamedContainer) + m.docker.RemoveContainer(NamedContainer, true) + return fmt.Errorf("named tunnel exited on startup (check ALIOS_SHARE_TUNNEL_TOKEN). Last output:\n%s", lastLines(logs, 10)) + } + + return nil +} + +// teardownTunnel removes the tunnel serving a share. In named mode the shared +// container is only removed once no share vhosts remain: left running with no +// matching vhost, requests would hit Caddy's http->https redirect and loop +// back through Cloudflare. +func (m *Manager) teardownTunnel(projectName, mode string) { + if mode != ModeNamed { + m.docker.RemoveContainer(QuickContainer(projectName), true) + return + } + + remaining, err := m.docker.ListVolumeFiles(vhostVolume, "*"+vhostSuffix) + if err != nil { + return + } + for _, file := range remaining { + if share, err := m.Get(strings.TrimSuffix(file, vhostSuffix)); err == nil && share != nil && share.Mode == ModeNamed { + return + } + } + m.docker.RemoveContainer(NamedContainer, true) +} + +func (m *Manager) writeVhost(projectName, host, mode, authLine string) error { + vhost := fmt.Sprintf(`# alios share: mode=%s +http://%s { +%s reverse_proxy alios_php_%s:80 { + header_up Host {host} + header_up X-Forwarded-Host {host} + header_up X-Forwarded-Proto https + header_up X-Real-IP {header.Cf-Connecting-Ip} + header_up X-Forwarded-For {header.Cf-Connecting-Ip} + # Tells the image or app that the request came through a share. + # Set here, so visitors can't forge or strip it. + header_up X-Alios-Share 1 + } + + # Scoped to upstream failures so basic_auth's 401 (and its + # WWW-Authenticate challenge) passes through untouched. + handle_errors 502 503 504 { + respond "Project unavailable" 503 + } +} +`, mode, host, authLine, projectName) + + if err := m.docker.WriteFileToVolume(vhostVolume, projectName+vhostSuffix, []byte(vhost)); err != nil { + return fmt.Errorf("failed to write share vhost: %w", err) + } + + if err := m.ssl.ReloadCaddy(); err != nil { + m.docker.RemoveFileFromVolume(vhostVolume, projectName+vhostSuffix) + m.reloadCaddy() + return fmt.Errorf("failed to reload Caddy: %w", err) + } + + return nil +} + +// reloadCaddy applies vhost changes. A stopped Caddy isn't serving anything, +// so there's nothing to reload. +func (m *Manager) reloadCaddy() error { + if m.docker.IsContainerRunning(proxyContainer) { + return m.ssl.ReloadCaddy() + } + return nil +} + +// hashPassword bcrypt-hashes a basic-auth password with Caddy's own tool, so +// alios doesn't need a bcrypt dependency. +func (m *Manager) hashPassword(password string) (string, error) { + // Sent on stdin rather than --plaintext, so it never shows in `ps`. + output, err := m.docker.RunWithInput(password+"\n", "exec", "-i", proxyContainer, "caddy", "hash-password") + if err != nil { + return "", fmt.Errorf("failed to hash --auth password: %w", err) + } + lines := strings.Split(strings.TrimSpace(output), "\n") + hash := strings.TrimSpace(lines[len(lines)-1]) + if !strings.HasPrefix(hash, "$2") { + return "", fmt.Errorf("unexpected output hashing --auth password: %s", output) + } + return hash, nil +} + +// parseVhost reads a share back out of the vhost file writeVhost produced. +func parseVhost(projectName, content string) *Share { + share := &Share{Project: projectName, Mode: ModeQuick} + for _, line := range strings.Split(content, "\n") { + line = strings.TrimSpace(line) + switch { + case strings.HasPrefix(line, "# alios share:") && strings.Contains(line, "mode="+ModeNamed): + share.Mode = ModeNamed + case strings.HasPrefix(line, "http://") && share.URL == "": + host := strings.TrimSpace(strings.TrimSuffix(strings.TrimPrefix(line, "http://"), "{")) + share.URL = "https://" + host + case strings.HasPrefix(line, "basic_auth"): + share.Auth = true + } + } + return share +} + +func lastLines(s string, n int) string { + lines := strings.Split(strings.TrimSpace(s), "\n") + if len(lines) > n { + lines = lines[len(lines)-n:] + } + return strings.Join(lines, "\n") +} diff --git a/internal/share/quickurl_test.go b/internal/share/quickurl_test.go new file mode 100644 index 0000000..7fc6a95 --- /dev/null +++ b/internal/share/quickurl_test.go @@ -0,0 +1,14 @@ +package share + +import "testing" + +func TestQuickTunnelURLSkipsAPIHost(t *testing.T) { + offline := `ERR Error requesting quick Tunnel error="failed to request quick Tunnel: Post \"https://api.trycloudflare.com/tunnel\": dial tcp: lookup api.trycloudflare.com: no such host"` + if got := quickTunnelURL(offline); got != "" { + t.Fatalf("offline log gave URL %q, want none", got) + } + ok := "INF | https://brave-otter-lamp-sun.trycloudflare.com |" + if got := quickTunnelURL(ok); got != "https://brave-otter-lamp-sun.trycloudflare.com" { + t.Fatalf("got %q", got) + } +}