Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ go run ./cmd <command> # 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 <version> [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).

Expand All @@ -38,6 +38,8 @@ Releases are cut with `scripts/release.sh <version> [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 (`<project>.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 `<project>.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_<project>` 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 `*.<domain>` 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://<project>.test` reaches Caddy, which reverse-proxies to `alios_php_<project>` 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.
Expand Down
74 changes: 74 additions & 0 deletions docs/SHARING.md
Original file line number Diff line number Diff line change
@@ -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_<project>:80
```

- `cloudflared` runs in a container on the `alios_internal` network and forwards traffic to Caddy.
- Each share is a single vhost file, `<project>.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_<project>` container and gets a random `https://<words>.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://<project>.<domain>` 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 `*` → `<tunnel-id>.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 `<project>.test`. No fix has been settled on yet.
40 changes: 40 additions & 0 deletions internal/commands/doctor.go
Original file line number Diff line number Diff line change
Expand Up @@ -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()
}
Expand Down Expand Up @@ -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://<project>.%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))
}
}
}
44 changes: 41 additions & 3 deletions internal/commands/handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand All @@ -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
}
Expand All @@ -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(),
}
Expand Down Expand Up @@ -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":
Expand Down Expand Up @@ -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)
}
Expand Down Expand Up @@ -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()

Expand Down Expand Up @@ -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
Expand All @@ -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
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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
Expand Down
10 changes: 10 additions & 0 deletions internal/commands/pause.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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
Expand Down
Loading