From c5c278952b3907638fc1f3883847dabccf360fe8 Mon Sep 17 00:00:00 2001 From: vvvomit Date: Sat, 24 Oct 2026 14:48:25 +0330 Subject: [PATCH] Initial commit: interzone TUI for matrix-docker-ansible-deploy Interactive wizard (Bubble Tea, Bubbles, Lip Gloss) that picks a homeserver, opts into any MDAD component, writes the inventory and runs the playbook. Supports in-country git, container registry, Docker, APT and PyPI mirrors for installing during an internet blackout. Co-Authored-By: Claude Opus 5.5 --- .gitignore | 3 + Makefile | 6 + README.md | 72 ++++ go.mod | 34 ++ go.sum | 58 ++++ internal/catalog/catalog.go | 421 ++++++++++++++++++++++++ internal/config/config.go | 200 ++++++++++++ internal/config/render.go | 294 +++++++++++++++++ internal/config/secrets.go | 82 +++++ internal/deploy/check.go | 124 +++++++ internal/deploy/deploy.go | 304 +++++++++++++++++ internal/ui/app.go | 210 ++++++++++++ internal/ui/form.go | 353 ++++++++++++++++++++ internal/ui/screens_components.go | 369 +++++++++++++++++++++ internal/ui/screens_deploy.go | 523 ++++++++++++++++++++++++++++++ internal/ui/screens_setup.go | 380 ++++++++++++++++++++++ internal/ui/theme.go | 125 +++++++ main.go | 38 +++ 18 files changed, 3596 insertions(+) create mode 100644 .gitignore create mode 100644 Makefile create mode 100644 README.md create mode 100644 go.mod create mode 100644 go.sum create mode 100644 internal/catalog/catalog.go create mode 100644 internal/config/config.go create mode 100644 internal/config/render.go create mode 100644 internal/config/secrets.go create mode 100644 internal/deploy/check.go create mode 100644 internal/deploy/deploy.go create mode 100644 internal/ui/app.go create mode 100644 internal/ui/form.go create mode 100644 internal/ui/screens_components.go create mode 100644 internal/ui/screens_deploy.go create mode 100644 internal/ui/screens_setup.go create mode 100644 internal/ui/theme.go create mode 100644 main.go diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..7de9456 --- /dev/null +++ b/.gitignore @@ -0,0 +1,3 @@ +/interzone +/vendor/ +/dist/ diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..28fb534 --- /dev/null +++ b/Makefile @@ -0,0 +1,6 @@ +VERSION ?= $(shell date +%Y.%m.%d) + +interzone: + CGO_ENABLED=0 go build -trimpath -ldflags "-s -w -X main.version=$(VERSION)" -o interzone . + +.PHONY: interzone diff --git a/README.md b/README.md new file mode 100644 index 0000000..1c424fd --- /dev/null +++ b/README.md @@ -0,0 +1,72 @@ +# interzone + +A friendly terminal wizard for +[matrix-docker-ansible-deploy](https://github.com/spantaleev/matrix-docker-ansible-deploy) +(MDAD). Pick a homeserver, tick the bridges, bots and services you want, and +interzone writes the inventory and runs the playbook for you, with a live +progress view. + +It is built to keep working during a **country-wide internet blackout**: +every download can come from mirrors inside the country. + +## Features + +- **Any homeserver:** Synapse, Continuwuity, Tuwunel, Conduit or Dendrite. + Synapse-only components are greyed out for the others. +- **Everything MDAD offers:** 82 components across clients, auth, storage, + bridges, bots, monitoring, backups and calls, with search (`/`). + Required settings are asked for; secrets are generated. +- **Blackout-ready.** Each source can be redirected: + + | What | Default | How it's used | + |---|---|---| + | Playbook git | `https://itsjustadream.g0th.ir/spantaleev/matrix-docker-ansible-deploy` | `git clone` / `git pull` | + | Ansible roles git | `https://itsjustadream.g0th.ir/` | `github.com` URLs in `requirements.yml` are rewritten with git `insteadOf`, so the playbook stays unmodified | + | Container images | `mechatok.g0th.ir/` | `matrix_container_global_registry_prefix_override` (every image, from every registry) | + | Docker Engine packages | – | `docker_repo_url` (mirror of `download.docker.com/linux`) | + | OS packages (APT) | – | Debian/Ubuntu sources on the server are rewritten (with backups) before install | + | PyPI | – | Installs Ansible into a private venv if it's missing | + + `ctrl+t` on the Network screen tests every source. +- **Certificates that work offline:** Let's Encrypt, a generated self-signed + wildcard certificate, your own certificate, or no HTTPS. +- **Install locally or over SSH.** +- **Remembers your answers** in `~/.config/interzone/config.json` (mode + `0600`). Re-run interzone to change anything. + +## Build + +```sh +make # static binary ./interzone +``` + +To build without internet, run `go mod vendor` while you still have access +and build with `go build -mod=vendor`. The resulting binary is static and has +no runtime dependencies besides `git`, `ssh` and Ansible (which interzone can +install itself from a PyPI mirror). + +## Use + +```sh +./interzone # start the wizard +./interzone --reset # forget saved answers +``` + +| Key | Action | +|---|---| +| `enter` / `↑↓` / `tab` | move through fields | +| `←→` / `space` | choose / toggle | +| `ctrl+n` / `ctrl+p` | next / previous step | +| `ctrl+r` | reveal secrets | +| `ctrl+s` | save answers | +| `esc` | back | + +On the Review screen, `enter` deploys and `s` only writes the files and prints +the `ansible-playbook` command to run later. + +Files: + +- playbook: `~/.local/share/interzone/matrix-docker-ansible-deploy` +- generated inventory: `/inventory/` +- last deployment log: `~/.config/interzone/last-deploy.log` +- self-signed certificates: `~/.config/interzone/ssl//` diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..67fb11c --- /dev/null +++ b/go.mod @@ -0,0 +1,34 @@ +module interzone + +go 1.27.1 + +require ( + github.com/charmbracelet/bubbles v0.21.1 + github.com/charmbracelet/bubbletea v1.3.10 + github.com/charmbracelet/lipgloss v1.1.0 + github.com/lucasb-eyer/go-colorful v1.3.0 +) + +require ( + github.com/atotto/clipboard v0.1.4 // indirect + github.com/aymanbagabas/go-osc52/v2 v2.0.1 // indirect + github.com/charmbracelet/colorprofile v0.4.1 // indirect + github.com/charmbracelet/harmonica v0.2.0 // indirect + github.com/charmbracelet/x/ansi v0.11.5 // indirect + github.com/charmbracelet/x/cellbuf v0.0.15 // indirect + github.com/charmbracelet/x/term v0.2.2 // indirect + github.com/clipperhouse/displaywidth v0.9.0 // indirect + github.com/clipperhouse/stringish v0.1.1 // indirect + github.com/clipperhouse/uax29/v2 v2.5.0 // indirect + github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f // indirect + github.com/mattn/go-isatty v0.0.20 // indirect + github.com/mattn/go-localereader v0.0.1 // indirect + github.com/mattn/go-runewidth v0.0.19 // indirect + github.com/muesli/ansi v0.0.0-20230316100256-276c6243b2f6 // indirect + github.com/muesli/cancelreader v0.2.2 // indirect + github.com/muesli/termenv v0.16.0 // indirect + github.com/rivo/uniseg v0.4.7 // indirect + github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e // indirect + golang.org/x/sys v0.38.0 // indirect + golang.org/x/text v0.3.8 // indirect +) diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..58f5a30 --- /dev/null +++ b/go.sum @@ -0,0 +1,58 @@ +github.com/MakeNowJust/heredoc v1.0.0 h1:cXCdzVdstXyiTqTvfqk9SDHpKNjxuom+DOlyEeQ4pzQ= +github.com/MakeNowJust/heredoc v1.0.0/go.mod h1:mG5amYoWBHf8vpLOuehzbGGw0EHxpZZ6lCpQ4fNJ8LE= +github.com/atotto/clipboard v0.1.4 h1:EH0zSVneZPSuFR11BlR9YppQTVDbh5+16AmcJi4g1z4= +github.com/atotto/clipboard v0.1.4/go.mod h1:ZY9tmq7sm5xIbd9bOK4onWV4S6X0u6GY7Vn0Yu86PYI= +github.com/aymanbagabas/go-osc52/v2 v2.0.1 h1:HwpRHbFMcZLEVr42D4p7XBqjyuxQH5SMiErDT4WkJ2k= +github.com/aymanbagabas/go-osc52/v2 v2.0.1/go.mod h1:uYgXzlJ7ZpABp8OJ+exZzJJhRNQ2ASbcXHWsFqH8hp8= +github.com/aymanbagabas/go-udiff v0.3.1 h1:LV+qyBQ2pqe0u42ZsUEtPiCaUoqgA9gYRDs3vj1nolY= +github.com/aymanbagabas/go-udiff v0.3.1/go.mod h1:G0fsKmG+P6ylD0r6N/KgQD/nWzgfnl8ZBcNLgcbrw8E= +github.com/charmbracelet/bubbles v0.21.1 h1:nj0decPiixaZeL9diI4uzzQTkkz1kYY8+jgzCZXSmW0= +github.com/charmbracelet/bubbles v0.21.1/go.mod h1:HHvIYRCpbkCJw2yo0vNX1O5loCwSr9/mWS8GYSg50Sk= +github.com/charmbracelet/bubbletea v1.3.10 h1:otUDHWMMzQSB0Pkc87rm691KZ3SWa4KUlvF9nRvCICw= +github.com/charmbracelet/bubbletea v1.3.10/go.mod h1:ORQfo0fk8U+po9VaNvnV95UPWA1BitP1E0N6xJPlHr4= +github.com/charmbracelet/colorprofile v0.4.1 h1:a1lO03qTrSIRaK8c3JRxJDZOvhvIeSco3ej+ngLk1kk= +github.com/charmbracelet/colorprofile v0.4.1/go.mod h1:U1d9Dljmdf9DLegaJ0nGZNJvoXAhayhmidOdcBwAvKk= +github.com/charmbracelet/harmonica v0.2.0 h1:8NxJWRWg/bzKqqEaaeFNipOu77YR5t8aSwG4pgaUBiQ= +github.com/charmbracelet/harmonica v0.2.0/go.mod h1:KSri/1RMQOZLbw7AHqgcBycp8pgJnQMYYT8QZRqZ1Ao= +github.com/charmbracelet/lipgloss v1.1.0 h1:vYXsiLHVkK7fp74RkV7b2kq9+zDLoEU4MZoFqR/noCY= +github.com/charmbracelet/lipgloss v1.1.0/go.mod h1:/6Q8FR2o+kj8rz4Dq0zQc3vYf7X+B0binUUBwA0aL30= +github.com/charmbracelet/x/ansi v0.11.5 h1:NBWeBpj/lJPE3Q5l+Lusa4+mH6v7487OP8K0r1IhRg4= +github.com/charmbracelet/x/ansi v0.11.5/go.mod h1:2JNYLgQUsyqaiLovhU2Rv/pb8r6ydXKS3NIttu3VGZQ= +github.com/charmbracelet/x/cellbuf v0.0.15 h1:ur3pZy0o6z/R7EylET877CBxaiE1Sp1GMxoFPAIztPI= +github.com/charmbracelet/x/cellbuf v0.0.15/go.mod h1:J1YVbR7MUuEGIFPCaaZ96KDl5NoS0DAWkskup+mOY+Q= +github.com/charmbracelet/x/term v0.2.2 h1:xVRT/S2ZcKdhhOuSP4t5cLi5o+JxklsoEObBSgfgZRk= +github.com/charmbracelet/x/term v0.2.2/go.mod h1:kF8CY5RddLWrsgVwpw4kAa6TESp6EB5y3uxGLeCqzAI= +github.com/clipperhouse/displaywidth v0.9.0 h1:Qb4KOhYwRiN3viMv1v/3cTBlz3AcAZX3+y9OLhMtAtA= +github.com/clipperhouse/displaywidth v0.9.0/go.mod h1:aCAAqTlh4GIVkhQnJpbL0T/WfcrJXHcj8C0yjYcjOZA= +github.com/clipperhouse/stringish v0.1.1 h1:+NSqMOr3GR6k1FdRhhnXrLfztGzuG+VuFDfatpWHKCs= +github.com/clipperhouse/stringish v0.1.1/go.mod h1:v/WhFtE1q0ovMta2+m+UbpZ+2/HEXNWYXQgCt4hdOzA= +github.com/clipperhouse/uax29/v2 v2.5.0 h1:x7T0T4eTHDONxFJsL94uKNKPHrclyFI0lm7+w94cO8U= +github.com/clipperhouse/uax29/v2 v2.5.0/go.mod h1:Wn1g7MK6OoeDT0vL+Q0SQLDz/KpfsVRgg6W7ihQeh4g= +github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f h1:Y/CXytFA4m6baUTXGLOoWe4PQhGxaX0KpnayAqC48p4= +github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f/go.mod h1:vw97MGsxSvLiUE2X8qFplwetxpGLQrlU1Q9AUEIzCaM= +github.com/lucasb-eyer/go-colorful v1.3.0 h1:2/yBRLdWBZKrf7gB40FoiKfAWYQ0lqNcbuQwVHXptag= +github.com/lucasb-eyer/go-colorful v1.3.0/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i7ruzyGqttikkLy0= +github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY= +github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= +github.com/mattn/go-localereader v0.0.1 h1:ygSAOl7ZXTx4RdPYinUpg6W99U8jWvWi9Ye2JC/oIi4= +github.com/mattn/go-localereader v0.0.1/go.mod h1:8fBrzywKY7BI3czFoHkuzRoWE9C+EiG4R1k4Cjx5p88= +github.com/mattn/go-runewidth v0.0.19 h1:v++JhqYnZuu5jSKrk9RbgF5v4CGUjqRfBm05byFGLdw= +github.com/mattn/go-runewidth v0.0.19/go.mod h1:XBkDxAl56ILZc9knddidhrOlY5R/pDhgLpndooCuJAs= +github.com/muesli/ansi v0.0.0-20230316100256-276c6243b2f6 h1:ZK8zHtRHOkbHy6Mmr5D264iyp3TiX5OmNcI5cIARiQI= +github.com/muesli/ansi v0.0.0-20230316100256-276c6243b2f6/go.mod h1:CJlz5H+gyd6CUWT45Oy4q24RdLyn7Md9Vj2/ldJBSIo= +github.com/muesli/cancelreader v0.2.2 h1:3I4Kt4BQjOR54NavqnDogx/MIoWBFa0StPA8ELUXHmA= +github.com/muesli/cancelreader v0.2.2/go.mod h1:3XuTXfFS2VjM+HTLZY9Ak0l6eUKfijIfMUZ4EgX0QYo= +github.com/muesli/termenv v0.16.0 h1:S5AlUN9dENB57rsbnkPyfdGuWIlkmzJjbFf0Tf5FWUc= +github.com/muesli/termenv v0.16.0/go.mod h1:ZRfOIKPFDYQoDFF4Olj7/QJbW60Ol/kL1pU3VfY/Cnk= +github.com/rivo/uniseg v0.4.7 h1:WUdvkW8uEhrYfLC4ZzdpI2ztxP1I582+49Oc5Mq64VQ= +github.com/rivo/uniseg v0.4.7/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88= +github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e h1:JVG44RsyaB9T2KIHavMF/ppJZNG9ZpyihvCd0w101no= +github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e/go.mod h1:RbqR21r5mrJuqunuUZ/Dhy/avygyECGrLceyNeo4LiM= +golang.org/x/exp v0.0.0-20231006140011-7918f672742d h1:jtJma62tbqLibJ5sFQz8bKtEM8rJBtfilJ2qTU199MI= +golang.org/x/exp v0.0.0-20231006140011-7918f672742d/go.mod h1:ldy0pHrwJyGW56pPQzzkH36rKxoZW1tw7ZJpeKx+hdo= +golang.org/x/sys v0.0.0-20210809222454-d867a43fc93e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.38.0 h1:3yZWxaJjBmCWXqhN1qh02AkOnCQ1poK6oF+a7xWL6Gc= +golang.org/x/sys v0.38.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks= +golang.org/x/text v0.3.8 h1:nAL+RVCQ9uMn3vJZbV+MRnydTJFPf8qqY42YiA6MrqY= +golang.org/x/text v0.3.8/go.mod h1:E6s5w1FMmriuDzIBO73fBruAKo1PCIq6d2Q6DHfQ8WQ= diff --git a/internal/catalog/catalog.go b/internal/catalog/catalog.go new file mode 100644 index 0000000..0066f79 --- /dev/null +++ b/internal/catalog/catalog.go @@ -0,0 +1,421 @@ +// Package catalog describes everything matrix-docker-ansible-deploy (MDAD) +// can install: homeserver implementations and optional components, together +// with the vars.yml variables each one needs. +package catalog + +// Kind controls how a field is edited in the UI and rendered into vars.yml. +type Kind int + +const ( + Text Kind = iota // quoted YAML string + Secret // quoted string, masked in the UI, auto-generated when empty + Hex64 // 64 hex characters, auto-generated when empty + Number // raw scalar + Bool // true/false + List // comma separated in the UI, YAML list in vars.yml + YAML // raw YAML block nested under the variable +) + +type Field struct { + Var string + Label string + Help string + Kind Kind + Default string + Required bool + // ShowIf names a Bool field of the same component that must be on for + // this field to be shown and written. + ShowIf string +} + +type Component struct { + ID string + Name string + Category string + Description string + EnableVar string + // DefaultOn components are enabled by MDAD unless explicitly disabled, + // so their enable variable is always written out. + DefaultOn bool + // Extra variables written verbatim when the component is enabled. + Extra map[string]string + Fields []Field + SynapseOnly bool + Status string // "", "unmaintained" or "deprecated" + Doc string + // Subdomain is the DNS label the component needs ("" if it lives on matrix.). + Subdomain string +} + +func (c Component) DocURL(base string) string { + return base + "/blob/master/docs/" + c.Doc +} + +type Homeserver struct { + ID string + Name string + Tagline string + Description string +} + +var Homeservers = []Homeserver{ + {"synapse", "Synapse", "the reference server · recommended", + "Most complete and best supported implementation. Every component in this tool works with it."}, + {"continuwuity", "Continuwuity", "lightweight Rust server", + "Community fork of conduwuit. Low memory use; some Synapse-only extras are hidden."}, + {"tuwunel", "Tuwunel", "lightweight Rust server", + "Enterprise-backed successor of conduwuit. Low memory use; some Synapse-only extras are hidden."}, + {"conduit", "Conduit", "minimal Rust server", + "The original Conduit. Very small footprint, fewer features."}, + {"dendrite", "Dendrite", "second-gen Go server", + "In maintenance mode upstream. Only pick this if you know you need it."}, +} + +var Categories = []string{ + "Core services", + "Clients", + "Authentication", + "File storage", + "Bridges", + "Bots", + "Administration", + "Calls & extras", +} + +// Components lists every component MDAD can still install. Removed ones are left out. +var Components = []Component{ + // ── Core services ────────────────────────────────────────────── + {ID: "coturn", Name: "Coturn TURN server", Category: "Core services", EnableVar: "coturn_enabled", DefaultOn: true, + Description: "Relays voice/video calls for users behind NAT. Strongly recommended.", Doc: "configuring-playbook-turn.md", + Fields: []Field{{Var: "coturn_turn_external_ip_addresses", Label: "Public IP address(es)", Help: "Leave empty to auto-detect (auto-detection needs internet).", Kind: List}}}, + {ID: "exim", Name: "Exim email relay", Category: "Core services", EnableVar: "exim_relay_enabled", DefaultOn: true, + Description: "Lets services send email (password resets, notifications).", Doc: "configuring-playbook-email.md", + Fields: []Field{ + {Var: "exim_relay_sender_address", Label: "Sender address", Help: "Leave empty for matrix@matrix..", Kind: Text}, + {Var: "exim_relay_relay_use", Label: "Relay through another SMTP server", Kind: Bool, Default: "false"}, + {Var: "exim_relay_relay_host_name", Label: "SMTP host", Kind: Text, ShowIf: "exim_relay_relay_use"}, + {Var: "exim_relay_relay_host_port", Label: "SMTP port", Kind: Number, Default: "587", ShowIf: "exim_relay_relay_use"}, + {Var: "exim_relay_relay_auth", Label: "SMTP needs authentication", Kind: Bool, Default: "false", ShowIf: "exim_relay_relay_use"}, + {Var: "exim_relay_relay_auth_username", Label: "SMTP username", Kind: Text, ShowIf: "exim_relay_relay_auth"}, + {Var: "exim_relay_relay_auth_password", Label: "SMTP password", Kind: Secret, ShowIf: "exim_relay_relay_auth"}, + }}, + {ID: "base-domain", Name: "Serve the base domain", Category: "Core services", EnableVar: "matrix_static_files_container_labels_base_domain_enabled", + Description: "Host a simple page and .well-known files on itself (only if nothing else runs there).", Doc: "configuring-playbook-base-domain-serving.md"}, + {ID: "ddclient", Name: "Dynamic DNS (ddclient)", Category: "Core services", EnableVar: "ddclient_enabled", + Description: "Keep DNS records updated when your server has a changing IP.", Doc: "configuring-playbook-dynamic-dns.md", + Fields: []Field{{Var: "ddclient_domain_configurations", Label: "Provider configuration", Kind: YAML, Required: true, + Default: "- provider: example.net\n protocol: dyndns2\n username: YOUR_USERNAME_HERE\n password: YOUR_PASSWORD_HERE\n domain: \"{{ matrix_domain }}\""}}}, + {ID: "external-postgres", Name: "Use external PostgreSQL", Category: "Core services", EnableVar: "", + Description: "Use your own Postgres server instead of the bundled one.", Doc: "configuring-playbook-external-postgres.md", + Extra: map[string]string{"postgres_enabled": "false"}, + Fields: []Field{ + {Var: "matrix_synapse_database_host", Label: "Database host", Kind: Text, Required: true}, + {Var: "matrix_synapse_database_user", Label: "Database user", Kind: Text, Required: true}, + {Var: "matrix_synapse_database_password", Label: "Database password", Kind: Text, Required: true}, + {Var: "matrix_synapse_database_database", Label: "Database name", Kind: Text, Default: "synapse"}, + }}, + {ID: "telemetry", Name: "Report anonymous usage stats", Category: "Core services", EnableVar: "matrix_synapse_report_stats", + Description: "Send anonymous statistics to matrix.org (needs internet).", Doc: "configuring-playbook-telemetry.md", SynapseOnly: true}, + + // ── Clients ──────────────────────────────────────────────────── + {ID: "element", Name: "Element Web", Category: "Clients", EnableVar: "matrix_client_element_enabled", DefaultOn: true, Subdomain: "element", + Description: "The flagship Matrix web client.", Doc: "configuring-playbook-client-element-web.md"}, + {ID: "cinny", Name: "Cinny", Category: "Clients", EnableVar: "cinny_enabled", Subdomain: "cinny", + Description: "A simple, elegant web client.", Doc: "configuring-playbook-client-cinny.md"}, + {ID: "sable", Name: "Sable", Category: "Clients", EnableVar: "sable_enabled", Subdomain: "sable", + Description: "Web client focused on a clean, elegant interface.", Doc: "configuring-playbook-client-sable.md"}, + {ID: "hydrogen", Name: "Hydrogen", Category: "Clients", EnableVar: "hydrogen_enabled", Subdomain: "hydrogen", + Description: "Lightweight client with legacy and mobile browser support.", Doc: "configuring-playbook-client-hydrogen.md"}, + {ID: "schildichat", Name: "SchildiChat Web", Category: "Clients", EnableVar: "matrix_client_schildichat_enabled", Subdomain: "schildichat", + Description: "Element-based client with extras and tweaks.", Doc: "configuring-playbook-client-schildichat-web.md"}, + {ID: "fluffychat", Name: "FluffyChat Web", Category: "Clients", EnableVar: "matrix_client_fluffychat_enabled", Subdomain: "fluffychat", + Description: "A cute cross-platform messenger written in Flutter.", Doc: "configuring-playbook-client-fluffychat-web.md"}, + {ID: "commet", Name: "Commet", Category: "Clients", EnableVar: "matrix_client_commet_enabled", Subdomain: "commet", + Description: "A feature-rich Matrix web client.", Doc: "configuring-playbook-client-commet.md"}, + + // ── Authentication ───────────────────────────────────────────── + {ID: "mas", Name: "Matrix Authentication Service", Category: "Authentication", EnableVar: "matrix_authentication_service_enabled", SynapseOnly: true, + Description: "Next-generation OAuth 2.0/OIDC login (required by Element X for some flows).", Doc: "configuring-playbook-matrix-authentication-service.md"}, + {ID: "double-puppet", Name: "Appservice Double Puppet", Category: "Authentication", EnableVar: "matrix_appservice_double_puppet_enabled", + Description: "Lets bridges show your messages sent from other apps as coming from you.", Doc: "configuring-playbook-appservice-double-puppet.md"}, + {ID: "ketesa", Name: "Ketesa admin panel", Category: "Authentication", EnableVar: "matrix_ketesa_enabled", SynapseOnly: true, + Description: "Web UI for managing users, rooms and media (synapse-admin successor).", Doc: "configuring-playbook-ketesa.md"}, + {ID: "element-admin", Name: "Element Admin", Category: "Authentication", EnableVar: "matrix_element_admin_enabled", + Description: "Element's admin web app. Works best together with MAS.", Doc: "configuring-playbook-element-admin.md", Subdomain: "admin.element"}, + {ID: "rest-auth", Name: "REST auth password provider", Category: "Authentication", EnableVar: "matrix_synapse_ext_password_provider_rest_auth_enabled", SynapseOnly: true, + Description: "Authenticate users against your own REST endpoint.", Doc: "configuring-playbook-rest-auth.md", + Fields: []Field{{Var: "matrix_synapse_ext_password_provider_rest_auth_endpoint", Label: "Endpoint URL", Kind: Text, Required: true}}}, + {ID: "shared-secret-auth", Name: "Shared Secret Auth", Category: "Authentication", EnableVar: "matrix_synapse_ext_password_provider_shared_secret_auth_enabled", SynapseOnly: true, + Description: "Log in as any user with a shared secret (used by bots and integrations).", Doc: "configuring-playbook-shared-secret-auth.md", + Fields: []Field{{Var: "matrix_synapse_ext_password_provider_shared_secret_auth_shared_secret", Label: "Shared secret", Kind: Secret, Required: true}}}, + {ID: "ldap-auth", Name: "LDAP auth password provider", Category: "Authentication", EnableVar: "matrix_synapse_ext_password_provider_ldap_enabled", SynapseOnly: true, + Description: "Log in with accounts from an LDAP directory.", Doc: "configuring-playbook-ldap-auth.md", + Fields: []Field{ + {Var: "matrix_synapse_ext_password_provider_ldap_uri", Label: "LDAP URIs", Kind: List, Required: true, Help: "e.g. ldap://ldap.example.com:389"}, + {Var: "matrix_synapse_ext_password_provider_ldap_start_tls", Label: "Use StartTLS", Kind: Bool, Default: "true"}, + {Var: "matrix_synapse_ext_password_provider_ldap_base", Label: "Base DN", Kind: Text, Required: true}, + {Var: "matrix_synapse_ext_password_provider_ldap_attributes_uid", Label: "UID attribute", Kind: Text, Default: "uid"}, + {Var: "matrix_synapse_ext_password_provider_ldap_attributes_mail", Label: "Mail attribute", Kind: Text, Default: "mail"}, + {Var: "matrix_synapse_ext_password_provider_ldap_attributes_name", Label: "Name attribute", Kind: Text, Default: "cn"}, + {Var: "matrix_synapse_ext_password_provider_ldap_bind_dn", Label: "Bind DN", Kind: Text}, + {Var: "matrix_synapse_ext_password_provider_ldap_bind_password", Label: "Bind password", Kind: Text}, + }}, + {ID: "simple-antispam", Name: "Synapse Simple Antispam", Category: "Authentication", EnableVar: "matrix_synapse_ext_spam_checker_synapse_simple_antispam_enabled", SynapseOnly: true, + Description: "Block invites from specific homeservers.", Doc: "configuring-playbook-synapse-simple-antispam.md", + Fields: []Field{{Var: "matrix_synapse_ext_spam_checker_synapse_simple_antispam_config_blocked_homeservers", Label: "Blocked homeservers", Kind: List, Required: true}}}, + {ID: "uvs", Name: "User Verification Service", Category: "Authentication", EnableVar: "matrix_user_verification_service_enabled", + Description: "Verify users' room membership for Jitsi and other widgets.", Doc: "configuring-playbook-user-verification-service.md", + Fields: []Field{ + {Var: "matrix_user_verification_service_uvs_access_token", Label: "Access token of a bot user", Kind: Text, Required: true}, + {Var: "matrix_user_verification_service_uvs_auth_token", Label: "Auth token", Kind: Secret}, + }}, + + // ── File storage ─────────────────────────────────────────────── + {ID: "media-repo", Name: "matrix-media-repo", Category: "File storage", EnableVar: "matrix_media_repo_enabled", + Description: "Advanced media repository with deduplication and multiple backends.", Doc: "configuring-playbook-matrix-media-repo.md", + Fields: []Field{{Var: "matrix_media_repo_datastore_file_id", Label: "Datastore ID", Kind: Secret}}}, + {ID: "s3-provider", Name: "S3 storage provider", Category: "File storage", EnableVar: "matrix_synapse_ext_synapse_s3_storage_provider_enabled", SynapseOnly: true, + Description: "Offload Synapse media to S3-compatible object storage.", Doc: "configuring-playbook-synapse-s3-storage-provider.md", + Fields: []Field{ + {Var: "matrix_synapse_ext_synapse_s3_storage_provider_config_bucket", Label: "Bucket", Kind: Text, Required: true}, + {Var: "matrix_synapse_ext_synapse_s3_storage_provider_config_region_name", Label: "Region", Kind: Text, Required: true}, + {Var: "matrix_synapse_ext_synapse_s3_storage_provider_config_endpoint_url", Label: "Endpoint URL", Kind: Text, Required: true}, + {Var: "matrix_synapse_ext_synapse_s3_storage_provider_config_access_key_id", Label: "Access key ID", Kind: Text, Required: true}, + {Var: "matrix_synapse_ext_synapse_s3_storage_provider_config_secret_access_key", Label: "Secret access key", Kind: Text, Required: true}, + }}, + {ID: "goofys", Name: "S3 via Goofys", Category: "File storage", EnableVar: "matrix_s3_media_store_enabled", SynapseOnly: true, + Description: "Mount an S3 bucket as Synapse's media store.", Doc: "configuring-playbook-s3-goofys.md", + Fields: []Field{ + {Var: "matrix_s3_media_store_bucket_name", Label: "Bucket", Kind: Text, Required: true}, + {Var: "matrix_s3_media_store_aws_access_key", Label: "Access key", Kind: Text, Required: true}, + {Var: "matrix_s3_media_store_aws_secret_key", Label: "Secret key", Kind: Text, Required: true}, + {Var: "matrix_s3_media_store_region", Label: "Region", Kind: Text, Default: "eu-central-1"}, + {Var: "matrix_s3_media_store_custom_endpoint_enabled", Label: "Custom endpoint", Kind: Bool, Default: "false"}, + {Var: "matrix_s3_media_store_custom_endpoint", Label: "Endpoint URL", Kind: Text, ShowIf: "matrix_s3_media_store_custom_endpoint_enabled"}, + }}, + + // ── Bridges ──────────────────────────────────────────────────── + {ID: "bridges-e2ee", Name: "Bridge encryption (all bridges)", Category: "Bridges", EnableVar: "matrix_bridges_encryption_enabled", + Description: "Enable end-to-bridge encryption for every mautrix bridge.", Doc: "configuring-playbook-bridge-mautrix-bridges.md"}, + {ID: "bridges-relay", Name: "Bridge relay mode (all bridges)", Category: "Bridges", EnableVar: "matrix_bridges_relay_enabled", + Description: "Let bridged rooms relay messages from users who haven't logged into the bridge.", Doc: "configuring-playbook-bridge-mautrix-bridges.md"}, + {ID: "telegram", Name: "Telegram (mautrix)", Category: "Bridges", EnableVar: "matrix_bridge_mautrix_telegram_enabled", + Description: "Bridge Telegram chats. Needs an API ID/hash from my.telegram.org.", Doc: "configuring-playbook-bridge-mautrix-telegram.md", + Fields: []Field{ + {Var: "matrix_bridge_mautrix_telegram_api_id", Label: "Telegram API ID", Kind: Number, Required: true}, + {Var: "matrix_bridge_mautrix_telegram_api_hash", Label: "Telegram API hash", Kind: Text, Required: true}, + }}, + {ID: "whatsapp", Name: "WhatsApp (mautrix)", Category: "Bridges", EnableVar: "matrix_bridge_mautrix_whatsapp_enabled", + Description: "Bridge WhatsApp chats via the multidevice API.", Doc: "configuring-playbook-bridge-mautrix-whatsapp.md"}, + {ID: "signal", Name: "Signal (mautrix)", Category: "Bridges", EnableVar: "matrix_bridge_mautrix_signal_enabled", + Description: "Bridge Signal chats as a linked device.", Doc: "configuring-playbook-bridge-mautrix-signal.md"}, + {ID: "discord", Name: "Discord (mautrix)", Category: "Bridges", EnableVar: "matrix_bridge_mautrix_discord_enabled", + Description: "Puppeting Discord bridge.", Doc: "configuring-playbook-bridge-mautrix-discord.md"}, + {ID: "slack", Name: "Slack (mautrix)", Category: "Bridges", EnableVar: "matrix_bridge_mautrix_slack_enabled", + Description: "Puppeting Slack bridge.", Doc: "configuring-playbook-bridge-mautrix-slack.md"}, + {ID: "meta-messenger", Name: "Messenger (mautrix-meta)", Category: "Bridges", EnableVar: "matrix_bridge_mautrix_meta_messenger_enabled", + Description: "Bridge Facebook Messenger.", Doc: "configuring-playbook-bridge-mautrix-meta-messenger.md"}, + {ID: "meta-instagram", Name: "Instagram (mautrix-meta)", Category: "Bridges", EnableVar: "matrix_bridge_mautrix_meta_instagram_enabled", + Description: "Bridge Instagram DMs.", Doc: "configuring-playbook-bridge-mautrix-meta-instagram.md"}, + {ID: "bluesky", Name: "Bluesky (mautrix)", Category: "Bridges", EnableVar: "matrix_bridge_mautrix_bluesky_enabled", + Description: "Bridge Bluesky direct messages.", Doc: "configuring-playbook-bridge-mautrix-bluesky.md"}, + {ID: "twitter", Name: "Twitter/X (mautrix)", Category: "Bridges", EnableVar: "matrix_bridge_mautrix_twitter_enabled", + Description: "Bridge Twitter/X direct messages.", Doc: "configuring-playbook-bridge-mautrix-twitter.md"}, + {ID: "linkedin", Name: "LinkedIn (mautrix)", Category: "Bridges", EnableVar: "matrix_bridge_mautrix_linkedin_enabled", + Description: "Bridge LinkedIn messaging.", Doc: "configuring-playbook-bridge-mautrix-linkedin.md"}, + {ID: "googlechat", Name: "Google Chat (mautrix)", Category: "Bridges", EnableVar: "matrix_bridge_mautrix_googlechat_enabled", + Description: "Bridge Google Chat.", Doc: "configuring-playbook-bridge-mautrix-googlechat.md"}, + {ID: "gmessages", Name: "Google Messages (mautrix)", Category: "Bridges", EnableVar: "matrix_bridge_mautrix_gmessages_enabled", + Description: "Bridge SMS/RCS through Google Messages on your phone.", Doc: "configuring-playbook-bridge-mautrix-gmessages.md"}, + {ID: "gvoice", Name: "Google Voice (mautrix)", Category: "Bridges", EnableVar: "matrix_bridge_mautrix_gvoice_enabled", + Description: "Bridge Google Voice.", Doc: "configuring-playbook-bridge-mautrix-gvoice.md"}, + {ID: "wsproxy", Name: "mautrix-wsproxy (SMS/iMessage)", Category: "Bridges", EnableVar: "matrix_bridge_mautrix_wsproxy_enabled", Subdomain: "wsproxy", + Description: "Websocket proxy for Android SMS or Apple iMessage bridges.", Doc: "configuring-playbook-bridge-mautrix-wsproxy.md", + Fields: []Field{ + {Var: "matrix_bridge_mautrix_wsproxy_android_appservice_token", Label: "Android appservice token", Kind: Secret}, + {Var: "matrix_bridge_mautrix_wsproxy_android_homeserver_token", Label: "Android homeserver token", Kind: Secret}, + {Var: "matrix_bridge_mautrix_wsproxy_imessage_appservice_token", Label: "iMessage appservice token", Kind: Secret}, + {Var: "matrix_bridge_mautrix_wsproxy_imessage_homeserver_token", Label: "iMessage homeserver token", Kind: Secret}, + }}, + {ID: "rustpush", Name: "iMessage (RustPush)", Category: "Bridges", EnableVar: "matrix_bridge_rustpush_enabled", + Description: "Bridge Apple iMessage.", Doc: "configuring-playbook-bridge-rustpush.md"}, + {ID: "appservice-irc", Name: "IRC (matrix-appservice-irc)", Category: "Bridges", EnableVar: "matrix_bridge_appservice_irc_enabled", + Description: "Bridge one or more IRC networks.", Doc: "configuring-playbook-bridge-appservice-irc.md", + Fields: []Field{{Var: "matrix_bridge_appservice_irc_ircService_servers", Label: "IRC servers", Kind: YAML, Required: true, + Default: "irc.example.com:\n name: \"ExampleNet\"\n port: 6697\n ssl: true\n botConfig:\n enabled: true\n nick: \"MatrixBot\"\n dynamicChannels:\n enabled: true\n aliasTemplate: \"#irc_$CHANNEL\"\n matrixClients:\n userTemplate: \"@irc_$NICK\"\n ircClients:\n nickTemplate: \"$DISPLAY[m]\""}}}, + {ID: "heisenbridge", Name: "Heisenbridge (IRC bouncer)", Category: "Bridges", EnableVar: "matrix_bridge_heisenbridge_enabled", + Description: "Bouncer-style IRC bridge, one connection per user.", Doc: "configuring-playbook-bridge-heisenbridge.md"}, + {ID: "appservice-discord", Name: "Discord (matrix-appservice-discord)", Category: "Bridges", EnableVar: "matrix_bridge_appservice_discord_enabled", + Description: "Bot-based (non-puppeting) Discord bridge.", Doc: "configuring-playbook-bridge-appservice-discord.md", + Fields: []Field{ + {Var: "matrix_bridge_appservice_discord_client_id", Label: "Discord app client ID", Kind: Text, Required: true}, + {Var: "matrix_bridge_appservice_discord_bot_token", Label: "Discord bot token", Kind: Text, Required: true}, + }}, + {ID: "hookshot", Name: "matrix-hookshot", Category: "Bridges", EnableVar: "matrix_bridge_hookshot_enabled", + Description: "Webhooks plus GitHub, GitLab, JIRA and RSS feeds.", Doc: "configuring-playbook-bridge-hookshot.md"}, + {ID: "beeper-line", Name: "LINE (Beeper)", Category: "Bridges", EnableVar: "matrix_bridge_beeper_line_enabled", + Description: "Bridge LINE messenger.", Doc: "configuring-playbook-bridge-beeper-line.md"}, + {ID: "beeper-linkedin", Name: "LinkedIn (Beeper)", Category: "Bridges", EnableVar: "matrix_bridge_beeper_linkedin_enabled", Status: "unmaintained", + Description: "Archived upstream. Prefer the mautrix LinkedIn bridge.", Doc: "configuring-playbook-bridge-beeper-linkedin.md"}, + {ID: "groupme", Name: "GroupMe (mx-puppet)", Category: "Bridges", EnableVar: "matrix_bridge_mx_puppet_groupme_enabled", + Description: "Bridge GroupMe.", Doc: "configuring-playbook-bridge-mx-puppet-groupme.md"}, + {ID: "steam", Name: "Steam", Category: "Bridges", EnableVar: "matrix_bridge_steam_enabled", + Description: "Bridge Steam chat.", Doc: "configuring-playbook-bridge-steam.md"}, + {ID: "mx-puppet-steam", Name: "Steam (mx-puppet)", Category: "Bridges", EnableVar: "matrix_bridge_mx_puppet_steam_enabled", + Description: "Alternative Steam bridge.", Doc: "configuring-playbook-bridge-mx-puppet-steam.md"}, + {ID: "postmoogle", Name: "Postmoogle (email)", Category: "Bridges", EnableVar: "matrix_bridge_postmoogle_enabled", + Description: "Send and receive email in Matrix rooms.", Doc: "configuring-playbook-bridge-postmoogle.md", + Fields: []Field{{Var: "matrix_bridge_postmoogle_password", Label: "Bot password", Kind: Secret, Required: true}}}, + {ID: "sms", Name: "SMS (matrix-sms-bridge)", Category: "Bridges", EnableVar: "matrix_bridge_sms_enabled", + Description: "Bridge SMS through an Android SMS gateway.", Doc: "configuring-playbook-bridge-matrix-bridge-sms.md", + Fields: []Field{ + {Var: "matrix_bridge_sms_default_region", Label: "Default region (e.g. DE)", Kind: Text, Required: true}, + {Var: "matrix_bridge_sms_default_timezone", Label: "Timezone (e.g. Europe/Berlin)", Kind: Text, Required: true}, + {Var: "matrix_bridge_sms_provider_android_baseurl", Label: "Android gateway URL", Kind: Text, Required: true}, + {Var: "matrix_bridge_sms_provider_android_username", Label: "Gateway username", Kind: Text, Required: true}, + {Var: "matrix_bridge_sms_provider_android_password", Label: "Gateway password", Kind: Text, Required: true}, + {Var: "matrix_bridge_sms_provider_android_truststore_local_path", Label: "Truststore file name", Kind: Text, Required: true}, + {Var: "matrix_bridge_sms_provider_android_truststore_password", Label: "Truststore password", Kind: Text, Required: true}, + }}, + {ID: "meshtastic", Name: "Meshtastic relay", Category: "Bridges", EnableVar: "matrix_bridge_meshtastic_relay_enabled", + Description: "Bridge Meshtastic LoRa mesh radios. Useful when the internet is down!", Doc: "configuring-playbook-bridge-meshtastic-relay.md", + Fields: []Field{ + {Var: "matrix_bridge_meshtastic_relay_matrix_bot_password", Label: "Bot password", Kind: Secret, Required: true}, + {Var: "matrix_bridge_meshtastic_relay_connection_type", Label: "Connection type (tcp/serial/ble)", Kind: Text, Default: "tcp"}, + {Var: "matrix_bridge_meshtastic_relay_tcp_host", Label: "Meshtastic node host", Kind: Text, Default: "meshtastic.local"}, + {Var: "matrix_bridge_meshtastic_relay_matrix_rooms_list", Label: "Rooms", Kind: YAML, + Default: "- id: \"#meshtastic:{{ matrix_domain }}\"\n meshtastic_channel: \"0\""}, + }}, + {ID: "wechat", Name: "WeChat", Category: "Bridges", EnableVar: "matrix_bridge_wechat_enabled", + Description: "Bridge WeChat.", Doc: "configuring-playbook-bridge-wechat.md"}, + + // ── Bots ─────────────────────────────────────────────────────── + {ID: "baibot", Name: "baibot (AI bot)", Category: "Bots", EnableVar: "matrix_bot_baibot_enabled", + Description: "Chat with LLMs (OpenAI, Anthropic, Venice, local models...).", Doc: "configuring-playbook-bot-baibot.md", + Fields: []Field{ + {Var: "matrix_bot_baibot_config_user_password", Label: "Bot password", Kind: Secret, Required: true}, + {Var: "matrix_bot_baibot_config_user_encryption_recovery_passphrase", Label: "Recovery passphrase", Kind: Secret, Required: true}, + {Var: "matrix_bot_baibot_config_persistence_session_encryption_key", Label: "Session encryption key", Kind: Hex64, Required: true}, + {Var: "matrix_bot_baibot_config_persistence_config_encryption_key", Label: "Config encryption key", Kind: Hex64, Required: true}, + }}, + {ID: "reminder-bot", Name: "matrix-reminder-bot", Category: "Bots", EnableVar: "matrix_bot_matrix_reminder_bot_enabled", + Description: "A bot to remind you about stuff.", Doc: "configuring-playbook-bot-matrix-reminder-bot.md", + Fields: []Field{ + {Var: "matrix_bot_matrix_reminder_bot_matrix_user_password", Label: "Bot password", Kind: Secret, Required: true}, + {Var: "matrix_bot_matrix_reminder_bot_reminders_timezone", Label: "Timezone", Kind: Text, Default: "Asia/Tehran", Required: true}, + }}, + {ID: "maubot", Name: "maubot", Category: "Bots", EnableVar: "matrix_bot_maubot_enabled", + Description: "Plugin-based bot system.", Doc: "configuring-playbook-bot-maubot.md", + Fields: []Field{ + {Var: "matrix_bot_maubot_initial_password", Label: "Bot password", Kind: Secret, Required: true}, + {Var: "matrix_bot_maubot_admins", Label: "Management UI admins", Kind: YAML, Default: "- admin: CHANGE_ME"}, + }}, + {ID: "honoroit", Name: "Honoroit (helpdesk)", Category: "Bots", EnableVar: "matrix_bot_honoroit_enabled", + Description: "Helpdesk bot that routes users' questions to a team room.", Doc: "configuring-playbook-bot-honoroit.md", + Fields: []Field{ + {Var: "matrix_bot_honoroit_password", Label: "Bot password", Kind: Secret, Required: true}, + {Var: "matrix_bot_honoroit_roomid", Label: "Helpdesk room ID", Kind: Text, Required: true, Help: "e.g. !abc:example.com"}, + }}, + {ID: "draupnir", Name: "Draupnir", Category: "Bots", EnableVar: "matrix_bot_draupnir_enabled", + Description: "Moderation bot (Mjolnir successor).", Doc: "configuring-playbook-bot-draupnir.md", + Extra: map[string]string{"matrix_bot_draupnir_zero_touch_deploy": "true"}, + Fields: []Field{{Var: "matrix_bot_draupnir_config_initialManager", Label: "Initial manager MXID", Kind: Text, Required: true, Help: "e.g. @you:example.com"}}}, + {ID: "d4a", Name: "Draupnir for all (D4A)", Category: "Bots", EnableVar: "matrix_appservice_draupnir_for_all_enabled", + Description: "Draupnir in appservice mode, multiple instances.", Doc: "configuring-playbook-appservice-draupnir-for-all.md", + Extra: map[string]string{"matrix_appservice_draupnir_for_all_zero_touch_deploy": "true"}, + Fields: []Field{{Var: "matrix_appservice_draupnir_for_all_config_initialManager", Label: "Initial manager MXID", Kind: Text, Required: true}}}, + {ID: "mjolnir", Name: "Mjolnir", Category: "Bots", EnableVar: "matrix_bot_mjolnir_enabled", + Description: "The classic moderation bot.", Doc: "configuring-playbook-bot-mjolnir.md", + Fields: []Field{ + {Var: "matrix_bot_mjolnir_access_token", Label: "Bot access token", Kind: Text, Required: true}, + {Var: "matrix_bot_mjolnir_management_room", Label: "Management room ID", Kind: Text, Required: true}, + }}, + {ID: "meowlnir", Name: "Meowlnir", Category: "Bots", EnableVar: "matrix_bot_meowlnir_enabled", + Description: "Appservice moderation bot compatible with Draupnir/Mjolnir policy lists.", Doc: "configuring-playbook-bot-meowlnir.md", + Fields: []Field{{Var: "matrix_bot_meowlnir_bots_custom", Label: "Bots", Kind: YAML, + Default: "- username: meowlnir_bot\n displayname: Meowlnir\n avatar_url: \"\"\n management_room_auto_create: true\n management_rooms: []"}}}, + {ID: "buscarron", Name: "Buscarron", Category: "Bots", EnableVar: "matrix_bot_buscarron_enabled", Subdomain: "buscarron", + Description: "Post web form submissions into a Matrix room.", Doc: "configuring-playbook-bot-buscarron.md", + Fields: []Field{ + {Var: "matrix_bot_buscarron_password", Label: "Bot password", Kind: Secret, Required: true}, + {Var: "matrix_bot_buscarron_forms", Label: "Forms", Kind: YAML, Required: true, + Default: "- name: contact\n room: \"!roomid:{{ matrix_domain }}\"\n redirect: https://example.com"}, + }}, + + // ── Administration ───────────────────────────────────────────── + {ID: "monitoring", Name: "Prometheus + Grafana", Category: "Administration", EnableVar: "prometheus_enabled", Subdomain: "stats", + Description: "Metrics and pretty dashboards for your server.", Doc: "configuring-playbook-prometheus-grafana.md", + Extra: map[string]string{"prometheus_node_exporter_enabled": "true", "prometheus_postgres_exporter_enabled": "true", "grafana_enabled": "true"}, + Fields: []Field{ + {Var: "grafana_default_admin_user", Label: "Grafana admin user", Kind: Text, Default: "admin"}, + {Var: "grafana_default_admin_password", Label: "Grafana admin password", Kind: Secret, Required: true}, + }}, + {ID: "alertmanager-receiver", Name: "Alertmanager receiver", Category: "Administration", EnableVar: "matrix_alertmanager_receiver_enabled", + Description: "Deliver Prometheus alerts into Matrix rooms.", Doc: "configuring-playbook-alertmanager-receiver.md", + Fields: []Field{ + {Var: "matrix_alertmanager_receiver_config_matrix_access_token", Label: "Bot access token", Kind: Text, Required: true}, + {Var: "matrix_alertmanager_receiver_config_matrix_room_mapping", Label: "Room mapping", Kind: YAML, Required: true, Default: "alerts: \"!roomid:{{ matrix_domain }}\""}, + }}, + {ID: "rageshake", Name: "Rageshake", Category: "Administration", EnableVar: "matrix_rageshake_enabled", Subdomain: "rageshake", + Description: "Bug report server for Element clients.", Doc: "configuring-playbook-rageshake.md"}, + {ID: "usage-exporter", Name: "synapse-usage-exporter", Category: "Administration", EnableVar: "matrix_synapse_usage_exporter_enabled", SynapseOnly: true, + Description: "Collect Synapse usage statistics.", Doc: "configuring-playbook-synapse-usage-exporter.md"}, + {ID: "auto-compressor", Name: "synapse-auto-compressor", Category: "Administration", EnableVar: "matrix_synapse_auto_compressor_enabled", SynapseOnly: true, + Description: "Periodically compress Synapse's state tables.", Doc: "configuring-playbook-synapse-auto-compressor.md"}, + {ID: "cleanup", Name: "System cleanup", Category: "Administration", EnableVar: "system_cleanup_docker_timer_enabled", + Description: "Daily timer that removes old Docker images and logs.", Doc: "configuring-playbook-system-cleanup.md"}, + {ID: "borg", Name: "BorgBackup", Category: "Administration", EnableVar: "backup_borg_enabled", + Description: "Full encrypted, deduplicated server backups including Postgres.", Doc: "configuring-playbook-backup-borg.md", + Fields: []Field{ + {Var: "backup_borg_location_repositories", Label: "Repositories", Kind: List, Required: true, Help: "e.g. ssh://user@backup.example.com/./repo"}, + {Var: "backup_borg_storage_encryption_passphrase", Label: "Encryption passphrase", Kind: Secret, Required: true}, + {Var: "backup_borg_ssh_key_private", Label: "SSH private key", Kind: YAML, Help: "Optional. First line |, then the key indented by two spaces."}, + }}, + {ID: "postgres-backup", Name: "Postgres backup", Category: "Administration", EnableVar: "postgres_backup_enabled", + Description: "Periodic local database dumps (database only).", Doc: "configuring-playbook-postgres-backup.md"}, + + // ── Calls & extras ───────────────────────────────────────────── + {ID: "element-call", Name: "Element Call", Category: "Calls & extras", EnableVar: "matrix_element_call_enabled", Subdomain: "call.element", + Description: "Native Matrix group video calls (includes LiveKit).", Doc: "configuring-playbook-element-call.md"}, + {ID: "matrix-rtc", Name: "Matrix RTC stack", Category: "Calls & extras", EnableVar: "matrix_rtc_enabled", + Description: "LiveKit + JWT service for Element X calls, without the Element Call web app.", Doc: "configuring-playbook-matrix-rtc.md"}, + {ID: "jitsi", Name: "Jitsi Meet", Category: "Calls & extras", EnableVar: "jitsi_enabled", Subdomain: "jitsi", + Description: "Self-hosted video conferencing.", Doc: "configuring-playbook-jitsi.md"}, + {ID: "etherpad", Name: "Etherpad", Category: "Calls & extras", EnableVar: "etherpad_enabled", Subdomain: "etherpad", + Description: "Collaborative documents you can embed in rooms.", Doc: "configuring-playbook-etherpad.md"}, + {ID: "matrixto", Name: "Matrix.to", Category: "Calls & extras", EnableVar: "matrix_matrixto_enabled", Subdomain: "mt", + Description: "Self-hosted link sharing service. Handy when matrix.to is unreachable.", Doc: "configuring-playbook-matrixto.md"}, + {ID: "cactus", Name: "Cactus Comments", Category: "Calls & extras", EnableVar: "matrix_cactus_comments_enabled", + Description: "Federated comment system for websites.", Doc: "configuring-playbook-cactus-comments.md", + Extra: map[string]string{"matrix_cactus_comments_client_enabled": "true"}}, + {ID: "pantalaimon", Name: "Pantalaimon", Category: "Calls & extras", EnableVar: "matrix_pantalaimon_enabled", + Description: "E2EE-aware proxy for bots and clients without encryption support.", Doc: "configuring-playbook-pantalaimon.md"}, + {ID: "sygnal", Name: "Sygnal push gateway", Category: "Calls & extras", EnableVar: "matrix_sygnal_enabled", Subdomain: "sygnal", + Description: "Push gateway for your own mobile apps.", Doc: "configuring-playbook-sygnal.md", + Fields: []Field{{Var: "matrix_sygnal_apps", Label: "Apps", Kind: YAML, Required: true, + Default: "com.example.myapp.android:\n type: gcm\n api_key: your_api_key_for_gcm"}}}, + {ID: "ntfy", Name: "ntfy push server", Category: "Calls & extras", EnableVar: "ntfy_enabled", Subdomain: "ntfy", + Description: "UnifiedPush notifications without Google. Very useful when Google services are blocked.", Doc: "configuring-playbook-ntfy.md"}, + {ID: "corporal", Name: "Matrix Corporal", Category: "Calls & extras", EnableVar: "matrix_corporal_enabled", SynapseOnly: true, + Description: "Manage users and rooms from a central policy (advanced).", Doc: "configuring-playbook-matrix-corporal.md", + Extra: map[string]string{ + "matrix_synapse_ext_password_provider_rest_auth_enabled": "true", + "matrix_synapse_ext_password_provider_rest_auth_endpoint": "\"http://matrix-corporal:41080/_matrix/corporal\"", + }, + Fields: []Field{ + {Var: "matrix_synapse_ext_password_provider_shared_secret_auth_enabled", Label: "Shared secret auth", Kind: Bool, Default: "true"}, + {Var: "matrix_synapse_ext_password_provider_shared_secret_auth_shared_secret", Label: "Shared secret", Kind: Secret, Required: true}, + {Var: "matrix_corporal_policy_provider_config", Label: "Policy provider (JSON)", Kind: YAML, Required: true, + Default: "|\n {\n \"Type\": \"static_file\",\n \"Path\": \"/etc/matrix-corporal/policy.json\"\n }"}, + }}, +} + +// ByID looks a component up by its ID. +func ByID(id string) (Component, bool) { + for _, c := range Components { + if c.ID == id { + return c, true + } + } + return Component{}, false +} diff --git a/internal/config/config.go b/internal/config/config.go new file mode 100644 index 0000000..7223ebd --- /dev/null +++ b/internal/config/config.go @@ -0,0 +1,200 @@ +// Package config holds the user's choices and turns them into the +// inventory files matrix-docker-ansible-deploy expects. +package config + +import ( + "encoding/json" + "os" + "path/filepath" + + "interzone/internal/catalog" +) + +const ( + DefaultPlaybookGit = "https://itsjustadream.g0th.ir/spantaleev/matrix-docker-ansible-deploy" + DefaultRegistryPrefix = "mechatok.g0th.ir/" + UpstreamGitHub = "https://github.com/" +) + +type Target struct { + Mode string // "local" or "ssh" + Host string + User string + Port string + SSHKey string + BecomePass string +} + +type Sources struct { + PlaybookGit string + // RolesGitBase replaces https://github.com/ in requirements.yml so Ansible + // roles come from the same in-country mirror as the playbook. + RolesGitBase string + UseRegistry bool + RegistryPrefix string + DockerPackageURL string // mirror of https://download.docker.com/linux + APTMirror string // mirror for the server's distro packages + PyPIIndex string // used when ansible has to be installed locally + Blackout bool +} + +type SSL struct { + Mode string // "letsencrypt", "selfsigned", "custom", "none" + ACMEEmail string + CertPath string + KeyPath string +} + +type Config struct { + Domain string + Homeserver string + Target Target + Sources Sources + SSL SSL + IPv6 bool + Federation bool + + Components map[string]bool + Values map[string]string + + AdminUser string + AdminPassword string + + GenericSecret string + PostgresPassword string + + ExtraYAML string + PlaybookDir string +} + +func Dir() string { + if d, err := os.UserConfigDir(); err == nil { + return filepath.Join(d, "interzone") + } + return ".interzone" +} + +func path() string { return filepath.Join(Dir(), "config.json") } + +func Default() *Config { + data, _ := os.UserHomeDir() + if x := os.Getenv("XDG_DATA_HOME"); x != "" { + data = x + } else { + data = filepath.Join(data, ".local", "share") + } + c := &Config{ + Homeserver: "synapse", + Target: Target{Mode: "local", User: "root", Port: "22"}, + Sources: Sources{ + PlaybookGit: DefaultPlaybookGit, + RolesGitBase: "https://itsjustadream.g0th.ir/", + UseRegistry: true, + RegistryPrefix: DefaultRegistryPrefix, + }, + SSL: SSL{Mode: "letsencrypt"}, + Federation: true, + Components: map[string]bool{}, + Values: map[string]string{}, + AdminUser: "admin", + AdminPassword: RandomPassword(20), + GenericSecret: RandomPassword(64), + PostgresPassword: RandomPassword(48), + PlaybookDir: filepath.Join(data, "interzone", "matrix-docker-ansible-deploy"), + } + for _, comp := range catalog.Components { + if comp.DefaultOn { + c.Components[comp.ID] = true + } + } + return c +} + +// Load returns the saved configuration, or defaults on first run. +func Load() (*Config, bool) { + b, err := os.ReadFile(path()) + if err != nil { + return Default(), false + } + c := Default() + if err := json.Unmarshal(b, c); err != nil { + return Default(), false + } + if c.Components == nil { + c.Components = map[string]bool{} + } + if c.Values == nil { + c.Values = map[string]string{} + } + return c, true +} + +// Save writes the configuration with owner-only permissions since it holds secrets. +func (c *Config) Save() error { + if err := os.MkdirAll(Dir(), 0o700); err != nil { + return err + } + b, err := json.MarshalIndent(c, "", " ") + if err != nil { + return err + } + return os.WriteFile(path(), b, 0o600) +} + +// Enabled reports whether a component is active for the chosen homeserver. +func (c *Config) Enabled(comp catalog.Component) bool { + if comp.SynapseOnly && c.Homeserver != "synapse" { + return false + } + return c.Components[comp.ID] +} + +// FillGenerated creates secrets for enabled components that still lack them. +func (c *Config) FillGenerated() { + for _, comp := range catalog.Components { + if !c.Enabled(comp) { + continue + } + for _, f := range comp.Fields { + if _, ok := c.Values[f.Var]; ok { + continue + } + switch f.Kind { + case catalog.Secret: + c.Values[f.Var] = RandomPassword(32) + case catalog.Hex64: + c.Values[f.Var] = RandomHex(32) + default: + c.Values[f.Var] = f.Default + } + } + } +} + +// Missing lists required fields that are still empty, as "Component: Field". +func (c *Config) Missing() []string { + var out []string + if c.Domain == "" { + out = append(out, "Server: base domain") + } + if c.Target.Mode == "ssh" && c.Target.Host == "" { + out = append(out, "Server: SSH host") + } + if c.SSL.Mode == "custom" && (c.SSL.CertPath == "" || c.SSL.KeyPath == "") { + out = append(out, "SSL: certificate and key paths") + } + for _, comp := range catalog.Components { + if !c.Enabled(comp) { + continue + } + for _, f := range comp.Fields { + if f.ShowIf != "" && c.Values[f.ShowIf] != "true" { + continue + } + if f.Required && c.Values[f.Var] == "" { + out = append(out, comp.Name+": "+f.Label) + } + } + } + return out +} diff --git a/internal/config/render.go b/internal/config/render.go new file mode 100644 index 0000000..576bca6 --- /dev/null +++ b/internal/config/render.go @@ -0,0 +1,294 @@ +package config + +import ( + "fmt" + "os" + "regexp" + "sort" + "strings" + "time" + + "interzone/internal/catalog" +) + +// HostName is the inventory name MDAD uses for the server. +func (c *Config) HostName() string { return "matrix." + c.Domain } + +type yamlWriter struct { + b strings.Builder + seen map[string]bool +} + +func (w *yamlWriter) section(title string) { + fmt.Fprintf(&w.b, "\n# ── %s %s\n", title, strings.Repeat("─", max(3, 60-len(title)))) +} + +func (w *yamlWriter) comment(s string) { fmt.Fprintf(&w.b, "# %s\n", s) } + +// raw writes an already-formatted scalar. Later writes of the same key are +// dropped so components that share a variable never produce duplicates. +func (w *yamlWriter) raw(key, value string) { + if w.seen[key] { + return + } + w.seen[key] = true + fmt.Fprintf(&w.b, "%s: %s\n", key, value) +} + +func (w *yamlWriter) str(key, value string) { w.raw(key, Quote(value)) } + +func (w *yamlWriter) block(key, body string) { + if w.seen[key] { + return + } + w.seen[key] = true + body = strings.TrimRight(body, "\n ") + if strings.HasPrefix(body, "|") || strings.HasPrefix(body, ">") { + head, rest, _ := strings.Cut(body, "\n") + fmt.Fprintf(&w.b, "%s: %s\n%s\n", key, head, rest) + return + } + fmt.Fprintf(&w.b, "%s:\n%s\n", key, indent(body, " ")) +} + +func indent(s, pad string) string { + lines := strings.Split(s, "\n") + for i, l := range lines { + if l != "" { + lines[i] = pad + l + } + } + return strings.Join(lines, "\n") +} + +// Quote renders s as a single-quoted YAML scalar. +func Quote(s string) string { return "'" + strings.ReplaceAll(s, "'", "''") + "'" } + +var numeric = regexp.MustCompile(`^-?[0-9]+(\.[0-9]+)?$`) + +func (w *yamlWriter) field(f catalog.Field, v string) { + if v == "" && !f.Required { + return + } + switch f.Kind { + case catalog.Bool: + if v != "true" { + v = "false" + } + w.raw(f.Var, v) + case catalog.Number: + if numeric.MatchString(v) { + w.raw(f.Var, v) + } else { + w.str(f.Var, v) + } + case catalog.List: + var items []string + for _, it := range strings.Split(v, ",") { + if it = strings.TrimSpace(it); it != "" { + items = append(items, "- "+Quote(it)) + } + } + if len(items) == 0 { + w.raw(f.Var, "[]") + } else { + w.block(f.Var, strings.Join(items, "\n")) + } + case catalog.YAML: + w.block(f.Var, v) + default: + w.str(f.Var, v) + } +} + +// MigrationVersion reads the value MDAD expects from the playbook's own example config. +func MigrationVersion(playbookDir string) string { + b, err := os.ReadFile(playbookDir + "/examples/vars.yml") + if err != nil { + return "" + } + m := regexp.MustCompile(`(?m)^matrix_playbook_migration_validated_version:\s*(\S+)`).FindSubmatch(b) + if m == nil { + return "" + } + return string(m[1]) +} + +// VarsYAML renders inventory/host_vars/matrix./vars.yml. +// certPath/keyPath are only used for the self-signed and custom SSL modes. +func (c *Config) VarsYAML(migrationVersion, certPath, keyPath string) string { + w := &yamlWriter{seen: map[string]bool{}} + fmt.Fprintf(&w.b, "# Generated by interzone on %s.\n", time.Now().Format("2006-01-02 15:04")) + w.comment("Re-running interzone rewrites this file. Put hand-written settings in the") + w.comment("\"Extra vars\" box inside interzone so they survive.") + w.b.WriteString("---\n") + + w.section("Basics") + if migrationVersion == "" { + migrationVersion = "'' # filled in from the playbook during deploy" + } + w.raw("matrix_playbook_migration_validated_version", migrationVersion) + w.str("matrix_domain", c.Domain) + w.raw("matrix_homeserver_implementation", c.Homeserver) + w.str("matrix_homeserver_generic_secret_key", c.GenericSecret) + w.raw("matrix_playbook_reverse_proxy_type", "playbook-managed-traefik") + w.raw("devture_systemd_docker_base_ipv6_enabled", fmt.Sprint(c.IPv6)) + w.str("postgres_connection_password", c.PostgresPassword) + w.raw("matrix_homeserver_federation_enabled", fmt.Sprint(c.Federation)) + + w.section("Mirrors") + if c.Sources.UseRegistry && c.Sources.RegistryPrefix != "" { + w.comment("Every container image is pulled from this registry instead of docker.io, ghcr.io, etc.") + w.str("matrix_container_global_registry_prefix_override", normalizePrefix(c.Sources.RegistryPrefix)) + // The RustPush role is not wired to the global override upstream. + w.raw("matrix_bridge_rustpush_container_image_registry_prefix_upstream", `"{{ matrix_container_global_registry_prefix_override }}"`) + } else { + w.comment("Images are pulled from their upstream registries.") + } + if c.Sources.DockerPackageURL != "" { + w.comment("Docker Engine packages come from this mirror of download.docker.com/linux.") + w.str("docker_repo_url", strings.TrimRight(c.Sources.DockerPackageURL, "/")) + } + + w.section("SSL certificates") + switch c.SSL.Mode { + case "letsencrypt": + if c.SSL.ACMEEmail != "" { + w.str("traefik_config_certificatesResolvers_acme_email", c.SSL.ACMEEmail) + } else { + w.comment("Let's Encrypt without a contact email.") + } + case "none": + w.comment("No HTTPS: put your own TLS-terminating proxy in front of this server.") + w.raw("traefik_config_entrypoint_web_secure_enabled", "false") + case "selfsigned", "custom": + w.raw("traefik_config_certificatesResolvers_acme_enabled", "false") + w.raw("traefik_ssl_dir_enabled", "true") + w.block("traefik_provider_configuration_extension_yaml", strings.TrimSpace(` +tls: + certificates: + - certFile: /ssl/cert.pem + keyFile: /ssl/privkey.pem + stores: + default: + defaultCertificate: + certFile: /ssl/cert.pem + keyFile: /ssl/privkey.pem`)) + w.block("aux_file_definitions", fmt.Sprintf(`- dest: "{{ traefik_ssl_dir_path }}/privkey.pem" + src: %s + mode: '0600' +- dest: "{{ traefik_ssl_dir_path }}/cert.pem" + src: %s`, Quote(keyPath), Quote(certPath))) + } + + w.section("First admin user") + switch c.Homeserver { + case "synapse", "dendrite": + w.block("matrix_user_creator_users_additional", fmt.Sprintf("- username: %s\n initial_password: %s\n initial_type: admin", + Quote(c.AdminUser), Quote(c.AdminPassword))) + case "continuwuity", "tuwunel": + w.comment("These servers can't create users from Ansible. Register the first account") + w.comment("from any client using this token, then turn registration off again.") + w.raw("matrix_"+c.Homeserver+"_config_allow_registration", "true") + w.str("matrix_"+c.Homeserver+"_config_registration_token", c.AdminPassword) + case "conduit": + w.comment("Conduit can't create users from Ansible. Registration is open until you") + w.comment("create your account; re-run interzone afterwards to close it.") + w.raw("matrix_conduit_allow_registration", "true") + } + + w.section("Components") + for _, cat := range catalog.Categories { + var comps []catalog.Component + for _, comp := range catalog.Components { + if comp.Category != cat { + continue + } + if c.Enabled(comp) || (comp.DefaultOn && comp.EnableVar != "") { + comps = append(comps, comp) + } + } + if len(comps) == 0 { + continue + } + fmt.Fprintf(&w.b, "\n# %s\n", cat) + for _, comp := range comps { + on := c.Enabled(comp) + if comp.EnableVar != "" { + w.raw(comp.EnableVar, fmt.Sprint(on)) + } + if !on { + continue + } + keys := make([]string, 0, len(comp.Extra)) + for k := range comp.Extra { + keys = append(keys, k) + } + sort.Strings(keys) + for _, k := range keys { + w.raw(k, comp.Extra[k]) + } + for _, f := range comp.Fields { + if f.ShowIf != "" && c.Values[f.ShowIf] != "true" { + continue + } + w.field(f, c.Values[f.Var]) + } + } + } + + if extra := strings.TrimSpace(c.ExtraYAML); extra != "" { + w.section("Extra vars (hand-written)") + w.b.WriteString(extra + "\n") + } + return w.b.String() +} + +func normalizePrefix(p string) string { + p = strings.TrimPrefix(strings.TrimPrefix(strings.TrimSpace(p), "https://"), "http://") + return strings.TrimRight(p, "/") + "/" +} + +// HostsINI renders inventory/hosts. +func (c *Config) HostsINI() string { + var b strings.Builder + b.WriteString("# Generated by interzone.\n[matrix_servers]\n") + parts := []string{c.HostName()} + t := c.Target + if t.Mode == "local" { + parts = append(parts, "ansible_connection=local") + if os.Geteuid() != 0 { + parts = append(parts, "ansible_become=true", "ansible_become_user=root") + } + } else { + parts = append(parts, "ansible_host="+t.Host, "ansible_ssh_user="+t.User) + if t.Port != "" && t.Port != "22" { + parts = append(parts, "ansible_port="+t.Port) + } + if t.SSHKey != "" { + parts = append(parts, "ansible_ssh_private_key_file="+t.SSHKey) + } + if t.User != "root" { + parts = append(parts, "ansible_become=true", "ansible_become_user=root") + } + } + if t.BecomePass != "" { + parts = append(parts, "ansible_become_password="+Quote(t.BecomePass)) + } + b.WriteString(strings.Join(parts, " ") + "\n") + return b.String() +} + +// DNSRecords lists the hostnames that must point at the server. +func (c *Config) DNSRecords() []string { + recs := []string{"matrix." + c.Domain} + for _, comp := range catalog.Components { + if comp.Subdomain != "" && c.Enabled(comp) { + recs = append(recs, comp.Subdomain+"."+c.Domain) + } + } + if c.Components["base-domain"] { + recs = append(recs, c.Domain) + } + return recs +} diff --git a/internal/config/secrets.go b/internal/config/secrets.go new file mode 100644 index 0000000..fa1b34e --- /dev/null +++ b/internal/config/secrets.go @@ -0,0 +1,82 @@ +package config + +import ( + "crypto/ecdsa" + "crypto/elliptic" + "crypto/rand" + "crypto/x509" + "crypto/x509/pkix" + "encoding/hex" + "encoding/pem" + "math/big" + "os" + "path/filepath" + "time" +) + +const alphabet = "abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789" + +// RandomPassword returns n characters that are safe to drop into YAML and shells. +func RandomPassword(n int) string { + b := make([]byte, n) + max := big.NewInt(int64(len(alphabet))) + for i := range b { + v, err := rand.Int(rand.Reader, max) + if err != nil { + panic(err) + } + b[i] = alphabet[v.Int64()] + } + return string(b) +} + +func RandomHex(nBytes int) string { + b := make([]byte, nBytes) + if _, err := rand.Read(b); err != nil { + panic(err) + } + return hex.EncodeToString(b) +} + +// SelfSignedCert writes a wildcard certificate for domain and *.domain into +// dir, reusing an existing pair so re-runs don't rotate it. +func SelfSignedCert(dir, domain string) (certPath, keyPath string, err error) { + certPath = filepath.Join(dir, "cert.pem") + keyPath = filepath.Join(dir, "privkey.pem") + if _, err := os.Stat(certPath); err == nil { + if _, err := os.Stat(keyPath); err == nil { + return certPath, keyPath, nil + } + } + if err = os.MkdirAll(dir, 0o700); err != nil { + return + } + key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) + if err != nil { + return + } + serial, _ := rand.Int(rand.Reader, new(big.Int).Lsh(big.NewInt(1), 120)) + tmpl := &x509.Certificate{ + SerialNumber: serial, + Subject: pkix.Name{CommonName: domain, Organization: []string{"interzone self-signed"}}, + DNSNames: []string{domain, "*." + domain, "*.element." + domain}, + NotBefore: time.Now().Add(-time.Hour), + NotAfter: time.Now().AddDate(10, 0, 0), + KeyUsage: x509.KeyUsageDigitalSignature | x509.KeyUsageKeyEncipherment, + ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}, + BasicConstraintsValid: true, + } + der, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, &key.PublicKey, key) + if err != nil { + return + } + keyDER, err := x509.MarshalECPrivateKey(key) + if err != nil { + return + } + if err = os.WriteFile(certPath, pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: der}), 0o644); err != nil { + return + } + err = os.WriteFile(keyPath, pem.EncodeToMemory(&pem.Block{Type: "EC PRIVATE KEY", Bytes: keyDER}), 0o600) + return +} diff --git a/internal/deploy/check.go b/internal/deploy/check.go new file mode 100644 index 0000000..d58fbda --- /dev/null +++ b/internal/deploy/check.go @@ -0,0 +1,124 @@ +package deploy + +import ( + "context" + "fmt" + "net/http" + "os/exec" + "strings" + "sync" + "time" + + "interzone/internal/config" +) + +type Check struct { + Name string + Target string + OK bool + Detail string +} + +// Preflight probes every configured source plus the local toolchain in parallel. +func Preflight(c *config.Config) []Check { + type probe struct { + name, target string + fn func(context.Context) (string, error) + } + var probes []probe + add := func(name, target string, fn func(context.Context) (string, error)) { + probes = append(probes, probe{name, target, fn}) + } + + for _, bin := range []string{"git", "ansible-playbook", "ansible-galaxy"} { + bin := bin + add("Local tool", bin, func(context.Context) (string, error) { + p, err := lookPath(bin) + if err != nil { + if strings.HasPrefix(bin, "ansible") { + return "", fmt.Errorf("not installed; will be installed from PyPI into a private venv") + } + return "", fmt.Errorf("not installed") + } + return p, nil + }) + } + s := c.Sources + add("Playbook git", s.PlaybookGit, func(ctx context.Context) (string, error) { return gitReachable(ctx, s.PlaybookGit) }) + if s.RolesGitBase != "" { + u := strings.TrimRight(s.RolesGitBase, "/") + "/mother-of-all-self-hosting/ansible-role-aux" + add("Roles git mirror", s.RolesGitBase, func(ctx context.Context) (string, error) { return gitReachable(ctx, u) }) + } + if s.UseRegistry && s.RegistryPrefix != "" { + host := strings.SplitN(strings.TrimPrefix(strings.TrimPrefix(s.RegistryPrefix, "https://"), "http://"), "/", 2)[0] + add("Container registry", s.RegistryPrefix, func(ctx context.Context) (string, error) { + return httpReachable(ctx, "https://"+host+"/v2/") + }) + } + if s.DockerPackageURL != "" { + add("Docker packages", s.DockerPackageURL, func(ctx context.Context) (string, error) { return httpReachable(ctx, s.DockerPackageURL) }) + } + if s.APTMirror != "" { + add("APT mirror", s.APTMirror, func(ctx context.Context) (string, error) { return httpReachable(ctx, s.APTMirror) }) + } + if s.PyPIIndex != "" { + u := strings.TrimRight(s.PyPIIndex, "/") + "/ansible/" + add("PyPI mirror", s.PyPIIndex, func(ctx context.Context) (string, error) { return httpReachable(ctx, u) }) + } + + out := make([]Check, len(probes)) + var wg sync.WaitGroup + for i, p := range probes { + wg.Add(1) + go func(i int, p probe) { + defer wg.Done() + ctx, cancel := context.WithTimeout(context.Background(), 12*time.Second) + defer cancel() + detail, err := p.fn(ctx) + out[i] = Check{Name: p.name, Target: p.target, OK: err == nil, Detail: detail} + if err != nil { + out[i].Detail = err.Error() + } + }(i, p) + } + wg.Wait() + return out +} + +func gitReachable(ctx context.Context, url string) (string, error) { + cmd := exec.CommandContext(ctx, "git", "ls-remote", url, "HEAD") + cmd.Env = append(cmd.Environ(), "GIT_TERMINAL_PROMPT=0") + b, err := cmd.Output() + if err != nil { + if ctx.Err() != nil { + return "", fmt.Errorf("timed out") + } + return "", fmt.Errorf("unreachable") + } + if f := strings.Fields(string(b)); len(f) > 0 { + return "HEAD " + f[0][:min(10, len(f[0]))], nil + } + return "reachable", nil +} + +func httpReachable(ctx context.Context, url string) (string, error) { + if !strings.Contains(url, "://") { + url = "https://" + url + } + req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil) + if err != nil { + return "", err + } + resp, err := http.DefaultClient.Do(req) + if err != nil { + if ctx.Err() != nil { + return "", fmt.Errorf("timed out") + } + return "", fmt.Errorf("unreachable") + } + resp.Body.Close() + if resp.StatusCode >= 500 { + return "", fmt.Errorf("HTTP %d", resp.StatusCode) + } + return fmt.Sprintf("HTTP %d", resp.StatusCode), nil +} diff --git a/internal/deploy/deploy.go b/internal/deploy/deploy.go new file mode 100644 index 0000000..20e75e6 --- /dev/null +++ b/internal/deploy/deploy.go @@ -0,0 +1,304 @@ +// Package deploy drives git and Ansible to install the playbook, streaming +// progress back to the UI as events. +package deploy + +import ( + "bufio" + "context" + "fmt" + "io" + "os" + "os/exec" + "path/filepath" + "regexp" + "strings" + + "interzone/internal/config" +) + +type Step int + +const ( + StepAnsible Step = iota + StepPlaybook + StepInventory + StepRoles + StepAPT + StepInstall + StepDone +) + +var StepNames = []string{ + "Prepare Ansible", + "Fetch playbook", + "Write configuration", + "Install Ansible roles", + "Point server at APT mirror", + "Run the playbook", +} + +type Event struct { + Step Step + Started bool // a step began + Skipped bool // a step was not needed + Line string // a line of command output + Task string // current Ansible task, when Line starts one + Failed bool // Line reports a failed task + Err error // the whole run failed + Done bool // the whole run finished successfully +} + +type Options struct { + SaveOnly bool // write configuration but don't run Ansible +} + +func venvDir() string { return filepath.Join(filepath.Dir(config.Default().PlaybookDir), "venv") } + +// lookPath also finds tools in the venv interzone creates when Ansible is missing. +func lookPath(bin string) (string, error) { + if p, err := exec.LookPath(bin); err == nil { + return p, nil + } + p := filepath.Join(venvDir(), "bin", bin) + if _, err := os.Stat(p); err == nil { + return p, nil + } + return "", exec.ErrNotFound +} + +type Runner struct { + cfg *config.Config + opts Options + events chan Event + env []string +} + +// Start launches the deployment in the background. Events arrive on the +// returned channel, which is closed when the run ends. +func Start(ctx context.Context, cfg *config.Config, opts Options) <-chan Event { + r := &Runner{cfg: cfg, opts: opts, events: make(chan Event, 256)} + go func() { + defer close(r.events) + if err := r.run(ctx); err != nil { + r.events <- Event{Err: err} + return + } + r.events <- Event{Done: true, Step: StepDone} + }() + return r.events +} + +func (r *Runner) emit(e Event) { r.events <- e } + +func (r *Runner) begin(s Step) { r.emit(Event{Step: s, Started: true}) } +func (r *Runner) skip(s Step, why string) { + r.emit(Event{Step: s, Skipped: true, Line: why}) +} + +func (r *Runner) run(ctx context.Context) error { + r.env = append(os.Environ(), + "GIT_TERMINAL_PROMPT=0", + "ANSIBLE_NOCOLOR=1", + "ANSIBLE_FORCE_COLOR=0", + "ANSIBLE_HOST_KEY_CHECKING=False", + "ANSIBLE_STDOUT_CALLBACK=default", + "PATH="+filepath.Join(venvDir(), "bin")+string(os.PathListSeparator)+os.Getenv("PATH"), + ) + if base := r.cfg.Sources.RolesGitBase; base != "" && strings.TrimRight(base, "/") != strings.TrimRight(config.UpstreamGitHub, "/") { + // Any git fetch of a github.com URL (requirements.yml) is redirected to the mirror. + r.env = append(r.env, + "GIT_CONFIG_COUNT=1", + "GIT_CONFIG_KEY_0=url."+strings.TrimRight(base, "/")+"/.insteadOf", + "GIT_CONFIG_VALUE_0="+config.UpstreamGitHub, + ) + } + if idx := r.cfg.Sources.PyPIIndex; idx != "" { + r.env = append(r.env, "PIP_INDEX_URL="+idx) + } + + steps := []func(context.Context) error{r.ansible, r.playbook, r.inventory, r.roles, r.apt, r.install} + for i, fn := range steps { + if r.opts.SaveOnly && (Step(i) == StepAnsible || Step(i) >= StepRoles) { + r.skip(Step(i), "save-only mode") + continue + } + if err := fn(ctx); err != nil { + return fmt.Errorf("%s: %w", StepNames[i], err) + } + } + return nil +} + +func (r *Runner) ansible(ctx context.Context) error { + if _, err := lookPath("ansible-playbook"); err == nil { + r.skip(StepAnsible, "ansible is already installed") + return nil + } + r.begin(StepAnsible) + if err := r.exec(ctx, StepAnsible, "", "python3", "-m", "venv", venvDir()); err != nil { + return err + } + args := []string{"install", "--upgrade", "ansible", "passlib"} + if idx := r.cfg.Sources.PyPIIndex; idx != "" { + args = append(args, "--index-url", idx) + } + return r.exec(ctx, StepAnsible, "", filepath.Join(venvDir(), "bin", "pip"), args...) +} + +func (r *Runner) playbook(ctx context.Context) error { + r.begin(StepPlaybook) + dir := r.cfg.PlaybookDir + if _, err := os.Stat(filepath.Join(dir, ".git")); err == nil { + if err := r.exec(ctx, StepPlaybook, dir, "git", "remote", "set-url", "origin", r.cfg.Sources.PlaybookGit); err != nil { + return err + } + return r.exec(ctx, StepPlaybook, dir, "git", "pull", "--ff-only") + } + if err := os.MkdirAll(filepath.Dir(dir), 0o755); err != nil { + return err + } + return r.exec(ctx, StepPlaybook, "", "git", "clone", "--depth", "1", r.cfg.Sources.PlaybookGit, dir) +} + +func (r *Runner) inventory(ctx context.Context) error { + r.begin(StepInventory) + c := r.cfg + inv := filepath.Join(c.PlaybookDir, "inventory") + hostDir := filepath.Join(inv, "host_vars", c.HostName()) + if err := os.MkdirAll(hostDir, 0o700); err != nil { + return err + } + + var cert, key string + switch c.SSL.Mode { + case "selfsigned": + var err error + cert, key, err = config.SelfSignedCert(filepath.Join(config.Dir(), "ssl", c.Domain), c.Domain) + if err != nil { + return fmt.Errorf("self-signed certificate: %w", err) + } + r.emit(Event{Step: StepInventory, Line: "self-signed certificate: " + cert}) + case "custom": + cert, key = c.SSL.CertPath, c.SSL.KeyPath + } + + vars := c.VarsYAML(config.MigrationVersion(c.PlaybookDir), cert, key) + files := map[string]string{ + filepath.Join(hostDir, "vars.yml"): vars, + filepath.Join(inv, "hosts"): c.HostsINI(), + } + for path, body := range files { + if err := os.WriteFile(path, []byte(body), 0o600); err != nil { + return err + } + r.emit(Event{Step: StepInventory, Line: "wrote " + path}) + } + return nil +} + +func (r *Runner) roles(ctx context.Context) error { + r.begin(StepRoles) + return r.exec(ctx, StepRoles, r.cfg.PlaybookDir, "ansible-galaxy", "install", "-r", "requirements.yml", "-p", "roles/galaxy/", "--force") +} + +const aptPlay = `- name: Point APT at the in-country mirror + hosts: matrix_servers + become: true + gather_facts: true + tasks: + - name: Find APT source files + ansible.builtin.find: + paths: [/etc/apt, /etc/apt/sources.list.d] + patterns: ["sources.list", "*.list", "*.sources"] + register: interzone_apt_sources + when: ansible_facts.os_family == 'Debian' + + - name: Rewrite Debian/Ubuntu archive hosts to the mirror + ansible.builtin.replace: + path: "{{ item.path }}" + regexp: 'https?://(?:(?:[a-z0-9-]+\.)*(?:archive|security|ports)\.ubuntu\.com|(?:[a-z0-9-]+\.)*debian\.org)' + replace: "{{ interzone_apt_mirror }}" + backup: true + loop: "{{ interzone_apt_sources.files | default([]) }}" + when: ansible_facts.os_family == 'Debian' + + - name: Warn about unsupported distributions + ansible.builtin.debug: + msg: "APT mirror skipped: {{ ansible_facts.distribution }} is not Debian-based." + when: ansible_facts.os_family != 'Debian' +` + +func (r *Runner) apt(ctx context.Context) error { + mirror := strings.TrimRight(r.cfg.Sources.APTMirror, "/") + if mirror == "" { + r.skip(StepAPT, "no APT mirror configured") + return nil + } + r.begin(StepAPT) + play := filepath.Join(r.cfg.PlaybookDir, "inventory", "interzone-apt-mirror.yml") + if err := os.WriteFile(play, []byte(aptPlay), 0o644); err != nil { + return err + } + return r.exec(ctx, StepAPT, r.cfg.PlaybookDir, "ansible-playbook", "-i", "inventory/hosts", play, + "-e", "interzone_apt_mirror="+mirror) +} + +func (r *Runner) install(ctx context.Context) error { + r.begin(StepInstall) + return r.exec(ctx, StepInstall, r.cfg.PlaybookDir, "ansible-playbook", "-i", "inventory/hosts", "setup.yml", + "--tags=install-all,ensure-matrix-users-created,start") +} + +var taskLine = regexp.MustCompile(`^(?:TASK|PLAY|RUNNING HANDLER) \[(.*)\]`) + +// exec runs a command and streams every output line as an event. +func (r *Runner) exec(ctx context.Context, step Step, dir, name string, args ...string) error { + if p, err := lookPath(name); err == nil { + name = p + } + r.emit(Event{Step: step, Line: "$ " + filepath.Base(name) + " " + strings.Join(redact(args), " ")}) + cmd := exec.CommandContext(ctx, name, args...) + cmd.Dir = dir + cmd.Env = r.env + pr, pw := io.Pipe() + cmd.Stdout = pw + cmd.Stderr = pw + if err := cmd.Start(); err != nil { + return err + } + done := make(chan struct{}) + go func() { + defer close(done) + sc := bufio.NewScanner(pr) + sc.Buffer(make([]byte, 64*1024), 1024*1024) + for sc.Scan() { + line := strings.TrimRight(sc.Text(), " *") + if strings.TrimSpace(line) == "" { + continue + } + ev := Event{Step: step, Line: line} + if m := taskLine.FindStringSubmatch(line); m != nil { + ev.Task = m[1] + } + if strings.HasPrefix(line, "fatal:") || strings.HasPrefix(line, "failed:") { + ev.Failed = true + } + r.emit(ev) + } + }() + err := cmd.Wait() + pw.Close() + <-done + return err +} + +func redact(args []string) []string { + out := make([]string, len(args)) + for i, a := range args { + if strings.Contains(a, "password") { + a = strings.SplitN(a, "=", 2)[0] + "=••••" + } + out[i] = a + } + return out +} diff --git a/internal/ui/app.go b/internal/ui/app.go new file mode 100644 index 0000000..5550059 --- /dev/null +++ b/internal/ui/app.go @@ -0,0 +1,210 @@ +// Package ui is the bubbletea front-end: a step-by-step wizard that ends in +// a live deployment view. +package ui + +import ( + "strings" + + tea "github.com/charmbracelet/bubbletea" + "github.com/charmbracelet/lipgloss" + + "interzone/internal/config" +) + +type screen interface { + name() string // short name for the stepper + title() string + enter(c *config.Config) tea.Cmd + leave(c *config.Config) + update(msg tea.Msg) tea.Cmd + view(w, h int) string + keys() [][2]string + typing() bool // printable keys go to an input +} + +type navMsg int + +func nav(dir int) tea.Cmd { return func() tea.Msg { return navMsg(dir) } } + +type App struct { + cfg *config.Config + loaded bool + screens []screen + step int + w, h int + status string +} + +func New(cfg *config.Config, loaded bool) *App { + a := &App{cfg: cfg, loaded: loaded} + a.screens = []screen{ + &welcomeScreen{loaded: loaded}, + newNetworkScreen(), + newServerScreen(), + &homeserverScreen{}, + newSSLScreen(), + newComponentsScreen(), + &settingsScreen{}, + newReviewScreen(), + newDeployScreen(), + } + return a +} + +func (a *App) Init() tea.Cmd { return a.screens[0].enter(a.cfg) } + +func (a *App) cur() screen { return a.screens[a.step] } + +func (a *App) go_(dir int) tea.Cmd { + n := a.step + dir + if n < 0 || n >= len(a.screens) { + return nil + } + a.cur().leave(a.cfg) + if err := a.cfg.Save(); err != nil { + a.status = "couldn't save config: " + err.Error() + } + a.step = n + return a.cur().enter(a.cfg) +} + +func (a *App) Update(msg tea.Msg) (tea.Model, tea.Cmd) { + switch m := msg.(type) { + case tea.WindowSizeMsg: + a.w, a.h = m.Width, m.Height + case navMsg: + return a, a.go_(int(m)) + case formDoneMsg: + return a, a.go_(1) + case tea.KeyMsg: + a.status = "" + ds, deploying := a.cur().(*deployScreen) + switch m.String() { + case "ctrl+c": + if deploying && ds.running { + ds.abort() + return a, nil + } + a.cur().leave(a.cfg) + _ = a.cfg.Save() + return a, tea.Quit + case "esc": + if deploying && ds.running { + return a, nil + } + if cs, ok := a.cur().(*componentsScreen); ok && (cs.filtering || cs.filter.Value() != "") { + break + } + return a, a.go_(-1) + case "ctrl+n", "pgdown": + if a.step < len(a.screens)-2 { + return a, a.go_(1) + } + case "ctrl+p", "pgup": + if !(deploying && ds.running) { + return a, a.go_(-1) + } + case "ctrl+s": + a.cur().leave(a.cfg) + if err := a.cfg.Save(); err != nil { + a.status = sBad.Render("save failed: " + err.Error()) + } else { + a.status = sGood.Render("✓ answers saved to " + config.Dir()) + } + return a, nil + case "q": + if !a.cur().typing() && !(deploying && ds.running) { + a.cur().leave(a.cfg) + _ = a.cfg.Save() + return a, tea.Quit + } + } + } + return a, a.cur().update(msg) +} + +func (a *App) View() string { + if a.w == 0 { + return "" + } + w := a.w + header := a.header(w) + stepper := a.stepper(w) + footer := a.footer(w) + + bodyH := a.h - lipgloss.Height(header) - lipgloss.Height(stepper) - lipgloss.Height(footer) - 2 + inner := w - 4 + title := sTitle.Render(a.cur().title()) + content := a.cur().view(inner, max(3, bodyH-3)) + body := sPanelFocus.Width(w - 2).Height(max(3, bodyH)).Render(title + "\n\n" + content) + + return lipgloss.JoinVertical(lipgloss.Left, header, stepper, body, footer) +} + +func (a *App) header(w int) string { + brand := gradient("◢◤ interzone") + sMuted.Render(" matrix, deployed anywhere") + mode := badge("ONLINE", cMint) + if a.cfg.Sources.Blackout { + mode = badge("BLACKOUT-READY", cAmber) + } + gap := w - lipgloss.Width(brand) - lipgloss.Width(mode) - 2 + return " " + brand + strings.Repeat(" ", max(1, gap)) + mode +} + +func (a *App) stepper(w int) string { + var parts []string + for i, s := range a.screens[1:] { + idx := i + 1 + switch { + case idx == a.step: + parts = append(parts, sAccent.Render("◉ "+s.name())) + case idx < a.step: + parts = append(parts, sGood.Render("●")+sMuted.Render(" "+s.name())) + default: + parts = append(parts, sFaint.Render("○ "+s.name())) + } + } + line := " " + strings.Join(parts, sFaint.Render(" ─ ")) + if lipgloss.Width(line) > w { + // Too narrow: show dots plus the current step's name. + var dots []string + for i := range a.screens[1:] { + switch { + case i+1 == a.step: + dots = append(dots, sAccent.Render("◉")) + case i+1 < a.step: + dots = append(dots, sGood.Render("●")) + default: + dots = append(dots, sFaint.Render("○")) + } + } + line = " " + strings.Join(dots, " ") + if a.step > 0 { + line += " " + sAccent.Render(a.cur().name()) + } + } + return line +} + +func (a *App) footer(w int) string { + var parts []string + for _, k := range a.cur().keys() { + parts = append(parts, sKey.Render(k[0])+" "+sMuted.Render(k[1])) + } + if a.step > 0 { + parts = append(parts, sKey.Render("esc")+" "+sMuted.Render("back")) + } + parts = append(parts, sKey.Render("ctrl+c")+" "+sMuted.Render("quit")) + line := " " + strings.Join(parts, sFaint.Render(" · ")) + if a.status != "" { + line = " " + a.status + } + return truncateANSI(line, w) +} + +func truncateANSI(s string, w int) string { + if lipgloss.Width(s) <= w { + return s + } + return lipgloss.NewStyle().MaxWidth(w).Render(s) +} diff --git a/internal/ui/form.go b/internal/ui/form.go new file mode 100644 index 0000000..5da5f95 --- /dev/null +++ b/internal/ui/form.go @@ -0,0 +1,353 @@ +package ui + +import ( + "strings" + + "github.com/charmbracelet/bubbles/textarea" + "github.com/charmbracelet/bubbles/textinput" + tea "github.com/charmbracelet/bubbletea" + "github.com/charmbracelet/lipgloss" +) + +type fieldKind int + +const ( + fText fieldKind = iota + fSecret + fToggle + fChoice + fArea +) + +type field struct { + key string + label string + help string + kind fieldKind + section string // rendered as a heading above the field when set + + input textinput.Model + area textarea.Model + on bool + choices []string + labels []string // display labels for choices; defaults to choices + choice int + + required bool + hidden func() bool +} + +func (f *field) visible() bool { return f.hidden == nil || !f.hidden() } + +func (f *field) Value() string { + switch f.kind { + case fToggle: + if f.on { + return "true" + } + return "false" + case fChoice: + return f.choices[f.choice] + case fArea: + return f.area.Value() + default: + return strings.TrimSpace(f.input.Value()) + } +} + +func newInput(value, placeholder string, secret bool) textinput.Model { + in := textinput.New() + in.SetValue(value) + in.Placeholder = placeholder + in.Prompt = "" + in.CharLimit = 4096 + in.Cursor.Style = lipgloss.NewStyle().Foreground(cPink) + in.TextStyle = lipgloss.NewStyle().Foreground(cText) + in.PlaceholderStyle = lipgloss.NewStyle().Foreground(cFaint) + if secret { + in.EchoMode = textinput.EchoPassword + in.EchoCharacter = '•' + } + return in +} + +func textField(key, label, value, placeholder, help string) *field { + return &field{key: key, label: label, help: help, kind: fText, input: newInput(value, placeholder, false)} +} + +func secretField(key, label, value, help string) *field { + return &field{key: key, label: label, help: help, kind: fSecret, input: newInput(value, "", true)} +} + +func toggleField(key, label string, on bool, help string) *field { + return &field{key: key, label: label, help: help, kind: fToggle, on: on} +} + +func choiceField(key, label string, choices, labels []string, value, help string) *field { + f := &field{key: key, label: label, help: help, kind: fChoice, choices: choices, labels: labels} + for i, c := range choices { + if c == value { + f.choice = i + } + } + return f +} + +func areaField(key, label, value, help string) *field { + ta := textarea.New() + ta.SetValue(value) + ta.ShowLineNumbers = false + ta.Prompt = "│ " + ta.CharLimit = 0 + ta.SetHeight(max(3, min(8, strings.Count(value, "\n")+2))) + ta.FocusedStyle.CursorLine = lipgloss.NewStyle() + ta.FocusedStyle.Prompt = lipgloss.NewStyle().Foreground(cPurple) + ta.BlurredStyle.Prompt = lipgloss.NewStyle().Foreground(cFaint) + ta.FocusedStyle.Text = lipgloss.NewStyle().Foreground(cText) + ta.BlurredStyle.Text = lipgloss.NewStyle().Foreground(cMuted) + ta.Blur() + return &field{key: key, label: label, help: help, kind: fArea, area: ta} +} + +// form is a vertically scrolling list of fields. +type form struct { + fields []*field + focus int + reveal bool + width int +} + +func newForm(fields ...*field) *form { + f := &form{fields: fields} + f.focus = -1 + f.move(1) + return f +} + +func (f *form) get(key string) *field { + for _, fl := range f.fields { + if fl.key == key { + return fl + } + } + return nil +} + +func (f *form) value(key string) string { + if fl := f.get(key); fl != nil { + return fl.Value() + } + return "" +} + +func (f *form) current() *field { + if f.focus < 0 || f.focus >= len(f.fields) { + return nil + } + return f.fields[f.focus] +} + +// move shifts focus by dir to the next visible field; it reports false when +// it would run off either end. +func (f *form) move(dir int) bool { + i := f.focus + for { + i += dir + if i < 0 || i >= len(f.fields) { + return false + } + if f.fields[i].visible() { + break + } + } + if c := f.current(); c != nil { + c.input.Blur() + c.area.Blur() + } + f.focus = i + c := f.fields[i] + switch c.kind { + case fText, fSecret: + c.input.Focus() + case fArea: + c.area.Focus() + } + return true +} + +// typing reports whether the focused field consumes printable keys. +func (f *form) typing() bool { + c := f.current() + return c != nil && (c.kind == fText || c.kind == fSecret || c.kind == fArea) +} + +type formDoneMsg struct{} + +// Update handles navigation and editing. Pressing enter on the last field +// returns formDoneMsg so the screen can advance. +func (f *form) Update(msg tea.Msg) tea.Cmd { + c := f.current() + if c == nil { + return nil + } + if k, ok := msg.(tea.KeyMsg); ok { + switch k.String() { + case "tab": + f.move(1) + return nil + case "shift+tab": + f.move(-1) + return nil + case "ctrl+r": + f.reveal = !f.reveal + for _, fl := range f.fields { + if fl.kind == fSecret { + if f.reveal { + fl.input.EchoMode = textinput.EchoNormal + } else { + fl.input.EchoMode = textinput.EchoPassword + } + } + } + return nil + } + if c.kind != fArea { + switch k.String() { + case "up": + f.move(-1) + return nil + case "down": + f.move(1) + return nil + case "enter": + if !f.move(1) { + return func() tea.Msg { return formDoneMsg{} } + } + return nil + } + } + switch c.kind { + case fToggle: + if k.String() == " " || k.String() == "x" || k.String() == "left" || k.String() == "right" { + c.on = !c.on + } + return nil + case fChoice: + switch k.String() { + case "left", "h": + c.choice = (c.choice + len(c.choices) - 1) % len(c.choices) + case "right", "l", " ": + c.choice = (c.choice + 1) % len(c.choices) + } + return nil + } + } + var cmd tea.Cmd + switch c.kind { + case fText, fSecret: + c.input, cmd = c.input.Update(msg) + case fArea: + c.area, cmd = c.area.Update(msg) + } + return cmd +} + +// View renders the form inside height lines, scrolled so the focused field stays visible. +func (f *form) View(width, height int) string { + f.width = width + var lines []string + focusStart, focusEnd := 0, 0 + for i, fl := range f.fields { + if !fl.visible() { + continue + } + if fl.section != "" { + lines = append(lines, strings.Split(sSection.Render("◆ "+fl.section), "\n")...) + } + start := len(lines) + lines = append(lines, strings.Split(f.renderField(fl, i == f.focus, width), "\n")...) + if i == f.focus { + focusStart, focusEnd = start, len(lines) + if fl.section != "" { + focusStart -= 2 // keep the heading and its margin in view + } + } + } + if len(lines) <= height { + return strings.Join(lines, "\n") + } + top := 0 + if focusEnd > height { + top = focusEnd - height + } + if focusStart < top { + top = focusStart + } + top = max(0, min(top, len(lines)-height)) + view := lines[top : top+height] + if top > 0 { + view[0] = sFaint.Render(strings.Repeat("─", 3) + " ▲ more ") + } + if top+height < len(lines) { + view[len(view)-1] = sFaint.Render(strings.Repeat("─", 3) + " ▼ more ") + } + return strings.Join(view, "\n") +} + +func (f *form) renderField(fl *field, focused bool, width int) string { + bar := sFaint.Render(" ") + label := sMuted.Render(fl.label) + if focused { + bar = sAccent.Render("▌ ") + label = sTitle.Render(fl.label) + } + if fl.required { + label += sPink.Render(" *") + } + inner := width - 4 + var body string + switch fl.kind { + case fToggle: + box := sFaint.Render("○") + if fl.on { + box = sGood.Render("●") + } + return bar + box + " " + label + helpLine(fl, focused, bar) + case fChoice: + var parts []string + for i, c := range fl.choices { + name := c + if fl.labels != nil { + name = fl.labels[i] + } + if i == fl.choice { + parts = append(parts, lipgloss.NewStyle().Foreground(lipgloss.Color("#111018")).Background(cPurple).Padding(0, 1).Render(name)) + } else { + parts = append(parts, sMuted.Padding(0, 1).Render(name)) + } + } + body = strings.Join(parts, " ") + case fArea: + fl.area.SetWidth(max(20, inner)) + body = fl.area.View() + default: + fl.input.Width = max(10, inner-2) + v := fl.input.View() + if !focused && fl.input.Value() == "" && fl.required { + v = sBad.Render("required") + } + body = v + } + out := bar + label + "\n" + for _, l := range strings.Split(body, "\n") { + out += bar + " " + l + "\n" + } + return strings.TrimRight(out, "\n") + helpLine(fl, focused, bar) +} + +func helpLine(fl *field, focused bool, bar string) string { + if fl.help == "" || !focused { + return "" + } + return "\n" + bar + " " + lipgloss.NewStyle().Foreground(cMuted).Italic(true).Render(fl.help) +} diff --git a/internal/ui/screens_components.go b/internal/ui/screens_components.go new file mode 100644 index 0000000..5d95000 --- /dev/null +++ b/internal/ui/screens_components.go @@ -0,0 +1,369 @@ +package ui + +import ( + "fmt" + "strings" + + "github.com/charmbracelet/bubbles/textinput" + tea "github.com/charmbracelet/bubbletea" + "github.com/charmbracelet/lipgloss" + + "interzone/internal/catalog" + "interzone/internal/config" +) + +// ── Components ───────────────────────────────────────────────────── + +type componentsScreen struct { + cfg *config.Config + selected map[string]bool + cat int + cursor int + offset int + filter textinput.Model + filtering bool +} + +func newComponentsScreen() *componentsScreen { + in := textinput.New() + in.Prompt = "/ " + in.PromptStyle = sAccent + in.Placeholder = "search every component…" + in.PlaceholderStyle = sFaint + return &componentsScreen{filter: in} +} + +func (s *componentsScreen) name() string { return "Components" } +func (s *componentsScreen) title() string { return "Pick what you want on your server" } +func (s *componentsScreen) typing() bool { return s.filtering } +func (s *componentsScreen) keys() [][2]string { + if s.filtering { + return [][2]string{{"type", "search"}, {"↑↓", "move"}, {"space", "toggle"}, {"enter", "done"}} + } + return [][2]string{{"←→", "category"}, {"↑↓", "move"}, {"space", "toggle"}, {"/", "search"}, {"enter", "next"}} +} + +func (s *componentsScreen) enter(c *config.Config) tea.Cmd { + s.cfg = c + s.selected = map[string]bool{} + for k, v := range c.Components { + s.selected[k] = v + } + return nil +} + +func (s *componentsScreen) leave(c *config.Config) { + c.Components = s.selected + c.FillGenerated() +} + +// items returns what the list currently shows: a category, or search results. +func (s *componentsScreen) items() []catalog.Component { + var out []catalog.Component + q := strings.ToLower(strings.TrimSpace(s.filter.Value())) + for _, c := range catalog.Components { + if q != "" { + if strings.Contains(strings.ToLower(c.Name+" "+c.Description+" "+c.Category), q) { + out = append(out, c) + } + } else if c.Category == catalog.Categories[s.cat] { + out = append(out, c) + } + } + return out +} + +func (s *componentsScreen) available(c catalog.Component) bool { + return !c.SynapseOnly || s.cfg.Homeserver == "synapse" +} + +func (s *componentsScreen) update(msg tea.Msg) tea.Cmd { + k, ok := msg.(tea.KeyMsg) + if !ok { + return nil + } + items := s.items() + switch k.String() { + case "up", "ctrl+k": + s.cursor = max(0, s.cursor-1) + return nil + case "down", "ctrl+j": + s.cursor = min(len(items)-1, s.cursor+1) + return nil + case " ", "ctrl+@": + if s.cursor < len(items) { + it := items[s.cursor] + if s.available(it) { + s.selected[it.ID] = !s.selected[it.ID] + } + } + return nil + } + if s.filtering { + switch k.String() { + case "enter", "esc": + s.filtering = false + s.filter.Blur() + if k.String() == "esc" { + s.filter.SetValue("") + s.cursor = 0 + } + return nil + } + var cmd tea.Cmd + s.filter, cmd = s.filter.Update(msg) + s.cursor = 0 + return cmd + } + switch k.String() { + case "esc": + s.filter.SetValue("") + s.cursor, s.offset = 0, 0 + case "left", "h", "shift+tab": + s.filter.SetValue("") + s.cat = (s.cat + len(catalog.Categories) - 1) % len(catalog.Categories) + s.cursor, s.offset = 0, 0 + case "right", "l", "tab": + s.filter.SetValue("") + s.cat = (s.cat + 1) % len(catalog.Categories) + s.cursor, s.offset = 0, 0 + case "k": + s.cursor = max(0, s.cursor-1) + case "j": + s.cursor = min(len(items)-1, s.cursor+1) + case "/": + s.filtering = true + s.filter.SetValue("") + return s.filter.Focus() + case "enter": + return nav(1) + } + return nil +} + +func (s *componentsScreen) view(w, h int) string { + // Category tabs. + var tabs []string + for i, cat := range catalog.Categories { + n, on := 0, 0 + for _, c := range catalog.Components { + if c.Category == cat { + n++ + if s.selected[c.ID] && s.available(c) { + on++ + } + } + } + label := fmt.Sprintf("%s %d/%d", cat, on, n) + if i == s.cat && s.filter.Value() == "" { + tabs = append(tabs, lipgloss.NewStyle().Foreground(lipgloss.Color("#111018")).Background(cPurple).Bold(true).Padding(0, 1).Render(label)) + } else { + tabs = append(tabs, sMuted.Padding(0, 1).Render(label)) + } + } + tabLine := tabStrip(tabs, s.cat, w-14) + + top := tabLine + if s.filtering || s.filter.Value() != "" { + top = s.filter.View() + } + + items := s.items() + s.cursor = max(0, min(s.cursor, len(items)-1)) + + detail := s.detail(items, w) + listH := max(3, h-lipgloss.Height(top)-lipgloss.Height(detail)-2) + if s.cursor < s.offset { + s.offset = s.cursor + } + if s.cursor >= s.offset+listH { + s.offset = s.cursor - listH + 1 + } + + var rows []string + for i := s.offset; i < len(items) && i < s.offset+listH; i++ { + rows = append(rows, s.row(items[i], i == s.cursor, w)) + } + if len(items) == 0 { + rows = append(rows, sMuted.Render(" nothing matches")) + } + list := lipgloss.NewStyle().Height(listH).Render(strings.Join(rows, "\n")) + + count := 0 + for _, c := range catalog.Components { + if s.selected[c.ID] && s.available(c) { + count++ + } + } + total := sMuted.Render(fmt.Sprintf("%d selected", count)) + return lipgloss.JoinVertical(lipgloss.Left, top+" "+total, "", list, detail) +} + +// tabStrip fits the tabs on one line, keeping the current tab visible and +// marking hidden ones with arrows. +func tabStrip(tabs []string, cur, w int) string { + lo, hi := cur, cur+1 + width := lipgloss.Width(tabs[cur]) + 4 + for { + grew := false + if hi < len(tabs) && width+lipgloss.Width(tabs[hi]) <= w { + width += lipgloss.Width(tabs[hi]) + hi++ + grew = true + } + if lo > 0 && width+lipgloss.Width(tabs[lo-1]) <= w { + lo-- + width += lipgloss.Width(tabs[lo]) + grew = true + } + if !grew { + break + } + } + left, right := " ", " " + if lo > 0 { + left = sAccent.Render("‹ ") + } + if hi < len(tabs) { + right = sAccent.Render(" ›") + } + return left + strings.Join(tabs[lo:hi], "") + right +} + +func (s *componentsScreen) row(c catalog.Component, cur bool, w int) string { + box := sFaint.Render("○") + if s.selected[c.ID] { + box = sGood.Render("●") + } + name := c.Name + style := sTitle + if !cur { + style = lipgloss.NewStyle().Foreground(cText) + } + var tags []string + if !s.available(c) { + box = sFaint.Render("⊘") + style = sFaint + tags = append(tags, sFaint.Render("Synapse only")) + } + if c.Status != "" { + tags = append(tags, sWarn.Render(c.Status)) + } + if len(c.Fields) > 0 && s.available(c) { + tags = append(tags, sFaint.Render("needs settings")) + } + if s.filter.Value() != "" { + tags = append(tags, sFaint.Render(c.Category)) + } + pointer := " " + if cur { + pointer = sAccent.Render("› ") + } + line := pointer + box + " " + style.Render(name) + if len(tags) > 0 { + line += " " + strings.Join(tags, sFaint.Render(" · ")) + } + return truncateANSI(line, w) +} + +func (s *componentsScreen) detail(items []catalog.Component, w int) string { + if len(items) == 0 { + return "" + } + c := items[s.cursor] + body := sTitle.Render(c.Name) + "\n" + sSub.Render(c.Description) + if c.Subdomain != "" { + body += "\n" + sMuted.Render("Needs DNS: ") + sPink.Render(c.Subdomain+".") + } + body += "\n" + sFaint.Render("docs/"+c.Doc) + return sPanel.Width(w - 2).Render(body) +} + +// ── Settings ─────────────────────────────────────────────────────── + +type settingsScreen struct { + form *form + vars map[string]string // form key → vars.yml variable +} + +func (s *settingsScreen) name() string { return "Settings" } +func (s *settingsScreen) title() string { return "Fill in the details" } +func (s *settingsScreen) typing() bool { return s.form.typing() } +func (s *settingsScreen) keys() [][2]string { + return [][2]string{{"tab/↑↓", "move"}, {"space", "toggle"}, {"ctrl+r", "reveal secrets"}, {"enter", "next"}} +} + +func (s *settingsScreen) enter(c *config.Config) tea.Cmd { + c.FillGenerated() + var fields []*field + switch c.Homeserver { + case "synapse", "dendrite": + u := textField("admin.user", "Admin username", c.AdminUser, "admin", "Created automatically after install.") + u.section = "Your admin account" + fields = append(fields, u, secretField("admin.pass", "Admin password", c.AdminPassword, "Generated for you. Press ctrl+r to see it.")) + case "continuwuity", "tuwunel": + t := secretField("admin.pass", "Registration token", c.AdminPassword, + "Use this token in any client to register your first account.") + t.section = "Your admin account" + fields = append(fields, t) + } + + s.vars = map[string]string{} + for _, comp := range catalog.Components { + if !c.Enabled(comp) || len(comp.Fields) == 0 { + continue + } + for i, f := range comp.Fields { + key := comp.ID + "." + f.Var + s.vars[key] = f.Var + v := c.Values[f.Var] + var fl *field + switch f.Kind { + case catalog.Bool: + fl = toggleField(key, f.Label, v == "true", f.Help) + case catalog.Secret, catalog.Hex64: + fl = secretField(key, f.Label, v, f.Help) + case catalog.YAML: + fl = areaField(key, f.Label, v, f.Help) + case catalog.List: + fl = textField(key, f.Label, v, "comma, separated, values", f.Help) + default: + fl = textField(key, f.Label, v, f.Default, f.Help) + } + fl.required = f.Required + if f.ShowIf != "" { + dep := comp.ID + "." + f.ShowIf + fl.hidden = func() bool { return s.form.value(dep) != "true" } + } + if i == 0 { + fl.section = comp.Name + } + fields = append(fields, fl) + } + } + extra := areaField("extra", "Extra vars.yml lines", c.ExtraYAML, + "Anything else from the MDAD docs. Written at the end of vars.yml as-is.") + extra.section = "Advanced" + fields = append(fields, extra) + s.form = newForm(fields...) + return nil +} + +func (s *settingsScreen) leave(c *config.Config) { + f := s.form + if fl := f.get("admin.user"); fl != nil { + c.AdminUser = fl.Value() + } + if fl := f.get("admin.pass"); fl != nil { + c.AdminPassword = fl.Value() + } + for key, v := range s.vars { + c.Values[v] = f.value(key) + } + c.ExtraYAML = f.value("extra") +} + +func (s *settingsScreen) update(msg tea.Msg) tea.Cmd { return s.form.Update(msg) } +func (s *settingsScreen) view(w, h int) string { + return s.form.View(w, h) +} diff --git a/internal/ui/screens_deploy.go b/internal/ui/screens_deploy.go new file mode 100644 index 0000000..14e6f71 --- /dev/null +++ b/internal/ui/screens_deploy.go @@ -0,0 +1,523 @@ +package ui + +import ( + "context" + "fmt" + "os" + "path/filepath" + "regexp" + "strings" + "time" + + "github.com/charmbracelet/bubbles/progress" + "github.com/charmbracelet/bubbles/spinner" + "github.com/charmbracelet/bubbles/viewport" + tea "github.com/charmbracelet/bubbletea" + "github.com/charmbracelet/lipgloss" + + "interzone/internal/catalog" + "interzone/internal/config" + "interzone/internal/deploy" +) + +// ── Review ───────────────────────────────────────────────────────── + +type startDeployMsg struct{ saveOnly bool } + +type reviewScreen struct { + cfg *config.Config + missing []string + vp viewport.Model + yaml string +} + +func newReviewScreen() *reviewScreen { return &reviewScreen{vp: viewport.New(0, 0)} } + +func (s *reviewScreen) name() string { return "Review" } +func (s *reviewScreen) title() string { return "Everything look right?" } +func (s *reviewScreen) typing() bool { return false } +func (s *reviewScreen) keys() [][2]string { + k := [][2]string{{"↑↓", "scroll vars.yml"}, {"s", "save files only"}} + if len(s.missing) == 0 { + k = append([][2]string{{"enter", "deploy"}}, k...) + } + return k +} + +func (s *reviewScreen) enter(c *config.Config) tea.Cmd { + s.cfg = c + c.FillGenerated() + s.missing = c.Missing() + cert, key := "", "" + if c.SSL.Mode == "custom" { + cert, key = c.SSL.CertPath, c.SSL.KeyPath + } + s.yaml = c.VarsYAML(config.MigrationVersion(c.PlaybookDir), cert, key) + s.vp.SetContent(highlightYAML(s.yaml)) + s.vp.GotoTop() + return nil +} + +func (s *reviewScreen) leave(*config.Config) {} + +func (s *reviewScreen) update(msg tea.Msg) tea.Cmd { + if k, ok := msg.(tea.KeyMsg); ok { + switch k.String() { + case "enter", "d": + if len(s.missing) == 0 { + return tea.Sequence(nav(1), func() tea.Msg { return startDeployMsg{} }) + } + return nil + case "s": + return tea.Sequence(nav(1), func() tea.Msg { return startDeployMsg{saveOnly: true} }) + } + } + var cmd tea.Cmd + s.vp, cmd = s.vp.Update(msg) + return cmd +} + +func (s *reviewScreen) view(w, h int) string { + c := s.cfg + hs := c.Homeserver + for _, x := range catalog.Homeservers { + if x.ID == c.Homeserver { + hs = x.Name + } + } + n := 0 + for _, comp := range catalog.Components { + if c.Enabled(comp) { + n++ + } + } + where := "this machine" + if c.Target.Mode == "ssh" { + where = c.Target.User + "@" + c.Target.Host + } + kv := func(k, v string) string { + return lipgloss.NewStyle().Width(14).Render(sMuted.Render(k)) + sTitle.Render(v) + } + summary := []string{ + kv("Domain", c.Domain), + kv("Homeserver", hs), + kv("Install on", where), + kv("Components", fmt.Sprint(n)), + kv("Certificates", sslLabels[indexOf(sslModes, c.SSL.Mode)]), + kv("Images from", map[bool]string{true: c.Sources.RegistryPrefix, false: "upstream registries"}[c.Sources.UseRegistry]), + } + + var status []string + if len(s.missing) > 0 { + status = append(status, sBad.Render(fmt.Sprintf("✗ %d required setting(s) missing. Go back with esc:", len(s.missing)))) + for i, m := range s.missing { + if i == 5 { + status = append(status, sMuted.Render(fmt.Sprintf(" …and %d more", len(s.missing)-5))) + break + } + status = append(status, sBad.Render(" • ")+m) + } + } else { + status = append(status, sGood.Render("✓ Ready to deploy.")) + } + status = append(status, "", sTitle.Render("DNS records pointing at your server:")) + for _, r := range c.DNSRecords() { + status = append(status, sPink.Render(" ◆ ")+r) + } + + left := lipgloss.JoinVertical(lipgloss.Left, append(summary, append([]string{""}, status...)...)...) + if w >= 110 { + lw := 46 + s.vp.Width = w - lw - 4 + s.vp.Height = h - 2 + right := sPanel.Width(w - lw - 2).Render(sMuted.Render("vars.yml preview") + "\n" + s.vp.View()) + return lipgloss.JoinHorizontal(lipgloss.Top, lipgloss.NewStyle().Width(lw).Render(left), right) + } + s.vp.Width = w - 4 + s.vp.Height = max(3, h-lipgloss.Height(left)-3) + return left + "\n" + sPanel.Width(w-2).Render(s.vp.View()) +} + +func indexOf(xs []string, v string) int { + for i, x := range xs { + if x == v { + return i + } + } + return 0 +} + +var yamlKey = regexp.MustCompile(`^(\s*-?\s*)([A-Za-z0-9_.]+)(:)(.*)$`) + +func highlightYAML(s string) string { + lines := strings.Split(s, "\n") + for i, l := range lines { + t := strings.TrimSpace(l) + switch { + case strings.HasPrefix(t, "# ──"): + lines[i] = sPink.Render(l) + case strings.HasPrefix(t, "#"): + lines[i] = sMuted.Render(l) + default: + if m := yamlKey.FindStringSubmatch(l); m != nil { + val := m[4] + vs := lipgloss.NewStyle().Foreground(cText) + if strings.Contains(m[2], "password") || strings.Contains(m[2], "secret") || strings.Contains(m[2], "token") || strings.Contains(m[2], "key") && len(strings.TrimSpace(val)) > 30 { + val = " " + sFaint.Render("••••••••") + } else if strings.TrimSpace(val) == "true" { + vs = sGood + } else if strings.TrimSpace(val) == "false" { + vs = sBad + } + lines[i] = m[1] + sAccent.Render(m[2]) + sFaint.Render(m[3]) + vs.Render(val) + } + } + } + return strings.Join(lines, "\n") +} + +// ── Deploy ───────────────────────────────────────────────────────── + +type deployEventMsg struct { + ev deploy.Event + ok bool +} + +type stepState int + +const ( + pending stepState = iota + active + done + skipped + failed +) + +type deployScreen struct { + cfg *config.Config + running bool + finished bool + saveOnly bool + err error + cancel context.CancelFunc + events <-chan deploy.Event + + states []stepState + task string + tasks int + fails int + started time.Time + elapsed time.Duration + + log []string + logFile *os.File + vp viewport.Model + follow bool + spin spinner.Model + bar progress.Model +} + +func newDeployScreen() *deployScreen { + sp := spinner.New() + sp.Spinner = spinner.Points + sp.Style = sPink + return &deployScreen{ + spin: sp, + vp: viewport.New(0, 0), + bar: progress.New(progress.WithGradient("#9D7CFF", "#3EF0B0"), progress.WithoutPercentage()), + } +} + +func (s *deployScreen) name() string { return "Deploy" } +func (s *deployScreen) title() string { + switch { + case s.running: + return "Deploying…" + case s.err != nil: + return "Deployment stopped" + case s.finished && s.saveOnly: + return "Configuration saved" + case s.finished: + return "Your Matrix server is live ✨" + } + return "Deploy" +} +func (s *deployScreen) typing() bool { return false } +func (s *deployScreen) keys() [][2]string { + if s.running { + return [][2]string{{"↑↓", "scroll log"}, {"end", "follow"}, {"ctrl+c", "abort"}} + } + return [][2]string{{"r", "run again"}, {"↑↓", "scroll log"}, {"q", "quit"}} +} + +func (s *deployScreen) enter(c *config.Config) tea.Cmd { s.cfg = c; return nil } +func (s *deployScreen) leave(*config.Config) {} + +func (s *deployScreen) abort() { + if s.cancel != nil { + s.cancel() + } + s.appendLog(sWarn.Render("aborting… (waiting for the current command to stop)")) +} + +func (s *deployScreen) start(saveOnly bool) tea.Cmd { + ctx, cancel := context.WithCancel(context.Background()) + s.cancel = cancel + s.saveOnly = saveOnly + s.running, s.finished, s.err = true, false, nil + s.states = make([]stepState, len(deploy.StepNames)) + s.task, s.tasks, s.fails = "", 0, 0 + s.log = nil + s.follow = true + s.started = time.Now() + if s.logFile != nil { + s.logFile.Close() + } + _ = os.MkdirAll(config.Dir(), 0o700) + s.logFile, _ = os.OpenFile(s.logPath(), os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0o600) + s.events = deploy.Start(ctx, s.cfg, deploy.Options{SaveOnly: saveOnly}) + return tea.Batch(s.spin.Tick, s.wait(), tick()) +} + +func (s *deployScreen) logPath() string { return filepath.Join(config.Dir(), "last-deploy.log") } + +func (s *deployScreen) wait() tea.Cmd { + ch := s.events + return func() tea.Msg { + ev, ok := <-ch + return deployEventMsg{ev, ok} + } +} + +type tickMsg struct{} + +func tick() tea.Cmd { return tea.Tick(time.Second, func(time.Time) tea.Msg { return tickMsg{} }) } + +func (s *deployScreen) appendLog(line string) { + s.log = append(s.log, line) + if len(s.log) > 5000 { + s.log = s.log[len(s.log)-4000:] + } +} + +func (s *deployScreen) update(msg tea.Msg) tea.Cmd { + switch m := msg.(type) { + case startDeployMsg: + return s.start(m.saveOnly) + case tickMsg: + if s.running { + s.elapsed = time.Since(s.started) + return tick() + } + case spinner.TickMsg: + if s.running { + var cmd tea.Cmd + s.spin, cmd = s.spin.Update(m) + return cmd + } + case deployEventMsg: + if !m.ok { + s.running = false + return nil + } + s.handle(m.ev) + return s.wait() + case tea.KeyMsg: + switch m.String() { + case "r": + if !s.running { + return s.start(s.saveOnly) + } + case "end", "G": + s.follow = true + s.vp.GotoBottom() + return nil + case "up", "k", "pgup", "home": + s.follow = false + } + } + var cmd tea.Cmd + s.vp, cmd = s.vp.Update(msg) + return cmd +} + +func (s *deployScreen) handle(ev deploy.Event) { + if ev.Line != "" && s.logFile != nil { + fmt.Fprintln(s.logFile, ev.Line) + } + switch { + case ev.Err != nil: + s.err = ev.Err + s.running = false + for i, st := range s.states { + if st == active { + s.states[i] = failed + } + } + s.appendLog(sBad.Render("✗ " + ev.Err.Error())) + return + case ev.Done: + s.finished = true + s.running = false + s.elapsed = time.Since(s.started) + for i, st := range s.states { + if st == active { + s.states[i] = done + } + } + return + case ev.Started: + for i := range s.states { + if s.states[i] == active { + s.states[i] = done + } + } + s.states[ev.Step] = active + return + case ev.Skipped: + s.states[ev.Step] = skipped + return + } + if ev.Task != "" { + s.task = ev.Task + if strings.HasPrefix(ev.Line, "TASK") { + s.tasks++ + } + } + if ev.Failed { + s.fails++ + } + s.appendLog(styleLogLine(ev.Line, ev.Failed)) +} + +func styleLogLine(l string, failed bool) string { + switch { + case failed: + return sBad.Render(l) + case strings.HasPrefix(l, "TASK"), strings.HasPrefix(l, "PLAY"), strings.HasPrefix(l, "RUNNING HANDLER"): + return sAccent.Render(l) + case strings.HasPrefix(l, "ok:"): + return sGood.Render(l) + case strings.HasPrefix(l, "changed:"): + return sWarn.Render(l) + case strings.HasPrefix(l, "skipping:"), strings.HasPrefix(l, "included:"): + return sFaint.Render(l) + case strings.HasPrefix(l, "$ "): + return sPink.Render(l) + case strings.Contains(l, "...ignoring"): + return sMuted.Render(l) + } + return sMuted.Render(l) +} + +func (s *deployScreen) view(w, h int) string { + if s.states == nil { + return sMuted.Render("Waiting to start…") + } + var steps []string + for i, name := range deploy.StepNames { + var icon string + style := sMuted + switch s.states[i] { + case pending: + icon = sFaint.Render("○") + style = sFaint + case active: + icon = s.spin.View() + style = sTitle + case done: + icon = sGood.Render("✓") + case skipped: + icon = sFaint.Render("–") + style = sFaint + case failed: + icon = sBad.Render("✗") + style = sBad + } + steps = append(steps, icon+" "+style.Render(name)) + } + stepsCol := lipgloss.NewStyle().Width(32).Render(strings.Join(steps, "\n")) + + nDone := 0 + for _, st := range s.states { + if st == done || st == skipped { + nDone++ + } + } + s.bar.Width = max(10, w-36) + stats := []string{ + s.bar.ViewAs(float64(nDone) / float64(len(s.states))), + "", + sMuted.Render("elapsed ") + sTitle.Render(s.elapsed.Round(time.Second).String()), + sMuted.Render("tasks ") + sTitle.Render(fmt.Sprint(s.tasks)), + } + if s.fails > 0 { + stats = append(stats, sMuted.Render("errors ")+sBad.Render(fmt.Sprint(s.fails))) + } + if s.task != "" && s.running { + stats = append(stats, "", sPink.Render("▸ ")+truncate(s.task, w-40)) + } + top := lipgloss.JoinHorizontal(lipgloss.Top, stepsCol, " ", strings.Join(stats, "\n")) + + var result string + if s.finished || s.err != nil { + result = s.resultView(w) + } + + logH := max(3, h-lipgloss.Height(top)-lipgloss.Height(result)-3) + s.vp.Width = w - 4 + s.vp.Height = logH + lines := make([]string, len(s.log)) + for i, l := range s.log { + lines[i] = truncateANSI(l, w-4) + } + s.vp.SetContent(strings.Join(lines, "\n")) + if s.follow { + s.vp.GotoBottom() + } + logBox := sPanel.Width(w - 2).Render(s.vp.View()) + + parts := []string{top} + if result != "" { + parts = append(parts, result) + } + parts = append(parts, logBox) + return strings.Join(parts, "\n") +} + +func (s *deployScreen) resultView(w int) string { + c := s.cfg + if s.err != nil { + body := sBad.Render("✗ "+s.err.Error()) + "\n" + + sMuted.Render("Full log: ") + s.logPath() + "\n" + + sMuted.Render("Fix the problem (esc goes back to the settings) and press ") + sKey.Render("r") + sMuted.Render(" to try again.") + return sPanel.BorderForeground(cRed).Width(w - 2).Render(body) + } + inv := filepath.Join(c.PlaybookDir, "inventory") + if s.saveOnly { + body := sGood.Render("✓ Files written to ") + inv + "\n" + + sMuted.Render("Deploy later with: ") + sTitle.Render("cd "+c.PlaybookDir+" && ansible-playbook -i inventory/hosts setup.yml --tags=install-all,ensure-matrix-users-created,start") + return sPanel.BorderForeground(cMint).Width(w - 2).Render(body) + } + scheme := "https://" + if c.SSL.Mode == "none" { + scheme = "http://" + } + lines := []string{sGood.Render("✓ Done in " + s.elapsed.Round(time.Second).String())} + lines = append(lines, sMuted.Render("Homeserver ")+sTitle.Render(scheme+"matrix."+c.Domain)) + if c.Components["element"] { + lines = append(lines, sMuted.Render("Element ")+sTitle.Render(scheme+"element."+c.Domain)) + } + switch c.Homeserver { + case "synapse", "dendrite": + lines = append(lines, sMuted.Render("Admin ")+sTitle.Render("@"+c.AdminUser+":"+c.Domain)+sMuted.Render(" (password saved in "+config.Dir()+")")) + case "continuwuity", "tuwunel": + lines = append(lines, sMuted.Render("Register your first account with token ")+sTitle.Render(c.AdminPassword)) + case "conduit": + lines = append(lines, sWarn.Render("Registration is open: create your account now, then disable it.")) + } + if c.SSL.Mode == "selfsigned" { + lines = append(lines, sWarn.Render("Self-signed certificate: import "+filepath.Join(config.Dir(), "ssl", c.Domain, "cert.pem")+" on your devices.")) + } + return sPanel.BorderForeground(cMint).Width(w - 2).Render(strings.Join(lines, "\n")) +} diff --git a/internal/ui/screens_setup.go b/internal/ui/screens_setup.go new file mode 100644 index 0000000..56ae9af --- /dev/null +++ b/internal/ui/screens_setup.go @@ -0,0 +1,380 @@ +package ui + +import ( + "fmt" + "os" + "strings" + + "github.com/charmbracelet/bubbles/spinner" + tea "github.com/charmbracelet/bubbletea" + "github.com/charmbracelet/lipgloss" + + "interzone/internal/catalog" + "interzone/internal/config" + "interzone/internal/deploy" +) + +// ── Welcome ──────────────────────────────────────────────────────── + +type welcomeScreen struct{ loaded bool } + +func (s *welcomeScreen) name() string { return "Welcome" } +func (s *welcomeScreen) title() string { return "" } +func (s *welcomeScreen) enter(*config.Config) tea.Cmd { return nil } +func (s *welcomeScreen) leave(*config.Config) {} +func (s *welcomeScreen) typing() bool { return false } +func (s *welcomeScreen) keys() [][2]string { return [][2]string{{"enter", "begin"}} } +func (s *welcomeScreen) update(msg tea.Msg) tea.Cmd { + if k, ok := msg.(tea.KeyMsg); ok && (k.String() == "enter" || k.String() == " ") { + return nav(1) + } + return nil +} + +func (s *welcomeScreen) view(w, h int) string { + feature := func(icon, title, text string) string { + return sPink.Render(icon) + " " + sTitle.Render(title) + "\n " + sMuted.Render(text) + } + head := lipgloss.JoinVertical(lipgloss.Center, + gradientLines(strings.TrimPrefix(logo, "\n")), + "", + sSub.Render("Your own Matrix server, set up with matrix-docker-ansible-deploy,"), + sSub.Render("without editing a single YAML file."), + ) + parts := []string{ + head, + "", + feature("◆", "Pick any homeserver", "Synapse, Continuwuity, Tuwunel, Conduit or Dendrite."), + feature("◆", "Opt into anything", fmt.Sprintf("%d bridges, bots, clients and services from the playbook.", len(catalog.Components))), + feature("◆", "Works during a blackout", "Git, container, Docker, APT and PyPI mirrors inside the country."), + "", + } + if s.loaded { + parts = append(parts, sGood.Render("✓ Picked up your previous answers."), "") + } + parts = append(parts, sAccent.Render("Press enter to begin ›")) + block := lipgloss.JoinVertical(lipgloss.Left, parts...) + return lipgloss.Place(w, h, lipgloss.Center, lipgloss.Center, block) +} + +// ── Network & mirrors ────────────────────────────────────────────── + +type checksMsg []deploy.Check + +type networkScreen struct { + cfg *config.Config + form *form + checks []deploy.Check + checking bool + spin spinner.Model +} + +func newNetworkScreen() *networkScreen { + sp := spinner.New() + sp.Spinner = spinner.MiniDot + sp.Style = sAccent + return &networkScreen{spin: sp} +} + +func (s *networkScreen) name() string { return "Network" } +func (s *networkScreen) title() string { return "Where should everything be downloaded from?" } +func (s *networkScreen) typing() bool { return s.form.typing() } +func (s *networkScreen) keys() [][2]string { + return [][2]string{{"↑↓", "move"}, {"←→", "choose"}, {"ctrl+t", "test sources"}, {"enter", "next"}} +} + +func (s *networkScreen) enter(c *config.Config) tea.Cmd { + s.cfg = c + src := c.Sources + mode := "online" + if src.Blackout { + mode = "blackout" + } + f := newForm( + choiceField("mode", "Network situation", []string{"online", "blackout"}, + []string{"Normal internet", "Blackout: in-country mirrors only"}, mode, + "Blackout mode adds mirrors for Docker Engine, OS packages and PyPI."), + textField("git", "Playbook git repository", src.PlaybookGit, config.DefaultPlaybookGit, + "Where matrix-docker-ansible-deploy is cloned from."), + textField("roles", "Git mirror for Ansible roles", src.RolesGitBase, "https://github.com/", + "Replaces https://github.com/ for the roles in requirements.yml. Use https://github.com/ for upstream."), + toggleField("useRegistry", "Pull container images from a mirror", src.UseRegistry, + "Every image (docker.io, ghcr.io, quay.io…) is pulled from one registry."), + textField("registry", "Container registry mirror", src.RegistryPrefix, config.DefaultRegistryPrefix, + "Images are pulled as //, e.g. mechatok.g0th.ir/element-hq/synapse."), + textField("dockerpkg", "Docker Engine package mirror", src.DockerPackageURL, "https://mirror.example.ir/docker-ce/linux", + "A mirror of download.docker.com/linux. Leave empty if Docker is already installed on the server."), + textField("apt", "OS package (APT) mirror", src.APTMirror, "https://mirror.example.ir", + "The server's Debian/Ubuntu sources are pointed here before installing. Original files are backed up."), + textField("pypi", "PyPI mirror", src.PyPIIndex, "https://mirror.example.ir/pypi/simple", + "Used to install Ansible on this machine if it's missing."), + ) + blackout := func() bool { return f.value("mode") != "blackout" } + f.get("registry").hidden = func() bool { return !f.get("useRegistry").on } + f.get("dockerpkg").hidden = blackout + f.get("apt").hidden = blackout + f.get("pypi").hidden = blackout + s.form = f + return nil +} + +func (s *networkScreen) leave(c *config.Config) { + f := s.form + c.Sources = config.Sources{ + Blackout: f.value("mode") == "blackout", + PlaybookGit: f.value("git"), + RolesGitBase: f.value("roles"), + UseRegistry: f.get("useRegistry").on, + RegistryPrefix: f.value("registry"), + DockerPackageURL: f.value("dockerpkg"), + APTMirror: f.value("apt"), + PyPIIndex: f.value("pypi"), + } + if c.Sources.PlaybookGit == "" { + c.Sources.PlaybookGit = config.DefaultPlaybookGit + } + if !c.Sources.Blackout { + c.Sources.DockerPackageURL, c.Sources.APTMirror, c.Sources.PyPIIndex = "", "", "" + } +} + +func (s *networkScreen) update(msg tea.Msg) tea.Cmd { + switch m := msg.(type) { + case checksMsg: + s.checking = false + s.checks = m + return nil + case spinner.TickMsg: + if s.checking { + var cmd tea.Cmd + s.spin, cmd = s.spin.Update(m) + return cmd + } + return nil + case tea.KeyMsg: + if m.String() == "ctrl+t" && !s.checking { + cfg := config.Default() + s.leave(cfg) + s.checking = true + s.checks = nil + return tea.Batch(s.spin.Tick, func() tea.Msg { return checksMsg(deploy.Preflight(cfg)) }) + } + } + cmd := s.form.Update(msg) + s.cfg.Sources.Blackout = s.form.value("mode") == "blackout" // keeps the header badge live + return cmd +} + +func (s *networkScreen) view(w, h int) string { + results := s.checksView(w) + formH := h - lipgloss.Height(results) - 1 + return s.form.View(w, formH) + "\n\n" + results +} + +func (s *networkScreen) checksView(w int) string { + if s.checking { + return s.spin.View() + sMuted.Render(" testing every source…") + } + if s.checks == nil { + return sMuted.Render("Press ") + sKey.Render("ctrl+t") + sMuted.Render(" to test that every source is reachable from here.") + } + var lines []string + for _, c := range s.checks { + icon, style := sGood.Render("✓"), sMuted + if !c.OK { + icon, style = sBad.Render("✗"), sBad + } + name := lipgloss.NewStyle().Width(20).Render(sTitle.Render(c.Name)) + lines = append(lines, truncateANSI(icon+" "+name+" "+style.Render(truncate(c.Target, 40)+" "+c.Detail), w)) + } + return strings.Join(lines, "\n") +} + +// ── Server ───────────────────────────────────────────────────────── + +type serverScreen struct{ form *form } + +func newServerScreen() *serverScreen { return &serverScreen{} } + +func (s *serverScreen) name() string { return "Server" } +func (s *serverScreen) title() string { return "Tell me about your server" } +func (s *serverScreen) typing() bool { return s.form.typing() } +func (s *serverScreen) keys() [][2]string { + return [][2]string{{"↑↓", "move"}, {"←→", "choose"}, {"space", "toggle"}, {"ctrl+r", "reveal"}, {"enter", "next"}} +} + +func (s *serverScreen) enter(c *config.Config) tea.Cmd { + t := c.Target + domain := textField("domain", "Base domain", c.Domain, "example.com", + "User IDs look like @alice:. Point matrix. at your server.") + domain.required = true + host := textField("host", "Server address", t.Host, "203.0.113.10 or server.example.com", "IP or hostname reachable over SSH.") + host.required = true + sudoHelp := "Needed if you're not root and sudo asks for a password. Leave empty otherwise." + if os.Geteuid() == 0 { + sudoHelp = "You're root here, so this is only used for SSH targets." + } + f := newForm( + domain, + choiceField("mode", "Install where?", []string{"local", "ssh"}, + []string{"This machine", "A remote server over SSH"}, t.Mode, + "Run interzone on the server itself, or from your computer over SSH."), + host, + textField("user", "SSH user", t.User, "root", ""), + textField("port", "SSH port", t.Port, "22", ""), + textField("key", "SSH private key", t.SSHKey, "~/.ssh/id_ed25519", "Leave empty to use your SSH agent or default key."), + secretField("become", "sudo password", t.BecomePass, sudoHelp), + toggleField("federation", "Federate with other Matrix servers", c.Federation, + "Turn off for a private server that never talks to the outside world."), + toggleField("ipv6", "Enable IPv6 networking for containers", c.IPv6, "Only if your server has working IPv6."), + ) + remote := func() bool { return f.value("mode") != "ssh" } + for _, k := range []string{"host", "user", "port", "key"} { + f.get(k).hidden = remote + } + f.get("federation").section = "Networking" + s.form = f + return nil +} + +func (s *serverScreen) leave(c *config.Config) { + f := s.form + c.Domain = strings.ToLower(strings.TrimPrefix(f.value("domain"), "matrix.")) + c.Target = config.Target{ + Mode: f.value("mode"), Host: f.value("host"), User: f.value("user"), + Port: f.value("port"), SSHKey: f.value("key"), BecomePass: f.value("become"), + } + if c.Target.User == "" { + c.Target.User = "root" + } + c.Federation = f.get("federation").on + c.IPv6 = f.get("ipv6").on +} + +func (s *serverScreen) update(msg tea.Msg) tea.Cmd { return s.form.Update(msg) } +func (s *serverScreen) view(w, h int) string { return s.form.View(w, h) } + +// ── Homeserver ───────────────────────────────────────────────────── + +type homeserverScreen struct{ sel int } + +func (s *homeserverScreen) name() string { return "Homeserver" } +func (s *homeserverScreen) title() string { return "Choose your homeserver" } +func (s *homeserverScreen) typing() bool { return false } +func (s *homeserverScreen) keys() [][2]string { + return [][2]string{{"↑↓", "select"}, {"enter", "choose"}} +} + +func (s *homeserverScreen) enter(c *config.Config) tea.Cmd { + for i, h := range catalog.Homeservers { + if h.ID == c.Homeserver { + s.sel = i + } + } + return nil +} + +func (s *homeserverScreen) leave(c *config.Config) { c.Homeserver = catalog.Homeservers[s.sel].ID } + +func (s *homeserverScreen) update(msg tea.Msg) tea.Cmd { + if k, ok := msg.(tea.KeyMsg); ok { + n := len(catalog.Homeservers) + switch k.String() { + case "up", "k", "shift+tab": + s.sel = (s.sel + n - 1) % n + case "down", "j", "tab": + s.sel = (s.sel + 1) % n + case "enter", " ": + return nav(1) + } + } + return nil +} + +func (s *homeserverScreen) view(w, h int) string { + cardW := min(w, 76) + compact := h < len(catalog.Homeservers)*5 + var cards []string + for i, hs := range catalog.Homeservers { + name := sTitle.Render(hs.Name) + tag := sMuted.Render(" " + hs.Tagline) + style := sPanel.Width(cardW - 2) + if i == s.sel { + style = sPanelFocus.Width(cardW - 2) + name = sAccent.Render("◉ ") + gradient(hs.Name) + } else { + name = sFaint.Render("○ ") + name + } + body := name + tag + if !compact || i == s.sel { + body += "\n" + sSub.Render(hs.Description) + } + if compact && i != s.sel { + cards = append(cards, " "+sMuted.Render("○ ")+sMuted.Render(hs.Name)+tag) + continue + } + cards = append(cards, style.Render(body)) + } + return lipgloss.JoinVertical(lipgloss.Left, cards...) +} + +// ── SSL ──────────────────────────────────────────────────────────── + +type sslScreen struct { + form *form + blackout bool +} + +func newSSLScreen() *sslScreen { return &sslScreen{} } + +func (s *sslScreen) name() string { return "Certificates" } +func (s *sslScreen) title() string { return "How should HTTPS certificates be handled?" } +func (s *sslScreen) typing() bool { return s.form.typing() } +func (s *sslScreen) keys() [][2]string { + return [][2]string{{"←→", "choose"}, {"↑↓", "move"}, {"enter", "next"}} +} + +var sslModes = []string{"letsencrypt", "selfsigned", "custom", "none"} +var sslLabels = []string{"Let's Encrypt", "Self-signed", "My own certificate", "No HTTPS"} +var sslExplain = map[string]string{ + "letsencrypt": "Free, trusted certificates issued automatically. Needs access to letsencrypt.org, so it won't work during a blackout.", + "selfsigned": "interzone generates a 10-year wildcard certificate locally. Works fully offline; clients will have to trust it manually.", + "custom": "Use a certificate you already have (e.g. from a national CA). Point to the PEM files on this machine.", + "none": "Plain HTTP. Only if another reverse proxy in front of this server terminates TLS.", +} + +func (s *sslScreen) enter(c *config.Config) tea.Cmd { + s.blackout = c.Sources.Blackout + mode := c.SSL.Mode + if s.blackout && mode == "letsencrypt" { + mode = "selfsigned" + } + f := newForm( + choiceField("mode", "Certificate source", sslModes, sslLabels, mode, ""), + textField("email", "Contact email for Let's Encrypt", c.SSL.ACMEEmail, "you@example.com", "Optional. Used for expiry warnings."), + textField("cert", "Certificate (fullchain PEM)", c.SSL.CertPath, "/path/to/fullchain.pem", ""), + textField("key", "Private key (PEM)", c.SSL.KeyPath, "/path/to/privkey.pem", ""), + ) + f.get("email").hidden = func() bool { return f.value("mode") != "letsencrypt" } + custom := func() bool { return f.value("mode") != "custom" } + f.get("cert").hidden, f.get("key").hidden = custom, custom + f.get("cert").required, f.get("key").required = true, true + s.form = f + return nil +} + +func (s *sslScreen) leave(c *config.Config) { + c.SSL = config.SSL{Mode: s.form.value("mode"), ACMEEmail: s.form.value("email"), + CertPath: s.form.value("cert"), KeyPath: s.form.value("key")} +} + +func (s *sslScreen) update(msg tea.Msg) tea.Cmd { return s.form.Update(msg) } + +func (s *sslScreen) view(w, h int) string { + mode := s.form.value("mode") + info := sPanel.Width(min(w, 80) - 2).Render(sSub.Render(sslExplain[mode])) + if s.blackout && mode == "letsencrypt" { + info += "\n" + sWarn.Render("⚠ You chose blackout mode: Let's Encrypt will fail without international internet.") + } + return s.form.View(w, h-lipgloss.Height(info)-1) + "\n\n" + info +} diff --git a/internal/ui/theme.go b/internal/ui/theme.go new file mode 100644 index 0000000..2330e4d --- /dev/null +++ b/internal/ui/theme.go @@ -0,0 +1,125 @@ +package ui + +import ( + "strings" + + "github.com/charmbracelet/lipgloss" + "github.com/lucasb-eyer/go-colorful" +) + +var ( + cPurple = lipgloss.AdaptiveColor{Light: "#5A3FD9", Dark: "#9D7CFF"} + cMint = lipgloss.AdaptiveColor{Light: "#00976B", Dark: "#3EF0B0"} + cPink = lipgloss.AdaptiveColor{Light: "#C2306B", Dark: "#FF7AB6"} + cAmber = lipgloss.AdaptiveColor{Light: "#A86400", Dark: "#FFC56B"} + cRed = lipgloss.AdaptiveColor{Light: "#C4243F", Dark: "#FF6B81"} + cText = lipgloss.AdaptiveColor{Light: "#1E1B2E", Dark: "#E8E6F3"} + cMuted = lipgloss.AdaptiveColor{Light: "#6E6A86", Dark: "#8A86A3"} + cFaint = lipgloss.AdaptiveColor{Light: "#C9C5DD", Dark: "#3A3650"} + cPanel = lipgloss.AdaptiveColor{Light: "#F3F0FF", Dark: "#1B1828"} +) + +var ( + sTitle = lipgloss.NewStyle().Foreground(cText).Bold(true) + sSub = lipgloss.NewStyle().Foreground(cMuted) + sMuted = lipgloss.NewStyle().Foreground(cMuted) + sFaint = lipgloss.NewStyle().Foreground(cFaint) + sAccent = lipgloss.NewStyle().Foreground(cPurple).Bold(true) + sGood = lipgloss.NewStyle().Foreground(cMint) + sWarn = lipgloss.NewStyle().Foreground(cAmber) + sBad = lipgloss.NewStyle().Foreground(cRed) + sPink = lipgloss.NewStyle().Foreground(cPink) + sKey = lipgloss.NewStyle().Foreground(cPurple).Bold(true) + sSection = lipgloss.NewStyle().Foreground(cPink).Bold(true).MarginTop(1) + + sPanel = lipgloss.NewStyle(). + Border(lipgloss.RoundedBorder()). + BorderForeground(cFaint). + Padding(0, 1) + sPanelFocus = sPanel.BorderForeground(cPurple) + + sBadge = lipgloss.NewStyle().Padding(0, 1).Bold(true) +) + +func badge(text string, bg lipgloss.TerminalColor) string { + return sBadge.Foreground(lipgloss.Color("#111018")).Background(bg).Render(text) +} + +// gradient colours each rune of s along a purple → pink → mint ramp. +func gradient(s string) string { + stops := []string{"#9D7CFF", "#FF7AB6", "#3EF0B0"} + runes := []rune(s) + n := 0 + for _, r := range runes { + if r != ' ' && r != '\n' { + n++ + } + } + var b strings.Builder + i := 0 + for _, r := range runes { + if r == ' ' || r == '\n' { + b.WriteRune(r) + continue + } + t := 0.0 + if n > 1 { + t = float64(i) / float64(n-1) + } + b.WriteString(lipgloss.NewStyle().Foreground(lipgloss.Color(ramp(stops, t))).Render(string(r))) + i++ + } + return b.String() +} + +// gradientLines colours a multi-line block column-wise so each line shares the ramp. +func gradientLines(block string) string { + stops := []string{"#9D7CFF", "#FF7AB6", "#3EF0B0"} + lines := strings.Split(block, "\n") + width := 0 + for _, l := range lines { + width = max(width, len([]rune(l))) + } + for li, l := range lines { + var b strings.Builder + for ci, r := range []rune(l) { + if r == ' ' { + b.WriteRune(r) + continue + } + t := float64(ci) / float64(max(1, width-1)) + b.WriteString(lipgloss.NewStyle().Foreground(lipgloss.Color(ramp(stops, t))).Render(string(r))) + } + lines[li] = b.String() + } + return strings.Join(lines, "\n") +} + +func ramp(stops []string, t float64) string { + if t <= 0 { + return stops[0] + } + if t >= 1 { + return stops[len(stops)-1] + } + seg := t * float64(len(stops)-1) + i := int(seg) + a, _ := colorful.Hex(stops[i]) + z, _ := colorful.Hex(stops[i+1]) + return a.BlendLuv(z, seg-float64(i)).Clamped().Hex() +} + +const logo = ` + ▀█▀ █▄ █ ▀█▀ █▀▀ █▀█ ▀▀█ █▀█ █▄ █ █▀▀ + █ █ ▀█ █ ██▄ █▀▄ ▄▀ █▄█ █ ▀█ ██▄` + +func truncate(s string, w int) string { + if w <= 1 { + return "" + } + r := []rune(s) + if len(r) <= w { + return s + } + return string(r[:w-1]) + "…" +} diff --git a/main.go b/main.go new file mode 100644 index 0000000..d9a1b31 --- /dev/null +++ b/main.go @@ -0,0 +1,38 @@ +// interzone is a friendly terminal wizard for matrix-docker-ansible-deploy +// that also works from behind a national internet blackout. +package main + +import ( + "flag" + "fmt" + "os" + + tea "github.com/charmbracelet/bubbletea" + + "interzone/internal/config" + "interzone/internal/ui" +) + +var version = "dev" + +func main() { + showVersion := flag.Bool("version", false, "print the version and exit") + reset := flag.Bool("reset", false, "forget saved answers and start fresh") + flag.Parse() + + if *showVersion { + fmt.Println("interzone", version) + return + } + + cfg, loaded := config.Load() + if *reset { + cfg, loaded = config.Default(), false + } + + p := tea.NewProgram(ui.New(cfg, loaded), tea.WithAltScreen()) + if _, err := p.Run(); err != nil { + fmt.Fprintln(os.Stderr, "interzone:", err) + os.Exit(1) + } +}